@gardenfi/core 2.4.3-beta.1 → 2.4.3-beta.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.
@@ -0,0 +1,105 @@
1
+ "use strict";var L1=Object.defineProperty;var D1=(e,t,r)=>t in e?L1(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ih=(e,t,r)=>D1(e,typeof t!="symbol"?t+"":t,r);const be=require("@gardenfi/orderbook"),v=require("@gardenfi/utils"),Em=require("varuint-bitcoin"),H1=require("tiny-secp256k1"),pe=require("bitcoinjs-lib"),z1=require("bignumber.js"),La=require("ecpair"),it=require("starknet"),Ph=require("yup"),Oh=require("bip39"),V1=require("bip32"),vr=require("@coral-xyz/anchor"),q1=require("@mysten/wallet-standard");function sd(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const Bh=sd(Em),or=sd(H1),Ae=sd(pe);var Se=(e=>(e.Idle="Idle",e.Initiate="Initiate",e.Redeem="Redeem",e.Refund="Refund",e))(Se||{});const G1="1.0.8";let Kt=class Jf extends Error{constructor(t,r={}){var o;const n=r.cause instanceof Jf?r.cause.details:(o=r.cause)!=null&&o.message?r.cause.message:r.details,s=r.cause instanceof Jf&&r.cause.docsPath||r.docsPath,i=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: https://abitype.dev${s}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${G1}`].join(`
2
+ `);super(i),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=s,this.metaMessages=r.metaMessages,this.shortMessage=t}};function _n(e,t){const r=e.exec(t);return r==null?void 0:r.groups}const Sm=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,xm=/^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)?$/,Am=/^\(.+?\).*?$/,Ch=/^tuple(?<array>(\[(\d*)\])*)$/;function Qf(e){let t=e.type;if(Ch.test(e.type)&&"components"in e){t="(";const r=e.components.length;for(let s=0;s<r;s++){const i=e.components[s];t+=Qf(i),s<r-1&&(t+=", ")}const n=_n(Ch,e.type);return t+=`)${(n==null?void 0:n.array)??""}`,Qf({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}function ji(e){let t="";const r=e.length;for(let n=0;n<r;n++){const s=e[n];t+=Qf(s),n!==r-1&&(t+=", ")}return t}function tc(e){var t;return e.type==="function"?`function ${e.name}(${ji(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${(t=e.outputs)!=null&&t.length?` returns (${ji(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${ji(e.inputs)})`:e.type==="error"?`error ${e.name}(${ji(e.inputs)})`:e.type==="constructor"?`constructor(${ji(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const _m=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function W1(e){return _m.test(e)}function K1(e){return _n(_m,e)}const Tm=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function Y1(e){return Tm.test(e)}function X1(e){return _n(Tm,e)}const km=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function Z1(e){return km.test(e)}function J1(e){return _n(km,e)}const Im=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function id(e){return Im.test(e)}function Q1(e){return _n(Im,e)}const Pm=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function e2(e){return Pm.test(e)}function t2(e){return _n(Pm,e)}const Om=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function r2(e){return Om.test(e)}function n2(e){return _n(Om,e)}const s2=/^receive\(\) external payable$/;function i2(e){return s2.test(e)}const o2=new Set(["indexed"]),el=new Set(["calldata","memory","storage"]);class a2 extends Kt{constructor({signature:t}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}}class c2 extends Kt{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}}class u2 extends Kt{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}class f2 extends Kt{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}}class l2 extends Kt{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}}class d2 extends Kt{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}}class h2 extends Kt{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}}class p2 extends Kt{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}class Oi extends Kt{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}}class y2 extends Kt{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}}class m2 extends Kt{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}class g2 extends Kt{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}class b2 extends Kt{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}function w2(e,t,r){let n="";if(r)for(const s of Object.entries(r)){if(!s)continue;let i="";for(const o of s[1])i+=`[${o.type}${o.name?`:${o.name}`:""}]`;n+=`(${s[0]}{${i}})`}return t?`${t}:${e}${n}`:e}const ou=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]]);function tl(e,t={}){if(Z1(e))return v2(e,t);if(Y1(e))return E2(e,t);if(W1(e))return S2(e,t);if(e2(e))return x2(e,t);if(r2(e))return A2(e);if(i2(e))return{type:"receive",stateMutability:"payable"};throw new y2({signature:e})}function v2(e,t={}){const r=J1(e);if(!r)throw new Oi({signature:e,type:"function"});const n=gr(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push(_s(n[a],{modifiers:el,structs:t,type:"function"}));const o=[];if(r.returns){const a=gr(r.returns),c=a.length;for(let f=0;f<c;f++)o.push(_s(a[f],{modifiers:el,structs:t,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:s,outputs:o}}function E2(e,t={}){const r=X1(e);if(!r)throw new Oi({signature:e,type:"event"});const n=gr(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(_s(n[o],{modifiers:o2,structs:t,type:"event"}));return{name:r.name,type:"event",inputs:s}}function S2(e,t={}){const r=K1(e);if(!r)throw new Oi({signature:e,type:"error"});const n=gr(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(_s(n[o],{structs:t,type:"error"}));return{name:r.name,type:"error",inputs:s}}function x2(e,t={}){const r=t2(e);if(!r)throw new Oi({signature:e,type:"constructor"});const n=gr(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(_s(n[o],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:s}}function A2(e){const t=n2(e);if(!t)throw new Oi({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}const _2=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,T2=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,k2=/^u?int$/;function _s(e,t){var l,p;const r=w2(e,t==null?void 0:t.type,t==null?void 0:t.structs);if(ou.has(r))return ou.get(r);const n=Am.test(e),s=_n(n?T2:_2,e);if(!s)throw new f2({param:e});if(s.name&&P2(s.name))throw new l2({param:e,name:s.name});const i=s.name?{name:s.name}:{},o=s.modifier==="indexed"?{indexed:!0}:{},a=(t==null?void 0:t.structs)??{};let c,f={};if(n){c="tuple";const d=gr(s.type),m=[],g=d.length;for(let w=0;w<g;w++)m.push(_s(d[w],{structs:a}));f={components:m}}else if(s.type in a)c="tuple",f={components:a[s.type]};else if(k2.test(s.type))c=`${s.type}256`;else if(c=s.type,(t==null?void 0:t.type)!=="struct"&&!Bm(c))throw new u2({type:c});if(s.modifier){if(!((p=(l=t==null?void 0:t.modifiers)==null?void 0:l.has)!=null&&p.call(l,s.modifier)))throw new d2({param:e,type:t==null?void 0:t.type,modifier:s.modifier});if(el.has(s.modifier)&&!O2(c,!!s.array))throw new h2({param:e,type:t==null?void 0:t.type,modifier:s.modifier})}const u={type:`${c}${s.array??""}`,...i,...o,...f};return ou.set(r,u),u}function gr(e,t=[],r="",n=0){const s=e.trim().length;for(let i=0;i<s;i++){const o=e[i],a=e.slice(i+1);switch(o){case",":return n===0?gr(a,[...t,r.trim()]):gr(a,t,`${r}${o}`,n);case"(":return gr(a,t,`${r}${o}`,n+1);case")":return gr(a,t,`${r}${o}`,n-1);default:return gr(a,t,`${r}${o}`,n)}}if(r==="")return t;if(n!==0)throw new b2({current:r,depth:n});return t.push(r.trim()),t}function Bm(e){return e==="address"||e==="bool"||e==="function"||e==="string"||Sm.test(e)||xm.test(e)}const I2=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;function P2(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||Sm.test(e)||xm.test(e)||I2.test(e)}function O2(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}function Cm(e){const t={},r=e.length;for(let o=0;o<r;o++){const a=e[o];if(!id(a))continue;const c=Q1(a);if(!c)throw new Oi({signature:a,type:"struct"});const f=c.properties.split(";"),u=[],l=f.length;for(let p=0;p<l;p++){const m=f[p].trim();if(!m)continue;const g=_s(m,{type:"struct"});u.push(g)}if(!u.length)throw new m2({signature:a});t[c.name]=u}const n={},s=Object.entries(t),i=s.length;for(let o=0;o<i;o++){const[a,c]=s[o];n[a]=Rm(c,t)}return n}const B2=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function Rm(e,t,r=new Set){const n=[],s=e.length;for(let i=0;i<s;i++){const o=e[i];if(Am.test(o.type))n.push(o);else{const c=_n(B2,o.type);if(!(c!=null&&c.type))throw new p2({abiParameter:o});const{array:f,type:u}=c;if(u in t){if(r.has(u))throw new g2({type:u});n.push({...o,type:`tuple${f??""}`,components:Rm(t[u]??[],t,new Set([...r,u]))})}else if(Bm(u))n.push(o);else throw new c2({type:u})}}return n}function $m(e){const t=Cm(e),r=[],n=e.length;for(let s=0;s<n;s++){const i=e[s];id(i)||r.push(tl(i,t))}return r}function Rh(e){let t;if(typeof e=="string")t=tl(e);else{const r=Cm(e),n=e.length;for(let s=0;s<n;s++){const i=e[s];if(!id(i)){t=tl(i,r);break}}}if(!t)throw new a2({signature:e});return t}function se(e,t,r){const n=e[t.name];if(typeof n=="function")return n;const s=e[r];return typeof s=="function"?s:i=>t(e,i)}function Sr(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new V2(e.type);return`${e.name}(${yc(e.inputs,{includeName:t})})`}function yc(e,{includeName:t=!1}={}){return e?e.map(r=>C2(r,{includeName:t})).join(t?", ":","):""}function C2(e,{includeName:t}){return e.type.startsWith("tuple")?`(${yc(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}function xr(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}function He(e){return xr(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}const Nm="2.31.7";let Li={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${Nm}`},H=class rl extends Error{constructor(t,r={}){var a;const n=(()=>{var c;return r.cause instanceof rl?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),s=r.cause instanceof rl&&r.cause.docsPath||r.docsPath,i=(a=Li.getDocsUrl)==null?void 0:a.call(Li,{...r,docsPath:s}),o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...Li.version?[`Version: ${Li.version}`]:[]].join(`
3
+ `);super(o,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=s,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=Nm}walk(t){return Mm(this,t)}};function Mm(e,t){return t!=null&&t(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?Mm(e.cause,t):t?null:e}class R2 extends H{constructor({docsPath:t}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
4
+ `),{docsPath:t,name:"AbiConstructorNotFoundError"})}}class $h extends H{constructor({docsPath:t}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
5
+ `),{docsPath:t,name:"AbiConstructorParamsNotFoundError"})}}class Um extends H{constructor({data:t,params:r,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join(`
6
+ `),{metaMessages:[`Params: (${yc(r,{includeName:!0})})`,`Data: ${t} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t,this.params=r,this.size=n}}class Jo extends H{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError"})}}class $2 extends H{constructor({expectedLength:t,givenLength:r,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${t}`,`Given length: ${r}`].join(`
7
+ `),{name:"AbiEncodingArrayLengthMismatchError"})}}class N2 extends H{constructor({expectedSize:t,value:r}){super(`Size of bytes "${r}" (bytes${He(r)}) does not match expected size (bytes${t}).`,{name:"AbiEncodingBytesSizeMismatchError"})}}class M2 extends H{constructor({expectedLength:t,givenLength:r}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${t}`,`Given length (values): ${r}`].join(`
8
+ `),{name:"AbiEncodingLengthMismatchError"})}}class U2 extends H{constructor(t,{docsPath:r}){super([`Arguments (\`args\`) were provided to "${t}", but "${t}" on the ABI does not contain any parameters (\`inputs\`).`,"Cannot encode error result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the inputs exist on it."].join(`
9
+ `),{docsPath:r,name:"AbiErrorInputsNotFoundError"})}}class Nh extends H{constructor(t,{docsPath:r}={}){super([`Error ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it."].join(`
10
+ `),{docsPath:r,name:"AbiErrorNotFoundError"})}}class Fm extends H{constructor(t,{docsPath:r}){super([`Encoded error signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${t}.`].join(`
11
+ `),{docsPath:r,name:"AbiErrorSignatureNotFoundError"}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=t}}class F2 extends H{constructor({docsPath:t}){super("Cannot extract event signature from empty topics.",{docsPath:t,name:"AbiEventSignatureEmptyTopicsError"})}}class jm extends H{constructor(t,{docsPath:r}){super([`Encoded event signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${t}.`].join(`
12
+ `),{docsPath:r,name:"AbiEventSignatureNotFoundError"})}}class Mh extends H{constructor(t,{docsPath:r}={}){super([`Event ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it."].join(`
13
+ `),{docsPath:r,name:"AbiEventNotFoundError"})}}class yi extends H{constructor(t,{docsPath:r}={}){super([`Function ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join(`
14
+ `),{docsPath:r,name:"AbiFunctionNotFoundError"})}}class Lm extends H{constructor(t,{docsPath:r}){super([`Function "${t}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join(`
15
+ `),{docsPath:r,name:"AbiFunctionOutputsNotFoundError"})}}class j2 extends H{constructor(t,{docsPath:r}){super([`Encoded function signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${t}.`].join(`
16
+ `),{docsPath:r,name:"AbiFunctionSignatureNotFoundError"})}}class L2 extends H{constructor(t,r){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${t.type}\` in \`${Sr(t.abiItem)}\`, and`,`\`${r.type}\` in \`${Sr(r.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}}let D2=class extends H{constructor({expectedSize:t,givenSize:r}){super(`Expected bytes${t}, got bytes${r}.`,{name:"BytesSizeMismatchError"})}};class bo extends H{constructor({abiItem:t,data:r,params:n,size:s}){super([`Data size of ${s} bytes is too small for non-indexed event parameters.`].join(`
17
+ `),{metaMessages:[`Params: (${yc(n,{includeName:!0})})`,`Data: ${r} (${s} bytes)`],name:"DecodeLogDataMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=t,this.data=r,this.params=n,this.size=s}}class mc extends H{constructor({abiItem:t,param:r}){super([`Expected a topic for indexed event parameter${r.name?` "${r.name}"`:""} on event "${Sr(t,{includeName:!0})}".`].join(`
18
+ `),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=t}}class H2 extends H{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid encoding type.`,"Please provide a valid ABI type."].join(`
19
+ `),{docsPath:r,name:"InvalidAbiEncodingType"})}}class z2 extends H{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(`
20
+ `),{docsPath:r,name:"InvalidAbiDecodingType"})}}let Dm=class extends H{constructor(t){super([`Value "${t}" is not a valid array.`].join(`
21
+ `),{name:"InvalidArrayError"})}};class V2 extends H{constructor(t){super([`"${t}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(`
22
+ `),{name:"InvalidDefinitionTypeError"})}}class q2 extends H{constructor(t){super(`Filter type "${t}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}let Hm=class extends H{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},zm=class extends H{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 Uh extends H{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 Bi(e,{dir:t,size:r=32}={}){return typeof e=="string"?Kn(e,{dir:t,size:r}):G2(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 zm({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function G2(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new zm({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 H{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 W2 extends H{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 K2 extends H{constructor(t){super(`Hex value "${t}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}let Y2=class extends H{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}};function ar(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let 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 Tr(e,{size:t}){if(He(e)>t)throw new Y2({givenSize:He(e),maxSize:t})}function ot(e,t={}){const{signed:r}=t;t.size&&Tr(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 X2(e,t={}){let r=e;if(t.size&&(Tr(r,{size:t.size}),r=ar(r)),ar(r)==="0x00")return!1;if(ar(r)==="0x01")return!0;throw new K2(r)}function cr(e,t={}){return Number(ot(e,t))}const Z2=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function mt(e,t={}){return typeof e=="number"||typeof e=="bigint"?Y(e,t):typeof e=="string"?mi(e,t):typeof e=="boolean"?qm(e,t):Je(e,t)}function qm(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?(Tr(r,{size:t.size}),Bi(r,{size:t.size})):r}function Je(e,t={}){let r="";for(let s=0;s<e.length;s++)r+=Z2[e[s]];const n=`0x${r}`;return typeof t.size=="number"?(Tr(n,{size:t.size}),Bi(n,{dir:"right",size:t.size})):n}function Y(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?Bi(a,{size:n}):a}const J2=new TextEncoder;function mi(e,t={}){const r=J2.encode(e);return Je(r,t)}const Q2=new TextEncoder;function Ci(e,t={}){return typeof e=="number"||typeof e=="bigint"?tv(e,t):typeof e=="boolean"?ev(e,t):xr(e)?Ar(e,t):ws(e,t)}function ev(e,t={}){const r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?(Tr(r,{size:t.size}),Bi(r,{size:t.size})):r}const Xr={zero:48,nine:57,A:65,F:70,a:97,f:102};function Fh(e){if(e>=Xr.zero&&e<=Xr.nine)return e-Xr.zero;if(e>=Xr.A&&e<=Xr.F)return e-(Xr.A-10);if(e>=Xr.a&&e<=Xr.f)return e-(Xr.a-10)}function Ar(e,t={}){let r=e;t.size&&(Tr(r,{size:t.size}),r=Bi(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=Fh(n.charCodeAt(a++)),f=Fh(n.charCodeAt(a++));if(c===void 0||f===void 0)throw new H(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);i[o]=c*16+f}return i}function tv(e,t){const r=Y(e,t);return Ar(r)}function ws(e,t={}){const r=Q2.encode(e);return typeof t.size=="number"?(Tr(r,{size:t.size}),Bi(r,{dir:"right",size:t.size})):r}const ga=BigInt(2**32-1),jh=BigInt(32);function Gm(e,t=!1){return t?{h:Number(e&ga),l:Number(e>>jh&ga)}:{h:Number(e>>jh&ga)|0,l:Number(e&ga)|0}}function rv(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}=Gm(e[i],t);[n[i],s[i]]=[o,a]}return[n,s]}const Wm=(e,t,r)=>e>>>r|t<<32-r,Km=(e,t,r)=>e<<32-r|t>>>r,nv=(e,t,r)=>e<<64-r|t>>>r-32,sv=(e,t,r)=>e>>>r-32|t<<64-r,iv=(e,t)=>t,ov=(e,t)=>e,av=(e,t,r)=>e<<r|t>>>32-r,cv=(e,t,r)=>t<<r|e>>>32-r,uv=(e,t,r)=>t<<r-32|e>>>64-r,fv=(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 Xm=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Zm=(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 od(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Jn(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ur(e,...t){if(!od(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 lv(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Jn(e.outputLen),Jn(e.blockLen)}function Qn(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 ad(e,t){ur(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function wo(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 au(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Br(e,t){return e<<32-t|e>>>t}function ba(e,t){return e<<t|e>>>32-t>>>0}const Jm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Qm(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const an=Jm?e=>e:e=>Qm(e);function dv(e){for(let t=0;t<e.length;t++)e[t]=Qm(e[t]);return e}const Hn=Jm?e=>e:dv,e0=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hv=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function vo(e){if(ur(e),e0)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=hv[e[r]];return t}const Zr={_0:48,_9:57,A:65,F:70,a:97,f:102};function Lh(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 cd(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(e0)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=Lh(e.charCodeAt(i)),a=Lh(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 pv(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=pv(e)),ur(e),e}function fs(...e){let t=0;for(let n=0;n<e.length;n++){const s=e[n];ur(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 gc{}function bc(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 yv(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 mv(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 gv=BigInt(0),Di=BigInt(1),bv=BigInt(2),wv=BigInt(7),vv=BigInt(256),Ev=BigInt(113),t0=[],r0=[],n0=[];for(let e=0,t=Di,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],t0.push(2*(5*n+r)),r0.push((e+1)*(e+2)/2%64);let s=gv;for(let i=0;i<7;i++)t=(t<<Di^(t>>wv)*Ev)%vv,t&bv&&(s^=Di<<(Di<<BigInt(i))-Di);n0.push(s)}const s0=rv(n0,!0),Sv=s0[0],xv=s0[1],Dh=(e,t,r)=>r>32?uv(e,t,r):av(e,t,r),Hh=(e,t,r)=>r>32?fv(e,t,r):cv(e,t,r);function Av(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,f=r[c],u=r[c+1],l=Dh(f,u,1)^r[a],p=Hh(f,u,1)^r[a+1];for(let d=0;d<50;d+=10)e[o+d]^=l,e[o+d+1]^=p}let s=e[2],i=e[3];for(let o=0;o<24;o++){const a=r0[o],c=Dh(s,i,a),f=Hh(s,i,a),u=t0[o];s=e[u],i=e[u+1],e[u]=c,e[u+1]=f}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]^=Sv[n],e[1]^=xv[n]}_r(r)}class ud extends gc{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,Jn(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=wo(this.state)}clone(){return this._cloneInto()}keccak(){Hn(this.state32),Av(this.state32,this.rounds),Hn(this.state32),this.posOut=0,this.pos=0}update(t){Qn(this),t=mn(t),ur(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){Qn(this,!1),ur(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 Jn(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(ad(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 ud(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 _v=(e,t,r)=>bc(()=>new ud(t,e,r)),i0=_v(1,136,256/8);function ft(e,t){const r=t||"hex",n=i0(xr(e,{strict:!1})?Ci(e):e);return r==="bytes"?n:mt(n)}const Tv=e=>ft(Ci(e));function kv(e){return Tv(e)}function Iv(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 H("Unable to normalize signature.");return s}const Pv=e=>{const t=typeof e=="string"?e:tc(e);return Iv(t)};function o0(e){return kv(Pv(e))}const wc=o0;let Ot=class extends H{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"})}},vc=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 cu=new vc(8192);function Qo(e,t){if(cu.has(`${e}.${t}`))return cu.get(`${e}.${t}`);const r=e.substring(2).toLowerCase(),n=ft(ws(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 cu.set(`${e}.${t}`,i),i}function a0(e,t){if(!st(e,{strict:!1}))throw new Ot({address:e});return Qo(e,t)}const Ov=/^0x[a-fA-F0-9]{40}$/,uu=new vc(8192);function st(e,t){const{strict:r=!0}=t??{},n=`${e}.${r}`;if(uu.has(n))return uu.get(n);const s=Ov.test(e)?e.toLowerCase()===e?!0:r?Qo(e)===e:!0:!1;return uu.set(n,s),s}function qt(e){return typeof e[0]=="string"?kr(e):Bv(e)}function Bv(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 kr(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function Ts(e,t,r,{strict:n}={}){return xr(e,{strict:!1})?rc(e,t,r,{strict:n}):f0(e,t,r,{strict:n})}function c0(e,t){if(typeof t=="number"&&t>0&&t>He(e)-1)throw new Hm({offset:t,position:"start",size:He(e)})}function u0(e,t,r){if(typeof t=="number"&&typeof r=="number"&&He(e)!==r-t)throw new Hm({offset:r,position:"end",size:He(e)})}function f0(e,t,r,{strict:n}={}){c0(e,t);const s=e.slice(t,r);return n&&u0(s,t,r),s}function rc(e,t,r,{strict:n}={}){c0(e,t);const s=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return n&&u0(s,t,r),s}const Cv=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,l0=/^(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 Tn(e,t){if(e.length!==t.length)throw new M2({expectedLength:e.length,givenLength:t.length});const r=Rv({params:e,values:t}),n=ld(r);return n.length===0?"0x":n}function Rv({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=dd(e.type);if(r){const[n,s]=r;return Nv(t,{length:n,param:{...e,type:s}})}if(e.type==="tuple")return Lv(t,{param:e});if(e.type==="address")return $v(t);if(e.type==="bool")return Uv(t);if(e.type.startsWith("uint")||e.type.startsWith("int")){const n=e.type.startsWith("int"),[,,s="256"]=l0.exec(e.type)??[];return Fv(t,{signed:n,size:Number(s)})}if(e.type.startsWith("bytes"))return Mv(t,{param:e});if(e.type==="string")return jv(t);throw new H2(e.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function ld(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(Y(t+s,{size:32})),n.push(a),s+=He(a)):r.push(a)}return qt([...r,...n])}function $v(e){if(!st(e))throw new Ot({address:e});return{dynamic:!1,encoded:Kn(e.toLowerCase())}}function Nv(e,{length:t,param:r}){const n=t===null;if(!Array.isArray(e))throw new Dm(e);if(!n&&e.length!==t)throw new $2({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=ld(i);if(n){const a=Y(i.length,{size:32});return{dynamic:!0,encoded:i.length>0?qt([a,o]):a}}if(s)return{dynamic:!0,encoded:o}}return{dynamic:!1,encoded:qt(i.map(({encoded:o})=>o))}}function Mv(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:qt([Kn(Y(n,{size:32})),s])}}if(n!==Number.parseInt(r))throw new N2({expectedSize:Number.parseInt(r),value:e});return{dynamic:!1,encoded:Kn(e,{dir:"right"})}}function Uv(e){if(typeof e!="boolean")throw new H(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Kn(qm(e))}}function Fv(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:Y(e,{size:32,signed:t})}}function jv(e){const t=mi(e),r=Math.ceil(He(t)/32),n=[];for(let s=0;s<r;s++)n.push(Kn(Ts(t,s*32,(s+1)*32),{dir:"right"}));return{dynamic:!0,encoded:qt([Kn(Y(He(t),{size:32})),...n])}}function Lv(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?ld(n):qt(n.map(({encoded:s})=>s))}}function dd(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}const ea=e=>Ts(o0(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"?ea(a)===n:a.type==="event"?wc(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((f,u)=>{const l="inputs"in a&&a.inputs[u];return l?nl(f,l):!1})){if(o&&"inputs"in o&&o.inputs){const f=d0(a.inputs,o.inputs,r);if(f)throw new L2({abiItem:a,type:f[0]},{abiItem:o,type:f[1]})}o=a}}return o||i[0]}function nl(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)=>nl(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=>nl(s,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function d0(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 d0(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 zh="/docs/contract/encodeEventTopics";function ta(e){var c;const{abi:t,eventName:r,args:n}=e;let s=t[0];if(r){const f=Fs({abi:t,name:r});if(!f)throw new Mh(r,{docsPath:zh});s=f}if(s.type!=="event")throw new Mh(void 0,{docsPath:zh});const i=Sr(s),o=wc(i);let a=[];if(n&&"inputs"in s){const f=(c=s.inputs)==null?void 0:c.filter(l=>"indexed"in l&&l.indexed),u=Array.isArray(n)?n:Object.values(n).length>0?(f==null?void 0:f.map(l=>n[l.name]))??[]:[];u.length>0&&(a=(f==null?void 0:f.map((l,p)=>Array.isArray(u[p])?u[p].map((d,m)=>Vh({param:l,value:u[p][m]})):typeof u[p]<"u"&&u[p]!==null?Vh({param:l,value:u[p]}):null))??[])}return[o,...a]}function Vh({param:e,value:t}){if(e.type==="string"||e.type==="bytes")return ft(Ci(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new q2(e.type);return Tn([e],[t])}function Ec(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 hd(e,t){const{address:r,abi:n,args:s,eventName:i,fromBlock:o,strict:a,toBlock:c}=t,f=Ec(e,{method:"eth_newFilter"}),u=i?ta({abi:n,args:s,eventName:i}):void 0,l=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof o=="bigint"?Y(o):o,toBlock:typeof c=="bigint"?Y(c):c,topics:u}]});return{abi:n,args:s,eventName:i,id:l,request:f(l),strict:!!a,type:"event"}}function Ye(e){return typeof e=="string"?{address:e,type:"json-rpc"}:e}const qh="/docs/contract/encodeFunctionData";function Dv(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:qh});s=i}if(s.type!=="function")throw new yi(void 0,{docsPath:qh});return{abi:[s],functionName:ea(Sr(s))}}function lr(e){const{args:t}=e,{abi:r,functionName:n}=(()=>{var a;return e.abi.length===1&&((a=e.functionName)!=null&&a.startsWith("0x"))?e:Dv(e)})(),s=r[0],i=n,o="inputs"in s&&s.inputs?Tn(s.inputs,t??[]):void 0;return kr([i,o??"0x"])}const h0={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."},p0={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},Hv={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};class Gh extends H{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class y0 extends H{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}}class zv extends H{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}}const Vv={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 zv({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new y0({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new Gh({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 Gh({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 pd(e,{recursiveReadLimit:t=8192}={}){const r=Object.create(Vv);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}function qv(e,t={}){typeof t.size<"u"&&Tr(e,{size:t.size});const r=Je(e,t);return ot(r,t)}function Gv(e,t={}){let r=e;if(typeof t.size<"u"&&(Tr(r,{size:t.size}),r=ar(r)),r.length>1||r[0]>1)throw new W2(r);return!!r[0]}function gn(e,t={}){typeof t.size<"u"&&Tr(e,{size:t.size});const r=Je(e,t);return cr(r,t)}function Wv(e,t={}){let r=e;return typeof t.size<"u"&&(Tr(r,{size:t.size}),r=ar(r,{dir:"right"})),new TextDecoder().decode(r)}function ra(e,t){const r=typeof t=="string"?Ar(t):t,n=pd(r);if(He(r)===0&&e.length>0)throw new Jo;if(He(t)&&He(t)<32)throw new Um({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,f]=ai(n,a,{staticPosition:0});s+=f,i.push(c)}return i}function ai(e,t,{staticPosition:r}){const n=dd(t.type);if(n){const[s,i]=n;return Yv(e,{...t,type:i},{length:s,staticPosition:r})}if(t.type==="tuple")return Qv(e,t,{staticPosition:r});if(t.type==="address")return Kv(e);if(t.type==="bool")return Xv(e);if(t.type.startsWith("bytes"))return Zv(e,t,{staticPosition:r});if(t.type.startsWith("uint")||t.type.startsWith("int"))return Jv(e,t);if(t.type==="string")return eE(e,{staticPosition:r});throw new z2(t.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const Wh=32,sl=32;function Kv(e){const t=e.readBytes(32);return[Qo(Je(f0(t,-20))),32]}function Yv(e,t,{length:r,staticPosition:n}){if(!r){const o=gn(e.readBytes(sl)),a=n+o,c=a+Wh;e.setPosition(a);const f=gn(e.readBytes(Wh)),u=Eo(t);let l=0;const p=[];for(let d=0;d<f;++d){e.setPosition(c+(u?d*32:l));const[m,g]=ai(e,t,{staticPosition:c});l+=g,p.push(m)}return e.setPosition(n+32),[p,32]}if(Eo(t)){const o=gn(e.readBytes(sl)),a=n+o,c=[];for(let f=0;f<r;++f){e.setPosition(a+f*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 Xv(e){return[Gv(e.readBytes(32),{size:32}),32]}function Zv(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 Jv(e,t){const r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256"),s=e.readBytes(32);return[n>48?qv(s,{signed:r}):gn(s,{signed:r}),32]}function Qv(e,t,{staticPosition:r}){const n=t.components.length===0||t.components.some(({name:o})=>!o),s=n?[]:{};let i=0;if(Eo(t)){const o=gn(e.readBytes(sl)),a=r+o;for(let c=0;c<t.components.length;++c){const f=t.components[c];e.setPosition(a+i);const[u,l]=ai(e,f,{staticPosition:a});i+=l,s[n?c:f==null?void 0:f.name]=u}return e.setPosition(r+32),[s,32]}for(let o=0;o<t.components.length;++o){const a=t.components[o],[c,f]=ai(e,a,{staticPosition:r});s[n?o:a==null?void 0:a.name]=c,i+=f}return[s,i]}function eE(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=Wv(ar(i));return e.setPosition(t+32),[o,32]}function Eo(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(Eo);const r=dd(e.type);return!!(r&&Eo({...e,type:r[1]}))}function m0(e){const{abi:t,data:r}=e,n=Ts(r,0,4);if(n==="0x")throw new Jo;const i=[...t||[],p0,Hv].find(o=>o.type==="error"&&n===ea(Sr(o)));if(!i)throw new Fm(n,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:i,args:"inputs"in i&&i.inputs&&i.inputs.length>0?ra(i.inputs,Ts(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 g0({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 tE={gwei:9,wei:18},rE={ether:-9,wei:9};function b0(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 yd(e,t="wei"){return b0(e,tE[t])}function Nt(e,t="wei"){return b0(e,rE[t])}class nE extends H{constructor({address:t}){super(`State for account "${t}" is set multiple times.`,{name:"AccountStateConflictError"})}}class sE extends H{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function Kh(e){return e.reduce((t,{slot:r,value:n})=>`${t} ${r}: ${n}
23
+ `,"")}function iE(e){return e.reduce((t,{address:r,...n})=>{let s=`${t} ${r}:
24
+ `;return n.nonce&&(s+=` nonce: ${n.nonce}
25
+ `),n.balance&&(s+=` balance: ${n.balance}
26
+ `),n.code&&(s+=` code: ${n.code}
27
+ `),n.state&&(s+=` state:
28
+ `,s+=Kh(n.state)),n.stateDiff&&(s+=` stateDiff:
29
+ `,s+=Kh(n.stateDiff)),s},` State Override:
30
+ `).slice(0,-1)}function na(e){const t=Object.entries(e).map(([n,s])=>s===void 0||s===!1?null:[n,s]).filter(Boolean),r=t.reduce((n,[s])=>Math.max(n,s.length),0);return t.map(([n,s])=>` ${`${n}:`.padEnd(r+1)} ${s}`).join(`
31
+ `)}class oE extends H{constructor(){super(["Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.","Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others."].join(`
32
+ `),{name:"FeeConflictError"})}}class aE extends H{constructor({v:t}){super(`Invalid \`v\` value "${t}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class cE extends H{constructor({transaction:t}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",na(t),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class uE extends H{constructor({storageKey:t}){super(`Size for storage key "${t}" is invalid. Expected 32 bytes. Got ${Math.floor((t.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}class fE extends H{constructor(t,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:f,nonce:u,to:l,value:p}){var m;const d=na({chain:s&&`${s==null?void 0:s.name} (id: ${s==null?void 0:s.id})`,from:r==null?void 0:r.address,to:l,value:typeof p<"u"&&`${yd(p)} ${((m=s==null?void 0:s.nativeCurrency)==null?void 0:m.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${Nt(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Nt(c)} gwei`,maxPriorityFeePerGas:typeof f<"u"&&`${Nt(f)} gwei`,nonce:u});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Request Arguments:",d].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}class w0 extends H{constructor({blockHash:t,blockNumber:r,blockTag:n,hash:s,index:i}){let o="Transaction";n&&i!==void 0&&(o=`Transaction at block time "${n}" at index "${i}"`),t&&i!==void 0&&(o=`Transaction at block hash "${t}" at index "${i}"`),r&&i!==void 0&&(o=`Transaction at block number "${r}" at index "${i}"`),s&&(o=`Transaction with hash "${s}"`),super(`${o} could not be found.`,{name:"TransactionNotFoundError"})}}class v0 extends H{constructor({hash:t}){super(`Transaction receipt with hash "${t}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class lE extends H{constructor({hash:t}){super(`Timed out while waiting for transaction with hash "${t}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}const dE=e=>e,Sc=e=>e;class E0 extends H{constructor(t,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:f,nonce:u,to:l,value:p,stateOverride:d}){var w;const m=r?Ye(r):void 0;let g=na({from:m==null?void 0:m.address,to:l,value:typeof p<"u"&&`${yd(p)} ${((w=s==null?void 0:s.nativeCurrency)==null?void 0:w.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${Nt(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Nt(c)} gwei`,maxPriorityFeePerGas:typeof f<"u"&&`${Nt(f)} gwei`,nonce:u});d&&(g+=`
33
+ ${iE(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 hE extends H{constructor(t,{abi:r,args:n,contractAddress:s,docsPath:i,functionName:o,sender:a}){const c=Fs({abi:r,args:n,name:o}),f=c?g0({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,u=c?Sr(c,{includeName:!0}):void 0,l=na({address:s&&dE(s),function:u,args:f&&f!=="()"&&`${[...Array((o==null?void 0:o.length)??0).keys()].map(()=>" ").join("")}${f}`,sender:a});super(t.shortMessage||`An unknown error occurred while executing the contract function "${o}".`,{cause:t,docsPath:i,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],l&&"Contract Call:",l].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=r,this.args=n,this.cause=t,this.contractAddress=s,this.functionName=o,this.sender=a}}class il extends H{constructor({abi:t,data:r,functionName:n,message:s}){let i,o,a,c;if(r&&r!=="0x")try{o=m0({abi:t,data:r});const{abiItem:u,errorName:l,args:p}=o;if(l==="Error")c=p[0];else if(l==="Panic"){const[d]=p;c=h0[d]}else{const d=u?Sr(u,{includeName:!0}):void 0,m=u&&p?g0({abiItem:u,args:p,includeFunctionName:!1,includeName:!1}):void 0;a=[d?`Error: ${d}`:"",m&&m!=="()"?` ${[...Array((l==null?void 0:l.length)??0).keys()].map(()=>" ").join("")}${m}`:""]}}catch(u){i=u}else s&&(c=s);let f;i instanceof Fm&&(f=i.signature,a=[`Unable to decode signature "${f}" 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=${f}.`]),super(c&&c!=="execution reverted"||f?[`The contract function "${n}" reverted with the following ${f?"signature":"reason"}:`,c||f].join(`
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=f}}class pE extends H{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 yE extends H{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 xc extends H{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 H{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: ${Sc(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 md extends H{constructor({body:t,error:r,url:n}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[`URL: ${Sc(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 H{constructor({body:t,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${Sc(r)}`,`Request body: ${Ze(t)}`],name:"TimeoutError"})}}const mE=-1;class Ut extends H{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 md?t.code:r??mE}}class Yt extends Ut{constructor(t,r){super(t,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}}class So extends Ut{constructor(t){super(t,{code:So.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(So,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class xo extends Ut{constructor(t){super(t,{code:xo.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(xo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class Ao extends Ut{constructor(t,{method:r}={}){super(t,{code:Ao.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}}Object.defineProperty(Ao,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class _o extends Ut{constructor(t){super(t,{code:_o.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
35
+ `)})}}Object.defineProperty(_o,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class ks extends Ut{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 Is extends Ut{constructor(t){super(t,{code:Is.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
36
+ `)})}}Object.defineProperty(Is,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class To extends Ut{constructor(t){super(t,{code:To.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(To,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class ko extends Ut{constructor(t){super(t,{code:ko.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(ko,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class Io extends Ut{constructor(t){super(t,{code:Io.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(Io,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class ls extends Ut{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 Ut{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 Po extends Ut{constructor(t){super(t,{code:Po.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(Po,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class ui extends Yt{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 Oo extends Yt{constructor(t){super(t,{code:Oo.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(Oo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class Bo extends Yt{constructor(t,{method:r}={}){super(t,{code:Bo.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}}Object.defineProperty(Bo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Co extends Yt{constructor(t){super(t,{code:Co.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Co,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class Ro extends Yt{constructor(t){super(t,{code:Ro.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Ro,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class $o extends Yt{constructor(t){super(t,{code:$o.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty($o,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class bi extends Yt{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 No extends Yt{constructor(t){super(t,{code:No.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(No,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class Mo extends Yt{constructor(t){super(t,{code:Mo.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(Mo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class Uo extends Yt{constructor(t){super(t,{code:Uo.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(Uo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class Fo extends Yt{constructor(t){super(t,{code:Fo.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(Fo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class jo extends Yt{constructor(t){super(t,{code:jo.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(jo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class wi extends Yt{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 gE extends Ut{constructor(t){super(t,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const bE=3;function Ps(e,{abi:t,address:r,args:n,docsPath:s,functionName:i,sender:o}){const a=e instanceof xc?e:e instanceof H?e.walk(m=>"data"in m)||e.walk():{},{code:c,data:f,details:u,message:l,shortMessage:p}=a,d=e instanceof Jo?new pE({functionName:i}):[bE,ks.code].includes(c)&&(f||u||l||p)?new il({abi:t,data:typeof f=="object"?f.data:f,functionName:i,message:a instanceof md?u:p??l}):e;return new hE(d,{abi:t,args:n,contractAddress:r,docsPath:s,functionName:i,sender:o})}function wE(e){const t=ft(`0x${e.substring(4)}`).substring(26);return Qo(`0x${t}`)}async function vE({hash:e,signature:t}){const r=xr(e)?e:mt(e),{secp256k1:n}=await Promise.resolve().then(()=>vA);return`0x${(()=>{if(typeof t=="object"&&"r"in t&&"s"in t){const{r:f,s:u,v:l,yParity:p}=t,d=Number(p??l),m=Xh(d);return new n.Signature(ot(f),ot(u)).addRecoveryBit(m)}const o=xr(t)?t:mt(t);if(He(o)!==65)throw new Error("invalid signature length");const a=cr(`0x${o.slice(130)}`),c=Xh(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Xh(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 S0({hash:e,signature:t}){return wE(await vE({hash:e,signature:t}))}function es(e,t="hex"){const r=x0(e),n=pd(new Uint8Array(r.length));return r.encode(n),t==="hex"?Je(n.bytes):n.bytes}function x0(e){return Array.isArray(e)?EE(e.map(t=>x0(t))):SE(e)}function EE(e){const t=e.reduce((s,i)=>s+i.length,0),r=A0(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 SE(e){const t=typeof e=="string"?Ar(e):e,r=A0(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 A0(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 H("Length is too large.")}function xE(e){const{chainId:t,nonce:r,to:n}=e,s=e.contractAddress??e.address,i=ft(kr(["0x05",es([t?Y(t):"0x",s,r?Y(r):"0x"])]));return n==="bytes"?Ar(i):i}async function _0(e){const{authorization:t,signature:r}=e;return S0({hash:xE(t),signature:r??t})}class AE extends H{constructor(t,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:f,nonce:u,to:l,value:p}){var m;const d=na({from:r==null?void 0:r.address,to:l,value:typeof p<"u"&&`${yd(p)} ${((m=s==null?void 0:s.nativeCurrency)==null?void 0:m.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${Nt(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Nt(c)} gwei`,maxPriorityFeePerGas:typeof f<"u"&&`${Nt(f)} 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 H{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 Os extends H{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Nt(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}}Object.defineProperty(Os,"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 ol extends H{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Nt(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:t,name:"FeeCapTooLowError"})}}Object.defineProperty(ol,"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 al extends H{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(al,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class cl extends H{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
+ `),{cause:t,name:"NonceTooLowError"})}}Object.defineProperty(cl,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class ul extends H{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:t,name:"NonceMaxValueError"})}}Object.defineProperty(ul,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class fl extends H{constructor({cause:t}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
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(fl,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class ll extends H{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(ll,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class dl extends H{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(dl,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class hl extends H{constructor({cause:t}){super("The transaction type is not supported for this chain.",{cause:t,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(hl,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class Lo extends H{constructor({cause:t,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${Nt(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${Nt(n)} gwei`:""}).`].join(`
39
+ `),{cause:t,name:"TipAboveFeeCapError"})}}Object.defineProperty(Lo,"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 sa extends H{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 H?e.walk(s=>(s==null?void 0:s.code)===ii.code):e;return n instanceof H?new ii({cause:e,message:n.details}):ii.nodeMessage.test(r)?new ii({cause:e,message:e.details}):Os.nodeMessage.test(r)?new Os({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):ol.nodeMessage.test(r)?new ol({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):al.nodeMessage.test(r)?new al({cause:e,nonce:t==null?void 0:t.nonce}):cl.nodeMessage.test(r)?new cl({cause:e,nonce:t==null?void 0:t.nonce}):ul.nodeMessage.test(r)?new ul({cause:e,nonce:t==null?void 0:t.nonce}):fl.nodeMessage.test(r)?new fl({cause:e}):ll.nodeMessage.test(r)?new ll({cause:e,gas:t==null?void 0:t.gas}):dl.nodeMessage.test(r)?new dl({cause:e,gas:t==null?void 0:t.gas}):hl.nodeMessage.test(r)?new hl({cause:e}):Lo.nodeMessage.test(r)?new Lo({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas,maxPriorityFeePerGas:t==null?void 0:t.maxPriorityFeePerGas}):new sa({cause:e})}function _E(e,{docsPath:t,...r}){const n=(()=>{const s=Ac(e,r);return s instanceof sa?e:s})();return new AE(n,{docsPath:t,...r})}function _c(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 gd(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 TE={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function Ri(e){const t={};return typeof e.authorizationList<"u"&&(t.authorizationList=kE(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=Y(e.gas)),typeof e.gasPrice<"u"&&(t.gasPrice=Y(e.gasPrice)),typeof e.maxFeePerBlobGas<"u"&&(t.maxFeePerBlobGas=Y(e.maxFeePerBlobGas)),typeof e.maxFeePerGas<"u"&&(t.maxFeePerGas=Y(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(t.maxPriorityFeePerGas=Y(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(t.nonce=Y(e.nonce)),typeof e.to<"u"&&(t.to=e.to),typeof e.type<"u"&&(t.type=TE[e.type]),typeof e.value<"u"&&(t.value=Y(e.value)),t}function kE(e){return e.map(t=>({address:t.address,r:t.r?Y(BigInt(t.r)):t.r,s:t.s?Y(BigInt(t.s)):t.s,chainId:Y(t.chainId),nonce:Y(t.nonce),...typeof t.yParity<"u"?{yParity:Y(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:Y(t.v)}:{}}))}function Zh(e){if(!(!e||e.length===0))return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new Uh({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new Uh({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function IE(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=Y(t)),r!==void 0&&(o.nonce=Y(r)),n!==void 0&&(o.state=Zh(n)),s!==void 0){if(o.state)throw new sE;o.stateDiff=Zh(s)}return o}function bd(e){if(!e)return;const t={};for(const{address:r,...n}of e){if(!st(r,{strict:!1}))throw new Ot({address:r});if(t[r])throw new nE({address:r});t[r]=IE(n)}return t}const Tc=2n**256n-1n;function js(e){const{account:t,gasPrice:r,maxFeePerGas:n,maxPriorityFeePerGas:s,to:i}=e,o=t?Ye(t):void 0;if(o&&!st(o.address))throw new Ot({address:o.address});if(i&&!st(i))throw new Ot({address:i});if(typeof r<"u"&&(typeof n<"u"||typeof s<"u"))throw new oE;if(n&&n>Tc)throw new Os({maxFeePerGas:n});if(s&&n&&s>n)throw new Lo({maxFeePerGas:n,maxPriorityFeePerGas:s})}class PE extends H{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class wd extends H{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class OE extends H{constructor({maxPriorityFeePerGas:t}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${Nt(t)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class T0 extends H{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 k0={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function kc(e){const t={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?cr(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?cr(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?k0[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=CE(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 BE=gd("transaction",kc);function CE(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 vd(e){const t=(e.transactions??[]).map(r=>typeof r=="string"?r:kc(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 RE=gd("block",vd);async function Vr(e,{blockHash:t,blockNumber:r,blockTag:n,includeTransactions:s}={}){var u,l,p;const i=n??"latest",o=s??!1,a=r!==void 0?Y(r):void 0;let c=null;if(t?c=await e.request({method:"eth_getBlockByHash",params:[t,o]},{dedupe:!0}):c=await e.request({method:"eth_getBlockByNumber",params:[a||i,o]},{dedupe:!!a}),!c)throw new T0({blockHash:t,blockNumber:r});return(((p=(l=(u=e.chain)==null?void 0:u.formatters)==null?void 0:l.block)==null?void 0:p.format)||vd)(c)}async function Ed(e){const t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function $E(e,t){return I0(e,t)}async function I0(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 f=r||await se(e,Vr,"getBlock")({}),u=await a({block:f,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,Vr,"getBlock")({}),se(e,Ed,"getGasPrice")({})]);if(typeof a.baseFeePerGas!="bigint")throw new wd;const f=c-a.baseFeePerGas;return f<0n?0n:f}}async function NE(e,t){return pl(e,t)}async function pl(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 PE;const c=10**(((p=o.toString().split(".")[1])==null?void 0:p.length)??0),f=m=>m*BigInt(Math.ceil(o*c))/BigInt(c),u=r||await se(e,Vr,"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:f,request:s,type:i});if(m!==null)return m}if(i==="eip1559"){if(typeof u.baseFeePerGas!="bigint")throw new wd;const m=typeof(s==null?void 0:s.maxPriorityFeePerGas)=="bigint"?s.maxPriorityFeePerGas:await I0(e,{block:u,chain:n,request:s}),g=f(u.baseFeePerGas);return{maxFeePerGas:(s==null?void 0:s.maxFeePerGas)??g+m,maxPriorityFeePerGas:m}}return{gasPrice:(s==null?void 0:s.gasPrice)??f(await se(e,Ed,"getGasPrice")({}))}}async function Sd(e,{address:t,blockTag:r="latest",blockNumber:n}){const s=await e.request({method:"eth_getTransactionCount",params:[t,typeof n=="bigint"?Y(n):r]},{dedupe:!!n});return cr(s)}function xd(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=>Ar(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 Ad(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=>Ar(o)):e.blobs,s=typeof e.commitments[0]=="string"?e.commitments.map(o=>Ar(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 ME(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,f=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+f,a,n)}function UE(e,t,r){return e&t^~e&r}function FE(e,t,r){return e&t^e&r^t&r}let P0=class extends gc{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=au(this.buffer)}update(t){Qn(this),t=mn(t),ur(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=au(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){Qn(this),ad(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 l=o;l<s;l++)r[l]=0;ME(n,s-8,BigInt(this.length*8),i),this.process(n,0);const a=au(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<f;l++)a.setUint32(4*l,u[l],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]),jE=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 _d=class extends P0{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 l=0;l<16;l++,r+=4)Bn[l]=t.getUint32(r,!1);for(let l=16;l<64;l++){const p=Bn[l-15],d=Bn[l-2],m=Br(p,7)^Br(p,18)^p>>>3,g=Br(d,17)^Br(d,19)^d>>>10;Bn[l]=g+Bn[l-7]+m+Bn[l-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:f,H:u}=this;for(let l=0;l<64;l++){const p=Br(a,6)^Br(a,11)^Br(a,25),d=u+p+UE(a,c,f)+jE[l]+Bn[l]|0,g=(Br(n,2)^Br(n,13)^Br(n,22))+FE(n,s,i)|0;u=f,f=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,f=f+this.G|0,u=u+this.H|0,this.set(n,s,i,o,a,c,f,u)}roundClean(){_r(Bn)}destroy(){this.set(0,0,0,0,0,0,0,0),_r(this.buffer)}},O0=class extends _d{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 B0=bc(()=>new _d),LE=bc(()=>new O0),DE=_d,C0=B0,HE=O0,zE=LE,VE=Object.freeze(Object.defineProperty({__proto__:null,SHA224:HE,SHA256:DE,sha224:zE,sha256:C0},Symbol.toStringTag,{value:"Module"}));function Ji(e,t){const r=t||"hex",n=C0(xr(e,{strict:!1})?Ci(e):e);return r==="bytes"?n:mt(n)}function qE(e){const{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),s=Ji(t,"bytes");return s.set([r],0),n==="bytes"?s:Je(s)}function R0(e){const{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),s=[];for(const i of t)s.push(qE({commitment:i,to:n,version:r}));return s}const Jh=6,$0=32,Td=4096,N0=$0*Td,Qh=N0*Jh-1-1*Td*Jh,M0=1;class GE extends H{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class U0 extends H{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class WE extends H{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class KE extends H{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${M0}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function YE(e){const t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?Ar(e.data):e.data,n=He(r);if(!n)throw new U0;if(n>Qh)throw new GE({maxSize:Qh,size:n});const s=[];let i=!0,o=0;for(;i;){const a=pd(new Uint8Array(N0));let c=0;for(;c<Td;){const f=r.slice(o,o+($0-1));if(a.pushByte(0),a.pushBytes(f),f.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 F0(e){const{data:t,kzg:r,to:n}=e,s=e.blobs??YE({data:t,to:n}),i=e.commitments??xd({blobs:s,kzg:r,to:n}),o=e.proofs??Ad({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 j0(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 cE({transaction:e})}async function $i(e){const t=await e.request({method:"eth_chainId"},{dedupe:!0});return cr(t)}const L0=["blobVersionedHashes","chainId","fees","gas","nonce","type"],ep=new Map;async function Ic(e,t){const{account:r=e.account,blobs:n,chain:s,gas:i,kzg:o,nonce:a,nonceManager:c,parameters:f=L0,type:u}=t,l=r&&Ye(r),p={...t,...l?{from:l==null?void 0:l.address}:{}};let d;async function m(){return d||(d=await se(e,Vr,"getBlock")({blockTag:"latest"}),d)}let g;async function w(){return g||(s?s.id:typeof t.chainId<"u"?t.chainId:(g=await se(e,$i,"getChainId")({}),g))}if(f.includes("nonce")&&typeof a>"u"&&l)if(c){const S=await w();p.nonce=await c.consume({address:l.address,chainId:S,client:e})}else p.nonce=await se(e,Sd,"getTransactionCount")({address:l.address,blockTag:"pending"});if((f.includes("blobVersionedHashes")||f.includes("sidecars"))&&n&&o){const S=xd({blobs:n,kzg:o});if(f.includes("blobVersionedHashes")){const k=R0({commitments:S,to:"hex"});p.blobVersionedHashes=k}if(f.includes("sidecars")){const k=Ad({blobs:n,commitments:S,kzg:o}),E=F0({blobs:n,commitments:S,proofs:k,to:"hex"});p.sidecars=E}}if(f.includes("chainId")&&(p.chainId=await w()),(f.includes("fees")||f.includes("type"))&&typeof u>"u")try{p.type=j0(p)}catch{let S=ep.get(e.uid);if(typeof S>"u"){const k=await m();S=typeof(k==null?void 0:k.baseFeePerGas)=="bigint",ep.set(e.uid,S)}p.type=S?"eip1559":"legacy"}if(f.includes("fees"))if(p.type!=="legacy"&&p.type!=="eip2930"){if(typeof p.maxFeePerGas>"u"||typeof p.maxPriorityFeePerGas>"u"){const S=await m(),{maxFeePerGas:k,maxPriorityFeePerGas:E}=await pl(e,{block:S,chain:s,request:p});if(typeof t.maxPriorityFeePerGas>"u"&&t.maxFeePerGas&&t.maxFeePerGas<E)throw new OE({maxPriorityFeePerGas:E});p.maxPriorityFeePerGas=E,p.maxFeePerGas=k}}else{if(typeof t.maxFeePerGas<"u"||typeof t.maxPriorityFeePerGas<"u")throw new wd;if(typeof t.gasPrice>"u"){const S=await m(),{gasPrice:k}=await pl(e,{block:S,chain:s,request:p,type:"legacy"});p.gasPrice=k}}return f.includes("gas")&&typeof i>"u"&&(p.gas=await se(e,kd,"estimateGas")({...p,account:l&&{address:l.address,type:"json-rpc"}})),js(p),delete p.parameters,p}async function D0(e,{address:t,blockNumber:r,blockTag:n="latest"}){const s=typeof r=="bigint"?Y(r):void 0,i=await e.request({method:"eth_getBalance",params:[t,s||n]});return BigInt(i)}async function kd(e,t){var s,i,o;const{account:r=e.account}=t,n=r?Ye(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??"latest",B]:re?[D,re]:[D]})};const{accessList:a,authorizationList:c,blobs:f,blobVersionedHashes:u,blockNumber:l,blockTag:p,data:d,gas:m,gasPrice:g,maxFeePerBlobGas:w,maxFeePerGas:S,maxPriorityFeePerGas:k,nonce:E,value:A,stateOverride:I,...P}=await Ic(e,{...t,parameters:(n==null?void 0:n.type)==="local"?void 0:["blobVersionedHashes"]}),L=(typeof l=="bigint"?Y(l):void 0)||p,T=bd(I),U=await(async()=>{if(P.to)return P.to;if(c&&c.length>0)return await _0({authorization:c[0]}).catch(()=>{throw new H("`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,z=(R||Ri)({..._c(P,{format:R}),from:n==null?void 0:n.address,accessList:a,authorizationList:c,blobs:f,blobVersionedHashes:u,data:d,gas:m,gasPrice:g,maxFeePerBlobGas:w,maxFeePerGas:S,maxPriorityFeePerGas:k,nonce:E,to:U,value:A});let Z=BigInt(await W({block:L,request:z,rpcStateOverride:T}));if(c){const Q=await D0(e,{address:z.from}),re=await Promise.all(c.map(async D=>{const{address:B}=D,q=await W({block:L,request:{authorizationList:void 0,data:d,from:n==null?void 0:n.address,to:B,value:Y(Q)},rpcStateOverride:T}).catch(()=>100000n);return 2n*BigInt(q)}));Z+=re.reduce((D,B)=>D+B,0n)}return Z}catch(a){throw _E(a,{...t,account:n,chain:e.chain})}}async function H0(e,t){const{abi:r,address:n,args:s,functionName:i,dataSuffix:o,...a}=t,c=lr({abi:r,args:s,functionName:i});try{return await se(e,kd,"estimateGas")({data:`${c}${o?o.replace("0x",""):""}`,to:n,...a})}catch(f){const u=a.account?Ye(a.account):void 0;throw Ps(f,{abi:r,address:n,args:s,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:u==null?void 0:u.address})}}function ia(e,t){if(!st(e,{strict:!1}))throw new Ot({address:e});if(!st(t,{strict:!1}))throw new Ot({address:t});return e.toLowerCase()===t.toLowerCase()}const tp="/docs/contract/decodeEventLog";function Id(e){const{abi:t,data:r,strict:n,topics:s}=e,i=n??!0,[o,...a]=s;if(!o)throw new F2({docsPath:tp});const c=t.find(g=>g.type==="event"&&o===wc(Sr(g)));if(!(c&&"name"in c)||c.type!=="event")throw new jm(o,{docsPath:tp});const{name:f,inputs:u}=c,l=u==null?void 0:u.some(g=>!("name"in g&&g.name)),p=l?[]:{},d=u.map((g,w)=>[g,w]).filter(([g])=>"indexed"in g&&g.indexed);for(let g=0;g<d.length;g++){const[w,S]=d[g],k=a[g];if(!k)throw new mc({abiItem:c,param:w});p[l?S:w.name||S]=XE({param:w,value:k})}const m=u.filter(g=>!("indexed"in g&&g.indexed));if(m.length>0){if(r&&r!=="0x")try{const g=ra(m,r);if(g)if(l)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 Um||g instanceof y0?new bo({abiItem:c,data:r,params:m,size:He(r)}):g}else if(i)throw new bo({abiItem:c,data:"0x",params:m,size:0})}return{eventName:f,args:Object.values(p).length>0?p:void 0}}function XE({param:e,value:t}){return e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/)?t:(ra([e],t)||[])[0]}function Pd(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]===wc(u));if(!c)return null;const f=Id({...o,abi:[c],strict:s});return i&&!i.includes(f.eventName)||!ZE({args:f.args,inputs:c.inputs,matchArgs:r})?null:{...f,...o}}catch(c){let f,u;if(c instanceof jm)return null;if(c instanceof bo||c instanceof mc){if(s)return null;f=c.abiItem.name,u=(a=c.abiItem.inputs)==null?void 0:a.some(l=>!("name"in l&&l.name))}return{...o,args:u?[]:{},eventName:f}}}).filter(Boolean)}function ZE(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"?ia(o,a):i.type==="string"||i.type==="bytes"?ft(Ci(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(f=>s(a,f,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(f=>f.name===i);return a?(Array.isArray(o)?o:[o]).some(f=>s(a,f,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 Od(e,{address:t,blockHash:r,fromBlock:n,toBlock:s,event:i,events:o,args:a,strict:c}={}){const f=c??!1,u=o??(i?[i]:void 0);let l=[];u&&(l=[u.flatMap(g=>ta({abi:[g],eventName:g.name,args:o?void 0:a}))],i&&(l=l[0]));let p;r?p=await e.request({method:"eth_getLogs",params:[{address:t,topics:l,blockHash:r}]}):p=await e.request({method:"eth_getLogs",params:[{address:t,topics:l,fromBlock:typeof n=="bigint"?Y(n):n,toBlock:typeof s=="bigint"?Y(s):s}]});const d=p.map(m=>wn(m));return u?Pd({abi:u,args:a,logs:d,strict:f}):d}async function Bd(e,t){const{abi:r,address:n,args:s,blockHash:i,eventName:o,fromBlock:a,toBlock:c,strict:f}=t,u=o?Fs({abi:r,name:o}):void 0,l=u?void 0:r.filter(p=>p.type==="event");return se(e,Od,"getLogs")({address:n,args:s,blockHash:i,event:u,events:l,fromBlock:a,toBlock:c,strict:f})}const fu="/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:fu});i=a}if(i.type!=="function")throw new yi(void 0,{docsPath:fu});if(!i.outputs)throw new Lm(i.name,{docsPath:fu});const o=ra(i.outputs,s);if(o&&o.length>1)return o;if(o&&o.length===1)return o[0]}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Cd=BigInt(0),yl=BigInt(1);function nc(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function wa(e){const t=e.toString(16);return t.length&1?"0"+t:t}function z0(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Cd:BigInt("0x"+e)}function Pc(e){return z0(vo(e))}function V0(e){return ur(e),z0(vo(Uint8Array.from(e).reverse()))}function Rd(e,t){return cd(e.toString(16).padStart(t*2,"0"))}function q0(e,t){return Rd(e,t).reverse()}function Qt(e,t,r){let n;if(typeof t=="string")try{n=cd(t)}catch(i){throw new Error(e+" must be hex string or Uint8Array, cause: "+i)}else if(od(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 lu=e=>typeof e=="bigint"&&Cd<=e;function JE(e,t,r){return lu(e)&&lu(t)&&lu(r)&&t<=e&&e<r}function QE(e,t,r,n){if(!JE(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function e6(e){let t;for(t=0;e>Cd;e>>=yl,t+=1);return t}const Oc=e=>(yl<<BigInt(e))-yl;function t6(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},f=(...d)=>r(o,i,...d),u=(d=n(0))=>{o=f(s(0),d),i=f(),d.length!==0&&(o=f(s(1),d),i=f())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0;const m=[];for(;d<t;){i=f();const g=i.slice();m.push(g),d+=i.length}return fs(...m)};return(d,m)=>{c(),u(d);let g;for(;!(g=m(l()));)u();return c(),g}}function $d(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 rp(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}}const r6="0.1.1";function n6(){return r6}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
+ `);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@${n6()}`}),this.cause=r.cause,this.details=n,this.docs=o,this.docsPath=s,this.shortMessage=t}walk(t){return G0(this,t)}}function G0(e,t){return t!=null&&t(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?G0(e.cause,t):t?null:e}const s6="#__bigint";function i6(e,t,r){return JSON.stringify(e,(n,s)=>typeof s=="bigint"?s.toString()+s6:s,r)}function o6(e,t){if(sp(e)>t)throw new m6({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 a6(e,t={}){const{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new g6({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 Nd(e,t){if(fr(e)>t)throw new S6({givenSize:fr(e),maxSize:t})}function c6(e,t){if(typeof t=="number"&&t>0&&t>fr(e)-1)throw new Z0({offset:t,position:"start",size:fr(e)})}function u6(e,t,r){if(typeof t=="number"&&typeof r=="number"&&fr(e)!==r-t)throw new Z0({offset:r,position:"end",size:fr(e)})}function W0(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 x6({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 l6(e){return e instanceof Uint8Array?e:typeof e=="string"?h6(e):d6(e)}function d6(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function h6(e,t={}){const{size:r}=t;let n=e;r&&(Nd(e,r),n=Cs(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 f=np(s.charCodeAt(c++)),u=np(s.charCodeAt(c++));if(f===void 0||u===void 0)throw new Fe(`Invalid byte sequence ("${s[c-2]}${s[c-1]}" in "${s}").`);o[a]=f*16+u}return o}function p6(e,t={}){const{size:r}=t,n=f6.encode(e);return typeof r=="number"?(o6(n,r),y6(n,r)):n}function y6(e,t){return a6(e,{dir:"right",size:t})}function sp(e){return e.length}let m6=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"})}},g6=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 b6=new TextEncoder,w6=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function v6(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 K0(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?(Nd(r,t.size),Bs(r,t.size)):r}function Y0(e,t={}){let r="";for(let s=0;s<e.length;s++)r+=w6[e[s]];const n=`0x${r}`;return typeof t.size=="number"?(Nd(n,t.size),Cs(n,t.size)):n}function kt(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 f=typeof e=="bigint"?"n":"";throw new X0({max:i?`${i}${f}`:void 0,min:`${o}${f}`,signed:r,size:n,value:`${e}${f}`})}const c=`0x${(r&&s<0?(1n<<BigInt(n*8))+BigInt(s):s).toString(16)}`;return n?Bs(c,n):c}function Md(e,t={}){return Y0(b6.encode(e),t)}function Bs(e,t){return W0(e,{dir:"left",size:t})}function Cs(e,t){return W0(e,{dir:"right",size:t})}function Ud(e,t,r,n={}){const{strict:s}=n;c6(e,t);const i=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return s&&u6(i,t,r),i}function fr(e){return Math.ceil((e.length-2)/2)}function E6(e,t={}){const{strict:r=!1}=t;try{return v6(e,{strict:r}),!0}catch{return!1}}class X0 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"?i6(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 S6 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 Z0 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 x6 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 A6(e){return{address:e.address,amount:kt(e.amount),index:kt(e.index),validatorIndex:kt(e.validatorIndex)}}function J0(e){return{...typeof e.baseFeePerGas=="bigint"&&{baseFeePerGas:kt(e.baseFeePerGas)},...typeof e.blobBaseFee=="bigint"&&{blobBaseFee:kt(e.blobBaseFee)},...typeof e.feeRecipient=="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit=="bigint"&&{gasLimit:kt(e.gasLimit)},...typeof e.number=="bigint"&&{number:kt(e.number)},...typeof e.prevRandao=="bigint"&&{prevRandao:kt(e.prevRandao)},...typeof e.time=="bigint"&&{time:kt(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(A6)}}}const ml=[{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"}],gl=[{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"}]}],Q0=[{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"}],eg=[...Q0,{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"}]}],_6=[...Q0,{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",tg="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",k6="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",I6="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572";class bl extends H{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 P6 extends H{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 O6 extends H{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 rg extends H{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class Bc extends H{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const du="/docs/contract/encodeDeployData";function Cc(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 R2({docsPath:du});if(!("inputs"in s))throw new $h({docsPath:du});if(!s.inputs||s.inputs.length===0)throw new $h({docsPath:du});const i=Tn(s.inputs,r);return kr([n,i])}function Ni({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 bl({chain:t,contract:{name:r}});if(e&&n.blockCreated&&n.blockCreated>e)throw new bl({blockNumber:e,chain:t,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function ng(e,{docsPath:t,...r}){const n=(()=>{const s=Ac(e,r);return s instanceof sa?e:s})();return new E0(n,{docsPath:t,...r})}function Fd(){let e=()=>{},t=()=>{};return{promise:new Promise((n,s)=>{e=n,t=s}),resolve:e,reject:t}}const hu=new Map;function sg({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:s}){const i=async()=>{const u=c();o();const l=u.map(({args:p})=>p);l.length!==0&&e(l).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=()=>hu.delete(t),a=()=>c().map(({args:u})=>u),c=()=>hu.get(t)||[],f=u=>hu.set(t,[...c(),u]);return{flush:o,async schedule(u){const{promise:l,resolve:p,reject:d}=Fd();return(r==null?void 0:r([...a(),u]))&&i(),c().length>0?(f({args:u,resolve:p,reject:d}),l):(f({args:u,resolve:p,reject:d}),setTimeout(i,n),l)}}}async function oa(e,t){var z,W,Z,Q;const{account:r=e.account,authorizationList:n,batch:s=!!((z=e.batch)!=null&&z.multicall),blockNumber:i,blockTag:o="latest",accessList:a,blobs:c,blockOverrides:f,code:u,data:l,factory:p,factoryData:d,gas:m,gasPrice:g,maxFeePerBlobGas:w,maxFeePerGas:S,maxPriorityFeePerGas:k,nonce:E,to:A,value:I,stateOverride:P,...$}=t,L=r?Ye(r):void 0;if(u&&(p||d))throw new H("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(u&&A)throw new H("Cannot provide both `code` & `to` as parameters.");const T=u&&l,U=p&&d&&A&&l,R=T||U,F=T?R6({code:u,data:l}):U?$6({data:l,factory:p,factoryData:d,to:A}):l;try{js(t);const D=(typeof i=="bigint"?Y(i):void 0)||o,B=f?J0(f):void 0,q=bd(P),K=(Q=(Z=(W=e.chain)==null?void 0:W.formatters)==null?void 0:Z.transactionRequest)==null?void 0:Q.format,N=(K||Ri)({..._c($,{format:K}),from:L==null?void 0:L.address,accessList:a,authorizationList:n,blobs:c,data:F,gas:m,gasPrice:g,maxFeePerBlobGas:w,maxFeePerGas:S,maxPriorityFeePerGas:k,nonce:E,to:R?void 0:A,value:I});if(s&&B6({request:N})&&!q&&!B)try{return await C6(e,{...N,blockNumber:i,blockTag:o})}catch(ne){if(!(ne instanceof rg)&&!(ne instanceof bl))throw ne}const j=(()=>{const ne=[N,D];return q&&B?[...ne,q,B]:q?[...ne,q]:B?[...ne,{},B]:ne})(),J=await e.request({method:"eth_call",params:j});return J==="0x"?{data:void 0}:{data:J}}catch(re){const D=N6(re),{offchainLookup:B,offchainLookupSignature:q}=await Promise.resolve().then(()=>require("./ccip-DLdsllZU.cjs"));if(e.ccipRead!==!1&&(D==null?void 0:D.slice(0,10))===q&&A)return{data:await B(e,{data:D,to:A})};throw R&&(D==null?void 0:D.slice(0,10))==="0x101bb98d"?new yE({factory:p}):ng(re,{...t,account:L,chain:e.chain})}}function B6({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 C6(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="latest",data:o,multicallAddress:a,to:c}=t;let f=a;if(!f){if(!e.chain)throw new rg;f=Ni({blockNumber:s,chain:e.chain,contract:"multicall3"})}const l=(typeof s=="bigint"?Y(s):void 0)||i,{schedule:p}=sg({id:`${e.uid}.${l}`,wait:n,shouldSplitBatch(w){return w.reduce((k,{data:E})=>k+(E.length-2),0)>r*2},fn:async w=>{const S=w.map(A=>({allowFailure:!0,callData:A.data,target:A.to})),k=lr({abi:ml,args:[S],functionName:"aggregate3"}),E=await e.request({method:"eth_call",params:[{data:k,to:f},l]});return Ls({abi:ml,args:[S],functionName:"aggregate3",data:E||"0x"})}}),[{returnData:d,success:m}]=await p({data:o,to:c});if(!m)throw new xc({data:d});return d==="0x"?{data:void 0}:{data:d}}function R6(e){const{code:t,data:r}=e;return Cc({abi:$m(["constructor(bytes, bytes)"]),bytecode:tg,args:[t,r]})}function $6(e){const{data:t,factory:r,factoryData:n,to:s}=e;return Cc({abi:$m(["constructor(address, bytes, address, bytes)"]),bytecode:k6,args:[s,t,r,n]})}function N6(e){var r;if(!(e instanceof H))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=lr({abi:r,args:s,functionName:i});try{const{data:c}=await se(e,oa,"call")({...o,data:a,to:n});return Ls({abi:r,args:s,functionName:i,data:c||"0x"})}catch(c){throw Ps(c,{abi:r,address:n,args:s,docsPath:"/docs/contract/readContract",functionName:i})}}async function ig(e,t){const{abi:r,address:n,args:s,dataSuffix:i,functionName:o,...a}=t,c=a.account?Ye(a.account):e.account,f=lr({abi:r,args:s,functionName:o});try{const{data:u}=await se(e,oa,"call")({batch:!1,data:`${f}${i?i.replace("0x",""):""}`,to:n,...a,account:c}),l=Ls({abi:r,args:s,functionName:o,data:u||"0x"}),p=r.filter(d=>"name"in d&&d.name===t.functionName);return{result:l,request:{abi:p,address:n,args:s,dataSuffix:i,functionName:o,...a,account:c}}}catch(u){throw Ps(u,{abi:r,address:n,args:s,docsPath:"/docs/contract/simulateContract",functionName:o,sender:c==null?void 0:c.address})}}const pu=new Map,fp=new Map;let M6=0;function vn(e,t,r){const n=++M6,s=()=>pu.get(e)||[],i=()=>{const u=s();pu.set(e,u.filter(l=>l.id!==n))},o=()=>{const u=s();if(!u.some(p=>p.id===n))return;const l=fp.get(e);if(u.length===1&&l){const p=l();p instanceof Promise&&p.catch(()=>{})}i()},a=s();if(pu.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return o;const c={};for(const u in t)c[u]=(...l)=>{var d,m;const p=s();if(p.length!==0)for(const g of p)(m=(d=g.fns)[u])==null||m.call(d,...l)};const f=r(c);return typeof f=="function"&&fp.set(e,f),o}async function wl(e){return new Promise(t=>setTimeout(t,e))}function Mi(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 wl(c);const f=async()=>{s&&(await e({unpoll:i}),await wl(n),f())};f()})(),i}const U6=new Map,F6=new Map;function j6(e){const t=(s,i)=>({clear:()=>i.delete(s),get:()=>i.get(s),set:o=>i.set(s,o)}),r=t(e,U6),n=t(e,F6);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function L6(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){const n=j6(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 D6=e=>`blockNumber.${e}`;async function aa(e,{cacheTime:t=e.cacheTime}={}){const r=await L6(()=>e.request({method:"eth_blockNumber"}),{cacheKey:D6(e.uid),cacheTime:t});return BigInt(r)}async function Rc(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:Pd({abi:t.abi,logs:s,strict:r})}async function $c(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}function og(e,t){const{abi:r,address:n,args:s,batch:i=!0,eventName:o,fromBlock:a,onError:c,onLogs:f,poll:u,pollingInterval:l=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,S=Ze(["watchContractEvent",n,s,i,e.uid,o,l,w,a]);return vn(S,{onLogs:f,onError:c},k=>{let E;a!==void 0&&(E=a-1n);let A,I=!1;const P=Mi(async()=>{var $;if(!I){try{A=await se(e,hd,"createContractEventFilter")({abi:r,address:n,args:s,eventName:o,strict:w,fromBlock:a})}catch{}I=!0;return}try{let L;if(A)L=await se(e,Rc,"getFilterChanges")({filter:A});else{const T=await se(e,aa,"getBlockNumber")({});E&&E<T?L=await se(e,Bd,"getContractEvents")({abi:r,address:n,args:s,eventName:o,fromBlock:E+1n,toBlock:T,strict:w}):L=[],E=T}if(L.length===0)return;if(i)k.onLogs(L);else for(const T of L)k.onLogs([T])}catch(L){A&&L instanceof Is&&(I=!1),($=k.onError)==null||$.call(k,L)}},{emitOnBegin:!0,interval:l});return async()=>{A&&await se(e,$c,"uninstallFilter")({filter:A}),P()}})})():(()=>{const w=p??!1,S=Ze(["watchContractEvent",n,s,i,e.uid,o,l,w]);let k=!0,E=()=>k=!1;return vn(S,{onLogs:f,onError:c},A=>((async()=>{try{const I=(()=>{if(e.transport.type==="fallback"){const L=e.transport.transports.find(T=>T.config.type==="webSocket"||T.config.type==="ipc");return L?L.value:e.transport}return e.transport})(),P=o?ta({abi:r,eventName:o,args:s}):[],{unsubscribe:$}=await I.subscribe({params:["logs",{address:n,topics:P}],onData(L){var U;if(!k)return;const T=L.result;try{const{eventName:R,args:F}=Id({abi:r,data:T.data,topics:T.topics,strict:p}),z=wn(T,{args:F,eventName:R});A.onLogs([z])}catch(R){let F,z;if(R instanceof bo||R instanceof mc){if(p)return;F=R.abiItem.name,z=(U=R.abiItem.inputs)==null?void 0:U.some(Z=>!("name"in Z&&Z.name))}const W=wn(T,{args:z?[]:{},eventName:F});A.onLogs([W])}},onError(L){var T;(T=A.onError)==null||T.call(A,L)}});E=$,k||E()}catch(I){c==null||c(I)}})(),()=>E()))})()}class Ds extends H{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 Da extends H{constructor({docsPath:t,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:t,metaMessages:r,name:"AccountTypeNotSupportedError"})}}function ag({chain:e,currentChainId:t}){if(!e)throw new O6;if(t!==e.id)throw new P6({chain:e,currentChainId:t})}function cg(e,{docsPath:t,...r}){const n=(()=>{const s=Ac(e,r);return s instanceof sa?e:s})();return new fE(n,{docsPath:t,...r})}async function jd(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}const yu=new vc(128);async function Nc(e,t){var k,E,A,I;const{account:r=e.account,chain:n=e.chain,accessList:s,authorizationList:i,blobs:o,data:a,gas:c,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:p,nonce:d,type:m,value:g,...w}=t;if(typeof r>"u")throw new Ds({docsPath:"/docs/actions/wallet/sendTransaction"});const S=r?Ye(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 _0({authorization:i[0]}).catch(()=>{throw new H("`to` is required. Could not infer from `authorizationList`.")})})();if((S==null?void 0:S.type)==="json-rpc"||S===null){let $;n!==null&&($=await se(e,$i,"getChainId")({}),ag({currentChainId:$,chain:n}));const L=(A=(E=(k=e.chain)==null?void 0:k.formatters)==null?void 0:E.transactionRequest)==null?void 0:A.format,U=(L||Ri)({..._c(w,{format:L}),accessList:s,authorizationList:i,blobs:o,chainId:$,data:a,from:S==null?void 0:S.address,gas:c,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:p,nonce:d,to:P,type:m,value:g}),R=yu.get(e.uid),F=R?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:F,params:[U]},{retryCount:0})}catch(z){if(R===!1)throw z;const W=z;if(W.name==="InvalidInputRpcError"||W.name==="InvalidParamsRpcError"||W.name==="MethodNotFoundRpcError"||W.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[U]},{retryCount:0}).then(Z=>(yu.set(e.uid,!0),Z)).catch(Z=>{const Q=Z;throw Q.name==="MethodNotFoundRpcError"||Q.name==="MethodNotSupportedRpcError"?(yu.set(e.uid,!1),W):Q});throw W}}if((S==null?void 0:S.type)==="local"){const $=await se(e,Ic,"prepareTransactionRequest")({account:S,accessList:s,authorizationList:i,blobs:o,chain:n,data:a,gas:c,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:p,nonce:d,nonceManager:S.nonceManager,parameters:[...L0,"sidecars"],type:m,value:g,...w,to:P}),L=(I=n==null?void 0:n.serializers)==null?void 0:I.transaction,T=await S.signTransaction($,{serializer:L});return await se(e,jd,"sendRawTransaction")({serializedTransaction:T})}throw(S==null?void 0:S.type)==="smart"?new Da({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new Da({docsPath:"/docs/actions/wallet/sendTransaction",type:S==null?void 0:S.type})}catch(P){throw P instanceof Da?P:cg(P,{...t,account:S,chain:t.chain||void 0})}}async function ug(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 f=n?Ye(n):null,u=lr({abi:r,args:i,functionName:a});try{return await se(e,Nc,"sendTransaction")({data:`${u}${o?o.replace("0x",""):""}`,to:s,account:f,...c})}catch(l){throw Ps(l,{abi:r,address:s,args:i,docsPath:"/docs/contract/writeContract",functionName:a,sender:f==null?void 0:f.address})}}function mu({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 f=!1,u=!1,l=!1;for(const p of e)if(p.type==="function"?p.stateMutability==="view"||p.stateMutability==="pure"?f=!0:u=!0:p.type==="event"&&(l=!0),f&&u&&l)break;return o&&(f&&(c.read=new Proxy({},{get(p,d){return(...m)=>{const{args:g,options:w}=va(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}=va(m);return se(s,ig,"simulateContract")({abi:e,address:t,functionName:d,args:g,...w})}}})),l&&(c.createEventFilter=new Proxy({},{get(p,d){return(...m)=>{const g=e.find(k=>k.type==="event"&&k.name===d),{args:w,options:S}=gu(m,g);return se(s,hd,"createContractEventFilter")({abi:e,address:t,eventName:d,args:w,...S})}}}),c.getEvents=new Proxy({},{get(p,d){return(...m)=>{const g=e.find(k=>k.type==="event"&&k.name===d),{args:w,options:S}=gu(m,g);return se(s,Bd,"getContractEvents")({abi:e,address:t,eventName:d,args:w,...S})}}}),c.watchEvent=new Proxy({},{get(p,d){return(...m)=>{const g=e.find(k=>k.type==="event"&&k.name===d),{args:w,options:S}=gu(m,g);return se(s,og,"watchContractEvent")({abi:e,address:t,eventName:d,args:w,...S})}}}))),a&&u&&(c.write=new Proxy({},{get(p,d){return(...m)=>{const{args:g,options:w}=va(m);return se(i,ug,"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}=va(m);return se(s??i,H0,"estimateContractGas")({abi:e,address:t,functionName:d,args:g,...w,account:w.account??i.account})}}})),c.address=t,c.abi=e,c}function va(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 gu(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}}const fg={"0x0":"reverted","0x1":"success"};function lg(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?cr(e.transactionIndex):null,status:e.status?fg[e.status]:null,type:e.type?k0[e.type]||e.type:null};return e.blobGasPrice&&(t.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(t.blobGasUsed=BigInt(e.blobGasUsed)),t}const H6=gd("transactionReceipt",lg),dg="0x5792579257925792579257925792579257925792579257925792579257925792",hg=Y(0,{size:32});async function z6(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:f="2.0.0"}=t,u=r?Ye(r):null,l=t.calls.map(p=>{const d=p,m=d.abi?lr({abi:d.abi,functionName:d.functionName,args:d.args}):d.data;return{data:d.dataSuffix&&m?qt([m,d.dataSuffix]):m,to:d.to,value:d.value?Y(d.value):void 0}});try{const p=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:a,calls:l,capabilities:n,chainId:Y(s.id),from:u==null?void 0:u.address,id:c,version:f}]},{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(k=>!k.optional)){const k="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new bi(new H(k,{details:k}))}if(a&&l.length>1){const S="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new wi(new H(S,{details:S}))}const m=[];for(const S of l){const k=Nc(e,{account:u,chain:s,data:S.data,to:S.to,value:S.value?ot(S.value):void 0});m.push(k),o>0&&await new Promise(E=>setTimeout(E,o))}const g=await Promise.allSettled(m);if(g.every(S=>S.status==="rejected"))throw g[0].reason;const w=g.map(S=>S.status==="fulfilled"?S.value:hg);return{id:qt([...w,Y(s.id,{size:32}),dg])}}throw cg(p,{...t,account:u,chain:t.chain})}}async function pg(e,t){async function r(u){if(u.endsWith(dg.slice(2))){const p=ar(rc(u,-64,-32)),d=rc(u,0,-64).slice(2).match(/.{1,64}/g),m=await Promise.all(d.map(w=>hg.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:cr(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,f]=(()=>{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?cr(s):void 0,receipts:(i==null?void 0:i.map(u=>({...u,blockNumber:ot(u.blockNumber),gasUsed:ot(u.gasUsed),status:fg[u.status]})))??[],statusCode:f,status:c,version:o}}async function V6(e,t){const{id:r,pollingInterval:n=e.pollingInterval,status:s=({statusCode:p})=>p>=200,timeout:i=6e4}=t,o=Ze(["waitForCallsStatus",e.uid,r]),{promise:a,resolve:c,reject:f}=Fd();let u;const l=vn(o,{resolve:c,reject:f},p=>{const d=Mi(async()=>{const m=g=>{clearTimeout(u),d(),g(),l()};try{const g=await pg(e,{id:r});if(!s(g))return;m(()=>p.resolve(g))}catch(g){m(()=>p.reject(g))}},{interval:n,emitOnBegin:!0});return d});return u=i?setTimeout(()=>{l(),clearTimeout(u),f(new q6({id:r}))},i):void 0,await a}class q6 extends H{constructor({id:t}){super(`Timed out while waiting for call bundle with id "${t}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}const vl=256;let Ea=vl,Sa;function yg(e=11){if(!Sa||Ea+e>vl*2){Sa="",Ea=0;for(let t=0;t<vl;t++)Sa+=(256+Math.random()*256|0).toString(16).substring(1)}return Sa.substring(Ea,Ea+++e)}function mg(e){const{batch:t,chain:r,ccipRead:n,key:s="base",name:i="Base Client",type:o="base"}=e,a=(r==null?void 0:r.blockTime)??12e3,c=Math.min(Math.max(Math.floor(a/2),500),4e3),f=e.pollingInterval??c,u=e.cacheTime??f,l=e.account?Ye(e.account):void 0,{config:p,request:d,value:m}=e.transport({chain:r,pollingInterval:f}),g={...p,...m},w={account:l,batch:t,cacheTime:u,ccipRead:n,chain:r,key:s,name:i,pollingInterval:f,request:d,transport:g,type:o,uid:yg()};function S(k){return E=>{const A=E(k);for(const P in w)delete A[P];const I={...k,...A};return Object.assign(I,{extend:S(I)})}}return Object.assign(w,{extend:S(w)})}const xa=new vc(8192);function G6(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(xa.get(r))return xa.get(r);const n=e().finally(()=>xa.delete(r));return xa.set(r,n),n}function El(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:f})=>{const u=typeof t=="function"?t({count:a,error:f}):t;u&&await wl(u),o({count:a+1})};try{const f=await e();s(f)}catch(f){if(a<r&&await n({count:a,error:f}))return c({error:f});i(f)}};o()})}function W6(e,t={}){return async(r,n={})=>{var l;const{dedupe:s=!1,methods:i,retryDelay:o=150,retryCount:a=3,uid:c}={...t,...n},{method:f}=r;if((l=i==null?void 0:i.exclude)!=null&&l.includes(f))throw new ls(new Error("method not supported"),{method:f});if(i!=null&&i.include&&!i.include.includes(f))throw new ls(new Error("method not supported"),{method:f});const u=s?mi(`${c}.${Ze(r)}`):void 0;return G6(()=>El(async()=>{try{return await e(r)}catch(p){const d=p;switch(d.code){case So.code:throw new So(d);case xo.code:throw new xo(d);case Ao.code:throw new Ao(d,{method:r.method});case _o.code:throw new _o(d);case ks.code:throw new ks(d);case Is.code:throw new Is(d);case To.code:throw new To(d);case ko.code:throw new ko(d);case Io.code:throw new Io(d);case ls.code:throw new ls(d,{method:r.method});case gi.code:throw new gi(d);case Po.code:throw new Po(d);case ui.code:throw new ui(d);case Oo.code:throw new Oo(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 bi.code:throw new bi(d);case No.code:throw new No(d);case Mo.code:throw new Mo(d);case Uo.code:throw new Uo(d);case Fo.code:throw new Fo(d);case jo.code:throw new jo(d);case wi.code:throw new wi(d);case 5e3:throw new ui(d);default:throw p instanceof H?p:new gE(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})=>K6(p)}),{enabled:s,id:u})}}function K6(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 gg({key:e,methods:t,name:r,request:n,retryCount:s=3,retryDelay:i=150,timeout:o,type:a},c){const f=yg();return{config:{key:e,methods:t,name:r,request:n,retryCount:s,retryDelay:i,timeout:o,type:a},request:W6(n,{methods:t,retryCount:s,retryDelay:i,uid:f}),value:c}}function lp(e,t={}){const{key:r="custom",methods:n,name:s="Custom Provider",retryDelay:i}=t;return({retryCount:o})=>gg({key:r,methods:n,name:s,request:e.request.bind(e),retryCount:t.retryCount??o,retryDelay:i,type:"custom"})}class Y6 extends H{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 X6(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 Z6(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const dp=Z6();function J6(e,t={}){return{async request(r){var l;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:f,signal:u}=a;try{const p=await X6(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:f||"POST",signal:u||(o>0?m:null)},w=new Request(e,g),S=await(s==null?void 0:s(w,g))??{...g,url:e};return await fetch(S.url??e,S)},{errorInstance:new Yh({body:n,url:e}),timeout:o,signal:!0});i&&await i(p);let d;if((l=p.headers.get("Content-Type"))!=null&&l.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 bg(e,t={}){const{batch:r,fetchOptions:n,key:s="http",methods:i,name:o="HTTP JSON-RPC",onFetchRequest:a,onFetchResponse:c,retryDelay:f,raw:u}=t;return({chain:l,retryCount:p,timeout:d})=>{const{batchSize:m=1e3,wait:g=0}=typeof r=="object"?r:{},w=t.retryCount??p,S=d??t.timeout??1e4,k=l==null?void 0:l.rpcUrls.default.http[0];if(!k)throw new Y6;const E=J6(k,{fetchOptions:n,onRequest:a,onResponse:c,timeout:S});return gg({key:s,methods:i,name:o,async request({method:A,params:I}){const P={method:A,params:I},{schedule:$}=sg({id:k,wait:g,shouldSplitBatch(R){return R.length>m},fn:R=>E.request({body:R}),sort:(R,F)=>R.id-F.id}),L=async R=>r?$(R):[await E.request({body:R})],[{error:T,result:U}]=await L(P);if(u)return{error:T,result:U};if(T)throw new md({body:P,error:T,url:k});return U},retryCount:w,retryDelay:f,timeout:S,type:"http"},{fetchOptions:n,url:k})}}function Ld(e,t){var n,s,i,o,a,c;if(!(e instanceof H))return!1;const r=e.walk(f=>f instanceof il);return r instanceof il?!!(((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===h0[50]):!1}function Q6(e){const{abi:t,data:r}=e,n=Ts(r,0,4),s=t.find(i=>i.type==="function"&&n===ea(Sr(i)));if(!s)throw new j2(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:s.name,args:"inputs"in s&&s.inputs&&s.inputs.length>0?ra(s.inputs,Ts(r,4)):void 0}}const bu="/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 Nh(r,{docsPath:bu});s=c}if(s.type!=="error")throw new Nh(void 0,{docsPath:bu});const i=Sr(s),o=ea(i);let a="0x";if(n&&n.length>0){if(!s.inputs)throw new U2(s.name,{docsPath:bu});a=Tn(s.inputs,n)}return kr([o,a])}const wu="/docs/contract/encodeFunctionResult";function eS(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:wu});s=o}if(s.type!=="function")throw new yi(void 0,{docsPath:wu});if(!s.outputs)throw new Lm(s.name,{docsPath:wu});const i=(()=>{if(s.outputs.length===0)return[];if(s.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new Dm(n)})();return Tn(s.outputs,i)}const Mc="x-batch-gateway:true";async function wg(e){const{data:t,ccipRequest:r}=e,{args:[n]}=Q6({abi:gl,data:t}),s=[],i=[];return await Promise.all(n.map(async(o,a)=>{try{i[a]=o.urls.includes(Mc)?await wg({data:o.data,ccipRequest:r}):await r(o),s[a]=!1}catch(c){s[a]=!0,i[a]=tS(c)}})),eS({abi:gl,functionName:"query",result:[s,i]})}function tS(e){return e.name==="HttpRequestError"&&e.status?hp({abi:gl,errorName:"HttpError",args:[e.status,e.shortMessage]}):hp({abi:[p0],errorName:"Error",args:["shortMessage"in e?e.shortMessage:e.message]})}function vg(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 Ha(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=vg(r[n]),i=s?Ci(s):ft(ws(r[n]),"bytes");t=ft(qt([t,i]),"bytes")}return Je(t)}function rS(e){return`[${e.slice(2)}]`}function nS(e){const t=new Uint8Array(32).fill(0);return e?vg(e)||ft(ws(e)):Je(t)}function Uc(e){const t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);const r=new Uint8Array(ws(t).byteLength+2);let n=0;const s=t.split(".");for(let i=0;i<s.length;i++){let o=ws(s[i]);o.byteLength>255&&(o=ws(rS(nS(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 sS(e,t){const{blockNumber:r,blockTag:n,coinType:s,name:i,gatewayUrls:o,strict:a}=t,{chain:c}=e,f=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Ni({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),u=c==null?void 0:c.ensTlds;if(u&&!u.some(l=>i.endsWith(l)))return null;try{const l=lr({abi:cp,functionName:"addr",...s!=null?{args:[Ha(i),BigInt(s)]}:{args:[Ha(i)]}}),p={address:f,abi:eg,functionName:"resolve",args:[mt(Uc(i)),l,o??[Mc]],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?[Ha(i),BigInt(s)]:void 0,functionName:"addr",data:m[0]});return g==="0x"||ar(g)==="0x00"?null:g}catch(l){if(a)throw l;if(Ld(l,"resolve"))return null;throw l}}class iS extends H{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 Hi extends H{constructor({reason:t}){super(`ENS NFT avatar URI is invalid. ${t}`,{name:"EnsAvatarInvalidNftUriError"})}}class Dd extends H{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 oS extends H{constructor({namespace:t}){super(`ENS NFT avatar namespace "${t}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const aS=/(?<protocol>https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,cS=/^(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>\/.*)?$/,uS=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,fS=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function lS(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 Eg({uri:e,gatewayUrls:t}){const r=uS.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(aS),{protocol:o,subpath:a,target:c,subtarget:f=""}=(i==null?void 0:i.groups)||{},u=o==="ipns:/"||a==="ipns/",l=o==="ipfs:/"||a==="ipfs/"||cS.test(e);if(e.startsWith("http")&&!u&&!l){let d=e;return t!=null&&t.arweave&&(d=e.replace(/https:\/\/arweave.net/g,t==null?void 0:t.arweave)),{uri:d,isOnChain:!1,isEncoded:!1}}if((u||l)&&c)return{uri:`${n}/${u?"ipns":"ipfs"}/${c}${f}`,isOnChain:!1,isEncoded:!1};if(o==="ar:/"&&c)return{uri:`${s}/${c}${f||""}`,isOnChain:!1,isEncoded:!1};let p=e.replace(fS,"");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 Dd({uri:e})}function Sg(e){if(typeof e!="object"||!("image"in e)&&!("image_url"in e)&&!("image_data"in e))throw new iS({data:e});return e.image||e.image_url||e.image_data}async function dS({gatewayUrls:e,uri:t}){try{const r=await fetch(t).then(s=>s.json());return await Hd({gatewayUrls:e,uri:Sg(r)})}catch{throw new Dd({uri:t})}}async function Hd({gatewayUrls:e,uri:t}){const{uri:r,isOnChain:n}=Eg({uri:t,gatewayUrls:e});if(n||await lS(r))return r;throw new Dd({uri:t})}function hS(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 Hi({reason:"Only EIP-155 supported"});if(!o)throw new Hi({reason:"Chain ID not found"});if(!c)throw new Hi({reason:"Contract address not found"});if(!s)throw new Hi({reason:"Token ID not found"});if(!a)throw new Hi({reason:"ERC namespace not found"});return{chainID:Number.parseInt(o),namespace:a.toLowerCase(),contractAddress:c,tokenID:s}}async function pS(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 oS({namespace:t.namespace})}async function yS(e,{gatewayUrls:t,record:r}){return/eip155:/i.test(r)?mS(e,{gatewayUrls:t,record:r}):Hd({uri:r,gatewayUrls:t})}async function mS(e,{gatewayUrls:t,record:r}){const n=hS(r),s=await pS(e,{nft:n}),{uri:i,isOnChain:o,isEncoded:a}=Eg({uri:s,gatewayUrls:t});if(o&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){const f=a?atob(i.replace("data:application/json;base64,","")):i,u=JSON.parse(f);return Hd({uri:Sg(u),gatewayUrls:t})}let c=n.tokenID;return n.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),dS({gatewayUrls:t,uri:i.replace(/(?:0x)?{id}/,c)})}async function xg(e,t){const{blockNumber:r,blockTag:n,key:s,name:i,gatewayUrls:o,strict:a}=t,{chain:c}=e,f=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Ni({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),u=c==null?void 0:c.ensTlds;if(u&&!u.some(l=>i.endsWith(l)))return null;try{const l={address:f,abi:eg,functionName:"resolve",args:[mt(Uc(i)),lr({abi:ap,functionName:"text",args:[Ha(i),s]}),o??[Mc]],blockNumber:r,blockTag:n},d=await se(e,Wr,"readContract")(l);if(d[0]==="0x")return null;const m=Ls({abi:ap,functionName:"text",data:d[0]});return m===""?null:m}catch(l){if(a)throw l;if(Ld(l,"resolve"))return null;throw l}}async function gS(e,{blockNumber:t,blockTag:r,assetGatewayUrls:n,name:s,gatewayUrls:i,strict:o,universalResolverAddress:a}){const c=await se(e,xg,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:s,universalResolverAddress:a,gatewayUrls:i,strict:o});if(!c)return null;try{return await yS(e,{record:c,gatewayUrls:n})}catch{return null}}async function bS(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=Ni({blockNumber:r,chain:e.chain,contract:"ensUniversalResolver"})}const c=`${t.toLowerCase().substring(2)}.addr.reverse`;try{const f={address:a,abi:_6,functionName:"reverse",args:[mt(Uc(c))],blockNumber:r,blockTag:n},u=se(e,Wr,"readContract"),[l,p]=s?await u({...f,args:[...f.args,s]}):await u(f);return t.toLowerCase()!==p.toLowerCase()?null:l}catch(f){if(i)throw f;if(Ld(f,"reverse"))return null;throw f}}async function wS(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 Ni({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),a=i==null?void 0:i.ensTlds;if(a&&!a.some(f=>s.endsWith(f)))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(Uc(s))],blockNumber:r,blockTag:n});return c}async function Ag(e,t){var w,S,k;const{account:r=e.account,blockNumber:n,blockTag:s="latest",blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:f,maxFeePerGas:u,maxPriorityFeePerGas:l,to:p,value:d,...m}=t,g=r?Ye(r):void 0;try{js(t);const A=(typeof n=="bigint"?Y(n):void 0)||s,I=(k=(S=(w=e.chain)==null?void 0:w.formatters)==null?void 0:S.transactionRequest)==null?void 0:k.format,$=(I||Ri)({..._c(m,{format:I}),from:g==null?void 0:g.address,blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:f,maxFeePerGas:u,maxPriorityFeePerGas:l,to:p,value:d}),L=await e.request({method:"eth_createAccessList",params:[$,A]});return{accessList:L.accessList,gasUsed:BigInt(L.gasUsed)}}catch(E){throw ng(E,{...t,account:g,chain:e.chain})}}async function vS(e){const t=Ec(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}async function _g(e,{address:t,args:r,event:n,events:s,fromBlock:i,strict:o,toBlock:a}={}){const c=s??(n?[n]:void 0),f=Ec(e,{method:"eth_newFilter"});let u=[];c&&(u=[c.flatMap(d=>ta({abi:[d],eventName:d.name,args:r}))],n&&(u=u[0]));const l=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof i=="bigint"?Y(i):i,toBlock:typeof a=="bigint"?Y(a):a,...u.length?{topics:u}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:i,id:l,request:f(l),strict:!!o,toBlock:a,type:"event"}}async function Tg(e){const t=Ec(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}async function ES(e){const t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}async function SS(e,{blockHash:t,blockNumber:r,blockTag:n="latest"}={}){const s=r!==void 0?Y(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}),cr(i)}async function yp(e,{address:t,blockNumber:r,blockTag:n="latest"}){const s=r!==void 0?Y(r):void 0,i=await e.request({method:"eth_getCode",params:[t,s||n]},{dedupe:!!s});if(i!=="0x")return i}class xS extends H{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 AS(e,t){const{address:r,factory:n,factoryData:s}=t;try{const[i,o,a,c,f,u,l]=await se(e,Wr,"readContract")({abi:_S,address:r,functionName:"eip712Domain",factory:n,factoryData:s});return{domain:{name:o,version:a,chainId:Number(c),verifyingContract:f,salt:u},extensions:l,fields:i}}catch(i){const o=i;throw o.name==="ContractFunctionExecutionError"&&o.cause.name==="ContractFunctionZeroDataError"?new xS({address:r}):o}}const _S=[{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 TS(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 kS(e,{blockCount:t,blockNumber:r,blockTag:n="latest",rewardPercentiles:s}){const i=typeof r=="bigint"?Y(r):void 0,o=await e.request({method:"eth_feeHistory",params:[Y(t),i||n,s]},{dedupe:!!i});return TS(o)}async function IS(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?Pd({abi:t.abi,logs:s,strict:r}):s}function Ft(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}class PS extends H{constructor({domain:t}){super(`Invalid domain "${Ze(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class OS extends H{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 BS extends H{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function CS(e){const{domain:t={},message:r,primaryType:n}=e,s={EIP712Domain:Cg({domain:t}),...e.types};Bg({domain:t,message:r,primaryType:n,types:s});const i=["0x1901"];return t&&i.push(RS({domain:t,types:s})),n!=="EIP712Domain"&&i.push(kg({data:r,primaryType:n,types:s})),ft(qt(i))}function RS({domain:e,types:t}){return kg({data:e,primaryType:"EIP712Domain",types:t})}function kg({data:e,primaryType:t,types:r}){const n=Ig({data:e,primaryType:t,types:r});return ft(n)}function Ig({data:e,primaryType:t,types:r}){const n=[{type:"bytes32"}],s=[$S({primaryType:t,types:r})];for(const i of r[t]){const[o,a]=Og({types:r,name:i.name,type:i.type,value:e[i.name]});n.push(o),s.push(a)}return Tn(n,s)}function $S({primaryType:e,types:t}){const r=mt(NS({primaryType:e,types:t}));return ft(r)}function NS({primaryType:e,types:t}){let r="";const n=Pg({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 Pg({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])Pg({primaryType:i.type,types:t},r);return r}function Og({types:e,name:t,type:r,value:n}){if(e[r]!==void 0)return[{type:"bytes32"},ft(Ig({data:n,primaryType:r,types:e}))];if(r==="bytes")return n=`0x${(n.length%2?"0":"")+n.slice(2)}`,[{type:"bytes32"},ft(n)];if(r==="string")return[{type:"bytes32"},ft(mt(n))];if(r.lastIndexOf("]")===r.length-1){const s=r.slice(0,r.lastIndexOf("[")),i=n.map(o=>Og({name:t,type:s,types:e,value:o}));return[{type:"bytes32"},ft(Tn(i.map(([o])=>o),i.map(([,o])=>o)))]}return[{type:r},n]}function MS(e){const{domain:t,message:r,primaryType:n,types:s}=e,i=(c,f)=>{const u={...f};for(const l of c){const{name:p,type:d}=l;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 Bg(e){const{domain:t,message:r,primaryType:n,types:s}=e,i=(o,a)=>{for(const c of o){const{name:f,type:u}=c,l=a[f],p=u.match(l0);if(p&&(typeof l=="number"||typeof l=="bigint")){const[g,w,S]=p;Y(l,{signed:w==="int",size:Number.parseInt(S)/8})}if(u==="address"&&typeof l=="string"&&!st(l))throw new Ot({address:l});const d=u.match(Cv);if(d){const[g,w]=d;if(w&&He(l)!==Number.parseInt(w))throw new D2({expectedSize:Number.parseInt(w),givenSize:He(l)})}const m=s[u];m&&(US(u),i(m,l))}};if(s.EIP712Domain&&t){if(typeof t!="object")throw new PS({domain:t});i(s.EIP712Domain,t)}if(n!=="EIP712Domain")if(s[n])i(s[n],r);else throw new OS({primaryType:n,types:s})}function Cg({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 US(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new BS({type:e})}function FS(e){const{authorizationList:t}=e;if(t)for(const r of t){const{chainId:n}=r,s=r.address;if(!st(s))throw new Ot({address:s});if(n<0)throw new Bc({chainId:n})}zd(e)}function jS(e){const{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new U0;for(const r of t){const n=He(r),s=cr(Ts(r,0,1));if(n!==32)throw new WE({hash:r,size:n});if(s!==M0)throw new KE({hash:r,version:s})}}zd(e)}function zd(e){const{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:s}=e;if(t<=0)throw new Bc({chainId:t});if(s&&!st(s))throw new Ot({address:s});if(n&&n>Tc)throw new Os({maxFeePerGas:n});if(r&&n&&r>n)throw new Lo({maxFeePerGas:n,maxPriorityFeePerGas:r})}function LS(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=e;if(t<=0)throw new Bc({chainId:t});if(i&&!st(i))throw new Ot({address:i});if(r||s)throw new H("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Tc)throw new Os({maxFeePerGas:n})}function DS(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=e;if(i&&!st(i))throw new Ot({address:i});if(typeof t<"u"&&t<=0)throw new Bc({chainId:t});if(r||s)throw new H("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Tc)throw new Os({maxFeePerGas:n})}function Fc(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 uE({storageKey:s[i]});if(!st(n,{strict:!1}))throw new Ot({address:n});t.push([n,s])}return t}function HS(e,t){const r=j0(e);return r==="eip1559"?qS(e,t):r==="eip2930"?GS(e,t):r==="eip4844"?VS(e,t):r==="eip7702"?zS(e,t):WS(e,t)}function zS(e,t){const{authorizationList:r,chainId:n,gas:s,nonce:i,to:o,value:a,maxFeePerGas:c,maxPriorityFeePerGas:f,accessList:u,data:l}=e;FS(e);const p=Fc(u),d=KS(r);return kr(["0x04",es([Y(n),i?Y(i):"0x",f?Y(f):"0x",c?Y(c):"0x",s?Y(s):"0x",o??"0x",a?Y(a):"0x",l??"0x",p,d,...ca(e,t)])])}function VS(e,t){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:f,accessList:u,data:l}=e;jS(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)),A=e.kzg,I=xd({blobs:E,kzg:A});if(typeof p>"u"&&(p=R0({commitments:I})),typeof d>"u"){const P=Ad({blobs:E,commitments:I,kzg:A});d=F0({blobs:E,commitments:I,proofs:P})}}const m=Fc(u),g=[Y(r),s?Y(s):"0x",f?Y(f):"0x",c?Y(c):"0x",n?Y(n):"0x",i??"0x",o?Y(o):"0x",l??"0x",m,a?Y(a):"0x",p??[],...ca(e,t)],w=[],S=[],k=[];if(d)for(let E=0;E<d.length;E++){const{blob:A,commitment:I,proof:P}=d[E];w.push(A),S.push(I),k.push(P)}return kr(["0x03",es(d?[g,w,S,k]:g)])}function qS(e,t){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:f,data:u}=e;zd(e);const l=Fc(f),p=[Y(r),s?Y(s):"0x",c?Y(c):"0x",a?Y(a):"0x",n?Y(n):"0x",i??"0x",o?Y(o):"0x",u??"0x",l,...ca(e,t)];return kr(["0x02",es(p)])}function GS(e,t){const{chainId:r,gas:n,data:s,nonce:i,to:o,value:a,accessList:c,gasPrice:f}=e;LS(e);const u=Fc(c),l=[Y(r),i?Y(i):"0x",f?Y(f):"0x",n?Y(n):"0x",o??"0x",a?Y(a):"0x",s??"0x",u,...ca(e,t)];return kr(["0x01",es(l)])}function WS(e,t){const{chainId:r=0,gas:n,data:s,nonce:i,to:o,value:a,gasPrice:c}=e;DS(e);let f=[i?Y(i):"0x",c?Y(c):"0x",n?Y(n):"0x",o??"0x",a?Y(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 aE({v:t.v});return d})(),l=ar(t.r),p=ar(t.s);f=[...f,Y(u),l==="0x00"?"0x":l,p==="0x00"?"0x":p]}else r>0&&(f=[...f,Y(r),"0x","0x"]);return es(f)}function ca(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=ar(r.r),o=ar(r.s);return[typeof s=="number"?s?Y(1):"0x":n===0n?"0x":n===1n?Y(1):n===27n?"0x":Y(1),i==="0x00"?"0x":i,o==="0x00"?"0x":o]}function KS(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",...ca({},i)])}return t}const YS=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Rg=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),XS=Rg.map(e=>(9*e+5)%16),$g=(()=>{const r=[[Rg],[XS]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>YS[i]));return r})(),Ng=$g[0],Mg=$g[1],Ug=[[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)),ZS=Ng.map((e,t)=>e.map(r=>Ug[t][r])),JS=Mg.map((e,t)=>e.map(r=>Ug[t][r])),QS=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),ex=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 Aa=new Uint32Array(16);let Fg=class extends P0{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)Aa[d]=t.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,o=i,a=this.h2|0,c=a,f=this.h3|0,u=f,l=this.h4|0,p=l;for(let d=0;d<5;d++){const m=4-d,g=QS[d],w=ex[d],S=Ng[d],k=Mg[d],E=ZS[d],A=JS[d];for(let I=0;I<16;I++){const P=ba(n+mp(d,i,a,f)+Aa[S[I]]+g,E[I])+l|0;n=l,l=f,f=ba(a,10)|0,a=i,i=P}for(let I=0;I<16;I++){const P=ba(s+mp(m,o,c,u)+Aa[k[I]]+w,A[I])+p|0;s=p,p=u,u=ba(c,10)|0,c=o,o=P}}this.set(this.h1+a+u|0,this.h2+f+p|0,this.h3+l+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){_r(Aa)}destroy(){this.destroyed=!0,_r(this.buffer),this.set(0,0,0,0,0)}};const tx=bc(()=>new Fg),rx=Fg,nx=tx,sx=Object.freeze(Object.defineProperty({__proto__:null,RIPEMD160:rx,ripemd160:nx},Symbol.toStringTag,{value:"Module"})),ix=`Ethereum Signed Message:
43
+ `;function ox(e){const t=typeof e=="string"?mi(e):typeof e.raw=="string"?e.raw:Je(e.raw),r=mi(`${ix}${He(t)}`);return qt([r,t])}function jg(e,t){return ft(ox(e),t)}const Lg="0x6492649264926492649264926492649264926492649264926492649264926492";function ax(e){return rc(e,-32)===Lg}function cx(e){const{address:t,data:r,signature:n,to:s="hex"}=e,i=kr([Tn([{type:"address"},{type:"bytes"},{type:"bytes"}],[t,r,n]),Lg]);return s==="hex"?i:Ar(i)}function ux(e){return e.map(t=>({...t,value:BigInt(t.value)}))}function fx(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?cr(e.nonce):void 0,storageProof:e.storageProof?ux(e.storageProof):void 0}}async function lx(e,{address:t,blockNumber:r,blockTag:n,storageKeys:s}){const i=n??"latest",o=r!==void 0?Y(r):void 0,a=await e.request({method:"eth_getProof",params:[t,s,o||i]});return fx(a)}async function dx(e,{address:t,blockNumber:r,blockTag:n="latest",slot:s}){const i=r!==void 0?Y(r):void 0;return await e.request({method:"eth_getStorageAt",params:[t,s,i||n]})}async function Vd(e,{blockHash:t,blockNumber:r,blockTag:n,hash:s,index:i}){var u,l,p;const o=n||"latest",a=r!==void 0?Y(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,Y(i)]},{dedupe:!0}):c=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[a||o,Y(i)]},{dedupe:!!a}),!c)throw new w0({blockHash:t,blockNumber:r,blockTag:o,hash:s,index:i});return(((p=(l=(u=e.chain)==null?void 0:u.formatters)==null?void 0:l.transaction)==null?void 0:p.format)||kc)(c)}async function hx(e,{hash:t,transactionReceipt:r}){const[n,s]=await Promise.all([se(e,aa,"getBlockNumber")({}),t?se(e,Vd,"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 Sl(e,{hash:t}){var s,i,o;const r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new v0({hash:t});return(((o=(i=(s=e.chain)==null?void 0:s.formatters)==null?void 0:i.transactionReceipt)==null?void 0:o.format)||lg)(r)}async function px(e,t){var S;const{account:r,allowFailure:n=!0,batchSize:s,blockNumber:i,blockTag:o,multicallAddress:a,stateOverride:c}=t,f=t.contracts,u=s??(typeof((S=e.batch)==null?void 0:S.multicall)=="object"&&e.batch.multicall.batchSize||1024);let l=a;if(!l){if(!e.chain)throw new Error("client chain not configured. multicallAddress is required.");l=Ni({blockNumber:i,chain:e.chain,contract:"multicall3"})}const p=[[]];let d=0,m=0;for(let k=0;k<f.length;k++){const{abi:E,address:A,args:I,functionName:P}=f[k];try{const $=lr({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:A}]}catch($){const L=Ps($,{abi:E,address:A,args:I,docsPath:"/docs/contract/multicall",functionName:P,sender:r});if(!n)throw L;p[d]=[...p[d],{allowFailure:!0,callData:"0x",target:A}]}}const g=await Promise.allSettled(p.map(k=>se(e,Wr,"readContract")({abi:ml,account:r,address:l,args:[k],blockNumber:i,blockTag:o,functionName:"aggregate3",stateOverride:c}))),w=[];for(let k=0;k<g.length;k++){const E=g[k];if(E.status==="rejected"){if(!n)throw E.reason;for(let I=0;I<p[k].length;I++)w.push({status:"failure",error:E.reason,result:void 0});continue}const A=E.value;for(let I=0;I<A.length;I++){const{returnData:P,success:$}=A[I],{callData:L}=p[k][I],{abi:T,address:U,functionName:R,args:F}=f[w.length];try{if(L==="0x")throw new Jo;if(!$)throw new xc({data:P});const z=Ls({abi:T,args:F,data:P,functionName:R});w.push(n?{result:z,status:"success"}:z)}catch(z){const W=Ps(z,{abi:T,address:U,args:F,docsPath:"/docs/contract/multicall",functionName:R});if(!n)throw W;w.push({error:W,result:void 0,status:"failure"})}}}if(w.length!==f.length)throw new H("multicall results mismatch");return w}async function xl(e,t){const{blockNumber:r,blockTag:n="latest",blocks:s,returnFullTransactions:i,traceTransfers:o,validation:a}=t;try{const c=[];for(const p of s){const d=p.blockOverrides?J0(p.blockOverrides):void 0,m=p.calls.map(w=>{const S=w,k=S.account?Ye(S.account):void 0,E=S.abi?lr(S):S.data,A={...S,data:S.dataSuffix?qt([E||"0x",S.dataSuffix]):E,from:S.from??(k==null?void 0:k.address)};return js(A),Ri(A)}),g=p.stateOverrides?bd(p.stateOverrides):void 0;c.push({blockOverrides:d,calls:m,stateOverrides:g})}const u=(typeof r=="bigint"?Y(r):void 0)||n;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:i,traceTransfers:o,validation:a},u]})).map((p,d)=>({...vd(p),calls:p.calls.map((m,g)=>{var U,R;const{abi:w,args:S,functionName:k,to:E}=s[d].calls[g],A=((U=m.error)==null?void 0:U.data)??m.returnData,I=BigInt(m.gasUsed),P=(R=m.logs)==null?void 0:R.map(F=>wn(F)),$=m.status==="0x1"?"success":"failure",L=w&&$==="success"&&A!=="0x"?Ls({abi:w,data:A,functionName:k}):null,T=(()=>{var z;if($==="success")return;let F;if(((z=m.error)==null?void 0:z.data)==="0x"?F=new Jo:m.error&&(F=new xc(m.error)),!!F)return Ps(F,{abi:w??[],address:E??"0x",args:S,functionName:k??"<unknown>"})})();return{data:A,gasUsed:I,logs:P,status:$,...$==="success"?{result:L}:{error:T}}})}))}catch(c){const f=c,u=Ac(f,{});throw u instanceof sa?f:u}}function Dg(e,t={}){const{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=i0(l6(e));return r==="Bytes"?n:Y0(n)}class yx 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 mx={checksum:new yx(8192)},vu=mx.checksum,gx=/^0x[a-fA-F0-9]{40}$/;function jc(e,t={}){const{strict:r=!0}=t;if(!gx.test(e))throw new gp({address:e,cause:new wx});if(r){if(e.toLowerCase()===e)return;if(bx(e)!==e)throw new gp({address:e,cause:new vx})}}function bx(e){if(vu.has(e))return vu.get(e);jc(e,{strict:!1});const t=e.substring(2).toLowerCase(),r=Dg(p6(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 vu.set(e,s),s}function Al(e,t={}){const{strict:r=!0}=t??{};try{return jc(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 wx 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 vx 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 _l(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 Tl(e,t){const r=typeof e,n=t.type;switch(n){case"address":return Al(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)=>Tl(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=>Tl(s,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function Hg(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 Hg(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")?Al(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?Al(r[n],{strict:!1}):!1)return o}}function zg(e,t={}){const{prepare:r=!0}=t,n=Array.isArray(e)||typeof e=="string"?Rh(e):e;return{...n,...r?{hash:oi(n)}:{}}}function Ex(e,t,r){const{args:n=[],prepare:s=!0}=r??{},i=E6(t,{strict:!1}),o=e.filter(f=>i?f.type==="function"||f.type==="error"?Vg(f)===Ud(t,0,4):f.type==="event"?oi(f)===t:!1:"name"in f&&f.name===t);if(o.length===0)throw new kl({name:t});if(o.length===1)return{...o[0],...s?{hash:oi(o[0])}:{}};let a;for(const f of o){if(!("inputs"in f))continue;if(!n||n.length===0){if(!f.inputs||f.inputs.length===0)return{...f,...s?{hash:oi(f)}:{}};continue}if(!f.inputs||f.inputs.length===0||f.inputs.length!==n.length)continue;if(n.every((l,p)=>{const d="inputs"in f&&f.inputs[p];return d?Tl(l,d):!1})){if(a&&"inputs"in a&&a.inputs){const l=Hg(f.inputs,a.inputs,n);if(l)throw new xx({abiItem:f,type:l[0]},{abiItem:a,type:l[1]})}a=f}}const c=(()=>{if(a)return a;const[f,...u]=o;return{...f,overloads:u}})();if(!c)throw new kl({name:t});return{...c,...s?{hash:oi(c)}:{}}}function Vg(e){return Ud(oi(e),0,4)}function Sx(e){const t=typeof e=="string"?e:tc(e);return _l(t)}function oi(e){return typeof e!="string"&&"hash"in e&&e.hash?e.hash:Dg(Md(Sx(e)))}class xx extends Fe{constructor(t,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${t.type}\` in \`${_l(tc(t.abiItem))}\`, and`,`\`${r.type}\` in \`${_l(tc(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 kl 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 Ax=/^(.*)\[([0-9]*)\]$/,_x=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,qg=/^(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 Tx({checksumAddress:e,parameters:t,values:r}){const n=[];for(let s=0;s<t.length;s++)n.push(qd({checksumAddress:e,parameter:t[s],value:r[s]}));return n}function qd({checksumAddress:e=!1,parameter:t,value:r}){const n=t,s=$x(n.type);if(s){const[i,o]=s;return Ix(r,{checksumAddress:e,length:i,parameter:{...n,type:o}})}if(n.type==="tuple")return Rx(r,{checksumAddress:e,parameter:n});if(n.type==="address")return kx(r,{checksum:e});if(n.type==="bool")return Ox(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){const i=n.type.startsWith("int"),[,,o="256"]=qg.exec(n.type)??[];return Bx(r,{signed:i,size:Number(o)})}if(n.type.startsWith("bytes"))return Px(r,{type:n.type});if(n.type==="string")return Cx(r);throw new Yg(n.type)}function Gd(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(kt(t+s,{size:32})),n.push(a),s+=fr(a)):r.push(a)}return Gr(...r,...n)}function kx(e,t){const{checksum:r=!1}=t;return jc(e,{strict:r}),{dynamic:!1,encoded:Bs(e.toLowerCase())}}function Ix(e,t){const{checksumAddress:r,length:n,parameter:s}=t,i=n===null;if(!Array.isArray(e))throw new Mx(e);if(!i&&e.length!==n)throw new Nx({expectedLength:n,givenLength:e.length,type:`${s.type}[${n}]`});let o=!1;const a=[];for(let c=0;c<e.length;c++){const f=qd({checksumAddress:r,parameter:s,value:e[c]});f.dynamic&&(o=!0),a.push(f)}if(i||o){const c=Gd(a);if(i){const f=kt(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?Gr(f,c):f}}if(o)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Gr(...a.map(({encoded:c})=>c))}}function Px(e,{type:t}){const[,r]=t.split("bytes"),n=fr(e);if(!r){let s=e;return n%32!==0&&(s=Cs(s,Math.ceil((e.length-2)/2/32)*32)),{dynamic:!0,encoded:Gr(Bs(kt(n,{size:32})),s)}}if(n!==Number.parseInt(r))throw new Wg({expectedSize:Number.parseInt(r),value:e});return{dynamic:!1,encoded:Cs(e)}}function Ox(e){if(typeof e!="boolean")throw new Fe(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Bs(K0(e))}}function Bx(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 X0({max:n.toString(),min:s.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:kt(e,{size:32,signed:t})}}function Cx(e){const t=Md(e),r=Math.ceil(fr(t)/32),n=[];for(let s=0;s<r;s++)n.push(Cs(Ud(t,s*32,(s+1)*32)));return{dynamic:!0,encoded:Gr(Cs(kt(fr(t),{size:32})),...n)}}function Rx(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,f=qd({checksumAddress:r,parameter:a,value:e[c]});i.push(f),f.dynamic&&(s=!0)}return{dynamic:s,encoded:s?Gd(i):Gr(...i.map(({encoded:o})=>o))}}function $x(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function Gg(e,t,r){const{checksumAddress:n=!1}={};if(e.length!==t.length)throw new Kg({expectedLength:e.length,givenLength:t.length});const s=Tx({checksumAddress:n,parameters:e,values:t}),i=Gd(s);return i.length===0?"0x":i}function Il(e,t){if(e.length!==t.length)throw new Kg({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(Il.encode(s,i))}return Gr(...r)}(function(e){function t(r,n,s=!1){if(r==="address"){const c=n;return jc(c),Bs(c.toLowerCase(),s?32:0)}if(r==="string")return Md(n);if(r==="bytes")return n;if(r==="bool")return Bs(K0(n),s?32:1);const i=r.match(qg);if(i){const[c,f,u="256"]=i,l=Number.parseInt(u)/8;return kt(n,{size:s?32:l,signed:f==="int"})}const o=r.match(_x);if(o){const[c,f]=o;if(Number.parseInt(f)!==(n.length-2)/2)throw new Wg({expectedSize:Number.parseInt(f),value:n});return Cs(n,s?32:0)}const a=r.match(Ax);if(a&&Array.isArray(n)){const[c,f]=a,u=[];for(let l=0;l<n.length;l++)u.push(t(f,n[l],!0));return u.length===0?"0x":Gr(...u)}throw new Yg(r)}e.encode=t})(Il||(Il={}));class Nx 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 Wg 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 Kg extends Fe{constructor({expectedLength:t,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${t}`,`Given length (values): ${r}`].join(`
44
+ `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class Mx 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 Yg 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 Ux(e,t){var s;const{bytecode:r,args:n}=t;return Gr(r,(s=e.inputs)!=null&&s.length&&(n!=null&&n.length)?Gg(e.inputs,n):"0x")}function Fx(e){return zg(e)}function jx(e,...t){const{overloads:r}=e,n=r?Lx([e,...r],e.name,{args:t[0]}):e,s=Dx(n),i=t.length>0?Gg(n.inputs,t[0]):void 0;return i?Gr(s,i):s}function Ks(e,t={}){return zg(e,t)}function Lx(e,t,r){const n=Ex(e,t,r);if(n.type!=="function")throw new kl({name:t,type:"function"});return n}function Dx(e){return Vg(e)}const Hx="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Cr="0x0000000000000000000000000000000000000000",zx="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function Vx(e,t){const{blockNumber:r,blockTag:n,calls:s,stateOverrides:i,traceAssetChanges:o,traceTransfers:a,validation:c}=t,f=t.account?Ye(t.account):void 0;if(o&&!f)throw new H("`account` is required when `traceAssetChanges` is true");const u=f?Ux(Fx("constructor(bytes, bytes)"),{bytecode:tg,args:[zx,jx(Ks("function getBalance(address)"),[f.address])]}):void 0,l=o?await Promise.all(t.calls.map(async D=>{if(!D.data&&!D.abi)return;const{accessList:B}=await Ag(e,{account:f.address,...D,data:D.abi?lr(D):D.data});return B.map(({address:q,storageKeys:K})=>K.length>0?q:null)})).then(D=>D.flat().filter(Boolean)):[],p=await xl(e,{blockNumber:r,blockTag:n,blocks:[...o?[{calls:[{data:u}],stateOverrides:i},{calls:l.map((D,B)=>({abi:[Ks("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[f.address],to:D,from:Cr,nonce:B})),stateOverrides:[{address:Cr,nonce:0}]}]:[],{calls:[...s,{}].map(D=>({...D,from:f==null?void 0:f.address})),stateOverrides:i},...o?[{calls:[{data:u}]},{calls:l.map((D,B)=>({abi:[Ks("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[f.address],to:D,from:Cr,nonce:B})),stateOverrides:[{address:Cr,nonce:0}]},{calls:l.map((D,B)=>({to:D,abi:[Ks("function decimals() returns (uint256)")],functionName:"decimals",from:Cr,nonce:B})),stateOverrides:[{address:Cr,nonce:0}]},{calls:l.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:l.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,S,k,E,A]=o?p:[],{calls:I,...P}=d,$=I.slice(0,-1)??[],L=(m==null?void 0:m.calls)??[],T=(g==null?void 0:g.calls)??[],U=[...L,...T].map(D=>D.status==="success"?ot(D.data):null),R=(w==null?void 0:w.calls)??[],F=(S==null?void 0:S.calls)??[],z=[...R,...F].map(D=>D.status==="success"?ot(D.data):null),W=((k==null?void 0:k.calls)??[]).map(D=>D.status==="success"?D.result:null),Z=((A==null?void 0:A.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 z.entries()){const q=U[D];if(typeof B!="bigint"||typeof q!="bigint")continue;const K=W[D-1],O=Z[D-1],N=Q[D-1],j=D===0?{address:Hx,decimals:18,symbol:"ETH"}:{address:l[D-1],decimals:N||K?Number(K??1):void 0,symbol:O??void 0};re.some(J=>J.token.address===j.address)||re.push({token:j,value:{pre:q,post:B,diff:B-q}})}return{assetChanges:re,block:P,results:$}}class Xg extends gc{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,lv(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 Qn(this),this.iHash.update(t),this}digestInto(t){Qn(this),ur(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 Zg=(e,t,r)=>new Xg(e,t).update(r).digest();Zg.create=(e,t)=>new Xg(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const $t=BigInt(0),Pt=BigInt(1),ds=BigInt(2),qx=BigInt(3),Jg=BigInt(4),Qg=BigInt(5),eb=BigInt(8);function rr(e,t){const r=e%t;return r>=$t?r:t+r}function Zt(e,t,r){let n=e;for(;t-- >$t;)n*=n,n%=r;return n}function bp(e,t){if(e===$t)throw new Error("invert: expected non-zero number");if(t<=$t)throw new Error("invert: expected positive modulus, got "+t);let r=rr(e,t),n=t,s=$t,i=Pt;for(;r!==$t;){const a=n/r,c=n%r,f=s-i*a;n=r,r=c,s=i,i=f}if(n!==Pt)throw new Error("invert: does not exist");return rr(s,t)}function tb(e,t){const r=(e.ORDER+Pt)/Jg,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function Gx(e,t){const r=(e.ORDER-Qg)/eb,n=e.mul(t,ds),s=e.pow(n,r),i=e.mul(t,s),o=e.mul(e.mul(i,ds),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 Wx(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");let t=e-Pt,r=0;for(;t%ds===$t;)t/=ds,r++;let n=ds;const s=Lc(e);for(;wp(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return tb;let i=s.pow(n,t);const o=(t+Pt)/ds;return function(c,f){if(c.is0(f))return f;if(wp(c,f)!==1)throw new Error("Cannot find square root");let u=r,l=c.mul(c.ONE,i),p=c.pow(f,t),d=c.pow(f,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=Pt<<BigInt(u-m-1),S=c.pow(l,w);u=m,l=c.sqr(S),p=c.mul(p,l),d=c.mul(d,S)}return d}}function Kx(e){return e%Jg===qx?tb:e%eb===Qg?Gx:Wx(e)}const Yx=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Xx(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=Yx.reduce((n,s)=>(n[s]="function",n),t);return $d(e,r),e}function Zx(e,t,r){if(r<$t)throw new Error("invalid exponent, negatives unsupported");if(r===$t)return e.ONE;if(r===Pt)return t;let n=e.ONE,s=t;for(;r>$t;)r&Pt&&(n=e.mul(n,s)),s=e.sqr(s),r>>=Pt;return n}function rb(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 wp(e,t){const r=(e.ORDER-Pt)/ds,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 Jx(e,t){t!==void 0&&Jn(t);const r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Lc(e,t,r=!1,n={}){if(e<=$t)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}=Jx(e,s);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c;const f=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:a,MASK:Oc(o),ZERO:$t,ONE:Pt,create:u=>rr(u,e),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return $t<=u&&u<e},is0:u=>u===$t,isValidNot0:u=>!f.is0(u)&&f.isValid(u),isOdd:u=>(u&Pt)===Pt,neg:u=>rr(-u,e),eql:(u,l)=>u===l,sqr:u=>rr(u*u,e),add:(u,l)=>rr(u+l,e),sub:(u,l)=>rr(u-l,e),mul:(u,l)=>rr(u*l,e),pow:(u,l)=>Zx(f,u,l),div:(u,l)=>rr(u*bp(l,e),e),sqrN:u=>u*u,addN:(u,l)=>u+l,subN:(u,l)=>u-l,mulN:(u,l)=>u*l,inv:u=>bp(u,e),sqrt:i||(u=>(c||(c=Kx(e)),c(f,u))),toBytes:u=>r?q0(u,a):Rd(u,a),fromBytes:u=>{if(u.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);return r?V0(u):Pc(u)},invertBatch:u=>rb(f,u),cmov:(u,l,p)=>p?l:u});return Object.freeze(f)}function nb(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 sb(e){const t=nb(e);return t+Math.ceil(t/2)}function Qx(e,t,r=!1){const n=e.length,s=nb(t),i=sb(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=r?V0(e):Pc(e),a=rr(o,t-Pt)+Pt;return r?q0(a,s):Rd(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const vi=BigInt(0),hs=BigInt(1);function io(e,t){const r=t.negate();return e?r:t}function eA(e,t,r){const n=o=>o.pz,s=rb(e.Fp,r.map(n));return r.map((o,a)=>o.toAffine(s[a])).map(e.fromAffine)}function ib(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Eu(e,t){ib(e,t);const r=Math.ceil(t/e)+1,n=2**(e-1),s=2**e,i=Oc(e),o=BigInt(e);return{windows:r,windowSize:n,mask:i,maxNumber:s,shiftBy:o}}function vp(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+=hs);const f=t*n,u=f+Math.abs(a)-1,l=a===0,p=a<0,d=t%2!==0;return{nextN:c,offset:u,isZero:l,isNeg:p,isNegF:d,offsetF:f}}function tA(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 rA(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,ob=new WeakMap;function xu(e){return ob.get(e)||1}function Ep(e){if(e!==vi)throw new Error("invalid wNAF")}function nA(e,t){return{constTimeNegate:io,hasPrecomputes(r){return xu(r)!==1},unsafeLadder(r,n,s=e.ZERO){let i=r;for(;n>vi;)n&hs&&(s=s.add(i)),i=i.double(),n>>=hs;return s},precomputeWindow(r,n){const{windows:s,windowSize:i}=Eu(n,t),o=[];let a=r,c=a;for(let f=0;f<s;f++){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=Eu(r,t);for(let c=0;c<a.windows;c++){const{nextN:f,offset:u,isZero:l,isNeg:p,isNegF:d,offsetF:m}=vp(s,c,a);s=f,l?o=o.add(io(d,n[m])):i=i.add(io(p,n[u]))}return Ep(s),{p:i,f:o}},wNAFUnsafe(r,n,s,i=e.ZERO){const o=Eu(r,t);for(let a=0;a<o.windows&&s!==vi;a++){const{nextN:c,offset:f,isZero:u,isNeg:l}=vp(s,a,o);if(s=c,!u){const p=n[f];i=i.add(l?p.negate():p)}}return Ep(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=xu(r);return this.wNAF(i,this.getPrecomputes(i,r,s),n)},wNAFCachedUnsafe(r,n,s,i){const o=xu(r);return o===1?this.unsafeLadder(r,n,i):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),n,i)},setWindowSize(r,n){ib(n,t),ob.set(r,n),Su.delete(r)}}}function sA(e,t,r,n){let s=t,i=e.ZERO,o=e.ZERO;for(;r>vi||n>vi;)r&hs&&(i=i.add(s)),n&hs&&(o=o.add(s)),s=s.double(),r>>=hs,n>>=hs;return{p1:i,p2:o}}function iA(e,t,r,n){tA(r,e),rA(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=e6(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const f=Oc(c),u=new Array(Number(f)+1).fill(o),l=Math.floor((t.BITS-1)/c)*c;let p=o;for(let d=l;d>=0;d-=c){u.fill(o);for(let g=0;g<i;g++){const w=n[g],S=Number(w>>BigInt(d)&f);u[S]=u[S].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 Sp(e,t){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Xx(t),t}else return Lc(e)}function oA(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=Sp(t.p,r.Fp),s=Sp(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 xp(e){e.lowS!==void 0&&nc("lowS",e.lowS),e.prehash!==void 0&&nc("prehash",e.prehash)}class aA extends Error{constructor(t=""){super(t)}}const un={Err:aA,_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=wa(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const i=n>127?wa(s.length/2|128):"";return wa(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 f=t.subarray(n,n+c);if(f.length!==c)throw new r("tlv.decode: length bytes not complete");if(f[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of f)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<oo)throw new t("integer: negative integers are not allowed");let r=wa(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 Pc(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:f,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(f)}},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)}},oo=BigInt(0),ao=BigInt(1),cA=BigInt(2),_a=BigInt(3),uA=BigInt(4);function fA(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 ab(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 lA(e,t={}){const{Fp:r,Fn:n}=oA("weierstrass",e,t),{h:s,n:i}=e;$d(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(L,T,U){const{x:R,y:F}=T.toAffine(),z=r.toBytes(R);if(nc("isCompressed",U),U){a();const W=!r.isOdd(F);return fs(cb(W),z)}else return fs(Uint8Array.of(4),z,r.toBytes(F))}function f(L){ur(L);const T=r.BYTES,U=T+1,R=2*T+1,F=L.length,z=L[0],W=L.subarray(1);if(F===U&&(z===2||z===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(q){const K=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+K)}a();const D=r.isOdd(re);return(z&1)===1!==D&&(re=r.neg(re)),{x:Z,y:re}}else if(F===R&&z===4){const Z=r.fromBytes(W.subarray(T*0,T*1)),Q=r.fromBytes(W.subarray(T*1,T*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 ${F}, expected compressed=${U} or uncompressed=${R}`)}const u=t.toBytes||c,l=t.fromBytes||f,p=fA(r,e.a,e.b);function d(L,T){const U=r.sqr(T),R=p(L);return r.eql(U,R)}if(!d(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const m=r.mul(r.pow(e.a,_a),uA),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(L,T,U=!1){if(!r.isValid(T)||U&&r.is0(T))throw new Error(`bad point coordinate ${L}`);return T}function S(L){if(!(L instanceof I))throw new Error("ProjectivePoint expected")}const k=rp((L,T)=>{const{px:U,py:R,pz:F}=L;if(r.eql(F,r.ONE))return{x:U,y:R};const z=L.is0();T==null&&(T=z?r.ONE:r.inv(F));const W=r.mul(U,T),Z=r.mul(R,T),Q=r.mul(F,T);if(z)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=rp(L=>{if(L.is0()){if(t.allowInfinityPoint&&!r.is0(L.py))return;throw new Error("bad point: ZERO")}const{x:T,y:U}=L.toAffine();if(!r.isValid(T)||!r.isValid(U))throw new Error("bad point: x or y not field elements");if(!d(T,U))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function A(L,T,U,R,F){return U=new I(r.mul(U.px,L),U.py,U.pz),T=io(R,T),U=io(F,U),T.add(U)}class I{constructor(T,U,R){this.px=w("x",T),this.py=w("y",U,!0),this.pz=w("z",R),Object.freeze(this)}static fromAffine(T){const{x:U,y:R}=T||{};if(!T||!r.isValid(U)||!r.isValid(R))throw new Error("invalid affine point");if(T instanceof I)throw new Error("projective point not allowed");return r.is0(U)&&r.is0(R)?I.ZERO:new I(U,R,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(T){return eA(I,"pz",T)}static fromBytes(T){return ur(T),I.fromHex(T)}static fromHex(T){const U=I.fromAffine(l(Qt("pointHex",T)));return U.assertValidity(),U}static fromPrivateKey(T){const U=ab(n,t.allowedPrivateKeyLengths,t.wrapPrivateKey);return I.BASE.multiply(U(T))}static msm(T,U){return iA(I,n,T,U)}precompute(T=8,U=!0){return $.setWindowSize(this,T),U||this.multiply(_a),this}_setWindowSize(T){this.precompute(T)}assertValidity(){E(this)}hasEvenY(){const{y:T}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(T)}equals(T){S(T);const{px:U,py:R,pz:F}=this,{px:z,py:W,pz:Z}=T,Q=r.eql(r.mul(U,Z),r.mul(z,F)),re=r.eql(r.mul(R,Z),r.mul(W,F));return Q&&re}negate(){return new I(this.px,r.neg(this.py),this.pz)}double(){const{a:T,b:U}=e,R=r.mul(U,_a),{px:F,py:z,pz:W}=this;let Z=r.ZERO,Q=r.ZERO,re=r.ZERO,D=r.mul(F,F),B=r.mul(z,z),q=r.mul(W,W),K=r.mul(F,z);return K=r.add(K,K),re=r.mul(F,W),re=r.add(re,re),Z=r.mul(T,re),Q=r.mul(R,q),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),q=r.mul(T,q),K=r.sub(D,q),K=r.mul(T,K),K=r.add(K,re),re=r.add(D,D),D=r.add(re,D),D=r.add(D,q),D=r.mul(D,K),Q=r.add(Q,D),q=r.mul(z,W),q=r.add(q,q),D=r.mul(q,K),Z=r.sub(Z,D),re=r.mul(q,B),re=r.add(re,re),re=r.add(re,re),new I(Z,Q,re)}add(T){S(T);const{px:U,py:R,pz:F}=this,{px:z,py:W,pz:Z}=T;let Q=r.ZERO,re=r.ZERO,D=r.ZERO;const B=e.a,q=r.mul(e.b,_a);let K=r.mul(U,z),O=r.mul(R,W),N=r.mul(F,Z),j=r.add(U,R),J=r.add(z,W);j=r.mul(j,J),J=r.add(K,O),j=r.sub(j,J),J=r.add(U,F);let ne=r.add(z,Z);return J=r.mul(J,ne),ne=r.add(K,N),J=r.sub(J,ne),ne=r.add(R,F),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(q,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(q,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(j,Q),Q=r.sub(Q,K),K=r.mul(j,O),D=r.mul(ne,D),D=r.add(D,K),new I(Q,re,D)}subtract(T){return this.add(T.negate())}is0(){return this.equals(I.ZERO)}multiply(T){const{endo:U}=t;if(!n.isValidNot0(T))throw new Error("invalid scalar: out of range");let R,F;const z=W=>$.wNAFCached(this,W,I.normalizeZ);if(U){const{k1neg:W,k1:Z,k2neg:Q,k2:re}=U.splitScalar(T),{p:D,f:B}=z(Z),{p:q,f:K}=z(re);F=B.add(K),R=A(U.beta,D,q,W,Q)}else{const{p:W,f:Z}=z(T);R=W,F=Z}return I.normalizeZ([R,F])[0]}multiplyUnsafe(T){const{endo:U}=t,R=this;if(!n.isValid(T))throw new Error("invalid scalar: out of range");if(T===oo||R.is0())return I.ZERO;if(T===ao)return R;if($.hasPrecomputes(this))return this.multiply(T);if(U){const{k1neg:F,k1:z,k2neg:W,k2:Z}=U.splitScalar(T),{p1:Q,p2:re}=sA(I,R,z,Z);return A(U.beta,Q,re,F,W)}else return $.wNAFCachedUnsafe(R,T)}multiplyAndAddUnsafe(T,U,R){const F=this.multiplyUnsafe(U).add(T.multiplyUnsafe(R));return F.is0()?void 0:F}toAffine(T){return k(this,T)}isTorsionFree(){const{isTorsionFree:T}=t;return s===ao?!0:T?T(I,this):$.wNAFCachedUnsafe(this,i).is0()}clearCofactor(){const{clearCofactor:T}=t;return s===ao?this:T?T(I,this):this.multiplyUnsafe(s)}toBytes(T=!0){return nc("isCompressed",T),this.assertValidity(),u(I,this,T)}toRawBytes(T=!0){return this.toBytes(T)}toHex(T=!0){return vo(this.toBytes(T))}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,$=nA(I,t.endo?Math.ceil(P/2):P);return I}function cb(e){return Uint8Array.of(e?2:3)}function dA(e,t,r={}){$d(t,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=t.randomBytes||mv,s=t.hmac||((R,...F)=>Zg(t.hash,R,fs(...F))),{Fp:i,Fn:o}=e,{ORDER:a,BITS:c}=o;function f(R){const F=a>>ao;return R>F}function u(R){return f(R)?o.neg(R):R}function l(R,F){if(!o.isValidNot0(F))throw new Error(`invalid signature ${R}: out of range 1..CURVE.n`)}class p{constructor(F,z,W){l("r",F),l("s",z),this.r=F,this.s=z,W!=null&&(this.recovery=W),Object.freeze(this)}static fromCompact(F){const z=o.BYTES,W=Qt("compactSignature",F,z*2);return new p(o.fromBytes(W.subarray(0,z)),o.fromBytes(W.subarray(z,z*2)))}static fromDER(F){const{r:z,s:W}=un.toSig(Qt("DER",F));return new p(z,W)}assertValidity(){}addRecoveryBit(F){return new p(this.r,this.s,F)}recoverPublicKey(F){const z=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*cA<z&&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),q=e.fromHex(fs(cb((Q&1)===0),B)),K=o.inv(D),O=E(Qt("msgHash",F)),N=o.create(-O*K),j=o.create(Z*K),J=e.BASE.multiplyUnsafe(N).add(q.multiplyUnsafe(j));if(J.is0())throw new Error("point at infinify");return J.assertValidity(),J}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new p(this.r,o.neg(this.s),this.recovery):this}toBytes(F){if(F==="compact")return fs(o.toBytes(this.r),o.toBytes(this.s));if(F==="der")return cd(un.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return vo(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return vo(this.toBytes("compact"))}}const d=ab(o,r.allowedPrivateKeyLengths,r.wrapPrivateKey),m={isValidPrivateKey(R){try{return d(R),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{const R=a;return Qx(n(sb(R)),R)},precompute(R=8,F=e.BASE){return F.precompute(R,!1)}};function g(R,F=!0){return e.fromPrivateKey(R).toBytes(F)}function w(R){if(typeof R=="bigint")return!1;if(R instanceof e)return!0;const z=Qt("key",R).length,W=i.BYTES,Z=W+1,Q=2*W+1;if(!(r.allowedPrivateKeyLengths||o.BYTES===Z))return z===Z||z===Q}function S(R,F,z=!0){if(w(R)===!0)throw new Error("first arg must be private key");if(w(F)===!1)throw new Error("second arg must be public key");return e.fromHex(F).multiply(d(R)).toBytes(z)}const k=t.bits2int||function(R){if(R.length>8192)throw new Error("input is too large");const F=Pc(R),z=R.length*8-c;return z>0?F>>BigInt(z):F},E=t.bits2int_modN||function(R){return o.create(k(R))},A=Oc(c);function I(R){return QE("num < 2^"+c,R,oo,A),o.toBytes(R)}function P(R,F,z=$){if(["recovered","canonical"].some(j=>j in z))throw new Error("sign() legacy options not supported");const{hash:W}=t;let{lowS:Z,prehash:Q,extraEntropy:re}=z;Z==null&&(Z=!0),R=Qt("msgHash",R),xp(z),Q&&(R=Qt("prehashed msgHash",W(R)));const D=E(R),B=d(F),q=[I(B),I(D)];if(re!=null&&re!==!1){const j=re===!0?n(i.BYTES):re;q.push(Qt("extraEntropy",j))}const K=fs(...q),O=D;function N(j){const J=k(j);if(!o.isValidNot0(J))return;const ne=o.inv(J),le=e.BASE.multiply(J).toAffine(),ce=o.create(le.x);if(ce===oo)return;const oe=o.create(ne*o.create(O+ce*B));if(oe===oo)return;let ie=(le.x===ce?0:2)|Number(le.y&ao),he=oe;return Z&&f(oe)&&(he=u(oe),ie^=1),new p(ce,he,ie)}return{seed:K,k2sig:N}}const $={lowS:t.lowS,prehash:!1},L={lowS:t.lowS,prehash:!1};function T(R,F,z=$){const{seed:W,k2sig:Z}=P(R,F,z);return t6(t.hash.outputLen,o.BYTES,s)(W,Z)}e.BASE.precompute(8);function U(R,F,z,W=L){const Z=R;F=Qt("msgHash",F),z=Qt("publicKey",z),xp(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"||od(Z),q=!B&&!D&&typeof Z=="object"&&Z!==null&&typeof Z.r=="bigint"&&typeof Z.s=="bigint";if(!B&&!q)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let K,O;try{if(q)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(z)}catch{return!1}if(!K||Q&&K.hasHighS())return!1;re&&(F=t.hash(F));const{r:N,s:j}=K,J=E(F),ne=o.inv(j),le=o.create(J*ne),ce=o.create(N*ne),oe=e.BASE.multiplyUnsafe(le).add(O.multiplyUnsafe(ce));return oe.is0()?!1:o.create(oe.x)===N}return Object.freeze({getPublicKey:g,getSharedSecret:S,sign:T,verify:U,utils:m,Point:e,Signature:p})}function hA(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=Lc(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 pA(e){const{CURVE:t,curveOpts:r}=hA(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 yA(e,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:e})}function mA(e){const{CURVE:t,curveOpts:r,ecdsaOpts:n}=pA(e),s=lA(t,r),i=dA(s,n,r);return yA(e,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function gA(e,t){const r=n=>mA({...e,hash:n});return{...r(t),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const sc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")};BigInt(0);const bA=BigInt(1),Pl=BigInt(2),Ap=(e,t)=>(e+t/Pl)/t;function wA(e){const t=sc.p,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),f=e*e*e%t,u=f*f*e%t,l=Zt(u,r,t)*u%t,p=Zt(l,r,t)*u%t,d=Zt(p,Pl,t)*f%t,m=Zt(d,s,t)*d%t,g=Zt(m,i,t)*m%t,w=Zt(g,a,t)*g%t,S=Zt(w,c,t)*w%t,k=Zt(S,a,t)*g%t,E=Zt(k,r,t)*u%t,A=Zt(E,o,t)*m%t,I=Zt(A,n,t)*f%t,P=Zt(I,Pl,t);if(!Ol.eql(Ol.sqr(P),e))throw new Error("Cannot find square root");return P}const Ol=Lc(sc.p,void 0,void 0,{sqrt:wA}),ub=gA({...sc,Fp:Ol,lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=sc.n,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-bA*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=Ap(i*e,t),c=Ap(-n*e,t);let f=rr(e-a*r-c*s,t),u=rr(-a*n-c*i,t);const l=f>o,p=u>o;if(l&&(f=t-f),p&&(u=t-u),f>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:l,k1:f,k2neg:p,k2:u}}}},B0),vA=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:ub},Symbol.toStringTag,{value:"Module"}));function EA({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 ub.Signature(ot(e),ot(t)).toCompactHex()}${i===0?"1b":"1c"}`;return r==="hex"?o:Ar(o)}async function Wd(e,t){var l,p,d;const{address:r,factory:n,factoryData:s,hash:i,signature:o,universalSignatureVerifierAddress:a=(d=(p=(l=e.chain)==null?void 0:l.contracts)==null?void 0:p.universalSignatureVerifier)==null?void 0:d.address,...c}=t,f=xr(o)?o:typeof o=="object"&&"r"in o&&"s"in o?EA(o):Je(o),u=await(async()=>!n&&!s||ax(f)?f:cx({address:n,data:s,signature:f}))();try{const m=a?{to:a,data:lr({abi:up,functionName:"isValidSig",args:[r,i,u]}),...c}:{data:Cc({abi:up,args:[r,i,u],bytecode:I6}),...c},{data:g}=await se(e,oa,"call")(m);return X2(g??"0x0")}catch(m){try{if(ia(a0(r),await S0({hash:i,signature:o})))return!0}catch{}if(m instanceof E0)return!1;throw m}}async function SA(e,{address:t,message:r,factory:n,factoryData:s,signature:i,...o}){const a=jg(r);return Wd(e,{address:t,factory:n,factoryData:s,hash:a,signature:i,...o})}async function xA(e,t){const{address:r,factory:n,factoryData:s,signature:i,message:o,primaryType:a,types:c,domain:f,...u}=t,l=CS({message:o,primaryType:a,types:c,domain:f});return Wd(e,{address:r,factory:n,factoryData:s,hash:l,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 l=Ze(["watchBlockNumber",e.uid,t,r,o]);return vn(l,{onBlockNumber:n,onError:s},p=>Mi(async()=>{var d;try{const m=await se(e,aa,"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 l=Ze(["watchBlockNumber",e.uid,t,r]);return vn(l,{onBlockNumber:n,onError:s},p=>{let d=!0,m=()=>d=!1;return(async()=>{try{const g=(()=>{if(e.transport.type==="fallback"){const S=e.transport.transports.find(k=>k.config.type==="webSocket"||k.config.type==="ipc");return S?S.value:e.transport}return e.transport})(),{unsubscribe:w}=await g.subscribe({params:["newHeads"],onData(S){var E;if(!d)return;const k=ot((E=S.result)==null?void 0:E.number);p.onBlockNumber(k,c),c=k},onError(S){var k;(k=p.onError)==null||k.call(p,S)}});m=w,d||m()}catch(g){s==null||s(g)}})(),()=>m()})})()}async function AA(e,{confirmations:t=1,hash:r,onReplaced:n,pollingInterval:s=e.pollingInterval,retryCount:i=6,retryDelay:o=({count:c})=>~~(1<<c)*200,timeout:a=18e4}){const c=Ze(["waitForTransactionReceipt",e.uid,r]);let f,u,l,p=!1,d,m;const{promise:g,resolve:w,reject:S}=Fd(),k=a?setTimeout(()=>{m(),d(),S(new lE({hash:r}))},a):void 0;return d=vn(c,{onReplaced:n,resolve:w,reject:S},E=>{m=se(e,fb,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:s,async onBlockNumber(A){const I=$=>{clearTimeout(k),m(),$(),d()};let P=A;if(!p)try{if(l){if(t>1&&(!l.blockNumber||P-l.blockNumber+1n<t))return;I(()=>E.resolve(l));return}if(f||(p=!0,await El(async()=>{f=await se(e,Vd,"getTransaction")({hash:r}),f.blockNumber&&(P=f.blockNumber)},{delay:o,retryCount:i}),p=!1),l=await se(e,Sl,"getTransactionReceipt")({hash:r}),t>1&&(!l.blockNumber||P-l.blockNumber+1n<t))return;I(()=>E.resolve(l))}catch($){if($ instanceof w0||$ instanceof v0){if(!f){p=!1;return}try{u=f,p=!0;const L=await El(()=>se(e,Vr,"getBlock")({blockNumber:P,includeTransactions:!0}),{delay:o,retryCount:i,shouldRetry:({error:R})=>R instanceof T0});p=!1;const T=L.transactions.find(({from:R,nonce:F})=>R===u.from&&F===u.nonce);if(!T||(l=await se(e,Sl,"getTransactionReceipt")({hash:T.hash}),t>1&&(!l.blockNumber||P-l.blockNumber+1n<t)))return;let U="replaced";T.to===u.to&&T.value===u.value&&T.input===u.input?U="repriced":T.from===T.to&&T.value===0n&&(U="cancelled"),I(()=>{var R;(R=E.onReplaced)==null||R.call(E,{reason:U,replacedTransaction:u,transaction:T,transactionReceipt:l}),E.resolve(l)})}catch(L){I(()=>E.reject(L))}}else I(()=>E.reject($))}}})}),g}function _A(e,{blockTag:t="latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:s,onError:i,includeTransactions:o,poll:a,pollingInterval:c=e.pollingInterval}){const f=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 l;return f?(()=>{const m=Ze(["watchBlocks",e.uid,t,r,n,u,c]);return vn(m,{onBlock:s,onError:i},g=>Mi(async()=>{var w;try{const S=await se(e,Vr,"getBlock")({blockTag:t,includeTransactions:u});if(S.number!==null&&(l==null?void 0:l.number)!=null){if(S.number===l.number)return;if(S.number-l.number>1&&r)for(let k=(l==null?void 0:l.number)+1n;k<S.number;k++){const E=await se(e,Vr,"getBlock")({blockNumber:k,includeTransactions:u});g.onBlock(E,l),l=E}}((l==null?void 0:l.number)==null||t==="pending"&&(S==null?void 0:S.number)==null||S.number!==null&&S.number>l.number)&&(g.onBlock(S,l),l=S)}catch(S){(w=g.onError)==null||w.call(g,S)}},{emitOnBegin:n,interval:c}))})():(()=>{let m=!0,g=!0,w=()=>m=!1;return(async()=>{try{n&&se(e,Vr,"getBlock")({blockTag:t,includeTransactions:u}).then(E=>{m&&g&&(s(E,void 0),g=!1)}).catch(i);const S=(()=>{if(e.transport.type==="fallback"){const E=e.transport.transports.find(A=>A.config.type==="webSocket"||A.config.type==="ipc");return E?E.value:e.transport}return e.transport})(),{unsubscribe:k}=await S.subscribe({params:["newHeads"],async onData(E){var I;if(!m)return;const A=await se(e,Vr,"getBlock")({blockNumber:(I=E.result)==null?void 0:I.number,includeTransactions:u}).catch(()=>{});m&&(s(A,l),g=!1,l=A)},onError(E){i==null||i(E)}});w=k,m||w()}catch(S){i==null||i(S)}})(),()=>w()})()}function TA(e,{address:t,args:r,batch:n=!0,event:s,events:i,fromBlock:o,onError:a,onLogs:c,poll:f,pollingInterval:u=e.pollingInterval,strict:l}){const p=typeof f<"u"?f:typeof o=="bigint"?!0:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),d=l??!1;return p?(()=>{const w=Ze(["watchEvent",t,r,n,e.uid,s,u,o]);return vn(w,{onLogs:c,onError:a},S=>{let k;o!==void 0&&(k=o-1n);let E,A=!1;const I=Mi(async()=>{var P;if(!A){try{E=await se(e,_g,"createEventFilter")({address:t,args:r,event:s,events:i,strict:d,fromBlock:o})}catch{}A=!0;return}try{let $;if(E)$=await se(e,Rc,"getFilterChanges")({filter:E});else{const L=await se(e,aa,"getBlockNumber")({});k&&k!==L?$=await se(e,Od,"getLogs")({address:t,args:r,event:s,events:i,fromBlock:k+1n,toBlock:L}):$=[],k=L}if($.length===0)return;if(n)S.onLogs($);else for(const L of $)S.onLogs([L])}catch($){E&&$ instanceof Is&&(A=!1),(P=S.onError)==null||P.call(S,$)}},{emitOnBegin:!0,interval:u});return async()=>{E&&await se(e,$c,"uninstallFilter")({filter:E}),I()}})})():(()=>{let w=!0,S=()=>w=!1;return(async()=>{try{const k=(()=>{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 A=[];E&&(A=[E.flatMap($=>ta({abi:[$],eventName:$.name,args:r}))],s&&(A=A[0]));const{unsubscribe:I}=await k.subscribe({params:["logs",{address:t,topics:A}],onData(P){var L;if(!w)return;const $=P.result;try{const{eventName:T,args:U}=Id({abi:E??[],data:$.data,topics:$.topics,strict:d}),R=wn($,{args:U,eventName:T});c([R])}catch(T){let U,R;if(T instanceof bo||T instanceof mc){if(l)return;U=T.abiItem.name,R=(L=T.abiItem.inputs)==null?void 0:L.some(z=>!("name"in z&&z.name))}const F=wn($,{args:R?[]:{},eventName:U});c([F])}},onError(P){a==null||a(P)}});S=I,w||S()}catch(k){a==null||a(k)}})(),()=>S()})()}function kA(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 f=Ze(["watchPendingTransactions",e.uid,t,i]);return vn(f,{onTransactions:n,onError:r},u=>{let l;const p=Mi(async()=>{var d;try{if(!l)try{l=await se(e,Tg,"createPendingTransactionFilter")({});return}catch(g){throw p(),g}const m=await se(e,Rc,"getFilterChanges")({filter:l});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()=>{l&&await se(e,$c,"uninstallFilter")({filter:l}),p()}})})():(()=>{let f=!0,u=()=>f=!1;return(async()=>{try{const{unsubscribe:l}=await e.transport.subscribe({params:["newPendingTransactions"],onData(p){if(!f)return;const d=p.result;n([d])},onError(p){r==null||r(p)}});u=l,f||u()}catch(l){r==null||r(l)}})(),()=>u()})()}function IA(e){var l,p,d;const{scheme:t,statement:r,...n}=((l=e.match(PA))==null?void 0:l.groups)??{},{chainId:s,expirationTime:i,issuedAt:o,notBefore:a,requestId:c,...f}=((p=e.match(OA))==null?void 0:p.groups)??{},u=(d=e.split("Resources:")[1])==null?void 0:d.split(`
45
+ - `).slice(1);return{...n,...f,...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 PA=/^(?:(?<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)?/,OA=/(?: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 BA(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&&!ia(n.address,t))return!1}catch{return!1}return!0}async function CA(e,t){const{address:r,domain:n,message:s,nonce:i,scheme:o,signature:a,time:c=new Date,...f}=t,u=IA(s);if(!u.address||!BA({address:r,domain:n,message:u,nonce:i,scheme:o,time:c}))return!1;const p=jg(s);return Wd(e,{address:u.address,hash:p,signature:a,...f})}function RA(e){return{call:t=>oa(e,t),createAccessList:t=>Ag(e,t),createBlockFilter:()=>vS(e),createContractEventFilter:t=>hd(e,t),createEventFilter:t=>_g(e,t),createPendingTransactionFilter:()=>Tg(e),estimateContractGas:t=>H0(e,t),estimateGas:t=>kd(e,t),getBalance:t=>D0(e,t),getBlobBaseFee:()=>ES(e),getBlock:t=>Vr(e,t),getBlockNumber:t=>aa(e,t),getBlockTransactionCount:t=>SS(e,t),getBytecode:t=>yp(e,t),getChainId:()=>$i(e),getCode:t=>yp(e,t),getContractEvents:t=>Bd(e,t),getEip712Domain:t=>AS(e,t),getEnsAddress:t=>sS(e,t),getEnsAvatar:t=>gS(e,t),getEnsName:t=>bS(e,t),getEnsResolver:t=>wS(e,t),getEnsText:t=>xg(e,t),getFeeHistory:t=>kS(e,t),estimateFeesPerGas:t=>NE(e,t),getFilterChanges:t=>Rc(e,t),getFilterLogs:t=>IS(e,t),getGasPrice:()=>Ed(e),getLogs:t=>Od(e,t),getProof:t=>lx(e,t),estimateMaxPriorityFeePerGas:t=>$E(e,t),getStorageAt:t=>dx(e,t),getTransaction:t=>Vd(e,t),getTransactionConfirmations:t=>hx(e,t),getTransactionCount:t=>Sd(e,t),getTransactionReceipt:t=>Sl(e,t),multicall:t=>px(e,t),prepareTransactionRequest:t=>Ic(e,t),readContract:t=>Wr(e,t),sendRawTransaction:t=>jd(e,t),simulate:t=>xl(e,t),simulateBlocks:t=>xl(e,t),simulateCalls:t=>Vx(e,t),simulateContract:t=>ig(e,t),verifyMessage:t=>SA(e,t),verifySiweMessage:t=>CA(e,t),verifyTypedData:t=>xA(e,t),uninstallFilter:t=>$c(e,t),waitForTransactionReceipt:t=>AA(e,t),watchBlocks:t=>_A(e,t),watchBlockNumber:t=>fb(e,t),watchContractEvent:t=>og(e,t),watchEvent:t=>TA(e,t),watchPendingTransactions:t=>kA(e,t)}}function $A(e){const{key:t="public",name:r="Public Client"}=e;return mg({...e,key:t,name:r,type:"publicClient"}).extend(RA)}async function NA(e,{chain:t}){const{id:r,name:n,nativeCurrency:s,rpcUrls:i,blockExplorers:o}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:Y(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 MA(e,t){const{abi:r,args:n,bytecode:s,...i}=t,o=Cc({abi:r,args:n,bytecode:s});return Nc(e,{...i,...i.authorizationList?{to:null}:{},data:o})}async function UA(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=>Qo(n))}async function FA(e,t={}){const{account:r=e.account,chainId:n}=t,s=r?Ye(r):void 0,i=n?[s==null?void 0:s.address,[Y(n)]]:[s==null?void 0:s.address],o=await e.request({method:"wallet_getCapabilities",params:i}),a={};for(const[c,f]of Object.entries(o)){a[Number(c)]={};for(let[u,l]of Object.entries(f))u==="addSubAccount"&&(u="unstable_addSubAccount"),a[Number(c)][u]=l}return typeof n=="number"?a[n]:a}async function jA(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}async function lb(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=Ye(r),o=(()=>{if(t.executor)return t.executor==="self"?t.executor:Ye(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,$i,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await se(e,Sd,"getTransactionCount")({address:i.address,blockTag:"pending"}),(o==="self"||o!=null&&o.address&&ia(o.address,i.address))&&(a.nonce+=1)),a}async function LA(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>a0(r))}async function DA(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}async function HA(e,t){const{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]})}async function zA(e,t){const{account:r=e.account}=t;if(!r)throw new Ds({docsPath:"/docs/eip7702/signAuthorization"});const n=Ye(r);if(!n.signAuthorization)throw new Da({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});const s=await lb(e,t);return n.signAuthorization(s)}async function VA(e,{account:t=e.account,message:r}){if(!t)throw new Ds({docsPath:"/docs/actions/wallet/signMessage"});const n=Ye(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 qA(e,t){var f,u,l,p;const{account:r=e.account,chain:n=e.chain,...s}=t;if(!r)throw new Ds({docsPath:"/docs/actions/wallet/signTransaction"});const i=Ye(r);js({account:i,...t});const o=await se(e,$i,"getChainId")({});n!==null&&ag({currentChainId:o,chain:n});const a=(n==null?void 0:n.formatters)||((f=e.chain)==null?void 0:f.formatters),c=((u=a==null?void 0:a.transactionRequest)==null?void 0:u.format)||Ri;return i.signTransaction?i.signTransaction({...s,chainId:o},{serializer:(p=(l=e.chain)==null?void 0:l.serializers)==null?void 0:p.transaction}):await e.request({method:"eth_signTransaction",params:[{...c(s),chainId:Y(o),from:i.address}]},{retryCount:0})}async function GA(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=Ye(r),a={EIP712Domain:Cg({domain:n}),...t.types};if(Bg({domain:n,message:s,primaryType:i,types:a}),o.signTypedData)return o.signTypedData({domain:n,message:s,primaryType:i,types:a});const c=MS({domain:n,message:s,primaryType:i,types:a});return e.request({method:"eth_signTypedData_v4",params:[o.address,c]},{retryCount:0})}async function WA(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:Y(t)}]},{retryCount:0})}async function KA(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}function YA(e){return{addChain:t=>NA(e,t),deployContract:t=>MA(e,t),getAddresses:()=>UA(e),getCallsStatus:t=>pg(e,t),getCapabilities:t=>FA(e,t),getChainId:()=>$i(e),getPermissions:()=>jA(e),prepareAuthorization:t=>lb(e,t),prepareTransactionRequest:t=>Ic(e,t),requestAddresses:()=>LA(e),requestPermissions:t=>DA(e,t),sendCalls:t=>z6(e,t),sendRawTransaction:t=>jd(e,t),sendTransaction:t=>Nc(e,t),showCallsStatus:t=>HA(e,t),signAuthorization:t=>zA(e,t),signMessage:t=>VA(e,t),signTransaction:t=>qA(e,t),signTypedData:t=>GA(e,t),switchChain:t=>WA(e,t),waitForCallsStatus:t=>V6(e,t),watchAsset:t=>KA(e,t),writeContract:t=>ug(e,t)}}function Au(e){const{key:t="wallet",name:r="Wallet Client",transport:n}=e;return mg({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(YA)}const za={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:""},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:""},localnet:{orderbook:"",auth:"",quote:"",info:"",evmRelay:"",starknetRelay:"",solanaRelay:"",suiRelay:""}},Do={[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:""}},Bl={[v.Network.MAINNET]:"9cBuPNiHXiMNg3Fin8xLCGJQBTXjYQTFtyaFQv2uiM1H",[v.Network.TESTNET]:"ANUVKxeqaec3bf4DVPqLTnG1PT3Fng56wPcE7LXAb46Q",[v.Network.LOCALNET]:"AKnL4NNf3DGWZJS6cPknBuEGnVsV4A4m5tgebLHaRSZ9"},db={mainnet:"2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",staging:"6eksgdCnSjUaGQWZ6iYvauv1qzvYPF33RTGTM1ZuyENx"},_p={[v.Network.TESTNET]:{packageId:"0x9f1a9894237645834ed8830ef9884c334b352b3d9de852ff463825c02f76f855",moduleName:"AtomicSwap"},[v.Network.MAINNET]:{packageId:"0x9f1a9894237645834ed8830ef9884c334b352b3d9de852ff463825c02f76f855",moduleName:"AtomicSwap"},[v.Network.LOCALNET]:{packageId:"",moduleName:""}},Tp={chain:be.SupportedAssets.mainnet.base_cbBTC.chain,asset:be.SupportedAssets.mainnet.base_cbBTC.atomicSwapAddress};var fi=(e=>(e.SLOW="SLOW",e.MEDIUM="MEDIUM",e.FAST="FAST",e))(fi||{}),Ht=(e=>(e.Mainnet="Mainnet",e.Testnet="Testnet",e.Regtest="Regtest",e))(Ht||{}),Va=(e=>(e.ALL="ALL",e.IN="IN",e.OUT="OUT",e))(Va||{});const XA={SLOW:"economyFee",MEDIUM:"hourFee",FAST:"fastestFee"};function Cl(e){const t=typeof e=="string"?e:e.environment,r=t===v.Environment.MAINNET?za.mainnet:v.Environment.TESTNET?za.testnet:za.localnet;return{api:typeof e=="string"?r:{...r,...e},environment:t}}function Rl(e){return typeof e=="string"&&(e=Buffer.from(e,"hex")),e.length===32?e:e.subarray(1,33)}function Ys(e,t){if(!e)throw new Error(t)}function ZA(e){return Buffer.concat([Uint8Array.from([192]),JA(e)])}function JA(e){const t=Bh.encodingLength(e.length),r=Buffer.allocUnsafe(t);return Bh.encode(e.length,r),Buffer.concat([r,e])}function QA(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),e_=e=>{if(!e)return!1;try{const t=Buffer.from(e,"hex");return or.isPoint(t)}catch{return!1}},$l=(e,t,r,n)=>e+":"+t.toLowerCase()+"::"+r+":"+n.toLowerCase();function t_(e,t){if(!e)return!1;const r=t===v.Environment.MAINNET?Ae.networks.bitcoin:t===v.Environment.TESTNET?Ae.networks.testnet:Ae.networks.regtest;if(!r)return!1;Ae.initEccLib(or);try{return Ae.address.toOutputScript(e,r),!0}catch{return!1}}const r_=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}`)}},n_=e=>{const t=e.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(t)},s_=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")&&n_(r)?BigInt(r).toString():r);return v.Ok(t)}return v.Err("Invalid signature format")};function Nl(e){return Buffer.from(e,"hex").reverse()}function Ml(e){return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"}const kp=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 ✅"),!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 Kd=(e,t,r)=>{const n=Ul(e.source_swap,t),s=Ul(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:Ho(i,12)?ge.DeadLineExceeded:n===Ne.Initiated?ge.Initiated:Ho(i,1)?ge.DeadLineExceeded:n===Ne.InitiateDetected?ge.InitiateDetected:n===Ne.Redeemed?ge.CounterPartyRedeemed:n===Ne.RedeemDetected?ge.CounterPartyRedeemDetected:ge.Matched},Ul=(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},i_=(e,t,r)=>{const n=Kd(e,t,r);return Yd(n)},Yd=e=>{switch(e){case ge.Matched:return Se.Initiate;case ge.CounterPartyInitiated:case ge.CounterPartyInitiateDetected:case ge.RedeemDetected:return Se.Redeem;case ge.Expired:return Se.Refund;default:return Se.Idle}},Ho=(e,t=0)=>{const r=Date.now(),n=e*1e3+t*36e5;return r>=n},o_=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)?Ho(Number(i),12):n?!1:Ho(Number(i),1)},a_=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),c_=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),u_=Buffer.concat([a_,c_]),f_=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),Ip={failedToCreateInternalPubkey:"failed to create internal pubkey"};function l_(){const e=pe.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),t=or.pointMultiply(Buffer.concat([Buffer.from("04","hex"),u_]),e);if(!t)throw new Error(Ip.failedToCreateInternalPubkey);const r=or.pointAdd(f_,t);if(!r)throw new Error(Ip.failedToCreateInternalPubkey);return Rl(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={},bt={},Hs={},Dc={};Dc.byteLength=p_;Dc.toByteArray=m_;Dc.fromByteArray=w_;var Hr=[],er=[],d_=typeof Uint8Array<"u"?Uint8Array:Array,_u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var Xs=0,h_=_u.length;Xs<h_;++Xs)Hr[Xs]=_u[Xs],er[_u.charCodeAt(Xs)]=Xs;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 p_(e){var t=yb(e),r=t[0],n=t[1];return(r+n)*3/4-n}function y_(e,t,r){return(t+r)*3/4-r}function m_(e){var t,r=yb(e),n=r[0],s=r[1],i=new d_(y_(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 g_(e){return Hr[e>>18&63]+Hr[e>>12&63]+Hr[e>>6&63]+Hr[e&63]}function b_(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(g_(n));return s.join("")}function w_(e){for(var t,r=e.length,n=r%3,s=[],i=16383,o=0,a=r-n;o<a;o+=i)s.push(b_(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 Xd={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Xd.read=function(e,t,r,n,s){var i,o,a=s*8-n-1,c=(1<<a)-1,f=c>>1,u=-7,l=r?s-1:0,p=r?-1:1,d=e[t+l];for(l+=p,i=d&(1<<-u)-1,d>>=-u,u+=a;u>0;i=i*256+e[t+l],l+=p,u-=8);for(o=i&(1<<-u)-1,i>>=-u,u+=n;u>0;o=o*256+e[t+l],l+=p,u-=8);if(i===0)i=1-f;else{if(i===c)return o?NaN:(d?-1:1)*(1/0);o=o+Math.pow(2,n),i=i-f}return(d?-1:1)*o*Math.pow(2,i-n)};Xd.write=function(e,t,r,n,s,i){var o,a,c,f=i*8-s-1,u=(1<<f)-1,l=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+l>=1?t+=p/c:t+=p*Math.pow(2,1-l),t*c>=2&&(o++,c/=2),o+l>=u?(a=0,o=u):o+l>=1?(a=(t*c-1)*Math.pow(2,s),o=o+l):(a=t*Math.pow(2,l-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,f+=s;f>0;e[r+d]=o&255,d+=m,o/=256,f-=8);e[r+d-m]|=g*128};/*!
46
+ * The buffer module from node.js, for the browser.
47
+ *
48
+ * @author Feross Aboukhadijeh <https://feross.org>
49
+ * @license MIT
50
+ */(function(e){const t=Dc,r=Xd,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=a,e.SlowBuffer=k,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 l(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(vt(b,ArrayBuffer)||b&&vt(b.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(vt(b,SharedArrayBuffer)||b&&vt(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 f(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 f(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 l(b){return f(b),o(b<0?0:S(b)|0)}a.allocUnsafe=function(b){return l(b)},a.allocUnsafeSlow=function(b){return l(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:S(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(vt(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=S(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"||kn(b.length)?o(0):d(b);if(b.type==="Buffer"&&Array.isArray(b.data))return d(b.data)}function S(b){if(b>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return b|0}function k(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(vt(h,Uint8Array)&&(h=a.from(h,h.offset,h.byteLength)),vt(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,V=Math.min(x,C);M<V;++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 V=h[x];if(vt(V,Uint8Array))M+V.length>C.length?(a.isBuffer(V)||(V=a.from(V)),V.copy(C,M)):Uint8Array.prototype.set.call(C,V,M);else if(a.isBuffer(V))V.copy(C,M);else throw new TypeError('"list" argument must be an Array of Buffers');M+=V.length}return C};function E(b,h){if(a.isBuffer(b))return b.length;if(ArrayBuffer.isView(b)||vt(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 A(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 z(this,h,y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(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):A.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(vt(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 V=M-C,me=x-y;const ze=Math.min(V,me),$e=this.slice(C,M),Ve=h.slice(y,x);for(let Te=0;Te<ze;++Te)if($e[Te]!==Ve[Te]){V=$e[Te],me=Ve[Te];break}return V<me?-1:me<V?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,kn(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,V=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,V/=2,me/=2,y/=2}function ze(Ve,Te){return M===1?Ve[Te]:Ve.readUInt16BE(Te*M)}let $e;if(C){let Ve=-1;for($e=y;$e<V;$e++)if(ze(b,$e)===ze(h,Ve===-1?0:$e-Ve)){if(Ve===-1&&(Ve=$e),$e-Ve+1===me)return Ve*M}else Ve!==-1&&($e-=$e-Ve),Ve=-1}else for(y+me>V&&(y=V-me),$e=y;$e>=0;$e--){let Ve=!0;for(let Te=0;Te<me;Te++)if(ze(b,$e+Te)!==ze(h,Te)){Ve=!1;break}if(Ve)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 L(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 V;for(V=0;V<x;++V){const me=parseInt(h.substr(V*2,2),16);if(kn(me))return V;b[y+V]=me}return V}function T(b,h,y,x){return wt(Pr(h,b.length-y),b,y,x)}function U(b,h,y,x){return wt(ss(h),b,y,x)}function R(b,h,y,x){return wt(Or(h),b,y,x)}function F(b,h,y,x){return wt(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 V=!1;for(;;)switch(C){case"hex":return L(this,h,y,x);case"utf8":case"utf-8":return T(this,h,y,x);case"ascii":case"latin1":case"binary":return U(this,h,y,x);case"base64":return R(this,h,y,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return F(this,h,y,x);default:if(V)throw new TypeError("Unknown encoding: "+C);C=(""+C).toLowerCase(),V=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function z(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 V=null,me=M>239?4:M>223?3:M>191?2:1;if(C+me<=y){let ze,$e,Ve,Te;switch(me){case 1:M<128&&(V=M);break;case 2:ze=b[C+1],(ze&192)===128&&(Te=(M&31)<<6|ze&63,Te>127&&(V=Te));break;case 3:ze=b[C+1],$e=b[C+2],(ze&192)===128&&($e&192)===128&&(Te=(M&15)<<12|(ze&63)<<6|$e&63,Te>2047&&(Te<55296||Te>57343)&&(V=Te));break;case 4:ze=b[C+1],$e=b[C+2],Ve=b[C+3],(ze&192)===128&&($e&192)===128&&(Ve&192)===128&&(Te=(M&15)<<18|(ze&63)<<12|($e&63)<<6|Ve&63,Te>65535&&Te<1114112&&(V=Te))}}V===null?(V=65533,me=1):V>65535&&(V-=65536,x.push(V>>>10&1023|55296),V=56320|V&1023),x.push(V),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 q(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,V=0;for(;++V<y&&(M*=256);)C+=this[h+V]*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,V=0;for(;++V<y&&(M*=256);)C+=this[h+V]*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,V=this[h+--C];for(;C>0&&(M*=256);)V+=this[h+--C]*M;return M*=128,V>=M&&(V-=Math.pow(2,8*y)),V},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,V=0;for(this[y]=h&255;++V<x&&(M*=256);)this[y+V]=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,V=1;for(this[y+M]=h&255;--M>=0&&(V*=256);)this[y+M]=h/V&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 V=Number(h>>BigInt(32)&BigInt(4294967295));return b[y++]=V,V=V>>8,b[y++]=V,V=V>>8,b[y++]=V,V=V>>8,b[y++]=V,y}function j(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 V=Number(h>>BigInt(32)&BigInt(4294967295));return b[y+3]=V,V=V>>8,b[y+2]=V,V=V>>8,b[y+1]=V,V=V>>8,b[y]=V,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 j(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,V=1,me=0;for(this[y]=h&255;++M<x&&(V*=256);)h<0&&me===0&&this[y+M-1]!==0&&(me=1),this[y+M]=(h/V>>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,V=1,me=0;for(this[y+M]=h&255;--M>=0&&(V*=256);)h<0&&me===0&&this[y+M+1]!==0&&(me=1),this[y+M]=(h/V>>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 j(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 le(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 le(this,h,y,!0,x)},a.prototype.writeDoubleBE=function(h,y,x){return le(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 V=h.charCodeAt(0);(C==="utf8"&&V<128||C==="latin1")&&(h=V)}}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 V=a.isBuffer(h)?h:a.from(h,C),me=V.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]=V[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 V=typeof h=="bigint"?"n":"";let me;throw h===0||h===BigInt(0)?me=`>= 0${V} and < 2${V} ** ${(M+1)*8}${V}`:me=`>= -(2${V} ** ${(M+1)*8-1}${V}) and < 2 ** ${(M+1)*8-1}${V}`,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 V=0;V<x;++V){if(y=b.charCodeAt(V),y>55295&&y<57344){if(!C){if(y>56319){(h-=3)>-1&&M.push(239,191,189);continue}else if(V+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 ss(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 V=0;V<b.length&&!((h-=2)<0);++V)y=b.charCodeAt(V),x=y>>8,C=y%256,M.push(C),M.push(x);return M}function Or(b){return t.toByteArray(Qe(b))}function wt(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 vt(b,h){return b instanceof h||b!=null&&b.constructor!=null&&b.constructor.name!=null&&b.constructor.name===h.name}function kn(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"?j1:b}function j1(){throw new Error("BigInt not supported")}})(Hs);var zo={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}};zo.Null=zo.Nil;for(var Pp in zo)zo[Pp].toJSON=(function(e){return e}).bind(null,Pp);var Zd=zo,vs=Zd;function mb(e){return e.name||e.toString().match(/function (.*?)\s*\(/)[1]}function Jd(e){return vs.Nil(e)?"":mb(e.constructor)}function v_(e){return vs.Function(e)?"":vs.String(e)?JSON.stringify(e):e&&vs.Object(e)?"":e}function Qd(e,t){Error.captureStackTrace&&Error.captureStackTrace(e,t)}function ic(e){return vs.Function(e)?e.toJSON?e.toJSON():mb(e):vs.Array(e)?"Array":e&&vs.Object(e)?"Object":e!==void 0?e:""}function gb(e,t,r){var n=v_(t);return"Expected "+ic(e)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function En(e,t,r){r=r||Jd(t),this.message=gb(e,t,r),Qd(this,En),this.__type=e,this.__value=t,this.__valueTypeName=r}En.prototype=Object.create(Error.prototype);En.prototype.constructor=En;function E_(e,t,r,n,s){var i='" of type ';return t==="key"&&(i='" with key type '),gb('property "'+ic(r)+i+ic(e),n,s)}function li(e,t,r,n,s){e?(s=s||Jd(n),this.message=E_(e,r,t,n,s)):this.message='Unexpected property "'+t+'"',Qd(this,En),this.__label=r,this.__property=t,this.__type=e,this.__value=n,this.__valueTypeName=s}li.prototype=Object.create(Error.prototype);li.prototype.constructor=En;function S_(e,t){return new En(e,{},t)}function x_(e,t,r){return e instanceof li?(t=t+"."+e.__property,e=new li(e.__type,t,e.__label,e.__value,e.__valueTypeName)):e instanceof En&&(e=new li(e.__type,t,r,e.__value,e.__valueTypeName)),Qd(e),e}var bb={TfTypeError:En,TfPropertyTypeError:li,tfCustomError:S_,tfSubError:x_,tfJSON:ic,getValueTypeName:Jd},Tu,Op;function A_(){if(Op)return Tu;Op=1;var e=Zd,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 L=P.toJSON();function T(U){if(!P(U))return!1;if(U.length===$)return!0;throw t.tfCustomError(L+"(Length: "+$+")",L+"(Length: "+U.length+")")}return T.toJSON=function(){return L},T}var i=s.bind(null,e.Array),o=s.bind(null,r),a=s.bind(null,n),c=s.bind(null,e.String);function f(P,$,L){L=L||e.Number;function T(U,R){return L(U,R)&&U>P&&U<$}return T.toJSON=function(){return`${L.toJSON()} between [${P}, ${$}]`},T}var u=Math.pow(2,53)-1;function l(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 S(P){return(P&65535)===P}function k(P){return P>>>0===P}function E(P){return typeof P=="number"&&P>=0&&P<=u&&Math.floor(P)===P}var A={ArrayN:i,Buffer:r,BufferN:o,Finite:l,Hex:n,HexN:a,Int8:p,Int16:d,Int32:m,Int53:g,Range:f,StringN:c,UInt8:w,UInt16:S,UInt32:k,UInt53:E};for(var I in A)A[I].toJSON=(function(P){return P}).bind(null,I);return Tu=A,Tu}var ua=bb,at=Zd,Qr=ua.tfJSON,wb=ua.TfTypeError,vb=ua.TfPropertyTypeError,zi=ua.tfSubError,__=ua.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 zi(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 zi(c,o,"key")}try{var a=s[o];Tt(t,a,i)}catch(c){throw zi(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],f=i[a];Tt(c,f,o)}}catch(u){throw zi(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===__(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 zi(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 Yn in at)Tt[Yn]=at[Yn];for(Yn in dn)Tt[Yn]=dn[Yn];var Bp=A_();for(Yn in Bp)Tt[Yn]=Bp[Yn];Tt.compile=Lr;Tt.TfTypeError=wb;Tt.TfPropertyTypeError=vb;var T_=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=T_;const r=t.Buffer.alloc(32,0),n=t.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function s(u,l){return u.length!==l.length?!1:u.every((p,d)=>p.equals(l[d]))}e.stacksEqual=s;function i(u){if(!t.Buffer.isBuffer(u)||u.length<33)return!1;const l=u[0],p=u.slice(1,33);if(p.compare(r)===0||p.compare(n)>=0)return!1;if((l===2||l===3)&&u.length===33)return!0;const d=u.slice(33);return d.compare(r)===0||d.compare(n)>=0?!1:l===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 f(u){return(0,e.Array)(u)?u.length!==2?!1:u.every(l=>f(l)):c(u)}e.isTaptree=f,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})(bt);var fa={},ct={};Object.defineProperty(ct,"__esModule",{value:!0});ct.BufferReader=ct.BufferWriter=ct.cloneBuffer=ct.reverseBuffer=ct.writeUInt64LE=ct.readUInt64LE=ct.varuint=void 0;const Es=bt,{typeforce:Eb}=Es,Vo=Em;ct.varuint=Vo;function Sb(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,Sb(n+r,9007199254740991),n+r}ct.readUInt64LE=xb;function Ab(e,t,r){return Sb(t,9007199254740991),e.writeInt32LE(t&-1,r),e.writeUInt32LE(Math.floor(t/4294967296),r+4),r+8}ct.writeUInt64LE=Ab;function k_(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=k_;function I_(e){const t=Buffer.allocUnsafe(e.length);return e.copy(t),t}ct.cloneBuffer=I_;class eh{static withCapacity(t){return new eh(Buffer.alloc(t))}constructor(t,r=0){this.buffer=t,this.offset=r,Eb(Es.tuple(Es.Buffer,Es.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=Ab(this.buffer,t,this.offset)}writeVarInt(t){Vo.encode(t,this.buffer,this.offset),this.offset+=Vo.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=eh;class P_{constructor(t,r=0){this.buffer=t,this.offset=r,Eb(Es.tuple(Es.Buffer,Es.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=Vo.decode(this.buffer,this.offset);return this.offset+=Vo.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=P_;var ns={};const O_=pb(sx);var Ei={},Bt={},It={},th={},Hc={};Object.defineProperty(Hc,"__esModule",{value:!0});Hc.crypto=void 0;Hc.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=f,e.clean=u,e.createView=l,e.rotr=p,e.rotl=d,e.byteSwap=m,e.byteSwap32=g,e.bytesToHex=k,e.hexToBytes=I,e.asyncLoop=$,e.utf8ToBytes=L,e.bytesToUtf8=T,e.toBytes=U,e.kdfInputToBytes=R,e.concatBytes=F,e.checkOpts=z,e.createHasher=Z,e.createOptHasher=Q,e.createXOFer=re,e.randomBytes=D;const t=Hc;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,...q){if(!r(B))throw new Error("Uint8Array expected");if(q.length>0&&!q.includes(B.length))throw new Error("Uint8Array expected of length "+q+", 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,q=!0){if(B.destroyed)throw new Error("Hash instance has been destroyed");if(q&&B.finished)throw new Error("Hash#digest() has already been called")}function a(B,q){s(B);const K=q.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 f(B){return new Uint32Array(B.buffer,B.byteOffset,Math.floor(B.byteLength/4))}function u(...B){for(let q=0;q<B.length;q++)B[q].fill(0)}function l(B){return new DataView(B.buffer,B.byteOffset,B.byteLength)}function p(B,q){return B<<32-q|B>>>q}function d(B,q){return B<<q|B>>>32-q>>>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 q=0;q<B.length;q++)B[q]=m(B[q]);return B}e.swap32IfBE=e.isLE?B=>B:g;const w=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",S=Array.from({length:256},(B,q)=>q.toString(16).padStart(2,"0"));function k(B){if(s(B),w)return B.toHex();let q="";for(let K=0;K<B.length;K++)q+=S[B[K]];return q}const E={_0:48,_9:57,A:65,F:70,a:97,f:102};function A(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 q=B.length,K=q/2;if(q%2)throw new Error("hex string expected, got unpadded hex of length "+q);const O=new Uint8Array(K);for(let N=0,j=0;N<K;N++,j+=2){const J=A(B.charCodeAt(j)),ne=A(B.charCodeAt(j+1));if(J===void 0||ne===void 0){const le=B[j]+B[j+1];throw new Error('hex string expected, got non-hex character "'+le+'" at index '+j)}O[N]=J*16+ne}return O}const P=async()=>{};e.nextTick=P;async function $(B,q,K){let O=Date.now();for(let N=0;N<B;N++){K(N);const j=Date.now()-O;j>=0&&j<q||(await(0,e.nextTick)(),O+=j)}}function L(B){if(typeof B!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(B))}function T(B){return new TextDecoder().decode(B)}function U(B){return typeof B=="string"&&(B=L(B)),s(B),B}function R(B){return typeof B=="string"&&(B=L(B)),s(B),B}function F(...B){let q=0;for(let O=0;O<B.length;O++){const N=B[O];s(N),q+=N.length}const K=new Uint8Array(q);for(let O=0,N=0;O<B.length;O++){const j=B[O];K.set(j,N),N+=j.length}return K}function z(B,q){if(q!==void 0&&{}.toString.call(q)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(B,q)}class W{}e.Hash=W;function Z(B){const q=O=>B().update(U(O)).digest(),K=B();return q.outputLen=K.outputLen,q.blockLen=K.blockLen,q.create=()=>B(),q}function Q(B){const q=(O,N)=>B(N).update(U(O)).digest(),K=B({});return q.outputLen=K.outputLen,q.blockLen=K.blockLen,q.create=O=>B(O),q}function re(B){const q=(O,N)=>B(N).update(U(O)).digest(),K=B({});return q.outputLen=K.outputLen,q.blockLen=K.blockLen,q.create=O=>B(O),q}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")}})(th);Object.defineProperty(It,"__esModule",{value:!0});It.SHA512_IV=It.SHA384_IV=It.SHA224_IV=It.SHA256_IV=It.HashMD=void 0;It.setBigUint64=_b;It.Chi=B_;It.Maj=C_;const Rr=th;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,f=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+f,a,n)}function B_(e,t,r){return e&t^~e&r}function C_(e,t,r){return e&t^e&r^t&r}class R_ 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 l=o;l<s;l++)r[l]=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 f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<f;l++)a.setUint32(4*l,u[l],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()}}It.HashMD=R_;It.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);It.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);It.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);It.SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);Object.defineProperty(Bt,"__esModule",{value:!0});Bt.ripemd160=Bt.RIPEMD160=Bt.md5=Bt.MD5=Bt.sha1=Bt.SHA1=void 0;const Ss=It,ut=th,Js=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Cn=new Uint32Array(80);class Tb extends Ss.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 f,u;c<20?(f=(0,Ss.Chi)(s,i,o),u=1518500249):c<40?(f=s^i^o,u=1859775393):c<60?(f=(0,Ss.Maj)(s,i,o),u=2400959708):(f=s^i^o,u=3395469782);const l=(0,ut.rotl)(n,5)+f+a+u+Cn[c]|0;a=o,o=i,i=(0,ut.rotl)(s,30),s=n,n=l}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)}}Bt.SHA1=Tb;Bt.sha1=(0,ut.createHasher)(()=>new Tb);const $_=Math.pow(2,32),N_=Array.from({length:64},(e,t)=>Math.floor($_*Math.abs(Math.sin(t+1)))),Ta=Js.slice(0,4),ku=new Uint32Array(16);class kb extends Ss.HashMD{constructor(){super(64,16,8,!0),this.A=Ta[0]|0,this.B=Ta[1]|0,this.C=Ta[2]|0,this.D=Ta[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)ku[a]=t.getUint32(r,!0);let{A:n,B:s,C:i,D:o}=this;for(let a=0;a<64;a++){let c,f,u;a<16?(c=(0,Ss.Chi)(s,i,o),f=a,u=[7,12,17,22]):a<32?(c=(0,Ss.Chi)(o,s,i),f=(5*a+1)%16,u=[5,9,14,20]):a<48?(c=s^i^o,f=(3*a+5)%16,u=[4,11,16,23]):(c=i^(s|~o),f=7*a%16,u=[6,10,15,21]),c=c+n+N_[a]+ku[f],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)(ku)}destroy(){this.set(0,0,0,0),(0,ut.clean)(this.buffer)}}Bt.MD5=kb;Bt.md5=(0,ut.createHasher)(()=>new kb);const M_=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)),U_=Ib.map(e=>(9*e+5)%16),Pb=(()=>{const r=[[Ib],[U_]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>M_[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)),F_=Ob.map((e,t)=>e.map(r=>Cb[t][r])),j_=Bb.map((e,t)=>e.map(r=>Cb[t][r])),L_=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),D_=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 ka=new Uint32Array(16);class Rb extends Ss.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)ka[d]=t.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,o=i,a=this.h2|0,c=a,f=this.h3|0,u=f,l=this.h4|0,p=l;for(let d=0;d<5;d++){const m=4-d,g=L_[d],w=D_[d],S=Ob[d],k=Bb[d],E=F_[d],A=j_[d];for(let I=0;I<16;I++){const P=(0,ut.rotl)(n+Cp(d,i,a,f)+ka[S[I]]+g,E[I])+l|0;n=l,l=f,f=(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)+ka[k[I]]+w,A[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+f+p|0,this.h3+l+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){(0,ut.clean)(ka)}destroy(){this.destroyed=!0,(0,ut.clean)(this.buffer),this.set(0,0,0,0,0)}}Bt.RIPEMD160=Rb;Bt.ripemd160=(0,ut.createHasher)(()=>new Rb);Object.defineProperty(Ei,"__esModule",{value:!0});Ei.sha1=Ei.SHA1=void 0;const $b=Bt;Ei.SHA1=$b.SHA1;Ei.sha1=$b.sha1;const Nb=pb(VE);(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=O_,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 f(u,l){return o(Buffer.concat([e.TAGGED_HASH_PREFIXES[u],l]))}e.taggedHash=f})(ns);var Iu={},bn={};Object.defineProperty(bn,"__esModule",{value:!0});bn.encode=bn.decode=bn.check=void 0;function H_(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=H_;function z_(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=z_;function V_(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=V_;var Rs={};Object.defineProperty(Rs,"__esModule",{value:!0});Rs.REVERSE_OPS=Rs.OPS=void 0;const Fl={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};Rs.OPS=Fl;const Mb={};Rs.REVERSE_OPS=Mb;for(const e of Object.keys(Fl)){const t=Fl[e];Mb[t]=e}var Xn={};Object.defineProperty(Xn,"__esModule",{value:!0});Xn.decode=Xn.encode=Xn.encodingLength=void 0;const Gn=Rs;function Ub(e){return e<Gn.OPS.OP_PUSHDATA1?1:e<=255?2:e<=65535?3:5}Xn.encodingLength=Ub;function q_(e,t,r){const n=Ub(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}Xn.encode=q_;function G_(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}}Xn.decode=G_;var Si={};Object.defineProperty(Si,"__esModule",{value:!0});Si.encode=Si.decode=void 0;function W_(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}Si.decode=W_;function K_(e){return e>2147483647?5:e>8388607?4:e>32767?3:e>127?2:e>0?1:0}function Y_(e){let t=Math.abs(e);const r=K_(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}Si.encode=Y_;var is={},Rp;function X_(){if(Rp)return is;Rp=1,Object.defineProperty(is,"__esModule",{value:!0}),is.encode=is.decode=void 0;const e=bn,t=Xt(),r=bt,{typeforce:n}=r,s=Buffer.alloc(1,0);function i(f){let u=0;for(;f[u]===0;)++u;return u===f.length?s:(f=f.slice(u),f[0]&128?Buffer.concat([s,f],1+f.length):f)}function o(f){f[0]===0&&(f=f.slice(1));const u=Buffer.alloc(32,0),l=Math.max(0,32-f.length);return f.copy(u,l),u}function a(f){const u=f.readUInt8(f.length-1);if(!(0,t.isDefinedHashType)(u))throw new Error("Invalid hashType "+u);const l=e.decode(f.slice(0,-1)),p=o(l.r),d=o(l.s);return{signature:Buffer.concat([p,d],64),hashType:u}}is.decode=a;function c(f,u){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:f,hashType:u}),!(0,t.isDefinedHashType)(u))throw new Error("Invalid hashType "+u);const l=Buffer.allocUnsafe(1);l.writeUInt8(u,0);const p=i(f.slice(0,32)),d=i(f.slice(32,64));return Buffer.concat([e.encode(p,d),l])}return is.encode=c,is}var $p;function Xt(){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=Rs;Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=Xn,s=Si,i=X_(),o=bt,{typeforce:a}=o,c=r.OPS.OP_RESERVED;function f(T){return o.Number(T)&&(T===r.OPS.OP_0||T>=r.OPS.OP_1&&T<=r.OPS.OP_16||T===r.OPS.OP_1NEGATE)}function u(T){return o.Buffer(T)||f(T)}function l(T){return o.Array(T)&&T.every(u)}e.isPushOnly=l;function p(T){return T.length-T.filter(u).length}e.countNonPushOnlyOPs=p;function d(T){if(T.length===0)return r.OPS.OP_0;if(T.length===1){if(T[0]>=1&&T[0]<=16)return c+T[0];if(T[0]===129)return r.OPS.OP_1NEGATE}}function m(T){return Buffer.isBuffer(T)}function g(T){return o.Array(T)}function w(T){return Buffer.isBuffer(T)}function S(T){if(m(T))return T;a(o.Array,T);const U=T.reduce((z,W)=>w(W)?W.length===1&&d(W)!==void 0?z+1:z+n.encodingLength(W.length)+W.length:z+1,0),R=Buffer.allocUnsafe(U);let F=0;if(T.forEach(z=>{if(w(z)){const W=d(z);if(W!==void 0){R.writeUInt8(W,F),F+=1;return}F+=n.encode(R,z.length,F),z.copy(R,F),F+=z.length}else R.writeUInt8(z,F),F+=1}),F!==R.length)throw new Error("Could not decode chunks");return R}e.compile=S;function k(T){if(g(T))return T;a(o.Buffer,T);const U=[];let R=0;for(;R<T.length;){const F=T[R];if(F>r.OPS.OP_0&&F<=r.OPS.OP_PUSHDATA4){const z=n.decode(T,R);if(z===null||(R+=z.size,R+z.number>T.length))return null;const W=T.slice(R,R+z.number);R+=z.number;const Z=d(W);Z!==void 0?U.push(Z):U.push(W)}else U.push(F),R+=1}return U}e.decompile=k;function E(T){if(m(T)&&(T=k(T)),!T)throw new Error("Could not convert invalid chunks to ASM");return T.map(U=>{if(w(U)){const R=d(U);if(R===void 0)return U.toString("hex");U=R}return r.REVERSE_OPS[U]}).join(" ")}e.toASM=E;function A(T){return a(o.String,T),S(T.split(" ").map(U=>r.OPS[U]!==void 0?r.OPS[U]:(a(o.Hex,U),Buffer.from(U,"hex"))))}e.fromASM=A;function I(T){return T=k(T),a(l,T),T.map(U=>w(U)?U:U===r.OPS.OP_0?Buffer.allocUnsafe(0):s.encode(U-c))}e.toStack=I;function P(T){return o.isPoint(T)}e.isCanonicalPubKey=P;function $(T){const U=T&-129;return U>0&&U<4}e.isDefinedHashType=$;function L(T){return!Buffer.isBuffer(T)||!$(T[T.length-1])?!1:t.check(T.slice(0,-1))}e.isCanonicalScriptSignature=L,e.number=s,e.signature=i}(Iu)),Iu}Object.defineProperty(fa,"__esModule",{value:!0});fa.Transaction=void 0;const Xe=ct,Et=ns,Np=Xt(),Z_=Xt(),we=bt,{typeforce:$r}=we;function Fr(e){const t=e.length;return Xe.varuint.encodingLength(t)+t}function J_(e){const t=e.length;return Xe.varuint.encodingLength(t)+e.reduce((r,n)=>r+Fr(n),0)}const jn=Buffer.allocUnsafe(0),Pu=[],Ou=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),Mp=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),Q_=Buffer.from("ffffffffffffffff","hex"),eT={script:jn,valueBuffer:Q_};function tT(e){return e.value!==void 0}let Ir=class ke{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(t,r){const n=new Xe.BufferReader(t),s=new ke;s.version=n.readInt32();const i=n.readUInt8(),o=n.readUInt8();let a=!1;i===ke.ADVANCED_TRANSACTION_MARKER&&o===ke.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:Pu});const f=n.readVarInt();for(let u=0;u<f;++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 ke.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&&ke.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=ke.DEFAULT_SEQUENCE),this.ins.push({hash:t,index:r,script:s||jn,sequence:n,witness:Pu})-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=Pu})}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)+Xe.varuint.encodingLength(this.ins.length)+Xe.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+J_(s.witness),0):0)}clone(){const t=new ke;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 Mp;const s=Np.compile(Np.decompile(r).filter(a=>a!==Z_.OPS.OP_CODESEPARATOR)),i=this.clone();if((n&31)===ke.SIGHASH_NONE)i.outs=[],i.ins.forEach((a,c)=>{c!==t&&(a.sequence=0)});else if((n&31)===ke.SIGHASH_SINGLE){if(t>=this.outs.length)return Mp;i.outs.length=t+1;for(let a=0;a<t;a++)i.outs[a]=eT;i.ins.forEach((a,c)=>{c!==t&&(a.sequence=0)})}n&ke.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),Et.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===ke.SIGHASH_DEFAULT?ke.SIGHASH_ALL:s&ke.SIGHASH_OUTPUT_MASK,f=(s&ke.SIGHASH_INPUT_MASK)===ke.SIGHASH_ANYONECANPAY,u=a===ke.SIGHASH_NONE,l=a===ke.SIGHASH_SINGLE;let p=jn,d=jn,m=jn,g=jn,w=jn;if(!f){let A=Xe.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(I=>{A.writeSlice(I.hash),A.writeUInt32(I.index)}),p=Et.sha256(A.end()),A=Xe.BufferWriter.withCapacity(8*this.ins.length),n.forEach(I=>A.writeUInt64(I)),d=Et.sha256(A.end()),A=Xe.BufferWriter.withCapacity(r.map(Fr).reduce((I,P)=>I+P)),r.forEach(I=>A.writeVarSlice(I)),m=Et.sha256(A.end()),A=Xe.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(I=>A.writeUInt32(I.sequence)),g=Et.sha256(A.end())}if(u||l){if(l&&t<this.outs.length){const A=this.outs[t],I=Xe.BufferWriter.withCapacity(8+Fr(A.script));I.writeUInt64(A.value),I.writeVarSlice(A.script),w=Et.sha256(I.end())}}else{const A=this.outs.map(P=>8+Fr(P.script)).reduce((P,$)=>P+$),I=Xe.BufferWriter.withCapacity(A);this.outs.forEach(P=>{I.writeUInt64(P.value),I.writeVarSlice(P.script)}),w=Et.sha256(I.end())}const S=(i?2:0)+(o?1:0),k=174-(f?49:0)-(u?32:0)+(o?32:0)+(i?37:0),E=Xe.BufferWriter.withCapacity(k);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||l||E.writeSlice(w),E.writeUInt8(S),f){const A=this.ins[t];E.writeSlice(A.hash),E.writeUInt32(A.index),E.writeUInt64(n[t]),E.writeVarSlice(r[t]),E.writeUInt32(A.sequence)}else E.writeUInt32(t);if(o){const A=Xe.BufferWriter.withCapacity(Fr(o));A.writeVarSlice(o),E.writeSlice(Et.sha256(A.end()))}return l&&E.writeSlice(w),i&&(E.writeSlice(i),E.writeUInt8(0),E.writeUInt32(4294967295)),Et.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=Ou,c=Ou,f=Ou;if(s&ke.SIGHASH_ANYONECANPAY||(i=Buffer.allocUnsafe(36*this.ins.length),o=new Xe.BufferWriter(i,0),this.ins.forEach(l=>{o.writeSlice(l.hash),o.writeUInt32(l.index)}),c=Et.hash256(i)),!(s&ke.SIGHASH_ANYONECANPAY)&&(s&31)!==ke.SIGHASH_SINGLE&&(s&31)!==ke.SIGHASH_NONE&&(i=Buffer.allocUnsafe(4*this.ins.length),o=new Xe.BufferWriter(i,0),this.ins.forEach(l=>{o.writeUInt32(l.sequence)}),f=Et.hash256(i)),(s&31)!==ke.SIGHASH_SINGLE&&(s&31)!==ke.SIGHASH_NONE){const l=this.outs.reduce((p,d)=>p+8+Fr(d.script),0);i=Buffer.allocUnsafe(l),o=new Xe.BufferWriter(i,0),this.outs.forEach(p=>{o.writeUInt64(p.value),o.writeVarSlice(p.script)}),a=Et.hash256(i)}else if((s&31)===ke.SIGHASH_SINGLE&&t<this.outs.length){const l=this.outs[t];i=Buffer.allocUnsafe(8+Fr(l.script)),o=new Xe.BufferWriter(i,0),o.writeUInt64(l.value),o.writeVarSlice(l.script),a=Et.hash256(i)}i=Buffer.allocUnsafe(156+Fr(r)),o=new Xe.BufferWriter(i,0);const u=this.ins[t];return o.writeInt32(this.version),o.writeSlice(c),o.writeSlice(f),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),Et.hash256(i)}getHash(t){return t&&this.isCoinbase()?Buffer.alloc(32,0):Et.hash256(this.__toBuffer(void 0,void 0,t))}getId(){return(0,Xe.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 Xe.BufferWriter(t,r||0);s.writeInt32(this.version);const i=n&&this.hasWitnesses();return i&&(s.writeUInt8(ke.ADVANCED_TRANSACTION_MARKER),s.writeUInt8(ke.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=>{tT(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}};fa.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={},la={};Object.defineProperty(la,"__esModule",{value:!0});const rT=9007199254740991;function rh(e){if(e<0||e>rT||e%1!==0)throw new RangeError("value out of range")}function Qi(e,t,r){if(rh(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(Qi,{bytes:1})):e<=65535?(t.writeUInt8(253,r),t.writeUInt16LE(e,r+1),Object.assign(Qi,{bytes:3})):e<=4294967295?(t.writeUInt8(254,r),t.writeUInt32LE(e,r+1),Object.assign(Qi,{bytes:5})):(t.writeUInt8(255,r),t.writeUInt32LE(e>>>0,r+1),t.writeUInt32LE(e/4294967296|0,r+5),Object.assign(Qi,{bytes:9})),t}la.encode=Qi;function eo(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(eo,{bytes:1}),r;if(r===253)return Object.assign(eo,{bytes:3}),e.readUInt16LE(t+1);if(r===254)return Object.assign(eo,{bytes:5}),e.readUInt32LE(t+1);{Object.assign(eo,{bytes:9});const n=e.readUInt32LE(t+1),i=e.readUInt32LE(t+5)*4294967296+n;return rh(i),i}}la.decode=eo;function Fb(e){return rh(e),e<253?1:e<=65535?3:e<=4294967295?5:9}la.encodingLength=Fb;var Bu={},zc={},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};gt.regtest={messagePrefix:`Bitcoin Signed Message:
52
+ `,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};gt.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 nT(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=nT;function sT(e){let t;return()=>(t!==void 0||(t=e()),t)}Gt.value=sT;Object.defineProperty(zc,"__esModule",{value:!0});zc.p2data=void 0;const iT=gt,qa=Xt(),Nr=bt,Up=Gt,Fp=qa.OPS;function oT(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||iT.bitcoin};if(Up.prop(n,"output",()=>{if(e.data)return qa.compile([Fp.OP_RETURN].concat(e.data))}),Up.prop(n,"data",()=>{if(e.output)return qa.decompile(e.output).slice(1)}),t.validate&&e.output){const s=qa.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)}zc.p2data=oT;var Vc={};Object.defineProperty(Vc,"__esModule",{value:!0});Vc.p2ms=void 0;const aT=gt,Qs=Xt(),We=bt,Rn=Gt,ei=Qs.OPS,Ia=ei.OP_RESERVED;function cT(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||aT.bitcoin};let i=[],o=!1;function a(c){o||(o=!0,i=Qs.decompile(c),s.m=i[0]-Ia,s.n=i[i.length-2]-Ia,s.pubkeys=i.slice(1,-2))}if(Rn.prop(s,"output",()=>{if(e.m&&s.n&&e.pubkeys)return Qs.compile([].concat(Ia+e.m,e.pubkeys,Ia+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)}Vc.p2ms=cT;var qc={};Object.defineProperty(qc,"__esModule",{value:!0});qc.p2pk=void 0;const uT=gt,ti=Xt(),dr=bt,Zs=Gt,jp=ti.OPS;function fT(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,dr.typeforce)({network:dr.typeforce.maybe(dr.typeforce.Object),output:dr.typeforce.maybe(dr.typeforce.Buffer),pubkey:dr.typeforce.maybe(dr.isPoint),signature:dr.typeforce.maybe(ti.isCanonicalScriptSignature),input:dr.typeforce.maybe(dr.typeforce.Buffer)},e);const r=Zs.value(()=>ti.decompile(e.input)),s={name:"p2pk",network:e.network||uT.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,dr.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)}qc.p2pk=fT;var Gc={};function lT(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),f=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,S=d.length;w!==S&&d[w]===0;)w++,m++;for(var k=(S-w)*f+1>>>0,E=new Uint8Array(k);w!==S;){for(var A=d[w],I=0,P=k-1;(A!==0||I<g)&&P!==-1;P--,I++)A+=256*E[P]>>>0,E[P]=A%o>>>0,A=A/o>>>0;if(A!==0)throw new Error("Non-zero carry");g=I,w++}for(var $=k-g;$!==k&&E[$]===0;)$++;for(var L=a.repeat(m);$<k;++$)L+=e.charAt(E[$]);return L}function l(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 S=(d.length-m)*c+1>>>0,k=new Uint8Array(S);d[m];){var E=d.charCodeAt(m);if(E>255)return;var A=t[E];if(A===255)return;for(var I=0,P=S-1;(A!==0||I<w)&&P!==-1;P--,I++)A+=o*k[P]>>>0,k[P]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");w=I,m++}for(var $=S-w;$!==S&&k[$]===0;)$++;for(var L=new Uint8Array(g+(S-$)),T=g;$!==S;)L[T++]=k[$++];return L}function p(d){var m=l(d);if(m)return m;throw new Error("Non-base"+o+" character")}return{encode:u,decodeUnsafe:l,decode:p}}var dT=lT;const hT=dT,pT="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var yT=hT(pT),Cu=yT,mT=function(e){function t(i){var o=Uint8Array.from(i),a=e(o),c=o.length+4,f=new Uint8Array(c);return f.set(o,0),f.set(a.subarray(0,4),o.length),Cu.encode(f,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=Cu.decodeUnsafe(i);if(o)return r(o)}function s(i){var o=Cu.decode(i),a=r(o);if(!a)throw new Error("Invalid checksum");return a}return{encode:t,decode:s,decodeUnsafe:n}},{sha256:Lp}=Nb,gT=mT;function bT(e){return Lp(Lp(e))}var nh=gT(bT);Object.defineProperty(Gc,"__esModule",{value:!0});Gc.p2pkh=void 0;const Ru=ns,wT=gt,ri=Xt(),St=bt,en=Gt,Dp=nh,$n=ri.OPS;function vT(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,St.typeforce)({network:St.typeforce.maybe(St.typeforce.Object),address:St.typeforce.maybe(St.typeforce.String),hash:St.typeforce.maybe(St.typeforce.BufferN(20)),output:St.typeforce.maybe(St.typeforce.BufferN(25)),pubkey:St.typeforce.maybe(St.isPoint),signature:St.typeforce.maybe(ri.isCanonicalScriptSignature),input:St.typeforce.maybe(St.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||wT.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 Ru.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=Ru.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,St.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=Ru.hash160(a[1]);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch")}}return Object.assign(i,e)}Gc.p2pkh=vT;var Wc={};Object.defineProperty(Wc,"__esModule",{value:!0});Wc.p2sh=void 0;const Hp=ns,ET=gt,jr=Xt(),Ce=bt,Mr=Gt,zp=nh,Vi=jr.OPS;function ST(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||ET.bitcoin);const n={network:r},s=Mr.value(()=>{const a=Buffer.from(zp.decode(e.address)),c=a.readUInt8(0),f=a.slice(1);return{version:c,hash:f}}),i=Mr.value(()=>jr.decompile(e.input)),o=Mr.value(()=>{const a=i(),c=a[a.length-1];return{network:r,output:c===Vi.OP_FALSE?Buffer.from([]):c,input:jr.compile(a.slice(0,-1)),witness:e.witness||[]}});if(Mr.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)}),Mr.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)}),Mr.prop(n,"output",()=>{if(n.hash)return jr.compile([Vi.OP_HASH160,n.hash,Vi.OP_EQUAL])}),Mr.prop(n,"redeem",()=>{if(e.input)return o()}),Mr.prop(n,"input",()=>{if(!(!e.redeem||!e.redeem.input||!e.redeem.output))return jr.compile([].concat(jr.decompile(e.redeem.input),e.redeem.output))}),Mr.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),Mr.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]!==Vi.OP_HASH160||e.output[1]!==20||e.output[22]!==Vi.OP_EQUAL)throw new TypeError("Output is invalid");const f=e.output.slice(2,22);if(a.length>0&&!a.equals(f))throw new TypeError("Hash mismatch");a=f}const c=f=>{if(f.output){const u=jr.decompile(f.output);if(!u||u.length<1)throw new TypeError("Redeem.output too short");if(f.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 l=Hp.hash160(f.output);if(a.length>0&&!a.equals(l))throw new TypeError("Hash mismatch");a=l}if(f.input){const u=f.input.length>0,l=f.witness&&f.witness.length>0;if(!u&&!l)throw new TypeError("Empty input");if(u&&l)throw new TypeError("Input and witness provided");if(u){const p=jr.decompile(f.input);if(!jr.isPushOnly(p))throw new TypeError("Non push-only scriptSig")}}};if(e.input){const f=i();if(!f||f.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 f=o();if(e.redeem.output&&!e.redeem.output.equals(f.output))throw new TypeError("Redeem.output mismatch");if(e.redeem.input&&!e.redeem.input.equals(f.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)}Wc.p2sh=ST;var Kc={},Sn={};Object.defineProperty(Sn,"__esModule",{value:!0});Sn.bech32m=Sn.bech32=void 0;const oc="qpzry9x8gf2tvdw0s3jn54khce6mua7l",jb={};for(let e=0;e<oc.length;e++){const t=oc.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 Vp(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 sh(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 xT(e){return sh(e,8,5,!0)}function AT(e){const t=sh(e,5,8,!1);if(Array.isArray(t))return t}function _T(e){const t=sh(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 f=Vp(o);if(typeof f=="string")throw new Error(f);let u=o+"1";for(let l=0;l<a.length;++l){const p=a[l];if(p>>5)throw new Error("Non 5-bit word");f=di(f)^p,u+=oc.charAt(p)}for(let l=0;l<6;++l)f=di(f);f^=t;for(let l=0;l<6;++l){const p=f>>(5-l)*5&31;u+=oc.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(),f=o.toUpperCase();if(o!==c&&o!==f)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 l=o.slice(0,u),p=o.slice(u+1);if(p.length<6)return"Data too short";let d=Vp(l);if(typeof d=="string")return d;const m=[];for(let g=0;g<p.length;++g){const w=p.charAt(g),S=jb[w];if(S===void 0)return"Unknown character "+w;d=di(d)^S,!(g+6>=p.length)&&m.push(S)}return d!==t?"Invalid checksum for "+o:{prefix:l,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:xT,fromWordsUnsafe:AT,fromWords:_T}}Sn.bech32=Lb("bech32");Sn.bech32m=Lb("bech32m");Object.defineProperty(Kc,"__esModule",{value:!0});Kc.p2wpkh=void 0;const $u=ns,TT=gt,Ga=Xt(),et=bt,Nn=Gt,Pa=Sn,qp=Ga.OPS,kT=Buffer.alloc(0);function IT(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(Ga.isCanonicalScriptSignature),witness:et.typeforce.maybe(et.typeforce.arrayOf(et.typeforce.Buffer))},e);const r=Nn.value(()=>{const i=Pa.bech32.decode(e.address),o=i.words.shift(),a=Pa.bech32.fromWords(i.words);return{version:o,prefix:i.prefix,data:Buffer.from(a)}}),n=e.network||TT.bitcoin,s={name:"p2wpkh",network:n};if(Nn.prop(s,"address",()=>{if(!s.hash)return;const i=Pa.bech32.toWords(s.hash);return i.unshift(0),Pa.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 $u.hash160(e.pubkey||s.pubkey)}),Nn.prop(s,"output",()=>{if(s.hash)return Ga.compile([qp.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 kT}),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]!==qp.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=$u.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(!Ga.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=$u.hash160(e.witness[1]);if(i.length>0&&!i.equals(o))throw new TypeError("Hash mismatch")}}return Object.assign(s,e)}Kc.p2wpkh=IT;var Yc={};Object.defineProperty(Yc,"__esModule",{value:!0});Yc.p2wsh=void 0;const Gp=ns,PT=gt,cn=Xt(),Oe=bt,tn=Gt,Oa=Sn,Wp=cn.OPS,Nu=Buffer.alloc(0);function Ba(e){return!!(Buffer.isBuffer(e)&&e.length===65&&e[0]===4&&(0,Oe.isPoint)(e))}function OT(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=Oa.bech32.decode(e.address),a=o.words.shift(),c=Oa.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||PT.bitcoin);const i={network:s};if(tn.prop(i,"address",()=>{if(!i.hash)return;const o=Oa.bech32.toWords(i.hash);return o.unshift(0),Oa.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:Nu,witness:e.witness.slice(0,-1)}}),tn.prop(i,"input",()=>{if(i.witness)return Nu}),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=Nu,[].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(Ba)||e.redeem.output&&(cn.decompile(e.redeem.output)||[]).some(Ba))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(Ba)||(cn.decompile(a)||[]).some(Ba))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(i,e)}Yc.p2wsh=OT;var qi={},$s={};Object.defineProperty($s,"__esModule",{value:!0});$s.getEccLib=$s.initEccLib=void 0;const co={};function BT(e,t){e?e!==co.eccLib&&(t!=null&&t.DANGER_DO_NOT_VERIFY_ECCLIB||RT(e),co.eccLib=e):co.eccLib=e}$s.initEccLib=BT;function CT(){if(!co.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return co.eccLib}$s.getEccLib=CT;const rn=e=>Buffer.from(e,"hex");function RT(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"),$T.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 $T=[{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 ih={};(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=$s,n=ns,s=ct,i=bt;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 S=(g.length-33)/32;let k=w;for(let E=0;E<S;E++){const A=g.slice(33+32*E,65+32*E);k.compare(A)<0?k=d(k,A):k=d(A,k)}return k}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,A)=>E.hash.compare(A.hash));const[S,k]=w;return{hash:d(S.hash,k.hash),left:S,right:k}}e.toHashTree=c;function f(g,w){if(o(g)){const S=f(g.left,w);if(S!==void 0)return[...S,g.right.hash];const k=f(g.right,w);if(k!==void 0)return[...k,g.left.hash]}else if(g.hash.equals(w))return[]}e.findScriptPath=f;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 l(g,w){return n.taggedHash("TapTweak",t.Buffer.concat(w?[g,w]:[g]))}e.tapTweakHash=l;function p(g,w){if(!t.Buffer.isBuffer(g)||g.length!==32||w&&w.length!==32)return null;const S=l(g,w),k=(0,r.getEccLib)().xOnlyPointAddTweak(g,S);return!k||k.xOnlyPubkey===null?null:{parity:k.parity,x:t.Buffer.from(k.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),S=t.Buffer.allocUnsafe(w);return s.varuint.encode(g.length,S),t.Buffer.concat([S,g])}})(ih);var xt={},Kp;function NT(){if(Kp)return xt;Kp=1,Object.defineProperty(xt,"__esModule",{value:!0}),xt.toOutputScript=xt.fromOutputScript=xt.toBech32=xt.toBase58Check=xt.fromBech32=xt.fromBase58Check=void 0;const e=gt,t=oh(),r=Xt(),n=bt,s=Sn,i=nh,o=40,a=2,c=16,f=2,u=80,l="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function p(E,A){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<f||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(l),w(I,P,A.bech32)}function d(E){const A=Buffer.from(i.decode(E));if(A.length<21)throw new TypeError(E+" is too short");if(A.length>21)throw new TypeError(E+" is too long");const I=A.readUInt8(0),P=A.slice(1);return{version:I,hash:P}}xt.fromBase58Check=d;function m(E){let A,I;try{A=s.bech32.decode(E)}catch{}if(A){if(I=A.words[0],I!==0)throw new TypeError(E+" uses wrong encoding")}else if(A=s.bech32m.decode(E),I=A.words[0],I===0)throw new TypeError(E+" uses wrong encoding");const P=s.bech32.fromWords(A.words.slice(1));return{version:I,prefix:A.prefix,data:Buffer.from(P)}}xt.fromBech32=m;function g(E,A){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const I=Buffer.allocUnsafe(21);return I.writeUInt8(A,0),E.copy(I,1),i.encode(I)}xt.toBase58Check=g;function w(E,A,I){const P=s.bech32.toWords(E);return P.unshift(A),A===0?s.bech32.encode(I,P):s.bech32m.encode(I,P)}xt.toBech32=w;function S(E,A){A=A||e.bitcoin;try{return t.p2pkh({output:E,network:A}).address}catch{}try{return t.p2sh({output:E,network:A}).address}catch{}try{return t.p2wpkh({output:E,network:A}).address}catch{}try{return t.p2wsh({output:E,network:A}).address}catch{}try{return t.p2tr({output:E,network:A}).address}catch{}try{return p(E,A)}catch{}throw new Error(r.toASM(E)+" has no matching Address")}xt.fromOutputScript=S;function k(E,A){A=A||e.bitcoin;let I,P;try{I=d(E)}catch{}if(I){if(I.version===A.pubKeyHash)return t.p2pkh({hash:I.hash}).output;if(I.version===A.scriptHash)return t.p2sh({hash:I.hash}).output}else{try{P=m(E)}catch{}if(P){if(P.prefix!==A.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>=f&&P.version<=c&&P.data.length>=a&&P.data.length<=o)return console.warn(l),r.compile([P.version+u,P.data])}}throw new Error(E+" has no matching Script")}return xt.toOutputScript=k,xt}var Yp;function MT(){if(Yp)return qi;Yp=1,Object.defineProperty(qi,"__esModule",{value:!0}),qi.p2tr=void 0;const e=Hs,t=gt,r=Xt(),n=bt,s=$s,i=ih,o=Gt,a=Sn,c=NT(),f=r.OPS,u=1,l=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]===l?d.witness.slice(0,-1):d.witness.slice()}),S=o.value(()=>{if(d.scriptTree)return(0,i.toHashTree)(d.scriptTree);if(d.hash)return{hash:d.hash}}),k=d.network||t.bitcoin,E={name:"p2tr",network:k};if(o.prop(E,"address",()=>{if(!E.pubkey)return;const A=a.bech32m.toWords(E.pubkey);return A.unshift(u),a.bech32m.encode(k.bech32,A)}),o.prop(E,"hash",()=>{const A=S();if(A)return A.hash;const I=w();if(I&&I.length>1){const P=I[I.length-1],$=P[0]&n.TAPLEAF_VERSION_MASK,L=I[I.length-2],T=(0,i.tapleafHash)({output:L,version:$});return(0,i.rootHashFromPath)(P,T)}return null}),o.prop(E,"output",()=>{if(E.pubkey)return r.compile([f.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 A=w();if(!(!A||A.length<2))return{output:A[A.length-2],witness:A.slice(0,-2),redeemVersion:A[A.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 A=(0,i.tweakKey)(E.internalPubkey,E.hash);if(A)return A.x}}),o.prop(E,"internalPubkey",()=>{if(d.internalPubkey)return d.internalPubkey;const A=w();if(A&&A.length>1)return A[A.length-1].slice(1,33)}),o.prop(E,"signature",()=>{if(d.signature)return d.signature;const A=w();if(!(!A||A.length!==1))return A[0]}),o.prop(E,"witness",()=>{if(d.witness)return d.witness;const A=S();if(A&&d.redeem&&d.redeem.output&&d.internalPubkey){const I=(0,i.tapleafHash)({output:d.redeem.output,version:E.redeemVersion}),P=(0,i.findScriptPath)(A,I);if(!P)return;const $=(0,i.tweakKey)(d.internalPubkey,A.hash);if(!$)return;const L=e.Buffer.concat([e.Buffer.from([E.redeemVersion|$.parity]),d.internalPubkey].concat(P));return[d.redeem.output,L]}if(d.signature)return[d.signature]}),m.validate){let A=e.Buffer.from([]);if(d.address){if(k&&k.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");A=g().data}if(d.pubkey){if(A.length>0&&!A.equals(d.pubkey))throw new TypeError("Pubkey mismatch");A=d.pubkey}if(d.output){if(d.output.length!==34||d.output[0]!==f.OP_1||d.output[1]!==32)throw new TypeError("Output is invalid");if(A.length>0&&!A.equals(d.output.slice(2)))throw new TypeError("Pubkey mismatch");A=d.output.slice(2)}if(d.internalPubkey){const $=(0,i.tweakKey)(d.internalPubkey,E.hash);if(A.length>0&&!A.equals($.x))throw new TypeError("Pubkey mismatch");A=$.x}if(A&&A.length&&!(0,s.getEccLib)().isXOnlyPoint(A))throw new TypeError("Invalid pubkey for p2tr");const I=S();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 L=($.length-33)/32;if(L>128)throw new TypeError(`The script path is too long. Got ${L}, expected max 128.`);const T=$.slice(1,33);if(d.internalPubkey&&!d.internalPubkey.equals(T))throw new TypeError("Internal pubkey mismatch");if(!(0,s.getEccLib)().isXOnlyPoint(T))throw new TypeError("Invalid internalPubkey for p2tr witness");const U=$[0]&n.TAPLEAF_VERSION_MASK,R=P[P.length-2],F=(0,i.tapleafHash)({output:R,version:U}),z=(0,i.rootHashFromPath)($,F),W=(0,i.tweakKey)(T,z);if(!W)throw new TypeError("Invalid outputKey for p2tr witness");if(A.length&&!A.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 qi.p2tr=p,qi}var Xp;function oh(){return Xp||(Xp=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=zc;Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const r=Vc;Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=qc;Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const s=Gc;Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return s.p2pkh}});const i=Wc;Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return i.p2sh}});const o=Kc;Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const a=Yc;Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return a.p2wsh}});const c=MT();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return c.p2tr}})}(Bu)),Bu}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=la,uo=Xt(),Ca=fa,UT=ns,zs=oh();function Vs(e){return t=>{try{return e({output:t}),!0}catch{return!1}}}Ie.isP2MS=Vs(zs.p2ms);Ie.isP2PK=Vs(zs.p2pk);Ie.isP2PKH=Vs(zs.p2pkh);Ie.isP2WPKH=Vs(zs.p2wpkh);Ie.isP2WSHScript=Vs(zs.p2wsh);Ie.isP2SHScript=Vs(zs.p2sh);Ie.isP2TR=Vs(zs.p2tr);function FT(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=FT;function Db(e,t){const r=(0,UT.hash160)(e),n=e.slice(1,33),s=uo.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 jT(e,t){return Db(e,t)!==-1}Ie.pubkeyInScript=jT;function LT(e,t){return DT(e).some(n=>Hb(n,uo.signature.decode,t))}Ie.checkInputForSig=LT;function Hb(e,t,r){const{hashType:n}=t(e),s=[];switch(n&Ca.Transaction.SIGHASH_ANYONECANPAY&&s.push("addInput"),n&31){case Ca.Transaction.SIGHASH_ALL:break;case Ca.Transaction.SIGHASH_SINGLE:case Ca.Transaction.SIGHASH_NONE:s.push("addOutput"),s.push("setInputSequence");break}return s.indexOf(r)===-1}Ie.signatureBlocksAction=Hb;function DT(e){let t=[];if((e.partialSig||[]).length===0){if(!e.finalScriptSig&&!e.finalScriptWitness)return[];t=HT(e)}else t=e.partialSig;return t.map(r=>r.signature)}function HT(e){const t=e.finalScriptSig?uo.decompile(e.finalScriptSig)||[]:[],r=e.finalScriptWitness?uo.decompile(e.finalScriptWitness)||[]:[];return t.concat(r).filter(n=>Buffer.isBuffer(n)&&uo.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=to=Le.serializeTaprootSignature=Le.tapScriptFinalizer=Le.toXOnly=void 0;const ah=bt,zT=fa,Xc=Ie,ts=ih,VT=oh(),qT=Ie,GT=e=>e.length===32?e:e.slice(1,33);Le.toXOnly=GT;function WT(e,t,r){const n=lk(t,e,r);try{const i=uk(t,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,Xc.witnessStackToScriptWitness)(i)}}catch(s){throw new Error(`Can not finalize taproot input #${e}: ${s}`)}}Le.tapScriptFinalizer=WT;function KT(e,t){const r=t?Buffer.from([t]):Buffer.from([]);return Buffer.concat([e,r])}var to=Le.serializeTaprootSignature=KT;function Wa(e){return e&&!!(e.tapInternalKey||e.tapMerkleRoot||e.tapLeafScript&&e.tapLeafScript.length||e.tapBip32Derivation&&e.tapBip32Derivation.length||e.witnessUtxo&&(0,Xc.isP2TR)(e.witnessUtxo.script))}Le.isTaprootInput=Wa;function Ka(e,t){return e&&!!(e.tapInternalKey||e.tapTree||e.tapBip32Derivation&&e.tapBip32Derivation.length||t&&(0,Xc.isP2TR)(t))}Le.isTaprootOutput=Ka;function YT(e,t,r){ok(e,t,r),ck(e,t,r)}Le.checkTaprootInputFields=YT;function XT(e,t,r){ak(e,t,r),ZT(e,t)}Le.checkTaprootOutputFields=XT;function ZT(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=JT(r,n);if(s&&!s.equals(i))throw new Error("Error adding output. Script or address missmatch.")}}function JT(e,t){const r=t&&zb(t.leaves),{output:n}=(0,VT.p2tr)({internalPubkey:e,scriptTree:r});return n}function QT(e,t){const r=t.tapInternalKey,n=r&&(0,ts.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=QT;function ek(e){if(!(0,ah.isTaptree)(e))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return jl(e)}Le.tapTreeToList=ek;function zb(e=[]){return e.length===1&&e[0].depth===0?{output:e[0].script,version:e[0].leafVersion}:ik(e)}Le.tapTreeFromList=zb;function tk(e,t){return nk(e).some(n=>(0,qT.signatureBlocksAction)(n,rk,t))}Le.checkTaprootInputForSigs=tk;function rk(e){return{signature:e.slice(0,64),hashType:e.slice(64)[0]||zT.Transaction.SIGHASH_DEFAULT}}function nk(e){const t=[];if(e.tapKeySig&&t.push(e.tapKeySig),e.tapScriptSig&&t.push(...e.tapScriptSig.map(r=>r.signature)),!t.length){const r=sk(e.finalScriptWitness);r&&t.push(r)}return t}function sk(e){if(!e)return;const t=e.slice(2);if(t.length===64||t.length===65)return t}function jl(e,t=[],r=0){if(r>ts.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return e?(0,ah.isTapleaf)(e)?(t.push({depth:r,leafVersion:e.version||ts.LEAF_VERSION_TAPSCRIPT,script:e.output}),t):(e[0]&&jl(e[0],t,r+1),e[1]&&jl(e[1],t,r+1),t):[]}function ik(e){let t;for(const r of e)if(t=Ll(r,t),!t)throw new Error("No room left to insert tapleaf in tree");return t}function Ll(e,t,r=0){if(r>ts.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,ah.isTapleaf)(t))return;const n=Ll(e,t&&t[0],r+1);if(n)return[n,t&&t[1]];const s=Ll(e,t&&t[1],r+1);if(s)return[t&&t[0],s]}function ok(e,t,r){const n=Wa(e)&&hi(t),s=hi(e)&&Wa(t),i=e===t&&Wa(t)&&hi(t);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function ak(e,t,r){const n=Ka(e)&&hi(t),s=hi(e)&&Ka(t),i=e===t&&Ka(t)&&hi(t);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function ck(e,t,r){if(t.tapMerkleRoot){const n=(t.tapLeafScript||[]).every(i=>Mu(i,t.tapMerkleRoot)),s=(e.tapLeafScript||[]).every(i=>Mu(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=>Mu(s,e.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function Mu(e,t){if(!t)return!0;const r=(0,ts.tapleafHash)({output:e.script,version:e.leafVersion});return(0,ts.rootHashFromPath)(e.controlBlock,r).equals(t)}function uk(e,t){const r=(0,ts.tapleafHash)({output:t.script,version:t.leafVersion});return(e.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>fk(t.script,n)).sort((n,s)=>s.positionInScript-n.positionInScript).map(n=>n.signature)}function fk(e,t){return Object.assign({positionInScript:(0,Xc.pubkeyPositionInScript)(t.pubkey,e)},t)}function lk(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=>dk(s,e.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${t}. Signature for tapleaf script not found.`);return n}function dk(e,t,r){const n=(0,ts.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 At={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"},Ra=192;Ae.initEccLib(or);class fo{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=l_(),this.initiateAmount=r,this.utxoHashes=c}static async from(t,r,n,s,i,o,a){n=n.startsWith("0x")?n.slice(2):n,Ys(n.length===64,At.secretHashLenMismatch),Ys(s.length===64||s.length===66,`initiator ${At.pubkeyLenMismatch}`),Ys(i.length===64||i.length===66,`redeemer ${At.pubkeyLenMismatch}`),Ys(o>0,At.zeroOrNegativeExpiry);const c=await t.getNetwork();return new fo(t,r,n,Rl(i).toString("hex"),Rl(s).toString("hex"),o,c,a)}address(){const{address:t}=Ae.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves()});if(!t)throw new Error(At.htlcAddressGenerationFailed);return t}id(){return this.address()}async _buildRawTx(t,r){const n=new Ae.Transaction;n.version=2;const s=this.address(),i=await this.signer.getProvider();let o=[];if(this.utxoHashes&&this.utxoHashes.length>0)for(const f of this.utxoHashes){const u=await i.getTransaction(f);for(let l=0;l<u.vout.length;l++){const p=u.vout[l];p.scriptpubkey_address===s&&o.push({txid:u.txid,vout:l,value:p.value,status:{confirmed:!1}})}}else o=await i.getUTXOs(s);const a=o.reduce((f,u)=>f+u.value,0);if(a===0)throw new Error(`${s} ${At.notFunded}`);for(let f=0;f<o.length;f++)n.addInput(Buffer.from(o[f].txid,"hex").reverse(),o[f].vout);if(r!=null&&r.vSize){const f=await i.getFeeRates(),u=Math.ceil(f.hourFee*r.vSize),l=a-u;return n.addOutput(Ae.address.toOutputScript(t,this.network),l),{tx:n,usedUtxos:o}}const c=(r==null?void 0:r.fee)??await i.suggestFee(s,a,fi.MEDIUM);return n.addOutput(Ae.address.toOutputScript(t,this.network),a-c),{tx:n,usedUtxos:o,fee:c,balance:a}}getOutputScript(){return Ae.address.toOutputScript(this.address(),this.network)}async init(t){return t??(t=await(await this.signer.getProvider()).suggestFee(await this.signer.getAddress(),this.initiateAmount,fi.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=Ae.Transaction.SIGHASH_SINGLE|Ae.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(1),f=i.map(l=>l.value),u=Gi(o,i.length);for(let l=0;l<s.ins.length;l++){const p=s.hashForWitnessV1(l,u,f,a,c),d=await this.signer.signSchnorr(p);s.setWitness(l,[to(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(l=>l.value));s.forEach(({value:l})=>{n.addOutput(r,l-(l===o?i??0:0))});const a=Ae.Transaction.SIGHASH_SINGLE|Ae.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(2),f=s.map(l=>l.value),u=Gi(r,s.length);for(let l=0;l<n.ins.length;l++){const p=n.hashForWitnessV1(l,u,f,a,c),d=await this.signer.signSchnorr(p);n.setWitness(l,[to(d,a),to(d,a),this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return n.toHex()}async generateInstantRefundSACPWithHash(t){const r=[],n=Ae.Transaction.SIGHASH_SINGLE|Ae.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(to(o,n).toString("hex"))}return r}async instantRefund(t,r){Ys(t.length>0,At.noCounterpartySigs);const{tx:n,usedUtxos:s}=await this._buildRawTx(await this.signer.getAddress(),{fee:r});for(const l of s)if(!t.find(p=>p.utxo===l.txid))throw new Error(At.counterPartySigNotFound(l.txid));const i=this.getOutputScript(),o=Ae.Transaction.SIGHASH_DEFAULT,a=this.leafHash(2),c=s.map(l=>l.value),f=Gi(i,s.length);for(let l=0;l<n.ins.length;l++){const p=n.hashForWitnessV1(l,f,c,o,a);if(!or.verifySchnorr(p,Buffer.from(this.redeemerPubkey,"hex"),Buffer.from(t[l].sig,"hex")))throw new Error(At.invalidCounterpartySigForUTXO(t[l].utxo));const d=await this.signer.signSchnorr(p),m=Buffer.from(n.ins[l].hash).reverse().toString("hex"),g=t.find(w=>w.utxo===m);if(!g)throw new Error(At.counterPartySigNotFound(m));n.setWitness(l,[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){Ys(Ae.crypto.sha256(Buffer.from(t,"hex")).toString("hex")===this.secretHash,At.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(l=>l.value),c=Gi(this.getOutputScript(),i.length),f=Ae.Transaction.SIGHASH_DEFAULT;for(let l=0;l<s.ins.length;l++){const p=s.hashForWitnessV1(l,c,a,f,o),d=await this.signer.signSchnorr(p);s.setWitness(l,[d,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}const{tx:u}=await this._buildRawTx(n,{vSize:s.virtualSize()});for(let l=0;l<u.ins.length;l++){const p=u.hashForWitnessV1(l,c,a,f,o),d=await this.signer.signSchnorr(p);u.setWitness(l,[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(At.htlcNotExpired(o));const a=this.leafHash(0),c=s.map(p=>p.value),f=Gi(this.getOutputScript(),s.length),u=Ae.Transaction.SIGHASH_DEFAULT;for(let p=0;p<n.ins.length;p++){n.ins[p].sequence=this.expiry;const d=n.hashForWitnessV1(p,f,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(At.invalidLeaf)}const n=Ae.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves(),redeem:{output:r,redeemVersion:Ra}});if(!n.witness)throw new Error(At.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()),Ae.crypto.taggedHash("TapLeaf",ZA(r))}refundLeaf(){return Ae.script.fromASM(`
54
+ ${Ae.script.number.encode(this.expiry).toString("hex")}
55
+ OP_CHECKSEQUENCEVERIFY
56
+ OP_DROP
57
+ ${this.initiatorPubkey}
58
+ OP_CHECKSIG
59
+ `.trim().replace(/\s+/g," "))}redeemLeaf(){return Ae.script.fromASM(`
60
+ OP_SHA256
61
+ ${this.secretHash}
62
+ OP_EQUALVERIFY
63
+ ${this.redeemerPubkey}
64
+ OP_CHECKSIG
65
+ `.trim().replace(/\s+/g," "))}instantRefundLeaf(){return Ae.script.fromASM(`
66
+ ${this.initiatorPubkey}
67
+ OP_CHECKSIG
68
+ ${this.redeemerPubkey}
69
+ OP_CHECKSIGADD
70
+ OP_2
71
+ OP_NUMEQUAL
72
+ `.trim().replace(/\s+/g," "))}leaves(){return[{version:Ra,output:this.redeemLeaf()},[{version:Ra,output:this.refundLeaf()},{version:Ra,output:this.instantRefundLeaf()}]]}generateMerkleProofFor(t){const r=this.leafHash(1),n=this.leafHash(2),s=this.leafHash(0);switch(t){case 1:{const i=QA(s,n);return[Ae.crypto.taggedHash("TapBranch",Buffer.concat(i))]}case 0:return[n,r];case 2:return[s,r];default:throw new Error(At.invalidLeaf)}}}function Gi(e,t){const r=[];for(let n=0;n<t;n++)r.push(e);return r}class hk{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 pk{constructor(){this.cache={}}set(t,r){this.cache[t]=r}get(t){return this.cache[t]||null}}class Vb{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 qb{constructor(t){this.quoteUrl=new v.Url(t)}async getQuoteFromAssets({fromAsset:t,toAsset:r,amount:n,isExactOut:s=!1,options:i}){const o=$l(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=$l(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 qo extends v.EventBroker{get isInitialized(){return!!this.digestKey}constructor(t,r){super(),this.digestKey=t,this.walletClient=r}static fromDigestKey(t){return new qo(v.trim0x(t))}static fromWalletClient(t){return new qo(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(Ji(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=Ji(v.with0x(r.val)),s=Ji(n);return v.Ok({secret:n,secretHash:s})}async signMessage(t){if(!this.digestKey){const f=await this.getDigestKey();if(!f.ok)return v.Err(f.error);this.digestKey=f.val}const r=La.ECPairFactory(or),n="Garden.fi"+t.toString(),s=Buffer.from(n,"utf8"),i=Ji(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"}],yk={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},mk={block:RE({format(e){var r;return{transactions:(r=e.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const s=kc(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:BE({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:H6({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 gk(e,t){return vk(e)?wk(e):HS(e,t)}const bk={transaction:gk};function wk(e){Ek(e);const{sourceHash:t,data:r,from:n,gas:s,isSystemTx:i,mint:o,to:a,value:c}=e,f=[t,n,a??"0x",o?mt(o):"0x",c?mt(c):"0x",s?mt(s):"0x",i?"0x1":"0x",r??"0x"];return kr(["0x7e",es(f)])}function vk(e){return e.type==="deposit"||typeof e.sourceHash<"u"}function Ek(e){const{from:t,to:r}=e;if(t&&!st(t))throw new Ot({address:t});if(r&&!st(r))throw new Ot({address:r})}const xi={blockTime:2e3,contracts:yk,formatters:mk,serializers:bk},Sk=Ft({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},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}}}),xk=Ft({id:421614,name:"Arbitrum Sepolia",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}),Wi=1,Ak=Ft({...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:{[Wi]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[Wi]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[Wi]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[Wi]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:Wi}),Ki=11155111,_k=Ft({...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:{[Ki]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[Ki]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[Ki]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[Ki]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:Ki}),Tk=Ft({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}),kk=Ft({id:80084,name:"Berachain bArtio",nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:109269},ensRegistry:{address:"0xB0eef18971290b333450586D33dcA6cE122651D2",blockCreated:7736794},ensUniversalResolver:{address:"0x41692Ef1EA0C79E6b73077E4A67572D2BDbD7057",blockCreated:7736795}},ensTlds:[".bera"],rpcUrls:{default:{http:["https://bartio.rpc.berachain.com"]}},blockExplorers:{default:{name:"Berachain bArtio Beratrail",url:"https://bartio.beratrail.io"}},testnet:!0}),Ik=Ft({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}}}),Pk=Ft({id:97,name:"BNB Smart Chain Testnet",nativeCurrency:{decimals:18,name:"BNB",symbol:"tBNB"},rpcUrls:{default:{http:["https://data-seed-prebsc-1-s1.bnbchain.org:8545"]}},blockExplorers:{default:{name:"BscScan",url:"https://testnet.bscscan.com",apiUrl:"https://api-testnet.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:17422483}},testnet:!0}),Ok=Ft({id:5115,name:"Citrea Testnet",nativeCurrency:{name:"cBTC",symbol:"cBTC",decimals:18},rpcUrls:{default:{http:["https://rpc.testnet.citrea.xyz"]}},blockExplorers:{default:{name:"Citrea Explorer",url:"https://explorer.testnet.citrea.xyz",apiUrl:"https://explorer.testnet.citrea.xyz/api"}},testnet:!0}),Bk=1,Ck=Ft({id:21e6,name:"Corn",nativeCurrency:{decimals:18,name:"Bitcorn",symbol:"BTCN"},rpcUrls:{default:{http:["https://21000000.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"Corn Explorer",url:"https://cornscan.io",apiUrl:"https://api.routescan.io/v2/network/mainnet/evm/21000000/etherscan/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:3228}},sourceId:Bk}),Rk=Ft({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}}}),$k=Ft({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}),Nk=Ft({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}),$a=1,Mk=Ft({...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:{[$a]:{address:"0x2F12d621a16e2d3285929C9996f478508951dFe4"}},portal:{[$a]:{address:"0x0bd48f6B86a26D3a217d0Fa6FfE2B491B956A7a2"}},l1StandardBridge:{[$a]:{address:"0x81014F44b0a345033bB2b3B21C7a1A308B35fEeA"}}},sourceId:$a}),Uk={...Nk,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},Gb={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/"]}}},Wb={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"]}}},Kb={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"]}}},ch={ethereum:Rk,arbitrum:Sk,ethereum_sepolia:Uk,arbitrum_sepolia:xk,ethereum_localnet:be.EthereumLocalnet,arbitrum_localnet:be.ArbitrumLocalnet,base_sepolia:_k,base:Ak,bera_testnet:kk,citrea_testnet:Ok,bera:Tk,monad_testnet:$k,hyperliquid_testnet:Wb,hyperliquid:Kb,unichain:Mk,corn:Ck,botanix:Gb,bnbchain:Ik,bnbchain_testnet:Pk},Yb=async(e,t)=>{var s,i,o;const r=ch[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=Au({account:t.account,chain:r,transport:lp(t.transport)});return v.Ok({message:"Switched chain",walletClient:a})}catch(a){if(Fk(a))if(a.code===4902||a.code===-32603)try{await t.addChain({chain:r});const c=Au({account:t.account,chain:r,transport:lp(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=Au({account:t.account,chain:r,transport:bg()});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")},Fk=e=>typeof e=="object"&&e!=null&&("code"in e||"message"in e||"body"in e),jk=[{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 Xb{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 Yb(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),f=await this.getTokenAddress(t.source_swap.asset);return f.ok?be.isEvmNativeToken(t.source_swap.chain,f.val)?this._initiateOnNativeHTLC(i,o,c,a,t.source_swap.asset):this._initiateOnErc20HTLC(i,o,c,a,t.source_swap.asset,f.val,n.create_id):v.Err(f.error)}async getTokenAddress(t){try{const n=await mu({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 mu({address:v.with0x(i),abi:jk,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 f=mu({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 l=await f.read.eip712Domain(),p=await this.wallet.signTypedData({account:this.wallet.account,domain:{name:l[1],version:l[2],chainId:Number(l[3]),verifyingContract:l[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=ch[t.destination_swap.chain],a=await $A({chain:i,transport:bg()}).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 Zb=[{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"}]}],Jb=async(e,t,r,n,s)=>{try{const i=await lo(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 f=0;f<20;f++){const u=await lo(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 l=0n;for(let p=0;p<20;p++){const d=await lo(e.address,t,r,s);if(!d.ok)return v.Err(d.error);if(l=d.val,l>=n)break;await v.sleep(2e3)}return l<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)}`)}},lo=async(e,t,r,n)=>{try{const i=await new it.Contract(Zb,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)}`)}},Qb=async(e,t,r,n,s)=>{const i=await lo(e,t,r,n);return i.ok?v.Ok(i.val>=s):v.Err(i.error)},ew=[{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"}]}],Lk={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 tw{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||Do[n].nodeUrl}),this.chainId=Do[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(ew,t.source_swap.asset,this.account),i=await(s==null?void 0:s.token()),o=it.num.toHex(i),a=await Qb(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 f=s.asset;try{const u=it.cairo.uint256(BigInt(o)),l={contractAddress:v.with0x(t),entrypoint:"approve",calldata:[f,u.low,u.high]},p=it.cairo.uint256(o),d={contractAddress:v.with0x(f),entrypoint:"initiate",calldata:[i,c.toString(),p.low.toString(),p.high.toString(),...v.hexToU32Array(a)]},m=await this.account.execute([l,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:Lk,message:{redeemer:s,amount:it.cairo.uint256(i),timelock:r.timelock,secretHash:v.hexToU32Array(o)}};try{const f=await this.account.signMessage(c),u=s_(f);if(u.error)return v.Err(u.error);const l=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 l.error?v.Err(l.error):l.result?v.Ok(l.result):v.Err("Init: No result found")}catch(f){return v.Err(`Failed to initiate relayer: ${String(f)}`)}}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 Dk=e=>e.map(t=>t),Hk=e=>{if(e===Ht.Testnet)return zk;if(e===Ht.Mainnet)return Vk;throw new Error("Invalid network")},zk=["https://mempool.space/testnet4/api"],Vk=["https://mempool.space/api","https://blockstream.info/api"],cs={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}`},ro={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 rw{constructor(t,r){this.cacheTimeout=2e3,this.utxosCache=new Map,this.APIs=r?Dk([r]):Hk(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===Va.ALL)return n;if(r===Va.IN)return n.filter(s=>s.vout.find(i=>i.scriptpubkey_address===t));if(r===Va.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[XA[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(cs.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[]},Yi={p2wpkh:"p2wpkh","p2wpkh-p2sh":"p2wpkh-p2sh"},Ya={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 xs{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 Ph.mixed().oneOf(["segwitV0","segwitV1","p2shSignature"]).required().validate(r),i=await Ph.mixed().oneOf(Object.values(Ya)).required().validate(parseInt(n));return new xs(s,i)}}const qk=(e,t,r=!1)=>{const n=o=>{try{o=pe.address.fromBech32(o).data.toString("hex")}catch(a){if(Ml(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
+ OP_IF
74
+ OP_SHA256
75
+ ${e.secretHash}
76
+ OP_EQUALVERIFY
77
+ OP_DUP
78
+ OP_HASH160
79
+ ${n(e.recipientAddress.address)}
80
+ OP_ELSE
81
+ ${pe.script.number.encode(e.expiryBlocks).toString("hex")}
82
+ OP_CHECKSEQUENCEVERIFY
83
+ OP_DROP
84
+ OP_DUP
85
+ OP_HASH160
86
+ ${n(e.refundAddress.address)}
87
+ OP_ENDIF
88
+ OP_EQUALVERIFY
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}},ho={P2SH:"p2sh",P2WSH:"p2wsh",P2TR:"p2tr"};var nw=(e=>(e[e.Bitcoin=0]="Bitcoin",e[e.EVM=1]="EVM",e))(nw||{});class Gk{addSignatureSegwitV0(t=Ya.ALL){return new xs("segwitV0",t)}addSignatureP2sh(t=Ya.ALL){return new xs("p2shSignature",t)}addSignatureSegwitV1(t=Ya.ALL){return new xs("segwitV1",t)}chain(){return nw.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(Nl(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(ro.INVALID_SECRET_HASH);const{script:r,address:n}=qk(t,await this.getNetwork());return new Wk(this,{...t,redeemScript:r,scriptAddress:n})}getScriptType(t,r){try{if(pe.address.fromBase58Check(t).version===r.scriptHash)return ho.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 ho.P2WSH}else if(s.version===1&&s.data.length===32)return ho.P2TR}throw new Error("Unsupported script type")}}class Wk{constructor(t,r){if(r.secretHash=v.trim0x(r.secretHash),r.secretHash.length!==64)throw new Error(ro.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 Ml(i)?i.message.includes("OP_EQUALVERIFY")?new Error(ro.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 Ml(n)?n.message.includes("OP_EQUALVERIFY")?new Error(ro.INVALID_PUBKEY):n.message.includes("BIP")?new Error(ro.ORDER_NOT_EXPIRED):new Error(n.message):new Error(String(n))}}}const Uu=(e,t,r,n)=>`m/${e}'/${t===Ht.Mainnet?0:1}'/${r}'/0/${n??0}`,sw={bip44:(e,t,r)=>Uu("44",e,r??0,t),bip49:(e,t,r)=>Uu("49",e,r??0,t),bip84:(e,t,r)=>Uu("84",e,r??0,t)};function Fu(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 Kk(e,t,r){if(!Oh.validateMnemonic(e))throw new Error("Invalid mnemonic");const n=(r==null?void 0:r.path)??sw.bip44(t,(r==null?void 0:r.index)??0),s=V1.BIP32Factory(or).fromSeed(Oh.mnemonicToSeedSync(e));return Yk(s,n)}const Yk=(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(or);class ps extends Gk{constructor({privateKey:t,provider:r,pkPath:n,pkType:s}){const i=La.ECPairFactory(or),o=Fu(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=sw.bip84(r.getNetwork(),n==null?void 0:n.index),i=Kk(t,r.getNetwork(),{path:s});return new ps({privateKey:i,provider:r,pkType:Yi.p2wpkh,pkPath:s})}static fromPrivateKey(t,r,n){return new ps({privateKey:t,provider:r,pkType:(n==null?void 0:n.pkType)??Yi.p2wpkh,pkPath:(n==null?void 0:n.pkPath)??"unknown"})}static createRandom(t){const r=La.ECPairFactory(or),n=Fu(t.getNetwork()),s=r.makeRandom({network:n});if(!s.privateKey)throw new Error("Failed to create random key");return new ps({privateKey:s.privateKey.toString("hex"),provider:t,pkType:Yi.p2wpkh,pkPath:"unknown"})}static fromWIF(t,r,n){const s=La.ECPairFactory(or),i=Fu(r.getNetwork()),o=s.fromWIF(t,i);if(!o.privateKey)throw new Error("Invalid WIF");return ps.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),f=await this.provider.getBalance(r);if(f===0)throw new Error(cs.SCRIPT_NOT_FUNDED);let u=new pe.Transaction;if(u.version=2,s??(s=await this.provider.suggestFee(r,f,fi.FAST)),s>f)throw new Error(cs.FEE_EXCEEDS_AMOUNT(s,f));const l=await this.provider.getUTXOs(r);u=await this.addAllInputs(u,r,this.provider,{nSequence:i,utxos:l}),u.addOutput(await this.toOutputScript(n??await this.getAddress()),f-s);for(let d=0;d<u.ins.length;d++)if(c===ho.P2SH){if(!o)throw new Error("Unlock script is required for p2sh");const m=[];for(const w of o)if(w instanceof xs){const S=w.sigHashType,k=u.hashForSignature(d,t,S);m.push(pe.script.signature.encode(Buffer.from(await this.sign(k.toString("hex")),"hex"),S))}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===ho.P2WSH){if(!a)throw new Error("Witness is required for p2wsh");const m=[];for(const g of a)if(g instanceof xs){const w=g.sigHashType,S=u.hashForWitnessV0(d,t,l[d].value,w);m.push(pe.script.signature.encode(Buffer.from(await this.sign(S.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===Yi["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,fi.FAST)),o>i)throw new Error(cs.FEE_EXCEEDS_AMOUNT(o,i));const a=await t.getUTXOs(n,i+o),c=a.reduce((l,p)=>l+p.value,0);if(c<i+o)throw new Error(cs.INSUFFICIENT_FUNDS(c,i+o));const f=new pe.Psbt({network:r});for(const l of a){const p=await t.getTransactionHex(l.txid);f.addInput({hash:Nl(l.txid),index:l.vout,nonWitnessUtxo:Buffer.from(p,"hex")})}const u=c-i-o;return f.addOutput({address:s,value:i}),u>546&&f.addOutput({address:n,value:u}),{txHex:f.toHex(),utxoCount:a.length}}async _send(t,r,n){var f;if(n||(n=await this.provider.suggestFee(await this.getAddress(),r,fi.FAST)),n>r)throw new Error(cs.FEE_EXCEEDS_AMOUNT(n,r));if(r<this.minAmt)throw new Error(cs.MIN_AMOUNT(this.minAmt));const s=await this.getAddress(),i=await this.provider.getUTXOs(s,r+n),o=i.reduce((u,l)=>u+l.value,0),a=new pe.Psbt({network:this.network});for(const u of i){const l=await this.provider.getTransactionHex(u.txid),p=await this.provider.getTransaction(u.txid);let d;this.pkType===Yi["p2wpkh-p2sh"]&&(d={witnessUtxo:{script:Buffer.from(p.vout[u.vout].scriptpubkey,"hex"),value:u.value},redeemScript:(f=pe.payments.p2sh({redeem:pe.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network}).redeem)==null?void 0:f.output}),a.addInput({hash:Nl(u.txid),index:u.vout,nonWitnessUtxo:Buffer.from(l,"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 Xk="2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",Zk={name:"solana_native_swaps",version:"0.3.0",spec:"0.1.0",description:"Created with Anchor"},Jk=[{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:[]}],Qk=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],eI=[{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]}],tI=[{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"}],rI=[{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]}}]}}],Dl={address:Xk,metadata:Zk,instructions:Jk,accounts:Qk,events:eI,errors:tI,types:rI};var hn={},Ai={};Object.defineProperty(Ai,"__esModule",{value:!0});Ai.decode=Ai.encode=void 0;const ty=Hs;function nI(e){return e.reduce((t,r)=>t+r.toString(16).padStart(2,"0"),"0x")}Ai.encode=nI;function sI(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?ty.Buffer.from([]):ty.Buffer.from(t.map(r=>parseInt(r,16)))}Ai.decode=sI;var _i={},Zn={},ju;Object.defineProperty(Zn,"__esModule",{value:!0});Zn.isVersionedTransaction=Zn.chunks=Zn.isBrowser=void 0;Zn.isBrowser=process.env.ANCHOR_BROWSER||typeof window<"u"&&!(!((ju=window.process)===null||ju===void 0)&&ju.hasOwnProperty("type"));function iI(e,t){return Array.apply(0,new Array(Math.ceil(e.length/t))).map((r,n)=>e.slice(n*t,(n+1)*t))}Zn.chunks=iI;const oI=e=>"version"in e;Zn.isVersionedTransaction=oI;var Lu={},Du={},Hu,ry;function iw(){return ry||(ry=1,Hu=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}),Hu}var zu,ny;function Zc(){if(ny)return zu;ny=1;var e=iw();return zu=function(){return e()&&!!Symbol.toStringTag},zu}var Vu,sy;function ow(){return sy||(sy=1,Vu=Object),Vu}var qu,iy;function aI(){return iy||(iy=1,qu=Error),qu}var Gu,oy;function cI(){return oy||(oy=1,Gu=EvalError),Gu}var Wu,ay;function uI(){return ay||(ay=1,Wu=RangeError),Wu}var Ku,cy;function fI(){return cy||(cy=1,Ku=ReferenceError),Ku}var Yu,uy;function aw(){return uy||(uy=1,Yu=SyntaxError),Yu}var Xu,fy;function da(){return fy||(fy=1,Xu=TypeError),Xu}var Zu,ly;function lI(){return ly||(ly=1,Zu=URIError),Zu}var Ju,dy;function dI(){return dy||(dy=1,Ju=Math.abs),Ju}var Qu,hy;function hI(){return hy||(hy=1,Qu=Math.floor),Qu}var ef,py;function pI(){return py||(py=1,ef=Math.max),ef}var tf,yy;function yI(){return yy||(yy=1,tf=Math.min),tf}var rf,my;function mI(){return my||(my=1,rf=Math.pow),rf}var nf,gy;function gI(){return gy||(gy=1,nf=Math.round),nf}var sf,by;function bI(){return by||(by=1,sf=Number.isNaN||function(t){return t!==t}),sf}var of,wy;function wI(){if(wy)return of;wy=1;var e=bI();return of=function(r){return e(r)||r===0?r:r<0?-1:1},of}var af,vy;function vI(){return vy||(vy=1,af=Object.getOwnPropertyDescriptor),af}var cf,Ey;function Ui(){if(Ey)return cf;Ey=1;var e=vI();if(e)try{e([],"length")}catch{e=null}return cf=e,cf}var uf,Sy;function Jc(){if(Sy)return uf;Sy=1;var e=Object.defineProperty||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return uf=e,uf}var ff,xy;function EI(){if(xy)return ff;xy=1;var e=typeof Symbol<"u"&&Symbol,t=iw();return ff=function(){return typeof e!="function"||typeof Symbol!="function"||typeof e("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:t()},ff}var lf,Ay;function cw(){return Ay||(Ay=1,lf=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),lf}var df,_y;function uw(){if(_y)return df;_y=1;var e=ow();return df=e.getPrototypeOf||null,df}var hf,Ty;function SI(){if(Ty)return hf;Ty=1;var e="Function.prototype.bind called on incompatible ",t=Object.prototype.toString,r=Math.max,n="[object Function]",s=function(c,f){for(var u=[],l=0;l<c.length;l+=1)u[l]=c[l];for(var p=0;p<f.length;p+=1)u[p+c.length]=f[p];return u},i=function(c,f){for(var u=[],l=f,p=0;l<c.length;l+=1,p+=1)u[p]=c[l];return u},o=function(a,c){for(var f="",u=0;u<a.length;u+=1)f+=a[u],u+1<a.length&&(f+=c);return f};return hf=function(c){var f=this;if(typeof f!="function"||t.apply(f)!==n)throw new TypeError(e+f);for(var u=i(arguments,1),l,p=function(){if(this instanceof l){var S=f.apply(this,s(u,arguments));return Object(S)===S?S:this}return f.apply(c,s(u,arguments))},d=r(0,f.length-u.length),m=[],g=0;g<d;g++)m[g]="$"+g;if(l=Function("binder","return function ("+o(m,",")+"){ return binder.apply(this,arguments); }")(p),f.prototype){var w=function(){};w.prototype=f.prototype,l.prototype=new w,w.prototype=null}return l},hf}var pf,ky;function ha(){if(ky)return pf;ky=1;var e=SI();return pf=Function.prototype.bind||e,pf}var yf,Iy;function uh(){return Iy||(Iy=1,yf=Function.prototype.call),yf}var mf,Py;function fh(){return Py||(Py=1,mf=Function.prototype.apply),mf}var gf,Oy;function xI(){return Oy||(Oy=1,gf=typeof Reflect<"u"&&Reflect&&Reflect.apply),gf}var bf,By;function fw(){if(By)return bf;By=1;var e=ha(),t=fh(),r=uh(),n=xI();return bf=n||e.call(r,t),bf}var wf,Cy;function lh(){if(Cy)return wf;Cy=1;var e=ha(),t=da(),r=uh(),n=fw();return wf=function(i){if(i.length<1||typeof i[0]!="function")throw new t("a function is required");return n(e,r,i)},wf}var vf,Ry;function AI(){if(Ry)return vf;Ry=1;var e=lh(),t=Ui(),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 vf=n&&typeof n.get=="function"?e([n.get]):typeof i=="function"?function(a){return i(a==null?a:s(a))}:!1,vf}var Ef,$y;function dh(){if($y)return Ef;$y=1;var e=cw(),t=uw(),r=AI();return Ef=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,Ef}var Sf,Ny;function lw(){if(Ny)return Sf;Ny=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=ha();return Sf=r.call(e,t),Sf}var xf,My;function dw(){if(My)return xf;My=1;var e,t=ow(),r=aI(),n=cI(),s=uI(),i=fI(),o=aw(),a=da(),c=lI(),f=dI(),u=hI(),l=pI(),p=yI(),d=mI(),m=gI(),g=wI(),w=Function,S=function(oe){try{return w('"use strict"; return ('+oe+").constructor;")()}catch{}},k=Ui(),E=Jc(),A=function(){throw new a},I=k?function(){try{return arguments.callee,A}catch{try{return k(arguments,"callee").get}catch{return A}}}():A,P=EI()(),$=dh(),L=uw(),T=cw(),U=fh(),R=uh(),F={},z=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%":F,"%AsyncGenerator%":F,"%AsyncGeneratorFunction%":F,"%AsyncIteratorPrototype%":F,"%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%":F,"%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%":k,"%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%":z,"%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%":U,"%Object.defineProperty%":E,"%Object.getPrototypeOf%":L,"%Math.abs%":f,"%Math.floor%":u,"%Math.max%":l,"%Math.min%":p,"%Math.pow%":d,"%Math.round%":m,"%Math.sign%":g,"%Reflect.getPrototypeOf%":T};if($)try{null.error}catch(oe){var Z=$($(oe));W["%Error.prototype%"]=Z}var Q=function oe(ie){var he;if(ie==="%AsyncFunction%")he=S("async function () {}");else if(ie==="%GeneratorFunction%")he=S("function* () {}");else if(ie==="%AsyncGeneratorFunction%")he=S("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=ha(),B=lw(),q=D.call(R,Array.prototype.concat),K=D.call(U,Array.prototype.splice),O=D.call(R,String.prototype.replace),N=D.call(R,String.prototype.slice),j=D.call(R,RegExp.prototype.exec),J=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,ne=/\\(\\)?/g,le=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===F&&(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 xf=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(j(/^%?[^%]*%?$/,ie)===null)throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var ve=le(ie),_e=ve.length>0?ve[0]:"",je=ce("%"+_e+"%",he),jt=je.name,Qe=je.value,Pr=!1,ss=je.alias;ss&&(_e=ss[0],K(ve,q([0,1],ss)));for(var G=1,Or=!0;G<ve.length;G+=1){var wt=ve[G],vt=N(wt,0,1),kn=N(wt,-1);if((vt==='"'||vt==="'"||vt==="`"||kn==='"'||kn==="'"||kn==="`")&&vt!==kn)throw new o("property names with quotes must have matching quotes");if((wt==="constructor"||!Or)&&(Pr=!0),_e+="."+wt,jt="%"+_e+"%",B(W,jt))Qe=W[jt];else if(Qe!=null){if(!(wt in Qe)){if(!he)throw new a("base intrinsic for "+ie+" exists, but the property is not available.");return}if(k&&G+1>=ve.length){var Gs=k(Qe,wt);Or=!!Gs,Or&&"get"in Gs&&!("originalValue"in Gs.get)?Qe=Gs.get:Qe=Qe[wt]}else Or=B(Qe,wt),Qe=Qe[wt];Or&&!Pr&&(W[jt]=Qe)}}return Qe},xf}var Af,Uy;function pa(){if(Uy)return Af;Uy=1;var e=dw(),t=lh(),r=t([e("%String.prototype.indexOf%")]);return Af=function(s,i){var o=e(s,!!i);return typeof o=="function"&&r(s,".prototype.")>-1?t([o]):o},Af}var _f,Fy;function _I(){if(Fy)return _f;Fy=1;var e=Zc()(),t=pa(),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,_f=i?n:s,_f}var Tf,jy;function TI(){if(jy)return Tf;jy=1;var e=pa(),t=Zc()(),r=lw(),n=Ui(),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 f=e("Object.prototype.toString"),u="[object RegExp]";s=function(p){return!p||typeof p!="object"&&typeof p!="function"?!1:f(p)===u}}return Tf=s,Tf}var kf,Ly;function kI(){if(Ly)return kf;Ly=1;var e=pa(),t=TI(),r=e("RegExp.prototype.exec"),n=da();return kf=function(i){if(!t(i))throw new n("`regex` must be a RegExp");return function(a){return r(i,a)!==null}},kf}var If,Dy;function II(){if(Dy)return If;Dy=1;var e=pa(),t=kI(),r=t(/^\s*(?:function)?\*/),n=Zc()(),s=dh(),i=e("Object.prototype.toString"),o=e("Function.prototype.toString"),a=function(){if(!n)return!1;try{return Function("return function*() {}")()}catch{}},c;return If=function(u){if(typeof u!="function")return!1;if(r(o(u)))return!0;if(!n){var l=i(u);return l==="[object GeneratorFunction]"}if(!s)return!1;if(typeof c>"u"){var p=a();c=p?s(p):!1}return s(u)===c},If}var Pf,Hy;function PI(){if(Hy)return Pf;Hy=1;var e=Function.prototype.toString,t=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,r,n;if(typeof t=="function"&&typeof Object.defineProperty=="function")try{r=Object.defineProperty({},"length",{get:function(){throw n}}),n={},t(function(){throw 42},null,r)}catch(k){k!==n&&(t=null)}else t=null;var s=/^\s*class\b/,i=function(E){try{var A=e.call(E);return s.test(A)}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]",f="[object Function]",u="[object GeneratorFunction]",l="[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 S=document.all;a.call(S)===a.call(document.all)&&(w=function(E){if((g||!E)&&(typeof E>"u"||typeof E=="object"))try{var A=a.call(E);return(A===l||A===p||A===d||A===c)&&E("")==null}catch{}return!1})}return Pf=t?function(E){if(w(E))return!0;if(!E||typeof E!="function"&&typeof E!="object")return!1;try{t(E,null,r)}catch(A){if(A!==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 A=a.call(E);return A!==f&&A!==u&&!/^\[object HTML/.test(A)?!1:o(E)},Pf}var Of,zy;function OI(){if(zy)return Of;zy=1;var e=PI(),t=Object.prototype.toString,r=Object.prototype.hasOwnProperty,n=function(c,f,u){for(var l=0,p=c.length;l<p;l++)r.call(c,l)&&(u==null?f(c[l],l,c):f.call(u,c[l],l,c))},s=function(c,f,u){for(var l=0,p=c.length;l<p;l++)u==null?f(c.charAt(l),l,c):f.call(u,c.charAt(l),l,c)},i=function(c,f,u){for(var l in c)r.call(c,l)&&(u==null?f(c[l],l,c):f.call(u,c[l],l,c))};function o(a){return t.call(a)==="[object Array]"}return Of=function(c,f,u){if(!e(f))throw new TypeError("iterator must be a function");var l;arguments.length>=3&&(l=u),o(c)?n(c,f,l):typeof c=="string"?s(c,f,l):i(c,f,l)},Of}var Bf,Vy;function BI(){return Vy||(Vy=1,Bf=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),Bf}var Cf,qy;function CI(){if(qy)return Cf;qy=1;var e=BI(),t=typeof globalThis>"u"?Kr:globalThis;return Cf=function(){for(var n=[],s=0;s<e.length;s++)typeof t[e[s]]=="function"&&(n[n.length]=e[s]);return n},Cf}var Rf={exports:{}},$f,Gy;function RI(){if(Gy)return $f;Gy=1;var e=Jc(),t=aw(),r=da(),n=Ui();return $f=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,f=arguments.length>4?arguments[4]:null,u=arguments.length>5?arguments[5]:null,l=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:f===null&&p?p.writable:!f});else if(l||!c&&!f&&!u)i[o]=a;else throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},$f}var Nf,Wy;function $I(){if(Wy)return Nf;Wy=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}},Nf=t,Nf}var Mf,Ky;function NI(){if(Ky)return Mf;Ky=1;var e=dw(),t=RI(),r=$I()(),n=Ui(),s=da(),i=e("%Math.floor%");return Mf=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 f=arguments.length>2&&!!arguments[2],u=!0,l=!0;if("length"in a&&n){var p=n(a,"length");p&&!p.configurable&&(u=!1),p&&!p.writable&&(l=!1)}return(u||l||!f)&&(r?t(a,"length",c,!0,!0):t(a,"length",c)),a},Mf}var Uf,Yy;function MI(){if(Yy)return Uf;Yy=1;var e=ha(),t=fh(),r=fw();return Uf=function(){return r(e,t,arguments)},Uf}var Xy;function UI(){return Xy||(Xy=1,function(e){var t=NI(),r=Jc(),n=lh(),s=MI();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}(Rf)),Rf.exports}var Ff,Zy;function hw(){if(Zy)return Ff;Zy=1;var e=OI(),t=CI(),r=UI(),n=pa(),s=Ui(),i=dh(),o=n("Object.prototype.toString"),a=Zc()(),c=typeof globalThis>"u"?Kr:globalThis,f=t(),u=n("String.prototype.slice"),l=n("Array.prototype.indexOf",!0)||function(w,S){for(var k=0;k<w.length;k+=1)if(w[k]===S)return k;return-1},p={__proto__:null};a&&s&&i?e(f,function(g){var w=new c[g];if(Symbol.toStringTag in w&&i){var S=i(w),k=s(S,Symbol.toStringTag);if(!k&&S){var E=i(S);k=s(E,Symbol.toStringTag)}p["$"+g]=r(k.get)}}):e(f,function(g){var w=new c[g],S=w.slice||w.set;S&&(p["$"+g]=r(S))});var d=function(w){var S=!1;return e(p,function(k,E){if(!S)try{"$"+k(w)===E&&(S=u(E,1))}catch{}}),S},m=function(w){var S=!1;return e(p,function(k,E){if(!S)try{k(w),S=u(E,1)}catch{}}),S};return Ff=function(w){if(!w||typeof w!="object")return!1;if(!a){var S=u(o(w),8,-1);return l(f,S)>-1?S:S!=="Object"?!1:m(w)}return s?d(w):null},Ff}var jf,Jy;function FI(){if(Jy)return jf;Jy=1;var e=hw();return jf=function(r){return!!e(r)},jf}var Qy;function jI(){return Qy||(Qy=1,function(e){var t=_I(),r=II(),n=hw(),s=FI();function i(G){return G.call.bind(G)}var o=typeof BigInt<"u",a=typeof Symbol<"u",c=i(Object.prototype.toString),f=i(Number.prototype.valueOf),u=i(String.prototype.valueOf),l=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 S(G){return n(G)==="Uint8Array"}e.isUint8Array=S;function k(G){return n(G)==="Uint8ClampedArray"}e.isUint8ClampedArray=k;function E(G){return n(G)==="Uint16Array"}e.isUint16Array=E;function A(G){return n(G)==="Uint32Array"}e.isUint32Array=A;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 L(G){return n(G)==="Float32Array"}e.isFloat32Array=L;function T(G){return n(G)==="Float64Array"}e.isFloat64Array=T;function U(G){return n(G)==="BigInt64Array"}e.isBigInt64Array=U;function R(G){return n(G)==="BigUint64Array"}e.isBigUint64Array=R;function F(G){return c(G)==="[object Map]"}F.working=typeof Map<"u"&&F(new Map);function z(G){return typeof Map>"u"?!1:F.working?F(G):G instanceof Map}e.isMap=z;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 q(G){return c(G)==="[object ArrayBuffer]"}q.working=typeof ArrayBuffer<"u"&&q(new ArrayBuffer);function K(G){return typeof ArrayBuffer>"u"?!1:q.working?q(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 j=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function J(G){return c(G)==="[object SharedArrayBuffer]"}function ne(G){return typeof j>"u"?!1:(typeof J.working>"u"&&(J.working=J(new j)),J.working?J(G):G instanceof j)}e.isSharedArrayBuffer=ne;function le(G){return c(G)==="[object AsyncFunction]"}e.isAsyncFunction=le;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,f)}e.isNumberObject=ve;function _e(G){return m(G,u)}e.isStringObject=_e;function je(G){return m(G,l)}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 ss(G){return typeof Uint8Array<"u"&&(K(G)||ne(G))}e.isAnyArrayBuffer=ss,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(G){Object.defineProperty(e,G,{enumerable:!1,value:function(){throw new Error(G+" is not supported in userland")}})})}(Du)),Du}var Lf,em;function LI(){return em||(em=1,Lf=function(t){return t&&typeof t=="object"&&typeof t.copy=="function"&&typeof t.fill=="function"&&typeof t.readUInt8=="function"}),Lf}var Na={exports:{}},tm;function DI(){return tm||(tm=1,typeof Object.create=="function"?Na.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:Na.exports=function(t,r){if(r){t.super_=r;var n=function(){};n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t}}),Na.exports}var rm;function pw(){return rm||(rm=1,function(e){var t=Object.getOwnPropertyDescriptors||function(N){for(var j=Object.keys(N),J={},ne=0;ne<j.length;ne++)J[j[ne]]=Object.getOwnPropertyDescriptor(N,j[ne]);return J},r=/%[sdj%]/g;e.format=function(O){if(!I(O)){for(var N=[],j=0;j<arguments.length;j++)N.push(o(arguments[j]));return N.join(" ")}for(var j=1,J=arguments,ne=J.length,le=String(O).replace(r,function(oe){if(oe==="%%")return"%";if(j>=ne)return oe;switch(oe){case"%s":return String(J[j++]);case"%d":return Number(J[j++]);case"%j":try{return JSON.stringify(J[j++])}catch{return"[Circular]"}default:return oe}}),ce=J[j];j<ne;ce=J[++j])k(ce)||!T(ce)?le+=" "+ce:le+=" "+o(ce);return le},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 j=!1;function J(){if(!j){if(process.throwDeprecation)throw new Error(N);process.traceDeprecation?console.trace(N):console.error(N),j=!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 j=e.format.apply(e,arguments);console.error("%s %d: %s",O,N,j)}}else n[O]=function(){};return n[O]};function o(O,N){var j={seen:[],stylize:c};return arguments.length>=3&&(j.depth=arguments[2]),arguments.length>=4&&(j.colors=arguments[3]),S(N)?j.showHidden=N:N&&e._extend(j,N),$(j.showHidden)&&(j.showHidden=!1),$(j.depth)&&(j.depth=2),$(j.colors)&&(j.colors=!1),$(j.customInspect)&&(j.customInspect=!0),j.colors&&(j.stylize=a),u(j,O,j.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 j=o.styles[N];return j?"\x1B["+o.colors[j][0]+"m"+O+"\x1B["+o.colors[j][1]+"m":O}function c(O,N){return O}function f(O){var N={};return O.forEach(function(j,J){N[j]=!0}),N}function u(O,N,j){if(O.customInspect&&N&&F(N.inspect)&&N.inspect!==e.inspect&&!(N.constructor&&N.constructor.prototype===N)){var J=N.inspect(j,O);return I(J)||(J=u(O,J,j)),J}var ne=l(O,N);if(ne)return ne;var le=Object.keys(N),ce=f(le);if(O.showHidden&&(le=Object.getOwnPropertyNames(N)),R(N)&&(le.indexOf("message")>=0||le.indexOf("description")>=0))return p(N);if(le.length===0){if(F(N)){var oe=N.name?": "+N.name:"";return O.stylize("[Function"+oe+"]","special")}if(L(N))return O.stylize(RegExp.prototype.toString.call(N),"regexp");if(U(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=["[","]"]),F(N)){var _e=N.name?": "+N.name:"";ie=" [Function"+_e+"]"}if(L(N)&&(ie=" "+RegExp.prototype.toString.call(N)),U(N)&&(ie=" "+Date.prototype.toUTCString.call(N)),R(N)&&(ie=" "+p(N)),le.length===0&&(!he||N.length==0))return ve[0]+ie+ve[1];if(j<0)return L(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,j,ce,le):je=le.map(function(jt){return m(O,N,j,ce,jt,he)}),O.seen.pop(),g(je,ie,ve)}function l(O,N){if($(N))return O.stylize("undefined","undefined");if(I(N)){var j="'"+JSON.stringify(N).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return O.stylize(j,"string")}if(A(N))return O.stylize(""+N,"number");if(S(N))return O.stylize(""+N,"boolean");if(k(N))return O.stylize("null","null")}function p(O){return"["+Error.prototype.toString.call(O)+"]"}function d(O,N,j,J,ne){for(var le=[],ce=0,oe=N.length;ce<oe;++ce)D(N,String(ce))?le.push(m(O,N,j,J,String(ce),!0)):le.push("");return ne.forEach(function(ie){ie.match(/^\d+$/)||le.push(m(O,N,j,J,ie,!0))}),le}function m(O,N,j,J,ne,le){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?(k(j)?oe=u(O,ie.value,null):oe=u(O,ie.value,j-1),oe.indexOf(`
91
+ `)>-1&&(le?oe=oe.split(`
92
+ `).map(function(he){return" "+he}).join(`
93
+ `).slice(2):oe=`
94
+ `+oe.split(`
95
+ `).map(function(he){return" "+he}).join(`
96
+ `))):oe=O.stylize("[Circular]","special")),$(ce)){if(le&&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,j){var J=O.reduce(function(ne,le){return le.indexOf(`
97
+ `)>=0,ne+le.replace(/\u001b\[\d\d?m/g,"").length+1},0);return J>60?j[0]+(N===""?"":N+`
98
+ `)+" "+O.join(`,
99
+ `)+" "+j[1]:j[0]+N+" "+O.join(", ")+" "+j[1]}e.types=jI();function w(O){return Array.isArray(O)}e.isArray=w;function S(O){return typeof O=="boolean"}e.isBoolean=S;function k(O){return O===null}e.isNull=k;function E(O){return O==null}e.isNullOrUndefined=E;function A(O){return typeof O=="number"}e.isNumber=A;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 L(O){return T(O)&&W(O)==="[object RegExp]"}e.isRegExp=L,e.types.isRegExp=L;function T(O){return typeof O=="object"&&O!==null}e.isObject=T;function U(O){return T(O)&&W(O)==="[object Date]"}e.isDate=U,e.types.isDate=U;function R(O){return T(O)&&(W(O)==="[object Error]"||O instanceof Error)}e.isError=R,e.types.isNativeError=R;function F(O){return typeof O=="function"}e.isFunction=F;function z(O){return O===null||typeof O=="boolean"||typeof O=="number"||typeof O=="string"||typeof O=="symbol"||typeof O>"u"}e.isPrimitive=z,e.isBuffer=LI();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=DI(),e._extend=function(O,N){if(!N||!T(N))return O;for(var j=Object.keys(N),J=j.length;J--;)O[j[J]]=N[j[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 j=N[B];if(typeof j!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(j,B,{value:j,enumerable:!1,writable:!1,configurable:!0}),j}function j(){for(var J,ne,le=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 le}return Object.setPrototypeOf(j,Object.getPrototypeOf(N)),B&&Object.defineProperty(j,B,{value:j,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(j,t(N))},e.promisify.custom=B;function q(O,N){if(!O){var j=new Error("Promise was rejected with a falsy value");j.reason=O,O=j}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 j=[],J=0;J<arguments.length;J++)j.push(arguments[J]);var ne=j.pop();if(typeof ne!="function")throw new TypeError("The last argument must be of type Function");var le=this,ce=function(){return ne.apply(le,arguments)};O.apply(this,j).then(function(oe){process.nextTick(ce.bind(null,null,oe))},function(oe){process.nextTick(q.bind(null,oe,ce))})}return Object.setPrototypeOf(N,Object.getPrototypeOf(O)),Object.defineProperties(N,t(O)),N}e.callbackify=K}(Lu)),Lu}Object.defineProperty(_i,"__esModule",{value:!0});_i.encode=_i.decode=void 0;const yw=Zn;function HI(e){return(yw.isBrowser?new TextDecoder("utf-8"):new(pw()).TextDecoder("utf-8")).decode(e)}_i.decode=HI;function zI(e){return(yw.isBrowser?new TextEncoder:new(pw()).TextEncoder("utf-8")).encode(e)}_i.encode=zI;var Ti={},Hl={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 f=n(o);return a!==void 0?typeof c=="string"?f.fill(a,c):f.fill(a):f.fill(0),f},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)}})(Hl,Hl.exports);var VI=Hl.exports,Ma=VI.Buffer;function qI(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),f=Math.log(256)/Math.log(o);function u(d){if((Array.isArray(d)||d instanceof Uint8Array)&&(d=Ma.from(d)),!Ma.isBuffer(d))throw new TypeError("Expected Buffer");if(d.length===0)return"";for(var m=0,g=0,w=0,S=d.length;w!==S&&d[w]===0;)w++,m++;for(var k=(S-w)*f+1>>>0,E=new Uint8Array(k);w!==S;){for(var A=d[w],I=0,P=k-1;(A!==0||I<g)&&P!==-1;P--,I++)A+=256*E[P]>>>0,E[P]=A%o>>>0,A=A/o>>>0;if(A!==0)throw new Error("Non-zero carry");g=I,w++}for(var $=k-g;$!==k&&E[$]===0;)$++;for(var L=a.repeat(m);$<k;++$)L+=e.charAt(E[$]);return L}function l(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return Ma.alloc(0);for(var m=0,g=0,w=0;d[m]===a;)g++,m++;for(var S=(d.length-m)*c+1>>>0,k=new Uint8Array(S);m<d.length;){var E=d.charCodeAt(m);if(E>255)return;var A=t[E];if(A===255)return;for(var I=0,P=S-1;(A!==0||I<w)&&P!==-1;P--,I++)A+=o*k[P]>>>0,k[P]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");w=I,m++}for(var $=S-w;$!==S&&k[$]===0;)$++;var L=Ma.allocUnsafe(g+(S-$));L.fill(0,0,g);for(var T=g;$!==S;)L[T++]=k[$++];return L}function p(d){var m=l(d);if(m)return m;throw new Error("Non-base"+o+" character")}return{encode:u,decodeUnsafe:l,decode:p}}var GI=qI,WI=GI,KI="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",YI=WI(KI),XI=Kr&&Kr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ti,"__esModule",{value:!0});Ti.decode=Ti.encode=void 0;const mw=XI(YI);function ZI(e){return mw.default.encode(e)}Ti.encode=ZI;function JI(e){return mw.default.decode(e)}Ti.decode=JI;var ki={};Object.defineProperty(ki,"__esModule",{value:!0});ki.decode=ki.encode=void 0;const QI=Hs;function eP(e){return e.toString("base64")}ki.encode=eP;function tP(e){return QI.Buffer.from(e,"base64")}ki.decode=tP;var rP=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]}),nP=Kr&&Kr.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Qc=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)&&rP(t,e,r);return nP(t,e),t};Object.defineProperty(hn,"__esModule",{value:!0});hn.base64=hn.bs58=hn.utf8=ac=hn.hex=void 0;var ac=hn.hex=Qc(Ai);hn.utf8=Qc(_i);hn.bs58=Qc(Ti);hn.base64=Qc(ki);class Wn{constructor(t,r,n,s,i){try{this.swapId=[...ac.decode(t)],this.secretHash=[...ac.decode(n)]}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 vr.web3.PublicKey(r)}catch(o){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:o})}try{this.amount=new vr.BN(s.toString(10),10),this.expiresIn=new vr.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 gw(e){let t;try{t=[...ac.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 bw{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");if(!s)throw new Error("Program address is required");try{this.relayer=new vr.web3.PublicKey(n)}catch(o){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:o})}const i={...Dl,metadata:{...Dl.metadata??{}},address:s};try{this.program=new vr.Program(i,this.provider)}catch(o){throw new Error("Error creating Program instance. Ensure the IDL and provider are correct.",{cause:o})}}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async sendViaRelayer(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={order_id:r,serialized_tx:s,perform_on:"source"},o=await v.Fetcher.post(this.url.endpoint("/spl-initiate"),{body:JSON.stringify(i),headers:{"Content-Type":"application/json"}});return o.error?v.Err(`Error from Relayer: ${o.error}`):o.result?v.Ok(o.result):v.Err("No result returned from relayer")}catch(n){return v.Err(`Failed to send 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 kp(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)}`)}}async initiate(t){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=vr.web3.PublicKey.findProgramAddressSync(o,this.program.programId)[0];try{const a=await this.program.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction();return be.isSolanaNativeToken(t.source_swap.chain,t.source_swap.asset)?this.initiateViaHTLC(a,t):this.sendViaRelayer(a,t.create_order.create_id)}catch(a){return v.Err("Error initiating swap: ",a)}}async redeem(t,r){const{secretHash:n}=Wn.from(t),s=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=vr.web3.PublicKey.findProgramAddressSync(s,this.program.programId)[0];try{const i=gw(r),o={order_id:t.create_order.create_id,secret:Buffer.from(i).toString("hex"),perform_on:"destination"},a=await v.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify(o),headers:{"Content-Type":"application/json"}});if(a.error)return v.Err(`Redeem: Error from relayer: ${a.error}`);if(!a.result)return v.Err("Redeem: No transaction hash returned from relayer");const c=a.result;return await kp(this.provider.connection,c)?v.Ok(c):v.Err("Redeem: Timed out waiting for confirmation")}catch(i){return console.error("Redeem: Caught exception:",i),v.Err(`Error redeeming: ${i instanceof Error?i.message:String(i)}`)}}async refund(){return v.Err("Refund is automatically handled by the relayer.")}}const ww="1.37.1",sP="1.54.0",iP={"-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 vw extends Error{}class Ew extends vw{constructor(t,r){super(t),this.code=r,this.type=iP[r]??"ServerError"}}class oP extends vw{constructor(t,r,n){super(t),this.status=r,this.statusText=n}}var Sw=e=>{throw TypeError(e)},hh=(e,t,r)=>t.has(e)||Sw("Cannot "+r),Me=(e,t,r)=>(hh(e,t,"read from private field"),r?r.call(e):t.get(e)),os=(e,t,r)=>t.has(e)?Sw("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),pi=(e,t,r,n)=>(hh(e,t,"write to private field"),t.set(e,r),r),xw=(e,t,r)=>(hh(e,t,"access private method"),r),aP=(e,t,r,n)=>({set _(s){pi(e,t,s)},get _(){return Me(e,t,n)}}),Ln,po,fn,ys,Go,ms,cc,Aw,_w;function cP(e){const t=new URL(e);return t.protocol=t.protocol.replace("http","ws"),t.toString()}const uP={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5};class fP{constructor(t,r={}){if(os(this,cc),os(this,Ln,0),os(this,po,0),os(this,fn,null),os(this,ys,null),os(this,Go,new Set),os(this,ms,new Map),this.endpoint=t,this.options={...uP,...r},!this.options.WebSocketConstructor)throw new Error("Missing WebSocket constructor");this.endpoint.startsWith("http")&&(this.endpoint=cP(this.endpoint))}async makeRequest(t,r,n){const s=await xw(this,cc,Aw).call(this);return new Promise((i,o)=>{pi(this,Ln,Me(this,Ln)+1),Me(this,ms).set(Me(this,Ln),{resolve:i,reject:o,timeout:setTimeout(()=>{Me(this,ms).delete(Me(this,Ln)),o(new Error(`Request timeout: ${t}`))},this.options.callTimeout)}),n==null||n.addEventListener("abort",()=>{Me(this,ms).delete(Me(this,Ln)),o(n.reason)}),s.send(JSON.stringify({jsonrpc:"2.0",id:Me(this,Ln),method:t,params:r}))}).then(({error:i,result:o})=>{if(i)throw new Ew(i.message,i.code);return o})}async subscribe(t){const r=new lP(t);return Me(this,Go).add(r),await r.subscribe(this),()=>r.unsubscribe(this)}}Ln=new WeakMap;po=new WeakMap;fn=new WeakMap;ys=new WeakMap;Go=new WeakMap;ms=new WeakMap;cc=new WeakSet;Aw=function(){return Me(this,ys)?Me(this,ys):(pi(this,ys,new Promise(e=>{var t;(t=Me(this,fn))==null||t.close(),pi(this,fn,new this.options.WebSocketConstructor(this.endpoint)),Me(this,fn).addEventListener("open",()=>{pi(this,po,0),e(Me(this,fn))}),Me(this,fn).addEventListener("close",()=>{aP(this,po)._++,Me(this,po)<=this.options.maxReconnects&&setTimeout(()=>{xw(this,cc,_w).call(this)},this.options.reconnectTimeout)}),Me(this,fn).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&&Me(this,ms).has(n.id)){const{resolve:s,timeout:i}=Me(this,ms).get(n.id);clearTimeout(i),s(n)}else if("params"in n){const{params:s}=n;Me(this,Go).forEach(i=>{i.subscriptionId===s.subscription&&s.subscription===i.subscriptionId&&i.onMessage(s.result)})}})})),Me(this,ys))};_w=async function(){var e;return(e=Me(this,fn))==null||e.close(),pi(this,ys,null),Promise.allSettled([...Me(this,Go)].map(t=>t.subscribe(this)))};class lP{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 Tw=e=>{throw TypeError(e)},ph=(e,t,r)=>t.has(e)||Tw("Cannot "+r),nr=(e,t,r)=>(ph(e,t,"read from private field"),r?r.call(e):t.get(e)),Ua=(e,t,r)=>t.has(e)?Tw("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),zl=(e,t,r,n)=>(ph(e,t,"write to private field"),t.set(e,r),r),dP=(e,t,r)=>(ph(e,t,"access private method"),r),no,pr,yo,Vl,kw;class hP{constructor(t){Ua(this,Vl),Ua(this,no,0),Ua(this,pr),Ua(this,yo),zl(this,pr,t)}fetch(t,r){const n=nr(this,pr).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;zl(this,no,nr(this,no)+1);const r=await this.fetch(((s=nr(this,pr).rpc)==null?void 0:s.url)??nr(this,pr).url,{method:"POST",signal:t.signal,headers:{"Content-Type":"application/json","Client-Sdk-Type":"typescript","Client-Sdk-Version":ww,"Client-Target-Api-Version":sP,"Client-Request-Method":t.method,...(i=nr(this,pr).rpc)==null?void 0:i.headers},body:JSON.stringify({jsonrpc:"2.0",id:nr(this,no),method:t.method,params:t.params})});if(!r.ok)throw new oP(`Unexpected status code: ${r.status}`,r.status,r.statusText);const n=await r.json();if("error"in n&&n.error!=null)throw new Ew(n.error.message,n.error.code);return n.result}async subscribe(t){const r=await dP(this,Vl,kw).call(this).subscribe(t);return t.signal&&(t.signal.throwIfAborted(),t.signal.addEventListener("abort",()=>{r()})),async()=>!!await r()}}no=new WeakMap;pr=new WeakMap;yo=new WeakMap;Vl=new WeakSet;kw=function(){var e;if(!nr(this,yo)){const t=nr(this,pr).WebSocketConstructor??WebSocket;if(!t)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");zl(this,yo,new fP(((e=nr(this,pr).websocket)==null?void 0:e.url)??nr(this,pr).url,{WebSocketConstructor:t,...nr(this,pr).websocket}))}return nr(this,yo)};function pP(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 yP(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Iw(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 ql(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function Pw(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function Gl(e){if(!Array.isArray(e))throw new Error("array expected")}function Ow(e,t){if(!Iw(!0,t))throw new Error(`${e}: array of strings expected`)}function mP(e,t){if(!Iw(!1,t))throw new Error(`${e}: array of numbers expected`)}function gP(...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 bP(e){const t=typeof e=="string"?e.split(""):e,r=t.length;Ow("alphabet",t);const n=new Map(t.map((s,i)=>[s,i]));return{encode:s=>(Gl(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=>(Gl(s),s.map(i=>{ql("alphabet.decode",i);const o=n.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${e}`);return o}))}}function wP(e=""){return ql("join",e),{encode:t=>(Ow("join.decode",t),t.join(e)),decode:t=>(ql("join.decode",t),t.split(e))}}function nm(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(Gl(e),!e.length)return[];let n=0;const s=[],i=Array.from(e,a=>{if(Pw(a),a<0||a>=t)throw new Error(`invalid integer: ${a}`);return a}),o=i.length;for(;;){let a=0,c=!0;for(let f=n;f<o;f++){const u=i[f],l=t*a,p=l+u;if(!Number.isSafeInteger(p)||l/t!==a||p-u!==l)throw new Error("convertRadix: carry overflow");const d=p/r;a=p%r;const m=Math.floor(d);if(i[f]=m,!Number.isSafeInteger(m)||m*r+a!==p)throw new Error("convertRadix: carry overflow");if(c)m?c=!1:n=f;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 vP(e){Pw(e);const t=2**8;return{encode:r=>{if(!yP(r))throw new Error("radix.encode input should be Uint8Array");return nm(Array.from(r),t,e)},decode:r=>(mP("radix.decode",r),Uint8Array.from(nm(r,e,t)))}}const EP=e=>gP(vP(58),bP(e),wP("")),Bw=EP("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),eu=e=>Bw.encode(e),Wo=e=>Bw.decode(e);function zt(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}const Df=8192;function yt(e){if(e.length<Df)return btoa(String.fromCharCode(...e));let t="";for(var r=0;r<e.length;r+=Df){const n=e.slice(r,r+Df);t+=String.fromCharCode(...n)}return btoa(t)}function Cw(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 Ii(e){return e.reduce((t,r)=>t+r.toString(16).padStart(2,"0"),"")}function tu(e,t){return Array.from({length:Math.ceil(e.length/t)},(r,n)=>e.slice(n*t,(n+1)*t))}class Rw{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=_P(r),this._batchScheduleFn=TP(r),this._cacheKeyFn=kP(r),this._cacheMap=IP(r),this._batch=null,this.name=PP(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=xP(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(!$w(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 SP=typeof process=="object"&&typeof process.nextTick=="function"?function(e){Hf||(Hf=Promise.resolve()),Hf.then(()=>{process.nextTick(e)})}:typeof setImmediate=="function"?function(e){setImmediate(e)}:function(e){setTimeout(e)};let Hf;function xP(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(()=>{AP(e,r)}),r}function AP(e,t){if(t.hasDispatched=!0,t.keys.length===0){Wl(t);return}let r;try{r=e._batchLoadFn(t.keys)}catch(n){return zf(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 zf(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(!$w(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
+
101
+ Keys:
102
+ ${String(t.keys)}
103
+
104
+ Values:
105
+ ${String(n)}`);Wl(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=>{zf(e,t,n)})}function zf(e,t,r){Wl(t);for(let n=0;n<t.keys.length;n++)e.clear(t.keys[n]),t.callbacks[n].reject(r)}function Wl(e){if(e.cacheHits)for(let t=0;t<e.cacheHits.length;t++)e.cacheHits[t]()}function _P(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 TP(e){const t=e&&e.batchScheduleFn;if(t===void 0)return SP;if(typeof t!="function")throw new TypeError(`batchScheduleFn must be a function: ${t}`);return t}function kP(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 IP(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 PP(e){return e&&e.name?e.name:null}function $w(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 uc(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 OP(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 BP{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}=OP(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 CP(e,t){switch(t){case"base58":return eu(e);case"base64":return yt(e);case"hex":return Ii(e);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}function Nw(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 RP{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 Vf(BigInt(t),8).forEach(r=>this.write8(r)),this}write128(t){return Vf(BigInt(t),16).forEach(r=>this.write8(r)),this}write256(t){return Vf(BigInt(t),32).forEach(r=>this.write8(r)),this}writeULEB(t){return uc(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 CP(this.toBytes(),t)}}function Vf(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 Mw=e=>{throw TypeError(e)},Uw=(e,t,r)=>t.has(e)||Mw("Cannot "+r),yr=(e,t,r)=>(Uw(e,t,"read from private field"),r?r.call(e):t.get(e)),fc=(e,t,r)=>t.has(e)?Mw("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),lc=(e,t,r,n)=>(Uw(e,t,"write to private field"),t.set(e,r),r),ni,so,Xa,Dn;const $P=class Fw{constructor(t){fc(this,ni),fc(this,so),this.name=t.name,this.read=t.read,this.serializedSize=t.serializedSize??(()=>null),lc(this,ni,t.write),lc(this,so,t.serialize??((r,n)=>{const s=new RP({initialSize:this.serializedSize(r)??void 0,...n});return yr(this,ni).call(this,r,s),s.toBytes()})),this.validate=t.validate??(()=>{})}write(t,r){this.validate(t),yr(this,ni).call(this,t,r)}serialize(t,r){return this.validate(t),new NP(this,yr(this,so).call(this,t,r))}parse(t){const r=new BP(t);return this.read(r)}fromHex(t){return this.parse(Cw(t))}fromBase58(t){return this.parse(Wo(t))}fromBase64(t){return this.parse(zt(t))}transform({name:t,input:r,output:n,validate:s}){return new Fw({name:t??this.name,read:i=>n?n(this.read(i)):this.read(i),write:(i,o)=>yr(this,ni).call(this,r?r(i):i,o),serializedSize:i=>this.serializedSize(r?r(i):i),serialize:(i,o)=>yr(this,so).call(this,r?r(i):i,o),validate:i=>{s==null||s(i),this.validate(r?r(i):i)}})}};ni=new WeakMap;so=new WeakMap;let Yr=$P;const jw=Symbol.for("@mysten/serialized-bcs");function yh(e){return!!e&&typeof e=="object"&&e[jw]===!0}class NP{constructor(t,r){fc(this,Xa),fc(this,Dn),lc(this,Xa,t),lc(this,Dn,r)}get[jw](){return!0}toBytes(){return yr(this,Dn)}toHex(){return Ii(yr(this,Dn))}toBase64(){return yt(yr(this,Dn))}toBase58(){return eu(yr(this,Dn))}parse(){return yr(this,Xa).parse(yr(this,Dn))}}Xa=new WeakMap;Dn=new WeakMap;function dc({size:e,...t}){return new Yr({...t,serializedSize:()=>e})}function qf({readMethod:e,writeMethod:t,...r}){return dc({...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 Gf({readMethod:e,writeMethod:t,...r}){return dc({...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 MP({serialize:e,...t}){const r=new Yr({...t,serialize:e,write:(n,s)=>{for(const i of r.serialize(n).toBytes())s.write8(i)}});return r}function UP({toBytes:e,fromBytes:t,...r}){return new Yr({...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=uc(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 FP(e){let t=null;function r(){return t||(t=e()),t}return new Yr({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 jP extends Yr{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 f=c.serializedSize(i[a]);if(f==null)return null;o+=f}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 LP extends Yr{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[f,u]=n[c];if(f===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 DP extends Yr{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 HP(e,t,r){return new Yr({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 zP(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 VP(e,t){return new Yr({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 qP(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 qf({readMethod:"read8",writeMethod:"write8",size:1,maxValue:2**8-1,...e,name:(e==null?void 0:e.name)??"u8"})},u16(e){return qf({readMethod:"read16",writeMethod:"write16",size:2,maxValue:2**16-1,...e,name:(e==null?void 0:e.name)??"u16"})},u32(e){return qf({readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...e,name:(e==null?void 0:e.name)??"u32"})},u64(e){return Gf({readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...e,name:(e==null?void 0:e.name)??"u64"})},u128(e){return Gf({readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...e,name:(e==null?void 0:e.name)??"u128"})},u256(e){return Gf({readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...e,name:(e==null?void 0:e.name)??"u256"})},bool(e){return dc({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 MP({read:t=>t.readULEB(),serialize:t=>Uint8Array.from(uc(t)),...e,name:(e==null?void 0:e.name)??"uleb128"})},bytes(e,t){return dc({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 Yr({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:uc(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 UP({toBytes:t=>new TextEncoder().encode(t),fromBytes:t=>new TextDecoder().decode(t),...e,name:(e==null?void 0:e.name)??"string"})},fixedArray:HP,option:zP,vector:VP,tuple(e,t){return new DP({fields:e,...t})},struct(e,t,r){return new jP({name:e,fields:t,...r})},enum(e,t,r){return new LP({name:e,fields:t,...r})},map:qP,lazy(e){return FP(e)}};var Lw=e=>{throw TypeError(e)},Dw=(e,t,r)=>t.has(e)||Lw("Cannot "+r),ht=(e,t,r)=>(Dw(e,t,"read from private field"),t.get(e)),sm=(e,t,r)=>t.has(e)?Lw("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),im=(e,t,r,n)=>(Dw(e,t,"write to private field"),t.set(e,r),r),us,_t;const GP=class Hw{constructor({prefix:t,cache:r}={}){sm(this,us),sm(this,_t),im(this,us,t??[]),im(this,_t,r??new Map)}read(t,r){const n=[ht(this,us),...t].join(":");if(ht(this,_t).has(n))return ht(this,_t).get(n);const s=r();return ht(this,_t).set(n,s),typeof s=="object"&&s!==null&&"then"in s?Promise.resolve(s).then(i=>(ht(this,_t).set(n,i),i)).catch(i=>{throw ht(this,_t).delete(n),i}):s}readSync(t,r){const n=[ht(this,us),...t].join(":");if(ht(this,_t).has(n))return ht(this,_t).get(n);const s=r();return ht(this,_t).set(n,s),s}clear(t){const r=[...ht(this,us),...t??[]].join(":");if(!r){ht(this,_t).clear();return}for(const n of ht(this,_t).keys())n.startsWith(r)&&ht(this,_t).delete(n)}scope(t){return new Hw({prefix:[...ht(this,us),...Array.isArray(t)?t:[t]],cache:ht(this,_t)})}};us=new WeakMap;_t=new WeakMap;let WP=GP;class zw{constructor({network:t,base:r,cache:n=(r==null?void 0:r.cache)??new WP}){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 Vw=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,qw=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i,KP=235;function YP(e){return e.length>KP?!1:e.includes("@")?Vw.test(e):qw.test(e)}function XP(e,t="at"){const r=e.toLowerCase();let n;if(r.includes("@")){if(!Vw.test(r))throw new Error(`Invalid SuiNS name ${e}`);const[s,i]=r.split("@");n=[...s?s.split("."):[],i]}else{if(!qw.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 ZP=/^([a-z0-9]+(?:-[a-z0-9]+)*)$/,JP=/^\d+$/,QP=64,Gw="/",Dt=e=>{const t=e.split(Gw);if(t.length<2||t.length>3)return!1;const[r,n,s]=t;return s!==void 0&&!JP.test(s)||!YP(r)?!1:ZP.test(n)&&n.length<QP},e5=e=>{const t=e.split(/::|<|>|,/);for(const r of t)if(r.includes(Gw)&&!Dt(r))return!1;return!0},t5=32;function om(e){try{return Wo(e).length===t5}catch{return!1}}const ru=32;function mr(e){return n5(e)&&s5(e)===ru}function Fa(e){return mr(e)}function r5(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("<")?Nw(s.slice(s.indexOf("<")+1,s.lastIndexOf(">"))).map(a=>r5(a.trim())):[];return{address:n?t:xe(t),module:r,name:i,typeParams:o}}function hc(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:hc(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(ru*2,"0")}`}function pn(e,t=!1){return xe(e,t)}function n5(e){return/^(0x|0X)?[a-fA-F0-9]+$/.test(e)&&e.length%2===0}function s5(e){return/^(0x|0X)/.test(e)?(e.length-2)/2:e.length/2}const i5=/^vector<(.+)>$/,o5=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class br{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(i5);if(n)return{vector:br.parseFromStr(n[1],r)};const s=t.match(o5);if(s)return{struct:{address:r?xe(s[1]):s[1],module:s[2],name:s[3],typeParams:s[5]===void 0?[]:br.parseStructTypeArgs(s[5],r)}};throw new Error(`Encountered unexpected token when parsing type args for ${t}`)}static parseStructTypeArgs(t,r=!1){return Nw(t).map(n=>br.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<${br.tagToString(t.vector)}>`;if("struct"in t){const r=t.struct,n=r.typeParams.map(br.tagToString).join(", ");return`${r.address}::${r.module}::${r.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}function a5(e){return _.u64({name:"unsafe_u64",...e}).transform({input:t=>t,output:t=>Number(t)})}function c5(e){return _.enum("Option",{None:null,Some:e})}const Re=_.bytes(ru).transform({validate:e=>{const t=typeof e=="string"?e:Ii(e);if(!t||!mr(xe(t)))throw new Error(`Invalid Sui address ${t}`)},input:e=>typeof e=="string"?Cw(xe(e)):e,output:e=>xe(Ii(e))}),Er=_.vector(_.u8()).transform({name:"ObjectDigest",input:e=>Wo(e),output:e=>eu(new Uint8Array(e)),validate:e=>{if(Wo(e).length!==32)throw new Error("ObjectDigest must be 32 bytes")}}),tr=_.struct("SuiObjectRef",{objectId:Re,version:_.u64(),digest:Er}),Ww=_.struct("SharedObjectRef",{objectId:Re,initialSharedVersion:_.u64(),mutable:_.bool()}),Kw=_.enum("ObjectArg",{ImmOrOwnedObject:tr,SharedObject:Ww,Receiving:tr}),gs=_.enum("Owner",{AddressOwner:Re,ObjectOwner:Re,Shared:_.struct("Shared",{initialSharedVersion:_.u64()}),Immutable:null,ConsensusAddressOwner:_.struct("ConsensusAddressOwner",{owner:Re,startVersion:_.u64()})}),Yw=_.enum("CallArg",{Pure:_.struct("Pure",{bytes:_.vector(_.u8()).transform({input:e=>typeof e=="string"?zt(e):e,output:e=>yt(new Uint8Array(e))})}),Object:Kw}),mh=_.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:_.lazy(()=>mh),struct:_.lazy(()=>t1),u16:null,u32:null,u256:null}),gh=mh.transform({input:e=>typeof e=="string"?br.parseFromStr(e,!0):e,output:e=>br.tagToString(e)}),Dr=_.enum("Argument",{GasCoin:null,Input:_.u16(),Result:_.u16(),NestedResult:_.tuple([_.u16(),_.u16()])}),Xw=_.struct("ProgrammableMoveCall",{package:Re,module:_.string(),function:_.string(),typeArguments:_.vector(gh),arguments:_.vector(Dr)}),Zw=_.enum("Command",{MoveCall:Xw,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:c5(gh).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})}),Jw=_.struct("ProgrammableTransaction",{inputs:_.vector(Yw),commands:_.vector(Zw)}),Qw=_.enum("TransactionKind",{ProgrammableTransaction:Jw,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),e1=_.enum("TransactionExpiration",{None:null,Epoch:a5()}),t1=_.struct("StructTag",{address:Re,module:_.string(),name:_.string(),typeParams:_.vector(mh)}),r1=_.struct("GasData",{payment:_.vector(tr),owner:Re,price:_.u64(),budget:_.u64()}),n1=_.struct("TransactionDataV1",{kind:Qw,sender:Re,gasData:r1,expiration:e1}),s1=_.enum("TransactionData",{V1:n1}),i1=_.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),o1=_.enum("IntentVersion",{V0:null}),a1=_.enum("AppId",{Sui:null}),c1=_.struct("Intent",{scope:i1,version:o1,appId:a1});function u1(e){return _.struct(`IntentMessage<${e.name}>`,{intent:c1,value:e})}const f1=_.enum("CompressedSignature",{ED25519:_.fixedArray(64,_.u8()),Secp256k1:_.fixedArray(64,_.u8()),Secp256r1:_.fixedArray(64,_.u8()),ZkLogin:_.vector(_.u8()),Passkey:_.vector(_.u8())}),l1=_.enum("PublicKey",{ED25519:_.fixedArray(32,_.u8()),Secp256k1:_.fixedArray(33,_.u8()),Secp256r1:_.fixedArray(33,_.u8()),ZkLogin:_.vector(_.u8()),Passkey:_.fixedArray(33,_.u8())}),d1=_.struct("MultiSigPkMap",{pubKey:l1,weight:_.u8()}),h1=_.struct("MultiSigPublicKey",{pk_map:_.vector(d1),threshold:_.u16()}),u5=_.struct("MultiSig",{sigs:_.vector(f1),bitmap:_.u16(),multisig_pk:h1}),f5=_.vector(_.u8()).transform({input:e=>typeof e=="string"?zt(e):e,output:e=>yt(new Uint8Array(e))}),p1=_.struct("SenderSignedTransaction",{intentMessage:u1(s1),txSignatures:_.vector(f5)}),l5=_.vector(p1,{name:"SenderSignedData"}),d5=_.struct("PasskeyAuthenticator",{authenticatorData:_.vector(_.u8()),clientDataJson:_.string(),userSignature:_.vector(_.u8())}),h5=_.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})}),p5=_.struct("ModuleId",{address:Re,name:_.string()}),am=_.struct("MoveLocation",{module:p5,function:_.u16(),instruction:_.u16(),functionName:_.option(_.string())}),y5=_.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}),m5=_.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),g5=_.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(am),MoveAbort:_.tuple([am,_.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:_.struct("CommandArgumentError",{argIdx:_.u16(),kind:y5}),TypeArgumentError:_.struct("TypeArgumentError",{argumentIdx:_.u16(),kind:m5}),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:h5}),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}),y1=_.enum("ExecutionStatus",{Success:null,Failed:_.struct("ExecutionFailed",{error:g5,command:_.option(_.u64())})}),m1=_.struct("GasCostSummary",{computationCost:_.u64(),storageCost:_.u64(),storageRebate:_.u64(),nonRefundableStorageFee:_.u64()}),b5=_.struct("TransactionEffectsV1",{status:y1,executedEpoch:_.u64(),gasUsed:m1,modifiedAtVersions:_.vector(_.tuple([Re,_.u64()])),sharedObjects:_.vector(tr),transactionDigest:Er,created:_.vector(_.tuple([tr,gs])),mutated:_.vector(_.tuple([tr,gs])),unwrapped:_.vector(_.tuple([tr,gs])),deleted:_.vector(tr),unwrappedThenDeleted:_.vector(tr),wrapped:_.vector(tr),gasObject:_.tuple([tr,gs]),eventsDigest:_.option(Er),dependencies:_.vector(Er)}),bh=_.tuple([_.u64(),Er]),w5=_.enum("ObjectIn",{NotExist:null,Exist:_.tuple([bh,gs])}),v5=_.enum("ObjectOut",{NotExist:null,ObjectWrite:_.tuple([Er,gs]),PackageWrite:bh}),E5=_.enum("IDOperation",{None:null,Created:null,Deleted:null}),S5=_.struct("EffectsObjectChange",{inputState:w5,outputState:v5,idOperation:E5}),x5=_.enum("UnchangedSharedKind",{ReadOnlyRoot:bh,MutateDeleted:_.u64(),ReadDeleted:_.u64(),Cancelled:_.u64(),PerEpochConfig:null}),A5=_.struct("TransactionEffectsV2",{status:y1,executedEpoch:_.u64(),gasUsed:m1,transactionDigest:Er,gasObjectIndex:_.option(_.u32()),eventsDigest:_.option(Er),dependencies:_.vector(Er),lamportVersion:_.u64(),changedObjects:_.vector(_.tuple([Re,S5])),unchangedSharedObjects:_.vector(_.tuple([Re,x5])),auxDataDigest:_.option(Er)}),_5=_.enum("TransactionEffects",{V1:b5,V2:A5});function mo(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(mo(n)):_.option(mo(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:a1,Argument:Dr,CallArg:Yw,Command:Zw,CompressedSignature:f1,GasData:r1,Intent:c1,IntentMessage:u1,IntentScope:i1,IntentVersion:o1,MultiSig:u5,MultiSigPkMap:d1,MultiSigPublicKey:h1,ObjectArg:Kw,ObjectDigest:Er,Owner:gs,PasskeyAuthenticator:d5,ProgrammableMoveCall:Xw,ProgrammableTransaction:Jw,PublicKey:l1,SenderSignedData:l5,SenderSignedTransaction:p1,SharedObjectRef:Ww,StructTag:t1,SuiObjectRef:tr,TransactionData:s1,TransactionDataV1:n1,TransactionEffects:_5,TransactionExpiration:e1,TransactionKind:Qw,TypeTag:gh};var nn;function T5(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 Wf;function k5(e){return Wf==null?void 0:Wf.get(e)}var Kf;function I5(e){return Kf==null?void 0:Kf.get(e)}var Yf;function P5(e,t){var r;return(r=Yf==null?void 0:Yf.get(e))==null?void 0:r.get(t)}function g1(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)??g1(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},f=e.kind==="schema",u=(s==null?void 0:s.message)??e.message??P5(e.reference,c.lang)??(f?I5(c.lang):null)??n.message??k5(c.lang);u&&(c.message=typeof u=="function"?u(c):u),f&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function O5(e,t){return Object.hasOwn(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}var B5=class extends Error{constructor(t){super(t[0].message);Ih(this,"issues");this.name="ValiError",this.issues=t}};function ya(e,t){return{kind:"validation",type:"check",reference:ya,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 nu(e){return{kind:"transformation",type:"transform",reference:nu,async:!1,operation:e,_run(t){return t.value=this.operation(t.value),t}}}function wh(e,t,r){return typeof e.default=="function"?e.default(t,r):e.default}function Kl(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 f={type:"array",origin:"value",input:s,key:o,value:a};for(const u of c.issues)u.path?u.path.unshift(f):u.path=[f],(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 vh(e){return{kind:"schema",type:"bigint",reference:vh,expects:"bigint",async:!1,message:e,_run(t,r){return typeof t.value=="bigint"?t.typed=!0:Wt(this,"type",t,r),t}}}function su(e){return{kind:"schema",type:"boolean",reference:su,expects:"boolean",async:!1,message:e,_run(t,r){return typeof t.value=="boolean"?t.typed=!0:Wt(this,"type",t,r),t}}}function Ko(e){return{kind:"schema",type:"lazy",reference:Ko,expects:"unknown",async:!1,getter:e,_run(t,r){return this.getter(t.value)._run(t,r)}}}function fe(e,t){return{kind:"schema",type:"literal",reference:fe,expects:g1(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=wh(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 Pi(e,...t){const r={kind:"schema",type:"nullish",reference:Pi,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=wh(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 f={type:"object",origin:"value",input:s,key:o,value:a};for(const u of c.issues)u.path?u.path.unshift(f):u.path=[f],(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 lt(e,...t){const r={kind:"schema",type:"optional",reference:lt,expects:`${e.expects} | undefined`,async:!1,wrapped:e,_run(n,s){return n.value===void 0&&("default"in this&&(n.value=wh(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 Yo(e,t,r){return{kind:"schema",type:"record",reference:Yo,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(O5(i,c)){const f=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:f};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 l=this.value._run({typed:!1,value:f},s);if(l.issues){const p={type:"object",origin:"value",input:i,key:c,value:f};for(const d of l.issues)d.path?d.path.unshift(p):d.path=[p],(a=n.issues)==null||a.push(d);if(n.issues||(n.issues=l.issues),s.abortEarly){n.typed=!1;break}}(!u.typed||!l.typed)&&(n.typed=!1),u.typed&&(n.value[u.value]=l.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 Eh(e,t){return{kind:"schema",type:"tuple",reference:Eh,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 f={type:"array",origin:"value",input:s,key:o,value:a};for(const u of c.issues)u.path?u.path.unshift(f):u.path=[f],(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 cm(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:cm(i)}),r.typed=!0}else{if((o==null?void 0:o.length)===1)return o[0];Wt(this,"type",r,n,{issues:cm(o)})}return r}}}function Ms(){return{kind:"schema",type:"unknown",reference:Ms,expects:"unknown",async:!1,_run(e){return e.typed=!0,e}}}function qe(e,t,r){const n=e._run({typed:!1,value:t},T5(r));if(n.issues)throw new B5(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 qs(e){const t=Object.entries(e).map(([r,n])=>ee({[r]:n}));return Pe(dt(t),nu(r=>({...r,$kind:Object.keys(r)[0]})))}const Fi=Pe(ye(),nu(e=>xe(e)),ya(mr)),Vt=Fi,Us=ye(),Mt=Pe(dt([ye(),Pe(De(),Ge())]),ya(e=>{try{return BigInt(e),BigInt(e)>=0&&BigInt(e)<=18446744073709551615n}catch{return!1}},"Invalid u64")),rs=ee({objectId:Fi,version:Mt,digest:ye()}),Ue=Pe(dt([ee({GasCoin:fe(!0)}),ee({Input:Pe(De(),Ge()),type:lt(fe("pure"))}),ee({Input:Pe(De(),Ge()),type:lt(fe("object"))}),ee({Result:Pe(De(),Ge())}),ee({NestedResult:Eh([Pe(De(),Ge()),Pe(De(),Ge())])})]),nu(e=>({...e,$kind:Object.keys(e)[0]}))),C5=ee({budget:Ee(Mt),price:Ee(Mt),owner:Ee(Fi),payment:Ee(ue(rs))}),Yl=dt([fe("address"),fe("bool"),fe("u8"),fe("u16"),fe("u32"),fe("u64"),fe("u128"),fe("u256"),ee({vector:Ko(()=>Yl)}),ee({datatype:ee({package:ye(),module:ye(),type:ye(),typeParameters:ue(Ko(()=>Yl))})}),ee({typeParameter:Pe(De(),Ge())})]),R5=ee({ref:Ee(dt([fe("&"),fe("&mut")])),body:Yl}),$5=ee({package:Vt,module:ye(),function:ye(),typeArguments:ue(ye()),arguments:ue(Ue),_argumentTypes:lt(Ee(ue(R5)))}),N5=ee({name:ye(),inputs:Yo(ye(),dt([Ue,ue(Ue)])),data:Yo(ye(),Ms())}),M5=qs({MoveCall:$5,TransferObjects:ee({objects:ue(Ue),address:Ue}),SplitCoins:ee({coin:Ue,amounts:ue(Ue)}),MergeCoins:ee({destination:Ue,sources:ue(Ue)}),Publish:ee({modules:ue(Us),dependencies:ue(Vt)}),MakeMoveVec:ee({type:Ee(ye()),elements:ue(Ue)}),Upgrade:ee({modules:ue(Us),dependencies:ue(Vt),package:Vt,ticket:Ue}),$Intent:N5}),b1=qs({ImmOrOwnedObject:rs,SharedObject:ee({objectId:Vt,initialSharedVersion:Mt,mutable:su()}),Receiving:rs}),U5=qs({Object:b1,Pure:ee({bytes:Us}),UnresolvedPure:ee({value:Ms()}),UnresolvedObject:ee({objectId:Vt,version:lt(Ee(Mt)),digest:lt(Ee(ye())),initialSharedVersion:lt(Ee(Mt))})}),um=qs({Object:b1,Pure:ee({bytes:Us})}),w1=qs({None:fe(!0),Epoch:Mt}),Za=ee({version:fe(2),sender:Pi(Fi),expiration:Pi(w1),gasData:C5,inputs:ue(U5),commands:ue(M5)}),as={MoveCall(e){const[t,r="",n=""]="target"in e?e.target.split("::"):[e.package,e.module,e.function];return{$kind:"MoveCall",MoveCall:{package:t,module:r,function:n,typeArguments:e.typeArguments??[],arguments:e.arguments??[]}}},TransferObjects(e,t){return{$kind:"TransferObjects",TransferObjects:{objects:e.map(r=>qe(Ue,r)),address:qe(Ue,t)}}},SplitCoins(e,t){return{$kind:"SplitCoins",SplitCoins:{coin:qe(Ue,e),amounts:t.map(r=>qe(Ue,r))}}},MergeCoins(e,t){return{$kind:"MergeCoins",MergeCoins:{destination:qe(Ue,e),sources:t.map(r=>qe(Ue,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:qe(Ue,n)}}},MakeMoveVec({type:e,elements:t}){return{$kind:"MakeMoveVec",MakeMoveVec:{type:e??null,elements:t.map(r=>qe(Ue,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=>qe(Ue,i)):qe(Ue,s)])),data:r}}}},Xl=ee({digest:ye(),objectId:ye(),version:dt([Pe(De(),Ge()),ye(),vh()])}),F5=qs({ImmOrOwned:Xl,Shared:ee({objectId:Vt,initialSharedVersion:Mt,mutable:su()}),Receiving:Xl}),fm=qs({Object:F5,Pure:ue(Pe(De(),Ge()))}),v1=dt([ee({kind:fe("Input"),index:Pe(De(),Ge()),value:Ms(),type:lt(fe("object"))}),ee({kind:fe("Input"),index:Pe(De(),Ge()),value:Ms(),type:fe("pure")})]),j5=dt([ee({Epoch:Pe(De(),Ge())}),ee({None:Ee(fe(!0))})]),lm=Pe(dt([De(),ye(),vh()]),ya(e=>{if(!["string","number","bigint"].includes(typeof e))return!1;try{return BigInt(e),!0}catch{return!1}})),Sh=dt([ee({bool:Ee(fe(!0))}),ee({u8:Ee(fe(!0))}),ee({u64:Ee(fe(!0))}),ee({u128:Ee(fe(!0))}),ee({address:Ee(fe(!0))}),ee({signer:Ee(fe(!0))}),ee({vector:Ko(()=>Sh)}),ee({struct:Ko(()=>L5)}),ee({u16:Ee(fe(!0))}),ee({u32:Ee(fe(!0))}),ee({u256:Ee(fe(!0))})]),L5=ee({address:ye(),module:ye(),name:ye(),typeParams:ue(Sh)}),D5=ee({budget:lt(lm),price:lt(lm),payment:lt(ue(Xl)),owner:lt(ye())}),H5=[v1,ee({kind:fe("GasCoin")}),ee({kind:fe("Result"),index:Pe(De(),Ge())}),ee({kind:fe("NestedResult"),index:Pe(De(),Ge()),resultIndex:Pe(De(),Ge())})],xn=dt([...H5]),z5=ee({kind:fe("MoveCall"),target:Pe(ye(),ya(e=>e.split("::").length===3)),typeArguments:ue(ye()),arguments:ue(xn)}),V5=ee({kind:fe("TransferObjects"),objects:ue(xn),address:xn}),q5=ee({kind:fe("SplitCoins"),coin:xn,amounts:ue(xn)}),G5=ee({kind:fe("MergeCoins"),destination:xn,sources:ue(xn)}),W5=ee({kind:fe("MakeMoveVec"),type:dt([ee({Some:Sh}),ee({None:Ee(fe(!0))})]),objects:ue(xn)}),K5=ee({kind:fe("Publish"),modules:ue(ue(Pe(De(),Ge()))),dependencies:ue(ye())}),Y5=ee({kind:fe("Upgrade"),modules:ue(ue(Pe(De(),Ge()))),dependencies:ue(ye()),packageId:ye(),ticket:xn}),X5=[z5,V5,q5,G5,K5,Y5,W5],Z5=dt([...X5]);ee({version:fe(1),sender:lt(ye()),expiration:Pi(j5),gasConfig:D5,inputs:ue(v1),transactions:ue(Z5)});function dm(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:br.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 J5(e){var t,r,n;return qe(Za,{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(Kl(fm,s.value)){const i=qe(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?br.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 ma(e){return dt(Object.entries(e).map(([t,r])=>ee({[t]:r})))}const hr=ma({GasCoin:fe(!0),Input:Pe(De(),Ge()),Result:Pe(De(),Ge()),NestedResult:Eh([Pe(De(),Ge()),Pe(De(),Ge())])}),Q5=ee({budget:Ee(Mt),price:Ee(Mt),owner:Ee(Fi),payment:Ee(ue(rs))}),eO=ee({package:Vt,module:ye(),function:ye(),typeArguments:ue(ye()),arguments:ue(hr)}),tO=ee({name:ye(),inputs:Yo(ye(),dt([hr,ue(hr)])),data:Yo(ye(),Ms())}),rO=ma({MoveCall:eO,TransferObjects:ee({objects:ue(hr),address:hr}),SplitCoins:ee({coin:hr,amounts:ue(hr)}),MergeCoins:ee({destination:hr,sources:ue(hr)}),Publish:ee({modules:ue(Us),dependencies:ue(Vt)}),MakeMoveVec:ee({type:Ee(ye()),elements:ue(hr)}),Upgrade:ee({modules:ue(Us),dependencies:ue(Vt),package:Vt,ticket:hr}),$Intent:tO}),nO=ma({ImmOrOwnedObject:rs,SharedObject:ee({objectId:Vt,initialSharedVersion:Mt,mutable:su()}),Receiving:rs}),sO=ma({Object:nO,Pure:ee({bytes:Us}),UnresolvedPure:ee({value:Ms()}),UnresolvedObject:ee({objectId:Vt,version:lt(Ee(Mt)),digest:lt(Ee(ye())),initialSharedVersion:lt(Ee(Mt))})}),iO=ma({None:fe(!0),Epoch:Mt}),oO=ee({version:fe(2),sender:Pi(Fi),expiration:Pi(iO),gasData:Q5,inputs:ue(sO),commands:ue(rO),digest:lt(Ee(ye()))});function aO(e){return{$kind:"Pure",Pure:{bytes:e instanceof Uint8Array?yt(e):e.toBase64()}}}const yn={Pure:aO,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 cO="0x1",E1="0x2",uO=pn("0x6"),fO=`${E1}::sui::SUI`;pn("0x5");const lO=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 Mn(e,t,r,n,s,i){const o=s[i],a=s[i+1];let c=te[2*e],f=te[2*e+1],u=te[2*t],l=te[2*t+1],p=te[2*r],d=te[2*r+1],m=te[2*n],g=te[2*n+1],w=Xm(c,u,o);f=Zm(w,f,l,a),c=w|0,{Dh:g,Dl:m}={Dh:g^f,Dl:m^c},{Dh:g,Dl:m}={Dh:iv(g,m),Dl:ov(g)},{h:d,l:p}=Ym(d,p,g,m),{Bh:l,Bl:u}={Bh:l^d,Bl:u^p},{Bh:l,Bl:u}={Bh:Wm(l,u,24),Bl:Km(l,u,24)},te[2*e]=c,te[2*e+1]=f,te[2*t]=u,te[2*t+1]=l,te[2*r]=p,te[2*r+1]=d,te[2*n]=m,te[2*n+1]=g}function Un(e,t,r,n,s,i){const o=s[i],a=s[i+1];let c=te[2*e],f=te[2*e+1],u=te[2*t],l=te[2*t+1],p=te[2*r],d=te[2*r+1],m=te[2*n],g=te[2*n+1],w=Xm(c,u,o);f=Zm(w,f,l,a),c=w|0,{Dh:g,Dl:m}={Dh:g^f,Dl:m^c},{Dh:g,Dl:m}={Dh:Wm(g,m,16),Dl:Km(g,m,16)},{h:d,l:p}=Ym(d,p,g,m),{Bh:l,Bl:u}={Bh:l^d,Bl:u^p},{Bh:l,Bl:u}={Bh:nv(l,u,63),Bl:sv(l,u,63)},te[2*e]=c,te[2*e+1]=f,te[2*t]=u,te[2*t+1]=l,te[2*r]=p,te[2*r+1]=d,te[2*n]=m,te[2*n+1]=g}function dO(e,t={},r,n,s){if(Jn(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 hO extends gc{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Jn(t),Jn(r),this.blockLen=t,this.outputLen=r,this.buffer=new Uint8Array(t),this.buffer32=wo(this.buffer)}update(t){Qn(this),t=mn(t),ur(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 f=Math.min(r-this.pos,i-c),u=o+c;if(f===r&&!(u%4)&&c+f<i){const l=new Uint32Array(a,u,Math.floor((i-c)/4));Hn(l);for(let p=0;c+r<i;p+=s.length,c+=r)this.length+=r,this.compress(l,p,!1);Hn(l);continue}n.set(t.subarray(c,c+f),this.pos),this.pos+=f,this.length+=f,c+=f}return this}digestInto(t){Qn(this),ad(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=wo(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 pO extends hO{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,dO(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=wo(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=wo(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:f,v4h:u,v5l:l,v5h:p,v6l:d,v6h:m,v7l:g,v7h:w}=this;return[t,r,n,s,i,o,a,c,f,u,l,p,d,m,g,w]}set(t,r,n,s,i,o,a,c,f,u,l,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=f|0,this.v4h=u|0,this.v5l=l|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,f)=>te[f]=c),te.set(tt,16);let{h:s,l:i}=Gm(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=lO;for(let c=0;c<12;c++)Mn(0,4,8,12,t,r+2*a[o++]),Un(0,4,8,12,t,r+2*a[o++]),Mn(1,5,9,13,t,r+2*a[o++]),Un(1,5,9,13,t,r+2*a[o++]),Mn(2,6,10,14,t,r+2*a[o++]),Un(2,6,10,14,t,r+2*a[o++]),Mn(3,7,11,15,t,r+2*a[o++]),Un(3,7,11,15,t,r+2*a[o++]),Mn(0,5,10,15,t,r+2*a[o++]),Un(0,5,10,15,t,r+2*a[o++]),Mn(1,6,11,12,t,r+2*a[o++]),Un(1,6,11,12,t,r+2*a[o++]),Mn(2,7,8,13,t,r+2*a[o++]),Un(2,7,8,13,t,r+2*a[o++]),Mn(3,4,9,14,t,r+2*a[o++]),Un(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 yO=yv(e=>new pO(e)),S1=yO;function mO(e,t,r){const n=de.Address.serialize(e).toBytes(),s=de.TypeTag.serialize(t).toBytes(),i=de.u64().serialize(r.length).toBytes(),o=S1.create({dkLen:32});return o.update(new Uint8Array([240])),o.update(n),o.update(i),o.update(r),o.update(s),`0x${Ii(o.digest().slice(0,32))}`}const gO="object",bO="ID",wO="ascii",vO="String",EO="string",SO="String",xO="option",AO="Option";function _O(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 Zl(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=Zl(e.vector);return t?de.vector(t):null}if("datatype"in e){const t=xe(e.datatype.package);if(t===xe(cO)){if(e.datatype.module===wO&&e.datatype.type===vO||e.datatype.module===EO&&e.datatype.type===SO)return de.String;if(e.datatype.module===xO&&e.datatype.type===AO){const r=Zl(e.datatype.typeParameters[0]);return r?de.vector(r):null}}if(t===xe(E1)&&e.datatype.module===gO&&e.datatype.type===bO)return de.Address}return null}function TO(e){return typeof e=="object"&&"Reference"in e?{ref:"&",body:go(e.Reference)}:typeof e=="object"&&"MutableReference"in e?{ref:"&mut",body:go(e.MutableReference)}:{ref:null,body:go(e)}}function go(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:go(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(go)}};if("TypeParameter"in e)return{typeParameter:e.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(e)}`)}const kO=50,IO=1000n,PO=5e10;function x1(e){return async function(r,n,s){return await $O(r,e),await RO(r,e),n.onlyTransactionKind||(await OO(r,e),await BO(r,e),await CO(r,e)),await s()}}async function OO(e,t){e.gasConfig.price||(e.gasConfig.price=String(await t.getReferenceGasPrice()))}async function BO(e,t){if(e.gasConfig.budget)return;const r=await t.dryRunTransactionBlock({transactionBlock:e.build({overrides:{gasData:{budget:String(PO),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=IO*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 CO(e,t){if(!e.gasConfig.payment){const n=(await t.getCoins({owner:e.gasConfig.owner||e.sender,coinType:fO})).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=>qe(rs,s))}}async function RO(e,t){const r=e.inputs.filter(u=>{var l;return u.UnresolvedObject&&!(u.UnresolvedObject.version||(l=u.UnresolvedObject)!=null&&l.initialSharedVersion)}),n=[...new Set(r.map(u=>pn(u.UnresolvedObject.objectId)))],s=n.length?tu(n,kO):[],i=(await Promise.all(s.map(u=>t.multiGetObjects({ids:u,options:{showOwner:!0}})))).flat(),o=new Map(n.map((u,l)=>[u,i[l]])),a=Array.from(o).filter(([u,l])=>l.error).map(([u,l])=>JSON.stringify(l.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 l=u.data.owner,p=l&&typeof l=="object"?"Shared"in l?l.Shared.initial_shared_version:"ConsensusAddressOwner"in l?l.ConsensusAddressOwner.start_version:null:null;return{objectId:u.data.objectId,digest:u.data.digest,version:u.data.version,initialSharedVersion:p}}),f=new Map(n.map((u,l)=>[u,c[l]]));for(const[u,l]of e.inputs.entries()){if(!l.UnresolvedObject)continue;let p;const d=xe(l.UnresolvedObject.objectId),m=f.get(d);l.UnresolvedObject.initialSharedVersion??(m==null?void 0:m.initialSharedVersion)?p=yn.SharedObjectRef({objectId:d,initialSharedVersion:l.UnresolvedObject.initialSharedVersion||(m==null?void 0:m.initialSharedVersion),mutable:NO(e,u)}):MO(e,u)&&(p=yn.ReceivingRef({objectId:d,digest:l.UnresolvedObject.digest??(m==null?void 0:m.digest),version:l.UnresolvedObject.version??(m==null?void 0:m.version)})),e.inputs[e.inputs.indexOf(l)]=p??yn.ObjectRef({objectId:d,digest:l.UnresolvedObject.digest??(m==null?void 0:m.digest),version:l.UnresolvedObject.version??(m==null?void 0:m.version)})}}async function $O(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,f,u]=a.split("::"),l=await t.getNormalizedMoveFunction({package:c,module:f,function:u});o.set(a,l.parameters.map(p=>TO(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&&_O(c.at(-1))?c.slice(0,c.length-1):c;a._argumentTypes=u})),n.forEach(a=>{if(!a.MoveCall)return;const c=a.MoveCall,f=`${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 ${f}`);u.forEach((l,p)=>{var k,E;const d=c.arguments[p];if(d.$kind!=="Input")return;const m=r[d.Input];if(!m.UnresolvedPure&&!m.UnresolvedObject)return;const g=((k=m.UnresolvedPure)==null?void 0:k.value)??((E=m.UnresolvedObject)==null?void 0:E.objectId),w=Zl(l.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 S=m.UnresolvedPure?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:g}}:m;r[d.Input]=S})}})}function NO(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 MO(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=UO(s.MoveCall._argumentTypes[i])||r}}),r}function UO(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 A1(e,t){return!!(e.inputs.some(r=>r.UnresolvedObject||r.UnresolvedPure)||!t.onlyTransactionKind&&(!e.gasConfig.price||!e.gasConfig.budget||!e.gasConfig.payment))}async function FO(e,t,r){var i;if(LO(e),!A1(e,t))return await hm(e),r();const n=jO(t);return(((i=n.core)==null?void 0:i.resolveTransactionPlugin())??x1(n))(e,t,async()=>{await hm(e),await r()})}function hm(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 jO(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 LO(e){for(const t of e.commands)switch(t.$kind){case"SplitCoins":t.SplitCoins.amounts.forEach(r=>{pm(r,de.U64,e)});break;case"TransferObjects":pm(t.TransferObjects.address,de.Address,e);break}}function pm(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 DO(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 HO(e){function t(r,n){if(typeof r=="string")return e(mo(r).serialize(n));if(r instanceof Uint8Array||yh(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(mo(r)).serialize(n)),t.option=(r,n)=>e(de.option(mo(r)).serialize(n)),t}function zO(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),S1(n,{dkLen:32})}function ym(e){return xe(e).replace("0x","")}class Ct{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 Ct.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 Ct.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 Ct(qe(Za,t)):new Ct(qe(Za,J5(t)))}static getDigestFromBytes(t){const r=zO("TransactionData",t);return eu(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,f={...this.gasData,...r==null?void 0:r.gasConfig,...r==null?void 0:r.gasData};if(!c)throw new Error("Missing transaction sender");if(!f.budget)throw new Error("Missing gas budget");if(!f.payment)throw new Error("Missing gas payment");if(!f.price)throw new Error("Missing gas price");const u={sender:ym(c),expiration:a||{None:!0},gasData:{payment:f.payment,owner:ym(this.gasData.owner??c),price:BigInt(f.price),budget:BigInt(f.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 Ct.getDigestFromBytes(t)}snapshot(){return qe(Za,this)}shallowClone(){return new Ct({version:this.version,sender:this.sender,expiration:this.expiration,gasData:{...this.gasData},inputs:[...this.inputs],commands:[...this.commands]})}}function mm(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 _1=e=>{throw TypeError(e)},xh=(e,t,r)=>t.has(e)||_1("Cannot "+r),nt=(e,t,r)=>(xh(e,t,"read from private field"),r?r.call(e):t.get(e)),Xi=(e,t,r)=>t.has(e)?_1("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),ja=(e,t,r,n)=>(xh(e,t,"write to private field"),t.set(e,r),r),iu=(e,t,r)=>(xh(e,t,"access private method"),r),Xo,An,Zo,zn,zr,Jl,Ql,T1,k1,Ah;const VO="/",qO={"Mvr-Source":`@mysten/sui@${ww}`};class GO{constructor({cache:t,url:r,pageSize:n=50,overrides:s}){Xi(this,zr),Xi(this,Xo),Xi(this,An),Xi(this,Zo),Xi(this,zn),ja(this,Xo,t),ja(this,An,r),ja(this,Zo,n),ja(this,zn,{packages:s==null?void 0:s.packages,types:s==null?void 0:s.types}),WO(nt(this,zn))}async resolvePackage({package:t}){return{package:await nt(this,zr,Jl).load(t)}}async resolveType({type:t}){const r=[...ed(t)],n=await nt(this,zr,Ql).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:td(t,s)}}async resolve({types:t=[],packages:r=[]}){var u,l,p;const n=new Set;for(const d of t??[])ed(d,n);const s=[...n],[i,o]=await Promise.all([s.length>0?nt(this,zr,Ql).loadMany(s):[],r.length>0?nt(this,zr,Jl).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=td(d,a);c[d]={type:m}}const f={};for(const[d,m]of(r??[]).entries()){const g=((p=(l=nt(this,zn))==null?void 0:l.packages)==null?void 0:p[m])??o[d];if(g instanceof Error)throw g;f[m]={package:g}}return{types:c,packages:f}}}Xo=new WeakMap;An=new WeakMap;Zo=new WeakMap;zn=new WeakMap;zr=new WeakSet;Jl=function(){return nt(this,Xo).readSync(["#mvrPackageDataLoader",nt(this,An)??""],()=>{var r;const e=new Rw(async n=>{if(!nt(this,An))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await iu(this,zr,T1).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})};Ql=function(){return nt(this,Xo).readSync(["#mvrTypeDataLoader",nt(this,An)??""],()=>{var r;const e=new Rw(async n=>{if(!nt(this,An))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await iu(this,zr,k1).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})};T1=async function(e){if(e.length===0)return{};const t=tu(e,nt(this,Zo)),r={};return await Promise.all(t.map(async n=>{var i;const s=await iu(this,zr,Ah).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};k1=async function(e){if(e.length===0)return{};const t=tu(e,nt(this,Zo)),r={};return await Promise.all(t.map(async n=>{var i;const s=await iu(this,zr,Ah).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};Ah=async function(e,t){if(!nt(this,An))throw new Error("MVR Api URL is not set for the current client");const r=await fetch(`${nt(this,An)}${e}`,{method:"POST",headers:{"Content-Type":"application/json",...qO},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 WO(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(!mr(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(!mr(n.address))throw new Error(`Invalid type: ${r}`)}}function ed(e,t=new Set){if(typeof e=="string"&&!Rt(e))return t;const r=I1(e)?e:Ns(e);Rt(r.address)&&t.add(`${r.address}::${r.module}::${r.name}`);for(const n of r.typeParams)ed(n,t);return t}function td(e,t){const r=I1(e)?e:Ns(e),n=`${r.address}::${r.module}::${r.name}`,s=t[n];return hc({...r,address:s?s.split("::")[0]:r.address,typeParams:r.typeParams.map(i=>td(i,t))})}function Rt(e){return e.includes(VO)||e.includes("@")||e.includes(".sui")}function I1(e){return typeof e=="object"&&"address"in e&&"module"in e&&"name"in e&&"typeParams"in e}function KO(e){const t=new Set,r=new Set;for(const n of e.commands)switch(n.$kind){case"MakeMoveVec":n.MakeMoveVec.type&&gm([n.MakeMoveVec.type]).forEach(o=>{r.add(o)});break;case"MoveCall":const s=n.MoveCall,i=s.package.split("::")[0];if(Rt(i)){if(!Dt(i))throw new Error(`Invalid package name: ${i}`);t.add(i)}gm(s.typeArguments??[]).forEach(o=>{r.add(o)});break}return{packages:[...t],types:[...r]}}function YO(e,t){var r;for(const n of e.commands){if((r=n.MakeMoveVec)!=null&&r.type){if(!Rt(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(Rt(o)&&!t.packages[o])throw new Error(`No address found for package: ${o}`);Rt(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(Rt(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 gm(e){const t=new Set;for(const r of e)if(Rt(r)){if(!e5(r))throw new Error(`Invalid type with names: ${r}`);t.add(r)}return t}const XO=e=>async(t,r,n)=>{const s=KO(t);if(s.types.length===0&&s.packages.length===0)return n();const i=await ZO(r).core.mvr.resolve({types:s.types,packages:s.packages});YO(t,i),await n()};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}var P1=e=>{throw TypeError(e)},_h=(e,t,r)=>t.has(e)||P1("Cannot "+r),X=(e,t,r)=>(_h(e,t,"read from private field"),r?r.call(e):t.get(e)),Ur=(e,t,r)=>t.has(e)?P1("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Be=(e,t,r,n)=>(_h(e,t,"write to private field"),t.set(e,r),r),rt=(e,t,r)=>(_h(e,t,"access private method"),r),bs,As,ln,qr,sr,ir,wr,Vn,ae,Ke,O1,Ja,Qa,ec,pc,rd,Th,B1,C1;function Xf(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 R1=Symbol.for("@mysten/transaction");function $1(e){return!!e&&typeof e=="object"&&e[R1]===!0}const bm={buildPlugins:new Map,serializationPlugins:new Map},Zf=Symbol.for("@mysten/transaction/registry");function Zi(){try{const e=globalThis;return e[Zf]||(e[Zf]=bm),e[Zf]}catch{return bm}}const N1=class nd{constructor(){Ur(this,Ke),Ur(this,bs),Ur(this,As),Ur(this,ln,new Map),Ur(this,qr,[]),Ur(this,sr,[]),Ur(this,ir,new Set),Ur(this,wr,new Set),Ur(this,Vn,new Map),Ur(this,ae),this.object=DO(r=>{var i,o;if(typeof r=="function")return this.object(this.add(r));if(typeof r=="object"&&Kl(Ue,r))return r;const n=mm(r),s=X(this,ae).inputs.find(a=>n===mm(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:X(this,ae).inputs.indexOf(s),type:"object"}:rt(this,Ke,Qa).call(this,"object",typeof r=="string"?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:xe(r)}}:r)});const t=Zi();Be(this,ae,new Ct),Be(this,As,[...t.buildPlugins.values()]),Be(this,bs,[...t.serializationPlugins.values()])}static fromKind(t){const r=new nd;return Be(r,ae,Ct.fromKindBytes(typeof t=="string"?zt(t):t)),Be(r,qr,X(r,ae).inputs.slice()),Be(r,sr,X(r,ae).commands.slice()),Be(r,ir,new Set(X(r,sr).map((n,s)=>s))),r}static from(t){const r=new nd;return $1(t)?Be(r,ae,new Ct(t.getData())):typeof t!="string"||!t.startsWith("{")?Be(r,ae,Ct.fromBytes(typeof t=="string"?zt(t):t)):Be(r,ae,Ct.restore(JSON.parse(t))),Be(r,qr,X(r,ae).inputs.slice()),Be(r,sr,X(r,ae).commands.slice()),Be(r,ir,new Set(X(r,sr).map((n,s)=>s))),r}static registerGlobalSerializationPlugin(t,r){Zi().serializationPlugins.set(t,r??t)}static unregisterGlobalSerializationPlugin(t){Zi().serializationPlugins.delete(t)}static registerGlobalBuildPlugin(t,r){Zi().buildPlugins.set(t,r??t)}static unregisterGlobalBuildPlugin(t){Zi().buildPlugins.delete(t)}addSerializationPlugin(t){X(this,bs).push(t)}addBuildPlugin(t){X(this,As).push(t)}addIntentResolver(t,r){if(X(this,ln).has(t)&&X(this,ln).get(t)!==r)throw new Error(`Intent resolver for ${t} already exists`);X(this,ln).set(t,r)}setSender(t){X(this,ae).sender=t}setSenderIfNotSet(t){X(this,ae).sender||(X(this,ae).sender=t)}setExpiration(t){X(this,ae).expiration=t?qe(w1,t):null}setGasPrice(t){X(this,ae).gasConfig.price=String(t)}setGasBudget(t){X(this,ae).gasConfig.budget=String(t)}setGasBudgetIfNotSet(t){X(this,ae).gasData.budget==null&&(X(this,ae).gasConfig.budget=String(t))}setGasOwner(t){X(this,ae).gasConfig.owner=t}setGasPayment(t){X(this,ae).gasConfig.payment=t.map(r=>qe(rs,r))}get blockData(){return dm(X(this,ae).snapshot())}getData(){return X(this,ae).snapshot()}get[R1](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:HO(t=>yh(t)?rt(this,Ke,Qa).call(this,"pure",{$kind:"Pure",Pure:{bytes:t.toBase64()}}):rt(this,Ke,Qa).call(this,"pure",Kl(um,t)?qe(um,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(X(this,Vn).has(t))return X(this,Vn).get(t);const r=rt(this,Ke,O1).call(this),n=t(r);if(!(n&&typeof n=="object"&&"then"in n))return Be(this,ir,X(r,ir)),X(this,Vn).set(t,n),n;const s=rt(this,Ke,Ja).call(this,{$kind:"$Intent",$Intent:{name:"AsyncTransactionThunk",inputs:{},data:{resultIndex:X(this,ae).commands.length,result:null}}});X(this,wr).add(Promise.resolve(n).then(o=>{s.$Intent.data.result=o}));const i=Xf(()=>s.$Intent.data.resultIndex);return X(this,Vn).set(t,i),i}else rt(this,Ke,Ja).call(this,t);return Xf(X(this,ae).commands.length-1)}splitCoins(t,r){const n=as.SplitCoins(typeof t=="string"?this.object(t):rt(this,Ke,pc).call(this,t),r.map(s=>typeof s=="number"||typeof s=="bigint"||typeof s=="string"?this.pure.u64(s):rt(this,Ke,ec).call(this,s)));return rt(this,Ke,Ja).call(this,n),Xf(X(this,ae).commands.length-1,r.length)}mergeCoins(t,r){return this.add(as.MergeCoins(this.object(t),r.map(n=>this.object(n))))}publish({modules:t,dependencies:r}){return this.add(as.Publish({modules:t,dependencies:r}))}upgrade({modules:t,dependencies:r,package:n,ticket:s}){return this.add(as.Upgrade({modules:t,dependencies:r,package:n,ticket:this.object(s)}))}moveCall({arguments:t,...r}){return this.add(as.MoveCall({...r,arguments:t==null?void 0:t.map(n=>rt(this,Ke,ec).call(this,n))}))}transferObjects(t,r){return this.add(as.TransferObjects(t.map(n=>this.object(n)),typeof r=="string"?this.pure.address(r):rt(this,Ke,ec).call(this,r)))}makeMoveVec({type:t,elements:r}){return this.add(as.MakeMoveVec({type:t,elements:r.map(n=>this.object(n))}))}serialize(){return JSON.stringify(dm(X(this,ae).snapshot()))}async toJSON(t={}){await this.prepareForSerialization(t);const r=this.isFullyResolved();return JSON.stringify(qe(oO,r?{...X(this,ae).snapshot(),digest:X(this,ae).getDigest()}:X(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!(!X(this,ae).sender||X(this,wr).size>0||X(this,ae).commands.some(t=>t.$Intent)||A1(X(this,ae),{}))}async build(t={}){return await this.prepareForSerialization(t),await rt(this,Ke,rd).call(this,t),X(this,ae).build({onlyTransactionKind:t.onlyTransactionKind})}async getDigest(t={}){return await this.prepareForSerialization(t),await rt(this,Ke,rd).call(this,t),X(this,ae).getDigest()}async prepareForSerialization(t){var s;await rt(this,Ke,B1).call(this),rt(this,Ke,C1).call(this);const r=new Set;for(const i of X(this,ae).commands)i.$Intent&&r.add(i.$Intent.name);const n=[...X(this,bs)];for(const i of r)if(!((s=t.supportedIntents)!=null&&s.includes(i))){if(!X(this,ln).has(i))throw new Error(`Missing intent resolver for ${i}`);n.push(X(this,ln).get(i))}n.push(XO()),await rt(this,Ke,Th).call(this,n,t)}};bs=new WeakMap;As=new WeakMap;ln=new WeakMap;qr=new WeakMap;sr=new WeakMap;ir=new WeakMap;wr=new WeakMap;Vn=new WeakMap;ae=new WeakMap;Ke=new WeakSet;O1=function(){const e=new N1;return Be(e,ae,X(this,ae)),Be(e,bs,X(this,bs)),Be(e,As,X(this,As)),Be(e,ln,X(this,ln)),Be(e,wr,X(this,wr)),Be(e,ir,new Set(X(this,ir))),Be(e,Vn,X(this,Vn)),X(this,qr).push(X(e,qr)),X(this,sr).push(X(e,sr)),e};Ja=function(e){const t=X(this,ae).commands.length;return X(this,sr).push(e),X(this,ir).add(t),X(this,ae).commands.push(e),X(this,ae).mapCommandArguments(t,r=>{if(r.$kind==="Result"&&!X(this,ir).has(r.Result))throw new Error(`Result { Result: ${r.Result} } is not available to use the current transaction`);if(r.$kind==="NestedResult"&&!X(this,ir).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>=X(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};Qa=function(e,t){return X(this,qr).push(t),X(this,ae).addInput(e,t)};ec=function(e){return yh(e)?this.pure(e):rt(this,Ke,pc).call(this,e)};pc=function(e){if(typeof e=="function"){const t=this.add(e);return typeof t=="function"?rt(this,Ke,pc).call(this,t):qe(Ue,t)}return qe(Ue,e)};rd=async function(e){if(!e.onlyTransactionKind&&!X(this,ae).sender)throw new Error("Missing transaction sender");await rt(this,Ke,Th).call(this,[...X(this,As),FO],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(X(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,qr,X(this,ae).inputs.slice()),Be(this,sr,X(this,ae).commands.slice())};B1=async function(){for(;X(this,wr).size>0;){const e=Promise.all(X(this,wr));X(this,wr).clear(),X(this,wr).add(e),await e,X(this,wr).delete(e)}};C1=function(){var o;const e=X(this,ae).commands,t=X(this,ae).inputs,r=X(this,sr).flat(1/0),n=X(this,qr).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"});X(this,ae).commands=s,X(this,ae).inputs=n,Be(this,sr,s),Be(this,qr,n),Be(this,ir,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 l=c.$Intent.data.result;if(l==null)throw new Error("AsyncTransactionThunk has not been resolved");return i(l.Result)}const f=s.indexOf(c);if(f===-1)throw new Error("Unable to find original index for command");return f}X(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 M1=N1;const JO={mainnet:"https://mainnet.mvr.mystenlabs.com",testnet:"https://testnet.mvr.mystenlabs.com"};class QO extends zw{constructor(t){var r,n,s;super(t),this.core=this,this.mvr=new GO({cache:this.cache.scope("core.mvr"),url:((r=t.mvr)==null?void 0:r.url)??JO[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=mO(t.parentId,br.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]:hc(s.typeParams[0]),bcs:t.name.bcs},value:{type:typeof s.typeParams[1]=="string"?s.typeParams[1]:hc(s.typeParams[1]),bcs:i.slice(ru+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 e3 extends Error{}class qn extends e3{constructor(t,r){super(r),this.code=t}static fromResponse(t,r){switch(t.code){case"notExists":return new qn(t.code,`Object ${t.object_id} does not exist`);case"dynamicFieldNotFound":return new qn(t.code,`Dynamic field not found for object ${t.parent_object_id}`);case"deleted":return new qn(t.code,`Object ${t.object_id} has been deleted`);case"displayError":return new qn(t.code,`Display error: ${t.error}`);case"unknown":default:return new qn(t.code,`Unknown error while loading object${r?` ${r}`:""}`)}}}function t3(e){return{...Ct.fromBytes(e).snapshot(),bcs:e}}function r3(e){const t=de.TransactionEffects.parse(e);switch(t.$kind){case"V1":return n3({effects:t.V1});case"V2":return s3({bytes:e,effects:t.V2});default:throw new Error(`Unknown transaction effects version: ${t.$kind}`)}}function n3(e){throw new Error("V1 effects are not supported yet")}function s3({bytes:e,effects:t}){const r=t.changedObjects.map(([n,s])=>{var i,o,a,c,f,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"?(f=s.outputState.PackageWrite)==null?void 0:f[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 U1=e=>{throw TypeError(e)},F1=(e,t,r)=>t.has(e)||U1("Cannot "+r),Lt=(e,t,r)=>(F1(e,t,"read from private field"),r?r.call(e):t.get(e)),i3=(e,t,r)=>t.has(e)?U1("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),o3=(e,t,r,n)=>(F1(e,t,"write to private field"),t.set(e,r),r),pt;class a3 extends QO{constructor({jsonRpcClient:t,mvr:r}){super({network:t.network,base:t,mvr:r}),i3(this,pt),o3(this,pt,t)}async getObjects(t){const r=tu(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(qn.fromResponse(a.error,s[o])):n.push(wm(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 qn.fromResponse(n.error);return wm(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(f3.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:vm(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:vm(r)}}async dryRunTransaction(t){const r=M1.from(t.transaction),n=await Lt(this,pt).dryRunTransactionBlock({transactionBlock:t.transaction,signal:t.signal}),{effects:s,objectTypes:i}=c3({effects:n.effects,objectChanges:n.objectChanges});return{transaction:{digest:await r.getDigest(),epoch:null,effects:s,objectTypes:Promise.resolve(i),signatures:[],transaction:t3(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 x1(Lt(this,pt))}}pt=new WeakMap;function wm(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 vm(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=Ct.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:r3(new Uint8Array(e.rawEffects)),objectTypes:Promise.resolve(r),transaction:{...s,bcs:n},signatures:t.txSignatures}}function c3({bytes:e,effects:t,objectChanges:r}){var o;const n=[],s=[],i={};return r==null||r.forEach(a=>{var c,f,u,l;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:((f=(c=t.deleted)==null?void 0:c.find(p=>p.objectId===a.objectId))==null?void 0:f.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:((l=(u=t.wrapped)==null?void 0:u.find(p=>p.objectId===a.objectId))==null?void 0:l.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 u3=de.struct("Balance",{value:de.u64()}),f3=de.struct("Coin",{id:de.Address,balance:u3}),l3=Symbol.for("@mysten/SuiClient");class d3 extends zw{constructor(t){super({network:t.network??"unknown"}),this.jsonRpc=this,this.transport=t.transport??new hP({url:t.url}),this.core=new a3({jsonRpcClient:this,mvr:t.mvr})}get[l3](){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||!mr(xe(r)))throw new Error("Invalid Sui address");return t&&Rt(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||!mr(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||!mr(xe(t)))throw new Error("Invalid Sui address");return r&&Rt(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||!mr(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&&Rt(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&&Rt(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||!mr(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&&Rt(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||!Fa(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||!Fa(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(!om(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(!om(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||!mr(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||!Fa(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&&Rt(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($1(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||!Fa(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=Wo(r.digest);return Ii(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=>XP(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 h3{constructor(t,r,n){this.client=new d3({url:pP(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?Buffer.from(this.account.accounts[0].publicKey).toString("hex"):Buffer.from(this.account.getPublicKey().toRawBytes()).toString("hex")}get userSuiAddress(){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,f=i.secret_hash,u="accounts"in this.account?this.account.accounts[0].publicKey:this.account.getPublicKey().toRawBytes(),l=Buffer.from(c,"hex"),p=new M1;p.setGasBudget(1e8),p.setSender(this.userSuiAddress);const[d]=p.splitCoins(p.gas,[o]);p.moveCall({target:`${_p[this.network].packageId}::${_p[this.network].moduleName}::initiate_swap`,typeArguments:[i.token_address],arguments:[p.object(a),p.pure.vector("u8",u),p.pure.vector("u8",l),p.pure.vector("u8",Buffer.from(f,"hex")),p.pure.u64(o),p.pure.u256(i.timelock),p.pure.vector("u8",Buffer.from("")),d,p.object(uO)]});const m=await p.build({client:this.client}),g=await this.client.dryRunTransactionBlock({transactionBlock:m});if(g.effects.status.status==="failure")return v.Err(`${g.effects.status.error}`);let w;if("features"in this.account?w=await((r=this.account.features[q1.SuiSignAndExecuteTransaction])==null?void 0:r.signAndExecuteTransaction({transaction:p,account:this.account.accounts[0],chain:this.account.chains[0]})):w=await this.client.signAndExecuteTransaction({signer:this.account,transaction:p,options:{showEffects:!0}}),!w)return v.Err("Failed to initiate");const S=await this.client.waitForTransaction({digest:w.digest,options:{showEffects:!0}});return((n=S.effects)==null?void 0:n.status.status)==="failure"?v.Err(`Failed to initiate: ${(s=S.effects)==null?void 0:s.status.error}`):v.Ok(S.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 kh extends v.EventBroker{constructor(t){super(),this.environment=v.Environment.TESTNET,this.getOrderThreshold=20,this.refundSacpCache=new Map,this.bitcoinRedeemCache=new pk,this.isSecretManagementEnabled=!1;const{api:r,environment:n}=Cl(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 qb(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??qo.fromDigestKey(this._digestKey.digestKey),this.orderExecutorCache=new hk,this._blockNumberFetcher=t.blockNumberFetcher??new Vb(this._api.info,this.environment);const s=new rw(r_(this.environment));this._btcWallet=ps.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}=Cl(t.environment);if(!n)throw new Error("API not found, invalid environment "+t.environment);const s={evm:t.wallets.evm?new Xb(n.evmRelay,t.wallets.evm,v.Siwe.fromDigestKey(new v.Url(n.auth),r)):void 0,starknet:t.wallets.starknet?new tw(n.starknetRelay,t.wallets.starknet,t.environment===v.Environment.MAINNET?v.Network.MAINNET:v.Network.TESTNET):void 0,solana:t.wallets.solana?new bw(t.wallets.solana,new v.Url(n.solanaRelay),t.environment===v.Environment.MAINNET?Bl.mainnet:Bl.testnet,t.solanaProgramAddress?t.solanaProgramAddress:db.mainnet):void 0,sui:t.wallets.sui?new h3(n.suiRelay,t.wallets.sui,t.environment===v.Environment.MAINNET?v.Network.MAINNET:v.Network.TESTNET):void 0};return new kh({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,f=be.isBitcoin(t.fromAsset.chain),u=be.isBitcoin(t.toAsset.chain),l=f||u;if(!this.isSecretManagementEnabled&&l&&!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&&f?{}:{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||!e_(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?(console.log("suiHTLC address",this._suiHTLC.htlcActorAddress),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 z1(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,Se.Redeem,s.destination_swap.redeem_tx_hash),this.emit("success",s,Se.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 Se.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 Se.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,Se.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,Se.Redeem,t.destination_swap.redeem_tx_hash);return}s.val&&(this.orderExecutorCache.set(t,Se.Redeem,s.val),this.emit("success",t,Se.Redeem,s.val))}async suiRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing sol redeem"),this.orderExecutorCache.get(t,Se.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._suiHTLC){this.emit("error",t,"Solana 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,Se.Redeem,t.destination_swap.redeem_tx_hash);return}s.val&&(this.orderExecutorCache.set(t,Se.Redeem,s.val),this.emit("success",t,Se.Redeem,s.val))}async evmRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing evm redeem"),this.orderExecutorCache.get(t,Se.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,Se.Redeem,t.destination_swap.redeem_tx_hash);return}this.orderExecutorCache.set(t,Se.Redeem,s.val),this.emit("success",t,Se.Redeem,s.val)}async starknetRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing starknet redeem"),this.orderExecutorCache.get(t,Se.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,Se.Redeem,t.destination_swap.redeem_tx_hash);return}s.val&&(this.orderExecutorCache.set(t,Se.Redeem,s.val),this.emit("success",t,Se.Redeem,s.val))}async btcRedeem(t,r,n){var a,c,f;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 l=!1;for(const p of u.vin)if(p.txid===i){l=!0;break}if(l){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 l=await(await fo.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),(f=r.create_order.additional_data)==null?void 0:f.bitcoin_optional_recipient),p=await this.broadcastRedeemTx(l,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,Se.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,Se.Refund)){this.emit("log",r.create_order.create_id,"executing btc refund");try{const o=await(await fo.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,Se.Refund,o),this.emit("success",r,Se.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 fo.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 f=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:f})})).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,f=r==null?void 0:r.val[a],u=r==null?void 0:r.val[c];if(!f||!u){this.emit("error",o,"Error while fetching CurrentBlockNumbers");continue}const l=Kd(o,f,u);n.push({...o,status:l})}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 p3{constructor(t,r,n){this.callData=new it.CallData(Zb),this.account=t,this.starknetProvider=new it.RpcProvider({nodeUrl:r||(n?Do[n].nodeUrl:Do.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(ew,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 Jb(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 y3{constructor(t){if(this.provider=t,!t)throw new Error("Provider is required");this.provider=t,this.program=new vr.Program(Dl,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=vr.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=vr.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(gw(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=vr.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=za;exports.BaseError=H;exports.BitcoinNetwork=Ht;exports.BitcoinProvider=rw;exports.BitcoinWallet=ps;exports.BlockNumberFetcher=Vb;exports.EvmRelay=Xb;exports.Garden=kh;exports.HttpRequestError=ci;exports.OrderActions=Se;exports.OrderStatus=ge;exports.ParseOrderStatus=Kd;exports.ParseSwapStatus=Ul;exports.Quote=qb;exports.STARKNET_CONFIG=Do;exports.SecretManager=qo;exports.SolanaHTLC=y3;exports.SolanaRelay=bw;exports.SolanaRelayerAddress=Bl;exports.StarknetHTLC=p3;exports.StarknetRelay=tw;exports.SwapStatus=Ne;exports.botanixMainnet=Gb;exports.call=oa;exports.checkAllowance=lo;exports.checkAllowanceAndApprove=Jb;exports.concat=qt;exports.constructOrderPair=$l;exports.decodeErrorResult=m0;exports.encodeAbiParameters=Tn;exports.evmToViemChainMap=ch;exports.filterDeadlineExpiredOrders=o_;exports.getUrl=Sc;exports.hyperliquid=Kb;exports.hyperliquidTestnet=Wb;exports.isAddressEqual=ia;exports.isAllowanceSufficient=Qb;exports.isExpired=Ho;exports.isHex=xr;exports.isOrderExpired=hb;exports.localBatchGatewayRequest=wg;exports.localBatchGatewayUrl=Mc;exports.parseAction=i_;exports.parseActionFromStatus=Yd;exports.resolveApiConfig=Cl;exports.solanaProgramAddress=db;exports.stringify=Ze;exports.switchOrAddNetwork=Yb;exports.toXOnly=Fn;exports.validateBTCAddress=t_;