@gardenfi/core 2.5.2 → 2.5.3
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/README.md +8 -10
- package/dist/{ccip-DW9K4PmQ.js → ccip-Bg3f6Dwh.js} +1 -1
- package/dist/{ccip-D9S6QM7J.cjs → ccip-DSGVoxhU.cjs} +1 -1
- package/dist/{index-BsWv07Gh.js → index-D-NHDZrP.js} +601 -576
- package/dist/{index-9VBMeQEM.cjs → index-s2tkcnpk.cjs} +14 -14
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +3 -3
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
`),{docsPath:r,name:"InvalidAbiEncodingType"})}}class Kv extends z{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(`
|
|
20
20
|
`),{docsPath:r,name:"InvalidAbiDecodingType"})}}let Hm=class extends z{constructor(t){super([`Value "${t}" is not a valid array.`].join(`
|
|
21
21
|
`),{name:"InvalidArrayError"})}};class Xv extends z{constructor(t){super([`"${t}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(`
|
|
22
|
-
`),{name:"InvalidDefinitionTypeError"})}}class Yv extends z{constructor(t){super(`Filter type "${t}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}let zm=class extends z{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},qm=class extends z{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 Fh extends z{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 Ti(e,{dir:t,size:r=32}={}){return typeof e=="string"?Kn(e,{dir:t,size:r}):Zv(e,{dir:t,size:r})}function Kn(e,{dir:t,size:r=32}={}){if(r===null)return e;const n=e.replace("0x","");if(n.length>r*2)throw new qm({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function Zv(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new qm({size:e.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let s=0;s<r;s++){const i=t==="right";n[i?s:r-s-1]=e[i?s:e.length-s-1]}return n}let Vm=class extends z{constructor({max:t,min:r,signed:n,size:s,value:i}){super(`Number "${i}" is not in safe ${s?`${s*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}};class Jv extends z{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 Qv extends z{constructor(t){super(`Hex value "${t}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}let e2=class extends z{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}};function cr(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let s=0;s<r.length-1&&r[t==="left"?s:r.length-s-1].toString()==="0";s++)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 kr(e,{size:t}){if(He(e)>t)throw new e2({givenSize:He(e),maxSize:t})}function ot(e,t={}){const{signed:r}=t;t.size&&kr(e,{size:t.size});const n=BigInt(e);if(!r)return n;const s=(e.length-2)/2,i=(1n<<BigInt(s)*8n-1n)-1n;return n<=i?n:n-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function t2(e,t={}){let r=e;if(t.size&&(kr(r,{size:t.size}),r=cr(r)),cr(r)==="0x00")return!1;if(cr(r)==="0x01")return!0;throw new Qv(r)}function ur(e,t={}){return Number(ot(e,t))}const r2=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function mt(e,t={}){return typeof e=="number"||typeof e=="bigint"?X(e,t):typeof e=="string"?mi(e,t):typeof e=="boolean"?Gm(e,t):Je(e,t)}function Gm(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?(kr(r,{size:t.size}),Ti(r,{size:t.size})):r}function Je(e,t={}){let r="";for(let s=0;s<e.length;s++)r+=r2[e[s]];const n=`0x${r}`;return typeof t.size=="number"?(kr(n,{size:t.size}),Ti(n,{dir:"right",size:t.size})):n}function X(e,t={}){const{signed:r,size:n}=t,s=BigInt(e);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<o){const c=typeof e=="bigint"?"n":"";throw new Vm({max:i?`${i}${c}`:void 0,min:`${o}${c}`,signed:r,size:n,value:`${e}${c}`})}const a=`0x${(r&&s<0?(1n<<BigInt(n*8))+BigInt(s):s).toString(16)}`;return n?Ti(a,{size:n}):a}const n2=new TextEncoder;function mi(e,t={}){const r=n2.encode(e);return Je(r,t)}const s2=new TextEncoder;function Ii(e,t={}){return typeof e=="number"||typeof e=="bigint"?o2(e,t):typeof e=="boolean"?i2(e,t):xr(e)?Sr(e,t):bs(e,t)}function i2(e,t={}){const r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?(kr(r,{size:t.size}),Ti(r,{size:t.size})):r}const Yr={zero:48,nine:57,A:65,F:70,a:97,f:102};function jh(e){if(e>=Yr.zero&&e<=Yr.nine)return e-Yr.zero;if(e>=Yr.A&&e<=Yr.F)return e-(Yr.A-10);if(e>=Yr.a&&e<=Yr.f)return e-(Yr.a-10)}function Sr(e,t={}){let r=e;t.size&&(kr(r,{size:t.size}),r=Ti(r,{dir:"right",size:t.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const s=n.length/2,i=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=jh(n.charCodeAt(a++)),l=jh(n.charCodeAt(a++));if(c===void 0||l===void 0)throw new z(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);i[o]=c*16+l}return i}function o2(e,t){const r=X(e,t);return Sr(r)}function bs(e,t={}){const r=s2.encode(e);return typeof t.size=="number"?(kr(r,{size:t.size}),Ti(r,{dir:"right",size:t.size})):r}const ha=BigInt(2**32-1),Lh=BigInt(32);function Wm(e,t=!1){return t?{h:Number(e&ha),l:Number(e>>Lh&ha)}:{h:Number(e>>Lh&ha)|0,l:Number(e&ha)|0}}function a2(e,t=!1){const r=e.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=Wm(e[i],t);[n[i],s[i]]=[o,a]}return[n,s]}const Km=(e,t,r)=>e>>>r|t<<32-r,Xm=(e,t,r)=>e<<32-r|t>>>r,c2=(e,t,r)=>e<<64-r|t>>>r-32,u2=(e,t,r)=>e>>>r-32|t<<64-r,l2=(e,t)=>t,f2=(e,t)=>e,d2=(e,t,r)=>e<<r|t>>>32-r,h2=(e,t,r)=>t<<r|e>>>32-r,p2=(e,t,r)=>t<<r-32|e>>>64-r,y2=(e,t,r)=>e<<r-32|t>>>64-r;function Ym(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:s|0}}const Zm=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Jm=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,Ws=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ad(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Zn(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function lr(e,...t){if(!ad(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 m2(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Zn(e.outputLen),Zn(e.blockLen)}function Jn(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 cd(e,t){lr(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function yo(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function _r(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function uu(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Br(e,t){return e<<32-t|e>>>t}function pa(e,t){return e<<t|e>>>32-t>>>0}const Qm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function e0(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const an=Qm?e=>e:e=>e0(e);function g2(e){for(let t=0;t<e.length;t++)e[t]=e0(e[t]);return e}const Hn=Qm?e=>e:g2,t0=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",b2=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function mo(e){if(lr(e),t0)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=b2[e[r]];return t}const Zr={_0:48,_9:57,A:65,F:70,a:97,f:102};function Dh(e){if(e>=Zr._0&&e<=Zr._9)return e-Zr._0;if(e>=Zr.A&&e<=Zr.F)return e-(Zr.A-10);if(e>=Zr.a&&e<=Zr.f)return e-(Zr.a-10)}function ud(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(t0)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 s=0,i=0;s<r;s++,i+=2){const o=Dh(e.charCodeAt(i)),a=Dh(e.charCodeAt(i+1));if(o===void 0||a===void 0){const c=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[s]=o*16+a}return n}function w2(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function mn(e){return typeof e=="string"&&(e=w2(e)),lr(e),e}function us(...e){let t=0;for(let n=0;n<e.length;n++){const s=e[n];lr(s),t+=s.length}const r=new Uint8Array(t);for(let n=0,s=0;n<e.length;n++){const i=e[n];r.set(i,s),s+=i.length}return r}class yc{}function mc(e){const t=n=>e().update(mn(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function v2(e){const t=(n,s)=>e(s).update(mn(n)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}function E2(e=32){if(Ws&&typeof Ws.getRandomValues=="function")return Ws.getRandomValues(new Uint8Array(e));if(Ws&&typeof Ws.randomBytes=="function")return Uint8Array.from(Ws.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const A2=BigInt(0),Mi=BigInt(1),x2=BigInt(2),S2=BigInt(7),_2=BigInt(256),k2=BigInt(113),r0=[],n0=[],s0=[];for(let e=0,t=Mi,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],r0.push(2*(5*n+r)),n0.push((e+1)*(e+2)/2%64);let s=A2;for(let i=0;i<7;i++)t=(t<<Mi^(t>>S2)*k2)%_2,t&x2&&(s^=Mi<<(Mi<<BigInt(i))-Mi);s0.push(s)}const i0=a2(s0,!0),T2=i0[0],I2=i0[1],Hh=(e,t,r)=>r>32?p2(e,t,r):d2(e,t,r),zh=(e,t,r)=>r>32?y2(e,t,r):h2(e,t,r);function P2(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let o=0;o<10;o++)r[o]=e[o]^e[o+10]^e[o+20]^e[o+30]^e[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],f=Hh(l,u,1)^r[a],p=zh(l,u,1)^r[a+1];for(let d=0;d<50;d+=10)e[o+d]^=f,e[o+d+1]^=p}let s=e[2],i=e[3];for(let o=0;o<24;o++){const a=n0[o],c=Hh(s,i,a),l=zh(s,i,a),u=r0[o];s=e[u],i=e[u+1],e[u]=c,e[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=e[o+a];for(let a=0;a<10;a++)e[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=T2[n],e[1]^=I2[n]}_r(r)}class ld extends yc{constructor(t,r,n,s=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=s,this.rounds=i,Zn(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=yo(this.state)}clone(){return this._cloneInto()}keccak(){Hn(this.state32),P2(this.state32,this.rounds),Hn(this.state32),this.posOut=0,this.pos=0}update(t){Jn(this),t=mn(t),lr(t);const{blockLen:r,state:n}=this,s=t.length;for(let i=0;i<s;){const o=Math.min(r-this.pos,s-i);for(let a=0;a<o;a++)n[this.pos++]^=t[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:r,pos:n,blockLen:s}=this;t[n]^=r,r&128&&n===s-1&&this.keccak(),t[s-1]^=128,this.keccak()}writeInto(t){Jn(this,!1),lr(t),this.finish();const r=this.state,{blockLen:n}=this;for(let s=0,i=t.length;s<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-s);t.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Zn(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(cd(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,_r(this.state)}_cloneInto(t){const{blockLen:r,suffix:n,outputLen:s,rounds:i,enableXOF:o}=this;return t||(t=new ld(r,n,s,o,i)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=n,t.outputLen=s,t.enableXOF=o,t.destroyed=this.destroyed,t}}const O2=(e,t,r)=>mc(()=>new ld(t,e,r)),o0=O2(1,136,256/8);function lt(e,t){const r=t||"hex",n=o0(xr(e,{strict:!1})?Ii(e):e);return r==="bytes"?n:mt(n)}const B2=e=>lt(Ii(e));function C2(e){return B2(e)}function R2(e){let t=!0,r="",n=0,s="",i=!1;for(let o=0;o<e.length;o++){const a=e[o];if(["(",")",","].includes(a)&&(t=!0),a==="("&&n++,a===")"&&n--,!!t){if(n===0){if(a===" "&&["event","function",""].includes(s))s="";else if(s+=a,a===")"){i=!0;break}continue}if(a===" "){e[o-1]!==","&&r!==","&&r!==",("&&(r="",t=!1);continue}s+=a,r+=a}}if(!i)throw new z("Unable to normalize signature.");return s}const $2=e=>{const t=typeof e=="string"?e:Ja(e);return R2(t)};function a0(e){return C2($2(e))}const gc=a0;let Bt=class extends z{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"})}},bc=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 lu=new bc(8192);function Xo(e,t){if(lu.has(`${e}.${t}`))return lu.get(`${e}.${t}`);const r=e.substring(2).toLowerCase(),n=lt(bs(r),"bytes"),s=r.split("");for(let o=0;o<40;o+=2)n[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(n[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const i=`0x${s.join("")}`;return lu.set(`${e}.${t}`,i),i}function c0(e,t){if(!st(e,{strict:!1}))throw new Bt({address:e});return Xo(e,t)}const N2=/^0x[a-fA-F0-9]{40}$/,fu=new bc(8192);function st(e,t){const{strict:r=!0}=t??{},n=`${e}.${r}`;if(fu.has(n))return fu.get(n);const s=N2.test(e)?e.toLowerCase()===e?!0:r?Xo(e)===e:!0:!1;return fu.set(n,s),s}function Vt(e){return typeof e[0]=="string"?Tr(e):U2(e)}function U2(e){let t=0;for(const s of e)t+=s.length;const r=new Uint8Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.length;return r}function Tr(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function _s(e,t,r,{strict:n}={}){return xr(e,{strict:!1})?Qa(e,t,r,{strict:n}):f0(e,t,r,{strict:n})}function u0(e,t){if(typeof t=="number"&&t>0&&t>He(e)-1)throw new zm({offset:t,position:"start",size:He(e)})}function l0(e,t,r){if(typeof t=="number"&&typeof r=="number"&&He(e)!==r-t)throw new zm({offset:r,position:"end",size:He(e)})}function f0(e,t,r,{strict:n}={}){u0(e,t);const s=e.slice(t,r);return n&&l0(s,t,r),s}function Qa(e,t,r,{strict:n}={}){u0(e,t);const s=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return n&&l0(s,t,r),s}const M2=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,d0=/^(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 kn(e,t){if(e.length!==t.length)throw new Dv({expectedLength:e.length,givenLength:t.length});const r=F2({params:e,values:t}),n=dd(r);return n.length===0?"0x":n}function F2({params:e,values:t}){const r=[];for(let n=0;n<e.length;n++)r.push(fd({param:e[n],value:t[n]}));return r}function fd({param:e,value:t}){const r=hd(e.type);if(r){const[n,s]=r;return L2(t,{length:n,param:{...e,type:s}})}if(e.type==="tuple")return V2(t,{param:e});if(e.type==="address")return j2(t);if(e.type==="bool")return H2(t);if(e.type.startsWith("uint")||e.type.startsWith("int")){const n=e.type.startsWith("int"),[,,s="256"]=d0.exec(e.type)??[];return z2(t,{signed:n,size:Number(s)})}if(e.type.startsWith("bytes"))return D2(t,{param:e});if(e.type==="string")return q2(t);throw new Wv(e.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function dd(e){let t=0;for(let i=0;i<e.length;i++){const{dynamic:o,encoded:a}=e[i];o?t+=32:t+=He(a)}const r=[],n=[];let s=0;for(let i=0;i<e.length;i++){const{dynamic:o,encoded:a}=e[i];o?(r.push(X(t+s,{size:32})),n.push(a),s+=He(a)):r.push(a)}return Vt([...r,...n])}function j2(e){if(!st(e))throw new Bt({address:e});return{dynamic:!1,encoded:Kn(e.toLowerCase())}}function L2(e,{length:t,param:r}){const n=t===null;if(!Array.isArray(e))throw new Hm(e);if(!n&&e.length!==t)throw new jv({expectedLength:t,givenLength:e.length,type:`${r.type}[${t}]`});let s=!1;const i=[];for(let o=0;o<e.length;o++){const a=fd({param:r,value:e[o]});a.dynamic&&(s=!0),i.push(a)}if(n||s){const o=dd(i);if(n){const a=X(i.length,{size:32});return{dynamic:!0,encoded:i.length>0?Vt([a,o]):a}}if(s)return{dynamic:!0,encoded:o}}return{dynamic:!1,encoded:Vt(i.map(({encoded:o})=>o))}}function D2(e,{param:t}){const[,r]=t.type.split("bytes"),n=He(e);if(!r){let s=e;return n%32!==0&&(s=Kn(s,{dir:"right",size:Math.ceil((e.length-2)/2/32)*32})),{dynamic:!0,encoded:Vt([Kn(X(n,{size:32})),s])}}if(n!==Number.parseInt(r))throw new Lv({expectedSize:Number.parseInt(r),value:e});return{dynamic:!1,encoded:Kn(e,{dir:"right"})}}function H2(e){if(typeof e!="boolean")throw new z(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Kn(Gm(e))}}function z2(e,{signed:t,size:r=256}){if(typeof r=="number"){const n=2n**(BigInt(r)-(t?1n:0n))-1n,s=t?-n-1n:0n;if(e>n||e<s)throw new Vm({max:n.toString(),min:s.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:X(e,{size:32,signed:t})}}function q2(e){const t=mi(e),r=Math.ceil(He(t)/32),n=[];for(let s=0;s<r;s++)n.push(Kn(_s(t,s*32,(s+1)*32),{dir:"right"}));return{dynamic:!0,encoded:Vt([Kn(X(He(t),{size:32})),...n])}}function V2(e,{param:t}){let r=!1;const n=[];for(let s=0;s<t.components.length;s++){const i=t.components[s],o=Array.isArray(e)?s:i.name,a=fd({param:i,value:e[o]});n.push(a),a.dynamic&&(r=!0)}return{dynamic:r,encoded:r?dd(n):Vt(n.map(({encoded:s})=>s))}}function hd(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}const Yo=e=>_s(a0(e),0,4);function Fs(e){const{abi:t,args:r=[],name:n}=e,s=xr(n,{strict:!1}),i=t.filter(a=>s?a.type==="function"?Yo(a)===n:a.type==="event"?gc(a)===n:!1:"name"in a&&a.name===n);if(i.length===0)return;if(i.length===1)return i[0];let o;for(const a of i){if(!("inputs"in a))continue;if(!r||r.length===0){if(!a.inputs||a.inputs.length===0)return a;continue}if(!a.inputs||a.inputs.length===0||a.inputs.length!==r.length)continue;if(r.every((l,u)=>{const f="inputs"in a&&a.inputs[u];return f?of(l,f):!1})){if(o&&"inputs"in o&&o.inputs){const l=h0(a.inputs,o.inputs,r);if(l)throw new Vv({abiItem:a,type:l[0]},{abiItem:o,type:l[1]})}o=a}}return o||i[0]}function of(e,t){const r=typeof e,n=t.type;switch(n){case"address":return st(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((s,i)=>of(Object.values(e)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(e)&&e.every(s=>of(s,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function h0(e,t,r){for(const n in e){const s=e[n],i=t[n];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return h0(s.components,i.components,r[n]);const o=[s.type,i.type];if(o.includes("address")&&o.includes("bytes20")?!0:o.includes("address")&&o.includes("string")?st(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?st(r[n],{strict:!1}):!1)return o}}const qh="/docs/contract/encodeEventTopics";function Zo(e){var c;const{abi:t,eventName:r,args:n}=e;let s=t[0];if(r){const l=Fs({abi:t,name:r});if(!l)throw new Mh(r,{docsPath:qh});s=l}if(s.type!=="event")throw new Mh(void 0,{docsPath:qh});const i=Ar(s),o=gc(i);let a=[];if(n&&"inputs"in s){const l=(c=s.inputs)==null?void 0:c.filter(f=>"indexed"in f&&f.indexed),u=Array.isArray(n)?n:Object.values(n).length>0?(l==null?void 0:l.map(f=>n[f.name]))??[]:[];u.length>0&&(a=(l==null?void 0:l.map((f,p)=>Array.isArray(u[p])?u[p].map((d,m)=>Vh({param:f,value:u[p][m]})):typeof u[p]<"u"&&u[p]!==null?Vh({param:f,value:u[p]}):null))??[])}return[o,...a]}function Vh({param:e,value:t}){if(e.type==="string"||e.type==="bytes")return lt(Ii(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new Yv(e.type);return kn([e],[t])}function wc(e,{method:t}){var n,s;const r={};return e.transport.type==="fallback"&&((s=(n=e.transport).onResponse)==null||s.call(n,({method:i,response:o,status:a,transport:c})=>{a==="success"&&t===i&&(r[o]=c.request)})),i=>r[i]||e.request}async function pd(e,t){const{address:r,abi:n,args:s,eventName:i,fromBlock:o,strict:a,toBlock:c}=t,l=wc(e,{method:"eth_newFilter"}),u=i?Zo({abi:n,args:s,eventName:i}):void 0,f=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof o=="bigint"?X(o):o,toBlock:typeof c=="bigint"?X(c):c,topics:u}]});return{abi:n,args:s,eventName:i,id:f,request:l(f),strict:!!a,type:"event"}}function Xe(e){return typeof e=="string"?{address:e,type:"json-rpc"}:e}const Gh="/docs/contract/encodeFunctionData";function G2(e){const{abi:t,args:r,functionName:n}=e;let s=t[0];if(n){const i=Fs({abi:t,args:r,name:n});if(!i)throw new yi(n,{docsPath:Gh});s=i}if(s.type!=="function")throw new yi(void 0,{docsPath:Gh});return{abi:[s],functionName:Yo(Ar(s))}}function dr(e){const{args:t}=e,{abi:r,functionName:n}=(()=>{var a;return e.abi.length===1&&((a=e.functionName)!=null&&a.startsWith("0x"))?e:G2(e)})(),s=r[0],i=n,o="inputs"in s&&s.inputs?kn(s.inputs,t??[]):void 0;return Tr([i,o??"0x"])}const p0={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."},y0={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},W2={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};class Wh extends z{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class m0 extends z{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}}class K2 extends z{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}}const X2={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 K2({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new m0({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new Wh({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 Wh({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 yd(e,{recursiveReadLimit:t=8192}={}){const r=Object.create(X2);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}function Y2(e,t={}){typeof t.size<"u"&&kr(e,{size:t.size});const r=Je(e,t);return ot(r,t)}function Z2(e,t={}){let r=e;if(typeof t.size<"u"&&(kr(r,{size:t.size}),r=cr(r)),r.length>1||r[0]>1)throw new Jv(r);return!!r[0]}function gn(e,t={}){typeof t.size<"u"&&kr(e,{size:t.size});const r=Je(e,t);return ur(r,t)}function J2(e,t={}){let r=e;return typeof t.size<"u"&&(kr(r,{size:t.size}),r=cr(r,{dir:"right"})),new TextDecoder().decode(r)}function Jo(e,t){const r=typeof t=="string"?Sr(t):t,n=yd(r);if(He(r)===0&&e.length>0)throw new Ko;if(He(t)&&He(t)<32)throw new Fm({data:typeof t=="string"?t:Je(t),params:e,size:He(t)});let s=0;const i=[];for(let o=0;o<e.length;++o){const a=e[o];n.setPosition(s);const[c,l]=ai(n,a,{staticPosition:0});s+=l,i.push(c)}return i}function ai(e,t,{staticPosition:r}){const n=hd(t.type);if(n){const[s,i]=n;return eE(e,{...t,type:i},{length:s,staticPosition:r})}if(t.type==="tuple")return sE(e,t,{staticPosition:r});if(t.type==="address")return Q2(e);if(t.type==="bool")return tE(e);if(t.type.startsWith("bytes"))return rE(e,t,{staticPosition:r});if(t.type.startsWith("uint")||t.type.startsWith("int"))return nE(e,t);if(t.type==="string")return iE(e,{staticPosition:r});throw new Kv(t.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const Kh=32,af=32;function Q2(e){const t=e.readBytes(32);return[Xo(Je(f0(t,-20))),32]}function eE(e,t,{length:r,staticPosition:n}){if(!r){const o=gn(e.readBytes(af)),a=n+o,c=a+Kh;e.setPosition(a);const l=gn(e.readBytes(Kh)),u=go(t);let f=0;const p=[];for(let d=0;d<l;++d){e.setPosition(c+(u?d*32:f));const[m,g]=ai(e,t,{staticPosition:c});f+=g,p.push(m)}return e.setPosition(n+32),[p,32]}if(go(t)){const o=gn(e.readBytes(af)),a=n+o,c=[];for(let l=0;l<r;++l){e.setPosition(a+l*32);const[u]=ai(e,t,{staticPosition:a});c.push(u)}return e.setPosition(n+32),[c,32]}let s=0;const i=[];for(let o=0;o<r;++o){const[a,c]=ai(e,t,{staticPosition:n+s});s+=c,i.push(a)}return[i,s]}function tE(e){return[Z2(e.readBytes(32),{size:32}),32]}function rE(e,t,{staticPosition:r}){const[n,s]=t.type.split("bytes");if(!s){const o=gn(e.readBytes(32));e.setPosition(r+o);const a=gn(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];const c=e.readBytes(a);return e.setPosition(r+32),[Je(c),32]}return[Je(e.readBytes(Number.parseInt(s),32)),32]}function nE(e,t){const r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256"),s=e.readBytes(32);return[n>48?Y2(s,{signed:r}):gn(s,{signed:r}),32]}function sE(e,t,{staticPosition:r}){const n=t.components.length===0||t.components.some(({name:o})=>!o),s=n?[]:{};let i=0;if(go(t)){const o=gn(e.readBytes(af)),a=r+o;for(let c=0;c<t.components.length;++c){const l=t.components[c];e.setPosition(a+i);const[u,f]=ai(e,l,{staticPosition:a});i+=f,s[n?c:l==null?void 0:l.name]=u}return e.setPosition(r+32),[s,32]}for(let o=0;o<t.components.length;++o){const a=t.components[o],[c,l]=ai(e,a,{staticPosition:r});s[n?o:a==null?void 0:a.name]=c,i+=l}return[s,i]}function iE(e,{staticPosition:t}){const r=gn(e.readBytes(32)),n=t+r;e.setPosition(n);const s=gn(e.readBytes(32));if(s===0)return e.setPosition(t+32),["",32];const i=e.readBytes(s,32),o=J2(cr(i));return e.setPosition(t+32),[o,32]}function go(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(go);const r=hd(e.type);return!!(r&&go({...e,type:r[1]}))}function g0(e){const{abi:t,data:r}=e,n=_s(r,0,4);if(n==="0x")throw new Ko;const i=[...t||[],y0,W2].find(o=>o.type==="error"&&n===Yo(Ar(o)));if(!i)throw new jm(n,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:i,args:"inputs"in i&&i.inputs&&i.inputs.length>0?Jo(i.inputs,_s(r,4)):void 0,errorName:i.name}}const Ze=(e,t,r)=>JSON.stringify(e,(n,s)=>typeof s=="bigint"?s.toString():s,r);function b0({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((s,i)=>`${n&&s.name?`${s.name}: `:""}${typeof t[i]=="object"?Ze(t[i]):t[i]}`).join(", ")})`}const oE={gwei:9,wei:18},aE={ether:-9,wei:9};function w0(e,t){let r=e.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[s,i]=[r.slice(0,r.length-t),r.slice(r.length-t)];return i=i.replace(/(0+)$/,""),`${n?"-":""}${s||"0"}${i?`.${i}`:""}`}function md(e,t="wei"){return w0(e,oE[t])}function Ut(e,t="wei"){return w0(e,aE[t])}class cE extends z{constructor({address:t}){super(`State for account "${t}" is set multiple times.`,{name:"AccountStateConflictError"})}}class uE extends z{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function Xh(e){return e.reduce((t,{slot:r,value:n})=>`${t} ${r}: ${n}
|
|
22
|
+
`),{name:"InvalidDefinitionTypeError"})}}class Yv extends z{constructor(t){super(`Filter type "${t}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}let zm=class extends z{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},qm=class extends z{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 Fh extends z{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 Ti(e,{dir:t,size:r=32}={}){return typeof e=="string"?Kn(e,{dir:t,size:r}):Zv(e,{dir:t,size:r})}function Kn(e,{dir:t,size:r=32}={}){if(r===null)return e;const n=e.replace("0x","");if(n.length>r*2)throw new qm({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function Zv(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new qm({size:e.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let s=0;s<r;s++){const i=t==="right";n[i?s:r-s-1]=e[i?s:e.length-s-1]}return n}let Vm=class extends z{constructor({max:t,min:r,signed:n,size:s,value:i}){super(`Number "${i}" is not in safe ${s?`${s*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}};class Jv extends z{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 Qv extends z{constructor(t){super(`Hex value "${t}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}let e2=class extends z{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}};function cr(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let s=0;s<r.length-1&&r[t==="left"?s:r.length-s-1].toString()==="0";s++)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 kr(e,{size:t}){if(He(e)>t)throw new e2({givenSize:He(e),maxSize:t})}function ot(e,t={}){const{signed:r}=t;t.size&&kr(e,{size:t.size});const n=BigInt(e);if(!r)return n;const s=(e.length-2)/2,i=(1n<<BigInt(s)*8n-1n)-1n;return n<=i?n:n-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function t2(e,t={}){let r=e;if(t.size&&(kr(r,{size:t.size}),r=cr(r)),cr(r)==="0x00")return!1;if(cr(r)==="0x01")return!0;throw new Qv(r)}function ur(e,t={}){return Number(ot(e,t))}const r2=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function gt(e,t={}){return typeof e=="number"||typeof e=="bigint"?X(e,t):typeof e=="string"?mi(e,t):typeof e=="boolean"?Gm(e,t):Je(e,t)}function Gm(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?(kr(r,{size:t.size}),Ti(r,{size:t.size})):r}function Je(e,t={}){let r="";for(let s=0;s<e.length;s++)r+=r2[e[s]];const n=`0x${r}`;return typeof t.size=="number"?(kr(n,{size:t.size}),Ti(n,{dir:"right",size:t.size})):n}function X(e,t={}){const{signed:r,size:n}=t,s=BigInt(e);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<o){const c=typeof e=="bigint"?"n":"";throw new Vm({max:i?`${i}${c}`:void 0,min:`${o}${c}`,signed:r,size:n,value:`${e}${c}`})}const a=`0x${(r&&s<0?(1n<<BigInt(n*8))+BigInt(s):s).toString(16)}`;return n?Ti(a,{size:n}):a}const n2=new TextEncoder;function mi(e,t={}){const r=n2.encode(e);return Je(r,t)}const s2=new TextEncoder;function Ii(e,t={}){return typeof e=="number"||typeof e=="bigint"?o2(e,t):typeof e=="boolean"?i2(e,t):xr(e)?Sr(e,t):bs(e,t)}function i2(e,t={}){const r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?(kr(r,{size:t.size}),Ti(r,{size:t.size})):r}const Yr={zero:48,nine:57,A:65,F:70,a:97,f:102};function jh(e){if(e>=Yr.zero&&e<=Yr.nine)return e-Yr.zero;if(e>=Yr.A&&e<=Yr.F)return e-(Yr.A-10);if(e>=Yr.a&&e<=Yr.f)return e-(Yr.a-10)}function Sr(e,t={}){let r=e;t.size&&(kr(r,{size:t.size}),r=Ti(r,{dir:"right",size:t.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const s=n.length/2,i=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=jh(n.charCodeAt(a++)),l=jh(n.charCodeAt(a++));if(c===void 0||l===void 0)throw new z(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);i[o]=c*16+l}return i}function o2(e,t){const r=X(e,t);return Sr(r)}function bs(e,t={}){const r=s2.encode(e);return typeof t.size=="number"?(kr(r,{size:t.size}),Ti(r,{dir:"right",size:t.size})):r}const ha=BigInt(2**32-1),Lh=BigInt(32);function Wm(e,t=!1){return t?{h:Number(e&ha),l:Number(e>>Lh&ha)}:{h:Number(e>>Lh&ha)|0,l:Number(e&ha)|0}}function a2(e,t=!1){const r=e.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=Wm(e[i],t);[n[i],s[i]]=[o,a]}return[n,s]}const Km=(e,t,r)=>e>>>r|t<<32-r,Xm=(e,t,r)=>e<<32-r|t>>>r,c2=(e,t,r)=>e<<64-r|t>>>r-32,u2=(e,t,r)=>e>>>r-32|t<<64-r,l2=(e,t)=>t,f2=(e,t)=>e,d2=(e,t,r)=>e<<r|t>>>32-r,h2=(e,t,r)=>t<<r|e>>>32-r,p2=(e,t,r)=>t<<r-32|e>>>64-r,y2=(e,t,r)=>e<<r-32|t>>>64-r;function Ym(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:s|0}}const Zm=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Jm=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,Ws=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ad(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Zn(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function lr(e,...t){if(!ad(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 m2(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Zn(e.outputLen),Zn(e.blockLen)}function Jn(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 cd(e,t){lr(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function yo(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function _r(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function uu(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Br(e,t){return e<<32-t|e>>>t}function pa(e,t){return e<<t|e>>>32-t>>>0}const Qm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function e0(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const an=Qm?e=>e:e=>e0(e);function g2(e){for(let t=0;t<e.length;t++)e[t]=e0(e[t]);return e}const Hn=Qm?e=>e:g2,t0=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",b2=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function mo(e){if(lr(e),t0)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=b2[e[r]];return t}const Zr={_0:48,_9:57,A:65,F:70,a:97,f:102};function Dh(e){if(e>=Zr._0&&e<=Zr._9)return e-Zr._0;if(e>=Zr.A&&e<=Zr.F)return e-(Zr.A-10);if(e>=Zr.a&&e<=Zr.f)return e-(Zr.a-10)}function ud(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(t0)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 s=0,i=0;s<r;s++,i+=2){const o=Dh(e.charCodeAt(i)),a=Dh(e.charCodeAt(i+1));if(o===void 0||a===void 0){const c=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[s]=o*16+a}return n}function w2(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function mn(e){return typeof e=="string"&&(e=w2(e)),lr(e),e}function us(...e){let t=0;for(let n=0;n<e.length;n++){const s=e[n];lr(s),t+=s.length}const r=new Uint8Array(t);for(let n=0,s=0;n<e.length;n++){const i=e[n];r.set(i,s),s+=i.length}return r}class yc{}function mc(e){const t=n=>e().update(mn(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function v2(e){const t=(n,s)=>e(s).update(mn(n)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}function E2(e=32){if(Ws&&typeof Ws.getRandomValues=="function")return Ws.getRandomValues(new Uint8Array(e));if(Ws&&typeof Ws.randomBytes=="function")return Uint8Array.from(Ws.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const A2=BigInt(0),Mi=BigInt(1),x2=BigInt(2),S2=BigInt(7),_2=BigInt(256),k2=BigInt(113),r0=[],n0=[],s0=[];for(let e=0,t=Mi,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],r0.push(2*(5*n+r)),n0.push((e+1)*(e+2)/2%64);let s=A2;for(let i=0;i<7;i++)t=(t<<Mi^(t>>S2)*k2)%_2,t&x2&&(s^=Mi<<(Mi<<BigInt(i))-Mi);s0.push(s)}const i0=a2(s0,!0),T2=i0[0],I2=i0[1],Hh=(e,t,r)=>r>32?p2(e,t,r):d2(e,t,r),zh=(e,t,r)=>r>32?y2(e,t,r):h2(e,t,r);function P2(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let o=0;o<10;o++)r[o]=e[o]^e[o+10]^e[o+20]^e[o+30]^e[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],f=Hh(l,u,1)^r[a],p=zh(l,u,1)^r[a+1];for(let d=0;d<50;d+=10)e[o+d]^=f,e[o+d+1]^=p}let s=e[2],i=e[3];for(let o=0;o<24;o++){const a=n0[o],c=Hh(s,i,a),l=zh(s,i,a),u=r0[o];s=e[u],i=e[u+1],e[u]=c,e[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=e[o+a];for(let a=0;a<10;a++)e[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=T2[n],e[1]^=I2[n]}_r(r)}class ld extends yc{constructor(t,r,n,s=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=s,this.rounds=i,Zn(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=yo(this.state)}clone(){return this._cloneInto()}keccak(){Hn(this.state32),P2(this.state32,this.rounds),Hn(this.state32),this.posOut=0,this.pos=0}update(t){Jn(this),t=mn(t),lr(t);const{blockLen:r,state:n}=this,s=t.length;for(let i=0;i<s;){const o=Math.min(r-this.pos,s-i);for(let a=0;a<o;a++)n[this.pos++]^=t[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:r,pos:n,blockLen:s}=this;t[n]^=r,r&128&&n===s-1&&this.keccak(),t[s-1]^=128,this.keccak()}writeInto(t){Jn(this,!1),lr(t),this.finish();const r=this.state,{blockLen:n}=this;for(let s=0,i=t.length;s<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-s);t.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Zn(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(cd(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,_r(this.state)}_cloneInto(t){const{blockLen:r,suffix:n,outputLen:s,rounds:i,enableXOF:o}=this;return t||(t=new ld(r,n,s,o,i)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=n,t.outputLen=s,t.enableXOF=o,t.destroyed=this.destroyed,t}}const O2=(e,t,r)=>mc(()=>new ld(t,e,r)),o0=O2(1,136,256/8);function lt(e,t){const r=t||"hex",n=o0(xr(e,{strict:!1})?Ii(e):e);return r==="bytes"?n:gt(n)}const B2=e=>lt(Ii(e));function C2(e){return B2(e)}function R2(e){let t=!0,r="",n=0,s="",i=!1;for(let o=0;o<e.length;o++){const a=e[o];if(["(",")",","].includes(a)&&(t=!0),a==="("&&n++,a===")"&&n--,!!t){if(n===0){if(a===" "&&["event","function",""].includes(s))s="";else if(s+=a,a===")"){i=!0;break}continue}if(a===" "){e[o-1]!==","&&r!==","&&r!==",("&&(r="",t=!1);continue}s+=a,r+=a}}if(!i)throw new z("Unable to normalize signature.");return s}const $2=e=>{const t=typeof e=="string"?e:Ja(e);return R2(t)};function a0(e){return C2($2(e))}const gc=a0;let Bt=class extends z{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"})}},bc=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 lu=new bc(8192);function Xo(e,t){if(lu.has(`${e}.${t}`))return lu.get(`${e}.${t}`);const r=e.substring(2).toLowerCase(),n=lt(bs(r),"bytes"),s=r.split("");for(let o=0;o<40;o+=2)n[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(n[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const i=`0x${s.join("")}`;return lu.set(`${e}.${t}`,i),i}function c0(e,t){if(!st(e,{strict:!1}))throw new Bt({address:e});return Xo(e,t)}const N2=/^0x[a-fA-F0-9]{40}$/,fu=new bc(8192);function st(e,t){const{strict:r=!0}=t??{},n=`${e}.${r}`;if(fu.has(n))return fu.get(n);const s=N2.test(e)?e.toLowerCase()===e?!0:r?Xo(e)===e:!0:!1;return fu.set(n,s),s}function Vt(e){return typeof e[0]=="string"?Tr(e):U2(e)}function U2(e){let t=0;for(const s of e)t+=s.length;const r=new Uint8Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.length;return r}function Tr(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function _s(e,t,r,{strict:n}={}){return xr(e,{strict:!1})?Qa(e,t,r,{strict:n}):f0(e,t,r,{strict:n})}function u0(e,t){if(typeof t=="number"&&t>0&&t>He(e)-1)throw new zm({offset:t,position:"start",size:He(e)})}function l0(e,t,r){if(typeof t=="number"&&typeof r=="number"&&He(e)!==r-t)throw new zm({offset:r,position:"end",size:He(e)})}function f0(e,t,r,{strict:n}={}){u0(e,t);const s=e.slice(t,r);return n&&l0(s,t,r),s}function Qa(e,t,r,{strict:n}={}){u0(e,t);const s=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return n&&l0(s,t,r),s}const M2=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,d0=/^(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 kn(e,t){if(e.length!==t.length)throw new Dv({expectedLength:e.length,givenLength:t.length});const r=F2({params:e,values:t}),n=dd(r);return n.length===0?"0x":n}function F2({params:e,values:t}){const r=[];for(let n=0;n<e.length;n++)r.push(fd({param:e[n],value:t[n]}));return r}function fd({param:e,value:t}){const r=hd(e.type);if(r){const[n,s]=r;return L2(t,{length:n,param:{...e,type:s}})}if(e.type==="tuple")return V2(t,{param:e});if(e.type==="address")return j2(t);if(e.type==="bool")return H2(t);if(e.type.startsWith("uint")||e.type.startsWith("int")){const n=e.type.startsWith("int"),[,,s="256"]=d0.exec(e.type)??[];return z2(t,{signed:n,size:Number(s)})}if(e.type.startsWith("bytes"))return D2(t,{param:e});if(e.type==="string")return q2(t);throw new Wv(e.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function dd(e){let t=0;for(let i=0;i<e.length;i++){const{dynamic:o,encoded:a}=e[i];o?t+=32:t+=He(a)}const r=[],n=[];let s=0;for(let i=0;i<e.length;i++){const{dynamic:o,encoded:a}=e[i];o?(r.push(X(t+s,{size:32})),n.push(a),s+=He(a)):r.push(a)}return Vt([...r,...n])}function j2(e){if(!st(e))throw new Bt({address:e});return{dynamic:!1,encoded:Kn(e.toLowerCase())}}function L2(e,{length:t,param:r}){const n=t===null;if(!Array.isArray(e))throw new Hm(e);if(!n&&e.length!==t)throw new jv({expectedLength:t,givenLength:e.length,type:`${r.type}[${t}]`});let s=!1;const i=[];for(let o=0;o<e.length;o++){const a=fd({param:r,value:e[o]});a.dynamic&&(s=!0),i.push(a)}if(n||s){const o=dd(i);if(n){const a=X(i.length,{size:32});return{dynamic:!0,encoded:i.length>0?Vt([a,o]):a}}if(s)return{dynamic:!0,encoded:o}}return{dynamic:!1,encoded:Vt(i.map(({encoded:o})=>o))}}function D2(e,{param:t}){const[,r]=t.type.split("bytes"),n=He(e);if(!r){let s=e;return n%32!==0&&(s=Kn(s,{dir:"right",size:Math.ceil((e.length-2)/2/32)*32})),{dynamic:!0,encoded:Vt([Kn(X(n,{size:32})),s])}}if(n!==Number.parseInt(r))throw new Lv({expectedSize:Number.parseInt(r),value:e});return{dynamic:!1,encoded:Kn(e,{dir:"right"})}}function H2(e){if(typeof e!="boolean")throw new z(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Kn(Gm(e))}}function z2(e,{signed:t,size:r=256}){if(typeof r=="number"){const n=2n**(BigInt(r)-(t?1n:0n))-1n,s=t?-n-1n:0n;if(e>n||e<s)throw new Vm({max:n.toString(),min:s.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:X(e,{size:32,signed:t})}}function q2(e){const t=mi(e),r=Math.ceil(He(t)/32),n=[];for(let s=0;s<r;s++)n.push(Kn(_s(t,s*32,(s+1)*32),{dir:"right"}));return{dynamic:!0,encoded:Vt([Kn(X(He(t),{size:32})),...n])}}function V2(e,{param:t}){let r=!1;const n=[];for(let s=0;s<t.components.length;s++){const i=t.components[s],o=Array.isArray(e)?s:i.name,a=fd({param:i,value:e[o]});n.push(a),a.dynamic&&(r=!0)}return{dynamic:r,encoded:r?dd(n):Vt(n.map(({encoded:s})=>s))}}function hd(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}const Yo=e=>_s(a0(e),0,4);function Fs(e){const{abi:t,args:r=[],name:n}=e,s=xr(n,{strict:!1}),i=t.filter(a=>s?a.type==="function"?Yo(a)===n:a.type==="event"?gc(a)===n:!1:"name"in a&&a.name===n);if(i.length===0)return;if(i.length===1)return i[0];let o;for(const a of i){if(!("inputs"in a))continue;if(!r||r.length===0){if(!a.inputs||a.inputs.length===0)return a;continue}if(!a.inputs||a.inputs.length===0||a.inputs.length!==r.length)continue;if(r.every((l,u)=>{const f="inputs"in a&&a.inputs[u];return f?of(l,f):!1})){if(o&&"inputs"in o&&o.inputs){const l=h0(a.inputs,o.inputs,r);if(l)throw new Vv({abiItem:a,type:l[0]},{abiItem:o,type:l[1]})}o=a}}return o||i[0]}function of(e,t){const r=typeof e,n=t.type;switch(n){case"address":return st(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((s,i)=>of(Object.values(e)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(e)&&e.every(s=>of(s,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function h0(e,t,r){for(const n in e){const s=e[n],i=t[n];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return h0(s.components,i.components,r[n]);const o=[s.type,i.type];if(o.includes("address")&&o.includes("bytes20")?!0:o.includes("address")&&o.includes("string")?st(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?st(r[n],{strict:!1}):!1)return o}}const qh="/docs/contract/encodeEventTopics";function Zo(e){var c;const{abi:t,eventName:r,args:n}=e;let s=t[0];if(r){const l=Fs({abi:t,name:r});if(!l)throw new Mh(r,{docsPath:qh});s=l}if(s.type!=="event")throw new Mh(void 0,{docsPath:qh});const i=Ar(s),o=gc(i);let a=[];if(n&&"inputs"in s){const l=(c=s.inputs)==null?void 0:c.filter(f=>"indexed"in f&&f.indexed),u=Array.isArray(n)?n:Object.values(n).length>0?(l==null?void 0:l.map(f=>n[f.name]))??[]:[];u.length>0&&(a=(l==null?void 0:l.map((f,p)=>Array.isArray(u[p])?u[p].map((d,m)=>Vh({param:f,value:u[p][m]})):typeof u[p]<"u"&&u[p]!==null?Vh({param:f,value:u[p]}):null))??[])}return[o,...a]}function Vh({param:e,value:t}){if(e.type==="string"||e.type==="bytes")return lt(Ii(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new Yv(e.type);return kn([e],[t])}function wc(e,{method:t}){var n,s;const r={};return e.transport.type==="fallback"&&((s=(n=e.transport).onResponse)==null||s.call(n,({method:i,response:o,status:a,transport:c})=>{a==="success"&&t===i&&(r[o]=c.request)})),i=>r[i]||e.request}async function pd(e,t){const{address:r,abi:n,args:s,eventName:i,fromBlock:o,strict:a,toBlock:c}=t,l=wc(e,{method:"eth_newFilter"}),u=i?Zo({abi:n,args:s,eventName:i}):void 0,f=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof o=="bigint"?X(o):o,toBlock:typeof c=="bigint"?X(c):c,topics:u}]});return{abi:n,args:s,eventName:i,id:f,request:l(f),strict:!!a,type:"event"}}function Xe(e){return typeof e=="string"?{address:e,type:"json-rpc"}:e}const Gh="/docs/contract/encodeFunctionData";function G2(e){const{abi:t,args:r,functionName:n}=e;let s=t[0];if(n){const i=Fs({abi:t,args:r,name:n});if(!i)throw new yi(n,{docsPath:Gh});s=i}if(s.type!=="function")throw new yi(void 0,{docsPath:Gh});return{abi:[s],functionName:Yo(Ar(s))}}function dr(e){const{args:t}=e,{abi:r,functionName:n}=(()=>{var a;return e.abi.length===1&&((a=e.functionName)!=null&&a.startsWith("0x"))?e:G2(e)})(),s=r[0],i=n,o="inputs"in s&&s.inputs?kn(s.inputs,t??[]):void 0;return Tr([i,o??"0x"])}const p0={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."},y0={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},W2={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};class Wh extends z{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class m0 extends z{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}}class K2 extends z{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}}const X2={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 K2({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new m0({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new Wh({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 Wh({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 yd(e,{recursiveReadLimit:t=8192}={}){const r=Object.create(X2);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}function Y2(e,t={}){typeof t.size<"u"&&kr(e,{size:t.size});const r=Je(e,t);return ot(r,t)}function Z2(e,t={}){let r=e;if(typeof t.size<"u"&&(kr(r,{size:t.size}),r=cr(r)),r.length>1||r[0]>1)throw new Jv(r);return!!r[0]}function gn(e,t={}){typeof t.size<"u"&&kr(e,{size:t.size});const r=Je(e,t);return ur(r,t)}function J2(e,t={}){let r=e;return typeof t.size<"u"&&(kr(r,{size:t.size}),r=cr(r,{dir:"right"})),new TextDecoder().decode(r)}function Jo(e,t){const r=typeof t=="string"?Sr(t):t,n=yd(r);if(He(r)===0&&e.length>0)throw new Ko;if(He(t)&&He(t)<32)throw new Fm({data:typeof t=="string"?t:Je(t),params:e,size:He(t)});let s=0;const i=[];for(let o=0;o<e.length;++o){const a=e[o];n.setPosition(s);const[c,l]=ai(n,a,{staticPosition:0});s+=l,i.push(c)}return i}function ai(e,t,{staticPosition:r}){const n=hd(t.type);if(n){const[s,i]=n;return eE(e,{...t,type:i},{length:s,staticPosition:r})}if(t.type==="tuple")return sE(e,t,{staticPosition:r});if(t.type==="address")return Q2(e);if(t.type==="bool")return tE(e);if(t.type.startsWith("bytes"))return rE(e,t,{staticPosition:r});if(t.type.startsWith("uint")||t.type.startsWith("int"))return nE(e,t);if(t.type==="string")return iE(e,{staticPosition:r});throw new Kv(t.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const Kh=32,af=32;function Q2(e){const t=e.readBytes(32);return[Xo(Je(f0(t,-20))),32]}function eE(e,t,{length:r,staticPosition:n}){if(!r){const o=gn(e.readBytes(af)),a=n+o,c=a+Kh;e.setPosition(a);const l=gn(e.readBytes(Kh)),u=go(t);let f=0;const p=[];for(let d=0;d<l;++d){e.setPosition(c+(u?d*32:f));const[m,g]=ai(e,t,{staticPosition:c});f+=g,p.push(m)}return e.setPosition(n+32),[p,32]}if(go(t)){const o=gn(e.readBytes(af)),a=n+o,c=[];for(let l=0;l<r;++l){e.setPosition(a+l*32);const[u]=ai(e,t,{staticPosition:a});c.push(u)}return e.setPosition(n+32),[c,32]}let s=0;const i=[];for(let o=0;o<r;++o){const[a,c]=ai(e,t,{staticPosition:n+s});s+=c,i.push(a)}return[i,s]}function tE(e){return[Z2(e.readBytes(32),{size:32}),32]}function rE(e,t,{staticPosition:r}){const[n,s]=t.type.split("bytes");if(!s){const o=gn(e.readBytes(32));e.setPosition(r+o);const a=gn(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];const c=e.readBytes(a);return e.setPosition(r+32),[Je(c),32]}return[Je(e.readBytes(Number.parseInt(s),32)),32]}function nE(e,t){const r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256"),s=e.readBytes(32);return[n>48?Y2(s,{signed:r}):gn(s,{signed:r}),32]}function sE(e,t,{staticPosition:r}){const n=t.components.length===0||t.components.some(({name:o})=>!o),s=n?[]:{};let i=0;if(go(t)){const o=gn(e.readBytes(af)),a=r+o;for(let c=0;c<t.components.length;++c){const l=t.components[c];e.setPosition(a+i);const[u,f]=ai(e,l,{staticPosition:a});i+=f,s[n?c:l==null?void 0:l.name]=u}return e.setPosition(r+32),[s,32]}for(let o=0;o<t.components.length;++o){const a=t.components[o],[c,l]=ai(e,a,{staticPosition:r});s[n?o:a==null?void 0:a.name]=c,i+=l}return[s,i]}function iE(e,{staticPosition:t}){const r=gn(e.readBytes(32)),n=t+r;e.setPosition(n);const s=gn(e.readBytes(32));if(s===0)return e.setPosition(t+32),["",32];const i=e.readBytes(s,32),o=J2(cr(i));return e.setPosition(t+32),[o,32]}function go(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(go);const r=hd(e.type);return!!(r&&go({...e,type:r[1]}))}function g0(e){const{abi:t,data:r}=e,n=_s(r,0,4);if(n==="0x")throw new Ko;const i=[...t||[],y0,W2].find(o=>o.type==="error"&&n===Yo(Ar(o)));if(!i)throw new jm(n,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:i,args:"inputs"in i&&i.inputs&&i.inputs.length>0?Jo(i.inputs,_s(r,4)):void 0,errorName:i.name}}const Ze=(e,t,r)=>JSON.stringify(e,(n,s)=>typeof s=="bigint"?s.toString():s,r);function b0({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((s,i)=>`${n&&s.name?`${s.name}: `:""}${typeof t[i]=="object"?Ze(t[i]):t[i]}`).join(", ")})`}const oE={gwei:9,wei:18},aE={ether:-9,wei:9};function w0(e,t){let r=e.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[s,i]=[r.slice(0,r.length-t),r.slice(r.length-t)];return i=i.replace(/(0+)$/,""),`${n?"-":""}${s||"0"}${i?`.${i}`:""}`}function md(e,t="wei"){return w0(e,oE[t])}function Ut(e,t="wei"){return w0(e,aE[t])}class cE extends z{constructor({address:t}){super(`State for account "${t}" is set multiple times.`,{name:"AccountStateConflictError"})}}class uE extends z{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function Xh(e){return e.reduce((t,{slot:r,value:n})=>`${t} ${r}: ${n}
|
|
23
23
|
`,"")}function lE(e){return e.reduce((t,{address:r,...n})=>{let s=`${t} ${r}:
|
|
24
24
|
`;return n.nonce&&(s+=` nonce: ${n.nonce}
|
|
25
25
|
`),n.balance&&(s+=` balance: ${n.balance}
|
|
@@ -33,24 +33,24 @@
|
|
|
33
33
|
${lE(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 bE extends z{constructor(t,{abi:r,args:n,contractAddress:s,docsPath:i,functionName:o,sender:a}){const c=Fs({abi:r,args:n,name:o}),l=c?b0({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,u=c?Ar(c,{includeName:!0}):void 0,f=Qo({address:s&&gE(s),function:u,args:l&&l!=="()"&&`${[...Array((o==null?void 0:o.length)??0).keys()].map(()=>" ").join("")}${l}`,sender:a});super(t.shortMessage||`An unknown error occurred while executing the contract function "${o}".`,{cause:t,docsPath:i,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],f&&"Contract Call:",f].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=r,this.args=n,this.cause=t,this.contractAddress=s,this.functionName=o,this.sender=a}}class cf extends z{constructor({abi:t,data:r,functionName:n,message:s}){let i,o,a,c;if(r&&r!=="0x")try{o=g0({abi:t,data:r});const{abiItem:u,errorName:f,args:p}=o;if(f==="Error")c=p[0];else if(f==="Panic"){const[d]=p;c=p0[d]}else{const d=u?Ar(u,{includeName:!0}):void 0,m=u&&p?b0({abiItem:u,args:p,includeFunctionName:!1,includeName:!1}):void 0;a=[d?`Error: ${d}`:"",m&&m!=="()"?` ${[...Array((f==null?void 0:f.length)??0).keys()].map(()=>" ").join("")}${m}`:""]}}catch(u){i=u}else s&&(c=s);let l;i instanceof jm&&(l=i.signature,a=[`Unable to decode signature "${l}" 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=${l}.`]),super(c&&c!=="execution reverted"||l?[`The contract function "${n}" reverted with the following ${l?"signature":"reason"}:`,c||l].join(`
|
|
34
34
|
`):`The contract function "${n}" reverted.`,{cause:i,metaMessages:a,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=o,this.raw=r,this.reason=c,this.signature=l}}class wE extends z{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 vE extends z{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 Ec extends z{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 ci extends z{constructor({body:t,cause:r,details:n,headers:s,status:i,url:o}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[i&&`Status: ${i}`,`URL: ${vc(o)}`,t&&`Request body: ${Ze(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=s,this.status=i,this.url=o}}class gd extends z{constructor({body:t,error:r,url:n}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[`URL: ${vc(n)}`,`Request body: ${Ze(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}),this.code=r.code,this.data=r.data}}class Yh extends z{constructor({body:t,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${vc(r)}`,`Request body: ${Ze(t)}`],name:"TimeoutError"})}}const EE=-1;class Ft extends z{constructor(t,{code:r,docsPath:n,metaMessages:s,name:i,shortMessage:o}){super(o,{cause:t,docsPath:n,metaMessages:s||(t==null?void 0:t.metaMessages),name:i||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i||t.name,this.code=t instanceof gd?t.code:r??EE}}class Xt extends Ft{constructor(t,r){super(t,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}}class bo extends Ft{constructor(t){super(t,{code:bo.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(bo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class wo extends Ft{constructor(t){super(t,{code:wo.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(wo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class vo extends Ft{constructor(t,{method:r}={}){super(t,{code:vo.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}}Object.defineProperty(vo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class Eo extends Ft{constructor(t){super(t,{code:Eo.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
|
|
35
35
|
`)})}}Object.defineProperty(Eo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class ks extends Ft{constructor(t){super(t,{code:ks.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(ks,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class Ts extends Ft{constructor(t){super(t,{code:Ts.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
|
|
36
|
-
`)})}}Object.defineProperty(Ts,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class Ao extends Ft{constructor(t){super(t,{code:Ao.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(Ao,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class xo extends Ft{constructor(t){super(t,{code:xo.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(xo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class So extends Ft{constructor(t){super(t,{code:So.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(So,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class ls extends Ft{constructor(t,{method:r}={}){super(t,{code:ls.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}}Object.defineProperty(ls,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class gi extends Ft{constructor(t){super(t,{code:gi.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(gi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class _o extends Ft{constructor(t){super(t,{code:_o.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(_o,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class ui extends Xt{constructor(t){super(t,{code:ui.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(ui,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class ko extends Xt{constructor(t){super(t,{code:ko.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(ko,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class To extends Xt{constructor(t,{method:r}={}){super(t,{code:To.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}}Object.defineProperty(To,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Io extends Xt{constructor(t){super(t,{code:Io.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Io,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class Po extends Xt{constructor(t){super(t,{code:Po.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Po,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class Oo extends Xt{constructor(t){super(t,{code:Oo.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(Oo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class bi extends Xt{constructor(t){super(t,{code:bi.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(bi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class Bo extends Xt{constructor(t){super(t,{code:Bo.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(Bo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class Co extends Xt{constructor(t){super(t,{code:Co.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(Co,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class Ro extends Xt{constructor(t){super(t,{code:Ro.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(Ro,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class $o extends Xt{constructor(t){super(t,{code:$o.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty($o,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class No extends Xt{constructor(t){super(t,{code:No.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(No,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class wi extends Xt{constructor(t){super(t,{code:wi.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(wi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class AE extends Ft{constructor(t){super(t,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const xE=3;function Is(e,{abi:t,address:r,args:n,docsPath:s,functionName:i,sender:o}){const a=e instanceof Ec?e:e instanceof z?e.walk(m=>"data"in m)||e.walk():{},{code:c,data:l,details:u,message:f,shortMessage:p}=a,d=e instanceof Ko?new wE({functionName:i}):[xE,ks.code].includes(c)&&(l||u||f||p)?new cf({abi:t,data:typeof l=="object"?l.data:l,functionName:i,message:a instanceof gd?u:p??f}):e;return new bE(d,{abi:t,args:n,contractAddress:r,docsPath:s,functionName:i,sender:o})}function SE(e){const t=lt(`0x${e.substring(4)}`).substring(26);return Xo(`0x${t}`)}async function _E({hash:e,signature:t}){const r=xr(e)?e:mt(e),{secp256k1:n}=await Promise.resolve().then(()=>kS);return`0x${(()=>{if(typeof t=="object"&&"r"in t&&"s"in t){const{r:l,s:u,v:f,yParity:p}=t,d=Number(p??f),m=Zh(d);return new n.Signature(ot(l),ot(u)).addRecoveryBit(m)}const o=xr(t)?t:mt(t);if(He(o)!==65)throw new Error("invalid signature length");const a=ur(`0x${o.slice(130)}`),c=Zh(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Zh(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 x0({hash:e,signature:t}){return SE(await _E({hash:e,signature:t}))}function Qn(e,t="hex"){const r=S0(e),n=yd(new Uint8Array(r.length));return r.encode(n),t==="hex"?Je(n.bytes):n.bytes}function S0(e){return Array.isArray(e)?kE(e.map(t=>S0(t))):TE(e)}function kE(e){const t=e.reduce((s,i)=>s+i.length,0),r=_0(t);return{length:t<=55?1+t:1+r+t,encode(s){t<=55?s.pushByte(192+t):(s.pushByte(247+r),r===1?s.pushUint8(t):r===2?s.pushUint16(t):r===3?s.pushUint24(t):s.pushUint32(t));for(const{encode:i}of e)i(s)}}}function TE(e){const t=typeof e=="string"?Sr(e):e,r=_0(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(s){t.length===1&&t[0]<128?s.pushBytes(t):t.length<=55?(s.pushByte(128+t.length),s.pushBytes(t)):(s.pushByte(183+r),r===1?s.pushUint8(t.length):r===2?s.pushUint16(t.length):r===3?s.pushUint24(t.length):s.pushUint32(t.length),s.pushBytes(t))}}}function _0(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 z("Length is too large.")}function IE(e){const{chainId:t,nonce:r,to:n}=e,s=e.contractAddress??e.address,i=lt(Tr(["0x05",Qn([t?X(t):"0x",s,r?X(r):"0x"])]));return n==="bytes"?Sr(i):i}async function k0(e){const{authorization:t,signature:r}=e;return x0({hash:IE(t),signature:r??t})}class PE extends z{constructor(t,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:l,nonce:u,to:f,value:p}){var m;const d=Qo({from:r==null?void 0:r.address,to:f,value:typeof p<"u"&&`${md(p)} ${((m=s==null?void 0:s.nativeCurrency)==null?void 0:m.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${Ut(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Ut(c)} gwei`,maxPriorityFeePerGas:typeof l<"u"&&`${Ut(l)} gwei`,nonce:u});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 ii extends z{constructor({cause:t,message:r}={}){var s;const n=(s=r==null?void 0:r.replace("execution reverted: ",""))==null?void 0:s.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:t,name:"ExecutionRevertedError"})}}Object.defineProperty(ii,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(ii,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});class Ps extends z{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Ut(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}}Object.defineProperty(Ps,"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 uf extends z{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Ut(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:t,name:"FeeCapTooLowError"})}}Object.defineProperty(uf,"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 lf extends z{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(lf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class ff extends z{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(`
|
|
36
|
+
`)})}}Object.defineProperty(Ts,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class Ao extends Ft{constructor(t){super(t,{code:Ao.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(Ao,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class xo extends Ft{constructor(t){super(t,{code:xo.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(xo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class So extends Ft{constructor(t){super(t,{code:So.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(So,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class ls extends Ft{constructor(t,{method:r}={}){super(t,{code:ls.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}}Object.defineProperty(ls,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class gi extends Ft{constructor(t){super(t,{code:gi.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(gi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class _o extends Ft{constructor(t){super(t,{code:_o.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(_o,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class ui extends Xt{constructor(t){super(t,{code:ui.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(ui,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class ko extends Xt{constructor(t){super(t,{code:ko.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(ko,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class To extends Xt{constructor(t,{method:r}={}){super(t,{code:To.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}}Object.defineProperty(To,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Io extends Xt{constructor(t){super(t,{code:Io.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Io,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class Po extends Xt{constructor(t){super(t,{code:Po.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Po,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class Oo extends Xt{constructor(t){super(t,{code:Oo.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(Oo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class bi extends Xt{constructor(t){super(t,{code:bi.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(bi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class Bo extends Xt{constructor(t){super(t,{code:Bo.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(Bo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class Co extends Xt{constructor(t){super(t,{code:Co.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(Co,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class Ro extends Xt{constructor(t){super(t,{code:Ro.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(Ro,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class $o extends Xt{constructor(t){super(t,{code:$o.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty($o,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class No extends Xt{constructor(t){super(t,{code:No.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(No,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class wi extends Xt{constructor(t){super(t,{code:wi.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(wi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class AE extends Ft{constructor(t){super(t,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const xE=3;function Is(e,{abi:t,address:r,args:n,docsPath:s,functionName:i,sender:o}){const a=e instanceof Ec?e:e instanceof z?e.walk(m=>"data"in m)||e.walk():{},{code:c,data:l,details:u,message:f,shortMessage:p}=a,d=e instanceof Ko?new wE({functionName:i}):[xE,ks.code].includes(c)&&(l||u||f||p)?new cf({abi:t,data:typeof l=="object"?l.data:l,functionName:i,message:a instanceof gd?u:p??f}):e;return new bE(d,{abi:t,args:n,contractAddress:r,docsPath:s,functionName:i,sender:o})}function SE(e){const t=lt(`0x${e.substring(4)}`).substring(26);return Xo(`0x${t}`)}async function _E({hash:e,signature:t}){const r=xr(e)?e:gt(e),{secp256k1:n}=await Promise.resolve().then(()=>kS);return`0x${(()=>{if(typeof t=="object"&&"r"in t&&"s"in t){const{r:l,s:u,v:f,yParity:p}=t,d=Number(p??f),m=Zh(d);return new n.Signature(ot(l),ot(u)).addRecoveryBit(m)}const o=xr(t)?t:gt(t);if(He(o)!==65)throw new Error("invalid signature length");const a=ur(`0x${o.slice(130)}`),c=Zh(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Zh(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 x0({hash:e,signature:t}){return SE(await _E({hash:e,signature:t}))}function Qn(e,t="hex"){const r=S0(e),n=yd(new Uint8Array(r.length));return r.encode(n),t==="hex"?Je(n.bytes):n.bytes}function S0(e){return Array.isArray(e)?kE(e.map(t=>S0(t))):TE(e)}function kE(e){const t=e.reduce((s,i)=>s+i.length,0),r=_0(t);return{length:t<=55?1+t:1+r+t,encode(s){t<=55?s.pushByte(192+t):(s.pushByte(247+r),r===1?s.pushUint8(t):r===2?s.pushUint16(t):r===3?s.pushUint24(t):s.pushUint32(t));for(const{encode:i}of e)i(s)}}}function TE(e){const t=typeof e=="string"?Sr(e):e,r=_0(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(s){t.length===1&&t[0]<128?s.pushBytes(t):t.length<=55?(s.pushByte(128+t.length),s.pushBytes(t)):(s.pushByte(183+r),r===1?s.pushUint8(t.length):r===2?s.pushUint16(t.length):r===3?s.pushUint24(t.length):s.pushUint32(t.length),s.pushBytes(t))}}}function _0(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 z("Length is too large.")}function IE(e){const{chainId:t,nonce:r,to:n}=e,s=e.contractAddress??e.address,i=lt(Tr(["0x05",Qn([t?X(t):"0x",s,r?X(r):"0x"])]));return n==="bytes"?Sr(i):i}async function k0(e){const{authorization:t,signature:r}=e;return x0({hash:IE(t),signature:r??t})}class PE extends z{constructor(t,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:l,nonce:u,to:f,value:p}){var m;const d=Qo({from:r==null?void 0:r.address,to:f,value:typeof p<"u"&&`${md(p)} ${((m=s==null?void 0:s.nativeCurrency)==null?void 0:m.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${Ut(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Ut(c)} gwei`,maxPriorityFeePerGas:typeof l<"u"&&`${Ut(l)} gwei`,nonce:u});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 ii extends z{constructor({cause:t,message:r}={}){var s;const n=(s=r==null?void 0:r.replace("execution reverted: ",""))==null?void 0:s.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:t,name:"ExecutionRevertedError"})}}Object.defineProperty(ii,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(ii,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});class Ps extends z{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Ut(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}}Object.defineProperty(Ps,"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 uf extends z{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Ut(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:t,name:"FeeCapTooLowError"})}}Object.defineProperty(uf,"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 lf extends z{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(lf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class ff extends z{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(`
|
|
37
37
|
`),{cause:t,name:"NonceTooLowError"})}}Object.defineProperty(ff,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class df extends z{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:t,name:"NonceMaxValueError"})}}Object.defineProperty(df,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class hf extends z{constructor({cause:t}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
|
|
38
38
|
`),{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(hf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class pf extends z{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(pf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class yf extends z{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(yf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class mf extends z{constructor({cause:t}){super("The transaction type is not supported for this chain.",{cause:t,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(mf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class Uo extends z{constructor({cause:t,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${Ut(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${Ut(n)} gwei`:""}).`].join(`
|
|
39
|
-
`),{cause:t,name:"TipAboveFeeCapError"})}}Object.defineProperty(Uo,"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 ea extends z{constructor({cause:t}){super(`An error occurred while executing: ${t==null?void 0:t.shortMessage}`,{cause:t,name:"UnknownNodeError"})}}function Ac(e,t){const r=(e.details||"").toLowerCase(),n=e instanceof z?e.walk(s=>(s==null?void 0:s.code)===ii.code):e;return n instanceof z?new ii({cause:e,message:n.details}):ii.nodeMessage.test(r)?new ii({cause:e,message:e.details}):Ps.nodeMessage.test(r)?new Ps({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):uf.nodeMessage.test(r)?new uf({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):lf.nodeMessage.test(r)?new lf({cause:e,nonce:t==null?void 0:t.nonce}):ff.nodeMessage.test(r)?new ff({cause:e,nonce:t==null?void 0:t.nonce}):df.nodeMessage.test(r)?new df({cause:e,nonce:t==null?void 0:t.nonce}):hf.nodeMessage.test(r)?new hf({cause:e}):pf.nodeMessage.test(r)?new pf({cause:e,gas:t==null?void 0:t.gas}):yf.nodeMessage.test(r)?new yf({cause:e,gas:t==null?void 0:t.gas}):mf.nodeMessage.test(r)?new mf({cause:e}):Uo.nodeMessage.test(r)?new Uo({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas,maxPriorityFeePerGas:t==null?void 0:t.maxPriorityFeePerGas}):new ea({cause:e})}function OE(e,{docsPath:t,...r}){const n=(()=>{const s=Ac(e,r);return s instanceof ea?e:s})();return new PE(n,{docsPath:t,...r})}function xc(e,{format:t}){if(!t)return{};const r={};function n(i){const o=Object.keys(i);for(const a of o)a in e&&(r[a]=e[a]),i[a]&&typeof i[a]=="object"&&!Array.isArray(i[a])&&n(i[a])}const s=t(e||{});return n(s),r}function bd(e,t){return({exclude:r,format:n})=>({exclude:r,format:s=>{const i=t(s);if(r)for(const o of r)delete i[o];return{...i,...n(s)}},type:e})}const BE={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function Pi(e){const t={};return typeof e.authorizationList<"u"&&(t.authorizationList=CE(e.authorizationList)),typeof e.accessList<"u"&&(t.accessList=e.accessList),typeof e.blobVersionedHashes<"u"&&(t.blobVersionedHashes=e.blobVersionedHashes),typeof e.blobs<"u"&&(typeof e.blobs[0]!="string"?t.blobs=e.blobs.map(r=>Je(r)):t.blobs=e.blobs),typeof e.data<"u"&&(t.data=e.data),typeof e.from<"u"&&(t.from=e.from),typeof e.gas<"u"&&(t.gas=X(e.gas)),typeof e.gasPrice<"u"&&(t.gasPrice=X(e.gasPrice)),typeof e.maxFeePerBlobGas<"u"&&(t.maxFeePerBlobGas=X(e.maxFeePerBlobGas)),typeof e.maxFeePerGas<"u"&&(t.maxFeePerGas=X(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(t.maxPriorityFeePerGas=X(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(t.nonce=X(e.nonce)),typeof e.to<"u"&&(t.to=e.to),typeof e.type<"u"&&(t.type=BE[e.type]),typeof e.value<"u"&&(t.value=X(e.value)),t}function CE(e){return e.map(t=>({address:t.address,r:t.r?X(BigInt(t.r)):t.r,s:t.s?X(BigInt(t.s)):t.s,chainId:X(t.chainId),nonce:X(t.nonce),...typeof t.yParity<"u"?{yParity:X(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:X(t.v)}:{}}))}function Jh(e){if(!(!e||e.length===0))return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new Fh({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new Fh({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function RE(e){const{balance:t,nonce:r,state:n,stateDiff:s,code:i}=e,o={};if(i!==void 0&&(o.code=i),t!==void 0&&(o.balance=X(t)),r!==void 0&&(o.nonce=X(r)),n!==void 0&&(o.state=Jh(n)),s!==void 0){if(o.state)throw new uE;o.stateDiff=Jh(s)}return o}function wd(e){if(!e)return;const t={};for(const{address:r,...n}of e){if(!st(r,{strict:!1}))throw new Bt({address:r});if(t[r])throw new cE({address:r});t[r]=RE(n)}return t}const Sc=2n**256n-1n;function js(e){const{account:t,gasPrice:r,maxFeePerGas:n,maxPriorityFeePerGas:s,to:i}=e,o=t?Xe(t):void 0;if(o&&!st(o.address))throw new Bt({address:o.address});if(i&&!st(i))throw new Bt({address:i});if(typeof r<"u"&&(typeof n<"u"||typeof s<"u"))throw new fE;if(n&&n>Sc)throw new Ps({maxFeePerGas:n});if(s&&n&&s>n)throw new Uo({maxFeePerGas:n,maxPriorityFeePerGas:s})}class $E extends z{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class vd extends z{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class NE extends z{constructor({maxPriorityFeePerGas:t}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${Ut(t)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class T0 extends z{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 I0={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function _c(e){const t={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?ur(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?ur(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?I0[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&&(t.authorizationList=ME(e.authorizationList)),t.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof t.v=="bigint"){if(t.v===0n||t.v===27n)return 0;if(t.v===1n||t.v===28n)return 1;if(t.v>=35n)return t.v%2n===0n?1:0}})(),t.type==="legacy"&&(delete t.accessList,delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas,delete t.yParity),t.type==="eip2930"&&(delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas),t.type==="eip1559"&&delete t.maxFeePerBlobGas,t}const UE=bd("transaction",_c);function ME(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 Ed(e){const t=(e.transactions??[]).map(r=>typeof r=="string"?r:_c(r));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:t,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}const FE=bd("block",Ed);async function qr(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",includeTransactions:s}={}){var l,u,f;const i=s??!1,o=r!==void 0?X(r):void 0;let a=null;if(t?a=await e.request({method:"eth_getBlockByHash",params:[t,i]},{dedupe:!0}):a=await e.request({method:"eth_getBlockByNumber",params:[o||n,i]},{dedupe:!!o}),!a)throw new T0({blockHash:t,blockNumber:r});return(((f=(u=(l=e.chain)==null?void 0:l.formatters)==null?void 0:u.block)==null?void 0:f.format)||Ed)(a)}async function Ad(e){const t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function jE(e,t){return P0(e,t)}async function P0(e,t){var i,o;const{block:r,chain:n=e.chain,request:s}=t||{};try{const a=((i=n==null?void 0:n.fees)==null?void 0:i.maxPriorityFeePerGas)??((o=n==null?void 0:n.fees)==null?void 0:o.defaultPriorityFee);if(typeof a=="function"){const l=r||await se(e,qr,"getBlock")({}),u=await a({block:l,client:e,request:s});if(u===null)throw new Error;return u}if(typeof a<"u")return a;const c=await e.request({method:"eth_maxPriorityFeePerGas"});return ot(c)}catch{const[a,c]=await Promise.all([r?Promise.resolve(r):se(e,qr,"getBlock")({}),se(e,Ad,"getGasPrice")({})]);if(typeof a.baseFeePerGas!="bigint")throw new vd;const l=c-a.baseFeePerGas;return l<0n?0n:l}}async function LE(e,t){return gf(e,t)}async function gf(e,t){var p,d;const{block:r,chain:n=e.chain,request:s,type:i="eip1559"}=t||{},o=await(async()=>{var m,g;return typeof((m=n==null?void 0:n.fees)==null?void 0:m.baseFeeMultiplier)=="function"?n.fees.baseFeeMultiplier({block:r,client:e,request:s}):((g=n==null?void 0:n.fees)==null?void 0:g.baseFeeMultiplier)??1.2})();if(o<1)throw new $E;const c=10**(((p=o.toString().split(".")[1])==null?void 0:p.length)??0),l=m=>m*BigInt(Math.ceil(o*c))/BigInt(c),u=r||await se(e,qr,"getBlock")({});if(typeof((d=n==null?void 0:n.fees)==null?void 0:d.estimateFeesPerGas)=="function"){const m=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:l,request:s,type:i});if(m!==null)return m}if(i==="eip1559"){if(typeof u.baseFeePerGas!="bigint")throw new vd;const m=typeof(s==null?void 0:s.maxPriorityFeePerGas)=="bigint"?s.maxPriorityFeePerGas:await P0(e,{block:u,chain:n,request:s}),g=l(u.baseFeePerGas);return{maxFeePerGas:(s==null?void 0:s.maxFeePerGas)??g+m,maxPriorityFeePerGas:m}}return{gasPrice:(s==null?void 0:s.gasPrice)??l(await se(e,Ad,"getGasPrice")({}))}}async function xd(e,{address:t,blockTag:r="latest",blockNumber:n}){const s=await e.request({method:"eth_getTransactionCount",params:[t,typeof n=="bigint"?X(n):r]},{dedupe:!!n});return ur(s)}function Sd(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(i=>Sr(i)):e.blobs,s=[];for(const i of n)s.push(Uint8Array.from(t.blobToKzgCommitment(i)));return r==="bytes"?s:s.map(i=>Je(i))}function _d(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(o=>Sr(o)):e.blobs,s=typeof e.commitments[0]=="string"?e.commitments.map(o=>Sr(o)):e.commitments,i=[];for(let o=0;o<n.length;o++){const a=n[o],c=s[o];i.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map(o=>Je(o))}function DE(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}function HE(e,t,r){return e&t^~e&r}function zE(e,t,r){return e&t^e&r^t&r}let O0=class extends yc{constructor(t,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(t),this.view=uu(this.buffer)}update(t){Jn(this),t=mn(t),lr(t);const{view:r,buffer:n,blockLen:s}=this,i=t.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=uu(t);for(;s<=i-o;o+=s)this.process(c,o);continue}n.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Jn(this),cd(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:o}=this;r[o++]=128,_r(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let f=o;f<s;f++)r[f]=0;DE(n,s-8,BigInt(this.length*8),i),this.process(n,0);const a=uu(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],i)}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:s,finished:i,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=i,t.length=s,t.pos=a,s%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}};const Pn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),On=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),qE=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]),Bn=new Uint32Array(64);let kd=class extends O0{constructor(t=32){super(64,t,8,!1),this.A=Pn[0]|0,this.B=Pn[1]|0,this.C=Pn[2]|0,this.D=Pn[3]|0,this.E=Pn[4]|0,this.F=Pn[5]|0,this.G=Pn[6]|0,this.H=Pn[7]|0}get(){const{A:t,B:r,C:n,D:s,E:i,F:o,G:a,H:c}=this;return[t,r,n,s,i,o,a,c]}set(t,r,n,s,i,o,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(t,r){for(let f=0;f<16;f++,r+=4)Bn[f]=t.getUint32(r,!1);for(let f=16;f<64;f++){const p=Bn[f-15],d=Bn[f-2],m=Br(p,7)^Br(p,18)^p>>>3,g=Br(d,17)^Br(d,19)^d>>>10;Bn[f]=g+Bn[f-7]+m+Bn[f-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){const p=Br(a,6)^Br(a,11)^Br(a,25),d=u+p+HE(a,c,l)+qE[f]+Bn[f]|0,g=(Br(n,2)^Br(n,13)^Br(n,22))+zE(n,s,i)|0;u=l,l=c,c=a,a=o+d|0,o=i,i=s,s=n,n=d+g|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,i,o,a,c,l,u)}roundClean(){_r(Bn)}destroy(){this.set(0,0,0,0,0,0,0,0),_r(this.buffer)}},B0=class extends kd{constructor(){super(28),this.A=On[0]|0,this.B=On[1]|0,this.C=On[2]|0,this.D=On[3]|0,this.E=On[4]|0,this.F=On[5]|0,this.G=On[6]|0,this.H=On[7]|0}};const C0=mc(()=>new kd),VE=mc(()=>new B0),GE=kd,R0=C0,WE=B0,KE=VE,XE=Object.freeze(Object.defineProperty({__proto__:null,SHA224:WE,SHA256:GE,sha224:KE,sha256:R0},Symbol.toStringTag,{value:"Module"}));function Ki(e,t){const r=t||"hex",n=R0(xr(e,{strict:!1})?Ii(e):e);return r==="bytes"?n:mt(n)}function YE(e){const{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),s=Ki(t,"bytes");return s.set([r],0),n==="bytes"?s:Je(s)}function $0(e){const{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),s=[];for(const i of t)s.push(YE({commitment:i,to:n,version:r}));return s}const Qh=6,N0=32,Td=4096,U0=N0*Td,ep=U0*Qh-1-1*Td*Qh,M0=1;class ZE extends z{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class F0 extends z{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class JE extends z{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class QE extends z{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${M0}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function e6(e){const t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?Sr(e.data):e.data,n=He(r);if(!n)throw new F0;if(n>ep)throw new ZE({maxSize:ep,size:n});const s=[];let i=!0,o=0;for(;i;){const a=yd(new Uint8Array(U0));let c=0;for(;c<Td;){const l=r.slice(o,o+(N0-1));if(a.pushByte(0),a.pushBytes(l),l.length<31){a.pushByte(128),i=!1;break}c++,o+=31}s.push(a)}return t==="bytes"?s.map(a=>a.bytes):s.map(a=>Je(a.bytes))}function j0(e){const{data:t,kzg:r,to:n}=e,s=e.blobs??e6({data:t,to:n}),i=e.commitments??Sd({blobs:s,kzg:r,to:n}),o=e.proofs??_d({blobs:s,commitments:i,kzg:r,to:n}),a=[];for(let c=0;c<s.length;c++)a.push({blob:s[c],commitment:i[c],proof:o[c]});return a}function L0(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 hE({transaction:e})}async function Oi(e){const t=await e.request({method:"eth_chainId"},{dedupe:!0});return ur(t)}const D0=["blobVersionedHashes","chainId","fees","gas","nonce","type"],tp=new Map;async function kc(e,t){const{account:r=e.account,blobs:n,chain:s,gas:i,kzg:o,nonce:a,nonceManager:c,parameters:l=D0,type:u}=t,f=r&&Xe(r),p={...t,...f?{from:f==null?void 0:f.address}:{}};let d;async function m(){return d||(d=await se(e,qr,"getBlock")({blockTag:"latest"}),d)}let g;async function w(){return g||(s?s.id:typeof t.chainId<"u"?t.chainId:(g=await se(e,Oi,"getChainId")({}),g))}if(l.includes("nonce")&&typeof a>"u"&&f)if(c){const A=await w();p.nonce=await c.consume({address:f.address,chainId:A,client:e})}else p.nonce=await se(e,xd,"getTransactionCount")({address:f.address,blockTag:"pending"});if((l.includes("blobVersionedHashes")||l.includes("sidecars"))&&n&&o){const A=Sd({blobs:n,kzg:o});if(l.includes("blobVersionedHashes")){const T=$0({commitments:A,to:"hex"});p.blobVersionedHashes=T}if(l.includes("sidecars")){const T=_d({blobs:n,commitments:A,kzg:o}),E=j0({blobs:n,commitments:A,proofs:T,to:"hex"});p.sidecars=E}}if(l.includes("chainId")&&(p.chainId=await w()),(l.includes("fees")||l.includes("type"))&&typeof u>"u")try{p.type=L0(p)}catch{let A=tp.get(e.uid);if(typeof A>"u"){const T=await m();A=typeof(T==null?void 0:T.baseFeePerGas)=="bigint",tp.set(e.uid,A)}p.type=A?"eip1559":"legacy"}if(l.includes("fees"))if(p.type!=="legacy"&&p.type!=="eip2930"){if(typeof p.maxFeePerGas>"u"||typeof p.maxPriorityFeePerGas>"u"){const A=await m(),{maxFeePerGas:T,maxPriorityFeePerGas:E}=await gf(e,{block:A,chain:s,request:p});if(typeof t.maxPriorityFeePerGas>"u"&&t.maxFeePerGas&&t.maxFeePerGas<E)throw new NE({maxPriorityFeePerGas:E});p.maxPriorityFeePerGas=E,p.maxFeePerGas=T}}else{if(typeof t.maxFeePerGas<"u"||typeof t.maxPriorityFeePerGas<"u")throw new vd;if(typeof t.gasPrice>"u"){const A=await m(),{gasPrice:T}=await gf(e,{block:A,chain:s,request:p,type:"legacy"});p.gasPrice=T}}return l.includes("gas")&&typeof i>"u"&&(p.gas=await se(e,Id,"estimateGas")({...p,account:f&&{address:f.address,type:"json-rpc"}})),js(p),delete p.parameters,p}async function H0(e,{address:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest"}){const s=typeof r=="bigint"?X(r):void 0,i=await e.request({method:"eth_getBalance",params:[t,s||n]});return BigInt(i)}async function Id(e,t){var s,i,o;const{account:r=e.account}=t,n=r?Xe(r):void 0;try{let W=function(Q){const{block:re,request:D,rpcStateOverride:B}=Q;return e.request({method:"eth_estimateGas",params:B?[D,re??e.experimental_blockTag??"latest",B]:re?[D,re]:[D]})};const{accessList:a,authorizationList:c,blobs:l,blobVersionedHashes:u,blockNumber:f,blockTag:p,data:d,gas:m,gasPrice:g,maxFeePerBlobGas:w,maxFeePerGas:A,maxPriorityFeePerGas:T,nonce:E,value:S,stateOverride:I,...P}=await kc(e,{...t,parameters:(n==null?void 0:n.type)==="local"?void 0:["blobVersionedHashes"]}),j=(typeof f=="bigint"?X(f):void 0)||p,k=wd(I),F=await(async()=>{if(P.to)return P.to;if(c&&c.length>0)return await k0({authorization:c[0]}).catch(()=>{throw new z("`to` is required. Could not infer from `authorizationList`")})})();js(t);const R=(o=(i=(s=e.chain)==null?void 0:s.formatters)==null?void 0:i.transactionRequest)==null?void 0:o.format,H=(R||Pi)({...xc(P,{format:R}),from:n==null?void 0:n.address,accessList:a,authorizationList:c,blobs:l,blobVersionedHashes:u,data:d,gas:m,gasPrice:g,maxFeePerBlobGas:w,maxFeePerGas:A,maxPriorityFeePerGas:T,nonce:E,to:F,value:S});let Z=BigInt(await W({block:j,request:H,rpcStateOverride:k}));if(c){const Q=await H0(e,{address:H.from}),re=await Promise.all(c.map(async D=>{const{address:B}=D,V=await W({block:j,request:{authorizationList:void 0,data:d,from:n==null?void 0:n.address,to:B,value:X(Q)},rpcStateOverride:k}).catch(()=>100000n);return 2n*BigInt(V)}));Z+=re.reduce((D,B)=>D+B,0n)}return Z}catch(a){throw OE(a,{...t,account:n,chain:e.chain})}}async function z0(e,t){const{abi:r,address:n,args:s,functionName:i,dataSuffix:o,...a}=t,c=dr({abi:r,args:s,functionName:i});try{return await se(e,Id,"estimateGas")({data:`${c}${o?o.replace("0x",""):""}`,to:n,...a})}catch(l){const u=a.account?Xe(a.account):void 0;throw Is(l,{abi:r,address:n,args:s,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:u==null?void 0:u.address})}}function ta(e,t){if(!st(e,{strict:!1}))throw new Bt({address:e});if(!st(t,{strict:!1}))throw new Bt({address:t});return e.toLowerCase()===t.toLowerCase()}const rp="/docs/contract/decodeEventLog";function Pd(e){const{abi:t,data:r,strict:n,topics:s}=e,i=n??!0,[o,...a]=s;if(!o)throw new zv({docsPath:rp});const c=t.find(g=>g.type==="event"&&o===gc(Ar(g)));if(!(c&&"name"in c)||c.type!=="event")throw new Lm(o,{docsPath:rp});const{name:l,inputs:u}=c,f=u==null?void 0:u.some(g=>!("name"in g&&g.name)),p=f?[]:{},d=u.map((g,w)=>[g,w]).filter(([g])=>"indexed"in g&&g.indexed);for(let g=0;g<d.length;g++){const[w,A]=d[g],T=a[g];if(!T)throw new pc({abiItem:c,param:w});p[f?A:w.name||A]=t6({param:w,value:T})}const m=u.filter(g=>!("indexed"in g&&g.indexed));if(m.length>0){if(r&&r!=="0x")try{const g=Jo(m,r);if(g)if(f)for(let w=0;w<u.length;w++)p[w]=p[w]??g.shift();else for(let w=0;w<m.length;w++)p[m[w].name]=g[w]}catch(g){if(i)throw g instanceof Fm||g instanceof m0?new po({abiItem:c,data:r,params:m,size:He(r)}):g}else if(i)throw new po({abiItem:c,data:"0x",params:m,size:0})}return{eventName:l,args:Object.values(p).length>0?p:void 0}}function t6({param:e,value:t}){return e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/)?t:(Jo([e],t)||[])[0]}function Od(e){const{abi:t,args:r,logs:n,strict:s=!0}=e,i=(()=>{if(e.eventName)return Array.isArray(e.eventName)?e.eventName:[e.eventName]})();return n.map(o=>{var a;try{const c=t.find(u=>u.type==="event"&&o.topics[0]===gc(u));if(!c)return null;const l=Pd({...o,abi:[c],strict:s});return i&&!i.includes(l.eventName)||!r6({args:l.args,inputs:c.inputs,matchArgs:r})?null:{...l,...o}}catch(c){let l,u;if(c instanceof Lm)return null;if(c instanceof po||c instanceof pc){if(s)return null;l=c.abiItem.name,u=(a=c.abiItem.inputs)==null?void 0:a.some(f=>!("name"in f&&f.name))}return{...o,args:u?[]:{},eventName:l}}}).filter(Boolean)}function r6(e){const{args:t,inputs:r,matchArgs:n}=e;if(!n)return!0;if(!t)return!1;function s(i,o,a){try{return i.type==="address"?ta(o,a):i.type==="string"||i.type==="bytes"?lt(Ii(o))===a:o===a}catch{return!1}}return Array.isArray(t)&&Array.isArray(n)?n.every((i,o)=>{if(i==null)return!0;const a=r[o];return a?(Array.isArray(i)?i:[i]).some(l=>s(a,l,t[o])):!1}):typeof t=="object"&&!Array.isArray(t)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([i,o])=>{if(o==null)return!0;const a=r.find(l=>l.name===i);return a?(Array.isArray(o)?o:[o]).some(l=>s(a,l,t[i])):!1}):!1}function wn(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,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 Bd(e,{address:t,blockHash:r,fromBlock:n,toBlock:s,event:i,events:o,args:a,strict:c}={}){const l=c??!1,u=o??(i?[i]:void 0);let f=[];u&&(f=[u.flatMap(g=>Zo({abi:[g],eventName:g.name,args:o?void 0:a}))],i&&(f=f[0]));let p;r?p=await e.request({method:"eth_getLogs",params:[{address:t,topics:f,blockHash:r}]}):p=await e.request({method:"eth_getLogs",params:[{address:t,topics:f,fromBlock:typeof n=="bigint"?X(n):n,toBlock:typeof s=="bigint"?X(s):s}]});const d=p.map(m=>wn(m));return u?Od({abi:u,args:a,logs:d,strict:l}):d}async function Cd(e,t){const{abi:r,address:n,args:s,blockHash:i,eventName:o,fromBlock:a,toBlock:c,strict:l}=t,u=o?Fs({abi:r,name:o}):void 0,f=u?void 0:r.filter(p=>p.type==="event");return se(e,Bd,"getLogs")({address:n,args:s,blockHash:i,event:u,events:f,fromBlock:a,toBlock:c,strict:l})}const du="/docs/contract/decodeFunctionResult";function Ls(e){const{abi:t,args:r,functionName:n,data:s}=e;let i=t[0];if(n){const a=Fs({abi:t,args:r,name:n});if(!a)throw new yi(n,{docsPath:du});i=a}if(i.type!=="function")throw new yi(void 0,{docsPath:du});if(!i.outputs)throw new Dm(i.name,{docsPath:du});const o=Jo(i.outputs,s);if(o&&o.length>1)return o;if(o&&o.length===1)return o[0]}const n6="0.1.1";function s6(){return n6}class Fe extends Error{constructor(t,r={}){const n=(()=>{var c;if(r.cause instanceof Fe){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:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),s=r.cause instanceof Fe&&r.cause.docsPath||r.docsPath,o=`https://oxlib.sh${s??""}`,a=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||s?["",n?`Details: ${n}`:void 0,s?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
|
|
39
|
+
`),{cause:t,name:"TipAboveFeeCapError"})}}Object.defineProperty(Uo,"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 ea extends z{constructor({cause:t}){super(`An error occurred while executing: ${t==null?void 0:t.shortMessage}`,{cause:t,name:"UnknownNodeError"})}}function Ac(e,t){const r=(e.details||"").toLowerCase(),n=e instanceof z?e.walk(s=>(s==null?void 0:s.code)===ii.code):e;return n instanceof z?new ii({cause:e,message:n.details}):ii.nodeMessage.test(r)?new ii({cause:e,message:e.details}):Ps.nodeMessage.test(r)?new Ps({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):uf.nodeMessage.test(r)?new uf({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):lf.nodeMessage.test(r)?new lf({cause:e,nonce:t==null?void 0:t.nonce}):ff.nodeMessage.test(r)?new ff({cause:e,nonce:t==null?void 0:t.nonce}):df.nodeMessage.test(r)?new df({cause:e,nonce:t==null?void 0:t.nonce}):hf.nodeMessage.test(r)?new hf({cause:e}):pf.nodeMessage.test(r)?new pf({cause:e,gas:t==null?void 0:t.gas}):yf.nodeMessage.test(r)?new yf({cause:e,gas:t==null?void 0:t.gas}):mf.nodeMessage.test(r)?new mf({cause:e}):Uo.nodeMessage.test(r)?new Uo({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas,maxPriorityFeePerGas:t==null?void 0:t.maxPriorityFeePerGas}):new ea({cause:e})}function OE(e,{docsPath:t,...r}){const n=(()=>{const s=Ac(e,r);return s instanceof ea?e:s})();return new PE(n,{docsPath:t,...r})}function xc(e,{format:t}){if(!t)return{};const r={};function n(i){const o=Object.keys(i);for(const a of o)a in e&&(r[a]=e[a]),i[a]&&typeof i[a]=="object"&&!Array.isArray(i[a])&&n(i[a])}const s=t(e||{});return n(s),r}function bd(e,t){return({exclude:r,format:n})=>({exclude:r,format:s=>{const i=t(s);if(r)for(const o of r)delete i[o];return{...i,...n(s)}},type:e})}const BE={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function Pi(e){const t={};return typeof e.authorizationList<"u"&&(t.authorizationList=CE(e.authorizationList)),typeof e.accessList<"u"&&(t.accessList=e.accessList),typeof e.blobVersionedHashes<"u"&&(t.blobVersionedHashes=e.blobVersionedHashes),typeof e.blobs<"u"&&(typeof e.blobs[0]!="string"?t.blobs=e.blobs.map(r=>Je(r)):t.blobs=e.blobs),typeof e.data<"u"&&(t.data=e.data),typeof e.from<"u"&&(t.from=e.from),typeof e.gas<"u"&&(t.gas=X(e.gas)),typeof e.gasPrice<"u"&&(t.gasPrice=X(e.gasPrice)),typeof e.maxFeePerBlobGas<"u"&&(t.maxFeePerBlobGas=X(e.maxFeePerBlobGas)),typeof e.maxFeePerGas<"u"&&(t.maxFeePerGas=X(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(t.maxPriorityFeePerGas=X(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(t.nonce=X(e.nonce)),typeof e.to<"u"&&(t.to=e.to),typeof e.type<"u"&&(t.type=BE[e.type]),typeof e.value<"u"&&(t.value=X(e.value)),t}function CE(e){return e.map(t=>({address:t.address,r:t.r?X(BigInt(t.r)):t.r,s:t.s?X(BigInt(t.s)):t.s,chainId:X(t.chainId),nonce:X(t.nonce),...typeof t.yParity<"u"?{yParity:X(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:X(t.v)}:{}}))}function Jh(e){if(!(!e||e.length===0))return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new Fh({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new Fh({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function RE(e){const{balance:t,nonce:r,state:n,stateDiff:s,code:i}=e,o={};if(i!==void 0&&(o.code=i),t!==void 0&&(o.balance=X(t)),r!==void 0&&(o.nonce=X(r)),n!==void 0&&(o.state=Jh(n)),s!==void 0){if(o.state)throw new uE;o.stateDiff=Jh(s)}return o}function wd(e){if(!e)return;const t={};for(const{address:r,...n}of e){if(!st(r,{strict:!1}))throw new Bt({address:r});if(t[r])throw new cE({address:r});t[r]=RE(n)}return t}const Sc=2n**256n-1n;function js(e){const{account:t,gasPrice:r,maxFeePerGas:n,maxPriorityFeePerGas:s,to:i}=e,o=t?Xe(t):void 0;if(o&&!st(o.address))throw new Bt({address:o.address});if(i&&!st(i))throw new Bt({address:i});if(typeof r<"u"&&(typeof n<"u"||typeof s<"u"))throw new fE;if(n&&n>Sc)throw new Ps({maxFeePerGas:n});if(s&&n&&s>n)throw new Uo({maxFeePerGas:n,maxPriorityFeePerGas:s})}class $E extends z{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class vd extends z{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class NE extends z{constructor({maxPriorityFeePerGas:t}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${Ut(t)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class T0 extends z{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 I0={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function _c(e){const t={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?ur(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?ur(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?I0[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&&(t.authorizationList=ME(e.authorizationList)),t.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof t.v=="bigint"){if(t.v===0n||t.v===27n)return 0;if(t.v===1n||t.v===28n)return 1;if(t.v>=35n)return t.v%2n===0n?1:0}})(),t.type==="legacy"&&(delete t.accessList,delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas,delete t.yParity),t.type==="eip2930"&&(delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas),t.type==="eip1559"&&delete t.maxFeePerBlobGas,t}const UE=bd("transaction",_c);function ME(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 Ed(e){const t=(e.transactions??[]).map(r=>typeof r=="string"?r:_c(r));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:t,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}const FE=bd("block",Ed);async function qr(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",includeTransactions:s}={}){var l,u,f;const i=s??!1,o=r!==void 0?X(r):void 0;let a=null;if(t?a=await e.request({method:"eth_getBlockByHash",params:[t,i]},{dedupe:!0}):a=await e.request({method:"eth_getBlockByNumber",params:[o||n,i]},{dedupe:!!o}),!a)throw new T0({blockHash:t,blockNumber:r});return(((f=(u=(l=e.chain)==null?void 0:l.formatters)==null?void 0:u.block)==null?void 0:f.format)||Ed)(a)}async function Ad(e){const t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function jE(e,t){return P0(e,t)}async function P0(e,t){var i,o;const{block:r,chain:n=e.chain,request:s}=t||{};try{const a=((i=n==null?void 0:n.fees)==null?void 0:i.maxPriorityFeePerGas)??((o=n==null?void 0:n.fees)==null?void 0:o.defaultPriorityFee);if(typeof a=="function"){const l=r||await se(e,qr,"getBlock")({}),u=await a({block:l,client:e,request:s});if(u===null)throw new Error;return u}if(typeof a<"u")return a;const c=await e.request({method:"eth_maxPriorityFeePerGas"});return ot(c)}catch{const[a,c]=await Promise.all([r?Promise.resolve(r):se(e,qr,"getBlock")({}),se(e,Ad,"getGasPrice")({})]);if(typeof a.baseFeePerGas!="bigint")throw new vd;const l=c-a.baseFeePerGas;return l<0n?0n:l}}async function LE(e,t){return gf(e,t)}async function gf(e,t){var p,d;const{block:r,chain:n=e.chain,request:s,type:i="eip1559"}=t||{},o=await(async()=>{var m,g;return typeof((m=n==null?void 0:n.fees)==null?void 0:m.baseFeeMultiplier)=="function"?n.fees.baseFeeMultiplier({block:r,client:e,request:s}):((g=n==null?void 0:n.fees)==null?void 0:g.baseFeeMultiplier)??1.2})();if(o<1)throw new $E;const c=10**(((p=o.toString().split(".")[1])==null?void 0:p.length)??0),l=m=>m*BigInt(Math.ceil(o*c))/BigInt(c),u=r||await se(e,qr,"getBlock")({});if(typeof((d=n==null?void 0:n.fees)==null?void 0:d.estimateFeesPerGas)=="function"){const m=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:l,request:s,type:i});if(m!==null)return m}if(i==="eip1559"){if(typeof u.baseFeePerGas!="bigint")throw new vd;const m=typeof(s==null?void 0:s.maxPriorityFeePerGas)=="bigint"?s.maxPriorityFeePerGas:await P0(e,{block:u,chain:n,request:s}),g=l(u.baseFeePerGas);return{maxFeePerGas:(s==null?void 0:s.maxFeePerGas)??g+m,maxPriorityFeePerGas:m}}return{gasPrice:(s==null?void 0:s.gasPrice)??l(await se(e,Ad,"getGasPrice")({}))}}async function xd(e,{address:t,blockTag:r="latest",blockNumber:n}){const s=await e.request({method:"eth_getTransactionCount",params:[t,typeof n=="bigint"?X(n):r]},{dedupe:!!n});return ur(s)}function Sd(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(i=>Sr(i)):e.blobs,s=[];for(const i of n)s.push(Uint8Array.from(t.blobToKzgCommitment(i)));return r==="bytes"?s:s.map(i=>Je(i))}function _d(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(o=>Sr(o)):e.blobs,s=typeof e.commitments[0]=="string"?e.commitments.map(o=>Sr(o)):e.commitments,i=[];for(let o=0;o<n.length;o++){const a=n[o],c=s[o];i.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map(o=>Je(o))}function DE(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}function HE(e,t,r){return e&t^~e&r}function zE(e,t,r){return e&t^e&r^t&r}let O0=class extends yc{constructor(t,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(t),this.view=uu(this.buffer)}update(t){Jn(this),t=mn(t),lr(t);const{view:r,buffer:n,blockLen:s}=this,i=t.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=uu(t);for(;s<=i-o;o+=s)this.process(c,o);continue}n.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Jn(this),cd(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:o}=this;r[o++]=128,_r(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let f=o;f<s;f++)r[f]=0;DE(n,s-8,BigInt(this.length*8),i),this.process(n,0);const a=uu(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],i)}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:s,finished:i,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=i,t.length=s,t.pos=a,s%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}};const Pn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),On=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),qE=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]),Bn=new Uint32Array(64);let kd=class extends O0{constructor(t=32){super(64,t,8,!1),this.A=Pn[0]|0,this.B=Pn[1]|0,this.C=Pn[2]|0,this.D=Pn[3]|0,this.E=Pn[4]|0,this.F=Pn[5]|0,this.G=Pn[6]|0,this.H=Pn[7]|0}get(){const{A:t,B:r,C:n,D:s,E:i,F:o,G:a,H:c}=this;return[t,r,n,s,i,o,a,c]}set(t,r,n,s,i,o,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(t,r){for(let f=0;f<16;f++,r+=4)Bn[f]=t.getUint32(r,!1);for(let f=16;f<64;f++){const p=Bn[f-15],d=Bn[f-2],m=Br(p,7)^Br(p,18)^p>>>3,g=Br(d,17)^Br(d,19)^d>>>10;Bn[f]=g+Bn[f-7]+m+Bn[f-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){const p=Br(a,6)^Br(a,11)^Br(a,25),d=u+p+HE(a,c,l)+qE[f]+Bn[f]|0,g=(Br(n,2)^Br(n,13)^Br(n,22))+zE(n,s,i)|0;u=l,l=c,c=a,a=o+d|0,o=i,i=s,s=n,n=d+g|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,i,o,a,c,l,u)}roundClean(){_r(Bn)}destroy(){this.set(0,0,0,0,0,0,0,0),_r(this.buffer)}},B0=class extends kd{constructor(){super(28),this.A=On[0]|0,this.B=On[1]|0,this.C=On[2]|0,this.D=On[3]|0,this.E=On[4]|0,this.F=On[5]|0,this.G=On[6]|0,this.H=On[7]|0}};const C0=mc(()=>new kd),VE=mc(()=>new B0),GE=kd,R0=C0,WE=B0,KE=VE,XE=Object.freeze(Object.defineProperty({__proto__:null,SHA224:WE,SHA256:GE,sha224:KE,sha256:R0},Symbol.toStringTag,{value:"Module"}));function Ki(e,t){const r=t||"hex",n=R0(xr(e,{strict:!1})?Ii(e):e);return r==="bytes"?n:gt(n)}function YE(e){const{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),s=Ki(t,"bytes");return s.set([r],0),n==="bytes"?s:Je(s)}function $0(e){const{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),s=[];for(const i of t)s.push(YE({commitment:i,to:n,version:r}));return s}const Qh=6,N0=32,Td=4096,U0=N0*Td,ep=U0*Qh-1-1*Td*Qh,M0=1;class ZE extends z{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class F0 extends z{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class JE extends z{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class QE extends z{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${M0}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function e6(e){const t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?Sr(e.data):e.data,n=He(r);if(!n)throw new F0;if(n>ep)throw new ZE({maxSize:ep,size:n});const s=[];let i=!0,o=0;for(;i;){const a=yd(new Uint8Array(U0));let c=0;for(;c<Td;){const l=r.slice(o,o+(N0-1));if(a.pushByte(0),a.pushBytes(l),l.length<31){a.pushByte(128),i=!1;break}c++,o+=31}s.push(a)}return t==="bytes"?s.map(a=>a.bytes):s.map(a=>Je(a.bytes))}function j0(e){const{data:t,kzg:r,to:n}=e,s=e.blobs??e6({data:t,to:n}),i=e.commitments??Sd({blobs:s,kzg:r,to:n}),o=e.proofs??_d({blobs:s,commitments:i,kzg:r,to:n}),a=[];for(let c=0;c<s.length;c++)a.push({blob:s[c],commitment:i[c],proof:o[c]});return a}function L0(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 hE({transaction:e})}async function Oi(e){const t=await e.request({method:"eth_chainId"},{dedupe:!0});return ur(t)}const D0=["blobVersionedHashes","chainId","fees","gas","nonce","type"],tp=new Map;async function kc(e,t){const{account:r=e.account,blobs:n,chain:s,gas:i,kzg:o,nonce:a,nonceManager:c,parameters:l=D0,type:u}=t,f=r&&Xe(r),p={...t,...f?{from:f==null?void 0:f.address}:{}};let d;async function m(){return d||(d=await se(e,qr,"getBlock")({blockTag:"latest"}),d)}let g;async function w(){return g||(s?s.id:typeof t.chainId<"u"?t.chainId:(g=await se(e,Oi,"getChainId")({}),g))}if(l.includes("nonce")&&typeof a>"u"&&f)if(c){const A=await w();p.nonce=await c.consume({address:f.address,chainId:A,client:e})}else p.nonce=await se(e,xd,"getTransactionCount")({address:f.address,blockTag:"pending"});if((l.includes("blobVersionedHashes")||l.includes("sidecars"))&&n&&o){const A=Sd({blobs:n,kzg:o});if(l.includes("blobVersionedHashes")){const T=$0({commitments:A,to:"hex"});p.blobVersionedHashes=T}if(l.includes("sidecars")){const T=_d({blobs:n,commitments:A,kzg:o}),E=j0({blobs:n,commitments:A,proofs:T,to:"hex"});p.sidecars=E}}if(l.includes("chainId")&&(p.chainId=await w()),(l.includes("fees")||l.includes("type"))&&typeof u>"u")try{p.type=L0(p)}catch{let A=tp.get(e.uid);if(typeof A>"u"){const T=await m();A=typeof(T==null?void 0:T.baseFeePerGas)=="bigint",tp.set(e.uid,A)}p.type=A?"eip1559":"legacy"}if(l.includes("fees"))if(p.type!=="legacy"&&p.type!=="eip2930"){if(typeof p.maxFeePerGas>"u"||typeof p.maxPriorityFeePerGas>"u"){const A=await m(),{maxFeePerGas:T,maxPriorityFeePerGas:E}=await gf(e,{block:A,chain:s,request:p});if(typeof t.maxPriorityFeePerGas>"u"&&t.maxFeePerGas&&t.maxFeePerGas<E)throw new NE({maxPriorityFeePerGas:E});p.maxPriorityFeePerGas=E,p.maxFeePerGas=T}}else{if(typeof t.maxFeePerGas<"u"||typeof t.maxPriorityFeePerGas<"u")throw new vd;if(typeof t.gasPrice>"u"){const A=await m(),{gasPrice:T}=await gf(e,{block:A,chain:s,request:p,type:"legacy"});p.gasPrice=T}}return l.includes("gas")&&typeof i>"u"&&(p.gas=await se(e,Id,"estimateGas")({...p,account:f&&{address:f.address,type:"json-rpc"}})),js(p),delete p.parameters,p}async function H0(e,{address:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest"}){const s=typeof r=="bigint"?X(r):void 0,i=await e.request({method:"eth_getBalance",params:[t,s||n]});return BigInt(i)}async function Id(e,t){var s,i,o;const{account:r=e.account}=t,n=r?Xe(r):void 0;try{let W=function(Q){const{block:re,request:D,rpcStateOverride:B}=Q;return e.request({method:"eth_estimateGas",params:B?[D,re??e.experimental_blockTag??"latest",B]:re?[D,re]:[D]})};const{accessList:a,authorizationList:c,blobs:l,blobVersionedHashes:u,blockNumber:f,blockTag:p,data:d,gas:m,gasPrice:g,maxFeePerBlobGas:w,maxFeePerGas:A,maxPriorityFeePerGas:T,nonce:E,value:S,stateOverride:I,...P}=await kc(e,{...t,parameters:(n==null?void 0:n.type)==="local"?void 0:["blobVersionedHashes"]}),j=(typeof f=="bigint"?X(f):void 0)||p,k=wd(I),F=await(async()=>{if(P.to)return P.to;if(c&&c.length>0)return await k0({authorization:c[0]}).catch(()=>{throw new z("`to` is required. Could not infer from `authorizationList`")})})();js(t);const R=(o=(i=(s=e.chain)==null?void 0:s.formatters)==null?void 0:i.transactionRequest)==null?void 0:o.format,H=(R||Pi)({...xc(P,{format:R}),from:n==null?void 0:n.address,accessList:a,authorizationList:c,blobs:l,blobVersionedHashes:u,data:d,gas:m,gasPrice:g,maxFeePerBlobGas:w,maxFeePerGas:A,maxPriorityFeePerGas:T,nonce:E,to:F,value:S});let Z=BigInt(await W({block:j,request:H,rpcStateOverride:k}));if(c){const Q=await H0(e,{address:H.from}),re=await Promise.all(c.map(async D=>{const{address:B}=D,V=await W({block:j,request:{authorizationList:void 0,data:d,from:n==null?void 0:n.address,to:B,value:X(Q)},rpcStateOverride:k}).catch(()=>100000n);return 2n*BigInt(V)}));Z+=re.reduce((D,B)=>D+B,0n)}return Z}catch(a){throw OE(a,{...t,account:n,chain:e.chain})}}async function z0(e,t){const{abi:r,address:n,args:s,functionName:i,dataSuffix:o,...a}=t,c=dr({abi:r,args:s,functionName:i});try{return await se(e,Id,"estimateGas")({data:`${c}${o?o.replace("0x",""):""}`,to:n,...a})}catch(l){const u=a.account?Xe(a.account):void 0;throw Is(l,{abi:r,address:n,args:s,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:u==null?void 0:u.address})}}function ta(e,t){if(!st(e,{strict:!1}))throw new Bt({address:e});if(!st(t,{strict:!1}))throw new Bt({address:t});return e.toLowerCase()===t.toLowerCase()}const rp="/docs/contract/decodeEventLog";function Pd(e){const{abi:t,data:r,strict:n,topics:s}=e,i=n??!0,[o,...a]=s;if(!o)throw new zv({docsPath:rp});const c=t.find(g=>g.type==="event"&&o===gc(Ar(g)));if(!(c&&"name"in c)||c.type!=="event")throw new Lm(o,{docsPath:rp});const{name:l,inputs:u}=c,f=u==null?void 0:u.some(g=>!("name"in g&&g.name)),p=f?[]:{},d=u.map((g,w)=>[g,w]).filter(([g])=>"indexed"in g&&g.indexed);for(let g=0;g<d.length;g++){const[w,A]=d[g],T=a[g];if(!T)throw new pc({abiItem:c,param:w});p[f?A:w.name||A]=t6({param:w,value:T})}const m=u.filter(g=>!("indexed"in g&&g.indexed));if(m.length>0){if(r&&r!=="0x")try{const g=Jo(m,r);if(g)if(f)for(let w=0;w<u.length;w++)p[w]=p[w]??g.shift();else for(let w=0;w<m.length;w++)p[m[w].name]=g[w]}catch(g){if(i)throw g instanceof Fm||g instanceof m0?new po({abiItem:c,data:r,params:m,size:He(r)}):g}else if(i)throw new po({abiItem:c,data:"0x",params:m,size:0})}return{eventName:l,args:Object.values(p).length>0?p:void 0}}function t6({param:e,value:t}){return e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/)?t:(Jo([e],t)||[])[0]}function Od(e){const{abi:t,args:r,logs:n,strict:s=!0}=e,i=(()=>{if(e.eventName)return Array.isArray(e.eventName)?e.eventName:[e.eventName]})();return n.map(o=>{var a;try{const c=t.find(u=>u.type==="event"&&o.topics[0]===gc(u));if(!c)return null;const l=Pd({...o,abi:[c],strict:s});return i&&!i.includes(l.eventName)||!r6({args:l.args,inputs:c.inputs,matchArgs:r})?null:{...l,...o}}catch(c){let l,u;if(c instanceof Lm)return null;if(c instanceof po||c instanceof pc){if(s)return null;l=c.abiItem.name,u=(a=c.abiItem.inputs)==null?void 0:a.some(f=>!("name"in f&&f.name))}return{...o,args:u?[]:{},eventName:l}}}).filter(Boolean)}function r6(e){const{args:t,inputs:r,matchArgs:n}=e;if(!n)return!0;if(!t)return!1;function s(i,o,a){try{return i.type==="address"?ta(o,a):i.type==="string"||i.type==="bytes"?lt(Ii(o))===a:o===a}catch{return!1}}return Array.isArray(t)&&Array.isArray(n)?n.every((i,o)=>{if(i==null)return!0;const a=r[o];return a?(Array.isArray(i)?i:[i]).some(l=>s(a,l,t[o])):!1}):typeof t=="object"&&!Array.isArray(t)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([i,o])=>{if(o==null)return!0;const a=r.find(l=>l.name===i);return a?(Array.isArray(o)?o:[o]).some(l=>s(a,l,t[i])):!1}):!1}function wn(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,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 Bd(e,{address:t,blockHash:r,fromBlock:n,toBlock:s,event:i,events:o,args:a,strict:c}={}){const l=c??!1,u=o??(i?[i]:void 0);let f=[];u&&(f=[u.flatMap(g=>Zo({abi:[g],eventName:g.name,args:o?void 0:a}))],i&&(f=f[0]));let p;r?p=await e.request({method:"eth_getLogs",params:[{address:t,topics:f,blockHash:r}]}):p=await e.request({method:"eth_getLogs",params:[{address:t,topics:f,fromBlock:typeof n=="bigint"?X(n):n,toBlock:typeof s=="bigint"?X(s):s}]});const d=p.map(m=>wn(m));return u?Od({abi:u,args:a,logs:d,strict:l}):d}async function Cd(e,t){const{abi:r,address:n,args:s,blockHash:i,eventName:o,fromBlock:a,toBlock:c,strict:l}=t,u=o?Fs({abi:r,name:o}):void 0,f=u?void 0:r.filter(p=>p.type==="event");return se(e,Bd,"getLogs")({address:n,args:s,blockHash:i,event:u,events:f,fromBlock:a,toBlock:c,strict:l})}const du="/docs/contract/decodeFunctionResult";function Ls(e){const{abi:t,args:r,functionName:n,data:s}=e;let i=t[0];if(n){const a=Fs({abi:t,args:r,name:n});if(!a)throw new yi(n,{docsPath:du});i=a}if(i.type!=="function")throw new yi(void 0,{docsPath:du});if(!i.outputs)throw new Dm(i.name,{docsPath:du});const o=Jo(i.outputs,s);if(o&&o.length>1)return o;if(o&&o.length===1)return o[0]}const n6="0.1.1";function s6(){return n6}class Fe extends Error{constructor(t,r={}){const n=(()=>{var c;if(r.cause instanceof Fe){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:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),s=r.cause instanceof Fe&&r.cause.docsPath||r.docsPath,o=`https://oxlib.sh${s??""}`,a=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||s?["",n?`Details: ${n}`:void 0,s?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
|
|
40
40
|
`);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,"docs",{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,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${s6()}`}),this.cause=r.cause,this.details=n,this.docs=o,this.docsPath=s,this.shortMessage=t}walk(t){return q0(this,t)}}function q0(e,t){return t!=null&&t(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?q0(e.cause,t):t?null:e}const i6="#__bigint";function o6(e,t,r){return JSON.stringify(e,(n,s)=>typeof s=="bigint"?s.toString()+i6:s,r)}function a6(e,t){if(sp(e)>t)throw new g6({givenSize:sp(e),maxSize:t})}const Jr={zero:48,nine:57,A:65,F:70,a:97,f:102};function np(e){if(e>=Jr.zero&&e<=Jr.nine)return e-Jr.zero;if(e>=Jr.A&&e<=Jr.F)return e-(Jr.A-10);if(e>=Jr.a&&e<=Jr.f)return e-(Jr.a-10)}function c6(e,t={}){const{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new b6({size:e.length,targetSize:n,type:"Bytes"});const s=new Uint8Array(n);for(let i=0;i<n;i++){const o=r==="right";s[o?i:n-i-1]=e[o?i:e.length-i-1]}return s}function Rd(e,t){if(fr(e)>t)throw new x6({givenSize:fr(e),maxSize:t})}function u6(e,t){if(typeof t=="number"&&t>0&&t>fr(e)-1)throw new X0({offset:t,position:"start",size:fr(e)})}function l6(e,t,r){if(typeof t=="number"&&typeof r=="number"&&fr(e)!==r-t)throw new X0({offset:r,position:"end",size:fr(e)})}function V0(e,t={}){const{dir:r,size:n=32}=t;if(n===0)return e;const s=e.replace("0x","");if(s.length>n*2)throw new S6({size:Math.ceil(s.length/2),targetSize:n,type:"Hex"});return`0x${s[r==="right"?"padEnd":"padStart"](n*2,"0")}`}const f6=new TextEncoder;function d6(e){return e instanceof Uint8Array?e:typeof e=="string"?p6(e):h6(e)}function h6(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function p6(e,t={}){const{size:r}=t;let n=e;r&&(Rd(e,r),n=Bs(e,r));let s=n.slice(2);s.length%2&&(s=`0${s}`);const i=s.length/2,o=new Uint8Array(i);for(let a=0,c=0;a<i;a++){const l=np(s.charCodeAt(c++)),u=np(s.charCodeAt(c++));if(l===void 0||u===void 0)throw new Fe(`Invalid byte sequence ("${s[c-2]}${s[c-1]}" in "${s}").`);o[a]=l*16+u}return o}function y6(e,t={}){const{size:r}=t,n=f6.encode(e);return typeof r=="number"?(a6(n,r),m6(n,r)):n}function m6(e,t){return c6(e,{dir:"right",size:t})}function sp(e){return e.length}let g6=class extends Fe{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"})}},b6=class extends Fe{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 w6=new TextEncoder,v6=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function E6(e,t={}){const{strict:r=!1}=t;if(!e)throw new ip(e);if(typeof e!="string")throw new ip(e);if(r&&!/^0x[0-9a-fA-F]*$/.test(e))throw new op(e);if(!e.startsWith("0x"))throw new op(e)}function Gr(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function G0(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?(Rd(r,t.size),Os(r,t.size)):r}function W0(e,t={}){let r="";for(let s=0;s<e.length;s++)r+=v6[e[s]];const n=`0x${r}`;return typeof t.size=="number"?(Rd(n,t.size),Bs(n,t.size)):n}function It(e,t={}){const{signed:r,size:n}=t,s=BigInt(e);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<o){const l=typeof e=="bigint"?"n":"";throw new K0({max:i?`${i}${l}`:void 0,min:`${o}${l}`,signed:r,size:n,value:`${e}${l}`})}const c=`0x${(r&&s<0?(1n<<BigInt(n*8))+BigInt(s):s).toString(16)}`;return n?Os(c,n):c}function $d(e,t={}){return W0(w6.encode(e),t)}function Os(e,t){return V0(e,{dir:"left",size:t})}function Bs(e,t){return V0(e,{dir:"right",size:t})}function Nd(e,t,r,n={}){const{strict:s}=n;u6(e,t);const i=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return s&&l6(i,t,r),i}function fr(e){return Math.ceil((e.length-2)/2)}function A6(e,t={}){const{strict:r=!1}=t;try{return E6(e,{strict:r}),!0}catch{return!1}}class K0 extends Fe{constructor({max:t,min:r,signed:n,size:s,value:i}){super(`Number \`${i}\` is not in safe${s?` ${s*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 ip extends Fe{constructor(t){super(`Value \`${typeof t=="object"?o6(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 op extends Fe{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 x6 extends Fe{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 X0 extends Fe{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 S6 extends Fe{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 _6(e){return{address:e.address,amount:It(e.amount),index:It(e.index),validatorIndex:It(e.validatorIndex)}}function Y0(e){return{...typeof e.baseFeePerGas=="bigint"&&{baseFeePerGas:It(e.baseFeePerGas)},...typeof e.blobBaseFee=="bigint"&&{blobBaseFee:It(e.blobBaseFee)},...typeof e.feeRecipient=="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit=="bigint"&&{gasLimit:It(e.gasLimit)},...typeof e.number=="bigint"&&{number:It(e.number)},...typeof e.prevRandao=="bigint"&&{prevRandao:It(e.prevRandao)},...typeof e.time=="bigint"&&{time:It(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(_6)}}}const bf=[{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"}],wf=[{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"}]}],Z0=[{inputs:[],name:"ResolverNotFound",type:"error"},{inputs:[],name:"ResolverWildcardNotSupported",type:"error"},{inputs:[],name:"ResolverNotContract",type:"error"},{inputs:[{name:"returnData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{components:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"errors",type:"tuple[]"}],name:"HttpError",type:"error"}],J0=[...Z0,{name:"resolve",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]},{name:"resolve",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"}]}],k6=[...Z0,{name:"reverse",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolvedAddress"},{type:"address",name:"reverseResolver"},{type:"address",name:"resolver"}]},{name:"reverse",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolvedAddress"},{type:"address",name:"reverseResolver"},{type:"address",name:"resolver"}]}],ap=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],cp=[{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"}]}],up=[{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"}],T6="0x82ad56cb",Q0="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",I6="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",P6="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572";class vf extends z{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 O6 extends z{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 B6 extends z{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(`
|
|
41
|
-
`),{name:"ChainNotFoundError"})}}class eg extends z{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class Tc extends z{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const hu="/docs/contract/encodeDeployData";function Ic(e){const{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;const s=t.find(o=>"type"in o&&o.type==="constructor");if(!s)throw new Fv({docsPath:hu});if(!("inputs"in s))throw new Nh({docsPath:hu});if(!s.inputs||s.inputs.length===0)throw new Nh({docsPath:hu});const i=kn(s.inputs,r);return Tr([n,i])}function Bi({blockNumber:e,chain:t,contract:r}){var s;const n=(s=t==null?void 0:t.contracts)==null?void 0:s[r];if(!n)throw new vf({chain:t,contract:{name:r}});if(e&&n.blockCreated&&n.blockCreated>e)throw new vf({blockNumber:e,chain:t,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function tg(e,{docsPath:t,...r}){const n=(()=>{const s=Ac(e,r);return s instanceof ea?e:s})();return new A0(n,{docsPath:t,...r})}function Ud(){let e=()=>{},t=()=>{};return{promise:new Promise((n,s)=>{e=n,t=s}),resolve:e,reject:t}}const pu=new Map;function rg({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:s}){const i=async()=>{const u=c();o();const f=u.map(({args:p})=>p);f.length!==0&&e(f).then(p=>{s&&Array.isArray(p)&&p.sort(s);for(let d=0;d<u.length;d++){const{resolve:m}=u[d];m==null||m([p[d],p])}}).catch(p=>{for(let d=0;d<u.length;d++){const{reject:m}=u[d];m==null||m(p)}})},o=()=>pu.delete(t),a=()=>c().map(({args:u})=>u),c=()=>pu.get(t)||[],l=u=>pu.set(t,[...c(),u]);return{flush:o,async schedule(u){const{promise:f,resolve:p,reject:d}=Ud();return(r==null?void 0:r([...a(),u]))&&i(),c().length>0?(l({args:u,resolve:p,reject:d}),f):(l({args:u,resolve:p,reject:d}),setTimeout(i,n),f)}}}async function ra(e,t){var H,W,Z,Q;const{account:r=e.account,authorizationList:n,batch:s=!!((H=e.batch)!=null&&H.multicall),blockNumber:i,blockTag:o=e.experimental_blockTag??"latest",accessList:a,blobs:c,blockOverrides:l,code:u,data:f,factory:p,factoryData:d,gas:m,gasPrice:g,maxFeePerBlobGas:w,maxFeePerGas:A,maxPriorityFeePerGas:T,nonce:E,to:S,value:I,stateOverride:P,...$}=t,j=r?Xe(r):void 0;if(u&&(p||d))throw new z("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(u&&S)throw new z("Cannot provide both `code` & `to` as parameters.");const k=u&&f,F=p&&d&&S&&f,R=k||F,U=k?$6({code:u,data:f}):F?N6({data:f,factory:p,factoryData:d,to:S}):f;try{js(t);const D=(typeof i=="bigint"?X(i):void 0)||o,B=l?Y0(l):void 0,V=wd(P),K=(Q=(Z=(W=e.chain)==null?void 0:W.formatters)==null?void 0:Z.transactionRequest)==null?void 0:Q.format,N=(K||Pi)({...xc($,{format:K}),from:j==null?void 0:j.address,accessList:a,authorizationList:n,blobs:c,data:U,gas:m,gasPrice:g,maxFeePerBlobGas:w,maxFeePerGas:A,maxPriorityFeePerGas:T,nonce:E,to:R?void 0:S,value:I});if(s&&C6({request:N})&&!V&&!B)try{return await R6(e,{...N,blockNumber:i,blockTag:o})}catch(ne){if(!(ne instanceof eg)&&!(ne instanceof vf))throw ne}const L=(()=>{const ne=[N,D];return V&&B?[...ne,V,B]:V?[...ne,V]:B?[...ne,{},B]:ne})(),J=await e.request({method:"eth_call",params:L});return J==="0x"?{data:void 0}:{data:J}}catch(re){const D=U6(re),{offchainLookup:B,offchainLookupSignature:V}=await Promise.resolve().then(()=>require("./ccip-D9S6QM7J.cjs"));if(e.ccipRead!==!1&&(D==null?void 0:D.slice(0,10))===V&&S)return{data:await B(e,{data:D,to:S})};throw R&&(D==null?void 0:D.slice(0,10))==="0x101bb98d"?new vE({factory:p}):tg(re,{...t,account:j,chain:e.chain})}}function C6({request:e}){const{data:t,to:r,...n}=e;return!(!t||t.startsWith(T6)||!r||Object.values(n).filter(s=>typeof s<"u").length>0)}async function R6(e,t){var g;const{batchSize:r=1024,wait:n=0}=typeof((g=e.batch)==null?void 0:g.multicall)=="object"?e.batch.multicall:{},{blockNumber:s,blockTag:i=e.experimental_blockTag??"latest",data:o,multicallAddress:a,to:c}=t;let l=a;if(!l){if(!e.chain)throw new eg;l=Bi({blockNumber:s,chain:e.chain,contract:"multicall3"})}const f=(typeof s=="bigint"?X(s):void 0)||i,{schedule:p}=rg({id:`${e.uid}.${f}`,wait:n,shouldSplitBatch(w){return w.reduce((T,{data:E})=>T+(E.length-2),0)>r*2},fn:async w=>{const A=w.map(S=>({allowFailure:!0,callData:S.data,target:S.to})),T=dr({abi:bf,args:[A],functionName:"aggregate3"}),E=await e.request({method:"eth_call",params:[{data:T,to:l},f]});return Ls({abi:bf,args:[A],functionName:"aggregate3",data:E||"0x"})}}),[{returnData:d,success:m}]=await p({data:o,to:c});if(!m)throw new Ec({data:d});return d==="0x"?{data:void 0}:{data:d}}function $6(e){const{code:t,data:r}=e;return Ic({abi:Nm(["constructor(bytes, bytes)"]),bytecode:Q0,args:[t,r]})}function N6(e){const{data:t,factory:r,factoryData:n,to:s}=e;return Ic({abi:Nm(["constructor(address, bytes, address, bytes)"]),bytecode:I6,args:[s,t,r,n]})}function U6(e){var r;if(!(e instanceof z))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 Wr(e,t){const{abi:r,address:n,args:s,functionName:i,...o}=t,a=dr({abi:r,args:s,functionName:i});try{const{data:c}=await se(e,ra,"call")({...o,data:a,to:n});return Ls({abi:r,args:s,functionName:i,data:c||"0x"})}catch(c){throw Is(c,{abi:r,address:n,args:s,docsPath:"/docs/contract/readContract",functionName:i})}}async function ng(e,t){const{abi:r,address:n,args:s,dataSuffix:i,functionName:o,...a}=t,c=a.account?Xe(a.account):e.account,l=dr({abi:r,args:s,functionName:o});try{const{data:u}=await se(e,ra,"call")({batch:!1,data:`${l}${i?i.replace("0x",""):""}`,to:n,...a,account:c}),f=Ls({abi:r,args:s,functionName:o,data:u||"0x"}),p=r.filter(d=>"name"in d&&d.name===t.functionName);return{result:f,request:{abi:p,address:n,args:s,dataSuffix:i,functionName:o,...a,account:c}}}catch(u){throw Is(u,{abi:r,address:n,args:s,docsPath:"/docs/contract/simulateContract",functionName:o,sender:c==null?void 0:c.address})}}const yu=new Map,lp=new Map;let M6=0;function vn(e,t,r){const n=++M6,s=()=>yu.get(e)||[],i=()=>{const u=s();yu.set(e,u.filter(f=>f.id!==n))},o=()=>{const u=s();if(!u.some(p=>p.id===n))return;const f=lp.get(e);if(u.length===1&&f){const p=f();p instanceof Promise&&p.catch(()=>{})}i()},a=s();if(yu.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return o;const c={};for(const u in t)c[u]=(...f)=>{var d,m;const p=s();if(p.length!==0)for(const g of p)(m=(d=g.fns)[u])==null||m.call(d,...f)};const l=r(c);return typeof l=="function"&&lp.set(e,l),o}async function Ef(e){return new Promise(t=>setTimeout(t,e))}function Ci(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let s=!0;const i=()=>s=!1;return(async()=>{let a;t&&(a=await e({unpoll:i}));const c=await(r==null?void 0:r(a))??n;await Ef(c);const l=async()=>{s&&(await e({unpoll:i}),await Ef(n),l())};l()})(),i}const F6=new Map,j6=new Map;function L6(e){const t=(s,i)=>({clear:()=>i.delete(s),get:()=>i.get(s),set:o=>i.set(s,o)}),r=t(e,F6),n=t(e,j6);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function D6(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){const n=L6(t),s=n.response.get();if(s&&r>0&&new Date().getTime()-s.created.getTime()<r)return s.data;let i=n.promise.get();i||(i=e(),n.promise.set(i));try{const o=await i;return n.response.set({created:new Date,data:o}),o}finally{n.promise.clear()}}const H6=e=>`blockNumber.${e}`;async function na(e,{cacheTime:t=e.cacheTime}={}){const r=await D6(()=>e.request({method:"eth_blockNumber"}),{cacheKey:H6(e.uid),cacheTime:t});return BigInt(r)}async function Pc(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 s=n.map(i=>wn(i));return!("abi"in t)||!t.abi?s:Od({abi:t.abi,logs:s,strict:r})}async function Oc(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}function sg(e,t){const{abi:r,address:n,args:s,batch:i=!0,eventName:o,fromBlock:a,onError:c,onLogs:l,poll:u,pollingInterval:f=e.pollingInterval,strict:p}=t;return(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")))?(()=>{const w=p??!1,A=Ze(["watchContractEvent",n,s,i,e.uid,o,f,w,a]);return vn(A,{onLogs:l,onError:c},T=>{let E;a!==void 0&&(E=a-1n);let S,I=!1;const P=Ci(async()=>{var $;if(!I){try{S=await se(e,pd,"createContractEventFilter")({abi:r,address:n,args:s,eventName:o,strict:w,fromBlock:a})}catch{}I=!0;return}try{let j;if(S)j=await se(e,Pc,"getFilterChanges")({filter:S});else{const k=await se(e,na,"getBlockNumber")({});E&&E<k?j=await se(e,Cd,"getContractEvents")({abi:r,address:n,args:s,eventName:o,fromBlock:E+1n,toBlock:k,strict:w}):j=[],E=k}if(j.length===0)return;if(i)T.onLogs(j);else for(const k of j)T.onLogs([k])}catch(j){S&&j instanceof Ts&&(I=!1),($=T.onError)==null||$.call(T,j)}},{emitOnBegin:!0,interval:f});return async()=>{S&&await se(e,Oc,"uninstallFilter")({filter:S}),P()}})})():(()=>{const w=p??!1,A=Ze(["watchContractEvent",n,s,i,e.uid,o,f,w]);let T=!0,E=()=>T=!1;return vn(A,{onLogs:l,onError:c},S=>((async()=>{try{const I=(()=>{if(e.transport.type==="fallback"){const j=e.transport.transports.find(k=>k.config.type==="webSocket"||k.config.type==="ipc");return j?j.value:e.transport}return e.transport})(),P=o?Zo({abi:r,eventName:o,args:s}):[],{unsubscribe:$}=await I.subscribe({params:["logs",{address:n,topics:P}],onData(j){var F;if(!T)return;const k=j.result;try{const{eventName:R,args:U}=Pd({abi:r,data:k.data,topics:k.topics,strict:p}),H=wn(k,{args:U,eventName:R});S.onLogs([H])}catch(R){let U,H;if(R instanceof po||R instanceof pc){if(p)return;U=R.abiItem.name,H=(F=R.abiItem.inputs)==null?void 0:F.some(Z=>!("name"in Z&&Z.name))}const W=wn(k,{args:H?[]:{},eventName:U});S.onLogs([W])}},onError(j){var k;(k=S.onError)==null||k.call(S,j)}});E=$,T||E()}catch(I){c==null||c(I)}})(),()=>E()))})()}class Ds extends z{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(`
|
|
42
|
-
`),{docsPath:t,docsSlug:"account",name:"AccountNotFoundError"})}}class Ma extends z{constructor({docsPath:t,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:t,metaMessages:r,name:"AccountTypeNotSupportedError"})}}function ig({chain:e,currentChainId:t}){if(!e)throw new B6;if(t!==e.id)throw new O6({chain:e,currentChainId:t})}function og(e,{docsPath:t,...r}){const n=(()=>{const s=Ac(e,r);return s instanceof ea?e:s})();return new yE(n,{docsPath:t,...r})}async function Md(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}const mu=new bc(128);async function Bc(e,t){var T,E,S,I;const{account:r=e.account,chain:n=e.chain,accessList:s,authorizationList:i,blobs:o,data:a,gas:c,gasPrice:l,maxFeePerBlobGas:u,maxFeePerGas:f,maxPriorityFeePerGas:p,nonce:d,type:m,value:g,...w}=t;if(typeof r>"u")throw new Ds({docsPath:"/docs/actions/wallet/sendTransaction"});const A=r?Xe(r):null;try{js(t);const P=await(async()=>{if(t.to)return t.to;if(t.to!==null&&i&&i.length>0)return await k0({authorization:i[0]}).catch(()=>{throw new z("`to` is required. Could not infer from `authorizationList`.")})})();if((A==null?void 0:A.type)==="json-rpc"||A===null){let $;n!==null&&($=await se(e,Oi,"getChainId")({}),ig({currentChainId:$,chain:n}));const j=(S=(E=(T=e.chain)==null?void 0:T.formatters)==null?void 0:E.transactionRequest)==null?void 0:S.format,F=(j||Pi)({...xc(w,{format:j}),accessList:s,authorizationList:i,blobs:o,chainId:$,data:a,from:A==null?void 0:A.address,gas:c,gasPrice:l,maxFeePerBlobGas:u,maxFeePerGas:f,maxPriorityFeePerGas:p,nonce:d,to:P,type:m,value:g}),R=mu.get(e.uid),U=R?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:U,params:[F]},{retryCount:0})}catch(H){if(R===!1)throw H;const W=H;if(W.name==="InvalidInputRpcError"||W.name==="InvalidParamsRpcError"||W.name==="MethodNotFoundRpcError"||W.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[F]},{retryCount:0}).then(Z=>(mu.set(e.uid,!0),Z)).catch(Z=>{const Q=Z;throw Q.name==="MethodNotFoundRpcError"||Q.name==="MethodNotSupportedRpcError"?(mu.set(e.uid,!1),W):Q});throw W}}if((A==null?void 0:A.type)==="local"){const $=await se(e,kc,"prepareTransactionRequest")({account:A,accessList:s,authorizationList:i,blobs:o,chain:n,data:a,gas:c,gasPrice:l,maxFeePerBlobGas:u,maxFeePerGas:f,maxPriorityFeePerGas:p,nonce:d,nonceManager:A.nonceManager,parameters:[...D0,"sidecars"],type:m,value:g,...w,to:P}),j=(I=n==null?void 0:n.serializers)==null?void 0:I.transaction,k=await A.signTransaction($,{serializer:j});return await se(e,Md,"sendRawTransaction")({serializedTransaction:k})}throw(A==null?void 0:A.type)==="smart"?new Ma({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new Ma({docsPath:"/docs/actions/wallet/sendTransaction",type:A==null?void 0:A.type})}catch(P){throw P instanceof Ma?P:og(P,{...t,account:A,chain:t.chain||void 0})}}async function ag(e,t){const{abi:r,account:n=e.account,address:s,args:i,dataSuffix:o,functionName:a,...c}=t;if(typeof n>"u")throw new Ds({docsPath:"/docs/contract/writeContract"});const l=n?Xe(n):null,u=dr({abi:r,args:i,functionName:a});try{return await se(e,Bc,"sendTransaction")({data:`${u}${o?o.replace("0x",""):""}`,to:s,account:l,...c})}catch(f){throw Is(f,{abi:r,address:s,args:i,docsPath:"/docs/contract/writeContract",functionName:a,sender:l==null?void 0:l.address})}}function gu({abi:e,address:t,client:r}){const n=r,[s,i]=n?"public"in n&&"wallet"in n?[n.public,n.wallet]:"public"in n?[n.public,void 0]:"wallet"in n?[void 0,n.wallet]:[n,n]:[void 0,void 0],o=s!=null,a=i!=null,c={};let l=!1,u=!1,f=!1;for(const p of e)if(p.type==="function"?p.stateMutability==="view"||p.stateMutability==="pure"?l=!0:u=!0:p.type==="event"&&(f=!0),l&&u&&f)break;return o&&(l&&(c.read=new Proxy({},{get(p,d){return(...m)=>{const{args:g,options:w}=ya(m);return se(s,Wr,"readContract")({abi:e,address:t,functionName:d,args:g,...w})}}})),u&&(c.simulate=new Proxy({},{get(p,d){return(...m)=>{const{args:g,options:w}=ya(m);return se(s,ng,"simulateContract")({abi:e,address:t,functionName:d,args:g,...w})}}})),f&&(c.createEventFilter=new Proxy({},{get(p,d){return(...m)=>{const g=e.find(T=>T.type==="event"&&T.name===d),{args:w,options:A}=bu(m,g);return se(s,pd,"createContractEventFilter")({abi:e,address:t,eventName:d,args:w,...A})}}}),c.getEvents=new Proxy({},{get(p,d){return(...m)=>{const g=e.find(T=>T.type==="event"&&T.name===d),{args:w,options:A}=bu(m,g);return se(s,Cd,"getContractEvents")({abi:e,address:t,eventName:d,args:w,...A})}}}),c.watchEvent=new Proxy({},{get(p,d){return(...m)=>{const g=e.find(T=>T.type==="event"&&T.name===d),{args:w,options:A}=bu(m,g);return se(s,sg,"watchContractEvent")({abi:e,address:t,eventName:d,args:w,...A})}}}))),a&&u&&(c.write=new Proxy({},{get(p,d){return(...m)=>{const{args:g,options:w}=ya(m);return se(i,ag,"writeContract")({abi:e,address:t,functionName:d,args:g,...w})}}})),(o||a)&&u&&(c.estimateGas=new Proxy({},{get(p,d){return(...m)=>{const{args:g,options:w}=ya(m);return se(s??i,z0,"estimateContractGas")({abi:e,address:t,functionName:d,args:g,...w,account:w.account??i.account})}}})),c.address=t,c.abi=e,c}function ya(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 bu(e,t){let r=!1;Array.isArray(e[0])?r=!0:e.length===1?r=t.inputs.some(i=>i.indexed):e.length===2&&(r=!0);const n=r?e[0]:void 0,s=(r?e[1]:e[0])??{};return{args:n,options:s}}class z6 extends z{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 ec(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0}={}){return new Promise((s,i)=>{const o=async({count:a=0}={})=>{const c=async({error:l})=>{const u=typeof t=="function"?t({count:a,error:l}):t;u&&await Ef(u),o({count:a+1})};try{const l=await e();s(l)}catch(l){if(a<r&&await n({count:a,error:l}))return c({error:l});i(l)}};o()})}const cg={"0x0":"reverted","0x1":"success"};function ug(e){const t={...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(r=>wn(r)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?ur(e.transactionIndex):null,status:e.status?cg[e.status]:null,type:e.type?I0[e.type]||e.type:null};return e.blobGasPrice&&(t.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(t.blobGasUsed=BigInt(e.blobGasUsed)),t}const q6=bd("transactionReceipt",ug),lg="0x5792579257925792579257925792579257925792579257925792579257925792",fg=X(0,{size:32});async function V6(e,t){const{account:r=e.account,capabilities:n,chain:s=e.chain,experimental_fallback:i,experimental_fallbackDelay:o=32,forceAtomic:a=!1,id:c,version:l="2.0.0"}=t,u=r?Xe(r):null,f=t.calls.map(p=>{const d=p,m=d.abi?dr({abi:d.abi,functionName:d.functionName,args:d.args}):d.data;return{data:d.dataSuffix&&m?Vt([m,d.dataSuffix]):m,to:d.to,value:d.value?X(d.value):void 0}});try{const p=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:a,calls:f,capabilities:n,chainId:X(s.id),from:u==null?void 0:u.address,id:c,version:l}]},{retryCount:0});return typeof p=="string"?{id:p}:p}catch(p){const d=p;if(i&&(d.name==="MethodNotFoundRpcError"||d.name==="MethodNotSupportedRpcError"||d.name==="UnknownRpcError"||d.details.toLowerCase().includes("does not exist / is not available")||d.details.toLowerCase().includes("missing or invalid. request()")||d.details.toLowerCase().includes("did not match any variant of untagged enum")||d.details.toLowerCase().includes("account upgraded to unsupported contract")||d.details.toLowerCase().includes("eip-7702 not supported")||d.details.toLowerCase().includes("unsupported wc_ method"))){if(n&&Object.values(n).some(T=>!T.optional)){const T="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new bi(new z(T,{details:T}))}if(a&&f.length>1){const A="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new wi(new z(A,{details:A}))}const m=[];for(const A of f){const T=Bc(e,{account:u,chain:s,data:A.data,to:A.to,value:A.value?ot(A.value):void 0});m.push(T),o>0&&await new Promise(E=>setTimeout(E,o))}const g=await Promise.allSettled(m);if(g.every(A=>A.status==="rejected"))throw g[0].reason;const w=g.map(A=>A.status==="fulfilled"?A.value:fg);return{id:Vt([...w,X(s.id,{size:32}),lg])}}throw og(p,{...t,account:u,chain:t.chain})}}async function dg(e,t){async function r(u){if(u.endsWith(lg.slice(2))){const p=cr(Qa(u,-64,-32)),d=Qa(u,0,-64).slice(2).match(/.{1,64}/g),m=await Promise.all(d.map(w=>fg.slice(2)!==w?e.request({method:"eth_getTransactionReceipt",params:[`0x${w}`]},{dedupe:!0}):void 0)),g=m.some(w=>w===null)?100:m.every(w=>(w==null?void 0:w.status)==="0x1")?200:m.every(w=>(w==null?void 0:w.status)==="0x0")?500:600;return{atomic:!1,chainId:ur(p),receipts:m.filter(Boolean),status:g,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[u]})}const{atomic:n=!1,chainId:s,receipts:i,version:o="2.0.0",...a}=await r(t.id),[c,l]=(()=>{const u=a.status;return u>=100&&u<200?["pending",u]:u>=200&&u<300?["success",u]:u>=300&&u<700?["failure",u]:u==="CONFIRMED"?["success",200]:u==="PENDING"?["pending",100]:[void 0,u]})();return{...a,atomic:n,chainId:s?ur(s):void 0,receipts:(i==null?void 0:i.map(u=>({...u,blockNumber:ot(u.blockNumber),gasUsed:ot(u.gasUsed),status:cg[u.status]})))??[],statusCode:l,status:c,version:o}}async function G6(e,t){const{id:r,pollingInterval:n=e.pollingInterval,status:s=({statusCode:g})=>g===200||g>=300,retryCount:i=4,retryDelay:o=({count:g})=>~~(1<<g)*200,timeout:a=6e4,throwOnFailure:c=!1}=t,l=Ze(["waitForCallsStatus",e.uid,r]),{promise:u,resolve:f,reject:p}=Ud();let d;const m=vn(l,{resolve:f,reject:p},g=>{const w=Ci(async()=>{const A=T=>{clearTimeout(d),w(),T(),m()};try{const T=await ec(async()=>{const E=await dg(e,{id:r});if(c&&E.status==="failure")throw new z6(E);return E},{retryCount:i,delay:o});if(!s(T))return;A(()=>g.resolve(T))}catch(T){A(()=>g.reject(T))}},{interval:n,emitOnBegin:!0});return w});return d=a?setTimeout(()=>{m(),clearTimeout(d),p(new W6({id:r}))},a):void 0,await u}class W6 extends z{constructor({id:t}){super(`Timed out while waiting for call bundle with id "${t}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}const Af=256;let ma=Af,ga;function hg(e=11){if(!ga||ma+e>Af*2){ga="",ma=0;for(let t=0;t<Af;t++)ga+=(256+Math.random()*256|0).toString(16).substring(1)}return ga.substring(ma,ma+++e)}function pg(e){const{batch:t,chain:r,ccipRead:n,key:s="base",name:i="Base Client",type:o="base"}=e,a=e.experimental_blockTag??(typeof(r==null?void 0:r.experimental_preconfirmationTime)=="number"?"pending":void 0),c=(r==null?void 0:r.blockTime)??12e3,l=Math.min(Math.max(Math.floor(c/2),500),4e3),u=e.pollingInterval??l,f=e.cacheTime??u,p=e.account?Xe(e.account):void 0,{config:d,request:m,value:g}=e.transport({chain:r,pollingInterval:u}),w={...d,...g},A={account:p,batch:t,cacheTime:f,ccipRead:n,chain:r,key:s,name:i,pollingInterval:u,request:m,transport:w,type:o,uid:hg(),...a?{experimental_blockTag:a}:{}};function T(E){return S=>{const I=S(E);for(const $ in A)delete I[$];const P={...E,...I};return Object.assign(P,{extend:T(P)})}}return Object.assign(A,{extend:T(A)})}const ba=new bc(8192);function K6(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(ba.get(r))return ba.get(r);const n=e().finally(()=>ba.delete(r));return ba.set(r,n),n}function X6(e,t={}){return async(r,n={})=>{var f;const{dedupe:s=!1,methods:i,retryDelay:o=150,retryCount:a=3,uid:c}={...t,...n},{method:l}=r;if((f=i==null?void 0:i.exclude)!=null&&f.includes(l))throw new ls(new Error("method not supported"),{method:l});if(i!=null&&i.include&&!i.include.includes(l))throw new ls(new Error("method not supported"),{method:l});const u=s?mi(`${c}.${Ze(r)}`):void 0;return K6(()=>ec(async()=>{try{return await e(r)}catch(p){const d=p;switch(d.code){case bo.code:throw new bo(d);case wo.code:throw new wo(d);case vo.code:throw new vo(d,{method:r.method});case Eo.code:throw new Eo(d);case ks.code:throw new ks(d);case Ts.code:throw new Ts(d);case Ao.code:throw new Ao(d);case xo.code:throw new xo(d);case So.code:throw new So(d);case ls.code:throw new ls(d,{method:r.method});case gi.code:throw new gi(d);case _o.code:throw new _o(d);case ui.code:throw new ui(d);case ko.code:throw new ko(d);case To.code:throw new To(d);case Io.code:throw new Io(d);case Po.code:throw new Po(d);case Oo.code:throw new Oo(d);case bi.code:throw new bi(d);case Bo.code:throw new Bo(d);case Co.code:throw new Co(d);case Ro.code:throw new Ro(d);case $o.code:throw new $o(d);case No.code:throw new No(d);case wi.code:throw new wi(d);case 5e3:throw new ui(d);default:throw p instanceof z?p:new AE(d)}}},{delay:({count:p,error:d})=>{var m;if(d&&d instanceof ci){const g=(m=d==null?void 0:d.headers)==null?void 0:m.get("Retry-After");if(g!=null&&g.match(/\d/))return Number.parseInt(g)*1e3}return~~(1<<p)*o},retryCount:a,shouldRetry:({error:p})=>Y6(p)}),{enabled:s,id:u})}}function Y6(e){return"code"in e&&typeof e.code=="number"?e.code===-1||e.code===gi.code||e.code===ks.code:e instanceof ci&&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 yg({key:e,methods:t,name:r,request:n,retryCount:s=3,retryDelay:i=150,timeout:o,type:a},c){const l=hg();return{config:{key:e,methods:t,name:r,request:n,retryCount:s,retryDelay:i,timeout:o,type:a},request:X6(n,{methods:t,retryCount:s,retryDelay:i,uid:l}),value:c}}function fp(e,t={}){const{key:r="custom",methods:n,name:s="Custom Provider",retryDelay:i}=t;return({retryCount:o})=>yg({key:r,methods:n,name:s,request:e.request.bind(e),retryCount:t.retryCount??o,retryDelay:i,type:"custom"})}class Z6 extends z{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 J6(e,{errorInstance:t=new Error("timed out"),timeout:r,signal:n}){return new Promise((s,i)=>{(async()=>{let o;try{const a=new AbortController;r>0&&(o=setTimeout(()=>{n&&a.abort()},r)),s(await e({signal:(a==null?void 0:a.signal)||null}))}catch(a){(a==null?void 0:a.name)==="AbortError"&&i(t),i(a)}finally{clearTimeout(o)}})()})}function Q6(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const dp=Q6();function eA(e,t={}){return{async request(r){var f;const{body:n,onRequest:s=t.onRequest,onResponse:i=t.onResponse,timeout:o=t.timeout??1e4}=r,a={...t.fetchOptions??{},...r.fetchOptions??{}},{headers:c,method:l,signal:u}=a;try{const p=await J6(async({signal:m})=>{const g={...a,body:Array.isArray(n)?Ze(n.map(E=>({jsonrpc:"2.0",id:E.id??dp.take(),...E}))):Ze({jsonrpc:"2.0",id:n.id??dp.take(),...n}),headers:{"Content-Type":"application/json",...c},method:l||"POST",signal:u||(o>0?m:null)},w=new Request(e,g),A=await(s==null?void 0:s(w,g))??{...g,url:e};return await fetch(A.url??e,A)},{errorInstance:new Yh({body:n,url:e}),timeout:o,signal:!0});i&&await i(p);let d;if((f=p.headers.get("Content-Type"))!=null&&f.startsWith("application/json"))d=await p.json();else{d=await p.text();try{d=JSON.parse(d||"{}")}catch(m){if(p.ok)throw m;d={error:d}}}if(!p.ok)throw new ci({body:n,details:Ze(d.error)||p.statusText,headers:p.headers,status:p.status,url:e});return d}catch(p){throw p instanceof ci||p instanceof Yh?p:new ci({body:n,cause:p,url:e})}}}}function mg(e,t={}){const{batch:r,fetchOptions:n,key:s="http",methods:i,name:o="HTTP JSON-RPC",onFetchRequest:a,onFetchResponse:c,retryDelay:l,raw:u}=t;return({chain:f,retryCount:p,timeout:d})=>{const{batchSize:m=1e3,wait:g=0}=typeof r=="object"?r:{},w=t.retryCount??p,A=d??t.timeout??1e4,T=f==null?void 0:f.rpcUrls.default.http[0];if(!T)throw new Z6;const E=eA(T,{fetchOptions:n,onRequest:a,onResponse:c,timeout:A});return yg({key:s,methods:i,name:o,async request({method:S,params:I}){const P={method:S,params:I},{schedule:$}=rg({id:T,wait:g,shouldSplitBatch(R){return R.length>m},fn:R=>E.request({body:R}),sort:(R,U)=>R.id-U.id}),j=async R=>r?$(R):[await E.request({body:R})],[{error:k,result:F}]=await j(P);if(u)return{error:k,result:F};if(k)throw new gd({body:P,error:k,url:T});return F},retryCount:w,retryDelay:l,timeout:A,type:"http"},{fetchOptions:n,url:T})}}function Fd(e,t){var n,s,i,o,a,c;if(!(e instanceof z))return!1;const r=e.walk(l=>l instanceof cf);return r instanceof cf?!!(((n=r.data)==null?void 0:n.errorName)==="ResolverNotFound"||((s=r.data)==null?void 0:s.errorName)==="ResolverWildcardNotSupported"||((i=r.data)==null?void 0:i.errorName)==="ResolverNotContract"||((o=r.data)==null?void 0:o.errorName)==="ResolverError"||((a=r.data)==null?void 0:a.errorName)==="HttpError"||(c=r.reason)!=null&&c.includes("Wildcard on non-extended resolvers is not supported")||t==="reverse"&&r.reason===p0[50]):!1}function tA(e){const{abi:t,data:r}=e,n=_s(r,0,4),s=t.find(i=>i.type==="function"&&n===Yo(Ar(i)));if(!s)throw new qv(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:s.name,args:"inputs"in s&&s.inputs&&s.inputs.length>0?Jo(s.inputs,_s(r,4)):void 0}}const wu="/docs/contract/encodeErrorResult";function hp(e){const{abi:t,errorName:r,args:n}=e;let s=t[0];if(r){const c=Fs({abi:t,args:n,name:r});if(!c)throw new Uh(r,{docsPath:wu});s=c}if(s.type!=="error")throw new Uh(void 0,{docsPath:wu});const i=Ar(s),o=Yo(i);let a="0x";if(n&&n.length>0){if(!s.inputs)throw new Hv(s.name,{docsPath:wu});a=kn(s.inputs,n)}return Tr([o,a])}const vu="/docs/contract/encodeFunctionResult";function rA(e){const{abi:t,functionName:r,result:n}=e;let s=t[0];if(r){const o=Fs({abi:t,name:r});if(!o)throw new yi(r,{docsPath:vu});s=o}if(s.type!=="function")throw new yi(void 0,{docsPath:vu});if(!s.outputs)throw new Dm(s.name,{docsPath:vu});const i=(()=>{if(s.outputs.length===0)return[];if(s.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new Hm(n)})();return kn(s.outputs,i)}const Cc="x-batch-gateway:true";async function gg(e){const{data:t,ccipRequest:r}=e,{args:[n]}=tA({abi:wf,data:t}),s=[],i=[];return await Promise.all(n.map(async(o,a)=>{try{i[a]=o.urls.includes(Cc)?await gg({data:o.data,ccipRequest:r}):await r(o),s[a]=!1}catch(c){s[a]=!0,i[a]=nA(c)}})),rA({abi:wf,functionName:"query",result:[s,i]})}function nA(e){return e.name==="HttpRequestError"&&e.status?hp({abi:wf,errorName:"HttpError",args:[e.status,e.shortMessage]}):hp({abi:[y0],errorName:"Error",args:["shortMessage"in e?e.shortMessage:e.message]})}function bg(e){if(e.length!==66||e.indexOf("[")!==0||e.indexOf("]")!==65)return null;const t=`0x${e.slice(1,65)}`;return xr(t)?t:null}function Fa(e){let t=new Uint8Array(32).fill(0);if(!e)return Je(t);const r=e.split(".");for(let n=r.length-1;n>=0;n-=1){const s=bg(r[n]),i=s?Ii(s):lt(bs(r[n]),"bytes");t=lt(Vt([t,i]),"bytes")}return Je(t)}function sA(e){return`[${e.slice(2)}]`}function iA(e){const t=new Uint8Array(32).fill(0);return e?bg(e)||lt(bs(e)):Je(t)}function Rc(e){const t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);const r=new Uint8Array(bs(t).byteLength+2);let n=0;const s=t.split(".");for(let i=0;i<s.length;i++){let o=bs(s[i]);o.byteLength>255&&(o=bs(sA(iA(s[i])))),r[n]=o.length,r.set(o,n+1),n+=o.length+1}return r.byteLength!==n+1?r.slice(0,n+1):r}async function oA(e,t){const{blockNumber:r,blockTag:n,coinType:s,name:i,gatewayUrls:o,strict:a}=t,{chain:c}=e,l=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Bi({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),u=c==null?void 0:c.ensTlds;if(u&&!u.some(f=>i.endsWith(f)))return null;try{const f=dr({abi:cp,functionName:"addr",...s!=null?{args:[Fa(i),BigInt(s)]}:{args:[Fa(i)]}}),p={address:l,abi:J0,functionName:"resolve",args:[mt(Rc(i)),f,o??[Cc]],blockNumber:r,blockTag:n},m=await se(e,Wr,"readContract")(p);if(m[0]==="0x")return null;const g=Ls({abi:cp,args:s!=null?[Fa(i),BigInt(s)]:void 0,functionName:"addr",data:m[0]});return g==="0x"||cr(g)==="0x00"?null:g}catch(f){if(a)throw f;if(Fd(f,"resolve"))return null;throw f}}class aA extends z{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 Fi extends z{constructor({reason:t}){super(`ENS NFT avatar URI is invalid. ${t}`,{name:"EnsAvatarInvalidNftUriError"})}}class jd extends z{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 cA extends z{constructor({namespace:t}){super(`ENS NFT avatar namespace "${t}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const uA=/(?<protocol>https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,lA=/^(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>\/.*)?$/,fA=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,dA=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function hA(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"||!globalThis.hasOwnProperty("Image")?!1:new Promise(r=>{const n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=e})}}function pp(e,t){return e?e.endsWith("/")?e.slice(0,-1):e:t}function wg({uri:e,gatewayUrls:t}){const r=fA.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};const n=pp(t==null?void 0:t.ipfs,"https://ipfs.io"),s=pp(t==null?void 0:t.arweave,"https://arweave.net"),i=e.match(uA),{protocol:o,subpath:a,target:c,subtarget:l=""}=(i==null?void 0:i.groups)||{},u=o==="ipns:/"||a==="ipns/",f=o==="ipfs:/"||a==="ipfs/"||lA.test(e);if(e.startsWith("http")&&!u&&!f){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((u||f)&&c)return{uri:`${n}/${u?"ipns":"ipfs"}/${c}${l}`,isOnChain:!1,isEncoded:!1};if(o==="ar:/"&&c)return{uri:`${s}/${c}${l||""}`,isOnChain:!1,isEncoded:!1};let p=e.replace(dA,"");if(p.startsWith("<svg")&&(p=`data:image/svg+xml;base64,${btoa(p)}`),p.startsWith("data:")||p.startsWith("{"))return{uri:p,isOnChain:!0,isEncoded:!1};throw new jd({uri:e})}function vg(e){if(typeof e!="object"||!("image"in e)&&!("image_url"in e)&&!("image_data"in e))throw new aA({data:e});return e.image||e.image_url||e.image_data}async function pA({gatewayUrls:e,uri:t}){try{const r=await fetch(t).then(s=>s.json());return await Ld({gatewayUrls:e,uri:vg(r)})}catch{throw new jd({uri:t})}}async function Ld({gatewayUrls:e,uri:t}){const{uri:r,isOnChain:n}=wg({uri:t,gatewayUrls:e});if(n||await hA(r))return r;throw new jd({uri:t})}function yA(e){let t=e;t.startsWith("did:nft:")&&(t=t.replace("did:nft:","").replace(/_/g,"/"));const[r,n,s]=t.split("/"),[i,o]=r.split(":"),[a,c]=n.split(":");if(!i||i.toLowerCase()!=="eip155")throw new Fi({reason:"Only EIP-155 supported"});if(!o)throw new Fi({reason:"Chain ID not found"});if(!c)throw new Fi({reason:"Contract address not found"});if(!s)throw new Fi({reason:"Token ID not found"});if(!a)throw new Fi({reason:"ERC namespace not found"});return{chainID:Number.parseInt(o),namespace:a.toLowerCase(),contractAddress:c,tokenID:s}}async function mA(e,{nft:t}){if(t.namespace==="erc721")return Wr(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 Wr(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 cA({namespace:t.namespace})}async function gA(e,{gatewayUrls:t,record:r}){return/eip155:/i.test(r)?bA(e,{gatewayUrls:t,record:r}):Ld({uri:r,gatewayUrls:t})}async function bA(e,{gatewayUrls:t,record:r}){const n=yA(r),s=await mA(e,{nft:n}),{uri:i,isOnChain:o,isEncoded:a}=wg({uri:s,gatewayUrls:t});if(o&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){const l=a?atob(i.replace("data:application/json;base64,","")):i,u=JSON.parse(l);return Ld({uri:vg(u),gatewayUrls:t})}let c=n.tokenID;return n.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),pA({gatewayUrls:t,uri:i.replace(/(?:0x)?{id}/,c)})}async function Eg(e,t){const{blockNumber:r,blockTag:n,key:s,name:i,gatewayUrls:o,strict:a}=t,{chain:c}=e,l=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Bi({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),u=c==null?void 0:c.ensTlds;if(u&&!u.some(f=>i.endsWith(f)))return null;try{const f={address:l,abi:J0,functionName:"resolve",args:[mt(Rc(i)),dr({abi:ap,functionName:"text",args:[Fa(i),s]}),o??[Cc]],blockNumber:r,blockTag:n},d=await se(e,Wr,"readContract")(f);if(d[0]==="0x")return null;const m=Ls({abi:ap,functionName:"text",data:d[0]});return m===""?null:m}catch(f){if(a)throw f;if(Fd(f,"resolve"))return null;throw f}}async function wA(e,{blockNumber:t,blockTag:r,assetGatewayUrls:n,name:s,gatewayUrls:i,strict:o,universalResolverAddress:a}){const c=await se(e,Eg,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:s,universalResolverAddress:a,gatewayUrls:i,strict:o});if(!c)return null;try{return await gA(e,{record:c,gatewayUrls:n})}catch{return null}}async function vA(e,{address:t,blockNumber:r,blockTag:n,gatewayUrls:s,strict:i,universalResolverAddress:o}){let a=o;if(!a){if(!e.chain)throw new Error("client chain not configured. universalResolverAddress is required.");a=Bi({blockNumber:r,chain:e.chain,contract:"ensUniversalResolver"})}const c=`${t.toLowerCase().substring(2)}.addr.reverse`;try{const l={address:a,abi:k6,functionName:"reverse",args:[mt(Rc(c))],blockNumber:r,blockTag:n},u=se(e,Wr,"readContract"),[f,p]=s?await u({...l,args:[...l.args,s]}):await u(l);return t.toLowerCase()!==p.toLowerCase()?null:f}catch(l){if(i)throw l;if(Fd(l,"reverse"))return null;throw l}}async function EA(e,t){const{blockNumber:r,blockTag:n,name:s}=t,{chain:i}=e,o=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!i)throw new Error("client chain not configured. universalResolverAddress is required.");return Bi({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),a=i==null?void 0:i.ensTlds;if(a&&!a.some(l=>s.endsWith(l)))throw new Error(`${s} is not a valid ENS TLD (${a==null?void 0:a.join(", ")}) for chain "${i.name}" (id: ${i.id}).`);const[c]=await se(e,Wr,"readContract")({address:o,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[mt(Rc(s))],blockNumber:r,blockTag:n});return c}async function Ag(e,t){var w,A,T;const{account:r=e.account,blockNumber:n,blockTag:s="latest",blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:l,maxFeePerGas:u,maxPriorityFeePerGas:f,to:p,value:d,...m}=t,g=r?Xe(r):void 0;try{js(t);const S=(typeof n=="bigint"?X(n):void 0)||s,I=(T=(A=(w=e.chain)==null?void 0:w.formatters)==null?void 0:A.transactionRequest)==null?void 0:T.format,$=(I||Pi)({...xc(m,{format:I}),from:g==null?void 0:g.address,blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:l,maxFeePerGas:u,maxPriorityFeePerGas:f,to:p,value:d}),j=await e.request({method:"eth_createAccessList",params:[$,S]});return{accessList:j.accessList,gasUsed:BigInt(j.gasUsed)}}catch(E){throw tg(E,{...t,account:g,chain:e.chain})}}async function AA(e){const t=wc(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}async function xg(e,{address:t,args:r,event:n,events:s,fromBlock:i,strict:o,toBlock:a}={}){const c=s??(n?[n]:void 0),l=wc(e,{method:"eth_newFilter"});let u=[];c&&(u=[c.flatMap(d=>Zo({abi:[d],eventName:d.name,args:r}))],n&&(u=u[0]));const f=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof i=="bigint"?X(i):i,toBlock:typeof a=="bigint"?X(a):a,...u.length?{topics:u}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:i,id:f,request:l(f),strict:!!o,toBlock:a,type:"event"}}async function Sg(e){const t=wc(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}async function xA(e){const t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}async function SA(e,{blockHash:t,blockNumber:r,blockTag:n="latest"}={}){const s=r!==void 0?X(r):void 0;let i;return t?i=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0}):i=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[s||n]},{dedupe:!!s}),ur(i)}async function yp(e,{address:t,blockNumber:r,blockTag:n="latest"}){const s=r!==void 0?X(r):void 0,i=await e.request({method:"eth_getCode",params:[t,s||n]},{dedupe:!!s});if(i!=="0x")return i}class _A extends z{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 kA(e,t){const{address:r,factory:n,factoryData:s}=t;try{const[i,o,a,c,l,u,f]=await se(e,Wr,"readContract")({abi:TA,address:r,functionName:"eip712Domain",factory:n,factoryData:s});return{domain:{name:o,version:a,chainId:Number(c),verifyingContract:l,salt:u},extensions:f,fields:i}}catch(i){const o=i;throw o.name==="ContractFunctionExecutionError"&&o.cause.name==="ContractFunctionZeroDataError"?new _A({address:r}):o}}const TA=[{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 IA(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 PA(e,{blockCount:t,blockNumber:r,blockTag:n="latest",rewardPercentiles:s}){const i=typeof r=="bigint"?X(r):void 0,o=await e.request({method:"eth_feeHistory",params:[X(t),i||n,s]},{dedupe:!!i});return IA(o)}async function OA(e,{filter:t}){const r=t.strict??!1,s=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map(i=>wn(i));return t.abi?Od({abi:t.abi,logs:s,strict:r}):s}function bt(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}class BA extends z{constructor({domain:t}){super(`Invalid domain "${Ze(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class CA extends z{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 RA extends z{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function $A(e){const{domain:t={},message:r,primaryType:n}=e,s={EIP712Domain:Og({domain:t}),...e.types};Pg({domain:t,message:r,primaryType:n,types:s});const i=["0x1901"];return t&&i.push(NA({domain:t,types:s})),n!=="EIP712Domain"&&i.push(_g({data:r,primaryType:n,types:s})),lt(Vt(i))}function NA({domain:e,types:t}){return _g({data:e,primaryType:"EIP712Domain",types:t})}function _g({data:e,primaryType:t,types:r}){const n=kg({data:e,primaryType:t,types:r});return lt(n)}function kg({data:e,primaryType:t,types:r}){const n=[{type:"bytes32"}],s=[UA({primaryType:t,types:r})];for(const i of r[t]){const[o,a]=Ig({types:r,name:i.name,type:i.type,value:e[i.name]});n.push(o),s.push(a)}return kn(n,s)}function UA({primaryType:e,types:t}){const r=mt(MA({primaryType:e,types:t}));return lt(r)}function MA({primaryType:e,types:t}){let r="";const n=Tg({primaryType:e,types:t});n.delete(e);const s=[e,...Array.from(n).sort()];for(const i of s)r+=`${i}(${t[i].map(({name:o,type:a})=>`${a} ${o}`).join(",")})`;return r}function Tg({primaryType:e,types:t},r=new Set){const n=e.match(/^\w*/u),s=n==null?void 0:n[0];if(r.has(s)||t[s]===void 0)return r;r.add(s);for(const i of t[s])Tg({primaryType:i.type,types:t},r);return r}function Ig({types:e,name:t,type:r,value:n}){if(e[r]!==void 0)return[{type:"bytes32"},lt(kg({data:n,primaryType:r,types:e}))];if(r==="bytes")return n=`0x${(n.length%2?"0":"")+n.slice(2)}`,[{type:"bytes32"},lt(n)];if(r==="string")return[{type:"bytes32"},lt(mt(n))];if(r.lastIndexOf("]")===r.length-1){const s=r.slice(0,r.lastIndexOf("[")),i=n.map(o=>Ig({name:t,type:s,types:e,value:o}));return[{type:"bytes32"},lt(kn(i.map(([o])=>o),i.map(([,o])=>o)))]}return[{type:r},n]}function FA(e){const{domain:t,message:r,primaryType:n,types:s}=e,i=(c,l)=>{const u={...l};for(const f of c){const{name:p,type:d}=f;d==="address"&&(u[p]=u[p].toLowerCase())}return u},o=s.EIP712Domain?t?i(s.EIP712Domain,t):{}:{},a=(()=>{if(n!=="EIP712Domain")return i(s[n],r)})();return Ze({domain:o,message:a,primaryType:n,types:s})}function Pg(e){const{domain:t,message:r,primaryType:n,types:s}=e,i=(o,a)=>{for(const c of o){const{name:l,type:u}=c,f=a[l],p=u.match(d0);if(p&&(typeof f=="number"||typeof f=="bigint")){const[g,w,A]=p;X(f,{signed:w==="int",size:Number.parseInt(A)/8})}if(u==="address"&&typeof f=="string"&&!st(f))throw new Bt({address:f});const d=u.match(M2);if(d){const[g,w]=d;if(w&&He(f)!==Number.parseInt(w))throw new Gv({expectedSize:Number.parseInt(w),givenSize:He(f)})}const m=s[u];m&&(jA(u),i(m,f))}};if(s.EIP712Domain&&t){if(typeof t!="object")throw new BA({domain:t});i(s.EIP712Domain,t)}if(n!=="EIP712Domain")if(s[n])i(s[n],r);else throw new CA({primaryType:n,types:s})}function Og({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 jA(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new RA({type:e})}function LA(e){const{authorizationList:t}=e;if(t)for(const r of t){const{chainId:n}=r,s=r.address;if(!st(s))throw new Bt({address:s});if(n<0)throw new Tc({chainId:n})}Dd(e)}function DA(e){const{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new F0;for(const r of t){const n=He(r),s=ur(_s(r,0,1));if(n!==32)throw new JE({hash:r,size:n});if(s!==M0)throw new QE({hash:r,version:s})}}Dd(e)}function Dd(e){const{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:s}=e;if(t<=0)throw new Tc({chainId:t});if(s&&!st(s))throw new Bt({address:s});if(n&&n>Sc)throw new Ps({maxFeePerGas:n});if(r&&n&&r>n)throw new Uo({maxFeePerGas:n,maxPriorityFeePerGas:r})}function HA(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=e;if(t<=0)throw new Tc({chainId:t});if(i&&!st(i))throw new Bt({address:i});if(r||s)throw new z("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Sc)throw new Ps({maxFeePerGas:n})}function zA(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=e;if(i&&!st(i))throw new Bt({address:i});if(typeof t<"u"&&t<=0)throw new Tc({chainId:t});if(r||s)throw new z("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Sc)throw new Ps({maxFeePerGas:n})}function $c(e){if(!e||e.length===0)return[];const t=[];for(let r=0;r<e.length;r++){const{address:n,storageKeys:s}=e[r];for(let i=0;i<s.length;i++)if(s[i].length-2!==64)throw new pE({storageKey:s[i]});if(!st(n,{strict:!1}))throw new Bt({address:n});t.push([n,s])}return t}function qA(e,t){const r=L0(e);return r==="eip1559"?WA(e,t):r==="eip2930"?KA(e,t):r==="eip4844"?GA(e,t):r==="eip7702"?VA(e,t):XA(e,t)}function VA(e,t){const{authorizationList:r,chainId:n,gas:s,nonce:i,to:o,value:a,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:u,data:f}=e;LA(e);const p=$c(u),d=YA(r);return Tr(["0x04",Qn([X(n),i?X(i):"0x",l?X(l):"0x",c?X(c):"0x",s?X(s):"0x",o??"0x",a?X(a):"0x",f??"0x",p,d,...sa(e,t)])])}function GA(e,t){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:u,data:f}=e;DA(e);let p=e.blobVersionedHashes,d=e.sidecars;if(e.blobs&&(typeof p>"u"||typeof d>"u")){const E=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(P=>Je(P)),S=e.kzg,I=Sd({blobs:E,kzg:S});if(typeof p>"u"&&(p=$0({commitments:I})),typeof d>"u"){const P=_d({blobs:E,commitments:I,kzg:S});d=j0({blobs:E,commitments:I,proofs:P})}}const m=$c(u),g=[X(r),s?X(s):"0x",l?X(l):"0x",c?X(c):"0x",n?X(n):"0x",i??"0x",o?X(o):"0x",f??"0x",m,a?X(a):"0x",p??[],...sa(e,t)],w=[],A=[],T=[];if(d)for(let E=0;E<d.length;E++){const{blob:S,commitment:I,proof:P}=d[E];w.push(S),A.push(I),T.push(P)}return Tr(["0x03",Qn(d?[g,w,A,T]:g)])}function WA(e,t){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:l,data:u}=e;Dd(e);const f=$c(l),p=[X(r),s?X(s):"0x",c?X(c):"0x",a?X(a):"0x",n?X(n):"0x",i??"0x",o?X(o):"0x",u??"0x",f,...sa(e,t)];return Tr(["0x02",Qn(p)])}function KA(e,t){const{chainId:r,gas:n,data:s,nonce:i,to:o,value:a,accessList:c,gasPrice:l}=e;HA(e);const u=$c(c),f=[X(r),i?X(i):"0x",l?X(l):"0x",n?X(n):"0x",o??"0x",a?X(a):"0x",s??"0x",u,...sa(e,t)];return Tr(["0x01",Qn(f)])}function XA(e,t){const{chainId:r=0,gas:n,data:s,nonce:i,to:o,value:a,gasPrice:c}=e;zA(e);let l=[i?X(i):"0x",c?X(c):"0x",n?X(n):"0x",o??"0x",a?X(a):"0x",s??"0x"];if(t){const u=(()=>{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 dE({v:t.v});return d})(),f=cr(t.r),p=cr(t.s);l=[...l,X(u),f==="0x00"?"0x":f,p==="0x00"?"0x":p]}else r>0&&(l=[...l,X(r),"0x","0x"]);return Qn(l)}function sa(e,t){const r=t??e,{v:n,yParity:s}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof s>"u")return[];const i=cr(r.r),o=cr(r.s);return[typeof s=="number"?s?X(1):"0x":n===0n?"0x":n===1n?X(1):n===27n?"0x":X(1),i==="0x00"?"0x":i,o==="0x00"?"0x":o]}function YA(e){if(!e||e.length===0)return[];const t=[];for(const r of e){const{chainId:n,nonce:s,...i}=r,o=r.address;t.push([n?mt(n):"0x",o,s?mt(s):"0x",...sa({},i)])}return t}const ZA=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Bg=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),JA=Bg.map(e=>(9*e+5)%16),Cg=(()=>{const r=[[Bg],[JA]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>ZA[i]));return r})(),Rg=Cg[0],$g=Cg[1],Ng=[[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)),QA=Rg.map((e,t)=>e.map(r=>Ng[t][r])),ex=$g.map((e,t)=>e.map(r=>Ng[t][r])),tx=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),rx=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function mp(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 wa=new Uint32Array(16);let Ug=class extends O0{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:s,h4:i}=this;return[t,r,n,s,i]}set(t,r,n,s,i){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=s|0,this.h4=i|0}process(t,r){for(let d=0;d<16;d++,r+=4)wa[d]=t.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,o=i,a=this.h2|0,c=a,l=this.h3|0,u=l,f=this.h4|0,p=f;for(let d=0;d<5;d++){const m=4-d,g=tx[d],w=rx[d],A=Rg[d],T=$g[d],E=QA[d],S=ex[d];for(let I=0;I<16;I++){const P=pa(n+mp(d,i,a,l)+wa[A[I]]+g,E[I])+f|0;n=f,f=l,l=pa(a,10)|0,a=i,i=P}for(let I=0;I<16;I++){const P=pa(s+mp(m,o,c,u)+wa[T[I]]+w,S[I])+p|0;s=p,p=u,u=pa(c,10)|0,c=o,o=P}}this.set(this.h1+a+u|0,this.h2+l+p|0,this.h3+f+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){_r(wa)}destroy(){this.destroyed=!0,_r(this.buffer),this.set(0,0,0,0,0)}};const nx=mc(()=>new Ug),sx=Ug,ix=nx,ox=Object.freeze(Object.defineProperty({__proto__:null,RIPEMD160:sx,ripemd160:ix},Symbol.toStringTag,{value:"Module"})),ax=`Ethereum Signed Message:
|
|
41
|
+
`),{name:"ChainNotFoundError"})}}class eg extends z{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class Tc extends z{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const hu="/docs/contract/encodeDeployData";function Ic(e){const{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;const s=t.find(o=>"type"in o&&o.type==="constructor");if(!s)throw new Fv({docsPath:hu});if(!("inputs"in s))throw new Nh({docsPath:hu});if(!s.inputs||s.inputs.length===0)throw new Nh({docsPath:hu});const i=kn(s.inputs,r);return Tr([n,i])}function Bi({blockNumber:e,chain:t,contract:r}){var s;const n=(s=t==null?void 0:t.contracts)==null?void 0:s[r];if(!n)throw new vf({chain:t,contract:{name:r}});if(e&&n.blockCreated&&n.blockCreated>e)throw new vf({blockNumber:e,chain:t,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function tg(e,{docsPath:t,...r}){const n=(()=>{const s=Ac(e,r);return s instanceof ea?e:s})();return new A0(n,{docsPath:t,...r})}function Ud(){let e=()=>{},t=()=>{};return{promise:new Promise((n,s)=>{e=n,t=s}),resolve:e,reject:t}}const pu=new Map;function rg({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:s}){const i=async()=>{const u=c();o();const f=u.map(({args:p})=>p);f.length!==0&&e(f).then(p=>{s&&Array.isArray(p)&&p.sort(s);for(let d=0;d<u.length;d++){const{resolve:m}=u[d];m==null||m([p[d],p])}}).catch(p=>{for(let d=0;d<u.length;d++){const{reject:m}=u[d];m==null||m(p)}})},o=()=>pu.delete(t),a=()=>c().map(({args:u})=>u),c=()=>pu.get(t)||[],l=u=>pu.set(t,[...c(),u]);return{flush:o,async schedule(u){const{promise:f,resolve:p,reject:d}=Ud();return(r==null?void 0:r([...a(),u]))&&i(),c().length>0?(l({args:u,resolve:p,reject:d}),f):(l({args:u,resolve:p,reject:d}),setTimeout(i,n),f)}}}async function ra(e,t){var H,W,Z,Q;const{account:r=e.account,authorizationList:n,batch:s=!!((H=e.batch)!=null&&H.multicall),blockNumber:i,blockTag:o=e.experimental_blockTag??"latest",accessList:a,blobs:c,blockOverrides:l,code:u,data:f,factory:p,factoryData:d,gas:m,gasPrice:g,maxFeePerBlobGas:w,maxFeePerGas:A,maxPriorityFeePerGas:T,nonce:E,to:S,value:I,stateOverride:P,...$}=t,j=r?Xe(r):void 0;if(u&&(p||d))throw new z("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(u&&S)throw new z("Cannot provide both `code` & `to` as parameters.");const k=u&&f,F=p&&d&&S&&f,R=k||F,U=k?$6({code:u,data:f}):F?N6({data:f,factory:p,factoryData:d,to:S}):f;try{js(t);const D=(typeof i=="bigint"?X(i):void 0)||o,B=l?Y0(l):void 0,V=wd(P),K=(Q=(Z=(W=e.chain)==null?void 0:W.formatters)==null?void 0:Z.transactionRequest)==null?void 0:Q.format,N=(K||Pi)({...xc($,{format:K}),from:j==null?void 0:j.address,accessList:a,authorizationList:n,blobs:c,data:U,gas:m,gasPrice:g,maxFeePerBlobGas:w,maxFeePerGas:A,maxPriorityFeePerGas:T,nonce:E,to:R?void 0:S,value:I});if(s&&C6({request:N})&&!V&&!B)try{return await R6(e,{...N,blockNumber:i,blockTag:o})}catch(ne){if(!(ne instanceof eg)&&!(ne instanceof vf))throw ne}const L=(()=>{const ne=[N,D];return V&&B?[...ne,V,B]:V?[...ne,V]:B?[...ne,{},B]:ne})(),J=await e.request({method:"eth_call",params:L});return J==="0x"?{data:void 0}:{data:J}}catch(re){const D=U6(re),{offchainLookup:B,offchainLookupSignature:V}=await Promise.resolve().then(()=>require("./ccip-DSGVoxhU.cjs"));if(e.ccipRead!==!1&&(D==null?void 0:D.slice(0,10))===V&&S)return{data:await B(e,{data:D,to:S})};throw R&&(D==null?void 0:D.slice(0,10))==="0x101bb98d"?new vE({factory:p}):tg(re,{...t,account:j,chain:e.chain})}}function C6({request:e}){const{data:t,to:r,...n}=e;return!(!t||t.startsWith(T6)||!r||Object.values(n).filter(s=>typeof s<"u").length>0)}async function R6(e,t){var g;const{batchSize:r=1024,wait:n=0}=typeof((g=e.batch)==null?void 0:g.multicall)=="object"?e.batch.multicall:{},{blockNumber:s,blockTag:i=e.experimental_blockTag??"latest",data:o,multicallAddress:a,to:c}=t;let l=a;if(!l){if(!e.chain)throw new eg;l=Bi({blockNumber:s,chain:e.chain,contract:"multicall3"})}const f=(typeof s=="bigint"?X(s):void 0)||i,{schedule:p}=rg({id:`${e.uid}.${f}`,wait:n,shouldSplitBatch(w){return w.reduce((T,{data:E})=>T+(E.length-2),0)>r*2},fn:async w=>{const A=w.map(S=>({allowFailure:!0,callData:S.data,target:S.to})),T=dr({abi:bf,args:[A],functionName:"aggregate3"}),E=await e.request({method:"eth_call",params:[{data:T,to:l},f]});return Ls({abi:bf,args:[A],functionName:"aggregate3",data:E||"0x"})}}),[{returnData:d,success:m}]=await p({data:o,to:c});if(!m)throw new Ec({data:d});return d==="0x"?{data:void 0}:{data:d}}function $6(e){const{code:t,data:r}=e;return Ic({abi:Nm(["constructor(bytes, bytes)"]),bytecode:Q0,args:[t,r]})}function N6(e){const{data:t,factory:r,factoryData:n,to:s}=e;return Ic({abi:Nm(["constructor(address, bytes, address, bytes)"]),bytecode:I6,args:[s,t,r,n]})}function U6(e){var r;if(!(e instanceof z))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 Wr(e,t){const{abi:r,address:n,args:s,functionName:i,...o}=t,a=dr({abi:r,args:s,functionName:i});try{const{data:c}=await se(e,ra,"call")({...o,data:a,to:n});return Ls({abi:r,args:s,functionName:i,data:c||"0x"})}catch(c){throw Is(c,{abi:r,address:n,args:s,docsPath:"/docs/contract/readContract",functionName:i})}}async function ng(e,t){const{abi:r,address:n,args:s,dataSuffix:i,functionName:o,...a}=t,c=a.account?Xe(a.account):e.account,l=dr({abi:r,args:s,functionName:o});try{const{data:u}=await se(e,ra,"call")({batch:!1,data:`${l}${i?i.replace("0x",""):""}`,to:n,...a,account:c}),f=Ls({abi:r,args:s,functionName:o,data:u||"0x"}),p=r.filter(d=>"name"in d&&d.name===t.functionName);return{result:f,request:{abi:p,address:n,args:s,dataSuffix:i,functionName:o,...a,account:c}}}catch(u){throw Is(u,{abi:r,address:n,args:s,docsPath:"/docs/contract/simulateContract",functionName:o,sender:c==null?void 0:c.address})}}const yu=new Map,lp=new Map;let M6=0;function vn(e,t,r){const n=++M6,s=()=>yu.get(e)||[],i=()=>{const u=s();yu.set(e,u.filter(f=>f.id!==n))},o=()=>{const u=s();if(!u.some(p=>p.id===n))return;const f=lp.get(e);if(u.length===1&&f){const p=f();p instanceof Promise&&p.catch(()=>{})}i()},a=s();if(yu.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return o;const c={};for(const u in t)c[u]=(...f)=>{var d,m;const p=s();if(p.length!==0)for(const g of p)(m=(d=g.fns)[u])==null||m.call(d,...f)};const l=r(c);return typeof l=="function"&&lp.set(e,l),o}async function Ef(e){return new Promise(t=>setTimeout(t,e))}function Ci(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let s=!0;const i=()=>s=!1;return(async()=>{let a;t&&(a=await e({unpoll:i}));const c=await(r==null?void 0:r(a))??n;await Ef(c);const l=async()=>{s&&(await e({unpoll:i}),await Ef(n),l())};l()})(),i}const F6=new Map,j6=new Map;function L6(e){const t=(s,i)=>({clear:()=>i.delete(s),get:()=>i.get(s),set:o=>i.set(s,o)}),r=t(e,F6),n=t(e,j6);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function D6(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){const n=L6(t),s=n.response.get();if(s&&r>0&&new Date().getTime()-s.created.getTime()<r)return s.data;let i=n.promise.get();i||(i=e(),n.promise.set(i));try{const o=await i;return n.response.set({created:new Date,data:o}),o}finally{n.promise.clear()}}const H6=e=>`blockNumber.${e}`;async function na(e,{cacheTime:t=e.cacheTime}={}){const r=await D6(()=>e.request({method:"eth_blockNumber"}),{cacheKey:H6(e.uid),cacheTime:t});return BigInt(r)}async function Pc(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 s=n.map(i=>wn(i));return!("abi"in t)||!t.abi?s:Od({abi:t.abi,logs:s,strict:r})}async function Oc(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}function sg(e,t){const{abi:r,address:n,args:s,batch:i=!0,eventName:o,fromBlock:a,onError:c,onLogs:l,poll:u,pollingInterval:f=e.pollingInterval,strict:p}=t;return(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")))?(()=>{const w=p??!1,A=Ze(["watchContractEvent",n,s,i,e.uid,o,f,w,a]);return vn(A,{onLogs:l,onError:c},T=>{let E;a!==void 0&&(E=a-1n);let S,I=!1;const P=Ci(async()=>{var $;if(!I){try{S=await se(e,pd,"createContractEventFilter")({abi:r,address:n,args:s,eventName:o,strict:w,fromBlock:a})}catch{}I=!0;return}try{let j;if(S)j=await se(e,Pc,"getFilterChanges")({filter:S});else{const k=await se(e,na,"getBlockNumber")({});E&&E<k?j=await se(e,Cd,"getContractEvents")({abi:r,address:n,args:s,eventName:o,fromBlock:E+1n,toBlock:k,strict:w}):j=[],E=k}if(j.length===0)return;if(i)T.onLogs(j);else for(const k of j)T.onLogs([k])}catch(j){S&&j instanceof Ts&&(I=!1),($=T.onError)==null||$.call(T,j)}},{emitOnBegin:!0,interval:f});return async()=>{S&&await se(e,Oc,"uninstallFilter")({filter:S}),P()}})})():(()=>{const w=p??!1,A=Ze(["watchContractEvent",n,s,i,e.uid,o,f,w]);let T=!0,E=()=>T=!1;return vn(A,{onLogs:l,onError:c},S=>((async()=>{try{const I=(()=>{if(e.transport.type==="fallback"){const j=e.transport.transports.find(k=>k.config.type==="webSocket"||k.config.type==="ipc");return j?j.value:e.transport}return e.transport})(),P=o?Zo({abi:r,eventName:o,args:s}):[],{unsubscribe:$}=await I.subscribe({params:["logs",{address:n,topics:P}],onData(j){var F;if(!T)return;const k=j.result;try{const{eventName:R,args:U}=Pd({abi:r,data:k.data,topics:k.topics,strict:p}),H=wn(k,{args:U,eventName:R});S.onLogs([H])}catch(R){let U,H;if(R instanceof po||R instanceof pc){if(p)return;U=R.abiItem.name,H=(F=R.abiItem.inputs)==null?void 0:F.some(Z=>!("name"in Z&&Z.name))}const W=wn(k,{args:H?[]:{},eventName:U});S.onLogs([W])}},onError(j){var k;(k=S.onError)==null||k.call(S,j)}});E=$,T||E()}catch(I){c==null||c(I)}})(),()=>E()))})()}class Ds extends z{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(`
|
|
42
|
+
`),{docsPath:t,docsSlug:"account",name:"AccountNotFoundError"})}}class Ma extends z{constructor({docsPath:t,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:t,metaMessages:r,name:"AccountTypeNotSupportedError"})}}function ig({chain:e,currentChainId:t}){if(!e)throw new B6;if(t!==e.id)throw new O6({chain:e,currentChainId:t})}function og(e,{docsPath:t,...r}){const n=(()=>{const s=Ac(e,r);return s instanceof ea?e:s})();return new yE(n,{docsPath:t,...r})}async function Md(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}const mu=new bc(128);async function Bc(e,t){var T,E,S,I;const{account:r=e.account,chain:n=e.chain,accessList:s,authorizationList:i,blobs:o,data:a,gas:c,gasPrice:l,maxFeePerBlobGas:u,maxFeePerGas:f,maxPriorityFeePerGas:p,nonce:d,type:m,value:g,...w}=t;if(typeof r>"u")throw new Ds({docsPath:"/docs/actions/wallet/sendTransaction"});const A=r?Xe(r):null;try{js(t);const P=await(async()=>{if(t.to)return t.to;if(t.to!==null&&i&&i.length>0)return await k0({authorization:i[0]}).catch(()=>{throw new z("`to` is required. Could not infer from `authorizationList`.")})})();if((A==null?void 0:A.type)==="json-rpc"||A===null){let $;n!==null&&($=await se(e,Oi,"getChainId")({}),ig({currentChainId:$,chain:n}));const j=(S=(E=(T=e.chain)==null?void 0:T.formatters)==null?void 0:E.transactionRequest)==null?void 0:S.format,F=(j||Pi)({...xc(w,{format:j}),accessList:s,authorizationList:i,blobs:o,chainId:$,data:a,from:A==null?void 0:A.address,gas:c,gasPrice:l,maxFeePerBlobGas:u,maxFeePerGas:f,maxPriorityFeePerGas:p,nonce:d,to:P,type:m,value:g}),R=mu.get(e.uid),U=R?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:U,params:[F]},{retryCount:0})}catch(H){if(R===!1)throw H;const W=H;if(W.name==="InvalidInputRpcError"||W.name==="InvalidParamsRpcError"||W.name==="MethodNotFoundRpcError"||W.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[F]},{retryCount:0}).then(Z=>(mu.set(e.uid,!0),Z)).catch(Z=>{const Q=Z;throw Q.name==="MethodNotFoundRpcError"||Q.name==="MethodNotSupportedRpcError"?(mu.set(e.uid,!1),W):Q});throw W}}if((A==null?void 0:A.type)==="local"){const $=await se(e,kc,"prepareTransactionRequest")({account:A,accessList:s,authorizationList:i,blobs:o,chain:n,data:a,gas:c,gasPrice:l,maxFeePerBlobGas:u,maxFeePerGas:f,maxPriorityFeePerGas:p,nonce:d,nonceManager:A.nonceManager,parameters:[...D0,"sidecars"],type:m,value:g,...w,to:P}),j=(I=n==null?void 0:n.serializers)==null?void 0:I.transaction,k=await A.signTransaction($,{serializer:j});return await se(e,Md,"sendRawTransaction")({serializedTransaction:k})}throw(A==null?void 0:A.type)==="smart"?new Ma({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new Ma({docsPath:"/docs/actions/wallet/sendTransaction",type:A==null?void 0:A.type})}catch(P){throw P instanceof Ma?P:og(P,{...t,account:A,chain:t.chain||void 0})}}async function ag(e,t){const{abi:r,account:n=e.account,address:s,args:i,dataSuffix:o,functionName:a,...c}=t;if(typeof n>"u")throw new Ds({docsPath:"/docs/contract/writeContract"});const l=n?Xe(n):null,u=dr({abi:r,args:i,functionName:a});try{return await se(e,Bc,"sendTransaction")({data:`${u}${o?o.replace("0x",""):""}`,to:s,account:l,...c})}catch(f){throw Is(f,{abi:r,address:s,args:i,docsPath:"/docs/contract/writeContract",functionName:a,sender:l==null?void 0:l.address})}}function gu({abi:e,address:t,client:r}){const n=r,[s,i]=n?"public"in n&&"wallet"in n?[n.public,n.wallet]:"public"in n?[n.public,void 0]:"wallet"in n?[void 0,n.wallet]:[n,n]:[void 0,void 0],o=s!=null,a=i!=null,c={};let l=!1,u=!1,f=!1;for(const p of e)if(p.type==="function"?p.stateMutability==="view"||p.stateMutability==="pure"?l=!0:u=!0:p.type==="event"&&(f=!0),l&&u&&f)break;return o&&(l&&(c.read=new Proxy({},{get(p,d){return(...m)=>{const{args:g,options:w}=ya(m);return se(s,Wr,"readContract")({abi:e,address:t,functionName:d,args:g,...w})}}})),u&&(c.simulate=new Proxy({},{get(p,d){return(...m)=>{const{args:g,options:w}=ya(m);return se(s,ng,"simulateContract")({abi:e,address:t,functionName:d,args:g,...w})}}})),f&&(c.createEventFilter=new Proxy({},{get(p,d){return(...m)=>{const g=e.find(T=>T.type==="event"&&T.name===d),{args:w,options:A}=bu(m,g);return se(s,pd,"createContractEventFilter")({abi:e,address:t,eventName:d,args:w,...A})}}}),c.getEvents=new Proxy({},{get(p,d){return(...m)=>{const g=e.find(T=>T.type==="event"&&T.name===d),{args:w,options:A}=bu(m,g);return se(s,Cd,"getContractEvents")({abi:e,address:t,eventName:d,args:w,...A})}}}),c.watchEvent=new Proxy({},{get(p,d){return(...m)=>{const g=e.find(T=>T.type==="event"&&T.name===d),{args:w,options:A}=bu(m,g);return se(s,sg,"watchContractEvent")({abi:e,address:t,eventName:d,args:w,...A})}}}))),a&&u&&(c.write=new Proxy({},{get(p,d){return(...m)=>{const{args:g,options:w}=ya(m);return se(i,ag,"writeContract")({abi:e,address:t,functionName:d,args:g,...w})}}})),(o||a)&&u&&(c.estimateGas=new Proxy({},{get(p,d){return(...m)=>{const{args:g,options:w}=ya(m);return se(s??i,z0,"estimateContractGas")({abi:e,address:t,functionName:d,args:g,...w,account:w.account??i.account})}}})),c.address=t,c.abi=e,c}function ya(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 bu(e,t){let r=!1;Array.isArray(e[0])?r=!0:e.length===1?r=t.inputs.some(i=>i.indexed):e.length===2&&(r=!0);const n=r?e[0]:void 0,s=(r?e[1]:e[0])??{};return{args:n,options:s}}class z6 extends z{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 ec(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0}={}){return new Promise((s,i)=>{const o=async({count:a=0}={})=>{const c=async({error:l})=>{const u=typeof t=="function"?t({count:a,error:l}):t;u&&await Ef(u),o({count:a+1})};try{const l=await e();s(l)}catch(l){if(a<r&&await n({count:a,error:l}))return c({error:l});i(l)}};o()})}const cg={"0x0":"reverted","0x1":"success"};function ug(e){const t={...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(r=>wn(r)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?ur(e.transactionIndex):null,status:e.status?cg[e.status]:null,type:e.type?I0[e.type]||e.type:null};return e.blobGasPrice&&(t.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(t.blobGasUsed=BigInt(e.blobGasUsed)),t}const q6=bd("transactionReceipt",ug),lg="0x5792579257925792579257925792579257925792579257925792579257925792",fg=X(0,{size:32});async function V6(e,t){const{account:r=e.account,capabilities:n,chain:s=e.chain,experimental_fallback:i,experimental_fallbackDelay:o=32,forceAtomic:a=!1,id:c,version:l="2.0.0"}=t,u=r?Xe(r):null,f=t.calls.map(p=>{const d=p,m=d.abi?dr({abi:d.abi,functionName:d.functionName,args:d.args}):d.data;return{data:d.dataSuffix&&m?Vt([m,d.dataSuffix]):m,to:d.to,value:d.value?X(d.value):void 0}});try{const p=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:a,calls:f,capabilities:n,chainId:X(s.id),from:u==null?void 0:u.address,id:c,version:l}]},{retryCount:0});return typeof p=="string"?{id:p}:p}catch(p){const d=p;if(i&&(d.name==="MethodNotFoundRpcError"||d.name==="MethodNotSupportedRpcError"||d.name==="UnknownRpcError"||d.details.toLowerCase().includes("does not exist / is not available")||d.details.toLowerCase().includes("missing or invalid. request()")||d.details.toLowerCase().includes("did not match any variant of untagged enum")||d.details.toLowerCase().includes("account upgraded to unsupported contract")||d.details.toLowerCase().includes("eip-7702 not supported")||d.details.toLowerCase().includes("unsupported wc_ method"))){if(n&&Object.values(n).some(T=>!T.optional)){const T="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new bi(new z(T,{details:T}))}if(a&&f.length>1){const A="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new wi(new z(A,{details:A}))}const m=[];for(const A of f){const T=Bc(e,{account:u,chain:s,data:A.data,to:A.to,value:A.value?ot(A.value):void 0});m.push(T),o>0&&await new Promise(E=>setTimeout(E,o))}const g=await Promise.allSettled(m);if(g.every(A=>A.status==="rejected"))throw g[0].reason;const w=g.map(A=>A.status==="fulfilled"?A.value:fg);return{id:Vt([...w,X(s.id,{size:32}),lg])}}throw og(p,{...t,account:u,chain:t.chain})}}async function dg(e,t){async function r(u){if(u.endsWith(lg.slice(2))){const p=cr(Qa(u,-64,-32)),d=Qa(u,0,-64).slice(2).match(/.{1,64}/g),m=await Promise.all(d.map(w=>fg.slice(2)!==w?e.request({method:"eth_getTransactionReceipt",params:[`0x${w}`]},{dedupe:!0}):void 0)),g=m.some(w=>w===null)?100:m.every(w=>(w==null?void 0:w.status)==="0x1")?200:m.every(w=>(w==null?void 0:w.status)==="0x0")?500:600;return{atomic:!1,chainId:ur(p),receipts:m.filter(Boolean),status:g,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[u]})}const{atomic:n=!1,chainId:s,receipts:i,version:o="2.0.0",...a}=await r(t.id),[c,l]=(()=>{const u=a.status;return u>=100&&u<200?["pending",u]:u>=200&&u<300?["success",u]:u>=300&&u<700?["failure",u]:u==="CONFIRMED"?["success",200]:u==="PENDING"?["pending",100]:[void 0,u]})();return{...a,atomic:n,chainId:s?ur(s):void 0,receipts:(i==null?void 0:i.map(u=>({...u,blockNumber:ot(u.blockNumber),gasUsed:ot(u.gasUsed),status:cg[u.status]})))??[],statusCode:l,status:c,version:o}}async function G6(e,t){const{id:r,pollingInterval:n=e.pollingInterval,status:s=({statusCode:g})=>g===200||g>=300,retryCount:i=4,retryDelay:o=({count:g})=>~~(1<<g)*200,timeout:a=6e4,throwOnFailure:c=!1}=t,l=Ze(["waitForCallsStatus",e.uid,r]),{promise:u,resolve:f,reject:p}=Ud();let d;const m=vn(l,{resolve:f,reject:p},g=>{const w=Ci(async()=>{const A=T=>{clearTimeout(d),w(),T(),m()};try{const T=await ec(async()=>{const E=await dg(e,{id:r});if(c&&E.status==="failure")throw new z6(E);return E},{retryCount:i,delay:o});if(!s(T))return;A(()=>g.resolve(T))}catch(T){A(()=>g.reject(T))}},{interval:n,emitOnBegin:!0});return w});return d=a?setTimeout(()=>{m(),clearTimeout(d),p(new W6({id:r}))},a):void 0,await u}class W6 extends z{constructor({id:t}){super(`Timed out while waiting for call bundle with id "${t}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}const Af=256;let ma=Af,ga;function hg(e=11){if(!ga||ma+e>Af*2){ga="",ma=0;for(let t=0;t<Af;t++)ga+=(256+Math.random()*256|0).toString(16).substring(1)}return ga.substring(ma,ma+++e)}function pg(e){const{batch:t,chain:r,ccipRead:n,key:s="base",name:i="Base Client",type:o="base"}=e,a=e.experimental_blockTag??(typeof(r==null?void 0:r.experimental_preconfirmationTime)=="number"?"pending":void 0),c=(r==null?void 0:r.blockTime)??12e3,l=Math.min(Math.max(Math.floor(c/2),500),4e3),u=e.pollingInterval??l,f=e.cacheTime??u,p=e.account?Xe(e.account):void 0,{config:d,request:m,value:g}=e.transport({chain:r,pollingInterval:u}),w={...d,...g},A={account:p,batch:t,cacheTime:f,ccipRead:n,chain:r,key:s,name:i,pollingInterval:u,request:m,transport:w,type:o,uid:hg(),...a?{experimental_blockTag:a}:{}};function T(E){return S=>{const I=S(E);for(const $ in A)delete I[$];const P={...E,...I};return Object.assign(P,{extend:T(P)})}}return Object.assign(A,{extend:T(A)})}const ba=new bc(8192);function K6(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(ba.get(r))return ba.get(r);const n=e().finally(()=>ba.delete(r));return ba.set(r,n),n}function X6(e,t={}){return async(r,n={})=>{var f;const{dedupe:s=!1,methods:i,retryDelay:o=150,retryCount:a=3,uid:c}={...t,...n},{method:l}=r;if((f=i==null?void 0:i.exclude)!=null&&f.includes(l))throw new ls(new Error("method not supported"),{method:l});if(i!=null&&i.include&&!i.include.includes(l))throw new ls(new Error("method not supported"),{method:l});const u=s?mi(`${c}.${Ze(r)}`):void 0;return K6(()=>ec(async()=>{try{return await e(r)}catch(p){const d=p;switch(d.code){case bo.code:throw new bo(d);case wo.code:throw new wo(d);case vo.code:throw new vo(d,{method:r.method});case Eo.code:throw new Eo(d);case ks.code:throw new ks(d);case Ts.code:throw new Ts(d);case Ao.code:throw new Ao(d);case xo.code:throw new xo(d);case So.code:throw new So(d);case ls.code:throw new ls(d,{method:r.method});case gi.code:throw new gi(d);case _o.code:throw new _o(d);case ui.code:throw new ui(d);case ko.code:throw new ko(d);case To.code:throw new To(d);case Io.code:throw new Io(d);case Po.code:throw new Po(d);case Oo.code:throw new Oo(d);case bi.code:throw new bi(d);case Bo.code:throw new Bo(d);case Co.code:throw new Co(d);case Ro.code:throw new Ro(d);case $o.code:throw new $o(d);case No.code:throw new No(d);case wi.code:throw new wi(d);case 5e3:throw new ui(d);default:throw p instanceof z?p:new AE(d)}}},{delay:({count:p,error:d})=>{var m;if(d&&d instanceof ci){const g=(m=d==null?void 0:d.headers)==null?void 0:m.get("Retry-After");if(g!=null&&g.match(/\d/))return Number.parseInt(g)*1e3}return~~(1<<p)*o},retryCount:a,shouldRetry:({error:p})=>Y6(p)}),{enabled:s,id:u})}}function Y6(e){return"code"in e&&typeof e.code=="number"?e.code===-1||e.code===gi.code||e.code===ks.code:e instanceof ci&&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 yg({key:e,methods:t,name:r,request:n,retryCount:s=3,retryDelay:i=150,timeout:o,type:a},c){const l=hg();return{config:{key:e,methods:t,name:r,request:n,retryCount:s,retryDelay:i,timeout:o,type:a},request:X6(n,{methods:t,retryCount:s,retryDelay:i,uid:l}),value:c}}function fp(e,t={}){const{key:r="custom",methods:n,name:s="Custom Provider",retryDelay:i}=t;return({retryCount:o})=>yg({key:r,methods:n,name:s,request:e.request.bind(e),retryCount:t.retryCount??o,retryDelay:i,type:"custom"})}class Z6 extends z{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 J6(e,{errorInstance:t=new Error("timed out"),timeout:r,signal:n}){return new Promise((s,i)=>{(async()=>{let o;try{const a=new AbortController;r>0&&(o=setTimeout(()=>{n&&a.abort()},r)),s(await e({signal:(a==null?void 0:a.signal)||null}))}catch(a){(a==null?void 0:a.name)==="AbortError"&&i(t),i(a)}finally{clearTimeout(o)}})()})}function Q6(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const dp=Q6();function eA(e,t={}){return{async request(r){var f;const{body:n,onRequest:s=t.onRequest,onResponse:i=t.onResponse,timeout:o=t.timeout??1e4}=r,a={...t.fetchOptions??{},...r.fetchOptions??{}},{headers:c,method:l,signal:u}=a;try{const p=await J6(async({signal:m})=>{const g={...a,body:Array.isArray(n)?Ze(n.map(E=>({jsonrpc:"2.0",id:E.id??dp.take(),...E}))):Ze({jsonrpc:"2.0",id:n.id??dp.take(),...n}),headers:{"Content-Type":"application/json",...c},method:l||"POST",signal:u||(o>0?m:null)},w=new Request(e,g),A=await(s==null?void 0:s(w,g))??{...g,url:e};return await fetch(A.url??e,A)},{errorInstance:new Yh({body:n,url:e}),timeout:o,signal:!0});i&&await i(p);let d;if((f=p.headers.get("Content-Type"))!=null&&f.startsWith("application/json"))d=await p.json();else{d=await p.text();try{d=JSON.parse(d||"{}")}catch(m){if(p.ok)throw m;d={error:d}}}if(!p.ok)throw new ci({body:n,details:Ze(d.error)||p.statusText,headers:p.headers,status:p.status,url:e});return d}catch(p){throw p instanceof ci||p instanceof Yh?p:new ci({body:n,cause:p,url:e})}}}}function mg(e,t={}){const{batch:r,fetchOptions:n,key:s="http",methods:i,name:o="HTTP JSON-RPC",onFetchRequest:a,onFetchResponse:c,retryDelay:l,raw:u}=t;return({chain:f,retryCount:p,timeout:d})=>{const{batchSize:m=1e3,wait:g=0}=typeof r=="object"?r:{},w=t.retryCount??p,A=d??t.timeout??1e4,T=f==null?void 0:f.rpcUrls.default.http[0];if(!T)throw new Z6;const E=eA(T,{fetchOptions:n,onRequest:a,onResponse:c,timeout:A});return yg({key:s,methods:i,name:o,async request({method:S,params:I}){const P={method:S,params:I},{schedule:$}=rg({id:T,wait:g,shouldSplitBatch(R){return R.length>m},fn:R=>E.request({body:R}),sort:(R,U)=>R.id-U.id}),j=async R=>r?$(R):[await E.request({body:R})],[{error:k,result:F}]=await j(P);if(u)return{error:k,result:F};if(k)throw new gd({body:P,error:k,url:T});return F},retryCount:w,retryDelay:l,timeout:A,type:"http"},{fetchOptions:n,url:T})}}function Fd(e,t){var n,s,i,o,a,c;if(!(e instanceof z))return!1;const r=e.walk(l=>l instanceof cf);return r instanceof cf?!!(((n=r.data)==null?void 0:n.errorName)==="ResolverNotFound"||((s=r.data)==null?void 0:s.errorName)==="ResolverWildcardNotSupported"||((i=r.data)==null?void 0:i.errorName)==="ResolverNotContract"||((o=r.data)==null?void 0:o.errorName)==="ResolverError"||((a=r.data)==null?void 0:a.errorName)==="HttpError"||(c=r.reason)!=null&&c.includes("Wildcard on non-extended resolvers is not supported")||t==="reverse"&&r.reason===p0[50]):!1}function tA(e){const{abi:t,data:r}=e,n=_s(r,0,4),s=t.find(i=>i.type==="function"&&n===Yo(Ar(i)));if(!s)throw new qv(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:s.name,args:"inputs"in s&&s.inputs&&s.inputs.length>0?Jo(s.inputs,_s(r,4)):void 0}}const wu="/docs/contract/encodeErrorResult";function hp(e){const{abi:t,errorName:r,args:n}=e;let s=t[0];if(r){const c=Fs({abi:t,args:n,name:r});if(!c)throw new Uh(r,{docsPath:wu});s=c}if(s.type!=="error")throw new Uh(void 0,{docsPath:wu});const i=Ar(s),o=Yo(i);let a="0x";if(n&&n.length>0){if(!s.inputs)throw new Hv(s.name,{docsPath:wu});a=kn(s.inputs,n)}return Tr([o,a])}const vu="/docs/contract/encodeFunctionResult";function rA(e){const{abi:t,functionName:r,result:n}=e;let s=t[0];if(r){const o=Fs({abi:t,name:r});if(!o)throw new yi(r,{docsPath:vu});s=o}if(s.type!=="function")throw new yi(void 0,{docsPath:vu});if(!s.outputs)throw new Dm(s.name,{docsPath:vu});const i=(()=>{if(s.outputs.length===0)return[];if(s.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new Hm(n)})();return kn(s.outputs,i)}const Cc="x-batch-gateway:true";async function gg(e){const{data:t,ccipRequest:r}=e,{args:[n]}=tA({abi:wf,data:t}),s=[],i=[];return await Promise.all(n.map(async(o,a)=>{try{i[a]=o.urls.includes(Cc)?await gg({data:o.data,ccipRequest:r}):await r(o),s[a]=!1}catch(c){s[a]=!0,i[a]=nA(c)}})),rA({abi:wf,functionName:"query",result:[s,i]})}function nA(e){return e.name==="HttpRequestError"&&e.status?hp({abi:wf,errorName:"HttpError",args:[e.status,e.shortMessage]}):hp({abi:[y0],errorName:"Error",args:["shortMessage"in e?e.shortMessage:e.message]})}function bg(e){if(e.length!==66||e.indexOf("[")!==0||e.indexOf("]")!==65)return null;const t=`0x${e.slice(1,65)}`;return xr(t)?t:null}function Fa(e){let t=new Uint8Array(32).fill(0);if(!e)return Je(t);const r=e.split(".");for(let n=r.length-1;n>=0;n-=1){const s=bg(r[n]),i=s?Ii(s):lt(bs(r[n]),"bytes");t=lt(Vt([t,i]),"bytes")}return Je(t)}function sA(e){return`[${e.slice(2)}]`}function iA(e){const t=new Uint8Array(32).fill(0);return e?bg(e)||lt(bs(e)):Je(t)}function Rc(e){const t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);const r=new Uint8Array(bs(t).byteLength+2);let n=0;const s=t.split(".");for(let i=0;i<s.length;i++){let o=bs(s[i]);o.byteLength>255&&(o=bs(sA(iA(s[i])))),r[n]=o.length,r.set(o,n+1),n+=o.length+1}return r.byteLength!==n+1?r.slice(0,n+1):r}async function oA(e,t){const{blockNumber:r,blockTag:n,coinType:s,name:i,gatewayUrls:o,strict:a}=t,{chain:c}=e,l=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Bi({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),u=c==null?void 0:c.ensTlds;if(u&&!u.some(f=>i.endsWith(f)))return null;try{const f=dr({abi:cp,functionName:"addr",...s!=null?{args:[Fa(i),BigInt(s)]}:{args:[Fa(i)]}}),p={address:l,abi:J0,functionName:"resolve",args:[gt(Rc(i)),f,o??[Cc]],blockNumber:r,blockTag:n},m=await se(e,Wr,"readContract")(p);if(m[0]==="0x")return null;const g=Ls({abi:cp,args:s!=null?[Fa(i),BigInt(s)]:void 0,functionName:"addr",data:m[0]});return g==="0x"||cr(g)==="0x00"?null:g}catch(f){if(a)throw f;if(Fd(f,"resolve"))return null;throw f}}class aA extends z{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 Fi extends z{constructor({reason:t}){super(`ENS NFT avatar URI is invalid. ${t}`,{name:"EnsAvatarInvalidNftUriError"})}}class jd extends z{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 cA extends z{constructor({namespace:t}){super(`ENS NFT avatar namespace "${t}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const uA=/(?<protocol>https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,lA=/^(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>\/.*)?$/,fA=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,dA=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function hA(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"||!globalThis.hasOwnProperty("Image")?!1:new Promise(r=>{const n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=e})}}function pp(e,t){return e?e.endsWith("/")?e.slice(0,-1):e:t}function wg({uri:e,gatewayUrls:t}){const r=fA.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};const n=pp(t==null?void 0:t.ipfs,"https://ipfs.io"),s=pp(t==null?void 0:t.arweave,"https://arweave.net"),i=e.match(uA),{protocol:o,subpath:a,target:c,subtarget:l=""}=(i==null?void 0:i.groups)||{},u=o==="ipns:/"||a==="ipns/",f=o==="ipfs:/"||a==="ipfs/"||lA.test(e);if(e.startsWith("http")&&!u&&!f){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((u||f)&&c)return{uri:`${n}/${u?"ipns":"ipfs"}/${c}${l}`,isOnChain:!1,isEncoded:!1};if(o==="ar:/"&&c)return{uri:`${s}/${c}${l||""}`,isOnChain:!1,isEncoded:!1};let p=e.replace(dA,"");if(p.startsWith("<svg")&&(p=`data:image/svg+xml;base64,${btoa(p)}`),p.startsWith("data:")||p.startsWith("{"))return{uri:p,isOnChain:!0,isEncoded:!1};throw new jd({uri:e})}function vg(e){if(typeof e!="object"||!("image"in e)&&!("image_url"in e)&&!("image_data"in e))throw new aA({data:e});return e.image||e.image_url||e.image_data}async function pA({gatewayUrls:e,uri:t}){try{const r=await fetch(t).then(s=>s.json());return await Ld({gatewayUrls:e,uri:vg(r)})}catch{throw new jd({uri:t})}}async function Ld({gatewayUrls:e,uri:t}){const{uri:r,isOnChain:n}=wg({uri:t,gatewayUrls:e});if(n||await hA(r))return r;throw new jd({uri:t})}function yA(e){let t=e;t.startsWith("did:nft:")&&(t=t.replace("did:nft:","").replace(/_/g,"/"));const[r,n,s]=t.split("/"),[i,o]=r.split(":"),[a,c]=n.split(":");if(!i||i.toLowerCase()!=="eip155")throw new Fi({reason:"Only EIP-155 supported"});if(!o)throw new Fi({reason:"Chain ID not found"});if(!c)throw new Fi({reason:"Contract address not found"});if(!s)throw new Fi({reason:"Token ID not found"});if(!a)throw new Fi({reason:"ERC namespace not found"});return{chainID:Number.parseInt(o),namespace:a.toLowerCase(),contractAddress:c,tokenID:s}}async function mA(e,{nft:t}){if(t.namespace==="erc721")return Wr(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 Wr(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 cA({namespace:t.namespace})}async function gA(e,{gatewayUrls:t,record:r}){return/eip155:/i.test(r)?bA(e,{gatewayUrls:t,record:r}):Ld({uri:r,gatewayUrls:t})}async function bA(e,{gatewayUrls:t,record:r}){const n=yA(r),s=await mA(e,{nft:n}),{uri:i,isOnChain:o,isEncoded:a}=wg({uri:s,gatewayUrls:t});if(o&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){const l=a?atob(i.replace("data:application/json;base64,","")):i,u=JSON.parse(l);return Ld({uri:vg(u),gatewayUrls:t})}let c=n.tokenID;return n.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),pA({gatewayUrls:t,uri:i.replace(/(?:0x)?{id}/,c)})}async function Eg(e,t){const{blockNumber:r,blockTag:n,key:s,name:i,gatewayUrls:o,strict:a}=t,{chain:c}=e,l=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Bi({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),u=c==null?void 0:c.ensTlds;if(u&&!u.some(f=>i.endsWith(f)))return null;try{const f={address:l,abi:J0,functionName:"resolve",args:[gt(Rc(i)),dr({abi:ap,functionName:"text",args:[Fa(i),s]}),o??[Cc]],blockNumber:r,blockTag:n},d=await se(e,Wr,"readContract")(f);if(d[0]==="0x")return null;const m=Ls({abi:ap,functionName:"text",data:d[0]});return m===""?null:m}catch(f){if(a)throw f;if(Fd(f,"resolve"))return null;throw f}}async function wA(e,{blockNumber:t,blockTag:r,assetGatewayUrls:n,name:s,gatewayUrls:i,strict:o,universalResolverAddress:a}){const c=await se(e,Eg,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:s,universalResolverAddress:a,gatewayUrls:i,strict:o});if(!c)return null;try{return await gA(e,{record:c,gatewayUrls:n})}catch{return null}}async function vA(e,{address:t,blockNumber:r,blockTag:n,gatewayUrls:s,strict:i,universalResolverAddress:o}){let a=o;if(!a){if(!e.chain)throw new Error("client chain not configured. universalResolverAddress is required.");a=Bi({blockNumber:r,chain:e.chain,contract:"ensUniversalResolver"})}const c=`${t.toLowerCase().substring(2)}.addr.reverse`;try{const l={address:a,abi:k6,functionName:"reverse",args:[gt(Rc(c))],blockNumber:r,blockTag:n},u=se(e,Wr,"readContract"),[f,p]=s?await u({...l,args:[...l.args,s]}):await u(l);return t.toLowerCase()!==p.toLowerCase()?null:f}catch(l){if(i)throw l;if(Fd(l,"reverse"))return null;throw l}}async function EA(e,t){const{blockNumber:r,blockTag:n,name:s}=t,{chain:i}=e,o=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!i)throw new Error("client chain not configured. universalResolverAddress is required.");return Bi({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),a=i==null?void 0:i.ensTlds;if(a&&!a.some(l=>s.endsWith(l)))throw new Error(`${s} is not a valid ENS TLD (${a==null?void 0:a.join(", ")}) for chain "${i.name}" (id: ${i.id}).`);const[c]=await se(e,Wr,"readContract")({address:o,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[gt(Rc(s))],blockNumber:r,blockTag:n});return c}async function Ag(e,t){var w,A,T;const{account:r=e.account,blockNumber:n,blockTag:s="latest",blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:l,maxFeePerGas:u,maxPriorityFeePerGas:f,to:p,value:d,...m}=t,g=r?Xe(r):void 0;try{js(t);const S=(typeof n=="bigint"?X(n):void 0)||s,I=(T=(A=(w=e.chain)==null?void 0:w.formatters)==null?void 0:A.transactionRequest)==null?void 0:T.format,$=(I||Pi)({...xc(m,{format:I}),from:g==null?void 0:g.address,blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:l,maxFeePerGas:u,maxPriorityFeePerGas:f,to:p,value:d}),j=await e.request({method:"eth_createAccessList",params:[$,S]});return{accessList:j.accessList,gasUsed:BigInt(j.gasUsed)}}catch(E){throw tg(E,{...t,account:g,chain:e.chain})}}async function AA(e){const t=wc(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}async function xg(e,{address:t,args:r,event:n,events:s,fromBlock:i,strict:o,toBlock:a}={}){const c=s??(n?[n]:void 0),l=wc(e,{method:"eth_newFilter"});let u=[];c&&(u=[c.flatMap(d=>Zo({abi:[d],eventName:d.name,args:r}))],n&&(u=u[0]));const f=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof i=="bigint"?X(i):i,toBlock:typeof a=="bigint"?X(a):a,...u.length?{topics:u}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:i,id:f,request:l(f),strict:!!o,toBlock:a,type:"event"}}async function Sg(e){const t=wc(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}async function xA(e){const t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}async function SA(e,{blockHash:t,blockNumber:r,blockTag:n="latest"}={}){const s=r!==void 0?X(r):void 0;let i;return t?i=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0}):i=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[s||n]},{dedupe:!!s}),ur(i)}async function yp(e,{address:t,blockNumber:r,blockTag:n="latest"}){const s=r!==void 0?X(r):void 0,i=await e.request({method:"eth_getCode",params:[t,s||n]},{dedupe:!!s});if(i!=="0x")return i}class _A extends z{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 kA(e,t){const{address:r,factory:n,factoryData:s}=t;try{const[i,o,a,c,l,u,f]=await se(e,Wr,"readContract")({abi:TA,address:r,functionName:"eip712Domain",factory:n,factoryData:s});return{domain:{name:o,version:a,chainId:Number(c),verifyingContract:l,salt:u},extensions:f,fields:i}}catch(i){const o=i;throw o.name==="ContractFunctionExecutionError"&&o.cause.name==="ContractFunctionZeroDataError"?new _A({address:r}):o}}const TA=[{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 IA(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 PA(e,{blockCount:t,blockNumber:r,blockTag:n="latest",rewardPercentiles:s}){const i=typeof r=="bigint"?X(r):void 0,o=await e.request({method:"eth_feeHistory",params:[X(t),i||n,s]},{dedupe:!!i});return IA(o)}async function OA(e,{filter:t}){const r=t.strict??!1,s=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map(i=>wn(i));return t.abi?Od({abi:t.abi,logs:s,strict:r}):s}function dt(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}class BA extends z{constructor({domain:t}){super(`Invalid domain "${Ze(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class CA extends z{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 RA extends z{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function $A(e){const{domain:t={},message:r,primaryType:n}=e,s={EIP712Domain:Og({domain:t}),...e.types};Pg({domain:t,message:r,primaryType:n,types:s});const i=["0x1901"];return t&&i.push(NA({domain:t,types:s})),n!=="EIP712Domain"&&i.push(_g({data:r,primaryType:n,types:s})),lt(Vt(i))}function NA({domain:e,types:t}){return _g({data:e,primaryType:"EIP712Domain",types:t})}function _g({data:e,primaryType:t,types:r}){const n=kg({data:e,primaryType:t,types:r});return lt(n)}function kg({data:e,primaryType:t,types:r}){const n=[{type:"bytes32"}],s=[UA({primaryType:t,types:r})];for(const i of r[t]){const[o,a]=Ig({types:r,name:i.name,type:i.type,value:e[i.name]});n.push(o),s.push(a)}return kn(n,s)}function UA({primaryType:e,types:t}){const r=gt(MA({primaryType:e,types:t}));return lt(r)}function MA({primaryType:e,types:t}){let r="";const n=Tg({primaryType:e,types:t});n.delete(e);const s=[e,...Array.from(n).sort()];for(const i of s)r+=`${i}(${t[i].map(({name:o,type:a})=>`${a} ${o}`).join(",")})`;return r}function Tg({primaryType:e,types:t},r=new Set){const n=e.match(/^\w*/u),s=n==null?void 0:n[0];if(r.has(s)||t[s]===void 0)return r;r.add(s);for(const i of t[s])Tg({primaryType:i.type,types:t},r);return r}function Ig({types:e,name:t,type:r,value:n}){if(e[r]!==void 0)return[{type:"bytes32"},lt(kg({data:n,primaryType:r,types:e}))];if(r==="bytes")return n=`0x${(n.length%2?"0":"")+n.slice(2)}`,[{type:"bytes32"},lt(n)];if(r==="string")return[{type:"bytes32"},lt(gt(n))];if(r.lastIndexOf("]")===r.length-1){const s=r.slice(0,r.lastIndexOf("[")),i=n.map(o=>Ig({name:t,type:s,types:e,value:o}));return[{type:"bytes32"},lt(kn(i.map(([o])=>o),i.map(([,o])=>o)))]}return[{type:r},n]}function FA(e){const{domain:t,message:r,primaryType:n,types:s}=e,i=(c,l)=>{const u={...l};for(const f of c){const{name:p,type:d}=f;d==="address"&&(u[p]=u[p].toLowerCase())}return u},o=s.EIP712Domain?t?i(s.EIP712Domain,t):{}:{},a=(()=>{if(n!=="EIP712Domain")return i(s[n],r)})();return Ze({domain:o,message:a,primaryType:n,types:s})}function Pg(e){const{domain:t,message:r,primaryType:n,types:s}=e,i=(o,a)=>{for(const c of o){const{name:l,type:u}=c,f=a[l],p=u.match(d0);if(p&&(typeof f=="number"||typeof f=="bigint")){const[g,w,A]=p;X(f,{signed:w==="int",size:Number.parseInt(A)/8})}if(u==="address"&&typeof f=="string"&&!st(f))throw new Bt({address:f});const d=u.match(M2);if(d){const[g,w]=d;if(w&&He(f)!==Number.parseInt(w))throw new Gv({expectedSize:Number.parseInt(w),givenSize:He(f)})}const m=s[u];m&&(jA(u),i(m,f))}};if(s.EIP712Domain&&t){if(typeof t!="object")throw new BA({domain:t});i(s.EIP712Domain,t)}if(n!=="EIP712Domain")if(s[n])i(s[n],r);else throw new CA({primaryType:n,types:s})}function Og({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 jA(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new RA({type:e})}function LA(e){const{authorizationList:t}=e;if(t)for(const r of t){const{chainId:n}=r,s=r.address;if(!st(s))throw new Bt({address:s});if(n<0)throw new Tc({chainId:n})}Dd(e)}function DA(e){const{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new F0;for(const r of t){const n=He(r),s=ur(_s(r,0,1));if(n!==32)throw new JE({hash:r,size:n});if(s!==M0)throw new QE({hash:r,version:s})}}Dd(e)}function Dd(e){const{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:s}=e;if(t<=0)throw new Tc({chainId:t});if(s&&!st(s))throw new Bt({address:s});if(n&&n>Sc)throw new Ps({maxFeePerGas:n});if(r&&n&&r>n)throw new Uo({maxFeePerGas:n,maxPriorityFeePerGas:r})}function HA(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=e;if(t<=0)throw new Tc({chainId:t});if(i&&!st(i))throw new Bt({address:i});if(r||s)throw new z("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Sc)throw new Ps({maxFeePerGas:n})}function zA(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=e;if(i&&!st(i))throw new Bt({address:i});if(typeof t<"u"&&t<=0)throw new Tc({chainId:t});if(r||s)throw new z("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Sc)throw new Ps({maxFeePerGas:n})}function $c(e){if(!e||e.length===0)return[];const t=[];for(let r=0;r<e.length;r++){const{address:n,storageKeys:s}=e[r];for(let i=0;i<s.length;i++)if(s[i].length-2!==64)throw new pE({storageKey:s[i]});if(!st(n,{strict:!1}))throw new Bt({address:n});t.push([n,s])}return t}function qA(e,t){const r=L0(e);return r==="eip1559"?WA(e,t):r==="eip2930"?KA(e,t):r==="eip4844"?GA(e,t):r==="eip7702"?VA(e,t):XA(e,t)}function VA(e,t){const{authorizationList:r,chainId:n,gas:s,nonce:i,to:o,value:a,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:u,data:f}=e;LA(e);const p=$c(u),d=YA(r);return Tr(["0x04",Qn([X(n),i?X(i):"0x",l?X(l):"0x",c?X(c):"0x",s?X(s):"0x",o??"0x",a?X(a):"0x",f??"0x",p,d,...sa(e,t)])])}function GA(e,t){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:u,data:f}=e;DA(e);let p=e.blobVersionedHashes,d=e.sidecars;if(e.blobs&&(typeof p>"u"||typeof d>"u")){const E=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(P=>Je(P)),S=e.kzg,I=Sd({blobs:E,kzg:S});if(typeof p>"u"&&(p=$0({commitments:I})),typeof d>"u"){const P=_d({blobs:E,commitments:I,kzg:S});d=j0({blobs:E,commitments:I,proofs:P})}}const m=$c(u),g=[X(r),s?X(s):"0x",l?X(l):"0x",c?X(c):"0x",n?X(n):"0x",i??"0x",o?X(o):"0x",f??"0x",m,a?X(a):"0x",p??[],...sa(e,t)],w=[],A=[],T=[];if(d)for(let E=0;E<d.length;E++){const{blob:S,commitment:I,proof:P}=d[E];w.push(S),A.push(I),T.push(P)}return Tr(["0x03",Qn(d?[g,w,A,T]:g)])}function WA(e,t){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:l,data:u}=e;Dd(e);const f=$c(l),p=[X(r),s?X(s):"0x",c?X(c):"0x",a?X(a):"0x",n?X(n):"0x",i??"0x",o?X(o):"0x",u??"0x",f,...sa(e,t)];return Tr(["0x02",Qn(p)])}function KA(e,t){const{chainId:r,gas:n,data:s,nonce:i,to:o,value:a,accessList:c,gasPrice:l}=e;HA(e);const u=$c(c),f=[X(r),i?X(i):"0x",l?X(l):"0x",n?X(n):"0x",o??"0x",a?X(a):"0x",s??"0x",u,...sa(e,t)];return Tr(["0x01",Qn(f)])}function XA(e,t){const{chainId:r=0,gas:n,data:s,nonce:i,to:o,value:a,gasPrice:c}=e;zA(e);let l=[i?X(i):"0x",c?X(c):"0x",n?X(n):"0x",o??"0x",a?X(a):"0x",s??"0x"];if(t){const u=(()=>{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 dE({v:t.v});return d})(),f=cr(t.r),p=cr(t.s);l=[...l,X(u),f==="0x00"?"0x":f,p==="0x00"?"0x":p]}else r>0&&(l=[...l,X(r),"0x","0x"]);return Qn(l)}function sa(e,t){const r=t??e,{v:n,yParity:s}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof s>"u")return[];const i=cr(r.r),o=cr(r.s);return[typeof s=="number"?s?X(1):"0x":n===0n?"0x":n===1n?X(1):n===27n?"0x":X(1),i==="0x00"?"0x":i,o==="0x00"?"0x":o]}function YA(e){if(!e||e.length===0)return[];const t=[];for(const r of e){const{chainId:n,nonce:s,...i}=r,o=r.address;t.push([n?gt(n):"0x",o,s?gt(s):"0x",...sa({},i)])}return t}const ZA=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Bg=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),JA=Bg.map(e=>(9*e+5)%16),Cg=(()=>{const r=[[Bg],[JA]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>ZA[i]));return r})(),Rg=Cg[0],$g=Cg[1],Ng=[[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)),QA=Rg.map((e,t)=>e.map(r=>Ng[t][r])),ex=$g.map((e,t)=>e.map(r=>Ng[t][r])),tx=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),rx=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function mp(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 wa=new Uint32Array(16);let Ug=class extends O0{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:s,h4:i}=this;return[t,r,n,s,i]}set(t,r,n,s,i){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=s|0,this.h4=i|0}process(t,r){for(let d=0;d<16;d++,r+=4)wa[d]=t.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,o=i,a=this.h2|0,c=a,l=this.h3|0,u=l,f=this.h4|0,p=f;for(let d=0;d<5;d++){const m=4-d,g=tx[d],w=rx[d],A=Rg[d],T=$g[d],E=QA[d],S=ex[d];for(let I=0;I<16;I++){const P=pa(n+mp(d,i,a,l)+wa[A[I]]+g,E[I])+f|0;n=f,f=l,l=pa(a,10)|0,a=i,i=P}for(let I=0;I<16;I++){const P=pa(s+mp(m,o,c,u)+wa[T[I]]+w,S[I])+p|0;s=p,p=u,u=pa(c,10)|0,c=o,o=P}}this.set(this.h1+a+u|0,this.h2+l+p|0,this.h3+f+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){_r(wa)}destroy(){this.destroyed=!0,_r(this.buffer),this.set(0,0,0,0,0)}};const nx=mc(()=>new Ug),sx=Ug,ix=nx,ox=Object.freeze(Object.defineProperty({__proto__:null,RIPEMD160:sx,ripemd160:ix},Symbol.toStringTag,{value:"Module"})),ax=`Ethereum Signed Message:
|
|
43
43
|
`;function cx(e){const t=typeof e=="string"?mi(e):typeof e.raw=="string"?e.raw:Je(e.raw),r=mi(`${ax}${He(t)}`);return Vt([r,t])}function Mg(e,t){return lt(cx(e),t)}const Fg="0x6492649264926492649264926492649264926492649264926492649264926492";function ux(e){return Qa(e,-32)===Fg}function lx(e){const{address:t,data:r,signature:n,to:s="hex"}=e,i=Tr([kn([{type:"address"},{type:"bytes"},{type:"bytes"}],[t,r,n]),Fg]);return s==="hex"?i:Sr(i)}function fx(e){return e.map(t=>({...t,value:BigInt(t.value)}))}function dx(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?ur(e.nonce):void 0,storageProof:e.storageProof?fx(e.storageProof):void 0}}async function hx(e,{address:t,blockNumber:r,blockTag:n,storageKeys:s}){const i=n??"latest",o=r!==void 0?X(r):void 0,a=await e.request({method:"eth_getProof",params:[t,s,o||i]});return dx(a)}async function px(e,{address:t,blockNumber:r,blockTag:n="latest",slot:s}){const i=r!==void 0?X(r):void 0;return await e.request({method:"eth_getStorageAt",params:[t,s,i||n]})}async function Hd(e,{blockHash:t,blockNumber:r,blockTag:n,hash:s,index:i}){var u,f,p;const o=n||"latest",a=r!==void 0?X(r):void 0;let c=null;if(s?c=await e.request({method:"eth_getTransactionByHash",params:[s]},{dedupe:!0}):t?c=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,X(i)]},{dedupe:!0}):c=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[a||o,X(i)]},{dedupe:!!a}),!c)throw new v0({blockHash:t,blockNumber:r,blockTag:o,hash:s,index:i});return(((p=(f=(u=e.chain)==null?void 0:u.formatters)==null?void 0:f.transaction)==null?void 0:p.format)||_c)(c)}async function yx(e,{hash:t,transactionReceipt:r}){const[n,s]=await Promise.all([se(e,na,"getBlockNumber")({}),t?se(e,Hd,"getTransaction")({hash:t}):void 0]),i=(r==null?void 0:r.blockNumber)||(s==null?void 0:s.blockNumber);return i?n-i+1n:0n}async function ja(e,{hash:t}){var s,i,o;const r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new E0({hash:t});return(((o=(i=(s=e.chain)==null?void 0:s.formatters)==null?void 0:i.transactionReceipt)==null?void 0:o.format)||ug)(r)}async function mx(e,t){var A;const{account:r,allowFailure:n=!0,batchSize:s,blockNumber:i,blockTag:o,multicallAddress:a,stateOverride:c}=t,l=t.contracts,u=s??(typeof((A=e.batch)==null?void 0:A.multicall)=="object"&&e.batch.multicall.batchSize||1024);let f=a;if(!f){if(!e.chain)throw new Error("client chain not configured. multicallAddress is required.");f=Bi({blockNumber:i,chain:e.chain,contract:"multicall3"})}const p=[[]];let d=0,m=0;for(let T=0;T<l.length;T++){const{abi:E,address:S,args:I,functionName:P}=l[T];try{const $=dr({abi:E,args:I,functionName:P});m+=($.length-2)/2,u>0&&m>u&&p[d].length>0&&(d++,m=($.length-2)/2,p[d]=[]),p[d]=[...p[d],{allowFailure:!0,callData:$,target:S}]}catch($){const j=Is($,{abi:E,address:S,args:I,docsPath:"/docs/contract/multicall",functionName:P,sender:r});if(!n)throw j;p[d]=[...p[d],{allowFailure:!0,callData:"0x",target:S}]}}const g=await Promise.allSettled(p.map(T=>se(e,Wr,"readContract")({abi:bf,account:r,address:f,args:[T],blockNumber:i,blockTag:o,functionName:"aggregate3",stateOverride:c}))),w=[];for(let T=0;T<g.length;T++){const E=g[T];if(E.status==="rejected"){if(!n)throw E.reason;for(let I=0;I<p[T].length;I++)w.push({status:"failure",error:E.reason,result:void 0});continue}const S=E.value;for(let I=0;I<S.length;I++){const{returnData:P,success:$}=S[I],{callData:j}=p[T][I],{abi:k,address:F,functionName:R,args:U}=l[w.length];try{if(j==="0x")throw new Ko;if(!$)throw new Ec({data:P});const H=Ls({abi:k,args:U,data:P,functionName:R});w.push(n?{result:H,status:"success"}:H)}catch(H){const W=Is(H,{abi:k,address:F,args:U,docsPath:"/docs/contract/multicall",functionName:R});if(!n)throw W;w.push({error:W,result:void 0,status:"failure"})}}}if(w.length!==l.length)throw new z("multicall results mismatch");return w}async function xf(e,t){const{blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",blocks:s,returnFullTransactions:i,traceTransfers:o,validation:a}=t;try{const c=[];for(const p of s){const d=p.blockOverrides?Y0(p.blockOverrides):void 0,m=p.calls.map(w=>{const A=w,T=A.account?Xe(A.account):void 0,E=A.abi?dr(A):A.data,S={...A,data:A.dataSuffix?Vt([E||"0x",A.dataSuffix]):E,from:A.from??(T==null?void 0:T.address)};return js(S),Pi(S)}),g=p.stateOverrides?wd(p.stateOverrides):void 0;c.push({blockOverrides:d,calls:m,stateOverrides:g})}const u=(typeof r=="bigint"?X(r):void 0)||n;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:i,traceTransfers:o,validation:a},u]})).map((p,d)=>({...Ed(p),calls:p.calls.map((m,g)=>{var F,R;const{abi:w,args:A,functionName:T,to:E}=s[d].calls[g],S=((F=m.error)==null?void 0:F.data)??m.returnData,I=BigInt(m.gasUsed),P=(R=m.logs)==null?void 0:R.map(U=>wn(U)),$=m.status==="0x1"?"success":"failure",j=w&&$==="success"&&S!=="0x"?Ls({abi:w,data:S,functionName:T}):null,k=(()=>{var H;if($==="success")return;let U;if(((H=m.error)==null?void 0:H.data)==="0x"?U=new Ko:m.error&&(U=new Ec(m.error)),!!U)return Is(U,{abi:w??[],address:E??"0x",args:A,functionName:T??"<unknown>"})})();return{data:S,gasUsed:I,logs:P,status:$,...$==="success"?{result:j}:{error:k}}})}))}catch(c){const l=c,u=Ac(l,{});throw u instanceof ea?l:u}}function jg(e,t={}){const{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=o0(d6(e));return r==="Bytes"?n:W0(n)}class gx 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 bx={checksum:new gx(8192)},Eu=bx.checksum,wx=/^0x[a-fA-F0-9]{40}$/;function Nc(e,t={}){const{strict:r=!0}=t;if(!wx.test(e))throw new gp({address:e,cause:new Ex});if(r){if(e.toLowerCase()===e)return;if(vx(e)!==e)throw new gp({address:e,cause:new Ax})}}function vx(e){if(Eu.has(e))return Eu.get(e);Nc(e,{strict:!1});const t=e.substring(2).toLowerCase(),r=jg(y6(t),{as:"Bytes"}),n=t.split("");for(let i=0;i<40;i+=2)r[i>>1]>>4>=8&&n[i]&&(n[i]=n[i].toUpperCase()),(r[i>>1]&15)>=8&&n[i+1]&&(n[i+1]=n[i+1].toUpperCase());const s=`0x${n.join("")}`;return Eu.set(e,s),s}function Sf(e,t={}){const{strict:r=!0}=t??{};try{return Nc(e,{strict:r}),!0}catch{return!1}}class gp extends Fe{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 Ex extends Fe{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 Ax extends Fe{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}function _f(e){let t=!0,r="",n=0,s="",i=!1;for(let o=0;o<e.length;o++){const a=e[o];if(["(",")",","].includes(a)&&(t=!0),a==="("&&n++,a===")"&&n--,!!t){if(n===0){if(a===" "&&["event","function","error",""].includes(s))s="";else if(s+=a,a===")"){i=!0;break}continue}if(a===" "){e[o-1]!==","&&r!==","&&r!==",("&&(r="",t=!1);continue}s+=a,r+=a}}if(!i)throw new Fe("Unable to normalize signature.");return s}function kf(e,t){const r=typeof e,n=t.type;switch(n){case"address":return Sf(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((s,i)=>kf(Object.values(e)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(e)&&e.every(s=>kf(s,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function Lg(e,t,r){for(const n in e){const s=e[n],i=t[n];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return Lg(s.components,i.components,r[n]);const o=[s.type,i.type];if(o.includes("address")&&o.includes("bytes20")?!0:o.includes("address")&&o.includes("string")?Sf(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?Sf(r[n],{strict:!1}):!1)return o}}function Dg(e,t={}){const{prepare:r=!0}=t,n=Array.isArray(e)||typeof e=="string"?$h(e):e;return{...n,...r?{hash:oi(n)}:{}}}function xx(e,t,r){const{args:n=[],prepare:s=!0}=r??{},i=A6(t,{strict:!1}),o=e.filter(l=>i?l.type==="function"||l.type==="error"?Hg(l)===Nd(t,0,4):l.type==="event"?oi(l)===t:!1:"name"in l&&l.name===t);if(o.length===0)throw new Tf({name:t});if(o.length===1)return{...o[0],...s?{hash:oi(o[0])}:{}};let a;for(const l of o){if(!("inputs"in l))continue;if(!n||n.length===0){if(!l.inputs||l.inputs.length===0)return{...l,...s?{hash:oi(l)}:{}};continue}if(!l.inputs||l.inputs.length===0||l.inputs.length!==n.length)continue;if(n.every((f,p)=>{const d="inputs"in l&&l.inputs[p];return d?kf(f,d):!1})){if(a&&"inputs"in a&&a.inputs){const f=Lg(l.inputs,a.inputs,n);if(f)throw new _x({abiItem:l,type:f[0]},{abiItem:a,type:f[1]})}a=l}}const c=(()=>{if(a)return a;const[l,...u]=o;return{...l,overloads:u}})();if(!c)throw new Tf({name:t});return{...c,...s?{hash:oi(c)}:{}}}function Hg(e){return Nd(oi(e),0,4)}function Sx(e){const t=typeof e=="string"?e:Ja(e);return _f(t)}function oi(e){return typeof e!="string"&&"hash"in e&&e.hash?e.hash:jg($d(Sx(e)))}class _x extends Fe{constructor(t,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${t.type}\` in \`${_f(Ja(t.abiItem))}\`, and`,`\`${r.type}\` in \`${_f(Ja(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 Tf extends Fe{constructor({name:t,data:r,type:n="item"}){const s=t?` with name "${t}"`:r?` with data "${r}"`:"";super(`ABI ${n}${s} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}const kx=/^(.*)\[([0-9]*)\]$/,Tx=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,zg=/^(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 Ix({checksumAddress:e,parameters:t,values:r}){const n=[];for(let s=0;s<t.length;s++)n.push(zd({checksumAddress:e,parameter:t[s],value:r[s]}));return n}function zd({checksumAddress:e=!1,parameter:t,value:r}){const n=t,s=Ux(n.type);if(s){const[i,o]=s;return Ox(r,{checksumAddress:e,length:i,parameter:{...n,type:o}})}if(n.type==="tuple")return Nx(r,{checksumAddress:e,parameter:n});if(n.type==="address")return Px(r,{checksum:e});if(n.type==="bool")return Cx(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){const i=n.type.startsWith("int"),[,,o="256"]=zg.exec(n.type)??[];return Rx(r,{signed:i,size:Number(o)})}if(n.type.startsWith("bytes"))return Bx(r,{type:n.type});if(n.type==="string")return $x(r);throw new Wg(n.type)}function qd(e){let t=0;for(let i=0;i<e.length;i++){const{dynamic:o,encoded:a}=e[i];o?t+=32:t+=fr(a)}const r=[],n=[];let s=0;for(let i=0;i<e.length;i++){const{dynamic:o,encoded:a}=e[i];o?(r.push(It(t+s,{size:32})),n.push(a),s+=fr(a)):r.push(a)}return Gr(...r,...n)}function Px(e,t){const{checksum:r=!1}=t;return Nc(e,{strict:r}),{dynamic:!1,encoded:Os(e.toLowerCase())}}function Ox(e,t){const{checksumAddress:r,length:n,parameter:s}=t,i=n===null;if(!Array.isArray(e))throw new Fx(e);if(!i&&e.length!==n)throw new Mx({expectedLength:n,givenLength:e.length,type:`${s.type}[${n}]`});let o=!1;const a=[];for(let c=0;c<e.length;c++){const l=zd({checksumAddress:r,parameter:s,value:e[c]});l.dynamic&&(o=!0),a.push(l)}if(i||o){const c=qd(a);if(i){const l=It(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?Gr(l,c):l}}if(o)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Gr(...a.map(({encoded:c})=>c))}}function Bx(e,{type:t}){const[,r]=t.split("bytes"),n=fr(e);if(!r){let s=e;return n%32!==0&&(s=Bs(s,Math.ceil((e.length-2)/2/32)*32)),{dynamic:!0,encoded:Gr(Os(It(n,{size:32})),s)}}if(n!==Number.parseInt(r))throw new Vg({expectedSize:Number.parseInt(r),value:e});return{dynamic:!1,encoded:Bs(e)}}function Cx(e){if(typeof e!="boolean")throw new Fe(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Os(G0(e))}}function Rx(e,{signed:t,size:r}){if(typeof r=="number"){const n=2n**(BigInt(r)-(t?1n:0n))-1n,s=t?-n-1n:0n;if(e>n||e<s)throw new K0({max:n.toString(),min:s.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:It(e,{size:32,signed:t})}}function $x(e){const t=$d(e),r=Math.ceil(fr(t)/32),n=[];for(let s=0;s<r;s++)n.push(Bs(Nd(t,s*32,(s+1)*32)));return{dynamic:!0,encoded:Gr(Bs(It(fr(t),{size:32})),...n)}}function Nx(e,t){const{checksumAddress:r,parameter:n}=t;let s=!1;const i=[];for(let o=0;o<n.components.length;o++){const a=n.components[o],c=Array.isArray(e)?o:a.name,l=zd({checksumAddress:r,parameter:a,value:e[c]});i.push(l),l.dynamic&&(s=!0)}return{dynamic:s,encoded:s?qd(i):Gr(...i.map(({encoded:o})=>o))}}function Ux(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function qg(e,t,r){const{checksumAddress:n=!1}={};if(e.length!==t.length)throw new Gg({expectedLength:e.length,givenLength:t.length});const s=Ix({checksumAddress:n,parameters:e,values:t}),i=qd(s);return i.length===0?"0x":i}function If(e,t){if(e.length!==t.length)throw new Gg({expectedLength:e.length,givenLength:t.length});const r=[];for(let n=0;n<e.length;n++){const s=e[n],i=t[n];r.push(If.encode(s,i))}return Gr(...r)}(function(e){function t(r,n,s=!1){if(r==="address"){const c=n;return Nc(c),Os(c.toLowerCase(),s?32:0)}if(r==="string")return $d(n);if(r==="bytes")return n;if(r==="bool")return Os(G0(n),s?32:1);const i=r.match(zg);if(i){const[c,l,u="256"]=i,f=Number.parseInt(u)/8;return It(n,{size:s?32:f,signed:l==="int"})}const o=r.match(Tx);if(o){const[c,l]=o;if(Number.parseInt(l)!==(n.length-2)/2)throw new Vg({expectedSize:Number.parseInt(l),value:n});return Bs(n,s?32:0)}const a=r.match(kx);if(a&&Array.isArray(n)){const[c,l]=a,u=[];for(let f=0;f<n.length;f++)u.push(t(l,n[f],!0));return u.length===0?"0x":Gr(...u)}throw new Wg(r)}e.encode=t})(If||(If={}));class Mx extends Fe{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 Vg extends Fe{constructor({expectedSize:t,value:r}){super(`Size of bytes "${r}" (bytes${fr(r)}) does not match expected size (bytes${t}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class Gg extends Fe{constructor({expectedLength:t,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${t}`,`Given length (values): ${r}`].join(`
|
|
44
44
|
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class Fx extends Fe{constructor(t){super(`Value \`${t}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class Wg extends Fe{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 jx(e,t){var s;const{bytecode:r,args:n}=t;return Gr(r,(s=e.inputs)!=null&&s.length&&(n!=null&&n.length)?qg(e.inputs,n):"0x")}function Lx(e){return Dg(e)}function Dx(e,...t){const{overloads:r}=e,n=r?Hx([e,...r],e.name,{args:t[0]}):e,s=zx(n),i=t.length>0?qg(n.inputs,t[0]):void 0;return i?Gr(s,i):s}function Ks(e,t={}){return Dg(e,t)}function Hx(e,t,r){const n=xx(e,t,r);if(n.type!=="function")throw new Tf({name:t,type:"function"});return n}function zx(e){return Hg(e)}const qx="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Cr="0x0000000000000000000000000000000000000000",Vx="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function Gx(e,t){const{blockNumber:r,blockTag:n,calls:s,stateOverrides:i,traceAssetChanges:o,traceTransfers:a,validation:c}=t,l=t.account?Xe(t.account):void 0;if(o&&!l)throw new z("`account` is required when `traceAssetChanges` is true");const u=l?jx(Lx("constructor(bytes, bytes)"),{bytecode:Q0,args:[Vx,Dx(Ks("function getBalance(address)"),[l.address])]}):void 0,f=o?await Promise.all(t.calls.map(async D=>{if(!D.data&&!D.abi)return;const{accessList:B}=await Ag(e,{account:l.address,...D,data:D.abi?dr(D):D.data});return B.map(({address:V,storageKeys:K})=>K.length>0?V:null)})).then(D=>D.flat().filter(Boolean)):[],p=await xf(e,{blockNumber:r,blockTag:n,blocks:[...o?[{calls:[{data:u}],stateOverrides:i},{calls:f.map((D,B)=>({abi:[Ks("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[l.address],to:D,from:Cr,nonce:B})),stateOverrides:[{address:Cr,nonce:0}]}]:[],{calls:[...s,{}].map(D=>({...D,from:l==null?void 0:l.address})),stateOverrides:i},...o?[{calls:[{data:u}]},{calls:f.map((D,B)=>({abi:[Ks("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[l.address],to:D,from:Cr,nonce:B})),stateOverrides:[{address:Cr,nonce:0}]},{calls:f.map((D,B)=>({to:D,abi:[Ks("function decimals() returns (uint256)")],functionName:"decimals",from:Cr,nonce:B})),stateOverrides:[{address:Cr,nonce:0}]},{calls:f.map((D,B)=>({to:D,abi:[Ks("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:Cr,nonce:B})),stateOverrides:[{address:Cr,nonce:0}]},{calls:f.map((D,B)=>({to:D,abi:[Ks("function symbol() returns (string)")],functionName:"symbol",from:Cr,nonce:B})),stateOverrides:[{address:Cr,nonce:0}]}]:[]],traceTransfers:a,validation:c}),d=o?p[2]:p[0],[m,g,,w,A,T,E,S]=o?p:[],{calls:I,...P}=d,$=I.slice(0,-1)??[],j=(m==null?void 0:m.calls)??[],k=(g==null?void 0:g.calls)??[],F=[...j,...k].map(D=>D.status==="success"?ot(D.data):null),R=(w==null?void 0:w.calls)??[],U=(A==null?void 0:A.calls)??[],H=[...R,...U].map(D=>D.status==="success"?ot(D.data):null),W=((T==null?void 0:T.calls)??[]).map(D=>D.status==="success"?D.result:null),Z=((S==null?void 0:S.calls)??[]).map(D=>D.status==="success"?D.result:null),Q=((E==null?void 0:E.calls)??[]).map(D=>D.status==="success"?D.result:null),re=[];for(const[D,B]of H.entries()){const V=F[D];if(typeof B!="bigint"||typeof V!="bigint")continue;const K=W[D-1],O=Z[D-1],N=Q[D-1],L=D===0?{address:qx,decimals:18,symbol:"ETH"}:{address:f[D-1],decimals:N||K?Number(K??1):void 0,symbol:O??void 0};re.some(J=>J.token.address===L.address)||re.push({token:L,value:{pre:V,post:B,diff:B-V}})}return{assetChanges:re,block:P,results:$}}class Kg extends yc{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,m2(t);const n=mn(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 s=this.blockLen,i=new Uint8Array(s);i.set(n.length>s?t.create().update(n).digest():n);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=t.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),_r(i)}update(t){return Jn(this),this.iHash.update(t),this}digestInto(t){Jn(this),lr(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:s,destroyed:i,blockLen:o,outputLen:a}=this;return t=t,t.finished=s,t.destroyed=i,t.blockLen=o,t.outputLen=a,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 Xg=(e,t,r)=>new Kg(e,t).update(r).digest();Xg.create=(e,t)=>new Kg(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Vd=BigInt(0),Pf=BigInt(1);function tc(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function va(e){const t=e.toString(16);return t.length&1?"0"+t:t}function Yg(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Vd:BigInt("0x"+e)}function Uc(e){return Yg(mo(e))}function Zg(e){return lr(e),Yg(mo(Uint8Array.from(e).reverse()))}function Gd(e,t){return ud(e.toString(16).padStart(t*2,"0"))}function Jg(e,t){return Gd(e,t).reverse()}function Qt(e,t,r){let n;if(typeof t=="string")try{n=ud(t)}catch(i){throw new Error(e+" must be hex string or Uint8Array, cause: "+i)}else if(ad(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const s=n.length;if(typeof r=="number"&&s!==r)throw new Error(e+" of length "+r+" expected, got "+s);return n}const Au=e=>typeof e=="bigint"&&Vd<=e;function Wx(e,t,r){return Au(e)&&Au(t)&&Au(r)&&t<=e&&e<r}function Kx(e,t,r,n){if(!Wx(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Xx(e){let t;for(t=0;e>Vd;e>>=Pf,t+=1);return t}const Mc=e=>(Pf<<BigInt(e))-Pf;function Yx(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");const n=d=>new Uint8Array(d),s=d=>Uint8Array.of(d);let i=n(e),o=n(e),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...d)=>r(o,i,...d),u=(d=n(0))=>{o=l(s(0),d),i=l(),d.length!==0&&(o=l(s(1),d),i=l())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0;const m=[];for(;d<t;){i=l();const g=i.slice();m.push(g),d+=i.length}return us(...m)};return(d,m)=>{c(),u(d);let g;for(;!(g=m(f()));)u();return c(),g}}function Wd(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(s,i,o){const a=e[s];if(o&&a===void 0)return;const c=typeof a;if(c!==i||a===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${c}`)}Object.entries(t).forEach(([s,i])=>n(s,i,!1)),Object.entries(r).forEach(([s,i])=>n(s,i,!0))}function bp(e){const t=new WeakMap;return(r,...n)=>{const s=t.get(r);if(s!==void 0)return s;const i=e(r,...n);return t.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Nt=BigInt(0),Ot=BigInt(1),fs=BigInt(2),Zx=BigInt(3),Qg=BigInt(4),eb=BigInt(5),tb=BigInt(8);function rr(e,t){const r=e%t;return r>=Nt?r:t+r}function Zt(e,t,r){let n=e;for(;t-- >Nt;)n*=n,n%=r;return n}function wp(e,t){if(e===Nt)throw new Error("invert: expected non-zero number");if(t<=Nt)throw new Error("invert: expected positive modulus, got "+t);let r=rr(e,t),n=t,s=Nt,i=Ot;for(;r!==Nt;){const a=n/r,c=n%r,l=s-i*a;n=r,r=c,s=i,i=l}if(n!==Ot)throw new Error("invert: does not exist");return rr(s,t)}function rb(e,t){const r=(e.ORDER+Ot)/Qg,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function Jx(e,t){const r=(e.ORDER-eb)/tb,n=e.mul(t,fs),s=e.pow(n,r),i=e.mul(t,s),o=e.mul(e.mul(i,fs),s),a=e.mul(i,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function Qx(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");let t=e-Ot,r=0;for(;t%fs===Nt;)t/=fs,r++;let n=fs;const s=Fc(e);for(;vp(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return rb;let i=s.pow(n,t);const o=(t+Ot)/fs;return function(c,l){if(c.is0(l))return l;if(vp(c,l)!==1)throw new Error("Cannot find square root");let u=r,f=c.mul(c.ONE,i),p=c.pow(l,t),d=c.pow(l,o);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let m=1,g=c.sqr(p);for(;!c.eql(g,c.ONE);)if(m++,g=c.sqr(g),m===u)throw new Error("Cannot find square root");const w=Ot<<BigInt(u-m-1),A=c.pow(f,w);u=m,f=c.sqr(A),p=c.mul(p,f),d=c.mul(d,A)}return d}}function eS(e){return e%Qg===Zx?rb:e%tb===eb?Jx:Qx(e)}const tS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function rS(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=tS.reduce((n,s)=>(n[s]="function",n),t);return Wd(e,r),e}function nS(e,t,r){if(r<Nt)throw new Error("invalid exponent, negatives unsupported");if(r===Nt)return e.ONE;if(r===Ot)return t;let n=e.ONE,s=t;for(;r>Nt;)r&Ot&&(n=e.mul(n,s)),s=e.sqr(s),r>>=Ot;return n}function nb(e,t,r=!1){const n=new Array(t.length).fill(r?e.ZERO:void 0),s=t.reduce((o,a,c)=>e.is0(a)?o:(n[c]=o,e.mul(o,a)),e.ONE),i=e.inv(s);return t.reduceRight((o,a,c)=>e.is0(a)?o:(n[c]=e.mul(o,n[c]),e.mul(o,a)),i),n}function vp(e,t){const r=(e.ORDER-Ot)/fs,n=e.pow(t,r),s=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),o=e.eql(n,e.neg(e.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function sS(e,t){t!==void 0&&Zn(t);const r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Fc(e,t,r=!1,n={}){if(e<=Nt)throw new Error("invalid field: expected ORDER > 0, got "+e);let s,i;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const u=t;u.BITS&&(s=u.BITS),u.sqrt&&(i=u.sqrt),typeof u.isLE=="boolean"&&(r=u.isLE)}else typeof t=="number"&&(s=t),n.sqrt&&(i=n.sqrt);const{nBitLength:o,nByteLength:a}=sS(e,s);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c;const l=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:a,MASK:Mc(o),ZERO:Nt,ONE:Ot,create:u=>rr(u,e),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return Nt<=u&&u<e},is0:u=>u===Nt,isValidNot0:u=>!l.is0(u)&&l.isValid(u),isOdd:u=>(u&Ot)===Ot,neg:u=>rr(-u,e),eql:(u,f)=>u===f,sqr:u=>rr(u*u,e),add:(u,f)=>rr(u+f,e),sub:(u,f)=>rr(u-f,e),mul:(u,f)=>rr(u*f,e),pow:(u,f)=>nS(l,u,f),div:(u,f)=>rr(u*wp(f,e),e),sqrN:u=>u*u,addN:(u,f)=>u+f,subN:(u,f)=>u-f,mulN:(u,f)=>u*f,inv:u=>wp(u,e),sqrt:i||(u=>(c||(c=eS(e)),c(l,u))),toBytes:u=>r?Jg(u,a):Gd(u,a),fromBytes:u=>{if(u.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);return r?Zg(u):Uc(u)},invertBatch:u=>nb(l,u),cmov:(u,f,p)=>p?f:u});return Object.freeze(l)}function sb(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 ib(e){const t=sb(e);return t+Math.ceil(t/2)}function iS(e,t,r=!1){const n=e.length,s=sb(t),i=ib(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=r?Zg(e):Uc(e),a=rr(o,t-Ot)+Ot;return r?Jg(a,s):Gd(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const vi=BigInt(0),ds=BigInt(1);function to(e,t){const r=t.negate();return e?r:t}function oS(e,t,r){const n=o=>o.pz,s=nb(e.Fp,r.map(n));return r.map((o,a)=>o.toAffine(s[a])).map(e.fromAffine)}function ob(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function xu(e,t){ob(e,t);const r=Math.ceil(t/e)+1,n=2**(e-1),s=2**e,i=Mc(e),o=BigInt(e);return{windows:r,windowSize:n,mask:i,maxNumber:s,shiftBy:o}}function Ep(e,t,r){const{windowSize:n,mask:s,maxNumber:i,shiftBy:o}=r;let a=Number(e&s),c=e>>o;a>n&&(a-=i,c+=ds);const l=t*n,u=l+Math.abs(a)-1,f=a===0,p=a<0,d=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:p,isNegF:d,offsetF:l}}function aS(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 cS(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 Su=new WeakMap,ab=new WeakMap;function _u(e){return ab.get(e)||1}function Ap(e){if(e!==vi)throw new Error("invalid wNAF")}function uS(e,t){return{constTimeNegate:to,hasPrecomputes(r){return _u(r)!==1},unsafeLadder(r,n,s=e.ZERO){let i=r;for(;n>vi;)n&ds&&(s=s.add(i)),i=i.double(),n>>=ds;return s},precomputeWindow(r,n){const{windows:s,windowSize:i}=xu(n,t),o=[];let a=r,c=a;for(let l=0;l<s;l++){c=a,o.push(c);for(let u=1;u<i;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,n,s){let i=e.ZERO,o=e.BASE;const a=xu(r,t);for(let c=0;c<a.windows;c++){const{nextN:l,offset:u,isZero:f,isNeg:p,isNegF:d,offsetF:m}=Ep(s,c,a);s=l,f?o=o.add(to(d,n[m])):i=i.add(to(p,n[u]))}return Ap(s),{p:i,f:o}},wNAFUnsafe(r,n,s,i=e.ZERO){const o=xu(r,t);for(let a=0;a<o.windows&&s!==vi;a++){const{nextN:c,offset:l,isZero:u,isNeg:f}=Ep(s,a,o);if(s=c,!u){const p=n[l];i=i.add(f?p.negate():p)}}return Ap(s),i},getPrecomputes(r,n,s){let i=Su.get(n);return i||(i=this.precomputeWindow(n,r),r!==1&&(typeof s=="function"&&(i=s(i)),Su.set(n,i))),i},wNAFCached(r,n,s){const i=_u(r);return this.wNAF(i,this.getPrecomputes(i,r,s),n)},wNAFCachedUnsafe(r,n,s,i){const o=_u(r);return o===1?this.unsafeLadder(r,n,i):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),n,i)},setWindowSize(r,n){ob(n,t),ab.set(r,n),Su.delete(r)}}}function lS(e,t,r,n){let s=t,i=e.ZERO,o=e.ZERO;for(;r>vi||n>vi;)r&ds&&(i=i.add(s)),n&ds&&(o=o.add(s)),s=s.double(),r>>=ds,n>>=ds;return{p1:i,p2:o}}function fS(e,t,r,n){aS(r,e),cS(n,t);const s=r.length,i=n.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=Xx(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Mc(c),u=new Array(Number(l)+1).fill(o),f=Math.floor((t.BITS-1)/c)*c;let p=o;for(let d=f;d>=0;d-=c){u.fill(o);for(let g=0;g<i;g++){const w=n[g],A=Number(w>>BigInt(d)&l);u[A]=u[A].add(r[g])}let m=o;for(let g=u.length-1,w=o;g>0;g--)w=w.add(u[g]),m=m.add(w);if(p=p.add(m),d!==0)for(let g=0;g<c;g++)p=p.double()}return p}function xp(e,t){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return rS(t),t}else return Fc(e)}function dS(e,t,r={}){if(!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(const a of["p","n","h"]){const c=t[a];if(!(typeof c=="bigint"&&c>vi))throw new Error(`CURVE.${a} must be positive bigint`)}const n=xp(t.p,r.Fp),s=xp(t.n,r.Fn),o=["Gx","Gy","a","b"];for(const a of o)if(!n.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return{Fp:n,Fn:s}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Sp(e){e.lowS!==void 0&&tc("lowS",e.lowS),e.prehash!==void 0&&tc("prehash",e.prehash)}class hS extends Error{constructor(t=""){super(t)}}const un={Err:hS,_tlv:{encode:(e,t)=>{const{Err:r}=un;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,s=va(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const i=n>127?va(s.length/2|128):"";return va(e)+i+s+t},decode(e,t){const{Err:r}=un;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 s=t[n++],i=!!(s&128);let o=0;if(!i)o=s;else{const c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=t.subarray(n,n+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=t.subarray(n,n+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+o)}}},_int:{encode(e){const{Err:t}=un;if(e<ro)throw new t("integer: negative integers are not allowed");let r=va(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}=un;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 Uc(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=un,s=Qt("signature",e),{v:i,l:o}=n.decode(48,s);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){const{_tlv:t,_int:r}=un,n=t.encode(2,r.encode(e.r)),s=t.encode(2,r.encode(e.s)),i=n+s;return t.encode(48,i)}},ro=BigInt(0),no=BigInt(1),pS=BigInt(2),Ea=BigInt(3),yS=BigInt(4);function mS(e,t,r){function n(s){const i=e.sqr(s),o=e.mul(i,s);return e.add(e.add(o,e.mul(s,t)),r)}return n}function cb(e,t,r){const{BYTES:n}=e;function s(i){let o;if(typeof i=="bigint")o=i;else{let a=Qt("private key",i);if(t){if(!t.includes(a.length*2))throw new Error("invalid private key");const c=new Uint8Array(n);c.set(a,c.length-a.length),a=c}try{o=e.fromBytes(a)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof i}`)}}if(r&&(o=e.create(o)),!e.isValidNot0(o))throw new Error("invalid private key: out of range [1..N-1]");return o}return s}function gS(e,t={}){const{Fp:r,Fn:n}=dS("weierstrass",e,t),{h:s,n:i}=e;Wd(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:o}=t;if(o&&(!r.is0(e.a)||typeof o.beta!="bigint"||typeof o.splitScalar!="function"))throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');function a(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(j,k,F){const{x:R,y:U}=k.toAffine(),H=r.toBytes(R);if(tc("isCompressed",F),F){a();const W=!r.isOdd(U);return us(ub(W),H)}else return us(Uint8Array.of(4),H,r.toBytes(U))}function l(j){lr(j);const k=r.BYTES,F=k+1,R=2*k+1,U=j.length,H=j[0],W=j.subarray(1);if(U===F&&(H===2||H===3)){const Z=r.fromBytes(W);if(!r.isValid(Z))throw new Error("bad point: is not on curve, wrong x");const Q=p(Z);let re;try{re=r.sqrt(Q)}catch(V){const K=V instanceof Error?": "+V.message:"";throw new Error("bad point: is not on curve, sqrt error"+K)}a();const D=r.isOdd(re);return(H&1)===1!==D&&(re=r.neg(re)),{x:Z,y:re}}else if(U===R&&H===4){const Z=r.fromBytes(W.subarray(k*0,k*1)),Q=r.fromBytes(W.subarray(k*1,k*2));if(!d(Z,Q))throw new Error("bad point: is not on curve");return{x:Z,y:Q}}else throw new Error(`bad point: got length ${U}, expected compressed=${F} or uncompressed=${R}`)}const u=t.toBytes||c,f=t.fromBytes||l,p=mS(r,e.a,e.b);function d(j,k){const F=r.sqr(k),R=p(j);return r.eql(F,R)}if(!d(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const m=r.mul(r.pow(e.a,Ea),yS),g=r.mul(r.sqr(e.b),BigInt(27));if(r.is0(r.add(m,g)))throw new Error("bad curve params: a or b");function w(j,k,F=!1){if(!r.isValid(k)||F&&r.is0(k))throw new Error(`bad point coordinate ${j}`);return k}function A(j){if(!(j instanceof I))throw new Error("ProjectivePoint expected")}const T=bp((j,k)=>{const{px:F,py:R,pz:U}=j;if(r.eql(U,r.ONE))return{x:F,y:R};const H=j.is0();k==null&&(k=H?r.ONE:r.inv(U));const W=r.mul(F,k),Z=r.mul(R,k),Q=r.mul(U,k);if(H)return{x:r.ZERO,y:r.ZERO};if(!r.eql(Q,r.ONE))throw new Error("invZ was invalid");return{x:W,y:Z}}),E=bp(j=>{if(j.is0()){if(t.allowInfinityPoint&&!r.is0(j.py))return;throw new Error("bad point: ZERO")}const{x:k,y:F}=j.toAffine();if(!r.isValid(k)||!r.isValid(F))throw new Error("bad point: x or y not field elements");if(!d(k,F))throw new Error("bad point: equation left != right");if(!j.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(j,k,F,R,U){return F=new I(r.mul(F.px,j),F.py,F.pz),k=to(R,k),F=to(U,F),k.add(F)}class I{constructor(k,F,R){this.px=w("x",k),this.py=w("y",F,!0),this.pz=w("z",R),Object.freeze(this)}static fromAffine(k){const{x:F,y:R}=k||{};if(!k||!r.isValid(F)||!r.isValid(R))throw new Error("invalid affine point");if(k instanceof I)throw new Error("projective point not allowed");return r.is0(F)&&r.is0(R)?I.ZERO:new I(F,R,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(k){return oS(I,"pz",k)}static fromBytes(k){return lr(k),I.fromHex(k)}static fromHex(k){const F=I.fromAffine(f(Qt("pointHex",k)));return F.assertValidity(),F}static fromPrivateKey(k){const F=cb(n,t.allowedPrivateKeyLengths,t.wrapPrivateKey);return I.BASE.multiply(F(k))}static msm(k,F){return fS(I,n,k,F)}precompute(k=8,F=!0){return $.setWindowSize(this,k),F||this.multiply(Ea),this}_setWindowSize(k){this.precompute(k)}assertValidity(){E(this)}hasEvenY(){const{y:k}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(k)}equals(k){A(k);const{px:F,py:R,pz:U}=this,{px:H,py:W,pz:Z}=k,Q=r.eql(r.mul(F,Z),r.mul(H,U)),re=r.eql(r.mul(R,Z),r.mul(W,U));return Q&&re}negate(){return new I(this.px,r.neg(this.py),this.pz)}double(){const{a:k,b:F}=e,R=r.mul(F,Ea),{px:U,py:H,pz:W}=this;let Z=r.ZERO,Q=r.ZERO,re=r.ZERO,D=r.mul(U,U),B=r.mul(H,H),V=r.mul(W,W),K=r.mul(U,H);return K=r.add(K,K),re=r.mul(U,W),re=r.add(re,re),Z=r.mul(k,re),Q=r.mul(R,V),Q=r.add(Z,Q),Z=r.sub(B,Q),Q=r.add(B,Q),Q=r.mul(Z,Q),Z=r.mul(K,Z),re=r.mul(R,re),V=r.mul(k,V),K=r.sub(D,V),K=r.mul(k,K),K=r.add(K,re),re=r.add(D,D),D=r.add(re,D),D=r.add(D,V),D=r.mul(D,K),Q=r.add(Q,D),V=r.mul(H,W),V=r.add(V,V),D=r.mul(V,K),Z=r.sub(Z,D),re=r.mul(V,B),re=r.add(re,re),re=r.add(re,re),new I(Z,Q,re)}add(k){A(k);const{px:F,py:R,pz:U}=this,{px:H,py:W,pz:Z}=k;let Q=r.ZERO,re=r.ZERO,D=r.ZERO;const B=e.a,V=r.mul(e.b,Ea);let K=r.mul(F,H),O=r.mul(R,W),N=r.mul(U,Z),L=r.add(F,R),J=r.add(H,W);L=r.mul(L,J),J=r.add(K,O),L=r.sub(L,J),J=r.add(F,U);let ne=r.add(H,Z);return J=r.mul(J,ne),ne=r.add(K,N),J=r.sub(J,ne),ne=r.add(R,U),Q=r.add(W,Z),ne=r.mul(ne,Q),Q=r.add(O,N),ne=r.sub(ne,Q),D=r.mul(B,J),Q=r.mul(V,N),D=r.add(Q,D),Q=r.sub(O,D),D=r.add(O,D),re=r.mul(Q,D),O=r.add(K,K),O=r.add(O,K),N=r.mul(B,N),J=r.mul(V,J),O=r.add(O,N),N=r.sub(K,N),N=r.mul(B,N),J=r.add(J,N),K=r.mul(O,J),re=r.add(re,K),K=r.mul(ne,J),Q=r.mul(L,Q),Q=r.sub(Q,K),K=r.mul(L,O),D=r.mul(ne,D),D=r.add(D,K),new I(Q,re,D)}subtract(k){return this.add(k.negate())}is0(){return this.equals(I.ZERO)}multiply(k){const{endo:F}=t;if(!n.isValidNot0(k))throw new Error("invalid scalar: out of range");let R,U;const H=W=>$.wNAFCached(this,W,I.normalizeZ);if(F){const{k1neg:W,k1:Z,k2neg:Q,k2:re}=F.splitScalar(k),{p:D,f:B}=H(Z),{p:V,f:K}=H(re);U=B.add(K),R=S(F.beta,D,V,W,Q)}else{const{p:W,f:Z}=H(k);R=W,U=Z}return I.normalizeZ([R,U])[0]}multiplyUnsafe(k){const{endo:F}=t,R=this;if(!n.isValid(k))throw new Error("invalid scalar: out of range");if(k===ro||R.is0())return I.ZERO;if(k===no)return R;if($.hasPrecomputes(this))return this.multiply(k);if(F){const{k1neg:U,k1:H,k2neg:W,k2:Z}=F.splitScalar(k),{p1:Q,p2:re}=lS(I,R,H,Z);return S(F.beta,Q,re,U,W)}else return $.wNAFCachedUnsafe(R,k)}multiplyAndAddUnsafe(k,F,R){const U=this.multiplyUnsafe(F).add(k.multiplyUnsafe(R));return U.is0()?void 0:U}toAffine(k){return T(this,k)}isTorsionFree(){const{isTorsionFree:k}=t;return s===no?!0:k?k(I,this):$.wNAFCachedUnsafe(this,i).is0()}clearCofactor(){const{clearCofactor:k}=t;return s===no?this:k?k(I,this):this.multiplyUnsafe(s)}toBytes(k=!0){return tc("isCompressed",k),this.assertValidity(),u(I,this,k)}toRawBytes(k=!0){return this.toBytes(k)}toHex(k=!0){return mo(this.toBytes(k))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}I.BASE=new I(e.Gx,e.Gy,r.ONE),I.ZERO=new I(r.ZERO,r.ONE,r.ZERO),I.Fp=r,I.Fn=n;const P=n.BITS,$=uS(I,t.endo?Math.ceil(P/2):P);return I}function ub(e){return Uint8Array.of(e?2:3)}function bS(e,t,r={}){Wd(t,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=t.randomBytes||E2,s=t.hmac||((R,...U)=>Xg(t.hash,R,us(...U))),{Fp:i,Fn:o}=e,{ORDER:a,BITS:c}=o;function l(R){const U=a>>no;return R>U}function u(R){return l(R)?o.neg(R):R}function f(R,U){if(!o.isValidNot0(U))throw new Error(`invalid signature ${R}: out of range 1..CURVE.n`)}class p{constructor(U,H,W){f("r",U),f("s",H),this.r=U,this.s=H,W!=null&&(this.recovery=W),Object.freeze(this)}static fromCompact(U){const H=o.BYTES,W=Qt("compactSignature",U,H*2);return new p(o.fromBytes(W.subarray(0,H)),o.fromBytes(W.subarray(H,H*2)))}static fromDER(U){const{r:H,s:W}=un.toSig(Qt("DER",U));return new p(H,W)}assertValidity(){}addRecoveryBit(U){return new p(this.r,this.s,U)}recoverPublicKey(U){const H=i.ORDER,{r:W,s:Z,recovery:Q}=this;if(Q==null||![0,1,2,3].includes(Q))throw new Error("recovery id invalid");if(a*pS<H&&Q>1)throw new Error("recovery id is ambiguous for h>1 curve");const D=Q===2||Q===3?W+a:W;if(!i.isValid(D))throw new Error("recovery id 2 or 3 invalid");const B=i.toBytes(D),V=e.fromHex(us(ub((Q&1)===0),B)),K=o.inv(D),O=E(Qt("msgHash",U)),N=o.create(-O*K),L=o.create(Z*K),J=e.BASE.multiplyUnsafe(N).add(V.multiplyUnsafe(L));if(J.is0())throw new Error("point at infinify");return J.assertValidity(),J}hasHighS(){return l(this.s)}normalizeS(){return this.hasHighS()?new p(this.r,o.neg(this.s),this.recovery):this}toBytes(U){if(U==="compact")return us(o.toBytes(this.r),o.toBytes(this.s));if(U==="der")return ud(un.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return mo(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return mo(this.toBytes("compact"))}}const d=cb(o,r.allowedPrivateKeyLengths,r.wrapPrivateKey),m={isValidPrivateKey(R){try{return d(R),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{const R=a;return iS(n(ib(R)),R)},precompute(R=8,U=e.BASE){return U.precompute(R,!1)}};function g(R,U=!0){return e.fromPrivateKey(R).toBytes(U)}function w(R){if(typeof R=="bigint")return!1;if(R instanceof e)return!0;const H=Qt("key",R).length,W=i.BYTES,Z=W+1,Q=2*W+1;if(!(r.allowedPrivateKeyLengths||o.BYTES===Z))return H===Z||H===Q}function A(R,U,H=!0){if(w(R)===!0)throw new Error("first arg must be private key");if(w(U)===!1)throw new Error("second arg must be public key");return e.fromHex(U).multiply(d(R)).toBytes(H)}const T=t.bits2int||function(R){if(R.length>8192)throw new Error("input is too large");const U=Uc(R),H=R.length*8-c;return H>0?U>>BigInt(H):U},E=t.bits2int_modN||function(R){return o.create(T(R))},S=Mc(c);function I(R){return Kx("num < 2^"+c,R,ro,S),o.toBytes(R)}function P(R,U,H=$){if(["recovered","canonical"].some(L=>L in H))throw new Error("sign() legacy options not supported");const{hash:W}=t;let{lowS:Z,prehash:Q,extraEntropy:re}=H;Z==null&&(Z=!0),R=Qt("msgHash",R),Sp(H),Q&&(R=Qt("prehashed msgHash",W(R)));const D=E(R),B=d(U),V=[I(B),I(D)];if(re!=null&&re!==!1){const L=re===!0?n(i.BYTES):re;V.push(Qt("extraEntropy",L))}const K=us(...V),O=D;function N(L){const J=T(L);if(!o.isValidNot0(J))return;const ne=o.inv(J),fe=e.BASE.multiply(J).toAffine(),ce=o.create(fe.x);if(ce===ro)return;const oe=o.create(ne*o.create(O+ce*B));if(oe===ro)return;let ie=(fe.x===ce?0:2)|Number(fe.y&no),he=oe;return Z&&l(oe)&&(he=u(oe),ie^=1),new p(ce,he,ie)}return{seed:K,k2sig:N}}const $={lowS:t.lowS,prehash:!1},j={lowS:t.lowS,prehash:!1};function k(R,U,H=$){const{seed:W,k2sig:Z}=P(R,U,H);return Yx(t.hash.outputLen,o.BYTES,s)(W,Z)}e.BASE.precompute(8);function F(R,U,H,W=j){const Z=R;U=Qt("msgHash",U),H=Qt("publicKey",H),Sp(W);const{lowS:Q,prehash:re,format:D}=W;if("strict"in W)throw new Error("options.strict was renamed to lowS");if(D!==void 0&&!["compact","der","js"].includes(D))throw new Error('format must be "compact", "der" or "js"');const B=typeof Z=="string"||ad(Z),V=!B&&!D&&typeof Z=="object"&&Z!==null&&typeof Z.r=="bigint"&&typeof Z.s=="bigint";if(!B&&!V)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let K,O;try{if(V)if(D===void 0||D==="js")K=new p(Z.r,Z.s);else throw new Error("invalid format");if(B){try{D!=="compact"&&(K=p.fromDER(Z))}catch(he){if(!(he instanceof un.Err))throw he}!K&&D!=="der"&&(K=p.fromCompact(Z))}O=e.fromHex(H)}catch{return!1}if(!K||Q&&K.hasHighS())return!1;re&&(U=t.hash(U));const{r:N,s:L}=K,J=E(U),ne=o.inv(L),fe=o.create(J*ne),ce=o.create(N*ne),oe=e.BASE.multiplyUnsafe(fe).add(O.multiplyUnsafe(ce));return oe.is0()?!1:o.create(oe.x)===N}return Object.freeze({getPublicKey:g,getSharedSecret:A,sign:k,verify:F,utils:m,Point:e,Signature:p})}function wS(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=Fc(t.n,e.nBitLength),s={Fp:r,Fn:n,allowedPrivateKeyLengths:e.allowedPrivateKeyLengths,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,wrapPrivateKey:e.wrapPrivateKey,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function vS(e){const{CURVE:t,curveOpts:r}=wS(e),n={hash:e.hash,hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,ecdsaOpts:n}}function ES(e,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:e})}function AS(e){const{CURVE:t,curveOpts:r,ecdsaOpts:n}=vS(e),s=gS(t,r),i=bS(s,n,r);return ES(e,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function xS(e,t){const r=n=>AS({...e,hash:n});return{...r(t),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const rc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")};BigInt(0);const SS=BigInt(1),Of=BigInt(2),_p=(e,t)=>(e+t/Of)/t;function _S(e){const t=rc.p,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,f=Zt(u,r,t)*u%t,p=Zt(f,r,t)*u%t,d=Zt(p,Of,t)*l%t,m=Zt(d,s,t)*d%t,g=Zt(m,i,t)*m%t,w=Zt(g,a,t)*g%t,A=Zt(w,c,t)*w%t,T=Zt(A,a,t)*g%t,E=Zt(T,r,t)*u%t,S=Zt(E,o,t)*m%t,I=Zt(S,n,t)*l%t,P=Zt(I,Of,t);if(!Bf.eql(Bf.sqr(P),e))throw new Error("Cannot find square root");return P}const Bf=Fc(rc.p,void 0,void 0,{sqrt:_S}),lb=xS({...rc,Fp:Bf,lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=rc.n,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-SS*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=_p(i*e,t),c=_p(-n*e,t);let l=rr(e-a*r-c*s,t),u=rr(-a*n-c*i,t);const f=l>o,p=u>o;if(f&&(l=t-l),p&&(u=t-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:f,k1:l,k2neg:p,k2:u}}}},C0),kS=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:lb},Symbol.toStringTag,{value:"Module"}));function TS({r:e,s:t,to:r="hex",v:n,yParity:s}){const i=(()=>{if(s===0||s===1)return s;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),o=`0x${new lb.Signature(ot(e),ot(t)).toCompactHex()}${i===0?"1b":"1c"}`;return r==="hex"?o:Sr(o)}async function Kd(e,t){var f,p,d;const{address:r,factory:n,factoryData:s,hash:i,signature:o,universalSignatureVerifierAddress:a=(d=(p=(f=e.chain)==null?void 0:f.contracts)==null?void 0:p.universalSignatureVerifier)==null?void 0:d.address,...c}=t,l=xr(o)?o:typeof o=="object"&&"r"in o&&"s"in o?TS(o):Je(o),u=await(async()=>!n&&!s||ux(l)?l:lx({address:n,data:s,signature:l}))();try{const m=a?{to:a,data:dr({abi:up,functionName:"isValidSig",args:[r,i,u]}),...c}:{data:Ic({abi:up,args:[r,i,u],bytecode:P6}),...c},{data:g}=await se(e,ra,"call")(m);return t2(g??"0x0")}catch(m){try{if(ta(c0(r),await x0({hash:i,signature:o})))return!0}catch{}if(m instanceof A0)return!1;throw m}}async function IS(e,{address:t,message:r,factory:n,factoryData:s,signature:i,...o}){const a=Mg(r);return Kd(e,{address:t,factory:n,factoryData:s,hash:a,signature:i,...o})}async function PS(e,t){const{address:r,factory:n,factoryData:s,signature:i,message:o,primaryType:a,types:c,domain:l,...u}=t,f=$A({message:o,primaryType:a,types:c,domain:l});return Kd(e,{address:r,factory:n,factoryData:s,hash:f,signature:i,...u})}function fb(e,{emitOnBegin:t=!1,emitMissed:r=!1,onBlockNumber:n,onError:s,poll:i,pollingInterval:o=e.pollingInterval}){const a=typeof i<"u"?i:!(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 a?(()=>{const f=Ze(["watchBlockNumber",e.uid,t,r,o]);return vn(f,{onBlockNumber:n,onError:s},p=>Ci(async()=>{var d;try{const m=await se(e,na,"getBlockNumber")({cacheTime:0});if(c){if(m===c)return;if(m-c>1&&r)for(let g=c+1n;g<m;g++)p.onBlockNumber(g,c),c=g}(!c||m>c)&&(p.onBlockNumber(m,c),c=m)}catch(m){(d=p.onError)==null||d.call(p,m)}},{emitOnBegin:t,interval:o}))})():(()=>{const f=Ze(["watchBlockNumber",e.uid,t,r]);return vn(f,{onBlockNumber:n,onError:s},p=>{let d=!0,m=()=>d=!1;return(async()=>{try{const g=(()=>{if(e.transport.type==="fallback"){const A=e.transport.transports.find(T=>T.config.type==="webSocket"||T.config.type==="ipc");return A?A.value:e.transport}return e.transport})(),{unsubscribe:w}=await g.subscribe({params:["newHeads"],onData(A){var E;if(!d)return;const T=ot((E=A.result)==null?void 0:E.number);p.onBlockNumber(T,c),c=T},onError(A){var T;(T=p.onError)==null||T.call(p,A)}});m=w,d||m()}catch(g){s==null||s(g)}})(),()=>m()})})()}async function OS(e,t){const{checkReplacement:r=!0,confirmations:n=1,hash:s,onReplaced:i,retryCount:o=6,retryDelay:a=({count:I})=>~~(1<<I)*200,timeout:c=18e4}=t,l=Ze(["waitForTransactionReceipt",e.uid,s]),u=(()=>{var I;return t.pollingInterval?t.pollingInterval:(I=e.chain)!=null&&I.experimental_preconfirmationTime?e.chain.experimental_preconfirmationTime:e.pollingInterval})();let f,p,d,m=!1,g,w;const{promise:A,resolve:T,reject:E}=Ud(),S=c?setTimeout(()=>{w(),g(),E(new mE({hash:s}))},c):void 0;return g=vn(l,{onReplaced:i,resolve:T,reject:E},async I=>{if(d=await se(e,ja,"getTransactionReceipt")({hash:s}).catch(()=>{}),d&&n<=1){clearTimeout(S),I.resolve(d),g();return}w=se(e,fb,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:u,async onBlockNumber(P){const $=k=>{clearTimeout(S),w(),k(),g()};let j=P;if(!m)try{if(d){if(n>1&&(!d.blockNumber||j-d.blockNumber+1n<n))return;$(()=>I.resolve(d));return}if(r&&!f&&(m=!0,await ec(async()=>{f=await se(e,Hd,"getTransaction")({hash:s}),f.blockNumber&&(j=f.blockNumber)},{delay:a,retryCount:o}),m=!1),d=await se(e,ja,"getTransactionReceipt")({hash:s}),n>1&&(!d.blockNumber||j-d.blockNumber+1n<n))return;$(()=>I.resolve(d))}catch(k){if(k instanceof v0||k instanceof E0){if(!f){m=!1;return}try{p=f,m=!0;const F=await ec(()=>se(e,qr,"getBlock")({blockNumber:j,includeTransactions:!0}),{delay:a,retryCount:o,shouldRetry:({error:H})=>H instanceof T0});m=!1;const R=F.transactions.find(({from:H,nonce:W})=>H===p.from&&W===p.nonce);if(!R||(d=await se(e,ja,"getTransactionReceipt")({hash:R.hash}),n>1&&(!d.blockNumber||j-d.blockNumber+1n<n)))return;let U="replaced";R.to===p.to&&R.value===p.value&&R.input===p.input?U="repriced":R.from===R.to&&R.value===0n&&(U="cancelled"),$(()=>{var H;(H=I.onReplaced)==null||H.call(I,{reason:U,replacedTransaction:p,transaction:R,transactionReceipt:d}),I.resolve(d)})}catch(F){$(()=>I.reject(F))}}else $(()=>I.reject(k))}}})}),A}function BS(e,{blockTag:t=e.experimental_blockTag??"latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:s,onError:i,includeTransactions:o,poll:a,pollingInterval:c=e.pollingInterval}){const l=typeof a<"u"?a:!(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")),u=o??!1;let f;return l?(()=>{const m=Ze(["watchBlocks",e.uid,t,r,n,u,c]);return vn(m,{onBlock:s,onError:i},g=>Ci(async()=>{var w;try{const A=await se(e,qr,"getBlock")({blockTag:t,includeTransactions:u});if(A.number!==null&&(f==null?void 0:f.number)!=null){if(A.number===f.number)return;if(A.number-f.number>1&&r)for(let T=(f==null?void 0:f.number)+1n;T<A.number;T++){const E=await se(e,qr,"getBlock")({blockNumber:T,includeTransactions:u});g.onBlock(E,f),f=E}}((f==null?void 0:f.number)==null||t==="pending"&&(A==null?void 0:A.number)==null||A.number!==null&&A.number>f.number)&&(g.onBlock(A,f),f=A)}catch(A){(w=g.onError)==null||w.call(g,A)}},{emitOnBegin:n,interval:c}))})():(()=>{let m=!0,g=!0,w=()=>m=!1;return(async()=>{try{n&&se(e,qr,"getBlock")({blockTag:t,includeTransactions:u}).then(E=>{m&&g&&(s(E,void 0),g=!1)}).catch(i);const A=(()=>{if(e.transport.type==="fallback"){const E=e.transport.transports.find(S=>S.config.type==="webSocket"||S.config.type==="ipc");return E?E.value:e.transport}return e.transport})(),{unsubscribe:T}=await A.subscribe({params:["newHeads"],async onData(E){var I;if(!m)return;const S=await se(e,qr,"getBlock")({blockNumber:(I=E.result)==null?void 0:I.number,includeTransactions:u}).catch(()=>{});m&&(s(S,f),g=!1,f=S)},onError(E){i==null||i(E)}});w=T,m||w()}catch(A){i==null||i(A)}})(),()=>w()})()}function CS(e,{address:t,args:r,batch:n=!0,event:s,events:i,fromBlock:o,onError:a,onLogs:c,poll:l,pollingInterval:u=e.pollingInterval,strict:f}){const p=typeof l<"u"?l: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")),d=f??!1;return p?(()=>{const w=Ze(["watchEvent",t,r,n,e.uid,s,u,o]);return vn(w,{onLogs:c,onError:a},A=>{let T;o!==void 0&&(T=o-1n);let E,S=!1;const I=Ci(async()=>{var P;if(!S){try{E=await se(e,xg,"createEventFilter")({address:t,args:r,event:s,events:i,strict:d,fromBlock:o})}catch{}S=!0;return}try{let $;if(E)$=await se(e,Pc,"getFilterChanges")({filter:E});else{const j=await se(e,na,"getBlockNumber")({});T&&T!==j?$=await se(e,Bd,"getLogs")({address:t,args:r,event:s,events:i,fromBlock:T+1n,toBlock:j}):$=[],T=j}if($.length===0)return;if(n)A.onLogs($);else for(const j of $)A.onLogs([j])}catch($){E&&$ instanceof Ts&&(S=!1),(P=A.onError)==null||P.call(A,$)}},{emitOnBegin:!0,interval:u});return async()=>{E&&await se(e,Oc,"uninstallFilter")({filter:E}),I()}})})():(()=>{let w=!0,A=()=>w=!1;return(async()=>{try{const T=(()=>{if(e.transport.type==="fallback"){const P=e.transport.transports.find($=>$.config.type==="webSocket"||$.config.type==="ipc");return P?P.value:e.transport}return e.transport})(),E=i??(s?[s]:void 0);let S=[];E&&(S=[E.flatMap($=>Zo({abi:[$],eventName:$.name,args:r}))],s&&(S=S[0]));const{unsubscribe:I}=await T.subscribe({params:["logs",{address:t,topics:S}],onData(P){var j;if(!w)return;const $=P.result;try{const{eventName:k,args:F}=Pd({abi:E??[],data:$.data,topics:$.topics,strict:d}),R=wn($,{args:F,eventName:k});c([R])}catch(k){let F,R;if(k instanceof po||k instanceof pc){if(f)return;F=k.abiItem.name,R=(j=k.abiItem.inputs)==null?void 0:j.some(H=>!("name"in H&&H.name))}const U=wn($,{args:R?[]:{},eventName:F});c([U])}},onError(P){a==null||a(P)}});A=I,w||A()}catch(T){a==null||a(T)}})(),()=>A()})()}function RS(e,{batch:t=!0,onError:r,onTransactions:n,poll:s,pollingInterval:i=e.pollingInterval}){return(typeof s<"u"?s:e.transport.type!=="webSocket"&&e.transport.type!=="ipc")?(()=>{const l=Ze(["watchPendingTransactions",e.uid,t,i]);return vn(l,{onTransactions:n,onError:r},u=>{let f;const p=Ci(async()=>{var d;try{if(!f)try{f=await se(e,Sg,"createPendingTransactionFilter")({});return}catch(g){throw p(),g}const m=await se(e,Pc,"getFilterChanges")({filter:f});if(m.length===0)return;if(t)u.onTransactions(m);else for(const g of m)u.onTransactions([g])}catch(m){(d=u.onError)==null||d.call(u,m)}},{emitOnBegin:!0,interval:i});return async()=>{f&&await se(e,Oc,"uninstallFilter")({filter:f}),p()}})})():(()=>{let l=!0,u=()=>l=!1;return(async()=>{try{const{unsubscribe:f}=await e.transport.subscribe({params:["newPendingTransactions"],onData(p){if(!l)return;const d=p.result;n([d])},onError(p){r==null||r(p)}});u=f,l||u()}catch(f){r==null||r(f)}})(),()=>u()})()}function $S(e){var f,p,d;const{scheme:t,statement:r,...n}=((f=e.match(NS))==null?void 0:f.groups)??{},{chainId:s,expirationTime:i,issuedAt:o,notBefore:a,requestId:c,...l}=((p=e.match(US))==null?void 0:p.groups)??{},u=(d=e.split("Resources:")[1])==null?void 0:d.split(`
|
|
45
|
-
- `).slice(1);return{...n,...l,...s?{chainId:Number(s)}:{},...i?{expirationTime:new Date(i)}:{},...o?{issuedAt:new Date(o)}:{},...a?{notBefore:new Date(a)}:{},...c?{requestId:c}:{},...u?{resources:u}:{},...t?{scheme:t}:{},...r?{statement:r}:{}}}const NS=/^(?:(?<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)?/,US=/(?: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 MS(e){const{address:t,domain:r,message:n,nonce:s,scheme:i,time:o=new Date}=e;if(r&&n.domain!==r||s&&n.nonce!==s||i&&n.scheme!==i||n.expirationTime&&o>=n.expirationTime||n.notBefore&&o<n.notBefore)return!1;try{if(!n.address||!st(n.address,{strict:!1})||t&&!ta(n.address,t))return!1}catch{return!1}return!0}async function FS(e,t){const{address:r,domain:n,message:s,nonce:i,scheme:o,signature:a,time:c=new Date,...l}=t,u=$S(s);if(!u.address||!MS({address:r,domain:n,message:u,nonce:i,scheme:o,time:c}))return!1;const p=Mg(s);return Kd(e,{address:u.address,hash:p,signature:a,...l})}function jS(e){return{call:t=>ra(e,t),createAccessList:t=>Ag(e,t),createBlockFilter:()=>AA(e),createContractEventFilter:t=>pd(e,t),createEventFilter:t=>xg(e,t),createPendingTransactionFilter:()=>Sg(e),estimateContractGas:t=>z0(e,t),estimateGas:t=>Id(e,t),getBalance:t=>H0(e,t),getBlobBaseFee:()=>xA(e),getBlock:t=>qr(e,t),getBlockNumber:t=>na(e,t),getBlockTransactionCount:t=>SA(e,t),getBytecode:t=>yp(e,t),getChainId:()=>Oi(e),getCode:t=>yp(e,t),getContractEvents:t=>Cd(e,t),getEip712Domain:t=>kA(e,t),getEnsAddress:t=>oA(e,t),getEnsAvatar:t=>wA(e,t),getEnsName:t=>vA(e,t),getEnsResolver:t=>EA(e,t),getEnsText:t=>Eg(e,t),getFeeHistory:t=>PA(e,t),estimateFeesPerGas:t=>LE(e,t),getFilterChanges:t=>Pc(e,t),getFilterLogs:t=>OA(e,t),getGasPrice:()=>Ad(e),getLogs:t=>Bd(e,t),getProof:t=>hx(e,t),estimateMaxPriorityFeePerGas:t=>jE(e,t),getStorageAt:t=>px(e,t),getTransaction:t=>Hd(e,t),getTransactionConfirmations:t=>yx(e,t),getTransactionCount:t=>xd(e,t),getTransactionReceipt:t=>ja(e,t),multicall:t=>mx(e,t),prepareTransactionRequest:t=>kc(e,t),readContract:t=>Wr(e,t),sendRawTransaction:t=>Md(e,t),simulate:t=>xf(e,t),simulateBlocks:t=>xf(e,t),simulateCalls:t=>Gx(e,t),simulateContract:t=>ng(e,t),verifyMessage:t=>IS(e,t),verifySiweMessage:t=>FS(e,t),verifyTypedData:t=>PS(e,t),uninstallFilter:t=>Oc(e,t),waitForTransactionReceipt:t=>OS(e,t),watchBlocks:t=>BS(e,t),watchBlockNumber:t=>fb(e,t),watchContractEvent:t=>sg(e,t),watchEvent:t=>CS(e,t),watchPendingTransactions:t=>RS(e,t)}}function LS(e){const{key:t="public",name:r="Public Client"}=e;return pg({...e,key:t,name:r,type:"publicClient"}).extend(jS)}async function DS(e,{chain:t}){const{id:r,name:n,nativeCurrency:s,rpcUrls:i,blockExplorers:o}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:X(r),chainName:n,nativeCurrency:s,rpcUrls:i.default.http,blockExplorerUrls:o?Object.values(o).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}function HS(e,t){const{abi:r,args:n,bytecode:s,...i}=t,o=Ic({abi:r,args:n,bytecode:s});return Bc(e,{...i,...i.authorizationList?{to:null}:{},data:o})}async function zS(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=>Xo(n))}async function qS(e,t={}){const{account:r=e.account,chainId:n}=t,s=r?Xe(r):void 0,i=n?[s==null?void 0:s.address,[X(n)]]:[s==null?void 0:s.address],o=await e.request({method:"wallet_getCapabilities",params:i}),a={};for(const[c,l]of Object.entries(o)){a[Number(c)]={};for(let[u,f]of Object.entries(l))u==="addSubAccount"&&(u="unstable_addSubAccount"),a[Number(c)][u]=f}return typeof n=="number"?a[n]:a}async function VS(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}async function db(e,t){var c;const{account:r=e.account,chainId:n,nonce:s}=t;if(!r)throw new Ds({docsPath:"/docs/eip7702/prepareAuthorization"});const i=Xe(r),o=(()=>{if(t.executor)return t.executor==="self"?t.executor:Xe(t.executor)})(),a={address:t.contractAddress??t.address,chainId:n,nonce:s};return typeof a.chainId>"u"&&(a.chainId=((c=e.chain)==null?void 0:c.id)??await se(e,Oi,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await se(e,xd,"getTransactionCount")({address:i.address,blockTag:"pending"}),(o==="self"||o!=null&&o.address&&ta(o.address,i.address))&&(a.nonce+=1)),a}async function GS(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>c0(r))}async function WS(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}async function KS(e,t){const{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]})}async function XS(e,t){const{account:r=e.account}=t;if(!r)throw new Ds({docsPath:"/docs/eip7702/signAuthorization"});const n=Xe(r);if(!n.signAuthorization)throw new Ma({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});const s=await db(e,t);return n.signAuthorization(s)}async function YS(e,{account:t=e.account,message:r}){if(!t)throw new Ds({docsPath:"/docs/actions/wallet/signMessage"});const n=Xe(t);if(n.signMessage)return n.signMessage({message:r});const s=typeof r=="string"?mi(r):r.raw instanceof Uint8Array?mt(r.raw):r.raw;return e.request({method:"personal_sign",params:[s,n.address]},{retryCount:0})}async function ZS(e,t){var l,u,f,p;const{account:r=e.account,chain:n=e.chain,...s}=t;if(!r)throw new Ds({docsPath:"/docs/actions/wallet/signTransaction"});const i=Xe(r);js({account:i,...t});const o=await se(e,Oi,"getChainId")({});n!==null&&ig({currentChainId:o,chain:n});const a=(n==null?void 0:n.formatters)||((l=e.chain)==null?void 0:l.formatters),c=((u=a==null?void 0:a.transactionRequest)==null?void 0:u.format)||Pi;return i.signTransaction?i.signTransaction({...s,chainId:o},{serializer:(p=(f=e.chain)==null?void 0:f.serializers)==null?void 0:p.transaction}):await e.request({method:"eth_signTransaction",params:[{...c(s),chainId:X(o),from:i.address}]},{retryCount:0})}async function JS(e,t){const{account:r=e.account,domain:n,message:s,primaryType:i}=t;if(!r)throw new Ds({docsPath:"/docs/actions/wallet/signTypedData"});const o=Xe(r),a={EIP712Domain:Og({domain:n}),...t.types};if(Pg({domain:n,message:s,primaryType:i,types:a}),o.signTypedData)return o.signTypedData({domain:n,message:s,primaryType:i,types:a});const c=FA({domain:n,message:s,primaryType:i,types:a});return e.request({method:"eth_signTypedData_v4",params:[o.address,c]},{retryCount:0})}async function QS(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:X(t)}]},{retryCount:0})}async function e_(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}function t_(e){return{addChain:t=>DS(e,t),deployContract:t=>HS(e,t),getAddresses:()=>zS(e),getCallsStatus:t=>dg(e,t),getCapabilities:t=>qS(e,t),getChainId:()=>Oi(e),getPermissions:()=>VS(e),prepareAuthorization:t=>db(e,t),prepareTransactionRequest:t=>kc(e,t),requestAddresses:()=>GS(e),requestPermissions:t=>WS(e,t),sendCalls:t=>V6(e,t),sendRawTransaction:t=>Md(e,t),sendTransaction:t=>Bc(e,t),showCallsStatus:t=>KS(e,t),signAuthorization:t=>XS(e,t),signMessage:t=>YS(e,t),signTransaction:t=>ZS(e,t),signTypedData:t=>JS(e,t),switchChain:t=>QS(e,t),waitForCallsStatus:t=>G6(e,t),watchAsset:t=>e_(e,t),writeContract:t=>ag(e,t)}}function ku(e){const{key:t="wallet",name:r="Wallet Client",transport:n}=e;return pg({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(t_)}const La={mainnet:{orderbook:"https://api.garden.finance/orders",auth:"https://api.garden.finance/auth",quote:"https://api.garden.finance/quote",info:"https://api.garden.finance/info",evmRelay:"https://api.garden.finance/relayer",solanaRelay:"https://solana-relayer.garden.finance/",starknetRelay:"https://api.garden.finance/starknet",suiRelay:"https://sui-relayer-mainnet.garden.finance/"},testnet:{orderbook:"https://testnet.api.garden.finance/orders",auth:"https://testnet.api.garden.finance/auth",quote:"https://testnet.api.garden.finance/quote",info:"https://testnet.api.garden.finance/info",evmRelay:"https://testnet.api.garden.finance/relayer",solanaRelay:"https://solana-relay.garden.finance",starknetRelay:"https://testnet.api.garden.finance/starknet",suiRelay:"https://testnet.api.garden.finance/sui"},localnet:{orderbook:"",auth:"",quote:"",info:"",evmRelay:"",starknetRelay:"",solanaRelay:"",suiRelay:""}},Mo={[v.Network.MAINNET]:{chainId:"0x534e5f4d41494e",nodeUrl:"https://starknet-mainnet.public.blastapi.io/rpc/v0_8"},[v.Network.TESTNET]:{chainId:"0x534e5f5345504f4c4941",nodeUrl:"https://starknet-sepolia.public.blastapi.io/rpc/v0_8"},[v.Network.LOCALNET]:{chainId:"",nodeUrl:""}},Cf={[v.Network.MAINNET]:"9cBuPNiHXiMNg3Fin8xLCGJQBTXjYQTFtyaFQv2uiM1H",[v.Network.TESTNET]:"ANUVKxeqaec3bf4DVPqLTnG1PT3Fng56wPcE7LXAb46Q",[v.Network.LOCALNET]:"AKnL4NNf3DGWZJS6cPknBuEGnVsV4A4m5tgebLHaRSZ9"},Rf={mainnet:{native:"2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",spl:"gdnvdMCHJgnidtU7SL8RkRshHPvDJU1pdfZEpoLvqdU"},staging:{native:"6eksgdCnSjUaGQWZ6iYvauv1qzvYPF33RTGTM1ZuyENx",spl:"2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC"}},kp={[v.Network.TESTNET]:{packageId:"0x99865b03dd1bc03d0a6a805c454ea257c464f7abcccae9cd4b621b91e7ca04de",moduleName:"AtomicSwap"},[v.Network.MAINNET]:{packageId:"0xbfb5728aab0dd117747ef4574af6d3540ea6093109c22856e3ae201dfd58c0fc",moduleName:"AtomicSwap"},[v.Network.LOCALNET]:{packageId:"",moduleName:""}},Tp={chain:be.SupportedAssets.mainnet.base_cbBTC.chain,asset:be.SupportedAssets.mainnet.base_cbBTC.atomicSwapAddress};var li=(e=>(e.SLOW="SLOW",e.MEDIUM="MEDIUM",e.FAST="FAST",e))(li||{}),Ht=(e=>(e.Mainnet="Mainnet",e.Testnet="Testnet",e.Regtest="Regtest",e))(Ht||{}),Da=(e=>(e.ALL="ALL",e.IN="IN",e.OUT="OUT",e))(Da||{});const r_={SLOW:"economyFee",MEDIUM:"hourFee",FAST:"fastestFee"};function $f(e){const t=typeof e=="string"?e:e.environment,r=t===v.Environment.MAINNET?La.mainnet:v.Environment.TESTNET?La.testnet:La.localnet;return{api:typeof e=="string"?r:{...r,...e},environment:t}}function Nf(e){return typeof e=="string"&&(e=Buffer.from(e,"hex")),e.length===32?e:e.subarray(1,33)}function Xs(e,t){if(!e)throw new Error(t)}function n_(e){return Buffer.concat([Uint8Array.from([192]),s_(e)])}function s_(e){const t=Ch.encodingLength(e.length),r=Buffer.allocUnsafe(t);return Ch.encode(e.length,r),Buffer.concat([r,e])}function i_(e,t){if(e.compare(t)>0){const r=e;e=t,t=r}return[e,t]}const Fn=e=>e.length===64?e:e.slice(2),o_=e=>{if(!e)return!1;try{const t=Buffer.from(e,"hex");return ar.isPoint(t)}catch{return!1}},Uf=(e,t,r,n)=>e+":"+t.toLowerCase()+"::"+r+":"+n.toLowerCase();function a_(e,t){if(!e)return!1;const r=t===v.Environment.MAINNET?Se.networks.bitcoin:t===v.Environment.TESTNET?Se.networks.testnet:Se.networks.regtest;if(!r)return!1;Se.initEccLib(ar);try{return Se.address.toOutputScript(e,r),!0}catch{return!1}}const c_=e=>{switch(e){case v.Environment.MAINNET:return Ht.Mainnet;case v.Environment.TESTNET:return Ht.Testnet;case v.Environment.LOCALNET:return Ht.Regtest;default:throw new Error(`Invalid bitcoin network ${e}`)}},u_=e=>{const t=e.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(t)},l_=e=>{if(typeof e=="object"&&"r"in e&&"s"in e)return v.Ok([e.r.toString(),e.s.toString()]);if(Array.isArray(e)){const t=e.map(r=>typeof r=="string"&&r.startsWith("0x")&&u_(r)?BigInt(r).toString():r);return v.Ok(t)}return v.Err("Invalid signature format")};function Mf(e){return Buffer.from(e,"hex").reverse()}function Ff(e){return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"}const Tu=async(e,t)=>{const r=Date.now(),n=3e4,s=2e3;for(;Date.now()-r<n;){const i=await e.getLatestBlockhash(),o=await e.confirmTransaction({signature:t,blockhash:i.blockhash,lastValidBlockHeight:i.lastValidBlockHeight},"confirmed");if(o.value&&o.value.err==null)return console.log("Tx Confirmed ✅",t),!0;console.log("Tx not confirmed yet. Retrying in 2 seconds..."),await new Promise(a=>setTimeout(a,s))}return!1};var ge=(e=>(e.Created="Created",e.Matched="Matched",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.CounterPartyInitiateDetected="CounterPartyInitiateDetected",e.CounterPartyInitiated="CounterPartyInitiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.CounterPartyRedeemDetected="CounterPartyRedeemDetected",e.CounterPartyRedeemed="CounterPartyRedeemed",e.Completed="Completed",e.CounterPartySwapExpired="CounterPartySwapExpired",e.Expired="Expired",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.CounterPartyRefundDetected="CounterPartyRefundDetected",e.CounterPartyRefunded="CounterPartyRefunded",e.Cancelled="Cancelled",e.DeadLineExceeded="DeadLineExceeded",e))(ge||{}),Ne=(e=>(e.Idle="Idle",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.Expired="Expired",e))(Ne||{});const Xd=(e,t,r)=>{const n=jf(e.source_swap,t),s=jf(e.destination_swap,r);if(s===Ne.RedeemDetected)return ge.RedeemDetected;if(s===Ne.Redeemed)return ge.Redeemed;if(n===Ne.Refunded)return ge.Refunded;if(n===Ne.RefundDetected)return ge.RefundDetected;if(s===Ne.Expired)return ge.CounterPartySwapExpired;if(n===Ne.Expired)return ge.Expired;if(s===Ne.Refunded)return ge.CounterPartyRefunded;if(s===Ne.RefundDetected)return ge.CounterPartyRefundDetected;const i=Number(e.create_order.additional_data.deadline);return s===Ne.Initiated?ge.CounterPartyInitiated:s===Ne.InitiateDetected?ge.CounterPartyInitiateDetected:Fo(i,0)?ge.DeadLineExceeded:n===Ne.Initiated?ge.Initiated:Fo(i,0)?ge.DeadLineExceeded:n===Ne.InitiateDetected?ge.InitiateDetected:n===Ne.Redeemed?ge.CounterPartyRedeemed:n===Ne.RedeemDetected?ge.CounterPartyRedeemDetected:ge.Matched},jf=(e,t)=>{if(e.redeem_tx_hash)return Number(e.redeem_block_number)?Ne.Redeemed:Ne.RedeemDetected;if(e.refund_tx_hash)return Number(e.refund_block_number)?Ne.Refunded:Ne.RefundDetected;if(Number(e.initiate_block_number)){const r=Number(e.initiate_block_number)+e.timelock;if(t>r)return Ne.Expired}return e.initiate_tx_hash?Number(e.initiate_block_number)?Ne.Initiated:Ne.InitiateDetected:Ne.Idle},f_=(e,t,r)=>{const n=Xd(e,t,r);return Yd(n)},Yd=e=>{switch(e){case ge.Matched:return Ae.Initiate;case ge.CounterPartyInitiated:case ge.CounterPartyInitiateDetected:case ge.RedeemDetected:return Ae.Redeem;case ge.Expired:return Ae.Refund;default:return Ae.Idle}},Fo=(e,t=0)=>{const r=Date.now(),n=e*1e3+t*36e5;return r>=n},d_=e=>e.filter(t=>!hb(t)),hb=e=>{const{source_swap:t,create_order:r}=e,{initiate_tx_hash:n,initiate_block_number:s}=t,{deadline:i}=r.additional_data;return n&&Number(s)?!1:n&&!Number(s)?Fo(Number(i),12):n?!1:Fo(Number(i),1)},h_=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),p_=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),y_=Buffer.concat([h_,p_]),m_=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),Ip={failedToCreateInternalPubkey:"failed to create internal pubkey"};function g_(){const e=pe.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),t=ar.pointMultiply(Buffer.concat([Buffer.from("04","hex"),y_]),e);if(!t)throw new Error(Ip.failedToCreateInternalPubkey);const r=ar.pointAdd(m_,t);if(!r)throw new Error(Ip.failedToCreateInternalPubkey);return Nf(Buffer.from(r))}var Kr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function pb(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,s.get?s:{enumerable:!0,get:function(){return e[n]}})}),r}var Le={},wt={},Hs={},jc={};jc.byteLength=v_;jc.toByteArray=A_;jc.fromByteArray=__;var Hr=[],er=[],b_=typeof Uint8Array<"u"?Uint8Array:Array,Iu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var Ys=0,w_=Iu.length;Ys<w_;++Ys)Hr[Ys]=Iu[Ys],er[Iu.charCodeAt(Ys)]=Ys;er[45]=62;er[95]=63;function yb(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 v_(e){var t=yb(e),r=t[0],n=t[1];return(r+n)*3/4-n}function E_(e,t,r){return(t+r)*3/4-r}function A_(e){var t,r=yb(e),n=r[0],s=r[1],i=new b_(E_(e,n,s)),o=0,a=s>0?n-4:n,c;for(c=0;c<a;c+=4)t=er[e.charCodeAt(c)]<<18|er[e.charCodeAt(c+1)]<<12|er[e.charCodeAt(c+2)]<<6|er[e.charCodeAt(c+3)],i[o++]=t>>16&255,i[o++]=t>>8&255,i[o++]=t&255;return s===2&&(t=er[e.charCodeAt(c)]<<2|er[e.charCodeAt(c+1)]>>4,i[o++]=t&255),s===1&&(t=er[e.charCodeAt(c)]<<10|er[e.charCodeAt(c+1)]<<4|er[e.charCodeAt(c+2)]>>2,i[o++]=t>>8&255,i[o++]=t&255),i}function x_(e){return Hr[e>>18&63]+Hr[e>>12&63]+Hr[e>>6&63]+Hr[e&63]}function S_(e,t,r){for(var n,s=[],i=t;i<r;i+=3)n=(e[i]<<16&16711680)+(e[i+1]<<8&65280)+(e[i+2]&255),s.push(x_(n));return s.join("")}function __(e){for(var t,r=e.length,n=r%3,s=[],i=16383,o=0,a=r-n;o<a;o+=i)s.push(S_(e,o,o+i>a?a:o+i));return n===1?(t=e[r-1],s.push(Hr[t>>2]+Hr[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],s.push(Hr[t>>10]+Hr[t>>4&63]+Hr[t<<2&63]+"=")),s.join("")}var Zd={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Zd.read=function(e,t,r,n,s){var i,o,a=s*8-n-1,c=(1<<a)-1,l=c>>1,u=-7,f=r?s-1:0,p=r?-1:1,d=e[t+f];for(f+=p,i=d&(1<<-u)-1,d>>=-u,u+=a;u>0;i=i*256+e[t+f],f+=p,u-=8);for(o=i&(1<<-u)-1,i>>=-u,u+=n;u>0;o=o*256+e[t+f],f+=p,u-=8);if(i===0)i=1-l;else{if(i===c)return o?NaN:(d?-1:1)*(1/0);o=o+Math.pow(2,n),i=i-l}return(d?-1:1)*o*Math.pow(2,i-n)};Zd.write=function(e,t,r,n,s,i){var o,a,c,l=i*8-s-1,u=(1<<l)-1,f=u>>1,p=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,m=n?1:-1,g=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+f>=1?t+=p/c:t+=p*Math.pow(2,1-f),t*c>=2&&(o++,c/=2),o+f>=u?(a=0,o=u):o+f>=1?(a=(t*c-1)*Math.pow(2,s),o=o+f):(a=t*Math.pow(2,f-1)*Math.pow(2,s),o=0));s>=8;e[r+d]=a&255,d+=m,a/=256,s-=8);for(o=o<<s|a,l+=s;l>0;e[r+d]=o&255,d+=m,o/=256,l-=8);e[r+d-m]|=g*128};/*!
|
|
45
|
+
- `).slice(1);return{...n,...l,...s?{chainId:Number(s)}:{},...i?{expirationTime:new Date(i)}:{},...o?{issuedAt:new Date(o)}:{},...a?{notBefore:new Date(a)}:{},...c?{requestId:c}:{},...u?{resources:u}:{},...t?{scheme:t}:{},...r?{statement:r}:{}}}const NS=/^(?:(?<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)?/,US=/(?: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 MS(e){const{address:t,domain:r,message:n,nonce:s,scheme:i,time:o=new Date}=e;if(r&&n.domain!==r||s&&n.nonce!==s||i&&n.scheme!==i||n.expirationTime&&o>=n.expirationTime||n.notBefore&&o<n.notBefore)return!1;try{if(!n.address||!st(n.address,{strict:!1})||t&&!ta(n.address,t))return!1}catch{return!1}return!0}async function FS(e,t){const{address:r,domain:n,message:s,nonce:i,scheme:o,signature:a,time:c=new Date,...l}=t,u=$S(s);if(!u.address||!MS({address:r,domain:n,message:u,nonce:i,scheme:o,time:c}))return!1;const p=Mg(s);return Kd(e,{address:u.address,hash:p,signature:a,...l})}function jS(e){return{call:t=>ra(e,t),createAccessList:t=>Ag(e,t),createBlockFilter:()=>AA(e),createContractEventFilter:t=>pd(e,t),createEventFilter:t=>xg(e,t),createPendingTransactionFilter:()=>Sg(e),estimateContractGas:t=>z0(e,t),estimateGas:t=>Id(e,t),getBalance:t=>H0(e,t),getBlobBaseFee:()=>xA(e),getBlock:t=>qr(e,t),getBlockNumber:t=>na(e,t),getBlockTransactionCount:t=>SA(e,t),getBytecode:t=>yp(e,t),getChainId:()=>Oi(e),getCode:t=>yp(e,t),getContractEvents:t=>Cd(e,t),getEip712Domain:t=>kA(e,t),getEnsAddress:t=>oA(e,t),getEnsAvatar:t=>wA(e,t),getEnsName:t=>vA(e,t),getEnsResolver:t=>EA(e,t),getEnsText:t=>Eg(e,t),getFeeHistory:t=>PA(e,t),estimateFeesPerGas:t=>LE(e,t),getFilterChanges:t=>Pc(e,t),getFilterLogs:t=>OA(e,t),getGasPrice:()=>Ad(e),getLogs:t=>Bd(e,t),getProof:t=>hx(e,t),estimateMaxPriorityFeePerGas:t=>jE(e,t),getStorageAt:t=>px(e,t),getTransaction:t=>Hd(e,t),getTransactionConfirmations:t=>yx(e,t),getTransactionCount:t=>xd(e,t),getTransactionReceipt:t=>ja(e,t),multicall:t=>mx(e,t),prepareTransactionRequest:t=>kc(e,t),readContract:t=>Wr(e,t),sendRawTransaction:t=>Md(e,t),simulate:t=>xf(e,t),simulateBlocks:t=>xf(e,t),simulateCalls:t=>Gx(e,t),simulateContract:t=>ng(e,t),verifyMessage:t=>IS(e,t),verifySiweMessage:t=>FS(e,t),verifyTypedData:t=>PS(e,t),uninstallFilter:t=>Oc(e,t),waitForTransactionReceipt:t=>OS(e,t),watchBlocks:t=>BS(e,t),watchBlockNumber:t=>fb(e,t),watchContractEvent:t=>sg(e,t),watchEvent:t=>CS(e,t),watchPendingTransactions:t=>RS(e,t)}}function LS(e){const{key:t="public",name:r="Public Client"}=e;return pg({...e,key:t,name:r,type:"publicClient"}).extend(jS)}async function DS(e,{chain:t}){const{id:r,name:n,nativeCurrency:s,rpcUrls:i,blockExplorers:o}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:X(r),chainName:n,nativeCurrency:s,rpcUrls:i.default.http,blockExplorerUrls:o?Object.values(o).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}function HS(e,t){const{abi:r,args:n,bytecode:s,...i}=t,o=Ic({abi:r,args:n,bytecode:s});return Bc(e,{...i,...i.authorizationList?{to:null}:{},data:o})}async function zS(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=>Xo(n))}async function qS(e,t={}){const{account:r=e.account,chainId:n}=t,s=r?Xe(r):void 0,i=n?[s==null?void 0:s.address,[X(n)]]:[s==null?void 0:s.address],o=await e.request({method:"wallet_getCapabilities",params:i}),a={};for(const[c,l]of Object.entries(o)){a[Number(c)]={};for(let[u,f]of Object.entries(l))u==="addSubAccount"&&(u="unstable_addSubAccount"),a[Number(c)][u]=f}return typeof n=="number"?a[n]:a}async function VS(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}async function db(e,t){var c;const{account:r=e.account,chainId:n,nonce:s}=t;if(!r)throw new Ds({docsPath:"/docs/eip7702/prepareAuthorization"});const i=Xe(r),o=(()=>{if(t.executor)return t.executor==="self"?t.executor:Xe(t.executor)})(),a={address:t.contractAddress??t.address,chainId:n,nonce:s};return typeof a.chainId>"u"&&(a.chainId=((c=e.chain)==null?void 0:c.id)??await se(e,Oi,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await se(e,xd,"getTransactionCount")({address:i.address,blockTag:"pending"}),(o==="self"||o!=null&&o.address&&ta(o.address,i.address))&&(a.nonce+=1)),a}async function GS(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>c0(r))}async function WS(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}async function KS(e,t){const{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]})}async function XS(e,t){const{account:r=e.account}=t;if(!r)throw new Ds({docsPath:"/docs/eip7702/signAuthorization"});const n=Xe(r);if(!n.signAuthorization)throw new Ma({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});const s=await db(e,t);return n.signAuthorization(s)}async function YS(e,{account:t=e.account,message:r}){if(!t)throw new Ds({docsPath:"/docs/actions/wallet/signMessage"});const n=Xe(t);if(n.signMessage)return n.signMessage({message:r});const s=typeof r=="string"?mi(r):r.raw instanceof Uint8Array?gt(r.raw):r.raw;return e.request({method:"personal_sign",params:[s,n.address]},{retryCount:0})}async function ZS(e,t){var l,u,f,p;const{account:r=e.account,chain:n=e.chain,...s}=t;if(!r)throw new Ds({docsPath:"/docs/actions/wallet/signTransaction"});const i=Xe(r);js({account:i,...t});const o=await se(e,Oi,"getChainId")({});n!==null&&ig({currentChainId:o,chain:n});const a=(n==null?void 0:n.formatters)||((l=e.chain)==null?void 0:l.formatters),c=((u=a==null?void 0:a.transactionRequest)==null?void 0:u.format)||Pi;return i.signTransaction?i.signTransaction({...s,chainId:o},{serializer:(p=(f=e.chain)==null?void 0:f.serializers)==null?void 0:p.transaction}):await e.request({method:"eth_signTransaction",params:[{...c(s),chainId:X(o),from:i.address}]},{retryCount:0})}async function JS(e,t){const{account:r=e.account,domain:n,message:s,primaryType:i}=t;if(!r)throw new Ds({docsPath:"/docs/actions/wallet/signTypedData"});const o=Xe(r),a={EIP712Domain:Og({domain:n}),...t.types};if(Pg({domain:n,message:s,primaryType:i,types:a}),o.signTypedData)return o.signTypedData({domain:n,message:s,primaryType:i,types:a});const c=FA({domain:n,message:s,primaryType:i,types:a});return e.request({method:"eth_signTypedData_v4",params:[o.address,c]},{retryCount:0})}async function QS(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:X(t)}]},{retryCount:0})}async function e_(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}function t_(e){return{addChain:t=>DS(e,t),deployContract:t=>HS(e,t),getAddresses:()=>zS(e),getCallsStatus:t=>dg(e,t),getCapabilities:t=>qS(e,t),getChainId:()=>Oi(e),getPermissions:()=>VS(e),prepareAuthorization:t=>db(e,t),prepareTransactionRequest:t=>kc(e,t),requestAddresses:()=>GS(e),requestPermissions:t=>WS(e,t),sendCalls:t=>V6(e,t),sendRawTransaction:t=>Md(e,t),sendTransaction:t=>Bc(e,t),showCallsStatus:t=>KS(e,t),signAuthorization:t=>XS(e,t),signMessage:t=>YS(e,t),signTransaction:t=>ZS(e,t),signTypedData:t=>JS(e,t),switchChain:t=>QS(e,t),waitForCallsStatus:t=>G6(e,t),watchAsset:t=>e_(e,t),writeContract:t=>ag(e,t)}}function ku(e){const{key:t="wallet",name:r="Wallet Client",transport:n}=e;return pg({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(t_)}const La={mainnet:{orderbook:"https://api.garden.finance/orders",auth:"https://api.garden.finance/auth",quote:"https://api.garden.finance/quote",info:"https://api.garden.finance/info",evmRelay:"https://api.garden.finance/relayer",solanaRelay:"https://solana-relayer.garden.finance/",starknetRelay:"https://api.garden.finance/starknet",suiRelay:"https://sui-relayer-mainnet.garden.finance/"},testnet:{orderbook:"https://testnet.api.garden.finance/orders",auth:"https://testnet.api.garden.finance/auth",quote:"https://testnet.api.garden.finance/quote",info:"https://testnet.api.garden.finance/info",evmRelay:"https://testnet.api.garden.finance/relayer",solanaRelay:"https://solana-relay.garden.finance",starknetRelay:"https://testnet.api.garden.finance/starknet",suiRelay:"https://testnet.api.garden.finance/sui"},localnet:{orderbook:"",auth:"",quote:"",info:"",evmRelay:"",starknetRelay:"",solanaRelay:"",suiRelay:""}},Mo={[v.Network.MAINNET]:{chainId:"0x534e5f4d41494e",nodeUrl:"https://starknet-mainnet.public.blastapi.io/rpc/v0_8"},[v.Network.TESTNET]:{chainId:"0x534e5f5345504f4c4941",nodeUrl:"https://starknet-sepolia.public.blastapi.io/rpc/v0_8"},[v.Network.LOCALNET]:{chainId:"",nodeUrl:""}},Cf={[v.Network.MAINNET]:"9cBuPNiHXiMNg3Fin8xLCGJQBTXjYQTFtyaFQv2uiM1H",[v.Network.TESTNET]:"ANUVKxeqaec3bf4DVPqLTnG1PT3Fng56wPcE7LXAb46Q",[v.Network.LOCALNET]:"AKnL4NNf3DGWZJS6cPknBuEGnVsV4A4m5tgebLHaRSZ9"},Rf={mainnet:{native:"2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",spl:"gdnvdMCHJgnidtU7SL8RkRshHPvDJU1pdfZEpoLvqdU"},staging:{native:"6eksgdCnSjUaGQWZ6iYvauv1qzvYPF33RTGTM1ZuyENx",spl:"2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC"}},kp={[v.Network.TESTNET]:{packageId:"0x99865b03dd1bc03d0a6a805c454ea257c464f7abcccae9cd4b621b91e7ca04de",moduleName:"AtomicSwap"},[v.Network.MAINNET]:{packageId:"0xbfb5728aab0dd117747ef4574af6d3540ea6093109c22856e3ae201dfd58c0fc",moduleName:"AtomicSwap"},[v.Network.LOCALNET]:{packageId:"",moduleName:""}},Tp={chain:be.SupportedAssets.mainnet.base_cbBTC.chain,asset:be.SupportedAssets.mainnet.base_cbBTC.atomicSwapAddress};var li=(e=>(e.SLOW="SLOW",e.MEDIUM="MEDIUM",e.FAST="FAST",e))(li||{}),Ht=(e=>(e.Mainnet="Mainnet",e.Testnet="Testnet",e.Regtest="Regtest",e))(Ht||{}),Da=(e=>(e.ALL="ALL",e.IN="IN",e.OUT="OUT",e))(Da||{});const r_={SLOW:"economyFee",MEDIUM:"hourFee",FAST:"fastestFee"};function $f(e){const t=typeof e=="string"?e:e.environment,r=t===v.Environment.MAINNET?La.mainnet:v.Environment.TESTNET?La.testnet:La.localnet;return{api:typeof e=="string"?r:{...r,...e},environment:t}}function Nf(e){return typeof e=="string"&&(e=Buffer.from(e,"hex")),e.length===32?e:e.subarray(1,33)}function Xs(e,t){if(!e)throw new Error(t)}function n_(e){return Buffer.concat([Uint8Array.from([192]),s_(e)])}function s_(e){const t=Ch.encodingLength(e.length),r=Buffer.allocUnsafe(t);return Ch.encode(e.length,r),Buffer.concat([r,e])}function i_(e,t){if(e.compare(t)>0){const r=e;e=t,t=r}return[e,t]}const Fn=e=>e.length===64?e:e.slice(2),o_=e=>{if(!e)return!1;try{const t=Buffer.from(e,"hex");return ar.isPoint(t)}catch{return!1}},Uf=(e,t,r,n)=>e+":"+t.toLowerCase()+"::"+r+":"+n.toLowerCase();function a_(e,t){if(!e)return!1;const r=t===v.Environment.MAINNET?Se.networks.bitcoin:t===v.Environment.TESTNET?Se.networks.testnet:Se.networks.regtest;if(!r)return!1;Se.initEccLib(ar);try{return Se.address.toOutputScript(e,r),!0}catch{return!1}}const c_=e=>{switch(e){case v.Environment.MAINNET:return Ht.Mainnet;case v.Environment.TESTNET:return Ht.Testnet;case v.Environment.LOCALNET:return Ht.Regtest;default:throw new Error(`Invalid bitcoin network ${e}`)}},u_=e=>{const t=e.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(t)},l_=e=>{if(typeof e=="object"&&"r"in e&&"s"in e)return v.Ok([e.r.toString(),e.s.toString()]);if(Array.isArray(e)){const t=e.map(r=>typeof r=="string"&&r.startsWith("0x")&&u_(r)?BigInt(r).toString():r);return v.Ok(t)}return v.Err("Invalid signature format")};function Mf(e){return Buffer.from(e,"hex").reverse()}function Ff(e){return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"}const Tu=async(e,t)=>{const r=Date.now(),n=3e4,s=2e3;for(;Date.now()-r<n;){const i=await e.getLatestBlockhash(),o=await e.confirmTransaction({signature:t,blockhash:i.blockhash,lastValidBlockHeight:i.lastValidBlockHeight},"confirmed");if(o.value&&o.value.err==null)return console.log("Tx Confirmed ✅",t),!0;console.log("Tx not confirmed yet. Retrying in 2 seconds..."),await new Promise(a=>setTimeout(a,s))}return!1};var ge=(e=>(e.Created="Created",e.Matched="Matched",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.CounterPartyInitiateDetected="CounterPartyInitiateDetected",e.CounterPartyInitiated="CounterPartyInitiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.CounterPartyRedeemDetected="CounterPartyRedeemDetected",e.CounterPartyRedeemed="CounterPartyRedeemed",e.Completed="Completed",e.CounterPartySwapExpired="CounterPartySwapExpired",e.Expired="Expired",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.CounterPartyRefundDetected="CounterPartyRefundDetected",e.CounterPartyRefunded="CounterPartyRefunded",e.Cancelled="Cancelled",e.DeadLineExceeded="DeadLineExceeded",e))(ge||{}),Ne=(e=>(e.Idle="Idle",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.Expired="Expired",e))(Ne||{});const Xd=(e,t,r)=>{const n=jf(e.source_swap,t),s=jf(e.destination_swap,r);if(s===Ne.RedeemDetected)return ge.RedeemDetected;if(s===Ne.Redeemed)return ge.Redeemed;if(n===Ne.Refunded)return ge.Refunded;if(n===Ne.RefundDetected)return ge.RefundDetected;if(s===Ne.Expired)return ge.CounterPartySwapExpired;if(n===Ne.Expired)return ge.Expired;if(s===Ne.Refunded)return ge.CounterPartyRefunded;if(s===Ne.RefundDetected)return ge.CounterPartyRefundDetected;const i=Number(e.create_order.additional_data.deadline);return s===Ne.Initiated?ge.CounterPartyInitiated:s===Ne.InitiateDetected?ge.CounterPartyInitiateDetected:Fo(i,0)?ge.DeadLineExceeded:n===Ne.Initiated?ge.Initiated:Fo(i,0)?ge.DeadLineExceeded:n===Ne.InitiateDetected?ge.InitiateDetected:n===Ne.Redeemed?ge.CounterPartyRedeemed:n===Ne.RedeemDetected?ge.CounterPartyRedeemDetected:ge.Matched},jf=(e,t)=>{if(e.redeem_tx_hash)return Number(e.redeem_block_number)?Ne.Redeemed:Ne.RedeemDetected;if(e.refund_tx_hash)return Number(e.refund_block_number)?Ne.Refunded:Ne.RefundDetected;if(Number(e.initiate_block_number)){const r=Number(e.initiate_block_number)+e.timelock;if(t>r)return Ne.Expired}return e.initiate_tx_hash?Number(e.initiate_block_number)?Ne.Initiated:Ne.InitiateDetected:Ne.Idle},f_=(e,t,r)=>{const n=Xd(e,t,r);return Yd(n)},Yd=e=>{switch(e){case ge.Matched:return Ae.Initiate;case ge.CounterPartyInitiated:case ge.CounterPartyInitiateDetected:case ge.RedeemDetected:return Ae.Redeem;case ge.Expired:return Ae.Refund;default:return Ae.Idle}},Fo=(e,t=0)=>{const r=Date.now(),n=e*1e3+t*36e5;return r>=n},d_=e=>e.filter(t=>!hb(t)),hb=e=>{const{source_swap:t,create_order:r}=e,{initiate_tx_hash:n,initiate_block_number:s}=t,{deadline:i}=r.additional_data;return n&&Number(s)?!1:n&&!Number(s)?Fo(Number(i),12):n?!1:Fo(Number(i),1)},h_=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),p_=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),y_=Buffer.concat([h_,p_]),m_=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),Ip={failedToCreateInternalPubkey:"failed to create internal pubkey"};function g_(){const e=pe.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),t=ar.pointMultiply(Buffer.concat([Buffer.from("04","hex"),y_]),e);if(!t)throw new Error(Ip.failedToCreateInternalPubkey);const r=ar.pointAdd(m_,t);if(!r)throw new Error(Ip.failedToCreateInternalPubkey);return Nf(Buffer.from(r))}var Kr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function pb(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,s.get?s:{enumerable:!0,get:function(){return e[n]}})}),r}var Le={},wt={},Hs={},jc={};jc.byteLength=v_;jc.toByteArray=A_;jc.fromByteArray=__;var Hr=[],er=[],b_=typeof Uint8Array<"u"?Uint8Array:Array,Iu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var Ys=0,w_=Iu.length;Ys<w_;++Ys)Hr[Ys]=Iu[Ys],er[Iu.charCodeAt(Ys)]=Ys;er[45]=62;er[95]=63;function yb(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 v_(e){var t=yb(e),r=t[0],n=t[1];return(r+n)*3/4-n}function E_(e,t,r){return(t+r)*3/4-r}function A_(e){var t,r=yb(e),n=r[0],s=r[1],i=new b_(E_(e,n,s)),o=0,a=s>0?n-4:n,c;for(c=0;c<a;c+=4)t=er[e.charCodeAt(c)]<<18|er[e.charCodeAt(c+1)]<<12|er[e.charCodeAt(c+2)]<<6|er[e.charCodeAt(c+3)],i[o++]=t>>16&255,i[o++]=t>>8&255,i[o++]=t&255;return s===2&&(t=er[e.charCodeAt(c)]<<2|er[e.charCodeAt(c+1)]>>4,i[o++]=t&255),s===1&&(t=er[e.charCodeAt(c)]<<10|er[e.charCodeAt(c+1)]<<4|er[e.charCodeAt(c+2)]>>2,i[o++]=t>>8&255,i[o++]=t&255),i}function x_(e){return Hr[e>>18&63]+Hr[e>>12&63]+Hr[e>>6&63]+Hr[e&63]}function S_(e,t,r){for(var n,s=[],i=t;i<r;i+=3)n=(e[i]<<16&16711680)+(e[i+1]<<8&65280)+(e[i+2]&255),s.push(x_(n));return s.join("")}function __(e){for(var t,r=e.length,n=r%3,s=[],i=16383,o=0,a=r-n;o<a;o+=i)s.push(S_(e,o,o+i>a?a:o+i));return n===1?(t=e[r-1],s.push(Hr[t>>2]+Hr[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],s.push(Hr[t>>10]+Hr[t>>4&63]+Hr[t<<2&63]+"=")),s.join("")}var Zd={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Zd.read=function(e,t,r,n,s){var i,o,a=s*8-n-1,c=(1<<a)-1,l=c>>1,u=-7,f=r?s-1:0,p=r?-1:1,d=e[t+f];for(f+=p,i=d&(1<<-u)-1,d>>=-u,u+=a;u>0;i=i*256+e[t+f],f+=p,u-=8);for(o=i&(1<<-u)-1,i>>=-u,u+=n;u>0;o=o*256+e[t+f],f+=p,u-=8);if(i===0)i=1-l;else{if(i===c)return o?NaN:(d?-1:1)*(1/0);o=o+Math.pow(2,n),i=i-l}return(d?-1:1)*o*Math.pow(2,i-n)};Zd.write=function(e,t,r,n,s,i){var o,a,c,l=i*8-s-1,u=(1<<l)-1,f=u>>1,p=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,m=n?1:-1,g=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+f>=1?t+=p/c:t+=p*Math.pow(2,1-f),t*c>=2&&(o++,c/=2),o+f>=u?(a=0,o=u):o+f>=1?(a=(t*c-1)*Math.pow(2,s),o=o+f):(a=t*Math.pow(2,f-1)*Math.pow(2,s),o=0));s>=8;e[r+d]=a&255,d+=m,a/=256,s-=8);for(o=o<<s|a,l+=s;l>0;e[r+d]=o&255,d+=m,o/=256,l-=8);e[r+d-m]|=g*128};/*!
|
|
46
46
|
* The buffer module from node.js, for the browser.
|
|
47
47
|
*
|
|
48
48
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
49
49
|
* @license MIT
|
|
50
|
-
*/(function(e){const t=jc,r=Zd,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=a,e.SlowBuffer=T,e.INSPECT_MAX_BYTES=50;const s=2147483647;e.kMaxLength=s,a.TYPED_ARRAY_SUPPORT=i(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function i(){try{const b=new Uint8Array(1),h={foo:function(){return 42}};return Object.setPrototypeOf(h,Uint8Array.prototype),Object.setPrototypeOf(b,h),b.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(b){if(b>s)throw new RangeError('The value "'+b+'" is invalid for option "size"');const h=new Uint8Array(b);return Object.setPrototypeOf(h,a.prototype),h}function a(b,h,y){if(typeof b=="number"){if(typeof h=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return f(b)}return c(b,h,y)}a.poolSize=8192;function c(b,h,y){if(typeof b=="string")return p(b,h);if(ArrayBuffer.isView(b))return m(b);if(b==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof b);if(Et(b,ArrayBuffer)||b&&Et(b.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Et(b,SharedArrayBuffer)||b&&Et(b.buffer,SharedArrayBuffer)))return g(b,h,y);if(typeof b=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const x=b.valueOf&&b.valueOf();if(x!=null&&x!==b)return a.from(x,h,y);const C=w(b);if(C)return C;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof b[Symbol.toPrimitive]=="function")return a.from(b[Symbol.toPrimitive]("string"),h,y);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof b)}a.from=function(b,h,y){return c(b,h,y)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function l(b){if(typeof b!="number")throw new TypeError('"size" argument must be of type number');if(b<0)throw new RangeError('The value "'+b+'" is invalid for option "size"')}function u(b,h,y){return l(b),b<=0?o(b):h!==void 0?typeof y=="string"?o(b).fill(h,y):o(b).fill(h):o(b)}a.alloc=function(b,h,y){return u(b,h,y)};function f(b){return l(b),o(b<0?0:A(b)|0)}a.allocUnsafe=function(b){return f(b)},a.allocUnsafeSlow=function(b){return f(b)};function p(b,h){if((typeof h!="string"||h==="")&&(h="utf8"),!a.isEncoding(h))throw new TypeError("Unknown encoding: "+h);const y=E(b,h)|0;let x=o(y);const C=x.write(b,h);return C!==y&&(x=x.slice(0,C)),x}function d(b){const h=b.length<0?0:A(b.length)|0,y=o(h);for(let x=0;x<h;x+=1)y[x]=b[x]&255;return y}function m(b){if(Et(b,Uint8Array)){const h=new Uint8Array(b);return g(h.buffer,h.byteOffset,h.byteLength)}return d(b)}function g(b,h,y){if(h<0||b.byteLength<h)throw new RangeError('"offset" is outside of buffer bounds');if(b.byteLength<h+(y||0))throw new RangeError('"length" is outside of buffer bounds');let x;return h===void 0&&y===void 0?x=new Uint8Array(b):y===void 0?x=new Uint8Array(b,h):x=new Uint8Array(b,h,y),Object.setPrototypeOf(x,a.prototype),x}function w(b){if(a.isBuffer(b)){const h=A(b.length)|0,y=o(h);return y.length===0||b.copy(y,0,0,h),y}if(b.length!==void 0)return typeof b.length!="number"||Tn(b.length)?o(0):d(b);if(b.type==="Buffer"&&Array.isArray(b.data))return d(b.data)}function A(b){if(b>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return b|0}function T(b){return+b!=b&&(b=0),a.alloc(+b)}a.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==a.prototype},a.compare=function(h,y){if(Et(h,Uint8Array)&&(h=a.from(h,h.offset,h.byteLength)),Et(y,Uint8Array)&&(y=a.from(y,y.offset,y.byteLength)),!a.isBuffer(h)||!a.isBuffer(y))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===y)return 0;let x=h.length,C=y.length;for(let M=0,q=Math.min(x,C);M<q;++M)if(h[M]!==y[M]){x=h[M],C=y[M];break}return x<C?-1:C<x?1:0},a.isEncoding=function(h){switch(String(h).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(h,y){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return a.alloc(0);let x;if(y===void 0)for(y=0,x=0;x<h.length;++x)y+=h[x].length;const C=a.allocUnsafe(y);let M=0;for(x=0;x<h.length;++x){let q=h[x];if(Et(q,Uint8Array))M+q.length>C.length?(a.isBuffer(q)||(q=a.from(q)),q.copy(C,M)):Uint8Array.prototype.set.call(C,q,M);else if(a.isBuffer(q))q.copy(C,M);else throw new TypeError('"list" argument must be an Array of Buffers');M+=q.length}return C};function E(b,h){if(a.isBuffer(b))return b.length;if(ArrayBuffer.isView(b)||Et(b,ArrayBuffer))return b.byteLength;if(typeof b!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof b);const y=b.length,x=arguments.length>2&&arguments[2]===!0;if(!x&&y===0)return 0;let C=!1;for(;;)switch(h){case"ascii":case"latin1":case"binary":return y;case"utf8":case"utf-8":return Pr(b).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return y*2;case"hex":return y>>>1;case"base64":return Or(b).length;default:if(C)return x?-1:Pr(b).length;h=(""+h).toLowerCase(),C=!0}}a.byteLength=E;function S(b,h,y){let x=!1;if((h===void 0||h<0)&&(h=0),h>this.length||((y===void 0||y>this.length)&&(y=this.length),y<=0)||(y>>>=0,h>>>=0,y<=h))return"";for(b||(b="utf8");;)switch(b){case"hex":return B(this,h,y);case"utf8":case"utf-8":return W(this,h,y);case"ascii":return re(this,h,y);case"latin1":case"binary":return D(this,h,y);case"base64":return H(this,h,y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,h,y);default:if(x)throw new TypeError("Unknown encoding: "+b);b=(b+"").toLowerCase(),x=!0}}a.prototype._isBuffer=!0;function I(b,h,y){const x=b[h];b[h]=b[y],b[y]=x}a.prototype.swap16=function(){const h=this.length;if(h%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let y=0;y<h;y+=2)I(this,y,y+1);return this},a.prototype.swap32=function(){const h=this.length;if(h%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let y=0;y<h;y+=4)I(this,y,y+3),I(this,y+1,y+2);return this},a.prototype.swap64=function(){const h=this.length;if(h%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let y=0;y<h;y+=8)I(this,y,y+7),I(this,y+1,y+6),I(this,y+2,y+5),I(this,y+3,y+4);return this},a.prototype.toString=function(){const h=this.length;return h===0?"":arguments.length===0?W(this,0,h):S.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(h){if(!a.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:a.compare(this,h)===0},a.prototype.inspect=function(){let h="";const y=e.INSPECT_MAX_BYTES;return h=this.toString("hex",0,y).replace(/(.{2})/g,"$1 ").trim(),this.length>y&&(h+=" ... "),"<Buffer "+h+">"},n&&(a.prototype[n]=a.prototype.inspect),a.prototype.compare=function(h,y,x,C,M){if(Et(h,Uint8Array)&&(h=a.from(h,h.offset,h.byteLength)),!a.isBuffer(h))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof h);if(y===void 0&&(y=0),x===void 0&&(x=h?h.length:0),C===void 0&&(C=0),M===void 0&&(M=this.length),y<0||x>h.length||C<0||M>this.length)throw new RangeError("out of range index");if(C>=M&&y>=x)return 0;if(C>=M)return-1;if(y>=x)return 1;if(y>>>=0,x>>>=0,C>>>=0,M>>>=0,this===h)return 0;let q=M-C,me=x-y;const ze=Math.min(q,me),$e=this.slice(C,M),qe=h.slice(y,x);for(let ke=0;ke<ze;++ke)if($e[ke]!==qe[ke]){q=$e[ke],me=qe[ke];break}return q<me?-1:me<q?1:0};function P(b,h,y,x,C){if(b.length===0)return-1;if(typeof y=="string"?(x=y,y=0):y>2147483647?y=2147483647:y<-2147483648&&(y=-2147483648),y=+y,Tn(y)&&(y=C?0:b.length-1),y<0&&(y=b.length+y),y>=b.length){if(C)return-1;y=b.length-1}else if(y<0)if(C)y=0;else return-1;if(typeof h=="string"&&(h=a.from(h,x)),a.isBuffer(h))return h.length===0?-1:$(b,h,y,x,C);if(typeof h=="number")return h=h&255,typeof Uint8Array.prototype.indexOf=="function"?C?Uint8Array.prototype.indexOf.call(b,h,y):Uint8Array.prototype.lastIndexOf.call(b,h,y):$(b,[h],y,x,C);throw new TypeError("val must be string, number or Buffer")}function $(b,h,y,x,C){let M=1,q=b.length,me=h.length;if(x!==void 0&&(x=String(x).toLowerCase(),x==="ucs2"||x==="ucs-2"||x==="utf16le"||x==="utf-16le")){if(b.length<2||h.length<2)return-1;M=2,q/=2,me/=2,y/=2}function ze(qe,ke){return M===1?qe[ke]:qe.readUInt16BE(ke*M)}let $e;if(C){let qe=-1;for($e=y;$e<q;$e++)if(ze(b,$e)===ze(h,qe===-1?0:$e-qe)){if(qe===-1&&(qe=$e),$e-qe+1===me)return qe*M}else qe!==-1&&($e-=$e-qe),qe=-1}else for(y+me>q&&(y=q-me),$e=y;$e>=0;$e--){let qe=!0;for(let ke=0;ke<me;ke++)if(ze(b,$e+ke)!==ze(h,ke)){qe=!1;break}if(qe)return $e}return-1}a.prototype.includes=function(h,y,x){return this.indexOf(h,y,x)!==-1},a.prototype.indexOf=function(h,y,x){return P(this,h,y,x,!0)},a.prototype.lastIndexOf=function(h,y,x){return P(this,h,y,x,!1)};function j(b,h,y,x){y=Number(y)||0;const C=b.length-y;x?(x=Number(x),x>C&&(x=C)):x=C;const M=h.length;x>M/2&&(x=M/2);let q;for(q=0;q<x;++q){const me=parseInt(h.substr(q*2,2),16);if(Tn(me))return q;b[y+q]=me}return q}function k(b,h,y,x){return vt(Pr(h,b.length-y),b,y,x)}function F(b,h,y,x){return vt(ns(h),b,y,x)}function R(b,h,y,x){return vt(Or(h),b,y,x)}function U(b,h,y,x){return vt(G(h,b.length-y),b,y,x)}a.prototype.write=function(h,y,x,C){if(y===void 0)C="utf8",x=this.length,y=0;else if(x===void 0&&typeof y=="string")C=y,x=this.length,y=0;else if(isFinite(y))y=y>>>0,isFinite(x)?(x=x>>>0,C===void 0&&(C="utf8")):(C=x,x=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const M=this.length-y;if((x===void 0||x>M)&&(x=M),h.length>0&&(x<0||y<0)||y>this.length)throw new RangeError("Attempt to write outside buffer bounds");C||(C="utf8");let q=!1;for(;;)switch(C){case"hex":return j(this,h,y,x);case"utf8":case"utf-8":return k(this,h,y,x);case"ascii":case"latin1":case"binary":return F(this,h,y,x);case"base64":return R(this,h,y,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U(this,h,y,x);default:if(q)throw new TypeError("Unknown encoding: "+C);C=(""+C).toLowerCase(),q=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function H(b,h,y){return h===0&&y===b.length?t.fromByteArray(b):t.fromByteArray(b.slice(h,y))}function W(b,h,y){y=Math.min(b.length,y);const x=[];let C=h;for(;C<y;){const M=b[C];let q=null,me=M>239?4:M>223?3:M>191?2:1;if(C+me<=y){let ze,$e,qe,ke;switch(me){case 1:M<128&&(q=M);break;case 2:ze=b[C+1],(ze&192)===128&&(ke=(M&31)<<6|ze&63,ke>127&&(q=ke));break;case 3:ze=b[C+1],$e=b[C+2],(ze&192)===128&&($e&192)===128&&(ke=(M&15)<<12|(ze&63)<<6|$e&63,ke>2047&&(ke<55296||ke>57343)&&(q=ke));break;case 4:ze=b[C+1],$e=b[C+2],qe=b[C+3],(ze&192)===128&&($e&192)===128&&(qe&192)===128&&(ke=(M&15)<<18|(ze&63)<<12|($e&63)<<6|qe&63,ke>65535&&ke<1114112&&(q=ke))}}q===null?(q=65533,me=1):q>65535&&(q-=65536,x.push(q>>>10&1023|55296),q=56320|q&1023),x.push(q),C+=me}return Q(x)}const Z=4096;function Q(b){const h=b.length;if(h<=Z)return String.fromCharCode.apply(String,b);let y="",x=0;for(;x<h;)y+=String.fromCharCode.apply(String,b.slice(x,x+=Z));return y}function re(b,h,y){let x="";y=Math.min(b.length,y);for(let C=h;C<y;++C)x+=String.fromCharCode(b[C]&127);return x}function D(b,h,y){let x="";y=Math.min(b.length,y);for(let C=h;C<y;++C)x+=String.fromCharCode(b[C]);return x}function B(b,h,y){const x=b.length;(!h||h<0)&&(h=0),(!y||y<0||y>x)&&(y=x);let C="";for(let M=h;M<y;++M)C+=Gs[b[M]];return C}function V(b,h,y){const x=b.slice(h,y);let C="";for(let M=0;M<x.length-1;M+=2)C+=String.fromCharCode(x[M]+x[M+1]*256);return C}a.prototype.slice=function(h,y){const x=this.length;h=~~h,y=y===void 0?x:~~y,h<0?(h+=x,h<0&&(h=0)):h>x&&(h=x),y<0?(y+=x,y<0&&(y=0)):y>x&&(y=x),y<h&&(y=h);const C=this.subarray(h,y);return Object.setPrototypeOf(C,a.prototype),C};function K(b,h,y){if(b%1!==0||b<0)throw new RangeError("offset is not uint");if(b+h>y)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(h,y,x){h=h>>>0,y=y>>>0,x||K(h,y,this.length);let C=this[h],M=1,q=0;for(;++q<y&&(M*=256);)C+=this[h+q]*M;return C},a.prototype.readUintBE=a.prototype.readUIntBE=function(h,y,x){h=h>>>0,y=y>>>0,x||K(h,y,this.length);let C=this[h+--y],M=1;for(;y>0&&(M*=256);)C+=this[h+--y]*M;return C},a.prototype.readUint8=a.prototype.readUInt8=function(h,y){return h=h>>>0,y||K(h,1,this.length),this[h]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(h,y){return h=h>>>0,y||K(h,2,this.length),this[h]|this[h+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(h,y){return h=h>>>0,y||K(h,2,this.length),this[h]<<8|this[h+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(h,y){return h=h>>>0,y||K(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(h,y){return h=h>>>0,y||K(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},a.prototype.readBigUInt64LE=In(function(h){h=h>>>0,_e(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&je(h,this.length-8);const C=y+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24,M=this[++h]+this[++h]*2**8+this[++h]*2**16+x*2**24;return BigInt(C)+(BigInt(M)<<BigInt(32))}),a.prototype.readBigUInt64BE=In(function(h){h=h>>>0,_e(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&je(h,this.length-8);const C=y*2**24+this[++h]*2**16+this[++h]*2**8+this[++h],M=this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+x;return(BigInt(C)<<BigInt(32))+BigInt(M)}),a.prototype.readIntLE=function(h,y,x){h=h>>>0,y=y>>>0,x||K(h,y,this.length);let C=this[h],M=1,q=0;for(;++q<y&&(M*=256);)C+=this[h+q]*M;return M*=128,C>=M&&(C-=Math.pow(2,8*y)),C},a.prototype.readIntBE=function(h,y,x){h=h>>>0,y=y>>>0,x||K(h,y,this.length);let C=y,M=1,q=this[h+--C];for(;C>0&&(M*=256);)q+=this[h+--C]*M;return M*=128,q>=M&&(q-=Math.pow(2,8*y)),q},a.prototype.readInt8=function(h,y){return h=h>>>0,y||K(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},a.prototype.readInt16LE=function(h,y){h=h>>>0,y||K(h,2,this.length);const x=this[h]|this[h+1]<<8;return x&32768?x|4294901760:x},a.prototype.readInt16BE=function(h,y){h=h>>>0,y||K(h,2,this.length);const x=this[h+1]|this[h]<<8;return x&32768?x|4294901760:x},a.prototype.readInt32LE=function(h,y){return h=h>>>0,y||K(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},a.prototype.readInt32BE=function(h,y){return h=h>>>0,y||K(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},a.prototype.readBigInt64LE=In(function(h){h=h>>>0,_e(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&je(h,this.length-8);const C=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(x<<24);return(BigInt(C)<<BigInt(32))+BigInt(y+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24)}),a.prototype.readBigInt64BE=In(function(h){h=h>>>0,_e(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&je(h,this.length-8);const C=(y<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt(C)<<BigInt(32))+BigInt(this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+x)}),a.prototype.readFloatLE=function(h,y){return h=h>>>0,y||K(h,4,this.length),r.read(this,h,!0,23,4)},a.prototype.readFloatBE=function(h,y){return h=h>>>0,y||K(h,4,this.length),r.read(this,h,!1,23,4)},a.prototype.readDoubleLE=function(h,y){return h=h>>>0,y||K(h,8,this.length),r.read(this,h,!0,52,8)},a.prototype.readDoubleBE=function(h,y){return h=h>>>0,y||K(h,8,this.length),r.read(this,h,!1,52,8)};function O(b,h,y,x,C,M){if(!a.isBuffer(b))throw new TypeError('"buffer" argument must be a Buffer instance');if(h>C||h<M)throw new RangeError('"value" argument is out of bounds');if(y+x>b.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(h,y,x,C){if(h=+h,y=y>>>0,x=x>>>0,!C){const me=Math.pow(2,8*x)-1;O(this,h,y,x,me,0)}let M=1,q=0;for(this[y]=h&255;++q<x&&(M*=256);)this[y+q]=h/M&255;return y+x},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(h,y,x,C){if(h=+h,y=y>>>0,x=x>>>0,!C){const me=Math.pow(2,8*x)-1;O(this,h,y,x,me,0)}let M=x-1,q=1;for(this[y+M]=h&255;--M>=0&&(q*=256);)this[y+M]=h/q&255;return y+x},a.prototype.writeUint8=a.prototype.writeUInt8=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,1,255,0),this[y]=h&255,y+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,65535,0),this[y]=h&255,this[y+1]=h>>>8,y+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,65535,0),this[y]=h>>>8,this[y+1]=h&255,y+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,4294967295,0),this[y+3]=h>>>24,this[y+2]=h>>>16,this[y+1]=h>>>8,this[y]=h&255,y+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,4294967295,0),this[y]=h>>>24,this[y+1]=h>>>16,this[y+2]=h>>>8,this[y+3]=h&255,y+4};function N(b,h,y,x,C){ve(h,x,C,b,y,7);let M=Number(h&BigInt(4294967295));b[y++]=M,M=M>>8,b[y++]=M,M=M>>8,b[y++]=M,M=M>>8,b[y++]=M;let q=Number(h>>BigInt(32)&BigInt(4294967295));return b[y++]=q,q=q>>8,b[y++]=q,q=q>>8,b[y++]=q,q=q>>8,b[y++]=q,y}function L(b,h,y,x,C){ve(h,x,C,b,y,7);let M=Number(h&BigInt(4294967295));b[y+7]=M,M=M>>8,b[y+6]=M,M=M>>8,b[y+5]=M,M=M>>8,b[y+4]=M;let q=Number(h>>BigInt(32)&BigInt(4294967295));return b[y+3]=q,q=q>>8,b[y+2]=q,q=q>>8,b[y+1]=q,q=q>>8,b[y]=q,y+8}a.prototype.writeBigUInt64LE=In(function(h,y=0){return N(this,h,y,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=In(function(h,y=0){return L(this,h,y,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(h,y,x,C){if(h=+h,y=y>>>0,!C){const ze=Math.pow(2,8*x-1);O(this,h,y,x,ze-1,-ze)}let M=0,q=1,me=0;for(this[y]=h&255;++M<x&&(q*=256);)h<0&&me===0&&this[y+M-1]!==0&&(me=1),this[y+M]=(h/q>>0)-me&255;return y+x},a.prototype.writeIntBE=function(h,y,x,C){if(h=+h,y=y>>>0,!C){const ze=Math.pow(2,8*x-1);O(this,h,y,x,ze-1,-ze)}let M=x-1,q=1,me=0;for(this[y+M]=h&255;--M>=0&&(q*=256);)h<0&&me===0&&this[y+M+1]!==0&&(me=1),this[y+M]=(h/q>>0)-me&255;return y+x},a.prototype.writeInt8=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,1,127,-128),h<0&&(h=255+h+1),this[y]=h&255,y+1},a.prototype.writeInt16LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,32767,-32768),this[y]=h&255,this[y+1]=h>>>8,y+2},a.prototype.writeInt16BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,32767,-32768),this[y]=h>>>8,this[y+1]=h&255,y+2},a.prototype.writeInt32LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,2147483647,-2147483648),this[y]=h&255,this[y+1]=h>>>8,this[y+2]=h>>>16,this[y+3]=h>>>24,y+4},a.prototype.writeInt32BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,2147483647,-2147483648),h<0&&(h=4294967295+h+1),this[y]=h>>>24,this[y+1]=h>>>16,this[y+2]=h>>>8,this[y+3]=h&255,y+4},a.prototype.writeBigInt64LE=In(function(h,y=0){return N(this,h,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=In(function(h,y=0){return L(this,h,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function J(b,h,y,x,C,M){if(y+x>b.length)throw new RangeError("Index out of range");if(y<0)throw new RangeError("Index out of range")}function ne(b,h,y,x,C){return h=+h,y=y>>>0,C||J(b,h,y,4),r.write(b,h,y,x,23,4),y+4}a.prototype.writeFloatLE=function(h,y,x){return ne(this,h,y,!0,x)},a.prototype.writeFloatBE=function(h,y,x){return ne(this,h,y,!1,x)};function fe(b,h,y,x,C){return h=+h,y=y>>>0,C||J(b,h,y,8),r.write(b,h,y,x,52,8),y+8}a.prototype.writeDoubleLE=function(h,y,x){return fe(this,h,y,!0,x)},a.prototype.writeDoubleBE=function(h,y,x){return fe(this,h,y,!1,x)},a.prototype.copy=function(h,y,x,C){if(!a.isBuffer(h))throw new TypeError("argument should be a Buffer");if(x||(x=0),!C&&C!==0&&(C=this.length),y>=h.length&&(y=h.length),y||(y=0),C>0&&C<x&&(C=x),C===x||h.length===0||this.length===0)return 0;if(y<0)throw new RangeError("targetStart out of bounds");if(x<0||x>=this.length)throw new RangeError("Index out of range");if(C<0)throw new RangeError("sourceEnd out of bounds");C>this.length&&(C=this.length),h.length-y<C-x&&(C=h.length-y+x);const M=C-x;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(y,x,C):Uint8Array.prototype.set.call(h,this.subarray(x,C),y),M},a.prototype.fill=function(h,y,x,C){if(typeof h=="string"){if(typeof y=="string"?(C=y,y=0,x=this.length):typeof x=="string"&&(C=x,x=this.length),C!==void 0&&typeof C!="string")throw new TypeError("encoding must be a string");if(typeof C=="string"&&!a.isEncoding(C))throw new TypeError("Unknown encoding: "+C);if(h.length===1){const q=h.charCodeAt(0);(C==="utf8"&&q<128||C==="latin1")&&(h=q)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));if(y<0||this.length<y||this.length<x)throw new RangeError("Out of range index");if(x<=y)return this;y=y>>>0,x=x===void 0?this.length:x>>>0,h||(h=0);let M;if(typeof h=="number")for(M=y;M<x;++M)this[M]=h;else{const q=a.isBuffer(h)?h:a.from(h,C),me=q.length;if(me===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for(M=0;M<x-y;++M)this[M+y]=q[M%me]}return this};const ce={};function oe(b,h,y){ce[b]=class extends y{constructor(){super(),Object.defineProperty(this,"message",{value:h.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${b}]`,this.stack,delete this.name}get code(){return b}set code(C){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:C,writable:!0})}toString(){return`${this.name} [${b}]: ${this.message}`}}}oe("ERR_BUFFER_OUT_OF_BOUNDS",function(b){return b?`${b} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),oe("ERR_INVALID_ARG_TYPE",function(b,h){return`The "${b}" argument must be of type number. Received type ${typeof h}`},TypeError),oe("ERR_OUT_OF_RANGE",function(b,h,y){let x=`The value of "${b}" is out of range.`,C=y;return Number.isInteger(y)&&Math.abs(y)>2**32?C=ie(String(y)):typeof y=="bigint"&&(C=String(y),(y>BigInt(2)**BigInt(32)||y<-(BigInt(2)**BigInt(32)))&&(C=ie(C)),C+="n"),x+=` It must be ${h}. Received ${C}`,x},RangeError);function ie(b){let h="",y=b.length;const x=b[0]==="-"?1:0;for(;y>=x+4;y-=3)h=`_${b.slice(y-3,y)}${h}`;return`${b.slice(0,y)}${h}`}function he(b,h,y){_e(h,"offset"),(b[h]===void 0||b[h+y]===void 0)&&je(h,b.length-(y+1))}function ve(b,h,y,x,C,M){if(b>y||b<h){const q=typeof h=="bigint"?"n":"";let me;throw h===0||h===BigInt(0)?me=`>= 0${q} and < 2${q} ** ${(M+1)*8}${q}`:me=`>= -(2${q} ** ${(M+1)*8-1}${q}) and < 2 ** ${(M+1)*8-1}${q}`,new ce.ERR_OUT_OF_RANGE("value",me,b)}he(x,C,M)}function _e(b,h){if(typeof b!="number")throw new ce.ERR_INVALID_ARG_TYPE(h,"number",b)}function je(b,h,y){throw Math.floor(b)!==b?(_e(b,y),new ce.ERR_OUT_OF_RANGE("offset","an integer",b)):h<0?new ce.ERR_BUFFER_OUT_OF_BOUNDS:new ce.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${h}`,b)}const jt=/[^+/0-9A-Za-z-_]/g;function Qe(b){if(b=b.split("=")[0],b=b.trim().replace(jt,""),b.length<2)return"";for(;b.length%4!==0;)b=b+"=";return b}function Pr(b,h){h=h||1/0;let y;const x=b.length;let C=null;const M=[];for(let q=0;q<x;++q){if(y=b.charCodeAt(q),y>55295&&y<57344){if(!C){if(y>56319){(h-=3)>-1&&M.push(239,191,189);continue}else if(q+1===x){(h-=3)>-1&&M.push(239,191,189);continue}C=y;continue}if(y<56320){(h-=3)>-1&&M.push(239,191,189),C=y;continue}y=(C-55296<<10|y-56320)+65536}else C&&(h-=3)>-1&&M.push(239,191,189);if(C=null,y<128){if((h-=1)<0)break;M.push(y)}else if(y<2048){if((h-=2)<0)break;M.push(y>>6|192,y&63|128)}else if(y<65536){if((h-=3)<0)break;M.push(y>>12|224,y>>6&63|128,y&63|128)}else if(y<1114112){if((h-=4)<0)break;M.push(y>>18|240,y>>12&63|128,y>>6&63|128,y&63|128)}else throw new Error("Invalid code point")}return M}function ns(b){const h=[];for(let y=0;y<b.length;++y)h.push(b.charCodeAt(y)&255);return h}function G(b,h){let y,x,C;const M=[];for(let q=0;q<b.length&&!((h-=2)<0);++q)y=b.charCodeAt(q),x=y>>8,C=y%256,M.push(C),M.push(x);return M}function Or(b){return t.toByteArray(Qe(b))}function vt(b,h,y,x){let C;for(C=0;C<x&&!(C+y>=h.length||C>=b.length);++C)h[C+y]=b[C];return C}function Et(b,h){return b instanceof h||b!=null&&b.constructor!=null&&b.constructor.name!=null&&b.constructor.name===h.name}function Tn(b){return b!==b}const Gs=function(){const b="0123456789abcdef",h=new Array(256);for(let y=0;y<16;++y){const x=y*16;for(let C=0;C<16;++C)h[x+C]=b[y]+b[C]}return h}();function In(b){return typeof BigInt>"u"?H1:b}function H1(){throw new Error("BigInt not supported")}})(Hs);var jo={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}};jo.Null=jo.Nil;for(var Pp in jo)jo[Pp].toJSON=(function(e){return e}).bind(null,Pp);var Jd=jo,ws=Jd;function mb(e){return e.name||e.toString().match(/function (.*?)\s*\(/)[1]}function Qd(e){return ws.Nil(e)?"":mb(e.constructor)}function k_(e){return ws.Function(e)?"":ws.String(e)?JSON.stringify(e):e&&ws.Object(e)?"":e}function eh(e,t){Error.captureStackTrace&&Error.captureStackTrace(e,t)}function nc(e){return ws.Function(e)?e.toJSON?e.toJSON():mb(e):ws.Array(e)?"Array":e&&ws.Object(e)?"Object":e!==void 0?e:""}function gb(e,t,r){var n=k_(t);return"Expected "+nc(e)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function En(e,t,r){r=r||Qd(t),this.message=gb(e,t,r),eh(this,En),this.__type=e,this.__value=t,this.__valueTypeName=r}En.prototype=Object.create(Error.prototype);En.prototype.constructor=En;function T_(e,t,r,n,s){var i='" of type ';return t==="key"&&(i='" with key type '),gb('property "'+nc(r)+i+nc(e),n,s)}function fi(e,t,r,n,s){e?(s=s||Qd(n),this.message=T_(e,r,t,n,s)):this.message='Unexpected property "'+t+'"',eh(this,En),this.__label=r,this.__property=t,this.__type=e,this.__value=n,this.__valueTypeName=s}fi.prototype=Object.create(Error.prototype);fi.prototype.constructor=En;function I_(e,t){return new En(e,{},t)}function P_(e,t,r){return e instanceof fi?(t=t+"."+e.__property,e=new fi(e.__type,t,e.__label,e.__value,e.__valueTypeName)):e instanceof En&&(e=new fi(e.__type,t,r,e.__value,e.__valueTypeName)),eh(e),e}var bb={TfTypeError:En,TfPropertyTypeError:fi,tfCustomError:I_,tfSubError:P_,tfJSON:nc,getValueTypeName:Qd},Pu,Op;function O_(){if(Op)return Pu;Op=1;var e=Jd,t=bb;function r(P){return Buffer.isBuffer(P)}function n(P){return typeof P=="string"&&/^([0-9a-f]{2})+$/i.test(P)}function s(P,$){var j=P.toJSON();function k(F){if(!P(F))return!1;if(F.length===$)return!0;throw t.tfCustomError(j+"(Length: "+$+")",j+"(Length: "+F.length+")")}return k.toJSON=function(){return j},k}var i=s.bind(null,e.Array),o=s.bind(null,r),a=s.bind(null,n),c=s.bind(null,e.String);function l(P,$,j){j=j||e.Number;function k(F,R){return j(F,R)&&F>P&&F<$}return k.toJSON=function(){return`${j.toJSON()} between [${P}, ${$}]`},k}var u=Math.pow(2,53)-1;function f(P){return typeof P=="number"&&isFinite(P)}function p(P){return P<<24>>24===P}function d(P){return P<<16>>16===P}function m(P){return(P|0)===P}function g(P){return typeof P=="number"&&P>=-u&&P<=u&&Math.floor(P)===P}function w(P){return(P&255)===P}function A(P){return(P&65535)===P}function T(P){return P>>>0===P}function E(P){return typeof P=="number"&&P>=0&&P<=u&&Math.floor(P)===P}var S={ArrayN:i,Buffer:r,BufferN:o,Finite:f,Hex:n,HexN:a,Int8:p,Int16:d,Int32:m,Int53:g,Range:l,StringN:c,UInt8:w,UInt16:A,UInt32:T,UInt53:E};for(var I in S)S[I].toJSON=(function(P){return P}).bind(null,I);return Pu=S,Pu}var ia=bb,at=Jd,Qr=ia.tfJSON,wb=ia.TfTypeError,vb=ia.TfPropertyTypeError,ji=ia.tfSubError,B_=ia.getValueTypeName,dn={arrayOf:function(t,r){t=Lr(t),r=r||{};function n(s,i){return!at.Array(s)||at.Nil(s)||r.minLength!==void 0&&s.length<r.minLength||r.maxLength!==void 0&&s.length>r.maxLength||r.length!==void 0&&s.length!==r.length?!1:s.every(function(o,a){try{return Tt(t,o,i)}catch(c){throw ji(c,a)}})}return n.toJSON=function(){var s="["+Qr(t)+"]";return r.length!==void 0?s+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(s+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),s},n},maybe:function e(t){t=Lr(t);function r(n,s){return at.Nil(n)||t(n,s,e)}return r.toJSON=function(){return"?"+Qr(t)},r},map:function(t,r){t=Lr(t),r&&(r=Lr(r));function n(s,i){if(!at.Object(s)||at.Nil(s))return!1;for(var o in s){try{r&&Tt(r,o,i)}catch(c){throw ji(c,o,"key")}try{var a=s[o];Tt(t,a,i)}catch(c){throw ji(c,o)}}return!0}return r?n.toJSON=function(){return"{"+Qr(r)+": "+Qr(t)+"}"}:n.toJSON=function(){return"{"+Qr(t)+"}"},n},object:function(t){var r={};for(var n in t)r[n]=Lr(t[n]);function s(i,o){if(!at.Object(i)||at.Nil(i))return!1;var a;try{for(a in r){var c=r[a],l=i[a];Tt(c,l,o)}}catch(u){throw ji(u,a)}if(o){for(a in i)if(!r[a])throw new vb(void 0,a)}return!0}return s.toJSON=function(){return Qr(r)},s},anyOf:function(){var t=[].slice.call(arguments).map(Lr);function r(n,s){return t.some(function(i){try{return Tt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return t.map(Qr).join("|")},r},allOf:function(){var t=[].slice.call(arguments).map(Lr);function r(n,s){return t.every(function(i){try{return Tt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return t.map(Qr).join(" & ")},r},quacksLike:function(t){function r(n){return t===B_(n)}return r.toJSON=function(){return t},r},tuple:function(){var t=[].slice.call(arguments).map(Lr);function r(n,s){return at.Nil(n)||at.Nil(n.length)||s&&n.length!==t.length?!1:t.every(function(i,o){try{return Tt(i,n[o],s)}catch(a){throw ji(a,o)}})}return r.toJSON=function(){return"("+t.map(Qr).join(", ")+")"},r},value:function(t){function r(n){return n===t}return r.toJSON=function(){return t},r}};dn.oneOf=dn.anyOf;function Lr(e){if(at.String(e))return e[0]==="?"?dn.maybe(e.slice(1)):at[e]||dn.quacksLike(e);if(e&&at.Object(e)){if(at.Array(e)){if(e.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return dn.arrayOf(e[0])}return dn.object(e)}else if(at.Function(e))return e;return dn.value(e)}function Tt(e,t,r,n){if(at.Function(e)){if(e(t,r))return!0;throw new wb(n||e,t)}return Tt(Lr(e),t,r)}for(var Xn in at)Tt[Xn]=at[Xn];for(Xn in dn)Tt[Xn]=dn[Xn];var Bp=O_();for(Xn in Bp)Tt[Xn]=Bp[Xn];Tt.compile=Lr;Tt.TfTypeError=wb;Tt.TfPropertyTypeError=vb;var C_=Tt;(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=Hs;e.typeforce=C_;const r=t.Buffer.alloc(32,0),n=t.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function s(u,f){return u.length!==f.length?!1:u.every((p,d)=>p.equals(f[d]))}e.stacksEqual=s;function i(u){if(!t.Buffer.isBuffer(u)||u.length<33)return!1;const f=u[0],p=u.slice(1,33);if(p.compare(r)===0||p.compare(n)>=0)return!1;if((f===2||f===3)&&u.length===33)return!0;const d=u.slice(33);return d.compare(r)===0||d.compare(n)>=0?!1:f===4&&u.length===65}e.isPoint=i;const o=21*1e14;function a(u){return e.typeforce.UInt53(u)&&u<=o}e.Satoshi=a,e.TAPLEAF_VERSION_MASK=254;function c(u){return!u||!("output"in u)||!t.Buffer.isBuffer(u.output)?!1:u.version!==void 0?(u.version&e.TAPLEAF_VERSION_MASK)===u.version:!0}e.isTapleaf=c;function l(u){return(0,e.Array)(u)?u.length!==2?!1:u.every(f=>l(f)):c(u)}e.isTaptree=l,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})(wt);var oa={},ct={};Object.defineProperty(ct,"__esModule",{value:!0});ct.BufferReader=ct.BufferWriter=ct.cloneBuffer=ct.reverseBuffer=ct.writeUInt64LE=ct.readUInt64LE=ct.varuint=void 0;const vs=wt,{typeforce:Eb}=vs,Lo=Am;ct.varuint=Lo;function Ab(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 xb(e,t){const r=e.readUInt32LE(t);let n=e.readUInt32LE(t+4);return n*=4294967296,Ab(n+r,9007199254740991),n+r}ct.readUInt64LE=xb;function Sb(e,t,r){return Ab(t,9007199254740991),e.writeInt32LE(t&-1,r),e.writeUInt32LE(Math.floor(t/4294967296),r+4),r+8}ct.writeUInt64LE=Sb;function R_(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}ct.reverseBuffer=R_;function $_(e){const t=Buffer.allocUnsafe(e.length);return e.copy(t),t}ct.cloneBuffer=$_;class th{static withCapacity(t){return new th(Buffer.alloc(t))}constructor(t,r=0){this.buffer=t,this.offset=r,Eb(vs.tuple(vs.Buffer,vs.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=Sb(this.buffer,t,this.offset)}writeVarInt(t){Lo.encode(t,this.buffer,this.offset),this.offset+=Lo.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}`)}}ct.BufferWriter=th;class N_{constructor(t,r=0){this.buffer=t,this.offset=r,Eb(vs.tuple(vs.Buffer,vs.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=xb(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Lo.decode(this.buffer,this.offset);return this.offset+=Lo.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}}ct.BufferReader=N_;var rs={};const U_=pb(ox);var Ei={},Ct={},Pt={},rh={},Lc={};Object.defineProperty(Lc,"__esModule",{value:!0});Lc.crypto=void 0;Lc.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=s,e.ahash=i,e.aexists=o,e.aoutput=a,e.u8=c,e.u32=l,e.clean=u,e.createView=f,e.rotr=p,e.rotl=d,e.byteSwap=m,e.byteSwap32=g,e.bytesToHex=T,e.hexToBytes=I,e.asyncLoop=$,e.utf8ToBytes=j,e.bytesToUtf8=k,e.toBytes=F,e.kdfInputToBytes=R,e.concatBytes=U,e.checkOpts=H,e.createHasher=Z,e.createOptHasher=Q,e.createXOFer=re,e.randomBytes=D;const t=Lc;function r(B){return B instanceof Uint8Array||ArrayBuffer.isView(B)&&B.constructor.name==="Uint8Array"}function n(B){if(!Number.isSafeInteger(B)||B<0)throw new Error("positive integer expected, got "+B)}function s(B,...V){if(!r(B))throw new Error("Uint8Array expected");if(V.length>0&&!V.includes(B.length))throw new Error("Uint8Array expected of length "+V+", got length="+B.length)}function i(B){if(typeof B!="function"||typeof B.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");n(B.outputLen),n(B.blockLen)}function o(B,V=!0){if(B.destroyed)throw new Error("Hash instance has been destroyed");if(V&&B.finished)throw new Error("Hash#digest() has already been called")}function a(B,V){s(B);const K=V.outputLen;if(B.length<K)throw new Error("digestInto() expects output buffer of length at least "+K)}function c(B){return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)}function l(B){return new Uint32Array(B.buffer,B.byteOffset,Math.floor(B.byteLength/4))}function u(...B){for(let V=0;V<B.length;V++)B[V].fill(0)}function f(B){return new DataView(B.buffer,B.byteOffset,B.byteLength)}function p(B,V){return B<<32-V|B>>>V}function d(B,V){return B<<V|B>>>32-V>>>0}e.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function m(B){return B<<24&4278190080|B<<8&16711680|B>>>8&65280|B>>>24&255}e.swap8IfBE=e.isLE?B=>B:B=>m(B),e.byteSwapIfBE=e.swap8IfBE;function g(B){for(let V=0;V<B.length;V++)B[V]=m(B[V]);return B}e.swap32IfBE=e.isLE?B=>B:g;const w=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",A=Array.from({length:256},(B,V)=>V.toString(16).padStart(2,"0"));function T(B){if(s(B),w)return B.toHex();let V="";for(let K=0;K<B.length;K++)V+=A[B[K]];return V}const E={_0:48,_9:57,A:65,F:70,a:97,f:102};function S(B){if(B>=E._0&&B<=E._9)return B-E._0;if(B>=E.A&&B<=E.F)return B-(E.A-10);if(B>=E.a&&B<=E.f)return B-(E.a-10)}function I(B){if(typeof B!="string")throw new Error("hex string expected, got "+typeof B);if(w)return Uint8Array.fromHex(B);const V=B.length,K=V/2;if(V%2)throw new Error("hex string expected, got unpadded hex of length "+V);const O=new Uint8Array(K);for(let N=0,L=0;N<K;N++,L+=2){const J=S(B.charCodeAt(L)),ne=S(B.charCodeAt(L+1));if(J===void 0||ne===void 0){const fe=B[L]+B[L+1];throw new Error('hex string expected, got non-hex character "'+fe+'" at index '+L)}O[N]=J*16+ne}return O}const P=async()=>{};e.nextTick=P;async function $(B,V,K){let O=Date.now();for(let N=0;N<B;N++){K(N);const L=Date.now()-O;L>=0&&L<V||(await(0,e.nextTick)(),O+=L)}}function j(B){if(typeof B!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(B))}function k(B){return new TextDecoder().decode(B)}function F(B){return typeof B=="string"&&(B=j(B)),s(B),B}function R(B){return typeof B=="string"&&(B=j(B)),s(B),B}function U(...B){let V=0;for(let O=0;O<B.length;O++){const N=B[O];s(N),V+=N.length}const K=new Uint8Array(V);for(let O=0,N=0;O<B.length;O++){const L=B[O];K.set(L,N),N+=L.length}return K}function H(B,V){if(V!==void 0&&{}.toString.call(V)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(B,V)}class W{}e.Hash=W;function Z(B){const V=O=>B().update(F(O)).digest(),K=B();return V.outputLen=K.outputLen,V.blockLen=K.blockLen,V.create=()=>B(),V}function Q(B){const V=(O,N)=>B(N).update(F(O)).digest(),K=B({});return V.outputLen=K.outputLen,V.blockLen=K.blockLen,V.create=O=>B(O),V}function re(B){const V=(O,N)=>B(N).update(F(O)).digest(),K=B({});return V.outputLen=K.outputLen,V.blockLen=K.blockLen,V.create=O=>B(O),V}e.wrapConstructor=Z,e.wrapConstructorWithOpts=Q,e.wrapXOFConstructorWithOpts=re;function D(B=32){if(t.crypto&&typeof t.crypto.getRandomValues=="function")return t.crypto.getRandomValues(new Uint8Array(B));if(t.crypto&&typeof t.crypto.randomBytes=="function")return Uint8Array.from(t.crypto.randomBytes(B));throw new Error("crypto.getRandomValues must be defined")}})(rh);Object.defineProperty(Pt,"__esModule",{value:!0});Pt.SHA512_IV=Pt.SHA384_IV=Pt.SHA224_IV=Pt.SHA256_IV=Pt.HashMD=void 0;Pt.setBigUint64=_b;Pt.Chi=M_;Pt.Maj=F_;const Rr=rh;function _b(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}function M_(e,t,r){return e&t^~e&r}function F_(e,t,r){return e&t^e&r^t&r}class j_ extends Rr.Hash{constructor(t,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(t),this.view=(0,Rr.createView)(this.buffer)}update(t){(0,Rr.aexists)(this),t=(0,Rr.toBytes)(t),(0,Rr.abytes)(t);const{view:r,buffer:n,blockLen:s}=this,i=t.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=(0,Rr.createView)(t);for(;s<=i-o;o+=s)this.process(c,o);continue}n.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){(0,Rr.aexists)(this),(0,Rr.aoutput)(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:o}=this;r[o++]=128,(0,Rr.clean)(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let f=o;f<s;f++)r[f]=0;_b(n,s-8,BigInt(this.length*8),i),this.process(n,0);const a=(0,Rr.createView)(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],i)}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:s,finished:i,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=i,t.length=s,t.pos=a,s%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}}Pt.HashMD=j_;Pt.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);Pt.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);Pt.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);Pt.SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);Object.defineProperty(Ct,"__esModule",{value:!0});Ct.ripemd160=Ct.RIPEMD160=Ct.md5=Ct.MD5=Ct.sha1=Ct.SHA1=void 0;const Es=Pt,ut=rh,Js=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Cn=new Uint32Array(80);class kb extends Es.HashMD{constructor(){super(64,20,8,!1),this.A=Js[0]|0,this.B=Js[1]|0,this.C=Js[2]|0,this.D=Js[3]|0,this.E=Js[4]|0}get(){const{A:t,B:r,C:n,D:s,E:i}=this;return[t,r,n,s,i]}set(t,r,n,s,i){this.A=t|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0}process(t,r){for(let c=0;c<16;c++,r+=4)Cn[c]=t.getUint32(r,!1);for(let c=16;c<80;c++)Cn[c]=(0,ut.rotl)(Cn[c-3]^Cn[c-8]^Cn[c-14]^Cn[c-16],1);let{A:n,B:s,C:i,D:o,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=(0,Es.Chi)(s,i,o),u=1518500249):c<40?(l=s^i^o,u=1859775393):c<60?(l=(0,Es.Maj)(s,i,o),u=2400959708):(l=s^i^o,u=3395469782);const f=(0,ut.rotl)(n,5)+l+a+u+Cn[c]|0;a=o,o=i,i=(0,ut.rotl)(s,30),s=n,n=f}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,this.set(n,s,i,o,a)}roundClean(){(0,ut.clean)(Cn)}destroy(){this.set(0,0,0,0,0),(0,ut.clean)(this.buffer)}}Ct.SHA1=kb;Ct.sha1=(0,ut.createHasher)(()=>new kb);const L_=Math.pow(2,32),D_=Array.from({length:64},(e,t)=>Math.floor(L_*Math.abs(Math.sin(t+1)))),Aa=Js.slice(0,4),Ou=new Uint32Array(16);class Tb extends Es.HashMD{constructor(){super(64,16,8,!0),this.A=Aa[0]|0,this.B=Aa[1]|0,this.C=Aa[2]|0,this.D=Aa[3]|0}get(){const{A:t,B:r,C:n,D:s}=this;return[t,r,n,s]}set(t,r,n,s){this.A=t|0,this.B=r|0,this.C=n|0,this.D=s|0}process(t,r){for(let a=0;a<16;a++,r+=4)Ou[a]=t.getUint32(r,!0);let{A:n,B:s,C:i,D:o}=this;for(let a=0;a<64;a++){let c,l,u;a<16?(c=(0,Es.Chi)(s,i,o),l=a,u=[7,12,17,22]):a<32?(c=(0,Es.Chi)(o,s,i),l=(5*a+1)%16,u=[5,9,14,20]):a<48?(c=s^i^o,l=(3*a+5)%16,u=[4,11,16,23]):(c=i^(s|~o),l=7*a%16,u=[6,10,15,21]),c=c+n+D_[a]+Ou[l],n=o,o=i,i=s,s=s+(0,ut.rotl)(c,u[a%4])}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,this.set(n,s,i,o)}roundClean(){(0,ut.clean)(Ou)}destroy(){this.set(0,0,0,0),(0,ut.clean)(this.buffer)}}Ct.MD5=Tb;Ct.md5=(0,ut.createHasher)(()=>new Tb);const H_=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Ib=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),z_=Ib.map(e=>(9*e+5)%16),Pb=(()=>{const r=[[Ib],[z_]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>H_[i]));return r})(),Ob=Pb[0],Bb=Pb[1],Cb=[[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)),q_=Ob.map((e,t)=>e.map(r=>Cb[t][r])),V_=Bb.map((e,t)=>e.map(r=>Cb[t][r])),G_=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),W_=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Cp(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 xa=new Uint32Array(16);class Rb extends Es.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:s,h4:i}=this;return[t,r,n,s,i]}set(t,r,n,s,i){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=s|0,this.h4=i|0}process(t,r){for(let d=0;d<16;d++,r+=4)xa[d]=t.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,o=i,a=this.h2|0,c=a,l=this.h3|0,u=l,f=this.h4|0,p=f;for(let d=0;d<5;d++){const m=4-d,g=G_[d],w=W_[d],A=Ob[d],T=Bb[d],E=q_[d],S=V_[d];for(let I=0;I<16;I++){const P=(0,ut.rotl)(n+Cp(d,i,a,l)+xa[A[I]]+g,E[I])+f|0;n=f,f=l,l=(0,ut.rotl)(a,10)|0,a=i,i=P}for(let I=0;I<16;I++){const P=(0,ut.rotl)(s+Cp(m,o,c,u)+xa[T[I]]+w,S[I])+p|0;s=p,p=u,u=(0,ut.rotl)(c,10)|0,c=o,o=P}}this.set(this.h1+a+u|0,this.h2+l+p|0,this.h3+f+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){(0,ut.clean)(xa)}destroy(){this.destroyed=!0,(0,ut.clean)(this.buffer),this.set(0,0,0,0,0)}}Ct.RIPEMD160=Rb;Ct.ripemd160=(0,ut.createHasher)(()=>new Rb);Object.defineProperty(Ei,"__esModule",{value:!0});Ei.sha1=Ei.SHA1=void 0;const $b=Ct;Ei.SHA1=$b.SHA1;Ei.sha1=$b.sha1;const Nb=pb(XE);(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=U_,r=Ei,n=Nb;function s(u){return Buffer.from((0,t.ripemd160)(Uint8Array.from(u)))}e.ripemd160=s;function i(u){return Buffer.from((0,r.sha1)(Uint8Array.from(u)))}e.sha1=i;function o(u){return Buffer.from((0,n.sha256)(Uint8Array.from(u)))}e.sha256=o;function a(u){return Buffer.from((0,t.ripemd160)((0,n.sha256)(Uint8Array.from(u))))}e.hash160=a;function c(u){return Buffer.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(u))))}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 l(u,f){return o(Buffer.concat([e.TAGGED_HASH_PREFIXES[u],f]))}e.taggedHash=l})(rs);var Bu={},bn={};Object.defineProperty(bn,"__esModule",{value:!0});bn.encode=bn.decode=bn.check=void 0;function K_(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))}bn.check=K_;function X_(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)}}bn.decode=X_;function Y_(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 s=Buffer.allocUnsafe(6+r+n);return s[0]=48,s[1]=s.length-2,s[2]=2,s[3]=e.length,e.copy(s,4),s[4+r]=2,s[5+r]=t.length,t.copy(s,6+r),s}bn.encode=Y_;var Cs={};Object.defineProperty(Cs,"__esModule",{value:!0});Cs.REVERSE_OPS=Cs.OPS=void 0;const Lf={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};Cs.OPS=Lf;const Ub={};Cs.REVERSE_OPS=Ub;for(const e of Object.keys(Lf)){const t=Lf[e];Ub[t]=e}var Yn={};Object.defineProperty(Yn,"__esModule",{value:!0});Yn.decode=Yn.encode=Yn.encodingLength=void 0;const Gn=Cs;function Mb(e){return e<Gn.OPS.OP_PUSHDATA1?1:e<=255?2:e<=65535?3:5}Yn.encodingLength=Mb;function Z_(e,t,r){const n=Mb(t);return n===1?e.writeUInt8(t,r):n===2?(e.writeUInt8(Gn.OPS.OP_PUSHDATA1,r),e.writeUInt8(t,r+1)):n===3?(e.writeUInt8(Gn.OPS.OP_PUSHDATA2,r),e.writeUInt16LE(t,r+1)):(e.writeUInt8(Gn.OPS.OP_PUSHDATA4,r),e.writeUInt32LE(t,r+1)),n}Yn.encode=Z_;function J_(e,t){const r=e.readUInt8(t);let n,s;if(r<Gn.OPS.OP_PUSHDATA1)n=r,s=1;else if(r===Gn.OPS.OP_PUSHDATA1){if(t+2>e.length)return null;n=e.readUInt8(t+1),s=2}else if(r===Gn.OPS.OP_PUSHDATA2){if(t+3>e.length)return null;n=e.readUInt16LE(t+1),s=3}else{if(t+5>e.length)return null;if(r!==Gn.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=e.readUInt32LE(t+1),s=5}return{opcode:r,number:n,size:s}}Yn.decode=J_;var Ai={};Object.defineProperty(Ai,"__esModule",{value:!0});Ai.encode=Ai.decode=void 0;function Q_(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 i=e.readUInt32LE(0),o=e.readUInt8(4);return o&128?-((o&-129)*4294967296+i):o*4294967296+i}let s=0;for(let i=0;i<n;++i)s|=e[i]<<8*i;return e[n-1]&128?-(s&~(128<<8*(n-1))):s}Ai.decode=Q_;function ek(e){return e>2147483647?5:e>8388607?4:e>32767?3:e>127?2:e>0?1:0}function tk(e){let t=Math.abs(e);const r=ek(t),n=Buffer.allocUnsafe(r),s=e<0;for(let i=0;i<r;++i)n.writeUInt8(t&255,i),t>>=8;return n[r-1]&128?n.writeUInt8(s?128:0,r-1):s&&(n[r-1]|=128),n}Ai.encode=tk;var ss={},Rp;function rk(){if(Rp)return ss;Rp=1,Object.defineProperty(ss,"__esModule",{value:!0}),ss.encode=ss.decode=void 0;const e=bn,t=Yt(),r=wt,{typeforce:n}=r,s=Buffer.alloc(1,0);function i(l){let u=0;for(;l[u]===0;)++u;return u===l.length?s:(l=l.slice(u),l[0]&128?Buffer.concat([s,l],1+l.length):l)}function o(l){l[0]===0&&(l=l.slice(1));const u=Buffer.alloc(32,0),f=Math.max(0,32-l.length);return l.copy(u,f),u}function a(l){const u=l.readUInt8(l.length-1);if(!(0,t.isDefinedHashType)(u))throw new Error("Invalid hashType "+u);const f=e.decode(l.slice(0,-1)),p=o(f.r),d=o(f.s);return{signature:Buffer.concat([p,d],64),hashType:u}}ss.decode=a;function c(l,u){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:l,hashType:u}),!(0,t.isDefinedHashType)(u))throw new Error("Invalid hashType "+u);const f=Buffer.allocUnsafe(1);f.writeUInt8(u,0);const p=i(l.slice(0,32)),d=i(l.slice(32,64));return Buffer.concat([e.encode(p,d),f])}return ss.encode=c,ss}var $p;function Yt(){return $p||($p=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=bn,r=Cs;Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=Yn,s=Ai,i=rk(),o=wt,{typeforce:a}=o,c=r.OPS.OP_RESERVED;function l(k){return o.Number(k)&&(k===r.OPS.OP_0||k>=r.OPS.OP_1&&k<=r.OPS.OP_16||k===r.OPS.OP_1NEGATE)}function u(k){return o.Buffer(k)||l(k)}function f(k){return o.Array(k)&&k.every(u)}e.isPushOnly=f;function p(k){return k.length-k.filter(u).length}e.countNonPushOnlyOPs=p;function d(k){if(k.length===0)return r.OPS.OP_0;if(k.length===1){if(k[0]>=1&&k[0]<=16)return c+k[0];if(k[0]===129)return r.OPS.OP_1NEGATE}}function m(k){return Buffer.isBuffer(k)}function g(k){return o.Array(k)}function w(k){return Buffer.isBuffer(k)}function A(k){if(m(k))return k;a(o.Array,k);const F=k.reduce((H,W)=>w(W)?W.length===1&&d(W)!==void 0?H+1:H+n.encodingLength(W.length)+W.length:H+1,0),R=Buffer.allocUnsafe(F);let U=0;if(k.forEach(H=>{if(w(H)){const W=d(H);if(W!==void 0){R.writeUInt8(W,U),U+=1;return}U+=n.encode(R,H.length,U),H.copy(R,U),U+=H.length}else R.writeUInt8(H,U),U+=1}),U!==R.length)throw new Error("Could not decode chunks");return R}e.compile=A;function T(k){if(g(k))return k;a(o.Buffer,k);const F=[];let R=0;for(;R<k.length;){const U=k[R];if(U>r.OPS.OP_0&&U<=r.OPS.OP_PUSHDATA4){const H=n.decode(k,R);if(H===null||(R+=H.size,R+H.number>k.length))return null;const W=k.slice(R,R+H.number);R+=H.number;const Z=d(W);Z!==void 0?F.push(Z):F.push(W)}else F.push(U),R+=1}return F}e.decompile=T;function E(k){if(m(k)&&(k=T(k)),!k)throw new Error("Could not convert invalid chunks to ASM");return k.map(F=>{if(w(F)){const R=d(F);if(R===void 0)return F.toString("hex");F=R}return r.REVERSE_OPS[F]}).join(" ")}e.toASM=E;function S(k){return a(o.String,k),A(k.split(" ").map(F=>r.OPS[F]!==void 0?r.OPS[F]:(a(o.Hex,F),Buffer.from(F,"hex"))))}e.fromASM=S;function I(k){return k=T(k),a(f,k),k.map(F=>w(F)?F:F===r.OPS.OP_0?Buffer.allocUnsafe(0):s.encode(F-c))}e.toStack=I;function P(k){return o.isPoint(k)}e.isCanonicalPubKey=P;function $(k){const F=k&-129;return F>0&&F<4}e.isDefinedHashType=$;function j(k){return!Buffer.isBuffer(k)||!$(k[k.length-1])?!1:t.check(k.slice(0,-1))}e.isCanonicalScriptSignature=j,e.number=s,e.signature=i}(Bu)),Bu}Object.defineProperty(oa,"__esModule",{value:!0});oa.Transaction=void 0;const Ye=ct,At=rs,Np=Yt(),nk=Yt(),we=wt,{typeforce:$r}=we;function Fr(e){const t=e.length;return Ye.varuint.encodingLength(t)+t}function sk(e){const t=e.length;return Ye.varuint.encodingLength(t)+e.reduce((r,n)=>r+Fr(n),0)}const jn=Buffer.allocUnsafe(0),Cu=[],Ru=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),Up=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),ik=Buffer.from("ffffffffffffffff","hex"),ok={script:jn,valueBuffer:ik};function ak(e){return e.value!==void 0}let Ir=class Te{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(t,r){const n=new Ye.BufferReader(t),s=new Te;s.version=n.readInt32();const i=n.readUInt8(),o=n.readUInt8();let a=!1;i===Te.ADVANCED_TRANSACTION_MARKER&&o===Te.ADVANCED_TRANSACTION_FLAG?a=!0:n.offset-=2;const c=n.readVarInt();for(let u=0;u<c;++u)s.ins.push({hash:n.readSlice(32),index:n.readUInt32(),script:n.readVarSlice(),sequence:n.readUInt32(),witness:Cu});const l=n.readVarInt();for(let u=0;u<l;++u)s.outs.push({value:n.readUInt64(),script:n.readVarSlice()});if(a){for(let u=0;u<c;++u)s.ins[u].witness=n.readVector();if(!s.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(s.locktime=n.readUInt32(),r)return s;if(n.offset!==t.length)throw new Error("Transaction has unexpected data");return s}static fromHex(t){return Te.fromBuffer(Buffer.from(t,"hex"),!1)}static isCoinbaseHash(t){$r(we.Hash256bit,t);for(let r=0;r<32;++r)if(t[r]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&Te.isCoinbaseHash(this.ins[0].hash)}addInput(t,r,n,s){return $r(we.tuple(we.Hash256bit,we.UInt32,we.maybe(we.UInt32),we.maybe(we.Buffer)),arguments),we.Null(n)&&(n=Te.DEFAULT_SEQUENCE),this.ins.push({hash:t,index:r,script:s||jn,sequence:n,witness:Cu})-1}addOutput(t,r){return $r(we.tuple(we.Buffer,we.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=Cu})}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)+Ye.varuint.encodingLength(this.ins.length)+Ye.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,s)=>n+40+Fr(s.script),0)+this.outs.reduce((n,s)=>n+8+Fr(s.script),0)+(r?this.ins.reduce((n,s)=>n+sk(s.witness),0):0)}clone(){const t=new Te;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($r(we.tuple(we.UInt32,we.Buffer,we.Number),arguments),t>=this.ins.length)return Up;const s=Np.compile(Np.decompile(r).filter(a=>a!==nk.OPS.OP_CODESEPARATOR)),i=this.clone();if((n&31)===Te.SIGHASH_NONE)i.outs=[],i.ins.forEach((a,c)=>{c!==t&&(a.sequence=0)});else if((n&31)===Te.SIGHASH_SINGLE){if(t>=this.outs.length)return Up;i.outs.length=t+1;for(let a=0;a<t;a++)i.outs[a]=ok;i.ins.forEach((a,c)=>{c!==t&&(a.sequence=0)})}n&Te.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[t]],i.ins[0].script=s):(i.ins.forEach(a=>{a.script=jn}),i.ins[t].script=s);const o=Buffer.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(n,o.length-4),i.__toBuffer(o,0,!1),At.hash256(o)}hashForWitnessV1(t,r,n,s,i,o){if($r(we.tuple(we.UInt32,$r.arrayOf(we.Buffer),$r.arrayOf(we.Satoshi),we.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 a=s===Te.SIGHASH_DEFAULT?Te.SIGHASH_ALL:s&Te.SIGHASH_OUTPUT_MASK,l=(s&Te.SIGHASH_INPUT_MASK)===Te.SIGHASH_ANYONECANPAY,u=a===Te.SIGHASH_NONE,f=a===Te.SIGHASH_SINGLE;let p=jn,d=jn,m=jn,g=jn,w=jn;if(!l){let S=Ye.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(I=>{S.writeSlice(I.hash),S.writeUInt32(I.index)}),p=At.sha256(S.end()),S=Ye.BufferWriter.withCapacity(8*this.ins.length),n.forEach(I=>S.writeUInt64(I)),d=At.sha256(S.end()),S=Ye.BufferWriter.withCapacity(r.map(Fr).reduce((I,P)=>I+P)),r.forEach(I=>S.writeVarSlice(I)),m=At.sha256(S.end()),S=Ye.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(I=>S.writeUInt32(I.sequence)),g=At.sha256(S.end())}if(u||f){if(f&&t<this.outs.length){const S=this.outs[t],I=Ye.BufferWriter.withCapacity(8+Fr(S.script));I.writeUInt64(S.value),I.writeVarSlice(S.script),w=At.sha256(I.end())}}else{const S=this.outs.map(P=>8+Fr(P.script)).reduce((P,$)=>P+$),I=Ye.BufferWriter.withCapacity(S);this.outs.forEach(P=>{I.writeUInt64(P.value),I.writeVarSlice(P.script)}),w=At.sha256(I.end())}const A=(i?2:0)+(o?1:0),T=174-(l?49:0)-(u?32:0)+(o?32:0)+(i?37:0),E=Ye.BufferWriter.withCapacity(T);if(E.writeUInt8(s),E.writeInt32(this.version),E.writeUInt32(this.locktime),E.writeSlice(p),E.writeSlice(d),E.writeSlice(m),E.writeSlice(g),u||f||E.writeSlice(w),E.writeUInt8(A),l){const S=this.ins[t];E.writeSlice(S.hash),E.writeUInt32(S.index),E.writeUInt64(n[t]),E.writeVarSlice(r[t]),E.writeUInt32(S.sequence)}else E.writeUInt32(t);if(o){const S=Ye.BufferWriter.withCapacity(Fr(o));S.writeVarSlice(o),E.writeSlice(At.sha256(S.end()))}return f&&E.writeSlice(w),i&&(E.writeSlice(i),E.writeUInt8(0),E.writeUInt32(4294967295)),At.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),E.end()]))}hashForWitnessV0(t,r,n,s){$r(we.tuple(we.UInt32,we.Buffer,we.Satoshi,we.UInt32),arguments);let i=Buffer.from([]),o,a=Ru,c=Ru,l=Ru;if(s&Te.SIGHASH_ANYONECANPAY||(i=Buffer.allocUnsafe(36*this.ins.length),o=new Ye.BufferWriter(i,0),this.ins.forEach(f=>{o.writeSlice(f.hash),o.writeUInt32(f.index)}),c=At.hash256(i)),!(s&Te.SIGHASH_ANYONECANPAY)&&(s&31)!==Te.SIGHASH_SINGLE&&(s&31)!==Te.SIGHASH_NONE&&(i=Buffer.allocUnsafe(4*this.ins.length),o=new Ye.BufferWriter(i,0),this.ins.forEach(f=>{o.writeUInt32(f.sequence)}),l=At.hash256(i)),(s&31)!==Te.SIGHASH_SINGLE&&(s&31)!==Te.SIGHASH_NONE){const f=this.outs.reduce((p,d)=>p+8+Fr(d.script),0);i=Buffer.allocUnsafe(f),o=new Ye.BufferWriter(i,0),this.outs.forEach(p=>{o.writeUInt64(p.value),o.writeVarSlice(p.script)}),a=At.hash256(i)}else if((s&31)===Te.SIGHASH_SINGLE&&t<this.outs.length){const f=this.outs[t];i=Buffer.allocUnsafe(8+Fr(f.script)),o=new Ye.BufferWriter(i,0),o.writeUInt64(f.value),o.writeVarSlice(f.script),a=At.hash256(i)}i=Buffer.allocUnsafe(156+Fr(r)),o=new Ye.BufferWriter(i,0);const u=this.ins[t];return o.writeInt32(this.version),o.writeSlice(c),o.writeSlice(l),o.writeSlice(u.hash),o.writeUInt32(u.index),o.writeVarSlice(r),o.writeUInt64(n),o.writeUInt32(u.sequence),o.writeSlice(a),o.writeUInt32(this.locktime),o.writeUInt32(s),At.hash256(i)}getHash(t){return t&&this.isCoinbase()?Buffer.alloc(32,0):At.hash256(this.__toBuffer(void 0,void 0,t))}getId(){return(0,Ye.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){$r(we.tuple(we.Number,we.Buffer),arguments),this.ins[t].script=r}setWitness(t,r){$r(we.tuple(we.Number,[we.Buffer]),arguments),this.ins[t].witness=r}__toBuffer(t,r,n=!1){t||(t=Buffer.allocUnsafe(this.byteLength(n)));const s=new Ye.BufferWriter(t,r||0);s.writeInt32(this.version);const i=n&&this.hasWitnesses();return i&&(s.writeUInt8(Te.ADVANCED_TRANSACTION_MARKER),s.writeUInt8(Te.ADVANCED_TRANSACTION_FLAG)),s.writeVarInt(this.ins.length),this.ins.forEach(o=>{s.writeSlice(o.hash),s.writeUInt32(o.index),s.writeVarSlice(o.script),s.writeUInt32(o.sequence)}),s.writeVarInt(this.outs.length),this.outs.forEach(o=>{ak(o)?s.writeUInt64(o.value):s.writeSlice(o.valueBuffer),s.writeVarSlice(o.script)}),i&&this.ins.forEach(o=>{s.writeVector(o.witness)}),s.writeUInt32(this.locktime),r!==void 0?t.slice(r,s.offset):t}};oa.Transaction=Ir;Ir.DEFAULT_SEQUENCE=4294967295;Ir.SIGHASH_DEFAULT=0;Ir.SIGHASH_ALL=1;Ir.SIGHASH_NONE=2;Ir.SIGHASH_SINGLE=3;Ir.SIGHASH_ANYONECANPAY=128;Ir.SIGHASH_OUTPUT_MASK=3;Ir.SIGHASH_INPUT_MASK=128;Ir.ADVANCED_TRANSACTION_MARKER=0;Ir.ADVANCED_TRANSACTION_FLAG=1;var Ie={},aa={};Object.defineProperty(aa,"__esModule",{value:!0});const ck=9007199254740991;function nh(e){if(e<0||e>ck||e%1!==0)throw new RangeError("value out of range")}function Xi(e,t,r){if(nh(e),t||(t=Buffer.allocUnsafe(Fb(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(Xi,{bytes:1})):e<=65535?(t.writeUInt8(253,r),t.writeUInt16LE(e,r+1),Object.assign(Xi,{bytes:3})):e<=4294967295?(t.writeUInt8(254,r),t.writeUInt32LE(e,r+1),Object.assign(Xi,{bytes:5})):(t.writeUInt8(255,r),t.writeUInt32LE(e>>>0,r+1),t.writeUInt32LE(e/4294967296|0,r+5),Object.assign(Xi,{bytes:9})),t}aa.encode=Xi;function Yi(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(Yi,{bytes:1}),r;if(r===253)return Object.assign(Yi,{bytes:3}),e.readUInt16LE(t+1);if(r===254)return Object.assign(Yi,{bytes:5}),e.readUInt32LE(t+1);{Object.assign(Yi,{bytes:9});const n=e.readUInt32LE(t+1),i=e.readUInt32LE(t+5)*4294967296+n;return nh(i),i}}aa.decode=Yi;function Fb(e){return nh(e),e<253?1:e<=65535?3:e<=4294967295?5:9}aa.encodingLength=Fb;var $u={},Dc={},gt={};Object.defineProperty(gt,"__esModule",{value:!0});gt.testnet=gt.regtest=gt.bitcoin=void 0;gt.bitcoin={messagePrefix:`Bitcoin Signed Message:
|
|
51
|
-
`,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};
|
|
52
|
-
`,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};
|
|
53
|
-
`,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var Gt={};Object.defineProperty(Gt,"__esModule",{value:!0});Gt.value=Gt.prop=void 0;function uk(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})}})}Gt.prop=uk;function lk(e){let t;return()=>(t!==void 0||(t=e()),t)}Gt.value=lk;Object.defineProperty(Dc,"__esModule",{value:!0});Dc.p2data=void 0;const fk=gt,Ha=Yt(),Nr=wt,Mp=Gt,Fp=Ha.OPS;function dk(e,t){if(!e.data&&!e.output)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Nr.typeforce)({network:Nr.typeforce.maybe(Nr.typeforce.Object),output:Nr.typeforce.maybe(Nr.typeforce.Buffer),data:Nr.typeforce.maybe(Nr.typeforce.arrayOf(Nr.typeforce.Buffer))},e);const n={name:"embed",network:e.network||fk.bitcoin};if(Mp.prop(n,"output",()=>{if(e.data)return Ha.compile([Fp.OP_RETURN].concat(e.data))}),Mp.prop(n,"data",()=>{if(e.output)return Ha.decompile(e.output).slice(1)}),t.validate&&e.output){const s=Ha.decompile(e.output);if(s[0]!==Fp.OP_RETURN)throw new TypeError("Output is invalid");if(!s.slice(1).every(Nr.typeforce.Buffer))throw new TypeError("Output is invalid");if(e.data&&!(0,Nr.stacksEqual)(e.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,e)}Dc.p2data=dk;var Hc={};Object.defineProperty(Hc,"__esModule",{value:!0});Hc.p2ms=void 0;const hk=gt,Qs=Yt(),We=wt,Rn=Gt,ei=Qs.OPS,Sa=ei.OP_RESERVED;function pk(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 Qs.isCanonicalScriptSignature(c)||(t.allowIncomplete&&c===ei.OP_0)!==void 0}(0,We.typeforce)({network:We.typeforce.maybe(We.typeforce.Object),m:We.typeforce.maybe(We.typeforce.Number),n:We.typeforce.maybe(We.typeforce.Number),output:We.typeforce.maybe(We.typeforce.Buffer),pubkeys:We.typeforce.maybe(We.typeforce.arrayOf(We.isPoint)),signatures:We.typeforce.maybe(We.typeforce.arrayOf(r)),input:We.typeforce.maybe(We.typeforce.Buffer)},e);const s={network:e.network||hk.bitcoin};let i=[],o=!1;function a(c){o||(o=!0,i=Qs.decompile(c),s.m=i[0]-Sa,s.n=i[i.length-2]-Sa,s.pubkeys=i.slice(1,-2))}if(Rn.prop(s,"output",()=>{if(e.m&&s.n&&e.pubkeys)return Qs.compile([].concat(Sa+e.m,e.pubkeys,Sa+s.n,ei.OP_CHECKMULTISIG))}),Rn.prop(s,"m",()=>{if(s.output)return a(s.output),s.m}),Rn.prop(s,"n",()=>{if(s.pubkeys)return s.pubkeys.length}),Rn.prop(s,"pubkeys",()=>{if(e.output)return a(e.output),s.pubkeys}),Rn.prop(s,"signatures",()=>{if(e.input)return Qs.decompile(e.input).slice(1)}),Rn.prop(s,"input",()=>{if(e.signatures)return Qs.compile([ei.OP_0].concat(e.signatures))}),Rn.prop(s,"witness",()=>{if(s.input)return[]}),Rn.prop(s,"name",()=>{if(!(!s.m||!s.n))return`p2ms(${s.m} of ${s.n})`}),t.validate){if(e.output){if(a(e.output),!We.typeforce.Number(i[0]))throw new TypeError("Output is invalid");if(!We.typeforce.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==ei.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(s.m<=0||s.n>16||s.m>s.n||s.n!==i.length-3)throw new TypeError("Output is invalid");if(!s.pubkeys.every(c=>(0,We.isPoint)(c)))throw new TypeError("Output is invalid");if(e.m!==void 0&&e.m!==s.m)throw new TypeError("m mismatch");if(e.n!==void 0&&e.n!==s.n)throw new TypeError("n mismatch");if(e.pubkeys&&!(0,We.stacksEqual)(e.pubkeys,s.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(s.n=e.pubkeys.length,s.n<s.m)throw new TypeError("Pubkey count cannot be less than m")}if(e.signatures){if(e.signatures.length<s.m)throw new TypeError("Not enough signatures provided");if(e.signatures.length>s.m)throw new TypeError("Too many signatures provided")}if(e.input){if(e.input[0]!==ei.OP_0)throw new TypeError("Input is invalid");if(s.signatures.length===0||!s.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(e.signatures&&!(0,We.stacksEqual)(e.signatures,s.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(s,e)}Hc.p2ms=pk;var zc={};Object.defineProperty(zc,"__esModule",{value:!0});zc.p2pk=void 0;const yk=gt,ti=Yt(),hr=wt,Zs=Gt,jp=ti.OPS;function mk(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,hr.typeforce)({network:hr.typeforce.maybe(hr.typeforce.Object),output:hr.typeforce.maybe(hr.typeforce.Buffer),pubkey:hr.typeforce.maybe(hr.isPoint),signature:hr.typeforce.maybe(ti.isCanonicalScriptSignature),input:hr.typeforce.maybe(hr.typeforce.Buffer)},e);const r=Zs.value(()=>ti.decompile(e.input)),s={name:"p2pk",network:e.network||yk.bitcoin};if(Zs.prop(s,"output",()=>{if(e.pubkey)return ti.compile([e.pubkey,jp.OP_CHECKSIG])}),Zs.prop(s,"pubkey",()=>{if(e.output)return e.output.slice(1,-1)}),Zs.prop(s,"signature",()=>{if(e.input)return r()[0]}),Zs.prop(s,"input",()=>{if(e.signature)return ti.compile([e.signature])}),Zs.prop(s,"witness",()=>{if(s.input)return[]}),t.validate){if(e.output){if(e.output[e.output.length-1]!==jp.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,hr.isPoint)(s.pubkey))throw new TypeError("Output pubkey is invalid");if(e.pubkey&&!e.pubkey.equals(s.pubkey))throw new TypeError("Pubkey mismatch")}if(e.signature&&e.input&&!e.input.equals(s.input))throw new TypeError("Signature mismatch");if(e.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!ti.isCanonicalScriptSignature(s.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(s,e)}zc.p2pk=mk;var qc={};function gk(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 s=e.charAt(n),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=n}var o=e.length,a=e.charAt(0),c=Math.log(o)/Math.log(256),l=Math.log(256)/Math.log(o);function u(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 m=0,g=0,w=0,A=d.length;w!==A&&d[w]===0;)w++,m++;for(var T=(A-w)*l+1>>>0,E=new Uint8Array(T);w!==A;){for(var S=d[w],I=0,P=T-1;(S!==0||I<g)&&P!==-1;P--,I++)S+=256*E[P]>>>0,E[P]=S%o>>>0,S=S/o>>>0;if(S!==0)throw new Error("Non-zero carry");g=I,w++}for(var $=T-g;$!==T&&E[$]===0;)$++;for(var j=a.repeat(m);$<T;++$)j+=e.charAt(E[$]);return j}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;for(var m=0,g=0,w=0;d[m]===a;)g++,m++;for(var A=(d.length-m)*c+1>>>0,T=new Uint8Array(A);d[m];){var E=d.charCodeAt(m);if(E>255)return;var S=t[E];if(S===255)return;for(var I=0,P=A-1;(S!==0||I<w)&&P!==-1;P--,I++)S+=o*T[P]>>>0,T[P]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");w=I,m++}for(var $=A-w;$!==A&&T[$]===0;)$++;for(var j=new Uint8Array(g+(A-$)),k=g;$!==A;)j[k++]=T[$++];return j}function p(d){var m=f(d);if(m)return m;throw new Error("Non-base"+o+" character")}return{encode:u,decodeUnsafe:f,decode:p}}var bk=gk;const wk=bk,vk="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var Ek=wk(vk),Nu=Ek,Ak=function(e){function t(i){var o=Uint8Array.from(i),a=e(o),c=o.length+4,l=new Uint8Array(c);return l.set(o,0),l.set(a.subarray(0,4),o.length),Nu.encode(l,c)}function r(i){var o=i.slice(0,-4),a=i.slice(-4),c=e(o);if(!(a[0]^c[0]|a[1]^c[1]|a[2]^c[2]|a[3]^c[3]))return o}function n(i){var o=Nu.decodeUnsafe(i);if(o)return r(o)}function s(i){var o=Nu.decode(i),a=r(o);if(!a)throw new Error("Invalid checksum");return a}return{encode:t,decode:s,decodeUnsafe:n}},{sha256:Lp}=Nb,xk=Ak;function Sk(e){return Lp(Lp(e))}var sh=xk(Sk);Object.defineProperty(qc,"__esModule",{value:!0});qc.p2pkh=void 0;const Uu=rs,_k=gt,ri=Yt(),xt=wt,en=Gt,Dp=sh,$n=ri.OPS;function kk(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,xt.typeforce)({network:xt.typeforce.maybe(xt.typeforce.Object),address:xt.typeforce.maybe(xt.typeforce.String),hash:xt.typeforce.maybe(xt.typeforce.BufferN(20)),output:xt.typeforce.maybe(xt.typeforce.BufferN(25)),pubkey:xt.typeforce.maybe(xt.isPoint),signature:xt.typeforce.maybe(ri.isCanonicalScriptSignature),input:xt.typeforce.maybe(xt.typeforce.Buffer)},e);const r=en.value(()=>{const o=Buffer.from(Dp.decode(e.address)),a=o.readUInt8(0),c=o.slice(1);return{version:a,hash:c}}),n=en.value(()=>ri.decompile(e.input)),s=e.network||_k.bitcoin,i={name:"p2pkh",network:s};if(en.prop(i,"address",()=>{if(!i.hash)return;const o=Buffer.allocUnsafe(21);return o.writeUInt8(s.pubKeyHash,0),i.hash.copy(o,1),Dp.encode(o)}),en.prop(i,"hash",()=>{if(e.output)return e.output.slice(3,23);if(e.address)return r().hash;if(e.pubkey||i.pubkey)return Uu.hash160(e.pubkey||i.pubkey)}),en.prop(i,"output",()=>{if(i.hash)return ri.compile([$n.OP_DUP,$n.OP_HASH160,i.hash,$n.OP_EQUALVERIFY,$n.OP_CHECKSIG])}),en.prop(i,"pubkey",()=>{if(e.input)return n()[1]}),en.prop(i,"signature",()=>{if(e.input)return n()[0]}),en.prop(i,"input",()=>{if(e.pubkey&&e.signature)return ri.compile([e.signature,e.pubkey])}),en.prop(i,"witness",()=>{if(i.input)return[]}),t.validate){let o=Buffer.from([]);if(e.address){if(r().version!==s.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");o=r().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!==25||e.output[0]!==$n.OP_DUP||e.output[1]!==$n.OP_HASH160||e.output[2]!==20||e.output[23]!==$n.OP_EQUALVERIFY||e.output[24]!==$n.OP_CHECKSIG)throw new TypeError("Output is invalid");const a=e.output.slice(3,23);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.pubkey){const a=Uu.hash160(e.pubkey);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.input){const a=n();if(a.length!==2)throw new TypeError("Input is invalid");if(!ri.isCanonicalScriptSignature(a[0]))throw new TypeError("Input has invalid signature");if(!(0,xt.isPoint)(a[1]))throw new TypeError("Input has invalid pubkey");if(e.signature&&!e.signature.equals(a[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(a[1]))throw new TypeError("Pubkey mismatch");const c=Uu.hash160(a[1]);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch")}}return Object.assign(i,e)}qc.p2pkh=kk;var Vc={};Object.defineProperty(Vc,"__esModule",{value:!0});Vc.p2sh=void 0;const Hp=rs,Tk=gt,jr=Yt(),Ce=wt,Ur=Gt,zp=sh,Li=jr.OPS;function Ik(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,Ce.typeforce)({network:Ce.typeforce.maybe(Ce.typeforce.Object),address:Ce.typeforce.maybe(Ce.typeforce.String),hash:Ce.typeforce.maybe(Ce.typeforce.BufferN(20)),output:Ce.typeforce.maybe(Ce.typeforce.BufferN(23)),redeem:Ce.typeforce.maybe({network:Ce.typeforce.maybe(Ce.typeforce.Object),output:Ce.typeforce.maybe(Ce.typeforce.Buffer),input:Ce.typeforce.maybe(Ce.typeforce.Buffer),witness:Ce.typeforce.maybe(Ce.typeforce.arrayOf(Ce.typeforce.Buffer))}),input:Ce.typeforce.maybe(Ce.typeforce.Buffer),witness:Ce.typeforce.maybe(Ce.typeforce.arrayOf(Ce.typeforce.Buffer))},e);let r=e.network;r||(r=e.redeem&&e.redeem.network||Tk.bitcoin);const n={network:r},s=Ur.value(()=>{const a=Buffer.from(zp.decode(e.address)),c=a.readUInt8(0),l=a.slice(1);return{version:c,hash:l}}),i=Ur.value(()=>jr.decompile(e.input)),o=Ur.value(()=>{const a=i(),c=a[a.length-1];return{network:r,output:c===Li.OP_FALSE?Buffer.from([]):c,input:jr.compile(a.slice(0,-1)),witness:e.witness||[]}});if(Ur.prop(n,"address",()=>{if(!n.hash)return;const a=Buffer.allocUnsafe(21);return a.writeUInt8(n.network.scriptHash,0),n.hash.copy(a,1),zp.encode(a)}),Ur.prop(n,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return s().hash;if(n.redeem&&n.redeem.output)return Hp.hash160(n.redeem.output)}),Ur.prop(n,"output",()=>{if(n.hash)return jr.compile([Li.OP_HASH160,n.hash,Li.OP_EQUAL])}),Ur.prop(n,"redeem",()=>{if(e.input)return o()}),Ur.prop(n,"input",()=>{if(!(!e.redeem||!e.redeem.input||!e.redeem.output))return jr.compile([].concat(jr.decompile(e.redeem.input),e.redeem.output))}),Ur.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),Ur.prop(n,"name",()=>{const a=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&a.push(n.redeem.name),a.join("-")}),t.validate){let a=Buffer.from([]);if(e.address){if(s().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(s().hash.length!==20)throw new TypeError("Invalid address");a=s().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!==23||e.output[0]!==Li.OP_HASH160||e.output[1]!==20||e.output[22]!==Li.OP_EQUAL)throw new TypeError("Output is invalid");const l=e.output.slice(2,22);if(a.length>0&&!a.equals(l))throw new TypeError("Hash mismatch");a=l}const c=l=>{if(l.output){const u=jr.decompile(l.output);if(!u||u.length<1)throw new TypeError("Redeem.output too short");if(l.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(jr.countNonPushOnlyOPs(u)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const f=Hp.hash160(l.output);if(a.length>0&&!a.equals(f))throw new TypeError("Hash mismatch");a=f}if(l.input){const u=l.input.length>0,f=l.witness&&l.witness.length>0;if(!u&&!f)throw new TypeError("Empty input");if(u&&f)throw new TypeError("Input and witness provided");if(u){const p=jr.decompile(l.input);if(!jr.isPushOnly(p))throw new TypeError("Non push-only scriptSig")}}};if(e.input){const l=i();if(!l||l.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(o().output))throw new TypeError("Input is invalid");c(o())}if(e.redeem){if(e.redeem.network&&e.redeem.network!==r)throw new TypeError("Network mismatch");if(e.input){const l=o();if(e.redeem.output&&!e.redeem.output.equals(l.output))throw new TypeError("Redeem.output mismatch");if(e.redeem.input&&!e.redeem.input.equals(l.input))throw new TypeError("Redeem.input mismatch")}c(e.redeem)}if(e.witness&&e.redeem&&e.redeem.witness&&!(0,Ce.stacksEqual)(e.redeem.witness,e.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,e)}Vc.p2sh=Ik;var Gc={},An={};Object.defineProperty(An,"__esModule",{value:!0});An.bech32m=An.bech32=void 0;const sc="qpzry9x8gf2tvdw0s3jn54khce6mua7l",jb={};for(let e=0;e<sc.length;e++){const t=sc.charAt(e);jb[t]=e}function di(e){const t=e>>25;return(e&33554431)<<5^-(t>>0&1)&996825010^-(t>>1&1)&642813549^-(t>>2&1)&513874426^-(t>>3&1)&1027748829^-(t>>4&1)&705979059}function qp(e){let t=1;for(let r=0;r<e.length;++r){const n=e.charCodeAt(r);if(n<33||n>126)return"Invalid prefix ("+e+")";t=di(t)^n>>5}t=di(t);for(let r=0;r<e.length;++r){const n=e.charCodeAt(r);t=di(t)^n&31}return t}function ih(e,t,r,n){let s=0,i=0;const o=(1<<r)-1,a=[];for(let c=0;c<e.length;++c)for(s=s<<t|e[c],i+=t;i>=r;)i-=r,a.push(s>>i&o);if(n)i>0&&a.push(s<<r-i&o);else{if(i>=t)return"Excess padding";if(s<<r-i&o)return"Non-zero padding"}return a}function Pk(e){return ih(e,8,5,!0)}function Ok(e){const t=ih(e,5,8,!1);if(Array.isArray(t))return t}function Bk(e){const t=ih(e,5,8,!1);if(Array.isArray(t))return t;throw new Error(t)}function Lb(e){let t;e==="bech32"?t=1:t=734539939;function r(o,a,c){if(c=c||90,o.length+7+a.length>c)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let l=qp(o);if(typeof l=="string")throw new Error(l);let u=o+"1";for(let f=0;f<a.length;++f){const p=a[f];if(p>>5)throw new Error("Non 5-bit word");l=di(l)^p,u+=sc.charAt(p)}for(let f=0;f<6;++f)l=di(l);l^=t;for(let f=0;f<6;++f){const p=l>>(5-f)*5&31;u+=sc.charAt(p)}return u}function n(o,a){if(a=a||90,o.length<8)return o+" too short";if(o.length>a)return"Exceeds length limit";const c=o.toLowerCase(),l=o.toUpperCase();if(o!==c&&o!==l)return"Mixed-case string "+o;o=c;const u=o.lastIndexOf("1");if(u===-1)return"No separator character for "+o;if(u===0)return"Missing prefix for "+o;const f=o.slice(0,u),p=o.slice(u+1);if(p.length<6)return"Data too short";let d=qp(f);if(typeof d=="string")return d;const m=[];for(let g=0;g<p.length;++g){const w=p.charAt(g),A=jb[w];if(A===void 0)return"Unknown character "+w;d=di(d)^A,!(g+6>=p.length)&&m.push(A)}return d!==t?"Invalid checksum for "+o:{prefix:f,words:m}}function s(o,a){const c=n(o,a);if(typeof c=="object")return c}function i(o,a){const c=n(o,a);if(typeof c=="object")return c;throw new Error(c)}return{decodeUnsafe:s,decode:i,encode:r,toWords:Pk,fromWordsUnsafe:Ok,fromWords:Bk}}An.bech32=Lb("bech32");An.bech32m=Lb("bech32m");Object.defineProperty(Gc,"__esModule",{value:!0});Gc.p2wpkh=void 0;const Mu=rs,Ck=gt,za=Yt(),et=wt,Nn=Gt,_a=An,Vp=za.OPS,Rk=Buffer.alloc(0);function $k(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,et.typeforce)({address:et.typeforce.maybe(et.typeforce.String),hash:et.typeforce.maybe(et.typeforce.BufferN(20)),input:et.typeforce.maybe(et.typeforce.BufferN(0)),network:et.typeforce.maybe(et.typeforce.Object),output:et.typeforce.maybe(et.typeforce.BufferN(22)),pubkey:et.typeforce.maybe(et.isPoint),signature:et.typeforce.maybe(za.isCanonicalScriptSignature),witness:et.typeforce.maybe(et.typeforce.arrayOf(et.typeforce.Buffer))},e);const r=Nn.value(()=>{const i=_a.bech32.decode(e.address),o=i.words.shift(),a=_a.bech32.fromWords(i.words);return{version:o,prefix:i.prefix,data:Buffer.from(a)}}),n=e.network||Ck.bitcoin,s={name:"p2wpkh",network:n};if(Nn.prop(s,"address",()=>{if(!s.hash)return;const i=_a.bech32.toWords(s.hash);return i.unshift(0),_a.bech32.encode(n.bech32,i)}),Nn.prop(s,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return r().data;if(e.pubkey||s.pubkey)return Mu.hash160(e.pubkey||s.pubkey)}),Nn.prop(s,"output",()=>{if(s.hash)return za.compile([Vp.OP_0,s.hash])}),Nn.prop(s,"pubkey",()=>{if(e.pubkey)return e.pubkey;if(e.witness)return e.witness[1]}),Nn.prop(s,"signature",()=>{if(e.witness)return e.witness[0]}),Nn.prop(s,"input",()=>{if(s.witness)return Rk}),Nn.prop(s,"witness",()=>{if(e.pubkey&&e.signature)return[e.signature,e.pubkey]}),t.validate){let i=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");i=r().data}if(e.hash){if(i.length>0&&!i.equals(e.hash))throw new TypeError("Hash mismatch");i=e.hash}if(e.output){if(e.output.length!==22||e.output[0]!==Vp.OP_0||e.output[1]!==20)throw new TypeError("Output is invalid");if(i.length>0&&!i.equals(e.output.slice(2)))throw new TypeError("Hash mismatch");i=e.output.slice(2)}if(e.pubkey){const o=Mu.hash160(e.pubkey);if(i.length>0&&!i.equals(o))throw new TypeError("Hash mismatch");if(i=o,!(0,et.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(!za.isCanonicalScriptSignature(e.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,et.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 o=Mu.hash160(e.witness[1]);if(i.length>0&&!i.equals(o))throw new TypeError("Hash mismatch")}}return Object.assign(s,e)}Gc.p2wpkh=$k;var Wc={};Object.defineProperty(Wc,"__esModule",{value:!0});Wc.p2wsh=void 0;const Gp=rs,Nk=gt,cn=Yt(),Oe=wt,tn=Gt,ka=An,Wp=cn.OPS,Fu=Buffer.alloc(0);function Ta(e){return!!(Buffer.isBuffer(e)&&e.length===65&&e[0]===4&&(0,Oe.isPoint)(e))}function Uk(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,Oe.typeforce)({network:Oe.typeforce.maybe(Oe.typeforce.Object),address:Oe.typeforce.maybe(Oe.typeforce.String),hash:Oe.typeforce.maybe(Oe.typeforce.BufferN(32)),output:Oe.typeforce.maybe(Oe.typeforce.BufferN(34)),redeem:Oe.typeforce.maybe({input:Oe.typeforce.maybe(Oe.typeforce.Buffer),network:Oe.typeforce.maybe(Oe.typeforce.Object),output:Oe.typeforce.maybe(Oe.typeforce.Buffer),witness:Oe.typeforce.maybe(Oe.typeforce.arrayOf(Oe.typeforce.Buffer))}),input:Oe.typeforce.maybe(Oe.typeforce.BufferN(0)),witness:Oe.typeforce.maybe(Oe.typeforce.arrayOf(Oe.typeforce.Buffer))},e);const r=tn.value(()=>{const o=ka.bech32.decode(e.address),a=o.words.shift(),c=ka.bech32.fromWords(o.words);return{version:a,prefix:o.prefix,data:Buffer.from(c)}}),n=tn.value(()=>cn.decompile(e.redeem.input));let s=e.network;s||(s=e.redeem&&e.redeem.network||Nk.bitcoin);const i={network:s};if(tn.prop(i,"address",()=>{if(!i.hash)return;const o=ka.bech32.toWords(i.hash);return o.unshift(0),ka.bech32.encode(s.bech32,o)}),tn.prop(i,"hash",()=>{if(e.output)return e.output.slice(2);if(e.address)return r().data;if(i.redeem&&i.redeem.output)return Gp.sha256(i.redeem.output)}),tn.prop(i,"output",()=>{if(i.hash)return cn.compile([Wp.OP_0,i.hash])}),tn.prop(i,"redeem",()=>{if(e.witness)return{output:e.witness[e.witness.length-1],input:Fu,witness:e.witness.slice(0,-1)}}),tn.prop(i,"input",()=>{if(i.witness)return Fu}),tn.prop(i,"witness",()=>{if(e.redeem&&e.redeem.input&&e.redeem.input.length>0&&e.redeem.output&&e.redeem.output.length>0){const o=cn.toStack(n());return i.redeem=Object.assign({witness:o},e.redeem),i.redeem.input=Fu,[].concat(o,e.redeem.output)}if(e.redeem&&e.redeem.output&&e.redeem.witness)return[].concat(e.redeem.witness,e.redeem.output)}),tn.prop(i,"name",()=>{const o=["p2wsh"];return i.redeem!==void 0&&i.redeem.name!==void 0&&o.push(i.redeem.name),o.join("-")}),t.validate){let o=Buffer.from([]);if(e.address){if(r().prefix!==s.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==32)throw new TypeError("Invalid address data");o=r().data}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!==34||e.output[0]!==Wp.OP_0||e.output[1]!==32)throw new TypeError("Output is invalid");const a=e.output.slice(2);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.redeem){if(e.redeem.network&&e.redeem.network!==s)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 a=cn.decompile(e.redeem.output);if(!a||a.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(cn.countNonPushOnlyOPs(a)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const c=Gp.sha256(e.redeem.output);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch");o=c}if(e.redeem.input&&!cn.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(e.witness&&e.redeem.witness&&!(0,Oe.stacksEqual)(e.witness,e.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(e.redeem.input&&n().some(Ta)||e.redeem.output&&(cn.decompile(e.redeem.output)||[]).some(Ta))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(e.witness&&e.witness.length>0){const a=e.witness[e.witness.length-1];if(e.redeem&&e.redeem.output&&!e.redeem.output.equals(a))throw new TypeError("Witness and redeem.output mismatch");if(e.witness.some(Ta)||(cn.decompile(a)||[]).some(Ta))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(i,e)}Wc.p2wsh=Uk;var Di={},Rs={};Object.defineProperty(Rs,"__esModule",{value:!0});Rs.getEccLib=Rs.initEccLib=void 0;const so={};function Mk(e,t){e?e!==so.eccLib&&(t!=null&&t.DANGER_DO_NOT_VERIFY_ECCLIB||jk(e),so.eccLib=e):so.eccLib=e}Rs.initEccLib=Mk;function Fk(){if(!so.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return so.eccLib}Rs.getEccLib=Fk;const rn=e=>Buffer.from(e,"hex");function jk(e){Jt(typeof e.isXOnlyPoint=="function"),Jt(e.isXOnlyPoint(rn("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),Jt(e.isXOnlyPoint(rn("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),Jt(e.isXOnlyPoint(rn("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),Jt(e.isXOnlyPoint(rn("0000000000000000000000000000000000000000000000000000000000000001"))),Jt(!e.isXOnlyPoint(rn("0000000000000000000000000000000000000000000000000000000000000000"))),Jt(!e.isXOnlyPoint(rn("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),Jt(typeof e.xOnlyPointAddTweak=="function"),Lk.forEach(t=>{const r=e.xOnlyPointAddTweak(rn(t.pubkey),rn(t.tweak));t.result===null?Jt(r===null):(Jt(r!==null),Jt(r.parity===t.parity),Jt(Buffer.from(r.xOnlyPubkey).equals(rn(t.result))))})}function Jt(e){if(!e)throw new Error("ecc library invalid")}const Lk=[{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 oh={};(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=Hs,r=Rs,n=rs,s=ct,i=wt;e.LEAF_VERSION_TAPSCRIPT=192,e.MAX_TAPTREE_DEPTH=128;const o=g=>"left"in g&&"right"in g;function a(g,w){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 T=w;for(let E=0;E<A;E++){const S=g.slice(33+32*E,65+32*E);T.compare(S)<0?T=d(T,S):T=d(S,T)}return T}e.rootHashFromPath=a;function c(g){if((0,i.isTapleaf)(g))return{hash:u(g)};const w=[c(g[0]),c(g[1])];w.sort((E,S)=>E.hash.compare(S.hash));const[A,T]=w;return{hash:d(A.hash,T.hash),left:A,right:T}}e.toHashTree=c;function l(g,w){if(o(g)){const A=l(g.left,w);if(A!==void 0)return[...A,g.right.hash];const T=l(g.right,w);if(T!==void 0)return[...T,g.left.hash]}else if(g.hash.equals(w))return[]}e.findScriptPath=l;function u(g){const w=g.version||e.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",t.Buffer.concat([t.Buffer.from([w]),m(g.output)]))}e.tapleafHash=u;function f(g,w){return n.taggedHash("TapTweak",t.Buffer.concat(w?[g,w]:[g]))}e.tapTweakHash=f;function p(g,w){if(!t.Buffer.isBuffer(g)||g.length!==32||w&&w.length!==32)return null;const A=f(g,w),T=(0,r.getEccLib)().xOnlyPointAddTweak(g,A);return!T||T.xOnlyPubkey===null?null:{parity:T.parity,x:t.Buffer.from(T.xOnlyPubkey)}}e.tweakKey=p;function d(g,w){return n.taggedHash("TapBranch",t.Buffer.concat([g,w]))}function m(g){const w=s.varuint.encodingLength(g.length),A=t.Buffer.allocUnsafe(w);return s.varuint.encode(g.length,A),t.Buffer.concat([A,g])}})(oh);var St={},Kp;function Dk(){if(Kp)return St;Kp=1,Object.defineProperty(St,"__esModule",{value:!0}),St.toOutputScript=St.fromOutputScript=St.toBech32=St.toBase58Check=St.fromBech32=St.fromBase58Check=void 0;const e=gt,t=ah(),r=Yt(),n=wt,s=An,i=sh,o=40,a=2,c=16,l=2,u=80,f="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function p(E,S){const I=E.slice(2);if(I.length<a||I.length>o)throw new TypeError("Invalid program length for segwit address");const P=E[0]-u;if(P<l||P>c)throw new TypeError("Invalid version for segwit address");if(E[1]!==I.length)throw new TypeError("Invalid script for segwit address");return console.warn(f),w(I,P,S.bech32)}function d(E){const S=Buffer.from(i.decode(E));if(S.length<21)throw new TypeError(E+" is too short");if(S.length>21)throw new TypeError(E+" is too long");const I=S.readUInt8(0),P=S.slice(1);return{version:I,hash:P}}St.fromBase58Check=d;function m(E){let S,I;try{S=s.bech32.decode(E)}catch{}if(S){if(I=S.words[0],I!==0)throw new TypeError(E+" uses wrong encoding")}else if(S=s.bech32m.decode(E),I=S.words[0],I===0)throw new TypeError(E+" uses wrong encoding");const P=s.bech32.fromWords(S.words.slice(1));return{version:I,prefix:S.prefix,data:Buffer.from(P)}}St.fromBech32=m;function g(E,S){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const I=Buffer.allocUnsafe(21);return I.writeUInt8(S,0),E.copy(I,1),i.encode(I)}St.toBase58Check=g;function w(E,S,I){const P=s.bech32.toWords(E);return P.unshift(S),S===0?s.bech32.encode(I,P):s.bech32m.encode(I,P)}St.toBech32=w;function A(E,S){S=S||e.bitcoin;try{return t.p2pkh({output:E,network:S}).address}catch{}try{return t.p2sh({output:E,network:S}).address}catch{}try{return t.p2wpkh({output:E,network:S}).address}catch{}try{return t.p2wsh({output:E,network:S}).address}catch{}try{return t.p2tr({output:E,network:S}).address}catch{}try{return p(E,S)}catch{}throw new Error(r.toASM(E)+" has no matching Address")}St.fromOutputScript=A;function T(E,S){S=S||e.bitcoin;let I,P;try{I=d(E)}catch{}if(I){if(I.version===S.pubKeyHash)return t.p2pkh({hash:I.hash}).output;if(I.version===S.scriptHash)return t.p2sh({hash:I.hash}).output}else{try{P=m(E)}catch{}if(P){if(P.prefix!==S.bech32)throw new Error(E+" has an invalid prefix");if(P.version===0){if(P.data.length===20)return t.p2wpkh({hash:P.data}).output;if(P.data.length===32)return t.p2wsh({hash:P.data}).output}else if(P.version===1){if(P.data.length===32)return t.p2tr({pubkey:P.data}).output}else if(P.version>=l&&P.version<=c&&P.data.length>=a&&P.data.length<=o)return console.warn(f),r.compile([P.version+u,P.data])}}throw new Error(E+" has no matching Script")}return St.toOutputScript=T,St}var Xp;function Hk(){if(Xp)return Di;Xp=1,Object.defineProperty(Di,"__esModule",{value:!0}),Di.p2tr=void 0;const e=Hs,t=gt,r=Yt(),n=wt,s=Rs,i=oh,o=Gt,a=An,c=Dk(),l=r.OPS,u=1,f=80;function p(d,m){if(!d.address&&!d.output&&!d.pubkey&&!d.internalPubkey&&!(d.witness&&d.witness.length>1))throw new TypeError("Not enough data");m=Object.assign({validate:!0},m||{}),(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=o.value(()=>(0,c.fromBech32)(d.address)),w=o.value(()=>{if(!(!d.witness||!d.witness.length))return d.witness.length>=2&&d.witness[d.witness.length-1][0]===f?d.witness.slice(0,-1):d.witness.slice()}),A=o.value(()=>{if(d.scriptTree)return(0,i.toHashTree)(d.scriptTree);if(d.hash)return{hash:d.hash}}),T=d.network||t.bitcoin,E={name:"p2tr",network:T};if(o.prop(E,"address",()=>{if(!E.pubkey)return;const S=a.bech32m.toWords(E.pubkey);return S.unshift(u),a.bech32m.encode(T.bech32,S)}),o.prop(E,"hash",()=>{const S=A();if(S)return S.hash;const I=w();if(I&&I.length>1){const P=I[I.length-1],$=P[0]&n.TAPLEAF_VERSION_MASK,j=I[I.length-2],k=(0,i.tapleafHash)({output:j,version:$});return(0,i.rootHashFromPath)(P,k)}return null}),o.prop(E,"output",()=>{if(E.pubkey)return r.compile([l.OP_1,E.pubkey])}),o.prop(E,"redeemVersion",()=>d.redeemVersion?d.redeemVersion:d.redeem&&d.redeem.redeemVersion!==void 0&&d.redeem.redeemVersion!==null?d.redeem.redeemVersion:i.LEAF_VERSION_TAPSCRIPT),o.prop(E,"redeem",()=>{const S=w();if(!(!S||S.length<2))return{output:S[S.length-2],witness:S.slice(0,-2),redeemVersion:S[S.length-1][0]&n.TAPLEAF_VERSION_MASK}}),o.prop(E,"pubkey",()=>{if(d.pubkey)return d.pubkey;if(d.output)return d.output.slice(2);if(d.address)return g().data;if(E.internalPubkey){const S=(0,i.tweakKey)(E.internalPubkey,E.hash);if(S)return S.x}}),o.prop(E,"internalPubkey",()=>{if(d.internalPubkey)return d.internalPubkey;const S=w();if(S&&S.length>1)return S[S.length-1].slice(1,33)}),o.prop(E,"signature",()=>{if(d.signature)return d.signature;const S=w();if(!(!S||S.length!==1))return S[0]}),o.prop(E,"witness",()=>{if(d.witness)return d.witness;const S=A();if(S&&d.redeem&&d.redeem.output&&d.internalPubkey){const I=(0,i.tapleafHash)({output:d.redeem.output,version:E.redeemVersion}),P=(0,i.findScriptPath)(S,I);if(!P)return;const $=(0,i.tweakKey)(d.internalPubkey,S.hash);if(!$)return;const j=e.Buffer.concat([e.Buffer.from([E.redeemVersion|$.parity]),d.internalPubkey].concat(P));return[d.redeem.output,j]}if(d.signature)return[d.signature]}),m.validate){let S=e.Buffer.from([]);if(d.address){if(T&&T.bech32!==g().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(g().version!==u)throw new TypeError("Invalid address version");if(g().data.length!==32)throw new TypeError("Invalid address data");S=g().data}if(d.pubkey){if(S.length>0&&!S.equals(d.pubkey))throw new TypeError("Pubkey mismatch");S=d.pubkey}if(d.output){if(d.output.length!==34||d.output[0]!==l.OP_1||d.output[1]!==32)throw new TypeError("Output is invalid");if(S.length>0&&!S.equals(d.output.slice(2)))throw new TypeError("Pubkey mismatch");S=d.output.slice(2)}if(d.internalPubkey){const $=(0,i.tweakKey)(d.internalPubkey,E.hash);if(S.length>0&&!S.equals($.x))throw new TypeError("Pubkey mismatch");S=$.x}if(S&&S.length&&!(0,s.getEccLib)().isXOnlyPoint(S))throw new TypeError("Invalid pubkey for p2tr");const I=A();if(d.hash&&I&&!d.hash.equals(I.hash))throw new TypeError("Hash mismatch");if(d.redeem&&d.redeem.output&&I){const $=(0,i.tapleafHash)({output:d.redeem.output,version:E.redeemVersion});if(!(0,i.findScriptPath)(I,$))throw new TypeError("Redeem script not in tree")}const P=w();if(d.redeem&&E.redeem){if(d.redeem.redeemVersion&&d.redeem.redeemVersion!==E.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(E.redeem.output&&!d.redeem.output.equals(E.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(d.redeem.witness&&E.redeem.witness&&!(0,n.stacksEqual)(d.redeem.witness,E.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(P&&P.length)if(P.length===1){if(d.signature&&!d.signature.equals(P[0]))throw new TypeError("Signature mismatch")}else{const $=P[P.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 j=($.length-33)/32;if(j>128)throw new TypeError(`The script path is too long. Got ${j}, expected max 128.`);const k=$.slice(1,33);if(d.internalPubkey&&!d.internalPubkey.equals(k))throw new TypeError("Internal pubkey mismatch");if(!(0,s.getEccLib)().isXOnlyPoint(k))throw new TypeError("Invalid internalPubkey for p2tr witness");const F=$[0]&n.TAPLEAF_VERSION_MASK,R=P[P.length-2],U=(0,i.tapleafHash)({output:R,version:F}),H=(0,i.rootHashFromPath)($,U),W=(0,i.tweakKey)(k,H);if(!W)throw new TypeError("Invalid outputKey for p2tr witness");if(S.length&&!S.equals(W.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(W.parity!==($[0]&1))throw new Error("Incorrect parity")}}return Object.assign(E,d)}return Di.p2tr=p,Di}var Yp;function ah(){return Yp||(Yp=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=Dc;Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const r=Hc;Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=zc;Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const s=qc;Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return s.p2pkh}});const i=Vc;Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return i.p2sh}});const o=Gc;Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const a=Wc;Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return a.p2wsh}});const c=Hk();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return c.p2tr}})}($u)),$u}Object.defineProperty(Ie,"__esModule",{value:!0});Ie.signatureBlocksAction=Ie.checkInputForSig=Ie.pubkeyInScript=Ie.pubkeyPositionInScript=Ie.witnessStackToScriptWitness=Ie.isP2TR=Ie.isP2SHScript=Ie.isP2WSHScript=Ie.isP2WPKH=Ie.isP2PKH=Ie.isP2PK=Ie.isP2MS=void 0;const Zp=aa,io=Yt(),Ia=oa,zk=rs,zs=ah();function qs(e){return t=>{try{return e({output:t}),!0}catch{return!1}}}Ie.isP2MS=qs(zs.p2ms);Ie.isP2PK=qs(zs.p2pk);Ie.isP2PKH=qs(zs.p2pkh);Ie.isP2WPKH=qs(zs.p2wpkh);Ie.isP2WSHScript=qs(zs.p2wsh);Ie.isP2SHScript=qs(zs.p2sh);Ie.isP2TR=qs(zs.p2tr);function qk(e){let t=Buffer.allocUnsafe(0);function r(o){t=Buffer.concat([t,Buffer.from(o)])}function n(o){const a=t.length,c=Zp.encodingLength(o);t=Buffer.concat([t,Buffer.allocUnsafe(c)]),Zp.encode(o,t,a)}function s(o){n(o.length),r(o)}function i(o){n(o.length),o.forEach(s)}return i(e),t}Ie.witnessStackToScriptWitness=qk;function Db(e,t){const r=(0,zk.hash160)(e),n=e.slice(1,33),s=io.decompile(t);if(s===null)throw new Error("Unknown script error");return s.findIndex(i=>typeof i=="number"?!1:i.equals(e)||i.equals(r)||i.equals(n))}Ie.pubkeyPositionInScript=Db;function Vk(e,t){return Db(e,t)!==-1}Ie.pubkeyInScript=Vk;function Gk(e,t){return Wk(e).some(n=>Hb(n,io.signature.decode,t))}Ie.checkInputForSig=Gk;function Hb(e,t,r){const{hashType:n}=t(e),s=[];switch(n&Ia.Transaction.SIGHASH_ANYONECANPAY&&s.push("addInput"),n&31){case Ia.Transaction.SIGHASH_ALL:break;case Ia.Transaction.SIGHASH_SINGLE:case Ia.Transaction.SIGHASH_NONE:s.push("addOutput"),s.push("setInputSequence");break}return s.indexOf(r)===-1}Ie.signatureBlocksAction=Hb;function Wk(e){let t=[];if((e.partialSig||[]).length===0){if(!e.finalScriptSig&&!e.finalScriptWitness)return[];t=Kk(e)}else t=e.partialSig;return t.map(r=>r.signature)}function Kk(e){const t=e.finalScriptSig?io.decompile(e.finalScriptSig)||[]:[],r=e.finalScriptWitness?io.decompile(e.finalScriptWitness)||[]:[];return t.concat(r).filter(n=>Buffer.isBuffer(n)&&io.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(Le,"__esModule",{value:!0});Le.checkTaprootInputForSigs=Le.tapTreeFromList=Le.tapTreeToList=Le.tweakInternalPubKey=Le.checkTaprootOutputFields=Le.checkTaprootInputFields=Le.isTaprootOutput=Le.isTaprootInput=Zi=Le.serializeTaprootSignature=Le.tapScriptFinalizer=Le.toXOnly=void 0;const ch=wt,Xk=oa,Kc=Ie,es=oh,Yk=ah(),Zk=Ie,Jk=e=>e.length===32?e:e.slice(1,33);Le.toXOnly=Jk;function Qk(e,t,r){const n=gT(t,e,r);try{const i=yT(t,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,Kc.witnessStackToScriptWitness)(i)}}catch(s){throw new Error(`Can not finalize taproot input #${e}: ${s}`)}}Le.tapScriptFinalizer=Qk;function eT(e,t){const r=t?Buffer.from([t]):Buffer.from([]);return Buffer.concat([e,r])}var Zi=Le.serializeTaprootSignature=eT;function qa(e){return e&&!!(e.tapInternalKey||e.tapMerkleRoot||e.tapLeafScript&&e.tapLeafScript.length||e.tapBip32Derivation&&e.tapBip32Derivation.length||e.witnessUtxo&&(0,Kc.isP2TR)(e.witnessUtxo.script))}Le.isTaprootInput=qa;function Va(e,t){return e&&!!(e.tapInternalKey||e.tapTree||e.tapBip32Derivation&&e.tapBip32Derivation.length||t&&(0,Kc.isP2TR)(t))}Le.isTaprootOutput=Va;function tT(e,t,r){dT(e,t,r),pT(e,t,r)}Le.checkTaprootInputFields=tT;function rT(e,t,r){hT(e,t,r),nT(e,t)}Le.checkTaprootOutputFields=rT;function nT(e,t){if(!t.tapTree&&!t.tapInternalKey)return;const r=t.tapInternalKey||e.tapInternalKey,n=t.tapTree||e.tapTree;if(r){const{script:s}=e,i=sT(r,n);if(s&&!s.equals(i))throw new Error("Error adding output. Script or address missmatch.")}}function sT(e,t){const r=t&&zb(t.leaves),{output:n}=(0,Yk.p2tr)({internalPubkey:e,scriptTree:r});return n}function iT(e,t){const r=t.tapInternalKey,n=r&&(0,es.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}Le.tweakInternalPubKey=iT;function oT(e){if(!(0,ch.isTaptree)(e))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return Df(e)}Le.tapTreeToList=oT;function zb(e=[]){return e.length===1&&e[0].depth===0?{output:e[0].script,version:e[0].leafVersion}:fT(e)}Le.tapTreeFromList=zb;function aT(e,t){return uT(e).some(n=>(0,Zk.signatureBlocksAction)(n,cT,t))}Le.checkTaprootInputForSigs=aT;function cT(e){return{signature:e.slice(0,64),hashType:e.slice(64)[0]||Xk.Transaction.SIGHASH_DEFAULT}}function uT(e){const t=[];if(e.tapKeySig&&t.push(e.tapKeySig),e.tapScriptSig&&t.push(...e.tapScriptSig.map(r=>r.signature)),!t.length){const r=lT(e.finalScriptWitness);r&&t.push(r)}return t}function lT(e){if(!e)return;const t=e.slice(2);if(t.length===64||t.length===65)return t}function Df(e,t=[],r=0){if(r>es.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return e?(0,ch.isTapleaf)(e)?(t.push({depth:r,leafVersion:e.version||es.LEAF_VERSION_TAPSCRIPT,script:e.output}),t):(e[0]&&Df(e[0],t,r+1),e[1]&&Df(e[1],t,r+1),t):[]}function fT(e){let t;for(const r of e)if(t=Hf(r,t),!t)throw new Error("No room left to insert tapleaf in tree");return t}function Hf(e,t,r=0){if(r>es.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,ch.isTapleaf)(t))return;const n=Hf(e,t&&t[0],r+1);if(n)return[n,t&&t[1]];const s=Hf(e,t&&t[1],r+1);if(s)return[t&&t[0],s]}function dT(e,t,r){const n=qa(e)&&hi(t),s=hi(e)&&qa(t),i=e===t&&qa(t)&&hi(t);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function hT(e,t,r){const n=Va(e)&&hi(t),s=hi(e)&&Va(t),i=e===t&&Va(t)&&hi(t);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function pT(e,t,r){if(t.tapMerkleRoot){const n=(t.tapLeafScript||[]).every(i=>ju(i,t.tapMerkleRoot)),s=(e.tapLeafScript||[]).every(i=>ju(i,t.tapMerkleRoot));if(!n||!s)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(e.tapMerkleRoot&&!(t.tapLeafScript||[]).every(s=>ju(s,e.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function ju(e,t){if(!t)return!0;const r=(0,es.tapleafHash)({output:e.script,version:e.leafVersion});return(0,es.rootHashFromPath)(e.controlBlock,r).equals(t)}function yT(e,t){const r=(0,es.tapleafHash)({output:t.script,version:t.leafVersion});return(e.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>mT(t.script,n)).sort((n,s)=>s.positionInScript-n.positionInScript).map(n=>n.signature)}function mT(e,t){return Object.assign({positionInScript:(0,Kc.pubkeyPositionInScript)(t.pubkey,e)},t)}function gT(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((s,i)=>s.controlBlock.length-i.controlBlock.length).find(s=>bT(s,e.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${t}. Signature for tapleaf script not found.`);return n}function bT(e,t,r){const n=(0,es.tapleafHash)({output:e.script,version:e.leafVersion});return(!r||r.equals(n))&&t.find(i=>i.leafHash.equals(n))!==void 0}function hi(e){return e&&!!(e.redeemScript||e.witnessScript||e.bip32Derivation&&e.bip32Derivation.length)}const _t={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"},Pa=192;Se.initEccLib(ar);class oo{constructor(t,r,n,s,i,o,a,c){this.secretHash=n,this.redeemerPubkey=s,this.initiatorPubkey=i,this.expiry=o,this.signer=t,this.network=a,this.internalPubkey=g_(),this.initiateAmount=r,this.utxoHashes=c}static async from(t,r,n,s,i,o,a){n=n.startsWith("0x")?n.slice(2):n,Xs(n.length===64,_t.secretHashLenMismatch),Xs(s.length===64||s.length===66,`initiator ${_t.pubkeyLenMismatch}`),Xs(i.length===64||i.length===66,`redeemer ${_t.pubkeyLenMismatch}`),Xs(o>0,_t.zeroOrNegativeExpiry);const c=await t.getNetwork();return new oo(t,r,n,Nf(i).toString("hex"),Nf(s).toString("hex"),o,c,a)}address(){const{address:t}=Se.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves()});if(!t)throw new Error(_t.htlcAddressGenerationFailed);return t}id(){return this.address()}async _buildRawTx(t,r){const n=new Se.Transaction;n.version=2;const s=this.address(),i=await this.signer.getProvider();let o=[];if(this.utxoHashes&&this.utxoHashes.length>0)for(const l of this.utxoHashes){const u=await i.getTransaction(l);for(let f=0;f<u.vout.length;f++){const p=u.vout[f];p.scriptpubkey_address===s&&o.push({txid:u.txid,vout:f,value:p.value,status:{confirmed:!1}})}}else o=await i.getUTXOs(s);const a=o.reduce((l,u)=>l+u.value,0);if(a===0)throw new Error(`${s} ${_t.notFunded}`);for(let l=0;l<o.length;l++)n.addInput(Buffer.from(o[l].txid,"hex").reverse(),o[l].vout);if(r!=null&&r.vSize){const l=await i.getFeeRates(),u=Math.ceil(l.hourFee*r.vSize),f=a-u;return n.addOutput(Se.address.toOutputScript(t,this.network),f),{tx:n,usedUtxos:o}}const c=(r==null?void 0:r.fee)??await i.suggestFee(s,a,li.MEDIUM);return n.addOutput(Se.address.toOutputScript(t,this.network),a-c),{tx:n,usedUtxos:o,fee:c,balance:a}}getOutputScript(){return Se.address.toOutputScript(this.address(),this.network)}async init(t){return t??(t=await(await this.signer.getProvider()).suggestFee(await this.signer.getAddress(),this.initiateAmount,li.MEDIUM)),await this.signer.send(this.address(),this.initiateAmount,t)}async generateRedeemSACP(t,r,n){const{tx:s,usedUtxos:i}=await this._buildRawTx(r,{fee:n}),o=this.getOutputScript(),a=Se.Transaction.SIGHASH_SINGLE|Se.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(1),l=i.map(f=>f.value),u=Hi(o,i.length);for(let f=0;f<s.ins.length;f++){const p=s.hashForWitnessV1(f,u,l,a,c),d=await this.signer.signSchnorr(p);s.setWitness(f,[Zi(d,a),Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return s.toHex()}async generateInstantRefundSACP(t){const r=this.getOutputScript(),{tx:n,usedUtxos:s,fee:i}=await this._buildRawTx(t,{fee:0});n.outs=[];const o=Math.max(...s.map(f=>f.value));s.forEach(({value:f})=>{n.addOutput(r,f-(f===o?i??0:0))});const a=Se.Transaction.SIGHASH_SINGLE|Se.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(2),l=s.map(f=>f.value),u=Hi(r,s.length);for(let f=0;f<n.ins.length;f++){const p=n.hashForWitnessV1(f,u,l,a,c),d=await this.signer.signSchnorr(p);n.setWitness(f,[Zi(d,a),Zi(d,a),this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return n.toHex()}async generateInstantRefundSACPWithHash(t){const r=[],n=Se.Transaction.SIGHASH_SINGLE|Se.Transaction.SIGHASH_ANYONECANPAY;for(let s=0;s<t.length;s++){const i=Buffer.from(t[s],"hex"),o=await this.signer.signSchnorr(i);r.push(Zi(o,n).toString("hex"))}return r}async instantRefund(t,r){Xs(t.length>0,_t.noCounterpartySigs);const{tx:n,usedUtxos:s}=await this._buildRawTx(await this.signer.getAddress(),{fee:r});for(const f of s)if(!t.find(p=>p.utxo===f.txid))throw new Error(_t.counterPartySigNotFound(f.txid));const i=this.getOutputScript(),o=Se.Transaction.SIGHASH_DEFAULT,a=this.leafHash(2),c=s.map(f=>f.value),l=Hi(i,s.length);for(let f=0;f<n.ins.length;f++){const p=n.hashForWitnessV1(f,l,c,o,a);if(!ar.verifySchnorr(p,Buffer.from(this.redeemerPubkey,"hex"),Buffer.from(t[f].sig,"hex")))throw new Error(_t.invalidCounterpartySigForUTXO(t[f].utxo));const d=await this.signer.signSchnorr(p),m=Buffer.from(n.ins[f].hash).reverse().toString("hex"),g=t.find(w=>w.utxo===m);if(!g)throw new Error(_t.counterPartySigNotFound(m));n.setWitness(f,[Buffer.from(g.sig,"hex"),d,this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async redeem(t,r){const n=await this.getRedeemHex(t,r);return await(await this.signer.getProvider()).broadcast(n)}async getRedeemHex(t,r){Xs(Se.crypto.sha256(Buffer.from(t,"hex")).toString("hex")===this.secretHash,_t.secretMismatch);const n=r??await this.signer.getAddress(),{tx:s,usedUtxos:i}=await this._buildRawTx(n,{fee:0}),o=this.leafHash(1),a=i.map(f=>f.value),c=Hi(this.getOutputScript(),i.length),l=Se.Transaction.SIGHASH_DEFAULT;for(let f=0;f<s.ins.length;f++){const p=s.hashForWitnessV1(f,c,a,l,o),d=await this.signer.signSchnorr(p);s.setWitness(f,[d,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}const{tx:u}=await this._buildRawTx(n,{vSize:s.virtualSize()});for(let f=0;f<u.ins.length;f++){const p=u.hashForWitnessV1(f,c,a,l,o),d=await this.signer.signSchnorr(p);u.setWitness(f,[d,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return u.toHex()}async refund(t,r){const{tx:n,usedUtxos:s}=await this._buildRawTx(t??await this.signer.getAddress(),{fee:r}),[i,o]=await this.canRefund(s);if(!i)throw new Error(_t.htlcNotExpired(o));const a=this.leafHash(0),c=s.map(p=>p.value),l=Hi(this.getOutputScript(),s.length),u=Se.Transaction.SIGHASH_DEFAULT;for(let p=0;p<n.ins.length;p++){n.ins[p].sequence=this.expiry;const d=n.hashForWitnessV1(p,l,c,u,a),m=await this.signer.signSchnorr(d);n.setWitness(p,[m,this.refundLeaf(),this.generateControlBlockFor(0)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async canRefund(t){const n=await(await this.signer.getProvider()).getLatestTip();for(const s of t){let i=0;if(s.status.confirmed&&s.status.block_height+this.expiry>n?i=s.status.block_height+this.expiry-n+1:s.status.confirmed||(i=this.expiry+1),i>0)return[!1,i]}return[!0,0]}generateControlBlockFor(t){let r;switch(t){case 1:r=this.redeemLeaf();break;case 0:r=this.refundLeaf();break;case 2:r=this.instantRefundLeaf();break;default:throw new Error(_t.invalidLeaf)}const n=Se.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves(),redeem:{output:r,redeemVersion:Pa}});if(!n.witness)throw new Error(_t.controlBlockGenerationFailed);return n.witness[n.witness.length-1]}leafHash(t){let r=this.redeemLeaf();return t===0&&(r=this.refundLeaf()),t===2&&(r=this.instantRefundLeaf()),Se.crypto.taggedHash("TapLeaf",n_(r))}refundLeaf(){return Se.script.fromASM(`
|
|
50
|
+
*/(function(e){const t=jc,r=Zd,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=a,e.SlowBuffer=T,e.INSPECT_MAX_BYTES=50;const s=2147483647;e.kMaxLength=s,a.TYPED_ARRAY_SUPPORT=i(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function i(){try{const b=new Uint8Array(1),h={foo:function(){return 42}};return Object.setPrototypeOf(h,Uint8Array.prototype),Object.setPrototypeOf(b,h),b.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(b){if(b>s)throw new RangeError('The value "'+b+'" is invalid for option "size"');const h=new Uint8Array(b);return Object.setPrototypeOf(h,a.prototype),h}function a(b,h,y){if(typeof b=="number"){if(typeof h=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return f(b)}return c(b,h,y)}a.poolSize=8192;function c(b,h,y){if(typeof b=="string")return p(b,h);if(ArrayBuffer.isView(b))return m(b);if(b==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof b);if(Et(b,ArrayBuffer)||b&&Et(b.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Et(b,SharedArrayBuffer)||b&&Et(b.buffer,SharedArrayBuffer)))return g(b,h,y);if(typeof b=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const x=b.valueOf&&b.valueOf();if(x!=null&&x!==b)return a.from(x,h,y);const C=w(b);if(C)return C;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof b[Symbol.toPrimitive]=="function")return a.from(b[Symbol.toPrimitive]("string"),h,y);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof b)}a.from=function(b,h,y){return c(b,h,y)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function l(b){if(typeof b!="number")throw new TypeError('"size" argument must be of type number');if(b<0)throw new RangeError('The value "'+b+'" is invalid for option "size"')}function u(b,h,y){return l(b),b<=0?o(b):h!==void 0?typeof y=="string"?o(b).fill(h,y):o(b).fill(h):o(b)}a.alloc=function(b,h,y){return u(b,h,y)};function f(b){return l(b),o(b<0?0:A(b)|0)}a.allocUnsafe=function(b){return f(b)},a.allocUnsafeSlow=function(b){return f(b)};function p(b,h){if((typeof h!="string"||h==="")&&(h="utf8"),!a.isEncoding(h))throw new TypeError("Unknown encoding: "+h);const y=E(b,h)|0;let x=o(y);const C=x.write(b,h);return C!==y&&(x=x.slice(0,C)),x}function d(b){const h=b.length<0?0:A(b.length)|0,y=o(h);for(let x=0;x<h;x+=1)y[x]=b[x]&255;return y}function m(b){if(Et(b,Uint8Array)){const h=new Uint8Array(b);return g(h.buffer,h.byteOffset,h.byteLength)}return d(b)}function g(b,h,y){if(h<0||b.byteLength<h)throw new RangeError('"offset" is outside of buffer bounds');if(b.byteLength<h+(y||0))throw new RangeError('"length" is outside of buffer bounds');let x;return h===void 0&&y===void 0?x=new Uint8Array(b):y===void 0?x=new Uint8Array(b,h):x=new Uint8Array(b,h,y),Object.setPrototypeOf(x,a.prototype),x}function w(b){if(a.isBuffer(b)){const h=A(b.length)|0,y=o(h);return y.length===0||b.copy(y,0,0,h),y}if(b.length!==void 0)return typeof b.length!="number"||Tn(b.length)?o(0):d(b);if(b.type==="Buffer"&&Array.isArray(b.data))return d(b.data)}function A(b){if(b>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return b|0}function T(b){return+b!=b&&(b=0),a.alloc(+b)}a.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==a.prototype},a.compare=function(h,y){if(Et(h,Uint8Array)&&(h=a.from(h,h.offset,h.byteLength)),Et(y,Uint8Array)&&(y=a.from(y,y.offset,y.byteLength)),!a.isBuffer(h)||!a.isBuffer(y))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===y)return 0;let x=h.length,C=y.length;for(let M=0,q=Math.min(x,C);M<q;++M)if(h[M]!==y[M]){x=h[M],C=y[M];break}return x<C?-1:C<x?1:0},a.isEncoding=function(h){switch(String(h).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(h,y){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return a.alloc(0);let x;if(y===void 0)for(y=0,x=0;x<h.length;++x)y+=h[x].length;const C=a.allocUnsafe(y);let M=0;for(x=0;x<h.length;++x){let q=h[x];if(Et(q,Uint8Array))M+q.length>C.length?(a.isBuffer(q)||(q=a.from(q)),q.copy(C,M)):Uint8Array.prototype.set.call(C,q,M);else if(a.isBuffer(q))q.copy(C,M);else throw new TypeError('"list" argument must be an Array of Buffers');M+=q.length}return C};function E(b,h){if(a.isBuffer(b))return b.length;if(ArrayBuffer.isView(b)||Et(b,ArrayBuffer))return b.byteLength;if(typeof b!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof b);const y=b.length,x=arguments.length>2&&arguments[2]===!0;if(!x&&y===0)return 0;let C=!1;for(;;)switch(h){case"ascii":case"latin1":case"binary":return y;case"utf8":case"utf-8":return Pr(b).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return y*2;case"hex":return y>>>1;case"base64":return Or(b).length;default:if(C)return x?-1:Pr(b).length;h=(""+h).toLowerCase(),C=!0}}a.byteLength=E;function S(b,h,y){let x=!1;if((h===void 0||h<0)&&(h=0),h>this.length||((y===void 0||y>this.length)&&(y=this.length),y<=0)||(y>>>=0,h>>>=0,y<=h))return"";for(b||(b="utf8");;)switch(b){case"hex":return B(this,h,y);case"utf8":case"utf-8":return W(this,h,y);case"ascii":return re(this,h,y);case"latin1":case"binary":return D(this,h,y);case"base64":return H(this,h,y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,h,y);default:if(x)throw new TypeError("Unknown encoding: "+b);b=(b+"").toLowerCase(),x=!0}}a.prototype._isBuffer=!0;function I(b,h,y){const x=b[h];b[h]=b[y],b[y]=x}a.prototype.swap16=function(){const h=this.length;if(h%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let y=0;y<h;y+=2)I(this,y,y+1);return this},a.prototype.swap32=function(){const h=this.length;if(h%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let y=0;y<h;y+=4)I(this,y,y+3),I(this,y+1,y+2);return this},a.prototype.swap64=function(){const h=this.length;if(h%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let y=0;y<h;y+=8)I(this,y,y+7),I(this,y+1,y+6),I(this,y+2,y+5),I(this,y+3,y+4);return this},a.prototype.toString=function(){const h=this.length;return h===0?"":arguments.length===0?W(this,0,h):S.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(h){if(!a.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:a.compare(this,h)===0},a.prototype.inspect=function(){let h="";const y=e.INSPECT_MAX_BYTES;return h=this.toString("hex",0,y).replace(/(.{2})/g,"$1 ").trim(),this.length>y&&(h+=" ... "),"<Buffer "+h+">"},n&&(a.prototype[n]=a.prototype.inspect),a.prototype.compare=function(h,y,x,C,M){if(Et(h,Uint8Array)&&(h=a.from(h,h.offset,h.byteLength)),!a.isBuffer(h))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof h);if(y===void 0&&(y=0),x===void 0&&(x=h?h.length:0),C===void 0&&(C=0),M===void 0&&(M=this.length),y<0||x>h.length||C<0||M>this.length)throw new RangeError("out of range index");if(C>=M&&y>=x)return 0;if(C>=M)return-1;if(y>=x)return 1;if(y>>>=0,x>>>=0,C>>>=0,M>>>=0,this===h)return 0;let q=M-C,me=x-y;const ze=Math.min(q,me),$e=this.slice(C,M),qe=h.slice(y,x);for(let ke=0;ke<ze;++ke)if($e[ke]!==qe[ke]){q=$e[ke],me=qe[ke];break}return q<me?-1:me<q?1:0};function P(b,h,y,x,C){if(b.length===0)return-1;if(typeof y=="string"?(x=y,y=0):y>2147483647?y=2147483647:y<-2147483648&&(y=-2147483648),y=+y,Tn(y)&&(y=C?0:b.length-1),y<0&&(y=b.length+y),y>=b.length){if(C)return-1;y=b.length-1}else if(y<0)if(C)y=0;else return-1;if(typeof h=="string"&&(h=a.from(h,x)),a.isBuffer(h))return h.length===0?-1:$(b,h,y,x,C);if(typeof h=="number")return h=h&255,typeof Uint8Array.prototype.indexOf=="function"?C?Uint8Array.prototype.indexOf.call(b,h,y):Uint8Array.prototype.lastIndexOf.call(b,h,y):$(b,[h],y,x,C);throw new TypeError("val must be string, number or Buffer")}function $(b,h,y,x,C){let M=1,q=b.length,me=h.length;if(x!==void 0&&(x=String(x).toLowerCase(),x==="ucs2"||x==="ucs-2"||x==="utf16le"||x==="utf-16le")){if(b.length<2||h.length<2)return-1;M=2,q/=2,me/=2,y/=2}function ze(qe,ke){return M===1?qe[ke]:qe.readUInt16BE(ke*M)}let $e;if(C){let qe=-1;for($e=y;$e<q;$e++)if(ze(b,$e)===ze(h,qe===-1?0:$e-qe)){if(qe===-1&&(qe=$e),$e-qe+1===me)return qe*M}else qe!==-1&&($e-=$e-qe),qe=-1}else for(y+me>q&&(y=q-me),$e=y;$e>=0;$e--){let qe=!0;for(let ke=0;ke<me;ke++)if(ze(b,$e+ke)!==ze(h,ke)){qe=!1;break}if(qe)return $e}return-1}a.prototype.includes=function(h,y,x){return this.indexOf(h,y,x)!==-1},a.prototype.indexOf=function(h,y,x){return P(this,h,y,x,!0)},a.prototype.lastIndexOf=function(h,y,x){return P(this,h,y,x,!1)};function j(b,h,y,x){y=Number(y)||0;const C=b.length-y;x?(x=Number(x),x>C&&(x=C)):x=C;const M=h.length;x>M/2&&(x=M/2);let q;for(q=0;q<x;++q){const me=parseInt(h.substr(q*2,2),16);if(Tn(me))return q;b[y+q]=me}return q}function k(b,h,y,x){return vt(Pr(h,b.length-y),b,y,x)}function F(b,h,y,x){return vt(ns(h),b,y,x)}function R(b,h,y,x){return vt(Or(h),b,y,x)}function U(b,h,y,x){return vt(G(h,b.length-y),b,y,x)}a.prototype.write=function(h,y,x,C){if(y===void 0)C="utf8",x=this.length,y=0;else if(x===void 0&&typeof y=="string")C=y,x=this.length,y=0;else if(isFinite(y))y=y>>>0,isFinite(x)?(x=x>>>0,C===void 0&&(C="utf8")):(C=x,x=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const M=this.length-y;if((x===void 0||x>M)&&(x=M),h.length>0&&(x<0||y<0)||y>this.length)throw new RangeError("Attempt to write outside buffer bounds");C||(C="utf8");let q=!1;for(;;)switch(C){case"hex":return j(this,h,y,x);case"utf8":case"utf-8":return k(this,h,y,x);case"ascii":case"latin1":case"binary":return F(this,h,y,x);case"base64":return R(this,h,y,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U(this,h,y,x);default:if(q)throw new TypeError("Unknown encoding: "+C);C=(""+C).toLowerCase(),q=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function H(b,h,y){return h===0&&y===b.length?t.fromByteArray(b):t.fromByteArray(b.slice(h,y))}function W(b,h,y){y=Math.min(b.length,y);const x=[];let C=h;for(;C<y;){const M=b[C];let q=null,me=M>239?4:M>223?3:M>191?2:1;if(C+me<=y){let ze,$e,qe,ke;switch(me){case 1:M<128&&(q=M);break;case 2:ze=b[C+1],(ze&192)===128&&(ke=(M&31)<<6|ze&63,ke>127&&(q=ke));break;case 3:ze=b[C+1],$e=b[C+2],(ze&192)===128&&($e&192)===128&&(ke=(M&15)<<12|(ze&63)<<6|$e&63,ke>2047&&(ke<55296||ke>57343)&&(q=ke));break;case 4:ze=b[C+1],$e=b[C+2],qe=b[C+3],(ze&192)===128&&($e&192)===128&&(qe&192)===128&&(ke=(M&15)<<18|(ze&63)<<12|($e&63)<<6|qe&63,ke>65535&&ke<1114112&&(q=ke))}}q===null?(q=65533,me=1):q>65535&&(q-=65536,x.push(q>>>10&1023|55296),q=56320|q&1023),x.push(q),C+=me}return Q(x)}const Z=4096;function Q(b){const h=b.length;if(h<=Z)return String.fromCharCode.apply(String,b);let y="",x=0;for(;x<h;)y+=String.fromCharCode.apply(String,b.slice(x,x+=Z));return y}function re(b,h,y){let x="";y=Math.min(b.length,y);for(let C=h;C<y;++C)x+=String.fromCharCode(b[C]&127);return x}function D(b,h,y){let x="";y=Math.min(b.length,y);for(let C=h;C<y;++C)x+=String.fromCharCode(b[C]);return x}function B(b,h,y){const x=b.length;(!h||h<0)&&(h=0),(!y||y<0||y>x)&&(y=x);let C="";for(let M=h;M<y;++M)C+=Gs[b[M]];return C}function V(b,h,y){const x=b.slice(h,y);let C="";for(let M=0;M<x.length-1;M+=2)C+=String.fromCharCode(x[M]+x[M+1]*256);return C}a.prototype.slice=function(h,y){const x=this.length;h=~~h,y=y===void 0?x:~~y,h<0?(h+=x,h<0&&(h=0)):h>x&&(h=x),y<0?(y+=x,y<0&&(y=0)):y>x&&(y=x),y<h&&(y=h);const C=this.subarray(h,y);return Object.setPrototypeOf(C,a.prototype),C};function K(b,h,y){if(b%1!==0||b<0)throw new RangeError("offset is not uint");if(b+h>y)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(h,y,x){h=h>>>0,y=y>>>0,x||K(h,y,this.length);let C=this[h],M=1,q=0;for(;++q<y&&(M*=256);)C+=this[h+q]*M;return C},a.prototype.readUintBE=a.prototype.readUIntBE=function(h,y,x){h=h>>>0,y=y>>>0,x||K(h,y,this.length);let C=this[h+--y],M=1;for(;y>0&&(M*=256);)C+=this[h+--y]*M;return C},a.prototype.readUint8=a.prototype.readUInt8=function(h,y){return h=h>>>0,y||K(h,1,this.length),this[h]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(h,y){return h=h>>>0,y||K(h,2,this.length),this[h]|this[h+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(h,y){return h=h>>>0,y||K(h,2,this.length),this[h]<<8|this[h+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(h,y){return h=h>>>0,y||K(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(h,y){return h=h>>>0,y||K(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},a.prototype.readBigUInt64LE=In(function(h){h=h>>>0,_e(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&je(h,this.length-8);const C=y+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24,M=this[++h]+this[++h]*2**8+this[++h]*2**16+x*2**24;return BigInt(C)+(BigInt(M)<<BigInt(32))}),a.prototype.readBigUInt64BE=In(function(h){h=h>>>0,_e(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&je(h,this.length-8);const C=y*2**24+this[++h]*2**16+this[++h]*2**8+this[++h],M=this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+x;return(BigInt(C)<<BigInt(32))+BigInt(M)}),a.prototype.readIntLE=function(h,y,x){h=h>>>0,y=y>>>0,x||K(h,y,this.length);let C=this[h],M=1,q=0;for(;++q<y&&(M*=256);)C+=this[h+q]*M;return M*=128,C>=M&&(C-=Math.pow(2,8*y)),C},a.prototype.readIntBE=function(h,y,x){h=h>>>0,y=y>>>0,x||K(h,y,this.length);let C=y,M=1,q=this[h+--C];for(;C>0&&(M*=256);)q+=this[h+--C]*M;return M*=128,q>=M&&(q-=Math.pow(2,8*y)),q},a.prototype.readInt8=function(h,y){return h=h>>>0,y||K(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},a.prototype.readInt16LE=function(h,y){h=h>>>0,y||K(h,2,this.length);const x=this[h]|this[h+1]<<8;return x&32768?x|4294901760:x},a.prototype.readInt16BE=function(h,y){h=h>>>0,y||K(h,2,this.length);const x=this[h+1]|this[h]<<8;return x&32768?x|4294901760:x},a.prototype.readInt32LE=function(h,y){return h=h>>>0,y||K(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},a.prototype.readInt32BE=function(h,y){return h=h>>>0,y||K(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},a.prototype.readBigInt64LE=In(function(h){h=h>>>0,_e(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&je(h,this.length-8);const C=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(x<<24);return(BigInt(C)<<BigInt(32))+BigInt(y+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24)}),a.prototype.readBigInt64BE=In(function(h){h=h>>>0,_e(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&je(h,this.length-8);const C=(y<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt(C)<<BigInt(32))+BigInt(this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+x)}),a.prototype.readFloatLE=function(h,y){return h=h>>>0,y||K(h,4,this.length),r.read(this,h,!0,23,4)},a.prototype.readFloatBE=function(h,y){return h=h>>>0,y||K(h,4,this.length),r.read(this,h,!1,23,4)},a.prototype.readDoubleLE=function(h,y){return h=h>>>0,y||K(h,8,this.length),r.read(this,h,!0,52,8)},a.prototype.readDoubleBE=function(h,y){return h=h>>>0,y||K(h,8,this.length),r.read(this,h,!1,52,8)};function O(b,h,y,x,C,M){if(!a.isBuffer(b))throw new TypeError('"buffer" argument must be a Buffer instance');if(h>C||h<M)throw new RangeError('"value" argument is out of bounds');if(y+x>b.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(h,y,x,C){if(h=+h,y=y>>>0,x=x>>>0,!C){const me=Math.pow(2,8*x)-1;O(this,h,y,x,me,0)}let M=1,q=0;for(this[y]=h&255;++q<x&&(M*=256);)this[y+q]=h/M&255;return y+x},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(h,y,x,C){if(h=+h,y=y>>>0,x=x>>>0,!C){const me=Math.pow(2,8*x)-1;O(this,h,y,x,me,0)}let M=x-1,q=1;for(this[y+M]=h&255;--M>=0&&(q*=256);)this[y+M]=h/q&255;return y+x},a.prototype.writeUint8=a.prototype.writeUInt8=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,1,255,0),this[y]=h&255,y+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,65535,0),this[y]=h&255,this[y+1]=h>>>8,y+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,65535,0),this[y]=h>>>8,this[y+1]=h&255,y+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,4294967295,0),this[y+3]=h>>>24,this[y+2]=h>>>16,this[y+1]=h>>>8,this[y]=h&255,y+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,4294967295,0),this[y]=h>>>24,this[y+1]=h>>>16,this[y+2]=h>>>8,this[y+3]=h&255,y+4};function N(b,h,y,x,C){ve(h,x,C,b,y,7);let M=Number(h&BigInt(4294967295));b[y++]=M,M=M>>8,b[y++]=M,M=M>>8,b[y++]=M,M=M>>8,b[y++]=M;let q=Number(h>>BigInt(32)&BigInt(4294967295));return b[y++]=q,q=q>>8,b[y++]=q,q=q>>8,b[y++]=q,q=q>>8,b[y++]=q,y}function L(b,h,y,x,C){ve(h,x,C,b,y,7);let M=Number(h&BigInt(4294967295));b[y+7]=M,M=M>>8,b[y+6]=M,M=M>>8,b[y+5]=M,M=M>>8,b[y+4]=M;let q=Number(h>>BigInt(32)&BigInt(4294967295));return b[y+3]=q,q=q>>8,b[y+2]=q,q=q>>8,b[y+1]=q,q=q>>8,b[y]=q,y+8}a.prototype.writeBigUInt64LE=In(function(h,y=0){return N(this,h,y,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=In(function(h,y=0){return L(this,h,y,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(h,y,x,C){if(h=+h,y=y>>>0,!C){const ze=Math.pow(2,8*x-1);O(this,h,y,x,ze-1,-ze)}let M=0,q=1,me=0;for(this[y]=h&255;++M<x&&(q*=256);)h<0&&me===0&&this[y+M-1]!==0&&(me=1),this[y+M]=(h/q>>0)-me&255;return y+x},a.prototype.writeIntBE=function(h,y,x,C){if(h=+h,y=y>>>0,!C){const ze=Math.pow(2,8*x-1);O(this,h,y,x,ze-1,-ze)}let M=x-1,q=1,me=0;for(this[y+M]=h&255;--M>=0&&(q*=256);)h<0&&me===0&&this[y+M+1]!==0&&(me=1),this[y+M]=(h/q>>0)-me&255;return y+x},a.prototype.writeInt8=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,1,127,-128),h<0&&(h=255+h+1),this[y]=h&255,y+1},a.prototype.writeInt16LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,32767,-32768),this[y]=h&255,this[y+1]=h>>>8,y+2},a.prototype.writeInt16BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,32767,-32768),this[y]=h>>>8,this[y+1]=h&255,y+2},a.prototype.writeInt32LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,2147483647,-2147483648),this[y]=h&255,this[y+1]=h>>>8,this[y+2]=h>>>16,this[y+3]=h>>>24,y+4},a.prototype.writeInt32BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,2147483647,-2147483648),h<0&&(h=4294967295+h+1),this[y]=h>>>24,this[y+1]=h>>>16,this[y+2]=h>>>8,this[y+3]=h&255,y+4},a.prototype.writeBigInt64LE=In(function(h,y=0){return N(this,h,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=In(function(h,y=0){return L(this,h,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function J(b,h,y,x,C,M){if(y+x>b.length)throw new RangeError("Index out of range");if(y<0)throw new RangeError("Index out of range")}function ne(b,h,y,x,C){return h=+h,y=y>>>0,C||J(b,h,y,4),r.write(b,h,y,x,23,4),y+4}a.prototype.writeFloatLE=function(h,y,x){return ne(this,h,y,!0,x)},a.prototype.writeFloatBE=function(h,y,x){return ne(this,h,y,!1,x)};function fe(b,h,y,x,C){return h=+h,y=y>>>0,C||J(b,h,y,8),r.write(b,h,y,x,52,8),y+8}a.prototype.writeDoubleLE=function(h,y,x){return fe(this,h,y,!0,x)},a.prototype.writeDoubleBE=function(h,y,x){return fe(this,h,y,!1,x)},a.prototype.copy=function(h,y,x,C){if(!a.isBuffer(h))throw new TypeError("argument should be a Buffer");if(x||(x=0),!C&&C!==0&&(C=this.length),y>=h.length&&(y=h.length),y||(y=0),C>0&&C<x&&(C=x),C===x||h.length===0||this.length===0)return 0;if(y<0)throw new RangeError("targetStart out of bounds");if(x<0||x>=this.length)throw new RangeError("Index out of range");if(C<0)throw new RangeError("sourceEnd out of bounds");C>this.length&&(C=this.length),h.length-y<C-x&&(C=h.length-y+x);const M=C-x;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(y,x,C):Uint8Array.prototype.set.call(h,this.subarray(x,C),y),M},a.prototype.fill=function(h,y,x,C){if(typeof h=="string"){if(typeof y=="string"?(C=y,y=0,x=this.length):typeof x=="string"&&(C=x,x=this.length),C!==void 0&&typeof C!="string")throw new TypeError("encoding must be a string");if(typeof C=="string"&&!a.isEncoding(C))throw new TypeError("Unknown encoding: "+C);if(h.length===1){const q=h.charCodeAt(0);(C==="utf8"&&q<128||C==="latin1")&&(h=q)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));if(y<0||this.length<y||this.length<x)throw new RangeError("Out of range index");if(x<=y)return this;y=y>>>0,x=x===void 0?this.length:x>>>0,h||(h=0);let M;if(typeof h=="number")for(M=y;M<x;++M)this[M]=h;else{const q=a.isBuffer(h)?h:a.from(h,C),me=q.length;if(me===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for(M=0;M<x-y;++M)this[M+y]=q[M%me]}return this};const ce={};function oe(b,h,y){ce[b]=class extends y{constructor(){super(),Object.defineProperty(this,"message",{value:h.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${b}]`,this.stack,delete this.name}get code(){return b}set code(C){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:C,writable:!0})}toString(){return`${this.name} [${b}]: ${this.message}`}}}oe("ERR_BUFFER_OUT_OF_BOUNDS",function(b){return b?`${b} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),oe("ERR_INVALID_ARG_TYPE",function(b,h){return`The "${b}" argument must be of type number. Received type ${typeof h}`},TypeError),oe("ERR_OUT_OF_RANGE",function(b,h,y){let x=`The value of "${b}" is out of range.`,C=y;return Number.isInteger(y)&&Math.abs(y)>2**32?C=ie(String(y)):typeof y=="bigint"&&(C=String(y),(y>BigInt(2)**BigInt(32)||y<-(BigInt(2)**BigInt(32)))&&(C=ie(C)),C+="n"),x+=` It must be ${h}. Received ${C}`,x},RangeError);function ie(b){let h="",y=b.length;const x=b[0]==="-"?1:0;for(;y>=x+4;y-=3)h=`_${b.slice(y-3,y)}${h}`;return`${b.slice(0,y)}${h}`}function he(b,h,y){_e(h,"offset"),(b[h]===void 0||b[h+y]===void 0)&&je(h,b.length-(y+1))}function ve(b,h,y,x,C,M){if(b>y||b<h){const q=typeof h=="bigint"?"n":"";let me;throw h===0||h===BigInt(0)?me=`>= 0${q} and < 2${q} ** ${(M+1)*8}${q}`:me=`>= -(2${q} ** ${(M+1)*8-1}${q}) and < 2 ** ${(M+1)*8-1}${q}`,new ce.ERR_OUT_OF_RANGE("value",me,b)}he(x,C,M)}function _e(b,h){if(typeof b!="number")throw new ce.ERR_INVALID_ARG_TYPE(h,"number",b)}function je(b,h,y){throw Math.floor(b)!==b?(_e(b,y),new ce.ERR_OUT_OF_RANGE("offset","an integer",b)):h<0?new ce.ERR_BUFFER_OUT_OF_BOUNDS:new ce.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${h}`,b)}const jt=/[^+/0-9A-Za-z-_]/g;function Qe(b){if(b=b.split("=")[0],b=b.trim().replace(jt,""),b.length<2)return"";for(;b.length%4!==0;)b=b+"=";return b}function Pr(b,h){h=h||1/0;let y;const x=b.length;let C=null;const M=[];for(let q=0;q<x;++q){if(y=b.charCodeAt(q),y>55295&&y<57344){if(!C){if(y>56319){(h-=3)>-1&&M.push(239,191,189);continue}else if(q+1===x){(h-=3)>-1&&M.push(239,191,189);continue}C=y;continue}if(y<56320){(h-=3)>-1&&M.push(239,191,189),C=y;continue}y=(C-55296<<10|y-56320)+65536}else C&&(h-=3)>-1&&M.push(239,191,189);if(C=null,y<128){if((h-=1)<0)break;M.push(y)}else if(y<2048){if((h-=2)<0)break;M.push(y>>6|192,y&63|128)}else if(y<65536){if((h-=3)<0)break;M.push(y>>12|224,y>>6&63|128,y&63|128)}else if(y<1114112){if((h-=4)<0)break;M.push(y>>18|240,y>>12&63|128,y>>6&63|128,y&63|128)}else throw new Error("Invalid code point")}return M}function ns(b){const h=[];for(let y=0;y<b.length;++y)h.push(b.charCodeAt(y)&255);return h}function G(b,h){let y,x,C;const M=[];for(let q=0;q<b.length&&!((h-=2)<0);++q)y=b.charCodeAt(q),x=y>>8,C=y%256,M.push(C),M.push(x);return M}function Or(b){return t.toByteArray(Qe(b))}function vt(b,h,y,x){let C;for(C=0;C<x&&!(C+y>=h.length||C>=b.length);++C)h[C+y]=b[C];return C}function Et(b,h){return b instanceof h||b!=null&&b.constructor!=null&&b.constructor.name!=null&&b.constructor.name===h.name}function Tn(b){return b!==b}const Gs=function(){const b="0123456789abcdef",h=new Array(256);for(let y=0;y<16;++y){const x=y*16;for(let C=0;C<16;++C)h[x+C]=b[y]+b[C]}return h}();function In(b){return typeof BigInt>"u"?H1:b}function H1(){throw new Error("BigInt not supported")}})(Hs);var jo={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}};jo.Null=jo.Nil;for(var Pp in jo)jo[Pp].toJSON=(function(e){return e}).bind(null,Pp);var Jd=jo,ws=Jd;function mb(e){return e.name||e.toString().match(/function (.*?)\s*\(/)[1]}function Qd(e){return ws.Nil(e)?"":mb(e.constructor)}function k_(e){return ws.Function(e)?"":ws.String(e)?JSON.stringify(e):e&&ws.Object(e)?"":e}function eh(e,t){Error.captureStackTrace&&Error.captureStackTrace(e,t)}function nc(e){return ws.Function(e)?e.toJSON?e.toJSON():mb(e):ws.Array(e)?"Array":e&&ws.Object(e)?"Object":e!==void 0?e:""}function gb(e,t,r){var n=k_(t);return"Expected "+nc(e)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function En(e,t,r){r=r||Qd(t),this.message=gb(e,t,r),eh(this,En),this.__type=e,this.__value=t,this.__valueTypeName=r}En.prototype=Object.create(Error.prototype);En.prototype.constructor=En;function T_(e,t,r,n,s){var i='" of type ';return t==="key"&&(i='" with key type '),gb('property "'+nc(r)+i+nc(e),n,s)}function fi(e,t,r,n,s){e?(s=s||Qd(n),this.message=T_(e,r,t,n,s)):this.message='Unexpected property "'+t+'"',eh(this,En),this.__label=r,this.__property=t,this.__type=e,this.__value=n,this.__valueTypeName=s}fi.prototype=Object.create(Error.prototype);fi.prototype.constructor=En;function I_(e,t){return new En(e,{},t)}function P_(e,t,r){return e instanceof fi?(t=t+"."+e.__property,e=new fi(e.__type,t,e.__label,e.__value,e.__valueTypeName)):e instanceof En&&(e=new fi(e.__type,t,r,e.__value,e.__valueTypeName)),eh(e),e}var bb={TfTypeError:En,TfPropertyTypeError:fi,tfCustomError:I_,tfSubError:P_,tfJSON:nc,getValueTypeName:Qd},Pu,Op;function O_(){if(Op)return Pu;Op=1;var e=Jd,t=bb;function r(P){return Buffer.isBuffer(P)}function n(P){return typeof P=="string"&&/^([0-9a-f]{2})+$/i.test(P)}function s(P,$){var j=P.toJSON();function k(F){if(!P(F))return!1;if(F.length===$)return!0;throw t.tfCustomError(j+"(Length: "+$+")",j+"(Length: "+F.length+")")}return k.toJSON=function(){return j},k}var i=s.bind(null,e.Array),o=s.bind(null,r),a=s.bind(null,n),c=s.bind(null,e.String);function l(P,$,j){j=j||e.Number;function k(F,R){return j(F,R)&&F>P&&F<$}return k.toJSON=function(){return`${j.toJSON()} between [${P}, ${$}]`},k}var u=Math.pow(2,53)-1;function f(P){return typeof P=="number"&&isFinite(P)}function p(P){return P<<24>>24===P}function d(P){return P<<16>>16===P}function m(P){return(P|0)===P}function g(P){return typeof P=="number"&&P>=-u&&P<=u&&Math.floor(P)===P}function w(P){return(P&255)===P}function A(P){return(P&65535)===P}function T(P){return P>>>0===P}function E(P){return typeof P=="number"&&P>=0&&P<=u&&Math.floor(P)===P}var S={ArrayN:i,Buffer:r,BufferN:o,Finite:f,Hex:n,HexN:a,Int8:p,Int16:d,Int32:m,Int53:g,Range:l,StringN:c,UInt8:w,UInt16:A,UInt32:T,UInt53:E};for(var I in S)S[I].toJSON=(function(P){return P}).bind(null,I);return Pu=S,Pu}var ia=bb,at=Jd,Qr=ia.tfJSON,wb=ia.TfTypeError,vb=ia.TfPropertyTypeError,ji=ia.tfSubError,B_=ia.getValueTypeName,dn={arrayOf:function(t,r){t=Lr(t),r=r||{};function n(s,i){return!at.Array(s)||at.Nil(s)||r.minLength!==void 0&&s.length<r.minLength||r.maxLength!==void 0&&s.length>r.maxLength||r.length!==void 0&&s.length!==r.length?!1:s.every(function(o,a){try{return Tt(t,o,i)}catch(c){throw ji(c,a)}})}return n.toJSON=function(){var s="["+Qr(t)+"]";return r.length!==void 0?s+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(s+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),s},n},maybe:function e(t){t=Lr(t);function r(n,s){return at.Nil(n)||t(n,s,e)}return r.toJSON=function(){return"?"+Qr(t)},r},map:function(t,r){t=Lr(t),r&&(r=Lr(r));function n(s,i){if(!at.Object(s)||at.Nil(s))return!1;for(var o in s){try{r&&Tt(r,o,i)}catch(c){throw ji(c,o,"key")}try{var a=s[o];Tt(t,a,i)}catch(c){throw ji(c,o)}}return!0}return r?n.toJSON=function(){return"{"+Qr(r)+": "+Qr(t)+"}"}:n.toJSON=function(){return"{"+Qr(t)+"}"},n},object:function(t){var r={};for(var n in t)r[n]=Lr(t[n]);function s(i,o){if(!at.Object(i)||at.Nil(i))return!1;var a;try{for(a in r){var c=r[a],l=i[a];Tt(c,l,o)}}catch(u){throw ji(u,a)}if(o){for(a in i)if(!r[a])throw new vb(void 0,a)}return!0}return s.toJSON=function(){return Qr(r)},s},anyOf:function(){var t=[].slice.call(arguments).map(Lr);function r(n,s){return t.some(function(i){try{return Tt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return t.map(Qr).join("|")},r},allOf:function(){var t=[].slice.call(arguments).map(Lr);function r(n,s){return t.every(function(i){try{return Tt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return t.map(Qr).join(" & ")},r},quacksLike:function(t){function r(n){return t===B_(n)}return r.toJSON=function(){return t},r},tuple:function(){var t=[].slice.call(arguments).map(Lr);function r(n,s){return at.Nil(n)||at.Nil(n.length)||s&&n.length!==t.length?!1:t.every(function(i,o){try{return Tt(i,n[o],s)}catch(a){throw ji(a,o)}})}return r.toJSON=function(){return"("+t.map(Qr).join(", ")+")"},r},value:function(t){function r(n){return n===t}return r.toJSON=function(){return t},r}};dn.oneOf=dn.anyOf;function Lr(e){if(at.String(e))return e[0]==="?"?dn.maybe(e.slice(1)):at[e]||dn.quacksLike(e);if(e&&at.Object(e)){if(at.Array(e)){if(e.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return dn.arrayOf(e[0])}return dn.object(e)}else if(at.Function(e))return e;return dn.value(e)}function Tt(e,t,r,n){if(at.Function(e)){if(e(t,r))return!0;throw new wb(n||e,t)}return Tt(Lr(e),t,r)}for(var Xn in at)Tt[Xn]=at[Xn];for(Xn in dn)Tt[Xn]=dn[Xn];var Bp=O_();for(Xn in Bp)Tt[Xn]=Bp[Xn];Tt.compile=Lr;Tt.TfTypeError=wb;Tt.TfPropertyTypeError=vb;var C_=Tt;(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=Hs;e.typeforce=C_;const r=t.Buffer.alloc(32,0),n=t.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function s(u,f){return u.length!==f.length?!1:u.every((p,d)=>p.equals(f[d]))}e.stacksEqual=s;function i(u){if(!t.Buffer.isBuffer(u)||u.length<33)return!1;const f=u[0],p=u.slice(1,33);if(p.compare(r)===0||p.compare(n)>=0)return!1;if((f===2||f===3)&&u.length===33)return!0;const d=u.slice(33);return d.compare(r)===0||d.compare(n)>=0?!1:f===4&&u.length===65}e.isPoint=i;const o=21*1e14;function a(u){return e.typeforce.UInt53(u)&&u<=o}e.Satoshi=a,e.TAPLEAF_VERSION_MASK=254;function c(u){return!u||!("output"in u)||!t.Buffer.isBuffer(u.output)?!1:u.version!==void 0?(u.version&e.TAPLEAF_VERSION_MASK)===u.version:!0}e.isTapleaf=c;function l(u){return(0,e.Array)(u)?u.length!==2?!1:u.every(f=>l(f)):c(u)}e.isTaptree=l,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})(wt);var oa={},ct={};Object.defineProperty(ct,"__esModule",{value:!0});ct.BufferReader=ct.BufferWriter=ct.cloneBuffer=ct.reverseBuffer=ct.writeUInt64LE=ct.readUInt64LE=ct.varuint=void 0;const vs=wt,{typeforce:Eb}=vs,Lo=Am;ct.varuint=Lo;function Ab(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 xb(e,t){const r=e.readUInt32LE(t);let n=e.readUInt32LE(t+4);return n*=4294967296,Ab(n+r,9007199254740991),n+r}ct.readUInt64LE=xb;function Sb(e,t,r){return Ab(t,9007199254740991),e.writeInt32LE(t&-1,r),e.writeUInt32LE(Math.floor(t/4294967296),r+4),r+8}ct.writeUInt64LE=Sb;function R_(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}ct.reverseBuffer=R_;function $_(e){const t=Buffer.allocUnsafe(e.length);return e.copy(t),t}ct.cloneBuffer=$_;class th{static withCapacity(t){return new th(Buffer.alloc(t))}constructor(t,r=0){this.buffer=t,this.offset=r,Eb(vs.tuple(vs.Buffer,vs.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=Sb(this.buffer,t,this.offset)}writeVarInt(t){Lo.encode(t,this.buffer,this.offset),this.offset+=Lo.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}`)}}ct.BufferWriter=th;class N_{constructor(t,r=0){this.buffer=t,this.offset=r,Eb(vs.tuple(vs.Buffer,vs.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=xb(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Lo.decode(this.buffer,this.offset);return this.offset+=Lo.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}}ct.BufferReader=N_;var rs={};const U_=pb(ox);var Ei={},Ct={},Pt={},rh={},Lc={};Object.defineProperty(Lc,"__esModule",{value:!0});Lc.crypto=void 0;Lc.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=s,e.ahash=i,e.aexists=o,e.aoutput=a,e.u8=c,e.u32=l,e.clean=u,e.createView=f,e.rotr=p,e.rotl=d,e.byteSwap=m,e.byteSwap32=g,e.bytesToHex=T,e.hexToBytes=I,e.asyncLoop=$,e.utf8ToBytes=j,e.bytesToUtf8=k,e.toBytes=F,e.kdfInputToBytes=R,e.concatBytes=U,e.checkOpts=H,e.createHasher=Z,e.createOptHasher=Q,e.createXOFer=re,e.randomBytes=D;const t=Lc;function r(B){return B instanceof Uint8Array||ArrayBuffer.isView(B)&&B.constructor.name==="Uint8Array"}function n(B){if(!Number.isSafeInteger(B)||B<0)throw new Error("positive integer expected, got "+B)}function s(B,...V){if(!r(B))throw new Error("Uint8Array expected");if(V.length>0&&!V.includes(B.length))throw new Error("Uint8Array expected of length "+V+", got length="+B.length)}function i(B){if(typeof B!="function"||typeof B.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");n(B.outputLen),n(B.blockLen)}function o(B,V=!0){if(B.destroyed)throw new Error("Hash instance has been destroyed");if(V&&B.finished)throw new Error("Hash#digest() has already been called")}function a(B,V){s(B);const K=V.outputLen;if(B.length<K)throw new Error("digestInto() expects output buffer of length at least "+K)}function c(B){return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)}function l(B){return new Uint32Array(B.buffer,B.byteOffset,Math.floor(B.byteLength/4))}function u(...B){for(let V=0;V<B.length;V++)B[V].fill(0)}function f(B){return new DataView(B.buffer,B.byteOffset,B.byteLength)}function p(B,V){return B<<32-V|B>>>V}function d(B,V){return B<<V|B>>>32-V>>>0}e.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function m(B){return B<<24&4278190080|B<<8&16711680|B>>>8&65280|B>>>24&255}e.swap8IfBE=e.isLE?B=>B:B=>m(B),e.byteSwapIfBE=e.swap8IfBE;function g(B){for(let V=0;V<B.length;V++)B[V]=m(B[V]);return B}e.swap32IfBE=e.isLE?B=>B:g;const w=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",A=Array.from({length:256},(B,V)=>V.toString(16).padStart(2,"0"));function T(B){if(s(B),w)return B.toHex();let V="";for(let K=0;K<B.length;K++)V+=A[B[K]];return V}const E={_0:48,_9:57,A:65,F:70,a:97,f:102};function S(B){if(B>=E._0&&B<=E._9)return B-E._0;if(B>=E.A&&B<=E.F)return B-(E.A-10);if(B>=E.a&&B<=E.f)return B-(E.a-10)}function I(B){if(typeof B!="string")throw new Error("hex string expected, got "+typeof B);if(w)return Uint8Array.fromHex(B);const V=B.length,K=V/2;if(V%2)throw new Error("hex string expected, got unpadded hex of length "+V);const O=new Uint8Array(K);for(let N=0,L=0;N<K;N++,L+=2){const J=S(B.charCodeAt(L)),ne=S(B.charCodeAt(L+1));if(J===void 0||ne===void 0){const fe=B[L]+B[L+1];throw new Error('hex string expected, got non-hex character "'+fe+'" at index '+L)}O[N]=J*16+ne}return O}const P=async()=>{};e.nextTick=P;async function $(B,V,K){let O=Date.now();for(let N=0;N<B;N++){K(N);const L=Date.now()-O;L>=0&&L<V||(await(0,e.nextTick)(),O+=L)}}function j(B){if(typeof B!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(B))}function k(B){return new TextDecoder().decode(B)}function F(B){return typeof B=="string"&&(B=j(B)),s(B),B}function R(B){return typeof B=="string"&&(B=j(B)),s(B),B}function U(...B){let V=0;for(let O=0;O<B.length;O++){const N=B[O];s(N),V+=N.length}const K=new Uint8Array(V);for(let O=0,N=0;O<B.length;O++){const L=B[O];K.set(L,N),N+=L.length}return K}function H(B,V){if(V!==void 0&&{}.toString.call(V)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(B,V)}class W{}e.Hash=W;function Z(B){const V=O=>B().update(F(O)).digest(),K=B();return V.outputLen=K.outputLen,V.blockLen=K.blockLen,V.create=()=>B(),V}function Q(B){const V=(O,N)=>B(N).update(F(O)).digest(),K=B({});return V.outputLen=K.outputLen,V.blockLen=K.blockLen,V.create=O=>B(O),V}function re(B){const V=(O,N)=>B(N).update(F(O)).digest(),K=B({});return V.outputLen=K.outputLen,V.blockLen=K.blockLen,V.create=O=>B(O),V}e.wrapConstructor=Z,e.wrapConstructorWithOpts=Q,e.wrapXOFConstructorWithOpts=re;function D(B=32){if(t.crypto&&typeof t.crypto.getRandomValues=="function")return t.crypto.getRandomValues(new Uint8Array(B));if(t.crypto&&typeof t.crypto.randomBytes=="function")return Uint8Array.from(t.crypto.randomBytes(B));throw new Error("crypto.getRandomValues must be defined")}})(rh);Object.defineProperty(Pt,"__esModule",{value:!0});Pt.SHA512_IV=Pt.SHA384_IV=Pt.SHA224_IV=Pt.SHA256_IV=Pt.HashMD=void 0;Pt.setBigUint64=_b;Pt.Chi=M_;Pt.Maj=F_;const Rr=rh;function _b(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}function M_(e,t,r){return e&t^~e&r}function F_(e,t,r){return e&t^e&r^t&r}class j_ extends Rr.Hash{constructor(t,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(t),this.view=(0,Rr.createView)(this.buffer)}update(t){(0,Rr.aexists)(this),t=(0,Rr.toBytes)(t),(0,Rr.abytes)(t);const{view:r,buffer:n,blockLen:s}=this,i=t.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=(0,Rr.createView)(t);for(;s<=i-o;o+=s)this.process(c,o);continue}n.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){(0,Rr.aexists)(this),(0,Rr.aoutput)(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:o}=this;r[o++]=128,(0,Rr.clean)(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let f=o;f<s;f++)r[f]=0;_b(n,s-8,BigInt(this.length*8),i),this.process(n,0);const a=(0,Rr.createView)(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],i)}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:s,finished:i,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=i,t.length=s,t.pos=a,s%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}}Pt.HashMD=j_;Pt.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);Pt.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);Pt.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);Pt.SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);Object.defineProperty(Ct,"__esModule",{value:!0});Ct.ripemd160=Ct.RIPEMD160=Ct.md5=Ct.MD5=Ct.sha1=Ct.SHA1=void 0;const Es=Pt,ut=rh,Js=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Cn=new Uint32Array(80);class kb extends Es.HashMD{constructor(){super(64,20,8,!1),this.A=Js[0]|0,this.B=Js[1]|0,this.C=Js[2]|0,this.D=Js[3]|0,this.E=Js[4]|0}get(){const{A:t,B:r,C:n,D:s,E:i}=this;return[t,r,n,s,i]}set(t,r,n,s,i){this.A=t|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0}process(t,r){for(let c=0;c<16;c++,r+=4)Cn[c]=t.getUint32(r,!1);for(let c=16;c<80;c++)Cn[c]=(0,ut.rotl)(Cn[c-3]^Cn[c-8]^Cn[c-14]^Cn[c-16],1);let{A:n,B:s,C:i,D:o,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=(0,Es.Chi)(s,i,o),u=1518500249):c<40?(l=s^i^o,u=1859775393):c<60?(l=(0,Es.Maj)(s,i,o),u=2400959708):(l=s^i^o,u=3395469782);const f=(0,ut.rotl)(n,5)+l+a+u+Cn[c]|0;a=o,o=i,i=(0,ut.rotl)(s,30),s=n,n=f}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,this.set(n,s,i,o,a)}roundClean(){(0,ut.clean)(Cn)}destroy(){this.set(0,0,0,0,0),(0,ut.clean)(this.buffer)}}Ct.SHA1=kb;Ct.sha1=(0,ut.createHasher)(()=>new kb);const L_=Math.pow(2,32),D_=Array.from({length:64},(e,t)=>Math.floor(L_*Math.abs(Math.sin(t+1)))),Aa=Js.slice(0,4),Ou=new Uint32Array(16);class Tb extends Es.HashMD{constructor(){super(64,16,8,!0),this.A=Aa[0]|0,this.B=Aa[1]|0,this.C=Aa[2]|0,this.D=Aa[3]|0}get(){const{A:t,B:r,C:n,D:s}=this;return[t,r,n,s]}set(t,r,n,s){this.A=t|0,this.B=r|0,this.C=n|0,this.D=s|0}process(t,r){for(let a=0;a<16;a++,r+=4)Ou[a]=t.getUint32(r,!0);let{A:n,B:s,C:i,D:o}=this;for(let a=0;a<64;a++){let c,l,u;a<16?(c=(0,Es.Chi)(s,i,o),l=a,u=[7,12,17,22]):a<32?(c=(0,Es.Chi)(o,s,i),l=(5*a+1)%16,u=[5,9,14,20]):a<48?(c=s^i^o,l=(3*a+5)%16,u=[4,11,16,23]):(c=i^(s|~o),l=7*a%16,u=[6,10,15,21]),c=c+n+D_[a]+Ou[l],n=o,o=i,i=s,s=s+(0,ut.rotl)(c,u[a%4])}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,this.set(n,s,i,o)}roundClean(){(0,ut.clean)(Ou)}destroy(){this.set(0,0,0,0),(0,ut.clean)(this.buffer)}}Ct.MD5=Tb;Ct.md5=(0,ut.createHasher)(()=>new Tb);const H_=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Ib=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),z_=Ib.map(e=>(9*e+5)%16),Pb=(()=>{const r=[[Ib],[z_]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>H_[i]));return r})(),Ob=Pb[0],Bb=Pb[1],Cb=[[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)),q_=Ob.map((e,t)=>e.map(r=>Cb[t][r])),V_=Bb.map((e,t)=>e.map(r=>Cb[t][r])),G_=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),W_=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Cp(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 xa=new Uint32Array(16);class Rb extends Es.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:s,h4:i}=this;return[t,r,n,s,i]}set(t,r,n,s,i){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=s|0,this.h4=i|0}process(t,r){for(let d=0;d<16;d++,r+=4)xa[d]=t.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,o=i,a=this.h2|0,c=a,l=this.h3|0,u=l,f=this.h4|0,p=f;for(let d=0;d<5;d++){const m=4-d,g=G_[d],w=W_[d],A=Ob[d],T=Bb[d],E=q_[d],S=V_[d];for(let I=0;I<16;I++){const P=(0,ut.rotl)(n+Cp(d,i,a,l)+xa[A[I]]+g,E[I])+f|0;n=f,f=l,l=(0,ut.rotl)(a,10)|0,a=i,i=P}for(let I=0;I<16;I++){const P=(0,ut.rotl)(s+Cp(m,o,c,u)+xa[T[I]]+w,S[I])+p|0;s=p,p=u,u=(0,ut.rotl)(c,10)|0,c=o,o=P}}this.set(this.h1+a+u|0,this.h2+l+p|0,this.h3+f+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){(0,ut.clean)(xa)}destroy(){this.destroyed=!0,(0,ut.clean)(this.buffer),this.set(0,0,0,0,0)}}Ct.RIPEMD160=Rb;Ct.ripemd160=(0,ut.createHasher)(()=>new Rb);Object.defineProperty(Ei,"__esModule",{value:!0});Ei.sha1=Ei.SHA1=void 0;const $b=Ct;Ei.SHA1=$b.SHA1;Ei.sha1=$b.sha1;const Nb=pb(XE);(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=U_,r=Ei,n=Nb;function s(u){return Buffer.from((0,t.ripemd160)(Uint8Array.from(u)))}e.ripemd160=s;function i(u){return Buffer.from((0,r.sha1)(Uint8Array.from(u)))}e.sha1=i;function o(u){return Buffer.from((0,n.sha256)(Uint8Array.from(u)))}e.sha256=o;function a(u){return Buffer.from((0,t.ripemd160)((0,n.sha256)(Uint8Array.from(u))))}e.hash160=a;function c(u){return Buffer.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(u))))}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 l(u,f){return o(Buffer.concat([e.TAGGED_HASH_PREFIXES[u],f]))}e.taggedHash=l})(rs);var Bu={},bn={};Object.defineProperty(bn,"__esModule",{value:!0});bn.encode=bn.decode=bn.check=void 0;function K_(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))}bn.check=K_;function X_(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)}}bn.decode=X_;function Y_(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 s=Buffer.allocUnsafe(6+r+n);return s[0]=48,s[1]=s.length-2,s[2]=2,s[3]=e.length,e.copy(s,4),s[4+r]=2,s[5+r]=t.length,t.copy(s,6+r),s}bn.encode=Y_;var Cs={};Object.defineProperty(Cs,"__esModule",{value:!0});Cs.REVERSE_OPS=Cs.OPS=void 0;const Lf={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};Cs.OPS=Lf;const Ub={};Cs.REVERSE_OPS=Ub;for(const e of Object.keys(Lf)){const t=Lf[e];Ub[t]=e}var Yn={};Object.defineProperty(Yn,"__esModule",{value:!0});Yn.decode=Yn.encode=Yn.encodingLength=void 0;const Gn=Cs;function Mb(e){return e<Gn.OPS.OP_PUSHDATA1?1:e<=255?2:e<=65535?3:5}Yn.encodingLength=Mb;function Z_(e,t,r){const n=Mb(t);return n===1?e.writeUInt8(t,r):n===2?(e.writeUInt8(Gn.OPS.OP_PUSHDATA1,r),e.writeUInt8(t,r+1)):n===3?(e.writeUInt8(Gn.OPS.OP_PUSHDATA2,r),e.writeUInt16LE(t,r+1)):(e.writeUInt8(Gn.OPS.OP_PUSHDATA4,r),e.writeUInt32LE(t,r+1)),n}Yn.encode=Z_;function J_(e,t){const r=e.readUInt8(t);let n,s;if(r<Gn.OPS.OP_PUSHDATA1)n=r,s=1;else if(r===Gn.OPS.OP_PUSHDATA1){if(t+2>e.length)return null;n=e.readUInt8(t+1),s=2}else if(r===Gn.OPS.OP_PUSHDATA2){if(t+3>e.length)return null;n=e.readUInt16LE(t+1),s=3}else{if(t+5>e.length)return null;if(r!==Gn.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=e.readUInt32LE(t+1),s=5}return{opcode:r,number:n,size:s}}Yn.decode=J_;var Ai={};Object.defineProperty(Ai,"__esModule",{value:!0});Ai.encode=Ai.decode=void 0;function Q_(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 i=e.readUInt32LE(0),o=e.readUInt8(4);return o&128?-((o&-129)*4294967296+i):o*4294967296+i}let s=0;for(let i=0;i<n;++i)s|=e[i]<<8*i;return e[n-1]&128?-(s&~(128<<8*(n-1))):s}Ai.decode=Q_;function ek(e){return e>2147483647?5:e>8388607?4:e>32767?3:e>127?2:e>0?1:0}function tk(e){let t=Math.abs(e);const r=ek(t),n=Buffer.allocUnsafe(r),s=e<0;for(let i=0;i<r;++i)n.writeUInt8(t&255,i),t>>=8;return n[r-1]&128?n.writeUInt8(s?128:0,r-1):s&&(n[r-1]|=128),n}Ai.encode=tk;var ss={},Rp;function rk(){if(Rp)return ss;Rp=1,Object.defineProperty(ss,"__esModule",{value:!0}),ss.encode=ss.decode=void 0;const e=bn,t=Yt(),r=wt,{typeforce:n}=r,s=Buffer.alloc(1,0);function i(l){let u=0;for(;l[u]===0;)++u;return u===l.length?s:(l=l.slice(u),l[0]&128?Buffer.concat([s,l],1+l.length):l)}function o(l){l[0]===0&&(l=l.slice(1));const u=Buffer.alloc(32,0),f=Math.max(0,32-l.length);return l.copy(u,f),u}function a(l){const u=l.readUInt8(l.length-1);if(!(0,t.isDefinedHashType)(u))throw new Error("Invalid hashType "+u);const f=e.decode(l.slice(0,-1)),p=o(f.r),d=o(f.s);return{signature:Buffer.concat([p,d],64),hashType:u}}ss.decode=a;function c(l,u){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:l,hashType:u}),!(0,t.isDefinedHashType)(u))throw new Error("Invalid hashType "+u);const f=Buffer.allocUnsafe(1);f.writeUInt8(u,0);const p=i(l.slice(0,32)),d=i(l.slice(32,64));return Buffer.concat([e.encode(p,d),f])}return ss.encode=c,ss}var $p;function Yt(){return $p||($p=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=bn,r=Cs;Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=Yn,s=Ai,i=rk(),o=wt,{typeforce:a}=o,c=r.OPS.OP_RESERVED;function l(k){return o.Number(k)&&(k===r.OPS.OP_0||k>=r.OPS.OP_1&&k<=r.OPS.OP_16||k===r.OPS.OP_1NEGATE)}function u(k){return o.Buffer(k)||l(k)}function f(k){return o.Array(k)&&k.every(u)}e.isPushOnly=f;function p(k){return k.length-k.filter(u).length}e.countNonPushOnlyOPs=p;function d(k){if(k.length===0)return r.OPS.OP_0;if(k.length===1){if(k[0]>=1&&k[0]<=16)return c+k[0];if(k[0]===129)return r.OPS.OP_1NEGATE}}function m(k){return Buffer.isBuffer(k)}function g(k){return o.Array(k)}function w(k){return Buffer.isBuffer(k)}function A(k){if(m(k))return k;a(o.Array,k);const F=k.reduce((H,W)=>w(W)?W.length===1&&d(W)!==void 0?H+1:H+n.encodingLength(W.length)+W.length:H+1,0),R=Buffer.allocUnsafe(F);let U=0;if(k.forEach(H=>{if(w(H)){const W=d(H);if(W!==void 0){R.writeUInt8(W,U),U+=1;return}U+=n.encode(R,H.length,U),H.copy(R,U),U+=H.length}else R.writeUInt8(H,U),U+=1}),U!==R.length)throw new Error("Could not decode chunks");return R}e.compile=A;function T(k){if(g(k))return k;a(o.Buffer,k);const F=[];let R=0;for(;R<k.length;){const U=k[R];if(U>r.OPS.OP_0&&U<=r.OPS.OP_PUSHDATA4){const H=n.decode(k,R);if(H===null||(R+=H.size,R+H.number>k.length))return null;const W=k.slice(R,R+H.number);R+=H.number;const Z=d(W);Z!==void 0?F.push(Z):F.push(W)}else F.push(U),R+=1}return F}e.decompile=T;function E(k){if(m(k)&&(k=T(k)),!k)throw new Error("Could not convert invalid chunks to ASM");return k.map(F=>{if(w(F)){const R=d(F);if(R===void 0)return F.toString("hex");F=R}return r.REVERSE_OPS[F]}).join(" ")}e.toASM=E;function S(k){return a(o.String,k),A(k.split(" ").map(F=>r.OPS[F]!==void 0?r.OPS[F]:(a(o.Hex,F),Buffer.from(F,"hex"))))}e.fromASM=S;function I(k){return k=T(k),a(f,k),k.map(F=>w(F)?F:F===r.OPS.OP_0?Buffer.allocUnsafe(0):s.encode(F-c))}e.toStack=I;function P(k){return o.isPoint(k)}e.isCanonicalPubKey=P;function $(k){const F=k&-129;return F>0&&F<4}e.isDefinedHashType=$;function j(k){return!Buffer.isBuffer(k)||!$(k[k.length-1])?!1:t.check(k.slice(0,-1))}e.isCanonicalScriptSignature=j,e.number=s,e.signature=i}(Bu)),Bu}Object.defineProperty(oa,"__esModule",{value:!0});oa.Transaction=void 0;const Ye=ct,At=rs,Np=Yt(),nk=Yt(),we=wt,{typeforce:$r}=we;function Fr(e){const t=e.length;return Ye.varuint.encodingLength(t)+t}function sk(e){const t=e.length;return Ye.varuint.encodingLength(t)+e.reduce((r,n)=>r+Fr(n),0)}const jn=Buffer.allocUnsafe(0),Cu=[],Ru=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),Up=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),ik=Buffer.from("ffffffffffffffff","hex"),ok={script:jn,valueBuffer:ik};function ak(e){return e.value!==void 0}let Ir=class Te{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(t,r){const n=new Ye.BufferReader(t),s=new Te;s.version=n.readInt32();const i=n.readUInt8(),o=n.readUInt8();let a=!1;i===Te.ADVANCED_TRANSACTION_MARKER&&o===Te.ADVANCED_TRANSACTION_FLAG?a=!0:n.offset-=2;const c=n.readVarInt();for(let u=0;u<c;++u)s.ins.push({hash:n.readSlice(32),index:n.readUInt32(),script:n.readVarSlice(),sequence:n.readUInt32(),witness:Cu});const l=n.readVarInt();for(let u=0;u<l;++u)s.outs.push({value:n.readUInt64(),script:n.readVarSlice()});if(a){for(let u=0;u<c;++u)s.ins[u].witness=n.readVector();if(!s.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(s.locktime=n.readUInt32(),r)return s;if(n.offset!==t.length)throw new Error("Transaction has unexpected data");return s}static fromHex(t){return Te.fromBuffer(Buffer.from(t,"hex"),!1)}static isCoinbaseHash(t){$r(we.Hash256bit,t);for(let r=0;r<32;++r)if(t[r]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&Te.isCoinbaseHash(this.ins[0].hash)}addInput(t,r,n,s){return $r(we.tuple(we.Hash256bit,we.UInt32,we.maybe(we.UInt32),we.maybe(we.Buffer)),arguments),we.Null(n)&&(n=Te.DEFAULT_SEQUENCE),this.ins.push({hash:t,index:r,script:s||jn,sequence:n,witness:Cu})-1}addOutput(t,r){return $r(we.tuple(we.Buffer,we.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=Cu})}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)+Ye.varuint.encodingLength(this.ins.length)+Ye.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,s)=>n+40+Fr(s.script),0)+this.outs.reduce((n,s)=>n+8+Fr(s.script),0)+(r?this.ins.reduce((n,s)=>n+sk(s.witness),0):0)}clone(){const t=new Te;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($r(we.tuple(we.UInt32,we.Buffer,we.Number),arguments),t>=this.ins.length)return Up;const s=Np.compile(Np.decompile(r).filter(a=>a!==nk.OPS.OP_CODESEPARATOR)),i=this.clone();if((n&31)===Te.SIGHASH_NONE)i.outs=[],i.ins.forEach((a,c)=>{c!==t&&(a.sequence=0)});else if((n&31)===Te.SIGHASH_SINGLE){if(t>=this.outs.length)return Up;i.outs.length=t+1;for(let a=0;a<t;a++)i.outs[a]=ok;i.ins.forEach((a,c)=>{c!==t&&(a.sequence=0)})}n&Te.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[t]],i.ins[0].script=s):(i.ins.forEach(a=>{a.script=jn}),i.ins[t].script=s);const o=Buffer.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(n,o.length-4),i.__toBuffer(o,0,!1),At.hash256(o)}hashForWitnessV1(t,r,n,s,i,o){if($r(we.tuple(we.UInt32,$r.arrayOf(we.Buffer),$r.arrayOf(we.Satoshi),we.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 a=s===Te.SIGHASH_DEFAULT?Te.SIGHASH_ALL:s&Te.SIGHASH_OUTPUT_MASK,l=(s&Te.SIGHASH_INPUT_MASK)===Te.SIGHASH_ANYONECANPAY,u=a===Te.SIGHASH_NONE,f=a===Te.SIGHASH_SINGLE;let p=jn,d=jn,m=jn,g=jn,w=jn;if(!l){let S=Ye.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(I=>{S.writeSlice(I.hash),S.writeUInt32(I.index)}),p=At.sha256(S.end()),S=Ye.BufferWriter.withCapacity(8*this.ins.length),n.forEach(I=>S.writeUInt64(I)),d=At.sha256(S.end()),S=Ye.BufferWriter.withCapacity(r.map(Fr).reduce((I,P)=>I+P)),r.forEach(I=>S.writeVarSlice(I)),m=At.sha256(S.end()),S=Ye.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(I=>S.writeUInt32(I.sequence)),g=At.sha256(S.end())}if(u||f){if(f&&t<this.outs.length){const S=this.outs[t],I=Ye.BufferWriter.withCapacity(8+Fr(S.script));I.writeUInt64(S.value),I.writeVarSlice(S.script),w=At.sha256(I.end())}}else{const S=this.outs.map(P=>8+Fr(P.script)).reduce((P,$)=>P+$),I=Ye.BufferWriter.withCapacity(S);this.outs.forEach(P=>{I.writeUInt64(P.value),I.writeVarSlice(P.script)}),w=At.sha256(I.end())}const A=(i?2:0)+(o?1:0),T=174-(l?49:0)-(u?32:0)+(o?32:0)+(i?37:0),E=Ye.BufferWriter.withCapacity(T);if(E.writeUInt8(s),E.writeInt32(this.version),E.writeUInt32(this.locktime),E.writeSlice(p),E.writeSlice(d),E.writeSlice(m),E.writeSlice(g),u||f||E.writeSlice(w),E.writeUInt8(A),l){const S=this.ins[t];E.writeSlice(S.hash),E.writeUInt32(S.index),E.writeUInt64(n[t]),E.writeVarSlice(r[t]),E.writeUInt32(S.sequence)}else E.writeUInt32(t);if(o){const S=Ye.BufferWriter.withCapacity(Fr(o));S.writeVarSlice(o),E.writeSlice(At.sha256(S.end()))}return f&&E.writeSlice(w),i&&(E.writeSlice(i),E.writeUInt8(0),E.writeUInt32(4294967295)),At.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),E.end()]))}hashForWitnessV0(t,r,n,s){$r(we.tuple(we.UInt32,we.Buffer,we.Satoshi,we.UInt32),arguments);let i=Buffer.from([]),o,a=Ru,c=Ru,l=Ru;if(s&Te.SIGHASH_ANYONECANPAY||(i=Buffer.allocUnsafe(36*this.ins.length),o=new Ye.BufferWriter(i,0),this.ins.forEach(f=>{o.writeSlice(f.hash),o.writeUInt32(f.index)}),c=At.hash256(i)),!(s&Te.SIGHASH_ANYONECANPAY)&&(s&31)!==Te.SIGHASH_SINGLE&&(s&31)!==Te.SIGHASH_NONE&&(i=Buffer.allocUnsafe(4*this.ins.length),o=new Ye.BufferWriter(i,0),this.ins.forEach(f=>{o.writeUInt32(f.sequence)}),l=At.hash256(i)),(s&31)!==Te.SIGHASH_SINGLE&&(s&31)!==Te.SIGHASH_NONE){const f=this.outs.reduce((p,d)=>p+8+Fr(d.script),0);i=Buffer.allocUnsafe(f),o=new Ye.BufferWriter(i,0),this.outs.forEach(p=>{o.writeUInt64(p.value),o.writeVarSlice(p.script)}),a=At.hash256(i)}else if((s&31)===Te.SIGHASH_SINGLE&&t<this.outs.length){const f=this.outs[t];i=Buffer.allocUnsafe(8+Fr(f.script)),o=new Ye.BufferWriter(i,0),o.writeUInt64(f.value),o.writeVarSlice(f.script),a=At.hash256(i)}i=Buffer.allocUnsafe(156+Fr(r)),o=new Ye.BufferWriter(i,0);const u=this.ins[t];return o.writeInt32(this.version),o.writeSlice(c),o.writeSlice(l),o.writeSlice(u.hash),o.writeUInt32(u.index),o.writeVarSlice(r),o.writeUInt64(n),o.writeUInt32(u.sequence),o.writeSlice(a),o.writeUInt32(this.locktime),o.writeUInt32(s),At.hash256(i)}getHash(t){return t&&this.isCoinbase()?Buffer.alloc(32,0):At.hash256(this.__toBuffer(void 0,void 0,t))}getId(){return(0,Ye.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){$r(we.tuple(we.Number,we.Buffer),arguments),this.ins[t].script=r}setWitness(t,r){$r(we.tuple(we.Number,[we.Buffer]),arguments),this.ins[t].witness=r}__toBuffer(t,r,n=!1){t||(t=Buffer.allocUnsafe(this.byteLength(n)));const s=new Ye.BufferWriter(t,r||0);s.writeInt32(this.version);const i=n&&this.hasWitnesses();return i&&(s.writeUInt8(Te.ADVANCED_TRANSACTION_MARKER),s.writeUInt8(Te.ADVANCED_TRANSACTION_FLAG)),s.writeVarInt(this.ins.length),this.ins.forEach(o=>{s.writeSlice(o.hash),s.writeUInt32(o.index),s.writeVarSlice(o.script),s.writeUInt32(o.sequence)}),s.writeVarInt(this.outs.length),this.outs.forEach(o=>{ak(o)?s.writeUInt64(o.value):s.writeSlice(o.valueBuffer),s.writeVarSlice(o.script)}),i&&this.ins.forEach(o=>{s.writeVector(o.witness)}),s.writeUInt32(this.locktime),r!==void 0?t.slice(r,s.offset):t}};oa.Transaction=Ir;Ir.DEFAULT_SEQUENCE=4294967295;Ir.SIGHASH_DEFAULT=0;Ir.SIGHASH_ALL=1;Ir.SIGHASH_NONE=2;Ir.SIGHASH_SINGLE=3;Ir.SIGHASH_ANYONECANPAY=128;Ir.SIGHASH_OUTPUT_MASK=3;Ir.SIGHASH_INPUT_MASK=128;Ir.ADVANCED_TRANSACTION_MARKER=0;Ir.ADVANCED_TRANSACTION_FLAG=1;var Ie={},aa={};Object.defineProperty(aa,"__esModule",{value:!0});const ck=9007199254740991;function nh(e){if(e<0||e>ck||e%1!==0)throw new RangeError("value out of range")}function Xi(e,t,r){if(nh(e),t||(t=Buffer.allocUnsafe(Fb(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(Xi,{bytes:1})):e<=65535?(t.writeUInt8(253,r),t.writeUInt16LE(e,r+1),Object.assign(Xi,{bytes:3})):e<=4294967295?(t.writeUInt8(254,r),t.writeUInt32LE(e,r+1),Object.assign(Xi,{bytes:5})):(t.writeUInt8(255,r),t.writeUInt32LE(e>>>0,r+1),t.writeUInt32LE(e/4294967296|0,r+5),Object.assign(Xi,{bytes:9})),t}aa.encode=Xi;function Yi(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(Yi,{bytes:1}),r;if(r===253)return Object.assign(Yi,{bytes:3}),e.readUInt16LE(t+1);if(r===254)return Object.assign(Yi,{bytes:5}),e.readUInt32LE(t+1);{Object.assign(Yi,{bytes:9});const n=e.readUInt32LE(t+1),i=e.readUInt32LE(t+5)*4294967296+n;return nh(i),i}}aa.decode=Yi;function Fb(e){return nh(e),e<253?1:e<=65535?3:e<=4294967295?5:9}aa.encodingLength=Fb;var $u={},Dc={},bt={};Object.defineProperty(bt,"__esModule",{value:!0});bt.testnet=bt.regtest=bt.bitcoin=void 0;bt.bitcoin={messagePrefix:`Bitcoin Signed Message:
|
|
51
|
+
`,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};bt.regtest={messagePrefix:`Bitcoin Signed Message:
|
|
52
|
+
`,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};bt.testnet={messagePrefix:`Bitcoin Signed Message:
|
|
53
|
+
`,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var Gt={};Object.defineProperty(Gt,"__esModule",{value:!0});Gt.value=Gt.prop=void 0;function uk(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})}})}Gt.prop=uk;function lk(e){let t;return()=>(t!==void 0||(t=e()),t)}Gt.value=lk;Object.defineProperty(Dc,"__esModule",{value:!0});Dc.p2data=void 0;const fk=bt,Ha=Yt(),Nr=wt,Mp=Gt,Fp=Ha.OPS;function dk(e,t){if(!e.data&&!e.output)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Nr.typeforce)({network:Nr.typeforce.maybe(Nr.typeforce.Object),output:Nr.typeforce.maybe(Nr.typeforce.Buffer),data:Nr.typeforce.maybe(Nr.typeforce.arrayOf(Nr.typeforce.Buffer))},e);const n={name:"embed",network:e.network||fk.bitcoin};if(Mp.prop(n,"output",()=>{if(e.data)return Ha.compile([Fp.OP_RETURN].concat(e.data))}),Mp.prop(n,"data",()=>{if(e.output)return Ha.decompile(e.output).slice(1)}),t.validate&&e.output){const s=Ha.decompile(e.output);if(s[0]!==Fp.OP_RETURN)throw new TypeError("Output is invalid");if(!s.slice(1).every(Nr.typeforce.Buffer))throw new TypeError("Output is invalid");if(e.data&&!(0,Nr.stacksEqual)(e.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,e)}Dc.p2data=dk;var Hc={};Object.defineProperty(Hc,"__esModule",{value:!0});Hc.p2ms=void 0;const hk=bt,Qs=Yt(),We=wt,Rn=Gt,ei=Qs.OPS,Sa=ei.OP_RESERVED;function pk(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 Qs.isCanonicalScriptSignature(c)||(t.allowIncomplete&&c===ei.OP_0)!==void 0}(0,We.typeforce)({network:We.typeforce.maybe(We.typeforce.Object),m:We.typeforce.maybe(We.typeforce.Number),n:We.typeforce.maybe(We.typeforce.Number),output:We.typeforce.maybe(We.typeforce.Buffer),pubkeys:We.typeforce.maybe(We.typeforce.arrayOf(We.isPoint)),signatures:We.typeforce.maybe(We.typeforce.arrayOf(r)),input:We.typeforce.maybe(We.typeforce.Buffer)},e);const s={network:e.network||hk.bitcoin};let i=[],o=!1;function a(c){o||(o=!0,i=Qs.decompile(c),s.m=i[0]-Sa,s.n=i[i.length-2]-Sa,s.pubkeys=i.slice(1,-2))}if(Rn.prop(s,"output",()=>{if(e.m&&s.n&&e.pubkeys)return Qs.compile([].concat(Sa+e.m,e.pubkeys,Sa+s.n,ei.OP_CHECKMULTISIG))}),Rn.prop(s,"m",()=>{if(s.output)return a(s.output),s.m}),Rn.prop(s,"n",()=>{if(s.pubkeys)return s.pubkeys.length}),Rn.prop(s,"pubkeys",()=>{if(e.output)return a(e.output),s.pubkeys}),Rn.prop(s,"signatures",()=>{if(e.input)return Qs.decompile(e.input).slice(1)}),Rn.prop(s,"input",()=>{if(e.signatures)return Qs.compile([ei.OP_0].concat(e.signatures))}),Rn.prop(s,"witness",()=>{if(s.input)return[]}),Rn.prop(s,"name",()=>{if(!(!s.m||!s.n))return`p2ms(${s.m} of ${s.n})`}),t.validate){if(e.output){if(a(e.output),!We.typeforce.Number(i[0]))throw new TypeError("Output is invalid");if(!We.typeforce.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==ei.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(s.m<=0||s.n>16||s.m>s.n||s.n!==i.length-3)throw new TypeError("Output is invalid");if(!s.pubkeys.every(c=>(0,We.isPoint)(c)))throw new TypeError("Output is invalid");if(e.m!==void 0&&e.m!==s.m)throw new TypeError("m mismatch");if(e.n!==void 0&&e.n!==s.n)throw new TypeError("n mismatch");if(e.pubkeys&&!(0,We.stacksEqual)(e.pubkeys,s.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(s.n=e.pubkeys.length,s.n<s.m)throw new TypeError("Pubkey count cannot be less than m")}if(e.signatures){if(e.signatures.length<s.m)throw new TypeError("Not enough signatures provided");if(e.signatures.length>s.m)throw new TypeError("Too many signatures provided")}if(e.input){if(e.input[0]!==ei.OP_0)throw new TypeError("Input is invalid");if(s.signatures.length===0||!s.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(e.signatures&&!(0,We.stacksEqual)(e.signatures,s.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(s,e)}Hc.p2ms=pk;var zc={};Object.defineProperty(zc,"__esModule",{value:!0});zc.p2pk=void 0;const yk=bt,ti=Yt(),hr=wt,Zs=Gt,jp=ti.OPS;function mk(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,hr.typeforce)({network:hr.typeforce.maybe(hr.typeforce.Object),output:hr.typeforce.maybe(hr.typeforce.Buffer),pubkey:hr.typeforce.maybe(hr.isPoint),signature:hr.typeforce.maybe(ti.isCanonicalScriptSignature),input:hr.typeforce.maybe(hr.typeforce.Buffer)},e);const r=Zs.value(()=>ti.decompile(e.input)),s={name:"p2pk",network:e.network||yk.bitcoin};if(Zs.prop(s,"output",()=>{if(e.pubkey)return ti.compile([e.pubkey,jp.OP_CHECKSIG])}),Zs.prop(s,"pubkey",()=>{if(e.output)return e.output.slice(1,-1)}),Zs.prop(s,"signature",()=>{if(e.input)return r()[0]}),Zs.prop(s,"input",()=>{if(e.signature)return ti.compile([e.signature])}),Zs.prop(s,"witness",()=>{if(s.input)return[]}),t.validate){if(e.output){if(e.output[e.output.length-1]!==jp.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,hr.isPoint)(s.pubkey))throw new TypeError("Output pubkey is invalid");if(e.pubkey&&!e.pubkey.equals(s.pubkey))throw new TypeError("Pubkey mismatch")}if(e.signature&&e.input&&!e.input.equals(s.input))throw new TypeError("Signature mismatch");if(e.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!ti.isCanonicalScriptSignature(s.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(s,e)}zc.p2pk=mk;var qc={};function gk(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 s=e.charAt(n),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=n}var o=e.length,a=e.charAt(0),c=Math.log(o)/Math.log(256),l=Math.log(256)/Math.log(o);function u(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 m=0,g=0,w=0,A=d.length;w!==A&&d[w]===0;)w++,m++;for(var T=(A-w)*l+1>>>0,E=new Uint8Array(T);w!==A;){for(var S=d[w],I=0,P=T-1;(S!==0||I<g)&&P!==-1;P--,I++)S+=256*E[P]>>>0,E[P]=S%o>>>0,S=S/o>>>0;if(S!==0)throw new Error("Non-zero carry");g=I,w++}for(var $=T-g;$!==T&&E[$]===0;)$++;for(var j=a.repeat(m);$<T;++$)j+=e.charAt(E[$]);return j}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;for(var m=0,g=0,w=0;d[m]===a;)g++,m++;for(var A=(d.length-m)*c+1>>>0,T=new Uint8Array(A);d[m];){var E=d.charCodeAt(m);if(E>255)return;var S=t[E];if(S===255)return;for(var I=0,P=A-1;(S!==0||I<w)&&P!==-1;P--,I++)S+=o*T[P]>>>0,T[P]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");w=I,m++}for(var $=A-w;$!==A&&T[$]===0;)$++;for(var j=new Uint8Array(g+(A-$)),k=g;$!==A;)j[k++]=T[$++];return j}function p(d){var m=f(d);if(m)return m;throw new Error("Non-base"+o+" character")}return{encode:u,decodeUnsafe:f,decode:p}}var bk=gk;const wk=bk,vk="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var Ek=wk(vk),Nu=Ek,Ak=function(e){function t(i){var o=Uint8Array.from(i),a=e(o),c=o.length+4,l=new Uint8Array(c);return l.set(o,0),l.set(a.subarray(0,4),o.length),Nu.encode(l,c)}function r(i){var o=i.slice(0,-4),a=i.slice(-4),c=e(o);if(!(a[0]^c[0]|a[1]^c[1]|a[2]^c[2]|a[3]^c[3]))return o}function n(i){var o=Nu.decodeUnsafe(i);if(o)return r(o)}function s(i){var o=Nu.decode(i),a=r(o);if(!a)throw new Error("Invalid checksum");return a}return{encode:t,decode:s,decodeUnsafe:n}},{sha256:Lp}=Nb,xk=Ak;function Sk(e){return Lp(Lp(e))}var sh=xk(Sk);Object.defineProperty(qc,"__esModule",{value:!0});qc.p2pkh=void 0;const Uu=rs,_k=bt,ri=Yt(),xt=wt,en=Gt,Dp=sh,$n=ri.OPS;function kk(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,xt.typeforce)({network:xt.typeforce.maybe(xt.typeforce.Object),address:xt.typeforce.maybe(xt.typeforce.String),hash:xt.typeforce.maybe(xt.typeforce.BufferN(20)),output:xt.typeforce.maybe(xt.typeforce.BufferN(25)),pubkey:xt.typeforce.maybe(xt.isPoint),signature:xt.typeforce.maybe(ri.isCanonicalScriptSignature),input:xt.typeforce.maybe(xt.typeforce.Buffer)},e);const r=en.value(()=>{const o=Buffer.from(Dp.decode(e.address)),a=o.readUInt8(0),c=o.slice(1);return{version:a,hash:c}}),n=en.value(()=>ri.decompile(e.input)),s=e.network||_k.bitcoin,i={name:"p2pkh",network:s};if(en.prop(i,"address",()=>{if(!i.hash)return;const o=Buffer.allocUnsafe(21);return o.writeUInt8(s.pubKeyHash,0),i.hash.copy(o,1),Dp.encode(o)}),en.prop(i,"hash",()=>{if(e.output)return e.output.slice(3,23);if(e.address)return r().hash;if(e.pubkey||i.pubkey)return Uu.hash160(e.pubkey||i.pubkey)}),en.prop(i,"output",()=>{if(i.hash)return ri.compile([$n.OP_DUP,$n.OP_HASH160,i.hash,$n.OP_EQUALVERIFY,$n.OP_CHECKSIG])}),en.prop(i,"pubkey",()=>{if(e.input)return n()[1]}),en.prop(i,"signature",()=>{if(e.input)return n()[0]}),en.prop(i,"input",()=>{if(e.pubkey&&e.signature)return ri.compile([e.signature,e.pubkey])}),en.prop(i,"witness",()=>{if(i.input)return[]}),t.validate){let o=Buffer.from([]);if(e.address){if(r().version!==s.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");o=r().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!==25||e.output[0]!==$n.OP_DUP||e.output[1]!==$n.OP_HASH160||e.output[2]!==20||e.output[23]!==$n.OP_EQUALVERIFY||e.output[24]!==$n.OP_CHECKSIG)throw new TypeError("Output is invalid");const a=e.output.slice(3,23);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.pubkey){const a=Uu.hash160(e.pubkey);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.input){const a=n();if(a.length!==2)throw new TypeError("Input is invalid");if(!ri.isCanonicalScriptSignature(a[0]))throw new TypeError("Input has invalid signature");if(!(0,xt.isPoint)(a[1]))throw new TypeError("Input has invalid pubkey");if(e.signature&&!e.signature.equals(a[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(a[1]))throw new TypeError("Pubkey mismatch");const c=Uu.hash160(a[1]);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch")}}return Object.assign(i,e)}qc.p2pkh=kk;var Vc={};Object.defineProperty(Vc,"__esModule",{value:!0});Vc.p2sh=void 0;const Hp=rs,Tk=bt,jr=Yt(),Ce=wt,Ur=Gt,zp=sh,Li=jr.OPS;function Ik(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,Ce.typeforce)({network:Ce.typeforce.maybe(Ce.typeforce.Object),address:Ce.typeforce.maybe(Ce.typeforce.String),hash:Ce.typeforce.maybe(Ce.typeforce.BufferN(20)),output:Ce.typeforce.maybe(Ce.typeforce.BufferN(23)),redeem:Ce.typeforce.maybe({network:Ce.typeforce.maybe(Ce.typeforce.Object),output:Ce.typeforce.maybe(Ce.typeforce.Buffer),input:Ce.typeforce.maybe(Ce.typeforce.Buffer),witness:Ce.typeforce.maybe(Ce.typeforce.arrayOf(Ce.typeforce.Buffer))}),input:Ce.typeforce.maybe(Ce.typeforce.Buffer),witness:Ce.typeforce.maybe(Ce.typeforce.arrayOf(Ce.typeforce.Buffer))},e);let r=e.network;r||(r=e.redeem&&e.redeem.network||Tk.bitcoin);const n={network:r},s=Ur.value(()=>{const a=Buffer.from(zp.decode(e.address)),c=a.readUInt8(0),l=a.slice(1);return{version:c,hash:l}}),i=Ur.value(()=>jr.decompile(e.input)),o=Ur.value(()=>{const a=i(),c=a[a.length-1];return{network:r,output:c===Li.OP_FALSE?Buffer.from([]):c,input:jr.compile(a.slice(0,-1)),witness:e.witness||[]}});if(Ur.prop(n,"address",()=>{if(!n.hash)return;const a=Buffer.allocUnsafe(21);return a.writeUInt8(n.network.scriptHash,0),n.hash.copy(a,1),zp.encode(a)}),Ur.prop(n,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return s().hash;if(n.redeem&&n.redeem.output)return Hp.hash160(n.redeem.output)}),Ur.prop(n,"output",()=>{if(n.hash)return jr.compile([Li.OP_HASH160,n.hash,Li.OP_EQUAL])}),Ur.prop(n,"redeem",()=>{if(e.input)return o()}),Ur.prop(n,"input",()=>{if(!(!e.redeem||!e.redeem.input||!e.redeem.output))return jr.compile([].concat(jr.decompile(e.redeem.input),e.redeem.output))}),Ur.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),Ur.prop(n,"name",()=>{const a=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&a.push(n.redeem.name),a.join("-")}),t.validate){let a=Buffer.from([]);if(e.address){if(s().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(s().hash.length!==20)throw new TypeError("Invalid address");a=s().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!==23||e.output[0]!==Li.OP_HASH160||e.output[1]!==20||e.output[22]!==Li.OP_EQUAL)throw new TypeError("Output is invalid");const l=e.output.slice(2,22);if(a.length>0&&!a.equals(l))throw new TypeError("Hash mismatch");a=l}const c=l=>{if(l.output){const u=jr.decompile(l.output);if(!u||u.length<1)throw new TypeError("Redeem.output too short");if(l.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(jr.countNonPushOnlyOPs(u)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const f=Hp.hash160(l.output);if(a.length>0&&!a.equals(f))throw new TypeError("Hash mismatch");a=f}if(l.input){const u=l.input.length>0,f=l.witness&&l.witness.length>0;if(!u&&!f)throw new TypeError("Empty input");if(u&&f)throw new TypeError("Input and witness provided");if(u){const p=jr.decompile(l.input);if(!jr.isPushOnly(p))throw new TypeError("Non push-only scriptSig")}}};if(e.input){const l=i();if(!l||l.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(o().output))throw new TypeError("Input is invalid");c(o())}if(e.redeem){if(e.redeem.network&&e.redeem.network!==r)throw new TypeError("Network mismatch");if(e.input){const l=o();if(e.redeem.output&&!e.redeem.output.equals(l.output))throw new TypeError("Redeem.output mismatch");if(e.redeem.input&&!e.redeem.input.equals(l.input))throw new TypeError("Redeem.input mismatch")}c(e.redeem)}if(e.witness&&e.redeem&&e.redeem.witness&&!(0,Ce.stacksEqual)(e.redeem.witness,e.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,e)}Vc.p2sh=Ik;var Gc={},An={};Object.defineProperty(An,"__esModule",{value:!0});An.bech32m=An.bech32=void 0;const sc="qpzry9x8gf2tvdw0s3jn54khce6mua7l",jb={};for(let e=0;e<sc.length;e++){const t=sc.charAt(e);jb[t]=e}function di(e){const t=e>>25;return(e&33554431)<<5^-(t>>0&1)&996825010^-(t>>1&1)&642813549^-(t>>2&1)&513874426^-(t>>3&1)&1027748829^-(t>>4&1)&705979059}function qp(e){let t=1;for(let r=0;r<e.length;++r){const n=e.charCodeAt(r);if(n<33||n>126)return"Invalid prefix ("+e+")";t=di(t)^n>>5}t=di(t);for(let r=0;r<e.length;++r){const n=e.charCodeAt(r);t=di(t)^n&31}return t}function ih(e,t,r,n){let s=0,i=0;const o=(1<<r)-1,a=[];for(let c=0;c<e.length;++c)for(s=s<<t|e[c],i+=t;i>=r;)i-=r,a.push(s>>i&o);if(n)i>0&&a.push(s<<r-i&o);else{if(i>=t)return"Excess padding";if(s<<r-i&o)return"Non-zero padding"}return a}function Pk(e){return ih(e,8,5,!0)}function Ok(e){const t=ih(e,5,8,!1);if(Array.isArray(t))return t}function Bk(e){const t=ih(e,5,8,!1);if(Array.isArray(t))return t;throw new Error(t)}function Lb(e){let t;e==="bech32"?t=1:t=734539939;function r(o,a,c){if(c=c||90,o.length+7+a.length>c)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let l=qp(o);if(typeof l=="string")throw new Error(l);let u=o+"1";for(let f=0;f<a.length;++f){const p=a[f];if(p>>5)throw new Error("Non 5-bit word");l=di(l)^p,u+=sc.charAt(p)}for(let f=0;f<6;++f)l=di(l);l^=t;for(let f=0;f<6;++f){const p=l>>(5-f)*5&31;u+=sc.charAt(p)}return u}function n(o,a){if(a=a||90,o.length<8)return o+" too short";if(o.length>a)return"Exceeds length limit";const c=o.toLowerCase(),l=o.toUpperCase();if(o!==c&&o!==l)return"Mixed-case string "+o;o=c;const u=o.lastIndexOf("1");if(u===-1)return"No separator character for "+o;if(u===0)return"Missing prefix for "+o;const f=o.slice(0,u),p=o.slice(u+1);if(p.length<6)return"Data too short";let d=qp(f);if(typeof d=="string")return d;const m=[];for(let g=0;g<p.length;++g){const w=p.charAt(g),A=jb[w];if(A===void 0)return"Unknown character "+w;d=di(d)^A,!(g+6>=p.length)&&m.push(A)}return d!==t?"Invalid checksum for "+o:{prefix:f,words:m}}function s(o,a){const c=n(o,a);if(typeof c=="object")return c}function i(o,a){const c=n(o,a);if(typeof c=="object")return c;throw new Error(c)}return{decodeUnsafe:s,decode:i,encode:r,toWords:Pk,fromWordsUnsafe:Ok,fromWords:Bk}}An.bech32=Lb("bech32");An.bech32m=Lb("bech32m");Object.defineProperty(Gc,"__esModule",{value:!0});Gc.p2wpkh=void 0;const Mu=rs,Ck=bt,za=Yt(),et=wt,Nn=Gt,_a=An,Vp=za.OPS,Rk=Buffer.alloc(0);function $k(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,et.typeforce)({address:et.typeforce.maybe(et.typeforce.String),hash:et.typeforce.maybe(et.typeforce.BufferN(20)),input:et.typeforce.maybe(et.typeforce.BufferN(0)),network:et.typeforce.maybe(et.typeforce.Object),output:et.typeforce.maybe(et.typeforce.BufferN(22)),pubkey:et.typeforce.maybe(et.isPoint),signature:et.typeforce.maybe(za.isCanonicalScriptSignature),witness:et.typeforce.maybe(et.typeforce.arrayOf(et.typeforce.Buffer))},e);const r=Nn.value(()=>{const i=_a.bech32.decode(e.address),o=i.words.shift(),a=_a.bech32.fromWords(i.words);return{version:o,prefix:i.prefix,data:Buffer.from(a)}}),n=e.network||Ck.bitcoin,s={name:"p2wpkh",network:n};if(Nn.prop(s,"address",()=>{if(!s.hash)return;const i=_a.bech32.toWords(s.hash);return i.unshift(0),_a.bech32.encode(n.bech32,i)}),Nn.prop(s,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return r().data;if(e.pubkey||s.pubkey)return Mu.hash160(e.pubkey||s.pubkey)}),Nn.prop(s,"output",()=>{if(s.hash)return za.compile([Vp.OP_0,s.hash])}),Nn.prop(s,"pubkey",()=>{if(e.pubkey)return e.pubkey;if(e.witness)return e.witness[1]}),Nn.prop(s,"signature",()=>{if(e.witness)return e.witness[0]}),Nn.prop(s,"input",()=>{if(s.witness)return Rk}),Nn.prop(s,"witness",()=>{if(e.pubkey&&e.signature)return[e.signature,e.pubkey]}),t.validate){let i=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");i=r().data}if(e.hash){if(i.length>0&&!i.equals(e.hash))throw new TypeError("Hash mismatch");i=e.hash}if(e.output){if(e.output.length!==22||e.output[0]!==Vp.OP_0||e.output[1]!==20)throw new TypeError("Output is invalid");if(i.length>0&&!i.equals(e.output.slice(2)))throw new TypeError("Hash mismatch");i=e.output.slice(2)}if(e.pubkey){const o=Mu.hash160(e.pubkey);if(i.length>0&&!i.equals(o))throw new TypeError("Hash mismatch");if(i=o,!(0,et.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(!za.isCanonicalScriptSignature(e.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,et.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 o=Mu.hash160(e.witness[1]);if(i.length>0&&!i.equals(o))throw new TypeError("Hash mismatch")}}return Object.assign(s,e)}Gc.p2wpkh=$k;var Wc={};Object.defineProperty(Wc,"__esModule",{value:!0});Wc.p2wsh=void 0;const Gp=rs,Nk=bt,cn=Yt(),Oe=wt,tn=Gt,ka=An,Wp=cn.OPS,Fu=Buffer.alloc(0);function Ta(e){return!!(Buffer.isBuffer(e)&&e.length===65&&e[0]===4&&(0,Oe.isPoint)(e))}function Uk(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,Oe.typeforce)({network:Oe.typeforce.maybe(Oe.typeforce.Object),address:Oe.typeforce.maybe(Oe.typeforce.String),hash:Oe.typeforce.maybe(Oe.typeforce.BufferN(32)),output:Oe.typeforce.maybe(Oe.typeforce.BufferN(34)),redeem:Oe.typeforce.maybe({input:Oe.typeforce.maybe(Oe.typeforce.Buffer),network:Oe.typeforce.maybe(Oe.typeforce.Object),output:Oe.typeforce.maybe(Oe.typeforce.Buffer),witness:Oe.typeforce.maybe(Oe.typeforce.arrayOf(Oe.typeforce.Buffer))}),input:Oe.typeforce.maybe(Oe.typeforce.BufferN(0)),witness:Oe.typeforce.maybe(Oe.typeforce.arrayOf(Oe.typeforce.Buffer))},e);const r=tn.value(()=>{const o=ka.bech32.decode(e.address),a=o.words.shift(),c=ka.bech32.fromWords(o.words);return{version:a,prefix:o.prefix,data:Buffer.from(c)}}),n=tn.value(()=>cn.decompile(e.redeem.input));let s=e.network;s||(s=e.redeem&&e.redeem.network||Nk.bitcoin);const i={network:s};if(tn.prop(i,"address",()=>{if(!i.hash)return;const o=ka.bech32.toWords(i.hash);return o.unshift(0),ka.bech32.encode(s.bech32,o)}),tn.prop(i,"hash",()=>{if(e.output)return e.output.slice(2);if(e.address)return r().data;if(i.redeem&&i.redeem.output)return Gp.sha256(i.redeem.output)}),tn.prop(i,"output",()=>{if(i.hash)return cn.compile([Wp.OP_0,i.hash])}),tn.prop(i,"redeem",()=>{if(e.witness)return{output:e.witness[e.witness.length-1],input:Fu,witness:e.witness.slice(0,-1)}}),tn.prop(i,"input",()=>{if(i.witness)return Fu}),tn.prop(i,"witness",()=>{if(e.redeem&&e.redeem.input&&e.redeem.input.length>0&&e.redeem.output&&e.redeem.output.length>0){const o=cn.toStack(n());return i.redeem=Object.assign({witness:o},e.redeem),i.redeem.input=Fu,[].concat(o,e.redeem.output)}if(e.redeem&&e.redeem.output&&e.redeem.witness)return[].concat(e.redeem.witness,e.redeem.output)}),tn.prop(i,"name",()=>{const o=["p2wsh"];return i.redeem!==void 0&&i.redeem.name!==void 0&&o.push(i.redeem.name),o.join("-")}),t.validate){let o=Buffer.from([]);if(e.address){if(r().prefix!==s.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==32)throw new TypeError("Invalid address data");o=r().data}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!==34||e.output[0]!==Wp.OP_0||e.output[1]!==32)throw new TypeError("Output is invalid");const a=e.output.slice(2);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.redeem){if(e.redeem.network&&e.redeem.network!==s)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 a=cn.decompile(e.redeem.output);if(!a||a.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(cn.countNonPushOnlyOPs(a)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const c=Gp.sha256(e.redeem.output);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch");o=c}if(e.redeem.input&&!cn.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(e.witness&&e.redeem.witness&&!(0,Oe.stacksEqual)(e.witness,e.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(e.redeem.input&&n().some(Ta)||e.redeem.output&&(cn.decompile(e.redeem.output)||[]).some(Ta))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(e.witness&&e.witness.length>0){const a=e.witness[e.witness.length-1];if(e.redeem&&e.redeem.output&&!e.redeem.output.equals(a))throw new TypeError("Witness and redeem.output mismatch");if(e.witness.some(Ta)||(cn.decompile(a)||[]).some(Ta))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(i,e)}Wc.p2wsh=Uk;var Di={},Rs={};Object.defineProperty(Rs,"__esModule",{value:!0});Rs.getEccLib=Rs.initEccLib=void 0;const so={};function Mk(e,t){e?e!==so.eccLib&&(t!=null&&t.DANGER_DO_NOT_VERIFY_ECCLIB||jk(e),so.eccLib=e):so.eccLib=e}Rs.initEccLib=Mk;function Fk(){if(!so.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return so.eccLib}Rs.getEccLib=Fk;const rn=e=>Buffer.from(e,"hex");function jk(e){Jt(typeof e.isXOnlyPoint=="function"),Jt(e.isXOnlyPoint(rn("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),Jt(e.isXOnlyPoint(rn("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),Jt(e.isXOnlyPoint(rn("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),Jt(e.isXOnlyPoint(rn("0000000000000000000000000000000000000000000000000000000000000001"))),Jt(!e.isXOnlyPoint(rn("0000000000000000000000000000000000000000000000000000000000000000"))),Jt(!e.isXOnlyPoint(rn("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),Jt(typeof e.xOnlyPointAddTweak=="function"),Lk.forEach(t=>{const r=e.xOnlyPointAddTweak(rn(t.pubkey),rn(t.tweak));t.result===null?Jt(r===null):(Jt(r!==null),Jt(r.parity===t.parity),Jt(Buffer.from(r.xOnlyPubkey).equals(rn(t.result))))})}function Jt(e){if(!e)throw new Error("ecc library invalid")}const Lk=[{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 oh={};(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=Hs,r=Rs,n=rs,s=ct,i=wt;e.LEAF_VERSION_TAPSCRIPT=192,e.MAX_TAPTREE_DEPTH=128;const o=g=>"left"in g&&"right"in g;function a(g,w){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 T=w;for(let E=0;E<A;E++){const S=g.slice(33+32*E,65+32*E);T.compare(S)<0?T=d(T,S):T=d(S,T)}return T}e.rootHashFromPath=a;function c(g){if((0,i.isTapleaf)(g))return{hash:u(g)};const w=[c(g[0]),c(g[1])];w.sort((E,S)=>E.hash.compare(S.hash));const[A,T]=w;return{hash:d(A.hash,T.hash),left:A,right:T}}e.toHashTree=c;function l(g,w){if(o(g)){const A=l(g.left,w);if(A!==void 0)return[...A,g.right.hash];const T=l(g.right,w);if(T!==void 0)return[...T,g.left.hash]}else if(g.hash.equals(w))return[]}e.findScriptPath=l;function u(g){const w=g.version||e.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",t.Buffer.concat([t.Buffer.from([w]),m(g.output)]))}e.tapleafHash=u;function f(g,w){return n.taggedHash("TapTweak",t.Buffer.concat(w?[g,w]:[g]))}e.tapTweakHash=f;function p(g,w){if(!t.Buffer.isBuffer(g)||g.length!==32||w&&w.length!==32)return null;const A=f(g,w),T=(0,r.getEccLib)().xOnlyPointAddTweak(g,A);return!T||T.xOnlyPubkey===null?null:{parity:T.parity,x:t.Buffer.from(T.xOnlyPubkey)}}e.tweakKey=p;function d(g,w){return n.taggedHash("TapBranch",t.Buffer.concat([g,w]))}function m(g){const w=s.varuint.encodingLength(g.length),A=t.Buffer.allocUnsafe(w);return s.varuint.encode(g.length,A),t.Buffer.concat([A,g])}})(oh);var St={},Kp;function Dk(){if(Kp)return St;Kp=1,Object.defineProperty(St,"__esModule",{value:!0}),St.toOutputScript=St.fromOutputScript=St.toBech32=St.toBase58Check=St.fromBech32=St.fromBase58Check=void 0;const e=bt,t=ah(),r=Yt(),n=wt,s=An,i=sh,o=40,a=2,c=16,l=2,u=80,f="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function p(E,S){const I=E.slice(2);if(I.length<a||I.length>o)throw new TypeError("Invalid program length for segwit address");const P=E[0]-u;if(P<l||P>c)throw new TypeError("Invalid version for segwit address");if(E[1]!==I.length)throw new TypeError("Invalid script for segwit address");return console.warn(f),w(I,P,S.bech32)}function d(E){const S=Buffer.from(i.decode(E));if(S.length<21)throw new TypeError(E+" is too short");if(S.length>21)throw new TypeError(E+" is too long");const I=S.readUInt8(0),P=S.slice(1);return{version:I,hash:P}}St.fromBase58Check=d;function m(E){let S,I;try{S=s.bech32.decode(E)}catch{}if(S){if(I=S.words[0],I!==0)throw new TypeError(E+" uses wrong encoding")}else if(S=s.bech32m.decode(E),I=S.words[0],I===0)throw new TypeError(E+" uses wrong encoding");const P=s.bech32.fromWords(S.words.slice(1));return{version:I,prefix:S.prefix,data:Buffer.from(P)}}St.fromBech32=m;function g(E,S){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const I=Buffer.allocUnsafe(21);return I.writeUInt8(S,0),E.copy(I,1),i.encode(I)}St.toBase58Check=g;function w(E,S,I){const P=s.bech32.toWords(E);return P.unshift(S),S===0?s.bech32.encode(I,P):s.bech32m.encode(I,P)}St.toBech32=w;function A(E,S){S=S||e.bitcoin;try{return t.p2pkh({output:E,network:S}).address}catch{}try{return t.p2sh({output:E,network:S}).address}catch{}try{return t.p2wpkh({output:E,network:S}).address}catch{}try{return t.p2wsh({output:E,network:S}).address}catch{}try{return t.p2tr({output:E,network:S}).address}catch{}try{return p(E,S)}catch{}throw new Error(r.toASM(E)+" has no matching Address")}St.fromOutputScript=A;function T(E,S){S=S||e.bitcoin;let I,P;try{I=d(E)}catch{}if(I){if(I.version===S.pubKeyHash)return t.p2pkh({hash:I.hash}).output;if(I.version===S.scriptHash)return t.p2sh({hash:I.hash}).output}else{try{P=m(E)}catch{}if(P){if(P.prefix!==S.bech32)throw new Error(E+" has an invalid prefix");if(P.version===0){if(P.data.length===20)return t.p2wpkh({hash:P.data}).output;if(P.data.length===32)return t.p2wsh({hash:P.data}).output}else if(P.version===1){if(P.data.length===32)return t.p2tr({pubkey:P.data}).output}else if(P.version>=l&&P.version<=c&&P.data.length>=a&&P.data.length<=o)return console.warn(f),r.compile([P.version+u,P.data])}}throw new Error(E+" has no matching Script")}return St.toOutputScript=T,St}var Xp;function Hk(){if(Xp)return Di;Xp=1,Object.defineProperty(Di,"__esModule",{value:!0}),Di.p2tr=void 0;const e=Hs,t=bt,r=Yt(),n=wt,s=Rs,i=oh,o=Gt,a=An,c=Dk(),l=r.OPS,u=1,f=80;function p(d,m){if(!d.address&&!d.output&&!d.pubkey&&!d.internalPubkey&&!(d.witness&&d.witness.length>1))throw new TypeError("Not enough data");m=Object.assign({validate:!0},m||{}),(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=o.value(()=>(0,c.fromBech32)(d.address)),w=o.value(()=>{if(!(!d.witness||!d.witness.length))return d.witness.length>=2&&d.witness[d.witness.length-1][0]===f?d.witness.slice(0,-1):d.witness.slice()}),A=o.value(()=>{if(d.scriptTree)return(0,i.toHashTree)(d.scriptTree);if(d.hash)return{hash:d.hash}}),T=d.network||t.bitcoin,E={name:"p2tr",network:T};if(o.prop(E,"address",()=>{if(!E.pubkey)return;const S=a.bech32m.toWords(E.pubkey);return S.unshift(u),a.bech32m.encode(T.bech32,S)}),o.prop(E,"hash",()=>{const S=A();if(S)return S.hash;const I=w();if(I&&I.length>1){const P=I[I.length-1],$=P[0]&n.TAPLEAF_VERSION_MASK,j=I[I.length-2],k=(0,i.tapleafHash)({output:j,version:$});return(0,i.rootHashFromPath)(P,k)}return null}),o.prop(E,"output",()=>{if(E.pubkey)return r.compile([l.OP_1,E.pubkey])}),o.prop(E,"redeemVersion",()=>d.redeemVersion?d.redeemVersion:d.redeem&&d.redeem.redeemVersion!==void 0&&d.redeem.redeemVersion!==null?d.redeem.redeemVersion:i.LEAF_VERSION_TAPSCRIPT),o.prop(E,"redeem",()=>{const S=w();if(!(!S||S.length<2))return{output:S[S.length-2],witness:S.slice(0,-2),redeemVersion:S[S.length-1][0]&n.TAPLEAF_VERSION_MASK}}),o.prop(E,"pubkey",()=>{if(d.pubkey)return d.pubkey;if(d.output)return d.output.slice(2);if(d.address)return g().data;if(E.internalPubkey){const S=(0,i.tweakKey)(E.internalPubkey,E.hash);if(S)return S.x}}),o.prop(E,"internalPubkey",()=>{if(d.internalPubkey)return d.internalPubkey;const S=w();if(S&&S.length>1)return S[S.length-1].slice(1,33)}),o.prop(E,"signature",()=>{if(d.signature)return d.signature;const S=w();if(!(!S||S.length!==1))return S[0]}),o.prop(E,"witness",()=>{if(d.witness)return d.witness;const S=A();if(S&&d.redeem&&d.redeem.output&&d.internalPubkey){const I=(0,i.tapleafHash)({output:d.redeem.output,version:E.redeemVersion}),P=(0,i.findScriptPath)(S,I);if(!P)return;const $=(0,i.tweakKey)(d.internalPubkey,S.hash);if(!$)return;const j=e.Buffer.concat([e.Buffer.from([E.redeemVersion|$.parity]),d.internalPubkey].concat(P));return[d.redeem.output,j]}if(d.signature)return[d.signature]}),m.validate){let S=e.Buffer.from([]);if(d.address){if(T&&T.bech32!==g().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(g().version!==u)throw new TypeError("Invalid address version");if(g().data.length!==32)throw new TypeError("Invalid address data");S=g().data}if(d.pubkey){if(S.length>0&&!S.equals(d.pubkey))throw new TypeError("Pubkey mismatch");S=d.pubkey}if(d.output){if(d.output.length!==34||d.output[0]!==l.OP_1||d.output[1]!==32)throw new TypeError("Output is invalid");if(S.length>0&&!S.equals(d.output.slice(2)))throw new TypeError("Pubkey mismatch");S=d.output.slice(2)}if(d.internalPubkey){const $=(0,i.tweakKey)(d.internalPubkey,E.hash);if(S.length>0&&!S.equals($.x))throw new TypeError("Pubkey mismatch");S=$.x}if(S&&S.length&&!(0,s.getEccLib)().isXOnlyPoint(S))throw new TypeError("Invalid pubkey for p2tr");const I=A();if(d.hash&&I&&!d.hash.equals(I.hash))throw new TypeError("Hash mismatch");if(d.redeem&&d.redeem.output&&I){const $=(0,i.tapleafHash)({output:d.redeem.output,version:E.redeemVersion});if(!(0,i.findScriptPath)(I,$))throw new TypeError("Redeem script not in tree")}const P=w();if(d.redeem&&E.redeem){if(d.redeem.redeemVersion&&d.redeem.redeemVersion!==E.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(E.redeem.output&&!d.redeem.output.equals(E.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(d.redeem.witness&&E.redeem.witness&&!(0,n.stacksEqual)(d.redeem.witness,E.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(P&&P.length)if(P.length===1){if(d.signature&&!d.signature.equals(P[0]))throw new TypeError("Signature mismatch")}else{const $=P[P.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 j=($.length-33)/32;if(j>128)throw new TypeError(`The script path is too long. Got ${j}, expected max 128.`);const k=$.slice(1,33);if(d.internalPubkey&&!d.internalPubkey.equals(k))throw new TypeError("Internal pubkey mismatch");if(!(0,s.getEccLib)().isXOnlyPoint(k))throw new TypeError("Invalid internalPubkey for p2tr witness");const F=$[0]&n.TAPLEAF_VERSION_MASK,R=P[P.length-2],U=(0,i.tapleafHash)({output:R,version:F}),H=(0,i.rootHashFromPath)($,U),W=(0,i.tweakKey)(k,H);if(!W)throw new TypeError("Invalid outputKey for p2tr witness");if(S.length&&!S.equals(W.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(W.parity!==($[0]&1))throw new Error("Incorrect parity")}}return Object.assign(E,d)}return Di.p2tr=p,Di}var Yp;function ah(){return Yp||(Yp=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=Dc;Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const r=Hc;Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=zc;Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const s=qc;Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return s.p2pkh}});const i=Vc;Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return i.p2sh}});const o=Gc;Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const a=Wc;Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return a.p2wsh}});const c=Hk();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return c.p2tr}})}($u)),$u}Object.defineProperty(Ie,"__esModule",{value:!0});Ie.signatureBlocksAction=Ie.checkInputForSig=Ie.pubkeyInScript=Ie.pubkeyPositionInScript=Ie.witnessStackToScriptWitness=Ie.isP2TR=Ie.isP2SHScript=Ie.isP2WSHScript=Ie.isP2WPKH=Ie.isP2PKH=Ie.isP2PK=Ie.isP2MS=void 0;const Zp=aa,io=Yt(),Ia=oa,zk=rs,zs=ah();function qs(e){return t=>{try{return e({output:t}),!0}catch{return!1}}}Ie.isP2MS=qs(zs.p2ms);Ie.isP2PK=qs(zs.p2pk);Ie.isP2PKH=qs(zs.p2pkh);Ie.isP2WPKH=qs(zs.p2wpkh);Ie.isP2WSHScript=qs(zs.p2wsh);Ie.isP2SHScript=qs(zs.p2sh);Ie.isP2TR=qs(zs.p2tr);function qk(e){let t=Buffer.allocUnsafe(0);function r(o){t=Buffer.concat([t,Buffer.from(o)])}function n(o){const a=t.length,c=Zp.encodingLength(o);t=Buffer.concat([t,Buffer.allocUnsafe(c)]),Zp.encode(o,t,a)}function s(o){n(o.length),r(o)}function i(o){n(o.length),o.forEach(s)}return i(e),t}Ie.witnessStackToScriptWitness=qk;function Db(e,t){const r=(0,zk.hash160)(e),n=e.slice(1,33),s=io.decompile(t);if(s===null)throw new Error("Unknown script error");return s.findIndex(i=>typeof i=="number"?!1:i.equals(e)||i.equals(r)||i.equals(n))}Ie.pubkeyPositionInScript=Db;function Vk(e,t){return Db(e,t)!==-1}Ie.pubkeyInScript=Vk;function Gk(e,t){return Wk(e).some(n=>Hb(n,io.signature.decode,t))}Ie.checkInputForSig=Gk;function Hb(e,t,r){const{hashType:n}=t(e),s=[];switch(n&Ia.Transaction.SIGHASH_ANYONECANPAY&&s.push("addInput"),n&31){case Ia.Transaction.SIGHASH_ALL:break;case Ia.Transaction.SIGHASH_SINGLE:case Ia.Transaction.SIGHASH_NONE:s.push("addOutput"),s.push("setInputSequence");break}return s.indexOf(r)===-1}Ie.signatureBlocksAction=Hb;function Wk(e){let t=[];if((e.partialSig||[]).length===0){if(!e.finalScriptSig&&!e.finalScriptWitness)return[];t=Kk(e)}else t=e.partialSig;return t.map(r=>r.signature)}function Kk(e){const t=e.finalScriptSig?io.decompile(e.finalScriptSig)||[]:[],r=e.finalScriptWitness?io.decompile(e.finalScriptWitness)||[]:[];return t.concat(r).filter(n=>Buffer.isBuffer(n)&&io.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(Le,"__esModule",{value:!0});Le.checkTaprootInputForSigs=Le.tapTreeFromList=Le.tapTreeToList=Le.tweakInternalPubKey=Le.checkTaprootOutputFields=Le.checkTaprootInputFields=Le.isTaprootOutput=Le.isTaprootInput=Zi=Le.serializeTaprootSignature=Le.tapScriptFinalizer=Le.toXOnly=void 0;const ch=wt,Xk=oa,Kc=Ie,es=oh,Yk=ah(),Zk=Ie,Jk=e=>e.length===32?e:e.slice(1,33);Le.toXOnly=Jk;function Qk(e,t,r){const n=gT(t,e,r);try{const i=yT(t,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,Kc.witnessStackToScriptWitness)(i)}}catch(s){throw new Error(`Can not finalize taproot input #${e}: ${s}`)}}Le.tapScriptFinalizer=Qk;function eT(e,t){const r=t?Buffer.from([t]):Buffer.from([]);return Buffer.concat([e,r])}var Zi=Le.serializeTaprootSignature=eT;function qa(e){return e&&!!(e.tapInternalKey||e.tapMerkleRoot||e.tapLeafScript&&e.tapLeafScript.length||e.tapBip32Derivation&&e.tapBip32Derivation.length||e.witnessUtxo&&(0,Kc.isP2TR)(e.witnessUtxo.script))}Le.isTaprootInput=qa;function Va(e,t){return e&&!!(e.tapInternalKey||e.tapTree||e.tapBip32Derivation&&e.tapBip32Derivation.length||t&&(0,Kc.isP2TR)(t))}Le.isTaprootOutput=Va;function tT(e,t,r){dT(e,t,r),pT(e,t,r)}Le.checkTaprootInputFields=tT;function rT(e,t,r){hT(e,t,r),nT(e,t)}Le.checkTaprootOutputFields=rT;function nT(e,t){if(!t.tapTree&&!t.tapInternalKey)return;const r=t.tapInternalKey||e.tapInternalKey,n=t.tapTree||e.tapTree;if(r){const{script:s}=e,i=sT(r,n);if(s&&!s.equals(i))throw new Error("Error adding output. Script or address missmatch.")}}function sT(e,t){const r=t&&zb(t.leaves),{output:n}=(0,Yk.p2tr)({internalPubkey:e,scriptTree:r});return n}function iT(e,t){const r=t.tapInternalKey,n=r&&(0,es.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}Le.tweakInternalPubKey=iT;function oT(e){if(!(0,ch.isTaptree)(e))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return Df(e)}Le.tapTreeToList=oT;function zb(e=[]){return e.length===1&&e[0].depth===0?{output:e[0].script,version:e[0].leafVersion}:fT(e)}Le.tapTreeFromList=zb;function aT(e,t){return uT(e).some(n=>(0,Zk.signatureBlocksAction)(n,cT,t))}Le.checkTaprootInputForSigs=aT;function cT(e){return{signature:e.slice(0,64),hashType:e.slice(64)[0]||Xk.Transaction.SIGHASH_DEFAULT}}function uT(e){const t=[];if(e.tapKeySig&&t.push(e.tapKeySig),e.tapScriptSig&&t.push(...e.tapScriptSig.map(r=>r.signature)),!t.length){const r=lT(e.finalScriptWitness);r&&t.push(r)}return t}function lT(e){if(!e)return;const t=e.slice(2);if(t.length===64||t.length===65)return t}function Df(e,t=[],r=0){if(r>es.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return e?(0,ch.isTapleaf)(e)?(t.push({depth:r,leafVersion:e.version||es.LEAF_VERSION_TAPSCRIPT,script:e.output}),t):(e[0]&&Df(e[0],t,r+1),e[1]&&Df(e[1],t,r+1),t):[]}function fT(e){let t;for(const r of e)if(t=Hf(r,t),!t)throw new Error("No room left to insert tapleaf in tree");return t}function Hf(e,t,r=0){if(r>es.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,ch.isTapleaf)(t))return;const n=Hf(e,t&&t[0],r+1);if(n)return[n,t&&t[1]];const s=Hf(e,t&&t[1],r+1);if(s)return[t&&t[0],s]}function dT(e,t,r){const n=qa(e)&&hi(t),s=hi(e)&&qa(t),i=e===t&&qa(t)&&hi(t);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function hT(e,t,r){const n=Va(e)&&hi(t),s=hi(e)&&Va(t),i=e===t&&Va(t)&&hi(t);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function pT(e,t,r){if(t.tapMerkleRoot){const n=(t.tapLeafScript||[]).every(i=>ju(i,t.tapMerkleRoot)),s=(e.tapLeafScript||[]).every(i=>ju(i,t.tapMerkleRoot));if(!n||!s)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(e.tapMerkleRoot&&!(t.tapLeafScript||[]).every(s=>ju(s,e.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function ju(e,t){if(!t)return!0;const r=(0,es.tapleafHash)({output:e.script,version:e.leafVersion});return(0,es.rootHashFromPath)(e.controlBlock,r).equals(t)}function yT(e,t){const r=(0,es.tapleafHash)({output:t.script,version:t.leafVersion});return(e.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>mT(t.script,n)).sort((n,s)=>s.positionInScript-n.positionInScript).map(n=>n.signature)}function mT(e,t){return Object.assign({positionInScript:(0,Kc.pubkeyPositionInScript)(t.pubkey,e)},t)}function gT(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((s,i)=>s.controlBlock.length-i.controlBlock.length).find(s=>bT(s,e.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${t}. Signature for tapleaf script not found.`);return n}function bT(e,t,r){const n=(0,es.tapleafHash)({output:e.script,version:e.leafVersion});return(!r||r.equals(n))&&t.find(i=>i.leafHash.equals(n))!==void 0}function hi(e){return e&&!!(e.redeemScript||e.witnessScript||e.bip32Derivation&&e.bip32Derivation.length)}const _t={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"},Pa=192;Se.initEccLib(ar);class oo{constructor(t,r,n,s,i,o,a,c){this.secretHash=n,this.redeemerPubkey=s,this.initiatorPubkey=i,this.expiry=o,this.signer=t,this.network=a,this.internalPubkey=g_(),this.initiateAmount=r,this.utxoHashes=c}static async from(t,r,n,s,i,o,a){n=n.startsWith("0x")?n.slice(2):n,Xs(n.length===64,_t.secretHashLenMismatch),Xs(s.length===64||s.length===66,`initiator ${_t.pubkeyLenMismatch}`),Xs(i.length===64||i.length===66,`redeemer ${_t.pubkeyLenMismatch}`),Xs(o>0,_t.zeroOrNegativeExpiry);const c=await t.getNetwork();return new oo(t,r,n,Nf(i).toString("hex"),Nf(s).toString("hex"),o,c,a)}address(){const{address:t}=Se.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves()});if(!t)throw new Error(_t.htlcAddressGenerationFailed);return t}id(){return this.address()}async _buildRawTx(t,r){const n=new Se.Transaction;n.version=2;const s=this.address(),i=await this.signer.getProvider();let o=[];if(this.utxoHashes&&this.utxoHashes.length>0)for(const l of this.utxoHashes){const u=await i.getTransaction(l);for(let f=0;f<u.vout.length;f++){const p=u.vout[f];p.scriptpubkey_address===s&&o.push({txid:u.txid,vout:f,value:p.value,status:{confirmed:!1}})}}else o=await i.getUTXOs(s);const a=o.reduce((l,u)=>l+u.value,0);if(a===0)throw new Error(`${s} ${_t.notFunded}`);for(let l=0;l<o.length;l++)n.addInput(Buffer.from(o[l].txid,"hex").reverse(),o[l].vout);if(r!=null&&r.vSize){const l=await i.getFeeRates(),u=Math.ceil(l.hourFee*r.vSize),f=a-u;return n.addOutput(Se.address.toOutputScript(t,this.network),f),{tx:n,usedUtxos:o}}const c=(r==null?void 0:r.fee)??await i.suggestFee(s,a,li.MEDIUM);return n.addOutput(Se.address.toOutputScript(t,this.network),a-c),{tx:n,usedUtxos:o,fee:c,balance:a}}getOutputScript(){return Se.address.toOutputScript(this.address(),this.network)}async init(t){return t??(t=await(await this.signer.getProvider()).suggestFee(await this.signer.getAddress(),this.initiateAmount,li.MEDIUM)),await this.signer.send(this.address(),this.initiateAmount,t)}async generateRedeemSACP(t,r,n){const{tx:s,usedUtxos:i}=await this._buildRawTx(r,{fee:n}),o=this.getOutputScript(),a=Se.Transaction.SIGHASH_SINGLE|Se.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(1),l=i.map(f=>f.value),u=Hi(o,i.length);for(let f=0;f<s.ins.length;f++){const p=s.hashForWitnessV1(f,u,l,a,c),d=await this.signer.signSchnorr(p);s.setWitness(f,[Zi(d,a),Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return s.toHex()}async generateInstantRefundSACP(t){const r=this.getOutputScript(),{tx:n,usedUtxos:s,fee:i}=await this._buildRawTx(t,{fee:0});n.outs=[];const o=Math.max(...s.map(f=>f.value));s.forEach(({value:f})=>{n.addOutput(r,f-(f===o?i??0:0))});const a=Se.Transaction.SIGHASH_SINGLE|Se.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(2),l=s.map(f=>f.value),u=Hi(r,s.length);for(let f=0;f<n.ins.length;f++){const p=n.hashForWitnessV1(f,u,l,a,c),d=await this.signer.signSchnorr(p);n.setWitness(f,[Zi(d,a),Zi(d,a),this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return n.toHex()}async generateInstantRefundSACPWithHash(t){const r=[],n=Se.Transaction.SIGHASH_SINGLE|Se.Transaction.SIGHASH_ANYONECANPAY;for(let s=0;s<t.length;s++){const i=Buffer.from(t[s],"hex"),o=await this.signer.signSchnorr(i);r.push(Zi(o,n).toString("hex"))}return r}async instantRefund(t,r){Xs(t.length>0,_t.noCounterpartySigs);const{tx:n,usedUtxos:s}=await this._buildRawTx(await this.signer.getAddress(),{fee:r});for(const f of s)if(!t.find(p=>p.utxo===f.txid))throw new Error(_t.counterPartySigNotFound(f.txid));const i=this.getOutputScript(),o=Se.Transaction.SIGHASH_DEFAULT,a=this.leafHash(2),c=s.map(f=>f.value),l=Hi(i,s.length);for(let f=0;f<n.ins.length;f++){const p=n.hashForWitnessV1(f,l,c,o,a);if(!ar.verifySchnorr(p,Buffer.from(this.redeemerPubkey,"hex"),Buffer.from(t[f].sig,"hex")))throw new Error(_t.invalidCounterpartySigForUTXO(t[f].utxo));const d=await this.signer.signSchnorr(p),m=Buffer.from(n.ins[f].hash).reverse().toString("hex"),g=t.find(w=>w.utxo===m);if(!g)throw new Error(_t.counterPartySigNotFound(m));n.setWitness(f,[Buffer.from(g.sig,"hex"),d,this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async redeem(t,r){const n=await this.getRedeemHex(t,r);return await(await this.signer.getProvider()).broadcast(n)}async getRedeemHex(t,r){Xs(Se.crypto.sha256(Buffer.from(t,"hex")).toString("hex")===this.secretHash,_t.secretMismatch);const n=r??await this.signer.getAddress(),{tx:s,usedUtxos:i}=await this._buildRawTx(n,{fee:0}),o=this.leafHash(1),a=i.map(f=>f.value),c=Hi(this.getOutputScript(),i.length),l=Se.Transaction.SIGHASH_DEFAULT;for(let f=0;f<s.ins.length;f++){const p=s.hashForWitnessV1(f,c,a,l,o),d=await this.signer.signSchnorr(p);s.setWitness(f,[d,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}const{tx:u}=await this._buildRawTx(n,{vSize:s.virtualSize()});for(let f=0;f<u.ins.length;f++){const p=u.hashForWitnessV1(f,c,a,l,o),d=await this.signer.signSchnorr(p);u.setWitness(f,[d,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return u.toHex()}async refund(t,r){const{tx:n,usedUtxos:s}=await this._buildRawTx(t??await this.signer.getAddress(),{fee:r}),[i,o]=await this.canRefund(s);if(!i)throw new Error(_t.htlcNotExpired(o));const a=this.leafHash(0),c=s.map(p=>p.value),l=Hi(this.getOutputScript(),s.length),u=Se.Transaction.SIGHASH_DEFAULT;for(let p=0;p<n.ins.length;p++){n.ins[p].sequence=this.expiry;const d=n.hashForWitnessV1(p,l,c,u,a),m=await this.signer.signSchnorr(d);n.setWitness(p,[m,this.refundLeaf(),this.generateControlBlockFor(0)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async canRefund(t){const n=await(await this.signer.getProvider()).getLatestTip();for(const s of t){let i=0;if(s.status.confirmed&&s.status.block_height+this.expiry>n?i=s.status.block_height+this.expiry-n+1:s.status.confirmed||(i=this.expiry+1),i>0)return[!1,i]}return[!0,0]}generateControlBlockFor(t){let r;switch(t){case 1:r=this.redeemLeaf();break;case 0:r=this.refundLeaf();break;case 2:r=this.instantRefundLeaf();break;default:throw new Error(_t.invalidLeaf)}const n=Se.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves(),redeem:{output:r,redeemVersion:Pa}});if(!n.witness)throw new Error(_t.controlBlockGenerationFailed);return n.witness[n.witness.length-1]}leafHash(t){let r=this.redeemLeaf();return t===0&&(r=this.refundLeaf()),t===2&&(r=this.instantRefundLeaf()),Se.crypto.taggedHash("TapLeaf",n_(r))}refundLeaf(){return Se.script.fromASM(`
|
|
54
54
|
${Se.script.number.encode(this.expiry).toString("hex")}
|
|
55
55
|
OP_CHECKSEQUENCEVERIFY
|
|
56
56
|
OP_DROP
|
|
@@ -69,7 +69,7 @@ ${lE(d)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessa
|
|
|
69
69
|
OP_CHECKSIGADD
|
|
70
70
|
OP_2
|
|
71
71
|
OP_NUMEQUAL
|
|
72
|
-
`.trim().replace(/\s+/g," "))}leaves(){return[{version:Pa,output:this.redeemLeaf()},[{version:Pa,output:this.refundLeaf()},{version:Pa,output:this.instantRefundLeaf()}]]}generateMerkleProofFor(t){const r=this.leafHash(1),n=this.leafHash(2),s=this.leafHash(0);switch(t){case 1:{const i=i_(s,n);return[Se.crypto.taggedHash("TapBranch",Buffer.concat(i))]}case 0:return[n,r];case 2:return[s,r];default:throw new Error(_t.invalidLeaf)}}}function Hi(e,t){const r=[];for(let n=0;n<t;n++)r.push(e);return r}class wT{constructor(){this.cache={}}set(t,r,n,s){const i={txHash:n,timeStamp:Date.now(),btcRedeemUTXO:s};this.cache[`${r}_${t.create_order.create_id}`]=i}get(t,r){return this.cache[`${r}_${t.create_order.create_id}`]||null}remove(t,r){delete this.cache[`${r}_${t.create_order.create_id}`]}}class vT{constructor(){this.cache={}}set(t,r){this.cache[t]=r}get(t){return this.cache[t]||null}}class qb{constructor(t,r){this.url=new v.Url(t).endpoint("blocknumbers").endpoint(r)}async fetchBlockNumbers(){try{const t=await v.Fetcher.get(this.url);return v.Ok(t)}catch(t){return v.Err("Failed to fetch block numbers",t)}}}class Vb{constructor(t){this.quoteUrl=new v.Url(t)}async getQuoteFromAssets({fromAsset:t,toAsset:r,amount:n,isExactOut:s=!1,options:i}){const o=Uf(t.chain,t.atomicSwapAddress,r.chain,r.atomicSwapAddress);return this.getQuote(o,n,s,i)}async getQuote(t,r,n=!1,s){try{const i={order_pair:t,amount:r.toString(),exact_out:n.toString(),...(s==null?void 0:s.affiliateFee)!==void 0&&{affiliate_fee:s.affiliateFee.toString()}},o=this.quoteUrl.endpoint("/").addSearchParams(i),a=await v.Fetcher.get(o,{retryCount:0,...s==null?void 0:s.request});return a.error?v.Err(a.error):a.result?v.Ok(a.result):v.Err("GetQuote: Unexpected error, result is undefined")}catch(i){return v.Err("GetQuote:",String(i))}}async getStrategies(){try{const t=await v.Fetcher.get(this.quoteUrl.endpoint("/strategies"));if(t.error)return v.Err(t.error);if(!t.result)return v.Err("GetStrategies: Unexpected error, result is undefined");const r={};for(const n of Object.values(t.result)){const s=Uf(n.source_chain,n.source_asset.asset,n.dest_chain,n.dest_asset.asset);r[s]={id:n.id,minAmount:n.min_amount,maxAmount:n.max_amount,fee:n.fee,fixed_fee:Number(n.fixed_fee)}}return v.Ok(r)}catch(t){return v.Err("GetStrategies:",String(t))}}}class Do extends v.EventBroker{get isInitialized(){return!!this.digestKey}constructor(t,r){super(),this.digestKey=t,this.walletClient=r}static fromDigestKey(t){return new Do(v.trim0x(t))}static fromWalletClient(t){return new Do(void 0,t)}async initialize(){if(this.digestKey)return v.Ok("Already initialized");const t=await this.deriveDigestKeyFromWalletClient();return t.error?v.Err(t.error):(this.emit("initialized",!0),v.Ok("Initialized"))}async deriveDigestKeyFromWalletClient(){if(!this.walletClient)return v.Err("No walletClient found");if(!this.walletClient.account)return v.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=v.trim0x(Ki(t)),this.emit("initialized",!0),v.Ok(this.digestKey)}catch(t){return v.Err("Failed to initialize: "+t)}}async getDigestKey(){if(!this.digestKey&&!this.walletClient)return v.Err("No private key or wallet client found");if(!this.digestKey&&this.walletClient){const t=await this.deriveDigestKeyFromWalletClient();if(t.error)return v.Err(t.error)}return this.digestKey?v.Ok(this.digestKey):v.Err("No private key found")}async generateSecret(t){const r=await this.signMessage(t);if(!r.ok)return v.Err(r.error);const n=Ki(v.with0x(r.val)),s=Ki(n);return v.Ok({secret:n,secretHash:s})}async signMessage(t){if(!this.digestKey){const l=await this.getDigestKey();if(!l.ok)return v.Err(l.error);this.digestKey=l.val}const r=Ua.ECPairFactory(ar),n="Garden.fi"+t.toString(),s=Buffer.from(n,"utf8"),i=Ki(s),o=Buffer.from(v.trim0x(this.digestKey),"hex");if(o.length!==32)return v.Err("Invalid private key length. Expected 32 bytes.");const c=r.fromPrivateKey(o).sign(Buffer.from(v.trim0x(i),"hex"));return v.Ok(c.toString("hex"))}}const Jp=[{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"}],ET={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},AT={block:FE({format(e){var r;return{transactions:(r=e.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const s=_c(n);return s.typeHex==="0x7e"&&(s.isSystemTx=n.isSystemTx,s.mint=n.mint?ot(n.mint):void 0,s.sourceHash=n.sourceHash,s.type="deposit"),s}),stateRoot:e.stateRoot}}}),transaction:UE({format(e){const t={};return e.type==="0x7e"&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?ot(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:q6({format(e){return{l1GasPrice:e.l1GasPrice?ot(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?ot(e.l1GasUsed):null,l1Fee:e.l1Fee?ot(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null}}})};function xT(e,t){return kT(e)?_T(e):qA(e,t)}const ST={transaction:xT};function _T(e){TT(e);const{sourceHash:t,data:r,from:n,gas:s,isSystemTx:i,mint:o,to:a,value:c}=e,l=[t,n,a??"0x",o?mt(o):"0x",c?mt(c):"0x",s?mt(s):"0x",i?"0x1":"0x",r??"0x"];return Tr(["0x7e",Qn(l)])}function kT(e){return e.type==="deposit"||typeof e.sourceHash<"u"}function TT(e){const{from:t,to:r}=e;if(t&&!st(t))throw new Bt({address:t});if(r&&!st(r))throw new Bt({address:r})}const xi={blockTime:2e3,contracts:ET,formatters:AT,serializers:ST},IT=bt({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}}}),PT=bt({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}),zi=1,Gb=bt({...xi,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:{...xi.contracts,disputeGameFactory:{[zi]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[zi]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[zi]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[zi]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:zi});({...Gb});const qi=11155111,Wb=bt({...xi,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:{...xi.contracts,disputeGameFactory:{[qi]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[qi]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[qi]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[qi]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:qi});({...Wb});const OT=bt({id:80094,name:"Berachain",nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},ensRegistry:{address:"0x5b22280886a2f5e09a49bea7e320eab0e5320e28",blockCreated:877007},ensUniversalResolver:{address:"0xddfb18888a9466688235887dec2a10c4f5effee9",blockCreated:877008}},rpcUrls:{default:{http:["https://rpc.berachain.com"]}},blockExplorers:{default:{name:"Berascan",url:"https://berascan.com"}},ensTlds:[".bera"],testnet:!1}),BT=bt({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}),CT=bt({id:56,name:"BNB Smart Chain",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}}}),RT=bt({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}),$T=bt({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}),NT=1,UT=bt({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:NT}),MT=bt({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xce01f8eee7E479C928F8919abD53E553a36CeF67",blockCreated:19258213},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),FT=bt({id:10143,name:"Monad Testnet",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}),jT=bt({id:11155111,name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.drpc.org"]}},blockExplorers:{default:{name:"Etherscan",url:"https://sepolia.etherscan.io",apiUrl:"https://api-sepolia.etherscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:751532},ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xc8Af999e38273D658BE1b921b88A9Ddf005769cC",blockCreated:5317080}},testnet:!0}),Oa=1,LT=bt({...xi,id:130,name:"Unichain",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.unichain.org/"]}},blockExplorers:{default:{name:"Uniscan",url:"https://uniscan.xyz",apiUrl:"https://api.uniscan.xyz/api"}},contracts:{...xi.contracts,multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:0},disputeGameFactory:{[Oa]:{address:"0x2F12d621a16e2d3285929C9996f478508951dFe4"}},portal:{[Oa]:{address:"0x0bd48f6B86a26D3a217d0Fa6FfE2B491B956A7a2"}},l1StandardBridge:{[Oa]:{address:"0x81014F44b0a345033bB2b3B21C7a1A308B35fEeA"}}},sourceId:Oa}),DT={...jT,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},Kb={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/"]}}},Xb={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"]}}},Yb={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"]}}},uh={ethereum:MT,arbitrum:IT,ethereum_sepolia:DT,arbitrum_sepolia:PT,ethereum_localnet:be.EthereumLocalnet,arbitrum_localnet:be.ArbitrumLocalnet,base_sepolia:Wb,base:Gb,bera_testnet:BT,citrea_testnet:$T,bera:OT,monad_testnet:FT,hyperliquid_testnet:Xb,hyperliquid:Yb,unichain:LT,corn:UT,botanix:Kb,bnbchain:CT,bnbchain_testnet:RT},Zb=async(e,t)=>{var s,i,o;const r=uh[e],n=await t.getChainId();if(r)try{if(r.id===n)return v.Ok({message:"Already on the network",walletClient:t});await t.switchChain({id:r.id});const a=ku({account:t.account,chain:r,transport:fp(t.transport)});return v.Ok({message:"Switched chain",walletClient:a})}catch(a){if(HT(a))if(a.code===4902||a.code===-32603)try{await t.addChain({chain:r});const c=ku({account:t.account,chain:r,transport:fp(t.transport)});return v.Ok({message:"Added network",walletClient:c})}catch{return v.Err("Failed to add network")}else if((i=(s=a.body)==null?void 0:s.method)!=null&&i.includes("wallet_switchEthereumChain")||(o=a.message)!=null&&o.includes("wallet_switchEthereumChain")){const c=ku({account:t.account,chain:r,transport:mg()});return v.Ok({message:"Added network",walletClient:c})}else return v.Err("Failed to switch network");else return v.Err("Failed to switch network")}else return v.Err("Chain not supported")},HT=e=>typeof e=="object"&&e!=null&&("code"in e||"message"in e||"body"in e),zT=[{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 Jb{constructor(t,r,n){this.url=new v.Url("/relayer",t),this.auth=n,this.wallet=r}get htlcActorAddress(){if(!this.wallet.account)throw new Error("No account found");return this.wallet.account.address}async initiate(t){if(!this.wallet.account)return v.Err("No account found");if(this.wallet.account.address.toLowerCase()!==t.source_swap.initiator.toLowerCase())return v.Err("Account address and order initiator mismatch");if(!be.isEVM(t.source_swap.chain))return v.Err("Source chain is not an EVM chain");const r=await Zb(t.source_swap.chain,this.wallet);if(!r.ok)return v.Err(r.error);if(this.wallet=r.val.walletClient,!this.wallet.account)return v.Err("No account found");const{create_order:n,source_swap:s}=t;if(!s.amount||!s.redeemer||!n.timelock||!n.secret_hash)return v.Err("Invalid order");const i=v.with0x(n.secret_hash),o=BigInt(n.timelock),a=v.with0x(s.redeemer),c=BigInt(s.amount),l=await this.getTokenAddress(t.source_swap.asset);return l.ok?be.isEvmNativeToken(t.source_swap.chain,l.val)?this._initiateOnNativeHTLC(i,o,c,a,t.source_swap.asset):this._initiateOnErc20HTLC(i,o,c,a,t.source_swap.asset,l.val,n.create_id):v.Err(l.error)}async getTokenAddress(t){try{const n=await gu({address:v.with0x(t),abi:Jp,client:this.wallet}).read.token();return v.Ok(n)}catch(r){return v.Err("Failed to get token address",String(r))}}async _initiateOnNativeHTLC(t,r,n,s,i){if(!this.wallet.account)return v.Err("No account found");try{const a=await gu({address:v.with0x(i),abi:zT,client:this.wallet}).write.initiate([s,r,n,t],{account:this.wallet.account,chain:this.wallet.chain,value:n});return v.Ok(a)}catch(o){return v.Err("Failed to initiate on native HTLC",String(o))}}async _initiateOnErc20HTLC(t,r,n,s,i,o,a){if(!this.wallet.account)return v.Err("No account found");try{const c=await this.auth.getAuthHeaders();if(!c.ok)return v.Err(c.error);const l=gu({address:v.with0x(i),abi:Jp,client:this.wallet}),u=await v.checkAllowanceAndApprove(Number(n),o,i,this.wallet);if(!u.ok)return v.Err(u.error);const f=await l.read.eip712Domain(),p=await this.wallet.signTypedData({account:this.wallet.account,domain:{name:f[1],version:f[2],chainId:Number(f[3]),verifyingContract:f[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:s,timelock:r,amount:n,secretHash:t}}),d={...c.val,"Content-Type":"application/json"},m=await v.Fetcher.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:a,signature:p,perform_on:"Source"}),headers:d});if(m.error)return v.Err(m.error);const g=await v.waitForTransactionReceipt(this.wallet,m.result);return g.val&&g.val.status==="success"?v.Ok(m.result?m.result:"Initiate hash not found"):v.Err("Init failed: Transaction receipt not successful")}catch(c){return console.log("init error :",c),v.Err(String(c))}}async redeem(t,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return v.Err(n.error);const s=await v.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:v.trim0x(r),perform_on:"Destination"}),headers:{...n.val,"Content-Type":"application/json"}});if(s.error)return v.Err(s.error);const i=uh[t.destination_swap.chain],a=await LS({chain:i,transport:mg()}).waitForTransactionReceipt({hash:s.result,confirmations:1,timeout:3e5});return a&&a.status==="success"?v.Ok(s.result?s.result:"Redeem hash not found"):v.Err("Redeem failed: Transaction receipt not successful")}catch(n){return v.Err(String(n))}}async refund(){return v.Err("Refund not supported")}}const Qb=[{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"}]}],ew=async(e,t,r,n,s)=>{try{const i=await ao(e.address,t,r,s);if(!i.ok)return v.Err(i.error);if(i.val>=n)return v.Ok("Allowance already approved");const a=it.cairo.uint256(BigInt(n)),c=await e.execute([{contractAddress:v.with0x(t),entrypoint:"approve",calldata:[v.with0x(r),a.low,a.high]}]);await s.waitForTransaction(c.transaction_hash,{retryInterval:3e3,successStates:[it.TransactionExecutionStatus.SUCCEEDED]}),await v.sleep(2e3);for(let l=0;l<20;l++){const u=await ao(e.address,t,r,s);if(!u.ok)return v.Err(u.error);if(u.val>=n)return v.Ok(c.transaction_hash);await v.sleep(2e3);let f=0n;for(let p=0;p<20;p++){const d=await ao(e.address,t,r,s);if(!d.ok)return v.Err(d.error);if(f=d.val,f>=n)break;await v.sleep(2e3)}return f<n?v.Err("Allowance not approved"):v.Ok(c.transaction_hash)}return v.Err("Allowance not approved after transaction.")}catch(i){return v.Err(`Failed to check or approve allowance: ${i instanceof Error?i.message:String(i)}`)}},ao=async(e,t,r,n)=>{try{const i=await new it.Contract(Qb,v.with0x(t),n).call("allowance",[v.with0x(e),v.with0x(r)]);return v.Ok(BigInt((i==null?void 0:i.toString())||"0"))}catch(s){return v.Err(`Failed to check allowance: ${s instanceof Error?s.message:String(s)}`)}},tw=async(e,t,r,n,s)=>{const i=await ao(e,t,r,n);return i.ok?v.Ok(i.val>=s):v.Err(i.error)},rw=[{name:"HTLC",type:"impl",interface_name:"starknet_htlc::interface::IHTLC"},{name:"core::integer::u256",type:"struct",members:[{name:"low",type:"core::integer::u128"},{name:"high",type:"core::integer::u128"}]},{name:"starknet_htlc::interface::IHTLC",type:"interface",items:[{name:"token",type:"function",inputs:[],outputs:[{type:"core::starknet::contract_address::ContractAddress"}],state_mutability:"view"},{name:"initiate",type:"function",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::u32; 8]"}],outputs:[],state_mutability:"external"},{name:"initiate_on_behalf",type:"function",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::u32; 8]"}],outputs:[],state_mutability:"external"},{name:"initiate_with_signature",type:"function",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::u32; 8]"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"},{name:"redeem",type:"function",inputs:[{name:"order_id",type:"core::felt252"},{name:"secret",type:"core::array::Array::<core::integer::u32>"}],outputs:[],state_mutability:"external"},{name:"refund",type:"function",inputs:[{name:"order_id",type:"core::felt252"}],outputs:[],state_mutability:"external"},{name:"instant_refund",type:"function",inputs:[{name:"order_id",type:"core::felt252"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"}]},{name:"constructor",type:"constructor",inputs:[{name:"token",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"starknet_htlc::interface::events::Initiated",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"},{kind:"data",name:"secret_hash",type:"[core::integer::u32; 8]"},{kind:"data",name:"amount",type:"core::integer::u256"}]},{kind:"struct",name:"starknet_htlc::interface::events::Redeemed",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"},{kind:"data",name:"secret_hash",type:"[core::integer::u32; 8]"},{kind:"data",name:"secret",type:"core::array::Array::<core::integer::u32>"}]},{kind:"struct",name:"starknet_htlc::interface::events::Refunded",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"}]},{kind:"enum",name:"starknet_htlc::htlc::HTLC::Event",type:"event",variants:[{kind:"nested",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"}]}],qT={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*"}]};class nw{constructor(t,r,n,s){this.url=t instanceof v.Url?t:new v.Url(t),this.account=r,this.starknetProvider=new it.RpcProvider({nodeUrl:s||Mo[n].nodeUrl}),this.chainId=Mo[n].chainId}get htlcActorAddress(){if(!this.account.address)throw new Error("No account found");return this.account.address}async initiate(t){if(!this.account.address)return v.Err("No account address");const{create_order:r,source_swap:n}=t;if(!n.amount||!n.redeemer||!r.timelock||!r.secret_hash)return v.Err("Invalid order");try{const s=new it.Contract(rw,t.source_swap.asset,this.account),i=await(s==null?void 0:s.token()),o=it.num.toHex(i),a=await tw(this.account.address,o,n.asset,this.starknetProvider,BigInt(n.amount));return a.error?v.Err(a.error):a.val?this.initiateRelay(t):this.approveAndInitiate(o,t)}catch(s){return v.Err(String(s))}}async approveAndInitiate(t,r){const{create_order:n,source_swap:s}=r,{redeemer:i,amount:o}=s,{secret_hash:a,timelock:c}=n;if(!a)return v.Err("Invalid order: secret_hash is undefined");const l=s.asset;try{const u=it.cairo.uint256(BigInt(o)),f={contractAddress:v.with0x(t),entrypoint:"approve",calldata:[l,u.low,u.high]},p=it.cairo.uint256(o),d={contractAddress:v.with0x(l),entrypoint:"initiate",calldata:[i,c.toString(),p.low.toString(),p.high.toString(),...v.hexToU32Array(a)]},m=await this.account.execute([f,d]);return await this.starknetProvider.waitForTransaction(m.transaction_hash,{retryInterval:2e3,successStates:[it.TransactionExecutionStatus.SUCCEEDED]}),v.Ok(m.transaction_hash)}catch(u){return v.Err(`Failed to approve and initiate: ${String(u)}`)}}async initiateRelay(t){const{create_order:r,source_swap:n}=t,{redeemer:s,amount:i}=n;if(!r.secret_hash)return v.Err("Invalid order: secret_hash is undefined");const o=v.with0x(r.secret_hash),c={domain:{name:"HTLC",version:it.shortString.encodeShortString("1"),chainId:this.chainId,revision:it.TypedDataRevision.ACTIVE},primaryType:"Initiate",types:qT,message:{redeemer:s,amount:it.cairo.uint256(i),timelock:r.timelock,secretHash:v.hexToU32Array(o)}};try{const l=await this.account.signMessage(c),u=l_(l);if(u.error)return v.Err(u.error);const f=await v.Fetcher.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:r.create_id,signature:u.val,perform_on:"Source"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return f.error?v.Err(f.error):f.result?v.Ok(f.result):v.Err("Init: No result found")}catch(l){return v.Err(`Failed to initiate relayer: ${String(l)}`)}}async redeem(t,r){try{const n=await v.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:r,perform_on:"Destination"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return n.error?v.Err(n.error):n.result?v.Ok(n.result):v.Err("Redeem: No result found")}catch(n){return v.Err(String(n))}}async refund(){return v.Err("Refund is taken care of by the relayer")}}const VT=e=>e.map(t=>t),GT=e=>{if(e===Ht.Testnet)return WT;if(e===Ht.Mainnet)return KT;throw new Error("Invalid network")},WT=["https://mempool.space/testnet4/api"],KT=["https://mempool.space/api","https://blockstream.info/api"],as={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}`},Ji={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"},Qp=e=>e.sort((t,r)=>t.status.confirmed!=r.status.confirmed?t.status.confirmed?-1:1:r.value-t.value);class sw{constructor(t,r){this.cacheTimeout=2e3,this.utxosCache=new Map,this.APIs=r?VT([r]):GT(t),this.network=t}async getTxIndex(t,r){const n=this.APIs.map(i=>`${i}/tx/${t}`),{vout:s}=await v.Fetcher.getWithFallback(n);for(let i=0;i<s.length;i++)if(s[i].scriptpubkey_address===r)return i;throw new Error("failed to get tx index")}async broadcast(t){if(!/^[0-9a-fA-F]+$/.test(t))throw new Error("invalid tx hex");for(let r=0;r<5;r++)try{return v.Fetcher.postWithFallback(this.APIs.map(n=>`${n}/tx`),{body:t})}catch(n){if(r===4)throw n;await new Promise(s=>setTimeout(s,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 ey(n.utxos,r);const s=await v.Fetcher.getWithFallback(this.APIs.map(i=>`${i}/address/${t}/utxo`),{signal:AbortSignal.timeout(5e3)});return this.utxosCache.set(t,{timestamp:Date.now(),utxos:s}),ey(s,r)}async getTransactionHex(t){return v.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${t}/hex`))}async getTransaction(t){return v.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===Ht.Regtest)return{fastestFee:8,halfHourFee:7,hourFee:6,economyFee:4,minimumFee:2};let t="";this.network===Ht.Testnet&&(t="testnet4/");const r=`https://mempool.space/${t}api/v1/fees/recommended`,n=`https://blockstream.info/${t}api/fee-estimates`,s=await v.Fetcher.getWithFallback([r,n],{signal:AbortSignal.timeout(5e3)});return"fastestFee"in s?s.fastestFee===1?{fastestFee:2,halfHourFee:2,hourFee:2,economyFee:2,minimumFee:2}:s:{fastestFee:s[1],halfHourFee:s[5],hourFee:s[10],economyFee:s[20],minimumFee:s[25]}}async getTransactions(t,r){const n=await v.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/address/${t}/txs`));if(r===Da.ALL)return n;if(r===Da.IN)return n.filter(s=>s.vout.find(i=>i.scriptpubkey_address===t));if(r===Da.OUT)return n.filter(s=>s.vin.find(i=>i.prevout.scriptpubkey_address===t));throw new Error("failed to get transactions: invalid bitcoin tx type")}getNetwork(){return this.network}async getLatestTip(){return v.Fetcher.getWithFallback(this.APIs.map(t=>`${t}/blocks/tip/height`))}async suggestFee(t,r,n){const i=(await this.getUTXOs(t,r)).length,o=2,a=await this.getFeeRates();return Math.floor(a[r_[n]]*1.05)*(i*70+o*31+10)}async getTransactionTimes(t){const r=t.map(s=>`txId[]=${s}`).join("&");return(await v.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/v1/transaction-times?${r}`))).map(s=>s*1e3)}}const ey=(e,t)=>{if(Array.isArray(e)){if(t){const r=e.reduce((i,o)=>i+o.value,0);if(r<t)throw new Error(as.INSUFFICIENT_FUNDS(r,t));let n=BigInt(0);e.sort((i,o)=>o.value-i.value);const s=[];for(const i of e)if(n+=BigInt(i.value),s.push(i),n>=t)break;return Qp(s)}return Qp(e)}return[]},Vi={p2wpkh:"p2wpkh","p2wpkh-p2sh":"p2wpkh-p2sh"},Ga={ALL:pe.Transaction.SIGHASH_ALL,NONE:pe.Transaction.SIGHASH_NONE,SINGLE:pe.Transaction.SIGHASH_SINGLE,ALL_ANYONECANPAY:pe.Transaction.SIGHASH_ALL|pe.Transaction.SIGHASH_ANYONECANPAY,NONE_ANYONECANPAY:pe.Transaction.SIGHASH_NONE|pe.Transaction.SIGHASH_ANYONECANPAY,SINGLE_ANYONECANPAY:pe.Transaction.SIGHASH_SINGLE|pe.Transaction.SIGHASH_ANYONECANPAY};class As{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(" "),s=await Oh.mixed().oneOf(["segwitV0","segwitV1","p2shSignature"]).required().validate(r),i=await Oh.mixed().oneOf(Object.values(Ga)).required().validate(parseInt(n));return new As(s,i)}}const XT=(e,t,r=!1)=>{const n=o=>{try{o=pe.address.fromBech32(o).data.toString("hex")}catch(a){if(Ff(a))(a.message.includes("Mixed-case string")||a.message.includes("too short"))&&(o=pe.address.fromBase58Check(o).hash.toString("hex"));else throw new Error(String(a))}return o},s=pe.script.fromASM(`
|
|
72
|
+
`.trim().replace(/\s+/g," "))}leaves(){return[{version:Pa,output:this.redeemLeaf()},[{version:Pa,output:this.refundLeaf()},{version:Pa,output:this.instantRefundLeaf()}]]}generateMerkleProofFor(t){const r=this.leafHash(1),n=this.leafHash(2),s=this.leafHash(0);switch(t){case 1:{const i=i_(s,n);return[Se.crypto.taggedHash("TapBranch",Buffer.concat(i))]}case 0:return[n,r];case 2:return[s,r];default:throw new Error(_t.invalidLeaf)}}}function Hi(e,t){const r=[];for(let n=0;n<t;n++)r.push(e);return r}class wT{constructor(){this.cache={}}set(t,r,n,s){const i={txHash:n,timeStamp:Date.now(),btcRedeemUTXO:s};this.cache[`${r}_${t.create_order.create_id}`]=i}get(t,r){return this.cache[`${r}_${t.create_order.create_id}`]||null}remove(t,r){delete this.cache[`${r}_${t.create_order.create_id}`]}}class vT{constructor(){this.cache={}}set(t,r){this.cache[t]=r}get(t){return this.cache[t]||null}}class qb{constructor(t,r){this.url=new v.Url(t).endpoint("blocknumbers").endpoint(r)}async fetchBlockNumbers(){try{const t=await v.Fetcher.get(this.url);return v.Ok(t)}catch(t){return v.Err("Failed to fetch block numbers",t)}}}class Vb{constructor(t){this.quoteUrl=new v.Url(t)}async getQuoteFromAssets({fromAsset:t,toAsset:r,amount:n,isExactOut:s=!1,options:i}){const o=Uf(t.chain,t.atomicSwapAddress,r.chain,r.atomicSwapAddress);return this.getQuote(o,n,s,i)}async getQuote(t,r,n=!1,s){try{const i={order_pair:t,amount:r.toString(),exact_out:n.toString(),...(s==null?void 0:s.affiliateFee)!==void 0&&{affiliate_fee:s.affiliateFee.toString()}},o=this.quoteUrl.endpoint("/").addSearchParams(i),a=await v.Fetcher.get(o,{retryCount:0,...s==null?void 0:s.request});return a.error?v.Err(a.error):a.result?v.Ok(a.result):v.Err("GetQuote: Unexpected error, result is undefined")}catch(i){return v.Err("GetQuote:",String(i))}}async getStrategies(){try{const t=await v.Fetcher.get(this.quoteUrl.endpoint("/strategies"));if(t.error)return v.Err(t.error);if(!t.result)return v.Err("GetStrategies: Unexpected error, result is undefined");const r={};for(const n of Object.values(t.result)){const s=Uf(n.source_chain,n.source_asset.asset,n.dest_chain,n.dest_asset.asset);r[s]={id:n.id,minAmount:n.min_amount,maxAmount:n.max_amount,fee:n.fee,fixed_fee:Number(n.fixed_fee)}}return v.Ok(r)}catch(t){return v.Err("GetStrategies:",String(t))}}}class Do extends v.EventBroker{get isInitialized(){return!!this.digestKey}constructor(t,r){super(),this.digestKey=t,this.walletClient=r}static fromDigestKey(t){return new Do(v.trim0x(t))}static fromWalletClient(t){return new Do(void 0,t)}async initialize(){if(this.digestKey)return v.Ok("Already initialized");const t=await this.deriveDigestKeyFromWalletClient();return t.error?v.Err(t.error):(this.emit("initialized",!0),v.Ok("Initialized"))}async deriveDigestKeyFromWalletClient(){if(!this.walletClient)return v.Err("No walletClient found");if(!this.walletClient.account)return v.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=v.trim0x(Ki(t)),this.emit("initialized",!0),v.Ok(this.digestKey)}catch(t){return v.Err("Failed to initialize: "+t)}}async getDigestKey(){if(!this.digestKey&&!this.walletClient)return v.Err("No private key or wallet client found");if(!this.digestKey&&this.walletClient){const t=await this.deriveDigestKeyFromWalletClient();if(t.error)return v.Err(t.error)}return this.digestKey?v.Ok(this.digestKey):v.Err("No private key found")}async generateSecret(t){const r=await this.signMessage(t);if(!r.ok)return v.Err(r.error);const n=Ki(v.with0x(r.val)),s=Ki(n);return v.Ok({secret:n,secretHash:s})}async signMessage(t){if(!this.digestKey){const l=await this.getDigestKey();if(!l.ok)return v.Err(l.error);this.digestKey=l.val}const r=Ua.ECPairFactory(ar),n="Garden.fi"+t.toString(),s=Buffer.from(n,"utf8"),i=Ki(s),o=Buffer.from(v.trim0x(this.digestKey),"hex");if(o.length!==32)return v.Err("Invalid private key length. Expected 32 bytes.");const c=r.fromPrivateKey(o).sign(Buffer.from(v.trim0x(i),"hex"));return v.Ok(c.toString("hex"))}}const Jp=[{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"}],ET={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},AT={block:FE({format(e){var r;return{transactions:(r=e.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const s=_c(n);return s.typeHex==="0x7e"&&(s.isSystemTx=n.isSystemTx,s.mint=n.mint?ot(n.mint):void 0,s.sourceHash=n.sourceHash,s.type="deposit"),s}),stateRoot:e.stateRoot}}}),transaction:UE({format(e){const t={};return e.type==="0x7e"&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?ot(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:q6({format(e){return{l1GasPrice:e.l1GasPrice?ot(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?ot(e.l1GasUsed):null,l1Fee:e.l1Fee?ot(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null}}})};function xT(e,t){return kT(e)?_T(e):qA(e,t)}const ST={transaction:xT};function _T(e){TT(e);const{sourceHash:t,data:r,from:n,gas:s,isSystemTx:i,mint:o,to:a,value:c}=e,l=[t,n,a??"0x",o?gt(o):"0x",c?gt(c):"0x",s?gt(s):"0x",i?"0x1":"0x",r??"0x"];return Tr(["0x7e",Qn(l)])}function kT(e){return e.type==="deposit"||typeof e.sourceHash<"u"}function TT(e){const{from:t,to:r}=e;if(t&&!st(t))throw new Bt({address:t});if(r&&!st(r))throw new Bt({address:r})}const xi={blockTime:2e3,contracts:ET,formatters:AT,serializers:ST},IT=dt({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}}}),PT=dt({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}),zi=1,Gb=dt({...xi,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:{...xi.contracts,disputeGameFactory:{[zi]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[zi]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[zi]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[zi]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:zi});({...Gb});const qi=11155111,Wb=dt({...xi,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:{...xi.contracts,disputeGameFactory:{[qi]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[qi]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[qi]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[qi]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:qi});({...Wb});const OT=dt({id:80094,name:"Berachain",nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},ensRegistry:{address:"0x5b22280886a2f5e09a49bea7e320eab0e5320e28",blockCreated:877007},ensUniversalResolver:{address:"0xddfb18888a9466688235887dec2a10c4f5effee9",blockCreated:877008}},rpcUrls:{default:{http:["https://rpc.berachain.com"]}},blockExplorers:{default:{name:"Berascan",url:"https://berascan.com"}},ensTlds:[".bera"],testnet:!1}),BT=dt({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}),CT=dt({id:56,name:"BNB Smart Chain",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}}}),RT=dt({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}),$T=dt({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}),NT=dt({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}),UT=1,MT=dt({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:UT}),FT=dt({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xce01f8eee7E479C928F8919abD53E553a36CeF67",blockCreated:19258213},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),jT=dt({id:10143,name:"Monad Testnet",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}),LT=dt({id:11155111,name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.drpc.org"]}},blockExplorers:{default:{name:"Etherscan",url:"https://sepolia.etherscan.io",apiUrl:"https://api-sepolia.etherscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:751532},ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xc8Af999e38273D658BE1b921b88A9Ddf005769cC",blockCreated:5317080}},testnet:!0}),Oa=1,DT=dt({...xi,id:130,name:"Unichain",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.unichain.org/"]}},blockExplorers:{default:{name:"Uniscan",url:"https://uniscan.xyz",apiUrl:"https://api.uniscan.xyz/api"}},contracts:{...xi.contracts,multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:0},disputeGameFactory:{[Oa]:{address:"0x2F12d621a16e2d3285929C9996f478508951dFe4"}},portal:{[Oa]:{address:"0x0bd48f6B86a26D3a217d0Fa6FfE2B491B956A7a2"}},l1StandardBridge:{[Oa]:{address:"0x81014F44b0a345033bB2b3B21C7a1A308B35fEeA"}}},sourceId:Oa}),HT={...LT,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},Kb={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/"]}}},Xb={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"]}}},Yb={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"]}}},uh={ethereum:FT,arbitrum:IT,ethereum_sepolia:HT,arbitrum_sepolia:PT,ethereum_localnet:be.EthereumLocalnet,arbitrum_localnet:be.ArbitrumLocalnet,base_sepolia:Wb,base:Gb,bera_testnet:BT,citrea_testnet:$T,core:NT,bera:OT,monad_testnet:jT,hyperliquid_testnet:Xb,hyperliquid:Yb,unichain:DT,corn:MT,botanix:Kb,bnbchain:CT,bnbchain_testnet:RT},Zb=async(e,t)=>{var s,i,o;const r=uh[e],n=await t.getChainId();if(r)try{if(r.id===n)return v.Ok({message:"Already on the network",walletClient:t});await t.switchChain({id:r.id});const a=ku({account:t.account,chain:r,transport:fp(t.transport)});return v.Ok({message:"Switched chain",walletClient:a})}catch(a){if(zT(a))if(a.code===4902||a.code===-32603)try{await t.addChain({chain:r});const c=ku({account:t.account,chain:r,transport:fp(t.transport)});return v.Ok({message:"Added network",walletClient:c})}catch{return v.Err("Failed to add network")}else if((i=(s=a.body)==null?void 0:s.method)!=null&&i.includes("wallet_switchEthereumChain")||(o=a.message)!=null&&o.includes("wallet_switchEthereumChain")){const c=ku({account:t.account,chain:r,transport:mg()});return v.Ok({message:"Added network",walletClient:c})}else return v.Err("Failed to switch network");else return v.Err("Failed to switch network")}else return v.Err("Chain not supported")},zT=e=>typeof e=="object"&&e!=null&&("code"in e||"message"in e||"body"in e),qT=[{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 Jb{constructor(t,r,n){this.url=new v.Url("/relayer",t),this.auth=n,this.wallet=r}get htlcActorAddress(){if(!this.wallet.account)throw new Error("No account found");return this.wallet.account.address}async initiate(t){if(!this.wallet.account)return v.Err("No account found");if(this.wallet.account.address.toLowerCase()!==t.source_swap.initiator.toLowerCase())return v.Err("Account address and order initiator mismatch");if(!be.isEVM(t.source_swap.chain))return v.Err("Source chain is not an EVM chain");const r=await Zb(t.source_swap.chain,this.wallet);if(!r.ok)return v.Err(r.error);if(this.wallet=r.val.walletClient,!this.wallet.account)return v.Err("No account found");const{create_order:n,source_swap:s}=t;if(!s.amount||!s.redeemer||!n.timelock||!n.secret_hash)return v.Err("Invalid order");const i=v.with0x(n.secret_hash),o=BigInt(n.timelock),a=v.with0x(s.redeemer),c=BigInt(s.amount),l=await this.getTokenAddress(t.source_swap.asset);return l.ok?be.isEvmNativeToken(t.source_swap.chain,l.val)?this._initiateOnNativeHTLC(i,o,c,a,t.source_swap.asset):this._initiateOnErc20HTLC(i,o,c,a,t.source_swap.asset,l.val,n.create_id):v.Err(l.error)}async getTokenAddress(t){try{const n=await gu({address:v.with0x(t),abi:Jp,client:this.wallet}).read.token();return v.Ok(n)}catch(r){return v.Err("Failed to get token address",String(r))}}async _initiateOnNativeHTLC(t,r,n,s,i){if(!this.wallet.account)return v.Err("No account found");try{const a=await gu({address:v.with0x(i),abi:qT,client:this.wallet}).write.initiate([s,r,n,t],{account:this.wallet.account,chain:this.wallet.chain,value:n});return v.Ok(a)}catch(o){return v.Err("Failed to initiate on native HTLC",String(o))}}async _initiateOnErc20HTLC(t,r,n,s,i,o,a){if(!this.wallet.account)return v.Err("No account found");try{const c=await this.auth.getAuthHeaders();if(!c.ok)return v.Err(c.error);const l=gu({address:v.with0x(i),abi:Jp,client:this.wallet}),u=await v.checkAllowanceAndApprove(Number(n),o,i,this.wallet);if(!u.ok)return v.Err(u.error);const f=await l.read.eip712Domain(),p=await this.wallet.signTypedData({account:this.wallet.account,domain:{name:f[1],version:f[2],chainId:Number(f[3]),verifyingContract:f[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:s,timelock:r,amount:n,secretHash:t}}),d={...c.val,"Content-Type":"application/json"},m=await v.Fetcher.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:a,signature:p,perform_on:"Source"}),headers:d});if(m.error)return v.Err(m.error);const g=await v.waitForTransactionReceipt(this.wallet,m.result);return g.val&&g.val.status==="success"?v.Ok(m.result?m.result:"Initiate hash not found"):v.Err("Init failed: Transaction receipt not successful")}catch(c){return console.log("init error :",c),v.Err(String(c))}}async redeem(t,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return v.Err(n.error);const s=await v.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:v.trim0x(r),perform_on:"Destination"}),headers:{...n.val,"Content-Type":"application/json"}});if(s.error)return v.Err(s.error);const i=uh[t.destination_swap.chain],a=await LS({chain:i,transport:mg()}).waitForTransactionReceipt({hash:s.result,confirmations:1,timeout:3e5});return a&&a.status==="success"?v.Ok(s.result?s.result:"Redeem hash not found"):v.Err("Redeem failed: Transaction receipt not successful")}catch(n){return v.Err(String(n))}}async refund(){return v.Err("Refund not supported")}}const Qb=[{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"}]}],ew=async(e,t,r,n,s)=>{try{const i=await ao(e.address,t,r,s);if(!i.ok)return v.Err(i.error);if(i.val>=n)return v.Ok("Allowance already approved");const a=it.cairo.uint256(BigInt(n)),c=await e.execute([{contractAddress:v.with0x(t),entrypoint:"approve",calldata:[v.with0x(r),a.low,a.high]}]);await s.waitForTransaction(c.transaction_hash,{retryInterval:3e3,successStates:[it.TransactionExecutionStatus.SUCCEEDED]}),await v.sleep(2e3);for(let l=0;l<20;l++){const u=await ao(e.address,t,r,s);if(!u.ok)return v.Err(u.error);if(u.val>=n)return v.Ok(c.transaction_hash);await v.sleep(2e3);let f=0n;for(let p=0;p<20;p++){const d=await ao(e.address,t,r,s);if(!d.ok)return v.Err(d.error);if(f=d.val,f>=n)break;await v.sleep(2e3)}return f<n?v.Err("Allowance not approved"):v.Ok(c.transaction_hash)}return v.Err("Allowance not approved after transaction.")}catch(i){return v.Err(`Failed to check or approve allowance: ${i instanceof Error?i.message:String(i)}`)}},ao=async(e,t,r,n)=>{try{const i=await new it.Contract(Qb,v.with0x(t),n).call("allowance",[v.with0x(e),v.with0x(r)]);return v.Ok(BigInt((i==null?void 0:i.toString())||"0"))}catch(s){return v.Err(`Failed to check allowance: ${s instanceof Error?s.message:String(s)}`)}},tw=async(e,t,r,n,s)=>{const i=await ao(e,t,r,n);return i.ok?v.Ok(i.val>=s):v.Err(i.error)},rw=[{name:"HTLC",type:"impl",interface_name:"starknet_htlc::interface::IHTLC"},{name:"core::integer::u256",type:"struct",members:[{name:"low",type:"core::integer::u128"},{name:"high",type:"core::integer::u128"}]},{name:"starknet_htlc::interface::IHTLC",type:"interface",items:[{name:"token",type:"function",inputs:[],outputs:[{type:"core::starknet::contract_address::ContractAddress"}],state_mutability:"view"},{name:"initiate",type:"function",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::u32; 8]"}],outputs:[],state_mutability:"external"},{name:"initiate_on_behalf",type:"function",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::u32; 8]"}],outputs:[],state_mutability:"external"},{name:"initiate_with_signature",type:"function",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::u32; 8]"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"},{name:"redeem",type:"function",inputs:[{name:"order_id",type:"core::felt252"},{name:"secret",type:"core::array::Array::<core::integer::u32>"}],outputs:[],state_mutability:"external"},{name:"refund",type:"function",inputs:[{name:"order_id",type:"core::felt252"}],outputs:[],state_mutability:"external"},{name:"instant_refund",type:"function",inputs:[{name:"order_id",type:"core::felt252"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"}]},{name:"constructor",type:"constructor",inputs:[{name:"token",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"starknet_htlc::interface::events::Initiated",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"},{kind:"data",name:"secret_hash",type:"[core::integer::u32; 8]"},{kind:"data",name:"amount",type:"core::integer::u256"}]},{kind:"struct",name:"starknet_htlc::interface::events::Redeemed",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"},{kind:"data",name:"secret_hash",type:"[core::integer::u32; 8]"},{kind:"data",name:"secret",type:"core::array::Array::<core::integer::u32>"}]},{kind:"struct",name:"starknet_htlc::interface::events::Refunded",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"}]},{kind:"enum",name:"starknet_htlc::htlc::HTLC::Event",type:"event",variants:[{kind:"nested",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"}]}],VT={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*"}]};class nw{constructor(t,r,n,s){this.url=t instanceof v.Url?t:new v.Url(t),this.account=r,this.starknetProvider=new it.RpcProvider({nodeUrl:s||Mo[n].nodeUrl}),this.chainId=Mo[n].chainId}get htlcActorAddress(){if(!this.account.address)throw new Error("No account found");return this.account.address}async initiate(t){if(!this.account.address)return v.Err("No account address");const{create_order:r,source_swap:n}=t;if(!n.amount||!n.redeemer||!r.timelock||!r.secret_hash)return v.Err("Invalid order");try{const s=new it.Contract(rw,t.source_swap.asset,this.account),i=await(s==null?void 0:s.token()),o=it.num.toHex(i),a=await tw(this.account.address,o,n.asset,this.starknetProvider,BigInt(n.amount));return a.error?v.Err(a.error):a.val?this.initiateRelay(t):this.approveAndInitiate(o,t)}catch(s){return v.Err(String(s))}}async approveAndInitiate(t,r){const{create_order:n,source_swap:s}=r,{redeemer:i,amount:o}=s,{secret_hash:a,timelock:c}=n;if(!a)return v.Err("Invalid order: secret_hash is undefined");const l=s.asset;try{const u=it.cairo.uint256(BigInt(o)),f={contractAddress:v.with0x(t),entrypoint:"approve",calldata:[l,u.low,u.high]},p=it.cairo.uint256(o),d={contractAddress:v.with0x(l),entrypoint:"initiate",calldata:[i,c.toString(),p.low.toString(),p.high.toString(),...v.hexToU32Array(a)]},m=await this.account.execute([f,d]);return await this.starknetProvider.waitForTransaction(m.transaction_hash,{retryInterval:2e3,successStates:[it.TransactionExecutionStatus.SUCCEEDED]}),v.Ok(m.transaction_hash)}catch(u){return v.Err(`Failed to approve and initiate: ${String(u)}`)}}async initiateRelay(t){const{create_order:r,source_swap:n}=t,{redeemer:s,amount:i}=n;if(!r.secret_hash)return v.Err("Invalid order: secret_hash is undefined");const o=v.with0x(r.secret_hash),c={domain:{name:"HTLC",version:it.shortString.encodeShortString("1"),chainId:this.chainId,revision:it.TypedDataRevision.ACTIVE},primaryType:"Initiate",types:VT,message:{redeemer:s,amount:it.cairo.uint256(i),timelock:r.timelock,secretHash:v.hexToU32Array(o)}};try{const l=await this.account.signMessage(c),u=l_(l);if(u.error)return v.Err(u.error);const f=await v.Fetcher.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:r.create_id,signature:u.val,perform_on:"Source"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return f.error?v.Err(f.error):f.result?v.Ok(f.result):v.Err("Init: No result found")}catch(l){return v.Err(`Failed to initiate relayer: ${String(l)}`)}}async redeem(t,r){try{const n=await v.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:r,perform_on:"Destination"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return n.error?v.Err(n.error):n.result?v.Ok(n.result):v.Err("Redeem: No result found")}catch(n){return v.Err(String(n))}}async refund(){return v.Err("Refund is taken care of by the relayer")}}const GT=e=>e.map(t=>t),WT=e=>{if(e===Ht.Testnet)return KT;if(e===Ht.Mainnet)return XT;throw new Error("Invalid network")},KT=["https://mempool.space/testnet4/api"],XT=["https://mempool.space/api","https://blockstream.info/api"],as={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}`},Ji={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"},Qp=e=>e.sort((t,r)=>t.status.confirmed!=r.status.confirmed?t.status.confirmed?-1:1:r.value-t.value);class sw{constructor(t,r){this.cacheTimeout=2e3,this.utxosCache=new Map,this.APIs=r?GT([r]):WT(t),this.network=t}async getTxIndex(t,r){const n=this.APIs.map(i=>`${i}/tx/${t}`),{vout:s}=await v.Fetcher.getWithFallback(n);for(let i=0;i<s.length;i++)if(s[i].scriptpubkey_address===r)return i;throw new Error("failed to get tx index")}async broadcast(t){if(!/^[0-9a-fA-F]+$/.test(t))throw new Error("invalid tx hex");for(let r=0;r<5;r++)try{return v.Fetcher.postWithFallback(this.APIs.map(n=>`${n}/tx`),{body:t})}catch(n){if(r===4)throw n;await new Promise(s=>setTimeout(s,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 ey(n.utxos,r);const s=await v.Fetcher.getWithFallback(this.APIs.map(i=>`${i}/address/${t}/utxo`),{signal:AbortSignal.timeout(5e3)});return this.utxosCache.set(t,{timestamp:Date.now(),utxos:s}),ey(s,r)}async getTransactionHex(t){return v.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${t}/hex`))}async getTransaction(t){return v.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===Ht.Regtest)return{fastestFee:8,halfHourFee:7,hourFee:6,economyFee:4,minimumFee:2};let t="";this.network===Ht.Testnet&&(t="testnet4/");const r=`https://mempool.space/${t}api/v1/fees/recommended`,n=`https://blockstream.info/${t}api/fee-estimates`,s=await v.Fetcher.getWithFallback([r,n],{signal:AbortSignal.timeout(5e3)});return"fastestFee"in s?s.fastestFee===1?{fastestFee:2,halfHourFee:2,hourFee:2,economyFee:2,minimumFee:2}:s:{fastestFee:s[1],halfHourFee:s[5],hourFee:s[10],economyFee:s[20],minimumFee:s[25]}}async getTransactions(t,r){const n=await v.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/address/${t}/txs`));if(r===Da.ALL)return n;if(r===Da.IN)return n.filter(s=>s.vout.find(i=>i.scriptpubkey_address===t));if(r===Da.OUT)return n.filter(s=>s.vin.find(i=>i.prevout.scriptpubkey_address===t));throw new Error("failed to get transactions: invalid bitcoin tx type")}getNetwork(){return this.network}async getLatestTip(){return v.Fetcher.getWithFallback(this.APIs.map(t=>`${t}/blocks/tip/height`))}async suggestFee(t,r,n){const i=(await this.getUTXOs(t,r)).length,o=2,a=await this.getFeeRates();return Math.floor(a[r_[n]]*1.05)*(i*70+o*31+10)}async getTransactionTimes(t){const r=t.map(s=>`txId[]=${s}`).join("&");return(await v.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/v1/transaction-times?${r}`))).map(s=>s*1e3)}}const ey=(e,t)=>{if(Array.isArray(e)){if(t){const r=e.reduce((i,o)=>i+o.value,0);if(r<t)throw new Error(as.INSUFFICIENT_FUNDS(r,t));let n=BigInt(0);e.sort((i,o)=>o.value-i.value);const s=[];for(const i of e)if(n+=BigInt(i.value),s.push(i),n>=t)break;return Qp(s)}return Qp(e)}return[]},Vi={p2wpkh:"p2wpkh","p2wpkh-p2sh":"p2wpkh-p2sh"},Ga={ALL:pe.Transaction.SIGHASH_ALL,NONE:pe.Transaction.SIGHASH_NONE,SINGLE:pe.Transaction.SIGHASH_SINGLE,ALL_ANYONECANPAY:pe.Transaction.SIGHASH_ALL|pe.Transaction.SIGHASH_ANYONECANPAY,NONE_ANYONECANPAY:pe.Transaction.SIGHASH_NONE|pe.Transaction.SIGHASH_ANYONECANPAY,SINGLE_ANYONECANPAY:pe.Transaction.SIGHASH_SINGLE|pe.Transaction.SIGHASH_ANYONECANPAY};class As{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(" "),s=await Oh.mixed().oneOf(["segwitV0","segwitV1","p2shSignature"]).required().validate(r),i=await Oh.mixed().oneOf(Object.values(Ga)).required().validate(parseInt(n));return new As(s,i)}}const YT=(e,t,r=!1)=>{const n=o=>{try{o=pe.address.fromBech32(o).data.toString("hex")}catch(a){if(Ff(a))(a.message.includes("Mixed-case string")||a.message.includes("too short"))&&(o=pe.address.fromBase58Check(o).hash.toString("hex"));else throw new Error(String(a))}return o},s=pe.script.fromASM(`
|
|
73
73
|
OP_IF
|
|
74
74
|
OP_SHA256
|
|
75
75
|
${e.secretHash}
|
|
@@ -87,7 +87,7 @@ ${lE(d)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessa
|
|
|
87
87
|
OP_ENDIF
|
|
88
88
|
OP_EQUALVERIFY
|
|
89
89
|
OP_CHECKSIG
|
|
90
|
-
`.trim().replace(/\s+/g," ")),i=pe.payments[r?"p2sh":"p2wsh"]({redeem:{output:s},network:t});if(!i.address)throw new Error("Could not build address");return{script:s,address:i.address}},co={P2SH:"p2sh",P2WSH:"p2wsh",P2TR:"p2tr"};var iw=(e=>(e[e.Bitcoin=0]="Bitcoin",e[e.EVM=1]="EVM",e))(iw||{});class YT{addSignatureSegwitV0(t=Ga.ALL){return new As("segwitV0",t)}addSignatureP2sh(t=Ga.ALL){return new As("p2shSignature",t)}addSignatureSegwitV1(t=Ga.ALL){return new As("segwitV1",t)}chain(){return iw.Bitcoin}async addAllInputs(t,r,n,s){const i=(s==null?void 0:s.utxos)||await n.getUTXOs(r);for(const o of i){const a=await n.getTxIndex(o.txid,r);t.addInput(Mf(o.txid),a,s==null?void 0:s.nSequence)}return t}async suggestFee(t,r){const n=await this.getAddress();return(await this.getProvider()).suggestFee(n,t,r)}async toOutputScript(t){return pe.address.toOutputScript(t,await this.getNetwork())}totalValueFromUTXOs(t){return t.reduce((r,n)=>r+n.value,0)}async scriptToAddress(t){const r=pe.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=v.trim0x(t.secretHash),t.secretHash.length!==64)throw new Error(Ji.INVALID_SECRET_HASH);const{script:r,address:n}=XT(t,await this.getNetwork());return new ZT(this,{...t,redeemScript:r,scriptAddress:n})}getScriptType(t,r){try{if(pe.address.fromBase58Check(t).version===r.scriptHash)return co.P2SH}catch{const s=pe.address.fromBech32(t);if(s.prefix!==r.bech32)throw new Error("Invalid address");if(s.version===0){if(s.data.length===32)return co.P2WSH}else if(s.version===1&&s.data.length===32)return co.P2TR}throw new Error("Unsupported script type")}}class ZT{constructor(t,r){if(r.secretHash=v.trim0x(r.secretHash),r.secretHash.length!==64)throw new Error(Ji.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=v.trim0x(t);const n=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),Buffer.from(t,"hex"),pe.script.number.encode(1),this.swap.redeemScript],s=pe.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!s)throw new Error("Could not generate p2wsh address for redeem script");try{return await this.wallet.spend(this.swap.redeemScript,s,{witness:n,toAddress:r})}catch(i){throw Ff(i)?i.message.includes("OP_EQUALVERIFY")?new Error(Ji.INVALID_PUBKEY_OR_SECRET):new Error(i.message):new Error(String(i))}}async refund(t){const r=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),pe.script.number.encode(0),this.swap.redeemScript];try{const n=pe.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 Ff(n)?n.message.includes("OP_EQUALVERIFY")?new Error(Ji.INVALID_PUBKEY):n.message.includes("BIP")?new Error(Ji.ORDER_NOT_EXPIRED):new Error(n.message):new Error(String(n))}}}const Lu=(e,t,r,n)=>`m/${e}'/${t===Ht.Mainnet?0:1}'/${r}'/0/${n??0}`,ow={bip44:(e,t,r)=>Lu("44",e,r??0,t),bip49:(e,t,r)=>Lu("49",e,r??0,t),bip84:(e,t,r)=>Lu("84",e,r??0,t)};function Du(e){if(e===Ht.Mainnet)return pe.networks.bitcoin;if(e===Ht.Testnet)return pe.networks.testnet;if(e===Ht.Regtest)return pe.networks.regtest;throw new Error("Invalid network")}function JT(e,t,r){if(!Bh.validateMnemonic(e))throw new Error("Invalid mnemonic");const n=(r==null?void 0:r.path)??ow.bip44(t,(r==null?void 0:r.index)??0),s=W1.BIP32Factory(ar).fromSeed(Bh.mnemonicToSeedSync(e));return QT(s,n)}const QT=(e,t)=>{const r=e.derivePath(t).privateKey;if(!r)throw new Error("Unable to derive private key from mnemonic");return r.toString("hex")};pe.initEccLib(ar);class hs extends YT{constructor({privateKey:t,provider:r,pkPath:n,pkType:s}){const i=Ua.ECPairFactory(ar),o=Du(r.getNetwork()),a=Buffer.from(t,"hex");if(a.length===0)throw new Error("invalid private key");super(),this.minAmt=1e3,this.path=n||"",this.pkType=s,this.signer=i.fromPrivateKey(a,{network:o}),this.provider=r,this.network=o}static fromMnemonic(t,r,n){const s=ow.bip84(r.getNetwork(),n==null?void 0:n.index),i=JT(t,r.getNetwork(),{path:s});return new hs({privateKey:i,provider:r,pkType:Vi.p2wpkh,pkPath:s})}static fromPrivateKey(t,r,n){return new hs({privateKey:t,provider:r,pkType:(n==null?void 0:n.pkType)??Vi.p2wpkh,pkPath:(n==null?void 0:n.pkPath)??"unknown"})}static createRandom(t){const r=Ua.ECPairFactory(ar),n=Du(t.getNetwork()),s=r.makeRandom({network:n});if(!s.privateKey)throw new Error("Failed to create random key");return new hs({privateKey:s.privateKey.toString("hex"),provider:t,pkType:Vi.p2wpkh,pkPath:"unknown"})}static fromWIF(t,r,n){const s=Ua.ECPairFactory(ar),i=Du(r.getNetwork()),o=s.fromWIF(t,i);if(!o.privateKey)throw new Error("Invalid WIF");return hs.fromPrivateKey(o.privateKey.toString("hex"),r,n)}walletConfig(){return{network:this.provider.getNetwork(),path:this.path,addressType:this.pkType}}async spend(t,r,{toAddress:n,fee:s,nSequence:i,unlockScript:o,witness:a}){var p;const c=this.getScriptType(r,this.network),l=await this.provider.getBalance(r);if(l===0)throw new Error(as.SCRIPT_NOT_FUNDED);let u=new pe.Transaction;if(u.version=2,s??(s=await this.provider.suggestFee(r,l,li.FAST)),s>l)throw new Error(as.FEE_EXCEEDS_AMOUNT(s,l));const f=await this.provider.getUTXOs(r);u=await this.addAllInputs(u,r,this.provider,{nSequence:i,utxos:f}),u.addOutput(await this.toOutputScript(n??await this.getAddress()),l-s);for(let d=0;d<u.ins.length;d++)if(c===co.P2SH){if(!o)throw new Error("Unlock script is required for p2sh");const m=[];for(const w of o)if(w instanceof As){const A=w.sigHashType,T=u.hashForSignature(d,t,A);m.push(pe.script.signature.encode(Buffer.from(await this.sign(T.toString("hex")),"hex"),A))}else m.push(w);const g=(p=pe.payments.p2sh({redeem:{input:pe.script.compile(m),output:t},network:this.network}).redeem)==null?void 0:p.input;u.setInputScript(d,g)}else if(c===co.P2WSH){if(!a)throw new Error("Witness is required for p2wsh");const m=[];for(const g of a)if(g instanceof As){const w=g.sigHashType,A=u.hashForWitnessV0(d,t,f[d].value,w);m.push(pe.script.signature.encode(Buffer.from(await this.sign(A.toString("hex")),"hex"),w))}else m.push(g);u.setWitness(d,m)}else throw new Error("Invalid script type "+c);return this.provider.broadcast(u.toHex())}async getAddress(){if(this.pkType===Vi["p2wpkh-p2sh"]){const{address:r}=pe.payments.p2sh({redeem:pe.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}=pe.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())}async getPublicKey(){return this.signer.publicKey.toString("hex")}getNetwork(){return Promise.resolve(this.network)}static async generateUnsignedPSBT(t,r,n,s,i,o){if(o||(o=await t.suggestFee(n,i,li.FAST)),o>i)throw new Error(as.FEE_EXCEEDS_AMOUNT(o,i));const a=await t.getUTXOs(n,i+o),c=a.reduce((f,p)=>f+p.value,0);if(c<i+o)throw new Error(as.INSUFFICIENT_FUNDS(c,i+o));const l=new pe.Psbt({network:r});for(const f of a){const p=await t.getTransactionHex(f.txid);l.addInput({hash:Mf(f.txid),index:f.vout,nonWitnessUtxo:Buffer.from(p,"hex")})}const u=c-i-o;return l.addOutput({address:s,value:i}),u>546&&l.addOutput({address:n,value:u}),{txHex:l.toHex(),utxoCount:a.length}}async _send(t,r,n){var l;if(n||(n=await this.provider.suggestFee(await this.getAddress(),r,li.FAST)),n>r)throw new Error(as.FEE_EXCEEDS_AMOUNT(n,r));if(r<this.minAmt)throw new Error(as.MIN_AMOUNT(this.minAmt));const s=await this.getAddress(),i=await this.provider.getUTXOs(s,r+n),o=i.reduce((u,f)=>u+f.value,0),a=new pe.Psbt({network:this.network});for(const u of i){const f=await this.provider.getTransactionHex(u.txid),p=await this.provider.getTransaction(u.txid);let d;this.pkType===Vi["p2wpkh-p2sh"]&&(d={witnessUtxo:{script:Buffer.from(p.vout[u.vout].scriptpubkey,"hex"),value:u.value},redeemScript:(l=pe.payments.p2sh({redeem:pe.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network}).redeem)==null?void 0:l.output}),a.addInput({hash:Mf(u.txid),index:u.vout,nonWitnessUtxo:Buffer.from(f,"hex"),...d})}const c=o-r-n;return a.addOutput({address:t,value:r}),c>0&&a.addOutput({address:s,value:c}),a.signAllInputs(this.signer).finalizeAllInputs(),a.extractTransaction().toHex()}async send(t,r,n){const s=await this._send(t,r,n);return this.provider.broadcast(s)}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)}}const eI="2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC",tI={name:"solana_spl_swaps",version:"0.4.0",spec:"0.1.0",description:"Created with Anchor"},rI=[{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:[]}],nI=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],sI=[{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]}],iI=[{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"}],oI=[{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"}]}}],ty={address:eI,metadata:tI,instructions:rI,accounts:nI,events:sI,errors:iI,types:oI},aI="2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",cI={name:"solana_native_swaps",version:"0.3.0",spec:"0.1.0",description:"Created with Anchor"},uI=[{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:[]}],lI=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],fI=[{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]}],dI=[{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"}],hI=[{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]}}]}}],zf={address:aI,metadata:cI,instructions:uI,accounts:lI,events:fI,errors:dI,types:hI};var hn={},Xc={};Object.defineProperty(Xc,"__esModule",{value:!0});Xc.encode=pI;Xc.decode=yI;const ry=Hs;function pI(e){return e.reduce((t,r)=>t+r.toString(16).padStart(2,"0"),"0x")}function yI(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?ry.Buffer.from([]):ry.Buffer.from(t.map(r=>parseInt(r,16)))}var Yc={},$s={},Hu;Object.defineProperty($s,"__esModule",{value:!0});$s.isVersionedTransaction=$s.isBrowser=void 0;$s.chunks=mI;$s.isBrowser=process.env.ANCHOR_BROWSER||typeof window<"u"&&!(!((Hu=window.process)===null||Hu===void 0)&&Hu.hasOwnProperty("type"));function mI(e,t){return Array.apply(0,new Array(Math.ceil(e.length/t))).map((r,n)=>e.slice(n*t,(n+1)*t))}const gI=e=>"version"in e;$s.isVersionedTransaction=gI;var zu={},qu={},Vu,ny;function aw(){return ny||(ny=1,Vu=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 s=42;t[r]=s;for(var i 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 o=Object.getOwnPropertySymbols(t);if(o.length!==1||o[0]!==r||!Object.prototype.propertyIsEnumerable.call(t,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var a=Object.getOwnPropertyDescriptor(t,r);if(a.value!==s||a.enumerable!==!0)return!1}return!0}),Vu}var Gu,sy;function Zc(){if(sy)return Gu;sy=1;var e=aw();return Gu=function(){return e()&&!!Symbol.toStringTag},Gu}var Wu,iy;function cw(){return iy||(iy=1,Wu=Object),Wu}var Ku,oy;function bI(){return oy||(oy=1,Ku=Error),Ku}var Xu,ay;function wI(){return ay||(ay=1,Xu=EvalError),Xu}var Yu,cy;function vI(){return cy||(cy=1,Yu=RangeError),Yu}var Zu,uy;function EI(){return uy||(uy=1,Zu=ReferenceError),Zu}var Ju,ly;function uw(){return ly||(ly=1,Ju=SyntaxError),Ju}var Qu,fy;function ca(){return fy||(fy=1,Qu=TypeError),Qu}var el,dy;function AI(){return dy||(dy=1,el=URIError),el}var tl,hy;function xI(){return hy||(hy=1,tl=Math.abs),tl}var rl,py;function SI(){return py||(py=1,rl=Math.floor),rl}var nl,yy;function _I(){return yy||(yy=1,nl=Math.max),nl}var sl,my;function kI(){return my||(my=1,sl=Math.min),sl}var il,gy;function TI(){return gy||(gy=1,il=Math.pow),il}var ol,by;function II(){return by||(by=1,ol=Math.round),ol}var al,wy;function PI(){return wy||(wy=1,al=Number.isNaN||function(t){return t!==t}),al}var cl,vy;function OI(){if(vy)return cl;vy=1;var e=PI();return cl=function(r){return e(r)||r===0?r:r<0?-1:1},cl}var ul,Ey;function BI(){return Ey||(Ey=1,ul=Object.getOwnPropertyDescriptor),ul}var ll,Ay;function Ri(){if(Ay)return ll;Ay=1;var e=BI();if(e)try{e([],"length")}catch{e=null}return ll=e,ll}var fl,xy;function Jc(){if(xy)return fl;xy=1;var e=Object.defineProperty||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return fl=e,fl}var dl,Sy;function CI(){if(Sy)return dl;Sy=1;var e=typeof Symbol<"u"&&Symbol,t=aw();return dl=function(){return typeof e!="function"||typeof Symbol!="function"||typeof e("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:t()},dl}var hl,_y;function lw(){return _y||(_y=1,hl=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),hl}var pl,ky;function fw(){if(ky)return pl;ky=1;var e=cw();return pl=e.getPrototypeOf||null,pl}var yl,Ty;function RI(){if(Ty)return yl;Ty=1;var e="Function.prototype.bind called on incompatible ",t=Object.prototype.toString,r=Math.max,n="[object Function]",s=function(c,l){for(var u=[],f=0;f<c.length;f+=1)u[f]=c[f];for(var p=0;p<l.length;p+=1)u[p+c.length]=l[p];return u},i=function(c,l){for(var u=[],f=l,p=0;f<c.length;f+=1,p+=1)u[p]=c[f];return u},o=function(a,c){for(var l="",u=0;u<a.length;u+=1)l+=a[u],u+1<a.length&&(l+=c);return l};return yl=function(c){var l=this;if(typeof l!="function"||t.apply(l)!==n)throw new TypeError(e+l);for(var u=i(arguments,1),f,p=function(){if(this instanceof f){var A=l.apply(this,s(u,arguments));return Object(A)===A?A:this}return l.apply(c,s(u,arguments))},d=r(0,l.length-u.length),m=[],g=0;g<d;g++)m[g]="$"+g;if(f=Function("binder","return function ("+o(m,",")+"){ return binder.apply(this,arguments); }")(p),l.prototype){var w=function(){};w.prototype=l.prototype,f.prototype=new w,w.prototype=null}return f},yl}var ml,Iy;function ua(){if(Iy)return ml;Iy=1;var e=RI();return ml=Function.prototype.bind||e,ml}var gl,Py;function lh(){return Py||(Py=1,gl=Function.prototype.call),gl}var bl,Oy;function fh(){return Oy||(Oy=1,bl=Function.prototype.apply),bl}var wl,By;function $I(){return By||(By=1,wl=typeof Reflect<"u"&&Reflect&&Reflect.apply),wl}var vl,Cy;function dw(){if(Cy)return vl;Cy=1;var e=ua(),t=fh(),r=lh(),n=$I();return vl=n||e.call(r,t),vl}var El,Ry;function dh(){if(Ry)return El;Ry=1;var e=ua(),t=ca(),r=lh(),n=dw();return El=function(i){if(i.length<1||typeof i[0]!="function")throw new t("a function is required");return n(e,r,i)},El}var Al,$y;function NI(){if($y)return Al;$y=1;var e=dh(),t=Ri(),r;try{r=[].__proto__===Array.prototype}catch(o){if(!o||typeof o!="object"||!("code"in o)||o.code!=="ERR_PROTO_ACCESS")throw o}var n=!!r&&t&&t(Object.prototype,"__proto__"),s=Object,i=s.getPrototypeOf;return Al=n&&typeof n.get=="function"?e([n.get]):typeof i=="function"?function(a){return i(a==null?a:s(a))}:!1,Al}var xl,Ny;function hh(){if(Ny)return xl;Ny=1;var e=lw(),t=fw(),r=NI();return xl=e?function(s){return e(s)}:t?function(s){if(!s||typeof s!="object"&&typeof s!="function")throw new TypeError("getProto: not an object");return t(s)}:r?function(s){return r(s)}:null,xl}var Sl,Uy;function hw(){if(Uy)return Sl;Uy=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=ua();return Sl=r.call(e,t),Sl}var _l,My;function pw(){if(My)return _l;My=1;var e,t=cw(),r=bI(),n=wI(),s=vI(),i=EI(),o=uw(),a=ca(),c=AI(),l=xI(),u=SI(),f=_I(),p=kI(),d=TI(),m=II(),g=OI(),w=Function,A=function(oe){try{return w('"use strict"; return ('+oe+").constructor;")()}catch{}},T=Ri(),E=Jc(),S=function(){throw new a},I=T?function(){try{return arguments.callee,S}catch{try{return T(arguments,"callee").get}catch{return S}}}():S,P=CI()(),$=hh(),j=fw(),k=lw(),F=fh(),R=lh(),U={},H=typeof Uint8Array>"u"||!$?e:$(Uint8Array),W={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?e:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?e:ArrayBuffer,"%ArrayIteratorPrototype%":P&&$?$([][Symbol.iterator]()):e,"%AsyncFromSyncIteratorPrototype%":e,"%AsyncFunction%":U,"%AsyncGenerator%":U,"%AsyncGeneratorFunction%":U,"%AsyncIteratorPrototype%":U,"%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%":w,"%GeneratorFunction%":U,"%Int8Array%":typeof Int8Array>"u"?e:Int8Array,"%Int16Array%":typeof Int16Array>"u"?e:Int16Array,"%Int32Array%":typeof Int32Array>"u"?e:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":P&&$?$($([][Symbol.iterator]())):e,"%JSON%":typeof JSON=="object"?JSON:e,"%Map%":typeof Map>"u"?e:Map,"%MapIteratorPrototype%":typeof Map>"u"||!P||!$?e:$(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":t,"%Object.getOwnPropertyDescriptor%":T,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?e:Promise,"%Proxy%":typeof Proxy>"u"?e:Proxy,"%RangeError%":s,"%ReferenceError%":i,"%Reflect%":typeof Reflect>"u"?e:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?e:Set,"%SetIteratorPrototype%":typeof Set>"u"||!P||!$?e:$(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?e:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":P&&$?$(""[Symbol.iterator]()):e,"%Symbol%":P?Symbol:e,"%SyntaxError%":o,"%ThrowTypeError%":I,"%TypedArray%":H,"%TypeError%":a,"%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%":R,"%Function.prototype.apply%":F,"%Object.defineProperty%":E,"%Object.getPrototypeOf%":j,"%Math.abs%":l,"%Math.floor%":u,"%Math.max%":f,"%Math.min%":p,"%Math.pow%":d,"%Math.round%":m,"%Math.sign%":g,"%Reflect.getPrototypeOf%":k};if($)try{null.error}catch(oe){var Z=$($(oe));W["%Error.prototype%"]=Z}var Q=function oe(ie){var he;if(ie==="%AsyncFunction%")he=A("async function () {}");else if(ie==="%GeneratorFunction%")he=A("function* () {}");else if(ie==="%AsyncGeneratorFunction%")he=A("async function* () {}");else if(ie==="%AsyncGenerator%"){var ve=oe("%AsyncGeneratorFunction%");ve&&(he=ve.prototype)}else if(ie==="%AsyncIteratorPrototype%"){var _e=oe("%AsyncGenerator%");_e&&$&&(he=$(_e.prototype))}return W[ie]=he,he},re={__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"]},D=ua(),B=hw(),V=D.call(R,Array.prototype.concat),K=D.call(F,Array.prototype.splice),O=D.call(R,String.prototype.replace),N=D.call(R,String.prototype.slice),L=D.call(R,RegExp.prototype.exec),J=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,ne=/\\(\\)?/g,fe=function(ie){var he=N(ie,0,1),ve=N(ie,-1);if(he==="%"&&ve!=="%")throw new o("invalid intrinsic syntax, expected closing `%`");if(ve==="%"&&he!=="%")throw new o("invalid intrinsic syntax, expected opening `%`");var _e=[];return O(ie,J,function(je,jt,Qe,Pr){_e[_e.length]=Qe?O(Pr,ne,"$1"):jt||je}),_e},ce=function(ie,he){var ve=ie,_e;if(B(re,ve)&&(_e=re[ve],ve="%"+_e[0]+"%"),B(W,ve)){var je=W[ve];if(je===U&&(je=Q(ve)),typeof je>"u"&&!he)throw new a("intrinsic "+ie+" exists, but is not available. Please file an issue!");return{alias:_e,name:ve,value:je}}throw new o("intrinsic "+ie+" does not exist!")};return _l=function(ie,he){if(typeof ie!="string"||ie.length===0)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof he!="boolean")throw new a('"allowMissing" argument must be a boolean');if(L(/^%?[^%]*%?$/,ie)===null)throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var ve=fe(ie),_e=ve.length>0?ve[0]:"",je=ce("%"+_e+"%",he),jt=je.name,Qe=je.value,Pr=!1,ns=je.alias;ns&&(_e=ns[0],K(ve,V([0,1],ns)));for(var G=1,Or=!0;G<ve.length;G+=1){var vt=ve[G],Et=N(vt,0,1),Tn=N(vt,-1);if((Et==='"'||Et==="'"||Et==="`"||Tn==='"'||Tn==="'"||Tn==="`")&&Et!==Tn)throw new o("property names with quotes must have matching quotes");if((vt==="constructor"||!Or)&&(Pr=!0),_e+="."+vt,jt="%"+_e+"%",B(W,jt))Qe=W[jt];else if(Qe!=null){if(!(vt in Qe)){if(!he)throw new a("base intrinsic for "+ie+" exists, but the property is not available.");return}if(T&&G+1>=ve.length){var Gs=T(Qe,vt);Or=!!Gs,Or&&"get"in Gs&&!("originalValue"in Gs.get)?Qe=Gs.get:Qe=Qe[vt]}else Or=B(Qe,vt),Qe=Qe[vt];Or&&!Pr&&(W[jt]=Qe)}}return Qe},_l}var kl,Fy;function la(){if(Fy)return kl;Fy=1;var e=pw(),t=dh(),r=t([e("%String.prototype.indexOf%")]);return kl=function(s,i){var o=e(s,!!i);return typeof o=="function"&&r(s,".prototype.")>-1?t([o]):o},kl}var Tl,jy;function UI(){if(jy)return Tl;jy=1;var e=Zc()(),t=la(),r=t("Object.prototype.toString"),n=function(a){return e&&a&&typeof a=="object"&&Symbol.toStringTag in a?!1:r(a)==="[object Arguments]"},s=function(a){return n(a)?!0:a!==null&&typeof a=="object"&&"length"in a&&typeof a.length=="number"&&a.length>=0&&r(a)!=="[object Array]"&&"callee"in a&&r(a.callee)==="[object Function]"},i=function(){return n(arguments)}();return n.isLegacyArguments=s,Tl=i?n:s,Tl}var Il,Ly;function MI(){if(Ly)return Il;Ly=1;var e=la(),t=Zc()(),r=hw(),n=Ri(),s;if(t){var i=e("RegExp.prototype.exec"),o={},a=function(){throw o},c={toString:a,valueOf:a};typeof Symbol.toPrimitive=="symbol"&&(c[Symbol.toPrimitive]=a),s=function(p){if(!p||typeof p!="object")return!1;var d=n(p,"lastIndex"),m=d&&r(d,"value");if(!m)return!1;try{i(p,c)}catch(g){return g===o}}}else{var l=e("Object.prototype.toString"),u="[object RegExp]";s=function(p){return!p||typeof p!="object"&&typeof p!="function"?!1:l(p)===u}}return Il=s,Il}var Pl,Dy;function FI(){if(Dy)return Pl;Dy=1;var e=la(),t=MI(),r=e("RegExp.prototype.exec"),n=ca();return Pl=function(i){if(!t(i))throw new n("`regex` must be a RegExp");return function(a){return r(i,a)!==null}},Pl}var Ol,Hy;function jI(){if(Hy)return Ol;Hy=1;var e=la(),t=FI(),r=t(/^\s*(?:function)?\*/),n=Zc()(),s=hh(),i=e("Object.prototype.toString"),o=e("Function.prototype.toString"),a=function(){if(!n)return!1;try{return Function("return function*() {}")()}catch{}},c;return Ol=function(u){if(typeof u!="function")return!1;if(r(o(u)))return!0;if(!n){var f=i(u);return f==="[object GeneratorFunction]"}if(!s)return!1;if(typeof c>"u"){var p=a();c=p?s(p):!1}return s(u)===c},Ol}var Bl,zy;function LI(){if(zy)return Bl;zy=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(T){T!==n&&(t=null)}else t=null;var s=/^\s*class\b/,i=function(E){try{var S=e.call(E);return s.test(S)}catch{return!1}},o=function(E){try{return i(E)?!1:(e.call(E),!0)}catch{return!1}},a=Object.prototype.toString,c="[object Object]",l="[object Function]",u="[object GeneratorFunction]",f="[object HTMLAllCollection]",p="[object HTML document.all class]",d="[object HTMLCollection]",m=typeof Symbol=="function"&&!!Symbol.toStringTag,g=!(0 in[,]),w=function(){return!1};if(typeof document=="object"){var A=document.all;a.call(A)===a.call(document.all)&&(w=function(E){if((g||!E)&&(typeof E>"u"||typeof E=="object"))try{var S=a.call(E);return(S===f||S===p||S===d||S===c)&&E("")==null}catch{}return!1})}return Bl=t?function(E){if(w(E))return!0;if(!E||typeof E!="function"&&typeof E!="object")return!1;try{t(E,null,r)}catch(S){if(S!==n)return!1}return!i(E)&&o(E)}:function(E){if(w(E))return!0;if(!E||typeof E!="function"&&typeof E!="object")return!1;if(m)return o(E);if(i(E))return!1;var S=a.call(E);return S!==l&&S!==u&&!/^\[object HTML/.test(S)?!1:o(E)},Bl}var Cl,qy;function DI(){if(qy)return Cl;qy=1;var e=LI(),t=Object.prototype.toString,r=Object.prototype.hasOwnProperty,n=function(c,l,u){for(var f=0,p=c.length;f<p;f++)r.call(c,f)&&(u==null?l(c[f],f,c):l.call(u,c[f],f,c))},s=function(c,l,u){for(var f=0,p=c.length;f<p;f++)u==null?l(c.charAt(f),f,c):l.call(u,c.charAt(f),f,c)},i=function(c,l,u){for(var f in c)r.call(c,f)&&(u==null?l(c[f],f,c):l.call(u,c[f],f,c))};function o(a){return t.call(a)==="[object Array]"}return Cl=function(c,l,u){if(!e(l))throw new TypeError("iterator must be a function");var f;arguments.length>=3&&(f=u),o(c)?n(c,l,f):typeof c=="string"?s(c,l,f):i(c,l,f)},Cl}var Rl,Vy;function HI(){return Vy||(Vy=1,Rl=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),Rl}var $l,Gy;function zI(){if(Gy)return $l;Gy=1;var e=HI(),t=typeof globalThis>"u"?Kr:globalThis;return $l=function(){for(var n=[],s=0;s<e.length;s++)typeof t[e[s]]=="function"&&(n[n.length]=e[s]);return n},$l}var Nl={exports:{}},Ul,Wy;function qI(){if(Wy)return Ul;Wy=1;var e=Jc(),t=uw(),r=ca(),n=Ri();return Ul=function(i,o,a){if(!i||typeof i!="object"&&typeof i!="function")throw new r("`obj` must be an object or a function`");if(typeof o!="string"&&typeof o!="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,l=arguments.length>4?arguments[4]:null,u=arguments.length>5?arguments[5]:null,f=arguments.length>6?arguments[6]:!1,p=!!n&&n(i,o);if(e)e(i,o,{configurable:u===null&&p?p.configurable:!u,enumerable:c===null&&p?p.enumerable:!c,value:a,writable:l===null&&p?p.writable:!l});else if(f||!c&&!l&&!u)i[o]=a;else throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Ul}var Ml,Ky;function VI(){if(Ky)return Ml;Ky=1;var e=Jc(),t=function(){return!!e};return t.hasArrayLengthDefineBug=function(){if(!e)return null;try{return e([],"length",{value:1}).length!==1}catch{return!0}},Ml=t,Ml}var Fl,Xy;function GI(){if(Xy)return Fl;Xy=1;var e=pw(),t=qI(),r=VI()(),n=Ri(),s=ca(),i=e("%Math.floor%");return Fl=function(a,c){if(typeof a!="function")throw new s("`fn` is not a function");if(typeof c!="number"||c<0||c>4294967295||i(c)!==c)throw new s("`length` must be a positive 32-bit integer");var l=arguments.length>2&&!!arguments[2],u=!0,f=!0;if("length"in a&&n){var p=n(a,"length");p&&!p.configurable&&(u=!1),p&&!p.writable&&(f=!1)}return(u||f||!l)&&(r?t(a,"length",c,!0,!0):t(a,"length",c)),a},Fl}var jl,Yy;function WI(){if(Yy)return jl;Yy=1;var e=ua(),t=fh(),r=dw();return jl=function(){return r(e,t,arguments)},jl}var Zy;function KI(){return Zy||(Zy=1,function(e){var t=GI(),r=Jc(),n=dh(),s=WI();e.exports=function(o){var a=n(arguments),c=o.length-(arguments.length-1);return t(a,1+(c>0?c:0),!0)},r?r(e.exports,"apply",{value:s}):e.exports.apply=s}(Nl)),Nl.exports}var Ll,Jy;function yw(){if(Jy)return Ll;Jy=1;var e=DI(),t=zI(),r=KI(),n=la(),s=Ri(),i=hh(),o=n("Object.prototype.toString"),a=Zc()(),c=typeof globalThis>"u"?Kr:globalThis,l=t(),u=n("String.prototype.slice"),f=n("Array.prototype.indexOf",!0)||function(w,A){for(var T=0;T<w.length;T+=1)if(w[T]===A)return T;return-1},p={__proto__:null};a&&s&&i?e(l,function(g){var w=new c[g];if(Symbol.toStringTag in w&&i){var A=i(w),T=s(A,Symbol.toStringTag);if(!T&&A){var E=i(A);T=s(E,Symbol.toStringTag)}p["$"+g]=r(T.get)}}):e(l,function(g){var w=new c[g],A=w.slice||w.set;A&&(p["$"+g]=r(A))});var d=function(w){var A=!1;return e(p,function(T,E){if(!A)try{"$"+T(w)===E&&(A=u(E,1))}catch{}}),A},m=function(w){var A=!1;return e(p,function(T,E){if(!A)try{T(w),A=u(E,1)}catch{}}),A};return Ll=function(w){if(!w||typeof w!="object")return!1;if(!a){var A=u(o(w),8,-1);return f(l,A)>-1?A:A!=="Object"?!1:m(w)}return s?d(w):null},Ll}var Dl,Qy;function XI(){if(Qy)return Dl;Qy=1;var e=yw();return Dl=function(r){return!!e(r)},Dl}var em;function YI(){return em||(em=1,function(e){var t=UI(),r=jI(),n=yw(),s=XI();function i(G){return G.call.bind(G)}var o=typeof BigInt<"u",a=typeof Symbol<"u",c=i(Object.prototype.toString),l=i(Number.prototype.valueOf),u=i(String.prototype.valueOf),f=i(Boolean.prototype.valueOf);if(o)var p=i(BigInt.prototype.valueOf);if(a)var d=i(Symbol.prototype.valueOf);function m(G,Or){if(typeof G!="object")return!1;try{return Or(G),!0}catch{return!1}}e.isArgumentsObject=t,e.isGeneratorFunction=r,e.isTypedArray=s;function g(G){return typeof Promise<"u"&&G instanceof Promise||G!==null&&typeof G=="object"&&typeof G.then=="function"&&typeof G.catch=="function"}e.isPromise=g;function w(G){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(G):s(G)||N(G)}e.isArrayBufferView=w;function A(G){return n(G)==="Uint8Array"}e.isUint8Array=A;function T(G){return n(G)==="Uint8ClampedArray"}e.isUint8ClampedArray=T;function E(G){return n(G)==="Uint16Array"}e.isUint16Array=E;function S(G){return n(G)==="Uint32Array"}e.isUint32Array=S;function I(G){return n(G)==="Int8Array"}e.isInt8Array=I;function P(G){return n(G)==="Int16Array"}e.isInt16Array=P;function $(G){return n(G)==="Int32Array"}e.isInt32Array=$;function j(G){return n(G)==="Float32Array"}e.isFloat32Array=j;function k(G){return n(G)==="Float64Array"}e.isFloat64Array=k;function F(G){return n(G)==="BigInt64Array"}e.isBigInt64Array=F;function R(G){return n(G)==="BigUint64Array"}e.isBigUint64Array=R;function U(G){return c(G)==="[object Map]"}U.working=typeof Map<"u"&&U(new Map);function H(G){return typeof Map>"u"?!1:U.working?U(G):G instanceof Map}e.isMap=H;function W(G){return c(G)==="[object Set]"}W.working=typeof Set<"u"&&W(new Set);function Z(G){return typeof Set>"u"?!1:W.working?W(G):G instanceof Set}e.isSet=Z;function Q(G){return c(G)==="[object WeakMap]"}Q.working=typeof WeakMap<"u"&&Q(new WeakMap);function re(G){return typeof WeakMap>"u"?!1:Q.working?Q(G):G instanceof WeakMap}e.isWeakMap=re;function D(G){return c(G)==="[object WeakSet]"}D.working=typeof WeakSet<"u"&&D(new WeakSet);function B(G){return D(G)}e.isWeakSet=B;function V(G){return c(G)==="[object ArrayBuffer]"}V.working=typeof ArrayBuffer<"u"&&V(new ArrayBuffer);function K(G){return typeof ArrayBuffer>"u"?!1:V.working?V(G):G instanceof ArrayBuffer}e.isArrayBuffer=K;function O(G){return c(G)==="[object DataView]"}O.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&O(new DataView(new ArrayBuffer(1),0,1));function N(G){return typeof DataView>"u"?!1:O.working?O(G):G instanceof DataView}e.isDataView=N;var L=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function J(G){return c(G)==="[object SharedArrayBuffer]"}function ne(G){return typeof L>"u"?!1:(typeof J.working>"u"&&(J.working=J(new L)),J.working?J(G):G instanceof L)}e.isSharedArrayBuffer=ne;function fe(G){return c(G)==="[object AsyncFunction]"}e.isAsyncFunction=fe;function ce(G){return c(G)==="[object Map Iterator]"}e.isMapIterator=ce;function oe(G){return c(G)==="[object Set Iterator]"}e.isSetIterator=oe;function ie(G){return c(G)==="[object Generator]"}e.isGeneratorObject=ie;function he(G){return c(G)==="[object WebAssembly.Module]"}e.isWebAssemblyCompiledModule=he;function ve(G){return m(G,l)}e.isNumberObject=ve;function _e(G){return m(G,u)}e.isStringObject=_e;function je(G){return m(G,f)}e.isBooleanObject=je;function jt(G){return o&&m(G,p)}e.isBigIntObject=jt;function Qe(G){return a&&m(G,d)}e.isSymbolObject=Qe;function Pr(G){return ve(G)||_e(G)||je(G)||jt(G)||Qe(G)}e.isBoxedPrimitive=Pr;function ns(G){return typeof Uint8Array<"u"&&(K(G)||ne(G))}e.isAnyArrayBuffer=ns,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(G){Object.defineProperty(e,G,{enumerable:!1,value:function(){throw new Error(G+" is not supported in userland")}})})}(qu)),qu}var Hl,tm;function ZI(){return tm||(tm=1,Hl=function(t){return t&&typeof t=="object"&&typeof t.copy=="function"&&typeof t.fill=="function"&&typeof t.readUInt8=="function"}),Hl}var Ba={exports:{}},rm;function JI(){return rm||(rm=1,typeof Object.create=="function"?Ba.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:Ba.exports=function(t,r){if(r){t.super_=r;var n=function(){};n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t}}),Ba.exports}var nm;function mw(){return nm||(nm=1,function(e){var t=Object.getOwnPropertyDescriptors||function(N){for(var L=Object.keys(N),J={},ne=0;ne<L.length;ne++)J[L[ne]]=Object.getOwnPropertyDescriptor(N,L[ne]);return J},r=/%[sdj%]/g;e.format=function(O){if(!I(O)){for(var N=[],L=0;L<arguments.length;L++)N.push(o(arguments[L]));return N.join(" ")}for(var L=1,J=arguments,ne=J.length,fe=String(O).replace(r,function(oe){if(oe==="%%")return"%";if(L>=ne)return oe;switch(oe){case"%s":return String(J[L++]);case"%d":return Number(J[L++]);case"%j":try{return JSON.stringify(J[L++])}catch{return"[Circular]"}default:return oe}}),ce=J[L];L<ne;ce=J[++L])T(ce)||!k(ce)?fe+=" "+ce:fe+=" "+o(ce);return fe},e.deprecate=function(O,N){if(typeof process<"u"&&process.noDeprecation===!0)return O;if(typeof process>"u")return function(){return e.deprecate(O,N).apply(this,arguments)};var L=!1;function J(){if(!L){if(process.throwDeprecation)throw new Error(N);process.traceDeprecation?console.trace(N):console.error(N),L=!0}return O.apply(this,arguments)}return J};var n={},s=/^$/;if(process.env.NODE_DEBUG){var i=process.env.NODE_DEBUG;i=i.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),s=new RegExp("^"+i+"$","i")}e.debuglog=function(O){if(O=O.toUpperCase(),!n[O])if(s.test(O)){var N=process.pid;n[O]=function(){var L=e.format.apply(e,arguments);console.error("%s %d: %s",O,N,L)}}else n[O]=function(){};return n[O]};function o(O,N){var L={seen:[],stylize:c};return arguments.length>=3&&(L.depth=arguments[2]),arguments.length>=4&&(L.colors=arguments[3]),A(N)?L.showHidden=N:N&&e._extend(L,N),$(L.showHidden)&&(L.showHidden=!1),$(L.depth)&&(L.depth=2),$(L.colors)&&(L.colors=!1),$(L.customInspect)&&(L.customInspect=!0),L.colors&&(L.stylize=a),u(L,O,L.depth)}e.inspect=o,o.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]},o.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function a(O,N){var L=o.styles[N];return L?"\x1B["+o.colors[L][0]+"m"+O+"\x1B["+o.colors[L][1]+"m":O}function c(O,N){return O}function l(O){var N={};return O.forEach(function(L,J){N[L]=!0}),N}function u(O,N,L){if(O.customInspect&&N&&U(N.inspect)&&N.inspect!==e.inspect&&!(N.constructor&&N.constructor.prototype===N)){var J=N.inspect(L,O);return I(J)||(J=u(O,J,L)),J}var ne=f(O,N);if(ne)return ne;var fe=Object.keys(N),ce=l(fe);if(O.showHidden&&(fe=Object.getOwnPropertyNames(N)),R(N)&&(fe.indexOf("message")>=0||fe.indexOf("description")>=0))return p(N);if(fe.length===0){if(U(N)){var oe=N.name?": "+N.name:"";return O.stylize("[Function"+oe+"]","special")}if(j(N))return O.stylize(RegExp.prototype.toString.call(N),"regexp");if(F(N))return O.stylize(Date.prototype.toString.call(N),"date");if(R(N))return p(N)}var ie="",he=!1,ve=["{","}"];if(w(N)&&(he=!0,ve=["[","]"]),U(N)){var _e=N.name?": "+N.name:"";ie=" [Function"+_e+"]"}if(j(N)&&(ie=" "+RegExp.prototype.toString.call(N)),F(N)&&(ie=" "+Date.prototype.toUTCString.call(N)),R(N)&&(ie=" "+p(N)),fe.length===0&&(!he||N.length==0))return ve[0]+ie+ve[1];if(L<0)return j(N)?O.stylize(RegExp.prototype.toString.call(N),"regexp"):O.stylize("[Object]","special");O.seen.push(N);var je;return he?je=d(O,N,L,ce,fe):je=fe.map(function(jt){return m(O,N,L,ce,jt,he)}),O.seen.pop(),g(je,ie,ve)}function f(O,N){if($(N))return O.stylize("undefined","undefined");if(I(N)){var L="'"+JSON.stringify(N).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return O.stylize(L,"string")}if(S(N))return O.stylize(""+N,"number");if(A(N))return O.stylize(""+N,"boolean");if(T(N))return O.stylize("null","null")}function p(O){return"["+Error.prototype.toString.call(O)+"]"}function d(O,N,L,J,ne){for(var fe=[],ce=0,oe=N.length;ce<oe;++ce)D(N,String(ce))?fe.push(m(O,N,L,J,String(ce),!0)):fe.push("");return ne.forEach(function(ie){ie.match(/^\d+$/)||fe.push(m(O,N,L,J,ie,!0))}),fe}function m(O,N,L,J,ne,fe){var ce,oe,ie;if(ie=Object.getOwnPropertyDescriptor(N,ne)||{value:N[ne]},ie.get?ie.set?oe=O.stylize("[Getter/Setter]","special"):oe=O.stylize("[Getter]","special"):ie.set&&(oe=O.stylize("[Setter]","special")),D(J,ne)||(ce="["+ne+"]"),oe||(O.seen.indexOf(ie.value)<0?(T(L)?oe=u(O,ie.value,null):oe=u(O,ie.value,L-1),oe.indexOf(`
|
|
90
|
+
`.trim().replace(/\s+/g," ")),i=pe.payments[r?"p2sh":"p2wsh"]({redeem:{output:s},network:t});if(!i.address)throw new Error("Could not build address");return{script:s,address:i.address}},co={P2SH:"p2sh",P2WSH:"p2wsh",P2TR:"p2tr"};var iw=(e=>(e[e.Bitcoin=0]="Bitcoin",e[e.EVM=1]="EVM",e))(iw||{});class ZT{addSignatureSegwitV0(t=Ga.ALL){return new As("segwitV0",t)}addSignatureP2sh(t=Ga.ALL){return new As("p2shSignature",t)}addSignatureSegwitV1(t=Ga.ALL){return new As("segwitV1",t)}chain(){return iw.Bitcoin}async addAllInputs(t,r,n,s){const i=(s==null?void 0:s.utxos)||await n.getUTXOs(r);for(const o of i){const a=await n.getTxIndex(o.txid,r);t.addInput(Mf(o.txid),a,s==null?void 0:s.nSequence)}return t}async suggestFee(t,r){const n=await this.getAddress();return(await this.getProvider()).suggestFee(n,t,r)}async toOutputScript(t){return pe.address.toOutputScript(t,await this.getNetwork())}totalValueFromUTXOs(t){return t.reduce((r,n)=>r+n.value,0)}async scriptToAddress(t){const r=pe.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=v.trim0x(t.secretHash),t.secretHash.length!==64)throw new Error(Ji.INVALID_SECRET_HASH);const{script:r,address:n}=YT(t,await this.getNetwork());return new JT(this,{...t,redeemScript:r,scriptAddress:n})}getScriptType(t,r){try{if(pe.address.fromBase58Check(t).version===r.scriptHash)return co.P2SH}catch{const s=pe.address.fromBech32(t);if(s.prefix!==r.bech32)throw new Error("Invalid address");if(s.version===0){if(s.data.length===32)return co.P2WSH}else if(s.version===1&&s.data.length===32)return co.P2TR}throw new Error("Unsupported script type")}}class JT{constructor(t,r){if(r.secretHash=v.trim0x(r.secretHash),r.secretHash.length!==64)throw new Error(Ji.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=v.trim0x(t);const n=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),Buffer.from(t,"hex"),pe.script.number.encode(1),this.swap.redeemScript],s=pe.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!s)throw new Error("Could not generate p2wsh address for redeem script");try{return await this.wallet.spend(this.swap.redeemScript,s,{witness:n,toAddress:r})}catch(i){throw Ff(i)?i.message.includes("OP_EQUALVERIFY")?new Error(Ji.INVALID_PUBKEY_OR_SECRET):new Error(i.message):new Error(String(i))}}async refund(t){const r=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),pe.script.number.encode(0),this.swap.redeemScript];try{const n=pe.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 Ff(n)?n.message.includes("OP_EQUALVERIFY")?new Error(Ji.INVALID_PUBKEY):n.message.includes("BIP")?new Error(Ji.ORDER_NOT_EXPIRED):new Error(n.message):new Error(String(n))}}}const Lu=(e,t,r,n)=>`m/${e}'/${t===Ht.Mainnet?0:1}'/${r}'/0/${n??0}`,ow={bip44:(e,t,r)=>Lu("44",e,r??0,t),bip49:(e,t,r)=>Lu("49",e,r??0,t),bip84:(e,t,r)=>Lu("84",e,r??0,t)};function Du(e){if(e===Ht.Mainnet)return pe.networks.bitcoin;if(e===Ht.Testnet)return pe.networks.testnet;if(e===Ht.Regtest)return pe.networks.regtest;throw new Error("Invalid network")}function QT(e,t,r){if(!Bh.validateMnemonic(e))throw new Error("Invalid mnemonic");const n=(r==null?void 0:r.path)??ow.bip44(t,(r==null?void 0:r.index)??0),s=W1.BIP32Factory(ar).fromSeed(Bh.mnemonicToSeedSync(e));return eI(s,n)}const eI=(e,t)=>{const r=e.derivePath(t).privateKey;if(!r)throw new Error("Unable to derive private key from mnemonic");return r.toString("hex")};pe.initEccLib(ar);class hs extends ZT{constructor({privateKey:t,provider:r,pkPath:n,pkType:s}){const i=Ua.ECPairFactory(ar),o=Du(r.getNetwork()),a=Buffer.from(t,"hex");if(a.length===0)throw new Error("invalid private key");super(),this.minAmt=1e3,this.path=n||"",this.pkType=s,this.signer=i.fromPrivateKey(a,{network:o}),this.provider=r,this.network=o}static fromMnemonic(t,r,n){const s=ow.bip84(r.getNetwork(),n==null?void 0:n.index),i=QT(t,r.getNetwork(),{path:s});return new hs({privateKey:i,provider:r,pkType:Vi.p2wpkh,pkPath:s})}static fromPrivateKey(t,r,n){return new hs({privateKey:t,provider:r,pkType:(n==null?void 0:n.pkType)??Vi.p2wpkh,pkPath:(n==null?void 0:n.pkPath)??"unknown"})}static createRandom(t){const r=Ua.ECPairFactory(ar),n=Du(t.getNetwork()),s=r.makeRandom({network:n});if(!s.privateKey)throw new Error("Failed to create random key");return new hs({privateKey:s.privateKey.toString("hex"),provider:t,pkType:Vi.p2wpkh,pkPath:"unknown"})}static fromWIF(t,r,n){const s=Ua.ECPairFactory(ar),i=Du(r.getNetwork()),o=s.fromWIF(t,i);if(!o.privateKey)throw new Error("Invalid WIF");return hs.fromPrivateKey(o.privateKey.toString("hex"),r,n)}walletConfig(){return{network:this.provider.getNetwork(),path:this.path,addressType:this.pkType}}async spend(t,r,{toAddress:n,fee:s,nSequence:i,unlockScript:o,witness:a}){var p;const c=this.getScriptType(r,this.network),l=await this.provider.getBalance(r);if(l===0)throw new Error(as.SCRIPT_NOT_FUNDED);let u=new pe.Transaction;if(u.version=2,s??(s=await this.provider.suggestFee(r,l,li.FAST)),s>l)throw new Error(as.FEE_EXCEEDS_AMOUNT(s,l));const f=await this.provider.getUTXOs(r);u=await this.addAllInputs(u,r,this.provider,{nSequence:i,utxos:f}),u.addOutput(await this.toOutputScript(n??await this.getAddress()),l-s);for(let d=0;d<u.ins.length;d++)if(c===co.P2SH){if(!o)throw new Error("Unlock script is required for p2sh");const m=[];for(const w of o)if(w instanceof As){const A=w.sigHashType,T=u.hashForSignature(d,t,A);m.push(pe.script.signature.encode(Buffer.from(await this.sign(T.toString("hex")),"hex"),A))}else m.push(w);const g=(p=pe.payments.p2sh({redeem:{input:pe.script.compile(m),output:t},network:this.network}).redeem)==null?void 0:p.input;u.setInputScript(d,g)}else if(c===co.P2WSH){if(!a)throw new Error("Witness is required for p2wsh");const m=[];for(const g of a)if(g instanceof As){const w=g.sigHashType,A=u.hashForWitnessV0(d,t,f[d].value,w);m.push(pe.script.signature.encode(Buffer.from(await this.sign(A.toString("hex")),"hex"),w))}else m.push(g);u.setWitness(d,m)}else throw new Error("Invalid script type "+c);return this.provider.broadcast(u.toHex())}async getAddress(){if(this.pkType===Vi["p2wpkh-p2sh"]){const{address:r}=pe.payments.p2sh({redeem:pe.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}=pe.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())}async getPublicKey(){return this.signer.publicKey.toString("hex")}getNetwork(){return Promise.resolve(this.network)}static async generateUnsignedPSBT(t,r,n,s,i,o){if(o||(o=await t.suggestFee(n,i,li.FAST)),o>i)throw new Error(as.FEE_EXCEEDS_AMOUNT(o,i));const a=await t.getUTXOs(n,i+o),c=a.reduce((f,p)=>f+p.value,0);if(c<i+o)throw new Error(as.INSUFFICIENT_FUNDS(c,i+o));const l=new pe.Psbt({network:r});for(const f of a){const p=await t.getTransactionHex(f.txid);l.addInput({hash:Mf(f.txid),index:f.vout,nonWitnessUtxo:Buffer.from(p,"hex")})}const u=c-i-o;return l.addOutput({address:s,value:i}),u>546&&l.addOutput({address:n,value:u}),{txHex:l.toHex(),utxoCount:a.length}}async _send(t,r,n){var l;if(n||(n=await this.provider.suggestFee(await this.getAddress(),r,li.FAST)),n>r)throw new Error(as.FEE_EXCEEDS_AMOUNT(n,r));if(r<this.minAmt)throw new Error(as.MIN_AMOUNT(this.minAmt));const s=await this.getAddress(),i=await this.provider.getUTXOs(s,r+n),o=i.reduce((u,f)=>u+f.value,0),a=new pe.Psbt({network:this.network});for(const u of i){const f=await this.provider.getTransactionHex(u.txid),p=await this.provider.getTransaction(u.txid);let d;this.pkType===Vi["p2wpkh-p2sh"]&&(d={witnessUtxo:{script:Buffer.from(p.vout[u.vout].scriptpubkey,"hex"),value:u.value},redeemScript:(l=pe.payments.p2sh({redeem:pe.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network}).redeem)==null?void 0:l.output}),a.addInput({hash:Mf(u.txid),index:u.vout,nonWitnessUtxo:Buffer.from(f,"hex"),...d})}const c=o-r-n;return a.addOutput({address:t,value:r}),c>0&&a.addOutput({address:s,value:c}),a.signAllInputs(this.signer).finalizeAllInputs(),a.extractTransaction().toHex()}async send(t,r,n){const s=await this._send(t,r,n);return this.provider.broadcast(s)}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)}}const tI="2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC",rI={name:"solana_spl_swaps",version:"0.4.0",spec:"0.1.0",description:"Created with Anchor"},nI=[{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:[]}],sI=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],iI=[{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]}],oI=[{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"}],aI=[{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"}]}}],ty={address:tI,metadata:rI,instructions:nI,accounts:sI,events:iI,errors:oI,types:aI},cI="2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",uI={name:"solana_native_swaps",version:"0.3.0",spec:"0.1.0",description:"Created with Anchor"},lI=[{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:[]}],fI=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],dI=[{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]}],hI=[{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"}],pI=[{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]}}]}}],zf={address:cI,metadata:uI,instructions:lI,accounts:fI,events:dI,errors:hI,types:pI};var hn={},Xc={};Object.defineProperty(Xc,"__esModule",{value:!0});Xc.encode=yI;Xc.decode=mI;const ry=Hs;function yI(e){return e.reduce((t,r)=>t+r.toString(16).padStart(2,"0"),"0x")}function mI(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?ry.Buffer.from([]):ry.Buffer.from(t.map(r=>parseInt(r,16)))}var Yc={},$s={},Hu;Object.defineProperty($s,"__esModule",{value:!0});$s.isVersionedTransaction=$s.isBrowser=void 0;$s.chunks=gI;$s.isBrowser=process.env.ANCHOR_BROWSER||typeof window<"u"&&!(!((Hu=window.process)===null||Hu===void 0)&&Hu.hasOwnProperty("type"));function gI(e,t){return Array.apply(0,new Array(Math.ceil(e.length/t))).map((r,n)=>e.slice(n*t,(n+1)*t))}const bI=e=>"version"in e;$s.isVersionedTransaction=bI;var zu={},qu={},Vu,ny;function aw(){return ny||(ny=1,Vu=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 s=42;t[r]=s;for(var i 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 o=Object.getOwnPropertySymbols(t);if(o.length!==1||o[0]!==r||!Object.prototype.propertyIsEnumerable.call(t,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var a=Object.getOwnPropertyDescriptor(t,r);if(a.value!==s||a.enumerable!==!0)return!1}return!0}),Vu}var Gu,sy;function Zc(){if(sy)return Gu;sy=1;var e=aw();return Gu=function(){return e()&&!!Symbol.toStringTag},Gu}var Wu,iy;function cw(){return iy||(iy=1,Wu=Object),Wu}var Ku,oy;function wI(){return oy||(oy=1,Ku=Error),Ku}var Xu,ay;function vI(){return ay||(ay=1,Xu=EvalError),Xu}var Yu,cy;function EI(){return cy||(cy=1,Yu=RangeError),Yu}var Zu,uy;function AI(){return uy||(uy=1,Zu=ReferenceError),Zu}var Ju,ly;function uw(){return ly||(ly=1,Ju=SyntaxError),Ju}var Qu,fy;function ca(){return fy||(fy=1,Qu=TypeError),Qu}var el,dy;function xI(){return dy||(dy=1,el=URIError),el}var tl,hy;function SI(){return hy||(hy=1,tl=Math.abs),tl}var rl,py;function _I(){return py||(py=1,rl=Math.floor),rl}var nl,yy;function kI(){return yy||(yy=1,nl=Math.max),nl}var sl,my;function TI(){return my||(my=1,sl=Math.min),sl}var il,gy;function II(){return gy||(gy=1,il=Math.pow),il}var ol,by;function PI(){return by||(by=1,ol=Math.round),ol}var al,wy;function OI(){return wy||(wy=1,al=Number.isNaN||function(t){return t!==t}),al}var cl,vy;function BI(){if(vy)return cl;vy=1;var e=OI();return cl=function(r){return e(r)||r===0?r:r<0?-1:1},cl}var ul,Ey;function CI(){return Ey||(Ey=1,ul=Object.getOwnPropertyDescriptor),ul}var ll,Ay;function Ri(){if(Ay)return ll;Ay=1;var e=CI();if(e)try{e([],"length")}catch{e=null}return ll=e,ll}var fl,xy;function Jc(){if(xy)return fl;xy=1;var e=Object.defineProperty||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return fl=e,fl}var dl,Sy;function RI(){if(Sy)return dl;Sy=1;var e=typeof Symbol<"u"&&Symbol,t=aw();return dl=function(){return typeof e!="function"||typeof Symbol!="function"||typeof e("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:t()},dl}var hl,_y;function lw(){return _y||(_y=1,hl=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),hl}var pl,ky;function fw(){if(ky)return pl;ky=1;var e=cw();return pl=e.getPrototypeOf||null,pl}var yl,Ty;function $I(){if(Ty)return yl;Ty=1;var e="Function.prototype.bind called on incompatible ",t=Object.prototype.toString,r=Math.max,n="[object Function]",s=function(c,l){for(var u=[],f=0;f<c.length;f+=1)u[f]=c[f];for(var p=0;p<l.length;p+=1)u[p+c.length]=l[p];return u},i=function(c,l){for(var u=[],f=l,p=0;f<c.length;f+=1,p+=1)u[p]=c[f];return u},o=function(a,c){for(var l="",u=0;u<a.length;u+=1)l+=a[u],u+1<a.length&&(l+=c);return l};return yl=function(c){var l=this;if(typeof l!="function"||t.apply(l)!==n)throw new TypeError(e+l);for(var u=i(arguments,1),f,p=function(){if(this instanceof f){var A=l.apply(this,s(u,arguments));return Object(A)===A?A:this}return l.apply(c,s(u,arguments))},d=r(0,l.length-u.length),m=[],g=0;g<d;g++)m[g]="$"+g;if(f=Function("binder","return function ("+o(m,",")+"){ return binder.apply(this,arguments); }")(p),l.prototype){var w=function(){};w.prototype=l.prototype,f.prototype=new w,w.prototype=null}return f},yl}var ml,Iy;function ua(){if(Iy)return ml;Iy=1;var e=$I();return ml=Function.prototype.bind||e,ml}var gl,Py;function lh(){return Py||(Py=1,gl=Function.prototype.call),gl}var bl,Oy;function fh(){return Oy||(Oy=1,bl=Function.prototype.apply),bl}var wl,By;function NI(){return By||(By=1,wl=typeof Reflect<"u"&&Reflect&&Reflect.apply),wl}var vl,Cy;function dw(){if(Cy)return vl;Cy=1;var e=ua(),t=fh(),r=lh(),n=NI();return vl=n||e.call(r,t),vl}var El,Ry;function dh(){if(Ry)return El;Ry=1;var e=ua(),t=ca(),r=lh(),n=dw();return El=function(i){if(i.length<1||typeof i[0]!="function")throw new t("a function is required");return n(e,r,i)},El}var Al,$y;function UI(){if($y)return Al;$y=1;var e=dh(),t=Ri(),r;try{r=[].__proto__===Array.prototype}catch(o){if(!o||typeof o!="object"||!("code"in o)||o.code!=="ERR_PROTO_ACCESS")throw o}var n=!!r&&t&&t(Object.prototype,"__proto__"),s=Object,i=s.getPrototypeOf;return Al=n&&typeof n.get=="function"?e([n.get]):typeof i=="function"?function(a){return i(a==null?a:s(a))}:!1,Al}var xl,Ny;function hh(){if(Ny)return xl;Ny=1;var e=lw(),t=fw(),r=UI();return xl=e?function(s){return e(s)}:t?function(s){if(!s||typeof s!="object"&&typeof s!="function")throw new TypeError("getProto: not an object");return t(s)}:r?function(s){return r(s)}:null,xl}var Sl,Uy;function hw(){if(Uy)return Sl;Uy=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=ua();return Sl=r.call(e,t),Sl}var _l,My;function pw(){if(My)return _l;My=1;var e,t=cw(),r=wI(),n=vI(),s=EI(),i=AI(),o=uw(),a=ca(),c=xI(),l=SI(),u=_I(),f=kI(),p=TI(),d=II(),m=PI(),g=BI(),w=Function,A=function(oe){try{return w('"use strict"; return ('+oe+").constructor;")()}catch{}},T=Ri(),E=Jc(),S=function(){throw new a},I=T?function(){try{return arguments.callee,S}catch{try{return T(arguments,"callee").get}catch{return S}}}():S,P=RI()(),$=hh(),j=fw(),k=lw(),F=fh(),R=lh(),U={},H=typeof Uint8Array>"u"||!$?e:$(Uint8Array),W={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?e:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?e:ArrayBuffer,"%ArrayIteratorPrototype%":P&&$?$([][Symbol.iterator]()):e,"%AsyncFromSyncIteratorPrototype%":e,"%AsyncFunction%":U,"%AsyncGenerator%":U,"%AsyncGeneratorFunction%":U,"%AsyncIteratorPrototype%":U,"%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%":w,"%GeneratorFunction%":U,"%Int8Array%":typeof Int8Array>"u"?e:Int8Array,"%Int16Array%":typeof Int16Array>"u"?e:Int16Array,"%Int32Array%":typeof Int32Array>"u"?e:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":P&&$?$($([][Symbol.iterator]())):e,"%JSON%":typeof JSON=="object"?JSON:e,"%Map%":typeof Map>"u"?e:Map,"%MapIteratorPrototype%":typeof Map>"u"||!P||!$?e:$(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":t,"%Object.getOwnPropertyDescriptor%":T,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?e:Promise,"%Proxy%":typeof Proxy>"u"?e:Proxy,"%RangeError%":s,"%ReferenceError%":i,"%Reflect%":typeof Reflect>"u"?e:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?e:Set,"%SetIteratorPrototype%":typeof Set>"u"||!P||!$?e:$(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?e:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":P&&$?$(""[Symbol.iterator]()):e,"%Symbol%":P?Symbol:e,"%SyntaxError%":o,"%ThrowTypeError%":I,"%TypedArray%":H,"%TypeError%":a,"%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%":R,"%Function.prototype.apply%":F,"%Object.defineProperty%":E,"%Object.getPrototypeOf%":j,"%Math.abs%":l,"%Math.floor%":u,"%Math.max%":f,"%Math.min%":p,"%Math.pow%":d,"%Math.round%":m,"%Math.sign%":g,"%Reflect.getPrototypeOf%":k};if($)try{null.error}catch(oe){var Z=$($(oe));W["%Error.prototype%"]=Z}var Q=function oe(ie){var he;if(ie==="%AsyncFunction%")he=A("async function () {}");else if(ie==="%GeneratorFunction%")he=A("function* () {}");else if(ie==="%AsyncGeneratorFunction%")he=A("async function* () {}");else if(ie==="%AsyncGenerator%"){var ve=oe("%AsyncGeneratorFunction%");ve&&(he=ve.prototype)}else if(ie==="%AsyncIteratorPrototype%"){var _e=oe("%AsyncGenerator%");_e&&$&&(he=$(_e.prototype))}return W[ie]=he,he},re={__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"]},D=ua(),B=hw(),V=D.call(R,Array.prototype.concat),K=D.call(F,Array.prototype.splice),O=D.call(R,String.prototype.replace),N=D.call(R,String.prototype.slice),L=D.call(R,RegExp.prototype.exec),J=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,ne=/\\(\\)?/g,fe=function(ie){var he=N(ie,0,1),ve=N(ie,-1);if(he==="%"&&ve!=="%")throw new o("invalid intrinsic syntax, expected closing `%`");if(ve==="%"&&he!=="%")throw new o("invalid intrinsic syntax, expected opening `%`");var _e=[];return O(ie,J,function(je,jt,Qe,Pr){_e[_e.length]=Qe?O(Pr,ne,"$1"):jt||je}),_e},ce=function(ie,he){var ve=ie,_e;if(B(re,ve)&&(_e=re[ve],ve="%"+_e[0]+"%"),B(W,ve)){var je=W[ve];if(je===U&&(je=Q(ve)),typeof je>"u"&&!he)throw new a("intrinsic "+ie+" exists, but is not available. Please file an issue!");return{alias:_e,name:ve,value:je}}throw new o("intrinsic "+ie+" does not exist!")};return _l=function(ie,he){if(typeof ie!="string"||ie.length===0)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof he!="boolean")throw new a('"allowMissing" argument must be a boolean');if(L(/^%?[^%]*%?$/,ie)===null)throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var ve=fe(ie),_e=ve.length>0?ve[0]:"",je=ce("%"+_e+"%",he),jt=je.name,Qe=je.value,Pr=!1,ns=je.alias;ns&&(_e=ns[0],K(ve,V([0,1],ns)));for(var G=1,Or=!0;G<ve.length;G+=1){var vt=ve[G],Et=N(vt,0,1),Tn=N(vt,-1);if((Et==='"'||Et==="'"||Et==="`"||Tn==='"'||Tn==="'"||Tn==="`")&&Et!==Tn)throw new o("property names with quotes must have matching quotes");if((vt==="constructor"||!Or)&&(Pr=!0),_e+="."+vt,jt="%"+_e+"%",B(W,jt))Qe=W[jt];else if(Qe!=null){if(!(vt in Qe)){if(!he)throw new a("base intrinsic for "+ie+" exists, but the property is not available.");return}if(T&&G+1>=ve.length){var Gs=T(Qe,vt);Or=!!Gs,Or&&"get"in Gs&&!("originalValue"in Gs.get)?Qe=Gs.get:Qe=Qe[vt]}else Or=B(Qe,vt),Qe=Qe[vt];Or&&!Pr&&(W[jt]=Qe)}}return Qe},_l}var kl,Fy;function la(){if(Fy)return kl;Fy=1;var e=pw(),t=dh(),r=t([e("%String.prototype.indexOf%")]);return kl=function(s,i){var o=e(s,!!i);return typeof o=="function"&&r(s,".prototype.")>-1?t([o]):o},kl}var Tl,jy;function MI(){if(jy)return Tl;jy=1;var e=Zc()(),t=la(),r=t("Object.prototype.toString"),n=function(a){return e&&a&&typeof a=="object"&&Symbol.toStringTag in a?!1:r(a)==="[object Arguments]"},s=function(a){return n(a)?!0:a!==null&&typeof a=="object"&&"length"in a&&typeof a.length=="number"&&a.length>=0&&r(a)!=="[object Array]"&&"callee"in a&&r(a.callee)==="[object Function]"},i=function(){return n(arguments)}();return n.isLegacyArguments=s,Tl=i?n:s,Tl}var Il,Ly;function FI(){if(Ly)return Il;Ly=1;var e=la(),t=Zc()(),r=hw(),n=Ri(),s;if(t){var i=e("RegExp.prototype.exec"),o={},a=function(){throw o},c={toString:a,valueOf:a};typeof Symbol.toPrimitive=="symbol"&&(c[Symbol.toPrimitive]=a),s=function(p){if(!p||typeof p!="object")return!1;var d=n(p,"lastIndex"),m=d&&r(d,"value");if(!m)return!1;try{i(p,c)}catch(g){return g===o}}}else{var l=e("Object.prototype.toString"),u="[object RegExp]";s=function(p){return!p||typeof p!="object"&&typeof p!="function"?!1:l(p)===u}}return Il=s,Il}var Pl,Dy;function jI(){if(Dy)return Pl;Dy=1;var e=la(),t=FI(),r=e("RegExp.prototype.exec"),n=ca();return Pl=function(i){if(!t(i))throw new n("`regex` must be a RegExp");return function(a){return r(i,a)!==null}},Pl}var Ol,Hy;function LI(){if(Hy)return Ol;Hy=1;var e=la(),t=jI(),r=t(/^\s*(?:function)?\*/),n=Zc()(),s=hh(),i=e("Object.prototype.toString"),o=e("Function.prototype.toString"),a=function(){if(!n)return!1;try{return Function("return function*() {}")()}catch{}},c;return Ol=function(u){if(typeof u!="function")return!1;if(r(o(u)))return!0;if(!n){var f=i(u);return f==="[object GeneratorFunction]"}if(!s)return!1;if(typeof c>"u"){var p=a();c=p?s(p):!1}return s(u)===c},Ol}var Bl,zy;function DI(){if(zy)return Bl;zy=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(T){T!==n&&(t=null)}else t=null;var s=/^\s*class\b/,i=function(E){try{var S=e.call(E);return s.test(S)}catch{return!1}},o=function(E){try{return i(E)?!1:(e.call(E),!0)}catch{return!1}},a=Object.prototype.toString,c="[object Object]",l="[object Function]",u="[object GeneratorFunction]",f="[object HTMLAllCollection]",p="[object HTML document.all class]",d="[object HTMLCollection]",m=typeof Symbol=="function"&&!!Symbol.toStringTag,g=!(0 in[,]),w=function(){return!1};if(typeof document=="object"){var A=document.all;a.call(A)===a.call(document.all)&&(w=function(E){if((g||!E)&&(typeof E>"u"||typeof E=="object"))try{var S=a.call(E);return(S===f||S===p||S===d||S===c)&&E("")==null}catch{}return!1})}return Bl=t?function(E){if(w(E))return!0;if(!E||typeof E!="function"&&typeof E!="object")return!1;try{t(E,null,r)}catch(S){if(S!==n)return!1}return!i(E)&&o(E)}:function(E){if(w(E))return!0;if(!E||typeof E!="function"&&typeof E!="object")return!1;if(m)return o(E);if(i(E))return!1;var S=a.call(E);return S!==l&&S!==u&&!/^\[object HTML/.test(S)?!1:o(E)},Bl}var Cl,qy;function HI(){if(qy)return Cl;qy=1;var e=DI(),t=Object.prototype.toString,r=Object.prototype.hasOwnProperty,n=function(c,l,u){for(var f=0,p=c.length;f<p;f++)r.call(c,f)&&(u==null?l(c[f],f,c):l.call(u,c[f],f,c))},s=function(c,l,u){for(var f=0,p=c.length;f<p;f++)u==null?l(c.charAt(f),f,c):l.call(u,c.charAt(f),f,c)},i=function(c,l,u){for(var f in c)r.call(c,f)&&(u==null?l(c[f],f,c):l.call(u,c[f],f,c))};function o(a){return t.call(a)==="[object Array]"}return Cl=function(c,l,u){if(!e(l))throw new TypeError("iterator must be a function");var f;arguments.length>=3&&(f=u),o(c)?n(c,l,f):typeof c=="string"?s(c,l,f):i(c,l,f)},Cl}var Rl,Vy;function zI(){return Vy||(Vy=1,Rl=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),Rl}var $l,Gy;function qI(){if(Gy)return $l;Gy=1;var e=zI(),t=typeof globalThis>"u"?Kr:globalThis;return $l=function(){for(var n=[],s=0;s<e.length;s++)typeof t[e[s]]=="function"&&(n[n.length]=e[s]);return n},$l}var Nl={exports:{}},Ul,Wy;function VI(){if(Wy)return Ul;Wy=1;var e=Jc(),t=uw(),r=ca(),n=Ri();return Ul=function(i,o,a){if(!i||typeof i!="object"&&typeof i!="function")throw new r("`obj` must be an object or a function`");if(typeof o!="string"&&typeof o!="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,l=arguments.length>4?arguments[4]:null,u=arguments.length>5?arguments[5]:null,f=arguments.length>6?arguments[6]:!1,p=!!n&&n(i,o);if(e)e(i,o,{configurable:u===null&&p?p.configurable:!u,enumerable:c===null&&p?p.enumerable:!c,value:a,writable:l===null&&p?p.writable:!l});else if(f||!c&&!l&&!u)i[o]=a;else throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Ul}var Ml,Ky;function GI(){if(Ky)return Ml;Ky=1;var e=Jc(),t=function(){return!!e};return t.hasArrayLengthDefineBug=function(){if(!e)return null;try{return e([],"length",{value:1}).length!==1}catch{return!0}},Ml=t,Ml}var Fl,Xy;function WI(){if(Xy)return Fl;Xy=1;var e=pw(),t=VI(),r=GI()(),n=Ri(),s=ca(),i=e("%Math.floor%");return Fl=function(a,c){if(typeof a!="function")throw new s("`fn` is not a function");if(typeof c!="number"||c<0||c>4294967295||i(c)!==c)throw new s("`length` must be a positive 32-bit integer");var l=arguments.length>2&&!!arguments[2],u=!0,f=!0;if("length"in a&&n){var p=n(a,"length");p&&!p.configurable&&(u=!1),p&&!p.writable&&(f=!1)}return(u||f||!l)&&(r?t(a,"length",c,!0,!0):t(a,"length",c)),a},Fl}var jl,Yy;function KI(){if(Yy)return jl;Yy=1;var e=ua(),t=fh(),r=dw();return jl=function(){return r(e,t,arguments)},jl}var Zy;function XI(){return Zy||(Zy=1,function(e){var t=WI(),r=Jc(),n=dh(),s=KI();e.exports=function(o){var a=n(arguments),c=o.length-(arguments.length-1);return t(a,1+(c>0?c:0),!0)},r?r(e.exports,"apply",{value:s}):e.exports.apply=s}(Nl)),Nl.exports}var Ll,Jy;function yw(){if(Jy)return Ll;Jy=1;var e=HI(),t=qI(),r=XI(),n=la(),s=Ri(),i=hh(),o=n("Object.prototype.toString"),a=Zc()(),c=typeof globalThis>"u"?Kr:globalThis,l=t(),u=n("String.prototype.slice"),f=n("Array.prototype.indexOf",!0)||function(w,A){for(var T=0;T<w.length;T+=1)if(w[T]===A)return T;return-1},p={__proto__:null};a&&s&&i?e(l,function(g){var w=new c[g];if(Symbol.toStringTag in w&&i){var A=i(w),T=s(A,Symbol.toStringTag);if(!T&&A){var E=i(A);T=s(E,Symbol.toStringTag)}p["$"+g]=r(T.get)}}):e(l,function(g){var w=new c[g],A=w.slice||w.set;A&&(p["$"+g]=r(A))});var d=function(w){var A=!1;return e(p,function(T,E){if(!A)try{"$"+T(w)===E&&(A=u(E,1))}catch{}}),A},m=function(w){var A=!1;return e(p,function(T,E){if(!A)try{T(w),A=u(E,1)}catch{}}),A};return Ll=function(w){if(!w||typeof w!="object")return!1;if(!a){var A=u(o(w),8,-1);return f(l,A)>-1?A:A!=="Object"?!1:m(w)}return s?d(w):null},Ll}var Dl,Qy;function YI(){if(Qy)return Dl;Qy=1;var e=yw();return Dl=function(r){return!!e(r)},Dl}var em;function ZI(){return em||(em=1,function(e){var t=MI(),r=LI(),n=yw(),s=YI();function i(G){return G.call.bind(G)}var o=typeof BigInt<"u",a=typeof Symbol<"u",c=i(Object.prototype.toString),l=i(Number.prototype.valueOf),u=i(String.prototype.valueOf),f=i(Boolean.prototype.valueOf);if(o)var p=i(BigInt.prototype.valueOf);if(a)var d=i(Symbol.prototype.valueOf);function m(G,Or){if(typeof G!="object")return!1;try{return Or(G),!0}catch{return!1}}e.isArgumentsObject=t,e.isGeneratorFunction=r,e.isTypedArray=s;function g(G){return typeof Promise<"u"&&G instanceof Promise||G!==null&&typeof G=="object"&&typeof G.then=="function"&&typeof G.catch=="function"}e.isPromise=g;function w(G){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(G):s(G)||N(G)}e.isArrayBufferView=w;function A(G){return n(G)==="Uint8Array"}e.isUint8Array=A;function T(G){return n(G)==="Uint8ClampedArray"}e.isUint8ClampedArray=T;function E(G){return n(G)==="Uint16Array"}e.isUint16Array=E;function S(G){return n(G)==="Uint32Array"}e.isUint32Array=S;function I(G){return n(G)==="Int8Array"}e.isInt8Array=I;function P(G){return n(G)==="Int16Array"}e.isInt16Array=P;function $(G){return n(G)==="Int32Array"}e.isInt32Array=$;function j(G){return n(G)==="Float32Array"}e.isFloat32Array=j;function k(G){return n(G)==="Float64Array"}e.isFloat64Array=k;function F(G){return n(G)==="BigInt64Array"}e.isBigInt64Array=F;function R(G){return n(G)==="BigUint64Array"}e.isBigUint64Array=R;function U(G){return c(G)==="[object Map]"}U.working=typeof Map<"u"&&U(new Map);function H(G){return typeof Map>"u"?!1:U.working?U(G):G instanceof Map}e.isMap=H;function W(G){return c(G)==="[object Set]"}W.working=typeof Set<"u"&&W(new Set);function Z(G){return typeof Set>"u"?!1:W.working?W(G):G instanceof Set}e.isSet=Z;function Q(G){return c(G)==="[object WeakMap]"}Q.working=typeof WeakMap<"u"&&Q(new WeakMap);function re(G){return typeof WeakMap>"u"?!1:Q.working?Q(G):G instanceof WeakMap}e.isWeakMap=re;function D(G){return c(G)==="[object WeakSet]"}D.working=typeof WeakSet<"u"&&D(new WeakSet);function B(G){return D(G)}e.isWeakSet=B;function V(G){return c(G)==="[object ArrayBuffer]"}V.working=typeof ArrayBuffer<"u"&&V(new ArrayBuffer);function K(G){return typeof ArrayBuffer>"u"?!1:V.working?V(G):G instanceof ArrayBuffer}e.isArrayBuffer=K;function O(G){return c(G)==="[object DataView]"}O.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&O(new DataView(new ArrayBuffer(1),0,1));function N(G){return typeof DataView>"u"?!1:O.working?O(G):G instanceof DataView}e.isDataView=N;var L=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function J(G){return c(G)==="[object SharedArrayBuffer]"}function ne(G){return typeof L>"u"?!1:(typeof J.working>"u"&&(J.working=J(new L)),J.working?J(G):G instanceof L)}e.isSharedArrayBuffer=ne;function fe(G){return c(G)==="[object AsyncFunction]"}e.isAsyncFunction=fe;function ce(G){return c(G)==="[object Map Iterator]"}e.isMapIterator=ce;function oe(G){return c(G)==="[object Set Iterator]"}e.isSetIterator=oe;function ie(G){return c(G)==="[object Generator]"}e.isGeneratorObject=ie;function he(G){return c(G)==="[object WebAssembly.Module]"}e.isWebAssemblyCompiledModule=he;function ve(G){return m(G,l)}e.isNumberObject=ve;function _e(G){return m(G,u)}e.isStringObject=_e;function je(G){return m(G,f)}e.isBooleanObject=je;function jt(G){return o&&m(G,p)}e.isBigIntObject=jt;function Qe(G){return a&&m(G,d)}e.isSymbolObject=Qe;function Pr(G){return ve(G)||_e(G)||je(G)||jt(G)||Qe(G)}e.isBoxedPrimitive=Pr;function ns(G){return typeof Uint8Array<"u"&&(K(G)||ne(G))}e.isAnyArrayBuffer=ns,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(G){Object.defineProperty(e,G,{enumerable:!1,value:function(){throw new Error(G+" is not supported in userland")}})})}(qu)),qu}var Hl,tm;function JI(){return tm||(tm=1,Hl=function(t){return t&&typeof t=="object"&&typeof t.copy=="function"&&typeof t.fill=="function"&&typeof t.readUInt8=="function"}),Hl}var Ba={exports:{}},rm;function QI(){return rm||(rm=1,typeof Object.create=="function"?Ba.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:Ba.exports=function(t,r){if(r){t.super_=r;var n=function(){};n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t}}),Ba.exports}var nm;function mw(){return nm||(nm=1,function(e){var t=Object.getOwnPropertyDescriptors||function(N){for(var L=Object.keys(N),J={},ne=0;ne<L.length;ne++)J[L[ne]]=Object.getOwnPropertyDescriptor(N,L[ne]);return J},r=/%[sdj%]/g;e.format=function(O){if(!I(O)){for(var N=[],L=0;L<arguments.length;L++)N.push(o(arguments[L]));return N.join(" ")}for(var L=1,J=arguments,ne=J.length,fe=String(O).replace(r,function(oe){if(oe==="%%")return"%";if(L>=ne)return oe;switch(oe){case"%s":return String(J[L++]);case"%d":return Number(J[L++]);case"%j":try{return JSON.stringify(J[L++])}catch{return"[Circular]"}default:return oe}}),ce=J[L];L<ne;ce=J[++L])T(ce)||!k(ce)?fe+=" "+ce:fe+=" "+o(ce);return fe},e.deprecate=function(O,N){if(typeof process<"u"&&process.noDeprecation===!0)return O;if(typeof process>"u")return function(){return e.deprecate(O,N).apply(this,arguments)};var L=!1;function J(){if(!L){if(process.throwDeprecation)throw new Error(N);process.traceDeprecation?console.trace(N):console.error(N),L=!0}return O.apply(this,arguments)}return J};var n={},s=/^$/;if(process.env.NODE_DEBUG){var i=process.env.NODE_DEBUG;i=i.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),s=new RegExp("^"+i+"$","i")}e.debuglog=function(O){if(O=O.toUpperCase(),!n[O])if(s.test(O)){var N=process.pid;n[O]=function(){var L=e.format.apply(e,arguments);console.error("%s %d: %s",O,N,L)}}else n[O]=function(){};return n[O]};function o(O,N){var L={seen:[],stylize:c};return arguments.length>=3&&(L.depth=arguments[2]),arguments.length>=4&&(L.colors=arguments[3]),A(N)?L.showHidden=N:N&&e._extend(L,N),$(L.showHidden)&&(L.showHidden=!1),$(L.depth)&&(L.depth=2),$(L.colors)&&(L.colors=!1),$(L.customInspect)&&(L.customInspect=!0),L.colors&&(L.stylize=a),u(L,O,L.depth)}e.inspect=o,o.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]},o.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function a(O,N){var L=o.styles[N];return L?"\x1B["+o.colors[L][0]+"m"+O+"\x1B["+o.colors[L][1]+"m":O}function c(O,N){return O}function l(O){var N={};return O.forEach(function(L,J){N[L]=!0}),N}function u(O,N,L){if(O.customInspect&&N&&U(N.inspect)&&N.inspect!==e.inspect&&!(N.constructor&&N.constructor.prototype===N)){var J=N.inspect(L,O);return I(J)||(J=u(O,J,L)),J}var ne=f(O,N);if(ne)return ne;var fe=Object.keys(N),ce=l(fe);if(O.showHidden&&(fe=Object.getOwnPropertyNames(N)),R(N)&&(fe.indexOf("message")>=0||fe.indexOf("description")>=0))return p(N);if(fe.length===0){if(U(N)){var oe=N.name?": "+N.name:"";return O.stylize("[Function"+oe+"]","special")}if(j(N))return O.stylize(RegExp.prototype.toString.call(N),"regexp");if(F(N))return O.stylize(Date.prototype.toString.call(N),"date");if(R(N))return p(N)}var ie="",he=!1,ve=["{","}"];if(w(N)&&(he=!0,ve=["[","]"]),U(N)){var _e=N.name?": "+N.name:"";ie=" [Function"+_e+"]"}if(j(N)&&(ie=" "+RegExp.prototype.toString.call(N)),F(N)&&(ie=" "+Date.prototype.toUTCString.call(N)),R(N)&&(ie=" "+p(N)),fe.length===0&&(!he||N.length==0))return ve[0]+ie+ve[1];if(L<0)return j(N)?O.stylize(RegExp.prototype.toString.call(N),"regexp"):O.stylize("[Object]","special");O.seen.push(N);var je;return he?je=d(O,N,L,ce,fe):je=fe.map(function(jt){return m(O,N,L,ce,jt,he)}),O.seen.pop(),g(je,ie,ve)}function f(O,N){if($(N))return O.stylize("undefined","undefined");if(I(N)){var L="'"+JSON.stringify(N).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return O.stylize(L,"string")}if(S(N))return O.stylize(""+N,"number");if(A(N))return O.stylize(""+N,"boolean");if(T(N))return O.stylize("null","null")}function p(O){return"["+Error.prototype.toString.call(O)+"]"}function d(O,N,L,J,ne){for(var fe=[],ce=0,oe=N.length;ce<oe;++ce)D(N,String(ce))?fe.push(m(O,N,L,J,String(ce),!0)):fe.push("");return ne.forEach(function(ie){ie.match(/^\d+$/)||fe.push(m(O,N,L,J,ie,!0))}),fe}function m(O,N,L,J,ne,fe){var ce,oe,ie;if(ie=Object.getOwnPropertyDescriptor(N,ne)||{value:N[ne]},ie.get?ie.set?oe=O.stylize("[Getter/Setter]","special"):oe=O.stylize("[Getter]","special"):ie.set&&(oe=O.stylize("[Setter]","special")),D(J,ne)||(ce="["+ne+"]"),oe||(O.seen.indexOf(ie.value)<0?(T(L)?oe=u(O,ie.value,null):oe=u(O,ie.value,L-1),oe.indexOf(`
|
|
91
91
|
`)>-1&&(fe?oe=oe.split(`
|
|
92
92
|
`).map(function(he){return" "+he}).join(`
|
|
93
93
|
`).slice(2):oe=`
|
|
@@ -96,10 +96,10 @@ ${lE(d)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessa
|
|
|
96
96
|
`))):oe=O.stylize("[Circular]","special")),$(ce)){if(fe&&ne.match(/^\d+$/))return oe;ce=JSON.stringify(""+ne),ce.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(ce=ce.slice(1,-1),ce=O.stylize(ce,"name")):(ce=ce.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),ce=O.stylize(ce,"string"))}return ce+": "+oe}function g(O,N,L){var J=O.reduce(function(ne,fe){return fe.indexOf(`
|
|
97
97
|
`)>=0,ne+fe.replace(/\u001b\[\d\d?m/g,"").length+1},0);return J>60?L[0]+(N===""?"":N+`
|
|
98
98
|
`)+" "+O.join(`,
|
|
99
|
-
`)+" "+L[1]:L[0]+N+" "+O.join(", ")+" "+L[1]}e.types=YI();function w(O){return Array.isArray(O)}e.isArray=w;function A(O){return typeof O=="boolean"}e.isBoolean=A;function T(O){return O===null}e.isNull=T;function E(O){return O==null}e.isNullOrUndefined=E;function S(O){return typeof O=="number"}e.isNumber=S;function I(O){return typeof O=="string"}e.isString=I;function P(O){return typeof O=="symbol"}e.isSymbol=P;function $(O){return O===void 0}e.isUndefined=$;function j(O){return k(O)&&W(O)==="[object RegExp]"}e.isRegExp=j,e.types.isRegExp=j;function k(O){return typeof O=="object"&&O!==null}e.isObject=k;function F(O){return k(O)&&W(O)==="[object Date]"}e.isDate=F,e.types.isDate=F;function R(O){return k(O)&&(W(O)==="[object Error]"||O instanceof Error)}e.isError=R,e.types.isNativeError=R;function U(O){return typeof O=="function"}e.isFunction=U;function H(O){return O===null||typeof O=="boolean"||typeof O=="number"||typeof O=="string"||typeof O=="symbol"||typeof O>"u"}e.isPrimitive=H,e.isBuffer=ZI();function W(O){return Object.prototype.toString.call(O)}function Z(O){return O<10?"0"+O.toString(10):O.toString(10)}var Q=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function re(){var O=new Date,N=[Z(O.getHours()),Z(O.getMinutes()),Z(O.getSeconds())].join(":");return[O.getDate(),Q[O.getMonth()],N].join(" ")}e.log=function(){console.log("%s - %s",re(),e.format.apply(e,arguments))},e.inherits=JI(),e._extend=function(O,N){if(!N||!k(N))return O;for(var L=Object.keys(N),J=L.length;J--;)O[L[J]]=N[L[J]];return O};function D(O,N){return Object.prototype.hasOwnProperty.call(O,N)}var B=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;e.promisify=function(N){if(typeof N!="function")throw new TypeError('The "original" argument must be of type Function');if(B&&N[B]){var L=N[B];if(typeof L!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(L,B,{value:L,enumerable:!1,writable:!1,configurable:!0}),L}function L(){for(var J,ne,fe=new Promise(function(ie,he){J=ie,ne=he}),ce=[],oe=0;oe<arguments.length;oe++)ce.push(arguments[oe]);ce.push(function(ie,he){ie?ne(ie):J(he)});try{N.apply(this,ce)}catch(ie){ne(ie)}return fe}return Object.setPrototypeOf(L,Object.getPrototypeOf(N)),B&&Object.defineProperty(L,B,{value:L,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(L,t(N))},e.promisify.custom=B;function V(O,N){if(!O){var L=new Error("Promise was rejected with a falsy value");L.reason=O,O=L}return N(O)}function K(O){if(typeof O!="function")throw new TypeError('The "original" argument must be of type Function');function N(){for(var L=[],J=0;J<arguments.length;J++)L.push(arguments[J]);var ne=L.pop();if(typeof ne!="function")throw new TypeError("The last argument must be of type Function");var fe=this,ce=function(){return ne.apply(fe,arguments)};O.apply(this,L).then(function(oe){process.nextTick(ce.bind(null,null,oe))},function(oe){process.nextTick(V.bind(null,oe,ce))})}return Object.setPrototypeOf(N,Object.getPrototypeOf(O)),Object.defineProperties(N,t(O)),N}e.callbackify=K}(zu)),zu}Object.defineProperty(Yc,"__esModule",{value:!0});Yc.decode=QI;Yc.encode=eP;const gw=$s;function QI(e){return(gw.isBrowser?new TextDecoder("utf-8"):new(mw()).TextDecoder("utf-8")).decode(e)}function eP(e){return(gw.isBrowser?new TextEncoder:new(mw()).TextEncoder("utf-8")).encode(e)}var Qc={},qf={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(e,t){var r=Hs,n=r.Buffer;function s(o,a){for(var c in o)a[c]=o[c]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(s(r,t),t.Buffer=i);function i(o,a,c){return n(o,a,c)}i.prototype=Object.create(n.prototype),s(n,i),i.from=function(o,a,c){if(typeof o=="number")throw new TypeError("Argument must not be a number");return n(o,a,c)},i.alloc=function(o,a,c){if(typeof o!="number")throw new TypeError("Argument must be a number");var l=n(o);return a!==void 0?typeof c=="string"?l.fill(a,c):l.fill(a):l.fill(0),l},i.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return n(o)},i.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(o)}})(qf,qf.exports);var tP=qf.exports,Ca=tP.Buffer;function rP(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 s=e.charAt(n),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=n}var o=e.length,a=e.charAt(0),c=Math.log(o)/Math.log(256),l=Math.log(256)/Math.log(o);function u(d){if((Array.isArray(d)||d instanceof Uint8Array)&&(d=Ca.from(d)),!Ca.isBuffer(d))throw new TypeError("Expected Buffer");if(d.length===0)return"";for(var m=0,g=0,w=0,A=d.length;w!==A&&d[w]===0;)w++,m++;for(var T=(A-w)*l+1>>>0,E=new Uint8Array(T);w!==A;){for(var S=d[w],I=0,P=T-1;(S!==0||I<g)&&P!==-1;P--,I++)S+=256*E[P]>>>0,E[P]=S%o>>>0,S=S/o>>>0;if(S!==0)throw new Error("Non-zero carry");g=I,w++}for(var $=T-g;$!==T&&E[$]===0;)$++;for(var j=a.repeat(m);$<T;++$)j+=e.charAt(E[$]);return j}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return Ca.alloc(0);for(var m=0,g=0,w=0;d[m]===a;)g++,m++;for(var A=(d.length-m)*c+1>>>0,T=new Uint8Array(A);m<d.length;){var E=d.charCodeAt(m);if(E>255)return;var S=t[E];if(S===255)return;for(var I=0,P=A-1;(S!==0||I<w)&&P!==-1;P--,I++)S+=o*T[P]>>>0,T[P]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");w=I,m++}for(var $=A-w;$!==A&&T[$]===0;)$++;var j=Ca.allocUnsafe(g+(A-$));j.fill(0,0,g);for(var k=g;$!==A;)j[k++]=T[$++];return j}function p(d){var m=f(d);if(m)return m;throw new Error("Non-base"+o+" character")}return{encode:u,decodeUnsafe:f,decode:p}}var nP=rP,sP=nP,iP="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",oP=sP(iP),aP=Kr&&Kr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Qc,"__esModule",{value:!0});Qc.encode=cP;Qc.decode=uP;const bw=aP(oP);function cP(e){return bw.default.encode(e)}function uP(e){return bw.default.decode(e)}var eu={};Object.defineProperty(eu,"__esModule",{value:!0});eu.encode=fP;eu.decode=dP;const lP=Hs;function fP(e){return e.toString("base64")}function dP(e){return lP.Buffer.from(e,"base64")}var hP=Kr&&Kr.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),pP=Kr&&Kr.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),tu=Kr&&Kr.__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)&&hP(t,e,r);return pP(t,e),t};Object.defineProperty(hn,"__esModule",{value:!0});hn.base64=hn.bs58=hn.utf8=ww=hn.hex=void 0;var ww=hn.hex=tu(Xc);hn.utf8=tu(Yc);hn.bs58=tu(Qc);hn.base64=tu(eu);class Wn{constructor(t,r,n,s,i){try{this.swapId=Array.from(Buffer.from(t,"hex")),this.secretHash=Array.from(Buffer.from(n,"hex"))}catch(o){throw new Error("Error decoding swapId or secretHash",{cause:o})}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 sr.web3.PublicKey(r)}catch(o){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:o})}try{this.amount=new sr.BN(s.toString(10),10),this.expiresIn=new sr.BN(i)}catch(o){throw new Error("Error decoding amount. Invalid value for amount",{cause:o})}if(!(Number.isInteger(i)&&i>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:s,secret_hash:i,timelock:o}=r,a=BigInt(r.amount);return new Wn(n,s,i,a,o)}}function vw(e){let t;try{t=[...ww.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 Ew{constructor(t,r,n,s){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)throw new Error("Relayer address is required");try{this.relayer=new sr.web3.PublicKey(n)}catch(a){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:a})}const i=s.spl?{...ty,metadata:{...ty.metadata??{}},address:s.spl}:void 0,o=s.native?{...zf,metadata:{...zf.metadata??{}},address:s.native}:void 0;try{this.splProgram=i?new sr.Program(i,this.provider):void 0,this.nativeProgram=o?new sr.Program(o,this.provider):void 0}catch(a){throw new Error("Error creating Program instances. Ensure the IDLs and provider are correct.",{cause:a})}}get htlcActorAddress(){if(!this.provider.publicKey)throw new Error("No provider public key found");return this.provider.publicKey.toBase58()}isNativeToken(t){return be.isSolanaNativeToken(t.source_swap.chain,t.source_swap.token_address)}async sendSplViaRelayer(t,r){try{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"),i=await v.Fetcher.post(this.url.endpoint("/initiate"),{body:JSON.stringify({order_id:r,serialized_tx:s}),headers:{"Content-Type":"application/json"}});return i.error||!i.result?v.Err(`Error from Relayer: ${i.error}`):await Tu(this.provider.connection,i.result)?v.Ok(i.result):v.Err("Relayer: Failed to Initiate swap, confirmation timed out")}catch(n){return v.Err(`Failed to send SPL transaction: ${n instanceof Error?n.message:String(n)}`)}}async initiateViaHTLC(t,r){if(!r)return v.Err("Order is required");try{const n=await this.provider.sendAndConfirm(t);return n?await Tu(this.provider.connection,n)?v.Ok(n):v.Err("HTLC: Failed to Initiate swap, confirmation timed out"):v.Err("Failed to initiate HTLC transaction")}catch(n){return v.Err(`Error initiating swap: ${n instanceof Error?n.message:String(n)}`)}}createSwapPDA(t,r){const n=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),t];return sr.web3.PublicKey.findProgramAddressSync(n,r)[0]}async initiateSplSwap(t){if(!this.splProgram)return v.Err("SPL program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=Wn.from(t),o=this.splProgram.methods.initiate(i,r,n,s,null),a=new sr.web3.PublicKey(t.source_swap.token_address),c={initiator:this.provider.publicKey,mint:a,initiatorTokenAccount:Y1.getAssociatedTokenAddressSync(a,this.provider.publicKey),sponsor:this.relayer},l=await o.accounts(c).transaction();return this.sendSplViaRelayer(l,t.create_order.create_id)}catch(r){return v.Err(`Error initiating SPL swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateNativeSwap(t){if(!this.nativeProgram)return v.Err("Native program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=Wn.from(t),o=await this.nativeProgram.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction();return this.initiateViaHTLC(o,t)}catch(r){return v.Err(`Error initiating native swap: ${r instanceof Error?r.message:String(r)}`)}}async initiate(t){if(!t)return v.Err("Order is required");try{return this.isNativeToken(t)?this.nativeProgram?await this.initiateNativeSwap(t):v.Err("Native program is not initialized"):this.splProgram?await this.initiateSplSwap(t):v.Err("SPL program is not initialized")}catch(r){return v.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(t,r){try{const n=vw(r),s={order_id:t.create_order.create_id,secret:Buffer.from(n).toString("hex")},i=await v.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify(s),headers:{"Content-Type":"application/json"}});if(i.error)return v.Err(`Redeem: Error from relayer: ${i.error}`);if(!i.result)return v.Err("Redeem: No transaction hash returned from relayer");const o=i.result;return await Tu(this.provider.connection,o)?v.Ok(o):v.Err("Redeem: Timed out waiting for confirmation")}catch(n){return console.error("Redeem: Caught exception:",n),v.Err(`Error redeeming: ${n instanceof Error?n.message:String(n)}`)}}async refund(){return v.Err("Refund is automatically handled by the relayer.")}}const Aw="1.37.2",yP="1.55.0",mP={"-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 xw extends Error{}class Sw extends xw{constructor(t,r){super(t),this.code=r,this.type=mP[r]??"ServerError"}}class gP extends xw{constructor(t,r,n){super(t),this.status=r,this.statusText=n}}var _w=e=>{throw TypeError(e)},ph=(e,t,r)=>t.has(e)||_w("Cannot "+r),Ue=(e,t,r)=>(ph(e,t,"read from private field"),r?r.call(e):t.get(e)),is=(e,t,r)=>t.has(e)?_w("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),pi=(e,t,r,n)=>(ph(e,t,"write to private field"),t.set(e,r),r),kw=(e,t,r)=>(ph(e,t,"access private method"),r),bP=(e,t,r,n)=>({set _(s){pi(e,t,s)},get _(){return Ue(e,t,n)}}),Ln,uo,ln,ps,Ho,ys,ic,Tw,Iw;function wP(e){const t=new URL(e);return t.protocol=t.protocol.replace("http","ws"),t.toString()}const vP={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5};class EP{constructor(t,r={}){if(is(this,ic),is(this,Ln,0),is(this,uo,0),is(this,ln,null),is(this,ps,null),is(this,Ho,new Set),is(this,ys,new Map),this.endpoint=t,this.options={...vP,...r},!this.options.WebSocketConstructor)throw new Error("Missing WebSocket constructor");this.endpoint.startsWith("http")&&(this.endpoint=wP(this.endpoint))}async makeRequest(t,r,n){const s=await kw(this,ic,Tw).call(this);return new Promise((i,o)=>{pi(this,Ln,Ue(this,Ln)+1),Ue(this,ys).set(Ue(this,Ln),{resolve:i,reject:o,timeout:setTimeout(()=>{Ue(this,ys).delete(Ue(this,Ln)),o(new Error(`Request timeout: ${t}`))},this.options.callTimeout)}),n==null||n.addEventListener("abort",()=>{Ue(this,ys).delete(Ue(this,Ln)),o(n.reason)}),s.send(JSON.stringify({jsonrpc:"2.0",id:Ue(this,Ln),method:t,params:r}))}).then(({error:i,result:o})=>{if(i)throw new Sw(i.message,i.code);return o})}async subscribe(t){const r=new AP(t);return Ue(this,Ho).add(r),await r.subscribe(this),()=>r.unsubscribe(this)}}Ln=new WeakMap;uo=new WeakMap;ln=new WeakMap;ps=new WeakMap;Ho=new WeakMap;ys=new WeakMap;ic=new WeakSet;Tw=function(){return Ue(this,ps)?Ue(this,ps):(pi(this,ps,new Promise(e=>{var t;(t=Ue(this,ln))==null||t.close(),pi(this,ln,new this.options.WebSocketConstructor(this.endpoint)),Ue(this,ln).addEventListener("open",()=>{pi(this,uo,0),e(Ue(this,ln))}),Ue(this,ln).addEventListener("close",()=>{bP(this,uo)._++,Ue(this,uo)<=this.options.maxReconnects&&setTimeout(()=>{kw(this,ic,Iw).call(this)},this.options.reconnectTimeout)}),Ue(this,ln).addEventListener("message",({data:r})=>{let n;try{n=JSON.parse(r)}catch(s){console.error(new Error(`Failed to parse RPC message: ${r}`,{cause:s}));return}if("id"in n&&n.id!=null&&Ue(this,ys).has(n.id)){const{resolve:s,timeout:i}=Ue(this,ys).get(n.id);clearTimeout(i),s(n)}else if("params"in n){const{params:s}=n;Ue(this,Ho).forEach(i=>{i.subscriptionId===s.subscription&&s.subscription===i.subscriptionId&&i.onMessage(s.result)})}})})),Ue(this,ps))};Iw=async function(){var e;return(e=Ue(this,ln))==null||e.close(),pi(this,ps,null),Promise.allSettled([...Ue(this,Ho)].map(t=>t.subscribe(this)))};class AP{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 Pw=e=>{throw TypeError(e)},yh=(e,t,r)=>t.has(e)||Pw("Cannot "+r),nr=(e,t,r)=>(yh(e,t,"read from private field"),r?r.call(e):t.get(e)),Ra=(e,t,r)=>t.has(e)?Pw("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Vf=(e,t,r,n)=>(yh(e,t,"write to private field"),t.set(e,r),r),xP=(e,t,r)=>(yh(e,t,"access private method"),r),Qi,yr,lo,Gf,Ow;class SP{constructor(t){Ra(this,Gf),Ra(this,Qi,0),Ra(this,yr),Ra(this,lo),Vf(this,yr,t)}fetch(t,r){const n=nr(this,yr).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 s,i;Vf(this,Qi,nr(this,Qi)+1);const r=await this.fetch(((s=nr(this,yr).rpc)==null?void 0:s.url)??nr(this,yr).url,{method:"POST",signal:t.signal,headers:{"Content-Type":"application/json","Client-Sdk-Type":"typescript","Client-Sdk-Version":Aw,"Client-Target-Api-Version":yP,"Client-Request-Method":t.method,...(i=nr(this,yr).rpc)==null?void 0:i.headers},body:JSON.stringify({jsonrpc:"2.0",id:nr(this,Qi),method:t.method,params:t.params})});if(!r.ok)throw new gP(`Unexpected status code: ${r.status}`,r.status,r.statusText);const n=await r.json();if("error"in n&&n.error!=null)throw new Sw(n.error.message,n.error.code);return n.result}async subscribe(t){const r=await xP(this,Gf,Ow).call(this).subscribe(t);return t.signal&&(t.signal.throwIfAborted(),t.signal.addEventListener("abort",()=>{r()})),async()=>!!await r()}}Qi=new WeakMap;yr=new WeakMap;lo=new WeakMap;Gf=new WeakSet;Ow=function(){var e;if(!nr(this,lo)){const t=nr(this,yr).WebSocketConstructor??WebSocket;if(!t)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");Vf(this,lo,new EP(((e=nr(this,yr).websocket)==null?void 0:e.url)??nr(this,yr).url,{WebSocketConstructor:t,...nr(this,yr).websocket}))}return nr(this,lo)};function _P(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 kP(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Bw(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 Wf(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function Cw(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function Kf(e){if(!Array.isArray(e))throw new Error("array expected")}function Rw(e,t){if(!Bw(!0,t))throw new Error(`${e}: array of strings expected`)}function TP(e,t){if(!Bw(!1,t))throw new Error(`${e}: array of numbers expected`)}function IP(...e){const t=i=>i,r=(i,o)=>a=>i(o(a)),n=e.map(i=>i.encode).reduceRight(r,t),s=e.map(i=>i.decode).reduce(r,t);return{encode:n,decode:s}}function PP(e){const t=typeof e=="string"?e.split(""):e,r=t.length;Rw("alphabet",t);const n=new Map(t.map((s,i)=>[s,i]));return{encode:s=>(Kf(s),s.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${e}`);return t[i]})),decode:s=>(Kf(s),s.map(i=>{Wf("alphabet.decode",i);const o=n.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${e}`);return o}))}}function OP(e=""){return Wf("join",e),{encode:t=>(Rw("join.decode",t),t.join(e)),decode:t=>(Wf("join.decode",t),t.split(e))}}function sm(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(Kf(e),!e.length)return[];let n=0;const s=[],i=Array.from(e,a=>{if(Cw(a),a<0||a>=t)throw new Error(`invalid integer: ${a}`);return a}),o=i.length;for(;;){let a=0,c=!0;for(let l=n;l<o;l++){const u=i[l],f=t*a,p=f+u;if(!Number.isSafeInteger(p)||f/t!==a||p-u!==f)throw new Error("convertRadix: carry overflow");const d=p/r;a=p%r;const m=Math.floor(d);if(i[l]=m,!Number.isSafeInteger(m)||m*r+a!==p)throw new Error("convertRadix: carry overflow");if(c)m?c=!1:n=l;else continue}if(s.push(a),c)break}for(let a=0;a<e.length-1&&e[a]===0;a++)s.push(0);return s.reverse()}function BP(e){Cw(e);const t=2**8;return{encode:r=>{if(!kP(r))throw new Error("radix.encode input should be Uint8Array");return sm(Array.from(r),t,e)},decode:r=>(TP("radix.decode",r),Uint8Array.from(sm(r,e,t)))}}const CP=e=>IP(BP(58),PP(e),OP("")),$w=CP("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),ru=e=>$w.encode(e),zo=e=>$w.decode(e);function zt(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}const zl=8192;function yt(e){if(e.length<zl)return btoa(String.fromCharCode(...e));let t="";for(var r=0;r<e.length;r+=zl){const n=e.slice(r,r+zl);t+=String.fromCharCode(...n)}return btoa(t)}function Nw(e){var s;const t=e.startsWith("0x")?e.slice(2):e,r=t.length%2===0?t:`0${t}`,n=((s=r.match(/[0-9a-fA-F]{2}/g))==null?void 0:s.map(i=>parseInt(i,16)))??[];if(n.length!==r.length/2)throw new Error(`Invalid hex string ${e}`);return Uint8Array.from(n)}function Si(e){return e.reduce((t,r)=>t+r.toString(16).padStart(2,"0"),"")}function nu(e,t){return Array.from({length:Math.ceil(e.length/t)},(r,n)=>e.slice(n*t,(n+1)*t))}class Uw{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=UP(r),this._batchScheduleFn=MP(r),this._cacheKeyFn=FP(r),this._cacheMap=jP(r),this._batch=null,this.name=LP(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=$P(this),n=this._cacheMap;let s;if(n){s=this._cacheKeyFn(t);const o=n.get(s);if(o){const a=r.cacheHits||(r.cacheHits=[]);return new Promise(c=>{a.push(()=>{c(o)})})}}r.keys.push(t);const i=new Promise((o,a)=>{r.callbacks.push({resolve:o,reject:a})});return n&&n.set(s,i),i}loadMany(t){if(!Mw(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(s=>s));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 s=this._cacheKeyFn(t);if(n.get(s)===void 0){let i;r instanceof Error?(i=Promise.reject(r),i.catch(()=>{})):i=Promise.resolve(r),n.set(s,i)}}return this}}const RP=typeof process=="object"&&typeof process.nextTick=="function"?function(e){ql||(ql=Promise.resolve()),ql.then(()=>{process.nextTick(e)})}:typeof setImmediate=="function"?function(e){setImmediate(e)}:function(e){setTimeout(e)};let ql;function $P(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(()=>{NP(e,r)}),r}function NP(e,t){if(t.hasDispatched=!0,t.keys.length===0){Xf(t);return}let r;try{r=e._batchLoadFn(t.keys)}catch(n){return Vl(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 Vl(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(!Mw(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.
|
|
99
|
+
`)+" "+L[1]:L[0]+N+" "+O.join(", ")+" "+L[1]}e.types=ZI();function w(O){return Array.isArray(O)}e.isArray=w;function A(O){return typeof O=="boolean"}e.isBoolean=A;function T(O){return O===null}e.isNull=T;function E(O){return O==null}e.isNullOrUndefined=E;function S(O){return typeof O=="number"}e.isNumber=S;function I(O){return typeof O=="string"}e.isString=I;function P(O){return typeof O=="symbol"}e.isSymbol=P;function $(O){return O===void 0}e.isUndefined=$;function j(O){return k(O)&&W(O)==="[object RegExp]"}e.isRegExp=j,e.types.isRegExp=j;function k(O){return typeof O=="object"&&O!==null}e.isObject=k;function F(O){return k(O)&&W(O)==="[object Date]"}e.isDate=F,e.types.isDate=F;function R(O){return k(O)&&(W(O)==="[object Error]"||O instanceof Error)}e.isError=R,e.types.isNativeError=R;function U(O){return typeof O=="function"}e.isFunction=U;function H(O){return O===null||typeof O=="boolean"||typeof O=="number"||typeof O=="string"||typeof O=="symbol"||typeof O>"u"}e.isPrimitive=H,e.isBuffer=JI();function W(O){return Object.prototype.toString.call(O)}function Z(O){return O<10?"0"+O.toString(10):O.toString(10)}var Q=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function re(){var O=new Date,N=[Z(O.getHours()),Z(O.getMinutes()),Z(O.getSeconds())].join(":");return[O.getDate(),Q[O.getMonth()],N].join(" ")}e.log=function(){console.log("%s - %s",re(),e.format.apply(e,arguments))},e.inherits=QI(),e._extend=function(O,N){if(!N||!k(N))return O;for(var L=Object.keys(N),J=L.length;J--;)O[L[J]]=N[L[J]];return O};function D(O,N){return Object.prototype.hasOwnProperty.call(O,N)}var B=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;e.promisify=function(N){if(typeof N!="function")throw new TypeError('The "original" argument must be of type Function');if(B&&N[B]){var L=N[B];if(typeof L!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(L,B,{value:L,enumerable:!1,writable:!1,configurable:!0}),L}function L(){for(var J,ne,fe=new Promise(function(ie,he){J=ie,ne=he}),ce=[],oe=0;oe<arguments.length;oe++)ce.push(arguments[oe]);ce.push(function(ie,he){ie?ne(ie):J(he)});try{N.apply(this,ce)}catch(ie){ne(ie)}return fe}return Object.setPrototypeOf(L,Object.getPrototypeOf(N)),B&&Object.defineProperty(L,B,{value:L,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(L,t(N))},e.promisify.custom=B;function V(O,N){if(!O){var L=new Error("Promise was rejected with a falsy value");L.reason=O,O=L}return N(O)}function K(O){if(typeof O!="function")throw new TypeError('The "original" argument must be of type Function');function N(){for(var L=[],J=0;J<arguments.length;J++)L.push(arguments[J]);var ne=L.pop();if(typeof ne!="function")throw new TypeError("The last argument must be of type Function");var fe=this,ce=function(){return ne.apply(fe,arguments)};O.apply(this,L).then(function(oe){process.nextTick(ce.bind(null,null,oe))},function(oe){process.nextTick(V.bind(null,oe,ce))})}return Object.setPrototypeOf(N,Object.getPrototypeOf(O)),Object.defineProperties(N,t(O)),N}e.callbackify=K}(zu)),zu}Object.defineProperty(Yc,"__esModule",{value:!0});Yc.decode=eP;Yc.encode=tP;const gw=$s;function eP(e){return(gw.isBrowser?new TextDecoder("utf-8"):new(mw()).TextDecoder("utf-8")).decode(e)}function tP(e){return(gw.isBrowser?new TextEncoder:new(mw()).TextEncoder("utf-8")).encode(e)}var Qc={},qf={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(e,t){var r=Hs,n=r.Buffer;function s(o,a){for(var c in o)a[c]=o[c]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(s(r,t),t.Buffer=i);function i(o,a,c){return n(o,a,c)}i.prototype=Object.create(n.prototype),s(n,i),i.from=function(o,a,c){if(typeof o=="number")throw new TypeError("Argument must not be a number");return n(o,a,c)},i.alloc=function(o,a,c){if(typeof o!="number")throw new TypeError("Argument must be a number");var l=n(o);return a!==void 0?typeof c=="string"?l.fill(a,c):l.fill(a):l.fill(0),l},i.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return n(o)},i.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(o)}})(qf,qf.exports);var rP=qf.exports,Ca=rP.Buffer;function nP(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 s=e.charAt(n),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=n}var o=e.length,a=e.charAt(0),c=Math.log(o)/Math.log(256),l=Math.log(256)/Math.log(o);function u(d){if((Array.isArray(d)||d instanceof Uint8Array)&&(d=Ca.from(d)),!Ca.isBuffer(d))throw new TypeError("Expected Buffer");if(d.length===0)return"";for(var m=0,g=0,w=0,A=d.length;w!==A&&d[w]===0;)w++,m++;for(var T=(A-w)*l+1>>>0,E=new Uint8Array(T);w!==A;){for(var S=d[w],I=0,P=T-1;(S!==0||I<g)&&P!==-1;P--,I++)S+=256*E[P]>>>0,E[P]=S%o>>>0,S=S/o>>>0;if(S!==0)throw new Error("Non-zero carry");g=I,w++}for(var $=T-g;$!==T&&E[$]===0;)$++;for(var j=a.repeat(m);$<T;++$)j+=e.charAt(E[$]);return j}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return Ca.alloc(0);for(var m=0,g=0,w=0;d[m]===a;)g++,m++;for(var A=(d.length-m)*c+1>>>0,T=new Uint8Array(A);m<d.length;){var E=d.charCodeAt(m);if(E>255)return;var S=t[E];if(S===255)return;for(var I=0,P=A-1;(S!==0||I<w)&&P!==-1;P--,I++)S+=o*T[P]>>>0,T[P]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");w=I,m++}for(var $=A-w;$!==A&&T[$]===0;)$++;var j=Ca.allocUnsafe(g+(A-$));j.fill(0,0,g);for(var k=g;$!==A;)j[k++]=T[$++];return j}function p(d){var m=f(d);if(m)return m;throw new Error("Non-base"+o+" character")}return{encode:u,decodeUnsafe:f,decode:p}}var sP=nP,iP=sP,oP="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",aP=iP(oP),cP=Kr&&Kr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Qc,"__esModule",{value:!0});Qc.encode=uP;Qc.decode=lP;const bw=cP(aP);function uP(e){return bw.default.encode(e)}function lP(e){return bw.default.decode(e)}var eu={};Object.defineProperty(eu,"__esModule",{value:!0});eu.encode=dP;eu.decode=hP;const fP=Hs;function dP(e){return e.toString("base64")}function hP(e){return fP.Buffer.from(e,"base64")}var pP=Kr&&Kr.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),yP=Kr&&Kr.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),tu=Kr&&Kr.__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)&&pP(t,e,r);return yP(t,e),t};Object.defineProperty(hn,"__esModule",{value:!0});hn.base64=hn.bs58=hn.utf8=ww=hn.hex=void 0;var ww=hn.hex=tu(Xc);hn.utf8=tu(Yc);hn.bs58=tu(Qc);hn.base64=tu(eu);class Wn{constructor(t,r,n,s,i){try{this.swapId=Array.from(Buffer.from(t,"hex")),this.secretHash=Array.from(Buffer.from(n,"hex"))}catch(o){throw new Error("Error decoding swapId or secretHash",{cause:o})}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 sr.web3.PublicKey(r)}catch(o){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:o})}try{this.amount=new sr.BN(s.toString(10),10),this.expiresIn=new sr.BN(i)}catch(o){throw new Error("Error decoding amount. Invalid value for amount",{cause:o})}if(!(Number.isInteger(i)&&i>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:s,secret_hash:i,timelock:o}=r,a=BigInt(r.amount);return new Wn(n,s,i,a,o)}}function vw(e){let t;try{t=[...ww.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 Ew{constructor(t,r,n,s){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)throw new Error("Relayer address is required");try{this.relayer=new sr.web3.PublicKey(n)}catch(a){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:a})}const i=s.spl?{...ty,metadata:{...ty.metadata??{}},address:s.spl}:void 0,o=s.native?{...zf,metadata:{...zf.metadata??{}},address:s.native}:void 0;try{this.splProgram=i?new sr.Program(i,this.provider):void 0,this.nativeProgram=o?new sr.Program(o,this.provider):void 0}catch(a){throw new Error("Error creating Program instances. Ensure the IDLs and provider are correct.",{cause:a})}}get htlcActorAddress(){if(!this.provider.publicKey)throw new Error("No provider public key found");return this.provider.publicKey.toBase58()}isNativeToken(t){return be.isSolanaNativeToken(t.source_swap.chain,t.source_swap.token_address)}async sendSplViaRelayer(t,r){try{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"),i=await v.Fetcher.post(this.url.endpoint("/initiate"),{body:JSON.stringify({order_id:r,serialized_tx:s}),headers:{"Content-Type":"application/json"}});return i.error||!i.result?v.Err(`Error from Relayer: ${i.error}`):await Tu(this.provider.connection,i.result)?v.Ok(i.result):v.Err("Relayer: Failed to Initiate swap, confirmation timed out")}catch(n){return v.Err(`Failed to send SPL transaction: ${n instanceof Error?n.message:String(n)}`)}}async initiateViaHTLC(t,r){if(!r)return v.Err("Order is required");try{const n=await this.provider.sendAndConfirm(t);return n?await Tu(this.provider.connection,n)?v.Ok(n):v.Err("HTLC: Failed to Initiate swap, confirmation timed out"):v.Err("Failed to initiate HTLC transaction")}catch(n){return v.Err(`Error initiating swap: ${n instanceof Error?n.message:String(n)}`)}}createSwapPDA(t,r){const n=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),t];return sr.web3.PublicKey.findProgramAddressSync(n,r)[0]}async initiateSplSwap(t){if(!this.splProgram)return v.Err("SPL program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=Wn.from(t),o=this.splProgram.methods.initiate(i,r,n,s,null),a=new sr.web3.PublicKey(t.source_swap.token_address),c={initiator:this.provider.publicKey,mint:a,initiatorTokenAccount:Y1.getAssociatedTokenAddressSync(a,this.provider.publicKey),sponsor:this.relayer},l=await o.accounts(c).transaction();return this.sendSplViaRelayer(l,t.create_order.create_id)}catch(r){return v.Err(`Error initiating SPL swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateNativeSwap(t){if(!this.nativeProgram)return v.Err("Native program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=Wn.from(t),o=await this.nativeProgram.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction();return this.initiateViaHTLC(o,t)}catch(r){return v.Err(`Error initiating native swap: ${r instanceof Error?r.message:String(r)}`)}}async initiate(t){if(!t)return v.Err("Order is required");try{return this.isNativeToken(t)?this.nativeProgram?await this.initiateNativeSwap(t):v.Err("Native program is not initialized"):this.splProgram?await this.initiateSplSwap(t):v.Err("SPL program is not initialized")}catch(r){return v.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(t,r){try{const n=vw(r),s={order_id:t.create_order.create_id,secret:Buffer.from(n).toString("hex")},i=await v.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify(s),headers:{"Content-Type":"application/json"}});if(i.error)return v.Err(`Redeem: Error from relayer: ${i.error}`);if(!i.result)return v.Err("Redeem: No transaction hash returned from relayer");const o=i.result;return await Tu(this.provider.connection,o)?v.Ok(o):v.Err("Redeem: Timed out waiting for confirmation")}catch(n){return console.error("Redeem: Caught exception:",n),v.Err(`Error redeeming: ${n instanceof Error?n.message:String(n)}`)}}async refund(){return v.Err("Refund is automatically handled by the relayer.")}}const Aw="1.37.2",mP="1.55.0",gP={"-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 xw extends Error{}class Sw extends xw{constructor(t,r){super(t),this.code=r,this.type=gP[r]??"ServerError"}}class bP extends xw{constructor(t,r,n){super(t),this.status=r,this.statusText=n}}var _w=e=>{throw TypeError(e)},ph=(e,t,r)=>t.has(e)||_w("Cannot "+r),Ue=(e,t,r)=>(ph(e,t,"read from private field"),r?r.call(e):t.get(e)),is=(e,t,r)=>t.has(e)?_w("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),pi=(e,t,r,n)=>(ph(e,t,"write to private field"),t.set(e,r),r),kw=(e,t,r)=>(ph(e,t,"access private method"),r),wP=(e,t,r,n)=>({set _(s){pi(e,t,s)},get _(){return Ue(e,t,n)}}),Ln,uo,ln,ps,Ho,ys,ic,Tw,Iw;function vP(e){const t=new URL(e);return t.protocol=t.protocol.replace("http","ws"),t.toString()}const EP={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5};class AP{constructor(t,r={}){if(is(this,ic),is(this,Ln,0),is(this,uo,0),is(this,ln,null),is(this,ps,null),is(this,Ho,new Set),is(this,ys,new Map),this.endpoint=t,this.options={...EP,...r},!this.options.WebSocketConstructor)throw new Error("Missing WebSocket constructor");this.endpoint.startsWith("http")&&(this.endpoint=vP(this.endpoint))}async makeRequest(t,r,n){const s=await kw(this,ic,Tw).call(this);return new Promise((i,o)=>{pi(this,Ln,Ue(this,Ln)+1),Ue(this,ys).set(Ue(this,Ln),{resolve:i,reject:o,timeout:setTimeout(()=>{Ue(this,ys).delete(Ue(this,Ln)),o(new Error(`Request timeout: ${t}`))},this.options.callTimeout)}),n==null||n.addEventListener("abort",()=>{Ue(this,ys).delete(Ue(this,Ln)),o(n.reason)}),s.send(JSON.stringify({jsonrpc:"2.0",id:Ue(this,Ln),method:t,params:r}))}).then(({error:i,result:o})=>{if(i)throw new Sw(i.message,i.code);return o})}async subscribe(t){const r=new xP(t);return Ue(this,Ho).add(r),await r.subscribe(this),()=>r.unsubscribe(this)}}Ln=new WeakMap;uo=new WeakMap;ln=new WeakMap;ps=new WeakMap;Ho=new WeakMap;ys=new WeakMap;ic=new WeakSet;Tw=function(){return Ue(this,ps)?Ue(this,ps):(pi(this,ps,new Promise(e=>{var t;(t=Ue(this,ln))==null||t.close(),pi(this,ln,new this.options.WebSocketConstructor(this.endpoint)),Ue(this,ln).addEventListener("open",()=>{pi(this,uo,0),e(Ue(this,ln))}),Ue(this,ln).addEventListener("close",()=>{wP(this,uo)._++,Ue(this,uo)<=this.options.maxReconnects&&setTimeout(()=>{kw(this,ic,Iw).call(this)},this.options.reconnectTimeout)}),Ue(this,ln).addEventListener("message",({data:r})=>{let n;try{n=JSON.parse(r)}catch(s){console.error(new Error(`Failed to parse RPC message: ${r}`,{cause:s}));return}if("id"in n&&n.id!=null&&Ue(this,ys).has(n.id)){const{resolve:s,timeout:i}=Ue(this,ys).get(n.id);clearTimeout(i),s(n)}else if("params"in n){const{params:s}=n;Ue(this,Ho).forEach(i=>{i.subscriptionId===s.subscription&&s.subscription===i.subscriptionId&&i.onMessage(s.result)})}})})),Ue(this,ps))};Iw=async function(){var e;return(e=Ue(this,ln))==null||e.close(),pi(this,ps,null),Promise.allSettled([...Ue(this,Ho)].map(t=>t.subscribe(this)))};class xP{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 Pw=e=>{throw TypeError(e)},yh=(e,t,r)=>t.has(e)||Pw("Cannot "+r),nr=(e,t,r)=>(yh(e,t,"read from private field"),r?r.call(e):t.get(e)),Ra=(e,t,r)=>t.has(e)?Pw("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Vf=(e,t,r,n)=>(yh(e,t,"write to private field"),t.set(e,r),r),SP=(e,t,r)=>(yh(e,t,"access private method"),r),Qi,yr,lo,Gf,Ow;class _P{constructor(t){Ra(this,Gf),Ra(this,Qi,0),Ra(this,yr),Ra(this,lo),Vf(this,yr,t)}fetch(t,r){const n=nr(this,yr).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 s,i;Vf(this,Qi,nr(this,Qi)+1);const r=await this.fetch(((s=nr(this,yr).rpc)==null?void 0:s.url)??nr(this,yr).url,{method:"POST",signal:t.signal,headers:{"Content-Type":"application/json","Client-Sdk-Type":"typescript","Client-Sdk-Version":Aw,"Client-Target-Api-Version":mP,"Client-Request-Method":t.method,...(i=nr(this,yr).rpc)==null?void 0:i.headers},body:JSON.stringify({jsonrpc:"2.0",id:nr(this,Qi),method:t.method,params:t.params})});if(!r.ok)throw new bP(`Unexpected status code: ${r.status}`,r.status,r.statusText);const n=await r.json();if("error"in n&&n.error!=null)throw new Sw(n.error.message,n.error.code);return n.result}async subscribe(t){const r=await SP(this,Gf,Ow).call(this).subscribe(t);return t.signal&&(t.signal.throwIfAborted(),t.signal.addEventListener("abort",()=>{r()})),async()=>!!await r()}}Qi=new WeakMap;yr=new WeakMap;lo=new WeakMap;Gf=new WeakSet;Ow=function(){var e;if(!nr(this,lo)){const t=nr(this,yr).WebSocketConstructor??WebSocket;if(!t)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");Vf(this,lo,new AP(((e=nr(this,yr).websocket)==null?void 0:e.url)??nr(this,yr).url,{WebSocketConstructor:t,...nr(this,yr).websocket}))}return nr(this,lo)};function kP(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 TP(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Bw(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 Wf(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function Cw(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function Kf(e){if(!Array.isArray(e))throw new Error("array expected")}function Rw(e,t){if(!Bw(!0,t))throw new Error(`${e}: array of strings expected`)}function IP(e,t){if(!Bw(!1,t))throw new Error(`${e}: array of numbers expected`)}function PP(...e){const t=i=>i,r=(i,o)=>a=>i(o(a)),n=e.map(i=>i.encode).reduceRight(r,t),s=e.map(i=>i.decode).reduce(r,t);return{encode:n,decode:s}}function OP(e){const t=typeof e=="string"?e.split(""):e,r=t.length;Rw("alphabet",t);const n=new Map(t.map((s,i)=>[s,i]));return{encode:s=>(Kf(s),s.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${e}`);return t[i]})),decode:s=>(Kf(s),s.map(i=>{Wf("alphabet.decode",i);const o=n.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${e}`);return o}))}}function BP(e=""){return Wf("join",e),{encode:t=>(Rw("join.decode",t),t.join(e)),decode:t=>(Wf("join.decode",t),t.split(e))}}function sm(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(Kf(e),!e.length)return[];let n=0;const s=[],i=Array.from(e,a=>{if(Cw(a),a<0||a>=t)throw new Error(`invalid integer: ${a}`);return a}),o=i.length;for(;;){let a=0,c=!0;for(let l=n;l<o;l++){const u=i[l],f=t*a,p=f+u;if(!Number.isSafeInteger(p)||f/t!==a||p-u!==f)throw new Error("convertRadix: carry overflow");const d=p/r;a=p%r;const m=Math.floor(d);if(i[l]=m,!Number.isSafeInteger(m)||m*r+a!==p)throw new Error("convertRadix: carry overflow");if(c)m?c=!1:n=l;else continue}if(s.push(a),c)break}for(let a=0;a<e.length-1&&e[a]===0;a++)s.push(0);return s.reverse()}function CP(e){Cw(e);const t=2**8;return{encode:r=>{if(!TP(r))throw new Error("radix.encode input should be Uint8Array");return sm(Array.from(r),t,e)},decode:r=>(IP("radix.decode",r),Uint8Array.from(sm(r,e,t)))}}const RP=e=>PP(CP(58),OP(e),BP("")),$w=RP("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),ru=e=>$w.encode(e),zo=e=>$w.decode(e);function zt(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}const zl=8192;function mt(e){if(e.length<zl)return btoa(String.fromCharCode(...e));let t="";for(var r=0;r<e.length;r+=zl){const n=e.slice(r,r+zl);t+=String.fromCharCode(...n)}return btoa(t)}function Nw(e){var s;const t=e.startsWith("0x")?e.slice(2):e,r=t.length%2===0?t:`0${t}`,n=((s=r.match(/[0-9a-fA-F]{2}/g))==null?void 0:s.map(i=>parseInt(i,16)))??[];if(n.length!==r.length/2)throw new Error(`Invalid hex string ${e}`);return Uint8Array.from(n)}function Si(e){return e.reduce((t,r)=>t+r.toString(16).padStart(2,"0"),"")}function nu(e,t){return Array.from({length:Math.ceil(e.length/t)},(r,n)=>e.slice(n*t,(n+1)*t))}class Uw{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=MP(r),this._batchScheduleFn=FP(r),this._cacheKeyFn=jP(r),this._cacheMap=LP(r),this._batch=null,this.name=DP(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=NP(this),n=this._cacheMap;let s;if(n){s=this._cacheKeyFn(t);const o=n.get(s);if(o){const a=r.cacheHits||(r.cacheHits=[]);return new Promise(c=>{a.push(()=>{c(o)})})}}r.keys.push(t);const i=new Promise((o,a)=>{r.callbacks.push({resolve:o,reject:a})});return n&&n.set(s,i),i}loadMany(t){if(!Mw(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(s=>s));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 s=this._cacheKeyFn(t);if(n.get(s)===void 0){let i;r instanceof Error?(i=Promise.reject(r),i.catch(()=>{})):i=Promise.resolve(r),n.set(s,i)}}return this}}const $P=typeof process=="object"&&typeof process.nextTick=="function"?function(e){ql||(ql=Promise.resolve()),ql.then(()=>{process.nextTick(e)})}:typeof setImmediate=="function"?function(e){setImmediate(e)}:function(e){setTimeout(e)};let ql;function NP(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(()=>{UP(e,r)}),r}function UP(e,t){if(t.hasDispatched=!0,t.keys.length===0){Xf(t);return}let r;try{r=e._batchLoadFn(t.keys)}catch(n){return Vl(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 Vl(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(!Mw(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.
|
|
100
100
|
|
|
101
101
|
Keys:
|
|
102
102
|
${String(t.keys)}
|
|
103
103
|
|
|
104
104
|
Values:
|
|
105
|
-
${String(n)}`);Xf(t);for(let s=0;s<t.callbacks.length;s++){const i=n[s];i instanceof Error?t.callbacks[s].reject(i):t.callbacks[s].resolve(i)}}).catch(n=>{Vl(e,t,n)})}function Vl(e,t,r){Xf(t);for(let n=0;n<t.keys.length;n++)e.clear(t.keys[n]),t.callbacks[n].reject(r)}function Xf(e){if(e.cacheHits)for(let t=0;t<e.cacheHits.length;t++)e.cacheHits[t]()}function UP(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 MP(e){const t=e&&e.batchScheduleFn;if(t===void 0)return RP;if(typeof t!="function")throw new TypeError(`batchScheduleFn must be a function: ${t}`);return t}function FP(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 jP(e){if(!(!e||e.cache!==!1))return null;const r=e&&e.cacheMap;if(r===void 0)return new Map;if(r!==null){const s=["get","set","delete","clear"].filter(i=>r&&typeof r[i]!="function");if(s.length!==0)throw new TypeError("Custom cacheMap missing methods: "+s.join(", "))}return r}function LP(e){return e&&e.name?e.name:null}function Mw(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 oc(e){const t=[];let r=0;if(e===0)return[0];for(;e>0;)t[r]=e&127,(e>>=7)&&(t[r]|=128),r+=1;return t}function DP(e){let t=0,r=0,n=0;for(;;){const s=e[n];if(n+=1,t|=(s&127)<<r,!(s&128))break;r+=7}return{value:t,length:n}}class HP{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:s}=DP(r);return this.shift(s),n}readVec(t){const r=this.readULEB(),n=[];for(let s=0;s<r;s++)n.push(t(this,s,r));return n}}function zP(e,t){switch(t){case"base58":return ru(e);case"base64":return yt(e);case"hex":return Si(e);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}function Fw(e,t=["<",">"]){const[r,n]=t,s=[];let i="",o=0;for(let a=0;a<e.length;a++){const c=e[a];if(c===r&&o++,c===n&&o--,o===0&&c===","){s.push(i.trim()),i="";continue}i+=c}return s.push(i.trim()),s}class qP{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,this.size+this.allocateSize);if(r>n)throw new Error(`Attempting to serialize to BCS, but buffer does not have enough size. Allocated size: ${this.size}, Max size: ${this.maxSize}, Required size: ${r}`);this.size=n;const s=new ArrayBuffer(this.size);new Uint8Array(s).set(new Uint8Array(this.dataView.buffer)),this.dataView=new DataView(s)}}shift(t){return this.bytePosition+=t,this}write8(t){return this.ensureSizeOrGrow(1),this.dataView.setUint8(this.bytePosition,Number(t)),this.shift(1)}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 Gl(BigInt(t),8).forEach(r=>this.write8(r)),this}write128(t){return Gl(BigInt(t),16).forEach(r=>this.write8(r)),this}write256(t){return Gl(BigInt(t),32).forEach(r=>this.write8(r)),this}writeULEB(t){return oc(t).forEach(r=>this.write8(r)),this}writeVec(t,r){return this.writeULEB(t.length),Array.from(t).forEach((n,s)=>r(this,n,s,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 zP(this.toBytes(),t)}}function Gl(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 jw=e=>{throw TypeError(e)},Lw=(e,t,r)=>t.has(e)||jw("Cannot "+r),mr=(e,t,r)=>(Lw(e,t,"read from private field"),r?r.call(e):t.get(e)),ac=(e,t,r)=>t.has(e)?jw("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),cc=(e,t,r,n)=>(Lw(e,t,"write to private field"),t.set(e,r),r),ni,eo,Wa,Dn;const VP=class Dw{constructor(t){ac(this,ni),ac(this,eo),this.name=t.name,this.read=t.read,this.serializedSize=t.serializedSize??(()=>null),cc(this,ni,t.write),cc(this,eo,t.serialize??((r,n)=>{const s=new qP({initialSize:this.serializedSize(r)??void 0,...n});return mr(this,ni).call(this,r,s),s.toBytes()})),this.validate=t.validate??(()=>{})}write(t,r){this.validate(t),mr(this,ni).call(this,t,r)}serialize(t,r){return this.validate(t),new GP(this,mr(this,eo).call(this,t,r))}parse(t){const r=new HP(t);return this.read(r)}fromHex(t){return this.parse(Nw(t))}fromBase58(t){return this.parse(zo(t))}fromBase64(t){return this.parse(zt(t))}transform({name:t,input:r,output:n,validate:s}){return new Dw({name:t??this.name,read:i=>n?n(this.read(i)):this.read(i),write:(i,o)=>mr(this,ni).call(this,r?r(i):i,o),serializedSize:i=>this.serializedSize(r?r(i):i),serialize:(i,o)=>mr(this,eo).call(this,r?r(i):i,o),validate:i=>{s==null||s(i),this.validate(r?r(i):i)}})}};ni=new WeakMap;eo=new WeakMap;let Xr=VP;const Hw=Symbol.for("@mysten/serialized-bcs");function mh(e){return!!e&&typeof e=="object"&&e[Hw]===!0}class GP{constructor(t,r){ac(this,Wa),ac(this,Dn),cc(this,Wa,t),cc(this,Dn,r)}get[Hw](){return!0}toBytes(){return mr(this,Dn)}toHex(){return Si(mr(this,Dn))}toBase64(){return yt(mr(this,Dn))}toBase58(){return ru(mr(this,Dn))}parse(){return mr(this,Wa).parse(mr(this,Dn))}}Wa=new WeakMap;Dn=new WeakMap;function uc({size:e,...t}){return new Xr({...t,serializedSize:()=>e})}function Wl({readMethod:e,writeMethod:t,...r}){return uc({...r,read:n=>n[e](),write:(n,s)=>s[t](n),validate:n=>{var s;if(n<0||n>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${n}. Expected value in range 0-${r.maxValue}`);(s=r.validate)==null||s.call(r,n)}})}function Kl({readMethod:e,writeMethod:t,...r}){return uc({...r,read:n=>n[e](),write:(n,s)=>s[t](BigInt(n)),validate:n=>{var i;const s=BigInt(n);if(s<0||s>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${s}. Expected value in range 0-${r.maxValue}`);(i=r.validate)==null||i.call(r,s)}})}function WP({serialize:e,...t}){const r=new Xr({...t,serialize:e,write:(n,s)=>{for(const i of r.serialize(n).toBytes())s.write8(i)}});return r}function KP({toBytes:e,fromBytes:t,...r}){return new Xr({...r,read:n=>{const s=n.readULEB(),i=n.readBytes(s);return t(i)},write:(n,s)=>{const i=e(n);s.writeULEB(i.length);for(let o=0;o<i.length;o++)s.write8(i[o])},serialize:n=>{const s=e(n),i=oc(s.length),o=new Uint8Array(i.length+s.length);return o.set(i,0),o.set(s,i.length),o},validate:n=>{var s;if(typeof n!="string")throw new TypeError(`Invalid ${r.name} value: ${n}. Expected string`);(s=r.validate)==null||s.call(r,n)}})}function XP(e){let t=null;function r(){return t||(t=e()),t}return new Xr({name:"lazy",read:n=>r().read(n),serializedSize:n=>r().serializedSize(n),write:(n,s)=>r().write(n,s),serialize:(n,s)=>r().serialize(n,s).toBytes()})}class YP extends Xr{constructor({name:t,fields:r,...n}){const s=Object.entries(r);super({name:t,serializedSize:i=>{let o=0;for(const[a,c]of s){const l=c.serializedSize(i[a]);if(l==null)return null;o+=l}return o},read:i=>{const o={};for(const[a,c]of s)o[a]=c.read(i);return o},write:(i,o)=>{for(const[a,c]of s)c.write(i[a],o)},...n,validate:i=>{var o;if((o=n==null?void 0:n.validate)==null||o.call(n,i),typeof i!="object"||i==null)throw new TypeError(`Expected object, found ${typeof i}`)}})}}class ZP extends Xr{constructor({fields:t,...r}){const n=Object.entries(t);super({read:s=>{const i=s.readULEB(),o=n[i];if(!o)throw new TypeError(`Unknown value ${i} for enum ${name}`);const[a,c]=o;return{[a]:(c==null?void 0:c.read(s))??!0,$kind:a}},write:(s,i)=>{const[o,a]=Object.entries(s).filter(([c])=>Object.hasOwn(t,c))[0];for(let c=0;c<n.length;c++){const[l,u]=n[c];if(l===o){i.writeULEB(c),u==null||u.write(a,i);return}}},...r,validate:s=>{var a;if((a=r==null?void 0:r.validate)==null||a.call(r,s),typeof s!="object"||s==null)throw new TypeError(`Expected object, found ${typeof s}`);const i=Object.keys(s).filter(c=>s[c]!==void 0&&Object.hasOwn(t,c));if(i.length!==1)throw new TypeError(`Expected object with one key, but found ${i.length} for type ${name}}`);const[o]=i;if(!Object.hasOwn(t,o))throw new TypeError(`Invalid enum variant ${o}`)}})}}class JP extends Xr{constructor({fields:t,name:r,...n}){super({name:r??`(${t.map(s=>s.name).join(", ")})`,serializedSize:s=>{let i=0;for(let o=0;o<t.length;o++){const a=t[o].serializedSize(s[o]);if(a==null)return null;i+=a}return i},read:s=>{const i=[];for(const o of t)i.push(o.read(s));return i},write:(s,i)=>{for(let o=0;o<t.length;o++)t[o].write(s[o],i)},...n,validate:s=>{var i;if((i=n==null?void 0:n.validate)==null||i.call(n,s),!Array.isArray(s))throw new TypeError(`Expected array, found ${typeof s}`);if(s.length!==t.length)throw new TypeError(`Expected array of length ${t.length}, found ${s.length}`)}})}}function QP(e,t,r){return new Xr({read:n=>{const s=new Array(e);for(let i=0;i<e;i++)s[i]=t.read(n);return s},write:(n,s)=>{for(const i of n)t.write(i,s)},...r,name:(r==null?void 0:r.name)??`${t.name}[${e}]`,validate:n=>{var s;if((s=r==null?void 0:r.validate)==null||s.call(r,n),!n||typeof n!="object"||!("length"in n))throw new TypeError(`Expected array, found ${typeof n}`);if(n.length!==e)throw new TypeError(`Expected array of length ${e}, found ${n.length}`)}})}function e5(e){return _.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 t5(e,t){return new Xr({read:r=>{const n=r.readULEB(),s=new Array(n);for(let i=0;i<n;i++)s[i]=e.read(r);return s},write:(r,n)=>{n.writeULEB(r.length);for(const s of r)e.write(s,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 r5(e,t){return _.vector(_.tuple([e,t])).transform({name:`Map<${e.name}, ${t.name}>`,input:r=>[...r.entries()],output:r=>{const n=new Map;for(const[s,i]of r)n.set(s,i);return n}})}const _={u8(e){return Wl({readMethod:"read8",writeMethod:"write8",size:1,maxValue:2**8-1,...e,name:(e==null?void 0:e.name)??"u8"})},u16(e){return Wl({readMethod:"read16",writeMethod:"write16",size:2,maxValue:2**16-1,...e,name:(e==null?void 0:e.name)??"u16"})},u32(e){return Wl({readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...e,name:(e==null?void 0:e.name)??"u32"})},u64(e){return Kl({readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...e,name:(e==null?void 0:e.name)??"u64"})},u128(e){return Kl({readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...e,name:(e==null?void 0:e.name)??"u128"})},u256(e){return Kl({readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...e,name:(e==null?void 0:e.name)??"u256"})},bool(e){return uc({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 WP({read:t=>t.readULEB(),serialize:t=>Uint8Array.from(oc(t)),...e,name:(e==null?void 0:e.name)??"uleb128"})},bytes(e,t){return uc({size:e,read:r=>r.readBytes(e),write:(r,n)=>{const s=new Uint8Array(r);for(let i=0;i<e;i++)n.write8(s[i]??0)},...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 Xr({read:t=>{const r=t.readULEB();return t.readBytes(r)},write:(t,r)=>{const n=new Uint8Array(t);r.writeULEB(n.length);for(let s=0;s<n.length;s++)r.write8(n[s]??0)},...e,name:(e==null?void 0:e.name)??"vector<u8>",serializedSize:t=>{const r="length"in t?t.length:null;return r==null?null:oc(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 KP({toBytes:t=>new TextEncoder().encode(t),fromBytes:t=>new TextDecoder().decode(t),...e,name:(e==null?void 0:e.name)??"string"})},fixedArray:QP,option:e5,vector:t5,tuple(e,t){return new JP({fields:e,...t})},struct(e,t,r){return new YP({name:e,fields:t,...r})},enum(e,t,r){return new ZP({name:e,fields:t,...r})},map:r5,lazy(e){return XP(e)}};var zw=e=>{throw TypeError(e)},qw=(e,t,r)=>t.has(e)||zw("Cannot "+r),ht=(e,t,r)=>(qw(e,t,"read from private field"),t.get(e)),im=(e,t,r)=>t.has(e)?zw("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),om=(e,t,r,n)=>(qw(e,t,"write to private field"),t.set(e,r),r),cs,kt;const n5=class Vw{constructor({prefix:t,cache:r}={}){im(this,cs),im(this,kt),om(this,cs,t??[]),om(this,kt,r??new Map)}read(t,r){const n=[ht(this,cs),...t].join(":");if(ht(this,kt).has(n))return ht(this,kt).get(n);const s=r();return ht(this,kt).set(n,s),typeof s=="object"&&s!==null&&"then"in s?Promise.resolve(s).then(i=>(ht(this,kt).set(n,i),i)).catch(i=>{throw ht(this,kt).delete(n),i}):s}readSync(t,r){const n=[ht(this,cs),...t].join(":");if(ht(this,kt).has(n))return ht(this,kt).get(n);const s=r();return ht(this,kt).set(n,s),s}clear(t){const r=[...ht(this,cs),...t??[]].join(":");if(!r){ht(this,kt).clear();return}for(const n of ht(this,kt).keys())n.startsWith(r)&&ht(this,kt).delete(n)}scope(t){return new Vw({prefix:[...ht(this,cs),...Array.isArray(t)?t:[t]],cache:ht(this,kt)})}};cs=new WeakMap;kt=new WeakMap;let s5=n5;class Gw{constructor({network:t,base:r,cache:n=(r==null?void 0:r.cache)??new s5}){this.network=t,this.base=r??this,this.cache=n}$extend(...t){return Object.create(this,Object.fromEntries(t.map(r=>{if("experimental_asClientExtension"in r){const{name:n,register:s}=r.experimental_asClientExtension();return[n,{value:s(this)}]}return[r.name,{value:r.register(this)}]})))}}const Ww=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,Kw=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i,i5=235;function o5(e){return e.length>i5?!1:e.includes("@")?Ww.test(e):Kw.test(e)}function a5(e,t="at"){const r=e.toLowerCase();let n;if(r.includes("@")){if(!Ww.test(r))throw new Error(`Invalid SuiNS name ${e}`);const[s,i]=r.split("@");n=[...s?s.split("."):[],i]}else{if(!Kw.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 c5=/^([a-z0-9]+(?:-[a-z0-9]+)*)$/,u5=/^\d+$/,l5=64,Xw="/",Dt=e=>{const t=e.split(Xw);if(t.length<2||t.length>3)return!1;const[r,n,s]=t;return s!==void 0&&!u5.test(s)||!o5(r)?!1:c5.test(n)&&n.length<l5},f5=e=>{const t=e.split(/::|<|>|,/);for(const r of t)if(r.includes(Xw)&&!Dt(r))return!1;return!0},d5=32;function am(e){try{return zo(e).length===d5}catch{return!1}}const su=32;function gr(e){return p5(e)&&y5(e)===su}function $a(e){return gr(e)}function h5(e){return e.includes("::")?Ns(e):e}function Ns(e){const[t,r]=e.split("::"),n=Dt(t),s=e.slice(t.length+r.length+4),i=s.includes("<")?s.slice(0,s.indexOf("<")):s,o=s.includes("<")?Fw(s.slice(s.indexOf("<")+1,s.lastIndexOf(">"))).map(a=>h5(a.trim())):[];return{address:n?t:xe(t),module:r,name:i,typeParams:o}}function lc(e){const{address:t,module:r,name:n,typeParams:s}=typeof e=="string"?Ns(e):e,i=(s==null?void 0:s.length)>0?`<${s.map(o=>typeof o=="string"?o:lc(o)).join(",")}>`:"";return`${t}::${r}::${n}${i}`}function xe(e,t=!1){let r=e.toLowerCase();return!t&&r.startsWith("0x")&&(r=r.slice(2)),`0x${r.padStart(su*2,"0")}`}function pn(e,t=!1){return xe(e,t)}function p5(e){return/^(0x|0X)?[a-fA-F0-9]+$/.test(e)&&e.length%2===0}function y5(e){return/^(0x|0X)/.test(e)?(e.length-2)/2:e.length/2}const m5=/^vector<(.+)>$/,g5=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class wr{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(m5);if(n)return{vector:wr.parseFromStr(n[1],r)};const s=t.match(g5);if(s)return{struct:{address:r?xe(s[1]):s[1],module:s[2],name:s[3],typeParams:s[5]===void 0?[]:wr.parseStructTypeArgs(s[5],r)}};throw new Error(`Encountered unexpected token when parsing type args for ${t}`)}static parseStructTypeArgs(t,r=!1){return Fw(t).map(n=>wr.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<${wr.tagToString(t.vector)}>`;if("struct"in t){const r=t.struct,n=r.typeParams.map(wr.tagToString).join(", ");return`${r.address}::${r.module}::${r.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}function b5(e){return _.u64({name:"unsafe_u64",...e}).transform({input:t=>t,output:t=>Number(t)})}function w5(e){return _.enum("Option",{None:null,Some:e})}const Re=_.bytes(su).transform({validate:e=>{const t=typeof e=="string"?e:Si(e);if(!t||!gr(xe(t)))throw new Error(`Invalid Sui address ${t}`)},input:e=>typeof e=="string"?Nw(xe(e)):e,output:e=>xe(Si(e))}),Er=_.vector(_.u8()).transform({name:"ObjectDigest",input:e=>zo(e),output:e=>ru(new Uint8Array(e)),validate:e=>{if(zo(e).length!==32)throw new Error("ObjectDigest must be 32 bytes")}}),tr=_.struct("SuiObjectRef",{objectId:Re,version:_.u64(),digest:Er}),Yw=_.struct("SharedObjectRef",{objectId:Re,initialSharedVersion:_.u64(),mutable:_.bool()}),Zw=_.enum("ObjectArg",{ImmOrOwnedObject:tr,SharedObject:Yw,Receiving:tr}),ms=_.enum("Owner",{AddressOwner:Re,ObjectOwner:Re,Shared:_.struct("Shared",{initialSharedVersion:_.u64()}),Immutable:null,ConsensusAddressOwner:_.struct("ConsensusAddressOwner",{owner:Re,startVersion:_.u64()})}),Jw=_.enum("CallArg",{Pure:_.struct("Pure",{bytes:_.vector(_.u8()).transform({input:e=>typeof e=="string"?zt(e):e,output:e=>yt(new Uint8Array(e))})}),Object:Zw}),gh=_.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:_.lazy(()=>gh),struct:_.lazy(()=>s1),u16:null,u32:null,u256:null}),bh=gh.transform({input:e=>typeof e=="string"?wr.parseFromStr(e,!0):e,output:e=>wr.tagToString(e)}),Dr=_.enum("Argument",{GasCoin:null,Input:_.u16(),Result:_.u16(),NestedResult:_.tuple([_.u16(),_.u16()])}),Qw=_.struct("ProgrammableMoveCall",{package:Re,module:_.string(),function:_.string(),typeArguments:_.vector(bh),arguments:_.vector(Dr)}),e1=_.enum("Command",{MoveCall:Qw,TransferObjects:_.struct("TransferObjects",{objects:_.vector(Dr),address:Dr}),SplitCoins:_.struct("SplitCoins",{coin:Dr,amounts:_.vector(Dr)}),MergeCoins:_.struct("MergeCoins",{destination:Dr,sources:_.vector(Dr)}),Publish:_.struct("Publish",{modules:_.vector(_.vector(_.u8()).transform({input:e=>typeof e=="string"?zt(e):e,output:e=>yt(new Uint8Array(e))})),dependencies:_.vector(Re)}),MakeMoveVec:_.struct("MakeMoveVec",{type:w5(bh).transform({input:e=>e===null?{None:!0}:{Some:e},output:e=>e.Some??null}),elements:_.vector(Dr)}),Upgrade:_.struct("Upgrade",{modules:_.vector(_.vector(_.u8()).transform({input:e=>typeof e=="string"?zt(e):e,output:e=>yt(new Uint8Array(e))})),dependencies:_.vector(Re),package:Re,ticket:Dr})}),t1=_.struct("ProgrammableTransaction",{inputs:_.vector(Jw),commands:_.vector(e1)}),r1=_.enum("TransactionKind",{ProgrammableTransaction:t1,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),n1=_.enum("TransactionExpiration",{None:null,Epoch:b5()}),s1=_.struct("StructTag",{address:Re,module:_.string(),name:_.string(),typeParams:_.vector(gh)}),i1=_.struct("GasData",{payment:_.vector(tr),owner:Re,price:_.u64(),budget:_.u64()}),o1=_.struct("TransactionDataV1",{kind:r1,sender:Re,gasData:i1,expiration:n1}),a1=_.enum("TransactionData",{V1:o1}),c1=_.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),u1=_.enum("IntentVersion",{V0:null}),l1=_.enum("AppId",{Sui:null}),f1=_.struct("Intent",{scope:c1,version:u1,appId:l1});function d1(e){return _.struct(`IntentMessage<${e.name}>`,{intent:f1,value:e})}const h1=_.enum("CompressedSignature",{ED25519:_.fixedArray(64,_.u8()),Secp256k1:_.fixedArray(64,_.u8()),Secp256r1:_.fixedArray(64,_.u8()),ZkLogin:_.vector(_.u8()),Passkey:_.vector(_.u8())}),p1=_.enum("PublicKey",{ED25519:_.fixedArray(32,_.u8()),Secp256k1:_.fixedArray(33,_.u8()),Secp256r1:_.fixedArray(33,_.u8()),ZkLogin:_.vector(_.u8()),Passkey:_.fixedArray(33,_.u8())}),y1=_.struct("MultiSigPkMap",{pubKey:p1,weight:_.u8()}),m1=_.struct("MultiSigPublicKey",{pk_map:_.vector(y1),threshold:_.u16()}),v5=_.struct("MultiSig",{sigs:_.vector(h1),bitmap:_.u16(),multisig_pk:m1}),E5=_.vector(_.u8()).transform({input:e=>typeof e=="string"?zt(e):e,output:e=>yt(new Uint8Array(e))}),g1=_.struct("SenderSignedTransaction",{intentMessage:d1(a1),txSignatures:_.vector(E5)}),A5=_.vector(g1,{name:"SenderSignedData"}),x5=_.struct("PasskeyAuthenticator",{authenticatorData:_.vector(_.u8()),clientDataJson:_.string(),userSignature:_.vector(_.u8())}),S5=_.enum("PackageUpgradeError",{UnableToFetchPackage:_.struct("UnableToFetchPackage",{packageId:Re}),NotAPackage:_.struct("NotAPackage",{objectId:Re}),IncompatibleUpgrade:null,DigestDoesNotMatch:_.struct("DigestDoesNotMatch",{digest:_.vector(_.u8())}),UnknownUpgradePolicy:_.struct("UnknownUpgradePolicy",{policy:_.u8()}),PackageIDDoesNotMatch:_.struct("PackageIDDoesNotMatch",{packageId:Re,ticketId:Re})}),_5=_.struct("ModuleId",{address:Re,name:_.string()}),cm=_.struct("MoveLocation",{module:_5,function:_.u16(),instruction:_.u16(),functionName:_.option(_.string())}),k5=_.enum("CommandArgumentError",{TypeMismatch:null,InvalidBCSBytes:null,InvalidUsageOfPureArg:null,InvalidArgumentToPrivateEntryFunction:null,IndexOutOfBounds:_.struct("IndexOutOfBounds",{idx:_.u16()}),SecondaryIndexOutOfBounds:_.struct("SecondaryIndexOutOfBounds",{resultIdx:_.u16(),secondaryIdx:_.u16()}),InvalidResultArity:_.struct("InvalidResultArity",{resultIdx:_.u16()}),InvalidGasCoinUsage:null,InvalidValueUsage:null,InvalidObjectByValue:null,InvalidObjectByMutRef:null,SharedObjectOperationNotAllowed:null}),T5=_.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),I5=_.enum("ExecutionFailureStatus",{InsufficientGas:null,InvalidGasObject:null,InvariantViolation:null,FeatureNotYetSupported:null,MoveObjectTooBig:_.struct("MoveObjectTooBig",{objectSize:_.u64(),maxObjectSize:_.u64()}),MovePackageTooBig:_.struct("MovePackageTooBig",{objectSize:_.u64(),maxObjectSize:_.u64()}),CircularObjectOwnership:_.struct("CircularObjectOwnership",{object:Re}),InsufficientCoinBalance:null,CoinBalanceOverflow:null,PublishErrorNonZeroAddress:null,SuiMoveVerificationError:null,MovePrimitiveRuntimeError:_.option(cm),MoveAbort:_.tuple([cm,_.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:_.struct("CommandArgumentError",{argIdx:_.u16(),kind:k5}),TypeArgumentError:_.struct("TypeArgumentError",{argumentIdx:_.u16(),kind:T5}),UnusedValueWithoutDrop:_.struct("UnusedValueWithoutDrop",{resultIdx:_.u16(),secondaryIdx:_.u16()}),InvalidPublicFunctionReturnType:_.struct("InvalidPublicFunctionReturnType",{idx:_.u16()}),InvalidTransferObject:null,EffectsTooLarge:_.struct("EffectsTooLarge",{currentSize:_.u64(),maxSize:_.u64()}),PublishUpgradeMissingDependency:null,PublishUpgradeDependencyDowngrade:null,PackageUpgradeError:_.struct("PackageUpgradeError",{upgradeError:S5}),WrittenObjectsTooLarge:_.struct("WrittenObjectsTooLarge",{currentSize:_.u64(),maxSize:_.u64()}),CertificateDenied:null,SuiMoveVerificationTimedout:null,SharedObjectOperationNotAllowed:null,InputObjectDeleted:null,ExecutionCancelledDueToSharedObjectCongestion:_.struct("ExecutionCancelledDueToSharedObjectCongestion",{congestedObjects:_.vector(Re)}),AddressDeniedForCoin:_.struct("AddressDeniedForCoin",{address:Re,coinType:_.string()}),CoinTypeGlobalPause:_.struct("CoinTypeGlobalPause",{coinType:_.string()}),ExecutionCancelledDueToRandomnessUnavailable:null}),b1=_.enum("ExecutionStatus",{Success:null,Failed:_.struct("ExecutionFailed",{error:I5,command:_.option(_.u64())})}),w1=_.struct("GasCostSummary",{computationCost:_.u64(),storageCost:_.u64(),storageRebate:_.u64(),nonRefundableStorageFee:_.u64()}),P5=_.struct("TransactionEffectsV1",{status:b1,executedEpoch:_.u64(),gasUsed:w1,modifiedAtVersions:_.vector(_.tuple([Re,_.u64()])),sharedObjects:_.vector(tr),transactionDigest:Er,created:_.vector(_.tuple([tr,ms])),mutated:_.vector(_.tuple([tr,ms])),unwrapped:_.vector(_.tuple([tr,ms])),deleted:_.vector(tr),unwrappedThenDeleted:_.vector(tr),wrapped:_.vector(tr),gasObject:_.tuple([tr,ms]),eventsDigest:_.option(Er),dependencies:_.vector(Er)}),wh=_.tuple([_.u64(),Er]),O5=_.enum("ObjectIn",{NotExist:null,Exist:_.tuple([wh,ms])}),B5=_.enum("ObjectOut",{NotExist:null,ObjectWrite:_.tuple([Er,ms]),PackageWrite:wh}),C5=_.enum("IDOperation",{None:null,Created:null,Deleted:null}),R5=_.struct("EffectsObjectChange",{inputState:O5,outputState:B5,idOperation:C5}),$5=_.enum("UnchangedSharedKind",{ReadOnlyRoot:wh,MutateDeleted:_.u64(),ReadDeleted:_.u64(),Cancelled:_.u64(),PerEpochConfig:null}),N5=_.struct("TransactionEffectsV2",{status:b1,executedEpoch:_.u64(),gasUsed:w1,transactionDigest:Er,gasObjectIndex:_.option(_.u32()),eventsDigest:_.option(Er),dependencies:_.vector(Er),lamportVersion:_.u64(),changedObjects:_.vector(_.tuple([Re,R5])),unchangedSharedObjects:_.vector(_.tuple([Re,$5])),auxDataDigest:_.option(Er)}),U5=_.enum("TransactionEffects",{V1:P5,V2:N5});function fo(e){switch(e){case"u8":return _.u8();case"u16":return _.u16();case"u32":return _.u32();case"u64":return _.u64();case"u128":return _.u128();case"u256":return _.u256();case"bool":return _.bool();case"string":return _.string();case"id":case"address":return Re}const t=e.match(/^(vector|option)<(.+)>$/);if(t){const[r,n]=t.slice(1);return r==="vector"?_.vector(fo(n)):_.option(fo(n))}throw new Error(`Invalid Pure type name: ${e}`)}const de={..._,U8:_.u8(),U16:_.u16(),U32:_.u32(),U64:_.u64(),U128:_.u128(),U256:_.u256(),ULEB128:_.uleb128(),Bool:_.bool(),String:_.string(),Address:Re,AppId:l1,Argument:Dr,CallArg:Jw,Command:e1,CompressedSignature:h1,GasData:i1,Intent:f1,IntentMessage:d1,IntentScope:c1,IntentVersion:u1,MultiSig:v5,MultiSigPkMap:y1,MultiSigPublicKey:m1,ObjectArg:Zw,ObjectDigest:Er,Owner:ms,PasskeyAuthenticator:x5,ProgrammableMoveCall:Qw,ProgrammableTransaction:t1,PublicKey:p1,SenderSignedData:A5,SenderSignedTransaction:g1,SharedObjectRef:Yw,StructTag:s1,SuiObjectRef:tr,TransactionData:a1,TransactionDataV1:o1,TransactionEffects:U5,TransactionExpiration:n1,TransactionKind:r1,TypeTag:bh};var nn;function M5(e){return{lang:(e==null?void 0:e.lang)??(nn==null?void 0:nn.lang),message:e==null?void 0:e.message,abortEarly:(e==null?void 0:e.abortEarly)??(nn==null?void 0:nn.abortEarly),abortPipeEarly:(e==null?void 0:e.abortPipeEarly)??(nn==null?void 0:nn.abortPipeEarly)}}var Xl;function F5(e){return Xl==null?void 0:Xl.get(e)}var Yl;function j5(e){return Yl==null?void 0:Yl.get(e)}var Zl;function L5(e,t){var r;return(r=Zl==null?void 0:Zl.get(e))==null?void 0:r.get(t)}function v1(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 Wt(e,t,r,n,s){const i=s&&"input"in s?s.input:r.value,o=(s==null?void 0:s.expected)??e.expects??null,a=(s==null?void 0:s.received)??v1(i),c={kind:e.kind,type:e.type,input:i,expected:o,received:a,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:e.requirement,path:s==null?void 0:s.path,issues:s==null?void 0:s.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},l=e.kind==="schema",u=(s==null?void 0:s.message)??e.message??L5(e.reference,c.lang)??(l?j5(c.lang):null)??n.message??F5(c.lang);u&&(c.message=typeof u=="function"?u(c):u),l&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function D5(e,t){return Object.hasOwn(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}var H5=class extends Error{constructor(t){super(t[0].message);Ph(this,"issues");this.name="ValiError",this.issues=t}};function fa(e,t){return{kind:"validation",type:"check",reference:fa,async:!1,expects:null,requirement:e,message:t,_run(r,n){return r.typed&&!this.requirement(r.value)&&Wt(this,"input",r,n),r}}}function Ge(e){return{kind:"validation",type:"integer",reference:Ge,async:!1,expects:null,requirement:Number.isInteger,message:e,_run(t,r){return t.typed&&!this.requirement(t.value)&&Wt(this,"integer",t,r),t}}}function iu(e){return{kind:"transformation",type:"transform",reference:iu,async:!1,operation:e,_run(t){return t.value=this.operation(t.value),t}}}function vh(e,t,r){return typeof e.default=="function"?e.default(t,r):e.default}function Yf(e,t){return!e._run({typed:!1,value:t},{abortEarly:!0}).issues}function ue(e,t){return{kind:"schema",type:"array",reference:ue,expects:"Array",async:!1,item:e,message:t,_run(r,n){var i;const s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let o=0;o<s.length;o++){const a=s[o],c=this.item._run({typed:!1,value:a},n);if(c.issues){const l={type:"array",origin:"value",input:s,key:o,value:a};for(const u of c.issues)u.path?u.path.unshift(l):u.path=[l],(i=r.issues)==null||i.push(u);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else Wt(this,"type",r,n);return r}}}function Eh(e){return{kind:"schema",type:"bigint",reference:Eh,expects:"bigint",async:!1,message:e,_run(t,r){return typeof t.value=="bigint"?t.typed=!0:Wt(this,"type",t,r),t}}}function ou(e){return{kind:"schema",type:"boolean",reference:ou,expects:"boolean",async:!1,message:e,_run(t,r){return typeof t.value=="boolean"?t.typed=!0:Wt(this,"type",t,r),t}}}function qo(e){return{kind:"schema",type:"lazy",reference:qo,expects:"unknown",async:!1,getter:e,_run(t,r){return this.getter(t.value)._run(t,r)}}}function le(e,t){return{kind:"schema",type:"literal",reference:le,expects:v1(e),async:!1,literal:e,message:t,_run(r,n){return r.value===this.literal?r.typed=!0:Wt(this,"type",r,n),r}}}function Ee(e,...t){const r={kind:"schema",type:"nullable",reference:Ee,expects:`${e.expects} | null`,async:!1,wrapped:e,_run(n,s){return n.value===null&&("default"in this&&(n.value=vh(this,n,s)),n.value===null)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in t&&(r.default=t[0]),r}function _i(e,...t){const r={kind:"schema",type:"nullish",reference:_i,expects:`${e.expects} | null | undefined`,async:!1,wrapped:e,_run(n,s){return(n.value===null||n.value===void 0)&&("default"in this&&(n.value=vh(this,n,s)),n.value===null||n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in t&&(r.default=t[0]),r}function De(e){return{kind:"schema",type:"number",reference:De,expects:"number",async:!1,message:e,_run(t,r){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:Wt(this,"type",t,r),t}}}function ee(e,t){return{kind:"schema",type:"object",reference:ee,expects:"Object",async:!1,entries:e,message:t,_run(r,n){var i;const s=r.value;if(s&&typeof s=="object"){r.typed=!0,r.value={};for(const o in this.entries){const a=s[o],c=this.entries[o]._run({typed:!1,value:a},n);if(c.issues){const l={type:"object",origin:"value",input:s,key:o,value:a};for(const u of c.issues)u.path?u.path.unshift(l):u.path=[l],(i=r.issues)==null||i.push(u);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),(c.value!==void 0||o in s)&&(r.value[o]=c.value)}}else Wt(this,"type",r,n);return r}}}function ft(e,...t){const r={kind:"schema",type:"optional",reference:ft,expects:`${e.expects} | undefined`,async:!1,wrapped:e,_run(n,s){return n.value===void 0&&("default"in this&&(n.value=vh(this,n,s)),n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in t&&(r.default=t[0]),r}function Vo(e,t,r){return{kind:"schema",type:"record",reference:Vo,expects:"Object",async:!1,key:e,value:t,message:r,_run(n,s){var o,a;const i=n.value;if(i&&typeof i=="object"){n.typed=!0,n.value={};for(const c in i)if(D5(i,c)){const l=i[c],u=this.key._run({typed:!1,value:c},s);if(u.issues){const p={type:"object",origin:"key",input:i,key:c,value:l};for(const d of u.issues)d.path=[p],(o=n.issues)==null||o.push(d);if(n.issues||(n.issues=u.issues),s.abortEarly){n.typed=!1;break}}const f=this.value._run({typed:!1,value:l},s);if(f.issues){const p={type:"object",origin:"value",input:i,key:c,value:l};for(const d of f.issues)d.path?d.path.unshift(p):d.path=[p],(a=n.issues)==null||a.push(d);if(n.issues||(n.issues=f.issues),s.abortEarly){n.typed=!1;break}}(!u.typed||!f.typed)&&(n.typed=!1),u.typed&&(n.value[u.value]=f.value)}}else Wt(this,"type",n,s);return n}}}function ye(e){return{kind:"schema",type:"string",reference:ye,expects:"string",async:!1,message:e,_run(t,r){return typeof t.value=="string"?t.typed=!0:Wt(this,"type",t,r),t}}}function Ah(e,t){return{kind:"schema",type:"tuple",reference:Ah,expects:"Array",async:!1,items:e,message:t,_run(r,n){var i;const s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let o=0;o<this.items.length;o++){const a=s[o],c=this.items[o]._run({typed:!1,value:a},n);if(c.issues){const l={type:"array",origin:"value",input:s,key:o,value:a};for(const u of c.issues)u.path?u.path.unshift(l):u.path=[l],(i=r.issues)==null||i.push(u);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else Wt(this,"type",r,n);return r}}}function um(e){let t;if(e)for(const r of e)t?t.push(...r.issues):t=r.issues;return t}function dt(e,t){return{kind:"schema",type:"union",reference:dt,expects:[...new Set(e.map(r=>r.expects))].join(" | ")||"never",async:!1,options:e,message:t,_run(r,n){let s,i,o;for(const a of this.options){const c=a._run({typed:!1,value:r.value},n);if(c.typed)if(c.issues)i?i.push(c):i=[c];else{s=c;break}else o?o.push(c):o=[c]}if(s)return s;if(i){if(i.length===1)return i[0];Wt(this,"type",r,n,{issues:um(i)}),r.typed=!0}else{if((o==null?void 0:o.length)===1)return o[0];Wt(this,"type",r,n,{issues:um(o)})}return r}}}function Us(){return{kind:"schema",type:"unknown",reference:Us,expects:"unknown",async:!1,_run(e){return e.typed=!0,e}}}function Ve(e,t,r){const n=e._run({typed:!1,value:t},M5(r));if(n.issues)throw new H5(n.issues);return n.value}function Pe(...e){return{...e[0],pipe:e,_run(t,r){for(let n=0;n<e.length;n++){if(t.issues&&(e[n].kind==="schema"||e[n].kind==="transformation")){t.typed=!1;break}(!t.issues||!r.abortEarly&&!r.abortPipeEarly)&&(t=e[n]._run(t,r))}return t}}}function Vs(e){const t=Object.entries(e).map(([r,n])=>ee({[r]:n}));return Pe(dt(t),iu(r=>({...r,$kind:Object.keys(r)[0]})))}const $i=Pe(ye(),iu(e=>xe(e)),fa(gr)),qt=$i,Ms=ye(),Mt=Pe(dt([ye(),Pe(De(),Ge())]),fa(e=>{try{return BigInt(e),BigInt(e)>=0&&BigInt(e)<=18446744073709551615n}catch{return!1}},"Invalid u64")),ts=ee({objectId:$i,version:Mt,digest:ye()}),Me=Pe(dt([ee({GasCoin:le(!0)}),ee({Input:Pe(De(),Ge()),type:ft(le("pure"))}),ee({Input:Pe(De(),Ge()),type:ft(le("object"))}),ee({Result:Pe(De(),Ge())}),ee({NestedResult:Ah([Pe(De(),Ge()),Pe(De(),Ge())])})]),iu(e=>({...e,$kind:Object.keys(e)[0]}))),z5=ee({budget:Ee(Mt),price:Ee(Mt),owner:Ee($i),payment:Ee(ue(ts))}),Zf=dt([le("address"),le("bool"),le("u8"),le("u16"),le("u32"),le("u64"),le("u128"),le("u256"),ee({vector:qo(()=>Zf)}),ee({datatype:ee({package:ye(),module:ye(),type:ye(),typeParameters:ue(qo(()=>Zf))})}),ee({typeParameter:Pe(De(),Ge())})]),q5=ee({ref:Ee(dt([le("&"),le("&mut")])),body:Zf}),V5=ee({package:qt,module:ye(),function:ye(),typeArguments:ue(ye()),arguments:ue(Me),_argumentTypes:ft(Ee(ue(q5)))}),G5=ee({name:ye(),inputs:Vo(ye(),dt([Me,ue(Me)])),data:Vo(ye(),Us())}),W5=Vs({MoveCall:V5,TransferObjects:ee({objects:ue(Me),address:Me}),SplitCoins:ee({coin:Me,amounts:ue(Me)}),MergeCoins:ee({destination:Me,sources:ue(Me)}),Publish:ee({modules:ue(Ms),dependencies:ue(qt)}),MakeMoveVec:ee({type:Ee(ye()),elements:ue(Me)}),Upgrade:ee({modules:ue(Ms),dependencies:ue(qt),package:qt,ticket:Me}),$Intent:G5}),E1=Vs({ImmOrOwnedObject:ts,SharedObject:ee({objectId:qt,initialSharedVersion:Mt,mutable:ou()}),Receiving:ts}),K5=Vs({Object:E1,Pure:ee({bytes:Ms}),UnresolvedPure:ee({value:Us()}),UnresolvedObject:ee({objectId:qt,version:ft(Ee(Mt)),digest:ft(Ee(ye())),initialSharedVersion:ft(Ee(Mt))})}),lm=Vs({Object:E1,Pure:ee({bytes:Ms})}),A1=Vs({None:le(!0),Epoch:Mt}),Ka=ee({version:le(2),sender:_i($i),expiration:_i(A1),gasData:z5,inputs:ue(K5),commands:ue(W5)}),os={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=>Ve(Me,r)),address:Ve(Me,t)}}},SplitCoins(e,t){return{$kind:"SplitCoins",SplitCoins:{coin:Ve(Me,e),amounts:t.map(r=>Ve(Me,r))}}},MergeCoins(e,t){return{$kind:"MergeCoins",MergeCoins:{destination:Ve(Me,e),sources:t.map(r=>Ve(Me,r))}}},Publish({modules:e,dependencies:t}){return{$kind:"Publish",Publish:{modules:e.map(r=>typeof r=="string"?r:yt(new Uint8Array(r))),dependencies:t.map(r=>pn(r))}}},Upgrade({modules:e,dependencies:t,package:r,ticket:n}){return{$kind:"Upgrade",Upgrade:{modules:e.map(s=>typeof s=="string"?s:yt(new Uint8Array(s))),dependencies:t.map(s=>pn(s)),package:r,ticket:Ve(Me,n)}}},MakeMoveVec({type:e,elements:t}){return{$kind:"MakeMoveVec",MakeMoveVec:{type:e??null,elements:t.map(r=>Ve(Me,r))}}},Intent({name:e,inputs:t={},data:r={}}){return{$kind:"$Intent",$Intent:{name:e,inputs:Object.fromEntries(Object.entries(t).map(([n,s])=>[n,Array.isArray(s)?s.map(i=>Ve(Me,i)):Ve(Me,s)])),data:r}}}},Jf=ee({digest:ye(),objectId:ye(),version:dt([Pe(De(),Ge()),ye(),Eh()])}),X5=Vs({ImmOrOwned:Jf,Shared:ee({objectId:qt,initialSharedVersion:Mt,mutable:ou()}),Receiving:Jf}),fm=Vs({Object:X5,Pure:ue(Pe(De(),Ge()))}),x1=dt([ee({kind:le("Input"),index:Pe(De(),Ge()),value:Us(),type:ft(le("object"))}),ee({kind:le("Input"),index:Pe(De(),Ge()),value:Us(),type:le("pure")})]),Y5=dt([ee({Epoch:Pe(De(),Ge())}),ee({None:Ee(le(!0))})]),dm=Pe(dt([De(),ye(),Eh()]),fa(e=>{if(!["string","number","bigint"].includes(typeof e))return!1;try{return BigInt(e),!0}catch{return!1}})),xh=dt([ee({bool:Ee(le(!0))}),ee({u8:Ee(le(!0))}),ee({u64:Ee(le(!0))}),ee({u128:Ee(le(!0))}),ee({address:Ee(le(!0))}),ee({signer:Ee(le(!0))}),ee({vector:qo(()=>xh)}),ee({struct:qo(()=>Z5)}),ee({u16:Ee(le(!0))}),ee({u32:Ee(le(!0))}),ee({u256:Ee(le(!0))})]),Z5=ee({address:ye(),module:ye(),name:ye(),typeParams:ue(xh)}),J5=ee({budget:ft(dm),price:ft(dm),payment:ft(ue(Jf)),owner:ft(ye())}),Q5=[x1,ee({kind:le("GasCoin")}),ee({kind:le("Result"),index:Pe(De(),Ge())}),ee({kind:le("NestedResult"),index:Pe(De(),Ge()),resultIndex:Pe(De(),Ge())})],xn=dt([...Q5]),eO=ee({kind:le("MoveCall"),target:Pe(ye(),fa(e=>e.split("::").length===3)),typeArguments:ue(ye()),arguments:ue(xn)}),tO=ee({kind:le("TransferObjects"),objects:ue(xn),address:xn}),rO=ee({kind:le("SplitCoins"),coin:xn,amounts:ue(xn)}),nO=ee({kind:le("MergeCoins"),destination:xn,sources:ue(xn)}),sO=ee({kind:le("MakeMoveVec"),type:dt([ee({Some:xh}),ee({None:Ee(le(!0))})]),objects:ue(xn)}),iO=ee({kind:le("Publish"),modules:ue(ue(Pe(De(),Ge()))),dependencies:ue(ye())}),oO=ee({kind:le("Upgrade"),modules:ue(ue(Pe(De(),Ge()))),dependencies:ue(ye()),packageId:ye(),ticket:xn}),aO=[eO,tO,rO,nO,iO,oO,sO],cO=dt([...aO]);ee({version:le(1),sender:ft(ye()),expiration:_i(Y5),gasConfig:J5,inputs:ue(x1),transactions:ue(cO)});function hm(e){var r;const t=e.inputs.map((n,s)=>{if(n.Object)return{kind:"Input",index:s,value:{Object:n.Object.ImmOrOwnedObject?{ImmOrOwned:n.Object.ImmOrOwnedObject}:n.Object.Receiving?{Receiving:{digest:n.Object.Receiving.digest,version:n.Object.Receiving.version,objectId:n.Object.Receiving.objectId}}:{Shared:{mutable:n.Object.SharedObject.mutable,initialSharedVersion:n.Object.SharedObject.initialSharedVersion,objectId:n.Object.SharedObject.objectId}}},type:"object"};if(n.Pure)return{kind:"Input",index:s,value:{Pure:Array.from(zt(n.Pure.bytes))},type:"pure"};if(n.UnresolvedPure)return{kind:"Input",type:"pure",index:s,value:n.UnresolvedPure.value};if(n.UnresolvedObject)return{kind:"Input",type:"object",index:s,value:n.UnresolvedObject.objectId};throw new Error("Invalid input")});return{version:1,sender: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:wr.parseFromStr(n.MakeMoveVec.type)},objects:n.MakeMoveVec.elements.map(s=>sn(s,t))};if(n.MergeCoins)return{kind:"MergeCoins",destination:sn(n.MergeCoins.destination,t),sources:n.MergeCoins.sources.map(s=>sn(s,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(s=>sn(s,t))};if(n.Publish)return{kind:"Publish",modules:n.Publish.modules.map(s=>Array.from(zt(s))),dependencies:n.Publish.dependencies};if(n.SplitCoins)return{kind:"SplitCoins",coin:sn(n.SplitCoins.coin,t),amounts:n.SplitCoins.amounts.map(s=>sn(s,t))};if(n.TransferObjects)return{kind:"TransferObjects",objects:n.TransferObjects.objects.map(s=>sn(s,t)),address:sn(n.TransferObjects.address,t)};if(n.Upgrade)return{kind:"Upgrade",modules:n.Upgrade.modules.map(s=>Array.from(zt(s))),dependencies:n.Upgrade.dependencies,packageId:n.Upgrade.package,ticket:sn(n.Upgrade.ticket,t)};throw new Error(`Unknown transaction ${Object.keys(n)}`)})}}function sn(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 uO(e){var t,r,n;return Ve(Ka,{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(s=>({digest:s.digest,objectId:s.objectId,version:s.version.toString()})))??null},inputs:e.inputs.map(s=>{if(s.kind==="Input"){if(Yf(fm,s.value)){const i=Ve(fm,s.value);if(i.Object){if(i.Object.ImmOrOwned)return{Object:{ImmOrOwnedObject:{objectId:i.Object.ImmOrOwned.objectId,version:String(i.Object.ImmOrOwned.version),digest:i.Object.ImmOrOwned.digest}}};if(i.Object.Shared)return{Object:{SharedObject:{mutable:i.Object.Shared.mutable??null,initialSharedVersion:i.Object.Shared.initialSharedVersion,objectId:i.Object.Shared.objectId}}};if(i.Object.Receiving)return{Object:{Receiving:{digest:i.Object.Receiving.digest,version:String(i.Object.Receiving.version),objectId:i.Object.Receiving.objectId}}};throw new Error("Invalid object input")}return{Pure:{bytes:yt(new Uint8Array(i.Pure))}}}return s.type==="object"?{UnresolvedObject:{objectId:s.value}}:{UnresolvedPure:{value:s.value}}}throw new Error("Invalid input")}),commands:e.transactions.map(s=>{switch(s.kind){case"MakeMoveVec":return{MakeMoveVec:{type:"Some"in s.type?wr.tagToString(s.type.Some):null,elements:s.objects.map(i=>on(i))}};case"MergeCoins":return{MergeCoins:{destination:on(s.destination),sources:s.sources.map(i=>on(i))}};case"MoveCall":{const[i,o,a]=s.target.split("::");return{MoveCall:{package:i,module:o,function:a,typeArguments:s.typeArguments,arguments:s.arguments.map(c=>on(c))}}}case"Publish":return{Publish:{modules:s.modules.map(i=>yt(Uint8Array.from(i))),dependencies:s.dependencies}};case"SplitCoins":return{SplitCoins:{coin:on(s.coin),amounts:s.amounts.map(i=>on(i))}};case"TransferObjects":return{TransferObjects:{objects:s.objects.map(i=>on(i)),address:on(s.address)}};case"Upgrade":return{Upgrade:{modules:s.modules.map(i=>yt(Uint8Array.from(i))),dependencies:s.dependencies,package:s.packageId,ticket:on(s.ticket)}}}throw new Error(`Unknown transaction ${Object.keys(s)}`)})})}function on(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 da(e){return dt(Object.entries(e).map(([t,r])=>ee({[t]:r})))}const pr=da({GasCoin:le(!0),Input:Pe(De(),Ge()),Result:Pe(De(),Ge()),NestedResult:Ah([Pe(De(),Ge()),Pe(De(),Ge())])}),lO=ee({budget:Ee(Mt),price:Ee(Mt),owner:Ee($i),payment:Ee(ue(ts))}),fO=ee({package:qt,module:ye(),function:ye(),typeArguments:ue(ye()),arguments:ue(pr)}),dO=ee({name:ye(),inputs:Vo(ye(),dt([pr,ue(pr)])),data:Vo(ye(),Us())}),hO=da({MoveCall:fO,TransferObjects:ee({objects:ue(pr),address:pr}),SplitCoins:ee({coin:pr,amounts:ue(pr)}),MergeCoins:ee({destination:pr,sources:ue(pr)}),Publish:ee({modules:ue(Ms),dependencies:ue(qt)}),MakeMoveVec:ee({type:Ee(ye()),elements:ue(pr)}),Upgrade:ee({modules:ue(Ms),dependencies:ue(qt),package:qt,ticket:pr}),$Intent:dO}),pO=da({ImmOrOwnedObject:ts,SharedObject:ee({objectId:qt,initialSharedVersion:Mt,mutable:ou()}),Receiving:ts}),yO=da({Object:pO,Pure:ee({bytes:Ms}),UnresolvedPure:ee({value:Us()}),UnresolvedObject:ee({objectId:qt,version:ft(Ee(Mt)),digest:ft(Ee(ye())),initialSharedVersion:ft(Ee(Mt))})}),mO=da({None:le(!0),Epoch:Mt}),gO=ee({version:le(2),sender:_i($i),expiration:_i(mO),gasData:lO,inputs:ue(yO),commands:ue(hO),digest:ft(Ee(ye()))});function bO(e){return{$kind:"Pure",Pure:{bytes:e instanceof Uint8Array?yt(e):e.toBase64()}}}const yn={Pure:bO,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 wO="0x1",S1="0x2",vO=pn("0x6"),EO=`${S1}::sui::SUI`;pn("0x5");const AO=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]),tt=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),te=new Uint32Array(32);function Un(e,t,r,n,s,i){const o=s[i],a=s[i+1];let c=te[2*e],l=te[2*e+1],u=te[2*t],f=te[2*t+1],p=te[2*r],d=te[2*r+1],m=te[2*n],g=te[2*n+1],w=Zm(c,u,o);l=Jm(w,l,f,a),c=w|0,{Dh:g,Dl:m}={Dh:g^l,Dl:m^c},{Dh:g,Dl:m}={Dh:l2(g,m),Dl:f2(g)},{h:d,l:p}=Ym(d,p,g,m),{Bh:f,Bl:u}={Bh:f^d,Bl:u^p},{Bh:f,Bl:u}={Bh:Km(f,u,24),Bl:Xm(f,u,24)},te[2*e]=c,te[2*e+1]=l,te[2*t]=u,te[2*t+1]=f,te[2*r]=p,te[2*r+1]=d,te[2*n]=m,te[2*n+1]=g}function Mn(e,t,r,n,s,i){const o=s[i],a=s[i+1];let c=te[2*e],l=te[2*e+1],u=te[2*t],f=te[2*t+1],p=te[2*r],d=te[2*r+1],m=te[2*n],g=te[2*n+1],w=Zm(c,u,o);l=Jm(w,l,f,a),c=w|0,{Dh:g,Dl:m}={Dh:g^l,Dl:m^c},{Dh:g,Dl:m}={Dh:Km(g,m,16),Dl:Xm(g,m,16)},{h:d,l:p}=Ym(d,p,g,m),{Bh:f,Bl:u}={Bh:f^d,Bl:u^p},{Bh:f,Bl:u}={Bh:c2(f,u,63),Bl:u2(f,u,63)},te[2*e]=c,te[2*e+1]=l,te[2*t]=u,te[2*t+1]=f,te[2*r]=p,te[2*r+1]=d,te[2*n]=m,te[2*n+1]=g}function xO(e,t={},r,n,s){if(Zn(r),e<0||e>r)throw new Error("outputLen bigger than keyLen");const{key:i,salt:o,personalization:a}=t;if(i!==void 0&&(i.length<1||i.length>r))throw new Error("key length must be undefined or 1.."+r);if(o!==void 0&&o.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==s)throw new Error("personalization must be undefined or "+s)}class SO extends yc{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Zn(t),Zn(r),this.blockLen=t,this.outputLen=r,this.buffer=new Uint8Array(t),this.buffer32=yo(this.buffer)}update(t){Jn(this),t=mn(t),lr(t);const{blockLen:r,buffer:n,buffer32:s}=this,i=t.length,o=t.byteOffset,a=t.buffer;for(let c=0;c<i;){this.pos===r&&(Hn(s),this.compress(s,0,!1),Hn(s),this.pos=0);const l=Math.min(r-this.pos,i-c),u=o+c;if(l===r&&!(u%4)&&c+l<i){const f=new Uint32Array(a,u,Math.floor((i-c)/4));Hn(f);for(let p=0;c+r<i;p+=s.length,c+=r)this.length+=r,this.compress(f,p,!1);Hn(f);continue}n.set(t.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(t){Jn(this),cd(t,this);const{pos:r,buffer32:n}=this;this.finished=!0,_r(this.buffer.subarray(r)),Hn(n),this.compress(n,0,!0),Hn(n);const s=yo(t);this.get().forEach((i,o)=>s[o]=an(i))}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:s,destroyed:i,outputLen:o,pos:a}=this;return t||(t=new this.constructor({dkLen:o})),t.set(...this.get()),t.buffer.set(r),t.destroyed=i,t.finished=s,t.length=n,t.pos=a,t.outputLen=o,t}clone(){return this._cloneInto()}}class _O extends SO{constructor(t={}){const r=t.dkLen===void 0?64:t.dkLen;super(128,r),this.v0l=tt[0]|0,this.v0h=tt[1]|0,this.v1l=tt[2]|0,this.v1h=tt[3]|0,this.v2l=tt[4]|0,this.v2h=tt[5]|0,this.v3l=tt[6]|0,this.v3h=tt[7]|0,this.v4l=tt[8]|0,this.v4h=tt[9]|0,this.v5l=tt[10]|0,this.v5h=tt[11]|0,this.v6l=tt[12]|0,this.v6h=tt[13]|0,this.v7l=tt[14]|0,this.v7h=tt[15]|0,xO(r,t,64,16,16);let{key:n,personalization:s,salt:i}=t,o=0;if(n!==void 0&&(n=mn(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=mn(i);const a=yo(i);this.v4l^=an(a[0]),this.v4h^=an(a[1]),this.v5l^=an(a[2]),this.v5h^=an(a[3])}if(s!==void 0){s=mn(s);const a=yo(s);this.v6l^=an(a[0]),this.v6h^=an(a[1]),this.v7l^=an(a[2]),this.v7h^=an(a[3])}if(n!==void 0){const a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:t,v0h:r,v1l:n,v1h:s,v2l:i,v2h:o,v3l:a,v3h:c,v4l:l,v4h:u,v5l:f,v5h:p,v6l:d,v6h:m,v7l:g,v7h:w}=this;return[t,r,n,s,i,o,a,c,l,u,f,p,d,m,g,w]}set(t,r,n,s,i,o,a,c,l,u,f,p,d,m,g,w){this.v0l=t|0,this.v0h=r|0,this.v1l=n|0,this.v1h=s|0,this.v2l=i|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=u|0,this.v5l=f|0,this.v5h=p|0,this.v6l=d|0,this.v6h=m|0,this.v7l=g|0,this.v7h=w|0}compress(t,r,n){this.get().forEach((c,l)=>te[l]=c),te.set(tt,16);let{h:s,l:i}=Wm(BigInt(this.length));te[24]=tt[8]^i,te[25]=tt[9]^s,n&&(te[28]=~te[28],te[29]=~te[29]);let o=0;const a=AO;for(let c=0;c<12;c++)Un(0,4,8,12,t,r+2*a[o++]),Mn(0,4,8,12,t,r+2*a[o++]),Un(1,5,9,13,t,r+2*a[o++]),Mn(1,5,9,13,t,r+2*a[o++]),Un(2,6,10,14,t,r+2*a[o++]),Mn(2,6,10,14,t,r+2*a[o++]),Un(3,7,11,15,t,r+2*a[o++]),Mn(3,7,11,15,t,r+2*a[o++]),Un(0,5,10,15,t,r+2*a[o++]),Mn(0,5,10,15,t,r+2*a[o++]),Un(1,6,11,12,t,r+2*a[o++]),Mn(1,6,11,12,t,r+2*a[o++]),Un(2,7,8,13,t,r+2*a[o++]),Mn(2,7,8,13,t,r+2*a[o++]),Un(3,4,9,14,t,r+2*a[o++]),Mn(3,4,9,14,t,r+2*a[o++]);this.v0l^=te[0]^te[16],this.v0h^=te[1]^te[17],this.v1l^=te[2]^te[18],this.v1h^=te[3]^te[19],this.v2l^=te[4]^te[20],this.v2h^=te[5]^te[21],this.v3l^=te[6]^te[22],this.v3h^=te[7]^te[23],this.v4l^=te[8]^te[24],this.v4h^=te[9]^te[25],this.v5l^=te[10]^te[26],this.v5h^=te[11]^te[27],this.v6l^=te[12]^te[28],this.v6h^=te[13]^te[29],this.v7l^=te[14]^te[30],this.v7h^=te[15]^te[31],_r(te)}destroy(){this.destroyed=!0,_r(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const kO=v2(e=>new _O(e)),_1=kO;function TO(e,t,r){const n=de.Address.serialize(e).toBytes(),s=de.TypeTag.serialize(t).toBytes(),i=de.u64().serialize(r.length).toBytes(),o=_1.create({dkLen:32});return o.update(new Uint8Array([240])),o.update(n),o.update(i),o.update(r),o.update(s),`0x${Si(o.digest().slice(0,32))}`}const IO="object",PO="ID",OO="ascii",BO="String",CO="string",RO="String",$O="option",NO="Option";function UO(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 Qf(e){if(typeof e=="string")switch(e){case"address":return de.Address;case"bool":return de.Bool;case"u8":return de.U8;case"u16":return de.U16;case"u32":return de.U32;case"u64":return de.U64;case"u128":return de.U128;case"u256":return de.U256;default:throw new Error(`Unknown type signature ${e}`)}if("vector"in e){if(e.vector==="u8")return de.vector(de.U8).transform({input:r=>typeof r=="string"?new TextEncoder().encode(r):r,output:r=>r});const t=Qf(e.vector);return t?de.vector(t):null}if("datatype"in e){const t=xe(e.datatype.package);if(t===xe(wO)){if(e.datatype.module===OO&&e.datatype.type===BO||e.datatype.module===CO&&e.datatype.type===RO)return de.String;if(e.datatype.module===$O&&e.datatype.type===NO){const r=Qf(e.datatype.typeParameters[0]);return r?de.vector(r):null}}if(t===xe(S1)&&e.datatype.module===IO&&e.datatype.type===PO)return de.Address}return null}function MO(e){return typeof e=="object"&&"Reference"in e?{ref:"&",body:ho(e.Reference)}:typeof e=="object"&&"MutableReference"in e?{ref:"&mut",body:ho(e.MutableReference)}:{ref:null,body:ho(e)}}function ho(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:ho(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(ho)}};if("TypeParameter"in e)return{typeParameter:e.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(e)}`)}const FO=50,jO=1000n,LO=5e10;function k1(e){return async function(r,n,s){return await VO(r,e),await qO(r,e),n.onlyTransactionKind||(await DO(r,e),await HO(r,e),await zO(r,e)),await s()}}async function DO(e,t){e.gasConfig.price||(e.gasConfig.price=String(await t.getReferenceGasPrice()))}async function HO(e,t){if(e.gasConfig.budget)return;const r=await t.dryRunTransactionBlock({transactionBlock:e.build({overrides:{gasData:{budget:String(LO),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=jO*BigInt(e.gasConfig.price||1n),s=BigInt(r.effects.gasUsed.computationCost)+n,i=s+BigInt(r.effects.gasUsed.storageCost)-BigInt(r.effects.gasUsed.storageRebate);e.gasConfig.budget=String(i>s?i:s)}async function zO(e,t){if(!e.gasConfig.payment){const n=(await t.getCoins({owner:e.gasConfig.owner||e.sender,coinType:EO})).data.filter(s=>!e.inputs.find(o=>{var a;return(a=o.Object)!=null&&a.ImmOrOwnedObject?s.coinObjectId===o.Object.ImmOrOwnedObject.objectId:!1})).map(s=>({objectId:s.coinObjectId,digest:s.digest,version:s.version}));if(!n.length)throw new Error("No valid gas coins found for the transaction.");e.gasConfig.payment=n.map(s=>Ve(ts,s))}}async function qO(e,t){const r=e.inputs.filter(u=>{var f;return u.UnresolvedObject&&!(u.UnresolvedObject.version||(f=u.UnresolvedObject)!=null&&f.initialSharedVersion)}),n=[...new Set(r.map(u=>pn(u.UnresolvedObject.objectId)))],s=n.length?nu(n,FO):[],i=(await Promise.all(s.map(u=>t.multiGetObjects({ids:u,options:{showOwner:!0}})))).flat(),o=new Map(n.map((u,f)=>[u,i[f]])),a=Array.from(o).filter(([u,f])=>f.error).map(([u,f])=>JSON.stringify(f.error));if(a.length)throw new Error(`The following input objects are invalid: ${a.join(", ")}`);const c=i.map(u=>{if(u.error||!u.data)throw new Error(`Failed to fetch object: ${u.error}`);const f=u.data.owner,p=f&&typeof f=="object"?"Shared"in f?f.Shared.initial_shared_version:"ConsensusAddressOwner"in f?f.ConsensusAddressOwner.start_version:null:null;return{objectId:u.data.objectId,digest:u.data.digest,version:u.data.version,initialSharedVersion:p}}),l=new Map(n.map((u,f)=>[u,c[f]]));for(const[u,f]of e.inputs.entries()){if(!f.UnresolvedObject)continue;let p;const d=xe(f.UnresolvedObject.objectId),m=l.get(d);f.UnresolvedObject.initialSharedVersion??(m==null?void 0:m.initialSharedVersion)?p=yn.SharedObjectRef({objectId:d,initialSharedVersion:f.UnresolvedObject.initialSharedVersion||(m==null?void 0:m.initialSharedVersion),mutable:GO(e,u)}):WO(e,u)&&(p=yn.ReceivingRef({objectId:d,digest:f.UnresolvedObject.digest??(m==null?void 0:m.digest),version:f.UnresolvedObject.version??(m==null?void 0:m.version)})),e.inputs[e.inputs.indexOf(f)]=p??yn.ObjectRef({objectId:d,digest:f.UnresolvedObject.digest??(m==null?void 0:m.digest),version:f.UnresolvedObject.version??(m==null?void 0:m.version)})}}async function VO(e,t){const{inputs:r,commands:n}=e,s=[],i=new Set;n.forEach(a=>{if(a.MoveCall){if(a.MoveCall._argumentTypes)return;if(a.MoveCall.arguments.map(u=>u.$kind==="Input"?e.inputs[u.Input]:null).some(u=>(u==null?void 0:u.UnresolvedPure)||(u==null?void 0:u.UnresolvedObject))){const u=`${a.MoveCall.package}::${a.MoveCall.module}::${a.MoveCall.function}`;i.add(u),s.push(a.MoveCall)}}});const o=new Map;i.size>0&&await Promise.all([...i].map(async a=>{const[c,l,u]=a.split("::"),f=await t.getNormalizedMoveFunction({package:c,module:l,function:u});o.set(a,f.parameters.map(p=>MO(p)))})),s.length&&await Promise.all(s.map(async a=>{const c=o.get(`${a.package}::${a.module}::${a.function}`);if(!c)return;const u=c.length>0&&UO(c.at(-1))?c.slice(0,c.length-1):c;a._argumentTypes=u})),n.forEach(a=>{if(!a.MoveCall)return;const c=a.MoveCall,l=`${c.package}::${c.module}::${c.function}`,u=c._argumentTypes;if(u){if(u.length!==a.MoveCall.arguments.length)throw new Error(`Incorrect number of arguments for ${l}`);u.forEach((f,p)=>{var T,E;const d=c.arguments[p];if(d.$kind!=="Input")return;const m=r[d.Input];if(!m.UnresolvedPure&&!m.UnresolvedObject)return;const g=((T=m.UnresolvedPure)==null?void 0:T.value)??((E=m.UnresolvedObject)==null?void 0:E.objectId),w=Qf(f.body);if(w){d.type="pure",r[r.indexOf(m)]=yn.Pure(w.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=m.UnresolvedPure?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:g}}:m;r[d.Input]=A})}})}function GO(e,t){let r=!1;return e.getInputUses(t,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=s.MoveCall._argumentTypes[i].ref!=="&"||r}(s.$kind==="MakeMoveVec"||s.$kind==="MergeCoins"||s.$kind==="SplitCoins"||s.$kind==="TransferObjects")&&(r=!0)}),r}function WO(e,t){let r=!1;return e.getInputUses(t,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=KO(s.MoveCall._argumentTypes[i])||r}}),r}function KO(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 T1(e,t){return!!(e.inputs.some(r=>r.UnresolvedObject||r.UnresolvedPure)||!t.onlyTransactionKind&&(!e.gasConfig.price||!e.gasConfig.budget||!e.gasConfig.payment))}async function XO(e,t,r){var i;if(ZO(e),!T1(e,t))return await pm(e),r();const n=YO(t);return(((i=n.core)==null?void 0:i.resolveTransactionPlugin())??k1(n))(e,t,async()=>{await pm(e),await r()})}function pm(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 YO(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 ZO(e){for(const t of e.commands)switch(t.$kind){case"SplitCoins":t.SplitCoins.amounts.forEach(r=>{ym(r,de.U64,e)});break;case"TransferObjects":ym(t.TransferObjects.address,de.Address,e);break}}function ym(e,t,r){if(e.$kind!=="Input")return;const n=r.inputs[e.Input];n.$kind==="UnresolvedPure"&&(r.inputs[e.Input]=yn.Pure(t.serialize(n.UnresolvedPure.value)))}function JO(e){function t(r){return e(r)}return t.system=()=>t("0x5"),t.clock=()=>t("0x6"),t.random=()=>t("0x8"),t.denyList=()=>t("0x403"),t.option=({type:r,value:n})=>s=>s.moveCall({typeArguments:[r],target:`0x1::option::${n===null?"none":"some"}`,arguments:n===null?[]:[s.object(n)]}),t}function QO(e){function t(r,n){if(typeof r=="string")return e(fo(r).serialize(n));if(r instanceof Uint8Array||mh(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(de.U8.serialize(r)),t.u16=r=>e(de.U16.serialize(r)),t.u32=r=>e(de.U32.serialize(r)),t.u64=r=>e(de.U64.serialize(r)),t.u128=r=>e(de.U128.serialize(r)),t.u256=r=>e(de.U256.serialize(r)),t.bool=r=>e(de.Bool.serialize(r)),t.string=r=>e(de.String.serialize(r)),t.address=r=>e(de.Address.serialize(r)),t.id=t.address,t.vector=(r,n)=>e(de.vector(fo(r)).serialize(n)),t.option=(r,n)=>e(de.option(fo(r)).serialize(n)),t}function e3(e,t){const r=Array.from(`${e}::`).map(s=>s.charCodeAt(0)),n=new Uint8Array(r.length+t.length);return n.set(r),n.set(t,r.length),_1(n,{dkLen:32})}function mm(e){return xe(e).replace("0x","")}class Rt{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=de.TransactionKind.parse(t).ProgrammableTransaction;if(!n)throw new Error("Unable to deserialize from bytes.");return Rt.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=de.TransactionData.parse(t),n=r==null?void 0:r.V1,s=n.kind.ProgrammableTransaction;if(!n||!s)throw new Error("Unable to deserialize from bytes.");return Rt.restore({version:2,sender:n.sender,expiration:n.expiration,gasData:n.gasData,inputs:s.inputs,commands:s.commands})}static restore(t){return t.version===2?new Rt(Ve(Ka,t)):new Rt(Ve(Ka,uO(t)))}static getDigestFromBytes(t){const r=e3("TransactionData",t);return ru(r)}get gasConfig(){return this.gasData}set gasConfig(t){this.gasData=t}build({maxSizeBytes:t=1/0,overrides:r,onlyTransactionKind:n}={}){const s=this.inputs,i=this.commands,o={ProgrammableTransaction:{inputs:s,commands:i}};if(n)return de.TransactionKind.serialize(o,{maxSize:t}).toBytes();const a=(r==null?void 0:r.expiration)??this.expiration,c=(r==null?void 0:r.sender)??this.sender,l={...this.gasData,...r==null?void 0:r.gasConfig,...r==null?void 0:r.gasData};if(!c)throw new Error("Missing transaction sender");if(!l.budget)throw new Error("Missing gas budget");if(!l.payment)throw new Error("Missing gas payment");if(!l.price)throw new Error("Missing gas price");const u={sender:mm(c),expiration:a||{None:!0},gasData:{payment:l.payment,owner:mm(this.gasData.owner??c),price:BigInt(l.price),budget:BigInt(l.budget)},kind:{ProgrammableTransaction:{inputs:s,commands:i}}};return de.TransactionData.serialize({V1:u},{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,s)=>(n.$kind==="Input"&&n.Input===t&&r(n,s),n))}mapCommandArguments(t,r){const n=this.commands[t];switch(n.$kind){case"MoveCall":n.MoveCall.arguments=n.MoveCall.arguments.map(i=>r(i,n,t));break;case"TransferObjects":n.TransferObjects.objects=n.TransferObjects.objects.map(i=>r(i,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(i=>r(i,n,t));break;case"MergeCoins":n.MergeCoins.destination=r(n.MergeCoins.destination,n,t),n.MergeCoins.sources=n.MergeCoins.sources.map(i=>r(i,n,t));break;case"MakeMoveVec":n.MakeMoveVec.elements=n.MakeMoveVec.elements.map(i=>r(i,n,t));break;case"Upgrade":n.Upgrade.ticket=r(n.Upgrade.ticket,n,t);break;case"$Intent":const s=n.$Intent.inputs;n.$Intent.inputs={};for(const[i,o]of Object.entries(s))n.$Intent.inputs[i]=Array.isArray(o)?o.map(a=>r(a,n,t)):r(o,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 s=r.length-1;this.commands.splice(t,1,...r),s!==0&&this.mapArguments((i,o,a)=>{if(a<t+r.length)return i;switch(i.$kind){case"Result":i.Result===t&&(i.Result=n),i.Result>t&&(i.Result+=s);break;case"NestedResult":i.NestedResult[0]===t&&(i.NestedResult[0]=n),i.NestedResult[0]>t&&(i.NestedResult[0]+=s);break}return i})}getDigest(){const t=this.build({onlyTransactionKind:!1});return Rt.getDigestFromBytes(t)}snapshot(){return Ve(Ka,this)}shallowClone(){return new Rt({version:this.version,sender:this.sender,expiration:this.expiration,gasData:{...this.gasData},inputs:[...this.inputs],commands:[...this.commands]})}}function gm(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)}var I1=e=>{throw TypeError(e)},Sh=(e,t,r)=>t.has(e)||I1("Cannot "+r),nt=(e,t,r)=>(Sh(e,t,"read from private field"),r?r.call(e):t.get(e)),Gi=(e,t,r)=>t.has(e)?I1("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Na=(e,t,r,n)=>(Sh(e,t,"write to private field"),t.set(e,r),r),au=(e,t,r)=>(Sh(e,t,"access private method"),r),Go,Sn,Wo,zn,zr,ed,td,P1,O1,_h;const t3="/",r3={"Mvr-Source":`@mysten/sui@${Aw}`};class n3{constructor({cache:t,url:r,pageSize:n=50,overrides:s}){Gi(this,zr),Gi(this,Go),Gi(this,Sn),Gi(this,Wo),Gi(this,zn),Na(this,Go,t),Na(this,Sn,r),Na(this,Wo,n),Na(this,zn,{packages:s==null?void 0:s.packages,types:s==null?void 0:s.types}),s3(nt(this,zn))}async resolvePackage({package:t}){return{package:await nt(this,zr,ed).load(t)}}async resolveType({type:t}){const r=[...rd(t)],n=await nt(this,zr,td).loadMany(r),s={};for(let i=0;i<r.length;i++){const o=n[i];if(o instanceof Error)throw o;s[r[i]]=o}return{type:nd(t,s)}}async resolve({types:t=[],packages:r=[]}){var u,f,p;const n=new Set;for(const d of t??[])rd(d,n);const s=[...n],[i,o]=await Promise.all([s.length>0?nt(this,zr,td).loadMany(s):[],r.length>0?nt(this,zr,ed).loadMany(r):[]]),a={...(u=nt(this,zn))==null?void 0:u.types};for(const[d,m]of s.entries()){const g=i[d];if(g instanceof Error)throw g;a[m]=g}const c={};for(const d of t??[]){const m=nd(d,a);c[d]={type:m}}const l={};for(const[d,m]of(r??[]).entries()){const g=((p=(f=nt(this,zn))==null?void 0:f.packages)==null?void 0:p[m])??o[d];if(g instanceof Error)throw g;l[m]={package:g}}return{types:c,packages:l}}}Go=new WeakMap;Sn=new WeakMap;Wo=new WeakMap;zn=new WeakMap;zr=new WeakSet;ed=function(){return nt(this,Go).readSync(["#mvrPackageDataLoader",nt(this,Sn)??""],()=>{var r;const e=new Uw(async n=>{if(!nt(this,Sn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await au(this,zr,P1).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve package: ${i}`))}),t=(r=nt(this,zn))==null?void 0:r.packages;if(t)for(const[n,s]of Object.entries(t))e.prime(n,s);return e})};td=function(){return nt(this,Go).readSync(["#mvrTypeDataLoader",nt(this,Sn)??""],()=>{var r;const e=new Uw(async n=>{if(!nt(this,Sn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await au(this,zr,O1).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve type: ${i}`))}),t=(r=nt(this,zn))==null?void 0:r.types;if(t)for(const[n,s]of Object.entries(t))e.prime(n,s);return e})};P1=async function(e){if(e.length===0)return{};const t=nu(e,nt(this,Wo)),r={};return await Promise.all(t.map(async n=>{var i;const s=await au(this,zr,_h).call(this,"/v1/resolution/bulk",{names:n});if(s!=null&&s.resolution)for(const o of Object.keys(s==null?void 0:s.resolution)){const a=(i=s.resolution[o])==null?void 0:i.package_id;a&&(r[o]=a)}})),r};O1=async function(e){if(e.length===0)return{};const t=nu(e,nt(this,Wo)),r={};return await Promise.all(t.map(async n=>{var i;const s=await au(this,zr,_h).call(this,"/v1/struct-definition/bulk",{types:n});if(s!=null&&s.resolution)for(const o of Object.keys(s==null?void 0:s.resolution)){const a=(i=s.resolution[o])==null?void 0:i.type_tag;a&&(r[o]=a)}})),r};_h=async function(e,t){if(!nt(this,Sn))throw new Error("MVR Api URL is not set for the current client");const r=await fetch(`${nt(this,Sn)}${e}`,{method:"POST",headers:{"Content-Type":"application/json",...r3},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 s3(e){if(e!=null&&e.packages)for(const[t,r]of Object.entries(e.packages)){if(!Dt(t))throw new Error(`Invalid package name: ${t}`);if(!gr(xe(r)))throw new Error(`Invalid package ID: ${r}`)}if(e!=null&&e.types)for(const[t,r]of Object.entries(e.types)){if(Ns(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=Ns(r);if(!gr(n.address))throw new Error(`Invalid type: ${r}`)}}function rd(e,t=new Set){if(typeof e=="string"&&!$t(e))return t;const r=B1(e)?e:Ns(e);$t(r.address)&&t.add(`${r.address}::${r.module}::${r.name}`);for(const n of r.typeParams)rd(n,t);return t}function nd(e,t){const r=B1(e)?e:Ns(e),n=`${r.address}::${r.module}::${r.name}`,s=t[n];return lc({...r,address:s?s.split("::")[0]:r.address,typeParams:r.typeParams.map(i=>nd(i,t))})}function $t(e){return e.includes(t3)||e.includes("@")||e.includes(".sui")}function B1(e){return typeof e=="object"&&"address"in e&&"module"in e&&"name"in e&&"typeParams"in e}function i3(e){const t=new Set,r=new Set;for(const n of e.commands)switch(n.$kind){case"MakeMoveVec":n.MakeMoveVec.type&&bm([n.MakeMoveVec.type]).forEach(o=>{r.add(o)});break;case"MoveCall":const s=n.MoveCall,i=s.package.split("::")[0];if($t(i)){if(!Dt(i))throw new Error(`Invalid package name: ${i}`);t.add(i)}bm(s.typeArguments??[]).forEach(o=>{r.add(o)});break}return{packages:[...t],types:[...r]}}function o3(e,t){var r;for(const n of e.commands){if((r=n.MakeMoveVec)!=null&&r.type){if(!$t(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 s=n.MoveCall;if(!s)continue;const i=s.package.split("::"),o=i[0];if($t(o)&&!t.packages[o])throw new Error(`No address found for package: ${o}`);$t(o)&&(i[0]=t.packages[o].package,s.package=i.join("::"));const a=s.typeArguments;if(a){for(let c=0;c<a.length;c++)if($t(a[c])){if(!t.types[a[c]])throw new Error(`No resolution found for type: ${a[c]}`);a[c]=t.types[a[c]].type}s.typeArguments=a}}}function bm(e){const t=new Set;for(const r of e)if($t(r)){if(!f5(r))throw new Error(`Invalid type with names: ${r}`);t.add(r)}return t}const a3=e=>async(t,r,n)=>{const s=i3(t);if(s.types.length===0&&s.packages.length===0)return n();const i=await c3(r).core.mvr.resolve({types:s.types,packages:s.packages});o3(t,i),await n()};function c3(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 C1=e=>{throw TypeError(e)},kh=(e,t,r)=>t.has(e)||C1("Cannot "+r),Y=(e,t,r)=>(kh(e,t,"read from private field"),r?r.call(e):t.get(e)),Mr=(e,t,r)=>t.has(e)?C1("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Be=(e,t,r,n)=>(kh(e,t,"write to private field"),t.set(e,r),r),rt=(e,t,r)=>(kh(e,t,"access private method"),r),gs,xs,fn,Vr,ir,or,vr,qn,ae,Ke,R1,Xa,Ya,Za,fc,sd,Th,$1,N1;function Jl(e,t=1/0){const r={$kind:"Result",get Result(){return typeof e=="function"?e():e}},n=[],s=i=>n[i]??(n[i]={$kind:"NestedResult",get NestedResult(){return[typeof e=="function"?e():e,i]}});return new Proxy(r,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(i,o){if(o in i)return Reflect.get(i,o);if(o===Symbol.iterator)return function*(){let c=0;for(;c<t;)yield s(c),c++};if(typeof o=="symbol")return;const a=parseInt(o,10);if(!(Number.isNaN(a)||a<0))return s(a)}})}const U1=Symbol.for("@mysten/transaction");function M1(e){return!!e&&typeof e=="object"&&e[U1]===!0}const wm={buildPlugins:new Map,serializationPlugins:new Map},Ql=Symbol.for("@mysten/transaction/registry");function Wi(){try{const e=globalThis;return e[Ql]||(e[Ql]=wm),e[Ql]}catch{return wm}}const F1=class id{constructor(){Mr(this,Ke),Mr(this,gs),Mr(this,xs),Mr(this,fn,new Map),Mr(this,Vr,[]),Mr(this,ir,[]),Mr(this,or,new Set),Mr(this,vr,new Set),Mr(this,qn,new Map),Mr(this,ae),this.object=JO(r=>{var i,o;if(typeof r=="function")return this.object(this.add(r));if(typeof r=="object"&&Yf(Me,r))return r;const n=gm(r),s=Y(this,ae).inputs.find(a=>n===gm(a));return(i=s==null?void 0:s.Object)!=null&&i.SharedObject&&typeof r=="object"&&((o=r.Object)!=null&&o.SharedObject)&&(s.Object.SharedObject.mutable=s.Object.SharedObject.mutable||r.Object.SharedObject.mutable),s?{$kind:"Input",Input:Y(this,ae).inputs.indexOf(s),type:"object"}:rt(this,Ke,Ya).call(this,"object",typeof r=="string"?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:xe(r)}}:r)});const t=Wi();Be(this,ae,new Rt),Be(this,xs,[...t.buildPlugins.values()]),Be(this,gs,[...t.serializationPlugins.values()])}static fromKind(t){const r=new id;return Be(r,ae,Rt.fromKindBytes(typeof t=="string"?zt(t):t)),Be(r,Vr,Y(r,ae).inputs.slice()),Be(r,ir,Y(r,ae).commands.slice()),Be(r,or,new Set(Y(r,ir).map((n,s)=>s))),r}static from(t){const r=new id;return M1(t)?Be(r,ae,new Rt(t.getData())):typeof t!="string"||!t.startsWith("{")?Be(r,ae,Rt.fromBytes(typeof t=="string"?zt(t):t)):Be(r,ae,Rt.restore(JSON.parse(t))),Be(r,Vr,Y(r,ae).inputs.slice()),Be(r,ir,Y(r,ae).commands.slice()),Be(r,or,new Set(Y(r,ir).map((n,s)=>s))),r}static registerGlobalSerializationPlugin(t,r){Wi().serializationPlugins.set(t,r??t)}static unregisterGlobalSerializationPlugin(t){Wi().serializationPlugins.delete(t)}static registerGlobalBuildPlugin(t,r){Wi().buildPlugins.set(t,r??t)}static unregisterGlobalBuildPlugin(t){Wi().buildPlugins.delete(t)}addSerializationPlugin(t){Y(this,gs).push(t)}addBuildPlugin(t){Y(this,xs).push(t)}addIntentResolver(t,r){if(Y(this,fn).has(t)&&Y(this,fn).get(t)!==r)throw new Error(`Intent resolver for ${t} already exists`);Y(this,fn).set(t,r)}setSender(t){Y(this,ae).sender=t}setSenderIfNotSet(t){Y(this,ae).sender||(Y(this,ae).sender=t)}setExpiration(t){Y(this,ae).expiration=t?Ve(A1,t):null}setGasPrice(t){Y(this,ae).gasConfig.price=String(t)}setGasBudget(t){Y(this,ae).gasConfig.budget=String(t)}setGasBudgetIfNotSet(t){Y(this,ae).gasData.budget==null&&(Y(this,ae).gasConfig.budget=String(t))}setGasOwner(t){Y(this,ae).gasConfig.owner=t}setGasPayment(t){Y(this,ae).gasConfig.payment=t.map(r=>Ve(ts,r))}get blockData(){return hm(Y(this,ae).snapshot())}getData(){return Y(this,ae).snapshot()}get[U1](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:QO(t=>mh(t)?rt(this,Ke,Ya).call(this,"pure",{$kind:"Pure",Pure:{bytes:t.toBase64()}}):rt(this,Ke,Ya).call(this,"pure",Yf(lm,t)?Ve(lm,t):t instanceof Uint8Array?yn.Pure(t):{$kind:"UnresolvedPure",UnresolvedPure:{value:t}}))}),this.pure}get gas(){return{$kind:"GasCoin",GasCoin:!0}}objectRef(...t){return this.object(yn.ObjectRef(...t))}receivingRef(...t){return this.object(yn.ReceivingRef(...t))}sharedObjectRef(...t){return this.object(yn.SharedObjectRef(...t))}add(t){if(typeof t=="function"){if(Y(this,qn).has(t))return Y(this,qn).get(t);const r=rt(this,Ke,R1).call(this),n=t(r);if(!(n&&typeof n=="object"&&"then"in n))return Be(this,or,Y(r,or)),Y(this,qn).set(t,n),n;const s=rt(this,Ke,Xa).call(this,{$kind:"$Intent",$Intent:{name:"AsyncTransactionThunk",inputs:{},data:{resultIndex:Y(this,ae).commands.length,result:null}}});Y(this,vr).add(Promise.resolve(n).then(o=>{s.$Intent.data.result=o}));const i=Jl(()=>s.$Intent.data.resultIndex);return Y(this,qn).set(t,i),i}else rt(this,Ke,Xa).call(this,t);return Jl(Y(this,ae).commands.length-1)}splitCoins(t,r){const n=os.SplitCoins(typeof t=="string"?this.object(t):rt(this,Ke,fc).call(this,t),r.map(s=>typeof s=="number"||typeof s=="bigint"||typeof s=="string"?this.pure.u64(s):rt(this,Ke,Za).call(this,s)));return rt(this,Ke,Xa).call(this,n),Jl(Y(this,ae).commands.length-1,r.length)}mergeCoins(t,r){return this.add(os.MergeCoins(this.object(t),r.map(n=>this.object(n))))}publish({modules:t,dependencies:r}){return this.add(os.Publish({modules:t,dependencies:r}))}upgrade({modules:t,dependencies:r,package:n,ticket:s}){return this.add(os.Upgrade({modules:t,dependencies:r,package:n,ticket:this.object(s)}))}moveCall({arguments:t,...r}){return this.add(os.MoveCall({...r,arguments:t==null?void 0:t.map(n=>rt(this,Ke,Za).call(this,n))}))}transferObjects(t,r){return this.add(os.TransferObjects(t.map(n=>this.object(n)),typeof r=="string"?this.pure.address(r):rt(this,Ke,Za).call(this,r)))}makeMoveVec({type:t,elements:r}){return this.add(os.MakeMoveVec({type:t,elements:r.map(n=>this.object(n))}))}serialize(){return JSON.stringify(hm(Y(this,ae).snapshot()))}async toJSON(t={}){await this.prepareForSerialization(t);const r=this.isFullyResolved();return JSON.stringify(Ve(gO,r?{...Y(this,ae).snapshot(),digest:Y(this,ae).getDigest()}:Y(this,ae).snapshot()),(n,s)=>typeof s=="bigint"?s.toString():s,2)}async sign(t){const{signer:r,...n}=t,s=await this.build(n);return r.signTransaction(s)}isFullyResolved(){return!(!Y(this,ae).sender||Y(this,vr).size>0||Y(this,ae).commands.some(t=>t.$Intent)||T1(Y(this,ae),{}))}async build(t={}){return await this.prepareForSerialization(t),await rt(this,Ke,sd).call(this,t),Y(this,ae).build({onlyTransactionKind:t.onlyTransactionKind})}async getDigest(t={}){return await this.prepareForSerialization(t),await rt(this,Ke,sd).call(this,t),Y(this,ae).getDigest()}async prepareForSerialization(t){var s;await rt(this,Ke,$1).call(this),rt(this,Ke,N1).call(this);const r=new Set;for(const i of Y(this,ae).commands)i.$Intent&&r.add(i.$Intent.name);const n=[...Y(this,gs)];for(const i of r)if(!((s=t.supportedIntents)!=null&&s.includes(i))){if(!Y(this,fn).has(i))throw new Error(`Missing intent resolver for ${i}`);n.push(Y(this,fn).get(i))}n.push(a3()),await rt(this,Ke,Th).call(this,n,t)}};gs=new WeakMap;xs=new WeakMap;fn=new WeakMap;Vr=new WeakMap;ir=new WeakMap;or=new WeakMap;vr=new WeakMap;qn=new WeakMap;ae=new WeakMap;Ke=new WeakSet;R1=function(){const e=new F1;return Be(e,ae,Y(this,ae)),Be(e,gs,Y(this,gs)),Be(e,xs,Y(this,xs)),Be(e,fn,Y(this,fn)),Be(e,vr,Y(this,vr)),Be(e,or,new Set(Y(this,or))),Be(e,qn,Y(this,qn)),Y(this,Vr).push(Y(e,Vr)),Y(this,ir).push(Y(e,ir)),e};Xa=function(e){const t=Y(this,ae).commands.length;return Y(this,ir).push(e),Y(this,or).add(t),Y(this,ae).commands.push(e),Y(this,ae).mapCommandArguments(t,r=>{if(r.$kind==="Result"&&!Y(this,or).has(r.Result))throw new Error(`Result { Result: ${r.Result} } is not available to use the current transaction`);if(r.$kind==="NestedResult"&&!Y(this,or).has(r.NestedResult[0]))throw new Error(`Result { NestedResult: [${r.NestedResult[0]}, ${r.NestedResult[1]}] } is not available to use the current transaction`);if(r.$kind==="Input"&&r.Input>=Y(this,ae).inputs.length)throw new Error(`Input { Input: ${r.Input} } references an input that does not exist in the current transaction`);return r}),e};Ya=function(e,t){return Y(this,Vr).push(t),Y(this,ae).addInput(e,t)};Za=function(e){return mh(e)?this.pure(e):rt(this,Ke,fc).call(this,e)};fc=function(e){if(typeof e=="function"){const t=this.add(e);return typeof t=="function"?rt(this,Ke,fc).call(this,t):Ve(Me,t)}return Ve(Me,e)};sd=async function(e){if(!e.onlyTransactionKind&&!Y(this,ae).sender)throw new Error("Missing transaction sender");await rt(this,Ke,Th).call(this,[...Y(this,xs),XO],e)};Th=async function(e,t){const r=n=>{if(n>=e.length)return()=>{};const s=e[n];return async()=>{const i=r(n+1);let o=!1,a=!1;if(await s(Y(this,ae),t,async()=>{if(o)throw new Error(`next() was call multiple times in TransactionPlugin ${n}`);o=!0,await i(),a=!0}),!o)throw new Error(`next() was not called in TransactionPlugin ${n}`);if(!a)throw new Error(`next() was not awaited in TransactionPlugin ${n}`)}};await r(0)(),Be(this,Vr,Y(this,ae).inputs.slice()),Be(this,ir,Y(this,ae).commands.slice())};$1=async function(){for(;Y(this,vr).size>0;){const e=Promise.all(Y(this,vr));Y(this,vr).clear(),Y(this,vr).add(e),await e,Y(this,vr).delete(e)}};N1=function(){var o;const e=Y(this,ae).commands,t=Y(this,ae).inputs,r=Y(this,ir).flat(1/0),n=Y(this,Vr).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 s=r.filter(a=>{var c;return((c=a.$Intent)==null?void 0:c.name)!=="AsyncTransactionThunk"});Y(this,ae).commands=s,Y(this,ae).inputs=n,Be(this,ir,s),Be(this,Vr,n),Be(this,or,new Set(s.map((a,c)=>c)));function i(a){var u;const c=e[a];if(((u=c.$Intent)==null?void 0:u.name)==="AsyncTransactionThunk"){const f=c.$Intent.data.result;if(f==null)throw new Error("AsyncTransactionThunk has not been resolved");return i(f.Result)}const l=s.indexOf(c);if(l===-1)throw new Error("Unable to find original index for command");return l}Y(this,ae).mapArguments(a=>{if(a.$kind==="Input"){const c=n.indexOf(t[a.Input]);if(c===-1)throw new Error("Input has not been resolved");return{...a,Input:c}}else if(a.$kind==="Result"){const c=i(a.Result);return{...a,Result:c}}else if(a.$kind==="NestedResult"){const c=i(a.NestedResult[0]);return{...a,NestedResult:[c,a.NestedResult[1]]}}return a});for(const[a,c]of e.entries())if(((o=c.$Intent)==null?void 0:o.name)==="AsyncTransactionThunk")try{c.$Intent.data.resultIndex=i(a)}catch{}};let j1=F1;const u3={mainnet:"https://mainnet.mvr.mystenlabs.com",testnet:"https://testnet.mvr.mystenlabs.com"};class l3 extends Gw{constructor(t){var r,n,s;super(t),this.core=this,this.mvr=new n3({cache:this.cache.scope("core.mvr"),url:((r=t.mvr)==null?void 0:r.url)??u3[this.network],pageSize:(n=t.mvr)==null?void 0:n.pageSize,overrides:(s=t.mvr)==null?void 0:s.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=TO(t.parentId,wr.parseFromStr(t.name.type),t.name.bcs),{objects:[n]}=await this.getObjects({objectIds:[r],signal:t.signal});if(n instanceof Error)throw n;const s=Ns(n.type),i=await n.content;return{dynamicField:{id:n.id,digest:n.digest,version:n.version,type:n.type,name:{type:typeof s.typeParams[0]=="string"?s.typeParams[0]:lc(s.typeParams[0]),bcs:t.name.bcs},value:{type:typeof s.typeParams[1]=="string"?s.typeParams[1]:lc(s.typeParams[1]),bcs:i.slice(su+t.name.bcs.length)}}}}async waitForTransaction({signal:t,timeout:r=60*1e3,...n}){const s=t?AbortSignal.any([AbortSignal.timeout(r),t]):AbortSignal.timeout(r),i=new Promise((o,a)=>{s.addEventListener("abort",()=>a(s.reason))});for(i.catch(()=>{});;){s.throwIfAborted();try{return await this.getTransaction({...n,signal:s})}catch{await Promise.race([new Promise(a=>setTimeout(a,2e3)),i])}}}}class f3 extends Error{}class Vn extends f3{constructor(t,r){super(r),this.code=t}static fromResponse(t,r){switch(t.code){case"notExists":return new Vn(t.code,`Object ${t.object_id} does not exist`);case"dynamicFieldNotFound":return new Vn(t.code,`Dynamic field not found for object ${t.parent_object_id}`);case"deleted":return new Vn(t.code,`Object ${t.object_id} has been deleted`);case"displayError":return new Vn(t.code,`Display error: ${t.error}`);case"unknown":default:return new Vn(t.code,`Unknown error while loading object${r?` ${r}`:""}`)}}}function d3(e){return{...Rt.fromBytes(e).snapshot(),bcs:e}}function h3(e){const t=de.TransactionEffects.parse(e);switch(t.$kind){case"V1":return p3({effects:t.V1});case"V2":return y3({bytes:e,effects:t.V2});default:throw new Error(`Unknown transaction effects version: ${t.$kind}`)}}function p3(e){throw new Error("V1 effects are not supported yet")}function y3({bytes:e,effects:t}){const r=t.changedObjects.map(([n,s])=>{var i,o,a,c,l,u;return{id:n,inputState:s.inputState.$kind==="Exist"?"Exists":"DoesNotExist",inputVersion:((i=s.inputState.Exist)==null?void 0:i[0][0])??null,inputDigest:((o=s.inputState.Exist)==null?void 0:o[0][1])??null,inputOwner:((a=s.inputState.Exist)==null?void 0:a[1])??null,outputState:s.outputState.$kind==="NotExist"?"DoesNotExist":s.outputState.$kind,outputVersion:s.outputState.$kind==="PackageWrite"?(c=s.outputState.PackageWrite)==null?void 0:c[0]:s.outputState.ObjectWrite?t.lamportVersion:null,outputDigest:s.outputState.$kind==="PackageWrite"?(l=s.outputState.PackageWrite)==null?void 0:l[1]:((u=s.outputState.ObjectWrite)==null?void 0:u[0])??null,outputOwner:s.outputState.ObjectWrite?s.outputState.ObjectWrite[1]:null,idOperation:s.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,unchangedSharedObjects:t.unchangedSharedObjects.map(([n,s])=>({kind:s.$kind==="MutateDeleted"?"MutateConsensusStreamEnded":s.$kind==="ReadDeleted"?"ReadConsensusStreamEnded":s.$kind,objectId:n,version:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[0]:s[s.$kind],digest:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[1]:null})),auxiliaryDataDigest:t.auxDataDigest}}var L1=e=>{throw TypeError(e)},D1=(e,t,r)=>t.has(e)||L1("Cannot "+r),Lt=(e,t,r)=>(D1(e,t,"read from private field"),r?r.call(e):t.get(e)),m3=(e,t,r)=>t.has(e)?L1("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),g3=(e,t,r,n)=>(D1(e,t,"write to private field"),t.set(e,r),r),pt;class b3 extends l3{constructor({jsonRpcClient:t,mvr:r}){super({network:t.network,base:t,mvr:r}),m3(this,pt),g3(this,pt,t)}async getObjects(t){const r=nu(t.objectIds,50),n=[];for(const s of r){const i=await Lt(this,pt).multiGetObjects({ids:s,options:{showOwner:!0,showType:!0,showBcs:!0},signal:t.signal});for(const[o,a]of i.entries())a.error?n.push(Vn.fromResponse(a.error,s[o])):n.push(vm(a.data))}return{objects:n}}async getOwnedObjects(t){const r=await Lt(this,pt).getOwnedObjects({owner:t.address,limit:t.limit,cursor:t.cursor,options:{showOwner:!0,showType:!0,showBcs:!0},filter:t.type?{StructType:t.type}:null,signal:t.signal});return{objects:r.data.map(n=>{if(n.error)throw Vn.fromResponse(n.error);return vm(n.data)}),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getCoins(t){const r=await Lt(this,pt).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(E3.serialize({id:n.coinObjectId,balance:{value:n.balance}}).toBytes()),owner:{$kind:"ObjectOwner",ObjectOwner:t.address}})),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getBalance(t){const r=await Lt(this,pt).getBalance({owner:t.address,coinType:t.coinType,signal:t.signal});return{balance:{coinType:r.coinType,balance:r.totalBalance}}}async getAllBalances(t){return{balances:(await Lt(this,pt).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 Lt(this,pt).getTransactionBlock({digest:t.digest,options:{showRawInput:!0,showObjectChanges:!0,showRawEffects:!0,showEvents:!0,showEffects:!0},signal:t.signal});return{transaction:Em(r)}}async executeTransaction(t){const r=await Lt(this,pt).executeTransactionBlock({transactionBlock:t.transaction,signature:t.signatures,options:{showRawEffects:!0,showEvents:!0,showObjectChanges:!0,showRawInput:!0,showEffects:!0},signal:t.signal});return{transaction:Em(r)}}async dryRunTransaction(t){const r=j1.from(t.transaction),n=await Lt(this,pt).dryRunTransactionBlock({transactionBlock:t.transaction,signal:t.signal}),{effects:s,objectTypes:i}=w3({effects:n.effects,objectChanges:n.objectChanges});return{transaction:{digest:await r.getDigest(),epoch:null,effects:s,objectTypes:Promise.resolve(i),signatures:[],transaction:d3(t.transaction)}}}async getReferenceGasPrice(t){const r=await Lt(this,pt).getReferenceGasPrice({signal:t==null?void 0:t.signal});return{referenceGasPrice:String(r)}}async getDynamicFields(t){const r=await Lt(this,pt).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:zt(n.bcsName)}})),hasNextPage:r.hasNextPage,cursor:r.nextCursor}}async verifyZkLoginSignature(t){const r=await Lt(this,pt).verifyZkLoginSignature({bytes:t.bytes,signature:t.signature,intentScope:t.intentScope,author:t.author});return{success:r.success,errors:r.errors}}resolveNameServiceNames(t){return Lt(this,pt).resolveNameServiceNames(t)}resolveTransactionPlugin(){return k1(Lt(this,pt))}}pt=new WeakMap;function vm(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"?zt(e.bcs.bcsBytes):new Uint8Array),owner:si(e.owner)}}function si(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 Em(e){var i,o;const t=de.SenderSignedData.parse(zt(e.rawTransaction))[0],r={};(i=e.objectChanges)==null||i.forEach(a=>{a.type!=="published"&&(r[a.objectId]=a.objectType)});const n=de.TransactionData.serialize(t.intentMessage.value).toBytes(),s=Rt.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:((o=e.effects)==null?void 0:o.executedEpoch)??null,effects:h3(new Uint8Array(e.rawEffects)),objectTypes:Promise.resolve(r),transaction:{...s,bcs:n},signatures:t.txSignatures}}function w3({bytes:e,effects:t,objectChanges:r}){var o;const n=[],s=[],i={};return r==null||r.forEach(a=>{var c,l,u,f;switch(a.type){case"published":n.push({id:a.packageId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"PackageWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:null,idOperation:"Created"});break;case"transferred":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:a.digest,inputOwner:{$kind:"AddressOwner",AddressOwner:a.sender},outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:si(a.recipient),idOperation:"None"}),i[a.objectId]=a.objectType;break;case"mutated":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.previousVersion,inputDigest:null,inputOwner:si(a.owner),outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:si(a.owner),idOperation:"None"}),i[a.objectId]=a.objectType;break;case"deleted":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:((l=(c=t.deleted)==null?void 0:c.find(p=>p.objectId===a.objectId))==null?void 0:l.digest)??null,inputOwner:null,outputState:"DoesNotExist",outputVersion:null,outputDigest:null,outputOwner:null,idOperation:"Deleted"}),i[a.objectId]=a.objectType;break;case"wrapped":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:null,inputOwner:{$kind:"AddressOwner",AddressOwner:a.sender},outputState:"ObjectWrite",outputVersion:a.version,outputDigest:((f=(u=t.wrapped)==null?void 0:u.find(p=>p.objectId===a.objectId))==null?void 0:f.digest)??null,outputOwner:{$kind:"ObjectOwner",ObjectOwner:a.sender},idOperation:"None"}),i[a.objectId]=a.objectType;break;case"created":n.push({id:a.objectId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:si(a.owner),idOperation:"Created"}),i[a.objectId]=a.objectType;break}}),{objectTypes:i,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:(o=t.gasObject)==null?void 0:o.reference.objectId,inputState:"Exists",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:t.gasObject.reference.version,outputDigest:t.gasObject.reference.digest,outputOwner:si(t.gasObject.owner),idOperation:"None"},eventsDigest:t.eventsDigest??null,dependencies:t.dependencies??[],lamportVersion:t.gasObject.reference.version,changedObjects:n,unchangedSharedObjects:s,auxiliaryDataDigest:null}}}const v3=de.struct("Balance",{value:de.u64()}),E3=de.struct("Coin",{id:de.Address,balance:v3}),A3=Symbol.for("@mysten/SuiClient");class x3 extends Gw{constructor(t){super({network:t.network??"unknown"}),this.jsonRpc=this,this.transport=t.transport??new SP({url:t.url}),this.core=new b3({jsonRpcClient:this,mvr:t.mvr})}get[A3](){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:s,signal:i}){if(!r||!gr(xe(r)))throw new Error("Invalid Sui address");return t&&$t(t)&&(t=(await this.core.mvr.resolveType({type:t})).type),await this.transport.request({method:"suix_getCoins",params:[r,t,n,s],signal:i})}async getAllCoins(t){if(!t.owner||!gr(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||!gr(xe(t)))throw new Error("Invalid Sui address");return r&&$t(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||!gr(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&&$t(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&&$t(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:s}){return t&&Dt(t)&&(t=(await this.core.mvr.resolvePackage({package:t})).package),await this.transport.request({method:"sui_getMoveFunctionArgTypes",params:[t,r,n],signal:s})}async getNormalizedMoveModulesByPackage({package:t,signal:r}){return t&&Dt(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&&Dt(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:s}){return t&&Dt(t)&&(t=(await this.core.mvr.resolvePackage({package:t})).package),await this.transport.request({method:"sui_getNormalizedMoveFunction",params:[t,r,n],signal:s})}async getNormalizedMoveStruct({package:t,module:r,struct:n,signal:s}){return t&&Dt(t)&&(t=(await this.core.mvr.resolvePackage({package:t})).package),await this.transport.request({method:"sui_getNormalizedMoveStruct",params:[t,r,n],signal:s})}async getOwnedObjects(t){if(!t.owner||!gr(xe(t.owner)))throw new Error("Invalid Sui address");const r=t.filter?{...t.filter}:void 0;return r&&"MoveModule"in r&&Dt(r.MoveModule.package)?r.MoveModule={module:r.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:r.MoveModule.package})).package}:r&&"StructType"in r&&$t(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||!$a(pn(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||!$a(pn(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:s,order:i,signal:o}){return t&&"MoveFunction"in t&&Dt(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,s,(i||"descending")==="descending"],signal:o})}async getTransactionBlock(t){if(!am(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(!am(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:s,signal:i}){const o=await this.transport.request({method:"sui_executeTransactionBlock",params:[typeof t=="string"?t:yt(t),Array.isArray(r)?r:[r],n],signal:i});if(s==="WaitForLocalExecution")try{await this.waitForTransaction({digest:o.digest})}catch{}return o}async signAndExecuteTransaction({transaction:t,signer:r,...n}){let s;t instanceof Uint8Array?s=t:(t.setSenderIfNotSet(r.toSuiAddress()),s=await t.build({client:this}));const{signature:i,bytes:o}=await r.signTransaction(s);return this.executeTransactionBlock({transactionBlock:o,signature:i,...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||!gr(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||!$a(pn(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:s,signal:i}){return t&&"MoveEventType"in t&&$t(t.MoveEventType)&&(t={...t,MoveEventType:(await this.core.mvr.resolveType({type:t.MoveEventType})).type}),t&&"MoveEventModule"in t&&Dt(t.MoveEventModule.package)&&(t={...t,MoveEventModule:{module:t.MoveEventModule.module,package:(await this.core.mvr.resolvePackage({package:t.MoveEventModule.package})).package}}),"MoveModule"in t&&Dt(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,(s||"descending")==="descending"],signal:i})}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,s;let r;if(M1(t.transactionBlock))t.transactionBlock.setSenderIfNotSet(t.sender),r=yt(await t.transactionBlock.build({client:this,onlyTransactionKind:!0}));else if(typeof t.transactionBlock=="string")r=t.transactionBlock;else if(t.transactionBlock instanceof Uint8Array)r=yt(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,(s=t.gasPrice)==null?void 0:s.toString(),t.epoch],signal:t.signal})}async dryRunTransactionBlock(t){return await this.transport.request({method:"sui_dryRunTransactionBlock",params:[typeof t.transactionBlock=="string"?t.transactionBlock:yt(t.transactionBlock)]})}async getDynamicFields(t){if(!t.parentId||!$a(pn(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=zo(r.digest);return Si(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:s,data:i}=await this.transport.request({method:"suix_resolveNameServiceNames",params:[r.address,r.cursor,r.limit],signal:r.signal});return{hasNextPage:s,nextCursor:n,data:i.map(o=>a5(o,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,...s}){const i=AbortSignal.timeout(r),o=new Promise((a,c)=>{i.addEventListener("abort",()=>c(i.reason))});for(o.catch(()=>{});!i.aborted;){t==null||t.throwIfAborted();try{return await this.getTransactionBlock(s)}catch{await Promise.race([new Promise(c=>setTimeout(c,n)),o])}}throw i.throwIfAborted(),new Error("Unexpected error while waiting for transaction block.")}experimental_asClientExtension(){return{name:"jsonRPC",register:()=>this}}}class S3{constructor(t,r,n){this.client=new x3({url:_P(n)}),this.url=t instanceof v.Url?t:new v.Url(t),this.account=r,this.network=n}get htlcActorAddress(){return"accounts"in this.account?this.account.accounts[0].address:this.account.toSuiAddress()}async initiate(t){var r,n,s;try{const{source_swap:i}=t,o=BigInt(i.amount),a=i.asset,c=i.redeemer,l=i.secret_hash,u=new j1;u.setSender(this.htlcActorAddress);const[f]=u.splitCoins(u.gas,[o]);u.moveCall({target:`${kp[this.network].packageId}::${kp[this.network].moduleName}::initiate`,typeArguments:[i.token_address],arguments:[u.object(a),u.pure.address(this.htlcActorAddress),u.pure.address(c),u.pure.vector("u8",Buffer.from(l,"hex")),u.pure.u64(o),u.pure.u256(i.timelock),u.pure.vector("u8",Buffer.from("")),f,u.object(vO)]});const p=await u.build({client:this.client}),d=await this.client.dryRunTransactionBlock({transactionBlock:p});if(d.effects.status.status==="failure")return v.Err(`${d.effects.status.error}`);let m;if("features"in this.account?m=await((r=this.account.features[X1.SuiSignAndExecuteTransaction])==null?void 0:r.signAndExecuteTransaction({transaction:u,account:this.account.accounts[0],chain:`sui:${this.network}`})):m=await this.client.signAndExecuteTransaction({signer:this.account,transaction:u,options:{showEffects:!0}}),!m)return v.Err("Failed to initiate");const g=await this.client.waitForTransaction({digest:m.digest,options:{showEffects:!0}});return((n=g.effects)==null?void 0:n.status.status)==="failure"?v.Err(`Failed to initiate: ${(s=g.effects)==null?void 0:s.status.error}`):v.Ok(g.digest)}catch(i){return v.Err(i)}}async redeem(t,r){try{const n=await v.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:r,perform_on:"Destination"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return n.error?v.Err(n.error):n.result?v.Ok(n.result):v.Err("Redeem: No result found")}catch(n){return v.Err(String(n))}}async refund(){return v.Err("Refund is taken care of by the relayer")}}class Ih extends v.EventBroker{constructor(t){super(),this.environment=v.Environment.TESTNET,this.getOrderThreshold=20,this.refundSacpCache=new Map,this.bitcoinRedeemCache=new vT,this.isSecretManagementEnabled=!1;const{api:r,environment:n}=$f(t.environment);if(this.environment=n,this._api=r,typeof t.digestKey=="string"){const i=v.DigestKey.from(t.digestKey);if(!i.ok)throw new Error(i.error);this._digestKey=i.val}else this._digestKey=t.digestKey;this._quote=t.quote??new Vb(this._api.quote),this._auth=t.auth??v.Siwe.fromDigestKey(new v.Url(this._api.auth),this._digestKey),this._orderbook=t.orderbook??new be.Orderbook(new v.Url(this._api.orderbook)),this._evmHTLC=t.htlc.evm,this._starknetHTLC=t.htlc.starknet,this._solanaHTLC=t.htlc.solana,this._suiHTLC=t.htlc.sui,this._secretManager=t.secretManager??Do.fromDigestKey(this._digestKey.digestKey),this.orderExecutorCache=new wT,this._blockNumberFetcher=t.blockNumberFetcher??new qb(this._api.info,this.environment);const s=new sw(c_(this.environment));this._btcWallet=hs.fromPrivateKey(this._digestKey.digestKey,s)}handleSecretManagement(t){return this.isSecretManagementEnabled=t,this}static fromWallets(t){let r;if(typeof t.digestKey=="string"){const i=v.DigestKey.from(t.digestKey);if(!i.ok)throw new Error(i.error);r=i.val}else r=t.digestKey;const{api:n}=$f(t.environment);if(!n)throw new Error("API not found, invalid environment "+t.environment);const s={evm:t.wallets.evm?new Jb(n.evmRelay,t.wallets.evm,v.Siwe.fromDigestKey(new v.Url(n.auth),r)):void 0,starknet:t.wallets.starknet?new nw(n.starknetRelay,t.wallets.starknet,t.environment===v.Environment.MAINNET?v.Network.MAINNET:v.Network.TESTNET):void 0,solana:t.wallets.solana?new Ew(t.wallets.solana,new v.Url(n.solanaRelay),t.environment===v.Environment.MAINNET?Cf.mainnet:Cf.testnet,{native:t.solanaProgramAddress&&t.solanaProgramAddress.native?t.solanaProgramAddress.native:Rf.mainnet.native,spl:t.solanaProgramAddress&&t.solanaProgramAddress.spl?t.solanaProgramAddress.spl:Rf.mainnet.spl}):void 0,sui:t.wallets.sui?new S3(n.suiRelay,t.wallets.sui,t.environment===v.Environment.MAINNET?v.Network.MAINNET:v.Network.TESTNET):void 0};return new Ih({htlc:s,...t})}get evmHTLC(){return this._evmHTLC}get starknetHTLC(){return this._starknetHTLC}get solanaHTLC(){return this._solanaHTLC}get suiHTLC(){return this._suiHTLC}get quote(){return this._quote}get btcWallet(){return this._btcWallet}get orderbook(){return this._orderbook}get blockNumberFetcher(){return this._blockNumberFetcher}get secretManager(){return this._secretManager}get auth(){return this._auth}get digestKey(){return this._digestKey}async swap(t){const r=await this.validateAndFillParams(t);if(!r.ok)return v.Err(r.error);const{sendAddress:n,receiveAddress:s}=r.val,i=Date.now().toString();let o;if(this.isSecretManagementEnabled){const w=await this._secretManager.generateSecret(i);if(!w.ok)return v.Err(w.error);o=w.val.secretHash}const{strategyId:a,btcAddress:c}=t.additionalData,l=be.isBitcoin(t.fromAsset.chain),u=be.isBitcoin(t.toAsset.chain),f=l||u;if(!this.isSecretManagementEnabled&&f&&!c)return v.Err("Bitcoin optional recipient is mandatory when secret management is enabled and any chain is Bitcoin");const p={strategy_id:a,...c&&{bitcoin_optional_recipient:c}},d={...!this.isSecretManagementEnabled&&l?{}:{initiator_source_address:n},...!this.isSecretManagementEnabled&&u?{}:{initiator_destination_address:s},...this.isSecretManagementEnabled&&o?{secret_hash:v.trim0x(o)}:{}},m={source_chain:t.fromAsset.chain,destination_chain:t.toAsset.chain,source_asset:t.fromAsset.atomicSwapAddress,destination_asset:t.toAsset.atomicSwapAddress,source_amount:t.sendAmount,destination_amount:t.receiveAmount,nonce:i,...d,additional_data:p,affiliate_fees:this.withDefaultAffiliateFees(t.affiliateFee)};console.log("Creating order",m);const g=await this._orderbook.createOrder(m,this.auth);return g.ok?v.Ok(g.val):v.Err(g.error)}withDefaultAffiliateFees(t){return(t??[]).map(r=>({fee:r.fee,address:r.address,chain:r.chain??Tp.chain,asset:r.asset??Tp.asset}))}async validateAndFillParams(t){if(!t.additionalData.strategyId)return v.Err("StrategyId is required");if(!t.fromAsset||!t.toAsset)return v.Err("Source and destination assets are required for swap");if(t.fromAsset.chain===t.toAsset.chain&&t.fromAsset.atomicSwapAddress===t.toAsset.atomicSwapAddress)return v.Err("Source and destination assets cannot be the same");if(be.isMainnet(t.fromAsset.chain)&&!be.isMainnet(t.toAsset.chain)||!be.isMainnet(t.fromAsset.chain)&&be.isMainnet(t.toAsset.chain))return v.Err("Both assets should be on the same network (either mainnet or testnet)");const r=this.validateAmount(t.sendAmount);if(!r.ok)return v.Err(r.error);const n=this.validateAmount(t.receiveAmount);if(!n.ok)return v.Err(n.error);if(r<n)return v.Err("Send amount should be greater than receive amount");if((be.isBitcoin(t.fromAsset.chain)||be.isBitcoin(t.toAsset.chain))&&!t.additionalData.btcAddress)return v.Err("btcAddress in additionalData is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const s=await this.getAddresses(t.fromAsset.chain);if(!s.ok)return v.Err(s.error);const i=await this.getAddresses(t.toAsset.chain);return i.ok?v.Ok({sendAddress:s.val,receiveAddress:i.val}):v.Err(i.error)}async getAddresses(t){var n;switch(be.getBlockchainType(t)){case be.BlockchainType.EVM:return this._evmHTLC?v.Ok(this._evmHTLC.htlcActorAddress):v.Err("Please provide evmHTLC when initializing garden");case be.BlockchainType.Bitcoin:{const s=await((n=this._btcWallet)==null?void 0:n.getPublicKey());return!s||!o_(s)?v.Err("Invalid btc public key"):v.Ok(Fn(s))}case be.BlockchainType.Solana:return this._solanaHTLC?v.Ok(this._solanaHTLC.htlcActorAddress):v.Err("Please provide solanaHTLC when initializing garden");case be.BlockchainType.Starknet:return this._starknetHTLC?v.Ok(this._starknetHTLC.htlcActorAddress):v.Err("Please provide starknetHTLC when initializing garden");case be.BlockchainType.Sui:return this._suiHTLC?v.Ok(this._suiHTLC.htlcActorAddress):v.Err("Please provide suiHTLC when initializing garden");default:return v.Err("Unsupported chain")}}validateAmount(t){if(t==null||t.includes("."))return v.Err("Invalid amount ",t);const r=new G1(t);return!r.isInteger()||r.isNaN()||r.lt(0)||r.isLessThanOrEqualTo(0)?v.Err("Invalid amount ",t):v.Ok(r)}async execute(t=5e3){return await this._orderbook.subscribeOrders(this._digestKey.userId,!0,t,async r=>{const n=await this.assignStatus(r.data);if(n.ok&&(this.emit("onPendingOrdersChanged",n.val),r.data.length!==0))for(const s of n.val){if(!this.isSecretManagementEnabled){switch(s.status){case ge.Completed:case ge.Redeemed:case ge.CounterPartyRedeemed:{if(!s.destination_swap.redeem_tx_hash)continue;this.orderExecutorCache.set(s,Ae.Redeem,s.destination_swap.redeem_tx_hash),this.emit("success",s,Ae.Redeem,s.destination_swap.redeem_tx_hash);break}}continue}const i=Yd(s.status);if(be.isBitcoin(s.source_swap.chain)&&(s.status===ge.InitiateDetected||s.status===ge.Initiated||s.status===ge.CounterPartyInitiated||s.status===ge.CounterPartyInitiateDetected||s.status===ge.CounterPartyRefundDetected||s.status===ge.CounterPartyRefunded||s.status===ge.CounterPartySwapExpired||s.status===ge.Expired||s.status===ge.DeadLineExceeded)){const o=this._btcWallet;if(!o){this.emit("error",s,"BTC wallet not found");continue}await this.postRefundSACP(s,o)}switch(i){case Ae.Redeem:{const o=await this._secretManager.generateSecret(s.create_order.nonce);if(!o.ok){this.emit("error",s,o.error);return}const a=o.val.secret;switch(be.getBlockchainType(s.destination_swap.chain)){case be.BlockchainType.EVM:await this.evmRedeem(s,a);break;case be.BlockchainType.Bitcoin:{const c=this.btcWallet;if(!c){this.emit("error",s,"BTC wallet not found");return}await this.btcRedeem(c,s,a);break}case be.BlockchainType.Starknet:{await this.starknetRedeem(s,a);break}case be.BlockchainType.Solana:{await this.solRedeem(s,o.val.secret);break}case be.BlockchainType.Sui:{await this.suiRedeem(s,o.val.secret);break}default:this.emit("error",s,"Unsupported chain: "+s.destination_swap.chain)}break}case Ae.Refund:{switch(be.getBlockchainType(s.source_swap.chain)){case be.BlockchainType.Solana:{this.emit("error",s,"Solana refund is automatically done by relay service");break}case be.BlockchainType.EVM:{this.emit("error",s,"EVM refund is automatically done by relay service");break}case be.BlockchainType.Bitcoin:{const o=this.btcWallet;if(!o){this.emit("error",s,"BTC wallet not found");continue}await this.btcRefund(o,s);break}case be.BlockchainType.Starknet:this.emit("error",s,"Starknet refund is automatically done by relay service");break;default:this.emit("error",s,"Unsupported chain: "+s.source_swap.chain)}break}}}},"pending",{per_page:500})}async solRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing sol redeem"),this.orderExecutorCache.get(t,Ae.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._solanaHTLC){this.emit("error",t,"Solana HTLC is required");return}const s=await this._solanaHTLC.redeem(t,r);if(s.error){this.emit("error",t,s.error),s.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,Ae.Redeem,t.destination_swap.redeem_tx_hash);return}s.val&&(this.orderExecutorCache.set(t,Ae.Redeem,s.val),this.emit("success",t,Ae.Redeem,s.val))}async suiRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing sui redeem"),this.orderExecutorCache.get(t,Ae.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._suiHTLC){this.emit("error",t,"Sui HTLC is required");return}const s=await this._suiHTLC.redeem(t,r);if(s.error){this.emit("error",t,s.error),s.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,Ae.Redeem,t.destination_swap.redeem_tx_hash);return}s.val&&(this.orderExecutorCache.set(t,Ae.Redeem,s.val),this.emit("success",t,Ae.Redeem,s.val))}async evmRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing evm redeem"),this.orderExecutorCache.get(t,Ae.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._evmHTLC){this.emit("error",t,"EVMHTLC is required");return}const s=await this._evmHTLC.redeem(t,r);if(!s.ok){this.emit("error",t,s.error),s.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,Ae.Redeem,t.destination_swap.redeem_tx_hash);return}this.orderExecutorCache.set(t,Ae.Redeem,s.val),this.emit("success",t,Ae.Redeem,s.val)}async starknetRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing starknet redeem"),this.orderExecutorCache.get(t,Ae.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._starknetHTLC){this.emit("error",t,"StarknetHTLC is required");return}const s=await this._starknetHTLC.redeem(t,r);if(!s.ok){this.emit("error",t,s.error),s.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,Ae.Redeem,t.destination_swap.redeem_tx_hash);return}s.val&&(this.orderExecutorCache.set(t,Ae.Redeem,s.val),this.emit("success",t,Ae.Redeem,s.val))}async btcRedeem(t,r,n){var a,c,l;const s=this.bitcoinRedeemCache.get(r.create_order.create_id),i=(a=r.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:a.split(":").at(0);if(!i){this.emit("error",r,"Failed to get initiate_tx_hash");return}let o=!1;if(s)if(s.redeemedFromUTXO&&s.redeemedFromUTXO!==i)o=!0,this.emit("log",r.create_order.create_id,"rbf btc redeem");else if(s.redeemedAt&&Date.now()-s.redeemedAt>1e3*60*15)this.emit("log",r.create_order.create_id,"redeem not confirmed in last 15 minutes"),o=!0;else{this.emit("log",r.create_order.create_id,"btcRedeem: already redeemed");return}else if(r.destination_swap.redeem_tx_hash&&!Number(r.destination_swap.redeem_block_number))try{const u=await(await t.getProvider()).getTransaction(r.destination_swap.redeem_tx_hash);let f=!1;for(const p of u.vin)if(p.txid===i){f=!0;break}if(f){this.emit("log",r.create_order.create_id,"already a valid redeem");let p=0;try{const[d]=await(await t.getProvider()).getTransactionTimes([r.destination_swap.redeem_tx_hash]);d!==0&&(p=d)}catch{p=Date.now()}this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:i,redeemedAt:p,redeemTxHash:r.destination_swap.redeem_tx_hash});return}o=!0}catch(u){if(u.message.includes("Transaction not found"))o=!0;else{this.emit("error",r,"Failed to get redeem tx: "+u);return}}this.emit("log",r.create_order.create_id,"executing btc redeem");try{const f=await(await oo.from(t,Number(r.destination_swap.amount),((c=r.create_order)==null?void 0:c.secret_hash)||"",Fn(r.destination_swap.initiator),Fn(r.destination_swap.redeemer),r.destination_swap.timelock,o?[i]:[])).getRedeemHex(v.trim0x(n),(l=r.create_order.additional_data)==null?void 0:l.bitcoin_optional_recipient),p=await this.broadcastRedeemTx(f,r.create_order.create_id);if(!p.ok){this.emit("error",r,p.error||"Failed to broadcast redeem tx");return}o?(this.emit("log",r.create_order.create_id,"rbf: btc redeem success"),this.emit("rbf",r,p.val)):this.emit("success",r,Ae.Redeem,p.val),this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:i,redeemedAt:Date.now(),redeemTxHash:p.val})}catch(u){this.emit("error",r,"Failed btc redeem: "+u)}}async btcRefund(t,r){var n,s;if(!this.orderExecutorCache.get(r,Ae.Refund)){this.emit("log",r.create_order.create_id,"executing btc refund");try{const o=await(await oo.from(t,Number(r.source_swap.amount),((n=r.create_order)==null?void 0:n.secret_hash)||"",Fn(r.source_swap.initiator),Fn(r.source_swap.redeemer),r.source_swap.timelock)).refund((s=r.create_order.additional_data)==null?void 0:s.bitcoin_optional_recipient);this.orderExecutorCache.set(r,Ae.Refund,o),this.emit("success",r,Ae.Refund,o)}catch(i){this.emit("error",r,"Failed btc refund: "+i)}}}async postRefundSACP(t,r){var o;const n=this.refundSacpCache.get(t.create_order.create_id);if((n==null?void 0:n.initTxHash)===t.source_swap.initiate_tx_hash)return;const s=await oo.from(r,Number(t.source_swap.amount),((o=t.create_order)==null?void 0:o.secret_hash)||"",Fn(t.source_swap.initiator),Fn(t.source_swap.redeemer),t.source_swap.timelock);if(t.create_order.additional_data.bitcoin_optional_recipient)try{if(!this._api)return;const a=await this._auth.getAuthHeaders();if(a.error){this.emit("error",t,"Failed to get auth headers: "+a.error);return}const c=await v.Fetcher.post(new v.Url(this._api.orderbook).endpoint("relayer/bitcoin/instant-refund-hash"),{body:JSON.stringify({order_id:t.create_order.create_id}),headers:{"Content-Type":"application/json",...a.val}});if(c.error||!c.result){this.emit("error",t,"Failed to get hash while posting instant refund SACP: "+c.error);return}const l=await s.generateInstantRefundSACPWithHash(c.result),u=new v.Url(this._api.orderbook).endpoint("relayer/bitcoin/instant-refund");(await v.Fetcher.post(u,{headers:{"Content-Type":"application/json",...a.val},body:JSON.stringify({order_id:t.create_order.create_id,signatures:l})})).status==="Ok"&&this.refundSacpCache.set(t.create_order.create_id,{initTxHash:t.source_swap.initiate_tx_hash})}catch(a){this.emit("error",t,"Failed to generate and post SACP: "+a);return}}async assignStatus(t){var s;if(t.length===0)return v.Ok([]);const r=await((s=this._blockNumberFetcher)==null?void 0:s.fetchBlockNumbers());if(!r.ok)return v.Err(r.error);const n=[];for(let i=0;i<t.length;i++){const o=t[i],a=o.source_swap.chain,c=o.destination_swap.chain,l=r==null?void 0:r.val[a],u=r==null?void 0:r.val[c];if(!l||!u){this.emit("error",o,"Error while fetching CurrentBlockNumbers");continue}const f=Xd(o,l,u);n.push({...o,status:f})}return v.Ok(n)}async broadcastRedeemTx(t,r){try{if(!this._api)return v.Err("API not found");const n=new v.Url(this._api.evmRelay).endpoint("/bitcoin/redeem "),s=await this._auth.getAuthHeaders(),o=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...s.val},body:JSON.stringify({redeem_tx_bytes:t,order_id:r})})).json();return o.status==="Ok"&&o.result?v.Ok(o.result):v.Err(o.error)}catch(n){return v.Err("Failed to broadcast redeem tx: "+n)}}}class _3{constructor(t,r,n){this.callData=new it.CallData(Qb),this.account=t,this.starknetProvider=new it.RpcProvider({nodeUrl:r||(n?Mo[n].nodeUrl:Mo.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 it.Contract(rw,n,this.account)}async initiate(t){try{const n=await(await this.getHTLCContract(t)).token();if(!n)throw new Error("Token address retrieval failed");const s=it.num.toHex(n),i=it.cairo.uint256(BigInt(t.source_swap.amount));try{const c=await ew(this.account,s,t.source_swap.asset,BigInt(t.source_swap.amount),this.starknetProvider);if(c.error)return v.Err(c.error)}catch(c){return v.Err(`Allowance check failed: ${c}`)}const{secret_hash:o}=t.create_order;if(!o)return v.Err("Invalid order: secret_hash is undefined");const a=await this.account.execute({contractAddress:t.source_swap.asset,entrypoint:"initiate",calldata:[t.source_swap.redeemer,BigInt(t.source_swap.timelock),i.low,i.high,...v.hexToU32Array(o)]});if(!a.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return v.Ok(a.transaction_hash)}catch(r){return v.Err(`HTLC Initiation Error: ${r}`)}}async redeem(t,r){try{const n=await this.getHTLCContract(t,!0),s=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,i=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:it.CallData.compile({swap_id:s,secret:v.hexToU32Array(r)})});return i.transaction_hash?v.Ok(i.transaction_hash):v.Err("Failed to redeem HTLC transaction")}catch{return v.Err("HTLC Redeem Error")}}async refund(t){try{const r=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,n=await this.getHTLCContract(t),s=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return s.transaction_hash?v.Ok(s.transaction_hash):v.Err("Failed to refund HTLC transaction")}catch{return v.Err("HTLC Refund Error")}}}class k3{constructor(t){if(this.provider=t,!t)throw new Error("Provider is required");this.provider=t,this.program=new sr.Program(zf,t)}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async initiate(t){if(!t)return v.Err("Order is required");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=Wn.from(t),o=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=sr.web3.PublicKey.findProgramAddressSync(o,this.program.programId)[0];const a=await this.program.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction(),c=await this.provider.sendAndConfirm(a);return c?v.Ok(c):v.Err("Failed to initiate HTLC transaction")}catch(r){return v.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(t,r){if(!t)return v.Err("Order is required");if(!r)return v.Err("Secret is required");const{secretHash:n}=Wn.from(t),s=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=sr.web3.PublicKey.findProgramAddressSync(s,this.program.programId)[0];try{const{redeemer:i}=Wn.from(t);if(!this.swapAccount)return v.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const o=await this.program.methods.redeem(vw(r)).accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey,redeemer:i}).transaction(),a=await this.provider.sendAndConfirm(o);return a?v.Ok(a):v.Err("Failed to redeem HTLC transaction")}catch(i){return v.Err(`Error redeeming swap: ${i instanceof Error?i.message:String(i)}`)}}async refund(t){if(!t)return v.Err("Order is required");const{secretHash:r}=Wn.from(t),n=[Buffer.from("swap_account"),Buffer.from(r)];this.swapAccount=sr.web3.PublicKey.findProgramAddressSync(n,this.program.programId)[0];try{if(console.log("Initiating refund for ::",t.source_swap.swap_id),!this.swapAccount)return v.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const s=await this.program.methods.refund().accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey}).transaction(),i=await this.provider.sendAndConfirm(s);return i?v.Ok(i):v.Err("Failed to refund HTLC transaction")}catch(s){return v.Err(`Error refunding swap: ${s instanceof Error?s.message:String(s)}`)}}}exports.API=La;exports.BaseError=z;exports.BitcoinNetwork=Ht;exports.BitcoinProvider=sw;exports.BitcoinWallet=hs;exports.BlockNumberFetcher=qb;exports.EvmRelay=Jb;exports.Garden=Ih;exports.HttpRequestError=ci;exports.OrderActions=Ae;exports.OrderStatus=ge;exports.ParseOrderStatus=Xd;exports.ParseSwapStatus=jf;exports.Quote=Vb;exports.STARKNET_CONFIG=Mo;exports.SecretManager=Do;exports.SolanaHTLC=k3;exports.SolanaRelay=Ew;exports.SolanaRelayerAddress=Cf;exports.StarknetHTLC=_3;exports.StarknetRelay=nw;exports.SwapStatus=Ne;exports.botanixMainnet=Kb;exports.call=ra;exports.checkAllowance=ao;exports.checkAllowanceAndApprove=ew;exports.concat=Vt;exports.constructOrderPair=Uf;exports.decodeErrorResult=g0;exports.encodeAbiParameters=kn;exports.evmToViemChainMap=uh;exports.filterDeadlineExpiredOrders=d_;exports.getUrl=vc;exports.hyperliquid=Yb;exports.hyperliquidTestnet=Xb;exports.isAddressEqual=ta;exports.isAllowanceSufficient=tw;exports.isExpired=Fo;exports.isHex=xr;exports.isOrderExpired=hb;exports.localBatchGatewayRequest=gg;exports.localBatchGatewayUrl=Cc;exports.parseAction=f_;exports.parseActionFromStatus=Yd;exports.resolveApiConfig=$f;exports.solanaProgramAddress=Rf;exports.stringify=Ze;exports.switchOrAddNetwork=Zb;exports.toXOnly=Fn;exports.validateBTCAddress=a_;
|
|
105
|
+
${String(n)}`);Xf(t);for(let s=0;s<t.callbacks.length;s++){const i=n[s];i instanceof Error?t.callbacks[s].reject(i):t.callbacks[s].resolve(i)}}).catch(n=>{Vl(e,t,n)})}function Vl(e,t,r){Xf(t);for(let n=0;n<t.keys.length;n++)e.clear(t.keys[n]),t.callbacks[n].reject(r)}function Xf(e){if(e.cacheHits)for(let t=0;t<e.cacheHits.length;t++)e.cacheHits[t]()}function MP(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 FP(e){const t=e&&e.batchScheduleFn;if(t===void 0)return $P;if(typeof t!="function")throw new TypeError(`batchScheduleFn must be a function: ${t}`);return t}function jP(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 LP(e){if(!(!e||e.cache!==!1))return null;const r=e&&e.cacheMap;if(r===void 0)return new Map;if(r!==null){const s=["get","set","delete","clear"].filter(i=>r&&typeof r[i]!="function");if(s.length!==0)throw new TypeError("Custom cacheMap missing methods: "+s.join(", "))}return r}function DP(e){return e&&e.name?e.name:null}function Mw(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 oc(e){const t=[];let r=0;if(e===0)return[0];for(;e>0;)t[r]=e&127,(e>>=7)&&(t[r]|=128),r+=1;return t}function HP(e){let t=0,r=0,n=0;for(;;){const s=e[n];if(n+=1,t|=(s&127)<<r,!(s&128))break;r+=7}return{value:t,length:n}}class zP{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:s}=HP(r);return this.shift(s),n}readVec(t){const r=this.readULEB(),n=[];for(let s=0;s<r;s++)n.push(t(this,s,r));return n}}function qP(e,t){switch(t){case"base58":return ru(e);case"base64":return mt(e);case"hex":return Si(e);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}function Fw(e,t=["<",">"]){const[r,n]=t,s=[];let i="",o=0;for(let a=0;a<e.length;a++){const c=e[a];if(c===r&&o++,c===n&&o--,o===0&&c===","){s.push(i.trim()),i="";continue}i+=c}return s.push(i.trim()),s}class VP{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,this.size+this.allocateSize);if(r>n)throw new Error(`Attempting to serialize to BCS, but buffer does not have enough size. Allocated size: ${this.size}, Max size: ${this.maxSize}, Required size: ${r}`);this.size=n;const s=new ArrayBuffer(this.size);new Uint8Array(s).set(new Uint8Array(this.dataView.buffer)),this.dataView=new DataView(s)}}shift(t){return this.bytePosition+=t,this}write8(t){return this.ensureSizeOrGrow(1),this.dataView.setUint8(this.bytePosition,Number(t)),this.shift(1)}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 Gl(BigInt(t),8).forEach(r=>this.write8(r)),this}write128(t){return Gl(BigInt(t),16).forEach(r=>this.write8(r)),this}write256(t){return Gl(BigInt(t),32).forEach(r=>this.write8(r)),this}writeULEB(t){return oc(t).forEach(r=>this.write8(r)),this}writeVec(t,r){return this.writeULEB(t.length),Array.from(t).forEach((n,s)=>r(this,n,s,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 qP(this.toBytes(),t)}}function Gl(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 jw=e=>{throw TypeError(e)},Lw=(e,t,r)=>t.has(e)||jw("Cannot "+r),mr=(e,t,r)=>(Lw(e,t,"read from private field"),r?r.call(e):t.get(e)),ac=(e,t,r)=>t.has(e)?jw("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),cc=(e,t,r,n)=>(Lw(e,t,"write to private field"),t.set(e,r),r),ni,eo,Wa,Dn;const GP=class Dw{constructor(t){ac(this,ni),ac(this,eo),this.name=t.name,this.read=t.read,this.serializedSize=t.serializedSize??(()=>null),cc(this,ni,t.write),cc(this,eo,t.serialize??((r,n)=>{const s=new VP({initialSize:this.serializedSize(r)??void 0,...n});return mr(this,ni).call(this,r,s),s.toBytes()})),this.validate=t.validate??(()=>{})}write(t,r){this.validate(t),mr(this,ni).call(this,t,r)}serialize(t,r){return this.validate(t),new WP(this,mr(this,eo).call(this,t,r))}parse(t){const r=new zP(t);return this.read(r)}fromHex(t){return this.parse(Nw(t))}fromBase58(t){return this.parse(zo(t))}fromBase64(t){return this.parse(zt(t))}transform({name:t,input:r,output:n,validate:s}){return new Dw({name:t??this.name,read:i=>n?n(this.read(i)):this.read(i),write:(i,o)=>mr(this,ni).call(this,r?r(i):i,o),serializedSize:i=>this.serializedSize(r?r(i):i),serialize:(i,o)=>mr(this,eo).call(this,r?r(i):i,o),validate:i=>{s==null||s(i),this.validate(r?r(i):i)}})}};ni=new WeakMap;eo=new WeakMap;let Xr=GP;const Hw=Symbol.for("@mysten/serialized-bcs");function mh(e){return!!e&&typeof e=="object"&&e[Hw]===!0}class WP{constructor(t,r){ac(this,Wa),ac(this,Dn),cc(this,Wa,t),cc(this,Dn,r)}get[Hw](){return!0}toBytes(){return mr(this,Dn)}toHex(){return Si(mr(this,Dn))}toBase64(){return mt(mr(this,Dn))}toBase58(){return ru(mr(this,Dn))}parse(){return mr(this,Wa).parse(mr(this,Dn))}}Wa=new WeakMap;Dn=new WeakMap;function uc({size:e,...t}){return new Xr({...t,serializedSize:()=>e})}function Wl({readMethod:e,writeMethod:t,...r}){return uc({...r,read:n=>n[e](),write:(n,s)=>s[t](n),validate:n=>{var s;if(n<0||n>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${n}. Expected value in range 0-${r.maxValue}`);(s=r.validate)==null||s.call(r,n)}})}function Kl({readMethod:e,writeMethod:t,...r}){return uc({...r,read:n=>n[e](),write:(n,s)=>s[t](BigInt(n)),validate:n=>{var i;const s=BigInt(n);if(s<0||s>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${s}. Expected value in range 0-${r.maxValue}`);(i=r.validate)==null||i.call(r,s)}})}function KP({serialize:e,...t}){const r=new Xr({...t,serialize:e,write:(n,s)=>{for(const i of r.serialize(n).toBytes())s.write8(i)}});return r}function XP({toBytes:e,fromBytes:t,...r}){return new Xr({...r,read:n=>{const s=n.readULEB(),i=n.readBytes(s);return t(i)},write:(n,s)=>{const i=e(n);s.writeULEB(i.length);for(let o=0;o<i.length;o++)s.write8(i[o])},serialize:n=>{const s=e(n),i=oc(s.length),o=new Uint8Array(i.length+s.length);return o.set(i,0),o.set(s,i.length),o},validate:n=>{var s;if(typeof n!="string")throw new TypeError(`Invalid ${r.name} value: ${n}. Expected string`);(s=r.validate)==null||s.call(r,n)}})}function YP(e){let t=null;function r(){return t||(t=e()),t}return new Xr({name:"lazy",read:n=>r().read(n),serializedSize:n=>r().serializedSize(n),write:(n,s)=>r().write(n,s),serialize:(n,s)=>r().serialize(n,s).toBytes()})}class ZP extends Xr{constructor({name:t,fields:r,...n}){const s=Object.entries(r);super({name:t,serializedSize:i=>{let o=0;for(const[a,c]of s){const l=c.serializedSize(i[a]);if(l==null)return null;o+=l}return o},read:i=>{const o={};for(const[a,c]of s)o[a]=c.read(i);return o},write:(i,o)=>{for(const[a,c]of s)c.write(i[a],o)},...n,validate:i=>{var o;if((o=n==null?void 0:n.validate)==null||o.call(n,i),typeof i!="object"||i==null)throw new TypeError(`Expected object, found ${typeof i}`)}})}}class JP extends Xr{constructor({fields:t,...r}){const n=Object.entries(t);super({read:s=>{const i=s.readULEB(),o=n[i];if(!o)throw new TypeError(`Unknown value ${i} for enum ${name}`);const[a,c]=o;return{[a]:(c==null?void 0:c.read(s))??!0,$kind:a}},write:(s,i)=>{const[o,a]=Object.entries(s).filter(([c])=>Object.hasOwn(t,c))[0];for(let c=0;c<n.length;c++){const[l,u]=n[c];if(l===o){i.writeULEB(c),u==null||u.write(a,i);return}}},...r,validate:s=>{var a;if((a=r==null?void 0:r.validate)==null||a.call(r,s),typeof s!="object"||s==null)throw new TypeError(`Expected object, found ${typeof s}`);const i=Object.keys(s).filter(c=>s[c]!==void 0&&Object.hasOwn(t,c));if(i.length!==1)throw new TypeError(`Expected object with one key, but found ${i.length} for type ${name}}`);const[o]=i;if(!Object.hasOwn(t,o))throw new TypeError(`Invalid enum variant ${o}`)}})}}class QP extends Xr{constructor({fields:t,name:r,...n}){super({name:r??`(${t.map(s=>s.name).join(", ")})`,serializedSize:s=>{let i=0;for(let o=0;o<t.length;o++){const a=t[o].serializedSize(s[o]);if(a==null)return null;i+=a}return i},read:s=>{const i=[];for(const o of t)i.push(o.read(s));return i},write:(s,i)=>{for(let o=0;o<t.length;o++)t[o].write(s[o],i)},...n,validate:s=>{var i;if((i=n==null?void 0:n.validate)==null||i.call(n,s),!Array.isArray(s))throw new TypeError(`Expected array, found ${typeof s}`);if(s.length!==t.length)throw new TypeError(`Expected array of length ${t.length}, found ${s.length}`)}})}}function e5(e,t,r){return new Xr({read:n=>{const s=new Array(e);for(let i=0;i<e;i++)s[i]=t.read(n);return s},write:(n,s)=>{for(const i of n)t.write(i,s)},...r,name:(r==null?void 0:r.name)??`${t.name}[${e}]`,validate:n=>{var s;if((s=r==null?void 0:r.validate)==null||s.call(r,n),!n||typeof n!="object"||!("length"in n))throw new TypeError(`Expected array, found ${typeof n}`);if(n.length!==e)throw new TypeError(`Expected array of length ${e}, found ${n.length}`)}})}function t5(e){return _.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 r5(e,t){return new Xr({read:r=>{const n=r.readULEB(),s=new Array(n);for(let i=0;i<n;i++)s[i]=e.read(r);return s},write:(r,n)=>{n.writeULEB(r.length);for(const s of r)e.write(s,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 n5(e,t){return _.vector(_.tuple([e,t])).transform({name:`Map<${e.name}, ${t.name}>`,input:r=>[...r.entries()],output:r=>{const n=new Map;for(const[s,i]of r)n.set(s,i);return n}})}const _={u8(e){return Wl({readMethod:"read8",writeMethod:"write8",size:1,maxValue:2**8-1,...e,name:(e==null?void 0:e.name)??"u8"})},u16(e){return Wl({readMethod:"read16",writeMethod:"write16",size:2,maxValue:2**16-1,...e,name:(e==null?void 0:e.name)??"u16"})},u32(e){return Wl({readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...e,name:(e==null?void 0:e.name)??"u32"})},u64(e){return Kl({readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...e,name:(e==null?void 0:e.name)??"u64"})},u128(e){return Kl({readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...e,name:(e==null?void 0:e.name)??"u128"})},u256(e){return Kl({readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...e,name:(e==null?void 0:e.name)??"u256"})},bool(e){return uc({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 KP({read:t=>t.readULEB(),serialize:t=>Uint8Array.from(oc(t)),...e,name:(e==null?void 0:e.name)??"uleb128"})},bytes(e,t){return uc({size:e,read:r=>r.readBytes(e),write:(r,n)=>{const s=new Uint8Array(r);for(let i=0;i<e;i++)n.write8(s[i]??0)},...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 Xr({read:t=>{const r=t.readULEB();return t.readBytes(r)},write:(t,r)=>{const n=new Uint8Array(t);r.writeULEB(n.length);for(let s=0;s<n.length;s++)r.write8(n[s]??0)},...e,name:(e==null?void 0:e.name)??"vector<u8>",serializedSize:t=>{const r="length"in t?t.length:null;return r==null?null:oc(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 XP({toBytes:t=>new TextEncoder().encode(t),fromBytes:t=>new TextDecoder().decode(t),...e,name:(e==null?void 0:e.name)??"string"})},fixedArray:e5,option:t5,vector:r5,tuple(e,t){return new QP({fields:e,...t})},struct(e,t,r){return new ZP({name:e,fields:t,...r})},enum(e,t,r){return new JP({name:e,fields:t,...r})},map:n5,lazy(e){return YP(e)}};var zw=e=>{throw TypeError(e)},qw=(e,t,r)=>t.has(e)||zw("Cannot "+r),pt=(e,t,r)=>(qw(e,t,"read from private field"),t.get(e)),im=(e,t,r)=>t.has(e)?zw("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),om=(e,t,r,n)=>(qw(e,t,"write to private field"),t.set(e,r),r),cs,kt;const s5=class Vw{constructor({prefix:t,cache:r}={}){im(this,cs),im(this,kt),om(this,cs,t??[]),om(this,kt,r??new Map)}read(t,r){const n=[pt(this,cs),...t].join(":");if(pt(this,kt).has(n))return pt(this,kt).get(n);const s=r();return pt(this,kt).set(n,s),typeof s=="object"&&s!==null&&"then"in s?Promise.resolve(s).then(i=>(pt(this,kt).set(n,i),i)).catch(i=>{throw pt(this,kt).delete(n),i}):s}readSync(t,r){const n=[pt(this,cs),...t].join(":");if(pt(this,kt).has(n))return pt(this,kt).get(n);const s=r();return pt(this,kt).set(n,s),s}clear(t){const r=[...pt(this,cs),...t??[]].join(":");if(!r){pt(this,kt).clear();return}for(const n of pt(this,kt).keys())n.startsWith(r)&&pt(this,kt).delete(n)}scope(t){return new Vw({prefix:[...pt(this,cs),...Array.isArray(t)?t:[t]],cache:pt(this,kt)})}};cs=new WeakMap;kt=new WeakMap;let i5=s5;class Gw{constructor({network:t,base:r,cache:n=(r==null?void 0:r.cache)??new i5}){this.network=t,this.base=r??this,this.cache=n}$extend(...t){return Object.create(this,Object.fromEntries(t.map(r=>{if("experimental_asClientExtension"in r){const{name:n,register:s}=r.experimental_asClientExtension();return[n,{value:s(this)}]}return[r.name,{value:r.register(this)}]})))}}const Ww=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,Kw=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i,o5=235;function a5(e){return e.length>o5?!1:e.includes("@")?Ww.test(e):Kw.test(e)}function c5(e,t="at"){const r=e.toLowerCase();let n;if(r.includes("@")){if(!Ww.test(r))throw new Error(`Invalid SuiNS name ${e}`);const[s,i]=r.split("@");n=[...s?s.split("."):[],i]}else{if(!Kw.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 u5=/^([a-z0-9]+(?:-[a-z0-9]+)*)$/,l5=/^\d+$/,f5=64,Xw="/",Dt=e=>{const t=e.split(Xw);if(t.length<2||t.length>3)return!1;const[r,n,s]=t;return s!==void 0&&!l5.test(s)||!a5(r)?!1:u5.test(n)&&n.length<f5},d5=e=>{const t=e.split(/::|<|>|,/);for(const r of t)if(r.includes(Xw)&&!Dt(r))return!1;return!0},h5=32;function am(e){try{return zo(e).length===h5}catch{return!1}}const su=32;function gr(e){return y5(e)&&m5(e)===su}function $a(e){return gr(e)}function p5(e){return e.includes("::")?Ns(e):e}function Ns(e){const[t,r]=e.split("::"),n=Dt(t),s=e.slice(t.length+r.length+4),i=s.includes("<")?s.slice(0,s.indexOf("<")):s,o=s.includes("<")?Fw(s.slice(s.indexOf("<")+1,s.lastIndexOf(">"))).map(a=>p5(a.trim())):[];return{address:n?t:xe(t),module:r,name:i,typeParams:o}}function lc(e){const{address:t,module:r,name:n,typeParams:s}=typeof e=="string"?Ns(e):e,i=(s==null?void 0:s.length)>0?`<${s.map(o=>typeof o=="string"?o:lc(o)).join(",")}>`:"";return`${t}::${r}::${n}${i}`}function xe(e,t=!1){let r=e.toLowerCase();return!t&&r.startsWith("0x")&&(r=r.slice(2)),`0x${r.padStart(su*2,"0")}`}function pn(e,t=!1){return xe(e,t)}function y5(e){return/^(0x|0X)?[a-fA-F0-9]+$/.test(e)&&e.length%2===0}function m5(e){return/^(0x|0X)/.test(e)?(e.length-2)/2:e.length/2}const g5=/^vector<(.+)>$/,b5=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class wr{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(g5);if(n)return{vector:wr.parseFromStr(n[1],r)};const s=t.match(b5);if(s)return{struct:{address:r?xe(s[1]):s[1],module:s[2],name:s[3],typeParams:s[5]===void 0?[]:wr.parseStructTypeArgs(s[5],r)}};throw new Error(`Encountered unexpected token when parsing type args for ${t}`)}static parseStructTypeArgs(t,r=!1){return Fw(t).map(n=>wr.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<${wr.tagToString(t.vector)}>`;if("struct"in t){const r=t.struct,n=r.typeParams.map(wr.tagToString).join(", ");return`${r.address}::${r.module}::${r.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}function w5(e){return _.u64({name:"unsafe_u64",...e}).transform({input:t=>t,output:t=>Number(t)})}function v5(e){return _.enum("Option",{None:null,Some:e})}const Re=_.bytes(su).transform({validate:e=>{const t=typeof e=="string"?e:Si(e);if(!t||!gr(xe(t)))throw new Error(`Invalid Sui address ${t}`)},input:e=>typeof e=="string"?Nw(xe(e)):e,output:e=>xe(Si(e))}),Er=_.vector(_.u8()).transform({name:"ObjectDigest",input:e=>zo(e),output:e=>ru(new Uint8Array(e)),validate:e=>{if(zo(e).length!==32)throw new Error("ObjectDigest must be 32 bytes")}}),tr=_.struct("SuiObjectRef",{objectId:Re,version:_.u64(),digest:Er}),Yw=_.struct("SharedObjectRef",{objectId:Re,initialSharedVersion:_.u64(),mutable:_.bool()}),Zw=_.enum("ObjectArg",{ImmOrOwnedObject:tr,SharedObject:Yw,Receiving:tr}),ms=_.enum("Owner",{AddressOwner:Re,ObjectOwner:Re,Shared:_.struct("Shared",{initialSharedVersion:_.u64()}),Immutable:null,ConsensusAddressOwner:_.struct("ConsensusAddressOwner",{owner:Re,startVersion:_.u64()})}),Jw=_.enum("CallArg",{Pure:_.struct("Pure",{bytes:_.vector(_.u8()).transform({input:e=>typeof e=="string"?zt(e):e,output:e=>mt(new Uint8Array(e))})}),Object:Zw}),gh=_.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:_.lazy(()=>gh),struct:_.lazy(()=>s1),u16:null,u32:null,u256:null}),bh=gh.transform({input:e=>typeof e=="string"?wr.parseFromStr(e,!0):e,output:e=>wr.tagToString(e)}),Dr=_.enum("Argument",{GasCoin:null,Input:_.u16(),Result:_.u16(),NestedResult:_.tuple([_.u16(),_.u16()])}),Qw=_.struct("ProgrammableMoveCall",{package:Re,module:_.string(),function:_.string(),typeArguments:_.vector(bh),arguments:_.vector(Dr)}),e1=_.enum("Command",{MoveCall:Qw,TransferObjects:_.struct("TransferObjects",{objects:_.vector(Dr),address:Dr}),SplitCoins:_.struct("SplitCoins",{coin:Dr,amounts:_.vector(Dr)}),MergeCoins:_.struct("MergeCoins",{destination:Dr,sources:_.vector(Dr)}),Publish:_.struct("Publish",{modules:_.vector(_.vector(_.u8()).transform({input:e=>typeof e=="string"?zt(e):e,output:e=>mt(new Uint8Array(e))})),dependencies:_.vector(Re)}),MakeMoveVec:_.struct("MakeMoveVec",{type:v5(bh).transform({input:e=>e===null?{None:!0}:{Some:e},output:e=>e.Some??null}),elements:_.vector(Dr)}),Upgrade:_.struct("Upgrade",{modules:_.vector(_.vector(_.u8()).transform({input:e=>typeof e=="string"?zt(e):e,output:e=>mt(new Uint8Array(e))})),dependencies:_.vector(Re),package:Re,ticket:Dr})}),t1=_.struct("ProgrammableTransaction",{inputs:_.vector(Jw),commands:_.vector(e1)}),r1=_.enum("TransactionKind",{ProgrammableTransaction:t1,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),n1=_.enum("TransactionExpiration",{None:null,Epoch:w5()}),s1=_.struct("StructTag",{address:Re,module:_.string(),name:_.string(),typeParams:_.vector(gh)}),i1=_.struct("GasData",{payment:_.vector(tr),owner:Re,price:_.u64(),budget:_.u64()}),o1=_.struct("TransactionDataV1",{kind:r1,sender:Re,gasData:i1,expiration:n1}),a1=_.enum("TransactionData",{V1:o1}),c1=_.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),u1=_.enum("IntentVersion",{V0:null}),l1=_.enum("AppId",{Sui:null}),f1=_.struct("Intent",{scope:c1,version:u1,appId:l1});function d1(e){return _.struct(`IntentMessage<${e.name}>`,{intent:f1,value:e})}const h1=_.enum("CompressedSignature",{ED25519:_.fixedArray(64,_.u8()),Secp256k1:_.fixedArray(64,_.u8()),Secp256r1:_.fixedArray(64,_.u8()),ZkLogin:_.vector(_.u8()),Passkey:_.vector(_.u8())}),p1=_.enum("PublicKey",{ED25519:_.fixedArray(32,_.u8()),Secp256k1:_.fixedArray(33,_.u8()),Secp256r1:_.fixedArray(33,_.u8()),ZkLogin:_.vector(_.u8()),Passkey:_.fixedArray(33,_.u8())}),y1=_.struct("MultiSigPkMap",{pubKey:p1,weight:_.u8()}),m1=_.struct("MultiSigPublicKey",{pk_map:_.vector(y1),threshold:_.u16()}),E5=_.struct("MultiSig",{sigs:_.vector(h1),bitmap:_.u16(),multisig_pk:m1}),A5=_.vector(_.u8()).transform({input:e=>typeof e=="string"?zt(e):e,output:e=>mt(new Uint8Array(e))}),g1=_.struct("SenderSignedTransaction",{intentMessage:d1(a1),txSignatures:_.vector(A5)}),x5=_.vector(g1,{name:"SenderSignedData"}),S5=_.struct("PasskeyAuthenticator",{authenticatorData:_.vector(_.u8()),clientDataJson:_.string(),userSignature:_.vector(_.u8())}),_5=_.enum("PackageUpgradeError",{UnableToFetchPackage:_.struct("UnableToFetchPackage",{packageId:Re}),NotAPackage:_.struct("NotAPackage",{objectId:Re}),IncompatibleUpgrade:null,DigestDoesNotMatch:_.struct("DigestDoesNotMatch",{digest:_.vector(_.u8())}),UnknownUpgradePolicy:_.struct("UnknownUpgradePolicy",{policy:_.u8()}),PackageIDDoesNotMatch:_.struct("PackageIDDoesNotMatch",{packageId:Re,ticketId:Re})}),k5=_.struct("ModuleId",{address:Re,name:_.string()}),cm=_.struct("MoveLocation",{module:k5,function:_.u16(),instruction:_.u16(),functionName:_.option(_.string())}),T5=_.enum("CommandArgumentError",{TypeMismatch:null,InvalidBCSBytes:null,InvalidUsageOfPureArg:null,InvalidArgumentToPrivateEntryFunction:null,IndexOutOfBounds:_.struct("IndexOutOfBounds",{idx:_.u16()}),SecondaryIndexOutOfBounds:_.struct("SecondaryIndexOutOfBounds",{resultIdx:_.u16(),secondaryIdx:_.u16()}),InvalidResultArity:_.struct("InvalidResultArity",{resultIdx:_.u16()}),InvalidGasCoinUsage:null,InvalidValueUsage:null,InvalidObjectByValue:null,InvalidObjectByMutRef:null,SharedObjectOperationNotAllowed:null}),I5=_.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),P5=_.enum("ExecutionFailureStatus",{InsufficientGas:null,InvalidGasObject:null,InvariantViolation:null,FeatureNotYetSupported:null,MoveObjectTooBig:_.struct("MoveObjectTooBig",{objectSize:_.u64(),maxObjectSize:_.u64()}),MovePackageTooBig:_.struct("MovePackageTooBig",{objectSize:_.u64(),maxObjectSize:_.u64()}),CircularObjectOwnership:_.struct("CircularObjectOwnership",{object:Re}),InsufficientCoinBalance:null,CoinBalanceOverflow:null,PublishErrorNonZeroAddress:null,SuiMoveVerificationError:null,MovePrimitiveRuntimeError:_.option(cm),MoveAbort:_.tuple([cm,_.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:_.struct("CommandArgumentError",{argIdx:_.u16(),kind:T5}),TypeArgumentError:_.struct("TypeArgumentError",{argumentIdx:_.u16(),kind:I5}),UnusedValueWithoutDrop:_.struct("UnusedValueWithoutDrop",{resultIdx:_.u16(),secondaryIdx:_.u16()}),InvalidPublicFunctionReturnType:_.struct("InvalidPublicFunctionReturnType",{idx:_.u16()}),InvalidTransferObject:null,EffectsTooLarge:_.struct("EffectsTooLarge",{currentSize:_.u64(),maxSize:_.u64()}),PublishUpgradeMissingDependency:null,PublishUpgradeDependencyDowngrade:null,PackageUpgradeError:_.struct("PackageUpgradeError",{upgradeError:_5}),WrittenObjectsTooLarge:_.struct("WrittenObjectsTooLarge",{currentSize:_.u64(),maxSize:_.u64()}),CertificateDenied:null,SuiMoveVerificationTimedout:null,SharedObjectOperationNotAllowed:null,InputObjectDeleted:null,ExecutionCancelledDueToSharedObjectCongestion:_.struct("ExecutionCancelledDueToSharedObjectCongestion",{congestedObjects:_.vector(Re)}),AddressDeniedForCoin:_.struct("AddressDeniedForCoin",{address:Re,coinType:_.string()}),CoinTypeGlobalPause:_.struct("CoinTypeGlobalPause",{coinType:_.string()}),ExecutionCancelledDueToRandomnessUnavailable:null}),b1=_.enum("ExecutionStatus",{Success:null,Failed:_.struct("ExecutionFailed",{error:P5,command:_.option(_.u64())})}),w1=_.struct("GasCostSummary",{computationCost:_.u64(),storageCost:_.u64(),storageRebate:_.u64(),nonRefundableStorageFee:_.u64()}),O5=_.struct("TransactionEffectsV1",{status:b1,executedEpoch:_.u64(),gasUsed:w1,modifiedAtVersions:_.vector(_.tuple([Re,_.u64()])),sharedObjects:_.vector(tr),transactionDigest:Er,created:_.vector(_.tuple([tr,ms])),mutated:_.vector(_.tuple([tr,ms])),unwrapped:_.vector(_.tuple([tr,ms])),deleted:_.vector(tr),unwrappedThenDeleted:_.vector(tr),wrapped:_.vector(tr),gasObject:_.tuple([tr,ms]),eventsDigest:_.option(Er),dependencies:_.vector(Er)}),wh=_.tuple([_.u64(),Er]),B5=_.enum("ObjectIn",{NotExist:null,Exist:_.tuple([wh,ms])}),C5=_.enum("ObjectOut",{NotExist:null,ObjectWrite:_.tuple([Er,ms]),PackageWrite:wh}),R5=_.enum("IDOperation",{None:null,Created:null,Deleted:null}),$5=_.struct("EffectsObjectChange",{inputState:B5,outputState:C5,idOperation:R5}),N5=_.enum("UnchangedSharedKind",{ReadOnlyRoot:wh,MutateDeleted:_.u64(),ReadDeleted:_.u64(),Cancelled:_.u64(),PerEpochConfig:null}),U5=_.struct("TransactionEffectsV2",{status:b1,executedEpoch:_.u64(),gasUsed:w1,transactionDigest:Er,gasObjectIndex:_.option(_.u32()),eventsDigest:_.option(Er),dependencies:_.vector(Er),lamportVersion:_.u64(),changedObjects:_.vector(_.tuple([Re,$5])),unchangedSharedObjects:_.vector(_.tuple([Re,N5])),auxDataDigest:_.option(Er)}),M5=_.enum("TransactionEffects",{V1:O5,V2:U5});function fo(e){switch(e){case"u8":return _.u8();case"u16":return _.u16();case"u32":return _.u32();case"u64":return _.u64();case"u128":return _.u128();case"u256":return _.u256();case"bool":return _.bool();case"string":return _.string();case"id":case"address":return Re}const t=e.match(/^(vector|option)<(.+)>$/);if(t){const[r,n]=t.slice(1);return r==="vector"?_.vector(fo(n)):_.option(fo(n))}throw new Error(`Invalid Pure type name: ${e}`)}const de={..._,U8:_.u8(),U16:_.u16(),U32:_.u32(),U64:_.u64(),U128:_.u128(),U256:_.u256(),ULEB128:_.uleb128(),Bool:_.bool(),String:_.string(),Address:Re,AppId:l1,Argument:Dr,CallArg:Jw,Command:e1,CompressedSignature:h1,GasData:i1,Intent:f1,IntentMessage:d1,IntentScope:c1,IntentVersion:u1,MultiSig:E5,MultiSigPkMap:y1,MultiSigPublicKey:m1,ObjectArg:Zw,ObjectDigest:Er,Owner:ms,PasskeyAuthenticator:S5,ProgrammableMoveCall:Qw,ProgrammableTransaction:t1,PublicKey:p1,SenderSignedData:x5,SenderSignedTransaction:g1,SharedObjectRef:Yw,StructTag:s1,SuiObjectRef:tr,TransactionData:a1,TransactionDataV1:o1,TransactionEffects:M5,TransactionExpiration:n1,TransactionKind:r1,TypeTag:bh};var nn;function F5(e){return{lang:(e==null?void 0:e.lang)??(nn==null?void 0:nn.lang),message:e==null?void 0:e.message,abortEarly:(e==null?void 0:e.abortEarly)??(nn==null?void 0:nn.abortEarly),abortPipeEarly:(e==null?void 0:e.abortPipeEarly)??(nn==null?void 0:nn.abortPipeEarly)}}var Xl;function j5(e){return Xl==null?void 0:Xl.get(e)}var Yl;function L5(e){return Yl==null?void 0:Yl.get(e)}var Zl;function D5(e,t){var r;return(r=Zl==null?void 0:Zl.get(e))==null?void 0:r.get(t)}function v1(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 Wt(e,t,r,n,s){const i=s&&"input"in s?s.input:r.value,o=(s==null?void 0:s.expected)??e.expects??null,a=(s==null?void 0:s.received)??v1(i),c={kind:e.kind,type:e.type,input:i,expected:o,received:a,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:e.requirement,path:s==null?void 0:s.path,issues:s==null?void 0:s.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},l=e.kind==="schema",u=(s==null?void 0:s.message)??e.message??D5(e.reference,c.lang)??(l?L5(c.lang):null)??n.message??j5(c.lang);u&&(c.message=typeof u=="function"?u(c):u),l&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function H5(e,t){return Object.hasOwn(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}var z5=class extends Error{constructor(t){super(t[0].message);Ph(this,"issues");this.name="ValiError",this.issues=t}};function fa(e,t){return{kind:"validation",type:"check",reference:fa,async:!1,expects:null,requirement:e,message:t,_run(r,n){return r.typed&&!this.requirement(r.value)&&Wt(this,"input",r,n),r}}}function Ge(e){return{kind:"validation",type:"integer",reference:Ge,async:!1,expects:null,requirement:Number.isInteger,message:e,_run(t,r){return t.typed&&!this.requirement(t.value)&&Wt(this,"integer",t,r),t}}}function iu(e){return{kind:"transformation",type:"transform",reference:iu,async:!1,operation:e,_run(t){return t.value=this.operation(t.value),t}}}function vh(e,t,r){return typeof e.default=="function"?e.default(t,r):e.default}function Yf(e,t){return!e._run({typed:!1,value:t},{abortEarly:!0}).issues}function ue(e,t){return{kind:"schema",type:"array",reference:ue,expects:"Array",async:!1,item:e,message:t,_run(r,n){var i;const s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let o=0;o<s.length;o++){const a=s[o],c=this.item._run({typed:!1,value:a},n);if(c.issues){const l={type:"array",origin:"value",input:s,key:o,value:a};for(const u of c.issues)u.path?u.path.unshift(l):u.path=[l],(i=r.issues)==null||i.push(u);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else Wt(this,"type",r,n);return r}}}function Eh(e){return{kind:"schema",type:"bigint",reference:Eh,expects:"bigint",async:!1,message:e,_run(t,r){return typeof t.value=="bigint"?t.typed=!0:Wt(this,"type",t,r),t}}}function ou(e){return{kind:"schema",type:"boolean",reference:ou,expects:"boolean",async:!1,message:e,_run(t,r){return typeof t.value=="boolean"?t.typed=!0:Wt(this,"type",t,r),t}}}function qo(e){return{kind:"schema",type:"lazy",reference:qo,expects:"unknown",async:!1,getter:e,_run(t,r){return this.getter(t.value)._run(t,r)}}}function le(e,t){return{kind:"schema",type:"literal",reference:le,expects:v1(e),async:!1,literal:e,message:t,_run(r,n){return r.value===this.literal?r.typed=!0:Wt(this,"type",r,n),r}}}function Ee(e,...t){const r={kind:"schema",type:"nullable",reference:Ee,expects:`${e.expects} | null`,async:!1,wrapped:e,_run(n,s){return n.value===null&&("default"in this&&(n.value=vh(this,n,s)),n.value===null)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in t&&(r.default=t[0]),r}function _i(e,...t){const r={kind:"schema",type:"nullish",reference:_i,expects:`${e.expects} | null | undefined`,async:!1,wrapped:e,_run(n,s){return(n.value===null||n.value===void 0)&&("default"in this&&(n.value=vh(this,n,s)),n.value===null||n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in t&&(r.default=t[0]),r}function De(e){return{kind:"schema",type:"number",reference:De,expects:"number",async:!1,message:e,_run(t,r){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:Wt(this,"type",t,r),t}}}function ee(e,t){return{kind:"schema",type:"object",reference:ee,expects:"Object",async:!1,entries:e,message:t,_run(r,n){var i;const s=r.value;if(s&&typeof s=="object"){r.typed=!0,r.value={};for(const o in this.entries){const a=s[o],c=this.entries[o]._run({typed:!1,value:a},n);if(c.issues){const l={type:"object",origin:"value",input:s,key:o,value:a};for(const u of c.issues)u.path?u.path.unshift(l):u.path=[l],(i=r.issues)==null||i.push(u);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),(c.value!==void 0||o in s)&&(r.value[o]=c.value)}}else Wt(this,"type",r,n);return r}}}function ft(e,...t){const r={kind:"schema",type:"optional",reference:ft,expects:`${e.expects} | undefined`,async:!1,wrapped:e,_run(n,s){return n.value===void 0&&("default"in this&&(n.value=vh(this,n,s)),n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in t&&(r.default=t[0]),r}function Vo(e,t,r){return{kind:"schema",type:"record",reference:Vo,expects:"Object",async:!1,key:e,value:t,message:r,_run(n,s){var o,a;const i=n.value;if(i&&typeof i=="object"){n.typed=!0,n.value={};for(const c in i)if(H5(i,c)){const l=i[c],u=this.key._run({typed:!1,value:c},s);if(u.issues){const p={type:"object",origin:"key",input:i,key:c,value:l};for(const d of u.issues)d.path=[p],(o=n.issues)==null||o.push(d);if(n.issues||(n.issues=u.issues),s.abortEarly){n.typed=!1;break}}const f=this.value._run({typed:!1,value:l},s);if(f.issues){const p={type:"object",origin:"value",input:i,key:c,value:l};for(const d of f.issues)d.path?d.path.unshift(p):d.path=[p],(a=n.issues)==null||a.push(d);if(n.issues||(n.issues=f.issues),s.abortEarly){n.typed=!1;break}}(!u.typed||!f.typed)&&(n.typed=!1),u.typed&&(n.value[u.value]=f.value)}}else Wt(this,"type",n,s);return n}}}function ye(e){return{kind:"schema",type:"string",reference:ye,expects:"string",async:!1,message:e,_run(t,r){return typeof t.value=="string"?t.typed=!0:Wt(this,"type",t,r),t}}}function Ah(e,t){return{kind:"schema",type:"tuple",reference:Ah,expects:"Array",async:!1,items:e,message:t,_run(r,n){var i;const s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let o=0;o<this.items.length;o++){const a=s[o],c=this.items[o]._run({typed:!1,value:a},n);if(c.issues){const l={type:"array",origin:"value",input:s,key:o,value:a};for(const u of c.issues)u.path?u.path.unshift(l):u.path=[l],(i=r.issues)==null||i.push(u);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else Wt(this,"type",r,n);return r}}}function um(e){let t;if(e)for(const r of e)t?t.push(...r.issues):t=r.issues;return t}function ht(e,t){return{kind:"schema",type:"union",reference:ht,expects:[...new Set(e.map(r=>r.expects))].join(" | ")||"never",async:!1,options:e,message:t,_run(r,n){let s,i,o;for(const a of this.options){const c=a._run({typed:!1,value:r.value},n);if(c.typed)if(c.issues)i?i.push(c):i=[c];else{s=c;break}else o?o.push(c):o=[c]}if(s)return s;if(i){if(i.length===1)return i[0];Wt(this,"type",r,n,{issues:um(i)}),r.typed=!0}else{if((o==null?void 0:o.length)===1)return o[0];Wt(this,"type",r,n,{issues:um(o)})}return r}}}function Us(){return{kind:"schema",type:"unknown",reference:Us,expects:"unknown",async:!1,_run(e){return e.typed=!0,e}}}function Ve(e,t,r){const n=e._run({typed:!1,value:t},F5(r));if(n.issues)throw new z5(n.issues);return n.value}function Pe(...e){return{...e[0],pipe:e,_run(t,r){for(let n=0;n<e.length;n++){if(t.issues&&(e[n].kind==="schema"||e[n].kind==="transformation")){t.typed=!1;break}(!t.issues||!r.abortEarly&&!r.abortPipeEarly)&&(t=e[n]._run(t,r))}return t}}}function Vs(e){const t=Object.entries(e).map(([r,n])=>ee({[r]:n}));return Pe(ht(t),iu(r=>({...r,$kind:Object.keys(r)[0]})))}const $i=Pe(ye(),iu(e=>xe(e)),fa(gr)),qt=$i,Ms=ye(),Mt=Pe(ht([ye(),Pe(De(),Ge())]),fa(e=>{try{return BigInt(e),BigInt(e)>=0&&BigInt(e)<=18446744073709551615n}catch{return!1}},"Invalid u64")),ts=ee({objectId:$i,version:Mt,digest:ye()}),Me=Pe(ht([ee({GasCoin:le(!0)}),ee({Input:Pe(De(),Ge()),type:ft(le("pure"))}),ee({Input:Pe(De(),Ge()),type:ft(le("object"))}),ee({Result:Pe(De(),Ge())}),ee({NestedResult:Ah([Pe(De(),Ge()),Pe(De(),Ge())])})]),iu(e=>({...e,$kind:Object.keys(e)[0]}))),q5=ee({budget:Ee(Mt),price:Ee(Mt),owner:Ee($i),payment:Ee(ue(ts))}),Zf=ht([le("address"),le("bool"),le("u8"),le("u16"),le("u32"),le("u64"),le("u128"),le("u256"),ee({vector:qo(()=>Zf)}),ee({datatype:ee({package:ye(),module:ye(),type:ye(),typeParameters:ue(qo(()=>Zf))})}),ee({typeParameter:Pe(De(),Ge())})]),V5=ee({ref:Ee(ht([le("&"),le("&mut")])),body:Zf}),G5=ee({package:qt,module:ye(),function:ye(),typeArguments:ue(ye()),arguments:ue(Me),_argumentTypes:ft(Ee(ue(V5)))}),W5=ee({name:ye(),inputs:Vo(ye(),ht([Me,ue(Me)])),data:Vo(ye(),Us())}),K5=Vs({MoveCall:G5,TransferObjects:ee({objects:ue(Me),address:Me}),SplitCoins:ee({coin:Me,amounts:ue(Me)}),MergeCoins:ee({destination:Me,sources:ue(Me)}),Publish:ee({modules:ue(Ms),dependencies:ue(qt)}),MakeMoveVec:ee({type:Ee(ye()),elements:ue(Me)}),Upgrade:ee({modules:ue(Ms),dependencies:ue(qt),package:qt,ticket:Me}),$Intent:W5}),E1=Vs({ImmOrOwnedObject:ts,SharedObject:ee({objectId:qt,initialSharedVersion:Mt,mutable:ou()}),Receiving:ts}),X5=Vs({Object:E1,Pure:ee({bytes:Ms}),UnresolvedPure:ee({value:Us()}),UnresolvedObject:ee({objectId:qt,version:ft(Ee(Mt)),digest:ft(Ee(ye())),initialSharedVersion:ft(Ee(Mt))})}),lm=Vs({Object:E1,Pure:ee({bytes:Ms})}),A1=Vs({None:le(!0),Epoch:Mt}),Ka=ee({version:le(2),sender:_i($i),expiration:_i(A1),gasData:q5,inputs:ue(X5),commands:ue(K5)}),os={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=>Ve(Me,r)),address:Ve(Me,t)}}},SplitCoins(e,t){return{$kind:"SplitCoins",SplitCoins:{coin:Ve(Me,e),amounts:t.map(r=>Ve(Me,r))}}},MergeCoins(e,t){return{$kind:"MergeCoins",MergeCoins:{destination:Ve(Me,e),sources:t.map(r=>Ve(Me,r))}}},Publish({modules:e,dependencies:t}){return{$kind:"Publish",Publish:{modules:e.map(r=>typeof r=="string"?r:mt(new Uint8Array(r))),dependencies:t.map(r=>pn(r))}}},Upgrade({modules:e,dependencies:t,package:r,ticket:n}){return{$kind:"Upgrade",Upgrade:{modules:e.map(s=>typeof s=="string"?s:mt(new Uint8Array(s))),dependencies:t.map(s=>pn(s)),package:r,ticket:Ve(Me,n)}}},MakeMoveVec({type:e,elements:t}){return{$kind:"MakeMoveVec",MakeMoveVec:{type:e??null,elements:t.map(r=>Ve(Me,r))}}},Intent({name:e,inputs:t={},data:r={}}){return{$kind:"$Intent",$Intent:{name:e,inputs:Object.fromEntries(Object.entries(t).map(([n,s])=>[n,Array.isArray(s)?s.map(i=>Ve(Me,i)):Ve(Me,s)])),data:r}}}},Jf=ee({digest:ye(),objectId:ye(),version:ht([Pe(De(),Ge()),ye(),Eh()])}),Y5=Vs({ImmOrOwned:Jf,Shared:ee({objectId:qt,initialSharedVersion:Mt,mutable:ou()}),Receiving:Jf}),fm=Vs({Object:Y5,Pure:ue(Pe(De(),Ge()))}),x1=ht([ee({kind:le("Input"),index:Pe(De(),Ge()),value:Us(),type:ft(le("object"))}),ee({kind:le("Input"),index:Pe(De(),Ge()),value:Us(),type:le("pure")})]),Z5=ht([ee({Epoch:Pe(De(),Ge())}),ee({None:Ee(le(!0))})]),dm=Pe(ht([De(),ye(),Eh()]),fa(e=>{if(!["string","number","bigint"].includes(typeof e))return!1;try{return BigInt(e),!0}catch{return!1}})),xh=ht([ee({bool:Ee(le(!0))}),ee({u8:Ee(le(!0))}),ee({u64:Ee(le(!0))}),ee({u128:Ee(le(!0))}),ee({address:Ee(le(!0))}),ee({signer:Ee(le(!0))}),ee({vector:qo(()=>xh)}),ee({struct:qo(()=>J5)}),ee({u16:Ee(le(!0))}),ee({u32:Ee(le(!0))}),ee({u256:Ee(le(!0))})]),J5=ee({address:ye(),module:ye(),name:ye(),typeParams:ue(xh)}),Q5=ee({budget:ft(dm),price:ft(dm),payment:ft(ue(Jf)),owner:ft(ye())}),eO=[x1,ee({kind:le("GasCoin")}),ee({kind:le("Result"),index:Pe(De(),Ge())}),ee({kind:le("NestedResult"),index:Pe(De(),Ge()),resultIndex:Pe(De(),Ge())})],xn=ht([...eO]),tO=ee({kind:le("MoveCall"),target:Pe(ye(),fa(e=>e.split("::").length===3)),typeArguments:ue(ye()),arguments:ue(xn)}),rO=ee({kind:le("TransferObjects"),objects:ue(xn),address:xn}),nO=ee({kind:le("SplitCoins"),coin:xn,amounts:ue(xn)}),sO=ee({kind:le("MergeCoins"),destination:xn,sources:ue(xn)}),iO=ee({kind:le("MakeMoveVec"),type:ht([ee({Some:xh}),ee({None:Ee(le(!0))})]),objects:ue(xn)}),oO=ee({kind:le("Publish"),modules:ue(ue(Pe(De(),Ge()))),dependencies:ue(ye())}),aO=ee({kind:le("Upgrade"),modules:ue(ue(Pe(De(),Ge()))),dependencies:ue(ye()),packageId:ye(),ticket:xn}),cO=[tO,rO,nO,sO,oO,aO,iO],uO=ht([...cO]);ee({version:le(1),sender:ft(ye()),expiration:_i(Z5),gasConfig:Q5,inputs:ue(x1),transactions:ue(uO)});function hm(e){var r;const t=e.inputs.map((n,s)=>{if(n.Object)return{kind:"Input",index:s,value:{Object:n.Object.ImmOrOwnedObject?{ImmOrOwned:n.Object.ImmOrOwnedObject}:n.Object.Receiving?{Receiving:{digest:n.Object.Receiving.digest,version:n.Object.Receiving.version,objectId:n.Object.Receiving.objectId}}:{Shared:{mutable:n.Object.SharedObject.mutable,initialSharedVersion:n.Object.SharedObject.initialSharedVersion,objectId:n.Object.SharedObject.objectId}}},type:"object"};if(n.Pure)return{kind:"Input",index:s,value:{Pure:Array.from(zt(n.Pure.bytes))},type:"pure"};if(n.UnresolvedPure)return{kind:"Input",type:"pure",index:s,value:n.UnresolvedPure.value};if(n.UnresolvedObject)return{kind:"Input",type:"object",index:s,value:n.UnresolvedObject.objectId};throw new Error("Invalid input")});return{version:1,sender: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:wr.parseFromStr(n.MakeMoveVec.type)},objects:n.MakeMoveVec.elements.map(s=>sn(s,t))};if(n.MergeCoins)return{kind:"MergeCoins",destination:sn(n.MergeCoins.destination,t),sources:n.MergeCoins.sources.map(s=>sn(s,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(s=>sn(s,t))};if(n.Publish)return{kind:"Publish",modules:n.Publish.modules.map(s=>Array.from(zt(s))),dependencies:n.Publish.dependencies};if(n.SplitCoins)return{kind:"SplitCoins",coin:sn(n.SplitCoins.coin,t),amounts:n.SplitCoins.amounts.map(s=>sn(s,t))};if(n.TransferObjects)return{kind:"TransferObjects",objects:n.TransferObjects.objects.map(s=>sn(s,t)),address:sn(n.TransferObjects.address,t)};if(n.Upgrade)return{kind:"Upgrade",modules:n.Upgrade.modules.map(s=>Array.from(zt(s))),dependencies:n.Upgrade.dependencies,packageId:n.Upgrade.package,ticket:sn(n.Upgrade.ticket,t)};throw new Error(`Unknown transaction ${Object.keys(n)}`)})}}function sn(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 lO(e){var t,r,n;return Ve(Ka,{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(s=>({digest:s.digest,objectId:s.objectId,version:s.version.toString()})))??null},inputs:e.inputs.map(s=>{if(s.kind==="Input"){if(Yf(fm,s.value)){const i=Ve(fm,s.value);if(i.Object){if(i.Object.ImmOrOwned)return{Object:{ImmOrOwnedObject:{objectId:i.Object.ImmOrOwned.objectId,version:String(i.Object.ImmOrOwned.version),digest:i.Object.ImmOrOwned.digest}}};if(i.Object.Shared)return{Object:{SharedObject:{mutable:i.Object.Shared.mutable??null,initialSharedVersion:i.Object.Shared.initialSharedVersion,objectId:i.Object.Shared.objectId}}};if(i.Object.Receiving)return{Object:{Receiving:{digest:i.Object.Receiving.digest,version:String(i.Object.Receiving.version),objectId:i.Object.Receiving.objectId}}};throw new Error("Invalid object input")}return{Pure:{bytes:mt(new Uint8Array(i.Pure))}}}return s.type==="object"?{UnresolvedObject:{objectId:s.value}}:{UnresolvedPure:{value:s.value}}}throw new Error("Invalid input")}),commands:e.transactions.map(s=>{switch(s.kind){case"MakeMoveVec":return{MakeMoveVec:{type:"Some"in s.type?wr.tagToString(s.type.Some):null,elements:s.objects.map(i=>on(i))}};case"MergeCoins":return{MergeCoins:{destination:on(s.destination),sources:s.sources.map(i=>on(i))}};case"MoveCall":{const[i,o,a]=s.target.split("::");return{MoveCall:{package:i,module:o,function:a,typeArguments:s.typeArguments,arguments:s.arguments.map(c=>on(c))}}}case"Publish":return{Publish:{modules:s.modules.map(i=>mt(Uint8Array.from(i))),dependencies:s.dependencies}};case"SplitCoins":return{SplitCoins:{coin:on(s.coin),amounts:s.amounts.map(i=>on(i))}};case"TransferObjects":return{TransferObjects:{objects:s.objects.map(i=>on(i)),address:on(s.address)}};case"Upgrade":return{Upgrade:{modules:s.modules.map(i=>mt(Uint8Array.from(i))),dependencies:s.dependencies,package:s.packageId,ticket:on(s.ticket)}}}throw new Error(`Unknown transaction ${Object.keys(s)}`)})})}function on(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 da(e){return ht(Object.entries(e).map(([t,r])=>ee({[t]:r})))}const pr=da({GasCoin:le(!0),Input:Pe(De(),Ge()),Result:Pe(De(),Ge()),NestedResult:Ah([Pe(De(),Ge()),Pe(De(),Ge())])}),fO=ee({budget:Ee(Mt),price:Ee(Mt),owner:Ee($i),payment:Ee(ue(ts))}),dO=ee({package:qt,module:ye(),function:ye(),typeArguments:ue(ye()),arguments:ue(pr)}),hO=ee({name:ye(),inputs:Vo(ye(),ht([pr,ue(pr)])),data:Vo(ye(),Us())}),pO=da({MoveCall:dO,TransferObjects:ee({objects:ue(pr),address:pr}),SplitCoins:ee({coin:pr,amounts:ue(pr)}),MergeCoins:ee({destination:pr,sources:ue(pr)}),Publish:ee({modules:ue(Ms),dependencies:ue(qt)}),MakeMoveVec:ee({type:Ee(ye()),elements:ue(pr)}),Upgrade:ee({modules:ue(Ms),dependencies:ue(qt),package:qt,ticket:pr}),$Intent:hO}),yO=da({ImmOrOwnedObject:ts,SharedObject:ee({objectId:qt,initialSharedVersion:Mt,mutable:ou()}),Receiving:ts}),mO=da({Object:yO,Pure:ee({bytes:Ms}),UnresolvedPure:ee({value:Us()}),UnresolvedObject:ee({objectId:qt,version:ft(Ee(Mt)),digest:ft(Ee(ye())),initialSharedVersion:ft(Ee(Mt))})}),gO=da({None:le(!0),Epoch:Mt}),bO=ee({version:le(2),sender:_i($i),expiration:_i(gO),gasData:fO,inputs:ue(mO),commands:ue(pO),digest:ft(Ee(ye()))});function wO(e){return{$kind:"Pure",Pure:{bytes:e instanceof Uint8Array?mt(e):e.toBase64()}}}const yn={Pure:wO,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 vO="0x1",S1="0x2",EO=pn("0x6"),AO=`${S1}::sui::SUI`;pn("0x5");const xO=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]),tt=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),te=new Uint32Array(32);function Un(e,t,r,n,s,i){const o=s[i],a=s[i+1];let c=te[2*e],l=te[2*e+1],u=te[2*t],f=te[2*t+1],p=te[2*r],d=te[2*r+1],m=te[2*n],g=te[2*n+1],w=Zm(c,u,o);l=Jm(w,l,f,a),c=w|0,{Dh:g,Dl:m}={Dh:g^l,Dl:m^c},{Dh:g,Dl:m}={Dh:l2(g,m),Dl:f2(g)},{h:d,l:p}=Ym(d,p,g,m),{Bh:f,Bl:u}={Bh:f^d,Bl:u^p},{Bh:f,Bl:u}={Bh:Km(f,u,24),Bl:Xm(f,u,24)},te[2*e]=c,te[2*e+1]=l,te[2*t]=u,te[2*t+1]=f,te[2*r]=p,te[2*r+1]=d,te[2*n]=m,te[2*n+1]=g}function Mn(e,t,r,n,s,i){const o=s[i],a=s[i+1];let c=te[2*e],l=te[2*e+1],u=te[2*t],f=te[2*t+1],p=te[2*r],d=te[2*r+1],m=te[2*n],g=te[2*n+1],w=Zm(c,u,o);l=Jm(w,l,f,a),c=w|0,{Dh:g,Dl:m}={Dh:g^l,Dl:m^c},{Dh:g,Dl:m}={Dh:Km(g,m,16),Dl:Xm(g,m,16)},{h:d,l:p}=Ym(d,p,g,m),{Bh:f,Bl:u}={Bh:f^d,Bl:u^p},{Bh:f,Bl:u}={Bh:c2(f,u,63),Bl:u2(f,u,63)},te[2*e]=c,te[2*e+1]=l,te[2*t]=u,te[2*t+1]=f,te[2*r]=p,te[2*r+1]=d,te[2*n]=m,te[2*n+1]=g}function SO(e,t={},r,n,s){if(Zn(r),e<0||e>r)throw new Error("outputLen bigger than keyLen");const{key:i,salt:o,personalization:a}=t;if(i!==void 0&&(i.length<1||i.length>r))throw new Error("key length must be undefined or 1.."+r);if(o!==void 0&&o.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==s)throw new Error("personalization must be undefined or "+s)}class _O extends yc{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Zn(t),Zn(r),this.blockLen=t,this.outputLen=r,this.buffer=new Uint8Array(t),this.buffer32=yo(this.buffer)}update(t){Jn(this),t=mn(t),lr(t);const{blockLen:r,buffer:n,buffer32:s}=this,i=t.length,o=t.byteOffset,a=t.buffer;for(let c=0;c<i;){this.pos===r&&(Hn(s),this.compress(s,0,!1),Hn(s),this.pos=0);const l=Math.min(r-this.pos,i-c),u=o+c;if(l===r&&!(u%4)&&c+l<i){const f=new Uint32Array(a,u,Math.floor((i-c)/4));Hn(f);for(let p=0;c+r<i;p+=s.length,c+=r)this.length+=r,this.compress(f,p,!1);Hn(f);continue}n.set(t.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(t){Jn(this),cd(t,this);const{pos:r,buffer32:n}=this;this.finished=!0,_r(this.buffer.subarray(r)),Hn(n),this.compress(n,0,!0),Hn(n);const s=yo(t);this.get().forEach((i,o)=>s[o]=an(i))}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:s,destroyed:i,outputLen:o,pos:a}=this;return t||(t=new this.constructor({dkLen:o})),t.set(...this.get()),t.buffer.set(r),t.destroyed=i,t.finished=s,t.length=n,t.pos=a,t.outputLen=o,t}clone(){return this._cloneInto()}}class kO extends _O{constructor(t={}){const r=t.dkLen===void 0?64:t.dkLen;super(128,r),this.v0l=tt[0]|0,this.v0h=tt[1]|0,this.v1l=tt[2]|0,this.v1h=tt[3]|0,this.v2l=tt[4]|0,this.v2h=tt[5]|0,this.v3l=tt[6]|0,this.v3h=tt[7]|0,this.v4l=tt[8]|0,this.v4h=tt[9]|0,this.v5l=tt[10]|0,this.v5h=tt[11]|0,this.v6l=tt[12]|0,this.v6h=tt[13]|0,this.v7l=tt[14]|0,this.v7h=tt[15]|0,SO(r,t,64,16,16);let{key:n,personalization:s,salt:i}=t,o=0;if(n!==void 0&&(n=mn(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=mn(i);const a=yo(i);this.v4l^=an(a[0]),this.v4h^=an(a[1]),this.v5l^=an(a[2]),this.v5h^=an(a[3])}if(s!==void 0){s=mn(s);const a=yo(s);this.v6l^=an(a[0]),this.v6h^=an(a[1]),this.v7l^=an(a[2]),this.v7h^=an(a[3])}if(n!==void 0){const a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:t,v0h:r,v1l:n,v1h:s,v2l:i,v2h:o,v3l:a,v3h:c,v4l:l,v4h:u,v5l:f,v5h:p,v6l:d,v6h:m,v7l:g,v7h:w}=this;return[t,r,n,s,i,o,a,c,l,u,f,p,d,m,g,w]}set(t,r,n,s,i,o,a,c,l,u,f,p,d,m,g,w){this.v0l=t|0,this.v0h=r|0,this.v1l=n|0,this.v1h=s|0,this.v2l=i|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=u|0,this.v5l=f|0,this.v5h=p|0,this.v6l=d|0,this.v6h=m|0,this.v7l=g|0,this.v7h=w|0}compress(t,r,n){this.get().forEach((c,l)=>te[l]=c),te.set(tt,16);let{h:s,l:i}=Wm(BigInt(this.length));te[24]=tt[8]^i,te[25]=tt[9]^s,n&&(te[28]=~te[28],te[29]=~te[29]);let o=0;const a=xO;for(let c=0;c<12;c++)Un(0,4,8,12,t,r+2*a[o++]),Mn(0,4,8,12,t,r+2*a[o++]),Un(1,5,9,13,t,r+2*a[o++]),Mn(1,5,9,13,t,r+2*a[o++]),Un(2,6,10,14,t,r+2*a[o++]),Mn(2,6,10,14,t,r+2*a[o++]),Un(3,7,11,15,t,r+2*a[o++]),Mn(3,7,11,15,t,r+2*a[o++]),Un(0,5,10,15,t,r+2*a[o++]),Mn(0,5,10,15,t,r+2*a[o++]),Un(1,6,11,12,t,r+2*a[o++]),Mn(1,6,11,12,t,r+2*a[o++]),Un(2,7,8,13,t,r+2*a[o++]),Mn(2,7,8,13,t,r+2*a[o++]),Un(3,4,9,14,t,r+2*a[o++]),Mn(3,4,9,14,t,r+2*a[o++]);this.v0l^=te[0]^te[16],this.v0h^=te[1]^te[17],this.v1l^=te[2]^te[18],this.v1h^=te[3]^te[19],this.v2l^=te[4]^te[20],this.v2h^=te[5]^te[21],this.v3l^=te[6]^te[22],this.v3h^=te[7]^te[23],this.v4l^=te[8]^te[24],this.v4h^=te[9]^te[25],this.v5l^=te[10]^te[26],this.v5h^=te[11]^te[27],this.v6l^=te[12]^te[28],this.v6h^=te[13]^te[29],this.v7l^=te[14]^te[30],this.v7h^=te[15]^te[31],_r(te)}destroy(){this.destroyed=!0,_r(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const TO=v2(e=>new kO(e)),_1=TO;function IO(e,t,r){const n=de.Address.serialize(e).toBytes(),s=de.TypeTag.serialize(t).toBytes(),i=de.u64().serialize(r.length).toBytes(),o=_1.create({dkLen:32});return o.update(new Uint8Array([240])),o.update(n),o.update(i),o.update(r),o.update(s),`0x${Si(o.digest().slice(0,32))}`}const PO="object",OO="ID",BO="ascii",CO="String",RO="string",$O="String",NO="option",UO="Option";function MO(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 Qf(e){if(typeof e=="string")switch(e){case"address":return de.Address;case"bool":return de.Bool;case"u8":return de.U8;case"u16":return de.U16;case"u32":return de.U32;case"u64":return de.U64;case"u128":return de.U128;case"u256":return de.U256;default:throw new Error(`Unknown type signature ${e}`)}if("vector"in e){if(e.vector==="u8")return de.vector(de.U8).transform({input:r=>typeof r=="string"?new TextEncoder().encode(r):r,output:r=>r});const t=Qf(e.vector);return t?de.vector(t):null}if("datatype"in e){const t=xe(e.datatype.package);if(t===xe(vO)){if(e.datatype.module===BO&&e.datatype.type===CO||e.datatype.module===RO&&e.datatype.type===$O)return de.String;if(e.datatype.module===NO&&e.datatype.type===UO){const r=Qf(e.datatype.typeParameters[0]);return r?de.vector(r):null}}if(t===xe(S1)&&e.datatype.module===PO&&e.datatype.type===OO)return de.Address}return null}function FO(e){return typeof e=="object"&&"Reference"in e?{ref:"&",body:ho(e.Reference)}:typeof e=="object"&&"MutableReference"in e?{ref:"&mut",body:ho(e.MutableReference)}:{ref:null,body:ho(e)}}function ho(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:ho(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(ho)}};if("TypeParameter"in e)return{typeParameter:e.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(e)}`)}const jO=50,LO=1000n,DO=5e10;function k1(e){return async function(r,n,s){return await GO(r,e),await VO(r,e),n.onlyTransactionKind||(await HO(r,e),await zO(r,e),await qO(r,e)),await s()}}async function HO(e,t){e.gasConfig.price||(e.gasConfig.price=String(await t.getReferenceGasPrice()))}async function zO(e,t){if(e.gasConfig.budget)return;const r=await t.dryRunTransactionBlock({transactionBlock:e.build({overrides:{gasData:{budget:String(DO),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=LO*BigInt(e.gasConfig.price||1n),s=BigInt(r.effects.gasUsed.computationCost)+n,i=s+BigInt(r.effects.gasUsed.storageCost)-BigInt(r.effects.gasUsed.storageRebate);e.gasConfig.budget=String(i>s?i:s)}async function qO(e,t){if(!e.gasConfig.payment){const n=(await t.getCoins({owner:e.gasConfig.owner||e.sender,coinType:AO})).data.filter(s=>!e.inputs.find(o=>{var a;return(a=o.Object)!=null&&a.ImmOrOwnedObject?s.coinObjectId===o.Object.ImmOrOwnedObject.objectId:!1})).map(s=>({objectId:s.coinObjectId,digest:s.digest,version:s.version}));if(!n.length)throw new Error("No valid gas coins found for the transaction.");e.gasConfig.payment=n.map(s=>Ve(ts,s))}}async function VO(e,t){const r=e.inputs.filter(u=>{var f;return u.UnresolvedObject&&!(u.UnresolvedObject.version||(f=u.UnresolvedObject)!=null&&f.initialSharedVersion)}),n=[...new Set(r.map(u=>pn(u.UnresolvedObject.objectId)))],s=n.length?nu(n,jO):[],i=(await Promise.all(s.map(u=>t.multiGetObjects({ids:u,options:{showOwner:!0}})))).flat(),o=new Map(n.map((u,f)=>[u,i[f]])),a=Array.from(o).filter(([u,f])=>f.error).map(([u,f])=>JSON.stringify(f.error));if(a.length)throw new Error(`The following input objects are invalid: ${a.join(", ")}`);const c=i.map(u=>{if(u.error||!u.data)throw new Error(`Failed to fetch object: ${u.error}`);const f=u.data.owner,p=f&&typeof f=="object"?"Shared"in f?f.Shared.initial_shared_version:"ConsensusAddressOwner"in f?f.ConsensusAddressOwner.start_version:null:null;return{objectId:u.data.objectId,digest:u.data.digest,version:u.data.version,initialSharedVersion:p}}),l=new Map(n.map((u,f)=>[u,c[f]]));for(const[u,f]of e.inputs.entries()){if(!f.UnresolvedObject)continue;let p;const d=xe(f.UnresolvedObject.objectId),m=l.get(d);f.UnresolvedObject.initialSharedVersion??(m==null?void 0:m.initialSharedVersion)?p=yn.SharedObjectRef({objectId:d,initialSharedVersion:f.UnresolvedObject.initialSharedVersion||(m==null?void 0:m.initialSharedVersion),mutable:WO(e,u)}):KO(e,u)&&(p=yn.ReceivingRef({objectId:d,digest:f.UnresolvedObject.digest??(m==null?void 0:m.digest),version:f.UnresolvedObject.version??(m==null?void 0:m.version)})),e.inputs[e.inputs.indexOf(f)]=p??yn.ObjectRef({objectId:d,digest:f.UnresolvedObject.digest??(m==null?void 0:m.digest),version:f.UnresolvedObject.version??(m==null?void 0:m.version)})}}async function GO(e,t){const{inputs:r,commands:n}=e,s=[],i=new Set;n.forEach(a=>{if(a.MoveCall){if(a.MoveCall._argumentTypes)return;if(a.MoveCall.arguments.map(u=>u.$kind==="Input"?e.inputs[u.Input]:null).some(u=>(u==null?void 0:u.UnresolvedPure)||(u==null?void 0:u.UnresolvedObject))){const u=`${a.MoveCall.package}::${a.MoveCall.module}::${a.MoveCall.function}`;i.add(u),s.push(a.MoveCall)}}});const o=new Map;i.size>0&&await Promise.all([...i].map(async a=>{const[c,l,u]=a.split("::"),f=await t.getNormalizedMoveFunction({package:c,module:l,function:u});o.set(a,f.parameters.map(p=>FO(p)))})),s.length&&await Promise.all(s.map(async a=>{const c=o.get(`${a.package}::${a.module}::${a.function}`);if(!c)return;const u=c.length>0&&MO(c.at(-1))?c.slice(0,c.length-1):c;a._argumentTypes=u})),n.forEach(a=>{if(!a.MoveCall)return;const c=a.MoveCall,l=`${c.package}::${c.module}::${c.function}`,u=c._argumentTypes;if(u){if(u.length!==a.MoveCall.arguments.length)throw new Error(`Incorrect number of arguments for ${l}`);u.forEach((f,p)=>{var T,E;const d=c.arguments[p];if(d.$kind!=="Input")return;const m=r[d.Input];if(!m.UnresolvedPure&&!m.UnresolvedObject)return;const g=((T=m.UnresolvedPure)==null?void 0:T.value)??((E=m.UnresolvedObject)==null?void 0:E.objectId),w=Qf(f.body);if(w){d.type="pure",r[r.indexOf(m)]=yn.Pure(w.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=m.UnresolvedPure?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:g}}:m;r[d.Input]=A})}})}function WO(e,t){let r=!1;return e.getInputUses(t,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=s.MoveCall._argumentTypes[i].ref!=="&"||r}(s.$kind==="MakeMoveVec"||s.$kind==="MergeCoins"||s.$kind==="SplitCoins"||s.$kind==="TransferObjects")&&(r=!0)}),r}function KO(e,t){let r=!1;return e.getInputUses(t,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=XO(s.MoveCall._argumentTypes[i])||r}}),r}function XO(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 T1(e,t){return!!(e.inputs.some(r=>r.UnresolvedObject||r.UnresolvedPure)||!t.onlyTransactionKind&&(!e.gasConfig.price||!e.gasConfig.budget||!e.gasConfig.payment))}async function YO(e,t,r){var i;if(JO(e),!T1(e,t))return await pm(e),r();const n=ZO(t);return(((i=n.core)==null?void 0:i.resolveTransactionPlugin())??k1(n))(e,t,async()=>{await pm(e),await r()})}function pm(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 ZO(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 JO(e){for(const t of e.commands)switch(t.$kind){case"SplitCoins":t.SplitCoins.amounts.forEach(r=>{ym(r,de.U64,e)});break;case"TransferObjects":ym(t.TransferObjects.address,de.Address,e);break}}function ym(e,t,r){if(e.$kind!=="Input")return;const n=r.inputs[e.Input];n.$kind==="UnresolvedPure"&&(r.inputs[e.Input]=yn.Pure(t.serialize(n.UnresolvedPure.value)))}function QO(e){function t(r){return e(r)}return t.system=()=>t("0x5"),t.clock=()=>t("0x6"),t.random=()=>t("0x8"),t.denyList=()=>t("0x403"),t.option=({type:r,value:n})=>s=>s.moveCall({typeArguments:[r],target:`0x1::option::${n===null?"none":"some"}`,arguments:n===null?[]:[s.object(n)]}),t}function e3(e){function t(r,n){if(typeof r=="string")return e(fo(r).serialize(n));if(r instanceof Uint8Array||mh(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(de.U8.serialize(r)),t.u16=r=>e(de.U16.serialize(r)),t.u32=r=>e(de.U32.serialize(r)),t.u64=r=>e(de.U64.serialize(r)),t.u128=r=>e(de.U128.serialize(r)),t.u256=r=>e(de.U256.serialize(r)),t.bool=r=>e(de.Bool.serialize(r)),t.string=r=>e(de.String.serialize(r)),t.address=r=>e(de.Address.serialize(r)),t.id=t.address,t.vector=(r,n)=>e(de.vector(fo(r)).serialize(n)),t.option=(r,n)=>e(de.option(fo(r)).serialize(n)),t}function t3(e,t){const r=Array.from(`${e}::`).map(s=>s.charCodeAt(0)),n=new Uint8Array(r.length+t.length);return n.set(r),n.set(t,r.length),_1(n,{dkLen:32})}function mm(e){return xe(e).replace("0x","")}class Rt{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=de.TransactionKind.parse(t).ProgrammableTransaction;if(!n)throw new Error("Unable to deserialize from bytes.");return Rt.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=de.TransactionData.parse(t),n=r==null?void 0:r.V1,s=n.kind.ProgrammableTransaction;if(!n||!s)throw new Error("Unable to deserialize from bytes.");return Rt.restore({version:2,sender:n.sender,expiration:n.expiration,gasData:n.gasData,inputs:s.inputs,commands:s.commands})}static restore(t){return t.version===2?new Rt(Ve(Ka,t)):new Rt(Ve(Ka,lO(t)))}static getDigestFromBytes(t){const r=t3("TransactionData",t);return ru(r)}get gasConfig(){return this.gasData}set gasConfig(t){this.gasData=t}build({maxSizeBytes:t=1/0,overrides:r,onlyTransactionKind:n}={}){const s=this.inputs,i=this.commands,o={ProgrammableTransaction:{inputs:s,commands:i}};if(n)return de.TransactionKind.serialize(o,{maxSize:t}).toBytes();const a=(r==null?void 0:r.expiration)??this.expiration,c=(r==null?void 0:r.sender)??this.sender,l={...this.gasData,...r==null?void 0:r.gasConfig,...r==null?void 0:r.gasData};if(!c)throw new Error("Missing transaction sender");if(!l.budget)throw new Error("Missing gas budget");if(!l.payment)throw new Error("Missing gas payment");if(!l.price)throw new Error("Missing gas price");const u={sender:mm(c),expiration:a||{None:!0},gasData:{payment:l.payment,owner:mm(this.gasData.owner??c),price:BigInt(l.price),budget:BigInt(l.budget)},kind:{ProgrammableTransaction:{inputs:s,commands:i}}};return de.TransactionData.serialize({V1:u},{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,s)=>(n.$kind==="Input"&&n.Input===t&&r(n,s),n))}mapCommandArguments(t,r){const n=this.commands[t];switch(n.$kind){case"MoveCall":n.MoveCall.arguments=n.MoveCall.arguments.map(i=>r(i,n,t));break;case"TransferObjects":n.TransferObjects.objects=n.TransferObjects.objects.map(i=>r(i,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(i=>r(i,n,t));break;case"MergeCoins":n.MergeCoins.destination=r(n.MergeCoins.destination,n,t),n.MergeCoins.sources=n.MergeCoins.sources.map(i=>r(i,n,t));break;case"MakeMoveVec":n.MakeMoveVec.elements=n.MakeMoveVec.elements.map(i=>r(i,n,t));break;case"Upgrade":n.Upgrade.ticket=r(n.Upgrade.ticket,n,t);break;case"$Intent":const s=n.$Intent.inputs;n.$Intent.inputs={};for(const[i,o]of Object.entries(s))n.$Intent.inputs[i]=Array.isArray(o)?o.map(a=>r(a,n,t)):r(o,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 s=r.length-1;this.commands.splice(t,1,...r),s!==0&&this.mapArguments((i,o,a)=>{if(a<t+r.length)return i;switch(i.$kind){case"Result":i.Result===t&&(i.Result=n),i.Result>t&&(i.Result+=s);break;case"NestedResult":i.NestedResult[0]===t&&(i.NestedResult[0]=n),i.NestedResult[0]>t&&(i.NestedResult[0]+=s);break}return i})}getDigest(){const t=this.build({onlyTransactionKind:!1});return Rt.getDigestFromBytes(t)}snapshot(){return Ve(Ka,this)}shallowClone(){return new Rt({version:this.version,sender:this.sender,expiration:this.expiration,gasData:{...this.gasData},inputs:[...this.inputs],commands:[...this.commands]})}}function gm(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)}var I1=e=>{throw TypeError(e)},Sh=(e,t,r)=>t.has(e)||I1("Cannot "+r),nt=(e,t,r)=>(Sh(e,t,"read from private field"),r?r.call(e):t.get(e)),Gi=(e,t,r)=>t.has(e)?I1("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Na=(e,t,r,n)=>(Sh(e,t,"write to private field"),t.set(e,r),r),au=(e,t,r)=>(Sh(e,t,"access private method"),r),Go,Sn,Wo,zn,zr,ed,td,P1,O1,_h;const r3="/",n3={"Mvr-Source":`@mysten/sui@${Aw}`};class s3{constructor({cache:t,url:r,pageSize:n=50,overrides:s}){Gi(this,zr),Gi(this,Go),Gi(this,Sn),Gi(this,Wo),Gi(this,zn),Na(this,Go,t),Na(this,Sn,r),Na(this,Wo,n),Na(this,zn,{packages:s==null?void 0:s.packages,types:s==null?void 0:s.types}),i3(nt(this,zn))}async resolvePackage({package:t}){return{package:await nt(this,zr,ed).load(t)}}async resolveType({type:t}){const r=[...rd(t)],n=await nt(this,zr,td).loadMany(r),s={};for(let i=0;i<r.length;i++){const o=n[i];if(o instanceof Error)throw o;s[r[i]]=o}return{type:nd(t,s)}}async resolve({types:t=[],packages:r=[]}){var u,f,p;const n=new Set;for(const d of t??[])rd(d,n);const s=[...n],[i,o]=await Promise.all([s.length>0?nt(this,zr,td).loadMany(s):[],r.length>0?nt(this,zr,ed).loadMany(r):[]]),a={...(u=nt(this,zn))==null?void 0:u.types};for(const[d,m]of s.entries()){const g=i[d];if(g instanceof Error)throw g;a[m]=g}const c={};for(const d of t??[]){const m=nd(d,a);c[d]={type:m}}const l={};for(const[d,m]of(r??[]).entries()){const g=((p=(f=nt(this,zn))==null?void 0:f.packages)==null?void 0:p[m])??o[d];if(g instanceof Error)throw g;l[m]={package:g}}return{types:c,packages:l}}}Go=new WeakMap;Sn=new WeakMap;Wo=new WeakMap;zn=new WeakMap;zr=new WeakSet;ed=function(){return nt(this,Go).readSync(["#mvrPackageDataLoader",nt(this,Sn)??""],()=>{var r;const e=new Uw(async n=>{if(!nt(this,Sn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await au(this,zr,P1).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve package: ${i}`))}),t=(r=nt(this,zn))==null?void 0:r.packages;if(t)for(const[n,s]of Object.entries(t))e.prime(n,s);return e})};td=function(){return nt(this,Go).readSync(["#mvrTypeDataLoader",nt(this,Sn)??""],()=>{var r;const e=new Uw(async n=>{if(!nt(this,Sn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await au(this,zr,O1).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve type: ${i}`))}),t=(r=nt(this,zn))==null?void 0:r.types;if(t)for(const[n,s]of Object.entries(t))e.prime(n,s);return e})};P1=async function(e){if(e.length===0)return{};const t=nu(e,nt(this,Wo)),r={};return await Promise.all(t.map(async n=>{var i;const s=await au(this,zr,_h).call(this,"/v1/resolution/bulk",{names:n});if(s!=null&&s.resolution)for(const o of Object.keys(s==null?void 0:s.resolution)){const a=(i=s.resolution[o])==null?void 0:i.package_id;a&&(r[o]=a)}})),r};O1=async function(e){if(e.length===0)return{};const t=nu(e,nt(this,Wo)),r={};return await Promise.all(t.map(async n=>{var i;const s=await au(this,zr,_h).call(this,"/v1/struct-definition/bulk",{types:n});if(s!=null&&s.resolution)for(const o of Object.keys(s==null?void 0:s.resolution)){const a=(i=s.resolution[o])==null?void 0:i.type_tag;a&&(r[o]=a)}})),r};_h=async function(e,t){if(!nt(this,Sn))throw new Error("MVR Api URL is not set for the current client");const r=await fetch(`${nt(this,Sn)}${e}`,{method:"POST",headers:{"Content-Type":"application/json",...n3},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 i3(e){if(e!=null&&e.packages)for(const[t,r]of Object.entries(e.packages)){if(!Dt(t))throw new Error(`Invalid package name: ${t}`);if(!gr(xe(r)))throw new Error(`Invalid package ID: ${r}`)}if(e!=null&&e.types)for(const[t,r]of Object.entries(e.types)){if(Ns(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=Ns(r);if(!gr(n.address))throw new Error(`Invalid type: ${r}`)}}function rd(e,t=new Set){if(typeof e=="string"&&!$t(e))return t;const r=B1(e)?e:Ns(e);$t(r.address)&&t.add(`${r.address}::${r.module}::${r.name}`);for(const n of r.typeParams)rd(n,t);return t}function nd(e,t){const r=B1(e)?e:Ns(e),n=`${r.address}::${r.module}::${r.name}`,s=t[n];return lc({...r,address:s?s.split("::")[0]:r.address,typeParams:r.typeParams.map(i=>nd(i,t))})}function $t(e){return e.includes(r3)||e.includes("@")||e.includes(".sui")}function B1(e){return typeof e=="object"&&"address"in e&&"module"in e&&"name"in e&&"typeParams"in e}function o3(e){const t=new Set,r=new Set;for(const n of e.commands)switch(n.$kind){case"MakeMoveVec":n.MakeMoveVec.type&&bm([n.MakeMoveVec.type]).forEach(o=>{r.add(o)});break;case"MoveCall":const s=n.MoveCall,i=s.package.split("::")[0];if($t(i)){if(!Dt(i))throw new Error(`Invalid package name: ${i}`);t.add(i)}bm(s.typeArguments??[]).forEach(o=>{r.add(o)});break}return{packages:[...t],types:[...r]}}function a3(e,t){var r;for(const n of e.commands){if((r=n.MakeMoveVec)!=null&&r.type){if(!$t(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 s=n.MoveCall;if(!s)continue;const i=s.package.split("::"),o=i[0];if($t(o)&&!t.packages[o])throw new Error(`No address found for package: ${o}`);$t(o)&&(i[0]=t.packages[o].package,s.package=i.join("::"));const a=s.typeArguments;if(a){for(let c=0;c<a.length;c++)if($t(a[c])){if(!t.types[a[c]])throw new Error(`No resolution found for type: ${a[c]}`);a[c]=t.types[a[c]].type}s.typeArguments=a}}}function bm(e){const t=new Set;for(const r of e)if($t(r)){if(!d5(r))throw new Error(`Invalid type with names: ${r}`);t.add(r)}return t}const c3=e=>async(t,r,n)=>{const s=o3(t);if(s.types.length===0&&s.packages.length===0)return n();const i=await u3(r).core.mvr.resolve({types:s.types,packages:s.packages});a3(t,i),await n()};function u3(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 C1=e=>{throw TypeError(e)},kh=(e,t,r)=>t.has(e)||C1("Cannot "+r),Y=(e,t,r)=>(kh(e,t,"read from private field"),r?r.call(e):t.get(e)),Mr=(e,t,r)=>t.has(e)?C1("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Be=(e,t,r,n)=>(kh(e,t,"write to private field"),t.set(e,r),r),rt=(e,t,r)=>(kh(e,t,"access private method"),r),gs,xs,fn,Vr,ir,or,vr,qn,ae,Ke,R1,Xa,Ya,Za,fc,sd,Th,$1,N1;function Jl(e,t=1/0){const r={$kind:"Result",get Result(){return typeof e=="function"?e():e}},n=[],s=i=>n[i]??(n[i]={$kind:"NestedResult",get NestedResult(){return[typeof e=="function"?e():e,i]}});return new Proxy(r,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(i,o){if(o in i)return Reflect.get(i,o);if(o===Symbol.iterator)return function*(){let c=0;for(;c<t;)yield s(c),c++};if(typeof o=="symbol")return;const a=parseInt(o,10);if(!(Number.isNaN(a)||a<0))return s(a)}})}const U1=Symbol.for("@mysten/transaction");function M1(e){return!!e&&typeof e=="object"&&e[U1]===!0}const wm={buildPlugins:new Map,serializationPlugins:new Map},Ql=Symbol.for("@mysten/transaction/registry");function Wi(){try{const e=globalThis;return e[Ql]||(e[Ql]=wm),e[Ql]}catch{return wm}}const F1=class id{constructor(){Mr(this,Ke),Mr(this,gs),Mr(this,xs),Mr(this,fn,new Map),Mr(this,Vr,[]),Mr(this,ir,[]),Mr(this,or,new Set),Mr(this,vr,new Set),Mr(this,qn,new Map),Mr(this,ae),this.object=QO(r=>{var i,o;if(typeof r=="function")return this.object(this.add(r));if(typeof r=="object"&&Yf(Me,r))return r;const n=gm(r),s=Y(this,ae).inputs.find(a=>n===gm(a));return(i=s==null?void 0:s.Object)!=null&&i.SharedObject&&typeof r=="object"&&((o=r.Object)!=null&&o.SharedObject)&&(s.Object.SharedObject.mutable=s.Object.SharedObject.mutable||r.Object.SharedObject.mutable),s?{$kind:"Input",Input:Y(this,ae).inputs.indexOf(s),type:"object"}:rt(this,Ke,Ya).call(this,"object",typeof r=="string"?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:xe(r)}}:r)});const t=Wi();Be(this,ae,new Rt),Be(this,xs,[...t.buildPlugins.values()]),Be(this,gs,[...t.serializationPlugins.values()])}static fromKind(t){const r=new id;return Be(r,ae,Rt.fromKindBytes(typeof t=="string"?zt(t):t)),Be(r,Vr,Y(r,ae).inputs.slice()),Be(r,ir,Y(r,ae).commands.slice()),Be(r,or,new Set(Y(r,ir).map((n,s)=>s))),r}static from(t){const r=new id;return M1(t)?Be(r,ae,new Rt(t.getData())):typeof t!="string"||!t.startsWith("{")?Be(r,ae,Rt.fromBytes(typeof t=="string"?zt(t):t)):Be(r,ae,Rt.restore(JSON.parse(t))),Be(r,Vr,Y(r,ae).inputs.slice()),Be(r,ir,Y(r,ae).commands.slice()),Be(r,or,new Set(Y(r,ir).map((n,s)=>s))),r}static registerGlobalSerializationPlugin(t,r){Wi().serializationPlugins.set(t,r??t)}static unregisterGlobalSerializationPlugin(t){Wi().serializationPlugins.delete(t)}static registerGlobalBuildPlugin(t,r){Wi().buildPlugins.set(t,r??t)}static unregisterGlobalBuildPlugin(t){Wi().buildPlugins.delete(t)}addSerializationPlugin(t){Y(this,gs).push(t)}addBuildPlugin(t){Y(this,xs).push(t)}addIntentResolver(t,r){if(Y(this,fn).has(t)&&Y(this,fn).get(t)!==r)throw new Error(`Intent resolver for ${t} already exists`);Y(this,fn).set(t,r)}setSender(t){Y(this,ae).sender=t}setSenderIfNotSet(t){Y(this,ae).sender||(Y(this,ae).sender=t)}setExpiration(t){Y(this,ae).expiration=t?Ve(A1,t):null}setGasPrice(t){Y(this,ae).gasConfig.price=String(t)}setGasBudget(t){Y(this,ae).gasConfig.budget=String(t)}setGasBudgetIfNotSet(t){Y(this,ae).gasData.budget==null&&(Y(this,ae).gasConfig.budget=String(t))}setGasOwner(t){Y(this,ae).gasConfig.owner=t}setGasPayment(t){Y(this,ae).gasConfig.payment=t.map(r=>Ve(ts,r))}get blockData(){return hm(Y(this,ae).snapshot())}getData(){return Y(this,ae).snapshot()}get[U1](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:e3(t=>mh(t)?rt(this,Ke,Ya).call(this,"pure",{$kind:"Pure",Pure:{bytes:t.toBase64()}}):rt(this,Ke,Ya).call(this,"pure",Yf(lm,t)?Ve(lm,t):t instanceof Uint8Array?yn.Pure(t):{$kind:"UnresolvedPure",UnresolvedPure:{value:t}}))}),this.pure}get gas(){return{$kind:"GasCoin",GasCoin:!0}}objectRef(...t){return this.object(yn.ObjectRef(...t))}receivingRef(...t){return this.object(yn.ReceivingRef(...t))}sharedObjectRef(...t){return this.object(yn.SharedObjectRef(...t))}add(t){if(typeof t=="function"){if(Y(this,qn).has(t))return Y(this,qn).get(t);const r=rt(this,Ke,R1).call(this),n=t(r);if(!(n&&typeof n=="object"&&"then"in n))return Be(this,or,Y(r,or)),Y(this,qn).set(t,n),n;const s=rt(this,Ke,Xa).call(this,{$kind:"$Intent",$Intent:{name:"AsyncTransactionThunk",inputs:{},data:{resultIndex:Y(this,ae).commands.length,result:null}}});Y(this,vr).add(Promise.resolve(n).then(o=>{s.$Intent.data.result=o}));const i=Jl(()=>s.$Intent.data.resultIndex);return Y(this,qn).set(t,i),i}else rt(this,Ke,Xa).call(this,t);return Jl(Y(this,ae).commands.length-1)}splitCoins(t,r){const n=os.SplitCoins(typeof t=="string"?this.object(t):rt(this,Ke,fc).call(this,t),r.map(s=>typeof s=="number"||typeof s=="bigint"||typeof s=="string"?this.pure.u64(s):rt(this,Ke,Za).call(this,s)));return rt(this,Ke,Xa).call(this,n),Jl(Y(this,ae).commands.length-1,r.length)}mergeCoins(t,r){return this.add(os.MergeCoins(this.object(t),r.map(n=>this.object(n))))}publish({modules:t,dependencies:r}){return this.add(os.Publish({modules:t,dependencies:r}))}upgrade({modules:t,dependencies:r,package:n,ticket:s}){return this.add(os.Upgrade({modules:t,dependencies:r,package:n,ticket:this.object(s)}))}moveCall({arguments:t,...r}){return this.add(os.MoveCall({...r,arguments:t==null?void 0:t.map(n=>rt(this,Ke,Za).call(this,n))}))}transferObjects(t,r){return this.add(os.TransferObjects(t.map(n=>this.object(n)),typeof r=="string"?this.pure.address(r):rt(this,Ke,Za).call(this,r)))}makeMoveVec({type:t,elements:r}){return this.add(os.MakeMoveVec({type:t,elements:r.map(n=>this.object(n))}))}serialize(){return JSON.stringify(hm(Y(this,ae).snapshot()))}async toJSON(t={}){await this.prepareForSerialization(t);const r=this.isFullyResolved();return JSON.stringify(Ve(bO,r?{...Y(this,ae).snapshot(),digest:Y(this,ae).getDigest()}:Y(this,ae).snapshot()),(n,s)=>typeof s=="bigint"?s.toString():s,2)}async sign(t){const{signer:r,...n}=t,s=await this.build(n);return r.signTransaction(s)}isFullyResolved(){return!(!Y(this,ae).sender||Y(this,vr).size>0||Y(this,ae).commands.some(t=>t.$Intent)||T1(Y(this,ae),{}))}async build(t={}){return await this.prepareForSerialization(t),await rt(this,Ke,sd).call(this,t),Y(this,ae).build({onlyTransactionKind:t.onlyTransactionKind})}async getDigest(t={}){return await this.prepareForSerialization(t),await rt(this,Ke,sd).call(this,t),Y(this,ae).getDigest()}async prepareForSerialization(t){var s;await rt(this,Ke,$1).call(this),rt(this,Ke,N1).call(this);const r=new Set;for(const i of Y(this,ae).commands)i.$Intent&&r.add(i.$Intent.name);const n=[...Y(this,gs)];for(const i of r)if(!((s=t.supportedIntents)!=null&&s.includes(i))){if(!Y(this,fn).has(i))throw new Error(`Missing intent resolver for ${i}`);n.push(Y(this,fn).get(i))}n.push(c3()),await rt(this,Ke,Th).call(this,n,t)}};gs=new WeakMap;xs=new WeakMap;fn=new WeakMap;Vr=new WeakMap;ir=new WeakMap;or=new WeakMap;vr=new WeakMap;qn=new WeakMap;ae=new WeakMap;Ke=new WeakSet;R1=function(){const e=new F1;return Be(e,ae,Y(this,ae)),Be(e,gs,Y(this,gs)),Be(e,xs,Y(this,xs)),Be(e,fn,Y(this,fn)),Be(e,vr,Y(this,vr)),Be(e,or,new Set(Y(this,or))),Be(e,qn,Y(this,qn)),Y(this,Vr).push(Y(e,Vr)),Y(this,ir).push(Y(e,ir)),e};Xa=function(e){const t=Y(this,ae).commands.length;return Y(this,ir).push(e),Y(this,or).add(t),Y(this,ae).commands.push(e),Y(this,ae).mapCommandArguments(t,r=>{if(r.$kind==="Result"&&!Y(this,or).has(r.Result))throw new Error(`Result { Result: ${r.Result} } is not available to use the current transaction`);if(r.$kind==="NestedResult"&&!Y(this,or).has(r.NestedResult[0]))throw new Error(`Result { NestedResult: [${r.NestedResult[0]}, ${r.NestedResult[1]}] } is not available to use the current transaction`);if(r.$kind==="Input"&&r.Input>=Y(this,ae).inputs.length)throw new Error(`Input { Input: ${r.Input} } references an input that does not exist in the current transaction`);return r}),e};Ya=function(e,t){return Y(this,Vr).push(t),Y(this,ae).addInput(e,t)};Za=function(e){return mh(e)?this.pure(e):rt(this,Ke,fc).call(this,e)};fc=function(e){if(typeof e=="function"){const t=this.add(e);return typeof t=="function"?rt(this,Ke,fc).call(this,t):Ve(Me,t)}return Ve(Me,e)};sd=async function(e){if(!e.onlyTransactionKind&&!Y(this,ae).sender)throw new Error("Missing transaction sender");await rt(this,Ke,Th).call(this,[...Y(this,xs),YO],e)};Th=async function(e,t){const r=n=>{if(n>=e.length)return()=>{};const s=e[n];return async()=>{const i=r(n+1);let o=!1,a=!1;if(await s(Y(this,ae),t,async()=>{if(o)throw new Error(`next() was call multiple times in TransactionPlugin ${n}`);o=!0,await i(),a=!0}),!o)throw new Error(`next() was not called in TransactionPlugin ${n}`);if(!a)throw new Error(`next() was not awaited in TransactionPlugin ${n}`)}};await r(0)(),Be(this,Vr,Y(this,ae).inputs.slice()),Be(this,ir,Y(this,ae).commands.slice())};$1=async function(){for(;Y(this,vr).size>0;){const e=Promise.all(Y(this,vr));Y(this,vr).clear(),Y(this,vr).add(e),await e,Y(this,vr).delete(e)}};N1=function(){var o;const e=Y(this,ae).commands,t=Y(this,ae).inputs,r=Y(this,ir).flat(1/0),n=Y(this,Vr).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 s=r.filter(a=>{var c;return((c=a.$Intent)==null?void 0:c.name)!=="AsyncTransactionThunk"});Y(this,ae).commands=s,Y(this,ae).inputs=n,Be(this,ir,s),Be(this,Vr,n),Be(this,or,new Set(s.map((a,c)=>c)));function i(a){var u;const c=e[a];if(((u=c.$Intent)==null?void 0:u.name)==="AsyncTransactionThunk"){const f=c.$Intent.data.result;if(f==null)throw new Error("AsyncTransactionThunk has not been resolved");return i(f.Result)}const l=s.indexOf(c);if(l===-1)throw new Error("Unable to find original index for command");return l}Y(this,ae).mapArguments(a=>{if(a.$kind==="Input"){const c=n.indexOf(t[a.Input]);if(c===-1)throw new Error("Input has not been resolved");return{...a,Input:c}}else if(a.$kind==="Result"){const c=i(a.Result);return{...a,Result:c}}else if(a.$kind==="NestedResult"){const c=i(a.NestedResult[0]);return{...a,NestedResult:[c,a.NestedResult[1]]}}return a});for(const[a,c]of e.entries())if(((o=c.$Intent)==null?void 0:o.name)==="AsyncTransactionThunk")try{c.$Intent.data.resultIndex=i(a)}catch{}};let j1=F1;const l3={mainnet:"https://mainnet.mvr.mystenlabs.com",testnet:"https://testnet.mvr.mystenlabs.com"};class f3 extends Gw{constructor(t){var r,n,s;super(t),this.core=this,this.mvr=new s3({cache:this.cache.scope("core.mvr"),url:((r=t.mvr)==null?void 0:r.url)??l3[this.network],pageSize:(n=t.mvr)==null?void 0:n.pageSize,overrides:(s=t.mvr)==null?void 0:s.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=IO(t.parentId,wr.parseFromStr(t.name.type),t.name.bcs),{objects:[n]}=await this.getObjects({objectIds:[r],signal:t.signal});if(n instanceof Error)throw n;const s=Ns(n.type),i=await n.content;return{dynamicField:{id:n.id,digest:n.digest,version:n.version,type:n.type,name:{type:typeof s.typeParams[0]=="string"?s.typeParams[0]:lc(s.typeParams[0]),bcs:t.name.bcs},value:{type:typeof s.typeParams[1]=="string"?s.typeParams[1]:lc(s.typeParams[1]),bcs:i.slice(su+t.name.bcs.length)}}}}async waitForTransaction({signal:t,timeout:r=60*1e3,...n}){const s=t?AbortSignal.any([AbortSignal.timeout(r),t]):AbortSignal.timeout(r),i=new Promise((o,a)=>{s.addEventListener("abort",()=>a(s.reason))});for(i.catch(()=>{});;){s.throwIfAborted();try{return await this.getTransaction({...n,signal:s})}catch{await Promise.race([new Promise(a=>setTimeout(a,2e3)),i])}}}}class d3 extends Error{}class Vn extends d3{constructor(t,r){super(r),this.code=t}static fromResponse(t,r){switch(t.code){case"notExists":return new Vn(t.code,`Object ${t.object_id} does not exist`);case"dynamicFieldNotFound":return new Vn(t.code,`Dynamic field not found for object ${t.parent_object_id}`);case"deleted":return new Vn(t.code,`Object ${t.object_id} has been deleted`);case"displayError":return new Vn(t.code,`Display error: ${t.error}`);case"unknown":default:return new Vn(t.code,`Unknown error while loading object${r?` ${r}`:""}`)}}}function h3(e){return{...Rt.fromBytes(e).snapshot(),bcs:e}}function p3(e){const t=de.TransactionEffects.parse(e);switch(t.$kind){case"V1":return y3({effects:t.V1});case"V2":return m3({bytes:e,effects:t.V2});default:throw new Error(`Unknown transaction effects version: ${t.$kind}`)}}function y3(e){throw new Error("V1 effects are not supported yet")}function m3({bytes:e,effects:t}){const r=t.changedObjects.map(([n,s])=>{var i,o,a,c,l,u;return{id:n,inputState:s.inputState.$kind==="Exist"?"Exists":"DoesNotExist",inputVersion:((i=s.inputState.Exist)==null?void 0:i[0][0])??null,inputDigest:((o=s.inputState.Exist)==null?void 0:o[0][1])??null,inputOwner:((a=s.inputState.Exist)==null?void 0:a[1])??null,outputState:s.outputState.$kind==="NotExist"?"DoesNotExist":s.outputState.$kind,outputVersion:s.outputState.$kind==="PackageWrite"?(c=s.outputState.PackageWrite)==null?void 0:c[0]:s.outputState.ObjectWrite?t.lamportVersion:null,outputDigest:s.outputState.$kind==="PackageWrite"?(l=s.outputState.PackageWrite)==null?void 0:l[1]:((u=s.outputState.ObjectWrite)==null?void 0:u[0])??null,outputOwner:s.outputState.ObjectWrite?s.outputState.ObjectWrite[1]:null,idOperation:s.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,unchangedSharedObjects:t.unchangedSharedObjects.map(([n,s])=>({kind:s.$kind==="MutateDeleted"?"MutateConsensusStreamEnded":s.$kind==="ReadDeleted"?"ReadConsensusStreamEnded":s.$kind,objectId:n,version:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[0]:s[s.$kind],digest:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[1]:null})),auxiliaryDataDigest:t.auxDataDigest}}var L1=e=>{throw TypeError(e)},D1=(e,t,r)=>t.has(e)||L1("Cannot "+r),Lt=(e,t,r)=>(D1(e,t,"read from private field"),r?r.call(e):t.get(e)),g3=(e,t,r)=>t.has(e)?L1("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),b3=(e,t,r,n)=>(D1(e,t,"write to private field"),t.set(e,r),r),yt;class w3 extends f3{constructor({jsonRpcClient:t,mvr:r}){super({network:t.network,base:t,mvr:r}),g3(this,yt),b3(this,yt,t)}async getObjects(t){const r=nu(t.objectIds,50),n=[];for(const s of r){const i=await Lt(this,yt).multiGetObjects({ids:s,options:{showOwner:!0,showType:!0,showBcs:!0},signal:t.signal});for(const[o,a]of i.entries())a.error?n.push(Vn.fromResponse(a.error,s[o])):n.push(vm(a.data))}return{objects:n}}async getOwnedObjects(t){const r=await Lt(this,yt).getOwnedObjects({owner:t.address,limit:t.limit,cursor:t.cursor,options:{showOwner:!0,showType:!0,showBcs:!0},filter:t.type?{StructType:t.type}:null,signal:t.signal});return{objects:r.data.map(n=>{if(n.error)throw Vn.fromResponse(n.error);return vm(n.data)}),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getCoins(t){const r=await Lt(this,yt).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(A3.serialize({id:n.coinObjectId,balance:{value:n.balance}}).toBytes()),owner:{$kind:"ObjectOwner",ObjectOwner:t.address}})),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getBalance(t){const r=await Lt(this,yt).getBalance({owner:t.address,coinType:t.coinType,signal:t.signal});return{balance:{coinType:r.coinType,balance:r.totalBalance}}}async getAllBalances(t){return{balances:(await Lt(this,yt).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 Lt(this,yt).getTransactionBlock({digest:t.digest,options:{showRawInput:!0,showObjectChanges:!0,showRawEffects:!0,showEvents:!0,showEffects:!0},signal:t.signal});return{transaction:Em(r)}}async executeTransaction(t){const r=await Lt(this,yt).executeTransactionBlock({transactionBlock:t.transaction,signature:t.signatures,options:{showRawEffects:!0,showEvents:!0,showObjectChanges:!0,showRawInput:!0,showEffects:!0},signal:t.signal});return{transaction:Em(r)}}async dryRunTransaction(t){const r=j1.from(t.transaction),n=await Lt(this,yt).dryRunTransactionBlock({transactionBlock:t.transaction,signal:t.signal}),{effects:s,objectTypes:i}=v3({effects:n.effects,objectChanges:n.objectChanges});return{transaction:{digest:await r.getDigest(),epoch:null,effects:s,objectTypes:Promise.resolve(i),signatures:[],transaction:h3(t.transaction)}}}async getReferenceGasPrice(t){const r=await Lt(this,yt).getReferenceGasPrice({signal:t==null?void 0:t.signal});return{referenceGasPrice:String(r)}}async getDynamicFields(t){const r=await Lt(this,yt).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:zt(n.bcsName)}})),hasNextPage:r.hasNextPage,cursor:r.nextCursor}}async verifyZkLoginSignature(t){const r=await Lt(this,yt).verifyZkLoginSignature({bytes:t.bytes,signature:t.signature,intentScope:t.intentScope,author:t.author});return{success:r.success,errors:r.errors}}resolveNameServiceNames(t){return Lt(this,yt).resolveNameServiceNames(t)}resolveTransactionPlugin(){return k1(Lt(this,yt))}}yt=new WeakMap;function vm(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"?zt(e.bcs.bcsBytes):new Uint8Array),owner:si(e.owner)}}function si(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 Em(e){var i,o;const t=de.SenderSignedData.parse(zt(e.rawTransaction))[0],r={};(i=e.objectChanges)==null||i.forEach(a=>{a.type!=="published"&&(r[a.objectId]=a.objectType)});const n=de.TransactionData.serialize(t.intentMessage.value).toBytes(),s=Rt.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:((o=e.effects)==null?void 0:o.executedEpoch)??null,effects:p3(new Uint8Array(e.rawEffects)),objectTypes:Promise.resolve(r),transaction:{...s,bcs:n},signatures:t.txSignatures}}function v3({bytes:e,effects:t,objectChanges:r}){var o;const n=[],s=[],i={};return r==null||r.forEach(a=>{var c,l,u,f;switch(a.type){case"published":n.push({id:a.packageId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"PackageWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:null,idOperation:"Created"});break;case"transferred":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:a.digest,inputOwner:{$kind:"AddressOwner",AddressOwner:a.sender},outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:si(a.recipient),idOperation:"None"}),i[a.objectId]=a.objectType;break;case"mutated":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.previousVersion,inputDigest:null,inputOwner:si(a.owner),outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:si(a.owner),idOperation:"None"}),i[a.objectId]=a.objectType;break;case"deleted":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:((l=(c=t.deleted)==null?void 0:c.find(p=>p.objectId===a.objectId))==null?void 0:l.digest)??null,inputOwner:null,outputState:"DoesNotExist",outputVersion:null,outputDigest:null,outputOwner:null,idOperation:"Deleted"}),i[a.objectId]=a.objectType;break;case"wrapped":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:null,inputOwner:{$kind:"AddressOwner",AddressOwner:a.sender},outputState:"ObjectWrite",outputVersion:a.version,outputDigest:((f=(u=t.wrapped)==null?void 0:u.find(p=>p.objectId===a.objectId))==null?void 0:f.digest)??null,outputOwner:{$kind:"ObjectOwner",ObjectOwner:a.sender},idOperation:"None"}),i[a.objectId]=a.objectType;break;case"created":n.push({id:a.objectId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:si(a.owner),idOperation:"Created"}),i[a.objectId]=a.objectType;break}}),{objectTypes:i,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:(o=t.gasObject)==null?void 0:o.reference.objectId,inputState:"Exists",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:t.gasObject.reference.version,outputDigest:t.gasObject.reference.digest,outputOwner:si(t.gasObject.owner),idOperation:"None"},eventsDigest:t.eventsDigest??null,dependencies:t.dependencies??[],lamportVersion:t.gasObject.reference.version,changedObjects:n,unchangedSharedObjects:s,auxiliaryDataDigest:null}}}const E3=de.struct("Balance",{value:de.u64()}),A3=de.struct("Coin",{id:de.Address,balance:E3}),x3=Symbol.for("@mysten/SuiClient");class S3 extends Gw{constructor(t){super({network:t.network??"unknown"}),this.jsonRpc=this,this.transport=t.transport??new _P({url:t.url}),this.core=new w3({jsonRpcClient:this,mvr:t.mvr})}get[x3](){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:s,signal:i}){if(!r||!gr(xe(r)))throw new Error("Invalid Sui address");return t&&$t(t)&&(t=(await this.core.mvr.resolveType({type:t})).type),await this.transport.request({method:"suix_getCoins",params:[r,t,n,s],signal:i})}async getAllCoins(t){if(!t.owner||!gr(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||!gr(xe(t)))throw new Error("Invalid Sui address");return r&&$t(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||!gr(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&&$t(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&&$t(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:s}){return t&&Dt(t)&&(t=(await this.core.mvr.resolvePackage({package:t})).package),await this.transport.request({method:"sui_getMoveFunctionArgTypes",params:[t,r,n],signal:s})}async getNormalizedMoveModulesByPackage({package:t,signal:r}){return t&&Dt(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&&Dt(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:s}){return t&&Dt(t)&&(t=(await this.core.mvr.resolvePackage({package:t})).package),await this.transport.request({method:"sui_getNormalizedMoveFunction",params:[t,r,n],signal:s})}async getNormalizedMoveStruct({package:t,module:r,struct:n,signal:s}){return t&&Dt(t)&&(t=(await this.core.mvr.resolvePackage({package:t})).package),await this.transport.request({method:"sui_getNormalizedMoveStruct",params:[t,r,n],signal:s})}async getOwnedObjects(t){if(!t.owner||!gr(xe(t.owner)))throw new Error("Invalid Sui address");const r=t.filter?{...t.filter}:void 0;return r&&"MoveModule"in r&&Dt(r.MoveModule.package)?r.MoveModule={module:r.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:r.MoveModule.package})).package}:r&&"StructType"in r&&$t(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||!$a(pn(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||!$a(pn(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:s,order:i,signal:o}){return t&&"MoveFunction"in t&&Dt(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,s,(i||"descending")==="descending"],signal:o})}async getTransactionBlock(t){if(!am(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(!am(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:s,signal:i}){const o=await this.transport.request({method:"sui_executeTransactionBlock",params:[typeof t=="string"?t:mt(t),Array.isArray(r)?r:[r],n],signal:i});if(s==="WaitForLocalExecution")try{await this.waitForTransaction({digest:o.digest})}catch{}return o}async signAndExecuteTransaction({transaction:t,signer:r,...n}){let s;t instanceof Uint8Array?s=t:(t.setSenderIfNotSet(r.toSuiAddress()),s=await t.build({client:this}));const{signature:i,bytes:o}=await r.signTransaction(s);return this.executeTransactionBlock({transactionBlock:o,signature:i,...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||!gr(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||!$a(pn(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:s,signal:i}){return t&&"MoveEventType"in t&&$t(t.MoveEventType)&&(t={...t,MoveEventType:(await this.core.mvr.resolveType({type:t.MoveEventType})).type}),t&&"MoveEventModule"in t&&Dt(t.MoveEventModule.package)&&(t={...t,MoveEventModule:{module:t.MoveEventModule.module,package:(await this.core.mvr.resolvePackage({package:t.MoveEventModule.package})).package}}),"MoveModule"in t&&Dt(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,(s||"descending")==="descending"],signal:i})}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,s;let r;if(M1(t.transactionBlock))t.transactionBlock.setSenderIfNotSet(t.sender),r=mt(await t.transactionBlock.build({client:this,onlyTransactionKind:!0}));else if(typeof t.transactionBlock=="string")r=t.transactionBlock;else if(t.transactionBlock instanceof Uint8Array)r=mt(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,(s=t.gasPrice)==null?void 0:s.toString(),t.epoch],signal:t.signal})}async dryRunTransactionBlock(t){return await this.transport.request({method:"sui_dryRunTransactionBlock",params:[typeof t.transactionBlock=="string"?t.transactionBlock:mt(t.transactionBlock)]})}async getDynamicFields(t){if(!t.parentId||!$a(pn(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=zo(r.digest);return Si(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:s,data:i}=await this.transport.request({method:"suix_resolveNameServiceNames",params:[r.address,r.cursor,r.limit],signal:r.signal});return{hasNextPage:s,nextCursor:n,data:i.map(o=>c5(o,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,...s}){const i=AbortSignal.timeout(r),o=new Promise((a,c)=>{i.addEventListener("abort",()=>c(i.reason))});for(o.catch(()=>{});!i.aborted;){t==null||t.throwIfAborted();try{return await this.getTransactionBlock(s)}catch{await Promise.race([new Promise(c=>setTimeout(c,n)),o])}}throw i.throwIfAborted(),new Error("Unexpected error while waiting for transaction block.")}experimental_asClientExtension(){return{name:"jsonRPC",register:()=>this}}}class _3{constructor(t,r,n){this.client=new S3({url:kP(n)}),this.url=t instanceof v.Url?t:new v.Url(t),this.account=r,this.network=n}get htlcActorAddress(){return"accounts"in this.account?this.account.accounts[0].address:this.account.toSuiAddress()}async initiate(t){var r,n,s;try{const{source_swap:i}=t,o=BigInt(i.amount),a=i.asset,c=i.redeemer,l=i.secret_hash,u=new j1;u.setSender(this.htlcActorAddress);const[f]=u.splitCoins(u.gas,[o]);u.moveCall({target:`${kp[this.network].packageId}::${kp[this.network].moduleName}::initiate`,typeArguments:[i.token_address],arguments:[u.object(a),u.pure.address(this.htlcActorAddress),u.pure.address(c),u.pure.vector("u8",Buffer.from(l,"hex")),u.pure.u64(o),u.pure.u256(i.timelock),u.pure.vector("u8",Buffer.from("")),f,u.object(EO)]});const p=await u.build({client:this.client}),d=await this.client.dryRunTransactionBlock({transactionBlock:p});if(d.effects.status.status==="failure")return v.Err(`${d.effects.status.error}`);let m;if("features"in this.account?m=await((r=this.account.features[X1.SuiSignAndExecuteTransaction])==null?void 0:r.signAndExecuteTransaction({transaction:u,account:this.account.accounts[0],chain:`sui:${this.network}`})):m=await this.client.signAndExecuteTransaction({signer:this.account,transaction:u,options:{showEffects:!0}}),!m)return v.Err("Failed to initiate");const g=await this.client.waitForTransaction({digest:m.digest,options:{showEffects:!0}});return((n=g.effects)==null?void 0:n.status.status)==="failure"?v.Err(`Failed to initiate: ${(s=g.effects)==null?void 0:s.status.error}`):v.Ok(g.digest)}catch(i){return v.Err(i)}}async redeem(t,r){try{const n=await v.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:r,perform_on:"Destination"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return n.error?v.Err(n.error):n.result?v.Ok(n.result):v.Err("Redeem: No result found")}catch(n){return v.Err(String(n))}}async refund(){return v.Err("Refund is taken care of by the relayer")}}class Ih extends v.EventBroker{constructor(t){super(),this.environment=v.Environment.TESTNET,this.getOrderThreshold=20,this.refundSacpCache=new Map,this.bitcoinRedeemCache=new vT,this.isSecretManagementEnabled=!1;const{api:r,environment:n}=$f(t.environment);if(this.environment=n,this._api=r,typeof t.digestKey=="string"){const i=v.DigestKey.from(t.digestKey);if(!i.ok)throw new Error(i.error);this._digestKey=i.val}else this._digestKey=t.digestKey;this._quote=t.quote??new Vb(this._api.quote),this._auth=t.auth??v.Siwe.fromDigestKey(new v.Url(this._api.auth),this._digestKey),this._orderbook=t.orderbook??new be.Orderbook(new v.Url(this._api.orderbook)),this._evmHTLC=t.htlc.evm,this._starknetHTLC=t.htlc.starknet,this._solanaHTLC=t.htlc.solana,this._suiHTLC=t.htlc.sui,this._secretManager=t.secretManager??Do.fromDigestKey(this._digestKey.digestKey),this.orderExecutorCache=new wT,this._blockNumberFetcher=t.blockNumberFetcher??new qb(this._api.info,this.environment);const s=new sw(c_(this.environment));this._btcWallet=hs.fromPrivateKey(this._digestKey.digestKey,s)}handleSecretManagement(t){return this.isSecretManagementEnabled=t,this}static fromWallets(t){let r;if(typeof t.digestKey=="string"){const i=v.DigestKey.from(t.digestKey);if(!i.ok)throw new Error(i.error);r=i.val}else r=t.digestKey;const{api:n}=$f(t.environment);if(!n)throw new Error("API not found, invalid environment "+t.environment);const s={evm:t.wallets.evm?new Jb(n.evmRelay,t.wallets.evm,v.Siwe.fromDigestKey(new v.Url(n.auth),r)):void 0,starknet:t.wallets.starknet?new nw(n.starknetRelay,t.wallets.starknet,t.environment===v.Environment.MAINNET?v.Network.MAINNET:v.Network.TESTNET):void 0,solana:t.wallets.solana?new Ew(t.wallets.solana,new v.Url(n.solanaRelay),t.environment===v.Environment.MAINNET?Cf.mainnet:Cf.testnet,{native:t.solanaProgramAddress&&t.solanaProgramAddress.native?t.solanaProgramAddress.native:Rf.mainnet.native,spl:t.solanaProgramAddress&&t.solanaProgramAddress.spl?t.solanaProgramAddress.spl:Rf.mainnet.spl}):void 0,sui:t.wallets.sui?new _3(n.suiRelay,t.wallets.sui,t.environment===v.Environment.MAINNET?v.Network.MAINNET:v.Network.TESTNET):void 0};return new Ih({htlc:s,...t})}get evmHTLC(){return this._evmHTLC}get starknetHTLC(){return this._starknetHTLC}get solanaHTLC(){return this._solanaHTLC}get suiHTLC(){return this._suiHTLC}get quote(){return this._quote}get btcWallet(){return this._btcWallet}get orderbook(){return this._orderbook}get blockNumberFetcher(){return this._blockNumberFetcher}get secretManager(){return this._secretManager}get auth(){return this._auth}get digestKey(){return this._digestKey}async swap(t){const r=await this.validateAndFillParams(t);if(!r.ok)return v.Err(r.error);const{sendAddress:n,receiveAddress:s}=r.val,i=Date.now().toString();let o;if(this.isSecretManagementEnabled){const w=await this._secretManager.generateSecret(i);if(!w.ok)return v.Err(w.error);o=w.val.secretHash}const{strategyId:a,btcAddress:c}=t.additionalData,l=be.isBitcoin(t.fromAsset.chain),u=be.isBitcoin(t.toAsset.chain),f=l||u;if(!this.isSecretManagementEnabled&&f&&!c)return v.Err("Bitcoin optional recipient is mandatory when secret management is enabled and any chain is Bitcoin");const p={strategy_id:a,...c&&{bitcoin_optional_recipient:c}},d={...!this.isSecretManagementEnabled&&l?{}:{initiator_source_address:n},...!this.isSecretManagementEnabled&&u?{}:{initiator_destination_address:s},...this.isSecretManagementEnabled&&o?{secret_hash:v.trim0x(o)}:{}},m={source_chain:t.fromAsset.chain,destination_chain:t.toAsset.chain,source_asset:t.fromAsset.atomicSwapAddress,destination_asset:t.toAsset.atomicSwapAddress,source_amount:t.sendAmount,destination_amount:t.receiveAmount,nonce:i,...d,additional_data:p,affiliate_fees:this.withDefaultAffiliateFees(t.affiliateFee)};console.log("Creating order",m);const g=await this._orderbook.createOrder(m,this.auth);return g.ok?v.Ok(g.val):v.Err(g.error)}withDefaultAffiliateFees(t){return(t??[]).map(r=>({fee:r.fee,address:r.address,chain:r.chain??Tp.chain,asset:r.asset??Tp.asset}))}async validateAndFillParams(t){if(!t.additionalData.strategyId)return v.Err("StrategyId is required");if(!t.fromAsset||!t.toAsset)return v.Err("Source and destination assets are required for swap");if(t.fromAsset.chain===t.toAsset.chain&&t.fromAsset.atomicSwapAddress===t.toAsset.atomicSwapAddress)return v.Err("Source and destination assets cannot be the same");if(be.isMainnet(t.fromAsset.chain)&&!be.isMainnet(t.toAsset.chain)||!be.isMainnet(t.fromAsset.chain)&&be.isMainnet(t.toAsset.chain))return v.Err("Both assets should be on the same network (either mainnet or testnet)");const r=this.validateAmount(t.sendAmount);if(!r.ok)return v.Err(r.error);const n=this.validateAmount(t.receiveAmount);if(!n.ok)return v.Err(n.error);if(r<n)return v.Err("Send amount should be greater than receive amount");if((be.isBitcoin(t.fromAsset.chain)||be.isBitcoin(t.toAsset.chain))&&!t.additionalData.btcAddress)return v.Err("btcAddress in additionalData is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const s=await this.getAddresses(t.fromAsset.chain);if(!s.ok)return v.Err(s.error);const i=await this.getAddresses(t.toAsset.chain);return i.ok?v.Ok({sendAddress:s.val,receiveAddress:i.val}):v.Err(i.error)}async getAddresses(t){var n;switch(be.getBlockchainType(t)){case be.BlockchainType.EVM:return this._evmHTLC?v.Ok(this._evmHTLC.htlcActorAddress):v.Err("Please provide evmHTLC when initializing garden");case be.BlockchainType.Bitcoin:{const s=await((n=this._btcWallet)==null?void 0:n.getPublicKey());return!s||!o_(s)?v.Err("Invalid btc public key"):v.Ok(Fn(s))}case be.BlockchainType.Solana:return this._solanaHTLC?v.Ok(this._solanaHTLC.htlcActorAddress):v.Err("Please provide solanaHTLC when initializing garden");case be.BlockchainType.Starknet:return this._starknetHTLC?v.Ok(this._starknetHTLC.htlcActorAddress):v.Err("Please provide starknetHTLC when initializing garden");case be.BlockchainType.Sui:return this._suiHTLC?v.Ok(this._suiHTLC.htlcActorAddress):v.Err("Please provide suiHTLC when initializing garden");default:return v.Err("Unsupported chain")}}validateAmount(t){if(t==null||t.includes("."))return v.Err("Invalid amount ",t);const r=new G1(t);return!r.isInteger()||r.isNaN()||r.lt(0)||r.isLessThanOrEqualTo(0)?v.Err("Invalid amount ",t):v.Ok(r)}async execute(t=5e3){return await this._orderbook.subscribeOrders(this._digestKey.userId,!0,t,async r=>{const n=await this.assignStatus(r.data);if(n.ok&&(this.emit("onPendingOrdersChanged",n.val),r.data.length!==0))for(const s of n.val){if(!this.isSecretManagementEnabled){switch(s.status){case ge.Completed:case ge.Redeemed:case ge.CounterPartyRedeemed:{if(!s.destination_swap.redeem_tx_hash)continue;this.orderExecutorCache.set(s,Ae.Redeem,s.destination_swap.redeem_tx_hash),this.emit("success",s,Ae.Redeem,s.destination_swap.redeem_tx_hash);break}}continue}const i=Yd(s.status);if(be.isBitcoin(s.source_swap.chain)&&(s.status===ge.InitiateDetected||s.status===ge.Initiated||s.status===ge.CounterPartyInitiated||s.status===ge.CounterPartyInitiateDetected||s.status===ge.CounterPartyRefundDetected||s.status===ge.CounterPartyRefunded||s.status===ge.CounterPartySwapExpired||s.status===ge.Expired||s.status===ge.DeadLineExceeded)){const o=this._btcWallet;if(!o){this.emit("error",s,"BTC wallet not found");continue}await this.postRefundSACP(s,o)}switch(i){case Ae.Redeem:{const o=await this._secretManager.generateSecret(s.create_order.nonce);if(!o.ok){this.emit("error",s,o.error);return}const a=o.val.secret;switch(be.getBlockchainType(s.destination_swap.chain)){case be.BlockchainType.EVM:await this.evmRedeem(s,a);break;case be.BlockchainType.Bitcoin:{const c=this.btcWallet;if(!c){this.emit("error",s,"BTC wallet not found");return}await this.btcRedeem(c,s,a);break}case be.BlockchainType.Starknet:{await this.starknetRedeem(s,a);break}case be.BlockchainType.Solana:{await this.solRedeem(s,o.val.secret);break}case be.BlockchainType.Sui:{await this.suiRedeem(s,o.val.secret);break}default:this.emit("error",s,"Unsupported chain: "+s.destination_swap.chain)}break}case Ae.Refund:{switch(be.getBlockchainType(s.source_swap.chain)){case be.BlockchainType.Solana:{this.emit("error",s,"Solana refund is automatically done by relay service");break}case be.BlockchainType.EVM:{this.emit("error",s,"EVM refund is automatically done by relay service");break}case be.BlockchainType.Bitcoin:{const o=this.btcWallet;if(!o){this.emit("error",s,"BTC wallet not found");continue}await this.btcRefund(o,s);break}case be.BlockchainType.Starknet:this.emit("error",s,"Starknet refund is automatically done by relay service");break;default:this.emit("error",s,"Unsupported chain: "+s.source_swap.chain)}break}}}},"pending",{per_page:500})}async solRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing sol redeem"),this.orderExecutorCache.get(t,Ae.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._solanaHTLC){this.emit("error",t,"Solana HTLC is required");return}const s=await this._solanaHTLC.redeem(t,r);if(s.error){this.emit("error",t,s.error),s.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,Ae.Redeem,t.destination_swap.redeem_tx_hash);return}s.val&&(this.orderExecutorCache.set(t,Ae.Redeem,s.val),this.emit("success",t,Ae.Redeem,s.val))}async suiRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing sui redeem"),this.orderExecutorCache.get(t,Ae.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._suiHTLC){this.emit("error",t,"Sui HTLC is required");return}const s=await this._suiHTLC.redeem(t,r);if(s.error){this.emit("error",t,s.error),s.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,Ae.Redeem,t.destination_swap.redeem_tx_hash);return}s.val&&(this.orderExecutorCache.set(t,Ae.Redeem,s.val),this.emit("success",t,Ae.Redeem,s.val))}async evmRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing evm redeem"),this.orderExecutorCache.get(t,Ae.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._evmHTLC){this.emit("error",t,"EVMHTLC is required");return}const s=await this._evmHTLC.redeem(t,r);if(!s.ok){this.emit("error",t,s.error),s.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,Ae.Redeem,t.destination_swap.redeem_tx_hash);return}this.orderExecutorCache.set(t,Ae.Redeem,s.val),this.emit("success",t,Ae.Redeem,s.val)}async starknetRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing starknet redeem"),this.orderExecutorCache.get(t,Ae.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._starknetHTLC){this.emit("error",t,"StarknetHTLC is required");return}const s=await this._starknetHTLC.redeem(t,r);if(!s.ok){this.emit("error",t,s.error),s.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,Ae.Redeem,t.destination_swap.redeem_tx_hash);return}s.val&&(this.orderExecutorCache.set(t,Ae.Redeem,s.val),this.emit("success",t,Ae.Redeem,s.val))}async btcRedeem(t,r,n){var a,c,l;const s=this.bitcoinRedeemCache.get(r.create_order.create_id),i=(a=r.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:a.split(":").at(0);if(!i){this.emit("error",r,"Failed to get initiate_tx_hash");return}let o=!1;if(s)if(s.redeemedFromUTXO&&s.redeemedFromUTXO!==i)o=!0,this.emit("log",r.create_order.create_id,"rbf btc redeem");else if(s.redeemedAt&&Date.now()-s.redeemedAt>1e3*60*15)this.emit("log",r.create_order.create_id,"redeem not confirmed in last 15 minutes"),o=!0;else{this.emit("log",r.create_order.create_id,"btcRedeem: already redeemed");return}else if(r.destination_swap.redeem_tx_hash&&!Number(r.destination_swap.redeem_block_number))try{const u=await(await t.getProvider()).getTransaction(r.destination_swap.redeem_tx_hash);let f=!1;for(const p of u.vin)if(p.txid===i){f=!0;break}if(f){this.emit("log",r.create_order.create_id,"already a valid redeem");let p=0;try{const[d]=await(await t.getProvider()).getTransactionTimes([r.destination_swap.redeem_tx_hash]);d!==0&&(p=d)}catch{p=Date.now()}this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:i,redeemedAt:p,redeemTxHash:r.destination_swap.redeem_tx_hash});return}o=!0}catch(u){if(u.message.includes("Transaction not found"))o=!0;else{this.emit("error",r,"Failed to get redeem tx: "+u);return}}this.emit("log",r.create_order.create_id,"executing btc redeem");try{const f=await(await oo.from(t,Number(r.destination_swap.amount),((c=r.create_order)==null?void 0:c.secret_hash)||"",Fn(r.destination_swap.initiator),Fn(r.destination_swap.redeemer),r.destination_swap.timelock,o?[i]:[])).getRedeemHex(v.trim0x(n),(l=r.create_order.additional_data)==null?void 0:l.bitcoin_optional_recipient),p=await this.broadcastRedeemTx(f,r.create_order.create_id);if(!p.ok){this.emit("error",r,p.error||"Failed to broadcast redeem tx");return}o?(this.emit("log",r.create_order.create_id,"rbf: btc redeem success"),this.emit("rbf",r,p.val)):this.emit("success",r,Ae.Redeem,p.val),this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:i,redeemedAt:Date.now(),redeemTxHash:p.val})}catch(u){this.emit("error",r,"Failed btc redeem: "+u)}}async btcRefund(t,r){var n,s;if(!this.orderExecutorCache.get(r,Ae.Refund)){this.emit("log",r.create_order.create_id,"executing btc refund");try{const o=await(await oo.from(t,Number(r.source_swap.amount),((n=r.create_order)==null?void 0:n.secret_hash)||"",Fn(r.source_swap.initiator),Fn(r.source_swap.redeemer),r.source_swap.timelock)).refund((s=r.create_order.additional_data)==null?void 0:s.bitcoin_optional_recipient);this.orderExecutorCache.set(r,Ae.Refund,o),this.emit("success",r,Ae.Refund,o)}catch(i){this.emit("error",r,"Failed btc refund: "+i)}}}async postRefundSACP(t,r){var o;const n=this.refundSacpCache.get(t.create_order.create_id);if((n==null?void 0:n.initTxHash)===t.source_swap.initiate_tx_hash)return;const s=await oo.from(r,Number(t.source_swap.amount),((o=t.create_order)==null?void 0:o.secret_hash)||"",Fn(t.source_swap.initiator),Fn(t.source_swap.redeemer),t.source_swap.timelock);if(t.create_order.additional_data.bitcoin_optional_recipient)try{if(!this._api)return;const a=await this._auth.getAuthHeaders();if(a.error){this.emit("error",t,"Failed to get auth headers: "+a.error);return}const c=await v.Fetcher.post(new v.Url(this._api.orderbook).endpoint("relayer/bitcoin/instant-refund-hash"),{body:JSON.stringify({order_id:t.create_order.create_id}),headers:{"Content-Type":"application/json",...a.val}});if(c.error||!c.result){this.emit("error",t,"Failed to get hash while posting instant refund SACP: "+c.error);return}const l=await s.generateInstantRefundSACPWithHash(c.result),u=new v.Url(this._api.orderbook).endpoint("relayer/bitcoin/instant-refund");(await v.Fetcher.post(u,{headers:{"Content-Type":"application/json",...a.val},body:JSON.stringify({order_id:t.create_order.create_id,signatures:l})})).status==="Ok"&&this.refundSacpCache.set(t.create_order.create_id,{initTxHash:t.source_swap.initiate_tx_hash})}catch(a){this.emit("error",t,"Failed to generate and post SACP: "+a);return}}async assignStatus(t){var s;if(t.length===0)return v.Ok([]);const r=await((s=this._blockNumberFetcher)==null?void 0:s.fetchBlockNumbers());if(!r.ok)return v.Err(r.error);const n=[];for(let i=0;i<t.length;i++){const o=t[i],a=o.source_swap.chain,c=o.destination_swap.chain,l=r==null?void 0:r.val[a],u=r==null?void 0:r.val[c];if(!l||!u){this.emit("error",o,"Error while fetching CurrentBlockNumbers");continue}const f=Xd(o,l,u);n.push({...o,status:f})}return v.Ok(n)}async broadcastRedeemTx(t,r){try{if(!this._api)return v.Err("API not found");const n=new v.Url(this._api.evmRelay).endpoint("/bitcoin/redeem "),s=await this._auth.getAuthHeaders(),o=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...s.val},body:JSON.stringify({redeem_tx_bytes:t,order_id:r})})).json();return o.status==="Ok"&&o.result?v.Ok(o.result):v.Err(o.error)}catch(n){return v.Err("Failed to broadcast redeem tx: "+n)}}}class k3{constructor(t,r,n){this.callData=new it.CallData(Qb),this.account=t,this.starknetProvider=new it.RpcProvider({nodeUrl:r||(n?Mo[n].nodeUrl:Mo.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 it.Contract(rw,n,this.account)}async initiate(t){try{const n=await(await this.getHTLCContract(t)).token();if(!n)throw new Error("Token address retrieval failed");const s=it.num.toHex(n),i=it.cairo.uint256(BigInt(t.source_swap.amount));try{const c=await ew(this.account,s,t.source_swap.asset,BigInt(t.source_swap.amount),this.starknetProvider);if(c.error)return v.Err(c.error)}catch(c){return v.Err(`Allowance check failed: ${c}`)}const{secret_hash:o}=t.create_order;if(!o)return v.Err("Invalid order: secret_hash is undefined");const a=await this.account.execute({contractAddress:t.source_swap.asset,entrypoint:"initiate",calldata:[t.source_swap.redeemer,BigInt(t.source_swap.timelock),i.low,i.high,...v.hexToU32Array(o)]});if(!a.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return v.Ok(a.transaction_hash)}catch(r){return v.Err(`HTLC Initiation Error: ${r}`)}}async redeem(t,r){try{const n=await this.getHTLCContract(t,!0),s=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,i=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:it.CallData.compile({swap_id:s,secret:v.hexToU32Array(r)})});return i.transaction_hash?v.Ok(i.transaction_hash):v.Err("Failed to redeem HTLC transaction")}catch{return v.Err("HTLC Redeem Error")}}async refund(t){try{const r=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,n=await this.getHTLCContract(t),s=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return s.transaction_hash?v.Ok(s.transaction_hash):v.Err("Failed to refund HTLC transaction")}catch{return v.Err("HTLC Refund Error")}}}class T3{constructor(t){if(this.provider=t,!t)throw new Error("Provider is required");this.provider=t,this.program=new sr.Program(zf,t)}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async initiate(t){if(!t)return v.Err("Order is required");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=Wn.from(t),o=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=sr.web3.PublicKey.findProgramAddressSync(o,this.program.programId)[0];const a=await this.program.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction(),c=await this.provider.sendAndConfirm(a);return c?v.Ok(c):v.Err("Failed to initiate HTLC transaction")}catch(r){return v.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(t,r){if(!t)return v.Err("Order is required");if(!r)return v.Err("Secret is required");const{secretHash:n}=Wn.from(t),s=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=sr.web3.PublicKey.findProgramAddressSync(s,this.program.programId)[0];try{const{redeemer:i}=Wn.from(t);if(!this.swapAccount)return v.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const o=await this.program.methods.redeem(vw(r)).accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey,redeemer:i}).transaction(),a=await this.provider.sendAndConfirm(o);return a?v.Ok(a):v.Err("Failed to redeem HTLC transaction")}catch(i){return v.Err(`Error redeeming swap: ${i instanceof Error?i.message:String(i)}`)}}async refund(t){if(!t)return v.Err("Order is required");const{secretHash:r}=Wn.from(t),n=[Buffer.from("swap_account"),Buffer.from(r)];this.swapAccount=sr.web3.PublicKey.findProgramAddressSync(n,this.program.programId)[0];try{if(console.log("Initiating refund for ::",t.source_swap.swap_id),!this.swapAccount)return v.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const s=await this.program.methods.refund().accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey}).transaction(),i=await this.provider.sendAndConfirm(s);return i?v.Ok(i):v.Err("Failed to refund HTLC transaction")}catch(s){return v.Err(`Error refunding swap: ${s instanceof Error?s.message:String(s)}`)}}}exports.API=La;exports.BaseError=z;exports.BitcoinNetwork=Ht;exports.BitcoinProvider=sw;exports.BitcoinWallet=hs;exports.BlockNumberFetcher=qb;exports.EvmRelay=Jb;exports.Garden=Ih;exports.HttpRequestError=ci;exports.OrderActions=Ae;exports.OrderStatus=ge;exports.ParseOrderStatus=Xd;exports.ParseSwapStatus=jf;exports.Quote=Vb;exports.STARKNET_CONFIG=Mo;exports.SecretManager=Do;exports.SolanaHTLC=T3;exports.SolanaRelay=Ew;exports.SolanaRelayerAddress=Cf;exports.StarknetHTLC=k3;exports.StarknetRelay=nw;exports.SwapStatus=Ne;exports.botanixMainnet=Kb;exports.call=ra;exports.checkAllowance=ao;exports.checkAllowanceAndApprove=ew;exports.concat=Vt;exports.constructOrderPair=Uf;exports.decodeErrorResult=g0;exports.encodeAbiParameters=kn;exports.evmToViemChainMap=uh;exports.filterDeadlineExpiredOrders=d_;exports.getUrl=vc;exports.hyperliquid=Yb;exports.hyperliquidTestnet=Xb;exports.isAddressEqual=ta;exports.isAllowanceSufficient=tw;exports.isExpired=Fo;exports.isHex=xr;exports.isOrderExpired=hb;exports.localBatchGatewayRequest=gg;exports.localBatchGatewayUrl=Cc;exports.parseAction=f_;exports.parseActionFromStatus=Yd;exports.resolveApiConfig=$f;exports.solanaProgramAddress=Rf;exports.stringify=Ze;exports.switchOrAddNetwork=Zb;exports.toXOnly=Fn;exports.validateBTCAddress=a_;
|