@gardenfi/core 2.5.3-beta.1 → 2.5.3-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,106 +0,0 @@
1
- "use strict";var $v=Object.defineProperty;var Dh=t=>{throw TypeError(t)};var Rv=(t,e,r)=>e in t?$v(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var zh=(t,e,r)=>Rv(t,typeof e!="symbol"?e+"":e,r),Vh=(t,e,r)=>e.has(t)||Dh("Cannot "+r);var Ie=(t,e,r)=>(Vh(t,e,"read from private field"),r?r.call(t):e.get(t)),us=(t,e,r)=>e.has(t)?Dh("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),ls=(t,e,r,n)=>(Vh(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r);const ee=require("@gardenfi/orderbook"),b=require("@gardenfi/utils"),pe=require("bitcoinjs-lib"),Nv=require("tiny-secp256k1"),Wm=require("varuint-bitcoin"),Uv=require("bignumber.js"),Xa=require("ecpair"),Ye=require("starknet"),zt=require("@coral-xyz/anchor"),Mv=require("@solana/spl-token"),qh=require("@mysten/wallet-standard"),Fv=require("node-cache"),Gh=require("yup"),Wh=require("bip39"),jv=require("bip32");function kc(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const ve=kc(pe),or=kc(Nv),Kh=kc(Wm),Lv=kc(Mv),Hv="1.0.8";let lr=class hf extends Error{constructor(e,r={}){var o;const n=r.cause instanceof hf?r.cause.details:(o=r.cause)!=null&&o.message?r.cause.message:r.details,s=r.cause instanceof hf&&r.cause.docsPath||r.docsPath,i=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: https://abitype.dev${s}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${Hv}`].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=e}};function In(t,e){const r=t.exec(e);return r==null?void 0:r.groups}const Km=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Zm=/^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)?$/,Xm=/^\(.+?\).*?$/,Zh=/^tuple(?<array>(\[(\d*)\])*)$/;function pf(t){let e=t.type;if(Zh.test(t.type)&&"components"in t){e="(";const r=t.components.length;for(let s=0;s<r;s++){const i=t.components[s];e+=pf(i),s<r-1&&(e+=", ")}const n=In(Zh,t.type);return e+=`)${(n==null?void 0:n.array)??""}`,pf({...t,type:e})}return"indexed"in t&&t.indexed&&(e=`${e} indexed`),t.name?`${e} ${t.name}`:e}function Ki(t){let e="";const r=t.length;for(let n=0;n<r;n++){const s=t[n];e+=pf(s),n!==r-1&&(e+=", ")}return e}function Dv(t){var e;return t.type==="function"?`function ${t.name}(${Ki(t.inputs)})${t.stateMutability&&t.stateMutability!=="nonpayable"?` ${t.stateMutability}`:""}${(e=t.outputs)!=null&&e.length?` returns (${Ki(t.outputs)})`:""}`:t.type==="event"?`event ${t.name}(${Ki(t.inputs)})`:t.type==="error"?`error ${t.name}(${Ki(t.inputs)})`:t.type==="constructor"?`constructor(${Ki(t.inputs)})${t.stateMutability==="payable"?" payable":""}`:t.type==="fallback"?`fallback() external${t.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const Ym=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function zv(t){return Ym.test(t)}function Vv(t){return In(Ym,t)}const Jm=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function qv(t){return Jm.test(t)}function Gv(t){return In(Jm,t)}const Qm=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function Wv(t){return Qm.test(t)}function Kv(t){return In(Qm,t)}const e0=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function t0(t){return e0.test(t)}function Zv(t){return In(e0,t)}const r0=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function Xv(t){return r0.test(t)}function Yv(t){return In(r0,t)}const n0=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function Jv(t){return n0.test(t)}function Qv(t){return In(n0,t)}const e2=/^receive\(\) external payable$/;function t2(t){return e2.test(t)}const r2=new Set(["indexed"]),yf=new Set(["calldata","memory","storage"]);let n2=class extends lr{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}},s2=class extends lr{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}},i2=class extends lr{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}},o2=class extends lr{constructor({param:e,name:r}){super("Invalid ABI parameter.",{details:e,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}},a2=class extends lr{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}},c2=class extends lr{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}},u2=class extends lr{constructor({abiParameter:e}){super("Invalid ABI parameter.",{details:JSON.stringify(e,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}},Fi=class extends lr{constructor({signature:e,type:r}){super(`Invalid ${r} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}},l2=class extends lr{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}},f2=class extends lr{constructor({signature:e}){super("Invalid struct signature.",{details:e,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}},d2=class extends lr{constructor({type:e}){super("Circular reference detected.",{metaMessages:[`Struct "${e}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}},h2=class extends lr{constructor({current:e,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${e.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}};function p2(t,e,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 e?`${e}:${t}${n}`:t}const wu=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 y2(t,e={}){if(Wv(t))return m2(t,e);if(qv(t))return g2(t,e);if(zv(t))return b2(t,e);if(Xv(t))return w2(t,e);if(Jv(t))return v2(t);if(t2(t))return{type:"receive",stateMutability:"payable"};throw new l2({signature:t})}function m2(t,e={}){const r=Kv(t);if(!r)throw new Fi({signature:t,type:"function"});const n=wr(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push(Bs(n[a],{modifiers:yf,structs:e,type:"function"}));const o=[];if(r.returns){const a=wr(r.returns),c=a.length;for(let u=0;u<c;u++)o.push(Bs(a[u],{modifiers:yf,structs:e,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:s,outputs:o}}function g2(t,e={}){const r=Gv(t);if(!r)throw new Fi({signature:t,type:"event"});const n=wr(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Bs(n[o],{modifiers:r2,structs:e,type:"event"}));return{name:r.name,type:"event",inputs:s}}function b2(t,e={}){const r=Vv(t);if(!r)throw new Fi({signature:t,type:"error"});const n=wr(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Bs(n[o],{structs:e,type:"error"}));return{name:r.name,type:"error",inputs:s}}function w2(t,e={}){const r=Yv(t);if(!r)throw new Fi({signature:t,type:"constructor"});const n=wr(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Bs(n[o],{structs:e,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:s}}function v2(t){const e=Qv(t);if(!e)throw new Fi({signature:t,type:"fallback"});return{type:"fallback",stateMutability:e.stateMutability??"nonpayable"}}const E2=/^(?<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$_]*))?$/,S2=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,A2=/^u?int$/;function Bs(t,e){var d,h;const r=p2(t,e==null?void 0:e.type,e==null?void 0:e.structs);if(wu.has(r))return wu.get(r);const n=Xm.test(t),s=In(n?S2:E2,t);if(!s)throw new i2({param:t});if(s.name&&k2(s.name))throw new o2({param:t,name:s.name});const i=s.name?{name:s.name}:{},o=s.modifier==="indexed"?{indexed:!0}:{},a=(e==null?void 0:e.structs)??{};let c,u={};if(n){c="tuple";const f=wr(s.type),m=[],g=f.length;for(let v=0;v<g;v++)m.push(Bs(f[v],{structs:a}));u={components:m}}else if(s.type in a)c="tuple",u={components:a[s.type]};else if(A2.test(s.type))c=`${s.type}256`;else if(c=s.type,(e==null?void 0:e.type)!=="struct"&&!s0(c))throw new s2({type:c});if(s.modifier){if(!((h=(d=e==null?void 0:e.modifiers)==null?void 0:d.has)!=null&&h.call(d,s.modifier)))throw new a2({param:t,type:e==null?void 0:e.type,modifier:s.modifier});if(yf.has(s.modifier)&&!_2(c,!!s.array))throw new c2({param:t,type:e==null?void 0:e.type,modifier:s.modifier})}const l={type:`${c}${s.array??""}`,...i,...o,...u};return wu.set(r,l),l}function wr(t,e=[],r="",n=0){const s=t.trim().length;for(let i=0;i<s;i++){const o=t[i],a=t.slice(i+1);switch(o){case",":return n===0?wr(a,[...e,r.trim()]):wr(a,e,`${r}${o}`,n);case"(":return wr(a,e,`${r}${o}`,n+1);case")":return wr(a,e,`${r}${o}`,n-1);default:return wr(a,e,`${r}${o}`,n)}}if(r==="")return e;if(n!==0)throw new h2({current:r,depth:n});return e.push(r.trim()),e}function s0(t){return t==="address"||t==="bool"||t==="function"||t==="string"||Km.test(t)||Zm.test(t)}const x2=/^(?: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 k2(t){return t==="address"||t==="bool"||t==="function"||t==="string"||t==="tuple"||Km.test(t)||Zm.test(t)||x2.test(t)}function _2(t,e){return e||t==="bytes"||t==="string"||t==="tuple"}function T2(t){const e={},r=t.length;for(let o=0;o<r;o++){const a=t[o];if(!t0(a))continue;const c=Zv(a);if(!c)throw new Fi({signature:a,type:"struct"});const u=c.properties.split(";"),l=[],d=u.length;for(let h=0;h<d;h++){const m=u[h].trim();if(!m)continue;const g=Bs(m,{type:"struct"});l.push(g)}if(!l.length)throw new f2({signature:a});e[c.name]=l}const n={},s=Object.entries(e),i=s.length;for(let o=0;o<i;o++){const[a,c]=s[o];n[a]=i0(c,e)}return n}const I2=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function i0(t,e,r=new Set){const n=[],s=t.length;for(let i=0;i<s;i++){const o=t[i];if(Xm.test(o.type))n.push(o);else{const c=In(I2,o.type);if(!(c!=null&&c.type))throw new u2({abiParameter:o});const{array:u,type:l}=c;if(l in e){if(r.has(l))throw new d2({type:l});n.push({...o,type:`tuple${u??""}`,components:i0(e[l]??[],e,new Set([...r,l]))})}else if(s0(l))n.push(o);else throw new n2({type:l})}}return n}function o0(t){const e=T2(t),r=[],n=t.length;for(let s=0;s<n;s++){const i=t[s];t0(i)||r.push(y2(i,e))}return r}function ae(t,e,r){const n=t[e.name];if(typeof n=="function")return n;const s=t[r];return typeof s=="function"?s:i=>e(t,i)}function kr(t,{includeName:e=!1}={}){if(t.type!=="function"&&t.type!=="event"&&t.type!=="error")throw new H2(t.type);return`${t.name}(${_c(t.inputs,{includeName:e})})`}function _c(t,{includeName:e=!1}={}){return t?t.map(r=>P2(r,{includeName:e})).join(e?", ":","):""}function P2(t,{includeName:e}){return t.type.startsWith("tuple")?`(${_c(t.components,{includeName:e})})${t.type.slice(5)}`:t.type+(e&&t.name?` ${t.name}`:"")}function _r(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function Le(t){return _r(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const a0="2.35.1";let Zi={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:r})=>e?`${t??"https://viem.sh"}${e}${r?`#${r}`:""}`:void 0,version:`viem@${a0}`},D=class mf extends Error{constructor(e,r={}){var a;const n=(()=>{var c;return r.cause instanceof mf?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),s=r.cause instanceof mf&&r.cause.docsPath||r.docsPath,i=(a=Zi.getDocsUrl)==null?void 0:a.call(Zi,{...r,docsPath:s}),o=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...Zi.version?[`Version: ${Zi.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=e,this.version=a0}walk(e){return c0(this,e)}};function c0(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?c0(t.cause,e):e?null:t}class O2 extends D{constructor({docsPath:e}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
4
- `),{docsPath:e,name:"AbiConstructorNotFoundError"})}}class Xh extends D{constructor({docsPath:e}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
5
- `),{docsPath:e,name:"AbiConstructorParamsNotFoundError"})}}class u0 extends D{constructor({data:e,params:r,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join(`
6
- `),{metaMessages:[`Params: (${_c(r,{includeName:!0})})`,`Data: ${e} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e,this.params=r,this.size=n}}class sa extends D{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError"})}}class B2 extends D{constructor({expectedLength:e,givenLength:r,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${e}`,`Given length: ${r}`].join(`
7
- `),{name:"AbiEncodingArrayLengthMismatchError"})}}class C2 extends D{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${Le(r)}) does not match expected size (bytes${e}).`,{name:"AbiEncodingBytesSizeMismatchError"})}}class $2 extends D{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${e}`,`Given length (values): ${r}`].join(`
8
- `),{name:"AbiEncodingLengthMismatchError"})}}class R2 extends D{constructor(e,{docsPath:r}){super([`Arguments (\`args\`) were provided to "${e}", but "${e}" on the ABI does not contain any parameters (\`inputs\`).`,"Cannot encode error result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the inputs exist on it."].join(`
9
- `),{docsPath:r,name:"AbiErrorInputsNotFoundError"})}}class Yh extends D{constructor(e,{docsPath:r}={}){super([`Error ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it."].join(`
10
- `),{docsPath:r,name:"AbiErrorNotFoundError"})}}class l0 extends D{constructor(e,{docsPath:r}){super([`Encoded error signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
11
- `),{docsPath:r,name:"AbiErrorSignatureNotFoundError"}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=e}}class N2 extends D{constructor({docsPath:e}){super("Cannot extract event signature from empty topics.",{docsPath:e,name:"AbiEventSignatureEmptyTopicsError"})}}class f0 extends D{constructor(e,{docsPath:r}){super([`Encoded event signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
12
- `),{docsPath:r,name:"AbiEventSignatureNotFoundError"})}}class Jh extends D{constructor(e,{docsPath:r}={}){super([`Event ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it."].join(`
13
- `),{docsPath:r,name:"AbiEventNotFoundError"})}}class _i extends D{constructor(e,{docsPath:r}={}){super([`Function ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join(`
14
- `),{docsPath:r,name:"AbiFunctionNotFoundError"})}}class d0 extends D{constructor(e,{docsPath:r}){super([`Function "${e}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join(`
15
- `),{docsPath:r,name:"AbiFunctionOutputsNotFoundError"})}}class U2 extends D{constructor(e,{docsPath:r}){super([`Encoded function signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
16
- `),{docsPath:r,name:"AbiFunctionSignatureNotFoundError"})}}class M2 extends D{constructor(e,r){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${e.type}\` in \`${kr(e.abiItem)}\`, and`,`\`${r.type}\` in \`${kr(r.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}}let F2=class extends D{constructor({expectedSize:e,givenSize:r}){super(`Expected bytes${e}, got bytes${r}.`,{name:"BytesSizeMismatchError"})}};class xo extends D{constructor({abiItem:e,data:r,params:n,size:s}){super([`Data size of ${s} bytes is too small for non-indexed event parameters.`].join(`
17
- `),{metaMessages:[`Params: (${_c(n,{includeName:!0})})`,`Data: ${r} (${s} bytes)`],name:"DecodeLogDataMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e,this.data=r,this.params=n,this.size=s}}class Tc extends D{constructor({abiItem:e,param:r}){super([`Expected a topic for indexed event parameter${r.name?` "${r.name}"`:""} on event "${kr(e,{includeName:!0})}".`].join(`
18
- `),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e}}class j2 extends D{constructor(e,{docsPath:r}){super([`Type "${e}" is not a valid encoding type.`,"Please provide a valid ABI type."].join(`
19
- `),{docsPath:r,name:"InvalidAbiEncodingType"})}}class L2 extends D{constructor(e,{docsPath:r}){super([`Type "${e}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(`
20
- `),{docsPath:r,name:"InvalidAbiDecodingType"})}}let h0=class extends D{constructor(e){super([`Value "${e}" is not a valid array.`].join(`
21
- `),{name:"InvalidArrayError"})}};class H2 extends D{constructor(e){super([`"${e}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(`
22
- `),{name:"InvalidDefinitionTypeError"})}}class D2 extends D{constructor(e){super(`Filter type "${e}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}let p0=class extends D{constructor({offset:e,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},y0=class extends D{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}};class Qh extends D{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${e} ${n} long.`,{name:"InvalidBytesLengthError"})}}function ji(t,{dir:e,size:r=32}={}){return typeof t=="string"?Qn(t,{dir:e,size:r}):z2(t,{dir:e,size:r})}function Qn(t,{dir:e,size:r=32}={}){if(r===null)return t;const n=t.replace("0x","");if(n.length>r*2)throw new y0({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function z2(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new y0({size:t.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let s=0;s<r;s++){const i=e==="right";n[i?s:r-s-1]=t[i?s:t.length-s-1]}return n}let m0=class extends D{constructor({max:e,min:r,signed:n,size:s,value:i}){super(`Number "${i}" is not in safe ${s?`${s*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}};class V2 extends D{constructor(e){super(`Bytes value "${e}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}}class q2 extends D{constructor(e){super(`Hex value "${e}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}let G2=class extends D{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function ar(t,{dir:e="left"}={}){let r=typeof t=="string"?t.replace("0x",""):t,n=0;for(let s=0;s<r.length-1&&r[e==="left"?s:r.length-s-1].toString()==="0";s++)n++;return r=e==="left"?r.slice(n):r.slice(0,r.length-n),typeof t=="string"?(r.length===1&&e==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}function Pr(t,{size:e}){if(Le(t)>e)throw new G2({givenSize:Le(t),maxSize:e})}function ot(t,e={}){const{signed:r}=e;e.size&&Pr(t,{size:e.size});const n=BigInt(t);if(!r)return n;const s=(t.length-2)/2,i=(1n<<BigInt(s)*8n-1n)-1n;return n<=i?n:n-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function W2(t,e={}){let r=t;if(e.size&&(Pr(r,{size:e.size}),r=ar(r)),ar(r)==="0x00")return!1;if(ar(r)==="0x01")return!0;throw new q2(r)}function cr(t,e={}){return Number(ot(t,e))}const K2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Pt(t,e={}){return typeof t=="number"||typeof t=="bigint"?X(t,e):typeof t=="string"?Ti(t,e):typeof t=="boolean"?g0(t,e):Qe(t,e)}function g0(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(Pr(r,{size:e.size}),ji(r,{size:e.size})):r}function Qe(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=K2[t[s]];const n=`0x${r}`;return typeof e.size=="number"?(Pr(n,{size:e.size}),ji(n,{dir:"right",size:e.size})):n}function X(t,e={}){const{signed:r,size:n}=e,s=BigInt(t);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<o){const c=typeof t=="bigint"?"n":"";throw new m0({max:i?`${i}${c}`:void 0,min:`${o}${c}`,signed:r,size:n,value:`${t}${c}`})}const a=`0x${(r&&s<0?(1n<<BigInt(n*8))+BigInt(s):s).toString(16)}`;return n?ji(a,{size:n}):a}const Z2=new TextEncoder;function Ti(t,e={}){const r=Z2.encode(t);return Qe(r,e)}const X2=new TextEncoder;function Li(t,e={}){return typeof t=="number"||typeof t=="bigint"?J2(t,e):typeof t=="boolean"?Y2(t,e):_r(t)?Tr(t,e):ks(t,e)}function Y2(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?(Pr(r,{size:e.size}),ji(r,{size:e.size})):r}const Qr={zero:48,nine:57,A:65,F:70,a:97,f:102};function ep(t){if(t>=Qr.zero&&t<=Qr.nine)return t-Qr.zero;if(t>=Qr.A&&t<=Qr.F)return t-(Qr.A-10);if(t>=Qr.a&&t<=Qr.f)return t-(Qr.a-10)}function Tr(t,e={}){let r=t;e.size&&(Pr(r,{size:e.size}),r=ji(r,{dir:"right",size:e.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const s=n.length/2,i=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=ep(n.charCodeAt(a++)),u=ep(n.charCodeAt(a++));if(c===void 0||u===void 0)throw new D(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);i[o]=c*16+u}return i}function J2(t,e){const r=X(t,e);return Tr(r)}function ks(t,e={}){const r=X2.encode(t);return typeof e.size=="number"?(Pr(r,{size:e.size}),ji(r,{dir:"right",size:e.size})):r}const _a=BigInt(2**32-1),tp=BigInt(32);function b0(t,e=!1){return e?{h:Number(t&_a),l:Number(t>>tp&_a)}:{h:Number(t>>tp&_a)|0,l:Number(t&_a)|0}}function Q2(t,e=!1){const r=t.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=b0(t[i],e);[n[i],s[i]]=[o,a]}return[n,s]}const w0=(t,e,r)=>t>>>r|e<<32-r,v0=(t,e,r)=>t<<32-r|e>>>r,eE=(t,e,r)=>t<<64-r|e>>>r-32,tE=(t,e,r)=>t>>>r-32|e<<64-r,rE=(t,e)=>e,nE=(t,e)=>t,sE=(t,e,r)=>t<<r|e>>>32-r,iE=(t,e,r)=>e<<r|t>>>32-r,oE=(t,e,r)=>e<<r-32|t>>>64-r,aE=(t,e,r)=>t<<r-32|e>>>64-r;function E0(t,e,r,n){const s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const S0=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),A0=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,ti=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ic(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function rs(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Kr(t,...e){if(!Ic(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function x0(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");rs(t.outputLen),rs(t.blockLen)}function ns(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Ed(t,e){Kr(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function ko(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ir(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function vu(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Rr(t,e){return t<<32-e|t>>>e}function Ta(t,e){return t<<e|t>>>32-e>>>0}const k0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function _0(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const ln=k0?t=>t:t=>_0(t);function cE(t){for(let e=0;e<t.length;e++)t[e]=_0(t[e]);return t}const qn=k0?t=>t:cE,T0=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",uE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function yi(t){if(Kr(t),T0)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=uE[t[r]];return e}const en={_0:48,_9:57,A:65,F:70,a:97,f:102};function rp(t){if(t>=en._0&&t<=en._9)return t-en._0;if(t>=en.A&&t<=en.F)return t-(en.A-10);if(t>=en.a&&t<=en.f)return t-(en.a-10)}function fc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(T0)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let s=0,i=0;s<r;s++,i+=2){const o=rp(t.charCodeAt(i)),a=rp(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[s]=o*16+a}return n}function lE(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function wn(t){return typeof t=="string"&&(t=lE(t)),Kr(t),t}function Gn(...t){let e=0;for(let n=0;n<t.length;n++){const s=t[n];Kr(s),e+=s.length}const r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){const i=t[n];r.set(i,s),s+=i.length}return r}class Pc{}function Oc(t){const e=n=>t().update(wn(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function fE(t){const e=(n,s)=>t(s).update(wn(n)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}function I0(t=32){if(ti&&typeof ti.getRandomValues=="function")return ti.getRandomValues(new Uint8Array(t));if(ti&&typeof ti.randomBytes=="function")return Uint8Array.from(ti.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const dE=BigInt(0),Xi=BigInt(1),hE=BigInt(2),pE=BigInt(7),yE=BigInt(256),mE=BigInt(113),P0=[],O0=[],B0=[];for(let t=0,e=Xi,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],P0.push(2*(5*n+r)),O0.push((t+1)*(t+2)/2%64);let s=dE;for(let i=0;i<7;i++)e=(e<<Xi^(e>>pE)*mE)%yE,e&hE&&(s^=Xi<<(Xi<<BigInt(i))-Xi);B0.push(s)}const C0=Q2(B0,!0),gE=C0[0],bE=C0[1],np=(t,e,r)=>r>32?oE(t,e,r):sE(t,e,r),sp=(t,e,r)=>r>32?aE(t,e,r):iE(t,e,r);function wE(t,e=24){const r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=r[c],l=r[c+1],d=np(u,l,1)^r[a],h=sp(u,l,1)^r[a+1];for(let f=0;f<50;f+=10)t[o+f]^=d,t[o+f+1]^=h}let s=t[2],i=t[3];for(let o=0;o<24;o++){const a=O0[o],c=np(s,i,a),u=sp(s,i,a),l=P0[o];s=t[l],i=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=gE[n],t[1]^=bE[n]}Ir(r)}class Sd extends Pc{constructor(e,r,n,s=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=s,this.rounds=i,rs(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ko(this.state)}clone(){return this._cloneInto()}keccak(){qn(this.state32),wE(this.state32,this.rounds),qn(this.state32),this.posOut=0,this.pos=0}update(e){ns(this),e=wn(e),Kr(e);const{blockLen:r,state:n}=this,s=e.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++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:n,blockLen:s}=this;e[n]^=r,r&128&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){ns(this,!1),Kr(e),this.finish();const r=this.state,{blockLen:n}=this;for(let s=0,i=e.length;s<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return rs(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ed(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Ir(this.state)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:s,rounds:i,enableXOF:o}=this;return e||(e=new Sd(r,n,s,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const vE=(t,e,r)=>Oc(()=>new Sd(e,t,r)),$0=vE(1,136,256/8);function lt(t,e){const r=e||"hex",n=$0(_r(t,{strict:!1})?Li(t):t);return r==="bytes"?n:Pt(n)}const EE=t=>lt(Li(t));function SE(t){return EE(t)}function AE(t){let e=!0,r="",n=0,s="",i=!1;for(let o=0;o<t.length;o++){const a=t[o];if(["(",")",","].includes(a)&&(e=!0),a==="("&&n++,a===")"&&n--,!!e){if(n===0){if(a===" "&&["event","function",""].includes(s))s="";else if(s+=a,a===")"){i=!0;break}continue}if(a===" "){t[o-1]!==","&&r!==","&&r!==",("&&(r="",e=!1);continue}s+=a,r+=a}}if(!i)throw new D("Unable to normalize signature.");return s}const xE=t=>{const e=typeof t=="string"?t:Dv(t);return AE(e)};function R0(t){return SE(xE(t))}const Bc=R0;let Bt=class extends D{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}},Cc=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}};const Eu=new Cc(8192);function ia(t,e){if(Eu.has(`${t}.${e}`))return Eu.get(`${t}.${e}`);const r=t.substring(2).toLowerCase(),n=lt(ks(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 Eu.set(`${t}.${e}`,i),i}function N0(t,e){if(!it(t,{strict:!1}))throw new Bt({address:t});return ia(t,e)}const kE=/^0x[a-fA-F0-9]{40}$/,Su=new Cc(8192);function it(t,e){const{strict:r=!0}=e??{},n=`${t}.${r}`;if(Su.has(n))return Su.get(n);const s=kE.test(t)?t.toLowerCase()===t?!0:r?ia(t)===t:!0:!1;return Su.set(n,s),s}function Wt(t){return typeof t[0]=="string"?Or(t):_E(t)}function _E(t){let e=0;for(const s of t)e+=s.length;const r=new Uint8Array(e);let n=0;for(const s of t)r.set(s,n),n+=s.length;return r}function Or(t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function Cs(t,e,r,{strict:n}={}){return _r(t,{strict:!1})?dc(t,e,r,{strict:n}):F0(t,e,r,{strict:n})}function U0(t,e){if(typeof e=="number"&&e>0&&e>Le(t)-1)throw new p0({offset:e,position:"start",size:Le(t)})}function M0(t,e,r){if(typeof e=="number"&&typeof r=="number"&&Le(t)!==r-e)throw new p0({offset:r,position:"end",size:Le(t)})}function F0(t,e,r,{strict:n}={}){U0(t,e);const s=t.slice(e,r);return n&&M0(s,e,r),s}function dc(t,e,r,{strict:n}={}){U0(t,e);const s=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return n&&M0(s,e,r),s}const TE=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,j0=/^(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 Pn(t,e){if(t.length!==e.length)throw new $2({expectedLength:t.length,givenLength:e.length});const r=IE({params:t,values:e}),n=xd(r);return n.length===0?"0x":n}function IE({params:t,values:e}){const r=[];for(let n=0;n<t.length;n++)r.push(Ad({param:t[n],value:e[n]}));return r}function Ad({param:t,value:e}){const r=kd(t.type);if(r){const[n,s]=r;return OE(e,{length:n,param:{...t,type:s}})}if(t.type==="tuple")return NE(e,{param:t});if(t.type==="address")return PE(e);if(t.type==="bool")return CE(e);if(t.type.startsWith("uint")||t.type.startsWith("int")){const n=t.type.startsWith("int"),[,,s="256"]=j0.exec(t.type)??[];return $E(e,{signed:n,size:Number(s)})}if(t.type.startsWith("bytes"))return BE(e,{param:t});if(t.type==="string")return RE(e);throw new j2(t.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function xd(t){let e=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?e+=32:e+=Le(a)}const r=[],n=[];let s=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?(r.push(X(e+s,{size:32})),n.push(a),s+=Le(a)):r.push(a)}return Wt([...r,...n])}function PE(t){if(!it(t))throw new Bt({address:t});return{dynamic:!1,encoded:Qn(t.toLowerCase())}}function OE(t,{length:e,param:r}){const n=e===null;if(!Array.isArray(t))throw new h0(t);if(!n&&t.length!==e)throw new B2({expectedLength:e,givenLength:t.length,type:`${r.type}[${e}]`});let s=!1;const i=[];for(let o=0;o<t.length;o++){const a=Ad({param:r,value:t[o]});a.dynamic&&(s=!0),i.push(a)}if(n||s){const o=xd(i);if(n){const a=X(i.length,{size:32});return{dynamic:!0,encoded:i.length>0?Wt([a,o]):a}}if(s)return{dynamic:!0,encoded:o}}return{dynamic:!1,encoded:Wt(i.map(({encoded:o})=>o))}}function BE(t,{param:e}){const[,r]=e.type.split("bytes"),n=Le(t);if(!r){let s=t;return n%32!==0&&(s=Qn(s,{dir:"right",size:Math.ceil((t.length-2)/2/32)*32})),{dynamic:!0,encoded:Wt([Qn(X(n,{size:32})),s])}}if(n!==Number.parseInt(r))throw new C2({expectedSize:Number.parseInt(r),value:t});return{dynamic:!1,encoded:Qn(t,{dir:"right"})}}function CE(t){if(typeof t!="boolean")throw new D(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Qn(g0(t))}}function $E(t,{signed:e,size:r=256}){if(typeof r=="number"){const n=2n**(BigInt(r)-(e?1n:0n))-1n,s=e?-n-1n:0n;if(t>n||t<s)throw new m0({max:n.toString(),min:s.toString(),signed:e,size:r/8,value:t.toString()})}return{dynamic:!1,encoded:X(t,{size:32,signed:e})}}function RE(t){const e=Ti(t),r=Math.ceil(Le(e)/32),n=[];for(let s=0;s<r;s++)n.push(Qn(Cs(e,s*32,(s+1)*32),{dir:"right"}));return{dynamic:!0,encoded:Wt([Qn(X(Le(e),{size:32})),...n])}}function NE(t,{param:e}){let r=!1;const n=[];for(let s=0;s<e.components.length;s++){const i=e.components[s],o=Array.isArray(t)?s:i.name,a=Ad({param:i,value:t[o]});n.push(a),a.dynamic&&(r=!0)}return{dynamic:r,encoded:r?xd(n):Wt(n.map(({encoded:s})=>s))}}function kd(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}const oa=t=>Cs(R0(t),0,4);function Gs(t){const{abi:e,args:r=[],name:n}=t,s=_r(n,{strict:!1}),i=e.filter(a=>s?a.type==="function"?oa(a)===n:a.type==="event"?Bc(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((u,l)=>{const d="inputs"in a&&a.inputs[l];return d?gf(u,d):!1})){if(o&&"inputs"in o&&o.inputs){const u=L0(a.inputs,o.inputs,r);if(u)throw new M2({abiItem:a,type:u[0]},{abiItem:o,type:u[1]})}o=a}}return o||i[0]}function gf(t,e){const r=typeof t,n=e.type;switch(n){case"address":return it(t,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in e?Object.values(e.components).every((s,i)=>gf(Object.values(t)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||t instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(t)&&t.every(s=>gf(s,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function L0(t,e,r){for(const n in t){const s=t[n],i=e[n];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return L0(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")?it(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?it(r[n],{strict:!1}):!1)return o}}const ip="/docs/contract/encodeEventTopics";function aa(t){var c;const{abi:e,eventName:r,args:n}=t;let s=e[0];if(r){const u=Gs({abi:e,name:r});if(!u)throw new Jh(r,{docsPath:ip});s=u}if(s.type!=="event")throw new Jh(void 0,{docsPath:ip});const i=kr(s),o=Bc(i);let a=[];if(n&&"inputs"in s){const u=(c=s.inputs)==null?void 0:c.filter(d=>"indexed"in d&&d.indexed),l=Array.isArray(n)?n:Object.values(n).length>0?(u==null?void 0:u.map(d=>n[d.name]))??[]:[];l.length>0&&(a=(u==null?void 0:u.map((d,h)=>Array.isArray(l[h])?l[h].map((f,m)=>op({param:d,value:l[h][m]})):typeof l[h]<"u"&&l[h]!==null?op({param:d,value:l[h]}):null))??[])}return[o,...a]}function op({param:t,value:e}){if(t.type==="string"||t.type==="bytes")return lt(Li(e));if(t.type==="tuple"||t.type.match(/^(.*)\[(\d+)?\]$/))throw new D2(t.type);return Pn([t],[e])}function $c(t,{method:e}){var n,s;const r={};return t.transport.type==="fallback"&&((s=(n=t.transport).onResponse)==null||s.call(n,({method:i,response:o,status:a,transport:c})=>{a==="success"&&e===i&&(r[o]=c.request)})),i=>r[i]||t.request}async function _d(t,e){const{address:r,abi:n,args:s,eventName:i,fromBlock:o,strict:a,toBlock:c}=e,u=$c(t,{method:"eth_newFilter"}),l=i?aa({abi:n,args:s,eventName:i}):void 0,d=await t.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof o=="bigint"?X(o):o,toBlock:typeof c=="bigint"?X(c):c,topics:l}]});return{abi:n,args:s,eventName:i,id:d,request:u(d),strict:!!a,type:"event"}}function We(t){return typeof t=="string"?{address:t,type:"json-rpc"}:t}const ap="/docs/contract/encodeFunctionData";function UE(t){const{abi:e,args:r,functionName:n}=t;let s=e[0];if(n){const i=Gs({abi:e,args:r,name:n});if(!i)throw new _i(n,{docsPath:ap});s=i}if(s.type!=="function")throw new _i(void 0,{docsPath:ap});return{abi:[s],functionName:oa(kr(s))}}function fr(t){const{args:e}=t,{abi:r,functionName:n}=(()=>{var a;return t.abi.length===1&&((a=t.functionName)!=null&&a.startsWith("0x"))?t:UE(t)})(),s=r[0],i=n,o="inputs"in s&&s.inputs?Pn(s.inputs,e??[]):void 0;return Or([i,o??"0x"])}const ME={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."},H0={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},FE={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};class cp extends D{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class D0 extends D{constructor({length:e,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${e}\`).`,{name:"PositionOutOfBoundsError"})}}class jE extends D{constructor({count:e,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${e}\`).`,{name:"RecursiveReadLimitExceededError"})}}const LE={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 jE({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(t){if(t<0||t>this.bytes.length-1)throw new D0({length:this.bytes.length,position:t})},decrementPosition(t){if(t<0)throw new cp({offset:t});const e=this.position-t;this.assertPosition(e),this.position=e},getReadCount(t){return this.positionReadCount.get(t||this.position)||0},incrementPosition(t){if(t<0)throw new cp({offset:t});const e=this.position+t;this.assertPosition(e),this.position=e},inspectByte(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectBytes(t,e){const r=e??this.position;return this.assertPosition(r+t-1),this.bytes.subarray(r,r+t)},inspectUint8(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectUint16(t){const e=t??this.position;return this.assertPosition(e+1),this.dataView.getUint16(e)},inspectUint24(t){const e=t??this.position;return this.assertPosition(e+2),(this.dataView.getUint16(e)<<8)+this.dataView.getUint8(e+2)},inspectUint32(t){const e=t??this.position;return this.assertPosition(e+3),this.dataView.getUint32(e)},pushByte(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushBytes(t){this.assertPosition(this.position+t.length-1),this.bytes.set(t,this.position),this.position+=t.length},pushUint8(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushUint16(t){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,t),this.position+=2},pushUint24(t){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,t>>8),this.dataView.setUint8(this.position+2,t&255),this.position+=3},pushUint32(t){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,t),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const t=this.inspectByte();return this.position++,t},readBytes(t,e){this.assertReadLimit(),this._touch();const r=this.inspectBytes(t);return this.position+=e??t,r},readUint8(){this.assertReadLimit(),this._touch();const t=this.inspectUint8();return this.position+=1,t},readUint16(){this.assertReadLimit(),this._touch();const t=this.inspectUint16();return this.position+=2,t},readUint24(){this.assertReadLimit(),this._touch();const t=this.inspectUint24();return this.position+=3,t},readUint32(){this.assertReadLimit(),this._touch();const t=this.inspectUint32();return this.position+=4,t},get remaining(){return this.bytes.length-this.position},setPosition(t){const e=this.position;return this.assertPosition(t),this.position=t,()=>this.position=e},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const t=this.getReadCount();this.positionReadCount.set(this.position,t+1),t>0&&this.recursiveReadCount++}};function Td(t,{recursiveReadLimit:e=8192}={}){const r=Object.create(LE);return r.bytes=t,r.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=e,r}function HE(t,e={}){typeof e.size<"u"&&Pr(t,{size:e.size});const r=Qe(t,e);return ot(r,e)}function DE(t,e={}){let r=t;if(typeof e.size<"u"&&(Pr(r,{size:e.size}),r=ar(r)),r.length>1||r[0]>1)throw new V2(r);return!!r[0]}function vn(t,e={}){typeof e.size<"u"&&Pr(t,{size:e.size});const r=Qe(t,e);return cr(r,e)}function zE(t,e={}){let r=t;return typeof e.size<"u"&&(Pr(r,{size:e.size}),r=ar(r,{dir:"right"})),new TextDecoder().decode(r)}function ca(t,e){const r=typeof e=="string"?Tr(e):e,n=Td(r);if(Le(r)===0&&t.length>0)throw new sa;if(Le(e)&&Le(e)<32)throw new u0({data:typeof e=="string"?e:Qe(e),params:t,size:Le(e)});let s=0;const i=[];for(let o=0;o<t.length;++o){const a=t[o];n.setPosition(s);const[c,u]=mi(n,a,{staticPosition:0});s+=u,i.push(c)}return i}function mi(t,e,{staticPosition:r}){const n=kd(e.type);if(n){const[s,i]=n;return qE(t,{...e,type:i},{length:s,staticPosition:r})}if(e.type==="tuple")return ZE(t,e,{staticPosition:r});if(e.type==="address")return VE(t);if(e.type==="bool")return GE(t);if(e.type.startsWith("bytes"))return WE(t,e,{staticPosition:r});if(e.type.startsWith("uint")||e.type.startsWith("int"))return KE(t,e);if(e.type==="string")return XE(t,{staticPosition:r});throw new L2(e.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const up=32,bf=32;function VE(t){const e=t.readBytes(32);return[ia(Qe(F0(e,-20))),32]}function qE(t,e,{length:r,staticPosition:n}){if(!r){const o=vn(t.readBytes(bf)),a=n+o,c=a+up;t.setPosition(a);const u=vn(t.readBytes(up)),l=_o(e);let d=0;const h=[];for(let f=0;f<u;++f){t.setPosition(c+(l?f*32:d));const[m,g]=mi(t,e,{staticPosition:c});d+=g,h.push(m)}return t.setPosition(n+32),[h,32]}if(_o(e)){const o=vn(t.readBytes(bf)),a=n+o,c=[];for(let u=0;u<r;++u){t.setPosition(a+u*32);const[l]=mi(t,e,{staticPosition:a});c.push(l)}return t.setPosition(n+32),[c,32]}let s=0;const i=[];for(let o=0;o<r;++o){const[a,c]=mi(t,e,{staticPosition:n+s});s+=c,i.push(a)}return[i,s]}function GE(t){return[DE(t.readBytes(32),{size:32}),32]}function WE(t,e,{staticPosition:r}){const[n,s]=e.type.split("bytes");if(!s){const o=vn(t.readBytes(32));t.setPosition(r+o);const a=vn(t.readBytes(32));if(a===0)return t.setPosition(r+32),["0x",32];const c=t.readBytes(a);return t.setPosition(r+32),[Qe(c),32]}return[Qe(t.readBytes(Number.parseInt(s),32)),32]}function KE(t,e){const r=e.type.startsWith("int"),n=Number.parseInt(e.type.split("int")[1]||"256"),s=t.readBytes(32);return[n>48?HE(s,{signed:r}):vn(s,{signed:r}),32]}function ZE(t,e,{staticPosition:r}){const n=e.components.length===0||e.components.some(({name:o})=>!o),s=n?[]:{};let i=0;if(_o(e)){const o=vn(t.readBytes(bf)),a=r+o;for(let c=0;c<e.components.length;++c){const u=e.components[c];t.setPosition(a+i);const[l,d]=mi(t,u,{staticPosition:a});i+=d,s[n?c:u==null?void 0:u.name]=l}return t.setPosition(r+32),[s,32]}for(let o=0;o<e.components.length;++o){const a=e.components[o],[c,u]=mi(t,a,{staticPosition:r});s[n?o:a==null?void 0:a.name]=c,i+=u}return[s,i]}function XE(t,{staticPosition:e}){const r=vn(t.readBytes(32)),n=e+r;t.setPosition(n);const s=vn(t.readBytes(32));if(s===0)return t.setPosition(e+32),["",32];const i=t.readBytes(s,32),o=zE(ar(i));return t.setPosition(e+32),[o,32]}function _o(t){var n;const{type:e}=t;if(e==="string"||e==="bytes"||e.endsWith("[]"))return!0;if(e==="tuple")return(n=t.components)==null?void 0:n.some(_o);const r=kd(t.type);return!!(r&&_o({...t,type:r[1]}))}function z0(t){const{abi:e,data:r}=t,n=Cs(r,0,4);if(n==="0x")throw new sa;const i=[...e||[],H0,FE].find(o=>o.type==="error"&&n===oa(kr(o)));if(!i)throw new l0(n,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:i,args:"inputs"in i&&i.inputs&&i.inputs.length>0?ca(i.inputs,Cs(r,4)):void 0,errorName:i.name}}const Je=(t,e,r)=>JSON.stringify(t,(n,s)=>typeof s=="bigint"?s.toString():s,r);function V0({abiItem:t,args:e,includeFunctionName:r=!0,includeName:n=!1}){if("name"in t&&"inputs"in t&&t.inputs)return`${r?t.name:""}(${t.inputs.map((s,i)=>`${n&&s.name?`${s.name}: `:""}${typeof e[i]=="object"?Je(e[i]):e[i]}`).join(", ")})`}const YE={gwei:9,wei:18},JE={ether:-9,wei:9};function q0(t,e){let r=t.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(e,"0");let[s,i]=[r.slice(0,r.length-e),r.slice(r.length-e)];return i=i.replace(/(0+)$/,""),`${n?"-":""}${s||"0"}${i?`.${i}`:""}`}function Id(t,e="wei"){return q0(t,YE[e])}function Mt(t,e="wei"){return q0(t,JE[e])}class QE extends D{constructor({address:e}){super(`State for account "${e}" is set multiple times.`,{name:"AccountStateConflictError"})}}class eS extends D{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function lp(t){return t.reduce((e,{slot:r,value:n})=>`${e} ${r}: ${n}
23
- `,"")}function tS(t){return t.reduce((e,{address:r,...n})=>{let s=`${e} ${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+=lp(n.state)),n.stateDiff&&(s+=` stateDiff:
29
- `,s+=lp(n.stateDiff)),s},` State Override:
30
- `).slice(0,-1)}function ua(t){const e=Object.entries(t).map(([n,s])=>s===void 0||s===!1?null:[n,s]).filter(Boolean),r=e.reduce((n,[s])=>Math.max(n,s.length),0);return e.map(([n,s])=>` ${`${n}:`.padEnd(r+1)} ${s}`).join(`
31
- `)}class rS extends D{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 nS extends D{constructor({v:e}){super(`Invalid \`v\` value "${e}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class sS extends D{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",ua(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class iS extends D{constructor({storageKey:e}){super(`Size for storage key "${e}" is invalid. Expected 32 bytes. Got ${Math.floor((e.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}class oS extends D{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:l,to:d,value:h}){var m;const f=ua({chain:s&&`${s==null?void 0:s.name} (id: ${s==null?void 0:s.id})`,from:r==null?void 0:r.address,to:d,value:typeof h<"u"&&`${Id(h)} ${((m=s==null?void 0:s.nativeCurrency)==null?void 0:m.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${Mt(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Mt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Mt(u)} gwei`,nonce:l});super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Request Arguments:",f].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class G0 extends D{constructor({blockHash:e,blockNumber:r,blockTag:n,hash:s,index:i}){let o="Transaction";n&&i!==void 0&&(o=`Transaction at block time "${n}" at index "${i}"`),e&&i!==void 0&&(o=`Transaction at block hash "${e}" 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 W0 extends D{constructor({hash:e}){super(`Transaction receipt with hash "${e}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class aS extends D{constructor({hash:e}){super(`Timed out while waiting for transaction with hash "${e}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}const cS=t=>t,Rc=t=>t;class K0 extends D{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:l,to:d,value:h,stateOverride:f}){var v;const m=r?We(r):void 0;let g=ua({from:m==null?void 0:m.address,to:d,value:typeof h<"u"&&`${Id(h)} ${((v=s==null?void 0:s.nativeCurrency)==null?void 0:v.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${Mt(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Mt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Mt(u)} gwei`,nonce:l});f&&(g+=`
33
- ${tS(f)}`),super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Raw Call Arguments:",g].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class uS extends D{constructor(e,{abi:r,args:n,contractAddress:s,docsPath:i,functionName:o,sender:a}){const c=Gs({abi:r,args:n,name:o}),u=c?V0({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,l=c?kr(c,{includeName:!0}):void 0,d=ua({address:s&&cS(s),function:l,args:u&&u!=="()"&&`${[...Array((o==null?void 0:o.length)??0).keys()].map(()=>" ").join("")}${u}`,sender:a});super(e.shortMessage||`An unknown error occurred while executing the contract function "${o}".`,{cause:e,docsPath:i,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],d&&"Contract Call:",d].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=r,this.args=n,this.cause=e,this.contractAddress=s,this.functionName=o,this.sender=a}}class wf extends D{constructor({abi:e,data:r,functionName:n,message:s}){let i,o,a,c;if(r&&r!=="0x")try{o=z0({abi:e,data:r});const{abiItem:l,errorName:d,args:h}=o;if(d==="Error")c=h[0];else if(d==="Panic"){const[f]=h;c=ME[f]}else{const f=l?kr(l,{includeName:!0}):void 0,m=l&&h?V0({abiItem:l,args:h,includeFunctionName:!1,includeName:!1}):void 0;a=[f?`Error: ${f}`:"",m&&m!=="()"?` ${[...Array((d==null?void 0:d.length)??0).keys()].map(()=>" ").join("")}${m}`:""]}}catch(l){i=l}else s&&(c=s);let u;i instanceof l0&&(u=i.signature,a=[`Unable to decode signature "${u}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${u}.`]),super(c&&c!=="execution reverted"||u?[`The contract function "${n}" reverted with the following ${u?"signature":"reason"}:`,c||u].join(`
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=u}}class lS extends D{constructor({functionName:e}){super(`The contract function "${e}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${e}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError"})}}class fS extends D{constructor({factory:e}){super(`Deployment for counterfactual contract call failed${e?` for factory "${e}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}}class Nc extends D{constructor({data:e,message:r}){super(r||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e}}class gi extends D{constructor({body:e,cause:r,details:n,headers:s,status:i,url:o}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[i&&`Status: ${i}`,`URL: ${Rc(o)}`,e&&`Request body: ${Je(e)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=e,this.headers=s,this.status=i,this.url=o}}class Pd extends D{constructor({body:e,error:r,url:n}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[`URL: ${Rc(n)}`,`Request body: ${Je(e)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=r.code,this.data=r.data}}class fp extends D{constructor({body:e,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${Rc(r)}`,`Request body: ${Je(e)}`],name:"TimeoutError"})}}const dS=-1;class jt extends D{constructor(e,{code:r,docsPath:n,metaMessages:s,name:i,shortMessage:o}){super(o,{cause:e,docsPath:n,metaMessages:s||(e==null?void 0:e.metaMessages),name:i||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i||e.name,this.code=e instanceof Pd?e.code:r??dS}}class Xt extends jt{constructor(e,r){super(e,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}}class To extends jt{constructor(e){super(e,{code:To.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(To,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class Io extends jt{constructor(e){super(e,{code:Io.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(Io,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class Po extends jt{constructor(e,{method:r}={}){super(e,{code:Po.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}}Object.defineProperty(Po,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class Oo extends jt{constructor(e){super(e,{code:Oo.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
35
- `)})}}Object.defineProperty(Oo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class $s extends jt{constructor(e){super(e,{code:$s.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty($s,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class Rs extends jt{constructor(e){super(e,{code:Rs.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
36
- `)})}}Object.defineProperty(Rs,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class Bo extends jt{constructor(e){super(e,{code:Bo.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(Bo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class Co extends jt{constructor(e){super(e,{code:Co.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(Co,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class $o extends jt{constructor(e){super(e,{code:$o.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty($o,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class ms extends jt{constructor(e,{method:r}={}){super(e,{code:ms.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}}Object.defineProperty(ms,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class Ii extends jt{constructor(e){super(e,{code:Ii.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(Ii,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class Ro extends jt{constructor(e){super(e,{code:Ro.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(Ro,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class bi extends Xt{constructor(e){super(e,{code:bi.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(bi,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class No extends Xt{constructor(e){super(e,{code:No.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(No,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class Uo extends Xt{constructor(e,{method:r}={}){super(e,{code:Uo.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}}Object.defineProperty(Uo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Mo extends Xt{constructor(e){super(e,{code:Mo.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Mo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class Fo extends Xt{constructor(e){super(e,{code:Fo.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Fo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class jo extends Xt{constructor(e){super(e,{code:jo.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(jo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class Pi extends Xt{constructor(e){super(e,{code:Pi.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(Pi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class Lo extends Xt{constructor(e){super(e,{code:Lo.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(Lo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class Ho extends Xt{constructor(e){super(e,{code:Ho.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(Ho,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class Do extends Xt{constructor(e){super(e,{code:Do.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(Do,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class zo extends Xt{constructor(e){super(e,{code:zo.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(zo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class Vo extends Xt{constructor(e){super(e,{code:Vo.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(Vo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class Oi extends Xt{constructor(e){super(e,{code:Oi.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(Oi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class hS extends jt{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const pS=3;function Ns(t,{abi:e,address:r,args:n,docsPath:s,functionName:i,sender:o}){const a=t instanceof Nc?t:t instanceof D?t.walk(m=>"data"in m)||t.walk():{},{code:c,data:u,details:l,message:d,shortMessage:h}=a,f=t instanceof sa?new lS({functionName:i}):[pS,$s.code].includes(c)&&(u||l||d||h)?new wf({abi:e,data:typeof u=="object"?u.data:u,functionName:i,message:a instanceof Pd?l:h??d}):t;return new uS(f,{abi:e,args:n,contractAddress:r,docsPath:s,functionName:i,sender:o})}function yS(t){const e=lt(`0x${t.substring(4)}`).substring(26);return ia(`0x${e}`)}async function mS({hash:t,signature:e}){const r=_r(t)?t:Pt(t),{secp256k1:n}=await Promise.resolve().then(()=>r_);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:d,yParity:h}=e,f=Number(h??d),m=dp(f);return new n.Signature(ot(u),ot(l)).addRecoveryBit(m)}const o=_r(e)?e:Pt(e);if(Le(o)!==65)throw new Error("invalid signature length");const a=cr(`0x${o.slice(130)}`),c=dp(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function dp(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function Z0({hash:t,signature:e}){return yS(await mS({hash:t,signature:e}))}function ss(t,e="hex"){const r=X0(t),n=Td(new Uint8Array(r.length));return r.encode(n),e==="hex"?Qe(n.bytes):n.bytes}function X0(t){return Array.isArray(t)?gS(t.map(e=>X0(e))):bS(t)}function gS(t){const e=t.reduce((s,i)=>s+i.length,0),r=Y0(e);return{length:e<=55?1+e:1+r+e,encode(s){e<=55?s.pushByte(192+e):(s.pushByte(247+r),r===1?s.pushUint8(e):r===2?s.pushUint16(e):r===3?s.pushUint24(e):s.pushUint32(e));for(const{encode:i}of t)i(s)}}}function bS(t){const e=typeof t=="string"?Tr(t):t,r=Y0(e.length);return{length:e.length===1&&e[0]<128?1:e.length<=55?1+e.length:1+r+e.length,encode(s){e.length===1&&e[0]<128?s.pushBytes(e):e.length<=55?(s.pushByte(128+e.length),s.pushBytes(e)):(s.pushByte(183+r),r===1?s.pushUint8(e.length):r===2?s.pushUint16(e.length):r===3?s.pushUint24(e.length):s.pushUint32(e.length),s.pushBytes(e))}}}function Y0(t){if(t<2**8)return 1;if(t<2**16)return 2;if(t<2**24)return 3;if(t<2**32)return 4;throw new D("Length is too large.")}function wS(t){const{chainId:e,nonce:r,to:n}=t,s=t.contractAddress??t.address,i=lt(Or(["0x05",ss([e?X(e):"0x",s,r?X(r):"0x"])]));return n==="bytes"?Tr(i):i}async function J0(t){const{authorization:e,signature:r}=t;return Z0({hash:wS(e),signature:r??e})}class vS extends D{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:l,to:d,value:h}){var m;const f=ua({from:r==null?void 0:r.address,to:d,value:typeof h<"u"&&`${Id(h)} ${((m=s==null?void 0:s.nativeCurrency)==null?void 0:m.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${Mt(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Mt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Mt(u)} gwei`,nonce:l});super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",f].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class di extends D{constructor({cause:e,message:r}={}){var s;const n=(s=r==null?void 0:r.replace("execution reverted: ",""))==null?void 0:s.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(di,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(di,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});class Us extends D{constructor({cause:e,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Mt(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(Us,"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 vf extends D{constructor({cause:e,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Mt(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}}Object.defineProperty(vf,"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 Ef extends D{constructor({cause:e,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:e,name:"NonceTooHighError"})}}Object.defineProperty(Ef,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class Sf extends D{constructor({cause:e,nonce:r}={}){super([`Nonce provided for the transaction ${r?`(${r}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
37
- `),{cause:e,name:"NonceTooLowError"})}}Object.defineProperty(Sf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class Af extends D{constructor({cause:e,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:e,name:"NonceMaxValueError"})}}Object.defineProperty(Af,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class xf extends D{constructor({cause:e}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
38
- `),{cause:e,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}}Object.defineProperty(xf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class kf extends D{constructor({cause:e,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:e,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(kf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class _f extends D{constructor({cause:e,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction is too low.`,{cause:e,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(_f,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class Tf extends D{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(Tf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class qo extends D{constructor({cause:e,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${Mt(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${Mt(n)} gwei`:""}).`].join(`
39
- `),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(qo,"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 la extends D{constructor({cause:e}){super(`An error occurred while executing: ${e==null?void 0:e.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}function Uc(t,e){const r=(t.details||"").toLowerCase(),n=t instanceof D?t.walk(s=>(s==null?void 0:s.code)===di.code):t;return n instanceof D?new di({cause:t,message:n.details}):di.nodeMessage.test(r)?new di({cause:t,message:t.details}):Us.nodeMessage.test(r)?new Us({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas}):vf.nodeMessage.test(r)?new vf({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas}):Ef.nodeMessage.test(r)?new Ef({cause:t,nonce:e==null?void 0:e.nonce}):Sf.nodeMessage.test(r)?new Sf({cause:t,nonce:e==null?void 0:e.nonce}):Af.nodeMessage.test(r)?new Af({cause:t,nonce:e==null?void 0:e.nonce}):xf.nodeMessage.test(r)?new xf({cause:t}):kf.nodeMessage.test(r)?new kf({cause:t,gas:e==null?void 0:e.gas}):_f.nodeMessage.test(r)?new _f({cause:t,gas:e==null?void 0:e.gas}):Tf.nodeMessage.test(r)?new Tf({cause:t}):qo.nodeMessage.test(r)?new qo({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas,maxPriorityFeePerGas:e==null?void 0:e.maxPriorityFeePerGas}):new la({cause:t})}function ES(t,{docsPath:e,...r}){const n=(()=>{const s=Uc(t,r);return s instanceof la?t:s})();return new vS(n,{docsPath:e,...r})}function Mc(t,{format:e}){if(!e)return{};const r={};function n(i){const o=Object.keys(i);for(const a of o)a in t&&(r[a]=t[a]),i[a]&&typeof i[a]=="object"&&!Array.isArray(i[a])&&n(i[a])}const s=e(t||{});return n(s),r}function Od(t,e){return({exclude:r,format:n})=>({exclude:r,format:s=>{const i=e(s);if(r)for(const o of r)delete i[o];return{...i,...n(s)}},type:t})}const SS={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function Hi(t){const e={};return typeof t.authorizationList<"u"&&(e.authorizationList=AS(t.authorizationList)),typeof t.accessList<"u"&&(e.accessList=t.accessList),typeof t.blobVersionedHashes<"u"&&(e.blobVersionedHashes=t.blobVersionedHashes),typeof t.blobs<"u"&&(typeof t.blobs[0]!="string"?e.blobs=t.blobs.map(r=>Qe(r)):e.blobs=t.blobs),typeof t.data<"u"&&(e.data=t.data),typeof t.from<"u"&&(e.from=t.from),typeof t.gas<"u"&&(e.gas=X(t.gas)),typeof t.gasPrice<"u"&&(e.gasPrice=X(t.gasPrice)),typeof t.maxFeePerBlobGas<"u"&&(e.maxFeePerBlobGas=X(t.maxFeePerBlobGas)),typeof t.maxFeePerGas<"u"&&(e.maxFeePerGas=X(t.maxFeePerGas)),typeof t.maxPriorityFeePerGas<"u"&&(e.maxPriorityFeePerGas=X(t.maxPriorityFeePerGas)),typeof t.nonce<"u"&&(e.nonce=X(t.nonce)),typeof t.to<"u"&&(e.to=t.to),typeof t.type<"u"&&(e.type=SS[t.type]),typeof t.value<"u"&&(e.value=X(t.value)),e}function AS(t){return t.map(e=>({address:e.address,r:e.r?X(BigInt(e.r)):e.r,s:e.s?X(BigInt(e.s)):e.s,chainId:X(e.chainId),nonce:X(e.nonce),...typeof e.yParity<"u"?{yParity:X(e.yParity)}:{},...typeof e.v<"u"&&typeof e.yParity>"u"?{v:X(e.v)}:{}}))}function hp(t){if(!(!t||t.length===0))return t.reduce((e,{slot:r,value:n})=>{if(r.length!==66)throw new Qh({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new Qh({size:n.length,targetSize:66,type:"hex"});return e[r]=n,e},{})}function xS(t){const{balance:e,nonce:r,state:n,stateDiff:s,code:i}=t,o={};if(i!==void 0&&(o.code=i),e!==void 0&&(o.balance=X(e)),r!==void 0&&(o.nonce=X(r)),n!==void 0&&(o.state=hp(n)),s!==void 0){if(o.state)throw new eS;o.stateDiff=hp(s)}return o}function Bd(t){if(!t)return;const e={};for(const{address:r,...n}of t){if(!it(r,{strict:!1}))throw new Bt({address:r});if(e[r])throw new QE({address:r});e[r]=xS(n)}return e}const Fc=2n**256n-1n;function Ws(t){const{account:e,gasPrice:r,maxFeePerGas:n,maxPriorityFeePerGas:s,to:i}=t,o=e?We(e):void 0;if(o&&!it(o.address))throw new Bt({address:o.address});if(i&&!it(i))throw new Bt({address:i});if(typeof r<"u"&&(typeof n<"u"||typeof s<"u"))throw new rS;if(n&&n>Fc)throw new Us({maxFeePerGas:n});if(s&&n&&s>n)throw new qo({maxFeePerGas:n,maxPriorityFeePerGas:s})}class kS extends D{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class Cd extends D{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class _S extends D{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${Mt(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class Q0 extends D{constructor({blockHash:e,blockNumber:r}){let n="Block";e&&(n=`Block at hash "${e}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}const eg={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function jc(t){const e={...t,blockHash:t.blockHash?t.blockHash:null,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,chainId:t.chainId?cr(t.chainId):void 0,gas:t.gas?BigInt(t.gas):void 0,gasPrice:t.gasPrice?BigInt(t.gasPrice):void 0,maxFeePerBlobGas:t.maxFeePerBlobGas?BigInt(t.maxFeePerBlobGas):void 0,maxFeePerGas:t.maxFeePerGas?BigInt(t.maxFeePerGas):void 0,maxPriorityFeePerGas:t.maxPriorityFeePerGas?BigInt(t.maxPriorityFeePerGas):void 0,nonce:t.nonce?cr(t.nonce):void 0,to:t.to?t.to:null,transactionIndex:t.transactionIndex?Number(t.transactionIndex):null,type:t.type?eg[t.type]:void 0,typeHex:t.type?t.type:void 0,value:t.value?BigInt(t.value):void 0,v:t.v?BigInt(t.v):void 0};return t.authorizationList&&(e.authorizationList=IS(t.authorizationList)),e.yParity=(()=>{if(t.yParity)return Number(t.yParity);if(typeof e.v=="bigint"){if(e.v===0n||e.v===27n)return 0;if(e.v===1n||e.v===28n)return 1;if(e.v>=35n)return e.v%2n===0n?1:0}})(),e.type==="legacy"&&(delete e.accessList,delete e.maxFeePerBlobGas,delete e.maxFeePerGas,delete e.maxPriorityFeePerGas,delete e.yParity),e.type==="eip2930"&&(delete e.maxFeePerBlobGas,delete e.maxFeePerGas,delete e.maxPriorityFeePerGas),e.type==="eip1559"&&delete e.maxFeePerBlobGas,e}const TS=Od("transaction",jc);function IS(t){return t.map(e=>({address:e.address,chainId:Number(e.chainId),nonce:Number(e.nonce),r:e.r,s:e.s,yParity:Number(e.yParity)}))}function $d(t){const e=(t.transactions??[]).map(r=>typeof r=="string"?r:jc(r));return{...t,baseFeePerGas:t.baseFeePerGas?BigInt(t.baseFeePerGas):null,blobGasUsed:t.blobGasUsed?BigInt(t.blobGasUsed):void 0,difficulty:t.difficulty?BigInt(t.difficulty):void 0,excessBlobGas:t.excessBlobGas?BigInt(t.excessBlobGas):void 0,gasLimit:t.gasLimit?BigInt(t.gasLimit):void 0,gasUsed:t.gasUsed?BigInt(t.gasUsed):void 0,hash:t.hash?t.hash:null,logsBloom:t.logsBloom?t.logsBloom:null,nonce:t.nonce?t.nonce:null,number:t.number?BigInt(t.number):null,size:t.size?BigInt(t.size):void 0,timestamp:t.timestamp?BigInt(t.timestamp):void 0,transactions:e,totalDifficulty:t.totalDifficulty?BigInt(t.totalDifficulty):null}}const PS=Od("block",$d);async function Gr(t,{blockHash:e,blockNumber:r,blockTag:n=t.experimental_blockTag??"latest",includeTransactions:s}={}){var u,l,d;const i=s??!1,o=r!==void 0?X(r):void 0;let a=null;if(e?a=await t.request({method:"eth_getBlockByHash",params:[e,i]},{dedupe:!0}):a=await t.request({method:"eth_getBlockByNumber",params:[o||n,i]},{dedupe:!!o}),!a)throw new Q0({blockHash:e,blockNumber:r});return(((d=(l=(u=t.chain)==null?void 0:u.formatters)==null?void 0:l.block)==null?void 0:d.format)||$d)(a)}async function Rd(t){const e=await t.request({method:"eth_gasPrice"});return BigInt(e)}async function OS(t,e){return tg(t,e)}async function tg(t,e){var i,o;const{block:r,chain:n=t.chain,request:s}=e||{};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 u=r||await ae(t,Gr,"getBlock")({}),l=await a({block:u,client:t,request:s});if(l===null)throw new Error;return l}if(typeof a<"u")return a;const c=await t.request({method:"eth_maxPriorityFeePerGas"});return ot(c)}catch{const[a,c]=await Promise.all([r?Promise.resolve(r):ae(t,Gr,"getBlock")({}),ae(t,Rd,"getGasPrice")({})]);if(typeof a.baseFeePerGas!="bigint")throw new Cd;const u=c-a.baseFeePerGas;return u<0n?0n:u}}async function BS(t,e){return If(t,e)}async function If(t,e){var h,f;const{block:r,chain:n=t.chain,request:s,type:i="eip1559"}=e||{},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:t,request:s}):((g=n==null?void 0:n.fees)==null?void 0:g.baseFeeMultiplier)??1.2})();if(o<1)throw new kS;const c=10**(((h=o.toString().split(".")[1])==null?void 0:h.length)??0),u=m=>m*BigInt(Math.ceil(o*c))/BigInt(c),l=r||await ae(t,Gr,"getBlock")({});if(typeof((f=n==null?void 0:n.fees)==null?void 0:f.estimateFeesPerGas)=="function"){const m=await n.fees.estimateFeesPerGas({block:r,client:t,multiply:u,request:s,type:i});if(m!==null)return m}if(i==="eip1559"){if(typeof l.baseFeePerGas!="bigint")throw new Cd;const m=typeof(s==null?void 0:s.maxPriorityFeePerGas)=="bigint"?s.maxPriorityFeePerGas:await tg(t,{block:l,chain:n,request:s}),g=u(l.baseFeePerGas);return{maxFeePerGas:(s==null?void 0:s.maxFeePerGas)??g+m,maxPriorityFeePerGas:m}}return{gasPrice:(s==null?void 0:s.gasPrice)??u(await ae(t,Rd,"getGasPrice")({}))}}async function Nd(t,{address:e,blockTag:r="latest",blockNumber:n}){const s=await t.request({method:"eth_getTransactionCount",params:[e,typeof n=="bigint"?X(n):r]},{dedupe:!!n});return cr(s)}function Ud(t){const{kzg:e}=t,r=t.to??(typeof t.blobs[0]=="string"?"hex":"bytes"),n=typeof t.blobs[0]=="string"?t.blobs.map(i=>Tr(i)):t.blobs,s=[];for(const i of n)s.push(Uint8Array.from(e.blobToKzgCommitment(i)));return r==="bytes"?s:s.map(i=>Qe(i))}function Md(t){const{kzg:e}=t,r=t.to??(typeof t.blobs[0]=="string"?"hex":"bytes"),n=typeof t.blobs[0]=="string"?t.blobs.map(o=>Tr(o)):t.blobs,s=typeof t.commitments[0]=="string"?t.commitments.map(o=>Tr(o)):t.commitments,i=[];for(let o=0;o<n.length;o++){const a=n[o],c=s[o];i.push(Uint8Array.from(e.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map(o=>Qe(o))}function CS(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function $S(t,e,r){return t&e^~t&r}function RS(t,e,r){return t&e^t&r^e&r}let rg=class extends Pc{constructor(e,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=vu(this.buffer)}update(e){ns(this),e=wn(e),Kr(e);const{view:r,buffer:n,blockLen:s}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=vu(e);for(;s<=i-o;o+=s)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ns(this),Ed(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:o}=this;r[o++]=128,Ir(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let d=o;d<s;d++)r[d]=0;CS(n,s-8,BigInt(this.length*8),i),this.process(n,0);const a=vu(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<u;d++)a.setUint32(4*d,l[d],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:s,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=s,e.pos=a,s%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const $n=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Rn=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),NS=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]),Nn=new Uint32Array(64);let Fd=class extends rg{constructor(e=32){super(64,e,8,!1),this.A=$n[0]|0,this.B=$n[1]|0,this.C=$n[2]|0,this.D=$n[3]|0,this.E=$n[4]|0,this.F=$n[5]|0,this.G=$n[6]|0,this.H=$n[7]|0}get(){const{A:e,B:r,C:n,D:s,E:i,F:o,G:a,H:c}=this;return[e,r,n,s,i,o,a,c]}set(e,r,n,s,i,o,a,c){this.A=e|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(e,r){for(let d=0;d<16;d++,r+=4)Nn[d]=e.getUint32(r,!1);for(let d=16;d<64;d++){const h=Nn[d-15],f=Nn[d-2],m=Rr(h,7)^Rr(h,18)^h>>>3,g=Rr(f,17)^Rr(f,19)^f>>>10;Nn[d]=g+Nn[d-7]+m+Nn[d-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:u,H:l}=this;for(let d=0;d<64;d++){const h=Rr(a,6)^Rr(a,11)^Rr(a,25),f=l+h+$S(a,c,u)+NS[d]+Nn[d]|0,g=(Rr(n,2)^Rr(n,13)^Rr(n,22))+RS(n,s,i)|0;l=u,u=c,c=a,a=o+f|0,o=i,i=s,s=n,n=f+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,u=u+this.G|0,l=l+this.H|0,this.set(n,s,i,o,a,c,u,l)}roundClean(){Ir(Nn)}destroy(){this.set(0,0,0,0,0,0,0,0),Ir(this.buffer)}},ng=class extends Fd{constructor(){super(28),this.A=Rn[0]|0,this.B=Rn[1]|0,this.C=Rn[2]|0,this.D=Rn[3]|0,this.E=Rn[4]|0,this.F=Rn[5]|0,this.G=Rn[6]|0,this.H=Rn[7]|0}};const sg=Oc(()=>new Fd),US=Oc(()=>new ng),MS=Fd,ig=sg,FS=ng,jS=US,LS=Object.freeze(Object.defineProperty({__proto__:null,SHA224:FS,SHA256:MS,sha224:jS,sha256:ig},Symbol.toStringTag,{value:"Module"}));function co(t,e){const r=e||"hex",n=ig(_r(t,{strict:!1})?Li(t):t);return r==="bytes"?n:Pt(n)}function HS(t){const{commitment:e,version:r=1}=t,n=t.to??(typeof e=="string"?"hex":"bytes"),s=co(e,"bytes");return s.set([r],0),n==="bytes"?s:Qe(s)}function og(t){const{commitments:e,version:r}=t,n=t.to??(typeof e[0]=="string"?"hex":"bytes"),s=[];for(const i of e)s.push(HS({commitment:i,to:n,version:r}));return s}const pp=6,ag=32,jd=4096,cg=ag*jd,yp=cg*pp-1-1*jd*pp,ug=1;class DS extends D{constructor({maxSize:e,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class lg extends D{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class zS extends D{constructor({hash:e,size:r}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class VS extends D{constructor({hash:e,version:r}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:[`Expected: ${ug}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function qS(t){const e=t.to??(typeof t.data=="string"?"hex":"bytes"),r=typeof t.data=="string"?Tr(t.data):t.data,n=Le(r);if(!n)throw new lg;if(n>yp)throw new DS({maxSize:yp,size:n});const s=[];let i=!0,o=0;for(;i;){const a=Td(new Uint8Array(cg));let c=0;for(;c<jd;){const u=r.slice(o,o+(ag-1));if(a.pushByte(0),a.pushBytes(u),u.length<31){a.pushByte(128),i=!1;break}c++,o+=31}s.push(a)}return e==="bytes"?s.map(a=>a.bytes):s.map(a=>Qe(a.bytes))}function fg(t){const{data:e,kzg:r,to:n}=t,s=t.blobs??qS({data:e,to:n}),i=t.commitments??Ud({blobs:s,kzg:r,to:n}),o=t.proofs??Md({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 dg(t){if(t.type)return t.type;if(typeof t.authorizationList<"u")return"eip7702";if(typeof t.blobs<"u"||typeof t.blobVersionedHashes<"u"||typeof t.maxFeePerBlobGas<"u"||typeof t.sidecars<"u")return"eip4844";if(typeof t.maxFeePerGas<"u"||typeof t.maxPriorityFeePerGas<"u")return"eip1559";if(typeof t.gasPrice<"u")return typeof t.accessList<"u"?"eip2930":"legacy";throw new sS({transaction:t})}async function Di(t){const e=await t.request({method:"eth_chainId"},{dedupe:!0});return cr(e)}const hg=["blobVersionedHashes","chainId","fees","gas","nonce","type"],mp=new Map;async function Lc(t,e){const{account:r=t.account,blobs:n,chain:s,gas:i,kzg:o,nonce:a,nonceManager:c,parameters:u=hg,type:l}=e,d=r&&We(r),h={...e,...d?{from:d==null?void 0:d.address}:{}};let f;async function m(){return f||(f=await ae(t,Gr,"getBlock")({blockTag:"latest"}),f)}let g;async function v(){return g||(s?s.id:typeof e.chainId<"u"?e.chainId:(g=await ae(t,Di,"getChainId")({}),g))}if(u.includes("nonce")&&typeof a>"u"&&d)if(c){const S=await v();h.nonce=await c.consume({address:d.address,chainId:S,client:t})}else h.nonce=await ae(t,Nd,"getTransactionCount")({address:d.address,blockTag:"pending"});if((u.includes("blobVersionedHashes")||u.includes("sidecars"))&&n&&o){const S=Ud({blobs:n,kzg:o});if(u.includes("blobVersionedHashes")){const _=og({commitments:S,to:"hex"});h.blobVersionedHashes=_}if(u.includes("sidecars")){const _=Md({blobs:n,commitments:S,kzg:o}),E=fg({blobs:n,commitments:S,proofs:_,to:"hex"});h.sidecars=E}}if(u.includes("chainId")&&(h.chainId=await v()),(u.includes("fees")||u.includes("type"))&&typeof l>"u")try{h.type=dg(h)}catch{let S=mp.get(t.uid);if(typeof S>"u"){const _=await m();S=typeof(_==null?void 0:_.baseFeePerGas)=="bigint",mp.set(t.uid,S)}h.type=S?"eip1559":"legacy"}if(u.includes("fees"))if(h.type!=="legacy"&&h.type!=="eip2930"){if(typeof h.maxFeePerGas>"u"||typeof h.maxPriorityFeePerGas>"u"){const S=await m(),{maxFeePerGas:_,maxPriorityFeePerGas:E}=await If(t,{block:S,chain:s,request:h});if(typeof e.maxPriorityFeePerGas>"u"&&e.maxFeePerGas&&e.maxFeePerGas<E)throw new _S({maxPriorityFeePerGas:E});h.maxPriorityFeePerGas=E,h.maxFeePerGas=_}}else{if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")throw new Cd;if(typeof e.gasPrice>"u"){const S=await m(),{gasPrice:_}=await If(t,{block:S,chain:s,request:h,type:"legacy"});h.gasPrice=_}}return u.includes("gas")&&typeof i>"u"&&(h.gas=await ae(t,Ld,"estimateGas")({...h,account:d&&{address:d.address,type:"json-rpc"}})),Ws(h),delete h.parameters,h}async function pg(t,{address:e,blockNumber:r,blockTag:n=t.experimental_blockTag??"latest"}){const s=typeof r=="bigint"?X(r):void 0,i=await t.request({method:"eth_getBalance",params:[e,s||n]});return BigInt(i)}async function Ld(t,e){var s,i,o;const{account:r=t.account}=e,n=r?We(r):void 0;try{let N=function(Z){const{block:te,request:H,rpcStateOverride:T}=Z;return t.request({method:"eth_estimateGas",params:T?[H,te??t.experimental_blockTag??"latest",T]:te?[H,te]:[H]})};const{accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:l,blockNumber:d,blockTag:h,data:f,gas:m,gasPrice:g,maxFeePerBlobGas:v,maxFeePerGas:S,maxPriorityFeePerGas:_,nonce:E,value:x,stateOverride:O,...P}=await Lc(t,{...e,parameters:(n==null?void 0:n.type)==="local"?void 0:["blobVersionedHashes"]}),z=(typeof d=="bigint"?X(d):void 0)||h,C=Bd(O),Y=await(async()=>{if(P.to)return P.to;if(c&&c.length>0)return await J0({authorization:c[0]}).catch(()=>{throw new D("`to` is required. Could not infer from `authorizationList`")})})();Ws(e);const W=(o=(i=(s=t.chain)==null?void 0:s.formatters)==null?void 0:i.transactionRequest)==null?void 0:o.format,U=(W||Hi)({...Mc(P,{format:W}),from:n==null?void 0:n.address,accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:l,data:f,gas:m,gasPrice:g,maxFeePerBlobGas:v,maxFeePerGas:S,maxPriorityFeePerGas:_,nonce:E,to:Y,value:x});let F=BigInt(await N({block:z,request:U,rpcStateOverride:C}));if(c){const Z=await pg(t,{address:U.from}),te=await Promise.all(c.map(async H=>{const{address:T}=H,L=await N({block:z,request:{authorizationList:void 0,data:f,from:n==null?void 0:n.address,to:T,value:X(Z)},rpcStateOverride:C}).catch(()=>100000n);return 2n*BigInt(L)}));F+=te.reduce((H,T)=>H+T,0n)}return F}catch(a){throw ES(a,{...e,account:n,chain:t.chain})}}async function yg(t,e){const{abi:r,address:n,args:s,functionName:i,dataSuffix:o,...a}=e,c=fr({abi:r,args:s,functionName:i});try{return await ae(t,Ld,"estimateGas")({data:`${c}${o?o.replace("0x",""):""}`,to:n,...a})}catch(u){const l=a.account?We(a.account):void 0;throw Ns(u,{abi:r,address:n,args:s,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:l==null?void 0:l.address})}}function fa(t,e){if(!it(t,{strict:!1}))throw new Bt({address:t});if(!it(e,{strict:!1}))throw new Bt({address:e});return t.toLowerCase()===e.toLowerCase()}const gp="/docs/contract/decodeEventLog";function Hd(t){const{abi:e,data:r,strict:n,topics:s}=t,i=n??!0,[o,...a]=s;if(!o)throw new N2({docsPath:gp});const c=e.find(g=>g.type==="event"&&o===Bc(kr(g)));if(!(c&&"name"in c)||c.type!=="event")throw new f0(o,{docsPath:gp});const{name:u,inputs:l}=c,d=l==null?void 0:l.some(g=>!("name"in g&&g.name)),h=d?[]:{},f=l.map((g,v)=>[g,v]).filter(([g])=>"indexed"in g&&g.indexed);for(let g=0;g<f.length;g++){const[v,S]=f[g],_=a[g];if(!_)throw new Tc({abiItem:c,param:v});h[d?S:v.name||S]=GS({param:v,value:_})}const m=l.filter(g=>!("indexed"in g&&g.indexed));if(m.length>0){if(r&&r!=="0x")try{const g=ca(m,r);if(g)if(d)for(let v=0;v<l.length;v++)h[v]=h[v]??g.shift();else for(let v=0;v<m.length;v++)h[m[v].name]=g[v]}catch(g){if(i)throw g instanceof u0||g instanceof D0?new xo({abiItem:c,data:r,params:m,size:Le(r)}):g}else if(i)throw new xo({abiItem:c,data:"0x",params:m,size:0})}return{eventName:u,args:Object.values(h).length>0?h:void 0}}function GS({param:t,value:e}){return t.type==="string"||t.type==="bytes"||t.type==="tuple"||t.type.match(/^(.*)\[(\d+)?\]$/)?e:(ca([t],e)||[])[0]}function Dd(t){const{abi:e,args:r,logs:n,strict:s=!0}=t,i=(()=>{if(t.eventName)return Array.isArray(t.eventName)?t.eventName:[t.eventName]})();return n.map(o=>{var a;try{const c=e.find(l=>l.type==="event"&&o.topics[0]===Bc(l));if(!c)return null;const u=Hd({...o,abi:[c],strict:s});return i&&!i.includes(u.eventName)||!WS({args:u.args,inputs:c.inputs,matchArgs:r})?null:{...u,...o}}catch(c){let u,l;if(c instanceof f0)return null;if(c instanceof xo||c instanceof Tc){if(s)return null;u=c.abiItem.name,l=(a=c.abiItem.inputs)==null?void 0:a.some(d=>!("name"in d&&d.name))}return{...o,args:l?[]:{},eventName:u}}}).filter(Boolean)}function WS(t){const{args:e,inputs:r,matchArgs:n}=t;if(!n)return!0;if(!e)return!1;function s(i,o,a){try{return i.type==="address"?fa(o,a):i.type==="string"||i.type==="bytes"?lt(Li(o))===a:o===a}catch{return!1}}return Array.isArray(e)&&Array.isArray(n)?n.every((i,o)=>{if(i==null)return!0;const a=r[o];return a?(Array.isArray(i)?i:[i]).some(u=>s(a,u,e[o])):!1}):typeof e=="object"&&!Array.isArray(e)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([i,o])=>{if(o==null)return!0;const a=r.find(u=>u.name===i);return a?(Array.isArray(o)?o:[o]).some(u=>s(a,u,e[i])):!1}):!1}function Sn(t,{args:e,eventName:r}={}){return{...t,blockHash:t.blockHash?t.blockHash:null,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,logIndex:t.logIndex?Number(t.logIndex):null,transactionHash:t.transactionHash?t.transactionHash:null,transactionIndex:t.transactionIndex?Number(t.transactionIndex):null,...r?{args:e,eventName:r}:{}}}async function zd(t,{address:e,blockHash:r,fromBlock:n,toBlock:s,event:i,events:o,args:a,strict:c}={}){const u=c??!1,l=o??(i?[i]:void 0);let d=[];l&&(d=[l.flatMap(g=>aa({abi:[g],eventName:g.name,args:o?void 0:a}))],i&&(d=d[0]));let h;r?h=await t.request({method:"eth_getLogs",params:[{address:e,topics:d,blockHash:r}]}):h=await t.request({method:"eth_getLogs",params:[{address:e,topics:d,fromBlock:typeof n=="bigint"?X(n):n,toBlock:typeof s=="bigint"?X(s):s}]});const f=h.map(m=>Sn(m));return l?Dd({abi:l,args:a,logs:f,strict:u}):f}async function Vd(t,e){const{abi:r,address:n,args:s,blockHash:i,eventName:o,fromBlock:a,toBlock:c,strict:u}=e,l=o?Gs({abi:r,name:o}):void 0,d=l?void 0:r.filter(h=>h.type==="event");return ae(t,zd,"getLogs")({address:n,args:s,blockHash:i,event:l,events:d,fromBlock:a,toBlock:c,strict:u})}const Au="/docs/contract/decodeFunctionResult";function Ks(t){const{abi:e,args:r,functionName:n,data:s}=t;let i=e[0];if(n){const a=Gs({abi:e,args:r,name:n});if(!a)throw new _i(n,{docsPath:Au});i=a}if(i.type!=="function")throw new _i(void 0,{docsPath:Au});if(!i.outputs)throw new d0(i.name,{docsPath:Au});const o=ca(i.outputs,s);if(o&&o.length>1)return o;if(o&&o.length===1)return o[0]}const KS="0.1.1";function ZS(){return KS}let Ke=class Pf extends Error{constructor(e,r={}){const n=(()=>{var c;if(r.cause instanceof Pf){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 Pf&&r.cause.docsPath||r.docsPath,o=`https://oxlib.sh${s??""}`,a=[e||"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@${ZS()}`}),this.cause=r.cause,this.details=n,this.docs=o,this.docsPath=s,this.shortMessage=e}walk(e){return mg(this,e)}};function mg(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?mg(t.cause,e):e?null:t}const XS="#__bigint";function YS(t,e,r){return JSON.stringify(t,(n,s)=>typeof s=="bigint"?s.toString()+XS:s,r)}function JS(t,e){if(wp(t)>e)throw new cA({givenSize:wp(t),maxSize:e})}const tn={zero:48,nine:57,A:65,F:70,a:97,f:102};function bp(t){if(t>=tn.zero&&t<=tn.nine)return t-tn.zero;if(t>=tn.A&&t<=tn.F)return t-(tn.A-10);if(t>=tn.a&&t<=tn.f)return t-(tn.a-10)}function QS(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;if(t.length>n)throw new uA({size:t.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]=t[o?i:t.length-i-1]}return s}function qd(t,e){if(ur(t)>e)throw new pA({givenSize:ur(t),maxSize:e})}function eA(t,e){if(typeof e=="number"&&e>0&&e>ur(t)-1)throw new Eg({offset:e,position:"start",size:ur(t)})}function tA(t,e,r){if(typeof e=="number"&&typeof r=="number"&&ur(t)!==r-e)throw new Eg({offset:r,position:"end",size:ur(t)})}function gg(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;const s=t.replace("0x","");if(s.length>n*2)throw new yA({size:Math.ceil(s.length/2),targetSize:n,type:"Hex"});return`0x${s[r==="right"?"padEnd":"padStart"](n*2,"0")}`}const rA=new TextEncoder;function nA(t){return t instanceof Uint8Array?t:typeof t=="string"?iA(t):sA(t)}function sA(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function iA(t,e={}){const{size:r}=e;let n=t;r&&(qd(t,r),n=Fs(t,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 u=bp(s.charCodeAt(c++)),l=bp(s.charCodeAt(c++));if(u===void 0||l===void 0)throw new Ke(`Invalid byte sequence ("${s[c-2]}${s[c-1]}" in "${s}").`);o[a]=u*16+l}return o}function oA(t,e={}){const{size:r}=e,n=rA.encode(t);return typeof r=="number"?(JS(n,r),aA(n,r)):n}function aA(t,e){return QS(t,{dir:"right",size:e})}function wp(t){return t.length}let cA=class extends Ke{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},uA=class extends Ke{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}};const lA=new TextEncoder,fA=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function dA(t,e={}){const{strict:r=!1}=e;if(!t)throw new vp(t);if(typeof t!="string")throw new vp(t);if(r&&!/^0x[0-9a-fA-F]*$/.test(t))throw new Ep(t);if(!t.startsWith("0x"))throw new Ep(t)}function Zr(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function bg(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(qd(r,e.size),Ms(r,e.size)):r}function wg(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=fA[t[s]];const n=`0x${r}`;return typeof e.size=="number"?(qd(n,e.size),Fs(n,e.size)):n}function Tt(t,e={}){const{signed:r,size:n}=e,s=BigInt(t);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<o){const u=typeof t=="bigint"?"n":"";throw new vg({max:i?`${i}${u}`:void 0,min:`${o}${u}`,signed:r,size:n,value:`${t}${u}`})}const c=`0x${(r&&s<0?(1n<<BigInt(n*8))+BigInt(s):s).toString(16)}`;return n?Ms(c,n):c}function Gd(t,e={}){return wg(lA.encode(t),e)}function Ms(t,e){return gg(t,{dir:"left",size:e})}function Fs(t,e){return gg(t,{dir:"right",size:e})}function Wd(t,e,r,n={}){const{strict:s}=n;eA(t,e);const i=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return s&&tA(i,e,r),i}function ur(t){return Math.ceil((t.length-2)/2)}function hA(t,e={}){const{strict:r=!1}=e;try{return dA(t,{strict:r}),!0}catch{return!1}}class vg extends Ke{constructor({max:e,min:r,signed:n,size:s,value:i}){super(`Number \`${i}\` is not in safe${s?` ${s*8}-bit`:""}${n?" signed":" unsigned"} integer range ${e?`(\`${r}\` to \`${e}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class vp extends Ke{constructor(e){super(`Value \`${typeof e=="object"?YS(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class Ep extends Ke{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class pA extends Ke{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class Eg extends Ke{constructor({offset:e,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class yA extends Ke{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}function mA(t){return{address:t.address,amount:Tt(t.amount),index:Tt(t.index),validatorIndex:Tt(t.validatorIndex)}}function Sg(t){return{...typeof t.baseFeePerGas=="bigint"&&{baseFeePerGas:Tt(t.baseFeePerGas)},...typeof t.blobBaseFee=="bigint"&&{blobBaseFee:Tt(t.blobBaseFee)},...typeof t.feeRecipient=="string"&&{feeRecipient:t.feeRecipient},...typeof t.gasLimit=="bigint"&&{gasLimit:Tt(t.gasLimit)},...typeof t.number=="bigint"&&{number:Tt(t.number)},...typeof t.prevRandao=="bigint"&&{prevRandao:Tt(t.prevRandao)},...typeof t.time=="bigint"&&{time:Tt(t.time)},...t.withdrawals&&{withdrawals:t.withdrawals.map(mA)}}}const Of=[{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"}],Bf=[{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"}]}],Ag=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],xg=[...Ag,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],gA=[...Ag,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],Sp=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],Ap=[{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"}]}],xp=[{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"}],bA="0x82ad56cb",kg="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",wA="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",vA="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572";class Cf extends D{constructor({blockNumber:e,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...e&&n.blockCreated&&n.blockCreated>e?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${e}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class EA extends D{constructor({chain:e,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${e.id} – ${e.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${e.id} – ${e.name}`],name:"ChainMismatchError"})}}class SA extends D{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 _g extends D{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class Hc extends D{constructor({chainId:e}){super(typeof e=="number"?`Chain ID "${e}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const xu="/docs/contract/encodeDeployData";function Dc(t){const{abi:e,args:r,bytecode:n}=t;if(!r||r.length===0)return n;const s=e.find(o=>"type"in o&&o.type==="constructor");if(!s)throw new O2({docsPath:xu});if(!("inputs"in s))throw new Xh({docsPath:xu});if(!s.inputs||s.inputs.length===0)throw new Xh({docsPath:xu});const i=Pn(s.inputs,r);return Or([n,i])}function zi({blockNumber:t,chain:e,contract:r}){var s;const n=(s=e==null?void 0:e.contracts)==null?void 0:s[r];if(!n)throw new Cf({chain:e,contract:{name:r}});if(t&&n.blockCreated&&n.blockCreated>t)throw new Cf({blockNumber:t,chain:e,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function Tg(t,{docsPath:e,...r}){const n=(()=>{const s=Uc(t,r);return s instanceof la?t:s})();return new K0(n,{docsPath:e,...r})}function Kd(){let t=()=>{},e=()=>{};return{promise:new Promise((n,s)=>{t=n,e=s}),resolve:t,reject:e}}const ku=new Map;function Ig({fn:t,id:e,shouldSplitBatch:r,wait:n=0,sort:s}){const i=async()=>{const l=c();o();const d=l.map(({args:h})=>h);d.length!==0&&t(d).then(h=>{s&&Array.isArray(h)&&h.sort(s);for(let f=0;f<l.length;f++){const{resolve:m}=l[f];m==null||m([h[f],h])}}).catch(h=>{for(let f=0;f<l.length;f++){const{reject:m}=l[f];m==null||m(h)}})},o=()=>ku.delete(e),a=()=>c().map(({args:l})=>l),c=()=>ku.get(e)||[],u=l=>ku.set(e,[...c(),l]);return{flush:o,async schedule(l){const{promise:d,resolve:h,reject:f}=Kd();return(r==null?void 0:r([...a(),l]))&&i(),c().length>0?(u({args:l,resolve:h,reject:f}),d):(u({args:l,resolve:h,reject:f}),setTimeout(i,n),d)}}}async function da(t,e){var U,N,F,Z;const{account:r=t.account,authorizationList:n,batch:s=!!((U=t.batch)!=null&&U.multicall),blockNumber:i,blockTag:o=t.experimental_blockTag??"latest",accessList:a,blobs:c,blockOverrides:u,code:l,data:d,factory:h,factoryData:f,gas:m,gasPrice:g,maxFeePerBlobGas:v,maxFeePerGas:S,maxPriorityFeePerGas:_,nonce:E,to:x,value:O,stateOverride:P,...$}=e,z=r?We(r):void 0;if(l&&(h||f))throw new D("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(l&&x)throw new D("Cannot provide both `code` & `to` as parameters.");const C=l&&d,Y=h&&f&&x&&d,W=C||Y,K=C?kA({code:l,data:d}):Y?_A({data:d,factory:h,factoryData:f,to:x}):d;try{Ws(e);const H=(typeof i=="bigint"?X(i):void 0)||o,T=u?Sg(u):void 0,L=Bd(P),G=(Z=(F=(N=t.chain)==null?void 0:N.formatters)==null?void 0:F.transactionRequest)==null?void 0:Z.format,R=(G||Hi)({...Mc($,{format:G}),from:z==null?void 0:z.address,accessList:a,authorizationList:n,blobs:c,data:K,gas:m,gasPrice:g,maxFeePerBlobGas:v,maxFeePerGas:S,maxPriorityFeePerGas:_,nonce:E,to:W?void 0:x,value:O});if(s&&AA({request:R})&&!L&&!T)try{return await xA(t,{...R,blockNumber:i,blockTag:o})}catch(se){if(!(se instanceof _g)&&!(se instanceof Cf))throw se}const j=(()=>{const se=[R,H];return L&&T?[...se,L,T]:L?[...se,L]:T?[...se,{},T]:se})(),J=await t.request({method:"eth_call",params:j});return J==="0x"?{data:void 0}:{data:J}}catch(te){const H=TA(te),{offchainLookup:T,offchainLookupSignature:L}=await Promise.resolve().then(()=>require("./ccip-Dz1z3fd5.cjs"));if(t.ccipRead!==!1&&(H==null?void 0:H.slice(0,10))===L&&x)return{data:await T(t,{data:H,to:x})};throw W&&(H==null?void 0:H.slice(0,10))==="0x101bb98d"?new fS({factory:h}):Tg(te,{...e,account:z,chain:t.chain})}}function AA({request:t}){const{data:e,to:r,...n}=t;return!(!e||e.startsWith(bA)||!r||Object.values(n).filter(s=>typeof s<"u").length>0)}async function xA(t,e){var g;const{batchSize:r=1024,wait:n=0}=typeof((g=t.batch)==null?void 0:g.multicall)=="object"?t.batch.multicall:{},{blockNumber:s,blockTag:i=t.experimental_blockTag??"latest",data:o,multicallAddress:a,to:c}=e;let u=a;if(!u){if(!t.chain)throw new _g;u=zi({blockNumber:s,chain:t.chain,contract:"multicall3"})}const d=(typeof s=="bigint"?X(s):void 0)||i,{schedule:h}=Ig({id:`${t.uid}.${d}`,wait:n,shouldSplitBatch(v){return v.reduce((_,{data:E})=>_+(E.length-2),0)>r*2},fn:async v=>{const S=v.map(x=>({allowFailure:!0,callData:x.data,target:x.to})),_=fr({abi:Of,args:[S],functionName:"aggregate3"}),E=await t.request({method:"eth_call",params:[{data:_,to:u},d]});return Ks({abi:Of,args:[S],functionName:"aggregate3",data:E||"0x"})}}),[{returnData:f,success:m}]=await h({data:o,to:c});if(!m)throw new Nc({data:f});return f==="0x"?{data:void 0}:{data:f}}function kA(t){const{code:e,data:r}=t;return Dc({abi:o0(["constructor(bytes, bytes)"]),bytecode:kg,args:[e,r]})}function _A(t){const{data:e,factory:r,factoryData:n,to:s}=t;return Dc({abi:o0(["constructor(address, bytes, address, bytes)"]),bytecode:wA,args:[s,e,r,n]})}function TA(t){var r;if(!(t instanceof D))return;const e=t.walk();return typeof(e==null?void 0:e.data)=="object"?(r=e.data)==null?void 0:r.data:e.data}async function Xr(t,e){const{abi:r,address:n,args:s,functionName:i,...o}=e,a=fr({abi:r,args:s,functionName:i});try{const{data:c}=await ae(t,da,"call")({...o,data:a,to:n});return Ks({abi:r,args:s,functionName:i,data:c||"0x"})}catch(c){throw Ns(c,{abi:r,address:n,args:s,docsPath:"/docs/contract/readContract",functionName:i})}}async function Pg(t,e){const{abi:r,address:n,args:s,dataSuffix:i,functionName:o,...a}=e,c=a.account?We(a.account):t.account,u=fr({abi:r,args:s,functionName:o});try{const{data:l}=await ae(t,da,"call")({batch:!1,data:`${u}${i?i.replace("0x",""):""}`,to:n,...a,account:c}),d=Ks({abi:r,args:s,functionName:o,data:l||"0x"}),h=r.filter(f=>"name"in f&&f.name===e.functionName);return{result:d,request:{abi:h,address:n,args:s,dataSuffix:i,functionName:o,...a,account:c}}}catch(l){throw Ns(l,{abi:r,address:n,args:s,docsPath:"/docs/contract/simulateContract",functionName:o,sender:c==null?void 0:c.address})}}const _u=new Map,kp=new Map;let IA=0;function An(t,e,r){const n=++IA,s=()=>_u.get(t)||[],i=()=>{const l=s();_u.set(t,l.filter(d=>d.id!==n))},o=()=>{const l=s();if(!l.some(h=>h.id===n))return;const d=kp.get(t);if(l.length===1&&d){const h=d();h instanceof Promise&&h.catch(()=>{})}i()},a=s();if(_u.set(t,[...a,{id:n,fns:e}]),a&&a.length>0)return o;const c={};for(const l in e)c[l]=(...d)=>{var f,m;const h=s();if(h.length!==0)for(const g of h)(m=(f=g.fns)[l])==null||m.call(f,...d)};const u=r(c);return typeof u=="function"&&kp.set(t,u),o}async function $f(t){return new Promise(e=>setTimeout(e,t))}function Vi(t,{emitOnBegin:e,initialWaitTime:r,interval:n}){let s=!0;const i=()=>s=!1;return(async()=>{let a;e&&(a=await t({unpoll:i}));const c=await(r==null?void 0:r(a))??n;await $f(c);const u=async()=>{s&&(await t({unpoll:i}),await $f(n),u())};u()})(),i}const PA=new Map,OA=new Map;function BA(t){const e=(s,i)=>({clear:()=>i.delete(s),get:()=>i.get(s),set:o=>i.set(s,o)}),r=e(t,PA),n=e(t,OA);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function CA(t,{cacheKey:e,cacheTime:r=Number.POSITIVE_INFINITY}){const n=BA(e),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=t(),n.promise.set(i));try{const o=await i;return n.response.set({created:new Date,data:o}),o}finally{n.promise.clear()}}const $A=t=>`blockNumber.${t}`;async function ha(t,{cacheTime:e=t.cacheTime}={}){const r=await CA(()=>t.request({method:"eth_blockNumber"}),{cacheKey:$A(t.uid),cacheTime:e});return BigInt(r)}async function zc(t,{filter:e}){const r="strict"in e&&e.strict,n=await e.request({method:"eth_getFilterChanges",params:[e.id]});if(typeof n[0]=="string")return n;const s=n.map(i=>Sn(i));return!("abi"in e)||!e.abi?s:Dd({abi:e.abi,logs:s,strict:r})}async function Vc(t,{filter:e}){return e.request({method:"eth_uninstallFilter",params:[e.id]})}function Og(t,e){const{abi:r,address:n,args:s,batch:i=!0,eventName:o,fromBlock:a,onError:c,onLogs:u,poll:l,pollingInterval:d=t.pollingInterval,strict:h}=e;return(typeof l<"u"?l:typeof a=="bigint"?!0:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")))?(()=>{const v=h??!1,S=Je(["watchContractEvent",n,s,i,t.uid,o,d,v,a]);return An(S,{onLogs:u,onError:c},_=>{let E;a!==void 0&&(E=a-1n);let x,O=!1;const P=Vi(async()=>{var $;if(!O){try{x=await ae(t,_d,"createContractEventFilter")({abi:r,address:n,args:s,eventName:o,strict:v,fromBlock:a})}catch{}O=!0;return}try{let z;if(x)z=await ae(t,zc,"getFilterChanges")({filter:x});else{const C=await ae(t,ha,"getBlockNumber")({});E&&E<C?z=await ae(t,Vd,"getContractEvents")({abi:r,address:n,args:s,eventName:o,fromBlock:E+1n,toBlock:C,strict:v}):z=[],E=C}if(z.length===0)return;if(i)_.onLogs(z);else for(const C of z)_.onLogs([C])}catch(z){x&&z instanceof Rs&&(O=!1),($=_.onError)==null||$.call(_,z)}},{emitOnBegin:!0,interval:d});return async()=>{x&&await ae(t,Vc,"uninstallFilter")({filter:x}),P()}})})():(()=>{const v=h??!1,S=Je(["watchContractEvent",n,s,i,t.uid,o,d,v]);let _=!0,E=()=>_=!1;return An(S,{onLogs:u,onError:c},x=>((async()=>{try{const O=(()=>{if(t.transport.type==="fallback"){const z=t.transport.transports.find(C=>C.config.type==="webSocket"||C.config.type==="ipc");return z?z.value:t.transport}return t.transport})(),P=o?aa({abi:r,eventName:o,args:s}):[],{unsubscribe:$}=await O.subscribe({params:["logs",{address:n,topics:P}],onData(z){var Y;if(!_)return;const C=z.result;try{const{eventName:W,args:K}=Hd({abi:r,data:C.data,topics:C.topics,strict:h}),U=Sn(C,{args:K,eventName:W});x.onLogs([U])}catch(W){let K,U;if(W instanceof xo||W instanceof Tc){if(h)return;K=W.abiItem.name,U=(Y=W.abiItem.inputs)==null?void 0:Y.some(F=>!("name"in F&&F.name))}const N=Sn(C,{args:U?[]:{},eventName:K});x.onLogs([N])}},onError(z){var C;(C=x.onError)==null||C.call(x,z)}});E=$,_||E()}catch(O){c==null||c(O)}})(),()=>E()))})()}class Zs extends D{constructor({docsPath:e}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
42
- `),{docsPath:e,docsSlug:"account",name:"AccountNotFoundError"})}}class Ya extends D{constructor({docsPath:e,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:e,metaMessages:r,name:"AccountTypeNotSupportedError"})}}function Bg({chain:t,currentChainId:e}){if(!t)throw new SA;if(e!==t.id)throw new EA({chain:t,currentChainId:e})}function Cg(t,{docsPath:e,...r}){const n=(()=>{const s=Uc(t,r);return s instanceof la?t:s})();return new oS(n,{docsPath:e,...r})}async function Zd(t,{serializedTransaction:e}){return t.request({method:"eth_sendRawTransaction",params:[e]},{retryCount:0})}const Tu=new Cc(128);async function qc(t,e){var _,E,x,O;const{account:r=t.account,chain:n=t.chain,accessList:s,authorizationList:i,blobs:o,data:a,gas:c,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:d,maxPriorityFeePerGas:h,nonce:f,type:m,value:g,...v}=e;if(typeof r>"u")throw new Zs({docsPath:"/docs/actions/wallet/sendTransaction"});const S=r?We(r):null;try{Ws(e);const P=await(async()=>{if(e.to)return e.to;if(e.to!==null&&i&&i.length>0)return await J0({authorization:i[0]}).catch(()=>{throw new D("`to` is required. Could not infer from `authorizationList`.")})})();if((S==null?void 0:S.type)==="json-rpc"||S===null){let $;n!==null&&($=await ae(t,Di,"getChainId")({}),Bg({currentChainId:$,chain:n}));const z=(x=(E=(_=t.chain)==null?void 0:_.formatters)==null?void 0:E.transactionRequest)==null?void 0:x.format,Y=(z||Hi)({...Mc(v,{format:z}),accessList:s,authorizationList:i,blobs:o,chainId:$,data:a,from:S==null?void 0:S.address,gas:c,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:d,maxPriorityFeePerGas:h,nonce:f,to:P,type:m,value:g}),W=Tu.get(t.uid),K=W?"wallet_sendTransaction":"eth_sendTransaction";try{return await t.request({method:K,params:[Y]},{retryCount:0})}catch(U){if(W===!1)throw U;const N=U;if(N.name==="InvalidInputRpcError"||N.name==="InvalidParamsRpcError"||N.name==="MethodNotFoundRpcError"||N.name==="MethodNotSupportedRpcError")return await t.request({method:"wallet_sendTransaction",params:[Y]},{retryCount:0}).then(F=>(Tu.set(t.uid,!0),F)).catch(F=>{const Z=F;throw Z.name==="MethodNotFoundRpcError"||Z.name==="MethodNotSupportedRpcError"?(Tu.set(t.uid,!1),N):Z});throw N}}if((S==null?void 0:S.type)==="local"){const $=await ae(t,Lc,"prepareTransactionRequest")({account:S,accessList:s,authorizationList:i,blobs:o,chain:n,data:a,gas:c,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:d,maxPriorityFeePerGas:h,nonce:f,nonceManager:S.nonceManager,parameters:[...hg,"sidecars"],type:m,value:g,...v,to:P}),z=(O=n==null?void 0:n.serializers)==null?void 0:O.transaction,C=await S.signTransaction($,{serializer:z});return await ae(t,Zd,"sendRawTransaction")({serializedTransaction:C})}throw(S==null?void 0:S.type)==="smart"?new Ya({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new Ya({docsPath:"/docs/actions/wallet/sendTransaction",type:S==null?void 0:S.type})}catch(P){throw P instanceof Ya?P:Cg(P,{...e,account:S,chain:e.chain||void 0})}}async function $g(t,e){const{abi:r,account:n=t.account,address:s,args:i,dataSuffix:o,functionName:a,...c}=e;if(typeof n>"u")throw new Zs({docsPath:"/docs/contract/writeContract"});const u=n?We(n):null,l=fr({abi:r,args:i,functionName:a});try{return await ae(t,qc,"sendTransaction")({data:`${l}${o?o.replace("0x",""):""}`,to:s,account:u,...c})}catch(d){throw Ns(d,{abi:r,address:s,args:i,docsPath:"/docs/contract/writeContract",functionName:a,sender:u==null?void 0:u.address})}}function _p({abi:t,address:e,client:r}){const n=r,[s,i]=n?"public"in n&&"wallet"in n?[n.public,n.wallet]:"public"in n?[n.public,void 0]:"wallet"in n?[void 0,n.wallet]:[n,n]:[void 0,void 0],o=s!=null,a=i!=null,c={};let u=!1,l=!1,d=!1;for(const h of t)if(h.type==="function"?h.stateMutability==="view"||h.stateMutability==="pure"?u=!0:l=!0:h.type==="event"&&(d=!0),u&&l&&d)break;return o&&(u&&(c.read=new Proxy({},{get(h,f){return(...m)=>{const{args:g,options:v}=Ia(m);return ae(s,Xr,"readContract")({abi:t,address:e,functionName:f,args:g,...v})}}})),l&&(c.simulate=new Proxy({},{get(h,f){return(...m)=>{const{args:g,options:v}=Ia(m);return ae(s,Pg,"simulateContract")({abi:t,address:e,functionName:f,args:g,...v})}}})),d&&(c.createEventFilter=new Proxy({},{get(h,f){return(...m)=>{const g=t.find(_=>_.type==="event"&&_.name===f),{args:v,options:S}=Iu(m,g);return ae(s,_d,"createContractEventFilter")({abi:t,address:e,eventName:f,args:v,...S})}}}),c.getEvents=new Proxy({},{get(h,f){return(...m)=>{const g=t.find(_=>_.type==="event"&&_.name===f),{args:v,options:S}=Iu(m,g);return ae(s,Vd,"getContractEvents")({abi:t,address:e,eventName:f,args:v,...S})}}}),c.watchEvent=new Proxy({},{get(h,f){return(...m)=>{const g=t.find(_=>_.type==="event"&&_.name===f),{args:v,options:S}=Iu(m,g);return ae(s,Og,"watchContractEvent")({abi:t,address:e,eventName:f,args:v,...S})}}}))),a&&l&&(c.write=new Proxy({},{get(h,f){return(...m)=>{const{args:g,options:v}=Ia(m);return ae(i,$g,"writeContract")({abi:t,address:e,functionName:f,args:g,...v})}}})),(o||a)&&l&&(c.estimateGas=new Proxy({},{get(h,f){return(...m)=>{const{args:g,options:v}=Ia(m);return ae(s??i,yg,"estimateContractGas")({abi:t,address:e,functionName:f,args:g,...v,account:v.account??i.account})}}})),c.address=e,c.abi=t,c}function Ia(t){const e=t.length&&Array.isArray(t[0]),r=e?t[0]:[],n=(e?t[1]:t[0])??{};return{args:r,options:n}}function Iu(t,e){let r=!1;Array.isArray(t[0])?r=!0:t.length===1?r=e.inputs.some(i=>i.indexed):t.length===2&&(r=!0);const n=r?t[0]:void 0,s=(r?t[1]:t[0])??{};return{args:n,options:s}}class RA extends D{constructor(e){super(`Call bundle failed with status: ${e.statusCode}`,{name:"BundleFailedError"}),Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=e}}function hc(t,{delay:e=100,retryCount:r=2,shouldRetry:n=()=>!0}={}){return new Promise((s,i)=>{const o=async({count:a=0}={})=>{const c=async({error:u})=>{const l=typeof e=="function"?e({count:a,error:u}):e;l&&await $f(l),o({count:a+1})};try{const u=await t();s(u)}catch(u){if(a<r&&await n({count:a,error:u}))return c({error:u});i(u)}};o()})}const Rg={"0x0":"reverted","0x1":"success"};function Ng(t){const e={...t,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,contractAddress:t.contractAddress?t.contractAddress:null,cumulativeGasUsed:t.cumulativeGasUsed?BigInt(t.cumulativeGasUsed):null,effectiveGasPrice:t.effectiveGasPrice?BigInt(t.effectiveGasPrice):null,gasUsed:t.gasUsed?BigInt(t.gasUsed):null,logs:t.logs?t.logs.map(r=>Sn(r)):null,to:t.to?t.to:null,transactionIndex:t.transactionIndex?cr(t.transactionIndex):null,status:t.status?Rg[t.status]:null,type:t.type?eg[t.type]||t.type:null};return t.blobGasPrice&&(e.blobGasPrice=BigInt(t.blobGasPrice)),t.blobGasUsed&&(e.blobGasUsed=BigInt(t.blobGasUsed)),e}const NA=Od("transactionReceipt",Ng),Ug="0x5792579257925792579257925792579257925792579257925792579257925792",Mg=X(0,{size:32});async function UA(t,e){const{account:r=t.account,capabilities:n,chain:s=t.chain,experimental_fallback:i,experimental_fallbackDelay:o=32,forceAtomic:a=!1,id:c,version:u="2.0.0"}=e,l=r?We(r):null,d=e.calls.map(h=>{const f=h,m=f.abi?fr({abi:f.abi,functionName:f.functionName,args:f.args}):f.data;return{data:f.dataSuffix&&m?Wt([m,f.dataSuffix]):m,to:f.to,value:f.value?X(f.value):void 0}});try{const h=await t.request({method:"wallet_sendCalls",params:[{atomicRequired:a,calls:d,capabilities:n,chainId:X(s.id),from:l==null?void 0:l.address,id:c,version:u}]},{retryCount:0});return typeof h=="string"?{id:h}:h}catch(h){const f=h;if(i&&(f.name==="MethodNotFoundRpcError"||f.name==="MethodNotSupportedRpcError"||f.name==="UnknownRpcError"||f.details.toLowerCase().includes("does not exist / is not available")||f.details.toLowerCase().includes("missing or invalid. request()")||f.details.toLowerCase().includes("did not match any variant of untagged enum")||f.details.toLowerCase().includes("account upgraded to unsupported contract")||f.details.toLowerCase().includes("eip-7702 not supported")||f.details.toLowerCase().includes("unsupported wc_ method")||f.details.toLowerCase().includes("feature toggled misconfigured"))){if(n&&Object.values(n).some(_=>!_.optional)){const _="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new Pi(new D(_,{details:_}))}if(a&&d.length>1){const S="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new Oi(new D(S,{details:S}))}const m=[];for(const S of d){const _=qc(t,{account:l,chain:s,data:S.data,to:S.to,value:S.value?ot(S.value):void 0});m.push(_),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 v=g.map(S=>S.status==="fulfilled"?S.value:Mg);return{id:Wt([...v,X(s.id,{size:32}),Ug])}}throw Cg(h,{...e,account:l,chain:e.chain})}}async function Fg(t,e){async function r(l){if(l.endsWith(Ug.slice(2))){const h=ar(dc(l,-64,-32)),f=dc(l,0,-64).slice(2).match(/.{1,64}/g),m=await Promise.all(f.map(v=>Mg.slice(2)!==v?t.request({method:"eth_getTransactionReceipt",params:[`0x${v}`]},{dedupe:!0}):void 0)),g=m.some(v=>v===null)?100:m.every(v=>(v==null?void 0:v.status)==="0x1")?200:m.every(v=>(v==null?void 0:v.status)==="0x0")?500:600;return{atomic:!1,chainId:cr(h),receipts:m.filter(Boolean),status:g,version:"2.0.0"}}return t.request({method:"wallet_getCallsStatus",params:[l]})}const{atomic:n=!1,chainId:s,receipts:i,version:o="2.0.0",...a}=await r(e.id),[c,u]=(()=>{const l=a.status;return l>=100&&l<200?["pending",l]:l>=200&&l<300?["success",l]:l>=300&&l<700?["failure",l]:l==="CONFIRMED"?["success",200]:l==="PENDING"?["pending",100]:[void 0,l]})();return{...a,atomic:n,chainId:s?cr(s):void 0,receipts:(i==null?void 0:i.map(l=>({...l,blockNumber:ot(l.blockNumber),gasUsed:ot(l.gasUsed),status:Rg[l.status]})))??[],statusCode:u,status:c,version:o}}async function MA(t,e){const{id:r,pollingInterval:n=t.pollingInterval,status:s=({statusCode:g})=>g===200||g>=300,retryCount:i=4,retryDelay:o=({count:g})=>~~(1<<g)*200,timeout:a=6e4,throwOnFailure:c=!1}=e,u=Je(["waitForCallsStatus",t.uid,r]),{promise:l,resolve:d,reject:h}=Kd();let f;const m=An(u,{resolve:d,reject:h},g=>{const v=Vi(async()=>{const S=_=>{clearTimeout(f),v(),_(),m()};try{const _=await hc(async()=>{const E=await Fg(t,{id:r});if(c&&E.status==="failure")throw new RA(E);return E},{retryCount:i,delay:o});if(!s(_))return;S(()=>g.resolve(_))}catch(_){S(()=>g.reject(_))}},{interval:n,emitOnBegin:!0});return v});return f=a?setTimeout(()=>{m(),clearTimeout(f),h(new FA({id:r}))},a):void 0,await l}class FA extends D{constructor({id:e}){super(`Timed out while waiting for call bundle with id "${e}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}const Rf=256;let Pa=Rf,Oa;function jg(t=11){if(!Oa||Pa+t>Rf*2){Oa="",Pa=0;for(let e=0;e<Rf;e++)Oa+=(256+Math.random()*256|0).toString(16).substring(1)}return Oa.substring(Pa,Pa+++t)}function Lg(t){const{batch:e,chain:r,ccipRead:n,key:s="base",name:i="Base Client",type:o="base"}=t,a=t.experimental_blockTag??(typeof(r==null?void 0:r.experimental_preconfirmationTime)=="number"?"pending":void 0),c=(r==null?void 0:r.blockTime)??12e3,u=Math.min(Math.max(Math.floor(c/2),500),4e3),l=t.pollingInterval??u,d=t.cacheTime??l,h=t.account?We(t.account):void 0,{config:f,request:m,value:g}=t.transport({chain:r,pollingInterval:l}),v={...f,...g},S={account:h,batch:e,cacheTime:d,ccipRead:n,chain:r,key:s,name:i,pollingInterval:l,request:m,transport:v,type:o,uid:jg(),...a?{experimental_blockTag:a}:{}};function _(E){return x=>{const O=x(E);for(const $ in S)delete O[$];const P={...E,...O};return Object.assign(P,{extend:_(P)})}}return Object.assign(S,{extend:_(S)})}const Ba=new Cc(8192);function jA(t,{enabled:e=!0,id:r}){if(!e||!r)return t();if(Ba.get(r))return Ba.get(r);const n=t().finally(()=>Ba.delete(r));return Ba.set(r,n),n}function LA(t,e={}){return async(r,n={})=>{var d;const{dedupe:s=!1,methods:i,retryDelay:o=150,retryCount:a=3,uid:c}={...e,...n},{method:u}=r;if((d=i==null?void 0:i.exclude)!=null&&d.includes(u))throw new ms(new Error("method not supported"),{method:u});if(i!=null&&i.include&&!i.include.includes(u))throw new ms(new Error("method not supported"),{method:u});const l=s?Ti(`${c}.${Je(r)}`):void 0;return jA(()=>hc(async()=>{try{return await t(r)}catch(h){const f=h;switch(f.code){case To.code:throw new To(f);case Io.code:throw new Io(f);case Po.code:throw new Po(f,{method:r.method});case Oo.code:throw new Oo(f);case $s.code:throw new $s(f);case Rs.code:throw new Rs(f);case Bo.code:throw new Bo(f);case Co.code:throw new Co(f);case $o.code:throw new $o(f);case ms.code:throw new ms(f,{method:r.method});case Ii.code:throw new Ii(f);case Ro.code:throw new Ro(f);case bi.code:throw new bi(f);case No.code:throw new No(f);case Uo.code:throw new Uo(f);case Mo.code:throw new Mo(f);case Fo.code:throw new Fo(f);case jo.code:throw new jo(f);case Pi.code:throw new Pi(f);case Lo.code:throw new Lo(f);case Ho.code:throw new Ho(f);case Do.code:throw new Do(f);case zo.code:throw new zo(f);case Vo.code:throw new Vo(f);case Oi.code:throw new Oi(f);case 5e3:throw new bi(f);default:throw h instanceof D?h:new hS(f)}}},{delay:({count:h,error:f})=>{var m;if(f&&f instanceof gi){const g=(m=f==null?void 0:f.headers)==null?void 0:m.get("Retry-After");if(g!=null&&g.match(/\d/))return Number.parseInt(g)*1e3}return~~(1<<h)*o},retryCount:a,shouldRetry:({error:h})=>HA(h)}),{enabled:s,id:l})}}function HA(t){return"code"in t&&typeof t.code=="number"?t.code===-1||t.code===Ii.code||t.code===$s.code:t instanceof gi&&t.status?t.status===403||t.status===408||t.status===413||t.status===429||t.status===500||t.status===502||t.status===503||t.status===504:!0}function Hg({key:t,methods:e,name:r,request:n,retryCount:s=3,retryDelay:i=150,timeout:o,type:a},c){const u=jg();return{config:{key:t,methods:e,name:r,request:n,retryCount:s,retryDelay:i,timeout:o,type:a},request:LA(n,{methods:e,retryCount:s,retryDelay:i,uid:u}),value:c}}function Tp(t,e={}){const{key:r="custom",methods:n,name:s="Custom Provider",retryDelay:i}=e;return({retryCount:o})=>Hg({key:r,methods:n,name:s,request:t.request.bind(t),retryCount:e.retryCount??o,retryDelay:i,type:"custom"})}class DA extends D{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 zA(t,{errorInstance:e=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 t({signal:(a==null?void 0:a.signal)||null}))}catch(a){(a==null?void 0:a.name)==="AbortError"&&i(e),i(a)}finally{clearTimeout(o)}})()})}function VA(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const Ip=VA();function qA(t,e={}){return{async request(r){var d;const{body:n,onRequest:s=e.onRequest,onResponse:i=e.onResponse,timeout:o=e.timeout??1e4}=r,a={...e.fetchOptions??{},...r.fetchOptions??{}},{headers:c,method:u,signal:l}=a;try{const h=await zA(async({signal:m})=>{const g={...a,body:Array.isArray(n)?Je(n.map(E=>({jsonrpc:"2.0",id:E.id??Ip.take(),...E}))):Je({jsonrpc:"2.0",id:n.id??Ip.take(),...n}),headers:{"Content-Type":"application/json",...c},method:u||"POST",signal:l||(o>0?m:null)},v=new Request(t,g),S=await(s==null?void 0:s(v,g))??{...g,url:t};return await fetch(S.url??t,S)},{errorInstance:new fp({body:n,url:t}),timeout:o,signal:!0});i&&await i(h);let f;if((d=h.headers.get("Content-Type"))!=null&&d.startsWith("application/json"))f=await h.json();else{f=await h.text();try{f=JSON.parse(f||"{}")}catch(m){if(h.ok)throw m;f={error:f}}}if(!h.ok)throw new gi({body:n,details:Je(f.error)||h.statusText,headers:h.headers,status:h.status,url:t});return f}catch(h){throw h instanceof gi||h instanceof fp?h:new gi({body:n,cause:h,url:t})}}}}function Dg(t,e={}){const{batch:r,fetchOptions:n,key:s="http",methods:i,name:o="HTTP JSON-RPC",onFetchRequest:a,onFetchResponse:c,retryDelay:u,raw:l}=e;return({chain:d,retryCount:h,timeout:f})=>{const{batchSize:m=1e3,wait:g=0}=typeof r=="object"?r:{},v=e.retryCount??h,S=f??e.timeout??1e4,_=d==null?void 0:d.rpcUrls.default.http[0];if(!_)throw new DA;const E=qA(_,{fetchOptions:n,onRequest:a,onResponse:c,timeout:S});return Hg({key:s,methods:i,name:o,async request({method:x,params:O}){const P={method:x,params:O},{schedule:$}=Ig({id:_,wait:g,shouldSplitBatch(W){return W.length>m},fn:W=>E.request({body:W}),sort:(W,K)=>W.id-K.id}),z=async W=>r?$(W):[await E.request({body:W})],[{error:C,result:Y}]=await z(P);if(l)return{error:C,result:Y};if(C)throw new Pd({body:P,error:C,url:_});return Y},retryCount:v,retryDelay:u,timeout:S,type:"http"},{fetchOptions:n,url:_})}}function Xd(t){var r,n,s,i,o,a;if(!(t instanceof D))return!1;const e=t.walk(c=>c instanceof wf);return e instanceof wf?((r=e.data)==null?void 0:r.errorName)==="HttpError"||((n=e.data)==null?void 0:n.errorName)==="ResolverError"||((s=e.data)==null?void 0:s.errorName)==="ResolverNotContract"||((i=e.data)==null?void 0:i.errorName)==="ResolverNotFound"||((o=e.data)==null?void 0:o.errorName)==="ReverseAddressMismatch"||((a=e.data)==null?void 0:a.errorName)==="UnsupportedResolverProfile":!1}function GA(t){const{abi:e,data:r}=t,n=Cs(r,0,4),s=e.find(i=>i.type==="function"&&n===oa(kr(i)));if(!s)throw new U2(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:s.name,args:"inputs"in s&&s.inputs&&s.inputs.length>0?ca(s.inputs,Cs(r,4)):void 0}}const Pu="/docs/contract/encodeErrorResult";function Pp(t){const{abi:e,errorName:r,args:n}=t;let s=e[0];if(r){const c=Gs({abi:e,args:n,name:r});if(!c)throw new Yh(r,{docsPath:Pu});s=c}if(s.type!=="error")throw new Yh(void 0,{docsPath:Pu});const i=kr(s),o=oa(i);let a="0x";if(n&&n.length>0){if(!s.inputs)throw new R2(s.name,{docsPath:Pu});a=Pn(s.inputs,n)}return Or([o,a])}const Ou="/docs/contract/encodeFunctionResult";function WA(t){const{abi:e,functionName:r,result:n}=t;let s=e[0];if(r){const o=Gs({abi:e,name:r});if(!o)throw new _i(r,{docsPath:Ou});s=o}if(s.type!=="function")throw new _i(void 0,{docsPath:Ou});if(!s.outputs)throw new d0(s.name,{docsPath:Ou});const i=(()=>{if(s.outputs.length===0)return[];if(s.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new h0(n)})();return Pn(s.outputs,i)}const pa="x-batch-gateway:true";async function zg(t){const{data:e,ccipRequest:r}=t,{args:[n]}=GA({abi:Bf,data:e}),s=[],i=[];return await Promise.all(n.map(async(o,a)=>{try{i[a]=o.urls.includes(pa)?await zg({data:o.data,ccipRequest:r}):await r(o),s[a]=!1}catch(c){s[a]=!0,i[a]=KA(c)}})),WA({abi:Bf,functionName:"query",result:[s,i]})}function KA(t){return t.name==="HttpRequestError"&&t.status?Pp({abi:Bf,errorName:"HttpError",args:[t.status,t.shortMessage]}):Pp({abi:[H0],errorName:"Error",args:["shortMessage"in t?t.shortMessage:t.message]})}function Vg(t){if(t.length!==66||t.indexOf("[")!==0||t.indexOf("]")!==65)return null;const e=`0x${t.slice(1,65)}`;return _r(e)?e:null}function Nf(t){let e=new Uint8Array(32).fill(0);if(!t)return Qe(e);const r=t.split(".");for(let n=r.length-1;n>=0;n-=1){const s=Vg(r[n]),i=s?Li(s):lt(ks(r[n]),"bytes");e=lt(Wt([e,i]),"bytes")}return Qe(e)}function ZA(t){return`[${t.slice(2)}]`}function XA(t){const e=new Uint8Array(32).fill(0);return t?Vg(t)||lt(ks(t)):Qe(e)}function Yd(t){const e=t.replace(/^\.|\.$/gm,"");if(e.length===0)return new Uint8Array(1);const r=new Uint8Array(ks(e).byteLength+2);let n=0;const s=e.split(".");for(let i=0;i<s.length;i++){let o=ks(s[i]);o.byteLength>255&&(o=ks(ZA(XA(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 YA(t,e){const{blockNumber:r,blockTag:n,coinType:s,name:i,gatewayUrls:o,strict:a}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return zi({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c==null?void 0:c.ensTlds;if(l&&!l.some(h=>i.endsWith(h)))return null;const d=s!=null?[Nf(i),BigInt(s)]:[Nf(i)];try{const h=fr({abi:Ap,functionName:"addr",args:d}),f={address:u,abi:xg,functionName:"resolveWithGateways",args:[Pt(Yd(i)),h,o??[pa]],blockNumber:r,blockTag:n},g=await ae(t,Xr,"readContract")(f);if(g[0]==="0x")return null;const v=Ks({abi:Ap,args:d,functionName:"addr",data:g[0]});return v==="0x"||ar(v)==="0x00"?null:v}catch(h){if(a)throw h;if(Xd(h))return null;throw h}}class JA extends D{constructor({data:e}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(e)}`],name:"EnsAvatarInvalidMetadataError"})}}class Yi extends D{constructor({reason:e}){super(`ENS NFT avatar URI is invalid. ${e}`,{name:"EnsAvatarInvalidNftUriError"})}}class Jd extends D{constructor({uri:e}){super(`Unable to resolve ENS avatar URI "${e}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class QA extends D{constructor({namespace:e}){super(`ENS NFT avatar namespace "${e}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const e6=/(?<protocol>https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,t6=/^(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>\/.*)?$/,r6=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,n6=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function s6(t){try{const e=await fetch(t,{method:"HEAD"});if(e.status===200){const r=e.headers.get("content-type");return r==null?void 0:r.startsWith("image/")}return!1}catch(e){return typeof e=="object"&&typeof e.response<"u"||!globalThis.hasOwnProperty("Image")?!1:new Promise(r=>{const n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=t})}}function Op(t,e){return t?t.endsWith("/")?t.slice(0,-1):t:e}function qg({uri:t,gatewayUrls:e}){const r=r6.test(t);if(r)return{uri:t,isOnChain:!0,isEncoded:r};const n=Op(e==null?void 0:e.ipfs,"https://ipfs.io"),s=Op(e==null?void 0:e.arweave,"https://arweave.net"),i=t.match(e6),{protocol:o,subpath:a,target:c,subtarget:u=""}=(i==null?void 0:i.groups)||{},l=o==="ipns:/"||a==="ipns/",d=o==="ipfs:/"||a==="ipfs/"||t6.test(t);if(t.startsWith("http")&&!l&&!d){let f=t;return e!=null&&e.arweave&&(f=t.replace(/https:\/\/arweave.net/g,e==null?void 0:e.arweave)),{uri:f,isOnChain:!1,isEncoded:!1}}if((l||d)&&c)return{uri:`${n}/${l?"ipns":"ipfs"}/${c}${u}`,isOnChain:!1,isEncoded:!1};if(o==="ar:/"&&c)return{uri:`${s}/${c}${u||""}`,isOnChain:!1,isEncoded:!1};let h=t.replace(n6,"");if(h.startsWith("<svg")&&(h=`data:image/svg+xml;base64,${btoa(h)}`),h.startsWith("data:")||h.startsWith("{"))return{uri:h,isOnChain:!0,isEncoded:!1};throw new Jd({uri:t})}function Gg(t){if(typeof t!="object"||!("image"in t)&&!("image_url"in t)&&!("image_data"in t))throw new JA({data:t});return t.image||t.image_url||t.image_data}async function i6({gatewayUrls:t,uri:e}){try{const r=await fetch(e).then(s=>s.json());return await Qd({gatewayUrls:t,uri:Gg(r)})}catch{throw new Jd({uri:e})}}async function Qd({gatewayUrls:t,uri:e}){const{uri:r,isOnChain:n}=qg({uri:e,gatewayUrls:t});if(n||await s6(r))return r;throw new Jd({uri:e})}function o6(t){let e=t;e.startsWith("did:nft:")&&(e=e.replace("did:nft:","").replace(/_/g,"/"));const[r,n,s]=e.split("/"),[i,o]=r.split(":"),[a,c]=n.split(":");if(!i||i.toLowerCase()!=="eip155")throw new Yi({reason:"Only EIP-155 supported"});if(!o)throw new Yi({reason:"Chain ID not found"});if(!c)throw new Yi({reason:"Contract address not found"});if(!s)throw new Yi({reason:"Token ID not found"});if(!a)throw new Yi({reason:"ERC namespace not found"});return{chainID:Number.parseInt(o),namespace:a.toLowerCase(),contractAddress:c,tokenID:s}}async function a6(t,{nft:e}){if(e.namespace==="erc721")return Xr(t,{address:e.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(e.tokenID)]});if(e.namespace==="erc1155")return Xr(t,{address:e.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(e.tokenID)]});throw new QA({namespace:e.namespace})}async function c6(t,{gatewayUrls:e,record:r}){return/eip155:/i.test(r)?u6(t,{gatewayUrls:e,record:r}):Qd({uri:r,gatewayUrls:e})}async function u6(t,{gatewayUrls:e,record:r}){const n=o6(r),s=await a6(t,{nft:n}),{uri:i,isOnChain:o,isEncoded:a}=qg({uri:s,gatewayUrls:e});if(o&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){const u=a?atob(i.replace("data:application/json;base64,","")):i,l=JSON.parse(u);return Qd({uri:Gg(l),gatewayUrls:e})}let c=n.tokenID;return n.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),i6({gatewayUrls:e,uri:i.replace(/(?:0x)?{id}/,c)})}async function Wg(t,e){const{blockNumber:r,blockTag:n,key:s,name:i,gatewayUrls:o,strict:a}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return zi({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c==null?void 0:c.ensTlds;if(l&&!l.some(d=>i.endsWith(d)))return null;try{const d={address:u,abi:xg,args:[Pt(Yd(i)),fr({abi:Sp,functionName:"text",args:[Nf(i),s]}),o??[pa]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},f=await ae(t,Xr,"readContract")(d);if(f[0]==="0x")return null;const m=Ks({abi:Sp,functionName:"text",data:f[0]});return m===""?null:m}catch(d){if(a)throw d;if(Xd(d))return null;throw d}}async function l6(t,{blockNumber:e,blockTag:r,assetGatewayUrls:n,name:s,gatewayUrls:i,strict:o,universalResolverAddress:a}){const c=await ae(t,Wg,"getEnsText")({blockNumber:e,blockTag:r,key:"avatar",name:s,universalResolverAddress:a,gatewayUrls:i,strict:o});if(!c)return null;try{return await c6(t,{record:c,gatewayUrls:n})}catch{return null}}async function f6(t,e){const{address:r,blockNumber:n,blockTag:s,coinType:i=60n,gatewayUrls:o,strict:a}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return zi({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{const l={address:u,abi:gA,args:[r,i,o??[pa]],functionName:"reverseWithGateways",blockNumber:n,blockTag:s},d=ae(t,Xr,"readContract"),[h]=await d(l);return h||null}catch(l){if(a)throw l;if(Xd(l))return null;throw l}}async function d6(t,e){const{blockNumber:r,blockTag:n,name:s}=e,{chain:i}=t,o=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!i)throw new Error("client chain not configured. universalResolverAddress is required.");return zi({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),a=i==null?void 0:i.ensTlds;if(a&&!a.some(u=>s.endsWith(u)))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 ae(t,Xr,"readContract")({address:o,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[Pt(Yd(s))],blockNumber:r,blockTag:n});return c}async function Kg(t,e){var v,S,_;const{account:r=t.account,blockNumber:n,blockTag:s="latest",blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:d,to:h,value:f,...m}=e,g=r?We(r):void 0;try{Ws(e);const x=(typeof n=="bigint"?X(n):void 0)||s,O=(_=(S=(v=t.chain)==null?void 0:v.formatters)==null?void 0:S.transactionRequest)==null?void 0:_.format,$=(O||Hi)({...Mc(m,{format:O}),from:g==null?void 0:g.address,blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:d,to:h,value:f}),z=await t.request({method:"eth_createAccessList",params:[$,x]});return{accessList:z.accessList,gasUsed:BigInt(z.gasUsed)}}catch(E){throw Tg(E,{...e,account:g,chain:t.chain})}}async function h6(t){const e=$c(t,{method:"eth_newBlockFilter"}),r=await t.request({method:"eth_newBlockFilter"});return{id:r,request:e(r),type:"block"}}async function Zg(t,{address:e,args:r,event:n,events:s,fromBlock:i,strict:o,toBlock:a}={}){const c=s??(n?[n]:void 0),u=$c(t,{method:"eth_newFilter"});let l=[];c&&(l=[c.flatMap(f=>aa({abi:[f],eventName:f.name,args:r}))],n&&(l=l[0]));const d=await t.request({method:"eth_newFilter",params:[{address:e,fromBlock:typeof i=="bigint"?X(i):i,toBlock:typeof a=="bigint"?X(a):a,...l.length?{topics:l}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:i,id:d,request:u(d),strict:!!o,toBlock:a,type:"event"}}async function Xg(t){const e=$c(t,{method:"eth_newPendingTransactionFilter"}),r=await t.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:e(r),type:"transaction"}}async function p6(t){const e=await t.request({method:"eth_blobBaseFee"});return BigInt(e)}async function y6(t,{blockHash:e,blockNumber:r,blockTag:n="latest"}={}){const s=r!==void 0?X(r):void 0;let i;return e?i=await t.request({method:"eth_getBlockTransactionCountByHash",params:[e]},{dedupe:!0}):i=await t.request({method:"eth_getBlockTransactionCountByNumber",params:[s||n]},{dedupe:!!s}),cr(i)}async function Bp(t,{address:e,blockNumber:r,blockTag:n="latest"}){const s=r!==void 0?X(r):void 0,i=await t.request({method:"eth_getCode",params:[e,s||n]},{dedupe:!!s});if(i!=="0x")return i}class m6 extends D{constructor({address:e}){super(`No EIP-712 domain found on contract "${e}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${e}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function g6(t,e){const{address:r,factory:n,factoryData:s}=e;try{const[i,o,a,c,u,l,d]=await ae(t,Xr,"readContract")({abi:b6,address:r,functionName:"eip712Domain",factory:n,factoryData:s});return{domain:{name:o,version:a,chainId:Number(c),verifyingContract:u,salt:l},extensions:d,fields:i}}catch(i){const o=i;throw o.name==="ContractFunctionExecutionError"&&o.cause.name==="ContractFunctionZeroDataError"?new m6({address:r}):o}}const b6=[{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 w6(t){var e;return{baseFeePerGas:t.baseFeePerGas.map(r=>BigInt(r)),gasUsedRatio:t.gasUsedRatio,oldestBlock:BigInt(t.oldestBlock),reward:(e=t.reward)==null?void 0:e.map(r=>r.map(n=>BigInt(n)))}}async function v6(t,{blockCount:e,blockNumber:r,blockTag:n="latest",rewardPercentiles:s}){const i=typeof r=="bigint"?X(r):void 0,o=await t.request({method:"eth_feeHistory",params:[X(e),i||n,s]},{dedupe:!!i});return w6(o)}async function E6(t,{filter:e}){const r=e.strict??!1,s=(await e.request({method:"eth_getFilterLogs",params:[e.id]})).map(i=>Sn(i));return e.abi?Dd({abi:e.abi,logs:s,strict:r}):s}function dt(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}class S6 extends D{constructor({domain:e}){super(`Invalid domain "${Je(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class A6 extends D{constructor({primaryType:e,types:r}){super(`Invalid primary type \`${e}\` must be one of \`${JSON.stringify(Object.keys(r))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class x6 extends D{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function k6(t){const{domain:e={},message:r,primaryType:n}=t,s={EIP712Domain:rb({domain:e}),...t.types};tb({domain:e,message:r,primaryType:n,types:s});const i=["0x1901"];return e&&i.push(_6({domain:e,types:s})),n!=="EIP712Domain"&&i.push(Yg({data:r,primaryType:n,types:s})),lt(Wt(i))}function _6({domain:t,types:e}){return Yg({data:t,primaryType:"EIP712Domain",types:e})}function Yg({data:t,primaryType:e,types:r}){const n=Jg({data:t,primaryType:e,types:r});return lt(n)}function Jg({data:t,primaryType:e,types:r}){const n=[{type:"bytes32"}],s=[T6({primaryType:e,types:r})];for(const i of r[e]){const[o,a]=eb({types:r,name:i.name,type:i.type,value:t[i.name]});n.push(o),s.push(a)}return Pn(n,s)}function T6({primaryType:t,types:e}){const r=Pt(I6({primaryType:t,types:e}));return lt(r)}function I6({primaryType:t,types:e}){let r="";const n=Qg({primaryType:t,types:e});n.delete(t);const s=[t,...Array.from(n).sort()];for(const i of s)r+=`${i}(${e[i].map(({name:o,type:a})=>`${a} ${o}`).join(",")})`;return r}function Qg({primaryType:t,types:e},r=new Set){const n=t.match(/^\w*/u),s=n==null?void 0:n[0];if(r.has(s)||e[s]===void 0)return r;r.add(s);for(const i of e[s])Qg({primaryType:i.type,types:e},r);return r}function eb({types:t,name:e,type:r,value:n}){if(t[r]!==void 0)return[{type:"bytes32"},lt(Jg({data:n,primaryType:r,types:t}))];if(r==="bytes")return n=`0x${(n.length%2?"0":"")+n.slice(2)}`,[{type:"bytes32"},lt(n)];if(r==="string")return[{type:"bytes32"},lt(Pt(n))];if(r.lastIndexOf("]")===r.length-1){const s=r.slice(0,r.lastIndexOf("[")),i=n.map(o=>eb({name:e,type:s,types:t,value:o}));return[{type:"bytes32"},lt(Pn(i.map(([o])=>o),i.map(([,o])=>o)))]}return[{type:r},n]}function P6(t){const{domain:e,message:r,primaryType:n,types:s}=t,i=(c,u)=>{const l={...u};for(const d of c){const{name:h,type:f}=d;f==="address"&&(l[h]=l[h].toLowerCase())}return l},o=s.EIP712Domain?e?i(s.EIP712Domain,e):{}:{},a=(()=>{if(n!=="EIP712Domain")return i(s[n],r)})();return Je({domain:o,message:a,primaryType:n,types:s})}function tb(t){const{domain:e,message:r,primaryType:n,types:s}=t,i=(o,a)=>{for(const c of o){const{name:u,type:l}=c,d=a[u],h=l.match(j0);if(h&&(typeof d=="number"||typeof d=="bigint")){const[g,v,S]=h;X(d,{signed:v==="int",size:Number.parseInt(S)/8})}if(l==="address"&&typeof d=="string"&&!it(d))throw new Bt({address:d});const f=l.match(TE);if(f){const[g,v]=f;if(v&&Le(d)!==Number.parseInt(v))throw new F2({expectedSize:Number.parseInt(v),givenSize:Le(d)})}const m=s[l];m&&(O6(l),i(m,d))}};if(s.EIP712Domain&&e){if(typeof e!="object")throw new S6({domain:e});i(s.EIP712Domain,e)}if(n!=="EIP712Domain")if(s[n])i(s[n],r);else throw new A6({primaryType:n,types:s})}function rb({domain:t}){return[typeof(t==null?void 0:t.name)=="string"&&{name:"name",type:"string"},(t==null?void 0:t.version)&&{name:"version",type:"string"},(typeof(t==null?void 0:t.chainId)=="number"||typeof(t==null?void 0:t.chainId)=="bigint")&&{name:"chainId",type:"uint256"},(t==null?void 0:t.verifyingContract)&&{name:"verifyingContract",type:"address"},(t==null?void 0:t.salt)&&{name:"salt",type:"bytes32"}].filter(Boolean)}function O6(t){if(t==="address"||t==="bool"||t==="string"||t.startsWith("bytes")||t.startsWith("uint")||t.startsWith("int"))throw new x6({type:t})}function B6(t){const{authorizationList:e}=t;if(e)for(const r of e){const{chainId:n}=r,s=r.address;if(!it(s))throw new Bt({address:s});if(n<0)throw new Hc({chainId:n})}eh(t)}function C6(t){const{blobVersionedHashes:e}=t;if(e){if(e.length===0)throw new lg;for(const r of e){const n=Le(r),s=cr(Cs(r,0,1));if(n!==32)throw new zS({hash:r,size:n});if(s!==ug)throw new VS({hash:r,version:s})}}eh(t)}function eh(t){const{chainId:e,maxPriorityFeePerGas:r,maxFeePerGas:n,to:s}=t;if(e<=0)throw new Hc({chainId:e});if(s&&!it(s))throw new Bt({address:s});if(n&&n>Fc)throw new Us({maxFeePerGas:n});if(r&&n&&r>n)throw new qo({maxFeePerGas:n,maxPriorityFeePerGas:r})}function $6(t){const{chainId:e,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=t;if(e<=0)throw new Hc({chainId:e});if(i&&!it(i))throw new Bt({address:i});if(r||s)throw new D("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Fc)throw new Us({maxFeePerGas:n})}function R6(t){const{chainId:e,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=t;if(i&&!it(i))throw new Bt({address:i});if(typeof e<"u"&&e<=0)throw new Hc({chainId:e});if(r||s)throw new D("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Fc)throw new Us({maxFeePerGas:n})}function Gc(t){if(!t||t.length===0)return[];const e=[];for(let r=0;r<t.length;r++){const{address:n,storageKeys:s}=t[r];for(let i=0;i<s.length;i++)if(s[i].length-2!==64)throw new iS({storageKey:s[i]});if(!it(n,{strict:!1}))throw new Bt({address:n});e.push([n,s])}return e}function N6(t,e){const r=dg(t);return r==="eip1559"?F6(t,e):r==="eip2930"?j6(t,e):r==="eip4844"?M6(t,e):r==="eip7702"?U6(t,e):L6(t,e)}function U6(t,e){const{authorizationList:r,chainId:n,gas:s,nonce:i,to:o,value:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:l,data:d}=t;B6(t);const h=Gc(l),f=H6(r);return Or(["0x04",ss([X(n),i?X(i):"0x",u?X(u):"0x",c?X(c):"0x",s?X(s):"0x",o??"0x",a?X(a):"0x",d??"0x",h,f,...ya(t,e)])])}function M6(t,e){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:l,data:d}=t;C6(t);let h=t.blobVersionedHashes,f=t.sidecars;if(t.blobs&&(typeof h>"u"||typeof f>"u")){const E=typeof t.blobs[0]=="string"?t.blobs:t.blobs.map(P=>Qe(P)),x=t.kzg,O=Ud({blobs:E,kzg:x});if(typeof h>"u"&&(h=og({commitments:O})),typeof f>"u"){const P=Md({blobs:E,commitments:O,kzg:x});f=fg({blobs:E,commitments:O,proofs:P})}}const m=Gc(l),g=[X(r),s?X(s):"0x",u?X(u):"0x",c?X(c):"0x",n?X(n):"0x",i??"0x",o?X(o):"0x",d??"0x",m,a?X(a):"0x",h??[],...ya(t,e)],v=[],S=[],_=[];if(f)for(let E=0;E<f.length;E++){const{blob:x,commitment:O,proof:P}=f[E];v.push(x),S.push(O),_.push(P)}return Or(["0x03",ss(f?[g,v,S,_]:g)])}function F6(t,e){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:u,data:l}=t;eh(t);const d=Gc(u),h=[X(r),s?X(s):"0x",c?X(c):"0x",a?X(a):"0x",n?X(n):"0x",i??"0x",o?X(o):"0x",l??"0x",d,...ya(t,e)];return Or(["0x02",ss(h)])}function j6(t,e){const{chainId:r,gas:n,data:s,nonce:i,to:o,value:a,accessList:c,gasPrice:u}=t;$6(t);const l=Gc(c),d=[X(r),i?X(i):"0x",u?X(u):"0x",n?X(n):"0x",o??"0x",a?X(a):"0x",s??"0x",l,...ya(t,e)];return Or(["0x01",ss(d)])}function L6(t,e){const{chainId:r=0,gas:n,data:s,nonce:i,to:o,value:a,gasPrice:c}=t;R6(t);let u=[i?X(i):"0x",c?X(c):"0x",n?X(n):"0x",o??"0x",a?X(a):"0x",s??"0x"];if(e){const l=(()=>{if(e.v>=35n)return(e.v-35n)/2n>0?e.v:27n+(e.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+e.v-27n);const f=27n+(e.v===27n?0n:1n);if(e.v!==f)throw new nS({v:e.v});return f})(),d=ar(e.r),h=ar(e.s);u=[...u,X(l),d==="0x00"?"0x":d,h==="0x00"?"0x":h]}else r>0&&(u=[...u,X(r),"0x","0x"]);return ss(u)}function ya(t,e){const r=e??t,{v:n,yParity:s}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof s>"u")return[];const i=ar(r.r),o=ar(r.s);return[typeof s=="number"?s?X(1):"0x":n===0n?"0x":n===1n?X(1):n===27n?"0x":X(1),i==="0x00"?"0x":i,o==="0x00"?"0x":o]}function H6(t){if(!t||t.length===0)return[];const e=[];for(const r of t){const{chainId:n,nonce:s,...i}=r,o=r.address;e.push([n?Pt(n):"0x",o,s?Pt(s):"0x",...ya({},i)])}return e}const D6=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),nb=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),z6=nb.map(t=>(9*t+5)%16),sb=(()=>{const r=[[nb],[z6]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>D6[i]));return r})(),ib=sb[0],ob=sb[1],ab=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),V6=ib.map((t,e)=>t.map(r=>ab[e][r])),q6=ob.map((t,e)=>t.map(r=>ab[e][r])),G6=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),W6=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Cp(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}const Ca=new Uint32Array(16);let cb=class extends rg{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:r,h2:n,h3:s,h4:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=s|0,this.h4=i|0}process(e,r){for(let f=0;f<16;f++,r+=4)Ca[f]=e.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,o=i,a=this.h2|0,c=a,u=this.h3|0,l=u,d=this.h4|0,h=d;for(let f=0;f<5;f++){const m=4-f,g=G6[f],v=W6[f],S=ib[f],_=ob[f],E=V6[f],x=q6[f];for(let O=0;O<16;O++){const P=Ta(n+Cp(f,i,a,u)+Ca[S[O]]+g,E[O])+d|0;n=d,d=u,u=Ta(a,10)|0,a=i,i=P}for(let O=0;O<16;O++){const P=Ta(s+Cp(m,o,c,l)+Ca[_[O]]+v,x[O])+h|0;s=h,h=l,l=Ta(c,10)|0,c=o,o=P}}this.set(this.h1+a+l|0,this.h2+u+h|0,this.h3+d+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){Ir(Ca)}destroy(){this.destroyed=!0,Ir(this.buffer),this.set(0,0,0,0,0)}};const K6=Oc(()=>new cb),Z6=cb,X6=K6,Y6=Object.freeze(Object.defineProperty({__proto__:null,RIPEMD160:Z6,ripemd160:X6},Symbol.toStringTag,{value:"Module"})),J6=`Ethereum Signed Message:
43
- `;function Q6(t){const e=typeof t=="string"?Ti(t):typeof t.raw=="string"?t.raw:Qe(t.raw),r=Ti(`${J6}${Le(e)}`);return Wt([r,e])}function ub(t,e){return lt(Q6(t),e)}const lb="0x6492649264926492649264926492649264926492649264926492649264926492";function ex(t){return dc(t,-32)===lb}function tx(t){const{address:e,data:r,signature:n,to:s="hex"}=t,i=Or([Pn([{type:"address"},{type:"bytes"},{type:"bytes"}],[e,r,n]),lb]);return s==="hex"?i:Tr(i)}function rx(t){return t.map(e=>({...e,value:BigInt(e.value)}))}function nx(t){return{...t,balance:t.balance?BigInt(t.balance):void 0,nonce:t.nonce?cr(t.nonce):void 0,storageProof:t.storageProof?rx(t.storageProof):void 0}}async function sx(t,{address:e,blockNumber:r,blockTag:n,storageKeys:s}){const i=n??"latest",o=r!==void 0?X(r):void 0,a=await t.request({method:"eth_getProof",params:[e,s,o||i]});return nx(a)}async function ix(t,{address:e,blockNumber:r,blockTag:n="latest",slot:s}){const i=r!==void 0?X(r):void 0;return await t.request({method:"eth_getStorageAt",params:[e,s,i||n]})}async function th(t,{blockHash:e,blockNumber:r,blockTag:n,hash:s,index:i}){var l,d,h;const o=n||"latest",a=r!==void 0?X(r):void 0;let c=null;if(s?c=await t.request({method:"eth_getTransactionByHash",params:[s]},{dedupe:!0}):e?c=await t.request({method:"eth_getTransactionByBlockHashAndIndex",params:[e,X(i)]},{dedupe:!0}):c=await t.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[a||o,X(i)]},{dedupe:!!a}),!c)throw new G0({blockHash:e,blockNumber:r,blockTag:o,hash:s,index:i});return(((h=(d=(l=t.chain)==null?void 0:l.formatters)==null?void 0:d.transaction)==null?void 0:h.format)||jc)(c)}async function ox(t,{hash:e,transactionReceipt:r}){const[n,s]=await Promise.all([ae(t,ha,"getBlockNumber")({}),e?ae(t,th,"getTransaction")({hash:e}):void 0]),i=(r==null?void 0:r.blockNumber)||(s==null?void 0:s.blockNumber);return i?n-i+1n:0n}async function Ja(t,{hash:e}){var s,i,o;const r=await t.request({method:"eth_getTransactionReceipt",params:[e]},{dedupe:!0});if(!r)throw new W0({hash:e});return(((o=(i=(s=t.chain)==null?void 0:s.formatters)==null?void 0:i.transactionReceipt)==null?void 0:o.format)||Ng)(r)}async function ax(t,e){var _;const{account:r,authorizationList:n,allowFailure:s=!0,batchSize:i,blockNumber:o,blockTag:a,multicallAddress:c,stateOverride:u}=e,l=e.contracts,d=i??(typeof((_=t.batch)==null?void 0:_.multicall)=="object"&&t.batch.multicall.batchSize||1024);let h=c;if(!h){if(!t.chain)throw new Error("client chain not configured. multicallAddress is required.");h=zi({blockNumber:o,chain:t.chain,contract:"multicall3"})}const f=[[]];let m=0,g=0;for(let E=0;E<l.length;E++){const{abi:x,address:O,args:P,functionName:$}=l[E];try{const z=fr({abi:x,args:P,functionName:$});g+=(z.length-2)/2,d>0&&g>d&&f[m].length>0&&(m++,g=(z.length-2)/2,f[m]=[]),f[m]=[...f[m],{allowFailure:!0,callData:z,target:O}]}catch(z){const C=Ns(z,{abi:x,address:O,args:P,docsPath:"/docs/contract/multicall",functionName:$,sender:r});if(!s)throw C;f[m]=[...f[m],{allowFailure:!0,callData:"0x",target:O}]}}const v=await Promise.allSettled(f.map(E=>ae(t,Xr,"readContract")({abi:Of,account:r,address:h,args:[E],authorizationList:n,blockNumber:o,blockTag:a,functionName:"aggregate3",stateOverride:u}))),S=[];for(let E=0;E<v.length;E++){const x=v[E];if(x.status==="rejected"){if(!s)throw x.reason;for(let P=0;P<f[E].length;P++)S.push({status:"failure",error:x.reason,result:void 0});continue}const O=x.value;for(let P=0;P<O.length;P++){const{returnData:$,success:z}=O[P],{callData:C}=f[E][P],{abi:Y,address:W,functionName:K,args:U}=l[S.length];try{if(C==="0x")throw new sa;if(!z)throw new Nc({data:$});const N=Ks({abi:Y,args:U,data:$,functionName:K});S.push(s?{result:N,status:"success"}:N)}catch(N){const F=Ns(N,{abi:Y,address:W,args:U,docsPath:"/docs/contract/multicall",functionName:K});if(!s)throw F;S.push({error:F,result:void 0,status:"failure"})}}}if(S.length!==l.length)throw new D("multicall results mismatch");return S}async function Uf(t,e){const{blockNumber:r,blockTag:n=t.experimental_blockTag??"latest",blocks:s,returnFullTransactions:i,traceTransfers:o,validation:a}=e;try{const c=[];for(const h of s){const f=h.blockOverrides?Sg(h.blockOverrides):void 0,m=h.calls.map(v=>{const S=v,_=S.account?We(S.account):void 0,E=S.abi?fr(S):S.data,x={...S,data:S.dataSuffix?Wt([E||"0x",S.dataSuffix]):E,from:S.from??(_==null?void 0:_.address)};return Ws(x),Hi(x)}),g=h.stateOverrides?Bd(h.stateOverrides):void 0;c.push({blockOverrides:f,calls:m,stateOverrides:g})}const l=(typeof r=="bigint"?X(r):void 0)||n;return(await t.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:i,traceTransfers:o,validation:a},l]})).map((h,f)=>({...$d(h),calls:h.calls.map((m,g)=>{var Y,W;const{abi:v,args:S,functionName:_,to:E}=s[f].calls[g],x=((Y=m.error)==null?void 0:Y.data)??m.returnData,O=BigInt(m.gasUsed),P=(W=m.logs)==null?void 0:W.map(K=>Sn(K)),$=m.status==="0x1"?"success":"failure",z=v&&$==="success"&&x!=="0x"?Ks({abi:v,data:x,functionName:_}):null,C=(()=>{var U;if($==="success")return;let K;if(((U=m.error)==null?void 0:U.data)==="0x"?K=new sa:m.error&&(K=new Nc(m.error)),!!K)return Ns(K,{abi:v??[],address:E??"0x",args:S,functionName:_??"<unknown>"})})();return{data:x,gasUsed:O,logs:P,status:$,...$==="success"?{result:z}:{error:C}}})}))}catch(c){const u=c,l=Uc(u,{});throw l instanceof la?u:l}}const cx="1.0.9";class bt extends Error{constructor(e,r={}){var o;const n=r.cause instanceof bt?r.cause.details:(o=r.cause)!=null&&o.message?r.cause.message:r.details,s=r.cause instanceof bt&&r.cause.docsPath||r.docsPath,i=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: https://abitype.dev${s}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${cx}`].join(`
44
- `);super(i),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=s,this.metaMessages=r.metaMessages,this.shortMessage=e}}function On(t,e){const r=t.exec(e);return r==null?void 0:r.groups}const fb=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,db=/^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)?$/,hb=/^\(.+?\).*?$/,$p=/^tuple(?<array>(\[(\d*)\])*)$/;function Mf(t){let e=t.type;if($p.test(t.type)&&"components"in t){e="(";const r=t.components.length;for(let s=0;s<r;s++){const i=t.components[s];e+=Mf(i),s<r-1&&(e+=", ")}const n=On($p,t.type);return e+=`)${(n==null?void 0:n.array)??""}`,Mf({...t,type:e})}return"indexed"in t&&t.indexed&&(e=`${e} indexed`),t.name?`${e} ${t.name}`:e}function Ji(t){let e="";const r=t.length;for(let n=0;n<r;n++){const s=t[n];e+=Mf(s),n!==r-1&&(e+=", ")}return e}function Ff(t){var e;return t.type==="function"?`function ${t.name}(${Ji(t.inputs)})${t.stateMutability&&t.stateMutability!=="nonpayable"?` ${t.stateMutability}`:""}${(e=t.outputs)!=null&&e.length?` returns (${Ji(t.outputs)})`:""}`:t.type==="event"?`event ${t.name}(${Ji(t.inputs)})`:t.type==="error"?`error ${t.name}(${Ji(t.inputs)})`:t.type==="constructor"?`constructor(${Ji(t.inputs)})${t.stateMutability==="payable"?" payable":""}`:t.type==="fallback"?`fallback() external${t.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const pb=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function ux(t){return pb.test(t)}function lx(t){return On(pb,t)}const yb=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function fx(t){return yb.test(t)}function dx(t){return On(yb,t)}const mb=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function hx(t){return mb.test(t)}function px(t){return On(mb,t)}const gb=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function bb(t){return gb.test(t)}function yx(t){return On(gb,t)}const wb=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function mx(t){return wb.test(t)}function gx(t){return On(wb,t)}const vb=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function bx(t){return vb.test(t)}function wx(t){return On(vb,t)}const vx=/^receive\(\) external payable$/;function Ex(t){return vx.test(t)}const Sx=new Set(["indexed"]),jf=new Set(["calldata","memory","storage"]);class Ax extends bt{constructor({signature:e}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}}class xx extends bt{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}}class kx extends bt{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}class _x extends bt{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}}class Tx extends bt{constructor({param:e,name:r}){super("Invalid ABI parameter.",{details:e,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}}class Ix extends bt{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}}class Px extends bt{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}}class Ox extends bt{constructor({abiParameter:e}){super("Invalid ABI parameter.",{details:JSON.stringify(e,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}class qi extends bt{constructor({signature:e,type:r}){super(`Invalid ${r} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}}class Bx extends bt{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}}class Cx extends bt{constructor({signature:e}){super("Invalid struct signature.",{details:e,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}class $x extends bt{constructor({type:e}){super("Circular reference detected.",{metaMessages:[`Struct "${e}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}class Rx extends bt{constructor({current:e,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${e.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}function Nx(t,e,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 e?`${e}:${t}${n}`:t}const Bu=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 Rp(t,e={}){if(hx(t))return Ux(t,e);if(fx(t))return Mx(t,e);if(ux(t))return Fx(t,e);if(mx(t))return jx(t,e);if(bx(t))return Lx(t);if(Ex(t))return{type:"receive",stateMutability:"payable"};throw new Bx({signature:t})}function Ux(t,e={}){const r=px(t);if(!r)throw new qi({signature:t,type:"function"});const n=vr(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push(js(n[a],{modifiers:jf,structs:e,type:"function"}));const o=[];if(r.returns){const a=vr(r.returns),c=a.length;for(let u=0;u<c;u++)o.push(js(a[u],{modifiers:jf,structs:e,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:s,outputs:o}}function Mx(t,e={}){const r=dx(t);if(!r)throw new qi({signature:t,type:"event"});const n=vr(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(js(n[o],{modifiers:Sx,structs:e,type:"event"}));return{name:r.name,type:"event",inputs:s}}function Fx(t,e={}){const r=lx(t);if(!r)throw new qi({signature:t,type:"error"});const n=vr(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(js(n[o],{structs:e,type:"error"}));return{name:r.name,type:"error",inputs:s}}function jx(t,e={}){const r=gx(t);if(!r)throw new qi({signature:t,type:"constructor"});const n=vr(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(js(n[o],{structs:e,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:s}}function Lx(t){const e=wx(t);if(!e)throw new qi({signature:t,type:"fallback"});return{type:"fallback",stateMutability:e.stateMutability??"nonpayable"}}const Hx=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,Dx=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,zx=/^u?int$/;function js(t,e){var d,h;const r=Nx(t,e==null?void 0:e.type,e==null?void 0:e.structs);if(Bu.has(r))return Bu.get(r);const n=hb.test(t),s=On(n?Dx:Hx,t);if(!s)throw new _x({param:t});if(s.name&&qx(s.name))throw new Tx({param:t,name:s.name});const i=s.name?{name:s.name}:{},o=s.modifier==="indexed"?{indexed:!0}:{},a=(e==null?void 0:e.structs)??{};let c,u={};if(n){c="tuple";const f=vr(s.type),m=[],g=f.length;for(let v=0;v<g;v++)m.push(js(f[v],{structs:a}));u={components:m}}else if(s.type in a)c="tuple",u={components:a[s.type]};else if(zx.test(s.type))c=`${s.type}256`;else if(s.type==="address payable")c="address";else if(c=s.type,(e==null?void 0:e.type)!=="struct"&&!Eb(c))throw new kx({type:c});if(s.modifier){if(!((h=(d=e==null?void 0:e.modifiers)==null?void 0:d.has)!=null&&h.call(d,s.modifier)))throw new Ix({param:t,type:e==null?void 0:e.type,modifier:s.modifier});if(jf.has(s.modifier)&&!Gx(c,!!s.array))throw new Px({param:t,type:e==null?void 0:e.type,modifier:s.modifier})}const l={type:`${c}${s.array??""}`,...i,...o,...u};return Bu.set(r,l),l}function vr(t,e=[],r="",n=0){const s=t.trim().length;for(let i=0;i<s;i++){const o=t[i],a=t.slice(i+1);switch(o){case",":return n===0?vr(a,[...e,r.trim()]):vr(a,e,`${r}${o}`,n);case"(":return vr(a,e,`${r}${o}`,n+1);case")":return vr(a,e,`${r}${o}`,n-1);default:return vr(a,e,`${r}${o}`,n)}}if(r==="")return e;if(n!==0)throw new Rx({current:r,depth:n});return e.push(r.trim()),e}function Eb(t){return t==="address"||t==="bool"||t==="function"||t==="string"||fb.test(t)||db.test(t)}const Vx=/^(?: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 qx(t){return t==="address"||t==="bool"||t==="function"||t==="string"||t==="tuple"||fb.test(t)||db.test(t)||Vx.test(t)}function Gx(t,e){return e||t==="bytes"||t==="string"||t==="tuple"}function Wx(t){const e={},r=t.length;for(let o=0;o<r;o++){const a=t[o];if(!bb(a))continue;const c=yx(a);if(!c)throw new qi({signature:a,type:"struct"});const u=c.properties.split(";"),l=[],d=u.length;for(let h=0;h<d;h++){const m=u[h].trim();if(!m)continue;const g=js(m,{type:"struct"});l.push(g)}if(!l.length)throw new Cx({signature:a});e[c.name]=l}const n={},s=Object.entries(e),i=s.length;for(let o=0;o<i;o++){const[a,c]=s[o];n[a]=Sb(c,e)}return n}const Kx=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function Sb(t,e,r=new Set){const n=[],s=t.length;for(let i=0;i<s;i++){const o=t[i];if(hb.test(o.type))n.push(o);else{const c=On(Kx,o.type);if(!(c!=null&&c.type))throw new Ox({abiParameter:o});const{array:u,type:l}=c;if(l in e){if(r.has(l))throw new $x({type:l});n.push({...o,type:`tuple${u??""}`,components:Sb(e[l]??[],e,new Set([...r,l]))})}else if(Eb(l))n.push(o);else throw new xx({type:l})}}return n}function Np(t){let e;if(typeof t=="string")e=Rp(t);else{const r=Wx(t),n=t.length;for(let s=0;s<n;s++){const i=t[s];if(!bb(i)){e=Rp(i,r);break}}}if(!e)throw new Ax({signature:t});return e}function Ab(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,n=$0(nA(t));return r==="Bytes"?n:wg(n)}class Zx extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const Xx={checksum:new Zx(8192)},Cu=Xx.checksum,Yx=/^0x[a-fA-F0-9]{40}$/;function Wc(t,e={}){const{strict:r=!0}=e;if(!Yx.test(t))throw new Up({address:t,cause:new Qx});if(r){if(t.toLowerCase()===t)return;if(Jx(t)!==t)throw new Up({address:t,cause:new ek})}}function Jx(t){if(Cu.has(t))return Cu.get(t);Wc(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=Ab(oA(e),{as:"Bytes"}),n=e.split("");for(let i=0;i<40;i+=2)r[i>>1]>>4>=8&&n[i]&&(n[i]=n[i].toUpperCase()),(r[i>>1]&15)>=8&&n[i+1]&&(n[i+1]=n[i+1].toUpperCase());const s=`0x${n.join("")}`;return Cu.set(t,s),s}function Lf(t,e={}){const{strict:r=!0}=e??{};try{return Wc(t,{strict:r}),!0}catch{return!1}}class Up extends Ke{constructor({address:e,cause:r}){super(`Address "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class Qx extends Ke{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 ek extends Ke{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}function Hf(t){let e=!0,r="",n=0,s="",i=!1;for(let o=0;o<t.length;o++){const a=t[o];if(["(",")",","].includes(a)&&(e=!0),a==="("&&n++,a===")"&&n--,!!e){if(n===0){if(a===" "&&["event","function","error",""].includes(s))s="";else if(s+=a,a===")"){i=!0;break}continue}if(a===" "){t[o-1]!==","&&r!==","&&r!==",("&&(r="",e=!1);continue}s+=a,r+=a}}if(!i)throw new Ke("Unable to normalize signature.");return s}function Df(t,e){const r=typeof t,n=e.type;switch(n){case"address":return Lf(t,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in e?Object.values(e.components).every((s,i)=>Df(Object.values(t)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||t instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(t)&&t.every(s=>Df(s,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function xb(t,e,r){for(const n in t){const s=t[n],i=e[n];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return xb(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")?Lf(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?Lf(r[n],{strict:!1}):!1)return o}}function kb(t,e={}){const{prepare:r=!0}=e,n=Array.isArray(t)||typeof t=="string"?Np(t):t;return{...n,...r?{hash:hi(n)}:{}}}function tk(t,e,r){const{args:n=[],prepare:s=!0}=r??{},i=hA(e,{strict:!1}),o=t.filter(u=>i?u.type==="function"||u.type==="error"?_b(u)===Wd(e,0,4):u.type==="event"?hi(u)===e:!1:"name"in u&&u.name===e);if(o.length===0)throw new zf({name:e});if(o.length===1)return{...o[0],...s?{hash:hi(o[0])}:{}};let a;for(const u of o){if(!("inputs"in u))continue;if(!n||n.length===0){if(!u.inputs||u.inputs.length===0)return{...u,...s?{hash:hi(u)}:{}};continue}if(!u.inputs||u.inputs.length===0||u.inputs.length!==n.length)continue;if(n.every((d,h)=>{const f="inputs"in u&&u.inputs[h];return f?Df(d,f):!1})){if(a&&"inputs"in a&&a.inputs){const d=xb(u.inputs,a.inputs,n);if(d)throw new nk({abiItem:u,type:d[0]},{abiItem:a,type:d[1]})}a=u}}const c=(()=>{if(a)return a;const[u,...l]=o;return{...u,overloads:l}})();if(!c)throw new zf({name:e});return{...c,...s?{hash:hi(c)}:{}}}function _b(t){return Wd(hi(t),0,4)}function rk(t){const e=typeof t=="string"?t:Ff(t);return Hf(e)}function hi(t){return typeof t!="string"&&"hash"in t&&t.hash?t.hash:Ab(Gd(rk(t)))}class nk extends Ke{constructor(e,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${e.type}\` in \`${Hf(Ff(e.abiItem))}\`, and`,`\`${r.type}\` in \`${Hf(Ff(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 zf extends Ke{constructor({name:e,data:r,type:n="item"}){const s=e?` with name "${e}"`:r?` with data "${r}"`:"";super(`ABI ${n}${s} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}const sk=/^(.*)\[([0-9]*)\]$/,ik=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Tb=/^(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 ok({checksumAddress:t,parameters:e,values:r}){const n=[];for(let s=0;s<e.length;s++)n.push(rh({checksumAddress:t,parameter:e[s],value:r[s]}));return n}function rh({checksumAddress:t=!1,parameter:e,value:r}){const n=e,s=pk(n.type);if(s){const[i,o]=s;return ck(r,{checksumAddress:t,length:i,parameter:{...n,type:o}})}if(n.type==="tuple")return hk(r,{checksumAddress:t,parameter:n});if(n.type==="address")return ak(r,{checksum:t});if(n.type==="bool")return lk(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){const i=n.type.startsWith("int"),[,,o="256"]=Tb.exec(n.type)??[];return fk(r,{signed:i,size:Number(o)})}if(n.type.startsWith("bytes"))return uk(r,{type:n.type});if(n.type==="string")return dk(r);throw new Bb(n.type)}function nh(t){let e=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?e+=32:e+=ur(a)}const r=[],n=[];let s=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?(r.push(Tt(e+s,{size:32})),n.push(a),s+=ur(a)):r.push(a)}return Zr(...r,...n)}function ak(t,e){const{checksum:r=!1}=e;return Wc(t,{strict:r}),{dynamic:!1,encoded:Ms(t.toLowerCase())}}function ck(t,e){const{checksumAddress:r,length:n,parameter:s}=e,i=n===null;if(!Array.isArray(t))throw new mk(t);if(!i&&t.length!==n)throw new yk({expectedLength:n,givenLength:t.length,type:`${s.type}[${n}]`});let o=!1;const a=[];for(let c=0;c<t.length;c++){const u=rh({checksumAddress:r,parameter:s,value:t[c]});u.dynamic&&(o=!0),a.push(u)}if(i||o){const c=nh(a);if(i){const u=Tt(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?Zr(u,c):u}}if(o)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Zr(...a.map(({encoded:c})=>c))}}function uk(t,{type:e}){const[,r]=e.split("bytes"),n=ur(t);if(!r){let s=t;return n%32!==0&&(s=Fs(s,Math.ceil((t.length-2)/2/32)*32)),{dynamic:!0,encoded:Zr(Ms(Tt(n,{size:32})),s)}}if(n!==Number.parseInt(r))throw new Pb({expectedSize:Number.parseInt(r),value:t});return{dynamic:!1,encoded:Fs(t)}}function lk(t){if(typeof t!="boolean")throw new Ke(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Ms(bg(t))}}function fk(t,{signed:e,size:r}){if(typeof r=="number"){const n=2n**(BigInt(r)-(e?1n:0n))-1n,s=e?-n-1n:0n;if(t>n||t<s)throw new vg({max:n.toString(),min:s.toString(),signed:e,size:r/8,value:t.toString()})}return{dynamic:!1,encoded:Tt(t,{size:32,signed:e})}}function dk(t){const e=Gd(t),r=Math.ceil(ur(e)/32),n=[];for(let s=0;s<r;s++)n.push(Fs(Wd(e,s*32,(s+1)*32)));return{dynamic:!0,encoded:Zr(Fs(Tt(ur(e),{size:32})),...n)}}function hk(t,e){const{checksumAddress:r,parameter:n}=e;let s=!1;const i=[];for(let o=0;o<n.components.length;o++){const a=n.components[o],c=Array.isArray(t)?o:a.name,u=rh({checksumAddress:r,parameter:a,value:t[c]});i.push(u),u.dynamic&&(s=!0)}return{dynamic:s,encoded:s?nh(i):Zr(...i.map(({encoded:o})=>o))}}function pk(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function Ib(t,e,r){const{checksumAddress:n=!1}={};if(t.length!==e.length)throw new Ob({expectedLength:t.length,givenLength:e.length});const s=ok({checksumAddress:n,parameters:t,values:e}),i=nh(s);return i.length===0?"0x":i}function Vf(t,e){if(t.length!==e.length)throw new Ob({expectedLength:t.length,givenLength:e.length});const r=[];for(let n=0;n<t.length;n++){const s=t[n],i=e[n];r.push(Vf.encode(s,i))}return Zr(...r)}(function(t){function e(r,n,s=!1){if(r==="address"){const c=n;return Wc(c),Ms(c.toLowerCase(),s?32:0)}if(r==="string")return Gd(n);if(r==="bytes")return n;if(r==="bool")return Ms(bg(n),s?32:1);const i=r.match(Tb);if(i){const[c,u,l="256"]=i,d=Number.parseInt(l)/8;return Tt(n,{size:s?32:d,signed:u==="int"})}const o=r.match(ik);if(o){const[c,u]=o;if(Number.parseInt(u)!==(n.length-2)/2)throw new Pb({expectedSize:Number.parseInt(u),value:n});return Fs(n,s?32:0)}const a=r.match(sk);if(a&&Array.isArray(n)){const[c,u]=a,l=[];for(let d=0;d<n.length;d++)l.push(e(u,n[d],!0));return l.length===0?"0x":Zr(...l)}throw new Bb(r)}t.encode=e})(Vf||(Vf={}));class yk extends Ke{constructor({expectedLength:e,givenLength:r,type:n}){super(`Array length mismatch for type \`${n}\`. Expected: \`${e}\`. Given: \`${r}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class Pb extends Ke{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${ur(r)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class Ob extends Ke{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${r}`].join(`
45
- `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class mk extends Ke{constructor(e){super(`Value \`${e}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class Bb extends Ke{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}function gk(t,e){var s;const{bytecode:r,args:n}=e;return Zr(r,(s=t.inputs)!=null&&s.length&&(n!=null&&n.length)?Ib(t.inputs,n):"0x")}function bk(t){return kb(t)}function wk(t,...e){const{overloads:r}=t,n=r?vk([t,...r],t.name,{args:e[0]}):t,s=Ek(n),i=e.length>0?Ib(n.inputs,e[0]):void 0;return i?Zr(s,i):s}function ri(t,e={}){return kb(t,e)}function vk(t,e,r){const n=tk(t,e,r);if(n.type!=="function")throw new zf({name:e,type:"function"});return n}function Ek(t){return _b(t)}const Sk="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Nr="0x0000000000000000000000000000000000000000",Ak="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function xk(t,e){const{blockNumber:r,blockTag:n,calls:s,stateOverrides:i,traceAssetChanges:o,traceTransfers:a,validation:c}=e,u=e.account?We(e.account):void 0;if(o&&!u)throw new D("`account` is required when `traceAssetChanges` is true");const l=u?gk(bk("constructor(bytes, bytes)"),{bytecode:kg,args:[Ak,wk(ri("function getBalance(address)"),[u.address])]}):void 0,d=o?await Promise.all(e.calls.map(async H=>{if(!H.data&&!H.abi)return;const{accessList:T}=await Kg(t,{account:u.address,...H,data:H.abi?fr(H):H.data});return T.map(({address:L,storageKeys:G})=>G.length>0?L:null)})).then(H=>H.flat().filter(Boolean)):[],h=await Uf(t,{blockNumber:r,blockTag:n,blocks:[...o?[{calls:[{data:l}],stateOverrides:i},{calls:d.map((H,T)=>({abi:[ri("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:H,from:Nr,nonce:T})),stateOverrides:[{address:Nr,nonce:0}]}]:[],{calls:[...s,{}].map(H=>({...H,from:u==null?void 0:u.address})),stateOverrides:i},...o?[{calls:[{data:l}]},{calls:d.map((H,T)=>({abi:[ri("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:H,from:Nr,nonce:T})),stateOverrides:[{address:Nr,nonce:0}]},{calls:d.map((H,T)=>({to:H,abi:[ri("function decimals() returns (uint256)")],functionName:"decimals",from:Nr,nonce:T})),stateOverrides:[{address:Nr,nonce:0}]},{calls:d.map((H,T)=>({to:H,abi:[ri("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:Nr,nonce:T})),stateOverrides:[{address:Nr,nonce:0}]},{calls:d.map((H,T)=>({to:H,abi:[ri("function symbol() returns (string)")],functionName:"symbol",from:Nr,nonce:T})),stateOverrides:[{address:Nr,nonce:0}]}]:[]],traceTransfers:a,validation:c}),f=o?h[2]:h[0],[m,g,,v,S,_,E,x]=o?h:[],{calls:O,...P}=f,$=O.slice(0,-1)??[],z=(m==null?void 0:m.calls)??[],C=(g==null?void 0:g.calls)??[],Y=[...z,...C].map(H=>H.status==="success"?ot(H.data):null),W=(v==null?void 0:v.calls)??[],K=(S==null?void 0:S.calls)??[],U=[...W,...K].map(H=>H.status==="success"?ot(H.data):null),N=((_==null?void 0:_.calls)??[]).map(H=>H.status==="success"?H.result:null),F=((x==null?void 0:x.calls)??[]).map(H=>H.status==="success"?H.result:null),Z=((E==null?void 0:E.calls)??[]).map(H=>H.status==="success"?H.result:null),te=[];for(const[H,T]of U.entries()){const L=Y[H];if(typeof T!="bigint"||typeof L!="bigint")continue;const G=N[H-1],I=F[H-1],R=Z[H-1],j=H===0?{address:Sk,decimals:18,symbol:"ETH"}:{address:d[H-1],decimals:R||G?Number(G??1):void 0,symbol:I??void 0};te.some(J=>J.token.address===j.address)||te.push({token:j,value:{pre:L,post:T,diff:T-L}})}return{assetChanges:te,block:P,results:$}}class Cb extends Pc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,x0(e);const n=wn(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,i=new Uint8Array(s);i.set(n.length>s?e.create().update(n).digest():n);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Ir(i)}update(e){return ns(this),this.iHash.update(e),this}digestInto(e){ns(this),Kr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:n,finished:s,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const $b=(t,e,r)=>new Cb(t,e).update(r).digest();$b.create=(t,e)=>new Cb(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const sh=BigInt(0),qf=BigInt(1);function pc(t,e=""){if(typeof t!="boolean"){const r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function gs(t,e,r=""){const n=Ic(t),s=t==null?void 0:t.length,i=e!==void 0;if(!n||i&&s!==e){const o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function $a(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Rb(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?sh:BigInt("0x"+t)}function Kc(t){return Rb(yi(t))}function Nb(t){return Kr(t),Rb(yi(Uint8Array.from(t).reverse()))}function ih(t,e){return fc(t.toString(16).padStart(e*2,"0"))}function Ub(t,e){return ih(t,e).reverse()}function Ct(t,e,r){let n;if(typeof e=="string")try{n=fc(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Ic(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");return n.length,n}const $u=t=>typeof t=="bigint"&&sh<=t;function kk(t,e,r){return $u(t)&&$u(e)&&$u(r)&&e<=t&&t<r}function _k(t,e,r,n){if(!kk(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Mb(t){let e;for(e=0;t>sh;t>>=qf,e+=1);return e}const ma=t=>(qf<<BigInt(t))-qf;function Tk(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");const n=f=>new Uint8Array(f),s=f=>Uint8Array.of(f);let i=n(t),o=n(t),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},u=(...f)=>r(o,i,...f),l=(f=n(0))=>{o=u(s(0),f),i=u(),f.length!==0&&(o=u(s(1),f),i=u())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const m=[];for(;f<e;){i=u();const g=i.slice();m.push(g),f+=i.length}return Gn(...m)};return(f,m)=>{c(),l(f);let g;for(;!(g=m(d()));)l();return c(),g}}function oh(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(s,i,o){const a=t[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(e).forEach(([s,i])=>n(s,i,!1)),Object.entries(r).forEach(([s,i])=>n(s,i,!0))}function Mp(t){const e=new WeakMap;return(r,...n)=>{const s=e.get(r);if(s!==void 0)return s;const i=t(r,...n);return e.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ut=BigInt(0),Ot=BigInt(1),bs=BigInt(2),Fb=BigInt(3),jb=BigInt(4),Lb=BigInt(5),Ik=BigInt(7),Hb=BigInt(8),Pk=BigInt(9),Db=BigInt(16);function pr(t,e){const r=t%e;return r>=Ut?r:e+r}function Jt(t,e,r){let n=t;for(;e-- >Ut;)n*=n,n%=r;return n}function Fp(t,e){if(t===Ut)throw new Error("invert: expected non-zero number");if(e<=Ut)throw new Error("invert: expected positive modulus, got "+e);let r=pr(t,e),n=e,s=Ut,i=Ot;for(;r!==Ut;){const a=n/r,c=n%r,u=s-i*a;n=r,r=c,s=i,i=u}if(n!==Ot)throw new Error("invert: does not exist");return pr(s,e)}function ah(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function zb(t,e){const r=(t.ORDER+Ot)/jb,n=t.pow(e,r);return ah(t,n,e),n}function Ok(t,e){const r=(t.ORDER-Lb)/Hb,n=t.mul(e,bs),s=t.pow(n,r),i=t.mul(e,s),o=t.mul(t.mul(i,bs),s),a=t.mul(i,t.sub(o,t.ONE));return ah(t,a,e),a}function Bk(t){const e=ga(t),r=Vb(t),n=r(e,e.neg(e.ONE)),s=r(e,n),i=r(e,e.neg(n)),o=(t+Ik)/Db;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,n);const d=a.mul(u,s),h=a.mul(u,i),f=a.eql(a.sqr(l),c),m=a.eql(a.sqr(d),c);u=a.cmov(u,l,f),l=a.cmov(h,d,m);const g=a.eql(a.sqr(l),c),v=a.cmov(u,l,g);return ah(a,v,c),v}}function Vb(t){if(t<Fb)throw new Error("sqrt is not defined for small field");let e=t-Ot,r=0;for(;e%bs===Ut;)e/=bs,r++;let n=bs;const s=ga(t);for(;jp(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return zb;let i=s.pow(n,e);const o=(e+Ot)/bs;return function(c,u){if(c.is0(u))return u;if(jp(c,u)!==1)throw new Error("Cannot find square root");let l=r,d=c.mul(c.ONE,i),h=c.pow(u,e),f=c.pow(u,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let m=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(m++,g=c.sqr(g),m===l)throw new Error("Cannot find square root");const v=Ot<<BigInt(l-m-1),S=c.pow(d,v);l=m,d=c.sqr(S),h=c.mul(h,d),f=c.mul(f,S)}return f}}function Ck(t){return t%jb===Fb?zb:t%Hb===Lb?Ok:t%Db===Pk?Bk(t):Vb(t)}const $k=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Rk(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=$k.reduce((n,s)=>(n[s]="function",n),e);return oh(t,r),t}function Nk(t,e,r){if(r<Ut)throw new Error("invalid exponent, negatives unsupported");if(r===Ut)return t.ONE;if(r===Ot)return e;let n=t.ONE,s=e;for(;r>Ut;)r&Ot&&(n=t.mul(n,s)),s=t.sqr(s),r>>=Ot;return n}function qb(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),i=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),i),n}function jp(t,e){const r=(t.ORDER-Ot)/bs,n=t.pow(e,r),s=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Gb(t,e){e!==void 0&&rs(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function ga(t,e,r=!1,n={}){if(t<=Ut)throw new Error("invalid field: expected ORDER > 0, got "+t);let s,i,o=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const h=e;h.BITS&&(s=h.BITS),h.sqrt&&(i=h.sqrt),typeof h.isLE=="boolean"&&(r=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(s=e),n.sqrt&&(i=n.sqrt);const{nBitLength:c,nByteLength:u}=Gb(t,s);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const d=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:u,MASK:ma(c),ZERO:Ut,ONE:Ot,allowedLengths:a,create:h=>pr(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return Ut<=h&&h<t},is0:h=>h===Ut,isValidNot0:h=>!d.is0(h)&&d.isValid(h),isOdd:h=>(h&Ot)===Ot,neg:h=>pr(-h,t),eql:(h,f)=>h===f,sqr:h=>pr(h*h,t),add:(h,f)=>pr(h+f,t),sub:(h,f)=>pr(h-f,t),mul:(h,f)=>pr(h*f,t),pow:(h,f)=>Nk(d,h,f),div:(h,f)=>pr(h*Fp(f,t),t),sqrN:h=>h*h,addN:(h,f)=>h+f,subN:(h,f)=>h-f,mulN:(h,f)=>h*f,inv:h=>Fp(h,t),sqrt:i||(h=>(l||(l=Ck(t)),l(d,h))),toBytes:h=>r?Ub(h,u):ih(h,u),fromBytes:(h,f=!0)=>{if(a){if(!a.includes(h.length)||h.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const g=new Uint8Array(u);g.set(h,r?0:g.length-h.length),h=g}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let m=r?Nb(h):Kc(h);if(o&&(m=pr(m,t)),!f&&!d.isValid(m))throw new Error("invalid field element: outside of range 0..ORDER");return m},invertBatch:h=>qb(d,h),cmov:(h,f,m)=>m?f:h});return Object.freeze(d)}function Wb(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function Kb(t){const e=Wb(t);return e+Math.ceil(e/2)}function Uk(t,e,r=!1){const n=t.length,s=Wb(e),i=Kb(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=r?Nb(t):Kc(t),a=pr(o,e-Ot)+Ot;return r?Ub(a,s):ih(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Bi=BigInt(0),ws=BigInt(1);function yc(t,e){const r=e.negate();return t?r:e}function Ru(t,e){const r=qb(t.Fp,e.map(n=>n.Z));return e.map((n,s)=>t.fromAffine(n.toAffine(r[s])))}function Zb(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Nu(t,e){Zb(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),s=2**t,i=ma(t),o=BigInt(t);return{windows:r,windowSize:n,mask:i,maxNumber:s,shiftBy:o}}function Lp(t,e,r){const{windowSize:n,mask:s,maxNumber:i,shiftBy:o}=r;let a=Number(t&s),c=t>>o;a>n&&(a-=i,c+=ws);const u=e*n,l=u+Math.abs(a)-1,d=a===0,h=a<0,f=e%2!==0;return{nextN:c,offset:l,isZero:d,isNeg:h,isNegF:f,offsetF:u}}function Mk(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function Fk(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const Uu=new WeakMap,Xb=new WeakMap;function Mu(t){return Xb.get(t)||1}function Hp(t){if(t!==Bi)throw new Error("invalid wNAF")}class jk{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let s=e;for(;r>Bi;)r&ws&&(n=n.add(s)),s=s.double(),r>>=ws;return n}precomputeWindow(e,r){const{windows:n,windowSize:s}=Nu(r,this.bits),i=[];let o=e,a=o;for(let c=0;c<n;c++){a=o,i.push(a);for(let u=1;u<s;u++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,i=this.BASE;const o=Nu(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:h,offsetF:f}=Lp(n,a,o);n=c,l?i=i.add(yc(h,r[f])):s=s.add(yc(d,r[u]))}return Hp(n),{p:s,f:i}}wNAFUnsafe(e,r,n,s=this.ZERO){const i=Nu(e,this.bits);for(let o=0;o<i.windows&&n!==Bi;o++){const{nextN:a,offset:c,isZero:u,isNeg:l}=Lp(n,o,i);if(n=a,!u){const d=r[c];s=s.add(l?d.negate():d)}}return Hp(n),s}getPrecomputes(e,r,n){let s=Uu.get(r);return s||(s=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(s=n(s)),Uu.set(r,s))),s}cached(e,r,n){const s=Mu(e);return this.wNAF(s,this.getPrecomputes(s,e,n),r)}unsafe(e,r,n,s){const i=Mu(e);return i===1?this._unsafeLadder(e,r,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),r,s)}createCache(e,r){Zb(r,this.bits),Xb.set(e,r),Uu.delete(e)}hasCache(e){return Mu(e)!==1}}function Lk(t,e,r,n){let s=e,i=t.ZERO,o=t.ZERO;for(;r>Bi||n>Bi;)r&ws&&(i=i.add(s)),n&ws&&(o=o.add(s)),s=s.double(),r>>=ws,n>>=ws;return{p1:i,p2:o}}function Hk(t,e,r,n){Mk(r,t),Fk(n,e);const s=r.length,i=n.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=Mb(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=ma(c),l=new Array(Number(u)+1).fill(o),d=Math.floor((e.BITS-1)/c)*c;let h=o;for(let f=d;f>=0;f-=c){l.fill(o);for(let g=0;g<i;g++){const v=n[g],S=Number(v>>BigInt(f)&u);l[S]=l[S].add(r[g])}let m=o;for(let g=l.length-1,v=o;g>0;g--)v=v.add(l[g]),m=m.add(v);if(h=h.add(m),f!==0)for(let g=0;g<c;g++)h=h.double()}return h}function Dp(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Rk(e),e}else return ga(t,{isLE:r})}function Dk(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const c of["p","n","h"]){const u=e[c];if(!(typeof u=="bigint"&&u>Bi))throw new Error(`CURVE.${c} must be positive bigint`)}const s=Dp(e.p,r.Fp,n),i=Dp(e.n,r.Fn,n),a=["Gx","Gy","a","b"];for(const c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const zp=(t,e)=>(t+(t>=0?e:-e)/Yb)/e;function zk(t,e,r){const[[n,s],[i,o]]=e,a=zp(o*t,r),c=zp(-s*t,r);let u=t-a*n-c*i,l=-a*s-c*o;const d=u<mn,h=l<mn;d&&(u=-u),h&&(l=-l);const f=ma(Math.ceil(Mb(r)/2))+wi;if(u<mn||u>=f||l<mn||l>=f)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:d,k1:u,k2neg:h,k2:l}}function Gf(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Fu(t,e){const r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return pc(r.lowS,"lowS"),pc(r.prehash,"prehash"),r.format!==void 0&&Gf(r.format),r}class Vk extends Error{constructor(e=""){super(e)}}const dn={Err:Vk,_tlv:{encode:(t,e)=>{const{Err:r}=dn;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,s=$a(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const i=n>127?$a(s.length/2|128):"";return $a(t)+i+s+e},decode(t,e){const{Err:r}=dn;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const s=e[n++],i=!!(s&128);let 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 u=e.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=dn;if(t<mn)throw new e("integer: negative integers are not allowed");let r=$a(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=dn;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Kc(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=dn,s=Ct("signature",t),{v:i,l:o}=n.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=dn,n=e.encode(2,r.encode(t.r)),s=e.encode(2,r.encode(t.s)),i=n+s;return e.encode(48,i)}},mn=BigInt(0),wi=BigInt(1),Yb=BigInt(2),Ra=BigInt(3),qk=BigInt(4);function pi(t,e){const{BYTES:r}=t;let n;if(typeof e=="bigint")n=e;else{let s=Ct("private key",e);try{n=t.fromBytes(s)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function Gk(t,e={}){const r=Dk("weierstrass",t,e),{Fp:n,Fn:s}=r;let i=r.CURVE;const{h:o,n:a}=i;oh(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=Qb(n,s);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(K,U,N){const{x:F,y:Z}=U.toAffine(),te=n.toBytes(F);if(pc(N,"isCompressed"),N){l();const H=!n.isOdd(Z);return Gn(Jb(H),te)}else return Gn(Uint8Array.of(4),te,n.toBytes(Z))}function h(K){gs(K,void 0,"Point");const{publicKey:U,publicKeyUncompressed:N}=u,F=K.length,Z=K[0],te=K.subarray(1);if(F===U&&(Z===2||Z===3)){const H=n.fromBytes(te);if(!n.isValid(H))throw new Error("bad point: is not on curve, wrong x");const T=g(H);let L;try{L=n.sqrt(T)}catch(R){const j=R instanceof Error?": "+R.message:"";throw new Error("bad point: is not on curve, sqrt error"+j)}l();const G=n.isOdd(L);return(Z&1)===1!==G&&(L=n.neg(L)),{x:H,y:L}}else if(F===N&&Z===4){const H=n.BYTES,T=n.fromBytes(te.subarray(0,H)),L=n.fromBytes(te.subarray(H,H*2));if(!v(T,L))throw new Error("bad point: is not on curve");return{x:T,y:L}}else throw new Error(`bad point: got length ${F}, expected compressed=${U} or uncompressed=${N}`)}const f=e.toBytes||d,m=e.fromBytes||h;function g(K){const U=n.sqr(K),N=n.mul(U,K);return n.add(n.add(N,n.mul(K,i.a)),i.b)}function v(K,U){const N=n.sqr(U),F=g(K);return n.eql(N,F)}if(!v(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const S=n.mul(n.pow(i.a,Ra),qk),_=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(S,_)))throw new Error("bad curve params: a or b");function E(K,U,N=!1){if(!n.isValid(U)||N&&n.is0(U))throw new Error(`bad point coordinate ${K}`);return U}function x(K){if(!(K instanceof C))throw new Error("ProjectivePoint expected")}function O(K){if(!c||!c.basises)throw new Error("no endo");return zk(K,c.basises,s.ORDER)}const P=Mp((K,U)=>{const{X:N,Y:F,Z}=K;if(n.eql(Z,n.ONE))return{x:N,y:F};const te=K.is0();U==null&&(U=te?n.ONE:n.inv(Z));const H=n.mul(N,U),T=n.mul(F,U),L=n.mul(Z,U);if(te)return{x:n.ZERO,y:n.ZERO};if(!n.eql(L,n.ONE))throw new Error("invZ was invalid");return{x:H,y:T}}),$=Mp(K=>{if(K.is0()){if(e.allowInfinityPoint&&!n.is0(K.Y))return;throw new Error("bad point: ZERO")}const{x:U,y:N}=K.toAffine();if(!n.isValid(U)||!n.isValid(N))throw new Error("bad point: x or y not field elements");if(!v(U,N))throw new Error("bad point: equation left != right");if(!K.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function z(K,U,N,F,Z){return N=new C(n.mul(N.X,K),N.Y,N.Z),U=yc(F,U),N=yc(Z,N),U.add(N)}class C{constructor(U,N,F){this.X=E("x",U),this.Y=E("y",N,!0),this.Z=E("z",F),Object.freeze(this)}static CURVE(){return i}static fromAffine(U){const{x:N,y:F}=U||{};if(!U||!n.isValid(N)||!n.isValid(F))throw new Error("invalid affine point");if(U instanceof C)throw new Error("projective point not allowed");return n.is0(N)&&n.is0(F)?C.ZERO:new C(N,F,n.ONE)}static fromBytes(U){const N=C.fromAffine(m(gs(U,void 0,"point")));return N.assertValidity(),N}static fromHex(U){return C.fromBytes(Ct("pointHex",U))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(U=8,N=!0){return W.createCache(this,U),N||this.multiply(Ra),this}assertValidity(){$(this)}hasEvenY(){const{y:U}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(U)}equals(U){x(U);const{X:N,Y:F,Z}=this,{X:te,Y:H,Z:T}=U,L=n.eql(n.mul(N,T),n.mul(te,Z)),G=n.eql(n.mul(F,T),n.mul(H,Z));return L&&G}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){const{a:U,b:N}=i,F=n.mul(N,Ra),{X:Z,Y:te,Z:H}=this;let T=n.ZERO,L=n.ZERO,G=n.ZERO,I=n.mul(Z,Z),R=n.mul(te,te),j=n.mul(H,H),J=n.mul(Z,te);return J=n.add(J,J),G=n.mul(Z,H),G=n.add(G,G),T=n.mul(U,G),L=n.mul(F,j),L=n.add(T,L),T=n.sub(R,L),L=n.add(R,L),L=n.mul(T,L),T=n.mul(J,T),G=n.mul(F,G),j=n.mul(U,j),J=n.sub(I,j),J=n.mul(U,J),J=n.add(J,G),G=n.add(I,I),I=n.add(G,I),I=n.add(I,j),I=n.mul(I,J),L=n.add(L,I),j=n.mul(te,H),j=n.add(j,j),I=n.mul(j,J),T=n.sub(T,I),G=n.mul(j,R),G=n.add(G,G),G=n.add(G,G),new C(T,L,G)}add(U){x(U);const{X:N,Y:F,Z}=this,{X:te,Y:H,Z:T}=U;let L=n.ZERO,G=n.ZERO,I=n.ZERO;const R=i.a,j=n.mul(i.b,Ra);let J=n.mul(N,te),se=n.mul(F,H),ue=n.mul(Z,T),ce=n.add(N,F),ie=n.add(te,H);ce=n.mul(ce,ie),ie=n.add(J,se),ce=n.sub(ce,ie),ie=n.add(N,Z);let oe=n.add(te,T);return ie=n.mul(ie,oe),oe=n.add(J,ue),ie=n.sub(ie,oe),oe=n.add(F,Z),L=n.add(H,T),oe=n.mul(oe,L),L=n.add(se,ue),oe=n.sub(oe,L),I=n.mul(R,ie),L=n.mul(j,ue),I=n.add(L,I),L=n.sub(se,I),I=n.add(se,I),G=n.mul(L,I),se=n.add(J,J),se=n.add(se,J),ue=n.mul(R,ue),ie=n.mul(j,ie),se=n.add(se,ue),ue=n.sub(J,ue),ue=n.mul(R,ue),ie=n.add(ie,ue),J=n.mul(se,ie),G=n.add(G,J),J=n.mul(oe,ie),L=n.mul(ce,L),L=n.sub(L,J),J=n.mul(ce,se),I=n.mul(oe,I),I=n.add(I,J),new C(L,G,I)}subtract(U){return this.add(U.negate())}is0(){return this.equals(C.ZERO)}multiply(U){const{endo:N}=e;if(!s.isValidNot0(U))throw new Error("invalid scalar: out of range");let F,Z;const te=H=>W.cached(this,H,T=>Ru(C,T));if(N){const{k1neg:H,k1:T,k2neg:L,k2:G}=O(U),{p:I,f:R}=te(T),{p:j,f:J}=te(G);Z=R.add(J),F=z(N.beta,I,j,H,L)}else{const{p:H,f:T}=te(U);F=H,Z=T}return Ru(C,[F,Z])[0]}multiplyUnsafe(U){const{endo:N}=e,F=this;if(!s.isValid(U))throw new Error("invalid scalar: out of range");if(U===mn||F.is0())return C.ZERO;if(U===wi)return F;if(W.hasCache(this))return this.multiply(U);if(N){const{k1neg:Z,k1:te,k2neg:H,k2:T}=O(U),{p1:L,p2:G}=Lk(C,F,te,T);return z(N.beta,L,G,Z,H)}else return W.unsafe(F,U)}multiplyAndAddUnsafe(U,N,F){const Z=this.multiplyUnsafe(N).add(U.multiplyUnsafe(F));return Z.is0()?void 0:Z}toAffine(U){return P(this,U)}isTorsionFree(){const{isTorsionFree:U}=e;return o===wi?!0:U?U(C,this):W.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:U}=e;return o===wi?this:U?U(C,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(U=!0){return pc(U,"isCompressed"),this.assertValidity(),f(C,this,U)}toHex(U=!0){return yi(this.toBytes(U))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(U=!0){return this.toBytes(U)}_setWindowSize(U){this.precompute(U)}static normalizeZ(U){return Ru(C,U)}static msm(U,N){return Hk(C,s,U,N)}static fromPrivateKey(U){return C.BASE.multiply(pi(s,U))}}C.BASE=new C(i.Gx,i.Gy,n.ONE),C.ZERO=new C(n.ZERO,n.ONE,n.ZERO),C.Fp=n,C.Fn=s;const Y=s.BITS,W=new jk(C,e.endo?Math.ceil(Y/2):Y);return C.BASE.precompute(8),C}function Jb(t){return Uint8Array.of(t?2:3)}function Qb(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Wk(t,e={}){const{Fn:r}=t,n=e.randomBytes||I0,s=Object.assign(Qb(t.Fp,r),{seed:Kb(r.ORDER)});function i(f){try{return!!pi(r,f)}catch{return!1}}function o(f,m){const{publicKey:g,publicKeyUncompressed:v}=s;try{const S=f.length;return m===!0&&S!==g||m===!1&&S!==v?!1:!!t.fromBytes(f)}catch{return!1}}function a(f=n(s.seed)){return Uk(gs(f,s.seed,"seed"),r.ORDER)}function c(f,m=!0){return t.BASE.multiply(pi(r,f)).toBytes(m)}function u(f){const m=a(f);return{secretKey:m,publicKey:c(m)}}function l(f){if(typeof f=="bigint")return!1;if(f instanceof t)return!0;const{secretKey:m,publicKey:g,publicKeyUncompressed:v}=s;if(r.allowedLengths||m===g)return;const S=Ct("key",f).length;return S===g||S===v}function d(f,m,g=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(m)===!1)throw new Error("second arg must be public key");const v=pi(r,f);return t.fromHex(m).multiply(v).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:u,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:f=>pi(r,f),precompute(f=8,m=t.BASE){return m.precompute(f,!1)}},lengths:s})}function Kk(t,e,r={}){x0(e),oh(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||I0,s=r.hmac||((N,...F)=>$b(e,N,Gn(...F))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:f}=Wk(t,r),m={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function v(N){const F=a>>wi;return N>F}function S(N,F){if(!o.isValidNot0(F))throw new Error(`invalid signature ${N}: out of range 1..Point.Fn.ORDER`);return F}function _(N,F){Gf(F);const Z=f.signature,te=F==="compact"?Z:F==="recovered"?Z+1:void 0;return gs(N,te,`${F} signature`)}class E{constructor(F,Z,te){this.r=S("r",F),this.s=S("s",Z),te!=null&&(this.recovery=te),Object.freeze(this)}static fromBytes(F,Z=g){_(F,Z);let te;if(Z==="der"){const{r:G,s:I}=dn.toSig(gs(F));return new E(G,I)}Z==="recovered"&&(te=F[0],Z="compact",F=F.subarray(1));const H=o.BYTES,T=F.subarray(0,H),L=F.subarray(H,H*2);return new E(o.fromBytes(T),o.fromBytes(L),te)}static fromHex(F,Z){return this.fromBytes(fc(F),Z)}addRecoveryBit(F){return new E(this.r,this.s,F)}recoverPublicKey(F){const Z=i.ORDER,{r:te,s:H,recovery:T}=this;if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");if(a*Yb<Z&&T>1)throw new Error("recovery id is ambiguous for h>1 curve");const G=T===2||T===3?te+a:te;if(!i.isValid(G))throw new Error("recovery id 2 or 3 invalid");const I=i.toBytes(G),R=t.fromBytes(Gn(Jb((T&1)===0),I)),j=o.inv(G),J=O(Ct("msgHash",F)),se=o.create(-J*j),ue=o.create(H*j),ce=t.BASE.multiplyUnsafe(se).add(R.multiplyUnsafe(ue));if(ce.is0())throw new Error("point at infinify");return ce.assertValidity(),ce}hasHighS(){return v(this.s)}toBytes(F=g){if(Gf(F),F==="der")return fc(dn.hexFromSig(this));const Z=o.toBytes(this.r),te=o.toBytes(this.s);if(F==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Gn(Uint8Array.of(this.recovery),Z,te)}return Gn(Z,te)}toHex(F){return yi(this.toBytes(F))}assertValidity(){}static fromCompact(F){return E.fromBytes(Ct("sig",F),"compact")}static fromDER(F){return E.fromBytes(Ct("sig",F),"der")}normalizeS(){return this.hasHighS()?new E(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return yi(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return yi(this.toBytes("compact"))}}const x=r.bits2int||function(F){if(F.length>8192)throw new Error("input is too large");const Z=Kc(F),te=F.length*8-c;return te>0?Z>>BigInt(te):Z},O=r.bits2int_modN||function(F){return o.create(x(F))},P=ma(c);function $(N){return _k("num < 2^"+c,N,mn,P),o.toBytes(N)}function z(N,F){return gs(N,void 0,"message"),F?gs(e(N),void 0,"prehashed message"):N}function C(N,F,Z){if(["recovered","canonical"].some(se=>se in Z))throw new Error("sign() legacy options not supported");const{lowS:te,prehash:H,extraEntropy:T}=Fu(Z,m);N=z(N,H);const L=O(N),G=pi(o,F),I=[$(G),$(L)];if(T!=null&&T!==!1){const se=T===!0?n(f.secretKey):T;I.push(Ct("extraEntropy",se))}const R=Gn(...I),j=L;function J(se){const ue=x(se);if(!o.isValidNot0(ue))return;const ce=o.inv(ue),ie=t.BASE.multiply(ue).toAffine(),oe=o.create(ie.x);if(oe===mn)return;const me=o.create(ce*o.create(j+oe*G));if(me===mn)return;let be=(ie.x===oe?0:2)|Number(ie.y&wi),Se=me;return te&&v(me)&&(Se=o.neg(me),be^=1),new E(oe,Se,be)}return{seed:R,k2sig:J}}function Y(N,F,Z={}){N=Ct("message",N);const{seed:te,k2sig:H}=C(N,F,Z);return Tk(e.outputLen,o.BYTES,s)(te,H)}function W(N){let F;const Z=typeof N=="string"||Ic(N),te=!Z&&N!==null&&typeof N=="object"&&typeof N.r=="bigint"&&typeof N.s=="bigint";if(!Z&&!te)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(te)F=new E(N.r,N.s);else if(Z){try{F=E.fromBytes(Ct("sig",N),"der")}catch(H){if(!(H instanceof dn.Err))throw H}if(!F)try{F=E.fromBytes(Ct("sig",N),"compact")}catch{return!1}}return F||!1}function K(N,F,Z,te={}){const{lowS:H,prehash:T,format:L}=Fu(te,m);if(Z=Ct("publicKey",Z),F=z(Ct("message",F),T),"strict"in te)throw new Error("options.strict was renamed to lowS");const G=L===void 0?W(N):E.fromBytes(Ct("sig",N),L);if(G===!1)return!1;try{const I=t.fromBytes(Z);if(H&&G.hasHighS())return!1;const{r:R,s:j}=G,J=O(F),se=o.inv(j),ue=o.create(J*se),ce=o.create(R*se),ie=t.BASE.multiplyUnsafe(ue).add(I.multiplyUnsafe(ce));return ie.is0()?!1:o.create(ie.x)===R}catch{return!1}}function U(N,F,Z={}){const{prehash:te}=Fu(Z,m);return F=z(F,te),E.fromBytes(N,"recovered").recoverPublicKey(F).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:f,Point:t,sign:Y,verify:K,recoverPublicKey:U,Signature:E,hash:e})}function Zk(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const s=ga(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),i={Fp:r,Fn:s,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function Xk(t){const{CURVE:e,curveOpts:r}=Zk(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function Yk(t,e){const r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,Gb(r.Fn.ORDER,r.Fn.BITS))})}function Jk(t){const{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:s}=Xk(t),i=Gk(e,r),o=Kk(i,n,s);return Yk(t,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Qk(t,e){const r=n=>Jk({...t,hash:n});return{...r(e),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ch={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},e_={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Vp=BigInt(2);function t_(t){const e=ch.p,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,d=Jt(l,r,e)*l%e,h=Jt(d,r,e)*l%e,f=Jt(h,Vp,e)*u%e,m=Jt(f,s,e)*f%e,g=Jt(m,i,e)*m%e,v=Jt(g,a,e)*g%e,S=Jt(v,c,e)*v%e,_=Jt(S,a,e)*g%e,E=Jt(_,r,e)*l%e,x=Jt(E,o,e)*m%e,O=Jt(x,n,e)*u%e,P=Jt(O,Vp,e);if(!Wf.eql(Wf.sqr(P),t))throw new Error("Cannot find square root");return P}const Wf=ga(ch.p,{sqrt:t_}),ew=Qk({...ch,Fp:Wf,lowS:!0,endo:e_},sg),r_=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:ew},Symbol.toStringTag,{value:"Module"}));function n_({r:t,s:e,to:r="hex",v:n,yParity:s}){const i=(()=>{if(s===0||s===1)return s;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),o=`0x${new ew.Signature(ot(t),ot(e)).toCompactHex()}${i===0?"1b":"1c"}`;return r==="hex"?o:Tr(o)}async function uh(t,e){var d,h,f;const{address:r,factory:n,factoryData:s,hash:i,signature:o,universalSignatureVerifierAddress:a=(f=(h=(d=t.chain)==null?void 0:d.contracts)==null?void 0:h.universalSignatureVerifier)==null?void 0:f.address,...c}=e,u=_r(o)?o:typeof o=="object"&&"r"in o&&"s"in o?n_(o):Qe(o),l=await(async()=>!n&&!s||ex(u)?u:tx({address:n,data:s,signature:u}))();try{const m=a?{to:a,data:fr({abi:xp,functionName:"isValidSig",args:[r,i,l]}),...c}:{data:Dc({abi:xp,args:[r,i,l],bytecode:vA}),...c},{data:g}=await ae(t,da,"call")(m);return W2(g??"0x0")}catch(m){try{if(fa(N0(r),await Z0({hash:i,signature:o})))return!0}catch{}if(m instanceof K0)return!1;throw m}}async function s_(t,{address:e,message:r,factory:n,factoryData:s,signature:i,...o}){const a=ub(r);return uh(t,{address:e,factory:n,factoryData:s,hash:a,signature:i,...o})}async function i_(t,e){const{address:r,factory:n,factoryData:s,signature:i,message:o,primaryType:a,types:c,domain:u,...l}=e,d=k6({message:o,primaryType:a,types:c,domain:u});return uh(t,{address:r,factory:n,factoryData:s,hash:d,signature:i,...l})}function tw(t,{emitOnBegin:e=!1,emitMissed:r=!1,onBlockNumber:n,onError:s,poll:i,pollingInterval:o=t.pollingInterval}){const a=typeof i<"u"?i:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc"));let c;return a?(()=>{const d=Je(["watchBlockNumber",t.uid,e,r,o]);return An(d,{onBlockNumber:n,onError:s},h=>Vi(async()=>{var f;try{const m=await ae(t,ha,"getBlockNumber")({cacheTime:0});if(c){if(m===c)return;if(m-c>1&&r)for(let g=c+1n;g<m;g++)h.onBlockNumber(g,c),c=g}(!c||m>c)&&(h.onBlockNumber(m,c),c=m)}catch(m){(f=h.onError)==null||f.call(h,m)}},{emitOnBegin:e,interval:o}))})():(()=>{const d=Je(["watchBlockNumber",t.uid,e,r]);return An(d,{onBlockNumber:n,onError:s},h=>{let f=!0,m=()=>f=!1;return(async()=>{try{const g=(()=>{if(t.transport.type==="fallback"){const S=t.transport.transports.find(_=>_.config.type==="webSocket"||_.config.type==="ipc");return S?S.value:t.transport}return t.transport})(),{unsubscribe:v}=await g.subscribe({params:["newHeads"],onData(S){var E;if(!f)return;const _=ot((E=S.result)==null?void 0:E.number);h.onBlockNumber(_,c),c=_},onError(S){var _;(_=h.onError)==null||_.call(h,S)}});m=v,f||m()}catch(g){s==null||s(g)}})(),()=>m()})})()}async function o_(t,e){const{checkReplacement:r=!0,confirmations:n=1,hash:s,onReplaced:i,retryCount:o=6,retryDelay:a=({count:O})=>~~(1<<O)*200,timeout:c=18e4}=e,u=Je(["waitForTransactionReceipt",t.uid,s]),l=(()=>{var O;return e.pollingInterval?e.pollingInterval:(O=t.chain)!=null&&O.experimental_preconfirmationTime?t.chain.experimental_preconfirmationTime:t.pollingInterval})();let d,h,f,m=!1,g,v;const{promise:S,resolve:_,reject:E}=Kd(),x=c?setTimeout(()=>{v==null||v(),g==null||g(),E(new aS({hash:s}))},c):void 0;return g=An(u,{onReplaced:i,resolve:_,reject:E},async O=>{if(f=await ae(t,Ja,"getTransactionReceipt")({hash:s}).catch(()=>{}),f&&n<=1){clearTimeout(x),O.resolve(f),g==null||g();return}v=ae(t,tw,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:l,async onBlockNumber(P){const $=C=>{clearTimeout(x),v==null||v(),C(),g==null||g()};let z=P;if(!m)try{if(f){if(n>1&&(!f.blockNumber||z-f.blockNumber+1n<n))return;$(()=>O.resolve(f));return}if(r&&!d&&(m=!0,await hc(async()=>{d=await ae(t,th,"getTransaction")({hash:s}),d.blockNumber&&(z=d.blockNumber)},{delay:a,retryCount:o}),m=!1),f=await ae(t,Ja,"getTransactionReceipt")({hash:s}),n>1&&(!f.blockNumber||z-f.blockNumber+1n<n))return;$(()=>O.resolve(f))}catch(C){if(C instanceof G0||C instanceof W0){if(!d){m=!1;return}try{h=d,m=!0;const Y=await hc(()=>ae(t,Gr,"getBlock")({blockNumber:z,includeTransactions:!0}),{delay:a,retryCount:o,shouldRetry:({error:U})=>U instanceof Q0});m=!1;const W=Y.transactions.find(({from:U,nonce:N})=>U===h.from&&N===h.nonce);if(!W||(f=await ae(t,Ja,"getTransactionReceipt")({hash:W.hash}),n>1&&(!f.blockNumber||z-f.blockNumber+1n<n)))return;let K="replaced";W.to===h.to&&W.value===h.value&&W.input===h.input?K="repriced":W.from===W.to&&W.value===0n&&(K="cancelled"),$(()=>{var U;(U=O.onReplaced)==null||U.call(O,{reason:K,replacedTransaction:h,transaction:W,transactionReceipt:f}),O.resolve(f)})}catch(Y){$(()=>O.reject(Y))}}else $(()=>O.reject(C))}}})}),S}function a_(t,{blockTag:e=t.experimental_blockTag??"latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:s,onError:i,includeTransactions:o,poll:a,pollingInterval:c=t.pollingInterval}){const u=typeof a<"u"?a:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")),l=o??!1;let d;return u?(()=>{const m=Je(["watchBlocks",t.uid,e,r,n,l,c]);return An(m,{onBlock:s,onError:i},g=>Vi(async()=>{var v;try{const S=await ae(t,Gr,"getBlock")({blockTag:e,includeTransactions:l});if(S.number!==null&&(d==null?void 0:d.number)!=null){if(S.number===d.number)return;if(S.number-d.number>1&&r)for(let _=(d==null?void 0:d.number)+1n;_<S.number;_++){const E=await ae(t,Gr,"getBlock")({blockNumber:_,includeTransactions:l});g.onBlock(E,d),d=E}}((d==null?void 0:d.number)==null||e==="pending"&&(S==null?void 0:S.number)==null||S.number!==null&&S.number>d.number)&&(g.onBlock(S,d),d=S)}catch(S){(v=g.onError)==null||v.call(g,S)}},{emitOnBegin:n,interval:c}))})():(()=>{let m=!0,g=!0,v=()=>m=!1;return(async()=>{try{n&&ae(t,Gr,"getBlock")({blockTag:e,includeTransactions:l}).then(E=>{m&&g&&(s(E,void 0),g=!1)}).catch(i);const S=(()=>{if(t.transport.type==="fallback"){const E=t.transport.transports.find(x=>x.config.type==="webSocket"||x.config.type==="ipc");return E?E.value:t.transport}return t.transport})(),{unsubscribe:_}=await S.subscribe({params:["newHeads"],async onData(E){var O;if(!m)return;const x=await ae(t,Gr,"getBlock")({blockNumber:(O=E.result)==null?void 0:O.number,includeTransactions:l}).catch(()=>{});m&&(s(x,d),g=!1,d=x)},onError(E){i==null||i(E)}});v=_,m||v()}catch(S){i==null||i(S)}})(),()=>v()})()}function c_(t,{address:e,args:r,batch:n=!0,event:s,events:i,fromBlock:o,onError:a,onLogs:c,poll:u,pollingInterval:l=t.pollingInterval,strict:d}){const h=typeof u<"u"?u:typeof o=="bigint"?!0:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")),f=d??!1;return h?(()=>{const v=Je(["watchEvent",e,r,n,t.uid,s,l,o]);return An(v,{onLogs:c,onError:a},S=>{let _;o!==void 0&&(_=o-1n);let E,x=!1;const O=Vi(async()=>{var P;if(!x){try{E=await ae(t,Zg,"createEventFilter")({address:e,args:r,event:s,events:i,strict:f,fromBlock:o})}catch{}x=!0;return}try{let $;if(E)$=await ae(t,zc,"getFilterChanges")({filter:E});else{const z=await ae(t,ha,"getBlockNumber")({});_&&_!==z?$=await ae(t,zd,"getLogs")({address:e,args:r,event:s,events:i,fromBlock:_+1n,toBlock:z}):$=[],_=z}if($.length===0)return;if(n)S.onLogs($);else for(const z of $)S.onLogs([z])}catch($){E&&$ instanceof Rs&&(x=!1),(P=S.onError)==null||P.call(S,$)}},{emitOnBegin:!0,interval:l});return async()=>{E&&await ae(t,Vc,"uninstallFilter")({filter:E}),O()}})})():(()=>{let v=!0,S=()=>v=!1;return(async()=>{try{const _=(()=>{if(t.transport.type==="fallback"){const P=t.transport.transports.find($=>$.config.type==="webSocket"||$.config.type==="ipc");return P?P.value:t.transport}return t.transport})(),E=i??(s?[s]:void 0);let x=[];E&&(x=[E.flatMap($=>aa({abi:[$],eventName:$.name,args:r}))],s&&(x=x[0]));const{unsubscribe:O}=await _.subscribe({params:["logs",{address:e,topics:x}],onData(P){var z;if(!v)return;const $=P.result;try{const{eventName:C,args:Y}=Hd({abi:E??[],data:$.data,topics:$.topics,strict:f}),W=Sn($,{args:Y,eventName:C});c([W])}catch(C){let Y,W;if(C instanceof xo||C instanceof Tc){if(d)return;Y=C.abiItem.name,W=(z=C.abiItem.inputs)==null?void 0:z.some(U=>!("name"in U&&U.name))}const K=Sn($,{args:W?[]:{},eventName:Y});c([K])}},onError(P){a==null||a(P)}});S=O,v||S()}catch(_){a==null||a(_)}})(),()=>S()})()}function u_(t,{batch:e=!0,onError:r,onTransactions:n,poll:s,pollingInterval:i=t.pollingInterval}){return(typeof s<"u"?s:t.transport.type!=="webSocket"&&t.transport.type!=="ipc")?(()=>{const u=Je(["watchPendingTransactions",t.uid,e,i]);return An(u,{onTransactions:n,onError:r},l=>{let d;const h=Vi(async()=>{var f;try{if(!d)try{d=await ae(t,Xg,"createPendingTransactionFilter")({});return}catch(g){throw h(),g}const m=await ae(t,zc,"getFilterChanges")({filter:d});if(m.length===0)return;if(e)l.onTransactions(m);else for(const g of m)l.onTransactions([g])}catch(m){(f=l.onError)==null||f.call(l,m)}},{emitOnBegin:!0,interval:i});return async()=>{d&&await ae(t,Vc,"uninstallFilter")({filter:d}),h()}})})():(()=>{let u=!0,l=()=>u=!1;return(async()=>{try{const{unsubscribe:d}=await t.transport.subscribe({params:["newPendingTransactions"],onData(h){if(!u)return;const f=h.result;n([f])},onError(h){r==null||r(h)}});l=d,u||l()}catch(d){r==null||r(d)}})(),()=>l()})()}function l_(t){var d,h,f;const{scheme:e,statement:r,...n}=((d=t.match(f_))==null?void 0:d.groups)??{},{chainId:s,expirationTime:i,issuedAt:o,notBefore:a,requestId:c,...u}=((h=t.match(d_))==null?void 0:h.groups)??{},l=(f=t.split("Resources:")[1])==null?void 0:f.split(`
46
- - `).slice(1);return{...n,...u,...s?{chainId:Number(s)}:{},...i?{expirationTime:new Date(i)}:{},...o?{issuedAt:new Date(o)}:{},...a?{notBefore:new Date(a)}:{},...c?{requestId:c}:{},...l?{resources:l}:{},...e?{scheme:e}:{},...r?{statement:r}:{}}}const f_=/^(?:(?<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)?/,d_=/(?: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 h_(t){const{address:e,domain:r,message:n,nonce:s,scheme:i,time:o=new Date}=t;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||!it(n.address,{strict:!1})||e&&!fa(n.address,e))return!1}catch{return!1}return!0}async function p_(t,e){const{address:r,domain:n,message:s,nonce:i,scheme:o,signature:a,time:c=new Date,...u}=e,l=l_(s);if(!l.address||!h_({address:r,domain:n,message:l,nonce:i,scheme:o,time:c}))return!1;const h=ub(s);return uh(t,{address:l.address,hash:h,signature:a,...u})}function y_(t){return{call:e=>da(t,e),createAccessList:e=>Kg(t,e),createBlockFilter:()=>h6(t),createContractEventFilter:e=>_d(t,e),createEventFilter:e=>Zg(t,e),createPendingTransactionFilter:()=>Xg(t),estimateContractGas:e=>yg(t,e),estimateGas:e=>Ld(t,e),getBalance:e=>pg(t,e),getBlobBaseFee:()=>p6(t),getBlock:e=>Gr(t,e),getBlockNumber:e=>ha(t,e),getBlockTransactionCount:e=>y6(t,e),getBytecode:e=>Bp(t,e),getChainId:()=>Di(t),getCode:e=>Bp(t,e),getContractEvents:e=>Vd(t,e),getEip712Domain:e=>g6(t,e),getEnsAddress:e=>YA(t,e),getEnsAvatar:e=>l6(t,e),getEnsName:e=>f6(t,e),getEnsResolver:e=>d6(t,e),getEnsText:e=>Wg(t,e),getFeeHistory:e=>v6(t,e),estimateFeesPerGas:e=>BS(t,e),getFilterChanges:e=>zc(t,e),getFilterLogs:e=>E6(t,e),getGasPrice:()=>Rd(t),getLogs:e=>zd(t,e),getProof:e=>sx(t,e),estimateMaxPriorityFeePerGas:e=>OS(t,e),getStorageAt:e=>ix(t,e),getTransaction:e=>th(t,e),getTransactionConfirmations:e=>ox(t,e),getTransactionCount:e=>Nd(t,e),getTransactionReceipt:e=>Ja(t,e),multicall:e=>ax(t,e),prepareTransactionRequest:e=>Lc(t,e),readContract:e=>Xr(t,e),sendRawTransaction:e=>Zd(t,e),simulate:e=>Uf(t,e),simulateBlocks:e=>Uf(t,e),simulateCalls:e=>xk(t,e),simulateContract:e=>Pg(t,e),verifyMessage:e=>s_(t,e),verifySiweMessage:e=>p_(t,e),verifyTypedData:e=>i_(t,e),uninstallFilter:e=>Vc(t,e),waitForTransactionReceipt:e=>o_(t,e),watchBlocks:e=>a_(t,e),watchBlockNumber:e=>tw(t,e),watchContractEvent:e=>Og(t,e),watchEvent:e=>c_(t,e),watchPendingTransactions:e=>u_(t,e)}}function m_(t){const{key:e="public",name:r="Public Client"}=t;return Lg({...t,key:e,name:r,type:"publicClient"}).extend(y_)}async function g_(t,{chain:e}){const{id:r,name:n,nativeCurrency:s,rpcUrls:i,blockExplorers:o}=e;await t.request({method:"wallet_addEthereumChain",params:[{chainId:X(r),chainName:n,nativeCurrency:s,rpcUrls:i.default.http,blockExplorerUrls:o?Object.values(o).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}function b_(t,e){const{abi:r,args:n,bytecode:s,...i}=e,o=Dc({abi:r,args:n,bytecode:s});return qc(t,{...i,...i.authorizationList?{to:null}:{},data:o})}async function w_(t){var r;return((r=t.account)==null?void 0:r.type)==="local"?[t.account.address]:(await t.request({method:"eth_accounts"},{dedupe:!0})).map(n=>ia(n))}async function v_(t,e={}){const{account:r=t.account,chainId:n}=e,s=r?We(r):void 0,i=n?[s==null?void 0:s.address,[X(n)]]:[s==null?void 0:s.address],o=await t.request({method:"wallet_getCapabilities",params:i}),a={};for(const[c,u]of Object.entries(o)){a[Number(c)]={};for(let[l,d]of Object.entries(u))l==="addSubAccount"&&(l="unstable_addSubAccount"),a[Number(c)][l]=d}return typeof n=="number"?a[n]:a}async function E_(t){return await t.request({method:"wallet_getPermissions"},{dedupe:!0})}async function rw(t,e){var c;const{account:r=t.account,chainId:n,nonce:s}=e;if(!r)throw new Zs({docsPath:"/docs/eip7702/prepareAuthorization"});const i=We(r),o=(()=>{if(e.executor)return e.executor==="self"?e.executor:We(e.executor)})(),a={address:e.contractAddress??e.address,chainId:n,nonce:s};return typeof a.chainId>"u"&&(a.chainId=((c=t.chain)==null?void 0:c.id)??await ae(t,Di,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await ae(t,Nd,"getTransactionCount")({address:i.address,blockTag:"pending"}),(o==="self"||o!=null&&o.address&&fa(o.address,i.address))&&(a.nonce+=1)),a}async function S_(t){return(await t.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>N0(r))}async function A_(t,e){return t.request({method:"wallet_requestPermissions",params:[e]},{retryCount:0})}async function x_(t,e){const{id:r}=e;await t.request({method:"wallet_showCallsStatus",params:[r]})}async function k_(t,e){const{account:r=t.account}=e;if(!r)throw new Zs({docsPath:"/docs/eip7702/signAuthorization"});const n=We(r);if(!n.signAuthorization)throw new Ya({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});const s=await rw(t,e);return n.signAuthorization(s)}async function __(t,{account:e=t.account,message:r}){if(!e)throw new Zs({docsPath:"/docs/actions/wallet/signMessage"});const n=We(e);if(n.signMessage)return n.signMessage({message:r});const s=typeof r=="string"?Ti(r):r.raw instanceof Uint8Array?Pt(r.raw):r.raw;return t.request({method:"personal_sign",params:[s,n.address]},{retryCount:0})}async function T_(t,e){var u,l,d,h;const{account:r=t.account,chain:n=t.chain,...s}=e;if(!r)throw new Zs({docsPath:"/docs/actions/wallet/signTransaction"});const i=We(r);Ws({account:i,...e});const o=await ae(t,Di,"getChainId")({});n!==null&&Bg({currentChainId:o,chain:n});const a=(n==null?void 0:n.formatters)||((u=t.chain)==null?void 0:u.formatters),c=((l=a==null?void 0:a.transactionRequest)==null?void 0:l.format)||Hi;return i.signTransaction?i.signTransaction({...s,chainId:o},{serializer:(h=(d=t.chain)==null?void 0:d.serializers)==null?void 0:h.transaction}):await t.request({method:"eth_signTransaction",params:[{...c(s),chainId:X(o),from:i.address}]},{retryCount:0})}async function I_(t,e){const{account:r=t.account,domain:n,message:s,primaryType:i}=e;if(!r)throw new Zs({docsPath:"/docs/actions/wallet/signTypedData"});const o=We(r),a={EIP712Domain:rb({domain:n}),...e.types};if(tb({domain:n,message:s,primaryType:i,types:a}),o.signTypedData)return o.signTypedData({domain:n,message:s,primaryType:i,types:a});const c=P6({domain:n,message:s,primaryType:i,types:a});return t.request({method:"eth_signTypedData_v4",params:[o.address,c]},{retryCount:0})}async function P_(t,{id:e}){await t.request({method:"wallet_switchEthereumChain",params:[{chainId:X(e)}]},{retryCount:0})}async function O_(t,e){return await t.request({method:"wallet_watchAsset",params:e},{retryCount:0})}function B_(t){return{addChain:e=>g_(t,e),deployContract:e=>b_(t,e),getAddresses:()=>w_(t),getCallsStatus:e=>Fg(t,e),getCapabilities:e=>v_(t,e),getChainId:()=>Di(t),getPermissions:()=>E_(t),prepareAuthorization:e=>rw(t,e),prepareTransactionRequest:e=>Lc(t,e),requestAddresses:()=>S_(t),requestPermissions:e=>A_(t,e),sendCalls:e=>UA(t,e),sendRawTransaction:e=>Zd(t,e),sendTransaction:e=>qc(t,e),showCallsStatus:e=>x_(t,e),signAuthorization:e=>k_(t,e),signMessage:e=>__(t,e),signTransaction:e=>T_(t,e),signTypedData:e=>I_(t,e),switchChain:e=>P_(t,e),waitForCallsStatus:e=>MA(t,e),watchAsset:e=>O_(t,e),writeContract:e=>$g(t,e)}}function ju(t){const{key:e="wallet",name:r="Wallet Client",transport:n}=t;return Lg({...t,key:e,name:r,transport:n,type:"walletClient"}).extend(B_)}const Qa={mainnet:{baseurl:"https://api.garden.finance",auth:"https://api.garden.finance/auth",info:"https://api.garden.finance/info",relayer:"https://relayer.garden.finance"},testnet:{baseurl:"https://testnet.api.garden.finance",auth:"https://testnet.api.garden.finance/auth",info:"https://testnet.api.garden.finance/info",relayer:"https://testnet.api.garden.finance/relayer"},localnet:{baseurl:"",auth:"",info:"",relayer:""}},Go={[b.Network.MAINNET]:{chainId:"0x534e5f4d41494e",nodeUrl:"https://starknet-mainnet.public.blastapi.io/rpc/v0_8"},[b.Network.TESTNET]:{chainId:"0x534e5f5345504f4c4941",nodeUrl:"https://starknet-sepolia.public.blastapi.io/rpc/v0_8"},[b.Network.LOCALNET]:{chainId:"",nodeUrl:""}},nw={[b.Network.MAINNET]:"9cBuPNiHXiMNg3Fin8xLCGJQBTXjYQTFtyaFQv2uiM1H",[b.Network.TESTNET]:"ANUVKxeqaec3bf4DVPqLTnG1PT3Fng56wPcE7LXAb46Q",[b.Network.LOCALNET]:"AKnL4NNf3DGWZJS6cPknBuEGnVsV4A4m5tgebLHaRSZ9"},Kf={mainnet:{native:"2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",spl:"gdnvdMCHJgnidtU7SL8RkRshHPvDJU1pdfZEpoLvqdU"},staging:{native:"6eksgdCnSjUaGQWZ6iYvauv1qzvYPF33RTGTM1ZuyENx",spl:"2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC"}},Zf={[b.Network.TESTNET]:{packageId:"0x99865b03dd1bc03d0a6a805c454ea257c464f7abcccae9cd4b621b91e7ca04de",moduleName:"AtomicSwap"},[b.Network.MAINNET]:{packageId:"0xbfb5728aab0dd117747ef4574af6d3540ea6093109c22856e3ae201dfd58c0fc",moduleName:"AtomicSwap"},[b.Network.LOCALNET]:{packageId:"",moduleName:""}},sw={asset:ee.ChainAsset.from(ee.Assets.base.cBBTC)};var vi=(t=>(t.SLOW="SLOW",t.MEDIUM="MEDIUM",t.FAST="FAST",t))(vi||{}),xr=(t=>(t.Mainnet="Mainnet",t.Testnet="Testnet",t.Regtest="Regtest",t))(xr||{}),ec=(t=>(t.ALL="ALL",t.IN="IN",t.OUT="OUT",t))(ec||{});const C_={SLOW:"economyFee",MEDIUM:"hourFee",FAST:"fastestFee"};function Xf(t){const e=typeof t=="string"?t:t.network,r=e===b.Network.MAINNET?Qa.mainnet:b.Network.TESTNET?Qa.testnet:Qa.localnet;return{api:typeof t=="string"?r:{...r,...t},network:e}}function $_(t){return typeof t=="string"&&(t=Buffer.from(t,"hex")),t.length===32?t:t.subarray(1,33)}function qp(t,e){if(!t)throw new Error(e)}function R_(t){return Buffer.concat([Uint8Array.from([192]),N_(t)])}function N_(t){const e=Kh.encodingLength(t.length),r=Buffer.allocUnsafe(e);return Kh.encode(t.length,r),Buffer.concat([r,t])}function U_(t,e){if(t.compare(e)>0){const r=t;t=e,e=r}return[t,e]}const Me=t=>t.length===64?t:t.slice(2),M_=t=>{if(!t)return!1;try{const e=Buffer.from(t,"hex");return or.isPoint(e)}catch{return!1}},iw=(t,e,r,n)=>t+":"+e.toLowerCase()+"::"+r+":"+n.toLowerCase();function F_(t,e){if(!t)return!1;const r=e===b.Environment.MAINNET?ve.networks.bitcoin:e===b.Environment.TESTNET?ve.networks.testnet:ve.networks.regtest;if(!r)return!1;ve.initEccLib(or);try{return ve.address.toOutputScript(t,r),!0}catch{return!1}}function Qi(t,e){const r=[];for(let n=0;n<e;n++)r.push(t);return r}const j_=t=>{switch(t){case b.Network.MAINNET:return xr.Mainnet;case b.Network.TESTNET:return xr.Testnet;case b.Network.LOCALNET:return xr.Regtest;default:throw new Error(`Invalid bitcoin network ${t}`)}},L_=t=>{switch(t){case b.Network.MAINNET:return ve.networks.bitcoin;case b.Network.TESTNET:return ve.networks.testnet;case b.Network.LOCALNET:return ve.networks.regtest;default:throw new Error(`Invalid bitcoin network ${t}`)}},H_=t=>{const e=t.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(e)},Gp=t=>{if(typeof t=="object"&&"r"in t&&"s"in t)return b.Ok([t.r.toString(),t.s.toString()]);if(Array.isArray(t)){const e=t.map(r=>typeof r=="string"&&r.startsWith("0x")&&H_(r)?BigInt(r).toString():r);return b.Ok(e)}return b.Err("Invalid signature format")};function Yf(t){return Buffer.from(t,"hex").reverse()}function Jf(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"}const Na=async(t,e)=>{const r=Date.now(),n=3e4,s=2e3;for(;Date.now()-r<n;){const i=await t.getLatestBlockhash(),o=await t.confirmTransaction({signature:e,blockhash:i.blockhash,lastValidBlockHeight:i.lastValidBlockHeight},"confirmed");if(o.value&&o.value.err==null)return console.log("Tx Confirmed ✅",e),!0;console.log("Tx not confirmed yet. Retrying in 2 seconds..."),await new Promise(a=>setTimeout(a,s))}return!1},lh=async(t,e)=>{var a,c;const r=await b.Fetcher.get(e+"/v2/assets");if(r.error)return b.Err("Failed to fetch asset info: "+r.error);const s=(r.result||[]).find(u=>u.id===t);if(!s)return b.Err(`Asset info not found for asset id: ${t}`);const i=((a=s.htlc)==null?void 0:a.address)||"",o=((c=s.token)==null?void 0:c.address)||"";return b.Ok({htlcAddress:i,tokenAddress:o})},Wp=t=>{if(t==null||t.includes("."))return b.Err("Invalid amount ",t);const e=new Uv.BigNumber(t);return!e.isInteger()||e.isNaN()||e.lt(0)||e.isLessThanOrEqualTo(0)?b.Err("Invalid amount ",t):b.Ok(e)},D_=t=>(t??[]).map(e=>({fee:e.fee,address:e.address,asset:e.asset??sw.asset})),Kp=async(t,e)=>{var r;switch(t){case ee.BlockchainType.evm:return e.evm?b.Ok(e.evm.htlcActorAddress):b.Err("Please provide evmHTLC when initializing garden or pass EVM address in SwapParams");case ee.BlockchainType.bitcoin:{const n=(r=e.bitcoin)==null?void 0:r.getPublicKey;return!n||!M_(n)?b.Err("Invalid btc public key or pass Bitcoin address in SwapParams"):b.Ok(Me(n))}case ee.BlockchainType.solana:return e.solana?b.Ok(e.solana.htlcActorAddress):b.Err("Please provide solanaHTLC when initializing garden or pass Solana address in SwapParams");case ee.BlockchainType.starknet:return e.starknet?b.Ok(e.starknet.htlcActorAddress):b.Err("Please provide starknetHTLC when initializing garden or pass Starknet address in SwapParams");case ee.BlockchainType.sui:return e.sui?b.Ok(e.sui.htlcActorAddress):b.Err("Please provide suiHTLC when initializing garden or pass Sui address in SwapParams");default:return b.Err("Unsupported chain")}},z_=async(t,e)=>{const n={[ee.BlockchainType.evm]:{htlc:e.evm,name:"EVM"},[ee.BlockchainType.solana]:{htlc:e.solana,name:"Solana"},[ee.BlockchainType.starknet]:{htlc:e.starknet,name:"Starknet"},[ee.BlockchainType.sui]:{htlc:e.sui,name:"Sui"},[ee.BlockchainType.bitcoin]:{htlc:e.bitcoin,name:"Bitcoin"}}[t];return n?n.htlc?b.Ok(void 0):b.Err(`${n.name} HTLC is required for swap initiation. Please provide ${n.name.toLowerCase()}HTLC when initializing garden.`):b.Err(`Unsupported blockchain type for swap initiation: ${t}`)},V_=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),q_=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),G_=Buffer.concat([V_,q_]),W_=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),Zp={failedToCreateInternalPubkey:"failed to create internal pubkey"};function Xp(){const t=pe.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),e=or.pointMultiply(Buffer.concat([Buffer.from("04","hex"),G_]),t);if(!e)throw new Error(Zp.failedToCreateInternalPubkey);const r=or.pointAdd(W_,e);if(!r)throw new Error(Zp.failedToCreateInternalPubkey);return $_(Buffer.from(r))}var Yr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ow(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}),r}var Fe={},wt={},Xs={},Zc={};Zc.byteLength=X_;Zc.toByteArray=J_;Zc.fromByteArray=tT;var Vr=[],tr=[],K_=typeof Uint8Array<"u"?Uint8Array:Array,Lu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var ni=0,Z_=Lu.length;ni<Z_;++ni)Vr[ni]=Lu[ni],tr[Lu.charCodeAt(ni)]=ni;tr[45]=62;tr[95]=63;function aw(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function X_(t){var e=aw(t),r=e[0],n=e[1];return(r+n)*3/4-n}function Y_(t,e,r){return(e+r)*3/4-r}function J_(t){var e,r=aw(t),n=r[0],s=r[1],i=new K_(Y_(t,n,s)),o=0,a=s>0?n-4:n,c;for(c=0;c<a;c+=4)e=tr[t.charCodeAt(c)]<<18|tr[t.charCodeAt(c+1)]<<12|tr[t.charCodeAt(c+2)]<<6|tr[t.charCodeAt(c+3)],i[o++]=e>>16&255,i[o++]=e>>8&255,i[o++]=e&255;return s===2&&(e=tr[t.charCodeAt(c)]<<2|tr[t.charCodeAt(c+1)]>>4,i[o++]=e&255),s===1&&(e=tr[t.charCodeAt(c)]<<10|tr[t.charCodeAt(c+1)]<<4|tr[t.charCodeAt(c+2)]>>2,i[o++]=e>>8&255,i[o++]=e&255),i}function Q_(t){return Vr[t>>18&63]+Vr[t>>12&63]+Vr[t>>6&63]+Vr[t&63]}function eT(t,e,r){for(var n,s=[],i=e;i<r;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(Q_(n));return s.join("")}function tT(t){for(var e,r=t.length,n=r%3,s=[],i=16383,o=0,a=r-n;o<a;o+=i)s.push(eT(t,o,o+i>a?a:o+i));return n===1?(e=t[r-1],s.push(Vr[e>>2]+Vr[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],s.push(Vr[e>>10]+Vr[e>>4&63]+Vr[e<<2&63]+"=")),s.join("")}var fh={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */fh.read=function(t,e,r,n,s){var i,o,a=s*8-n-1,c=(1<<a)-1,u=c>>1,l=-7,d=r?s-1:0,h=r?-1:1,f=t[e+d];for(d+=h,i=f&(1<<-l)-1,f>>=-l,l+=a;l>0;i=i*256+t[e+d],d+=h,l-=8);for(o=i&(1<<-l)-1,i>>=-l,l+=n;l>0;o=o*256+t[e+d],d+=h,l-=8);if(i===0)i=1-u;else{if(i===c)return o?NaN:(f?-1:1)*(1/0);o=o+Math.pow(2,n),i=i-u}return(f?-1:1)*o*Math.pow(2,i-n)};fh.write=function(t,e,r,n,s,i){var o,a,c,u=i*8-s-1,l=(1<<u)-1,d=l>>1,h=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:i-1,m=n?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=l):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+d>=1?e+=h/c:e+=h*Math.pow(2,1-d),e*c>=2&&(o++,c/=2),o+d>=l?(a=0,o=l):o+d>=1?(a=(e*c-1)*Math.pow(2,s),o=o+d):(a=e*Math.pow(2,d-1)*Math.pow(2,s),o=0));s>=8;t[r+f]=a&255,f+=m,a/=256,s-=8);for(o=o<<s|a,u+=s;u>0;t[r+f]=o&255,f+=m,o/=256,u-=8);t[r+f-m]|=g*128};/*!
47
- * The buffer module from node.js, for the browser.
48
- *
49
- * @author Feross Aboukhadijeh <https://feross.org>
50
- * @license MIT
51
- */(function(t){const e=Zc,r=fh,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=a,t.SlowBuffer=_,t.INSPECT_MAX_BYTES=50;const s=2147483647;t.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 w=new Uint8Array(1),p={foo:function(){return 42}};return Object.setPrototypeOf(p,Uint8Array.prototype),Object.setPrototypeOf(w,p),w.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(w){if(w>s)throw new RangeError('The value "'+w+'" is invalid for option "size"');const p=new Uint8Array(w);return Object.setPrototypeOf(p,a.prototype),p}function a(w,p,y){if(typeof w=="number"){if(typeof p=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return d(w)}return c(w,p,y)}a.poolSize=8192;function c(w,p,y){if(typeof w=="string")return h(w,p);if(ArrayBuffer.isView(w))return m(w);if(w==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof w);if(Et(w,ArrayBuffer)||w&&Et(w.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Et(w,SharedArrayBuffer)||w&&Et(w.buffer,SharedArrayBuffer)))return g(w,p,y);if(typeof w=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const A=w.valueOf&&w.valueOf();if(A!=null&&A!==w)return a.from(A,p,y);const B=v(w);if(B)return B;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof w[Symbol.toPrimitive]=="function")return a.from(w[Symbol.toPrimitive]("string"),p,y);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof w)}a.from=function(w,p,y){return c(w,p,y)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function u(w){if(typeof w!="number")throw new TypeError('"size" argument must be of type number');if(w<0)throw new RangeError('The value "'+w+'" is invalid for option "size"')}function l(w,p,y){return u(w),w<=0?o(w):p!==void 0?typeof y=="string"?o(w).fill(p,y):o(w).fill(p):o(w)}a.alloc=function(w,p,y){return l(w,p,y)};function d(w){return u(w),o(w<0?0:S(w)|0)}a.allocUnsafe=function(w){return d(w)},a.allocUnsafeSlow=function(w){return d(w)};function h(w,p){if((typeof p!="string"||p==="")&&(p="utf8"),!a.isEncoding(p))throw new TypeError("Unknown encoding: "+p);const y=E(w,p)|0;let A=o(y);const B=A.write(w,p);return B!==y&&(A=A.slice(0,B)),A}function f(w){const p=w.length<0?0:S(w.length)|0,y=o(p);for(let A=0;A<p;A+=1)y[A]=w[A]&255;return y}function m(w){if(Et(w,Uint8Array)){const p=new Uint8Array(w);return g(p.buffer,p.byteOffset,p.byteLength)}return f(w)}function g(w,p,y){if(p<0||w.byteLength<p)throw new RangeError('"offset" is outside of buffer bounds');if(w.byteLength<p+(y||0))throw new RangeError('"length" is outside of buffer bounds');let A;return p===void 0&&y===void 0?A=new Uint8Array(w):y===void 0?A=new Uint8Array(w,p):A=new Uint8Array(w,p,y),Object.setPrototypeOf(A,a.prototype),A}function v(w){if(a.isBuffer(w)){const p=S(w.length)|0,y=o(p);return y.length===0||w.copy(y,0,0,p),y}if(w.length!==void 0)return typeof w.length!="number"||Bn(w.length)?o(0):f(w);if(w.type==="Buffer"&&Array.isArray(w.data))return f(w.data)}function S(w){if(w>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return w|0}function _(w){return+w!=w&&(w=0),a.alloc(+w)}a.isBuffer=function(p){return p!=null&&p._isBuffer===!0&&p!==a.prototype},a.compare=function(p,y){if(Et(p,Uint8Array)&&(p=a.from(p,p.offset,p.byteLength)),Et(y,Uint8Array)&&(y=a.from(y,y.offset,y.byteLength)),!a.isBuffer(p)||!a.isBuffer(y))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(p===y)return 0;let A=p.length,B=y.length;for(let M=0,V=Math.min(A,B);M<V;++M)if(p[M]!==y[M]){A=p[M],B=y[M];break}return A<B?-1:B<A?1:0},a.isEncoding=function(p){switch(String(p).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(p,y){if(!Array.isArray(p))throw new TypeError('"list" argument must be an Array of Buffers');if(p.length===0)return a.alloc(0);let A;if(y===void 0)for(y=0,A=0;A<p.length;++A)y+=p[A].length;const B=a.allocUnsafe(y);let M=0;for(A=0;A<p.length;++A){let V=p[A];if(Et(V,Uint8Array))M+V.length>B.length?(a.isBuffer(V)||(V=a.from(V)),V.copy(B,M)):Uint8Array.prototype.set.call(B,V,M);else if(a.isBuffer(V))V.copy(B,M);else throw new TypeError('"list" argument must be an Array of Buffers');M+=V.length}return B};function E(w,p){if(a.isBuffer(w))return w.length;if(ArrayBuffer.isView(w)||Et(w,ArrayBuffer))return w.byteLength;if(typeof w!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof w);const y=w.length,A=arguments.length>2&&arguments[2]===!0;if(!A&&y===0)return 0;let B=!1;for(;;)switch(p){case"ascii":case"latin1":case"binary":return y;case"utf8":case"utf-8":return Cr(w).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return y*2;case"hex":return y>>>1;case"base64":return $r(w).length;default:if(B)return A?-1:Cr(w).length;p=(""+p).toLowerCase(),B=!0}}a.byteLength=E;function x(w,p,y){let A=!1;if((p===void 0||p<0)&&(p=0),p>this.length||((y===void 0||y>this.length)&&(y=this.length),y<=0)||(y>>>=0,p>>>=0,y<=p))return"";for(w||(w="utf8");;)switch(w){case"hex":return T(this,p,y);case"utf8":case"utf-8":return N(this,p,y);case"ascii":return te(this,p,y);case"latin1":case"binary":return H(this,p,y);case"base64":return U(this,p,y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,p,y);default:if(A)throw new TypeError("Unknown encoding: "+w);w=(w+"").toLowerCase(),A=!0}}a.prototype._isBuffer=!0;function O(w,p,y){const A=w[p];w[p]=w[y],w[y]=A}a.prototype.swap16=function(){const p=this.length;if(p%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let y=0;y<p;y+=2)O(this,y,y+1);return this},a.prototype.swap32=function(){const p=this.length;if(p%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let y=0;y<p;y+=4)O(this,y,y+3),O(this,y+1,y+2);return this},a.prototype.swap64=function(){const p=this.length;if(p%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let y=0;y<p;y+=8)O(this,y,y+7),O(this,y+1,y+6),O(this,y+2,y+5),O(this,y+3,y+4);return this},a.prototype.toString=function(){const p=this.length;return p===0?"":arguments.length===0?N(this,0,p):x.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(p){if(!a.isBuffer(p))throw new TypeError("Argument must be a Buffer");return this===p?!0:a.compare(this,p)===0},a.prototype.inspect=function(){let p="";const y=t.INSPECT_MAX_BYTES;return p=this.toString("hex",0,y).replace(/(.{2})/g,"$1 ").trim(),this.length>y&&(p+=" ... "),"<Buffer "+p+">"},n&&(a.prototype[n]=a.prototype.inspect),a.prototype.compare=function(p,y,A,B,M){if(Et(p,Uint8Array)&&(p=a.from(p,p.offset,p.byteLength)),!a.isBuffer(p))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof p);if(y===void 0&&(y=0),A===void 0&&(A=p?p.length:0),B===void 0&&(B=0),M===void 0&&(M=this.length),y<0||A>p.length||B<0||M>this.length)throw new RangeError("out of range index");if(B>=M&&y>=A)return 0;if(B>=M)return-1;if(y>=A)return 1;if(y>>>=0,A>>>=0,B>>>=0,M>>>=0,this===p)return 0;let V=M-B,ge=A-y;const He=Math.min(V,ge),$e=this.slice(B,M),De=p.slice(y,A);for(let xe=0;xe<He;++xe)if($e[xe]!==De[xe]){V=$e[xe],ge=De[xe];break}return V<ge?-1:ge<V?1:0};function P(w,p,y,A,B){if(w.length===0)return-1;if(typeof y=="string"?(A=y,y=0):y>2147483647?y=2147483647:y<-2147483648&&(y=-2147483648),y=+y,Bn(y)&&(y=B?0:w.length-1),y<0&&(y=w.length+y),y>=w.length){if(B)return-1;y=w.length-1}else if(y<0)if(B)y=0;else return-1;if(typeof p=="string"&&(p=a.from(p,A)),a.isBuffer(p))return p.length===0?-1:$(w,p,y,A,B);if(typeof p=="number")return p=p&255,typeof Uint8Array.prototype.indexOf=="function"?B?Uint8Array.prototype.indexOf.call(w,p,y):Uint8Array.prototype.lastIndexOf.call(w,p,y):$(w,[p],y,A,B);throw new TypeError("val must be string, number or Buffer")}function $(w,p,y,A,B){let M=1,V=w.length,ge=p.length;if(A!==void 0&&(A=String(A).toLowerCase(),A==="ucs2"||A==="ucs-2"||A==="utf16le"||A==="utf-16le")){if(w.length<2||p.length<2)return-1;M=2,V/=2,ge/=2,y/=2}function He(De,xe){return M===1?De[xe]:De.readUInt16BE(xe*M)}let $e;if(B){let De=-1;for($e=y;$e<V;$e++)if(He(w,$e)===He(p,De===-1?0:$e-De)){if(De===-1&&(De=$e),$e-De+1===ge)return De*M}else De!==-1&&($e-=$e-De),De=-1}else for(y+ge>V&&(y=V-ge),$e=y;$e>=0;$e--){let De=!0;for(let xe=0;xe<ge;xe++)if(He(w,$e+xe)!==He(p,xe)){De=!1;break}if(De)return $e}return-1}a.prototype.includes=function(p,y,A){return this.indexOf(p,y,A)!==-1},a.prototype.indexOf=function(p,y,A){return P(this,p,y,A,!0)},a.prototype.lastIndexOf=function(p,y,A){return P(this,p,y,A,!1)};function z(w,p,y,A){y=Number(y)||0;const B=w.length-y;A?(A=Number(A),A>B&&(A=B)):A=B;const M=p.length;A>M/2&&(A=M/2);let V;for(V=0;V<A;++V){const ge=parseInt(p.substr(V*2,2),16);if(Bn(ge))return V;w[y+V]=ge}return V}function C(w,p,y,A){return vt(Cr(p,w.length-y),w,y,A)}function Y(w,p,y,A){return vt(cs(p),w,y,A)}function W(w,p,y,A){return vt($r(p),w,y,A)}function K(w,p,y,A){return vt(q(p,w.length-y),w,y,A)}a.prototype.write=function(p,y,A,B){if(y===void 0)B="utf8",A=this.length,y=0;else if(A===void 0&&typeof y=="string")B=y,A=this.length,y=0;else if(isFinite(y))y=y>>>0,isFinite(A)?(A=A>>>0,B===void 0&&(B="utf8")):(B=A,A=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const M=this.length-y;if((A===void 0||A>M)&&(A=M),p.length>0&&(A<0||y<0)||y>this.length)throw new RangeError("Attempt to write outside buffer bounds");B||(B="utf8");let V=!1;for(;;)switch(B){case"hex":return z(this,p,y,A);case"utf8":case"utf-8":return C(this,p,y,A);case"ascii":case"latin1":case"binary":return Y(this,p,y,A);case"base64":return W(this,p,y,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return K(this,p,y,A);default:if(V)throw new TypeError("Unknown encoding: "+B);B=(""+B).toLowerCase(),V=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function U(w,p,y){return p===0&&y===w.length?e.fromByteArray(w):e.fromByteArray(w.slice(p,y))}function N(w,p,y){y=Math.min(w.length,y);const A=[];let B=p;for(;B<y;){const M=w[B];let V=null,ge=M>239?4:M>223?3:M>191?2:1;if(B+ge<=y){let He,$e,De,xe;switch(ge){case 1:M<128&&(V=M);break;case 2:He=w[B+1],(He&192)===128&&(xe=(M&31)<<6|He&63,xe>127&&(V=xe));break;case 3:He=w[B+1],$e=w[B+2],(He&192)===128&&($e&192)===128&&(xe=(M&15)<<12|(He&63)<<6|$e&63,xe>2047&&(xe<55296||xe>57343)&&(V=xe));break;case 4:He=w[B+1],$e=w[B+2],De=w[B+3],(He&192)===128&&($e&192)===128&&(De&192)===128&&(xe=(M&15)<<18|(He&63)<<12|($e&63)<<6|De&63,xe>65535&&xe<1114112&&(V=xe))}}V===null?(V=65533,ge=1):V>65535&&(V-=65536,A.push(V>>>10&1023|55296),V=56320|V&1023),A.push(V),B+=ge}return Z(A)}const F=4096;function Z(w){const p=w.length;if(p<=F)return String.fromCharCode.apply(String,w);let y="",A=0;for(;A<p;)y+=String.fromCharCode.apply(String,w.slice(A,A+=F));return y}function te(w,p,y){let A="";y=Math.min(w.length,y);for(let B=p;B<y;++B)A+=String.fromCharCode(w[B]&127);return A}function H(w,p,y){let A="";y=Math.min(w.length,y);for(let B=p;B<y;++B)A+=String.fromCharCode(w[B]);return A}function T(w,p,y){const A=w.length;(!p||p<0)&&(p=0),(!y||y<0||y>A)&&(y=A);let B="";for(let M=p;M<y;++M)B+=ei[w[M]];return B}function L(w,p,y){const A=w.slice(p,y);let B="";for(let M=0;M<A.length-1;M+=2)B+=String.fromCharCode(A[M]+A[M+1]*256);return B}a.prototype.slice=function(p,y){const A=this.length;p=~~p,y=y===void 0?A:~~y,p<0?(p+=A,p<0&&(p=0)):p>A&&(p=A),y<0?(y+=A,y<0&&(y=0)):y>A&&(y=A),y<p&&(y=p);const B=this.subarray(p,y);return Object.setPrototypeOf(B,a.prototype),B};function G(w,p,y){if(w%1!==0||w<0)throw new RangeError("offset is not uint");if(w+p>y)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(p,y,A){p=p>>>0,y=y>>>0,A||G(p,y,this.length);let B=this[p],M=1,V=0;for(;++V<y&&(M*=256);)B+=this[p+V]*M;return B},a.prototype.readUintBE=a.prototype.readUIntBE=function(p,y,A){p=p>>>0,y=y>>>0,A||G(p,y,this.length);let B=this[p+--y],M=1;for(;y>0&&(M*=256);)B+=this[p+--y]*M;return B},a.prototype.readUint8=a.prototype.readUInt8=function(p,y){return p=p>>>0,y||G(p,1,this.length),this[p]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(p,y){return p=p>>>0,y||G(p,2,this.length),this[p]|this[p+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(p,y){return p=p>>>0,y||G(p,2,this.length),this[p]<<8|this[p+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(p,y){return p=p>>>0,y||G(p,4,this.length),(this[p]|this[p+1]<<8|this[p+2]<<16)+this[p+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(p,y){return p=p>>>0,y||G(p,4,this.length),this[p]*16777216+(this[p+1]<<16|this[p+2]<<8|this[p+3])},a.prototype.readBigUInt64LE=Cn(function(p){p=p>>>0,Se(p,"offset");const y=this[p],A=this[p+7];(y===void 0||A===void 0)&&Ue(p,this.length-8);const B=y+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24,M=this[++p]+this[++p]*2**8+this[++p]*2**16+A*2**24;return BigInt(B)+(BigInt(M)<<BigInt(32))}),a.prototype.readBigUInt64BE=Cn(function(p){p=p>>>0,Se(p,"offset");const y=this[p],A=this[p+7];(y===void 0||A===void 0)&&Ue(p,this.length-8);const B=y*2**24+this[++p]*2**16+this[++p]*2**8+this[++p],M=this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+A;return(BigInt(B)<<BigInt(32))+BigInt(M)}),a.prototype.readIntLE=function(p,y,A){p=p>>>0,y=y>>>0,A||G(p,y,this.length);let B=this[p],M=1,V=0;for(;++V<y&&(M*=256);)B+=this[p+V]*M;return M*=128,B>=M&&(B-=Math.pow(2,8*y)),B},a.prototype.readIntBE=function(p,y,A){p=p>>>0,y=y>>>0,A||G(p,y,this.length);let B=y,M=1,V=this[p+--B];for(;B>0&&(M*=256);)V+=this[p+--B]*M;return M*=128,V>=M&&(V-=Math.pow(2,8*y)),V},a.prototype.readInt8=function(p,y){return p=p>>>0,y||G(p,1,this.length),this[p]&128?(255-this[p]+1)*-1:this[p]},a.prototype.readInt16LE=function(p,y){p=p>>>0,y||G(p,2,this.length);const A=this[p]|this[p+1]<<8;return A&32768?A|4294901760:A},a.prototype.readInt16BE=function(p,y){p=p>>>0,y||G(p,2,this.length);const A=this[p+1]|this[p]<<8;return A&32768?A|4294901760:A},a.prototype.readInt32LE=function(p,y){return p=p>>>0,y||G(p,4,this.length),this[p]|this[p+1]<<8|this[p+2]<<16|this[p+3]<<24},a.prototype.readInt32BE=function(p,y){return p=p>>>0,y||G(p,4,this.length),this[p]<<24|this[p+1]<<16|this[p+2]<<8|this[p+3]},a.prototype.readBigInt64LE=Cn(function(p){p=p>>>0,Se(p,"offset");const y=this[p],A=this[p+7];(y===void 0||A===void 0)&&Ue(p,this.length-8);const B=this[p+4]+this[p+5]*2**8+this[p+6]*2**16+(A<<24);return(BigInt(B)<<BigInt(32))+BigInt(y+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24)}),a.prototype.readBigInt64BE=Cn(function(p){p=p>>>0,Se(p,"offset");const y=this[p],A=this[p+7];(y===void 0||A===void 0)&&Ue(p,this.length-8);const B=(y<<24)+this[++p]*2**16+this[++p]*2**8+this[++p];return(BigInt(B)<<BigInt(32))+BigInt(this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+A)}),a.prototype.readFloatLE=function(p,y){return p=p>>>0,y||G(p,4,this.length),r.read(this,p,!0,23,4)},a.prototype.readFloatBE=function(p,y){return p=p>>>0,y||G(p,4,this.length),r.read(this,p,!1,23,4)},a.prototype.readDoubleLE=function(p,y){return p=p>>>0,y||G(p,8,this.length),r.read(this,p,!0,52,8)},a.prototype.readDoubleBE=function(p,y){return p=p>>>0,y||G(p,8,this.length),r.read(this,p,!1,52,8)};function I(w,p,y,A,B,M){if(!a.isBuffer(w))throw new TypeError('"buffer" argument must be a Buffer instance');if(p>B||p<M)throw new RangeError('"value" argument is out of bounds');if(y+A>w.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(p,y,A,B){if(p=+p,y=y>>>0,A=A>>>0,!B){const ge=Math.pow(2,8*A)-1;I(this,p,y,A,ge,0)}let M=1,V=0;for(this[y]=p&255;++V<A&&(M*=256);)this[y+V]=p/M&255;return y+A},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(p,y,A,B){if(p=+p,y=y>>>0,A=A>>>0,!B){const ge=Math.pow(2,8*A)-1;I(this,p,y,A,ge,0)}let M=A-1,V=1;for(this[y+M]=p&255;--M>=0&&(V*=256);)this[y+M]=p/V&255;return y+A},a.prototype.writeUint8=a.prototype.writeUInt8=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,1,255,0),this[y]=p&255,y+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,2,65535,0),this[y]=p&255,this[y+1]=p>>>8,y+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,2,65535,0),this[y]=p>>>8,this[y+1]=p&255,y+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,4,4294967295,0),this[y+3]=p>>>24,this[y+2]=p>>>16,this[y+1]=p>>>8,this[y]=p&255,y+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,4,4294967295,0),this[y]=p>>>24,this[y+1]=p>>>16,this[y+2]=p>>>8,this[y+3]=p&255,y+4};function R(w,p,y,A,B){be(p,A,B,w,y,7);let M=Number(p&BigInt(4294967295));w[y++]=M,M=M>>8,w[y++]=M,M=M>>8,w[y++]=M,M=M>>8,w[y++]=M;let V=Number(p>>BigInt(32)&BigInt(4294967295));return w[y++]=V,V=V>>8,w[y++]=V,V=V>>8,w[y++]=V,V=V>>8,w[y++]=V,y}function j(w,p,y,A,B){be(p,A,B,w,y,7);let M=Number(p&BigInt(4294967295));w[y+7]=M,M=M>>8,w[y+6]=M,M=M>>8,w[y+5]=M,M=M>>8,w[y+4]=M;let V=Number(p>>BigInt(32)&BigInt(4294967295));return w[y+3]=V,V=V>>8,w[y+2]=V,V=V>>8,w[y+1]=V,V=V>>8,w[y]=V,y+8}a.prototype.writeBigUInt64LE=Cn(function(p,y=0){return R(this,p,y,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=Cn(function(p,y=0){return j(this,p,y,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(p,y,A,B){if(p=+p,y=y>>>0,!B){const He=Math.pow(2,8*A-1);I(this,p,y,A,He-1,-He)}let M=0,V=1,ge=0;for(this[y]=p&255;++M<A&&(V*=256);)p<0&&ge===0&&this[y+M-1]!==0&&(ge=1),this[y+M]=(p/V>>0)-ge&255;return y+A},a.prototype.writeIntBE=function(p,y,A,B){if(p=+p,y=y>>>0,!B){const He=Math.pow(2,8*A-1);I(this,p,y,A,He-1,-He)}let M=A-1,V=1,ge=0;for(this[y+M]=p&255;--M>=0&&(V*=256);)p<0&&ge===0&&this[y+M+1]!==0&&(ge=1),this[y+M]=(p/V>>0)-ge&255;return y+A},a.prototype.writeInt8=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,1,127,-128),p<0&&(p=255+p+1),this[y]=p&255,y+1},a.prototype.writeInt16LE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,2,32767,-32768),this[y]=p&255,this[y+1]=p>>>8,y+2},a.prototype.writeInt16BE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,2,32767,-32768),this[y]=p>>>8,this[y+1]=p&255,y+2},a.prototype.writeInt32LE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,4,2147483647,-2147483648),this[y]=p&255,this[y+1]=p>>>8,this[y+2]=p>>>16,this[y+3]=p>>>24,y+4},a.prototype.writeInt32BE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,4,2147483647,-2147483648),p<0&&(p=4294967295+p+1),this[y]=p>>>24,this[y+1]=p>>>16,this[y+2]=p>>>8,this[y+3]=p&255,y+4},a.prototype.writeBigInt64LE=Cn(function(p,y=0){return R(this,p,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=Cn(function(p,y=0){return j(this,p,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function J(w,p,y,A,B,M){if(y+A>w.length)throw new RangeError("Index out of range");if(y<0)throw new RangeError("Index out of range")}function se(w,p,y,A,B){return p=+p,y=y>>>0,B||J(w,p,y,4),r.write(w,p,y,A,23,4),y+4}a.prototype.writeFloatLE=function(p,y,A){return se(this,p,y,!0,A)},a.prototype.writeFloatBE=function(p,y,A){return se(this,p,y,!1,A)};function ue(w,p,y,A,B){return p=+p,y=y>>>0,B||J(w,p,y,8),r.write(w,p,y,A,52,8),y+8}a.prototype.writeDoubleLE=function(p,y,A){return ue(this,p,y,!0,A)},a.prototype.writeDoubleBE=function(p,y,A){return ue(this,p,y,!1,A)},a.prototype.copy=function(p,y,A,B){if(!a.isBuffer(p))throw new TypeError("argument should be a Buffer");if(A||(A=0),!B&&B!==0&&(B=this.length),y>=p.length&&(y=p.length),y||(y=0),B>0&&B<A&&(B=A),B===A||p.length===0||this.length===0)return 0;if(y<0)throw new RangeError("targetStart out of bounds");if(A<0||A>=this.length)throw new RangeError("Index out of range");if(B<0)throw new RangeError("sourceEnd out of bounds");B>this.length&&(B=this.length),p.length-y<B-A&&(B=p.length-y+A);const M=B-A;return this===p&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(y,A,B):Uint8Array.prototype.set.call(p,this.subarray(A,B),y),M},a.prototype.fill=function(p,y,A,B){if(typeof p=="string"){if(typeof y=="string"?(B=y,y=0,A=this.length):typeof A=="string"&&(B=A,A=this.length),B!==void 0&&typeof B!="string")throw new TypeError("encoding must be a string");if(typeof B=="string"&&!a.isEncoding(B))throw new TypeError("Unknown encoding: "+B);if(p.length===1){const V=p.charCodeAt(0);(B==="utf8"&&V<128||B==="latin1")&&(p=V)}}else typeof p=="number"?p=p&255:typeof p=="boolean"&&(p=Number(p));if(y<0||this.length<y||this.length<A)throw new RangeError("Out of range index");if(A<=y)return this;y=y>>>0,A=A===void 0?this.length:A>>>0,p||(p=0);let M;if(typeof p=="number")for(M=y;M<A;++M)this[M]=p;else{const V=a.isBuffer(p)?p:a.from(p,B),ge=V.length;if(ge===0)throw new TypeError('The value "'+p+'" is invalid for argument "value"');for(M=0;M<A-y;++M)this[M+y]=V[M%ge]}return this};const ce={};function ie(w,p,y){ce[w]=class extends y{constructor(){super(),Object.defineProperty(this,"message",{value:p.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${w}]`,this.stack,delete this.name}get code(){return w}set code(B){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:B,writable:!0})}toString(){return`${this.name} [${w}]: ${this.message}`}}}ie("ERR_BUFFER_OUT_OF_BOUNDS",function(w){return w?`${w} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),ie("ERR_INVALID_ARG_TYPE",function(w,p){return`The "${w}" argument must be of type number. Received type ${typeof p}`},TypeError),ie("ERR_OUT_OF_RANGE",function(w,p,y){let A=`The value of "${w}" is out of range.`,B=y;return Number.isInteger(y)&&Math.abs(y)>2**32?B=oe(String(y)):typeof y=="bigint"&&(B=String(y),(y>BigInt(2)**BigInt(32)||y<-(BigInt(2)**BigInt(32)))&&(B=oe(B)),B+="n"),A+=` It must be ${p}. Received ${B}`,A},RangeError);function oe(w){let p="",y=w.length;const A=w[0]==="-"?1:0;for(;y>=A+4;y-=3)p=`_${w.slice(y-3,y)}${p}`;return`${w.slice(0,y)}${p}`}function me(w,p,y){Se(p,"offset"),(w[p]===void 0||w[p+y]===void 0)&&Ue(p,w.length-(y+1))}function be(w,p,y,A,B,M){if(w>y||w<p){const V=typeof p=="bigint"?"n":"";let ge;throw p===0||p===BigInt(0)?ge=`>= 0${V} and < 2${V} ** ${(M+1)*8}${V}`:ge=`>= -(2${V} ** ${(M+1)*8-1}${V}) and < 2 ** ${(M+1)*8-1}${V}`,new ce.ERR_OUT_OF_RANGE("value",ge,w)}me(A,B,M)}function Se(w,p){if(typeof w!="number")throw new ce.ERR_INVALID_ARG_TYPE(p,"number",w)}function Ue(w,p,y){throw Math.floor(w)!==w?(Se(w,y),new ce.ERR_OUT_OF_RANGE("offset","an integer",w)):p<0?new ce.ERR_BUFFER_OUT_OF_BOUNDS:new ce.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${p}`,w)}const Lt=/[^+/0-9A-Za-z-_]/g;function et(w){if(w=w.split("=")[0],w=w.trim().replace(Lt,""),w.length<2)return"";for(;w.length%4!==0;)w=w+"=";return w}function Cr(w,p){p=p||1/0;let y;const A=w.length;let B=null;const M=[];for(let V=0;V<A;++V){if(y=w.charCodeAt(V),y>55295&&y<57344){if(!B){if(y>56319){(p-=3)>-1&&M.push(239,191,189);continue}else if(V+1===A){(p-=3)>-1&&M.push(239,191,189);continue}B=y;continue}if(y<56320){(p-=3)>-1&&M.push(239,191,189),B=y;continue}y=(B-55296<<10|y-56320)+65536}else B&&(p-=3)>-1&&M.push(239,191,189);if(B=null,y<128){if((p-=1)<0)break;M.push(y)}else if(y<2048){if((p-=2)<0)break;M.push(y>>6|192,y&63|128)}else if(y<65536){if((p-=3)<0)break;M.push(y>>12|224,y>>6&63|128,y&63|128)}else if(y<1114112){if((p-=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 cs(w){const p=[];for(let y=0;y<w.length;++y)p.push(w.charCodeAt(y)&255);return p}function q(w,p){let y,A,B;const M=[];for(let V=0;V<w.length&&!((p-=2)<0);++V)y=w.charCodeAt(V),A=y>>8,B=y%256,M.push(B),M.push(A);return M}function $r(w){return e.toByteArray(et(w))}function vt(w,p,y,A){let B;for(B=0;B<A&&!(B+y>=p.length||B>=w.length);++B)p[B+y]=w[B];return B}function Et(w,p){return w instanceof p||w!=null&&w.constructor!=null&&w.constructor.name!=null&&w.constructor.name===p.name}function Bn(w){return w!==w}const ei=function(){const w="0123456789abcdef",p=new Array(256);for(let y=0;y<16;++y){const A=y*16;for(let B=0;B<16;++B)p[A+B]=w[y]+w[B]}return p}();function Cn(w){return typeof BigInt>"u"?Cv:w}function Cv(){throw new Error("BigInt not supported")}})(Xs);var Wo={Array:function(t){return t!=null&&t.constructor===Array},Boolean:function(t){return typeof t=="boolean"},Function:function(t){return typeof t=="function"},Nil:function(t){return t==null},Number:function(t){return typeof t=="number"},Object:function(t){return typeof t=="object"},String:function(t){return typeof t=="string"},"":function(){return!0}};Wo.Null=Wo.Nil;for(var Yp in Wo)Wo[Yp].toJSON=(function(t){return t}).bind(null,Yp);var dh=Wo,_s=dh;function cw(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function hh(t){return _s.Nil(t)?"":cw(t.constructor)}function rT(t){return _s.Function(t)?"":_s.String(t)?JSON.stringify(t):t&&_s.Object(t)?"":t}function ph(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function mc(t){return _s.Function(t)?t.toJSON?t.toJSON():cw(t):_s.Array(t)?"Array":t&&_s.Object(t)?"Object":t!==void 0?t:""}function uw(t,e,r){var n=rT(e);return"Expected "+mc(t)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function xn(t,e,r){r=r||hh(e),this.message=uw(t,e,r),ph(this,xn),this.__type=t,this.__value=e,this.__valueTypeName=r}xn.prototype=Object.create(Error.prototype);xn.prototype.constructor=xn;function nT(t,e,r,n,s){var i='" of type ';return e==="key"&&(i='" with key type '),uw('property "'+mc(r)+i+mc(t),n,s)}function Ei(t,e,r,n,s){t?(s=s||hh(n),this.message=nT(t,r,e,n,s)):this.message='Unexpected property "'+e+'"',ph(this,xn),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=s}Ei.prototype=Object.create(Error.prototype);Ei.prototype.constructor=xn;function sT(t,e){return new xn(t,{},e)}function iT(t,e,r){return t instanceof Ei?(e=e+"."+t.__property,t=new Ei(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof xn&&(t=new Ei(t.__type,e,r,t.__value,t.__valueTypeName)),ph(t),t}var lw={TfTypeError:xn,TfPropertyTypeError:Ei,tfCustomError:sT,tfSubError:iT,tfJSON:mc,getValueTypeName:hh},Hu,Jp;function oT(){if(Jp)return Hu;Jp=1;var t=dh,e=lw;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 z=P.toJSON();function C(Y){if(!P(Y))return!1;if(Y.length===$)return!0;throw e.tfCustomError(z+"(Length: "+$+")",z+"(Length: "+Y.length+")")}return C.toJSON=function(){return z},C}var i=s.bind(null,t.Array),o=s.bind(null,r),a=s.bind(null,n),c=s.bind(null,t.String);function u(P,$,z){z=z||t.Number;function C(Y,W){return z(Y,W)&&Y>P&&Y<$}return C.toJSON=function(){return`${z.toJSON()} between [${P}, ${$}]`},C}var l=Math.pow(2,53)-1;function d(P){return typeof P=="number"&&isFinite(P)}function h(P){return P<<24>>24===P}function f(P){return P<<16>>16===P}function m(P){return(P|0)===P}function g(P){return typeof P=="number"&&P>=-l&&P<=l&&Math.floor(P)===P}function v(P){return(P&255)===P}function S(P){return(P&65535)===P}function _(P){return P>>>0===P}function E(P){return typeof P=="number"&&P>=0&&P<=l&&Math.floor(P)===P}var x={ArrayN:i,Buffer:r,BufferN:o,Finite:d,Hex:n,HexN:a,Int8:h,Int16:f,Int32:m,Int53:g,Range:u,StringN:c,UInt8:v,UInt16:S,UInt32:_,UInt53:E};for(var O in x)x[O].toJSON=(function(P){return P}).bind(null,O);return Hu=x,Hu}var ba=lw,at=dh,rn=ba.tfJSON,fw=ba.TfTypeError,dw=ba.TfPropertyTypeError,eo=ba.tfSubError,aT=ba.getValueTypeName,yn={arrayOf:function(e,r){e=Dr(e),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 _t(e,o,i)}catch(c){throw eo(c,a)}})}return n.toJSON=function(){var s="["+rn(e)+"]";return r.length!==void 0?s+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(s+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),s},n},maybe:function t(e){e=Dr(e);function r(n,s){return at.Nil(n)||e(n,s,t)}return r.toJSON=function(){return"?"+rn(e)},r},map:function(e,r){e=Dr(e),r&&(r=Dr(r));function n(s,i){if(!at.Object(s)||at.Nil(s))return!1;for(var o in s){try{r&&_t(r,o,i)}catch(c){throw eo(c,o,"key")}try{var a=s[o];_t(e,a,i)}catch(c){throw eo(c,o)}}return!0}return r?n.toJSON=function(){return"{"+rn(r)+": "+rn(e)+"}"}:n.toJSON=function(){return"{"+rn(e)+"}"},n},object:function(e){var r={};for(var n in e)r[n]=Dr(e[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],u=i[a];_t(c,u,o)}}catch(l){throw eo(l,a)}if(o){for(a in i)if(!r[a])throw new dw(void 0,a)}return!0}return s.toJSON=function(){return rn(r)},s},anyOf:function(){var e=[].slice.call(arguments).map(Dr);function r(n,s){return e.some(function(i){try{return _t(i,n,s)}catch{return!1}})}return r.toJSON=function(){return e.map(rn).join("|")},r},allOf:function(){var e=[].slice.call(arguments).map(Dr);function r(n,s){return e.every(function(i){try{return _t(i,n,s)}catch{return!1}})}return r.toJSON=function(){return e.map(rn).join(" & ")},r},quacksLike:function(e){function r(n){return e===aT(n)}return r.toJSON=function(){return e},r},tuple:function(){var e=[].slice.call(arguments).map(Dr);function r(n,s){return at.Nil(n)||at.Nil(n.length)||s&&n.length!==e.length?!1:e.every(function(i,o){try{return _t(i,n[o],s)}catch(a){throw eo(a,o)}})}return r.toJSON=function(){return"("+e.map(rn).join(", ")+")"},r},value:function(e){function r(n){return n===e}return r.toJSON=function(){return e},r}};yn.oneOf=yn.anyOf;function Dr(t){if(at.String(t))return t[0]==="?"?yn.maybe(t.slice(1)):at[t]||yn.quacksLike(t);if(t&&at.Object(t)){if(at.Array(t)){if(t.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return yn.arrayOf(t[0])}return yn.object(t)}else if(at.Function(t))return t;return yn.value(t)}function _t(t,e,r,n){if(at.Function(t)){if(t(e,r))return!0;throw new fw(n||t,e)}return _t(Dr(t),e,r)}for(var es in at)_t[es]=at[es];for(es in yn)_t[es]=yn[es];var Qp=oT();for(es in Qp)_t[es]=Qp[es];_t.compile=Dr;_t.TfTypeError=fw;_t.TfPropertyTypeError=dw;var cT=_t;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.oneOf=t.Null=t.BufferN=t.Function=t.UInt32=t.UInt8=t.tuple=t.maybe=t.Hex=t.Buffer=t.String=t.Boolean=t.Array=t.Number=t.Hash256bit=t.Hash160bit=t.Buffer256bit=t.isTaptree=t.isTapleaf=t.TAPLEAF_VERSION_MASK=t.Satoshi=t.isPoint=t.stacksEqual=t.typeforce=void 0;const e=Xs;t.typeforce=cT;const r=e.Buffer.alloc(32,0),n=e.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function s(l,d){return l.length!==d.length?!1:l.every((h,f)=>h.equals(d[f]))}t.stacksEqual=s;function i(l){if(!e.Buffer.isBuffer(l)||l.length<33)return!1;const d=l[0],h=l.slice(1,33);if(h.compare(r)===0||h.compare(n)>=0)return!1;if((d===2||d===3)&&l.length===33)return!0;const f=l.slice(33);return f.compare(r)===0||f.compare(n)>=0?!1:d===4&&l.length===65}t.isPoint=i;const o=21*1e14;function a(l){return t.typeforce.UInt53(l)&&l<=o}t.Satoshi=a,t.TAPLEAF_VERSION_MASK=254;function c(l){return!l||!("output"in l)||!e.Buffer.isBuffer(l.output)?!1:l.version!==void 0?(l.version&t.TAPLEAF_VERSION_MASK)===l.version:!0}t.isTapleaf=c;function u(l){return(0,t.Array)(l)?l.length!==2?!1:l.every(d=>u(d)):c(l)}t.isTaptree=u,t.Buffer256bit=t.typeforce.BufferN(32),t.Hash160bit=t.typeforce.BufferN(20),t.Hash256bit=t.typeforce.BufferN(32),t.Number=t.typeforce.Number,t.Array=t.typeforce.Array,t.Boolean=t.typeforce.Boolean,t.String=t.typeforce.String,t.Buffer=t.typeforce.Buffer,t.Hex=t.typeforce.Hex,t.maybe=t.typeforce.maybe,t.tuple=t.typeforce.tuple,t.UInt8=t.typeforce.UInt8,t.UInt32=t.typeforce.UInt32,t.Function=t.typeforce.Function,t.BufferN=t.typeforce.BufferN,t.Null=t.typeforce.Null,t.oneOf=t.typeforce.oneOf})(wt);var wa={},ct={};Object.defineProperty(ct,"__esModule",{value:!0});ct.BufferReader=ct.BufferWriter=ct.cloneBuffer=ct.reverseBuffer=ct.writeUInt64LE=ct.readUInt64LE=ct.varuint=void 0;const Ts=wt,{typeforce:hw}=Ts,Ko=Wm;ct.varuint=Ko;function pw(t,e){if(typeof t!="number")throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function yw(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,pw(n+r,9007199254740991),n+r}ct.readUInt64LE=yw;function mw(t,e,r){return pw(e,9007199254740991),t.writeInt32LE(e&-1,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}ct.writeUInt64LE=mw;function uT(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n<t.length/2;n++)r=t[n],t[n]=t[e],t[e]=r,e--;return t}ct.reverseBuffer=uT;function lT(t){const e=Buffer.allocUnsafe(t.length);return t.copy(e),e}ct.cloneBuffer=lT;class yh{static withCapacity(e){return new yh(Buffer.alloc(e))}constructor(e,r=0){this.buffer=e,this.offset=r,hw(Ts.tuple(Ts.Buffer,Ts.UInt32),[e,r])}writeUInt8(e){this.offset=this.buffer.writeUInt8(e,this.offset)}writeInt32(e){this.offset=this.buffer.writeInt32LE(e,this.offset)}writeUInt32(e){this.offset=this.buffer.writeUInt32LE(e,this.offset)}writeUInt64(e){this.offset=mw(this.buffer,e,this.offset)}writeVarInt(e){Ko.encode(e,this.buffer,this.offset),this.offset+=Ko.encode.bytes}writeSlice(e){if(this.buffer.length<this.offset+e.length)throw new Error("Cannot write slice out of bounds");this.offset+=e.copy(this.buffer,this.offset)}writeVarSlice(e){this.writeVarInt(e.length),this.writeSlice(e)}writeVector(e){this.writeVarInt(e.length),e.forEach(r=>this.writeVarSlice(r))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}ct.BufferWriter=yh;class fT{constructor(e,r=0){this.buffer=e,this.offset=r,hw(Ts.tuple(Ts.Buffer,Ts.UInt32),[e,r])}readUInt8(){const e=this.buffer.readUInt8(this.offset);return this.offset++,e}readInt32(){const e=this.buffer.readInt32LE(this.offset);return this.offset+=4,e}readUInt32(){const e=this.buffer.readUInt32LE(this.offset);return this.offset+=4,e}readUInt64(){const e=yw(this.buffer,this.offset);return this.offset+=8,e}readVarInt(){const e=Ko.decode(this.buffer,this.offset);return this.offset+=Ko.decode.bytes,e}readSlice(e){if(this.buffer.length<this.offset+e)throw new Error("Cannot read slice out of bounds");const r=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,r}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const e=this.readVarInt(),r=[];for(let n=0;n<e;n++)r.push(this.readVarSlice());return r}}ct.BufferReader=fT;var as={};const dT=ow(Y6);var Ci={},$t={},It={},mh={},Xc={};Object.defineProperty(Xc,"__esModule",{value:!0});Xc.crypto=void 0;Xc.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;(function(t){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(t,"__esModule",{value:!0}),t.wrapXOFConstructorWithOpts=t.wrapConstructorWithOpts=t.wrapConstructor=t.Hash=t.nextTick=t.swap32IfBE=t.byteSwapIfBE=t.swap8IfBE=t.isLE=void 0,t.isBytes=r,t.anumber=n,t.abytes=s,t.ahash=i,t.aexists=o,t.aoutput=a,t.u8=c,t.u32=u,t.clean=l,t.createView=d,t.rotr=h,t.rotl=f,t.byteSwap=m,t.byteSwap32=g,t.bytesToHex=_,t.hexToBytes=O,t.asyncLoop=$,t.utf8ToBytes=z,t.bytesToUtf8=C,t.toBytes=Y,t.kdfInputToBytes=W,t.concatBytes=K,t.checkOpts=U,t.createHasher=F,t.createOptHasher=Z,t.createXOFer=te,t.randomBytes=H;const e=Xc;function r(T){return T instanceof Uint8Array||ArrayBuffer.isView(T)&&T.constructor.name==="Uint8Array"}function n(T){if(!Number.isSafeInteger(T)||T<0)throw new Error("positive integer expected, got "+T)}function s(T,...L){if(!r(T))throw new Error("Uint8Array expected");if(L.length>0&&!L.includes(T.length))throw new Error("Uint8Array expected of length "+L+", got length="+T.length)}function i(T){if(typeof T!="function"||typeof T.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");n(T.outputLen),n(T.blockLen)}function o(T,L=!0){if(T.destroyed)throw new Error("Hash instance has been destroyed");if(L&&T.finished)throw new Error("Hash#digest() has already been called")}function a(T,L){s(T);const G=L.outputLen;if(T.length<G)throw new Error("digestInto() expects output buffer of length at least "+G)}function c(T){return new Uint8Array(T.buffer,T.byteOffset,T.byteLength)}function u(T){return new Uint32Array(T.buffer,T.byteOffset,Math.floor(T.byteLength/4))}function l(...T){for(let L=0;L<T.length;L++)T[L].fill(0)}function d(T){return new DataView(T.buffer,T.byteOffset,T.byteLength)}function h(T,L){return T<<32-L|T>>>L}function f(T,L){return T<<L|T>>>32-L>>>0}t.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function m(T){return T<<24&4278190080|T<<8&16711680|T>>>8&65280|T>>>24&255}t.swap8IfBE=t.isLE?T=>T:T=>m(T),t.byteSwapIfBE=t.swap8IfBE;function g(T){for(let L=0;L<T.length;L++)T[L]=m(T[L]);return T}t.swap32IfBE=t.isLE?T=>T:g;const v=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",S=Array.from({length:256},(T,L)=>L.toString(16).padStart(2,"0"));function _(T){if(s(T),v)return T.toHex();let L="";for(let G=0;G<T.length;G++)L+=S[T[G]];return L}const E={_0:48,_9:57,A:65,F:70,a:97,f:102};function x(T){if(T>=E._0&&T<=E._9)return T-E._0;if(T>=E.A&&T<=E.F)return T-(E.A-10);if(T>=E.a&&T<=E.f)return T-(E.a-10)}function O(T){if(typeof T!="string")throw new Error("hex string expected, got "+typeof T);if(v)return Uint8Array.fromHex(T);const L=T.length,G=L/2;if(L%2)throw new Error("hex string expected, got unpadded hex of length "+L);const I=new Uint8Array(G);for(let R=0,j=0;R<G;R++,j+=2){const J=x(T.charCodeAt(j)),se=x(T.charCodeAt(j+1));if(J===void 0||se===void 0){const ue=T[j]+T[j+1];throw new Error('hex string expected, got non-hex character "'+ue+'" at index '+j)}I[R]=J*16+se}return I}const P=async()=>{};t.nextTick=P;async function $(T,L,G){let I=Date.now();for(let R=0;R<T;R++){G(R);const j=Date.now()-I;j>=0&&j<L||(await(0,t.nextTick)(),I+=j)}}function z(T){if(typeof T!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(T))}function C(T){return new TextDecoder().decode(T)}function Y(T){return typeof T=="string"&&(T=z(T)),s(T),T}function W(T){return typeof T=="string"&&(T=z(T)),s(T),T}function K(...T){let L=0;for(let I=0;I<T.length;I++){const R=T[I];s(R),L+=R.length}const G=new Uint8Array(L);for(let I=0,R=0;I<T.length;I++){const j=T[I];G.set(j,R),R+=j.length}return G}function U(T,L){if(L!==void 0&&{}.toString.call(L)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(T,L)}class N{}t.Hash=N;function F(T){const L=I=>T().update(Y(I)).digest(),G=T();return L.outputLen=G.outputLen,L.blockLen=G.blockLen,L.create=()=>T(),L}function Z(T){const L=(I,R)=>T(R).update(Y(I)).digest(),G=T({});return L.outputLen=G.outputLen,L.blockLen=G.blockLen,L.create=I=>T(I),L}function te(T){const L=(I,R)=>T(R).update(Y(I)).digest(),G=T({});return L.outputLen=G.outputLen,L.blockLen=G.blockLen,L.create=I=>T(I),L}t.wrapConstructor=F,t.wrapConstructorWithOpts=Z,t.wrapXOFConstructorWithOpts=te;function H(T=32){if(e.crypto&&typeof e.crypto.getRandomValues=="function")return e.crypto.getRandomValues(new Uint8Array(T));if(e.crypto&&typeof e.crypto.randomBytes=="function")return Uint8Array.from(e.crypto.randomBytes(T));throw new Error("crypto.getRandomValues must be defined")}})(mh);Object.defineProperty(It,"__esModule",{value:!0});It.SHA512_IV=It.SHA384_IV=It.SHA224_IV=It.SHA256_IV=It.HashMD=void 0;It.setBigUint64=gw;It.Chi=hT;It.Maj=pT;const Ur=mh;function gw(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function hT(t,e,r){return t&e^~t&r}function pT(t,e,r){return t&e^t&r^e&r}class yT extends Ur.Hash{constructor(e,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=(0,Ur.createView)(this.buffer)}update(e){(0,Ur.aexists)(this),e=(0,Ur.toBytes)(e),(0,Ur.abytes)(e);const{view:r,buffer:n,blockLen:s}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=(0,Ur.createView)(e);for(;s<=i-o;o+=s)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){(0,Ur.aexists)(this),(0,Ur.aoutput)(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:o}=this;r[o++]=128,(0,Ur.clean)(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let d=o;d<s;d++)r[d]=0;gw(n,s-8,BigInt(this.length*8),i),this.process(n,0);const a=(0,Ur.createView)(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<u;d++)a.setUint32(4*d,l[d],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:s,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=s,e.pos=a,s%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}}It.HashMD=yT;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($t,"__esModule",{value:!0});$t.ripemd160=$t.RIPEMD160=$t.md5=$t.MD5=$t.sha1=$t.SHA1=void 0;const Is=It,ut=mh,ii=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Un=new Uint32Array(80);class bw extends Is.HashMD{constructor(){super(64,20,8,!1),this.A=ii[0]|0,this.B=ii[1]|0,this.C=ii[2]|0,this.D=ii[3]|0,this.E=ii[4]|0}get(){const{A:e,B:r,C:n,D:s,E:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0}process(e,r){for(let c=0;c<16;c++,r+=4)Un[c]=e.getUint32(r,!1);for(let c=16;c<80;c++)Un[c]=(0,ut.rotl)(Un[c-3]^Un[c-8]^Un[c-14]^Un[c-16],1);let{A:n,B:s,C:i,D:o,E:a}=this;for(let c=0;c<80;c++){let u,l;c<20?(u=(0,Is.Chi)(s,i,o),l=1518500249):c<40?(u=s^i^o,l=1859775393):c<60?(u=(0,Is.Maj)(s,i,o),l=2400959708):(u=s^i^o,l=3395469782);const d=(0,ut.rotl)(n,5)+u+a+l+Un[c]|0;a=o,o=i,i=(0,ut.rotl)(s,30),s=n,n=d}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)(Un)}destroy(){this.set(0,0,0,0,0),(0,ut.clean)(this.buffer)}}$t.SHA1=bw;$t.sha1=(0,ut.createHasher)(()=>new bw);const mT=Math.pow(2,32),gT=Array.from({length:64},(t,e)=>Math.floor(mT*Math.abs(Math.sin(e+1)))),Ua=ii.slice(0,4),Du=new Uint32Array(16);class ww extends Is.HashMD{constructor(){super(64,16,8,!0),this.A=Ua[0]|0,this.B=Ua[1]|0,this.C=Ua[2]|0,this.D=Ua[3]|0}get(){const{A:e,B:r,C:n,D:s}=this;return[e,r,n,s]}set(e,r,n,s){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0}process(e,r){for(let a=0;a<16;a++,r+=4)Du[a]=e.getUint32(r,!0);let{A:n,B:s,C:i,D:o}=this;for(let a=0;a<64;a++){let c,u,l;a<16?(c=(0,Is.Chi)(s,i,o),u=a,l=[7,12,17,22]):a<32?(c=(0,Is.Chi)(o,s,i),u=(5*a+1)%16,l=[5,9,14,20]):a<48?(c=s^i^o,u=(3*a+5)%16,l=[4,11,16,23]):(c=i^(s|~o),u=7*a%16,l=[6,10,15,21]),c=c+n+gT[a]+Du[u],n=o,o=i,i=s,s=s+(0,ut.rotl)(c,l[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)(Du)}destroy(){this.set(0,0,0,0),(0,ut.clean)(this.buffer)}}$t.MD5=ww;$t.md5=(0,ut.createHasher)(()=>new ww);const bT=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),vw=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),wT=vw.map(t=>(9*t+5)%16),Ew=(()=>{const r=[[vw],[wT]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>bT[i]));return r})(),Sw=Ew[0],Aw=Ew[1],xw=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),vT=Sw.map((t,e)=>t.map(r=>xw[e][r])),ET=Aw.map((t,e)=>t.map(r=>xw[e][r])),ST=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),AT=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function ey(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}const Ma=new Uint32Array(16);class kw extends Is.HashMD{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:r,h2:n,h3:s,h4:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=s|0,this.h4=i|0}process(e,r){for(let f=0;f<16;f++,r+=4)Ma[f]=e.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,o=i,a=this.h2|0,c=a,u=this.h3|0,l=u,d=this.h4|0,h=d;for(let f=0;f<5;f++){const m=4-f,g=ST[f],v=AT[f],S=Sw[f],_=Aw[f],E=vT[f],x=ET[f];for(let O=0;O<16;O++){const P=(0,ut.rotl)(n+ey(f,i,a,u)+Ma[S[O]]+g,E[O])+d|0;n=d,d=u,u=(0,ut.rotl)(a,10)|0,a=i,i=P}for(let O=0;O<16;O++){const P=(0,ut.rotl)(s+ey(m,o,c,l)+Ma[_[O]]+v,x[O])+h|0;s=h,h=l,l=(0,ut.rotl)(c,10)|0,c=o,o=P}}this.set(this.h1+a+l|0,this.h2+u+h|0,this.h3+d+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){(0,ut.clean)(Ma)}destroy(){this.destroyed=!0,(0,ut.clean)(this.buffer),this.set(0,0,0,0,0)}}$t.RIPEMD160=kw;$t.ripemd160=(0,ut.createHasher)(()=>new kw);Object.defineProperty(Ci,"__esModule",{value:!0});Ci.sha1=Ci.SHA1=void 0;const _w=$t;Ci.SHA1=_w.SHA1;Ci.sha1=_w.sha1;const Tw=ow(LS);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.taggedHash=t.TAGGED_HASH_PREFIXES=t.TAGS=t.hash256=t.hash160=t.sha256=t.sha1=t.ripemd160=void 0;const e=dT,r=Ci,n=Tw;function s(l){return Buffer.from((0,e.ripemd160)(Uint8Array.from(l)))}t.ripemd160=s;function i(l){return Buffer.from((0,r.sha1)(Uint8Array.from(l)))}t.sha1=i;function o(l){return Buffer.from((0,n.sha256)(Uint8Array.from(l)))}t.sha256=o;function a(l){return Buffer.from((0,e.ripemd160)((0,n.sha256)(Uint8Array.from(l))))}t.hash160=a;function c(l){return Buffer.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(l))))}t.hash256=c,t.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],t.TAGGED_HASH_PREFIXES={"BIP0340/challenge":Buffer.from([123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124,123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124]),"BIP0340/aux":Buffer.from([241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144,241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144]),"BIP0340/nonce":Buffer.from([7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47,7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47]),TapLeaf:Buffer.from([174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238,174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238]),TapBranch:Buffer.from([25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21,25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21]),TapSighash:Buffer.from([244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49,244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49]),TapTweak:Buffer.from([232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233,232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233]),"KeyAgg list":Buffer.from([72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240,72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240]),"KeyAgg coefficient":Buffer.from([191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129,191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129])};function u(l,d){return o(Buffer.concat([t.TAGGED_HASH_PREFIXES[l],d]))}t.taggedHash=u})(as);var zu={},En={};Object.defineProperty(En,"__esModule",{value:!0});En.encode=En.decode=En.check=void 0;function xT(t){if(t.length<8||t.length>72||t[0]!==48||t[1]!==t.length-2||t[2]!==2)return!1;const e=t[3];if(e===0||5+e>=t.length||t[4+e]!==2)return!1;const r=t[5+e];return!(r===0||6+e+r!==t.length||t[4]&128||e>1&&t[4]===0&&!(t[5]&128)||t[e+6]&128||r>1&&t[e+6]===0&&!(t[e+7]&128))}En.check=xT;function kT(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(t[0]!==48)throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(t[2]!==2)throw new Error("Expected DER integer");const e=t[3];if(e===0)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(t[4+e]!==2)throw new Error("Expected DER integer (2)");const r=t[5+e];if(r===0)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(t[4]&128)throw new Error("R value is negative");if(e>1&&t[4]===0&&!(t[5]&128))throw new Error("R value excessively padded");if(t[e+6]&128)throw new Error("S value is negative");if(r>1&&t[e+6]===0&&!(t[e+7]&128))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}}En.decode=kT;function _T(t,e){const r=t.length,n=e.length;if(r===0)throw new Error("R length is zero");if(n===0)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(t[0]&128)throw new Error("R value is negative");if(e[0]&128)throw new Error("S value is negative");if(r>1&&t[0]===0&&!(t[1]&128))throw new Error("R value excessively padded");if(n>1&&e[0]===0&&!(e[1]&128))throw new Error("S value excessively padded");const s=Buffer.allocUnsafe(6+r+n);return s[0]=48,s[1]=s.length-2,s[2]=2,s[3]=t.length,t.copy(s,4),s[4+r]=2,s[5+r]=e.length,e.copy(s,6+r),s}En.encode=_T;var Ls={};Object.defineProperty(Ls,"__esModule",{value:!0});Ls.REVERSE_OPS=Ls.OPS=void 0;const Qf={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};Ls.OPS=Qf;const Iw={};Ls.REVERSE_OPS=Iw;for(const t of Object.keys(Qf)){const e=Qf[t];Iw[e]=t}var ts={};Object.defineProperty(ts,"__esModule",{value:!0});ts.decode=ts.encode=ts.encodingLength=void 0;const Yn=Ls;function Pw(t){return t<Yn.OPS.OP_PUSHDATA1?1:t<=255?2:t<=65535?3:5}ts.encodingLength=Pw;function TT(t,e,r){const n=Pw(e);return n===1?t.writeUInt8(e,r):n===2?(t.writeUInt8(Yn.OPS.OP_PUSHDATA1,r),t.writeUInt8(e,r+1)):n===3?(t.writeUInt8(Yn.OPS.OP_PUSHDATA2,r),t.writeUInt16LE(e,r+1)):(t.writeUInt8(Yn.OPS.OP_PUSHDATA4,r),t.writeUInt32LE(e,r+1)),n}ts.encode=TT;function IT(t,e){const r=t.readUInt8(e);let n,s;if(r<Yn.OPS.OP_PUSHDATA1)n=r,s=1;else if(r===Yn.OPS.OP_PUSHDATA1){if(e+2>t.length)return null;n=t.readUInt8(e+1),s=2}else if(r===Yn.OPS.OP_PUSHDATA2){if(e+3>t.length)return null;n=t.readUInt16LE(e+1),s=3}else{if(e+5>t.length)return null;if(r!==Yn.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=t.readUInt32LE(e+1),s=5}return{opcode:r,number:n,size:s}}ts.decode=IT;var $i={};Object.defineProperty($i,"__esModule",{value:!0});$i.encode=$i.decode=void 0;function PT(t,e,r){e=e||4,r=r===void 0?!0:r;const n=t.length;if(n===0)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&!(t[n-1]&127)&&(n<=1||!(t[n-2]&128)))throw new Error("Non-minimally encoded script number");if(n===5){const i=t.readUInt32LE(0),o=t.readUInt8(4);return o&128?-((o&-129)*4294967296+i):o*4294967296+i}let s=0;for(let i=0;i<n;++i)s|=t[i]<<8*i;return t[n-1]&128?-(s&~(128<<8*(n-1))):s}$i.decode=PT;function OT(t){return t>2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}function BT(t){let e=Math.abs(t);const r=OT(e),n=Buffer.allocUnsafe(r),s=t<0;for(let i=0;i<r;++i)n.writeUInt8(e&255,i),e>>=8;return n[r-1]&128?n.writeUInt8(s?128:0,r-1):s&&(n[r-1]|=128),n}$i.encode=BT;var fs={},ty;function CT(){if(ty)return fs;ty=1,Object.defineProperty(fs,"__esModule",{value:!0}),fs.encode=fs.decode=void 0;const t=En,e=Yt(),r=wt,{typeforce:n}=r,s=Buffer.alloc(1,0);function i(u){let l=0;for(;u[l]===0;)++l;return l===u.length?s:(u=u.slice(l),u[0]&128?Buffer.concat([s,u],1+u.length):u)}function o(u){u[0]===0&&(u=u.slice(1));const l=Buffer.alloc(32,0),d=Math.max(0,32-u.length);return u.copy(l,d),l}function a(u){const l=u.readUInt8(u.length-1);if(!(0,e.isDefinedHashType)(l))throw new Error("Invalid hashType "+l);const d=t.decode(u.slice(0,-1)),h=o(d.r),f=o(d.s);return{signature:Buffer.concat([h,f],64),hashType:l}}fs.decode=a;function c(u,l){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:u,hashType:l}),!(0,e.isDefinedHashType)(l))throw new Error("Invalid hashType "+l);const d=Buffer.allocUnsafe(1);d.writeUInt8(l,0);const h=i(u.slice(0,32)),f=i(u.slice(32,64));return Buffer.concat([t.encode(h,f),d])}return fs.encode=c,fs}var ry;function Yt(){return ry||(ry=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.signature=t.number=t.isCanonicalScriptSignature=t.isDefinedHashType=t.isCanonicalPubKey=t.toStack=t.fromASM=t.toASM=t.decompile=t.compile=t.countNonPushOnlyOPs=t.isPushOnly=t.OPS=void 0;const e=En,r=Ls;Object.defineProperty(t,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=ts,s=$i,i=CT(),o=wt,{typeforce:a}=o,c=r.OPS.OP_RESERVED;function u(C){return o.Number(C)&&(C===r.OPS.OP_0||C>=r.OPS.OP_1&&C<=r.OPS.OP_16||C===r.OPS.OP_1NEGATE)}function l(C){return o.Buffer(C)||u(C)}function d(C){return o.Array(C)&&C.every(l)}t.isPushOnly=d;function h(C){return C.length-C.filter(l).length}t.countNonPushOnlyOPs=h;function f(C){if(C.length===0)return r.OPS.OP_0;if(C.length===1){if(C[0]>=1&&C[0]<=16)return c+C[0];if(C[0]===129)return r.OPS.OP_1NEGATE}}function m(C){return Buffer.isBuffer(C)}function g(C){return o.Array(C)}function v(C){return Buffer.isBuffer(C)}function S(C){if(m(C))return C;a(o.Array,C);const Y=C.reduce((U,N)=>v(N)?N.length===1&&f(N)!==void 0?U+1:U+n.encodingLength(N.length)+N.length:U+1,0),W=Buffer.allocUnsafe(Y);let K=0;if(C.forEach(U=>{if(v(U)){const N=f(U);if(N!==void 0){W.writeUInt8(N,K),K+=1;return}K+=n.encode(W,U.length,K),U.copy(W,K),K+=U.length}else W.writeUInt8(U,K),K+=1}),K!==W.length)throw new Error("Could not decode chunks");return W}t.compile=S;function _(C){if(g(C))return C;a(o.Buffer,C);const Y=[];let W=0;for(;W<C.length;){const K=C[W];if(K>r.OPS.OP_0&&K<=r.OPS.OP_PUSHDATA4){const U=n.decode(C,W);if(U===null||(W+=U.size,W+U.number>C.length))return null;const N=C.slice(W,W+U.number);W+=U.number;const F=f(N);F!==void 0?Y.push(F):Y.push(N)}else Y.push(K),W+=1}return Y}t.decompile=_;function E(C){if(m(C)&&(C=_(C)),!C)throw new Error("Could not convert invalid chunks to ASM");return C.map(Y=>{if(v(Y)){const W=f(Y);if(W===void 0)return Y.toString("hex");Y=W}return r.REVERSE_OPS[Y]}).join(" ")}t.toASM=E;function x(C){return a(o.String,C),S(C.split(" ").map(Y=>r.OPS[Y]!==void 0?r.OPS[Y]:(a(o.Hex,Y),Buffer.from(Y,"hex"))))}t.fromASM=x;function O(C){return C=_(C),a(d,C),C.map(Y=>v(Y)?Y:Y===r.OPS.OP_0?Buffer.allocUnsafe(0):s.encode(Y-c))}t.toStack=O;function P(C){return o.isPoint(C)}t.isCanonicalPubKey=P;function $(C){const Y=C&-129;return Y>0&&Y<4}t.isDefinedHashType=$;function z(C){return!Buffer.isBuffer(C)||!$(C[C.length-1])?!1:e.check(C.slice(0,-1))}t.isCanonicalScriptSignature=z,t.number=s,t.signature=i}(zu)),zu}Object.defineProperty(wa,"__esModule",{value:!0});wa.Transaction=void 0;const Ze=ct,St=as,ny=Yt(),$T=Yt(),we=wt,{typeforce:Mr}=we;function hr(t){const e=t.length;return Ze.varuint.encodingLength(e)+e}function RT(t){const e=t.length;return Ze.varuint.encodingLength(e)+t.reduce((r,n)=>r+hr(n),0)}const Dn=Buffer.allocUnsafe(0),Vu=[],qu=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),sy=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),NT=Buffer.from("ffffffffffffffff","hex"),UT={script:Dn,valueBuffer:NT};function MT(t){return t.value!==void 0}let Br=class ke{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(e,r){const n=new Ze.BufferReader(e),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 l=0;l<c;++l)s.ins.push({hash:n.readSlice(32),index:n.readUInt32(),script:n.readVarSlice(),sequence:n.readUInt32(),witness:Vu});const u=n.readVarInt();for(let l=0;l<u;++l)s.outs.push({value:n.readUInt64(),script:n.readVarSlice()});if(a){for(let l=0;l<c;++l)s.ins[l].witness=n.readVector();if(!s.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(s.locktime=n.readUInt32(),r)return s;if(n.offset!==e.length)throw new Error("Transaction has unexpected data");return s}static fromHex(e){return ke.fromBuffer(Buffer.from(e,"hex"),!1)}static isCoinbaseHash(e){Mr(we.Hash256bit,e);for(let r=0;r<32;++r)if(e[r]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&ke.isCoinbaseHash(this.ins[0].hash)}addInput(e,r,n,s){return Mr(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:e,index:r,script:s||Dn,sequence:n,witness:Vu})-1}addOutput(e,r){return Mr(we.tuple(we.Buffer,we.Satoshi),arguments),this.outs.push({script:e,value:r})-1}hasWitnesses(){return this.ins.some(e=>e.witness.length!==0)}stripWitnesses(){this.ins.forEach(e=>{e.witness=Vu})}weight(){const e=this.byteLength(!1),r=this.byteLength(!0);return e*3+r}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(e=!0){const r=e&&this.hasWitnesses();return(r?10:8)+Ze.varuint.encodingLength(this.ins.length)+Ze.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,s)=>n+40+hr(s.script),0)+this.outs.reduce((n,s)=>n+8+hr(s.script),0)+(r?this.ins.reduce((n,s)=>n+RT(s.witness),0):0)}clone(){const e=new ke;return e.version=this.version,e.locktime=this.locktime,e.ins=this.ins.map(r=>({hash:r.hash,index:r.index,script:r.script,sequence:r.sequence,witness:r.witness})),e.outs=this.outs.map(r=>({script:r.script,value:r.value})),e}hashForSignature(e,r,n){if(Mr(we.tuple(we.UInt32,we.Buffer,we.Number),arguments),e>=this.ins.length)return sy;const s=ny.compile(ny.decompile(r).filter(a=>a!==$T.OPS.OP_CODESEPARATOR)),i=this.clone();if((n&31)===ke.SIGHASH_NONE)i.outs=[],i.ins.forEach((a,c)=>{c!==e&&(a.sequence=0)});else if((n&31)===ke.SIGHASH_SINGLE){if(e>=this.outs.length)return sy;i.outs.length=e+1;for(let a=0;a<e;a++)i.outs[a]=UT;i.ins.forEach((a,c)=>{c!==e&&(a.sequence=0)})}n&ke.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[e]],i.ins[0].script=s):(i.ins.forEach(a=>{a.script=Dn}),i.ins[e].script=s);const o=Buffer.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(n,o.length-4),i.__toBuffer(o,0,!1),St.hash256(o)}hashForWitnessV1(e,r,n,s,i,o){if(console.log("hashForWitnessV1 :"),Mr(we.tuple(we.UInt32,Mr.arrayOf(we.Buffer),Mr.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,u=(s&ke.SIGHASH_INPUT_MASK)===ke.SIGHASH_ANYONECANPAY,l=a===ke.SIGHASH_NONE,d=a===ke.SIGHASH_SINGLE;let h=Dn,f=Dn,m=Dn,g=Dn,v=Dn;if(!u){let x=Ze.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(O=>{x.writeSlice(O.hash),x.writeUInt32(O.index)}),h=St.sha256(x.end()),x=Ze.BufferWriter.withCapacity(8*this.ins.length),n.forEach(O=>x.writeUInt64(O)),f=St.sha256(x.end()),console.log("prevOutScripts.map(varSliceSize).reduce((a, b) => a + b), :",r.map(hr).reduce((O,P)=>O+P)),x=Ze.BufferWriter.withCapacity(r.map(hr).reduce((O,P)=>O+P)),r.forEach(O=>x.writeVarSlice(O)),m=St.sha256(x.end()),x=Ze.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(O=>x.writeUInt32(O.sequence)),g=St.sha256(x.end())}if(l||d){if(d&&e<this.outs.length){const x=this.outs[e],O=Ze.BufferWriter.withCapacity(8+hr(x.script));O.writeUInt64(x.value),O.writeVarSlice(x.script),v=St.sha256(O.end())}}else{const x=this.outs.map(P=>8+hr(P.script)).reduce((P,$)=>P+$),O=Ze.BufferWriter.withCapacity(x);this.outs.forEach(P=>{O.writeUInt64(P.value),O.writeVarSlice(P.script)}),v=St.sha256(O.end())}const S=(i?2:0)+(o?1:0),_=174-(u?49:0)-(l?32:0)+(o?32:0)+(i?37:0),E=Ze.BufferWriter.withCapacity(_);if(E.writeUInt8(s),E.writeInt32(this.version),E.writeUInt32(this.locktime),E.writeSlice(h),E.writeSlice(f),E.writeSlice(m),E.writeSlice(g),l||d||E.writeSlice(v),E.writeUInt8(S),u){const x=this.ins[e];E.writeSlice(x.hash),E.writeUInt32(x.index),E.writeUInt64(n[e]),E.writeVarSlice(r[e]),E.writeUInt32(x.sequence)}else E.writeUInt32(e);if(o){const x=Ze.BufferWriter.withCapacity(hr(o));x.writeVarSlice(o),E.writeSlice(St.sha256(x.end()))}return d&&E.writeSlice(v),i&&(E.writeSlice(i),E.writeUInt8(0),E.writeUInt32(4294967295)),St.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),E.end()]))}hashForWitnessV0(e,r,n,s){Mr(we.tuple(we.UInt32,we.Buffer,we.Satoshi,we.UInt32),arguments);let i=Buffer.from([]),o,a=qu,c=qu,u=qu;if(s&ke.SIGHASH_ANYONECANPAY||(i=Buffer.allocUnsafe(36*this.ins.length),o=new Ze.BufferWriter(i,0),this.ins.forEach(d=>{o.writeSlice(d.hash),o.writeUInt32(d.index)}),c=St.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 Ze.BufferWriter(i,0),this.ins.forEach(d=>{o.writeUInt32(d.sequence)}),u=St.hash256(i)),(s&31)!==ke.SIGHASH_SINGLE&&(s&31)!==ke.SIGHASH_NONE){const d=this.outs.reduce((h,f)=>h+8+hr(f.script),0);i=Buffer.allocUnsafe(d),o=new Ze.BufferWriter(i,0),this.outs.forEach(h=>{o.writeUInt64(h.value),o.writeVarSlice(h.script)}),a=St.hash256(i)}else if((s&31)===ke.SIGHASH_SINGLE&&e<this.outs.length){const d=this.outs[e];i=Buffer.allocUnsafe(8+hr(d.script)),o=new Ze.BufferWriter(i,0),o.writeUInt64(d.value),o.writeVarSlice(d.script),a=St.hash256(i)}i=Buffer.allocUnsafe(156+hr(r)),o=new Ze.BufferWriter(i,0);const l=this.ins[e];return o.writeInt32(this.version),o.writeSlice(c),o.writeSlice(u),o.writeSlice(l.hash),o.writeUInt32(l.index),o.writeVarSlice(r),o.writeUInt64(n),o.writeUInt32(l.sequence),o.writeSlice(a),o.writeUInt32(this.locktime),o.writeUInt32(s),St.hash256(i)}getHash(e){return e&&this.isCoinbase()?Buffer.alloc(32,0):St.hash256(this.__toBuffer(void 0,void 0,e))}getId(){return(0,Ze.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(e,r){return this.__toBuffer(e,r,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(e,r){Mr(we.tuple(we.Number,we.Buffer),arguments),this.ins[e].script=r}setWitness(e,r){Mr(we.tuple(we.Number,[we.Buffer]),arguments),this.ins[e].witness=r}__toBuffer(e,r,n=!1){e||(e=Buffer.allocUnsafe(this.byteLength(n)));const s=new Ze.BufferWriter(e,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=>{MT(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?e.slice(r,s.offset):e}};wa.Transaction=Br;Br.DEFAULT_SEQUENCE=4294967295;Br.SIGHASH_DEFAULT=0;Br.SIGHASH_ALL=1;Br.SIGHASH_NONE=2;Br.SIGHASH_SINGLE=3;Br.SIGHASH_ANYONECANPAY=128;Br.SIGHASH_OUTPUT_MASK=3;Br.SIGHASH_INPUT_MASK=128;Br.ADVANCED_TRANSACTION_MARKER=0;Br.ADVANCED_TRANSACTION_FLAG=1;var _e={},va={};Object.defineProperty(va,"__esModule",{value:!0});const FT=9007199254740991;function gh(t){if(t<0||t>FT||t%1!==0)throw new RangeError("value out of range")}function uo(t,e,r){if(gh(t),e||(e=Buffer.allocUnsafe(Ow(t))),!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),t<253?(e.writeUInt8(t,r),Object.assign(uo,{bytes:1})):t<=65535?(e.writeUInt8(253,r),e.writeUInt16LE(t,r+1),Object.assign(uo,{bytes:3})):t<=4294967295?(e.writeUInt8(254,r),e.writeUInt32LE(t,r+1),Object.assign(uo,{bytes:5})):(e.writeUInt8(255,r),e.writeUInt32LE(t>>>0,r+1),e.writeUInt32LE(t/4294967296|0,r+5),Object.assign(uo,{bytes:9})),e}va.encode=uo;function lo(t,e){if(!Buffer.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");e||(e=0);const r=t.readUInt8(e);if(r<253)return Object.assign(lo,{bytes:1}),r;if(r===253)return Object.assign(lo,{bytes:3}),t.readUInt16LE(e+1);if(r===254)return Object.assign(lo,{bytes:5}),t.readUInt32LE(e+1);{Object.assign(lo,{bytes:9});const n=t.readUInt32LE(e+1),i=t.readUInt32LE(e+5)*4294967296+n;return gh(i),i}}va.decode=lo;function Ow(t){return gh(t),t<253?1:t<=65535?3:t<=4294967295?5:9}va.encodingLength=Ow;var Gu={},Yc={},gt={};Object.defineProperty(gt,"__esModule",{value:!0});gt.testnet=gt.regtest=gt.bitcoin=void 0;gt.bitcoin={messagePrefix:`Bitcoin Signed Message:
52
- `,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};gt.regtest={messagePrefix:`Bitcoin Signed Message:
53
- `,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};gt.testnet={messagePrefix:`Bitcoin Signed Message:
54
- `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var Kt={};Object.defineProperty(Kt,"__esModule",{value:!0});Kt.value=Kt.prop=void 0;function jT(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const n=r.call(this);return this[e]=n,n},set(n){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:n,writable:!0})}})}Kt.prop=jT;function LT(t){let e;return()=>(e!==void 0||(e=t()),e)}Kt.value=LT;Object.defineProperty(Yc,"__esModule",{value:!0});Yc.p2data=void 0;const HT=gt,tc=Yt(),Fr=wt,iy=Kt,oy=tc.OPS;function DT(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Fr.typeforce)({network:Fr.typeforce.maybe(Fr.typeforce.Object),output:Fr.typeforce.maybe(Fr.typeforce.Buffer),data:Fr.typeforce.maybe(Fr.typeforce.arrayOf(Fr.typeforce.Buffer))},t);const n={name:"embed",network:t.network||HT.bitcoin};if(iy.prop(n,"output",()=>{if(t.data)return tc.compile([oy.OP_RETURN].concat(t.data))}),iy.prop(n,"data",()=>{if(t.output)return tc.decompile(t.output).slice(1)}),e.validate&&t.output){const s=tc.decompile(t.output);if(s[0]!==oy.OP_RETURN)throw new TypeError("Output is invalid");if(!s.slice(1).every(Fr.typeforce.Buffer))throw new TypeError("Output is invalid");if(t.data&&!(0,Fr.stacksEqual)(t.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,t)}Yc.p2data=DT;var Jc={};Object.defineProperty(Jc,"__esModule",{value:!0});Jc.p2ms=void 0;const zT=gt,oi=Yt(),qe=wt,Mn=Kt,ai=oi.OPS,Fa=ai.OP_RESERVED;function VT(t,e){if(!t.input&&!t.output&&!(t.pubkeys&&t.m!==void 0)&&!t.signatures)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{});function r(c){return oi.isCanonicalScriptSignature(c)||(e.allowIncomplete&&c===ai.OP_0)!==void 0}(0,qe.typeforce)({network:qe.typeforce.maybe(qe.typeforce.Object),m:qe.typeforce.maybe(qe.typeforce.Number),n:qe.typeforce.maybe(qe.typeforce.Number),output:qe.typeforce.maybe(qe.typeforce.Buffer),pubkeys:qe.typeforce.maybe(qe.typeforce.arrayOf(qe.isPoint)),signatures:qe.typeforce.maybe(qe.typeforce.arrayOf(r)),input:qe.typeforce.maybe(qe.typeforce.Buffer)},t);const s={network:t.network||zT.bitcoin};let i=[],o=!1;function a(c){o||(o=!0,i=oi.decompile(c),s.m=i[0]-Fa,s.n=i[i.length-2]-Fa,s.pubkeys=i.slice(1,-2))}if(Mn.prop(s,"output",()=>{if(t.m&&s.n&&t.pubkeys)return oi.compile([].concat(Fa+t.m,t.pubkeys,Fa+s.n,ai.OP_CHECKMULTISIG))}),Mn.prop(s,"m",()=>{if(s.output)return a(s.output),s.m}),Mn.prop(s,"n",()=>{if(s.pubkeys)return s.pubkeys.length}),Mn.prop(s,"pubkeys",()=>{if(t.output)return a(t.output),s.pubkeys}),Mn.prop(s,"signatures",()=>{if(t.input)return oi.decompile(t.input).slice(1)}),Mn.prop(s,"input",()=>{if(t.signatures)return oi.compile([ai.OP_0].concat(t.signatures))}),Mn.prop(s,"witness",()=>{if(s.input)return[]}),Mn.prop(s,"name",()=>{if(!(!s.m||!s.n))return`p2ms(${s.m} of ${s.n})`}),e.validate){if(t.output){if(a(t.output),!qe.typeforce.Number(i[0]))throw new TypeError("Output is invalid");if(!qe.typeforce.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==ai.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,qe.isPoint)(c)))throw new TypeError("Output is invalid");if(t.m!==void 0&&t.m!==s.m)throw new TypeError("m mismatch");if(t.n!==void 0&&t.n!==s.n)throw new TypeError("n mismatch");if(t.pubkeys&&!(0,qe.stacksEqual)(t.pubkeys,s.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(t.n!==void 0&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(s.n=t.pubkeys.length,s.n<s.m)throw new TypeError("Pubkey count cannot be less than m")}if(t.signatures){if(t.signatures.length<s.m)throw new TypeError("Not enough signatures provided");if(t.signatures.length>s.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==ai.OP_0)throw new TypeError("Input is invalid");if(s.signatures.length===0||!s.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!(0,qe.stacksEqual)(t.signatures,s.signatures))throw new TypeError("Signature mismatch");if(t.m!==void 0&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(s,t)}Jc.p2ms=VT;var Qc={};Object.defineProperty(Qc,"__esModule",{value:!0});Qc.p2pk=void 0;const qT=gt,ci=Yt(),dr=wt,si=Kt,ay=ci.OPS;function GT(t,e){if(!t.input&&!t.output&&!t.pubkey&&!t.input&&!t.signature)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,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(ci.isCanonicalScriptSignature),input:dr.typeforce.maybe(dr.typeforce.Buffer)},t);const r=si.value(()=>ci.decompile(t.input)),s={name:"p2pk",network:t.network||qT.bitcoin};if(si.prop(s,"output",()=>{if(t.pubkey)return ci.compile([t.pubkey,ay.OP_CHECKSIG])}),si.prop(s,"pubkey",()=>{if(t.output)return t.output.slice(1,-1)}),si.prop(s,"signature",()=>{if(t.input)return r()[0]}),si.prop(s,"input",()=>{if(t.signature)return ci.compile([t.signature])}),si.prop(s,"witness",()=>{if(s.input)return[]}),e.validate){if(t.output){if(t.output[t.output.length-1]!==ay.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,dr.isPoint)(s.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(s.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(s.input))throw new TypeError("Signature mismatch");if(t.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!ci.isCanonicalScriptSignature(s.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(s,t)}Qc.p2pk=GT;var eu={};function WT(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r<e.length;r++)e[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=n}var o=t.length,a=t.charAt(0),c=Math.log(o)/Math.log(256),u=Math.log(256)/Math.log(o);function l(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var m=0,g=0,v=0,S=f.length;v!==S&&f[v]===0;)v++,m++;for(var _=(S-v)*u+1>>>0,E=new Uint8Array(_);v!==S;){for(var x=f[v],O=0,P=_-1;(x!==0||O<g)&&P!==-1;P--,O++)x+=256*E[P]>>>0,E[P]=x%o>>>0,x=x/o>>>0;if(x!==0)throw new Error("Non-zero carry");g=O,v++}for(var $=_-g;$!==_&&E[$]===0;)$++;for(var z=a.repeat(m);$<_;++$)z+=t.charAt(E[$]);return z}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;for(var m=0,g=0,v=0;f[m]===a;)g++,m++;for(var S=(f.length-m)*c+1>>>0,_=new Uint8Array(S);f[m];){var E=f.charCodeAt(m);if(E>255)return;var x=e[E];if(x===255)return;for(var O=0,P=S-1;(x!==0||O<v)&&P!==-1;P--,O++)x+=o*_[P]>>>0,_[P]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");v=O,m++}for(var $=S-v;$!==S&&_[$]===0;)$++;for(var z=new Uint8Array(g+(S-$)),C=g;$!==S;)z[C++]=_[$++];return z}function h(f){var m=d(f);if(m)return m;throw new Error("Non-base"+o+" character")}return{encode:l,decodeUnsafe:d,decode:h}}var KT=WT;const ZT=KT,XT="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var YT=ZT(XT),Wu=YT,JT=function(t){function e(i){var o=Uint8Array.from(i),a=t(o),c=o.length+4,u=new Uint8Array(c);return u.set(o,0),u.set(a.subarray(0,4),o.length),Wu.encode(u,c)}function r(i){var o=i.slice(0,-4),a=i.slice(-4),c=t(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=Wu.decodeUnsafe(i);if(o)return r(o)}function s(i){var o=Wu.decode(i),a=r(o);if(!a)throw new Error("Invalid checksum");return a}return{encode:e,decode:s,decodeUnsafe:n}},{sha256:cy}=Tw,QT=JT;function eI(t){return cy(cy(t))}var bh=QT(eI);Object.defineProperty(eu,"__esModule",{value:!0});eu.p2pkh=void 0;const Ku=as,tI=gt,ui=Yt(),At=wt,nn=Kt,uy=bh,Fn=ui.OPS;function rI(t,e){if(!t.address&&!t.hash&&!t.output&&!t.pubkey&&!t.input)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,At.typeforce)({network:At.typeforce.maybe(At.typeforce.Object),address:At.typeforce.maybe(At.typeforce.String),hash:At.typeforce.maybe(At.typeforce.BufferN(20)),output:At.typeforce.maybe(At.typeforce.BufferN(25)),pubkey:At.typeforce.maybe(At.isPoint),signature:At.typeforce.maybe(ui.isCanonicalScriptSignature),input:At.typeforce.maybe(At.typeforce.Buffer)},t);const r=nn.value(()=>{const o=Buffer.from(uy.decode(t.address)),a=o.readUInt8(0),c=o.slice(1);return{version:a,hash:c}}),n=nn.value(()=>ui.decompile(t.input)),s=t.network||tI.bitcoin,i={name:"p2pkh",network:s};if(nn.prop(i,"address",()=>{if(!i.hash)return;const o=Buffer.allocUnsafe(21);return o.writeUInt8(s.pubKeyHash,0),i.hash.copy(o,1),uy.encode(o)}),nn.prop(i,"hash",()=>{if(t.output)return t.output.slice(3,23);if(t.address)return r().hash;if(t.pubkey||i.pubkey)return Ku.hash160(t.pubkey||i.pubkey)}),nn.prop(i,"output",()=>{if(i.hash)return ui.compile([Fn.OP_DUP,Fn.OP_HASH160,i.hash,Fn.OP_EQUALVERIFY,Fn.OP_CHECKSIG])}),nn.prop(i,"pubkey",()=>{if(t.input)return n()[1]}),nn.prop(i,"signature",()=>{if(t.input)return n()[0]}),nn.prop(i,"input",()=>{if(t.pubkey&&t.signature)return ui.compile([t.signature,t.pubkey])}),nn.prop(i,"witness",()=>{if(i.input)return[]}),e.validate){let o=Buffer.from([]);if(t.address){if(r().version!==s.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");o=r().hash}if(t.hash){if(o.length>0&&!o.equals(t.hash))throw new TypeError("Hash mismatch");o=t.hash}if(t.output){if(t.output.length!==25||t.output[0]!==Fn.OP_DUP||t.output[1]!==Fn.OP_HASH160||t.output[2]!==20||t.output[23]!==Fn.OP_EQUALVERIFY||t.output[24]!==Fn.OP_CHECKSIG)throw new TypeError("Output is invalid");const a=t.output.slice(3,23);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(t.pubkey){const a=Ku.hash160(t.pubkey);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(t.input){const a=n();if(a.length!==2)throw new TypeError("Input is invalid");if(!ui.isCanonicalScriptSignature(a[0]))throw new TypeError("Input has invalid signature");if(!(0,At.isPoint)(a[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(a[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(a[1]))throw new TypeError("Pubkey mismatch");const c=Ku.hash160(a[1]);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)}eu.p2pkh=rI;var tu={};Object.defineProperty(tu,"__esModule",{value:!0});tu.p2sh=void 0;const ly=as,nI=gt,Hr=Yt(),Be=wt,jr=Kt,fy=bh,to=Hr.OPS;function sI(t,e){if(!t.address&&!t.hash&&!t.output&&!t.redeem&&!t.input)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Be.typeforce)({network:Be.typeforce.maybe(Be.typeforce.Object),address:Be.typeforce.maybe(Be.typeforce.String),hash:Be.typeforce.maybe(Be.typeforce.BufferN(20)),output:Be.typeforce.maybe(Be.typeforce.BufferN(23)),redeem:Be.typeforce.maybe({network:Be.typeforce.maybe(Be.typeforce.Object),output:Be.typeforce.maybe(Be.typeforce.Buffer),input:Be.typeforce.maybe(Be.typeforce.Buffer),witness:Be.typeforce.maybe(Be.typeforce.arrayOf(Be.typeforce.Buffer))}),input:Be.typeforce.maybe(Be.typeforce.Buffer),witness:Be.typeforce.maybe(Be.typeforce.arrayOf(Be.typeforce.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||nI.bitcoin);const n={network:r},s=jr.value(()=>{const a=Buffer.from(fy.decode(t.address)),c=a.readUInt8(0),u=a.slice(1);return{version:c,hash:u}}),i=jr.value(()=>Hr.decompile(t.input)),o=jr.value(()=>{const a=i(),c=a[a.length-1];return{network:r,output:c===to.OP_FALSE?Buffer.from([]):c,input:Hr.compile(a.slice(0,-1)),witness:t.witness||[]}});if(jr.prop(n,"address",()=>{if(!n.hash)return;const a=Buffer.allocUnsafe(21);return a.writeUInt8(n.network.scriptHash,0),n.hash.copy(a,1),fy.encode(a)}),jr.prop(n,"hash",()=>{if(t.output)return t.output.slice(2,22);if(t.address)return s().hash;if(n.redeem&&n.redeem.output)return ly.hash160(n.redeem.output)}),jr.prop(n,"output",()=>{if(n.hash)return Hr.compile([to.OP_HASH160,n.hash,to.OP_EQUAL])}),jr.prop(n,"redeem",()=>{if(t.input)return o()}),jr.prop(n,"input",()=>{if(!(!t.redeem||!t.redeem.input||!t.redeem.output))return Hr.compile([].concat(Hr.decompile(t.redeem.input),t.redeem.output))}),jr.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),jr.prop(n,"name",()=>{const a=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&a.push(n.redeem.name),a.join("-")}),e.validate){let a=Buffer.from([]);if(t.address){if(s().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(s().hash.length!==20)throw new TypeError("Invalid address");a=s().hash}if(t.hash){if(a.length>0&&!a.equals(t.hash))throw new TypeError("Hash mismatch");a=t.hash}if(t.output){if(t.output.length!==23||t.output[0]!==to.OP_HASH160||t.output[1]!==20||t.output[22]!==to.OP_EQUAL)throw new TypeError("Output is invalid");const u=t.output.slice(2,22);if(a.length>0&&!a.equals(u))throw new TypeError("Hash mismatch");a=u}const c=u=>{if(u.output){const l=Hr.decompile(u.output);if(!l||l.length<1)throw new TypeError("Redeem.output too short");if(u.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(Hr.countNonPushOnlyOPs(l)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const d=ly.hash160(u.output);if(a.length>0&&!a.equals(d))throw new TypeError("Hash mismatch");a=d}if(u.input){const l=u.input.length>0,d=u.witness&&u.witness.length>0;if(!l&&!d)throw new TypeError("Empty input");if(l&&d)throw new TypeError("Input and witness provided");if(l){const h=Hr.decompile(u.input);if(!Hr.isPushOnly(h))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const u=i();if(!u||u.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(o().output))throw new TypeError("Input is invalid");c(o())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const u=o();if(t.redeem.output&&!t.redeem.output.equals(u.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(u.input))throw new TypeError("Redeem.input mismatch")}c(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!(0,Be.stacksEqual)(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)}tu.p2sh=sI;var ru={},kn={};Object.defineProperty(kn,"__esModule",{value:!0});kn.bech32m=kn.bech32=void 0;const gc="qpzry9x8gf2tvdw0s3jn54khce6mua7l",Bw={};for(let t=0;t<gc.length;t++){const e=gc.charAt(t);Bw[e]=t}function Si(t){const e=t>>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function dy(t){let e=1;for(let r=0;r<t.length;++r){const n=t.charCodeAt(r);if(n<33||n>126)return"Invalid prefix ("+t+")";e=Si(e)^n>>5}e=Si(e);for(let r=0;r<t.length;++r){const n=t.charCodeAt(r);e=Si(e)^n&31}return e}function wh(t,e,r,n){let s=0,i=0;const o=(1<<r)-1,a=[];for(let c=0;c<t.length;++c)for(s=s<<e|t[c],i+=e;i>=r;)i-=r,a.push(s>>i&o);if(n)i>0&&a.push(s<<r-i&o);else{if(i>=e)return"Excess padding";if(s<<r-i&o)return"Non-zero padding"}return a}function iI(t){return wh(t,8,5,!0)}function oI(t){const e=wh(t,5,8,!1);if(Array.isArray(e))return e}function aI(t){const e=wh(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}function Cw(t){let e;t==="bech32"?e=1:e=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 u=dy(o);if(typeof u=="string")throw new Error(u);let l=o+"1";for(let d=0;d<a.length;++d){const h=a[d];if(h>>5)throw new Error("Non 5-bit word");u=Si(u)^h,l+=gc.charAt(h)}for(let d=0;d<6;++d)u=Si(u);u^=e;for(let d=0;d<6;++d){const h=u>>(5-d)*5&31;l+=gc.charAt(h)}return l}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(),u=o.toUpperCase();if(o!==c&&o!==u)return"Mixed-case string "+o;o=c;const l=o.lastIndexOf("1");if(l===-1)return"No separator character for "+o;if(l===0)return"Missing prefix for "+o;const d=o.slice(0,l),h=o.slice(l+1);if(h.length<6)return"Data too short";let f=dy(d);if(typeof f=="string")return f;const m=[];for(let g=0;g<h.length;++g){const v=h.charAt(g),S=Bw[v];if(S===void 0)return"Unknown character "+v;f=Si(f)^S,!(g+6>=h.length)&&m.push(S)}return f!==e?"Invalid checksum for "+o:{prefix:d,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:iI,fromWordsUnsafe:oI,fromWords:aI}}kn.bech32=Cw("bech32");kn.bech32m=Cw("bech32m");Object.defineProperty(ru,"__esModule",{value:!0});ru.p2wpkh=void 0;const Zu=as,cI=gt,rc=Yt(),tt=wt,jn=Kt,ja=kn,hy=rc.OPS,uI=Buffer.alloc(0);function lI(t,e){if(!t.address&&!t.hash&&!t.output&&!t.pubkey&&!t.witness)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,tt.typeforce)({address:tt.typeforce.maybe(tt.typeforce.String),hash:tt.typeforce.maybe(tt.typeforce.BufferN(20)),input:tt.typeforce.maybe(tt.typeforce.BufferN(0)),network:tt.typeforce.maybe(tt.typeforce.Object),output:tt.typeforce.maybe(tt.typeforce.BufferN(22)),pubkey:tt.typeforce.maybe(tt.isPoint),signature:tt.typeforce.maybe(rc.isCanonicalScriptSignature),witness:tt.typeforce.maybe(tt.typeforce.arrayOf(tt.typeforce.Buffer))},t);const r=jn.value(()=>{const i=ja.bech32.decode(t.address),o=i.words.shift(),a=ja.bech32.fromWords(i.words);return{version:o,prefix:i.prefix,data:Buffer.from(a)}}),n=t.network||cI.bitcoin,s={name:"p2wpkh",network:n};if(jn.prop(s,"address",()=>{if(!s.hash)return;const i=ja.bech32.toWords(s.hash);return i.unshift(0),ja.bech32.encode(n.bech32,i)}),jn.prop(s,"hash",()=>{if(t.output)return t.output.slice(2,22);if(t.address)return r().data;if(t.pubkey||s.pubkey)return Zu.hash160(t.pubkey||s.pubkey)}),jn.prop(s,"output",()=>{if(s.hash)return rc.compile([hy.OP_0,s.hash])}),jn.prop(s,"pubkey",()=>{if(t.pubkey)return t.pubkey;if(t.witness)return t.witness[1]}),jn.prop(s,"signature",()=>{if(t.witness)return t.witness[0]}),jn.prop(s,"input",()=>{if(s.witness)return uI}),jn.prop(s,"witness",()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]}),e.validate){let i=Buffer.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==20)throw new TypeError("Invalid address data");i=r().data}if(t.hash){if(i.length>0&&!i.equals(t.hash))throw new TypeError("Hash mismatch");i=t.hash}if(t.output){if(t.output.length!==22||t.output[0]!==hy.OP_0||t.output[1]!==20)throw new TypeError("Output is invalid");if(i.length>0&&!i.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");i=t.output.slice(2)}if(t.pubkey){const o=Zu.hash160(t.pubkey);if(i.length>0&&!i.equals(o))throw new TypeError("Hash mismatch");if(i=o,!(0,tt.isPoint)(t.pubkey)||t.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(t.witness.length!==2)throw new TypeError("Witness is invalid");if(!rc.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,tt.isPoint)(t.witness[1])||t.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const o=Zu.hash160(t.witness[1]);if(i.length>0&&!i.equals(o))throw new TypeError("Hash mismatch")}}return Object.assign(s,t)}ru.p2wpkh=lI;var nu={};Object.defineProperty(nu,"__esModule",{value:!0});nu.p2wsh=void 0;const py=as,fI=gt,fn=Yt(),Pe=wt,sn=Kt,La=kn,yy=fn.OPS,Xu=Buffer.alloc(0);function Ha(t){return!!(Buffer.isBuffer(t)&&t.length===65&&t[0]===4&&(0,Pe.isPoint)(t))}function dI(t,e){if(!t.address&&!t.hash&&!t.output&&!t.redeem&&!t.witness)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Pe.typeforce)({network:Pe.typeforce.maybe(Pe.typeforce.Object),address:Pe.typeforce.maybe(Pe.typeforce.String),hash:Pe.typeforce.maybe(Pe.typeforce.BufferN(32)),output:Pe.typeforce.maybe(Pe.typeforce.BufferN(34)),redeem:Pe.typeforce.maybe({input:Pe.typeforce.maybe(Pe.typeforce.Buffer),network:Pe.typeforce.maybe(Pe.typeforce.Object),output:Pe.typeforce.maybe(Pe.typeforce.Buffer),witness:Pe.typeforce.maybe(Pe.typeforce.arrayOf(Pe.typeforce.Buffer))}),input:Pe.typeforce.maybe(Pe.typeforce.BufferN(0)),witness:Pe.typeforce.maybe(Pe.typeforce.arrayOf(Pe.typeforce.Buffer))},t);const r=sn.value(()=>{const o=La.bech32.decode(t.address),a=o.words.shift(),c=La.bech32.fromWords(o.words);return{version:a,prefix:o.prefix,data:Buffer.from(c)}}),n=sn.value(()=>fn.decompile(t.redeem.input));let s=t.network;s||(s=t.redeem&&t.redeem.network||fI.bitcoin);const i={network:s};if(sn.prop(i,"address",()=>{if(!i.hash)return;const o=La.bech32.toWords(i.hash);return o.unshift(0),La.bech32.encode(s.bech32,o)}),sn.prop(i,"hash",()=>{if(t.output)return t.output.slice(2);if(t.address)return r().data;if(i.redeem&&i.redeem.output)return py.sha256(i.redeem.output)}),sn.prop(i,"output",()=>{if(i.hash)return fn.compile([yy.OP_0,i.hash])}),sn.prop(i,"redeem",()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:Xu,witness:t.witness.slice(0,-1)}}),sn.prop(i,"input",()=>{if(i.witness)return Xu}),sn.prop(i,"witness",()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const o=fn.toStack(n());return i.redeem=Object.assign({witness:o},t.redeem),i.redeem.input=Xu,[].concat(o,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)}),sn.prop(i,"name",()=>{const o=["p2wsh"];return i.redeem!==void 0&&i.redeem.name!==void 0&&o.push(i.redeem.name),o.join("-")}),e.validate){let o=Buffer.from([]);if(t.address){if(r().prefix!==s.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==32)throw new TypeError("Invalid address data");o=r().data}if(t.hash){if(o.length>0&&!o.equals(t.hash))throw new TypeError("Hash mismatch");o=t.hash}if(t.output){if(t.output.length!==34||t.output[0]!==yy.OP_0||t.output[1]!==32)throw new TypeError("Output is invalid");const a=t.output.slice(2);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(t.redeem){if(t.redeem.network&&t.redeem.network!==s)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){const a=fn.decompile(t.redeem.output);if(!a||a.length<1)throw new TypeError("Redeem.output is invalid");if(t.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(fn.countNonPushOnlyOPs(a)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const c=py.sha256(t.redeem.output);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch");o=c}if(t.redeem.input&&!fn.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!(0,Pe.stacksEqual)(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Ha)||t.redeem.output&&(fn.decompile(t.redeem.output)||[]).some(Ha))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const a=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(a))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Ha)||(fn.decompile(a)||[]).some(Ha))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(i,t)}nu.p2wsh=dI;var ro={},Hs={};Object.defineProperty(Hs,"__esModule",{value:!0});Hs.getEccLib=Hs.initEccLib=void 0;const mo={};function hI(t,e){t?t!==mo.eccLib&&(e!=null&&e.DANGER_DO_NOT_VERIFY_ECCLIB||yI(t),mo.eccLib=t):mo.eccLib=t}Hs.initEccLib=hI;function pI(){if(!mo.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return mo.eccLib}Hs.getEccLib=pI;const on=t=>Buffer.from(t,"hex");function yI(t){Qt(typeof t.isXOnlyPoint=="function"),Qt(t.isXOnlyPoint(on("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),Qt(t.isXOnlyPoint(on("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),Qt(t.isXOnlyPoint(on("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),Qt(t.isXOnlyPoint(on("0000000000000000000000000000000000000000000000000000000000000001"))),Qt(!t.isXOnlyPoint(on("0000000000000000000000000000000000000000000000000000000000000000"))),Qt(!t.isXOnlyPoint(on("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),Qt(typeof t.xOnlyPointAddTweak=="function"),mI.forEach(e=>{const r=t.xOnlyPointAddTweak(on(e.pubkey),on(e.tweak));e.result===null?Qt(r===null):(Qt(r!==null),Qt(r.parity===e.parity),Qt(Buffer.from(r.xOnlyPubkey).equals(on(e.result))))})}function Qt(t){if(!t)throw new Error("ecc library invalid")}const mI=[{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 vh={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.tweakKey=t.tapTweakHash=t.tapleafHash=t.findScriptPath=t.toHashTree=t.rootHashFromPath=t.MAX_TAPTREE_DEPTH=t.LEAF_VERSION_TAPSCRIPT=void 0;const e=Xs,r=Hs,n=as,s=ct,i=wt;t.LEAF_VERSION_TAPSCRIPT=192,t.MAX_TAPTREE_DEPTH=128;const o=g=>"left"in g&&"right"in g;function a(g,v){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 _=v;for(let E=0;E<S;E++){const x=g.slice(33+32*E,65+32*E);_.compare(x)<0?_=f(_,x):_=f(x,_)}return _}t.rootHashFromPath=a;function c(g){if((0,i.isTapleaf)(g))return{hash:l(g)};const v=[c(g[0]),c(g[1])];v.sort((E,x)=>E.hash.compare(x.hash));const[S,_]=v;return{hash:f(S.hash,_.hash),left:S,right:_}}t.toHashTree=c;function u(g,v){if(o(g)){const S=u(g.left,v);if(S!==void 0)return[...S,g.right.hash];const _=u(g.right,v);if(_!==void 0)return[..._,g.left.hash]}else if(g.hash.equals(v))return[]}t.findScriptPath=u;function l(g){const v=g.version||t.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",e.Buffer.concat([e.Buffer.from([v]),m(g.output)]))}t.tapleafHash=l;function d(g,v){return n.taggedHash("TapTweak",e.Buffer.concat(v?[g,v]:[g]))}t.tapTweakHash=d;function h(g,v){if(!e.Buffer.isBuffer(g)||g.length!==32||v&&v.length!==32)return null;const S=d(g,v),_=(0,r.getEccLib)().xOnlyPointAddTweak(g,S);return!_||_.xOnlyPubkey===null?null:{parity:_.parity,x:e.Buffer.from(_.xOnlyPubkey)}}t.tweakKey=h;function f(g,v){return n.taggedHash("TapBranch",e.Buffer.concat([g,v]))}function m(g){const v=s.varuint.encodingLength(g.length),S=e.Buffer.allocUnsafe(v);return s.varuint.encode(g.length,S),e.Buffer.concat([S,g])}})(vh);var xt={},my;function gI(){if(my)return xt;my=1,Object.defineProperty(xt,"__esModule",{value:!0}),xt.toOutputScript=xt.fromOutputScript=xt.toBech32=xt.toBase58Check=xt.fromBech32=xt.fromBase58Check=void 0;const t=gt,e=Eh(),r=Yt(),n=wt,s=kn,i=bh,o=40,a=2,c=16,u=2,l=80,d="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function h(E,x){const O=E.slice(2);if(O.length<a||O.length>o)throw new TypeError("Invalid program length for segwit address");const P=E[0]-l;if(P<u||P>c)throw new TypeError("Invalid version for segwit address");if(E[1]!==O.length)throw new TypeError("Invalid script for segwit address");return console.warn(d),v(O,P,x.bech32)}function f(E){const x=Buffer.from(i.decode(E));if(x.length<21)throw new TypeError(E+" is too short");if(x.length>21)throw new TypeError(E+" is too long");const O=x.readUInt8(0),P=x.slice(1);return{version:O,hash:P}}xt.fromBase58Check=f;function m(E){let x,O;try{x=s.bech32.decode(E)}catch{}if(x){if(O=x.words[0],O!==0)throw new TypeError(E+" uses wrong encoding")}else if(x=s.bech32m.decode(E),O=x.words[0],O===0)throw new TypeError(E+" uses wrong encoding");const P=s.bech32.fromWords(x.words.slice(1));return{version:O,prefix:x.prefix,data:Buffer.from(P)}}xt.fromBech32=m;function g(E,x){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const O=Buffer.allocUnsafe(21);return O.writeUInt8(x,0),E.copy(O,1),i.encode(O)}xt.toBase58Check=g;function v(E,x,O){const P=s.bech32.toWords(E);return P.unshift(x),x===0?s.bech32.encode(O,P):s.bech32m.encode(O,P)}xt.toBech32=v;function S(E,x){x=x||t.bitcoin;try{return e.p2pkh({output:E,network:x}).address}catch{}try{return e.p2sh({output:E,network:x}).address}catch{}try{return e.p2wpkh({output:E,network:x}).address}catch{}try{return e.p2wsh({output:E,network:x}).address}catch{}try{return e.p2tr({output:E,network:x}).address}catch{}try{return h(E,x)}catch{}throw new Error(r.toASM(E)+" has no matching Address")}xt.fromOutputScript=S;function _(E,x){x=x||t.bitcoin;let O,P;try{O=f(E)}catch{}if(O){if(O.version===x.pubKeyHash)return e.p2pkh({hash:O.hash}).output;if(O.version===x.scriptHash)return e.p2sh({hash:O.hash}).output}else{try{P=m(E)}catch{}if(P){if(P.prefix!==x.bech32)throw new Error(E+" has an invalid prefix");if(P.version===0){if(P.data.length===20)return e.p2wpkh({hash:P.data}).output;if(P.data.length===32)return e.p2wsh({hash:P.data}).output}else if(P.version===1){if(P.data.length===32)return e.p2tr({pubkey:P.data}).output}else if(P.version>=u&&P.version<=c&&P.data.length>=a&&P.data.length<=o)return console.warn(d),r.compile([P.version+l,P.data])}}throw new Error(E+" has no matching Script")}return xt.toOutputScript=_,xt}var gy;function bI(){if(gy)return ro;gy=1,Object.defineProperty(ro,"__esModule",{value:!0}),ro.p2tr=void 0;const t=Xs,e=gt,r=Yt(),n=wt,s=Hs,i=vh,o=Kt,a=kn,c=gI(),u=r.OPS,l=1,d=80;function h(f,m){if(!f.address&&!f.output&&!f.pubkey&&!f.internalPubkey&&!(f.witness&&f.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)},f);const g=o.value(()=>(0,c.fromBech32)(f.address)),v=o.value(()=>{if(!(!f.witness||!f.witness.length))return f.witness.length>=2&&f.witness[f.witness.length-1][0]===d?f.witness.slice(0,-1):f.witness.slice()}),S=o.value(()=>{if(f.scriptTree)return(0,i.toHashTree)(f.scriptTree);if(f.hash)return{hash:f.hash}}),_=f.network||e.bitcoin,E={name:"p2tr",network:_};if(o.prop(E,"address",()=>{if(!E.pubkey)return;const x=a.bech32m.toWords(E.pubkey);return x.unshift(l),a.bech32m.encode(_.bech32,x)}),o.prop(E,"hash",()=>{const x=S();if(x)return x.hash;const O=v();if(O&&O.length>1){const P=O[O.length-1],$=P[0]&n.TAPLEAF_VERSION_MASK,z=O[O.length-2],C=(0,i.tapleafHash)({output:z,version:$});return(0,i.rootHashFromPath)(P,C)}return null}),o.prop(E,"output",()=>{if(E.pubkey)return r.compile([u.OP_1,E.pubkey])}),o.prop(E,"redeemVersion",()=>f.redeemVersion?f.redeemVersion:f.redeem&&f.redeem.redeemVersion!==void 0&&f.redeem.redeemVersion!==null?f.redeem.redeemVersion:i.LEAF_VERSION_TAPSCRIPT),o.prop(E,"redeem",()=>{const x=v();if(!(!x||x.length<2))return{output:x[x.length-2],witness:x.slice(0,-2),redeemVersion:x[x.length-1][0]&n.TAPLEAF_VERSION_MASK}}),o.prop(E,"pubkey",()=>{if(f.pubkey)return f.pubkey;if(f.output)return f.output.slice(2);if(f.address)return g().data;if(E.internalPubkey){const x=(0,i.tweakKey)(E.internalPubkey,E.hash);if(x)return x.x}}),o.prop(E,"internalPubkey",()=>{if(f.internalPubkey)return f.internalPubkey;const x=v();if(x&&x.length>1)return x[x.length-1].slice(1,33)}),o.prop(E,"signature",()=>{if(f.signature)return f.signature;const x=v();if(!(!x||x.length!==1))return x[0]}),o.prop(E,"witness",()=>{if(f.witness)return f.witness;const x=S();if(x&&f.redeem&&f.redeem.output&&f.internalPubkey){const O=(0,i.tapleafHash)({output:f.redeem.output,version:E.redeemVersion}),P=(0,i.findScriptPath)(x,O);if(!P)return;const $=(0,i.tweakKey)(f.internalPubkey,x.hash);if(!$)return;const z=t.Buffer.concat([t.Buffer.from([E.redeemVersion|$.parity]),f.internalPubkey].concat(P));return[f.redeem.output,z]}if(f.signature)return[f.signature]}),m.validate){let x=t.Buffer.from([]);if(f.address){if(_&&_.bech32!==g().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(g().version!==l)throw new TypeError("Invalid address version");if(g().data.length!==32)throw new TypeError("Invalid address data");x=g().data}if(f.pubkey){if(x.length>0&&!x.equals(f.pubkey))throw new TypeError("Pubkey mismatch");x=f.pubkey}if(f.output){if(f.output.length!==34||f.output[0]!==u.OP_1||f.output[1]!==32)throw new TypeError("Output is invalid");if(x.length>0&&!x.equals(f.output.slice(2)))throw new TypeError("Pubkey mismatch");x=f.output.slice(2)}if(f.internalPubkey){const $=(0,i.tweakKey)(f.internalPubkey,E.hash);if(x.length>0&&!x.equals($.x))throw new TypeError("Pubkey mismatch");x=$.x}if(x&&x.length&&!(0,s.getEccLib)().isXOnlyPoint(x))throw new TypeError("Invalid pubkey for p2tr");const O=S();if(f.hash&&O&&!f.hash.equals(O.hash))throw new TypeError("Hash mismatch");if(f.redeem&&f.redeem.output&&O){const $=(0,i.tapleafHash)({output:f.redeem.output,version:E.redeemVersion});if(!(0,i.findScriptPath)(O,$))throw new TypeError("Redeem script not in tree")}const P=v();if(f.redeem&&E.redeem){if(f.redeem.redeemVersion&&f.redeem.redeemVersion!==E.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(f.redeem.output){if(r.decompile(f.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(E.redeem.output&&!f.redeem.output.equals(E.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(f.redeem.witness&&E.redeem.witness&&!(0,n.stacksEqual)(f.redeem.witness,E.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(P&&P.length)if(P.length===1){if(f.signature&&!f.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 z=($.length-33)/32;if(z>128)throw new TypeError(`The script path is too long. Got ${z}, expected max 128.`);const C=$.slice(1,33);if(f.internalPubkey&&!f.internalPubkey.equals(C))throw new TypeError("Internal pubkey mismatch");if(!(0,s.getEccLib)().isXOnlyPoint(C))throw new TypeError("Invalid internalPubkey for p2tr witness");const Y=$[0]&n.TAPLEAF_VERSION_MASK,W=P[P.length-2],K=(0,i.tapleafHash)({output:W,version:Y}),U=(0,i.rootHashFromPath)($,K),N=(0,i.tweakKey)(C,U);if(!N)throw new TypeError("Invalid outputKey for p2tr witness");if(x.length&&!x.equals(N.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(N.parity!==($[0]&1))throw new Error("Incorrect parity")}}return Object.assign(E,f)}return ro.p2tr=h,ro}var by;function Eh(){return by||(by=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.p2tr=t.p2wsh=t.p2wpkh=t.p2sh=t.p2pkh=t.p2pk=t.p2ms=t.embed=void 0;const e=Yc;Object.defineProperty(t,"embed",{enumerable:!0,get:function(){return e.p2data}});const r=Jc;Object.defineProperty(t,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=Qc;Object.defineProperty(t,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const s=eu;Object.defineProperty(t,"p2pkh",{enumerable:!0,get:function(){return s.p2pkh}});const i=tu;Object.defineProperty(t,"p2sh",{enumerable:!0,get:function(){return i.p2sh}});const o=ru;Object.defineProperty(t,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const a=nu;Object.defineProperty(t,"p2wsh",{enumerable:!0,get:function(){return a.p2wsh}});const c=bI();Object.defineProperty(t,"p2tr",{enumerable:!0,get:function(){return c.p2tr}})}(Gu)),Gu}Object.defineProperty(_e,"__esModule",{value:!0});_e.signatureBlocksAction=_e.checkInputForSig=_e.pubkeyInScript=_e.pubkeyPositionInScript=_e.witnessStackToScriptWitness=_e.isP2TR=_e.isP2SHScript=_e.isP2WSHScript=_e.isP2WPKH=_e.isP2PKH=_e.isP2PK=_e.isP2MS=void 0;const wy=va,go=Yt(),Da=wa,wI=as,Ys=Eh();function Js(t){return e=>{try{return t({output:e}),!0}catch{return!1}}}_e.isP2MS=Js(Ys.p2ms);_e.isP2PK=Js(Ys.p2pk);_e.isP2PKH=Js(Ys.p2pkh);_e.isP2WPKH=Js(Ys.p2wpkh);_e.isP2WSHScript=Js(Ys.p2wsh);_e.isP2SHScript=Js(Ys.p2sh);_e.isP2TR=Js(Ys.p2tr);function vI(t){let e=Buffer.allocUnsafe(0);function r(o){e=Buffer.concat([e,Buffer.from(o)])}function n(o){const a=e.length,c=wy.encodingLength(o);e=Buffer.concat([e,Buffer.allocUnsafe(c)]),wy.encode(o,e,a)}function s(o){n(o.length),r(o)}function i(o){n(o.length),o.forEach(s)}return i(t),e}_e.witnessStackToScriptWitness=vI;function $w(t,e){const r=(0,wI.hash160)(t),n=t.slice(1,33),s=go.decompile(e);if(s===null)throw new Error("Unknown script error");return s.findIndex(i=>typeof i=="number"?!1:i.equals(t)||i.equals(r)||i.equals(n))}_e.pubkeyPositionInScript=$w;function EI(t,e){return $w(t,e)!==-1}_e.pubkeyInScript=EI;function SI(t,e){return AI(t).some(n=>Rw(n,go.signature.decode,e))}_e.checkInputForSig=SI;function Rw(t,e,r){const{hashType:n}=e(t),s=[];switch(n&Da.Transaction.SIGHASH_ANYONECANPAY&&s.push("addInput"),n&31){case Da.Transaction.SIGHASH_ALL:break;case Da.Transaction.SIGHASH_SINGLE:case Da.Transaction.SIGHASH_NONE:s.push("addOutput"),s.push("setInputSequence");break}return s.indexOf(r)===-1}_e.signatureBlocksAction=Rw;function AI(t){let e=[];if((t.partialSig||[]).length===0){if(!t.finalScriptSig&&!t.finalScriptWitness)return[];e=xI(t)}else e=t.partialSig;return e.map(r=>r.signature)}function xI(t){const e=t.finalScriptSig?go.decompile(t.finalScriptSig)||[]:[],r=t.finalScriptWitness?go.decompile(t.finalScriptWitness)||[]:[];return e.concat(r).filter(n=>Buffer.isBuffer(n)&&go.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(Fe,"__esModule",{value:!0});Fe.checkTaprootInputForSigs=Fe.tapTreeFromList=Fe.tapTreeToList=Fe.tweakInternalPubKey=Fe.checkTaprootOutputFields=Fe.checkTaprootInputFields=Fe.isTaprootOutput=Fe.isTaprootInput=fo=Fe.serializeTaprootSignature=Fe.tapScriptFinalizer=Fe.toXOnly=void 0;const Sh=wt,kI=wa,su=_e,is=vh,_I=Eh(),TI=_e,II=t=>t.length===32?t:t.slice(1,33);Fe.toXOnly=II;function PI(t,e,r){const n=WI(e,t,r);try{const i=qI(e,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,su.witnessStackToScriptWitness)(i)}}catch(s){throw new Error(`Can not finalize taproot input #${t}: ${s}`)}}Fe.tapScriptFinalizer=PI;function OI(t,e){const r=e?Buffer.from([e]):Buffer.from([]);return Buffer.concat([t,r])}var fo=Fe.serializeTaprootSignature=OI;function nc(t){return t&&!!(t.tapInternalKey||t.tapMerkleRoot||t.tapLeafScript&&t.tapLeafScript.length||t.tapBip32Derivation&&t.tapBip32Derivation.length||t.witnessUtxo&&(0,su.isP2TR)(t.witnessUtxo.script))}Fe.isTaprootInput=nc;function sc(t,e){return t&&!!(t.tapInternalKey||t.tapTree||t.tapBip32Derivation&&t.tapBip32Derivation.length||e&&(0,su.isP2TR)(e))}Fe.isTaprootOutput=sc;function BI(t,e,r){DI(t,e,r),VI(t,e,r)}Fe.checkTaprootInputFields=BI;function CI(t,e,r){zI(t,e,r),$I(t,e)}Fe.checkTaprootOutputFields=CI;function $I(t,e){if(!e.tapTree&&!e.tapInternalKey)return;const r=e.tapInternalKey||t.tapInternalKey,n=e.tapTree||t.tapTree;if(r){const{script:s}=t,i=RI(r,n);if(s&&!s.equals(i))throw new Error("Error adding output. Script or address missmatch.")}}function RI(t,e){const r=e&&Nw(e.leaves),{output:n}=(0,_I.p2tr)({internalPubkey:t,scriptTree:r});return n}function NI(t,e){const r=e.tapInternalKey,n=r&&(0,is.tweakKey)(r,e.tapMerkleRoot);if(!n)throw new Error(`Cannot tweak tap internal key for input #${t}. Public key: ${r&&r.toString("hex")}`);return n.x}Fe.tweakInternalPubKey=NI;function UI(t){if(!(0,Sh.isTaptree)(t))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return ed(t)}Fe.tapTreeToList=UI;function Nw(t=[]){return t.length===1&&t[0].depth===0?{output:t[0].script,version:t[0].leafVersion}:HI(t)}Fe.tapTreeFromList=Nw;function MI(t,e){return jI(t).some(n=>(0,TI.signatureBlocksAction)(n,FI,e))}Fe.checkTaprootInputForSigs=MI;function FI(t){return{signature:t.slice(0,64),hashType:t.slice(64)[0]||kI.Transaction.SIGHASH_DEFAULT}}function jI(t){const e=[];if(t.tapKeySig&&e.push(t.tapKeySig),t.tapScriptSig&&e.push(...t.tapScriptSig.map(r=>r.signature)),!e.length){const r=LI(t.finalScriptWitness);r&&e.push(r)}return e}function LI(t){if(!t)return;const e=t.slice(2);if(e.length===64||e.length===65)return e}function ed(t,e=[],r=0){if(r>is.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return t?(0,Sh.isTapleaf)(t)?(e.push({depth:r,leafVersion:t.version||is.LEAF_VERSION_TAPSCRIPT,script:t.output}),e):(t[0]&&ed(t[0],e,r+1),t[1]&&ed(t[1],e,r+1),e):[]}function HI(t){let e;for(const r of t)if(e=td(r,e),!e)throw new Error("No room left to insert tapleaf in tree");return e}function td(t,e,r=0){if(r>is.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(t.depth===r)return e?void 0:{output:t.script,version:t.leafVersion};if((0,Sh.isTapleaf)(e))return;const n=td(t,e&&e[0],r+1);if(n)return[n,e&&e[1]];const s=td(t,e&&e[1],r+1);if(s)return[e&&e[0],s]}function DI(t,e,r){const n=nc(t)&&Ai(e),s=Ai(t)&&nc(e),i=t===e&&nc(e)&&Ai(e);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function zI(t,e,r){const n=sc(t)&&Ai(e),s=Ai(t)&&sc(e),i=t===e&&sc(e)&&Ai(e);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function VI(t,e,r){if(e.tapMerkleRoot){const n=(e.tapLeafScript||[]).every(i=>Yu(i,e.tapMerkleRoot)),s=(t.tapLeafScript||[]).every(i=>Yu(i,e.tapMerkleRoot));if(!n||!s)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(t.tapMerkleRoot&&!(e.tapLeafScript||[]).every(s=>Yu(s,t.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function Yu(t,e){if(!e)return!0;const r=(0,is.tapleafHash)({output:t.script,version:t.leafVersion});return(0,is.rootHashFromPath)(t.controlBlock,r).equals(e)}function qI(t,e){const r=(0,is.tapleafHash)({output:e.script,version:e.leafVersion});return(t.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>GI(e.script,n)).sort((n,s)=>s.positionInScript-n.positionInScript).map(n=>n.signature)}function GI(t,e){return Object.assign({positionInScript:(0,su.pubkeyPositionInScript)(e.pubkey,t)},e)}function WI(t,e,r){if(!t.tapScriptSig||!t.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${e}. No tapleaf script signature provided.`);const n=(t.tapLeafScript||[]).sort((s,i)=>s.controlBlock.length-i.controlBlock.length).find(s=>KI(s,t.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${e}. Signature for tapleaf script not found.`);return n}function KI(t,e,r){const n=(0,is.tapleafHash)({output:t.script,version:t.leafVersion});return(!r||r.equals(n))&&e.find(i=>i.leafHash.equals(n))!==void 0}function Ai(t){return t&&!!(t.redeemScript||t.witnessScript||t.bip32Derivation&&t.bip32Derivation.length)}const er={secretMismatch:"invalid secret",secretHashLenMismatch:"secret hash should be 32 bytes",pubkeyLenMismatch:"pubkey should be 32 bytes",zeroOrNegativeExpiry:"expiry should be greater than 0",htlcAddressGenerationFailed:"failed to generate htlc address",notFunded:"address not funded",noCounterpartySigs:"counterparty signatures are required",counterPartySigNotFound:t=>"counterparty signature not found for utxo "+t,invalidCounterpartySigForUTXO:t=>"invalid counterparty signature for utxo "+t,htlcNotExpired:t=>`HTLC not expired, need more ${t} blocks`,controlBlockGenerationFailed:"failed to generate control block",invalidLeaf:"invalid leaf"},za=192;ve.initEccLib(or);let vy=class{constructor(e,r){this.signer=e,this.internalPubkey=Xp(),this.network=L_(r)}address(e,r){const n=this.generateLeaves(e,r),{address:s}=ve.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:n});if(!s)throw new Error(er.htlcAddressGenerationFailed);return s}async _buildRawTx(e,r,n,s,i){const o=new ve.Transaction;o.version=2;const a=this.address(e,n||"redeem"),c=await this.getProvider();let u=[];if(i&&i.length>0)for(const h of i){const f=await c.getTransaction(h);for(let m=0;m<f.vout.length;m++){const g=f.vout[m];g.scriptpubkey_address===a&&u.push({txid:f.txid,vout:m,value:g.value,status:{confirmed:!1}})}}else u=await c.getUTXOs(a);const l=u.reduce((h,f)=>h+f.value,0);if(l===0)throw new Error(`${a} ${er.notFunded}`);for(let h=0;h<u.length;h++)o.addInput(Buffer.from(u[h].txid,"hex").reverse(),u[h].vout);if(s!=null&&s.vSize){const h=await c.getFeeRates(),f=Math.ceil(h.hourFee*s.vSize),m=l-f;return o.addOutput(ve.address.toOutputScript(r,this.network),m),{tx:o,usedUtxos:u}}const d=(s==null?void 0:s.fee)??await c.suggestFee(a,l,vi.MEDIUM);return o.addOutput(ve.address.toOutputScript(r,this.network),l-d),{tx:o,usedUtxos:u,fee:d,balance:l}}getOutputScript(e,r){return ve.address.toOutputScript(this.address(e,r||"redeem"),this.network)}async initiate(e,r){const n=await this.getProvider(),s=await this.signer.getAddress();let i,o;ee.isOrder(e)?(i=e.destination_swap.swap_id,o=Number(e.destination_swap.amount)):(i=e.to,o=Number(e.amount)),r===void 0&&(r=await n.suggestFee(s,o,vi.MEDIUM));const a=await this.signer.send(i,o,r);return b.Ok(a)}async generateRedeemSACP(e,r,n){const{tx:s,usedUtxos:i}=await this._buildRawTx(e,e.destination_swap.delegate,"redeem",{fee:n}),o=this.getOutputScript(e,"redeem"),a=ve.Transaction.SIGHASH_SINGLE|ve.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(1,e),u=i.map(d=>d.value),l=Qi(o,i.length);for(let d=0;d<s.ins.length;d++){const h=s.hashForWitnessV1(d,l,u,a,c),f=await this.signer.signSchnorr(h);s.setWitness(d,[fo(f,a),Buffer.from(r,"hex"),this.redeemLeaf(b.trim0x(e.destination_swap.secret_hash),Me(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}return s.toHex()}async generateInstantRefundSACP(e){const r=this.getOutputScript(e,"instantRefund"),{tx:n,usedUtxos:s,fee:i}=await this._buildRawTx(e,e.destination_swap.delegate,"instantRefund",{fee:0});n.outs=[];const o=Math.max(...s.map(d=>d.value));s.forEach(({value:d})=>{n.addOutput(r,d-(d===o?i??0:0))});const a=ve.Transaction.SIGHASH_SINGLE|ve.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(2,e),u=s.map(d=>d.value),l=Qi(r,s.length);for(let d=0;d<n.ins.length;d++){const h=n.hashForWitnessV1(d,l,u,a,c),f=await this.signer.signSchnorr(h);n.setWitness(d,[fo(f,a),fo(f,a),this.instantRefundLeaf(Me(e.source_swap.initiator),Me(e.destination_swap.delegate)),await this.generateControlBlockFor(2,e)])}return n.toHex()}async generateInstantRefundSACPWithHash(e){const r=[],n=ve.Transaction.SIGHASH_SINGLE|ve.Transaction.SIGHASH_ANYONECANPAY;for(let s=0;s<e.length;s++){const i=Buffer.from(e[s],"hex"),o=await this.signer.signSchnorr(i);r.push(fo(o,n).toString("hex"))}return b.Ok(r)}async instantRefund(e,r,n){qp(r.length>0,er.noCounterpartySigs);const{tx:s,usedUtxos:i}=await this._buildRawTx(e,await this.signer.getAddress(),"instantRefund",{fee:n});for(const h of i)if(!r.find(f=>f.utxo===h.txid))throw new Error(er.counterPartySigNotFound(h.txid));const o=this.getOutputScript(e,"instantRefund"),a=ve.Transaction.SIGHASH_DEFAULT,c=this.leafHash(2,e),u=i.map(h=>h.value),l=Qi(o,i.length);for(let h=0;h<s.ins.length;h++){const f=s.hashForWitnessV1(h,l,u,a,c);if(!or.verifySchnorr(f,Buffer.from(Me(e.destination_swap.delegate),"hex"),Buffer.from(r[h].sig,"hex")))throw new Error(er.invalidCounterpartySigForUTXO(r[h].utxo));const m=await this.signer.signSchnorr(f),g=Buffer.from(s.ins[h].hash).reverse().toString("hex"),v=r.find(S=>S.utxo===g);if(!v)throw new Error(er.counterPartySigNotFound(g));s.setWitness(h,[Buffer.from(v.sig,"hex"),m,this.instantRefundLeaf(Me(e.source_swap.initiator),Me(e.destination_swap.delegate)),await this.generateControlBlockFor(2,e)])}return await(await this.getProvider()).broadcast(s.toHex())}async redeem(e,r,n){const s=await this.getRedeemHex(e,r,n);if(!s.ok)return b.Err(s.error);const o=await(await this.getProvider()).broadcast(s.val);return b.Ok(o)}async getRedeemHex(e,r,n){qp(ve.crypto.sha256(Buffer.from(r,"hex")).toString("hex")===b.trim0x(e.destination_swap.secret_hash),er.secretMismatch);const o=(ee.isBitcoin(e.source_swap.chain)?e.source_swap.redeemer:e.destination_swap.redeemer)??await this.signer.getAddress(),{tx:a,usedUtxos:c}=await this._buildRawTx(e,o,"redeem",{fee:0},n),u=this.leafHash(1,e),l=c.map(m=>m.value),d=Qi(this.getOutputScript(e,"redeem"),c.length),h=ve.Transaction.SIGHASH_DEFAULT;for(let m=0;m<a.ins.length;m++){const g=a.hashForWitnessV1(m,d,l,h,u),v=await this.signer.signSchnorr(g);a.setWitness(m,[v,Buffer.from(r,"hex"),this.redeemLeaf(b.trim0x(e.destination_swap.secret_hash),Me(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}const{tx:f}=await this._buildRawTx(e,o,"redeem",{vSize:a.virtualSize()},n);for(let m=0;m<f.ins.length;m++){const g=f.hashForWitnessV1(m,d,l,h,u),v=await this.signer.signSchnorr(g);f.setWitness(m,[v,Buffer.from(r,"hex"),this.redeemLeaf(b.trim0x(e.destination_swap.secret_hash),Me(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}return b.Ok(f.toHex())}async refund(e,r){const{tx:n,usedUtxos:s}=await this._buildRawTx(e,e.source_swap.delegate??await this.signer.getAddress(),"refund",{fee:r}),[i,o]=await this.canRefund(e,s);if(!i)throw new Error(er.htlcNotExpired(o));const a=this.leafHash(0,e),c=s.map(f=>f.value),u=Qi(this.getOutputScript(e,"refund"),s.length),l=ve.Transaction.SIGHASH_DEFAULT;for(let f=0;f<n.ins.length;f++){n.ins[f].sequence=e.source_swap.timelock;const m=n.hashForWitnessV1(f,u,c,l,a),g=await this.signer.signSchnorr(m);n.setWitness(f,[g,this.refundLeaf(e.source_swap.timelock,Me(e.source_swap.initiator)),await this.generateControlBlockFor(0,e)])}const h=await(await this.getProvider()).broadcast(n.toHex());return b.Ok(h)}async canRefund(e,r){const s=await(await this.getProvider()).getLatestTip();for(const i of r){let o=0;if(i.status.confirmed&&i.status.block_height+e.source_swap.timelock>s?o=i.status.block_height+e.source_swap.timelock-s+1:i.status.confirmed||(o=e.source_swap.timelock+1),o>0)return[!1,o]}return[!0,0]}async generateControlBlockFor(e,r){let n,s;switch(e){case 1:n=this.redeemLeaf(b.trim0x(r.destination_swap.secret_hash),Me(r.destination_swap.delegate)),s=this.generateLeaves(r,"redeem");break;case 0:n=this.refundLeaf(r.source_swap.timelock,Me(r.source_swap.initiator)),s=this.generateLeaves(r,"refund");break;case 2:n=this.instantRefundLeaf(Me(r.source_swap.initiator),Me(r.destination_swap.delegate)),s=this.generateLeaves(r,"instantRefund");break;default:throw new Error(er.controlBlockGenerationFailed)}const i=await this.signer.getNetwork(),o=ve.payments.p2tr({internalPubkey:Xp(),network:i,scriptTree:s,redeem:{output:n,redeemVersion:za}});if(!o.witness)throw new Error(er.controlBlockGenerationFailed);return o.witness[o.witness.length-1]}leafHash(e,r){let n;switch(e){case 1:n=this.redeemLeaf(b.trim0x(r.destination_swap.secret_hash),Me(r.destination_swap.delegate));break;case 0:n=this.refundLeaf(r.source_swap.timelock,Me(r.source_swap.initiator));break;case 2:n=this.instantRefundLeaf(Me(r.source_swap.initiator),Me(r.destination_swap.redeemer));break;default:throw new Error(er.invalidLeaf)}return ve.crypto.taggedHash("TapLeaf",R_(n))}refundLeaf(e,r){return ve.script.fromASM(`
55
- ${ve.script.number.encode(e).toString("hex")}
56
- OP_CHECKSEQUENCEVERIFY
57
- OP_DROP
58
- ${r}
59
- OP_CHECKSIG
60
- `.trim().replace(/\s+/g," "))}redeemLeaf(e,r){return ve.script.fromASM(`
61
- OP_SHA256
62
- ${e}
63
- OP_EQUALVERIFY
64
- ${r}
65
- OP_CHECKSIG
66
- `.trim().replace(/\s+/g," "))}instantRefundLeaf(e,r){return ve.script.fromASM(`
67
- ${e}
68
- OP_CHECKSIG
69
- ${r}
70
- OP_CHECKSIGADD
71
- OP_2
72
- OP_NUMEQUAL
73
- `.trim().replace(/\s+/g," "))}generateLeaves(e,r){let n,s,i;switch(r){case"redeem":n=e.destination_swap,s=n.delegate,i=n.delegate;break;case"refund":n=e.source_swap,s=n.delegate,i=n.delegate;break;case"instantRefund":n=e.source_swap,s=n.redeemer,i=n.redeemer;break;default:throw new Error("Invalid leaf generation type")}return[{version:za,output:this.redeemLeaf(n.secret_hash,Me(s))},[{version:za,output:this.refundLeaf(n.timelock,Me(n.initiator))},{version:za,output:this.instantRefundLeaf(Me(n.initiator),Me(i))}]]}generateMerkleProofFor(e,r){const n=this.leafHash(1,r),s=this.leafHash(2,r),i=this.leafHash(0,r);switch(e){case 1:{const o=U_(i,s);return[ve.crypto.taggedHash("TapBranch",Buffer.concat(o))]}case 0:return[s,n];case 2:return[i,n];default:throw new Error(er.invalidLeaf)}}getProvider(){return this.signer.getProvider()}get getPublicKey(){return this.signer.getPublicKey()}get htlcActorAddress(){return this.signer.getPublicKey()}};class Uw{constructor(e){this.quoteUrl=new b.Url(e)}async getQuoteFromAssets({fromAsset:e,toAsset:r,amount:n,isExactOut:s=!1,options:i}){const o=ee.ChainAsset.from(e),a=ee.ChainAsset.from(r);return this.getQuote(o,a,n,s,i)}async getQuote(e,r,n,s=!1,i){try{const o={from:e.toString(),to:r.toString(),...s?{to_amount:n.toString()}:{from_amount:n.toString()},...(i==null?void 0:i.affiliateFee)!==void 0&&{affiliate_fee:i.affiliateFee.toString()}},a=this.quoteUrl.endpoint("/v2/quote").addSearchParams(o),c=await b.Fetcher.get(a,{retryCount:0,...i==null?void 0:i.request});return c.error?b.Err(c.error):c.result?b.Ok(c.result):b.Err("GetQuote: Unexpected error, result is undefined")}catch(o){return b.Err("GetQuote:",String(o))}}async getStrategies(){try{const e=await b.Fetcher.get(this.quoteUrl.endpoint("/strategies"));if(e.error)return b.Err(e.error);if(!e.result)return b.Err("GetStrategies: Unexpected error, result is undefined");const r={};for(const n of Object.values(e.result)){const s=iw(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 b.Ok(r)}catch(e){return b.Err("GetStrategies:",String(e))}}}class Ri extends b.EventBroker{get isInitialized(){return!!this.digestKey}constructor(e,r){super(),this.digestKey=e,this.walletClient=r}static fromDigestKey(e){return new Ri(b.trim0x(e))}static fromWalletClient(e){return new Ri(void 0,e)}async initialize(){if(this.digestKey)return b.Ok("Already initialized");const e=await this.deriveDigestKeyFromWalletClient();return e.error?b.Err(e.error):(this.emit("initialized",!0),b.Ok("Initialized"))}async deriveDigestKeyFromWalletClient(){if(!this.walletClient)return b.Err("No walletClient found");if(!this.walletClient.account)return b.Err("No account found");try{const e=await this.walletClient.signTypedData({account:this.walletClient.account,types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"}],Data:[{name:"Message",type:"string"},{name:"Version",type:"string"},{name:"Nonce",type:"uint256"}]},domain:{name:"GARDEN FINANCE",version:"1"},primaryType:"Data",message:{Message:"Initialize your account",Version:"1.0.2",Nonce:1n}});return this.digestKey=b.trim0x(co(e)),this.emit("initialized",!0),b.Ok(this.digestKey)}catch(e){return b.Err("Failed to initialize: "+e)}}async getDigestKey(){if(!this.digestKey&&!this.walletClient)return b.Err("No private key or wallet client found");if(!this.digestKey&&this.walletClient){const e=await this.deriveDigestKeyFromWalletClient();if(e.error)return b.Err(e.error)}return this.digestKey?b.Ok(this.digestKey):b.Err("No private key found")}async generateSecret(e){const r=await this.signMessage(e);if(!r.ok)return b.Err(r.error);const n=co(b.with0x(r.val)),s=co(n);return b.Ok({secret:n,secretHash:s})}async signMessage(e){if(!this.digestKey){const u=await this.getDigestKey();if(!u.ok)return b.Err(u.error);this.digestKey=u.val}const r=Xa.ECPairFactory(or),n="Garden.fi"+e.toString(),s=Buffer.from(n,"utf8"),i=co(s),o=Buffer.from(b.trim0x(this.digestKey),"hex");if(o.length!==32)return b.Err("Invalid private key length. Expected 32 bytes.");const c=r.fromPrivateKey(o).sign(Buffer.from(b.trim0x(i),"hex"));return b.Ok(c.toString("hex"))}}const ZI=[{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"}],XI={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},YI={block:PS({format(t){var r;return{transactions:(r=t.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const s=jc(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:t.stateRoot}}}),transaction:TS({format(t){const e={};return t.type==="0x7e"&&(e.isSystemTx=t.isSystemTx,e.mint=t.mint?ot(t.mint):void 0,e.sourceHash=t.sourceHash,e.type="deposit"),e}}),transactionReceipt:NA({format(t){return{l1GasPrice:t.l1GasPrice?ot(t.l1GasPrice):null,l1GasUsed:t.l1GasUsed?ot(t.l1GasUsed):null,l1Fee:t.l1Fee?ot(t.l1Fee):null,l1FeeScalar:t.l1FeeScalar?Number(t.l1FeeScalar):null}}})};function JI(t,e){return tP(t)?eP(t):N6(t,e)}const QI={transaction:JI};function eP(t){rP(t);const{sourceHash:e,data:r,from:n,gas:s,isSystemTx:i,mint:o,to:a,value:c}=t,u=[e,n,a??"0x",o?Pt(o):"0x",c?Pt(c):"0x",s?Pt(s):"0x",i?"0x1":"0x",r??"0x"];return Or(["0x7e",ss(u)])}function tP(t){return t.type==="deposit"||typeof t.sourceHash<"u"}function rP(t){const{from:e,to:r}=t;if(e&&!it(e))throw new Bt({address:e});if(r&&!it(r))throw new Bt({address:r})}const Ni={blockTime:2e3,contracts:XI,formatters:YI,serializers:QI},nP=dt({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:250,rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),sP=dt({id:421614,name:"Arbitrum Sepolia",blockTime:250,nativeCurrency:{name:"Arbitrum Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://sepolia.arbiscan.io",apiUrl:"https://api-sepolia.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:81930}},testnet:!0}),no=1,Mw=dt({...Ni,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:{...Ni.contracts,disputeGameFactory:{[no]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[no]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[no]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[no]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:no});({...Mw});const so=11155111,Fw=dt({...Ni,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:{...Ni.contracts,disputeGameFactory:{[so]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[so]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[so]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[so]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:so});({...Fw});const iP=dt({id:80094,name:"Berachain",blockTime:2e3,nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},ensRegistry:{address:"0x5b22280886a2f5e09a49bea7e320eab0e5320e28",blockCreated:877007},ensUniversalResolver:{address:"0x4D41762915F83c76EcaF6776d9b08076aA32b492",blockCreated:9310021}},rpcUrls:{default:{http:["https://rpc.berachain.com"]}},blockExplorers:{default:{name:"Berascan",url:"https://berascan.com"}},ensTlds:[".bera"],testnet:!1}),oP=dt({id:80084,name:"Berachain bArtio",nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:109269},ensRegistry:{address:"0xB0eef18971290b333450586D33dcA6cE122651D2",blockCreated:7736794},ensUniversalResolver:{address:"0x41692Ef1EA0C79E6b73077E4A67572D2BDbD7057",blockCreated:7736795}},ensTlds:[".bera"],rpcUrls:{default:{http:["https://bartio.rpc.berachain.com"]}},blockExplorers:{default:{name:"Berachain bArtio Beratrail",url:"https://bartio.beratrail.io"}},testnet:!0}),aP=dt({id:56,name:"BNB Smart Chain",blockTime:750,nativeCurrency:{decimals:18,name:"BNB",symbol:"BNB"},rpcUrls:{default:{http:["https://56.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"BscScan",url:"https://bscscan.com",apiUrl:"https://api.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:15921452}}}),cP=dt({id:97,name:"BNB Smart Chain Testnet",nativeCurrency:{decimals:18,name:"BNB",symbol:"tBNB"},rpcUrls:{default:{http:["https://data-seed-prebsc-1-s1.bnbchain.org:8545"]}},blockExplorers:{default:{name:"BscScan",url:"https://testnet.bscscan.com",apiUrl:"https://api-testnet.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:17422483}},testnet:!0}),uP=dt({id:5115,name:"Citrea Testnet",nativeCurrency:{name:"cBTC",symbol:"cBTC",decimals:18},rpcUrls:{default:{http:["https://rpc.testnet.citrea.xyz"]}},blockExplorers:{default:{name:"Citrea Explorer",url:"https://explorer.testnet.citrea.xyz",apiUrl:"https://explorer.testnet.citrea.xyz/api"}},testnet:!0}),lP=dt({id:1116,name:"Core Dao",nativeCurrency:{decimals:18,name:"Core",symbol:"CORE"},rpcUrls:{default:{http:["https://rpc.coredao.org"]}},blockExplorers:{default:{name:"CoreDao",url:"https://scan.coredao.org"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:11907934}},testnet:!1}),fP=1,dP=dt({id:21e6,name:"Corn",nativeCurrency:{decimals:18,name:"Bitcorn",symbol:"BTCN"},rpcUrls:{default:{http:["https://21000000.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"Corn Explorer",url:"https://cornscan.io",apiUrl:"https://api.routescan.io/v2/network/mainnet/evm/21000000/etherscan/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:3228}},sourceId:fP}),hP=dt({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:12e3,rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:23085558},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),pP=dt({id:10143,name:"Monad Testnet",blockTime:400,nativeCurrency:{name:"Testnet MON Token",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://testnet-rpc.monad.xyz"]}},blockExplorers:{default:{name:"Monad Testnet explorer",url:"https://testnet.monadexplorer.com"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:251449}},testnet:!0}),yP=dt({id:11155111,name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.drpc.org"]}},blockExplorers:{default:{name:"Etherscan",url:"https://sepolia.etherscan.io",apiUrl:"https://api-sepolia.etherscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:751532},ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:8928790}},testnet:!0}),Va=1,mP=dt({...Ni,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:{...Ni.contracts,multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:0},disputeGameFactory:{[Va]:{address:"0x2F12d621a16e2d3285929C9996f478508951dFe4"}},portal:{[Va]:{address:"0x0bd48f6B86a26D3a217d0Fa6FfE2B491B956A7a2"}},l1StandardBridge:{[Va]:{address:"0x81014F44b0a345033bB2b3B21C7a1A308B35fEeA"}}},sourceId:Va}),gP={...yP,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},jw={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/"]}}},Lw={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"]}}},Hw={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"]}}},iu={ethereum:hP,arbitrum:nP,ethereum_sepolia:gP,arbitrum_sepolia:sP,ethereum_localnet:ee.EthereumLocalnet,arbitrum_localnet:ee.ArbitrumLocalnet,base_sepolia:Fw,base:Mw,bera_testnet:oP,citrea_testnet:uP,core:lP,bera:iP,monad_testnet:pP,hyperliquid_testnet:Lw,hyperliquid:Hw,unichain:mP,corn:dP,botanix:jw,bnbchain:aP,bnbchain_testnet:cP},Dw=t=>{for(const[e,r]of Object.entries(iu))if(r.id===t)return e;return null},rd=async(t,e)=>{var s,i,o;const r=iu[t],n=await e.getChainId();if(r)try{if(r.id===n)return b.Ok({message:"Already on the network",walletClient:e});await e.switchChain({id:r.id});const a=ju({account:e.account,chain:r,transport:Tp(e.transport)});return b.Ok({message:"Switched chain",walletClient:a})}catch(a){if(bP(a))if(a.code===4902||a.code===-32603)try{await e.addChain({chain:r});const c=ju({account:e.account,chain:r,transport:Tp(e.transport)});return b.Ok({message:"Added network",walletClient:c})}catch{return b.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=ju({account:e.account,chain:r,transport:Dg()});return b.Ok({message:"Added network",walletClient:c})}else return b.Err("Failed to switch network");else return b.Err("Failed to switch network")}else return b.Err("Chain not supported")},bP=t=>typeof t=="object"&&t!=null&&("code"in t||"message"in t||"body"in t),wP=[{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 zw{constructor(e,r,n){this.url=new b.Url(e.toString()),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(e){if(ee.isEvmOrderResponse(e))return this.initiateWithCreateOrderResponse(e);if(!this.wallet.account)return b.Err("No account found");if(this.wallet.account.address.toLowerCase()!==e.source_swap.initiator.toLowerCase())return b.Err("Account address and order initiator mismatch");if(!ee.isEVM(e.source_swap.chain))return b.Err("Source chain is not an EVM chain");const r=e.source_swap.chain,n=await rd(r,this.wallet);if(!n.ok)return b.Err(n.error);if(this.wallet=n.val.walletClient,!this.wallet.account)return b.Err("No account found");const{source_swap:s}=e;if(!s.amount||!s.redeemer||!s.timelock||!s.secret_hash)return b.Err("Invalid order");const i=b.with0x(s.secret_hash),o=BigInt(s.timelock),a=b.with0x(s.redeemer),c=BigInt(s.amount),u=await lh(e.source_swap.asset,this.url);if(!u.ok)return b.Err(u.error);const{htlcAddress:l,tokenAddress:d}=u.val,h=ee.ChainAsset.fromString(e.source_swap.asset);return ee.isEvmNativeToken(h.chain,h.symbol)?this._initiateOnNativeHTLC(i,o,c,a,l):this._initiateOnErc20HTLC(i,o,c,a,l,d,e.order_id)}async _initiateOnNativeHTLC(e,r,n,s,i){if(!this.wallet.account)return b.Err("No account found");try{const a=await _p({address:b.with0x(i),abi:wP,client:this.wallet}).write.initiate([s,r,n,e],{account:this.wallet.account,chain:this.wallet.chain,value:n});return b.Ok(a)}catch(o){return b.Err("Failed to initiate on native HTLC",String(o))}}async _initiateOnErc20HTLC(e,r,n,s,i,o,a){if(!this.wallet.account)return b.Err("No account found");try{const c=await this.auth.getAuthHeaders();if(!c.ok)return b.Err(c.error);const u=_p({address:b.with0x(i),abi:ZI,client:this.wallet}),l=await b.checkAllowanceAndApprove(Number(n),o,i,this.wallet);if(!l.ok)return b.Err(l.error);const d=await u.read.eip712Domain(),h=await this.wallet.signTypedData({account:this.wallet.account,domain:{name:d[1],version:d[2],chainId:Number(d[3]),verifyingContract:d[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:e}}),f={...c.val,"Content-Type":"application/json"},m=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(a).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:h}),headers:f});if(m.error)return b.Err(m.error);const g=await b.waitForTransactionReceipt(this.wallet,m.result);return g.val&&g.val.status==="success"?b.Ok(m.result?m.result:"Initiate hash not found"):b.Err("Init failed: Transaction receipt not successful")}catch(c){return console.log("init error :",c),b.Err(String(c))}}async initiateWithCreateOrderResponse(e){const r=e.initiate_transaction.chain_id,n=Dw(r);if(!n)return b.Err(`Unsupported chain ID: ${r}`);const s=await rd(n,this.wallet);if(!s.ok)return b.Err(s.error);if(this.wallet=s.val.walletClient,!this.wallet.account)return b.Err("No account found");try{if(e.typed_data===null){const u=e.initiate_transaction;if(!u)return b.Err("No initiate_transaction found for native initiate");const l=await this.wallet.sendTransaction({account:this.wallet.account,to:b.with0x(u.to),value:BigInt(u.value),data:b.with0x(u.data),gas:BigInt(u.gas_limit),chain:this.wallet.chain}),d=await b.waitForTransactionReceipt(this.wallet,l);return d.val&&d.val.status!=="success"?b.Err("Native initiate transaction failed"):b.Ok(l)}if(e.approval_transaction){const u=await this.executeApprovalTransaction(e);if(u.error)return b.Err(`Approval failed: ${u.error}`);console.log("Approval transaction completed:",u.val)}const{typed_data:i}=e,o=await this.wallet.signTypedData({account:this.wallet.account,domain:i.domain,types:i.types,primaryType:i.primaryType,message:i.message}),a={...(await this.auth.getAuthHeaders()).val,"Content-Type":"application/json"},c=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:o}),headers:a});return c.error?b.Err(c.error):c.result?b.Ok(c.result):b.Err("Initiate failed: Result is undefined")}catch(i){return console.error("initiateWithCreateOrderResponse error:",i),b.Err("Failed to initiate: "+String(i))}}async executeApprovalTransaction(e){if(!this.wallet.account)return b.Err("No account found");if(!e.approval_transaction)return b.Ok("No approval transaction required");try{const r=e.approval_transaction,n=await this.wallet.sendTransaction({account:this.wallet.account,to:b.with0x(r.to),value:BigInt(r.value),data:b.with0x(r.data),gas:BigInt(r.gas_limit),chain:this.wallet.chain}),s=await b.waitForTransactionReceipt(this.wallet,n);return s.val&&s.val.status!=="success"?b.Err("Approval transaction failed"):b.Ok(n)}catch(r){return console.error("executeApprovalTransaction error:",r),b.Err("Failed to execute approval: "+((r==null?void 0:r.message)||String(r)))}}async redeem(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return b.Err(n.error);const s=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:b.trim0x(r)}),headers:{...n.val,"Content-Type":"application/json"}});if(s.error)return b.Err(s.error);const i=iu[e.destination_swap.chain],a=await m_({chain:i,transport:Dg()}).waitForTransactionReceipt({hash:s.result,confirmations:1,timeout:3e5});return a&&a.status==="success"?b.Ok(s.result?s.result:"Redeem hash not found"):b.Err("Redeem failed: Transaction receipt not successful")}catch(n){return b.Err(String(n))}}async refund(){return b.Err("Refund not supported")}}const Vw=[{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"}]}],qw=async(t,e,r,n,s)=>{try{const i=await bo(t.address,e,r,s);if(!i.ok)return b.Err(i.error);if(i.val>=n)return b.Ok("Allowance already approved");const a=Ye.cairo.uint256(BigInt(n)),c=await t.execute([{contractAddress:b.with0x(e),entrypoint:"approve",calldata:[b.with0x(r),a.low,a.high]}]);await s.waitForTransaction(c.transaction_hash,{retryInterval:3e3,successStates:[Ye.TransactionExecutionStatus.SUCCEEDED]}),await b.sleep(2e3);for(let u=0;u<20;u++){const l=await bo(t.address,e,r,s);if(!l.ok)return b.Err(l.error);if(l.val>=n)return b.Ok(c.transaction_hash);await b.sleep(2e3);let d=0n;for(let h=0;h<20;h++){const f=await bo(t.address,e,r,s);if(!f.ok)return b.Err(f.error);if(d=f.val,d>=n)break;await b.sleep(2e3)}return d<n?b.Err("Allowance not approved"):b.Ok(c.transaction_hash)}return b.Err("Allowance not approved after transaction.")}catch(i){return b.Err(`Failed to check or approve allowance: ${i instanceof Error?i.message:String(i)}`)}},bo=async(t,e,r,n)=>{try{const i=await new Ye.Contract(Vw,b.with0x(e),n).call("allowance",[b.with0x(t),b.with0x(r)]);return b.Ok(BigInt((i==null?void 0:i.toString())||"0"))}catch(s){return b.Err(`Failed to check allowance: ${s instanceof Error?s.message:String(s)}`)}},Gw=async(t,e,r,n,s)=>{const i=await bo(t,e,r,n);return i.ok?b.Ok(i.val>=s):b.Err(i.error)},Ww=[{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"}]}],vP={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 Kw{constructor(e,r,n,s,i){this.url=e instanceof b.Url?e:new b.Url(e),this.account=r,this.starknetProvider=new Ye.RpcProvider({nodeUrl:i||Go[n].nodeUrl}),this.chainId=Go[n].chainId,this.auth=s}get htlcActorAddress(){if(!this.account.address)throw new Error("No account found");return this.account.address}async initiate(e){if(ee.isStarknetOrderResponse(e))return this.initiateWithCreateOrderResponse(e);if(!this.account.address)return b.Err("No account address");const{source_swap:r}=e,{redeemer:n,amount:s}=r;if(!s||!n||!r.secret_hash||!r.timelock)return b.Err("Invalid order");try{const i=new Ye.Contract(Ww,e.source_swap.asset,this.account),o=await(i==null?void 0:i.token()),a=Ye.num.toHex(o),c=await Gw(this.account.address,a,r.asset,this.starknetProvider,BigInt(r.amount));return c.error?b.Err(c.error):c.val?this.initiateRelay(e):this.approveAndInitiate(a,e)}catch(i){return b.Err(String(i))}}async approveAndInitiate(e,r){const{source_swap:n}=r,{redeemer:s,amount:i}=n,{secret_hash:o,timelock:a}=n,c=n.asset;try{const u=Ye.cairo.uint256(BigInt(i)),l={contractAddress:b.with0x(e),entrypoint:"approve",calldata:[c,u.low,u.high]},d=Ye.cairo.uint256(i),h={contractAddress:b.with0x(c),entrypoint:"initiate",calldata:[s,a.toString(),d.low.toString(),d.high.toString(),...b.hexToU32Array(o)]},f=await this.account.execute([l,h]);return await this.starknetProvider.waitForTransaction(f.transaction_hash,{retryInterval:2e3,successStates:[Ye.TransactionExecutionStatus.SUCCEEDED]}),b.Ok(f.transaction_hash)}catch(u){return b.Err(`Failed to approve and initiate: ${String(u)}`)}}async initiateRelay(e){const{source_swap:r}=e,{redeemer:n,amount:s}=r;if(!r.secret_hash)return b.Err("Invalid order: secret_hash is undefined");const i=b.with0x(r.secret_hash),a={domain:{name:"HTLC",version:Ye.shortString.encodeShortString("1"),chainId:this.chainId,revision:Ye.TypedDataRevision.ACTIVE},primaryType:"Initiate",types:vP,message:{redeemer:n,amount:Ye.cairo.uint256(s),timelock:e.source_swap.timelock,secretHash:b.hexToU32Array(i)}};try{const c=await this.account.signMessage(a),u=Gp(c);if(u.error)return b.Err(u.error);const l=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:u.val}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return l.error?b.Err(l.error):l.result?b.Ok(l.result):b.Err("Init: No result found")}catch(c){return b.Err(`Failed to initiate relayer: ${String(c)}`)}}async redeem(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return b.Err(n.error);const s=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:b.trim0x(r)}),headers:{...n.val,"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return s.error?b.Err(s.error):s.result?b.Ok(s.result):b.Err("Redeem: No result found")}catch(n){return b.Err(String(n))}}async executeApprovalTransaction(e){if(!this.account.address)return b.Err("No account address");if(!e.approval_transaction)return b.Ok("No approval transaction required");try{const r=e.approval_transaction,n=await this.account.execute([{contractAddress:b.with0x(r.to),entrypoint:b.with0x(r.selector),calldata:r.calldata}]);return await this.starknetProvider.waitForTransaction(n.transaction_hash,{retryInterval:2e3,successStates:[Ye.TransactionExecutionStatus.SUCCEEDED]}),b.Ok(n.transaction_hash)}catch(r){return console.error("executeApprovalTransaction error:",r),b.Err("Failed to execute approval: "+(r instanceof Error&&(r==null?void 0:r.message)||String(r)))}}async initiateWithCreateOrderResponse(e){const r=await this.auth.getAuthHeaders();if(!r.ok)return b.Err(r.error);if(!this.account.address)return b.Err("No account address");const n=await this.executeApprovalTransaction(e);if(n.error)return b.Err(n.error);const{typed_data:s}=e;if(s===null){const c=e.initiate_transaction;if(!c)return b.Err("No initiate_transaction found for native initiate");const u=await this.account.execute([{contractAddress:b.with0x(c.to),entrypoint:b.with0x(c.selector),calldata:c.calldata}]);return await this.starknetProvider.waitForTransaction(u.transaction_hash,{retryInterval:2e3,successStates:[Ye.TransactionExecutionStatus.SUCCEEDED]}),b.Ok(u.transaction_hash)}const i=await this.account.signMessage(s),o=Gp(i);if(o.error)return b.Err(o.error);const a=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:Array.isArray(o.val)?o.val.join(","):o.val}),headers:{...r.val,"Content-Type":"application/json"}});return a.error?b.Err(a.error):b.Ok(a.result)}async refund(){return b.Err("Refund is taken care of by the relayer")}}const EP="2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC",SP={name:"solana_spl_swaps",version:"0.4.0",spec:"0.1.0",description:"Created with Anchor"},AP=[{name:"initiate",docs:["Initiates the atomic swap. Funds are transferred from the initiator to the token vault.","As such, the initiator's signature is required for this instruction.","A sponsor may be involved, who pays PDA rent and transaction fees in SOL, allowing for the","initiator to participate without holding SOL. As such, the sponsor must also sign this transaction.","`swap_amount` represents the quantity of tokens to be transferred through this atomic swap","in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals',"must be provided as 1,000,000.","`expires_in_slots` represents the number of slots after which (non-instant) refunds are allowed.","`destination_data` can hold optional information regarding the destination chain","in the atomic swap, to be emitted in the logs as-is."],discriminator:[5,63,123,113,153,75,148,14],accounts:[{name:"identity_pda",docs:["the token transfers of the `token_vault` PDA.","This PDA will be created during the first most invocation of the `initiate()` function","using the `init_if_needed` attribute, and be reused for all succeeding instructions."],writable:!0,pda:{seeds:[]}},{name:"swap_data",docs:["A PDA that maintains the on-chain state of the atomic swap throughout its lifecycle.","The choice of seeds ensure that any swap with equal `initiator` and","`secret_hash` wont be created until an existing one completes.","This PDA will be deleted upon completion of the swap."],writable:!0,pda:{seeds:[{kind:"account",path:"initiator"},{kind:"arg",path:"secret_hash"}]}},{name:"token_vault",docs:["A permanent PDA that is controlled by the program through the `identity_pda`, as implied",'by the value of the `authority` field below. As such, it serves as the "vault" by escrowing tokens',"of type `mint` for the atomic swap.","It is intended to be reused for all swaps involving the same mint.","Just like `identity_pda`, it will be created during the first most invocation of `initiate()`","of every distinct mint using the `init_if_needed` attribute."],writable:!0,pda:{seeds:[{kind:"account",path:"mint"}]}},{name:"initiator",docs:["The initiator of the atomic swap. They must sign this transaction."],signer:!0},{name:"initiator_token_account",docs:["The token account of the initiator"],writable:!0},{name:"mint",docs:["The mint of the tokens involved in this swap. As this is a parameter, this program can thus be reused","for atomic swaps with different mints."]},{name:"sponsor",docs:["Any entity that pays the PDA rent.","Upon completion of the swap, the PDA rent refund resulting from the","deletion of `swap_data` will be refunded to this address."],writable:!0,signer:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},{name:"system_program",address:"11111111111111111111111111111111"}],args:[{name:"expires_in_slots",type:"u64"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}},{name:"swap_amount",type:"u64"},{name:"destination_data",type:{option:"bytes"}}]},{name:"instant_refund",docs:["Funds are returned to the initiator, with the redeemer's consent.","As such, the redeemer's signature is required for this instruction.","This allows for refunds before the expiry slot."],discriminator:[211,202,103,41,183,147,59,251],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"initiator_token_account",writable:!0},{name:"redeemer",docs:["The redeemer of the atomic swap. They must sign this transaction."],writable:!0,signer:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[]},{name:"redeem",docs:["Funds are transferred to the redeemer. This instruction does not require any signatures."],discriminator:[184,12,86,149,70,196,97,225],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"redeemer_token_account",writable:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[{name:"secret",type:{array:["u8",32]}}]},{name:"refund",docs:["Funds are returned to the initiator, given that no redeems have occured","and the expiry slot has been reached.","This instruction does not require any signatures."],discriminator:[2,96,183,251,63,208,46,46],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"initiator_token_account",writable:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[]}],xP=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],kP=[{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]}],_P=[{code:6e3,name:"InvalidRedeemer",msg:"The provider redeemer is not the original redeemer of this swap"},{code:6001,name:"InvalidSecret",msg:"The provided secret does not correspond to the secret hash of this swap"},{code:6002,name:"InvalidSponsor",msg:"The provided sponsor is not the original sponsor of this swap"},{code:6003,name:"RefundBeforeExpiry",msg:"Attempt to perform a refund before expiry time"}],TP=[{name:"Initiated",docs:["Represents the initiated state of the swap where the initiator has deposited funds into the vault"],type:{kind:"struct",fields:[{name:"swap_amount",docs:["The quantity of tokens transferred through this atomic swap in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals will be represented as 1,000,000.'],type:"u64"},{name:"expires_in_slots",docs:["`expires_in_slots` represents the number of slots after which (non-instant) refunds are allowed"],type:"u64"},{name:"initiator",type:"pubkey"},{name:"mint",type:"pubkey"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}},{name:"destination_data",docs:["Information regarding the destination chain in the atomic swap"],type:{option:"bytes"}}]}},{name:"InstantRefunded",docs:["Represents the instant refund state of the swap, where the initiator has withdrawn funds the vault","with the redeemer's consent"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"Redeemed",docs:["Represents the redeemed state of the swap, where the redeemer has withdrawn funds from the vault"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret",type:{array:["u8",32]}}]}},{name:"Refunded",docs:["Represents the refund state of the swap, where the initiator has withdrawn funds from the vault past expiry"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"SwapAccount",docs:["Stores the state information of the atomic swap on-chain"],type:{kind:"struct",fields:[{name:"expiry_slot",docs:["The exact slot after which (non-instant) refunds are allowed"],type:"u64"},{name:"initiator",docs:["The initiator of the atomic swap"],type:"pubkey"},{name:"redeemer",docs:["The redeemer of the atomic swap"],type:"pubkey"},{name:"secret_hash",docs:["The secret hash associated with the atomic swap"],type:{array:["u8",32]}},{name:"swap_amount",docs:["The quantity tokens to be transferred through this atomic swap","in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals',"must be provided as 1,000,000."],type:"u64"},{name:"identity_pda_bump",docs:["The bump associated with the identity pda.","This is needed by the program to authorize token transfers via the token vault."],type:"u8"},{name:"sponsor",docs:["The entity that paid the rent fees for the creation of this PDA.","This will be referenced during the refund of the same upon closing this PDA."],type:"pubkey"}]}}],Ey={address:EP,metadata:SP,instructions:AP,accounts:xP,events:kP,errors:_P,types:TP},IP="2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",PP={name:"solana_native_swaps",version:"0.3.0",spec:"0.1.0",description:"Created with Anchor"},OP=[{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:[]}],BP=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],CP=[{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]}],$P=[{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"}],RP=[{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]}}]}}],nd={address:IP,metadata:PP,instructions:OP,accounts:BP,events:CP,errors:$P,types:RP};var gn={},ou={};Object.defineProperty(ou,"__esModule",{value:!0});ou.encode=NP;ou.decode=UP;const Sy=Xs;function NP(t){return t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),"0x")}function UP(t){t.indexOf("0x")===0&&(t=t.substr(2)),t.length%2===1&&(t="0"+t);let e=t.match(/.{2}/g);return e===null?Sy.Buffer.from([]):Sy.Buffer.from(e.map(r=>parseInt(r,16)))}var au={},Ds={},Ju;Object.defineProperty(Ds,"__esModule",{value:!0});Ds.isVersionedTransaction=Ds.isBrowser=void 0;Ds.chunks=MP;Ds.isBrowser=process.env.ANCHOR_BROWSER||typeof window<"u"&&!(!((Ju=window.process)===null||Ju===void 0)&&Ju.hasOwnProperty("type"));function MP(t,e){return Array.apply(0,new Array(Math.ceil(t.length/e))).map((r,n)=>t.slice(n*e,(n+1)*e))}const FP=t=>"version"in t;Ds.isVersionedTransaction=FP;var Qu={},el={},tl,Ay;function Zw(){return Ay||(Ay=1,tl=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var s=42;e[r]=s;for(var i in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var o=Object.getOwnPropertySymbols(e);if(o.length!==1||o[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var a=Object.getOwnPropertyDescriptor(e,r);if(a.value!==s||a.enumerable!==!0)return!1}return!0}),tl}var rl,xy;function cu(){if(xy)return rl;xy=1;var t=Zw();return rl=function(){return t()&&!!Symbol.toStringTag},rl}var nl,ky;function Xw(){return ky||(ky=1,nl=Object),nl}var sl,_y;function jP(){return _y||(_y=1,sl=Error),sl}var il,Ty;function LP(){return Ty||(Ty=1,il=EvalError),il}var ol,Iy;function HP(){return Iy||(Iy=1,ol=RangeError),ol}var al,Py;function DP(){return Py||(Py=1,al=ReferenceError),al}var cl,Oy;function Yw(){return Oy||(Oy=1,cl=SyntaxError),cl}var ul,By;function Ea(){return By||(By=1,ul=TypeError),ul}var ll,Cy;function zP(){return Cy||(Cy=1,ll=URIError),ll}var fl,$y;function VP(){return $y||($y=1,fl=Math.abs),fl}var dl,Ry;function qP(){return Ry||(Ry=1,dl=Math.floor),dl}var hl,Ny;function GP(){return Ny||(Ny=1,hl=Math.max),hl}var pl,Uy;function WP(){return Uy||(Uy=1,pl=Math.min),pl}var yl,My;function KP(){return My||(My=1,yl=Math.pow),yl}var ml,Fy;function ZP(){return Fy||(Fy=1,ml=Math.round),ml}var gl,jy;function XP(){return jy||(jy=1,gl=Number.isNaN||function(e){return e!==e}),gl}var bl,Ly;function YP(){if(Ly)return bl;Ly=1;var t=XP();return bl=function(r){return t(r)||r===0?r:r<0?-1:1},bl}var wl,Hy;function JP(){return Hy||(Hy=1,wl=Object.getOwnPropertyDescriptor),wl}var vl,Dy;function Gi(){if(Dy)return vl;Dy=1;var t=JP();if(t)try{t([],"length")}catch{t=null}return vl=t,vl}var El,zy;function uu(){if(zy)return El;zy=1;var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch{t=!1}return El=t,El}var Sl,Vy;function QP(){if(Vy)return Sl;Vy=1;var t=typeof Symbol<"u"&&Symbol,e=Zw();return Sl=function(){return typeof t!="function"||typeof Symbol!="function"||typeof t("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Sl}var Al,qy;function Jw(){return qy||(qy=1,Al=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),Al}var xl,Gy;function Qw(){if(Gy)return xl;Gy=1;var t=Xw();return xl=t.getPrototypeOf||null,xl}var kl,Wy;function eO(){if(Wy)return kl;Wy=1;var t="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,r=Math.max,n="[object Function]",s=function(c,u){for(var l=[],d=0;d<c.length;d+=1)l[d]=c[d];for(var h=0;h<u.length;h+=1)l[h+c.length]=u[h];return l},i=function(c,u){for(var l=[],d=u,h=0;d<c.length;d+=1,h+=1)l[h]=c[d];return l},o=function(a,c){for(var u="",l=0;l<a.length;l+=1)u+=a[l],l+1<a.length&&(u+=c);return u};return kl=function(c){var u=this;if(typeof u!="function"||e.apply(u)!==n)throw new TypeError(t+u);for(var l=i(arguments,1),d,h=function(){if(this instanceof d){var S=u.apply(this,s(l,arguments));return Object(S)===S?S:this}return u.apply(c,s(l,arguments))},f=r(0,u.length-l.length),m=[],g=0;g<f;g++)m[g]="$"+g;if(d=Function("binder","return function ("+o(m,",")+"){ return binder.apply(this,arguments); }")(h),u.prototype){var v=function(){};v.prototype=u.prototype,d.prototype=new v,v.prototype=null}return d},kl}var _l,Ky;function Sa(){if(Ky)return _l;Ky=1;var t=eO();return _l=Function.prototype.bind||t,_l}var Tl,Zy;function Ah(){return Zy||(Zy=1,Tl=Function.prototype.call),Tl}var Il,Xy;function xh(){return Xy||(Xy=1,Il=Function.prototype.apply),Il}var Pl,Yy;function tO(){return Yy||(Yy=1,Pl=typeof Reflect<"u"&&Reflect&&Reflect.apply),Pl}var Ol,Jy;function e1(){if(Jy)return Ol;Jy=1;var t=Sa(),e=xh(),r=Ah(),n=tO();return Ol=n||t.call(r,e),Ol}var Bl,Qy;function kh(){if(Qy)return Bl;Qy=1;var t=Sa(),e=Ea(),r=Ah(),n=e1();return Bl=function(i){if(i.length<1||typeof i[0]!="function")throw new e("a function is required");return n(t,r,i)},Bl}var Cl,em;function rO(){if(em)return Cl;em=1;var t=kh(),e=Gi(),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&&e&&e(Object.prototype,"__proto__"),s=Object,i=s.getPrototypeOf;return Cl=n&&typeof n.get=="function"?t([n.get]):typeof i=="function"?function(a){return i(a==null?a:s(a))}:!1,Cl}var $l,tm;function _h(){if(tm)return $l;tm=1;var t=Jw(),e=Qw(),r=rO();return $l=t?function(s){return t(s)}:e?function(s){if(!s||typeof s!="object"&&typeof s!="function")throw new TypeError("getProto: not an object");return e(s)}:r?function(s){return r(s)}:null,$l}var Rl,rm;function t1(){if(rm)return Rl;rm=1;var t=Function.prototype.call,e=Object.prototype.hasOwnProperty,r=Sa();return Rl=r.call(t,e),Rl}var Nl,nm;function r1(){if(nm)return Nl;nm=1;var t,e=Xw(),r=jP(),n=LP(),s=HP(),i=DP(),o=Yw(),a=Ea(),c=zP(),u=VP(),l=qP(),d=GP(),h=WP(),f=KP(),m=ZP(),g=YP(),v=Function,S=function(ie){try{return v('"use strict"; return ('+ie+").constructor;")()}catch{}},_=Gi(),E=uu(),x=function(){throw new a},O=_?function(){try{return arguments.callee,x}catch{try{return _(arguments,"callee").get}catch{return x}}}():x,P=QP()(),$=_h(),z=Qw(),C=Jw(),Y=xh(),W=Ah(),K={},U=typeof Uint8Array>"u"||!$?t:$(Uint8Array),N={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?t:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?t:ArrayBuffer,"%ArrayIteratorPrototype%":P&&$?$([][Symbol.iterator]()):t,"%AsyncFromSyncIteratorPrototype%":t,"%AsyncFunction%":K,"%AsyncGenerator%":K,"%AsyncGeneratorFunction%":K,"%AsyncIteratorPrototype%":K,"%Atomics%":typeof Atomics>"u"?t:Atomics,"%BigInt%":typeof BigInt>"u"?t:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?t:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?t:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?t:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":typeof Float16Array>"u"?t:Float16Array,"%Float32Array%":typeof Float32Array>"u"?t:Float32Array,"%Float64Array%":typeof Float64Array>"u"?t:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?t:FinalizationRegistry,"%Function%":v,"%GeneratorFunction%":K,"%Int8Array%":typeof Int8Array>"u"?t:Int8Array,"%Int16Array%":typeof Int16Array>"u"?t:Int16Array,"%Int32Array%":typeof Int32Array>"u"?t:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":P&&$?$($([][Symbol.iterator]())):t,"%JSON%":typeof JSON=="object"?JSON:t,"%Map%":typeof Map>"u"?t:Map,"%MapIteratorPrototype%":typeof Map>"u"||!P||!$?t:$(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":e,"%Object.getOwnPropertyDescriptor%":_,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?t:Promise,"%Proxy%":typeof Proxy>"u"?t:Proxy,"%RangeError%":s,"%ReferenceError%":i,"%Reflect%":typeof Reflect>"u"?t:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?t:Set,"%SetIteratorPrototype%":typeof Set>"u"||!P||!$?t:$(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?t:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":P&&$?$(""[Symbol.iterator]()):t,"%Symbol%":P?Symbol:t,"%SyntaxError%":o,"%ThrowTypeError%":O,"%TypedArray%":U,"%TypeError%":a,"%Uint8Array%":typeof Uint8Array>"u"?t:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?t:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?t:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?t:Uint32Array,"%URIError%":c,"%WeakMap%":typeof WeakMap>"u"?t:WeakMap,"%WeakRef%":typeof WeakRef>"u"?t:WeakRef,"%WeakSet%":typeof WeakSet>"u"?t:WeakSet,"%Function.prototype.call%":W,"%Function.prototype.apply%":Y,"%Object.defineProperty%":E,"%Object.getPrototypeOf%":z,"%Math.abs%":u,"%Math.floor%":l,"%Math.max%":d,"%Math.min%":h,"%Math.pow%":f,"%Math.round%":m,"%Math.sign%":g,"%Reflect.getPrototypeOf%":C};if($)try{null.error}catch(ie){var F=$($(ie));N["%Error.prototype%"]=F}var Z=function ie(oe){var me;if(oe==="%AsyncFunction%")me=S("async function () {}");else if(oe==="%GeneratorFunction%")me=S("function* () {}");else if(oe==="%AsyncGeneratorFunction%")me=S("async function* () {}");else if(oe==="%AsyncGenerator%"){var be=ie("%AsyncGeneratorFunction%");be&&(me=be.prototype)}else if(oe==="%AsyncIteratorPrototype%"){var Se=ie("%AsyncGenerator%");Se&&$&&(me=$(Se.prototype))}return N[oe]=me,me},te={__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"]},H=Sa(),T=t1(),L=H.call(W,Array.prototype.concat),G=H.call(Y,Array.prototype.splice),I=H.call(W,String.prototype.replace),R=H.call(W,String.prototype.slice),j=H.call(W,RegExp.prototype.exec),J=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,se=/\\(\\)?/g,ue=function(oe){var me=R(oe,0,1),be=R(oe,-1);if(me==="%"&&be!=="%")throw new o("invalid intrinsic syntax, expected closing `%`");if(be==="%"&&me!=="%")throw new o("invalid intrinsic syntax, expected opening `%`");var Se=[];return I(oe,J,function(Ue,Lt,et,Cr){Se[Se.length]=et?I(Cr,se,"$1"):Lt||Ue}),Se},ce=function(oe,me){var be=oe,Se;if(T(te,be)&&(Se=te[be],be="%"+Se[0]+"%"),T(N,be)){var Ue=N[be];if(Ue===K&&(Ue=Z(be)),typeof Ue>"u"&&!me)throw new a("intrinsic "+oe+" exists, but is not available. Please file an issue!");return{alias:Se,name:be,value:Ue}}throw new o("intrinsic "+oe+" does not exist!")};return Nl=function(oe,me){if(typeof oe!="string"||oe.length===0)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof me!="boolean")throw new a('"allowMissing" argument must be a boolean');if(j(/^%?[^%]*%?$/,oe)===null)throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var be=ue(oe),Se=be.length>0?be[0]:"",Ue=ce("%"+Se+"%",me),Lt=Ue.name,et=Ue.value,Cr=!1,cs=Ue.alias;cs&&(Se=cs[0],G(be,L([0,1],cs)));for(var q=1,$r=!0;q<be.length;q+=1){var vt=be[q],Et=R(vt,0,1),Bn=R(vt,-1);if((Et==='"'||Et==="'"||Et==="`"||Bn==='"'||Bn==="'"||Bn==="`")&&Et!==Bn)throw new o("property names with quotes must have matching quotes");if((vt==="constructor"||!$r)&&(Cr=!0),Se+="."+vt,Lt="%"+Se+"%",T(N,Lt))et=N[Lt];else if(et!=null){if(!(vt in et)){if(!me)throw new a("base intrinsic for "+oe+" exists, but the property is not available.");return}if(_&&q+1>=be.length){var ei=_(et,vt);$r=!!ei,$r&&"get"in ei&&!("originalValue"in ei.get)?et=ei.get:et=et[vt]}else $r=T(et,vt),et=et[vt];$r&&!Cr&&(N[Lt]=et)}}return et},Nl}var Ul,sm;function Aa(){if(sm)return Ul;sm=1;var t=r1(),e=kh(),r=e([t("%String.prototype.indexOf%")]);return Ul=function(s,i){var o=t(s,!!i);return typeof o=="function"&&r(s,".prototype.")>-1?e([o]):o},Ul}var Ml,im;function nO(){if(im)return Ml;im=1;var t=cu()(),e=Aa(),r=e("Object.prototype.toString"),n=function(a){return t&&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,Ml=i?n:s,Ml}var Fl,om;function sO(){if(om)return Fl;om=1;var t=Aa(),e=cu()(),r=t1(),n=Gi(),s;if(e){var i=t("RegExp.prototype.exec"),o={},a=function(){throw o},c={toString:a,valueOf:a};typeof Symbol.toPrimitive=="symbol"&&(c[Symbol.toPrimitive]=a),s=function(h){if(!h||typeof h!="object")return!1;var f=n(h,"lastIndex"),m=f&&r(f,"value");if(!m)return!1;try{i(h,c)}catch(g){return g===o}}}else{var u=t("Object.prototype.toString"),l="[object RegExp]";s=function(h){return!h||typeof h!="object"&&typeof h!="function"?!1:u(h)===l}}return Fl=s,Fl}var jl,am;function iO(){if(am)return jl;am=1;var t=Aa(),e=sO(),r=t("RegExp.prototype.exec"),n=Ea();return jl=function(i){if(!e(i))throw new n("`regex` must be a RegExp");return function(a){return r(i,a)!==null}},jl}var Ll,cm;function oO(){if(cm)return Ll;cm=1;var t=Aa(),e=iO(),r=e(/^\s*(?:function)?\*/),n=cu()(),s=_h(),i=t("Object.prototype.toString"),o=t("Function.prototype.toString"),a=function(){if(!n)return!1;try{return Function("return function*() {}")()}catch{}},c;return Ll=function(l){if(typeof l!="function")return!1;if(r(o(l)))return!0;if(!n){var d=i(l);return d==="[object GeneratorFunction]"}if(!s)return!1;if(typeof c>"u"){var h=a();c=h?s(h):!1}return s(l)===c},Ll}var Hl,um;function aO(){if(um)return Hl;um=1;var t=Function.prototype.toString,e=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,r,n;if(typeof e=="function"&&typeof Object.defineProperty=="function")try{r=Object.defineProperty({},"length",{get:function(){throw n}}),n={},e(function(){throw 42},null,r)}catch(_){_!==n&&(e=null)}else e=null;var s=/^\s*class\b/,i=function(E){try{var x=t.call(E);return s.test(x)}catch{return!1}},o=function(E){try{return i(E)?!1:(t.call(E),!0)}catch{return!1}},a=Object.prototype.toString,c="[object Object]",u="[object Function]",l="[object GeneratorFunction]",d="[object HTMLAllCollection]",h="[object HTML document.all class]",f="[object HTMLCollection]",m=typeof Symbol=="function"&&!!Symbol.toStringTag,g=!(0 in[,]),v=function(){return!1};if(typeof document=="object"){var S=document.all;a.call(S)===a.call(document.all)&&(v=function(E){if((g||!E)&&(typeof E>"u"||typeof E=="object"))try{var x=a.call(E);return(x===d||x===h||x===f||x===c)&&E("")==null}catch{}return!1})}return Hl=e?function(E){if(v(E))return!0;if(!E||typeof E!="function"&&typeof E!="object")return!1;try{e(E,null,r)}catch(x){if(x!==n)return!1}return!i(E)&&o(E)}:function(E){if(v(E))return!0;if(!E||typeof E!="function"&&typeof E!="object")return!1;if(m)return o(E);if(i(E))return!1;var x=a.call(E);return x!==u&&x!==l&&!/^\[object HTML/.test(x)?!1:o(E)},Hl}var Dl,lm;function cO(){if(lm)return Dl;lm=1;var t=aO(),e=Object.prototype.toString,r=Object.prototype.hasOwnProperty,n=function(c,u,l){for(var d=0,h=c.length;d<h;d++)r.call(c,d)&&(l==null?u(c[d],d,c):u.call(l,c[d],d,c))},s=function(c,u,l){for(var d=0,h=c.length;d<h;d++)l==null?u(c.charAt(d),d,c):u.call(l,c.charAt(d),d,c)},i=function(c,u,l){for(var d in c)r.call(c,d)&&(l==null?u(c[d],d,c):u.call(l,c[d],d,c))};function o(a){return e.call(a)==="[object Array]"}return Dl=function(c,u,l){if(!t(u))throw new TypeError("iterator must be a function");var d;arguments.length>=3&&(d=l),o(c)?n(c,u,d):typeof c=="string"?s(c,u,d):i(c,u,d)},Dl}var zl,fm;function uO(){return fm||(fm=1,zl=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),zl}var Vl,dm;function lO(){if(dm)return Vl;dm=1;var t=uO(),e=typeof globalThis>"u"?Yr:globalThis;return Vl=function(){for(var n=[],s=0;s<t.length;s++)typeof e[t[s]]=="function"&&(n[n.length]=t[s]);return n},Vl}var ql={exports:{}},Gl,hm;function fO(){if(hm)return Gl;hm=1;var t=uu(),e=Yw(),r=Ea(),n=Gi();return Gl=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,u=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,d=arguments.length>6?arguments[6]:!1,h=!!n&&n(i,o);if(t)t(i,o,{configurable:l===null&&h?h.configurable:!l,enumerable:c===null&&h?h.enumerable:!c,value:a,writable:u===null&&h?h.writable:!u});else if(d||!c&&!u&&!l)i[o]=a;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Gl}var Wl,pm;function dO(){if(pm)return Wl;pm=1;var t=uu(),e=function(){return!!t};return e.hasArrayLengthDefineBug=function(){if(!t)return null;try{return t([],"length",{value:1}).length!==1}catch{return!0}},Wl=e,Wl}var Kl,ym;function hO(){if(ym)return Kl;ym=1;var t=r1(),e=fO(),r=dO()(),n=Gi(),s=Ea(),i=t("%Math.floor%");return Kl=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 u=arguments.length>2&&!!arguments[2],l=!0,d=!0;if("length"in a&&n){var h=n(a,"length");h&&!h.configurable&&(l=!1),h&&!h.writable&&(d=!1)}return(l||d||!u)&&(r?e(a,"length",c,!0,!0):e(a,"length",c)),a},Kl}var Zl,mm;function pO(){if(mm)return Zl;mm=1;var t=Sa(),e=xh(),r=e1();return Zl=function(){return r(t,e,arguments)},Zl}var gm;function yO(){return gm||(gm=1,function(t){var e=hO(),r=uu(),n=kh(),s=pO();t.exports=function(o){var a=n(arguments),c=o.length-(arguments.length-1);return e(a,1+(c>0?c:0),!0)},r?r(t.exports,"apply",{value:s}):t.exports.apply=s}(ql)),ql.exports}var Xl,bm;function n1(){if(bm)return Xl;bm=1;var t=cO(),e=lO(),r=yO(),n=Aa(),s=Gi(),i=_h(),o=n("Object.prototype.toString"),a=cu()(),c=typeof globalThis>"u"?Yr:globalThis,u=e(),l=n("String.prototype.slice"),d=n("Array.prototype.indexOf",!0)||function(v,S){for(var _=0;_<v.length;_+=1)if(v[_]===S)return _;return-1},h={__proto__:null};a&&s&&i?t(u,function(g){var v=new c[g];if(Symbol.toStringTag in v&&i){var S=i(v),_=s(S,Symbol.toStringTag);if(!_&&S){var E=i(S);_=s(E,Symbol.toStringTag)}h["$"+g]=r(_.get)}}):t(u,function(g){var v=new c[g],S=v.slice||v.set;S&&(h["$"+g]=r(S))});var f=function(v){var S=!1;return t(h,function(_,E){if(!S)try{"$"+_(v)===E&&(S=l(E,1))}catch{}}),S},m=function(v){var S=!1;return t(h,function(_,E){if(!S)try{_(v),S=l(E,1)}catch{}}),S};return Xl=function(v){if(!v||typeof v!="object")return!1;if(!a){var S=l(o(v),8,-1);return d(u,S)>-1?S:S!=="Object"?!1:m(v)}return s?f(v):null},Xl}var Yl,wm;function mO(){if(wm)return Yl;wm=1;var t=n1();return Yl=function(r){return!!t(r)},Yl}var vm;function gO(){return vm||(vm=1,function(t){var e=nO(),r=oO(),n=n1(),s=mO();function i(q){return q.call.bind(q)}var o=typeof BigInt<"u",a=typeof Symbol<"u",c=i(Object.prototype.toString),u=i(Number.prototype.valueOf),l=i(String.prototype.valueOf),d=i(Boolean.prototype.valueOf);if(o)var h=i(BigInt.prototype.valueOf);if(a)var f=i(Symbol.prototype.valueOf);function m(q,$r){if(typeof q!="object")return!1;try{return $r(q),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=r,t.isTypedArray=s;function g(q){return typeof Promise<"u"&&q instanceof Promise||q!==null&&typeof q=="object"&&typeof q.then=="function"&&typeof q.catch=="function"}t.isPromise=g;function v(q){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(q):s(q)||R(q)}t.isArrayBufferView=v;function S(q){return n(q)==="Uint8Array"}t.isUint8Array=S;function _(q){return n(q)==="Uint8ClampedArray"}t.isUint8ClampedArray=_;function E(q){return n(q)==="Uint16Array"}t.isUint16Array=E;function x(q){return n(q)==="Uint32Array"}t.isUint32Array=x;function O(q){return n(q)==="Int8Array"}t.isInt8Array=O;function P(q){return n(q)==="Int16Array"}t.isInt16Array=P;function $(q){return n(q)==="Int32Array"}t.isInt32Array=$;function z(q){return n(q)==="Float32Array"}t.isFloat32Array=z;function C(q){return n(q)==="Float64Array"}t.isFloat64Array=C;function Y(q){return n(q)==="BigInt64Array"}t.isBigInt64Array=Y;function W(q){return n(q)==="BigUint64Array"}t.isBigUint64Array=W;function K(q){return c(q)==="[object Map]"}K.working=typeof Map<"u"&&K(new Map);function U(q){return typeof Map>"u"?!1:K.working?K(q):q instanceof Map}t.isMap=U;function N(q){return c(q)==="[object Set]"}N.working=typeof Set<"u"&&N(new Set);function F(q){return typeof Set>"u"?!1:N.working?N(q):q instanceof Set}t.isSet=F;function Z(q){return c(q)==="[object WeakMap]"}Z.working=typeof WeakMap<"u"&&Z(new WeakMap);function te(q){return typeof WeakMap>"u"?!1:Z.working?Z(q):q instanceof WeakMap}t.isWeakMap=te;function H(q){return c(q)==="[object WeakSet]"}H.working=typeof WeakSet<"u"&&H(new WeakSet);function T(q){return H(q)}t.isWeakSet=T;function L(q){return c(q)==="[object ArrayBuffer]"}L.working=typeof ArrayBuffer<"u"&&L(new ArrayBuffer);function G(q){return typeof ArrayBuffer>"u"?!1:L.working?L(q):q instanceof ArrayBuffer}t.isArrayBuffer=G;function I(q){return c(q)==="[object DataView]"}I.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&I(new DataView(new ArrayBuffer(1),0,1));function R(q){return typeof DataView>"u"?!1:I.working?I(q):q instanceof DataView}t.isDataView=R;var j=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function J(q){return c(q)==="[object SharedArrayBuffer]"}function se(q){return typeof j>"u"?!1:(typeof J.working>"u"&&(J.working=J(new j)),J.working?J(q):q instanceof j)}t.isSharedArrayBuffer=se;function ue(q){return c(q)==="[object AsyncFunction]"}t.isAsyncFunction=ue;function ce(q){return c(q)==="[object Map Iterator]"}t.isMapIterator=ce;function ie(q){return c(q)==="[object Set Iterator]"}t.isSetIterator=ie;function oe(q){return c(q)==="[object Generator]"}t.isGeneratorObject=oe;function me(q){return c(q)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=me;function be(q){return m(q,u)}t.isNumberObject=be;function Se(q){return m(q,l)}t.isStringObject=Se;function Ue(q){return m(q,d)}t.isBooleanObject=Ue;function Lt(q){return o&&m(q,h)}t.isBigIntObject=Lt;function et(q){return a&&m(q,f)}t.isSymbolObject=et;function Cr(q){return be(q)||Se(q)||Ue(q)||Lt(q)||et(q)}t.isBoxedPrimitive=Cr;function cs(q){return typeof Uint8Array<"u"&&(G(q)||se(q))}t.isAnyArrayBuffer=cs,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(q){Object.defineProperty(t,q,{enumerable:!1,value:function(){throw new Error(q+" is not supported in userland")}})})}(el)),el}var Jl,Em;function bO(){return Em||(Em=1,Jl=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"}),Jl}var qa={exports:{}},Sm;function wO(){return Sm||(Sm=1,typeof Object.create=="function"?qa.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:qa.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}),qa.exports}var Am;function s1(){return Am||(Am=1,function(t){var e=Object.getOwnPropertyDescriptors||function(R){for(var j=Object.keys(R),J={},se=0;se<j.length;se++)J[j[se]]=Object.getOwnPropertyDescriptor(R,j[se]);return J},r=/%[sdj%]/g;t.format=function(I){if(!O(I)){for(var R=[],j=0;j<arguments.length;j++)R.push(o(arguments[j]));return R.join(" ")}for(var j=1,J=arguments,se=J.length,ue=String(I).replace(r,function(ie){if(ie==="%%")return"%";if(j>=se)return ie;switch(ie){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 ie}}),ce=J[j];j<se;ce=J[++j])_(ce)||!C(ce)?ue+=" "+ce:ue+=" "+o(ce);return ue},t.deprecate=function(I,R){if(typeof process<"u"&&process.noDeprecation===!0)return I;if(typeof process>"u")return function(){return t.deprecate(I,R).apply(this,arguments)};var j=!1;function J(){if(!j){if(process.throwDeprecation)throw new Error(R);process.traceDeprecation?console.trace(R):console.error(R),j=!0}return I.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")}t.debuglog=function(I){if(I=I.toUpperCase(),!n[I])if(s.test(I)){var R=process.pid;n[I]=function(){var j=t.format.apply(t,arguments);console.error("%s %d: %s",I,R,j)}}else n[I]=function(){};return n[I]};function o(I,R){var j={seen:[],stylize:c};return arguments.length>=3&&(j.depth=arguments[2]),arguments.length>=4&&(j.colors=arguments[3]),S(R)?j.showHidden=R:R&&t._extend(j,R),$(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),l(j,I,j.depth)}t.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(I,R){var j=o.styles[R];return j?"\x1B["+o.colors[j][0]+"m"+I+"\x1B["+o.colors[j][1]+"m":I}function c(I,R){return I}function u(I){var R={};return I.forEach(function(j,J){R[j]=!0}),R}function l(I,R,j){if(I.customInspect&&R&&K(R.inspect)&&R.inspect!==t.inspect&&!(R.constructor&&R.constructor.prototype===R)){var J=R.inspect(j,I);return O(J)||(J=l(I,J,j)),J}var se=d(I,R);if(se)return se;var ue=Object.keys(R),ce=u(ue);if(I.showHidden&&(ue=Object.getOwnPropertyNames(R)),W(R)&&(ue.indexOf("message")>=0||ue.indexOf("description")>=0))return h(R);if(ue.length===0){if(K(R)){var ie=R.name?": "+R.name:"";return I.stylize("[Function"+ie+"]","special")}if(z(R))return I.stylize(RegExp.prototype.toString.call(R),"regexp");if(Y(R))return I.stylize(Date.prototype.toString.call(R),"date");if(W(R))return h(R)}var oe="",me=!1,be=["{","}"];if(v(R)&&(me=!0,be=["[","]"]),K(R)){var Se=R.name?": "+R.name:"";oe=" [Function"+Se+"]"}if(z(R)&&(oe=" "+RegExp.prototype.toString.call(R)),Y(R)&&(oe=" "+Date.prototype.toUTCString.call(R)),W(R)&&(oe=" "+h(R)),ue.length===0&&(!me||R.length==0))return be[0]+oe+be[1];if(j<0)return z(R)?I.stylize(RegExp.prototype.toString.call(R),"regexp"):I.stylize("[Object]","special");I.seen.push(R);var Ue;return me?Ue=f(I,R,j,ce,ue):Ue=ue.map(function(Lt){return m(I,R,j,ce,Lt,me)}),I.seen.pop(),g(Ue,oe,be)}function d(I,R){if($(R))return I.stylize("undefined","undefined");if(O(R)){var j="'"+JSON.stringify(R).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return I.stylize(j,"string")}if(x(R))return I.stylize(""+R,"number");if(S(R))return I.stylize(""+R,"boolean");if(_(R))return I.stylize("null","null")}function h(I){return"["+Error.prototype.toString.call(I)+"]"}function f(I,R,j,J,se){for(var ue=[],ce=0,ie=R.length;ce<ie;++ce)H(R,String(ce))?ue.push(m(I,R,j,J,String(ce),!0)):ue.push("");return se.forEach(function(oe){oe.match(/^\d+$/)||ue.push(m(I,R,j,J,oe,!0))}),ue}function m(I,R,j,J,se,ue){var ce,ie,oe;if(oe=Object.getOwnPropertyDescriptor(R,se)||{value:R[se]},oe.get?oe.set?ie=I.stylize("[Getter/Setter]","special"):ie=I.stylize("[Getter]","special"):oe.set&&(ie=I.stylize("[Setter]","special")),H(J,se)||(ce="["+se+"]"),ie||(I.seen.indexOf(oe.value)<0?(_(j)?ie=l(I,oe.value,null):ie=l(I,oe.value,j-1),ie.indexOf(`
74
- `)>-1&&(ue?ie=ie.split(`
75
- `).map(function(me){return" "+me}).join(`
76
- `).slice(2):ie=`
77
- `+ie.split(`
78
- `).map(function(me){return" "+me}).join(`
79
- `))):ie=I.stylize("[Circular]","special")),$(ce)){if(ue&&se.match(/^\d+$/))return ie;ce=JSON.stringify(""+se),ce.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(ce=ce.slice(1,-1),ce=I.stylize(ce,"name")):(ce=ce.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),ce=I.stylize(ce,"string"))}return ce+": "+ie}function g(I,R,j){var J=I.reduce(function(se,ue){return ue.indexOf(`
80
- `)>=0,se+ue.replace(/\u001b\[\d\d?m/g,"").length+1},0);return J>60?j[0]+(R===""?"":R+`
81
- `)+" "+I.join(`,
82
- `)+" "+j[1]:j[0]+R+" "+I.join(", ")+" "+j[1]}t.types=gO();function v(I){return Array.isArray(I)}t.isArray=v;function S(I){return typeof I=="boolean"}t.isBoolean=S;function _(I){return I===null}t.isNull=_;function E(I){return I==null}t.isNullOrUndefined=E;function x(I){return typeof I=="number"}t.isNumber=x;function O(I){return typeof I=="string"}t.isString=O;function P(I){return typeof I=="symbol"}t.isSymbol=P;function $(I){return I===void 0}t.isUndefined=$;function z(I){return C(I)&&N(I)==="[object RegExp]"}t.isRegExp=z,t.types.isRegExp=z;function C(I){return typeof I=="object"&&I!==null}t.isObject=C;function Y(I){return C(I)&&N(I)==="[object Date]"}t.isDate=Y,t.types.isDate=Y;function W(I){return C(I)&&(N(I)==="[object Error]"||I instanceof Error)}t.isError=W,t.types.isNativeError=W;function K(I){return typeof I=="function"}t.isFunction=K;function U(I){return I===null||typeof I=="boolean"||typeof I=="number"||typeof I=="string"||typeof I=="symbol"||typeof I>"u"}t.isPrimitive=U,t.isBuffer=bO();function N(I){return Object.prototype.toString.call(I)}function F(I){return I<10?"0"+I.toString(10):I.toString(10)}var Z=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function te(){var I=new Date,R=[F(I.getHours()),F(I.getMinutes()),F(I.getSeconds())].join(":");return[I.getDate(),Z[I.getMonth()],R].join(" ")}t.log=function(){console.log("%s - %s",te(),t.format.apply(t,arguments))},t.inherits=wO(),t._extend=function(I,R){if(!R||!C(R))return I;for(var j=Object.keys(R),J=j.length;J--;)I[j[J]]=R[j[J]];return I};function H(I,R){return Object.prototype.hasOwnProperty.call(I,R)}var T=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;t.promisify=function(R){if(typeof R!="function")throw new TypeError('The "original" argument must be of type Function');if(T&&R[T]){var j=R[T];if(typeof j!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(j,T,{value:j,enumerable:!1,writable:!1,configurable:!0}),j}function j(){for(var J,se,ue=new Promise(function(oe,me){J=oe,se=me}),ce=[],ie=0;ie<arguments.length;ie++)ce.push(arguments[ie]);ce.push(function(oe,me){oe?se(oe):J(me)});try{R.apply(this,ce)}catch(oe){se(oe)}return ue}return Object.setPrototypeOf(j,Object.getPrototypeOf(R)),T&&Object.defineProperty(j,T,{value:j,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(j,e(R))},t.promisify.custom=T;function L(I,R){if(!I){var j=new Error("Promise was rejected with a falsy value");j.reason=I,I=j}return R(I)}function G(I){if(typeof I!="function")throw new TypeError('The "original" argument must be of type Function');function R(){for(var j=[],J=0;J<arguments.length;J++)j.push(arguments[J]);var se=j.pop();if(typeof se!="function")throw new TypeError("The last argument must be of type Function");var ue=this,ce=function(){return se.apply(ue,arguments)};I.apply(this,j).then(function(ie){process.nextTick(ce.bind(null,null,ie))},function(ie){process.nextTick(L.bind(null,ie,ce))})}return Object.setPrototypeOf(R,Object.getPrototypeOf(I)),Object.defineProperties(R,e(I)),R}t.callbackify=G}(Qu)),Qu}Object.defineProperty(au,"__esModule",{value:!0});au.decode=vO;au.encode=EO;const i1=Ds;function vO(t){return(i1.isBrowser?new TextDecoder("utf-8"):new(s1()).TextDecoder("utf-8")).decode(t)}function EO(t){return(i1.isBrowser?new TextEncoder:new(s1()).TextEncoder("utf-8")).encode(t)}var lu={},sd={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(t,e){var r=Xs,n=r.Buffer;function s(o,a){for(var c in o)a[c]=o[c]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(s(r,e),e.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 u=n(o);return a!==void 0?typeof c=="string"?u.fill(a,c):u.fill(a):u.fill(0),u},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)}})(sd,sd.exports);var SO=sd.exports,Ga=SO.Buffer;function AO(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r<e.length;r++)e[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=n}var o=t.length,a=t.charAt(0),c=Math.log(o)/Math.log(256),u=Math.log(256)/Math.log(o);function l(f){if((Array.isArray(f)||f instanceof Uint8Array)&&(f=Ga.from(f)),!Ga.isBuffer(f))throw new TypeError("Expected Buffer");if(f.length===0)return"";for(var m=0,g=0,v=0,S=f.length;v!==S&&f[v]===0;)v++,m++;for(var _=(S-v)*u+1>>>0,E=new Uint8Array(_);v!==S;){for(var x=f[v],O=0,P=_-1;(x!==0||O<g)&&P!==-1;P--,O++)x+=256*E[P]>>>0,E[P]=x%o>>>0,x=x/o>>>0;if(x!==0)throw new Error("Non-zero carry");g=O,v++}for(var $=_-g;$!==_&&E[$]===0;)$++;for(var z=a.repeat(m);$<_;++$)z+=t.charAt(E[$]);return z}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return Ga.alloc(0);for(var m=0,g=0,v=0;f[m]===a;)g++,m++;for(var S=(f.length-m)*c+1>>>0,_=new Uint8Array(S);m<f.length;){var E=f.charCodeAt(m);if(E>255)return;var x=e[E];if(x===255)return;for(var O=0,P=S-1;(x!==0||O<v)&&P!==-1;P--,O++)x+=o*_[P]>>>0,_[P]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");v=O,m++}for(var $=S-v;$!==S&&_[$]===0;)$++;var z=Ga.allocUnsafe(g+(S-$));z.fill(0,0,g);for(var C=g;$!==S;)z[C++]=_[$++];return z}function h(f){var m=d(f);if(m)return m;throw new Error("Non-base"+o+" character")}return{encode:l,decodeUnsafe:d,decode:h}}var xO=AO,kO=xO,_O="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",TO=kO(_O),IO=Yr&&Yr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(lu,"__esModule",{value:!0});lu.encode=PO;lu.decode=OO;const o1=IO(TO);function PO(t){return o1.default.encode(t)}function OO(t){return o1.default.decode(t)}var fu={};Object.defineProperty(fu,"__esModule",{value:!0});fu.encode=CO;fu.decode=$O;const BO=Xs;function CO(t){return t.toString("base64")}function $O(t){return BO.Buffer.from(t,"base64")}var RO=Yr&&Yr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),NO=Yr&&Yr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),du=Yr&&Yr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&RO(e,t,r);return NO(e,t),e};Object.defineProperty(gn,"__esModule",{value:!0});gn.base64=gn.bs58=gn.utf8=a1=gn.hex=void 0;var a1=gn.hex=du(ou);gn.utf8=du(au);gn.bs58=du(lu);gn.base64=du(fu);class Jn{constructor(e,r,n,s,i){try{this.swapId=Array.from(Buffer.from(e,"hex")),this.secretHash=Array.from(Buffer.from(n,"hex"))}catch(o){throw new Error("Error decoding swapId or secretHash",{cause:o})}if(this.secretHash.length!=32||this.swapId.length!=32)throw new Error("swapId or secretHash must be exactly 32 bits in size");try{this.redeemer=new zt.web3.PublicKey(r)}catch(o){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:o})}try{this.amount=new zt.BN(s.toString(10),10),this.expiresIn=new zt.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(e){let r;if(e.source_swap.chain.includes("solana"))r=e.source_swap;else if(e.destination_swap.chain.includes("solana"))r=e.destination_swap;else throw new Error("Expected source_swap or destination_swap to be one of 'solana', 'solana_localnet', 'solana_devnet'");const{swap_id:n,redeemer:s,secret_hash:i,timelock:o}=r,a=BigInt(r.amount);return new Jn(n,s,i,a,o)}}function c1(t){let e;try{e=[...a1.decode(t)]}catch(r){throw new Error("Error decoding secret. Ensure it is a hex string",{cause:r})}if(e.length!=32)throw new Error("Invalid Secret size. Expected 32 bytes, got "+e.length);return e}class u1{constructor(e,r,n,s,i){var d,h;if(this.provider=e,this.url=r,!e)throw new Error("Provider is required");if(!r)throw new Error("Endpoint URL is required");if(n==null)throw new Error("Network is required");const o=n===b.Network.MAINNET?Kf.mainnet:Kf.staging,a={native:((d=i==null?void 0:i.programAddress)==null?void 0:d.native)??o.native,spl:((h=i==null?void 0:i.programAddress)==null?void 0:h.spl)??o.spl},c=(i==null?void 0:i.relayer)??nw[n];try{this.relayer=new zt.web3.PublicKey(c),this.auth=s}catch(f){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:f})}const u=a.spl?{...Ey,metadata:{...Ey.metadata??{}},address:a.spl}:void 0,l=a.native?{...nd,metadata:{...nd.metadata??{}},address:a.native}:void 0;try{this.splProgram=u?new zt.Program(u,this.provider):void 0,this.nativeProgram=l?new zt.Program(l,this.provider):void 0}catch(f){throw new Error("Error creating Program instances. Ensure the IDLs and provider are correct.",{cause:f})}}get htlcActorAddress(){if(!this.provider.publicKey)throw new Error("No provider public key found");return this.provider.publicKey.toBase58()}async initiate(e){if(!e)return b.Err("Order is required");if(ee.isSolanaOrderResponse(e))return this.initiateWithCreateOrderResponse(e);try{const r=ee.ChainAsset.fromString(e.source_swap.asset);return ee.isSolanaNativeToken(r.chain,r.symbol)?this.nativeProgram?await this.initiateNativeSwap(e):b.Err("Native program is not initialized"):this.splProgram?await this.initiateSplSwap(e):b.Err("SPL program is not initialized")}catch(r){return b.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async sendSplViaRelayer(e,r){try{e.recentBlockhash=(await this.provider.connection.getLatestBlockhash()).blockhash,e.feePayer=this.relayer;const s=(await this.provider.wallet.signTransaction(e)).serialize({requireAllSignatures:!1}).toString("base64"),i=await b.Fetcher.post(this.url.endpoint("/initiate"),{body:JSON.stringify({order_id:r,serialized_tx:s}),headers:{"Content-Type":"application/json"}});return i.error||!i.result?b.Err(`Error from Relayer: ${i.error}`):await Na(this.provider.connection,i.result)?b.Ok(i.result):b.Err("Relayer: Failed to Initiate swap, confirmation timed out")}catch(n){return b.Err(`Failed to send SPL transaction: ${n instanceof Error?n.message:String(n)}`)}}async initiateViaHTLC(e,r){if(!r)return b.Err("Order is required");try{const n=await this.provider.sendAndConfirm(e);return n?await Na(this.provider.connection,n)?b.Ok(n):b.Err("HTLC: Failed to Initiate swap, confirmation timed out"):b.Err("Failed to initiate HTLC transaction")}catch(n){return b.Err(`Error initiating swap: ${n instanceof Error?n.message:String(n)}`)}}async initiateSplSwap(e){if(!this.splProgram)return b.Err("SPL program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=Jn.from(e),o=this.splProgram.methods.initiate(i,r,n,s,null),a=await lh(e.source_swap.asset,this.url);if(!a.ok)return b.Err(a.error);const{tokenAddress:c}=a.val,u=new zt.web3.PublicKey(c),l={initiator:this.provider.publicKey,mint:u,initiatorTokenAccount:Lv.getAssociatedTokenAddressSync(u,this.provider.publicKey),sponsor:this.relayer},d=await o.accounts(l).transaction();return this.sendSplViaRelayer(d,e.order_id)}catch(r){return b.Err(`Error initiating SPL swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateNativeSwap(e){if(!this.nativeProgram)return b.Err("Native program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=Jn.from(e),o=await this.nativeProgram.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction();return this.initiateViaHTLC(o,e)}catch(r){return b.Err(`Error initiating native swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateWithCreateOrderResponse(e){if(!this.relayer)return b.Err("No relayer address");const{versioned_tx:r,versioned_tx_gasless:n}=e;if(n===null)try{const i=Buffer.from(r,"base64"),o=zt.web3.VersionedTransaction.deserialize(i),a=await this.provider.sendAndConfirm(o);return await Na(this.provider.connection,a)?b.Ok(a):b.Err("Failed to initiate HTLC transaction")}catch(i){return b.Err(`Error in non-gasless flow: ${i}`)}const s=await this.auth.getAuthHeaders();if(!s.ok)return b.Err(s.error);try{const i=zt.web3.VersionedTransaction.deserialize(Buffer.from(n,"base64")),o=await this.provider.wallet.signTransaction(i);if(!o.signatures[0])return b.Err("No signature found after signing transaction");const c=Buffer.from(o.serialize()).toString("base64"),u=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:c}),headers:{...s.val,"Content-Type":"application/json"}});return u.error?b.Err(`Initiate: Error from relayer: ${u.error}`):u.result?b.Ok(u.result):b.Err("Initiate: No transaction hash returned from relayer")}catch(i){return b.Err(`Error initiating with create order response: ${i}`)}}async redeem(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return b.Err(n.error);const s=c1(r),i=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:Buffer.from(s).toString("hex")}),headers:{...n.val,"Content-Type":"application/json"}});if(i.error||!i.result)return b.Err(`Redeem: Error from relayer: ${i.error}`);const o=i.result;return await Na(this.provider.connection,o)?b.Ok(o):b.Err("Redeem: Timed out waiting for confirmation")}catch(n){return console.error("Redeem: Caught exception:",n),b.Err(`Error redeeming: ${n}`)}}async refund(){return b.Err("Refund is automatically handled by the relayer.")}}const l1="1.37.4",UO="1.55.0",MO={"-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 f1 extends Error{}class d1 extends f1{constructor(e,r){super(e),this.code=r,this.type=MO[r]??"ServerError"}}class FO extends f1{constructor(e,r,n){super(e),this.status=r,this.statusText=n}}var h1=t=>{throw TypeError(t)},Th=(t,e,r)=>e.has(t)||h1("Cannot "+r),Re=(t,e,r)=>(Th(t,e,"read from private field"),r?r.call(t):e.get(t)),ds=(t,e,r)=>e.has(t)?h1("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),xi=(t,e,r,n)=>(Th(t,e,"write to private field"),e.set(t,r),r),p1=(t,e,r)=>(Th(t,e,"access private method"),r),jO=(t,e,r,n)=>({set _(s){xi(t,e,s)},get _(){return Re(t,e,n)}}),zn,wo,hn,vs,Zo,Es,bc,y1,m1;function LO(t){const e=new URL(t);return e.protocol=e.protocol.replace("http","ws"),e.toString()}const HO={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5};class DO{constructor(e,r={}){if(ds(this,bc),ds(this,zn,0),ds(this,wo,0),ds(this,hn,null),ds(this,vs,null),ds(this,Zo,new Set),ds(this,Es,new Map),this.endpoint=e,this.options={...HO,...r},!this.options.WebSocketConstructor)throw new Error("Missing WebSocket constructor");this.endpoint.startsWith("http")&&(this.endpoint=LO(this.endpoint))}async makeRequest(e,r,n){const s=await p1(this,bc,y1).call(this);return new Promise((i,o)=>{xi(this,zn,Re(this,zn)+1),Re(this,Es).set(Re(this,zn),{resolve:i,reject:o,timeout:setTimeout(()=>{Re(this,Es).delete(Re(this,zn)),o(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n==null||n.addEventListener("abort",()=>{Re(this,Es).delete(Re(this,zn)),o(n.reason)}),s.send(JSON.stringify({jsonrpc:"2.0",id:Re(this,zn),method:e,params:r}))}).then(({error:i,result:o})=>{if(i)throw new d1(i.message,i.code);return o})}async subscribe(e){const r=new zO(e);return Re(this,Zo).add(r),await r.subscribe(this),()=>r.unsubscribe(this)}}zn=new WeakMap;wo=new WeakMap;hn=new WeakMap;vs=new WeakMap;Zo=new WeakMap;Es=new WeakMap;bc=new WeakSet;y1=function(){return Re(this,vs)?Re(this,vs):(xi(this,vs,new Promise(t=>{var e;(e=Re(this,hn))==null||e.close(),xi(this,hn,new this.options.WebSocketConstructor(this.endpoint)),Re(this,hn).addEventListener("open",()=>{xi(this,wo,0),t(Re(this,hn))}),Re(this,hn).addEventListener("close",()=>{jO(this,wo)._++,Re(this,wo)<=this.options.maxReconnects&&setTimeout(()=>{p1(this,bc,m1).call(this)},this.options.reconnectTimeout)}),Re(this,hn).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&&Re(this,Es).has(n.id)){const{resolve:s,timeout:i}=Re(this,Es).get(n.id);clearTimeout(i),s(n)}else if("params"in n){const{params:s}=n;Re(this,Zo).forEach(i=>{i.subscriptionId===s.subscription&&s.subscription===i.subscriptionId&&i.onMessage(s.result)})}})})),Re(this,vs))};m1=async function(){var t;return(t=Re(this,hn))==null||t.close(),xi(this,vs,null),Promise.allSettled([...Re(this,Zo)].map(e=>e.subscribe(this)))};class zO{constructor(e){this.subscriptionId=null,this.subscribed=!1,this.input=e}onMessage(e){this.subscribed&&this.input.onMessage(e)}async unsubscribe(e){const{subscriptionId:r}=this;return this.subscribed=!1,r==null?!1:(this.subscriptionId=null,e.makeRequest(this.input.unsubscribe,[r]))}async subscribe(e){this.subscriptionId=null,this.subscribed=!0;const r=await e.makeRequest(this.input.method,this.input.params,this.input.signal);this.subscribed&&(this.subscriptionId=r)}}var g1=t=>{throw TypeError(t)},Ih=(t,e,r)=>e.has(t)||g1("Cannot "+r),nr=(t,e,r)=>(Ih(t,e,"read from private field"),r?r.call(t):e.get(t)),Wa=(t,e,r)=>e.has(t)?g1("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),id=(t,e,r,n)=>(Ih(t,e,"write to private field"),e.set(t,r),r),VO=(t,e,r)=>(Ih(t,e,"access private method"),r),ho,mr,vo,od,b1;class qO{constructor(e){Wa(this,od),Wa(this,ho,0),Wa(this,mr),Wa(this,vo),id(this,mr,e)}fetch(e,r){const n=nr(this,mr).fetch??fetch;if(!n)throw new Error("The current environment does not support fetch, you can provide a fetch implementation in the options for SuiHTTPTransport.");return n(e,r)}async request(e){var s,i;id(this,ho,nr(this,ho)+1);const r=await this.fetch(((s=nr(this,mr).rpc)==null?void 0:s.url)??nr(this,mr).url,{method:"POST",signal:e.signal,headers:{"Content-Type":"application/json","Client-Sdk-Type":"typescript","Client-Sdk-Version":l1,"Client-Target-Api-Version":UO,"Client-Request-Method":e.method,...(i=nr(this,mr).rpc)==null?void 0:i.headers},body:JSON.stringify({jsonrpc:"2.0",id:nr(this,ho),method:e.method,params:e.params})});if(!r.ok)throw new FO(`Unexpected status code: ${r.status}`,r.status,r.statusText);const n=await r.json();if("error"in n&&n.error!=null)throw new d1(n.error.message,n.error.code);return n.result}async subscribe(e){const r=await VO(this,od,b1).call(this).subscribe(e);return e.signal&&(e.signal.throwIfAborted(),e.signal.addEventListener("abort",()=>{r()})),async()=>!!await r()}}ho=new WeakMap;mr=new WeakMap;vo=new WeakMap;od=new WeakSet;b1=function(){var t;if(!nr(this,vo)){const e=nr(this,mr).WebSocketConstructor??WebSocket;if(!e)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");id(this,vo,new DO(((t=nr(this,mr).websocket)==null?void 0:t.url)??nr(this,mr).url,{WebSocketConstructor:e,...nr(this,mr).websocket}))}return nr(this,vo)};function xm(t){switch(t){case"mainnet":return"https://fullnode.mainnet.sui.io:443";case"testnet":return"https://fullnode.testnet.sui.io:443";case"devnet":return"https://fullnode.devnet.sui.io:443";case"localnet":return"http://127.0.0.1:9000";default:throw new Error(`Unknown network: ${t}`)}}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function GO(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function w1(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function ad(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function v1(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function cd(t){if(!Array.isArray(t))throw new Error("array expected")}function E1(t,e){if(!w1(!0,e))throw new Error(`${t}: array of strings expected`)}function WO(t,e){if(!w1(!1,e))throw new Error(`${t}: array of numbers expected`)}function KO(...t){const e=i=>i,r=(i,o)=>a=>i(o(a)),n=t.map(i=>i.encode).reduceRight(r,e),s=t.map(i=>i.decode).reduce(r,e);return{encode:n,decode:s}}function ZO(t){const e=typeof t=="string"?t.split(""):t,r=e.length;E1("alphabet",e);const n=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(cd(s),s.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${t}`);return e[i]})),decode:s=>(cd(s),s.map(i=>{ad("alphabet.decode",i);const o=n.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${t}`);return o}))}}function XO(t=""){return ad("join",t),{encode:e=>(E1("join.decode",e),e.join(t)),decode:e=>(ad("join.decode",e),e.split(t))}}function km(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(cd(t),!t.length)return[];let n=0;const s=[],i=Array.from(t,a=>{if(v1(a),a<0||a>=e)throw new Error(`invalid integer: ${a}`);return a}),o=i.length;for(;;){let a=0,c=!0;for(let u=n;u<o;u++){const l=i[u],d=e*a,h=d+l;if(!Number.isSafeInteger(h)||d/e!==a||h-l!==d)throw new Error("convertRadix: carry overflow");const f=h/r;a=h%r;const m=Math.floor(f);if(i[u]=m,!Number.isSafeInteger(m)||m*r+a!==h)throw new Error("convertRadix: carry overflow");if(c)m?c=!1:n=u;else continue}if(s.push(a),c)break}for(let a=0;a<t.length-1&&t[a]===0;a++)s.push(0);return s.reverse()}function YO(t){v1(t);const e=2**8;return{encode:r=>{if(!GO(r))throw new Error("radix.encode input should be Uint8Array");return km(Array.from(r),e,t)},decode:r=>(WO("radix.decode",r),Uint8Array.from(km(r,t,e)))}}const JO=t=>KO(YO(58),ZO(t),XO("")),S1=JO("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),hu=t=>S1.encode(t),Xo=t=>S1.decode(t);function qt(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}const Ql=8192;function mt(t){if(t.length<Ql)return btoa(String.fromCharCode(...t));let e="";for(var r=0;r<t.length;r+=Ql){const n=t.slice(r,r+Ql);e+=String.fromCharCode(...n)}return btoa(e)}function A1(t){var s;const e=t.startsWith("0x")?t.slice(2):t,r=e.length%2===0?e:`0${e}`,n=((s=r.match(/[0-9a-fA-F]{2}/g))==null?void 0:s.map(i=>parseInt(i,16)))??[];if(n.length!==r.length/2)throw new Error(`Invalid hex string ${t}`);return Uint8Array.from(n)}function Ui(t){return t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),"")}function pu(t,e){return Array.from({length:Math.ceil(t.length/e)},(r,n)=>t.slice(n*e,(n+1)*e))}class x1{constructor(e,r){if(typeof e!="function")throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but got: ${e}.`);this._batchLoadFn=e,this._maxBatchSize=r5(r),this._batchScheduleFn=n5(r),this._cacheKeyFn=s5(r),this._cacheMap=i5(r),this._batch=null,this.name=o5(r)}load(e){if(e==null)throw new TypeError(`The loader.load() function must be called with a value, but got: ${String(e)}.`);const r=e5(this),n=this._cacheMap;let s;if(n){s=this._cacheKeyFn(e);const o=n.get(s);if(o){const a=r.cacheHits||(r.cacheHits=[]);return new Promise(c=>{a.push(()=>{c(o)})})}}r.keys.push(e);const i=new Promise((o,a)=>{r.callbacks.push({resolve:o,reject:a})});return n&&n.set(s,i),i}loadMany(e){if(!k1(e))throw new TypeError(`The loader.loadMany() function must be called with Array<key>, but got: ${e}.`);const r=[];for(let n=0;n<e.length;n++)r.push(this.load(e[n]).catch(s=>s));return Promise.all(r)}clear(e){const r=this._cacheMap;if(r){const n=this._cacheKeyFn(e);r.delete(n)}return this}clearAll(){const e=this._cacheMap;return e&&e.clear(),this}prime(e,r){const n=this._cacheMap;if(n){const s=this._cacheKeyFn(e);if(n.get(s)===void 0){let i;r instanceof Error?(i=Promise.reject(r),i.catch(()=>{})):i=Promise.resolve(r),n.set(s,i)}}return this}}const QO=typeof process=="object"&&typeof process.nextTick=="function"?function(t){ef||(ef=Promise.resolve()),ef.then(()=>{process.nextTick(t)})}:typeof setImmediate=="function"?function(t){setImmediate(t)}:function(t){setTimeout(t)};let ef;function e5(t){const e=t._batch;if(e!==null&&!e.hasDispatched&&e.keys.length<t._maxBatchSize)return e;const r={hasDispatched:!1,keys:[],callbacks:[]};return t._batch=r,t._batchScheduleFn(()=>{t5(t,r)}),r}function t5(t,e){if(e.hasDispatched=!0,e.keys.length===0){ud(e);return}let r;try{r=t._batchLoadFn(e.keys)}catch(n){return tf(t,e,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function errored synchronously: ${String(n)}.`))}if(!r||typeof r.then!="function")return tf(t,e,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise: ${String(r)}.`));Promise.resolve(r).then(n=>{if(!k1(n))throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array: ${String(n)}.`);if(n.length!==e.keys.length)throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys.
83
-
84
- Keys:
85
- ${String(e.keys)}
86
-
87
- Values:
88
- ${String(n)}`);ud(e);for(let s=0;s<e.callbacks.length;s++){const i=n[s];i instanceof Error?e.callbacks[s].reject(i):e.callbacks[s].resolve(i)}}).catch(n=>{tf(t,e,n)})}function tf(t,e,r){ud(e);for(let n=0;n<e.keys.length;n++)t.clear(e.keys[n]),e.callbacks[n].reject(r)}function ud(t){if(t.cacheHits)for(let e=0;e<t.cacheHits.length;e++)t.cacheHits[e]()}function r5(t){if(!(!t||t.batch!==!1))return 1;const r=t&&t.maxBatchSize;if(r===void 0)return 1/0;if(typeof r!="number"||r<1)throw new TypeError(`maxBatchSize must be a positive number: ${r}`);return r}function n5(t){const e=t&&t.batchScheduleFn;if(e===void 0)return QO;if(typeof e!="function")throw new TypeError(`batchScheduleFn must be a function: ${e}`);return e}function s5(t){const e=t&&t.cacheKeyFn;if(e===void 0)return r=>r;if(typeof e!="function")throw new TypeError(`cacheKeyFn must be a function: ${e}`);return e}function i5(t){if(!(!t||t.cache!==!1))return null;const r=t&&t.cacheMap;if(r===void 0)return new Map;if(r!==null){const s=["get","set","delete","clear"].filter(i=>r&&typeof r[i]!="function");if(s.length!==0)throw new TypeError("Custom cacheMap missing methods: "+s.join(", "))}return r}function o5(t){return t&&t.name?t.name:null}function k1(t){return typeof t=="object"&&t!==null&&"length"in t&&typeof t.length=="number"&&(t.length===0||t.length>0&&Object.prototype.hasOwnProperty.call(t,t.length-1))}function wc(t){const e=[];let r=0;if(t===0)return[0];for(;t>0;)e[r]=t&127,(t>>=7)&&(e[r]|=128),r+=1;return e}function a5(t){let e=0,r=0,n=0;for(;;){const s=t[n];if(n+=1,e|=(s&127)<<r,!(s&128))break;r+=7}return{value:e,length:n}}class c5{constructor(e){this.bytePosition=0,this.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)}shift(e){return this.bytePosition+=e,this}read8(){const e=this.dataView.getUint8(this.bytePosition);return this.shift(1),e}read16(){const e=this.dataView.getUint16(this.bytePosition,!0);return this.shift(2),e}read32(){const e=this.dataView.getUint32(this.bytePosition,!0);return this.shift(4),e}read64(){const e=this.read32(),n=this.read32().toString(16)+e.toString(16).padStart(8,"0");return BigInt("0x"+n).toString(10)}read128(){const e=BigInt(this.read64()),n=BigInt(this.read64()).toString(16)+e.toString(16).padStart(16,"0");return BigInt("0x"+n).toString(10)}read256(){const e=BigInt(this.read128()),n=BigInt(this.read128()).toString(16)+e.toString(16).padStart(32,"0");return BigInt("0x"+n).toString(10)}readBytes(e){const r=this.bytePosition+this.dataView.byteOffset,n=new Uint8Array(this.dataView.buffer,r,e);return this.shift(e),n}readULEB(){const e=this.bytePosition+this.dataView.byteOffset,r=new Uint8Array(this.dataView.buffer,e),{value:n,length:s}=a5(r);return this.shift(s),n}readVec(e){const r=this.readULEB(),n=[];for(let s=0;s<r;s++)n.push(e(this,s,r));return n}}function u5(t,e){switch(e){case"base58":return hu(t);case"base64":return mt(t);case"hex":return Ui(t);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}function _1(t,e=["<",">"]){const[r,n]=e,s=[];let i="",o=0;for(let a=0;a<t.length;a++){const c=t[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 l5{constructor({initialSize:e=1024,maxSize:r=1/0,allocateSize:n=1024}={}){this.bytePosition=0,this.size=e,this.maxSize=r,this.allocateSize=n,this.dataView=new DataView(new ArrayBuffer(e))}ensureSizeOrGrow(e){const r=this.bytePosition+e;if(r>this.size){const n=Math.min(this.maxSize,this.size+this.allocateSize);if(r>n)throw new Error(`Attempting to serialize to BCS, but buffer does not have enough size. Allocated size: ${this.size}, Max size: ${this.maxSize}, Required size: ${r}`);this.size=n;const s=new ArrayBuffer(this.size);new Uint8Array(s).set(new Uint8Array(this.dataView.buffer)),this.dataView=new DataView(s)}}shift(e){return this.bytePosition+=e,this}write8(e){return this.ensureSizeOrGrow(1),this.dataView.setUint8(this.bytePosition,Number(e)),this.shift(1)}write16(e){return this.ensureSizeOrGrow(2),this.dataView.setUint16(this.bytePosition,Number(e),!0),this.shift(2)}write32(e){return this.ensureSizeOrGrow(4),this.dataView.setUint32(this.bytePosition,Number(e),!0),this.shift(4)}write64(e){return rf(BigInt(e),8).forEach(r=>this.write8(r)),this}write128(e){return rf(BigInt(e),16).forEach(r=>this.write8(r)),this}write256(e){return rf(BigInt(e),32).forEach(r=>this.write8(r)),this}writeULEB(e){return wc(e).forEach(r=>this.write8(r)),this}writeVec(e,r){return this.writeULEB(e.length),Array.from(e).forEach((n,s)=>r(this,n,s,e.length)),this}*[Symbol.iterator](){for(let e=0;e<this.bytePosition;e++)yield this.dataView.getUint8(e);return this.toBytes()}toBytes(){return new Uint8Array(this.dataView.buffer.slice(0,this.bytePosition))}toString(e){return u5(this.toBytes(),e)}}function rf(t,e){const r=new Uint8Array(e);let n=0;for(;t>0;)r[n]=Number(t%BigInt(256)),t=t/BigInt(256),n+=1;return r}var T1=t=>{throw TypeError(t)},I1=(t,e,r)=>e.has(t)||T1("Cannot "+r),gr=(t,e,r)=>(I1(t,e,"read from private field"),r?r.call(t):e.get(t)),vc=(t,e,r)=>e.has(t)?T1("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Ec=(t,e,r,n)=>(I1(t,e,"write to private field"),e.set(t,r),r),li,po,ic,Vn;const f5=class P1{constructor(e){vc(this,li),vc(this,po),this.name=e.name,this.read=e.read,this.serializedSize=e.serializedSize??(()=>null),Ec(this,li,e.write),Ec(this,po,e.serialize??((r,n)=>{const s=new l5({initialSize:this.serializedSize(r)??void 0,...n});return gr(this,li).call(this,r,s),s.toBytes()})),this.validate=e.validate??(()=>{})}write(e,r){this.validate(e),gr(this,li).call(this,e,r)}serialize(e,r){return this.validate(e),new d5(this,gr(this,po).call(this,e,r))}parse(e){const r=new c5(e);return this.read(r)}fromHex(e){return this.parse(A1(e))}fromBase58(e){return this.parse(Xo(e))}fromBase64(e){return this.parse(qt(e))}transform({name:e,input:r,output:n,validate:s}){return new P1({name:e??this.name,read:i=>n?n(this.read(i)):this.read(i),write:(i,o)=>gr(this,li).call(this,r?r(i):i,o),serializedSize:i=>this.serializedSize(r?r(i):i),serialize:(i,o)=>gr(this,po).call(this,r?r(i):i,o),validate:i=>{s==null||s(i),this.validate(r?r(i):i)}})}};li=new WeakMap;po=new WeakMap;let Jr=f5;const O1=Symbol.for("@mysten/serialized-bcs");function Ph(t){return!!t&&typeof t=="object"&&t[O1]===!0}class d5{constructor(e,r){vc(this,ic),vc(this,Vn),Ec(this,ic,e),Ec(this,Vn,r)}get[O1](){return!0}toBytes(){return gr(this,Vn)}toHex(){return Ui(gr(this,Vn))}toBase64(){return mt(gr(this,Vn))}toBase58(){return hu(gr(this,Vn))}parse(){return gr(this,ic).parse(gr(this,Vn))}}ic=new WeakMap;Vn=new WeakMap;function Sc({size:t,...e}){return new Jr({...e,serializedSize:()=>t})}function nf({readMethod:t,writeMethod:e,...r}){return Sc({...r,read:n=>n[t](),write:(n,s)=>s[e](n),validate:n=>{var s;if(n<0||n>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${n}. Expected value in range 0-${r.maxValue}`);(s=r.validate)==null||s.call(r,n)}})}function sf({readMethod:t,writeMethod:e,...r}){return Sc({...r,read:n=>n[t](),write:(n,s)=>s[e](BigInt(n)),validate:n=>{var i;const s=BigInt(n);if(s<0||s>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${s}. Expected value in range 0-${r.maxValue}`);(i=r.validate)==null||i.call(r,s)}})}function h5({serialize:t,...e}){const r=new Jr({...e,serialize:t,write:(n,s)=>{for(const i of r.serialize(n).toBytes())s.write8(i)}});return r}function p5({toBytes:t,fromBytes:e,...r}){return new Jr({...r,read:n=>{const s=n.readULEB(),i=n.readBytes(s);return e(i)},write:(n,s)=>{const i=t(n);s.writeULEB(i.length);for(let o=0;o<i.length;o++)s.write8(i[o])},serialize:n=>{const s=t(n),i=wc(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 y5(t){let e=null;function r(){return e||(e=t()),e}return new Jr({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 m5 extends Jr{constructor({name:e,fields:r,...n}){const s=Object.entries(r);super({name:e,serializedSize:i=>{let o=0;for(const[a,c]of s){const u=c.serializedSize(i[a]);if(u==null)return null;o+=u}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 g5 extends Jr{constructor({fields:e,...r}){const n=Object.entries(e);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(e,c))[0];for(let c=0;c<n.length;c++){const[u,l]=n[c];if(u===o){i.writeULEB(c),l==null||l.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(e,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(e,o))throw new TypeError(`Invalid enum variant ${o}`)}})}}class b5 extends Jr{constructor({fields:e,name:r,...n}){super({name:r??`(${e.map(s=>s.name).join(", ")})`,serializedSize:s=>{let i=0;for(let o=0;o<e.length;o++){const a=e[o].serializedSize(s[o]);if(a==null)return null;i+=a}return i},read:s=>{const i=[];for(const o of e)i.push(o.read(s));return i},write:(s,i)=>{for(let o=0;o<e.length;o++)e[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!==e.length)throw new TypeError(`Expected array of length ${e.length}, found ${s.length}`)}})}}function w5(t,e,r){return new Jr({read:n=>{const s=new Array(t);for(let i=0;i<t;i++)s[i]=e.read(n);return s},write:(n,s)=>{for(const i of n)e.write(i,s)},...r,name:(r==null?void 0:r.name)??`${e.name}[${t}]`,validate:n=>{var s;if((s=r==null?void 0:r.validate)==null||s.call(r,n),!n||typeof n!="object"||!("length"in n))throw new TypeError(`Expected array, found ${typeof n}`);if(n.length!==t)throw new TypeError(`Expected array of length ${t}, found ${n.length}`)}})}function v5(t){return k.enum(`Option<${t.name}>`,{None:null,Some:t}).transform({input:e=>e==null?{None:!0}:{Some:e},output:e=>e.$kind==="Some"?e.Some:null})}function E5(t,e){return new Jr({read:r=>{const n=r.readULEB(),s=new Array(n);for(let i=0;i<n;i++)s[i]=t.read(r);return s},write:(r,n)=>{n.writeULEB(r.length);for(const s of r)t.write(s,n)},...e,name:(e==null?void 0:e.name)??`vector<${t.name}>`,validate:r=>{var n;if((n=e==null?void 0:e.validate)==null||n.call(e,r),!r||typeof r!="object"||!("length"in r))throw new TypeError(`Expected array, found ${typeof r}`)}})}function S5(t,e){return k.vector(k.tuple([t,e])).transform({name:`Map<${t.name}, ${e.name}>`,input:r=>[...r.entries()],output:r=>{const n=new Map;for(const[s,i]of r)n.set(s,i);return n}})}const k={u8(t){return nf({readMethod:"read8",writeMethod:"write8",size:1,maxValue:2**8-1,...t,name:(t==null?void 0:t.name)??"u8"})},u16(t){return nf({readMethod:"read16",writeMethod:"write16",size:2,maxValue:2**16-1,...t,name:(t==null?void 0:t.name)??"u16"})},u32(t){return nf({readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...t,name:(t==null?void 0:t.name)??"u32"})},u64(t){return sf({readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...t,name:(t==null?void 0:t.name)??"u64"})},u128(t){return sf({readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...t,name:(t==null?void 0:t.name)??"u128"})},u256(t){return sf({readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...t,name:(t==null?void 0:t.name)??"u256"})},bool(t){return Sc({size:1,read:e=>e.read8()===1,write:(e,r)=>r.write8(e?1:0),...t,name:(t==null?void 0:t.name)??"bool",validate:e=>{var r;if((r=t==null?void 0:t.validate)==null||r.call(t,e),typeof e!="boolean")throw new TypeError(`Expected boolean, found ${typeof e}`)}})},uleb128(t){return h5({read:e=>e.readULEB(),serialize:e=>Uint8Array.from(wc(e)),...t,name:(t==null?void 0:t.name)??"uleb128"})},bytes(t,e){return Sc({size:t,read:r=>r.readBytes(t),write:(r,n)=>{const s=new Uint8Array(r);for(let i=0;i<t;i++)n.write8(s[i]??0)},...e,name:(e==null?void 0:e.name)??`bytes[${t}]`,validate:r=>{var n;if((n=e==null?void 0:e.validate)==null||n.call(e,r),!r||typeof r!="object"||!("length"in r))throw new TypeError(`Expected array, found ${typeof r}`);if(r.length!==t)throw new TypeError(`Expected array of length ${t}, found ${r.length}`)}})},byteVector(t){return new Jr({read:e=>{const r=e.readULEB();return e.readBytes(r)},write:(e,r)=>{const n=new Uint8Array(e);r.writeULEB(n.length);for(let s=0;s<n.length;s++)r.write8(n[s]??0)},...t,name:(t==null?void 0:t.name)??"vector<u8>",serializedSize:e=>{const r="length"in e?e.length:null;return r==null?null:wc(r).length+r},validate:e=>{var r;if((r=t==null?void 0:t.validate)==null||r.call(t,e),!e||typeof e!="object"||!("length"in e))throw new TypeError(`Expected array, found ${typeof e}`)}})},string(t){return p5({toBytes:e=>new TextEncoder().encode(e),fromBytes:e=>new TextDecoder().decode(e),...t,name:(t==null?void 0:t.name)??"string"})},fixedArray:w5,option:v5,vector:E5,tuple(t,e){return new b5({fields:t,...e})},struct(t,e,r){return new m5({name:t,fields:e,...r})},enum(t,e,r){return new g5({name:t,fields:e,...r})},map:S5,lazy(t){return y5(t)}};var B1=t=>{throw TypeError(t)},C1=(t,e,r)=>e.has(t)||B1("Cannot "+r),pt=(t,e,r)=>(C1(t,e,"read from private field"),e.get(t)),_m=(t,e,r)=>e.has(t)?B1("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Tm=(t,e,r,n)=>(C1(t,e,"write to private field"),e.set(t,r),r),ps,kt;const A5=class $1{constructor({prefix:e,cache:r}={}){_m(this,ps),_m(this,kt),Tm(this,ps,e??[]),Tm(this,kt,r??new Map)}read(e,r){const n=[pt(this,ps),...e].join(":");if(pt(this,kt).has(n))return pt(this,kt).get(n);const s=r();return pt(this,kt).set(n,s),typeof s=="object"&&s!==null&&"then"in s?Promise.resolve(s).then(i=>(pt(this,kt).set(n,i),i)).catch(i=>{throw pt(this,kt).delete(n),i}):s}readSync(e,r){const n=[pt(this,ps),...e].join(":");if(pt(this,kt).has(n))return pt(this,kt).get(n);const s=r();return pt(this,kt).set(n,s),s}clear(e){const r=[...pt(this,ps),...e??[]].join(":");if(!r){pt(this,kt).clear();return}for(const n of pt(this,kt).keys())n.startsWith(r)&&pt(this,kt).delete(n)}scope(e){return new $1({prefix:[...pt(this,ps),...Array.isArray(e)?e:[e]],cache:pt(this,kt)})}};ps=new WeakMap;kt=new WeakMap;let x5=A5;class R1{constructor({network:e,base:r,cache:n=(r==null?void 0:r.cache)??new x5}){this.network=e,this.base=r??this,this.cache=n}$extend(...e){return Object.create(this,Object.fromEntries(e.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 N1=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,U1=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i,k5=235;function _5(t){return t.length>k5?!1:t.includes("@")?N1.test(t):U1.test(t)}function T5(t,e="at"){const r=t.toLowerCase();let n;if(r.includes("@")){if(!N1.test(r))throw new Error(`Invalid SuiNS name ${t}`);const[s,i]=r.split("@");n=[...s?s.split("."):[],i]}else{if(!U1.test(r))throw new Error(`Invalid SuiNS name ${t}`);n=r.split(".").slice(0,-1)}return e==="dot"?`${n.join(".")}.sui`:`${n.slice(0,-1).join(".")}@${n[n.length-1]}`}const I5=/^([a-z0-9]+(?:-[a-z0-9]+)*)$/,P5=/^\d+$/,O5=64,M1="/",Dt=t=>{const e=t.split(M1);if(e.length<2||e.length>3)return!1;const[r,n,s]=e;return s!==void 0&&!P5.test(s)||!_5(r)?!1:I5.test(n)&&n.length<O5},B5=t=>{const e=t.split(/::|<|>|,/);for(const r of e)if(r.includes(M1)&&!Dt(r))return!1;return!0},C5=32;function Im(t){try{return Xo(t).length===C5}catch{return!1}}const yu=32;function br(t){return R5(t)&&N5(t)===yu}function Ka(t){return br(t)}function $5(t){return t.includes("::")?zs(t):t}function zs(t){const[e,r]=t.split("::"),n=Dt(e),s=t.slice(e.length+r.length+4),i=s.includes("<")?s.slice(0,s.indexOf("<")):s,o=s.includes("<")?_1(s.slice(s.indexOf("<")+1,s.lastIndexOf(">"))).map(a=>$5(a.trim())):[];return{address:n?e:Ae(e),module:r,name:i,typeParams:o}}function Ac(t){const{address:e,module:r,name:n,typeParams:s}=typeof t=="string"?zs(t):t,i=(s==null?void 0:s.length)>0?`<${s.map(o=>typeof o=="string"?o:Ac(o)).join(",")}>`:"";return`${e}::${r}::${n}${i}`}function Ae(t,e=!1){let r=t.toLowerCase();return!e&&r.startsWith("0x")&&(r=r.slice(2)),`0x${r.padStart(yu*2,"0")}`}function bn(t,e=!1){return Ae(t,e)}function R5(t){return/^(0x|0X)?[a-fA-F0-9]+$/.test(t)&&t.length%2===0}function N5(t){return/^(0x|0X)/.test(t)?(t.length-2)/2:t.length/2}const U5=/^vector<(.+)>$/,M5=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class Er{static parseFromStr(e,r=!1){if(e==="address")return{address:null};if(e==="bool")return{bool:null};if(e==="u8")return{u8:null};if(e==="u16")return{u16:null};if(e==="u32")return{u32:null};if(e==="u64")return{u64:null};if(e==="u128")return{u128:null};if(e==="u256")return{u256:null};if(e==="signer")return{signer:null};const n=e.match(U5);if(n)return{vector:Er.parseFromStr(n[1],r)};const s=e.match(M5);if(s)return{struct:{address:r?Ae(s[1]):s[1],module:s[2],name:s[3],typeParams:s[5]===void 0?[]:Er.parseStructTypeArgs(s[5],r)}};throw new Error(`Encountered unexpected token when parsing type args for ${e}`)}static parseStructTypeArgs(e,r=!1){return _1(e).map(n=>Er.parseFromStr(n,r))}static tagToString(e){if("bool"in e)return"bool";if("u8"in e)return"u8";if("u16"in e)return"u16";if("u32"in e)return"u32";if("u64"in e)return"u64";if("u128"in e)return"u128";if("u256"in e)return"u256";if("address"in e)return"address";if("signer"in e)return"signer";if("vector"in e)return`vector<${Er.tagToString(e.vector)}>`;if("struct"in e){const r=e.struct,n=r.typeParams.map(Er.tagToString).join(", ");return`${r.address}::${r.module}::${r.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}function F5(t){return k.u64({name:"unsafe_u64",...t}).transform({input:e=>e,output:e=>Number(e)})}function j5(t){return k.enum("Option",{None:null,Some:t})}const Ce=k.bytes(yu).transform({validate:t=>{const e=typeof t=="string"?t:Ui(t);if(!e||!br(Ae(e)))throw new Error(`Invalid Sui address ${e}`)},input:t=>typeof t=="string"?A1(Ae(t)):t,output:t=>Ae(Ui(t))}),Ar=k.vector(k.u8()).transform({name:"ObjectDigest",input:t=>Xo(t),output:t=>hu(new Uint8Array(t)),validate:t=>{if(Xo(t).length!==32)throw new Error("ObjectDigest must be 32 bytes")}}),rr=k.struct("SuiObjectRef",{objectId:Ce,version:k.u64(),digest:Ar}),F1=k.struct("SharedObjectRef",{objectId:Ce,initialSharedVersion:k.u64(),mutable:k.bool()}),j1=k.enum("ObjectArg",{ImmOrOwnedObject:rr,SharedObject:F1,Receiving:rr}),Ss=k.enum("Owner",{AddressOwner:Ce,ObjectOwner:Ce,Shared:k.struct("Shared",{initialSharedVersion:k.u64()}),Immutable:null,ConsensusAddressOwner:k.struct("ConsensusAddressOwner",{owner:Ce,startVersion:k.u64()})}),L1=k.enum("CallArg",{Pure:k.struct("Pure",{bytes:k.vector(k.u8()).transform({input:t=>typeof t=="string"?qt(t):t,output:t=>mt(new Uint8Array(t))})}),Object:j1}),Oh=k.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:k.lazy(()=>Oh),struct:k.lazy(()=>G1),u16:null,u32:null,u256:null}),Bh=Oh.transform({input:t=>typeof t=="string"?Er.parseFromStr(t,!0):t,output:t=>Er.tagToString(t)}),zr=k.enum("Argument",{GasCoin:null,Input:k.u16(),Result:k.u16(),NestedResult:k.tuple([k.u16(),k.u16()])}),H1=k.struct("ProgrammableMoveCall",{package:Ce,module:k.string(),function:k.string(),typeArguments:k.vector(Bh),arguments:k.vector(zr)}),D1=k.enum("Command",{MoveCall:H1,TransferObjects:k.struct("TransferObjects",{objects:k.vector(zr),address:zr}),SplitCoins:k.struct("SplitCoins",{coin:zr,amounts:k.vector(zr)}),MergeCoins:k.struct("MergeCoins",{destination:zr,sources:k.vector(zr)}),Publish:k.struct("Publish",{modules:k.vector(k.vector(k.u8()).transform({input:t=>typeof t=="string"?qt(t):t,output:t=>mt(new Uint8Array(t))})),dependencies:k.vector(Ce)}),MakeMoveVec:k.struct("MakeMoveVec",{type:j5(Bh).transform({input:t=>t===null?{None:!0}:{Some:t},output:t=>t.Some??null}),elements:k.vector(zr)}),Upgrade:k.struct("Upgrade",{modules:k.vector(k.vector(k.u8()).transform({input:t=>typeof t=="string"?qt(t):t,output:t=>mt(new Uint8Array(t))})),dependencies:k.vector(Ce),package:Ce,ticket:zr})}),z1=k.struct("ProgrammableTransaction",{inputs:k.vector(L1),commands:k.vector(D1)}),V1=k.enum("TransactionKind",{ProgrammableTransaction:z1,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),q1=k.enum("TransactionExpiration",{None:null,Epoch:F5()}),G1=k.struct("StructTag",{address:Ce,module:k.string(),name:k.string(),typeParams:k.vector(Oh)}),W1=k.struct("GasData",{payment:k.vector(rr),owner:Ce,price:k.u64(),budget:k.u64()}),K1=k.struct("TransactionDataV1",{kind:V1,sender:Ce,gasData:W1,expiration:q1}),Z1=k.enum("TransactionData",{V1:K1}),X1=k.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),Y1=k.enum("IntentVersion",{V0:null}),J1=k.enum("AppId",{Sui:null}),Q1=k.struct("Intent",{scope:X1,version:Y1,appId:J1});function ev(t){return k.struct(`IntentMessage<${t.name}>`,{intent:Q1,value:t})}const tv=k.enum("CompressedSignature",{ED25519:k.fixedArray(64,k.u8()),Secp256k1:k.fixedArray(64,k.u8()),Secp256r1:k.fixedArray(64,k.u8()),ZkLogin:k.vector(k.u8()),Passkey:k.vector(k.u8())}),rv=k.enum("PublicKey",{ED25519:k.fixedArray(32,k.u8()),Secp256k1:k.fixedArray(33,k.u8()),Secp256r1:k.fixedArray(33,k.u8()),ZkLogin:k.vector(k.u8()),Passkey:k.fixedArray(33,k.u8())}),nv=k.struct("MultiSigPkMap",{pubKey:rv,weight:k.u8()}),sv=k.struct("MultiSigPublicKey",{pk_map:k.vector(nv),threshold:k.u16()}),L5=k.struct("MultiSig",{sigs:k.vector(tv),bitmap:k.u16(),multisig_pk:sv}),H5=k.vector(k.u8()).transform({input:t=>typeof t=="string"?qt(t):t,output:t=>mt(new Uint8Array(t))}),iv=k.struct("SenderSignedTransaction",{intentMessage:ev(Z1),txSignatures:k.vector(H5)}),D5=k.vector(iv,{name:"SenderSignedData"}),z5=k.struct("PasskeyAuthenticator",{authenticatorData:k.vector(k.u8()),clientDataJson:k.string(),userSignature:k.vector(k.u8())}),V5=k.enum("PackageUpgradeError",{UnableToFetchPackage:k.struct("UnableToFetchPackage",{packageId:Ce}),NotAPackage:k.struct("NotAPackage",{objectId:Ce}),IncompatibleUpgrade:null,DigestDoesNotMatch:k.struct("DigestDoesNotMatch",{digest:k.vector(k.u8())}),UnknownUpgradePolicy:k.struct("UnknownUpgradePolicy",{policy:k.u8()}),PackageIDDoesNotMatch:k.struct("PackageIDDoesNotMatch",{packageId:Ce,ticketId:Ce})}),q5=k.struct("ModuleId",{address:Ce,name:k.string()}),Pm=k.struct("MoveLocation",{module:q5,function:k.u16(),instruction:k.u16(),functionName:k.option(k.string())}),G5=k.enum("CommandArgumentError",{TypeMismatch:null,InvalidBCSBytes:null,InvalidUsageOfPureArg:null,InvalidArgumentToPrivateEntryFunction:null,IndexOutOfBounds:k.struct("IndexOutOfBounds",{idx:k.u16()}),SecondaryIndexOutOfBounds:k.struct("SecondaryIndexOutOfBounds",{resultIdx:k.u16(),secondaryIdx:k.u16()}),InvalidResultArity:k.struct("InvalidResultArity",{resultIdx:k.u16()}),InvalidGasCoinUsage:null,InvalidValueUsage:null,InvalidObjectByValue:null,InvalidObjectByMutRef:null,SharedObjectOperationNotAllowed:null}),W5=k.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),K5=k.enum("ExecutionFailureStatus",{InsufficientGas:null,InvalidGasObject:null,InvariantViolation:null,FeatureNotYetSupported:null,MoveObjectTooBig:k.struct("MoveObjectTooBig",{objectSize:k.u64(),maxObjectSize:k.u64()}),MovePackageTooBig:k.struct("MovePackageTooBig",{objectSize:k.u64(),maxObjectSize:k.u64()}),CircularObjectOwnership:k.struct("CircularObjectOwnership",{object:Ce}),InsufficientCoinBalance:null,CoinBalanceOverflow:null,PublishErrorNonZeroAddress:null,SuiMoveVerificationError:null,MovePrimitiveRuntimeError:k.option(Pm),MoveAbort:k.tuple([Pm,k.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:k.struct("CommandArgumentError",{argIdx:k.u16(),kind:G5}),TypeArgumentError:k.struct("TypeArgumentError",{argumentIdx:k.u16(),kind:W5}),UnusedValueWithoutDrop:k.struct("UnusedValueWithoutDrop",{resultIdx:k.u16(),secondaryIdx:k.u16()}),InvalidPublicFunctionReturnType:k.struct("InvalidPublicFunctionReturnType",{idx:k.u16()}),InvalidTransferObject:null,EffectsTooLarge:k.struct("EffectsTooLarge",{currentSize:k.u64(),maxSize:k.u64()}),PublishUpgradeMissingDependency:null,PublishUpgradeDependencyDowngrade:null,PackageUpgradeError:k.struct("PackageUpgradeError",{upgradeError:V5}),WrittenObjectsTooLarge:k.struct("WrittenObjectsTooLarge",{currentSize:k.u64(),maxSize:k.u64()}),CertificateDenied:null,SuiMoveVerificationTimedout:null,SharedObjectOperationNotAllowed:null,InputObjectDeleted:null,ExecutionCancelledDueToSharedObjectCongestion:k.struct("ExecutionCancelledDueToSharedObjectCongestion",{congestedObjects:k.vector(Ce)}),AddressDeniedForCoin:k.struct("AddressDeniedForCoin",{address:Ce,coinType:k.string()}),CoinTypeGlobalPause:k.struct("CoinTypeGlobalPause",{coinType:k.string()}),ExecutionCancelledDueToRandomnessUnavailable:null}),ov=k.enum("ExecutionStatus",{Success:null,Failed:k.struct("ExecutionFailed",{error:K5,command:k.option(k.u64())})}),av=k.struct("GasCostSummary",{computationCost:k.u64(),storageCost:k.u64(),storageRebate:k.u64(),nonRefundableStorageFee:k.u64()}),Z5=k.struct("TransactionEffectsV1",{status:ov,executedEpoch:k.u64(),gasUsed:av,modifiedAtVersions:k.vector(k.tuple([Ce,k.u64()])),sharedObjects:k.vector(rr),transactionDigest:Ar,created:k.vector(k.tuple([rr,Ss])),mutated:k.vector(k.tuple([rr,Ss])),unwrapped:k.vector(k.tuple([rr,Ss])),deleted:k.vector(rr),unwrappedThenDeleted:k.vector(rr),wrapped:k.vector(rr),gasObject:k.tuple([rr,Ss]),eventsDigest:k.option(Ar),dependencies:k.vector(Ar)}),Ch=k.tuple([k.u64(),Ar]),X5=k.enum("ObjectIn",{NotExist:null,Exist:k.tuple([Ch,Ss])}),Y5=k.enum("ObjectOut",{NotExist:null,ObjectWrite:k.tuple([Ar,Ss]),PackageWrite:Ch}),J5=k.enum("IDOperation",{None:null,Created:null,Deleted:null}),Q5=k.struct("EffectsObjectChange",{inputState:X5,outputState:Y5,idOperation:J5}),e3=k.enum("UnchangedSharedKind",{ReadOnlyRoot:Ch,MutateDeleted:k.u64(),ReadDeleted:k.u64(),Cancelled:k.u64(),PerEpochConfig:null}),t3=k.struct("TransactionEffectsV2",{status:ov,executedEpoch:k.u64(),gasUsed:av,transactionDigest:Ar,gasObjectIndex:k.option(k.u32()),eventsDigest:k.option(Ar),dependencies:k.vector(Ar),lamportVersion:k.u64(),changedObjects:k.vector(k.tuple([Ce,Q5])),unchangedSharedObjects:k.vector(k.tuple([Ce,e3])),auxDataDigest:k.option(Ar)}),r3=k.enum("TransactionEffects",{V1:Z5,V2:t3});function Eo(t){switch(t){case"u8":return k.u8();case"u16":return k.u16();case"u32":return k.u32();case"u64":return k.u64();case"u128":return k.u128();case"u256":return k.u256();case"bool":return k.bool();case"string":return k.string();case"id":case"address":return Ce}const e=t.match(/^(vector|option)<(.+)>$/);if(e){const[r,n]=e.slice(1);return r==="vector"?k.vector(Eo(n)):k.option(Eo(n))}throw new Error(`Invalid Pure type name: ${t}`)}const he={...k,U8:k.u8(),U16:k.u16(),U32:k.u32(),U64:k.u64(),U128:k.u128(),U256:k.u256(),ULEB128:k.uleb128(),Bool:k.bool(),String:k.string(),Address:Ce,AppId:J1,Argument:zr,CallArg:L1,Command:D1,CompressedSignature:tv,GasData:W1,Intent:Q1,IntentMessage:ev,IntentScope:X1,IntentVersion:Y1,MultiSig:L5,MultiSigPkMap:nv,MultiSigPublicKey:sv,ObjectArg:j1,ObjectDigest:Ar,Owner:Ss,PasskeyAuthenticator:z5,ProgrammableMoveCall:H1,ProgrammableTransaction:z1,PublicKey:rv,SenderSignedData:D5,SenderSignedTransaction:iv,SharedObjectRef:F1,StructTag:G1,SuiObjectRef:rr,TransactionData:Z1,TransactionDataV1:K1,TransactionEffects:r3,TransactionExpiration:q1,TransactionKind:V1,TypeTag:Bh};var an;function n3(t){return{lang:(t==null?void 0:t.lang)??(an==null?void 0:an.lang),message:t==null?void 0:t.message,abortEarly:(t==null?void 0:t.abortEarly)??(an==null?void 0:an.abortEarly),abortPipeEarly:(t==null?void 0:t.abortPipeEarly)??(an==null?void 0:an.abortPipeEarly)}}var of;function s3(t){return of==null?void 0:of.get(t)}var af;function i3(t){return af==null?void 0:af.get(t)}var cf;function o3(t,e){var r;return(r=cf==null?void 0:cf.get(t))==null?void 0:r.get(e)}function cv(t){var r,n;const e=typeof t;return e==="string"?`"${t}"`:e==="number"||e==="bigint"||e==="boolean"?`${t}`:e==="object"||e==="function"?(t&&((n=(r=Object.getPrototypeOf(t))==null?void 0:r.constructor)==null?void 0:n.name))??"null":e}function Zt(t,e,r,n,s){const i=s&&"input"in s?s.input:r.value,o=(s==null?void 0:s.expected)??t.expects??null,a=(s==null?void 0:s.received)??cv(i),c={kind:t.kind,type:t.type,input:i,expected:o,received:a,message:`Invalid ${e}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:t.requirement,path:s==null?void 0:s.path,issues:s==null?void 0:s.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},u=t.kind==="schema",l=(s==null?void 0:s.message)??t.message??o3(t.reference,c.lang)??(u?i3(c.lang):null)??n.message??s3(c.lang);l&&(c.message=typeof l=="function"?l(c):l),u&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function a3(t,e){return Object.hasOwn(t,e)&&e!=="__proto__"&&e!=="prototype"&&e!=="constructor"}var c3=class extends Error{constructor(e){super(e[0].message);zh(this,"issues");this.name="ValiError",this.issues=e}};function xa(t,e){return{kind:"validation",type:"check",reference:xa,async:!1,expects:null,requirement:t,message:e,_run(r,n){return r.typed&&!this.requirement(r.value)&&Zt(this,"input",r,n),r}}}function Ve(t){return{kind:"validation",type:"integer",reference:Ve,async:!1,expects:null,requirement:Number.isInteger,message:t,_run(e,r){return e.typed&&!this.requirement(e.value)&&Zt(this,"integer",e,r),e}}}function mu(t){return{kind:"transformation",type:"transform",reference:mu,async:!1,operation:t,_run(e){return e.value=this.operation(e.value),e}}}function $h(t,e,r){return typeof t.default=="function"?t.default(e,r):t.default}function ld(t,e){return!t._run({typed:!1,value:e},{abortEarly:!0}).issues}function fe(t,e){return{kind:"schema",type:"array",reference:fe,expects:"Array",async:!1,item:t,message:e,_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 u={type:"array",origin:"value",input:s,key:o,value:a};for(const l of c.issues)l.path?l.path.unshift(u):l.path=[u],(i=r.issues)==null||i.push(l);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else Zt(this,"type",r,n);return r}}}function Rh(t){return{kind:"schema",type:"bigint",reference:Rh,expects:"bigint",async:!1,message:t,_run(e,r){return typeof e.value=="bigint"?e.typed=!0:Zt(this,"type",e,r),e}}}function gu(t){return{kind:"schema",type:"boolean",reference:gu,expects:"boolean",async:!1,message:t,_run(e,r){return typeof e.value=="boolean"?e.typed=!0:Zt(this,"type",e,r),e}}}function Yo(t){return{kind:"schema",type:"lazy",reference:Yo,expects:"unknown",async:!1,getter:t,_run(e,r){return this.getter(e.value)._run(e,r)}}}function de(t,e){return{kind:"schema",type:"literal",reference:de,expects:cv(t),async:!1,literal:t,message:e,_run(r,n){return r.value===this.literal?r.typed=!0:Zt(this,"type",r,n),r}}}function Ee(t,...e){const r={kind:"schema",type:"nullable",reference:Ee,expects:`${t.expects} | null`,async:!1,wrapped:t,_run(n,s){return n.value===null&&("default"in this&&(n.value=$h(this,n,s)),n.value===null)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in e&&(r.default=e[0]),r}function Mi(t,...e){const r={kind:"schema",type:"nullish",reference:Mi,expects:`${t.expects} | null | undefined`,async:!1,wrapped:t,_run(n,s){return(n.value===null||n.value===void 0)&&("default"in this&&(n.value=$h(this,n,s)),n.value===null||n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in e&&(r.default=e[0]),r}function je(t){return{kind:"schema",type:"number",reference:je,expects:"number",async:!1,message:t,_run(e,r){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:Zt(this,"type",e,r),e}}}function re(t,e){return{kind:"schema",type:"object",reference:re,expects:"Object",async:!1,entries:t,message:e,_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 u={type:"object",origin:"value",input:s,key:o,value:a};for(const l of c.issues)l.path?l.path.unshift(u):l.path=[u],(i=r.issues)==null||i.push(l);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),(c.value!==void 0||o in s)&&(r.value[o]=c.value)}}else Zt(this,"type",r,n);return r}}}function ft(t,...e){const r={kind:"schema",type:"optional",reference:ft,expects:`${t.expects} | undefined`,async:!1,wrapped:t,_run(n,s){return n.value===void 0&&("default"in this&&(n.value=$h(this,n,s)),n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in e&&(r.default=e[0]),r}function Jo(t,e,r){return{kind:"schema",type:"record",reference:Jo,expects:"Object",async:!1,key:t,value:e,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(a3(i,c)){const u=i[c],l=this.key._run({typed:!1,value:c},s);if(l.issues){const h={type:"object",origin:"key",input:i,key:c,value:u};for(const f of l.issues)f.path=[h],(o=n.issues)==null||o.push(f);if(n.issues||(n.issues=l.issues),s.abortEarly){n.typed=!1;break}}const d=this.value._run({typed:!1,value:u},s);if(d.issues){const h={type:"object",origin:"value",input:i,key:c,value:u};for(const f of d.issues)f.path?f.path.unshift(h):f.path=[h],(a=n.issues)==null||a.push(f);if(n.issues||(n.issues=d.issues),s.abortEarly){n.typed=!1;break}}(!l.typed||!d.typed)&&(n.typed=!1),l.typed&&(n.value[l.value]=d.value)}}else Zt(this,"type",n,s);return n}}}function ye(t){return{kind:"schema",type:"string",reference:ye,expects:"string",async:!1,message:t,_run(e,r){return typeof e.value=="string"?e.typed=!0:Zt(this,"type",e,r),e}}}function Nh(t,e){return{kind:"schema",type:"tuple",reference:Nh,expects:"Array",async:!1,items:t,message:e,_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 u={type:"array",origin:"value",input:s,key:o,value:a};for(const l of c.issues)l.path?l.path.unshift(u):l.path=[u],(i=r.issues)==null||i.push(l);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else Zt(this,"type",r,n);return r}}}function Om(t){let e;if(t)for(const r of t)e?e.push(...r.issues):e=r.issues;return e}function ht(t,e){return{kind:"schema",type:"union",reference:ht,expects:[...new Set(t.map(r=>r.expects))].join(" | ")||"never",async:!1,options:t,message:e,_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];Zt(this,"type",r,n,{issues:Om(i)}),r.typed=!0}else{if((o==null?void 0:o.length)===1)return o[0];Zt(this,"type",r,n,{issues:Om(o)})}return r}}}function Vs(){return{kind:"schema",type:"unknown",reference:Vs,expects:"unknown",async:!1,_run(t){return t.typed=!0,t}}}function ze(t,e,r){const n=t._run({typed:!1,value:e},n3(r));if(n.issues)throw new c3(n.issues);return n.value}function Te(...t){return{...t[0],pipe:t,_run(e,r){for(let n=0;n<t.length;n++){if(e.issues&&(t[n].kind==="schema"||t[n].kind==="transformation")){e.typed=!1;break}(!e.issues||!r.abortEarly&&!r.abortPipeEarly)&&(e=t[n]._run(e,r))}return e}}}function Qs(t){const e=Object.entries(t).map(([r,n])=>re({[r]:n}));return Te(ht(e),mu(r=>({...r,$kind:Object.keys(r)[0]})))}const Wi=Te(ye(),mu(t=>Ae(t)),xa(br)),Gt=Wi,qs=ye(),Ft=Te(ht([ye(),Te(je(),Ve())]),xa(t=>{try{return BigInt(t),BigInt(t)>=0&&BigInt(t)<=18446744073709551615n}catch{return!1}},"Invalid u64")),os=re({objectId:Wi,version:Ft,digest:ye()}),Ne=Te(ht([re({GasCoin:de(!0)}),re({Input:Te(je(),Ve()),type:ft(de("pure"))}),re({Input:Te(je(),Ve()),type:ft(de("object"))}),re({Result:Te(je(),Ve())}),re({NestedResult:Nh([Te(je(),Ve()),Te(je(),Ve())])})]),mu(t=>({...t,$kind:Object.keys(t)[0]}))),u3=re({budget:Ee(Ft),price:Ee(Ft),owner:Ee(Wi),payment:Ee(fe(os))}),fd=ht([de("address"),de("bool"),de("u8"),de("u16"),de("u32"),de("u64"),de("u128"),de("u256"),re({vector:Yo(()=>fd)}),re({datatype:re({package:ye(),module:ye(),type:ye(),typeParameters:fe(Yo(()=>fd))})}),re({typeParameter:Te(je(),Ve())})]),l3=re({ref:Ee(ht([de("&"),de("&mut")])),body:fd}),f3=re({package:Gt,module:ye(),function:ye(),typeArguments:fe(ye()),arguments:fe(Ne),_argumentTypes:ft(Ee(fe(l3)))}),d3=re({name:ye(),inputs:Jo(ye(),ht([Ne,fe(Ne)])),data:Jo(ye(),Vs())}),h3=Qs({MoveCall:f3,TransferObjects:re({objects:fe(Ne),address:Ne}),SplitCoins:re({coin:Ne,amounts:fe(Ne)}),MergeCoins:re({destination:Ne,sources:fe(Ne)}),Publish:re({modules:fe(qs),dependencies:fe(Gt)}),MakeMoveVec:re({type:Ee(ye()),elements:fe(Ne)}),Upgrade:re({modules:fe(qs),dependencies:fe(Gt),package:Gt,ticket:Ne}),$Intent:d3}),uv=Qs({ImmOrOwnedObject:os,SharedObject:re({objectId:Gt,initialSharedVersion:Ft,mutable:gu()}),Receiving:os}),p3=Qs({Object:uv,Pure:re({bytes:qs}),UnresolvedPure:re({value:Vs()}),UnresolvedObject:re({objectId:Gt,version:ft(Ee(Ft)),digest:ft(Ee(ye())),initialSharedVersion:ft(Ee(Ft))})}),Bm=Qs({Object:uv,Pure:re({bytes:qs})}),lv=Qs({None:de(!0),Epoch:Ft}),oc=re({version:de(2),sender:Mi(Wi),expiration:Mi(lv),gasData:u3,inputs:fe(p3),commands:fe(h3)}),hs={MoveCall(t){const[e,r="",n=""]="target"in t?t.target.split("::"):[t.package,t.module,t.function];return{$kind:"MoveCall",MoveCall:{package:e,module:r,function:n,typeArguments:t.typeArguments??[],arguments:t.arguments??[]}}},TransferObjects(t,e){return{$kind:"TransferObjects",TransferObjects:{objects:t.map(r=>ze(Ne,r)),address:ze(Ne,e)}}},SplitCoins(t,e){return{$kind:"SplitCoins",SplitCoins:{coin:ze(Ne,t),amounts:e.map(r=>ze(Ne,r))}}},MergeCoins(t,e){return{$kind:"MergeCoins",MergeCoins:{destination:ze(Ne,t),sources:e.map(r=>ze(Ne,r))}}},Publish({modules:t,dependencies:e}){return{$kind:"Publish",Publish:{modules:t.map(r=>typeof r=="string"?r:mt(new Uint8Array(r))),dependencies:e.map(r=>bn(r))}}},Upgrade({modules:t,dependencies:e,package:r,ticket:n}){return{$kind:"Upgrade",Upgrade:{modules:t.map(s=>typeof s=="string"?s:mt(new Uint8Array(s))),dependencies:e.map(s=>bn(s)),package:r,ticket:ze(Ne,n)}}},MakeMoveVec({type:t,elements:e}){return{$kind:"MakeMoveVec",MakeMoveVec:{type:t??null,elements:e.map(r=>ze(Ne,r))}}},Intent({name:t,inputs:e={},data:r={}}){return{$kind:"$Intent",$Intent:{name:t,inputs:Object.fromEntries(Object.entries(e).map(([n,s])=>[n,Array.isArray(s)?s.map(i=>ze(Ne,i)):ze(Ne,s)])),data:r}}}},dd=re({digest:ye(),objectId:ye(),version:ht([Te(je(),Ve()),ye(),Rh()])}),y3=Qs({ImmOrOwned:dd,Shared:re({objectId:Gt,initialSharedVersion:Ft,mutable:gu()}),Receiving:dd}),Cm=Qs({Object:y3,Pure:fe(Te(je(),Ve()))}),fv=ht([re({kind:de("Input"),index:Te(je(),Ve()),value:Vs(),type:ft(de("object"))}),re({kind:de("Input"),index:Te(je(),Ve()),value:Vs(),type:de("pure")})]),m3=ht([re({Epoch:Te(je(),Ve())}),re({None:Ee(de(!0))})]),$m=Te(ht([je(),ye(),Rh()]),xa(t=>{if(!["string","number","bigint"].includes(typeof t))return!1;try{return BigInt(t),!0}catch{return!1}})),Uh=ht([re({bool:Ee(de(!0))}),re({u8:Ee(de(!0))}),re({u64:Ee(de(!0))}),re({u128:Ee(de(!0))}),re({address:Ee(de(!0))}),re({signer:Ee(de(!0))}),re({vector:Yo(()=>Uh)}),re({struct:Yo(()=>g3)}),re({u16:Ee(de(!0))}),re({u32:Ee(de(!0))}),re({u256:Ee(de(!0))})]),g3=re({address:ye(),module:ye(),name:ye(),typeParams:fe(Uh)}),b3=re({budget:ft($m),price:ft($m),payment:ft(fe(dd)),owner:ft(ye())}),w3=[fv,re({kind:de("GasCoin")}),re({kind:de("Result"),index:Te(je(),Ve())}),re({kind:de("NestedResult"),index:Te(je(),Ve()),resultIndex:Te(je(),Ve())})],_n=ht([...w3]),v3=re({kind:de("MoveCall"),target:Te(ye(),xa(t=>t.split("::").length===3)),typeArguments:fe(ye()),arguments:fe(_n)}),E3=re({kind:de("TransferObjects"),objects:fe(_n),address:_n}),S3=re({kind:de("SplitCoins"),coin:_n,amounts:fe(_n)}),A3=re({kind:de("MergeCoins"),destination:_n,sources:fe(_n)}),x3=re({kind:de("MakeMoveVec"),type:ht([re({Some:Uh}),re({None:Ee(de(!0))})]),objects:fe(_n)}),k3=re({kind:de("Publish"),modules:fe(fe(Te(je(),Ve()))),dependencies:fe(ye())}),_3=re({kind:de("Upgrade"),modules:fe(fe(Te(je(),Ve()))),dependencies:fe(ye()),packageId:ye(),ticket:_n}),T3=[v3,E3,S3,A3,k3,_3,x3],I3=ht([...T3]);re({version:de(1),sender:ft(ye()),expiration:Mi(m3),gasConfig:b3,inputs:fe(fv),transactions:fe(I3)});function Rm(t){var r;const e=t.inputs.map((n,s)=>{if(n.Object)return{kind:"Input",index:s,value:{Object:n.Object.ImmOrOwnedObject?{ImmOrOwned:n.Object.ImmOrOwnedObject}:n.Object.Receiving?{Receiving:{digest:n.Object.Receiving.digest,version:n.Object.Receiving.version,objectId:n.Object.Receiving.objectId}}:{Shared:{mutable:n.Object.SharedObject.mutable,initialSharedVersion:n.Object.SharedObject.initialSharedVersion,objectId:n.Object.SharedObject.objectId}}},type:"object"};if(n.Pure)return{kind:"Input",index:s,value:{Pure:Array.from(qt(n.Pure.bytes))},type:"pure"};if(n.UnresolvedPure)return{kind:"Input",type:"pure",index:s,value:n.UnresolvedPure.value};if(n.UnresolvedObject)return{kind:"Input",type:"object",index:s,value:n.UnresolvedObject.objectId};throw new Error("Invalid input")});return{version:1,sender:t.sender??void 0,expiration:((r=t.expiration)==null?void 0:r.$kind)==="Epoch"?{Epoch:Number(t.expiration.Epoch)}:t.expiration?{None:!0}:null,gasConfig:{owner:t.gasData.owner??void 0,budget:t.gasData.budget??void 0,price:t.gasData.price??void 0,payment:t.gasData.payment??void 0},inputs:e,transactions:t.commands.map(n=>{if(n.MakeMoveVec)return{kind:"MakeMoveVec",type:n.MakeMoveVec.type===null?{None:!0}:{Some:Er.parseFromStr(n.MakeMoveVec.type)},objects:n.MakeMoveVec.elements.map(s=>cn(s,e))};if(n.MergeCoins)return{kind:"MergeCoins",destination:cn(n.MergeCoins.destination,e),sources:n.MergeCoins.sources.map(s=>cn(s,e))};if(n.MoveCall)return{kind:"MoveCall",target:`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`,typeArguments:n.MoveCall.typeArguments,arguments:n.MoveCall.arguments.map(s=>cn(s,e))};if(n.Publish)return{kind:"Publish",modules:n.Publish.modules.map(s=>Array.from(qt(s))),dependencies:n.Publish.dependencies};if(n.SplitCoins)return{kind:"SplitCoins",coin:cn(n.SplitCoins.coin,e),amounts:n.SplitCoins.amounts.map(s=>cn(s,e))};if(n.TransferObjects)return{kind:"TransferObjects",objects:n.TransferObjects.objects.map(s=>cn(s,e)),address:cn(n.TransferObjects.address,e)};if(n.Upgrade)return{kind:"Upgrade",modules:n.Upgrade.modules.map(s=>Array.from(qt(s))),dependencies:n.Upgrade.dependencies,packageId:n.Upgrade.package,ticket:cn(n.Upgrade.ticket,e)};throw new Error(`Unknown transaction ${Object.keys(n)}`)})}}function cn(t,e){if(t.$kind==="GasCoin")return{kind:"GasCoin"};if(t.$kind==="Result")return{kind:"Result",index:t.Result};if(t.$kind==="NestedResult")return{kind:"NestedResult",index:t.NestedResult[0],resultIndex:t.NestedResult[1]};if(t.$kind==="Input")return e[t.Input];throw new Error(`Invalid argument ${Object.keys(t)}`)}function P3(t){var e,r,n;return ze(oc,{version:2,sender:t.sender??null,expiration:t.expiration?"Epoch"in t.expiration?{Epoch:t.expiration.Epoch}:{None:!0}:null,gasData:{owner:t.gasConfig.owner??null,budget:((e=t.gasConfig.budget)==null?void 0:e.toString())??null,price:((r=t.gasConfig.price)==null?void 0:r.toString())??null,payment:((n=t.gasConfig.payment)==null?void 0:n.map(s=>({digest:s.digest,objectId:s.objectId,version:s.version.toString()})))??null},inputs:t.inputs.map(s=>{if(s.kind==="Input"){if(ld(Cm,s.value)){const i=ze(Cm,s.value);if(i.Object){if(i.Object.ImmOrOwned)return{Object:{ImmOrOwnedObject:{objectId:i.Object.ImmOrOwned.objectId,version:String(i.Object.ImmOrOwned.version),digest:i.Object.ImmOrOwned.digest}}};if(i.Object.Shared)return{Object:{SharedObject:{mutable:i.Object.Shared.mutable??null,initialSharedVersion:i.Object.Shared.initialSharedVersion,objectId:i.Object.Shared.objectId}}};if(i.Object.Receiving)return{Object:{Receiving:{digest:i.Object.Receiving.digest,version:String(i.Object.Receiving.version),objectId:i.Object.Receiving.objectId}}};throw new Error("Invalid object input")}return{Pure:{bytes:mt(new Uint8Array(i.Pure))}}}return s.type==="object"?{UnresolvedObject:{objectId:s.value}}:{UnresolvedPure:{value:s.value}}}throw new Error("Invalid input")}),commands:t.transactions.map(s=>{switch(s.kind){case"MakeMoveVec":return{MakeMoveVec:{type:"Some"in s.type?Er.tagToString(s.type.Some):null,elements:s.objects.map(i=>un(i))}};case"MergeCoins":return{MergeCoins:{destination:un(s.destination),sources:s.sources.map(i=>un(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=>un(c))}}}case"Publish":return{Publish:{modules:s.modules.map(i=>mt(Uint8Array.from(i))),dependencies:s.dependencies}};case"SplitCoins":return{SplitCoins:{coin:un(s.coin),amounts:s.amounts.map(i=>un(i))}};case"TransferObjects":return{TransferObjects:{objects:s.objects.map(i=>un(i)),address:un(s.address)}};case"Upgrade":return{Upgrade:{modules:s.modules.map(i=>mt(Uint8Array.from(i))),dependencies:s.dependencies,package:s.packageId,ticket:un(s.ticket)}}}throw new Error(`Unknown transaction ${Object.keys(s)}`)})})}function un(t){switch(t.kind){case"GasCoin":return{GasCoin:!0};case"Result":return{Result:t.index};case"NestedResult":return{NestedResult:[t.index,t.resultIndex]};case"Input":return{Input:t.index}}}function ka(t){return ht(Object.entries(t).map(([e,r])=>re({[e]:r})))}const yr=ka({GasCoin:de(!0),Input:Te(je(),Ve()),Result:Te(je(),Ve()),NestedResult:Nh([Te(je(),Ve()),Te(je(),Ve())])}),O3=re({budget:Ee(Ft),price:Ee(Ft),owner:Ee(Wi),payment:Ee(fe(os))}),B3=re({package:Gt,module:ye(),function:ye(),typeArguments:fe(ye()),arguments:fe(yr)}),C3=re({name:ye(),inputs:Jo(ye(),ht([yr,fe(yr)])),data:Jo(ye(),Vs())}),$3=ka({MoveCall:B3,TransferObjects:re({objects:fe(yr),address:yr}),SplitCoins:re({coin:yr,amounts:fe(yr)}),MergeCoins:re({destination:yr,sources:fe(yr)}),Publish:re({modules:fe(qs),dependencies:fe(Gt)}),MakeMoveVec:re({type:Ee(ye()),elements:fe(yr)}),Upgrade:re({modules:fe(qs),dependencies:fe(Gt),package:Gt,ticket:yr}),$Intent:C3}),R3=ka({ImmOrOwnedObject:os,SharedObject:re({objectId:Gt,initialSharedVersion:Ft,mutable:gu()}),Receiving:os}),N3=ka({Object:R3,Pure:re({bytes:qs}),UnresolvedPure:re({value:Vs()}),UnresolvedObject:re({objectId:Gt,version:ft(Ee(Ft)),digest:ft(Ee(ye())),initialSharedVersion:ft(Ee(Ft))})}),U3=ka({None:de(!0),Epoch:Ft}),M3=re({version:de(2),sender:Mi(Wi),expiration:Mi(U3),gasData:O3,inputs:fe(N3),commands:fe($3),digest:ft(Ee(ye()))});function F3(t){return{$kind:"Pure",Pure:{bytes:t instanceof Uint8Array?mt(t):t.toBase64()}}}const Vt={Pure:F3,ObjectRef({objectId:t,digest:e,version:r}){return{$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{digest:e,version:r,objectId:Ae(t)}}}},SharedObjectRef({objectId:t,mutable:e,initialSharedVersion:r}){return{$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{mutable:e,initialSharedVersion:r,objectId:Ae(t)}}}},ReceivingRef({objectId:t,digest:e,version:r}){return{$kind:"Object",Object:{$kind:"Receiving",Receiving:{digest:e,version:r,objectId:Ae(t)}}}}};BigInt(1e9);const j3="0x1",dv="0x2",L3=bn("0x6"),H3=`${dv}::sui::SUI`;bn("0x5");const D3=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]),rt=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),ne=new Uint32Array(32);function Ln(t,e,r,n,s,i){const o=s[i],a=s[i+1];let c=ne[2*t],u=ne[2*t+1],l=ne[2*e],d=ne[2*e+1],h=ne[2*r],f=ne[2*r+1],m=ne[2*n],g=ne[2*n+1],v=S0(c,l,o);u=A0(v,u,d,a),c=v|0,{Dh:g,Dl:m}={Dh:g^u,Dl:m^c},{Dh:g,Dl:m}={Dh:rE(g,m),Dl:nE(g)},{h:f,l:h}=E0(f,h,g,m),{Bh:d,Bl:l}={Bh:d^f,Bl:l^h},{Bh:d,Bl:l}={Bh:w0(d,l,24),Bl:v0(d,l,24)},ne[2*t]=c,ne[2*t+1]=u,ne[2*e]=l,ne[2*e+1]=d,ne[2*r]=h,ne[2*r+1]=f,ne[2*n]=m,ne[2*n+1]=g}function Hn(t,e,r,n,s,i){const o=s[i],a=s[i+1];let c=ne[2*t],u=ne[2*t+1],l=ne[2*e],d=ne[2*e+1],h=ne[2*r],f=ne[2*r+1],m=ne[2*n],g=ne[2*n+1],v=S0(c,l,o);u=A0(v,u,d,a),c=v|0,{Dh:g,Dl:m}={Dh:g^u,Dl:m^c},{Dh:g,Dl:m}={Dh:w0(g,m,16),Dl:v0(g,m,16)},{h:f,l:h}=E0(f,h,g,m),{Bh:d,Bl:l}={Bh:d^f,Bl:l^h},{Bh:d,Bl:l}={Bh:eE(d,l,63),Bl:tE(d,l,63)},ne[2*t]=c,ne[2*t+1]=u,ne[2*e]=l,ne[2*e+1]=d,ne[2*r]=h,ne[2*r+1]=f,ne[2*n]=m,ne[2*n+1]=g}function z3(t,e={},r,n,s){if(rs(r),t<0||t>r)throw new Error("outputLen bigger than keyLen");const{key:i,salt:o,personalization:a}=e;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 V3 extends Pc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,rs(e),rs(r),this.blockLen=e,this.outputLen=r,this.buffer=new Uint8Array(e),this.buffer32=ko(this.buffer)}update(e){ns(this),e=wn(e),Kr(e);const{blockLen:r,buffer:n,buffer32:s}=this,i=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<i;){this.pos===r&&(qn(s),this.compress(s,0,!1),qn(s),this.pos=0);const u=Math.min(r-this.pos,i-c),l=o+c;if(u===r&&!(l%4)&&c+u<i){const d=new Uint32Array(a,l,Math.floor((i-c)/4));qn(d);for(let h=0;c+r<i;h+=s.length,c+=r)this.length+=r,this.compress(d,h,!1);qn(d);continue}n.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){ns(this),Ed(e,this);const{pos:r,buffer32:n}=this;this.finished=!0,Ir(this.buffer.subarray(r)),qn(n),this.compress(n,0,!0),qn(n);const s=ko(e);this.get().forEach((i,o)=>s[o]=ln(i))}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){const{buffer:r,length:n,finished:s,destroyed:i,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(r),e.destroyed=i,e.finished=s,e.length=n,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class q3 extends V3{constructor(e={}){const r=e.dkLen===void 0?64:e.dkLen;super(128,r),this.v0l=rt[0]|0,this.v0h=rt[1]|0,this.v1l=rt[2]|0,this.v1h=rt[3]|0,this.v2l=rt[4]|0,this.v2h=rt[5]|0,this.v3l=rt[6]|0,this.v3h=rt[7]|0,this.v4l=rt[8]|0,this.v4h=rt[9]|0,this.v5l=rt[10]|0,this.v5h=rt[11]|0,this.v6l=rt[12]|0,this.v6h=rt[13]|0,this.v7l=rt[14]|0,this.v7h=rt[15]|0,z3(r,e,64,16,16);let{key:n,personalization:s,salt:i}=e,o=0;if(n!==void 0&&(n=wn(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=wn(i);const a=ko(i);this.v4l^=ln(a[0]),this.v4h^=ln(a[1]),this.v5l^=ln(a[2]),this.v5h^=ln(a[3])}if(s!==void 0){s=wn(s);const a=ko(s);this.v6l^=ln(a[0]),this.v6h^=ln(a[1]),this.v7l^=ln(a[2]),this.v7h^=ln(a[3])}if(n!==void 0){const a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:e,v0h:r,v1l:n,v1h:s,v2l:i,v2h:o,v3l:a,v3h:c,v4l:u,v4h:l,v5l:d,v5h:h,v6l:f,v6h:m,v7l:g,v7h:v}=this;return[e,r,n,s,i,o,a,c,u,l,d,h,f,m,g,v]}set(e,r,n,s,i,o,a,c,u,l,d,h,f,m,g,v){this.v0l=e|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=u|0,this.v4h=l|0,this.v5l=d|0,this.v5h=h|0,this.v6l=f|0,this.v6h=m|0,this.v7l=g|0,this.v7h=v|0}compress(e,r,n){this.get().forEach((c,u)=>ne[u]=c),ne.set(rt,16);let{h:s,l:i}=b0(BigInt(this.length));ne[24]=rt[8]^i,ne[25]=rt[9]^s,n&&(ne[28]=~ne[28],ne[29]=~ne[29]);let o=0;const a=D3;for(let c=0;c<12;c++)Ln(0,4,8,12,e,r+2*a[o++]),Hn(0,4,8,12,e,r+2*a[o++]),Ln(1,5,9,13,e,r+2*a[o++]),Hn(1,5,9,13,e,r+2*a[o++]),Ln(2,6,10,14,e,r+2*a[o++]),Hn(2,6,10,14,e,r+2*a[o++]),Ln(3,7,11,15,e,r+2*a[o++]),Hn(3,7,11,15,e,r+2*a[o++]),Ln(0,5,10,15,e,r+2*a[o++]),Hn(0,5,10,15,e,r+2*a[o++]),Ln(1,6,11,12,e,r+2*a[o++]),Hn(1,6,11,12,e,r+2*a[o++]),Ln(2,7,8,13,e,r+2*a[o++]),Hn(2,7,8,13,e,r+2*a[o++]),Ln(3,4,9,14,e,r+2*a[o++]),Hn(3,4,9,14,e,r+2*a[o++]);this.v0l^=ne[0]^ne[16],this.v0h^=ne[1]^ne[17],this.v1l^=ne[2]^ne[18],this.v1h^=ne[3]^ne[19],this.v2l^=ne[4]^ne[20],this.v2h^=ne[5]^ne[21],this.v3l^=ne[6]^ne[22],this.v3h^=ne[7]^ne[23],this.v4l^=ne[8]^ne[24],this.v4h^=ne[9]^ne[25],this.v5l^=ne[10]^ne[26],this.v5h^=ne[11]^ne[27],this.v6l^=ne[12]^ne[28],this.v6h^=ne[13]^ne[29],this.v7l^=ne[14]^ne[30],this.v7h^=ne[15]^ne[31],Ir(ne)}destroy(){this.destroyed=!0,Ir(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const G3=fE(t=>new q3(t)),hv=G3;function W3(t,e,r){const n=he.Address.serialize(t).toBytes(),s=he.TypeTag.serialize(e).toBytes(),i=he.u64().serialize(r.length).toBytes(),o=hv.create({dkLen:32});return o.update(new Uint8Array([240])),o.update(n),o.update(i),o.update(r),o.update(s),`0x${Ui(o.digest().slice(0,32))}`}const K3="object",Z3="ID",X3="ascii",Y3="String",J3="string",Q3="String",eB="option",tB="Option";function rB(t){const e=typeof t.body=="object"&&"datatype"in t.body?t.body.datatype:null;return!!e&&Ae(e.package)===Ae("0x2")&&e.module==="tx_context"&&e.type==="TxContext"}function hd(t){if(typeof t=="string")switch(t){case"address":return he.Address;case"bool":return he.Bool;case"u8":return he.U8;case"u16":return he.U16;case"u32":return he.U32;case"u64":return he.U64;case"u128":return he.U128;case"u256":return he.U256;default:throw new Error(`Unknown type signature ${t}`)}if("vector"in t){if(t.vector==="u8")return he.vector(he.U8).transform({input:r=>typeof r=="string"?new TextEncoder().encode(r):r,output:r=>r});const e=hd(t.vector);return e?he.vector(e):null}if("datatype"in t){const e=Ae(t.datatype.package);if(e===Ae(j3)){if(t.datatype.module===X3&&t.datatype.type===Y3||t.datatype.module===J3&&t.datatype.type===Q3)return he.String;if(t.datatype.module===eB&&t.datatype.type===tB){const r=hd(t.datatype.typeParameters[0]);return r?he.vector(r):null}}if(e===Ae(dv)&&t.datatype.module===K3&&t.datatype.type===Z3)return he.Address}return null}function nB(t){return typeof t=="object"&&"Reference"in t?{ref:"&",body:So(t.Reference)}:typeof t=="object"&&"MutableReference"in t?{ref:"&mut",body:So(t.MutableReference)}:{ref:null,body:So(t)}}function So(t){if(typeof t=="string")switch(t){case"Address":return"address";case"Bool":return"bool";case"U8":return"u8";case"U16":return"u16";case"U32":return"u32";case"U64":return"u64";case"U128":return"u128";case"U256":return"u256";default:throw new Error(`Unexpected type ${t}`)}if("Vector"in t)return{vector:So(t.Vector)};if("Struct"in t)return{datatype:{package:t.Struct.address,module:t.Struct.module,type:t.Struct.name,typeParameters:t.Struct.typeArguments.map(So)}};if("TypeParameter"in t)return{typeParameter:t.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(t)}`)}const sB=50,iB=1000n,oB=5e10;function pv(t){return async function(r,n,s){return await fB(r,t),await lB(r,t),n.onlyTransactionKind||(await aB(r,t),await cB(r,t),await uB(r,t)),await s()}}async function aB(t,e){t.gasConfig.price||(t.gasConfig.price=String(await e.getReferenceGasPrice()))}async function cB(t,e){if(t.gasConfig.budget)return;const r=await e.dryRunTransactionBlock({transactionBlock:t.build({overrides:{gasData:{budget:String(oB),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=iB*BigInt(t.gasConfig.price||1n),s=BigInt(r.effects.gasUsed.computationCost)+n,i=s+BigInt(r.effects.gasUsed.storageCost)-BigInt(r.effects.gasUsed.storageRebate);t.gasConfig.budget=String(i>s?i:s)}async function uB(t,e){if(!t.gasConfig.payment){const n=(await e.getCoins({owner:t.gasConfig.owner||t.sender,coinType:H3})).data.filter(s=>!t.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.");t.gasConfig.payment=n.map(s=>ze(os,s))}}async function lB(t,e){const r=t.inputs.filter(l=>{var d;return l.UnresolvedObject&&!(l.UnresolvedObject.version||(d=l.UnresolvedObject)!=null&&d.initialSharedVersion)}),n=[...new Set(r.map(l=>bn(l.UnresolvedObject.objectId)))],s=n.length?pu(n,sB):[],i=(await Promise.all(s.map(l=>e.multiGetObjects({ids:l,options:{showOwner:!0}})))).flat(),o=new Map(n.map((l,d)=>[l,i[d]])),a=Array.from(o).filter(([l,d])=>d.error).map(([l,d])=>JSON.stringify(d.error));if(a.length)throw new Error(`The following input objects are invalid: ${a.join(", ")}`);const c=i.map(l=>{if(l.error||!l.data)throw new Error(`Failed to fetch object: ${l.error}`);const d=l.data.owner,h=d&&typeof d=="object"?"Shared"in d?d.Shared.initial_shared_version:"ConsensusAddressOwner"in d?d.ConsensusAddressOwner.start_version:null:null;return{objectId:l.data.objectId,digest:l.data.digest,version:l.data.version,initialSharedVersion:h}}),u=new Map(n.map((l,d)=>[l,c[d]]));for(const[l,d]of t.inputs.entries()){if(!d.UnresolvedObject)continue;let h;const f=Ae(d.UnresolvedObject.objectId),m=u.get(f);d.UnresolvedObject.initialSharedVersion??(m==null?void 0:m.initialSharedVersion)?h=Vt.SharedObjectRef({objectId:f,initialSharedVersion:d.UnresolvedObject.initialSharedVersion||(m==null?void 0:m.initialSharedVersion),mutable:dB(t,l)}):hB(t,l)&&(h=Vt.ReceivingRef({objectId:f,digest:d.UnresolvedObject.digest??(m==null?void 0:m.digest),version:d.UnresolvedObject.version??(m==null?void 0:m.version)})),t.inputs[t.inputs.indexOf(d)]=h??Vt.ObjectRef({objectId:f,digest:d.UnresolvedObject.digest??(m==null?void 0:m.digest),version:d.UnresolvedObject.version??(m==null?void 0:m.version)})}}async function fB(t,e){const{inputs:r,commands:n}=t,s=[],i=new Set;n.forEach(a=>{if(a.MoveCall){if(a.MoveCall._argumentTypes)return;if(a.MoveCall.arguments.map(l=>l.$kind==="Input"?t.inputs[l.Input]:null).some(l=>(l==null?void 0:l.UnresolvedPure)||(l==null?void 0:l.UnresolvedObject))){const l=`${a.MoveCall.package}::${a.MoveCall.module}::${a.MoveCall.function}`;i.add(l),s.push(a.MoveCall)}}});const o=new Map;i.size>0&&await Promise.all([...i].map(async a=>{const[c,u,l]=a.split("::"),d=await e.getNormalizedMoveFunction({package:c,module:u,function:l});o.set(a,d.parameters.map(h=>nB(h)))})),s.length&&await Promise.all(s.map(async a=>{const c=o.get(`${a.package}::${a.module}::${a.function}`);if(!c)return;const l=c.length>0&&rB(c.at(-1))?c.slice(0,c.length-1):c;a._argumentTypes=l})),n.forEach(a=>{if(!a.MoveCall)return;const c=a.MoveCall,u=`${c.package}::${c.module}::${c.function}`,l=c._argumentTypes;if(l){if(l.length!==a.MoveCall.arguments.length)throw new Error(`Incorrect number of arguments for ${u}`);l.forEach((d,h)=>{var _,E;const f=c.arguments[h];if(f.$kind!=="Input")return;const m=r[f.Input];if(!m.UnresolvedPure&&!m.UnresolvedObject)return;const g=((_=m.UnresolvedPure)==null?void 0:_.value)??((E=m.UnresolvedObject)==null?void 0:E.objectId),v=hd(d.body);if(v){f.type="pure",r[r.indexOf(m)]=Vt.Pure(v.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)}`);f.type="object";const S=m.UnresolvedPure?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:g}}:m;r[f.Input]=S})}})}function dB(t,e){let r=!1;return t.getInputUses(e,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=s.MoveCall._argumentTypes[i].ref!=="&"||r}(s.$kind==="MakeMoveVec"||s.$kind==="MergeCoins"||s.$kind==="SplitCoins"||s.$kind==="TransferObjects")&&(r=!0)}),r}function hB(t,e){let r=!1;return t.getInputUses(e,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=pB(s.MoveCall._argumentTypes[i])||r}}),r}function pB(t){return typeof t.body!="object"||!("datatype"in t.body)?!1:t.body.datatype.package==="0x2"&&t.body.datatype.module==="transfer"&&t.body.datatype.type==="Receiving"}function yv(t,e){return!!(t.inputs.some(r=>r.UnresolvedObject||r.UnresolvedPure)||!e.onlyTransactionKind&&(!t.gasConfig.price||!t.gasConfig.budget||!t.gasConfig.payment))}async function yB(t,e,r){var i;if(gB(t),!yv(t,e))return await Nm(t),r();const n=mB(e);return(((i=n.core)==null?void 0:i.resolveTransactionPlugin())??pv(n))(t,e,async()=>{await Nm(t),await r()})}function Nm(t){t.inputs.forEach((e,r)=>{if(e.$kind!=="Object"&&e.$kind!=="Pure")throw new Error(`Input at index ${r} has not been resolved. Expected a Pure or Object input, but found ${JSON.stringify(e)}`)})}function mB(t){if(!t.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return t.client}function gB(t){for(const e of t.commands)switch(e.$kind){case"SplitCoins":e.SplitCoins.amounts.forEach(r=>{Um(r,he.U64,t)});break;case"TransferObjects":Um(e.TransferObjects.address,he.Address,t);break}}function Um(t,e,r){if(t.$kind!=="Input")return;const n=r.inputs[t.Input];n.$kind==="UnresolvedPure"&&(r.inputs[t.Input]=Vt.Pure(e.serialize(n.UnresolvedPure.value)))}function bB(t){function e(r){return t(r)}return e.system=r=>{const n=r==null?void 0:r.mutable;return e(n!==void 0?Vt.SharedObjectRef({objectId:"0x5",initialSharedVersion:1,mutable:n}):{$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x5",initialSharedVersion:1}})},e.clock=()=>e(Vt.SharedObjectRef({objectId:"0x6",initialSharedVersion:1,mutable:!1})),e.random=()=>e(Vt.SharedObjectRef({objectId:"0x8",initialSharedVersion:1,mutable:!1})),e.denyList=r=>{const n=r==null?void 0:r.mutable;return e(n!==void 0?Vt.SharedObjectRef({objectId:"0x403",initialSharedVersion:1,mutable:n}):{$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x403",initialSharedVersion:1}})},e.option=({type:r,value:n})=>s=>s.moveCall({typeArguments:[r],target:`0x1::option::${n===null?"none":"some"}`,arguments:n===null?[]:[s.object(n)]}),e}function wB(t){function e(r,n){if(typeof r=="string")return t(Eo(r).serialize(n));if(r instanceof Uint8Array||Ph(r))return t(r);throw new Error("tx.pure must be called either a bcs type name, or a serialized bcs value")}return e.u8=r=>t(he.U8.serialize(r)),e.u16=r=>t(he.U16.serialize(r)),e.u32=r=>t(he.U32.serialize(r)),e.u64=r=>t(he.U64.serialize(r)),e.u128=r=>t(he.U128.serialize(r)),e.u256=r=>t(he.U256.serialize(r)),e.bool=r=>t(he.Bool.serialize(r)),e.string=r=>t(he.String.serialize(r)),e.address=r=>t(he.Address.serialize(r)),e.id=e.address,e.vector=(r,n)=>t(he.vector(Eo(r)).serialize(n)),e.option=(r,n)=>t(he.option(Eo(r)).serialize(n)),e}function vB(t,e){const r=Array.from(`${t}::`).map(s=>s.charCodeAt(0)),n=new Uint8Array(r.length+e.length);return n.set(r),n.set(e,r.length),hv(n,{dkLen:32})}function Mm(t){return Ae(t).replace("0x","")}class Rt{constructor(e){this.version=2,this.sender=(e==null?void 0:e.sender)??null,this.expiration=(e==null?void 0:e.expiration)??null,this.inputs=(e==null?void 0:e.inputs)??[],this.commands=(e==null?void 0:e.commands)??[],this.gasData=(e==null?void 0:e.gasData)??{budget:null,price:null,owner:null,payment:null}}static fromKindBytes(e){const n=he.TransactionKind.parse(e).ProgrammableTransaction;if(!n)throw new Error("Unable to deserialize from bytes.");return Rt.restore({version:2,sender:null,expiration:null,gasData:{budget:null,owner:null,payment:null,price:null},inputs:n.inputs,commands:n.commands})}static fromBytes(e){const r=he.TransactionData.parse(e),n=r==null?void 0:r.V1,s=n.kind.ProgrammableTransaction;if(!n||!s)throw new Error("Unable to deserialize from bytes.");return Rt.restore({version:2,sender:n.sender,expiration:n.expiration,gasData:n.gasData,inputs:s.inputs,commands:s.commands})}static restore(e){return e.version===2?new Rt(ze(oc,e)):new Rt(ze(oc,P3(e)))}static getDigestFromBytes(e){const r=vB("TransactionData",e);return hu(r)}get gasConfig(){return this.gasData}set gasConfig(e){this.gasData=e}build({maxSizeBytes:e=1/0,overrides:r,onlyTransactionKind:n}={}){const s=this.inputs,i=this.commands,o={ProgrammableTransaction:{inputs:s,commands:i}};if(n)return he.TransactionKind.serialize(o,{maxSize:e}).toBytes();const a=(r==null?void 0:r.expiration)??this.expiration,c=(r==null?void 0:r.sender)??this.sender,u={...this.gasData,...r==null?void 0:r.gasConfig,...r==null?void 0:r.gasData};if(!c)throw new Error("Missing transaction sender");if(!u.budget)throw new Error("Missing gas budget");if(!u.payment)throw new Error("Missing gas payment");if(!u.price)throw new Error("Missing gas price");const l={sender:Mm(c),expiration:a||{None:!0},gasData:{payment:u.payment,owner:Mm(this.gasData.owner??c),price:BigInt(u.price),budget:BigInt(u.budget)},kind:{ProgrammableTransaction:{inputs:s,commands:i}}};return he.TransactionData.serialize({V1:l},{maxSize:e}).toBytes()}addInput(e,r){const n=this.inputs.length;return this.inputs.push(r),{Input:n,type:e,$kind:"Input"}}getInputUses(e,r){this.mapArguments((n,s)=>(n.$kind==="Input"&&n.Input===e&&r(n,s),n))}mapCommandArguments(e,r){const n=this.commands[e];switch(n.$kind){case"MoveCall":n.MoveCall.arguments=n.MoveCall.arguments.map(i=>r(i,n,e));break;case"TransferObjects":n.TransferObjects.objects=n.TransferObjects.objects.map(i=>r(i,n,e)),n.TransferObjects.address=r(n.TransferObjects.address,n,e);break;case"SplitCoins":n.SplitCoins.coin=r(n.SplitCoins.coin,n,e),n.SplitCoins.amounts=n.SplitCoins.amounts.map(i=>r(i,n,e));break;case"MergeCoins":n.MergeCoins.destination=r(n.MergeCoins.destination,n,e),n.MergeCoins.sources=n.MergeCoins.sources.map(i=>r(i,n,e));break;case"MakeMoveVec":n.MakeMoveVec.elements=n.MakeMoveVec.elements.map(i=>r(i,n,e));break;case"Upgrade":n.Upgrade.ticket=r(n.Upgrade.ticket,n,e);break;case"$Intent":const s=n.$Intent.inputs;n.$Intent.inputs={};for(const[i,o]of Object.entries(s))n.$Intent.inputs[i]=Array.isArray(o)?o.map(a=>r(a,n,e)):r(o,n,e);break;case"Publish":break;default:throw new Error(`Unexpected transaction kind: ${n.$kind}`)}}mapArguments(e){for(const r of this.commands.keys())this.mapCommandArguments(r,e)}replaceCommand(e,r,n=e){if(!Array.isArray(r)){this.commands[e]=r;return}const s=r.length-1;this.commands.splice(e,1,...r),s!==0&&this.mapArguments((i,o,a)=>{if(a<e+r.length)return i;switch(i.$kind){case"Result":i.Result===e&&(i.Result=n),i.Result>e&&(i.Result+=s);break;case"NestedResult":i.NestedResult[0]===e&&(i.NestedResult[0]=n),i.NestedResult[0]>e&&(i.NestedResult[0]+=s);break}return i})}getDigest(){const e=this.build({onlyTransactionKind:!1});return Rt.getDigestFromBytes(e)}snapshot(){return ze(oc,this)}shallowClone(){return new Rt({version:this.version,sender:this.sender,expiration:this.expiration,gasData:{...this.gasData},inputs:[...this.inputs],commands:[...this.commands]})}}function Fm(t){if(typeof t=="string")return Ae(t);if(t.Object)return t.Object.ImmOrOwnedObject?Ae(t.Object.ImmOrOwnedObject.objectId):t.Object.Receiving?Ae(t.Object.Receiving.objectId):Ae(t.Object.SharedObject.objectId);if(t.UnresolvedObject)return Ae(t.UnresolvedObject.objectId)}var mv=t=>{throw TypeError(t)},Mh=(t,e,r)=>e.has(t)||mv("Cannot "+r),st=(t,e,r)=>(Mh(t,e,"read from private field"),r?r.call(t):e.get(t)),io=(t,e,r)=>e.has(t)?mv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Za=(t,e,r,n)=>(Mh(t,e,"write to private field"),e.set(t,r),r),bu=(t,e,r)=>(Mh(t,e,"access private method"),r),Qo,Tn,ea,Wn,qr,pd,yd,gv,bv,Fh;const EB="/",SB={"Mvr-Source":`@mysten/sui@${l1}`};class AB{constructor({cache:e,url:r,pageSize:n=50,overrides:s}){io(this,qr),io(this,Qo),io(this,Tn),io(this,ea),io(this,Wn),Za(this,Qo,e),Za(this,Tn,r),Za(this,ea,n),Za(this,Wn,{packages:s==null?void 0:s.packages,types:s==null?void 0:s.types}),xB(st(this,Wn))}async resolvePackage({package:e}){return{package:await st(this,qr,pd).load(e)}}async resolveType({type:e}){const r=[...md(e)],n=await st(this,qr,yd).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:gd(e,s)}}async resolve({types:e=[],packages:r=[]}){var l,d,h;const n=new Set;for(const f of e??[])md(f,n);const s=[...n],[i,o]=await Promise.all([s.length>0?st(this,qr,yd).loadMany(s):[],r.length>0?st(this,qr,pd).loadMany(r):[]]),a={...(l=st(this,Wn))==null?void 0:l.types};for(const[f,m]of s.entries()){const g=i[f];if(g instanceof Error)throw g;a[m]=g}const c={};for(const f of e??[]){const m=gd(f,a);c[f]={type:m}}const u={};for(const[f,m]of(r??[]).entries()){const g=((h=(d=st(this,Wn))==null?void 0:d.packages)==null?void 0:h[m])??o[f];if(g instanceof Error)throw g;u[m]={package:g}}return{types:c,packages:u}}}Qo=new WeakMap;Tn=new WeakMap;ea=new WeakMap;Wn=new WeakMap;qr=new WeakSet;pd=function(){return st(this,Qo).readSync(["#mvrPackageDataLoader",st(this,Tn)??""],()=>{var r;const t=new x1(async n=>{if(!st(this,Tn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await bu(this,qr,gv).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve package: ${i}`))}),e=(r=st(this,Wn))==null?void 0:r.packages;if(e)for(const[n,s]of Object.entries(e))t.prime(n,s);return t})};yd=function(){return st(this,Qo).readSync(["#mvrTypeDataLoader",st(this,Tn)??""],()=>{var r;const t=new x1(async n=>{if(!st(this,Tn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await bu(this,qr,bv).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve type: ${i}`))}),e=(r=st(this,Wn))==null?void 0:r.types;if(e)for(const[n,s]of Object.entries(e))t.prime(n,s);return t})};gv=async function(t){if(t.length===0)return{};const e=pu(t,st(this,ea)),r={};return await Promise.all(e.map(async n=>{var i;const s=await bu(this,qr,Fh).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};bv=async function(t){if(t.length===0)return{};const e=pu(t,st(this,ea)),r={};return await Promise.all(e.map(async n=>{var i;const s=await bu(this,qr,Fh).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};Fh=async function(t,e){if(!st(this,Tn))throw new Error("MVR Api URL is not set for the current client");const r=await fetch(`${st(this,Tn)}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...SB},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(`Failed to resolve types: ${n==null?void 0:n.message}`)}return r.json()};function xB(t){if(t!=null&&t.packages)for(const[e,r]of Object.entries(t.packages)){if(!Dt(e))throw new Error(`Invalid package name: ${e}`);if(!br(Ae(r)))throw new Error(`Invalid package ID: ${r}`)}if(t!=null&&t.types)for(const[e,r]of Object.entries(t.types)){if(zs(e).typeParams.length>0)throw new Error("Type overrides must be first-level only. If you want to supply generic types, just pass each type individually.");const n=zs(r);if(!br(n.address))throw new Error(`Invalid type: ${r}`)}}function md(t,e=new Set){if(typeof t=="string"&&!Nt(t))return e;const r=wv(t)?t:zs(t);Nt(r.address)&&e.add(`${r.address}::${r.module}::${r.name}`);for(const n of r.typeParams)md(n,e);return e}function gd(t,e){const r=wv(t)?t:zs(t),n=`${r.address}::${r.module}::${r.name}`,s=e[n];return Ac({...r,address:s?s.split("::")[0]:r.address,typeParams:r.typeParams.map(i=>gd(i,e))})}function Nt(t){return t.includes(EB)||t.includes("@")||t.includes(".sui")}function wv(t){return typeof t=="object"&&"address"in t&&"module"in t&&"name"in t&&"typeParams"in t}function kB(t){const e=new Set,r=new Set;for(const n of t.commands)switch(n.$kind){case"MakeMoveVec":n.MakeMoveVec.type&&jm([n.MakeMoveVec.type]).forEach(o=>{r.add(o)});break;case"MoveCall":const s=n.MoveCall,i=s.package.split("::")[0];if(Nt(i)){if(!Dt(i))throw new Error(`Invalid package name: ${i}`);e.add(i)}jm(s.typeArguments??[]).forEach(o=>{r.add(o)});break}return{packages:[...e],types:[...r]}}function _B(t,e){var r;for(const n of t.commands){if((r=n.MakeMoveVec)!=null&&r.type){if(!Nt(n.MakeMoveVec.type))continue;if(!e.types[n.MakeMoveVec.type])throw new Error(`No resolution found for type: ${n.MakeMoveVec.type}`);n.MakeMoveVec.type=e.types[n.MakeMoveVec.type].type}const s=n.MoveCall;if(!s)continue;const i=s.package.split("::"),o=i[0];if(Nt(o)&&!e.packages[o])throw new Error(`No address found for package: ${o}`);Nt(o)&&(i[0]=e.packages[o].package,s.package=i.join("::"));const a=s.typeArguments;if(a){for(let c=0;c<a.length;c++)if(Nt(a[c])){if(!e.types[a[c]])throw new Error(`No resolution found for type: ${a[c]}`);a[c]=e.types[a[c]].type}s.typeArguments=a}}}function jm(t){const e=new Set;for(const r of t)if(Nt(r)){if(!B5(r))throw new Error(`Invalid type with names: ${r}`);e.add(r)}return e}const TB=t=>async(e,r,n)=>{const s=kB(e);if(s.types.length===0&&s.packages.length===0)return n();const i=await IB(r).core.mvr.resolve({types:s.types,packages:s.packages});_B(e,i),await n()};function IB(t){if(!t.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return t.client}var vv=t=>{throw TypeError(t)},jh=(t,e,r)=>e.has(t)||vv("Cannot "+r),Q=(t,e,r)=>(jh(t,e,"read from private field"),r?r.call(t):e.get(t)),Lr=(t,e,r)=>e.has(t)?vv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Oe=(t,e,r,n)=>(jh(t,e,"write to private field"),e.set(t,r),r),nt=(t,e,r)=>(jh(t,e,"access private method"),r),As,Ps,pn,Wr,sr,ir,Sr,Kn,le,Ge,Ev,ac,cc,uc,xc,bd,Lh,Sv,Av;function uf(t,e=1/0){const r={$kind:"Result",get Result(){return typeof t=="function"?t():t}},n=[],s=i=>n[i]??(n[i]={$kind:"NestedResult",get NestedResult(){return[typeof t=="function"?t():t,i]}});return new Proxy(r,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(i,o){if(o in i)return Reflect.get(i,o);if(o===Symbol.iterator)return function*(){let c=0;for(;c<e;)yield s(c),c++};if(typeof o=="symbol")return;const a=parseInt(o,10);if(!(Number.isNaN(a)||a<0))return s(a)}})}const xv=Symbol.for("@mysten/transaction");function kv(t){return!!t&&typeof t=="object"&&t[xv]===!0}const Lm={buildPlugins:new Map,serializationPlugins:new Map},lf=Symbol.for("@mysten/transaction/registry");function oo(){try{const t=globalThis;return t[lf]||(t[lf]=Lm),t[lf]}catch{return Lm}}const _v=class wd{constructor(){Lr(this,Ge),Lr(this,As),Lr(this,Ps),Lr(this,pn,new Map),Lr(this,Wr,[]),Lr(this,sr,[]),Lr(this,ir,new Set),Lr(this,Sr,new Set),Lr(this,Kn,new Map),Lr(this,le),this.object=bB(r=>{var i,o;if(typeof r=="function")return this.object(this.add(r));if(typeof r=="object"&&ld(Ne,r))return r;const n=Fm(r),s=Q(this,le).inputs.find(a=>n===Fm(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:Q(this,le).inputs.indexOf(s),type:"object"}:nt(this,Ge,cc).call(this,"object",typeof r=="string"?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:Ae(r)}}:r)});const e=oo();Oe(this,le,new Rt),Oe(this,Ps,[...e.buildPlugins.values()]),Oe(this,As,[...e.serializationPlugins.values()])}static fromKind(e){const r=new wd;return Oe(r,le,Rt.fromKindBytes(typeof e=="string"?qt(e):e)),Oe(r,Wr,Q(r,le).inputs.slice()),Oe(r,sr,Q(r,le).commands.slice()),Oe(r,ir,new Set(Q(r,sr).map((n,s)=>s))),r}static from(e){const r=new wd;return kv(e)?Oe(r,le,new Rt(e.getData())):typeof e!="string"||!e.startsWith("{")?Oe(r,le,Rt.fromBytes(typeof e=="string"?qt(e):e)):Oe(r,le,Rt.restore(JSON.parse(e))),Oe(r,Wr,Q(r,le).inputs.slice()),Oe(r,sr,Q(r,le).commands.slice()),Oe(r,ir,new Set(Q(r,sr).map((n,s)=>s))),r}static registerGlobalSerializationPlugin(e,r){oo().serializationPlugins.set(e,r??e)}static unregisterGlobalSerializationPlugin(e){oo().serializationPlugins.delete(e)}static registerGlobalBuildPlugin(e,r){oo().buildPlugins.set(e,r??e)}static unregisterGlobalBuildPlugin(e){oo().buildPlugins.delete(e)}addSerializationPlugin(e){Q(this,As).push(e)}addBuildPlugin(e){Q(this,Ps).push(e)}addIntentResolver(e,r){if(Q(this,pn).has(e)&&Q(this,pn).get(e)!==r)throw new Error(`Intent resolver for ${e} already exists`);Q(this,pn).set(e,r)}setSender(e){Q(this,le).sender=e}setSenderIfNotSet(e){Q(this,le).sender||(Q(this,le).sender=e)}setExpiration(e){Q(this,le).expiration=e?ze(lv,e):null}setGasPrice(e){Q(this,le).gasConfig.price=String(e)}setGasBudget(e){Q(this,le).gasConfig.budget=String(e)}setGasBudgetIfNotSet(e){Q(this,le).gasData.budget==null&&(Q(this,le).gasConfig.budget=String(e))}setGasOwner(e){Q(this,le).gasConfig.owner=e}setGasPayment(e){Q(this,le).gasConfig.payment=e.map(r=>ze(os,r))}get blockData(){return Rm(Q(this,le).snapshot())}getData(){return Q(this,le).snapshot()}get[xv](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:wB(e=>Ph(e)?nt(this,Ge,cc).call(this,"pure",{$kind:"Pure",Pure:{bytes:e.toBase64()}}):nt(this,Ge,cc).call(this,"pure",ld(Bm,e)?ze(Bm,e):e instanceof Uint8Array?Vt.Pure(e):{$kind:"UnresolvedPure",UnresolvedPure:{value:e}}))}),this.pure}get gas(){return{$kind:"GasCoin",GasCoin:!0}}objectRef(...e){return this.object(Vt.ObjectRef(...e))}receivingRef(...e){return this.object(Vt.ReceivingRef(...e))}sharedObjectRef(...e){return this.object(Vt.SharedObjectRef(...e))}add(e){if(typeof e=="function"){if(Q(this,Kn).has(e))return Q(this,Kn).get(e);const r=nt(this,Ge,Ev).call(this),n=e(r);if(!(n&&typeof n=="object"&&"then"in n))return Oe(this,ir,Q(r,ir)),Q(this,Kn).set(e,n),n;const s=nt(this,Ge,ac).call(this,{$kind:"$Intent",$Intent:{name:"AsyncTransactionThunk",inputs:{},data:{resultIndex:Q(this,le).commands.length,result:null}}});Q(this,Sr).add(Promise.resolve(n).then(o=>{s.$Intent.data.result=o}));const i=uf(()=>s.$Intent.data.resultIndex);return Q(this,Kn).set(e,i),i}else nt(this,Ge,ac).call(this,e);return uf(Q(this,le).commands.length-1)}splitCoins(e,r){const n=hs.SplitCoins(typeof e=="string"?this.object(e):nt(this,Ge,xc).call(this,e),r.map(s=>typeof s=="number"||typeof s=="bigint"||typeof s=="string"?this.pure.u64(s):nt(this,Ge,uc).call(this,s)));return nt(this,Ge,ac).call(this,n),uf(Q(this,le).commands.length-1,r.length)}mergeCoins(e,r){return this.add(hs.MergeCoins(this.object(e),r.map(n=>this.object(n))))}publish({modules:e,dependencies:r}){return this.add(hs.Publish({modules:e,dependencies:r}))}upgrade({modules:e,dependencies:r,package:n,ticket:s}){return this.add(hs.Upgrade({modules:e,dependencies:r,package:n,ticket:this.object(s)}))}moveCall({arguments:e,...r}){return this.add(hs.MoveCall({...r,arguments:e==null?void 0:e.map(n=>nt(this,Ge,uc).call(this,n))}))}transferObjects(e,r){return this.add(hs.TransferObjects(e.map(n=>this.object(n)),typeof r=="string"?this.pure.address(r):nt(this,Ge,uc).call(this,r)))}makeMoveVec({type:e,elements:r}){return this.add(hs.MakeMoveVec({type:e,elements:r.map(n=>this.object(n))}))}serialize(){return JSON.stringify(Rm(Q(this,le).snapshot()))}async toJSON(e={}){await this.prepareForSerialization(e);const r=this.isFullyResolved();return JSON.stringify(ze(M3,r?{...Q(this,le).snapshot(),digest:Q(this,le).getDigest()}:Q(this,le).snapshot()),(n,s)=>typeof s=="bigint"?s.toString():s,2)}async sign(e){const{signer:r,...n}=e,s=await this.build(n);return r.signTransaction(s)}isFullyResolved(){return!(!Q(this,le).sender||Q(this,Sr).size>0||Q(this,le).commands.some(e=>e.$Intent)||yv(Q(this,le),{}))}async build(e={}){return await this.prepareForSerialization(e),await nt(this,Ge,bd).call(this,e),Q(this,le).build({onlyTransactionKind:e.onlyTransactionKind})}async getDigest(e={}){return await this.prepareForSerialization(e),await nt(this,Ge,bd).call(this,e),Q(this,le).getDigest()}async prepareForSerialization(e){var s;await nt(this,Ge,Sv).call(this),nt(this,Ge,Av).call(this);const r=new Set;for(const i of Q(this,le).commands)i.$Intent&&r.add(i.$Intent.name);const n=[...Q(this,As)];for(const i of r)if(!((s=e.supportedIntents)!=null&&s.includes(i))){if(!Q(this,pn).has(i))throw new Error(`Missing intent resolver for ${i}`);n.push(Q(this,pn).get(i))}n.push(TB()),await nt(this,Ge,Lh).call(this,n,e)}};As=new WeakMap;Ps=new WeakMap;pn=new WeakMap;Wr=new WeakMap;sr=new WeakMap;ir=new WeakMap;Sr=new WeakMap;Kn=new WeakMap;le=new WeakMap;Ge=new WeakSet;Ev=function(){const t=new _v;return Oe(t,le,Q(this,le)),Oe(t,As,Q(this,As)),Oe(t,Ps,Q(this,Ps)),Oe(t,pn,Q(this,pn)),Oe(t,Sr,Q(this,Sr)),Oe(t,ir,new Set(Q(this,ir))),Oe(t,Kn,Q(this,Kn)),Q(this,Wr).push(Q(t,Wr)),Q(this,sr).push(Q(t,sr)),t};ac=function(t){const e=Q(this,le).commands.length;return Q(this,sr).push(t),Q(this,ir).add(e),Q(this,le).commands.push(t),Q(this,le).mapCommandArguments(e,r=>{if(r.$kind==="Result"&&!Q(this,ir).has(r.Result))throw new Error(`Result { Result: ${r.Result} } is not available to use the current transaction`);if(r.$kind==="NestedResult"&&!Q(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>=Q(this,le).inputs.length)throw new Error(`Input { Input: ${r.Input} } references an input that does not exist in the current transaction`);return r}),t};cc=function(t,e){return Q(this,Wr).push(e),Q(this,le).addInput(t,e)};uc=function(t){return Ph(t)?this.pure(t):nt(this,Ge,xc).call(this,t)};xc=function(t){if(typeof t=="function"){const e=this.add(t);return typeof e=="function"?nt(this,Ge,xc).call(this,e):ze(Ne,e)}return ze(Ne,t)};bd=async function(t){if(!t.onlyTransactionKind&&!Q(this,le).sender)throw new Error("Missing transaction sender");await nt(this,Ge,Lh).call(this,[...Q(this,Ps),yB],t)};Lh=async function(t,e){const r=n=>{if(n>=t.length)return()=>{};const s=t[n];return async()=>{const i=r(n+1);let o=!1,a=!1;if(await s(Q(this,le),e,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)(),Oe(this,Wr,Q(this,le).inputs.slice()),Oe(this,sr,Q(this,le).commands.slice())};Sv=async function(){for(;Q(this,Sr).size>0;){const t=Promise.all(Q(this,Sr));Q(this,Sr).clear(),Q(this,Sr).add(t),await t,Q(this,Sr).delete(t)}};Av=function(){var o;const t=Q(this,le).commands,e=Q(this,le).inputs,r=Q(this,sr).flat(1/0),n=Q(this,Wr).flat(1/0);if(r.length!==t.length)throw new Error("Unexpected number of commands found in transaction data");if(n.length!==e.length)throw new Error("Unexpected number of inputs found in transaction data");const s=r.filter(a=>{var c;return((c=a.$Intent)==null?void 0:c.name)!=="AsyncTransactionThunk"});Q(this,le).commands=s,Q(this,le).inputs=n,Oe(this,sr,s),Oe(this,Wr,n),Oe(this,ir,new Set(s.map((a,c)=>c)));function i(a){var l;const c=t[a];if(((l=c.$Intent)==null?void 0:l.name)==="AsyncTransactionThunk"){const d=c.$Intent.data.result;if(d==null)throw new Error("AsyncTransactionThunk has not been resolved");return i(d.Result)}const u=s.indexOf(c);if(u===-1)throw new Error("Unable to find original index for command");return u}Q(this,le).mapArguments(a=>{if(a.$kind==="Input"){const c=n.indexOf(e[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 t.entries())if(((o=c.$Intent)==null?void 0:o.name)==="AsyncTransactionThunk")try{c.$Intent.data.resultIndex=i(a)}catch{}};let vd=_v;const PB={mainnet:"https://mainnet.mvr.mystenlabs.com",testnet:"https://testnet.mvr.mystenlabs.com"};class OB extends R1{constructor(e){var r,n,s;super(e),this.core=this,this.mvr=new AB({cache:this.cache.scope("core.mvr"),url:((r=e.mvr)==null?void 0:r.url)??PB[this.network],pageSize:(n=e.mvr)==null?void 0:n.pageSize,overrides:(s=e.mvr)==null?void 0:s.overrides})}async getObject(e){const{objectId:r}=e,{objects:[n]}=await this.getObjects({objectIds:[r],signal:e.signal});if(n instanceof Error)throw n;return{object:n}}async getDynamicField(e){const r=W3(e.parentId,Er.parseFromStr(e.name.type),e.name.bcs),{objects:[n]}=await this.getObjects({objectIds:[r],signal:e.signal});if(n instanceof Error)throw n;const s=zs(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]:Ac(s.typeParams[0]),bcs:e.name.bcs},value:{type:typeof s.typeParams[1]=="string"?s.typeParams[1]:Ac(s.typeParams[1]),bcs:i.slice(yu+e.name.bcs.length)}}}}async waitForTransaction({signal:e,timeout:r=60*1e3,...n}){const s=e?AbortSignal.any([AbortSignal.timeout(r),e]):AbortSignal.timeout(r),i=new Promise((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 BB extends Error{}class Zn extends BB{constructor(e,r){super(r),this.code=e}static fromResponse(e,r){switch(e.code){case"notExists":return new Zn(e.code,`Object ${e.object_id} does not exist`);case"dynamicFieldNotFound":return new Zn(e.code,`Dynamic field not found for object ${e.parent_object_id}`);case"deleted":return new Zn(e.code,`Object ${e.object_id} has been deleted`);case"displayError":return new Zn(e.code,`Display error: ${e.error}`);case"unknown":default:return new Zn(e.code,`Unknown error while loading object${r?` ${r}`:""}`)}}}function CB(t){return{...Rt.fromBytes(t).snapshot(),bcs:t}}function $B(t){const e=he.TransactionEffects.parse(t);switch(e.$kind){case"V1":return RB({effects:e.V1});case"V2":return NB({bytes:t,effects:e.V2});default:throw new Error(`Unknown transaction effects version: ${e.$kind}`)}}function RB(t){throw new Error("V1 effects are not supported yet")}function NB({bytes:t,effects:e}){const r=e.changedObjects.map(([n,s])=>{var i,o,a,c,u,l;return{id:n,inputState:s.inputState.$kind==="Exist"?"Exists":"DoesNotExist",inputVersion:((i=s.inputState.Exist)==null?void 0:i[0][0])??null,inputDigest:((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?e.lamportVersion:null,outputDigest:s.outputState.$kind==="PackageWrite"?(u=s.outputState.PackageWrite)==null?void 0:u[1]:((l=s.outputState.ObjectWrite)==null?void 0:l[0])??null,outputOwner:s.outputState.ObjectWrite?s.outputState.ObjectWrite[1]:null,idOperation:s.idOperation.$kind}});return{bcs:t,digest:e.transactionDigest,version:2,status:e.status.$kind==="Success"?{success:!0,error:null}:{success:!1,error:e.status.Failed.error.$kind},gasUsed:e.gasUsed,transactionDigest:e.transactionDigest,gasObject:e.gasObjectIndex===null?null:r[e.gasObjectIndex]??null,eventsDigest:e.eventsDigest,dependencies:e.dependencies,lamportVersion:e.lamportVersion,changedObjects:r,unchangedSharedObjects:e.unchangedSharedObjects.map(([n,s])=>({kind:s.$kind==="MutateDeleted"?"MutateConsensusStreamEnded":s.$kind==="ReadDeleted"?"ReadConsensusStreamEnded":s.$kind,objectId:n,version:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[0]:s[s.$kind],digest:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[1]:null})),auxiliaryDataDigest:e.auxDataDigest}}var Tv=t=>{throw TypeError(t)},Iv=(t,e,r)=>e.has(t)||Tv("Cannot "+r),Ht=(t,e,r)=>(Iv(t,e,"read from private field"),r?r.call(t):e.get(t)),UB=(t,e,r)=>e.has(t)?Tv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),MB=(t,e,r,n)=>(Iv(t,e,"write to private field"),e.set(t,r),r),yt;class FB extends OB{constructor({jsonRpcClient:e,mvr:r}){super({network:e.network,base:e,mvr:r}),UB(this,yt),MB(this,yt,e)}async getObjects(e){const r=pu(e.objectIds,50),n=[];for(const s of r){const i=await Ht(this,yt).multiGetObjects({ids:s,options:{showOwner:!0,showType:!0,showBcs:!0},signal:e.signal});for(const[o,a]of i.entries())a.error?n.push(Zn.fromResponse(a.error,s[o])):n.push(Hm(a.data))}return{objects:n}}async getOwnedObjects(e){const r=await Ht(this,yt).getOwnedObjects({owner:e.address,limit:e.limit,cursor:e.cursor,options:{showOwner:!0,showType:!0,showBcs:!0},filter:e.type?{StructType:e.type}:null,signal:e.signal});return{objects:r.data.map(n=>{if(n.error)throw Zn.fromResponse(n.error);return Hm(n.data)}),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getCoins(e){const r=await Ht(this,yt).getCoins({owner:e.address,coinType:e.coinType,limit:e.limit,cursor:e.cursor,signal:e.signal});return{objects:r.data.map(n=>({id:n.coinObjectId,version:n.version,digest:n.digest,balance:n.balance,type:`0x2::coin::Coin<${n.coinType}>`,content:Promise.resolve(HB.serialize({id:n.coinObjectId,balance:{value:n.balance}}).toBytes()),owner:{$kind:"ObjectOwner",ObjectOwner:e.address}})),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getBalance(e){const r=await Ht(this,yt).getBalance({owner:e.address,coinType:e.coinType,signal:e.signal});return{balance:{coinType:r.coinType,balance:r.totalBalance}}}async getAllBalances(e){return{balances:(await Ht(this,yt).getAllBalances({owner:e.address,signal:e.signal})).map(n=>({coinType:n.coinType,balance:n.totalBalance})),hasNextPage:!1,cursor:null}}async getTransaction(e){const r=await Ht(this,yt).getTransactionBlock({digest:e.digest,options:{showRawInput:!0,showObjectChanges:!0,showRawEffects:!0,showEvents:!0,showEffects:!0},signal:e.signal});return{transaction:Dm(r)}}async executeTransaction(e){const r=await Ht(this,yt).executeTransactionBlock({transactionBlock:e.transaction,signature:e.signatures,options:{showRawEffects:!0,showEvents:!0,showObjectChanges:!0,showRawInput:!0,showEffects:!0},signal:e.signal});return{transaction:Dm(r)}}async dryRunTransaction(e){const r=vd.from(e.transaction),n=await Ht(this,yt).dryRunTransactionBlock({transactionBlock:e.transaction,signal:e.signal}),{effects:s,objectTypes:i}=jB({effects:n.effects,objectChanges:n.objectChanges});return{transaction:{digest:await r.getDigest(),epoch:null,effects:s,objectTypes:Promise.resolve(i),signatures:[],transaction:CB(e.transaction)}}}async getReferenceGasPrice(e){const r=await Ht(this,yt).getReferenceGasPrice({signal:e==null?void 0:e.signal});return{referenceGasPrice:String(r)}}async getDynamicFields(e){const r=await Ht(this,yt).getDynamicFields({parentId:e.parentId,limit:e.limit,cursor:e.cursor});return{dynamicFields:r.data.map(n=>({id:n.objectId,type:n.objectType,name:{type:n.name.type,bcs:qt(n.bcsName)}})),hasNextPage:r.hasNextPage,cursor:r.nextCursor}}async verifyZkLoginSignature(e){const r=await Ht(this,yt).verifyZkLoginSignature({bytes:e.bytes,signature:e.signature,intentScope:e.intentScope,author:e.author});return{success:r.success,errors:r.errors}}resolveNameServiceNames(e){return Ht(this,yt).resolveNameServiceNames(e)}resolveTransactionPlugin(){return pv(Ht(this,yt))}}yt=new WeakMap;function Hm(t){var e;return{id:t.objectId,version:t.version,digest:t.digest,type:t.type,content:Promise.resolve(((e=t.bcs)==null?void 0:e.dataType)==="moveObject"?qt(t.bcs.bcsBytes):new Uint8Array),owner:fi(t.owner)}}function fi(t){if(t==="Immutable")return{$kind:"Immutable",Immutable:!0};if("ConsensusAddressOwner"in t)return{$kind:"ConsensusAddressOwner",ConsensusAddressOwner:{owner:t.ConsensusAddressOwner.owner,startVersion:t.ConsensusAddressOwner.start_version}};if("AddressOwner"in t)return{$kind:"AddressOwner",AddressOwner:t.AddressOwner};if("ObjectOwner"in t)return{$kind:"ObjectOwner",ObjectOwner:t.ObjectOwner};if("Shared"in t)return{$kind:"Shared",Shared:{initialSharedVersion:t.Shared.initial_shared_version}};throw new Error(`Unknown owner type: ${JSON.stringify(t)}`)}function Dm(t){var i,o;const e=he.SenderSignedData.parse(qt(t.rawTransaction))[0],r={};(i=t.objectChanges)==null||i.forEach(a=>{a.type!=="published"&&(r[a.objectId]=a.objectType)});const n=he.TransactionData.serialize(e.intentMessage.value).toBytes(),s=Rt.restore({version:2,sender:e.intentMessage.value.V1.sender,expiration:e.intentMessage.value.V1.expiration,gasData:e.intentMessage.value.V1.gasData,inputs:e.intentMessage.value.V1.kind.ProgrammableTransaction.inputs,commands:e.intentMessage.value.V1.kind.ProgrammableTransaction.commands});return{digest:t.digest,epoch:((o=t.effects)==null?void 0:o.executedEpoch)??null,effects:$B(new Uint8Array(t.rawEffects)),objectTypes:Promise.resolve(r),transaction:{...s,bcs:n},signatures:e.txSignatures}}function jB({bytes:t,effects:e,objectChanges:r}){var o;const n=[],s=[],i={};return r==null||r.forEach(a=>{var c,u,l,d;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:fi(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:fi(a.owner),outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:fi(a.owner),idOperation:"None"}),i[a.objectId]=a.objectType;break;case"deleted":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:((u=(c=e.deleted)==null?void 0:c.find(h=>h.objectId===a.objectId))==null?void 0:u.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:((d=(l=e.wrapped)==null?void 0:l.find(h=>h.objectId===a.objectId))==null?void 0:d.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:fi(a.owner),idOperation:"Created"}),i[a.objectId]=a.objectType;break}}),{objectTypes:i,effects:{bcs:t??null,digest:e.transactionDigest,version:2,status:e.status.status==="success"?{success:!0,error:null}:{success:!1,error:e.status.error},gasUsed:e.gasUsed,transactionDigest:e.transactionDigest,gasObject:{id:(o=e.gasObject)==null?void 0:o.reference.objectId,inputState:"Exists",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:e.gasObject.reference.version,outputDigest:e.gasObject.reference.digest,outputOwner:fi(e.gasObject.owner),idOperation:"None"},eventsDigest:e.eventsDigest??null,dependencies:e.dependencies??[],lamportVersion:e.gasObject.reference.version,changedObjects:n,unchangedSharedObjects:s,auxiliaryDataDigest:null}}}const LB=he.struct("Balance",{value:he.u64()}),HB=he.struct("Coin",{id:he.Address,balance:LB}),DB=Symbol.for("@mysten/SuiClient");class zm extends R1{constructor(e){super({network:e.network??"unknown"}),this.jsonRpc=this,this.transport=e.transport??new qO({url:e.url}),this.core=new FB({jsonRpcClient:this,mvr:e.mvr})}get[DB](){return!0}async getRpcApiVersion({signal:e}={}){return(await this.transport.request({method:"rpc.discover",params:[],signal:e})).info.version}async getCoins({coinType:e,owner:r,cursor:n,limit:s,signal:i}){if(!r||!br(Ae(r)))throw new Error("Invalid Sui address");return e&&Nt(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoins",params:[r,e,n,s],signal:i})}async getAllCoins(e){if(!e.owner||!br(Ae(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllCoins",params:[e.owner,e.cursor,e.limit],signal:e.signal})}async getBalance({owner:e,coinType:r,signal:n}){if(!e||!br(Ae(e)))throw new Error("Invalid Sui address");return r&&Nt(r)&&(r=(await this.core.mvr.resolveType({type:r})).type),await this.transport.request({method:"suix_getBalance",params:[e,r],signal:n})}async getAllBalances(e){if(!e.owner||!br(Ae(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllBalances",params:[e.owner],signal:e.signal})}async getCoinMetadata({coinType:e,signal:r}){return e&&Nt(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoinMetadata",params:[e],signal:r})}async getTotalSupply({coinType:e,signal:r}){return e&&Nt(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getTotalSupply",params:[e],signal:r})}async call(e,r,{signal:n}={}){return await this.transport.request({method:e,params:r,signal:n})}async getMoveFunctionArgTypes({package:e,module:r,function:n,signal:s}){return e&&Dt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getMoveFunctionArgTypes",params:[e,r,n],signal:s})}async getNormalizedMoveModulesByPackage({package:e,signal:r}){return e&&Dt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModulesByPackage",params:[e],signal:r})}async getNormalizedMoveModule({package:e,module:r,signal:n}){return e&&Dt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModule",params:[e,r],signal:n})}async getNormalizedMoveFunction({package:e,module:r,function:n,signal:s}){return e&&Dt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveFunction",params:[e,r,n],signal:s})}async getNormalizedMoveStruct({package:e,module:r,struct:n,signal:s}){return e&&Dt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveStruct",params:[e,r,n],signal:s})}async getOwnedObjects(e){if(!e.owner||!br(Ae(e.owner)))throw new Error("Invalid Sui address");const r=e.filter?{...e.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&&Nt(r.StructType)&&(r.StructType=(await this.core.mvr.resolveType({type:r.StructType})).type),await this.transport.request({method:"suix_getOwnedObjects",params:[e.owner,{filter:r,options:e.options},e.cursor,e.limit],signal:e.signal})}async getObject(e){if(!e.id||!Ka(bn(e.id)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"sui_getObject",params:[e.id,e.options],signal:e.signal})}async tryGetPastObject(e){return await this.transport.request({method:"sui_tryGetPastObject",params:[e.id,e.version,e.options],signal:e.signal})}async multiGetObjects(e){if(e.ids.forEach(n=>{if(!n||!Ka(bn(n)))throw new Error(`Invalid Sui Object id ${n}`)}),e.ids.length!==new Set(e.ids).size)throw new Error(`Duplicate object ids in batch call ${e.ids}`);return await this.transport.request({method:"sui_multiGetObjects",params:[e.ids,e.options],signal:e.signal})}async queryTransactionBlocks({filter:e,options:r,cursor:n,limit:s,order:i,signal:o}){return e&&"MoveFunction"in e&&Dt(e.MoveFunction.package)&&(e={...e,MoveFunction:{package:(await this.core.mvr.resolvePackage({package:e.MoveFunction.package})).package}}),await this.transport.request({method:"suix_queryTransactionBlocks",params:[{filter:e,options:r},n,s,(i||"descending")==="descending"],signal:o})}async getTransactionBlock(e){if(!Im(e.digest))throw new Error("Invalid Transaction digest");return await this.transport.request({method:"sui_getTransactionBlock",params:[e.digest,e.options],signal:e.signal})}async multiGetTransactionBlocks(e){if(e.digests.forEach(n=>{if(!Im(n))throw new Error(`Invalid Transaction digest ${n}`)}),e.digests.length!==new Set(e.digests).size)throw new Error(`Duplicate digests in batch call ${e.digests}`);return await this.transport.request({method:"sui_multiGetTransactionBlocks",params:[e.digests,e.options],signal:e.signal})}async executeTransactionBlock({transactionBlock:e,signature:r,options:n,requestType:s,signal:i}){const o=await this.transport.request({method:"sui_executeTransactionBlock",params:[typeof e=="string"?e:mt(e),Array.isArray(r)?r:[r],n],signal:i});if(s==="WaitForLocalExecution")try{await this.waitForTransaction({digest:o.digest})}catch{}return o}async signAndExecuteTransaction({transaction:e,signer:r,...n}){let s;e instanceof Uint8Array?s=e:(e.setSenderIfNotSet(r.toSuiAddress()),s=await e.build({client:this}));const{signature:i,bytes:o}=await r.signTransaction(s);return this.executeTransactionBlock({transactionBlock:o,signature:i,...n})}async getTotalTransactionBlocks({signal:e}={}){const r=await this.transport.request({method:"sui_getTotalTransactionBlocks",params:[],signal:e});return BigInt(r)}async getReferenceGasPrice({signal:e}={}){const r=await this.transport.request({method:"suix_getReferenceGasPrice",params:[],signal:e});return BigInt(r)}async getStakes(e){if(!e.owner||!br(Ae(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getStakes",params:[e.owner],signal:e.signal})}async getStakesByIds(e){return e.stakedSuiIds.forEach(r=>{if(!r||!Ka(bn(r)))throw new Error(`Invalid Sui Stake id ${r}`)}),await this.transport.request({method:"suix_getStakesByIds",params:[e.stakedSuiIds],signal:e.signal})}async getLatestSuiSystemState({signal:e}={}){return await this.transport.request({method:"suix_getLatestSuiSystemState",params:[],signal:e})}async queryEvents({query:e,cursor:r,limit:n,order:s,signal:i}){return e&&"MoveEventType"in e&&Nt(e.MoveEventType)&&(e={...e,MoveEventType:(await this.core.mvr.resolveType({type:e.MoveEventType})).type}),e&&"MoveEventModule"in e&&Dt(e.MoveEventModule.package)&&(e={...e,MoveEventModule:{module:e.MoveEventModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveEventModule.package})).package}}),"MoveModule"in e&&Dt(e.MoveModule.package)&&(e={...e,MoveModule:{module:e.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveModule.package})).package}}),await this.transport.request({method:"suix_queryEvents",params:[e,r,n,(s||"descending")==="descending"],signal:i})}async subscribeEvent(e){return this.transport.subscribe({method:"suix_subscribeEvent",unsubscribe:"suix_unsubscribeEvent",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async subscribeTransaction(e){return this.transport.subscribe({method:"suix_subscribeTransaction",unsubscribe:"suix_unsubscribeTransaction",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async devInspectTransactionBlock(e){var n,s;let r;if(kv(e.transactionBlock))e.transactionBlock.setSenderIfNotSet(e.sender),r=mt(await e.transactionBlock.build({client:this,onlyTransactionKind:!0}));else if(typeof e.transactionBlock=="string")r=e.transactionBlock;else if(e.transactionBlock instanceof Uint8Array)r=mt(e.transactionBlock);else throw new Error("Unknown transaction block format.");return(n=e.signal)==null||n.throwIfAborted(),await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e.sender,r,(s=e.gasPrice)==null?void 0:s.toString(),e.epoch],signal:e.signal})}async dryRunTransactionBlock(e){return await this.transport.request({method:"sui_dryRunTransactionBlock",params:[typeof e.transactionBlock=="string"?e.transactionBlock:mt(e.transactionBlock)]})}async getDynamicFields(e){if(!e.parentId||!Ka(bn(e.parentId)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"suix_getDynamicFields",params:[e.parentId,e.cursor,e.limit],signal:e.signal})}async getDynamicFieldObject(e){return await this.transport.request({method:"suix_getDynamicFieldObject",params:[e.parentId,e.name],signal:e.signal})}async getLatestCheckpointSequenceNumber({signal:e}={}){const r=await this.transport.request({method:"sui_getLatestCheckpointSequenceNumber",params:[],signal:e});return String(r)}async getCheckpoint(e){return await this.transport.request({method:"sui_getCheckpoint",params:[e.id],signal:e.signal})}async getCheckpoints(e){return await this.transport.request({method:"sui_getCheckpoints",params:[e.cursor,e==null?void 0:e.limit,e.descendingOrder],signal:e.signal})}async getCommitteeInfo(e){return await this.transport.request({method:"suix_getCommitteeInfo",params:[e==null?void 0:e.epoch],signal:e==null?void 0:e.signal})}async getNetworkMetrics({signal:e}={}){return await this.transport.request({method:"suix_getNetworkMetrics",params:[],signal:e})}async getAddressMetrics({signal:e}={}){return await this.transport.request({method:"suix_getLatestAddressMetrics",params:[],signal:e})}async getEpochMetrics(e){return await this.transport.request({method:"suix_getEpochMetrics",params:[e==null?void 0:e.cursor,e==null?void 0:e.limit,e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getAllEpochAddressMetrics(e){return await this.transport.request({method:"suix_getAllEpochAddressMetrics",params:[e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getEpochs(e){return await this.transport.request({method:"suix_getEpochs",params:[e==null?void 0:e.cursor,e==null?void 0:e.limit,e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getMoveCallMetrics({signal:e}={}){return await this.transport.request({method:"suix_getMoveCallMetrics",params:[],signal:e})}async getCurrentEpoch({signal:e}={}){return await this.transport.request({method:"suix_getCurrentEpoch",params:[],signal:e})}async getValidatorsApy({signal:e}={}){return await this.transport.request({method:"suix_getValidatorsApy",params:[],signal:e})}async getChainIdentifier({signal:e}={}){const r=await this.getCheckpoint({id:"0",signal:e}),n=Xo(r.digest);return Ui(n.slice(0,4))}async resolveNameServiceAddress(e){return await this.transport.request({method:"suix_resolveNameServiceAddress",params:[e.name],signal:e.signal})}async resolveNameServiceNames({format:e="dot",...r}){const{nextCursor:n,hasNextPage:s,data:i}=await this.transport.request({method:"suix_resolveNameServiceNames",params:[r.address,r.cursor,r.limit],signal:r.signal});return{hasNextPage:s,nextCursor:n,data:i.map(o=>T5(o,e))}}async getProtocolConfig(e){return await this.transport.request({method:"sui_getProtocolConfig",params:[e==null?void 0:e.version],signal:e==null?void 0:e.signal})}async verifyZkLoginSignature(e){return await this.transport.request({method:"sui_verifyZkLoginSignature",params:[e.bytes,e.signature,e.intentScope,e.author],signal:e.signal})}async waitForTransaction({signal:e,timeout:r=60*1e3,pollInterval:n=2*1e3,...s}){const i=AbortSignal.timeout(r),o=new Promise((a,c)=>{i.addEventListener("abort",()=>c(i.reason))});for(o.catch(()=>{});!i.aborted;){e==null||e.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 zB{constructor(e,r,n){this.client=new zm({url:xm(n)}),this.url=e instanceof b.Url?e:new b.Url(e),this.account=r,this.network=n}get htlcActorAddress(){return"accounts"in this.account?this.account.accounts[0].address:this.account.toSuiAddress()}async initiate(e){var r,n,s;if(!e)return b.Err("Order is required");if(ee.isSuiOrderResponse(e))return this.initiateWithCreateOrderResponse(e);try{const{source_swap:i}=e,o=BigInt(i.amount),a=i.asset,c=i.redeemer,u=i.secret_hash,l=await lh(i.asset,this.url);if(!l.ok)return b.Err(l.error);const{tokenAddress:d}=l.val,h=new vd;h.setSender(this.htlcActorAddress);const[f]=h.splitCoins(h.gas,[o]);h.moveCall({target:`${Zf[this.network].packageId}::${Zf[this.network].moduleName}::initiate`,typeArguments:[d],arguments:[h.object(a),h.pure.address(this.htlcActorAddress),h.pure.address(c),h.pure.vector("u8",Buffer.from(u,"hex")),h.pure.u64(o),h.pure.u256(i.timelock),h.pure.vector("u8",Buffer.from("")),f,h.object(L3)]});const m=await h.build({client:this.client}),g=await this.client.dryRunTransactionBlock({transactionBlock:m});if(g.effects.status.status==="failure")return b.Err(`${g.effects.status.error}`);let v;if("features"in this.account?v=await((r=this.account.features[qh.SuiSignAndExecuteTransaction])==null?void 0:r.signAndExecuteTransaction({transaction:h,account:this.account.accounts[0],chain:`sui:${this.network}`})):v=await this.client.signAndExecuteTransaction({signer:this.account,transaction:h,options:{showEffects:!0}}),!v)return b.Err("Failed to initiate");const S=await this.client.waitForTransaction({digest:v.digest,options:{showEffects:!0}});return((n=S.effects)==null?void 0:n.status.status)==="failure"?b.Err(`Failed to initiate: ${(s=S.effects)==null?void 0:s.status.error}`):b.Ok(S.digest)}catch(i){return b.Err(i)}}async initiateWithCreateOrderResponse(e){var a,c,u;const{ptb_bytes:r}=e,s=await new zm({url:xm("testnet")}).getReferenceGasPrice(),i=1e7,o=vd.fromKind(new Uint8Array(r));o.setSender(this.htlcActorAddress),o.setGasPrice(s),o.setGasBudget(i);try{let l;if("features"in this.account?l=await((a=this.account.features[qh.SuiSignAndExecuteTransaction])==null?void 0:a.signAndExecuteTransaction({transaction:o,account:this.account.accounts[0],chain:`sui:${this.network}`})):l=await this.client.signAndExecuteTransaction({signer:this.account,transaction:o,options:{showEffects:!0}}),!l)return b.Err("Failed to initiate");const d=await this.client.waitForTransaction({digest:l.digest,options:{showEffects:!0}});return((c=d.effects)==null?void 0:c.status.status)==="failure"?b.Err(`Failed to initiate: ${(u=d.effects)==null?void 0:u.status.error}`):b.Ok(d.digest)}catch(l){return b.Err(String(l))}}async redeem(e,r){try{const n=await b.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:e.order_id,secret:r,perform_on:"Destination"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return n.error?b.Err(n.error):n.result?b.Ok(n.result):b.Err("Redeem: No result found")}catch(n){return b.Err(String(n))}}async refund(){return b.Err("Refund is taken care of by the relayer")}}const VB=t=>{if(t)if(typeof t=="string"){const e=b.DigestKey.from(t);if(!e.ok)throw new Error(e.error);return e.val}else return t},Vm=t=>typeof t=="string"?new b.ApiKey(t):t;class qB{constructor(e={}){const r={stdTTL:e.ttl?e.ttl/1e3:3600,checkperiod:600};this.cache=new Fv(r)}makeKey(e,r){return`${e}:${r}`}set(e,r,n,s){const i=this.makeKey(e,r);s?this.cache.set(i,n,s/1e3):this.cache.set(i,n)}get(e,r){const n=this.makeKey(e,r);return this.cache.get(n)}remove(e,r){const n=this.makeKey(e,r);this.cache.del(n)}clear(e){if(e){const r=this.cache.keys().filter(n=>n.startsWith(`${e}:`));this.cache.del(r)}else this.cache.flushAll()}setBitcoinRedeem(e,r,n){this.set("bitcoinRedeem",e,r,n)}getBitcoinRedeem(e){return this.get("bitcoinRedeem",e)}setOrderExecution(e,r,n,s,i){const o=this.makeOrderKey(e,r),a={txHash:n,timeStamp:Date.now(),btcRedeemUTXO:s};this.set("orderExecutor",o,a,i)}getOrderExecution(e,r){const n=this.makeOrderKey(e,r);return this.get("orderExecutor",n)}removeOrderExecution(e,r){const n=this.makeOrderKey(e,r);this.remove("orderExecutor",n)}makeOrderKey(e,r){return`${r}_${e.order_id??e.created_at}`}setSacpCache(e,r,n){this.set("refundSacp",e,r,n)}getSacpCache(e){return this.get("refundSacp",e)}has(e,r){const n=this.makeKey(e,r);return this.cache.has(n)}peek(e,r){return this.get(e,r)}getRemainingTTL(e,r){const n=this.makeKey(e,r),s=this.cache.getTtl(n);if(s===void 0)return-1;const i=Date.now();return Math.max(0,s-i)}}var ta,ra,na,Xe,ki,Xn;class GB{constructor(e,r,n,s,i,o){us(this,ta);us(this,ra);us(this,na);us(this,Xe);us(this,ki);us(this,Xn);this.isBackgroundServiceRunning=!1,this.stopBackgroundExecution=null,this.htlcs=r,this.events=o,ls(this,ta,e),ls(this,ra,n),ls(this,na,Ri.fromDigestKey(e.digestKey)),ls(this,Xe,new qB),ls(this,ki,s),ls(this,Xn,i)}async getAddressesFromHTLCs(){var n,s,i,o,a;const e=new Set;return[(n=this.htlcs.evm)==null?void 0:n.htlcActorAddress,(s=this.htlcs.sui)==null?void 0:s.htlcActorAddress,(i=this.htlcs.solana)==null?void 0:i.htlcActorAddress,(o=this.htlcs.starknet)==null?void 0:o.htlcActorAddress,(a=this.htlcs.bitcoin)==null?void 0:a.htlcActorAddress].filter(c=>!!c&&c.length>0).forEach(c=>e.add(c.toLowerCase())),Array.from(e)}start(e=5e3,r){this.isBackgroundServiceRunning||this.stopBackgroundExecution||(this.isBackgroundServiceRunning=!0,(async()=>{try{if(r){this.stop();return}const n=await this.execute(e);n&&(this.stopBackgroundExecution=n)}catch(n){console.error("Error starting background executor:",n),this.isBackgroundServiceRunning=!1}})())}stop(){if(this.stopBackgroundExecution){try{this.stopBackgroundExecution()}catch{console.error("Error stopping background executor")}this.stopBackgroundExecution=null}this.isBackgroundServiceRunning=!1}async execute(e=5e3){const r=await this.getAddressesFromHTLCs();r.length===0&&r.push(Ie(this,ta).userId.toLowerCase());let n=!1,s=null;const i=async()=>{if(!n){n=!0;try{const o=r.map(async c=>{try{const u=await Ie(this,ra).getOrders({from_owner:c,status:ee.OrderLifecycle.pending,per_page:500});return u.ok?u.val.data:(this.events.emit("error",{},`Failed to fetch orders for address ${c}: ${u.error}`),[])}catch(u){return this.events.emit("error",{},`Failed to fetch orders for address ${c}: ${u}`),[]}}),a=await Promise.all(o);this.events.emit("onPendingOrdersChanged",a.flat()),await this.processOrderActions(a.flat())}finally{n=!1}}};return await i(),s=setInterval(i,e),()=>{s&&clearInterval(s)}}async processOrderActions(e){const r=new Set([ee.OrderStatus.InitiateDetected,ee.OrderStatus.AwaitingRefund,ee.OrderStatus.Initiated,ee.OrderStatus.RefundDetected,ee.OrderStatus.Refunded,ee.OrderStatus.Expired]),n=e.map(async s=>{try{ee.isBitcoin(s.source_swap.chain)&&r.has(s.status)&&!ee.isCompleted(s)&&await this.postRefundSACP(s),ee.parseAction(s)===ee.OrderAction.Redeem&&await this.handleRedeemAction(s)}catch(i){this.events.emit("error",s,`Error processing order ${s.order_id}: ${i}`)}});await Promise.all(n)}async handleRedeemAction(e){const r=await Ie(this,na).generateSecret(e.nonce);if(!r.ok){this.events.emit("error",e,r.error);return}const n=b.trim0x(r.val.secretHash),s=b.trim0x(e.source_swap.secret_hash);if(n!==s){this.events.emit("log",e.order_id,"skipping redeem: secret hash mismatch");return}const i=r.val.secret,o=ee.getBlockchainType(e.destination_swap.chain),c={[ee.BlockchainType.evm]:()=>this.evmRedeem(e,i),[ee.BlockchainType.bitcoin]:()=>this.btcRedeem(e,i),[ee.BlockchainType.starknet]:()=>this.starknetRedeem(e,i),[ee.BlockchainType.solana]:()=>this.solRedeem(e,i),[ee.BlockchainType.sui]:()=>this.suiRedeem(e,i)}[o];c?await c():this.events.emit("error",e,`Unsupported chain: ${e.destination_swap.chain}`)}async evmRedeem(e,r){if(this.events.emit("log",e.order_id,"executing evm redeem"),Ie(this,Xe).getOrderExecution(e,ee.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.evm){this.events.emit("error",e,"EVM HTLC is required");return}const s=await this.htlcs.evm.redeem(e,r);if(!s.ok){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Ie(this,Xe).setOrderExecution(e,ee.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}Ie(this,Xe).setOrderExecution(e,ee.OrderAction.Redeem,s.val),this.events.emit("success",e,ee.OrderAction.Redeem,s.val)}async starknetRedeem(e,r){if(this.events.emit("log",e.order_id,"executing starknet redeem"),Ie(this,Xe).getOrderExecution(e,ee.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.starknet){this.events.emit("error",e,"Starknet HTLC is required");return}const s=await this.htlcs.starknet.redeem(e,r);if(!s.ok){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Ie(this,Xe).setOrderExecution(e,ee.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Ie(this,Xe).setOrderExecution(e,ee.OrderAction.Redeem,s.val),this.events.emit("success",e,ee.OrderAction.Redeem,s.val))}async solRedeem(e,r){if(this.events.emit("log",e.order_id,"executing sol redeem"),Ie(this,Xe).getOrderExecution(e,ee.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.solana){this.events.emit("error",e,"Solana HTLC is required");return}const s=await this.htlcs.solana.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Ie(this,Xe).setOrderExecution(e,ee.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Ie(this,Xe).setOrderExecution(e,ee.OrderAction.Redeem,s.val),this.events.emit("success",e,ee.OrderAction.Redeem,s.val))}async suiRedeem(e,r){if(this.events.emit("log",e.order_id,"executing sui redeem"),Ie(this,Xe).getOrderExecution(e,ee.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.sui){this.events.emit("error",e,"Sui HTLC is required");return}const s=await this.htlcs.sui.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Ie(this,Xe).setOrderExecution(e,ee.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Ie(this,Xe).setOrderExecution(e,ee.OrderAction.Redeem,s.val),this.events.emit("success",e,ee.OrderAction.Redeem,s.val))}async btcRedeem(e,r){var a,c;const n=(a=this.htlcs.bitcoin)==null?void 0:a.getProvider();if(!n){this.events.emit("error",e,"Bitcoin provider not found");return}const s=Ie(this,Xe).getBitcoinRedeem(e.order_id),i=(c=e.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:c.split(":").at(0);if(!i){this.events.emit("error",e,"Failed to get initiate_tx_hash");return}let o=!1;if(s)if(s.redeemedFromUTXO&&s.redeemedFromUTXO!==i)o=!0,this.events.emit("log",e.order_id,"rbf btc redeem");else if(s.redeemedAt&&Date.now()-s.redeemedAt>1e3*60*15)this.events.emit("log",e.order_id,"redeem not confirmed in last 15 minutes"),o=!0;else{this.events.emit("log",e.order_id,"btcRedeem: already redeemed");return}else if(e.destination_swap.redeem_tx_hash&&!Number(e.destination_swap.redeem_block_number))try{const u=await(await n).getTransaction(e.destination_swap.redeem_tx_hash);let l=!1;for(const d of u.vin)if(d.txid===i){l=!0;break}if(l){this.events.emit("log",e.order_id,"already a valid redeem");let d=0;try{const[h]=await(await n).getTransactionTimes([e.destination_swap.redeem_tx_hash]);h!==0&&(d=h)}catch{d=Date.now()}Ie(this,Xe).setBitcoinRedeem(e.order_id,{redeemedFromUTXO:i,redeemedAt:d,redeemTxHash:e.destination_swap.redeem_tx_hash});return}o=!0}catch(u){if(u.message.includes("Transaction not found"))o=!0;else{this.events.emit("error",e,"Failed to get redeem tx: "+u);return}}this.events.emit("log",e.order_id,"executing btc redeem");try{if(!this.htlcs.bitcoin){this.events.emit("error",e,"Bitcoin HTLC is required");return}const u=await this.htlcs.bitcoin.getRedeemHex(e,b.trim0x(r),o?[i]:[]);if(!u.ok){this.events.emit("error",e,"Failed to get redeem hex");return}const l=await this.broadcastRedeemTx(u.val,e.order_id);if(!l.ok){this.events.emit("error",e,l.error||"Failed to broadcast redeem tx");return}o?(this.events.emit("log",e.order_id,"rbf: btc redeem success"),this.events.emit("rbf",e,l.val)):this.events.emit("success",e,ee.OrderAction.Redeem,l.val),Ie(this,Xe).setBitcoinRedeem(e.order_id,{redeemedFromUTXO:i,redeemedAt:Date.now(),redeemTxHash:l.val})}catch(u){this.events.emit("error",e,"Failed btc redeem: "+u)}}async postRefundSACP(e){if(e.source_swap.delegate)try{if(!this.htlcs.bitcoin){this.events.emit("error",e,"Bitcoin HTLC is required");return}const n=await Ie(this,ki).getAuthHeaders();if(n.error){this.events.emit("error",e,"Failed to get auth headers: "+n.error);return}const s=await b.Fetcher.post(new b.Url(Ie(this,Xn).baseurl).endpoint("relayer/bitcoin/instant-refund-hash"),{body:JSON.stringify({order_id:e.order_id}),headers:{"Content-Type":"application/json",...n.val}});if(s.error||!s.result){this.events.emit("error",e,"Failed to get hash while posting instant refund SACP: "+s.error);return}const i=await this.htlcs.bitcoin.generateInstantRefundSACPWithHash(s.result),o=new b.Url(Ie(this,Xn).baseurl).endpoint("relayer/bitcoin/instant-refund");(await b.Fetcher.post(o,{headers:{"Content-Type":"application/json",...n.val},body:JSON.stringify({order_id:e.order_id,signatures:i.val})})).ok&&Ie(this,Xe).setSacpCache(e.order_id,{initTxHash:e.source_swap.initiate_tx_hash})}catch(n){this.events.emit("error",e,"Failed to generate and post SACP: "+n);return}}async broadcastRedeemTx(e,r){try{if(!Ie(this,Xn))return b.Err("API not found");const n=new b.Url(Ie(this,Xn).relayer).endpoint("/bitcoin/redeem "),s=await Ie(this,ki).getAuthHeaders(),o=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...s.val},body:JSON.stringify({redeem_tx_bytes:e,order_id:r})})).json();return o.status==="Ok"&&o.result?b.Ok(o.result):b.Err(o.error)}catch(n){return b.Err("Failed to broadcast redeem tx: "+n)}}}ta=new WeakMap,ra=new WeakMap,na=new WeakMap,Xe=new WeakMap,ki=new WeakMap,Xn=new WeakMap;const ao={p2wpkh:"p2wpkh","p2wpkh-p2sh":"p2wpkh-p2sh"},lc={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 Os{constructor(e,r){this._scriptType=e,this._sigHashType=r}get scriptType(){return this._scriptType}get sigHashType(){return this._sigHashType}toString(){return`${this._scriptType} ${this._sigHashType}`}static async fromString(e){const[r,n]=e.split(" "),s=await Gh.mixed().oneOf(["segwitV0","segwitV1","p2shSignature"]).required().validate(r),i=await Gh.mixed().oneOf(Object.values(lc)).required().validate(parseInt(n));return new Os(s,i)}}const ys={INVALID_PK:"invalid private key",FEE_EXCEEDS_AMOUNT:(t,e)=>`fee exceeds amount: fee: ${t} > amount: ${e}`,SWAP_NOT_FOUND:"swap config not found, please set the swap config first",SCRIPT_NOT_FUNDED:"script not funded",SWAP_NOT_EXPIRED:t=>`swap not expired. Need ${t} more blocks`,MIN_AMOUNT:t=>`amount is too low. Minimum amount is ${t}`,INSUFFICIENT_FUNDS:(t,e)=>`insufficient funds, need ${e} but got ${t}`,AmtPlusFeeExceedsBalance:(t,e,r)=>`amount + fee exceeds balance. Need ${t+e} but got ${r}`},yo={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"},WB=(t,e,r=!1)=>{const n=o=>{try{o=pe.address.fromBech32(o).data.toString("hex")}catch(a){if(Jf(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(`
89
- OP_IF
90
- OP_SHA256
91
- ${t.secretHash}
92
- OP_EQUALVERIFY
93
- OP_DUP
94
- OP_HASH160
95
- ${n(t.recipientAddress.address)}
96
- OP_ELSE
97
- ${pe.script.number.encode(t.expiryBlocks).toString("hex")}
98
- OP_CHECKSEQUENCEVERIFY
99
- OP_DROP
100
- OP_DUP
101
- OP_HASH160
102
- ${n(t.refundAddress.address)}
103
- OP_ENDIF
104
- OP_EQUALVERIFY
105
- OP_CHECKSIG
106
- `.trim().replace(/\s+/g," ")),i=pe.payments[r?"p2sh":"p2wsh"]({redeem:{output:s},network:e});if(!i.address)throw new Error("Could not build address");return{script:s,address:i.address}},Ao={P2SH:"p2sh",P2WSH:"p2wsh",P2TR:"p2tr"};var Pv=(t=>(t[t.Bitcoin=0]="Bitcoin",t[t.EVM=1]="EVM",t))(Pv||{});class KB{addSignatureSegwitV0(e=lc.ALL){return new Os("segwitV0",e)}addSignatureP2sh(e=lc.ALL){return new Os("p2shSignature",e)}addSignatureSegwitV1(e=lc.ALL){return new Os("segwitV1",e)}chain(){return Pv.Bitcoin}async addAllInputs(e,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);e.addInput(Yf(o.txid),a,s==null?void 0:s.nSequence)}return e}async suggestFee(e,r){const n=await this.getAddress();return(await this.getProvider()).suggestFee(n,e,r)}async toOutputScript(e){return pe.address.toOutputScript(e,await this.getNetwork())}totalValueFromUTXOs(e){return e.reduce((r,n)=>r+n.value,0)}async scriptToAddress(e){const r=pe.payments.p2wsh({redeem:{output:e},network:await this.getNetwork()});if(!r.address)throw new Error("Could not generate p2wsh address");return r.address}async newSwap(e){if(e.secretHash=b.trim0x(e.secretHash),e.secretHash.length!==64)throw new Error(yo.INVALID_SECRET_HASH);const{script:r,address:n}=WB(e,await this.getNetwork());return new ZB(this,{...e,redeemScript:r,scriptAddress:n})}getScriptType(e,r){try{if(pe.address.fromBase58Check(e).version===r.scriptHash)return Ao.P2SH}catch{const s=pe.address.fromBech32(e);if(s.prefix!==r.bech32)throw new Error("Invalid address");if(s.version===0){if(s.data.length===32)return Ao.P2WSH}else if(s.version===1&&s.data.length===32)return Ao.P2TR}throw new Error("Unsupported script type")}}class ZB{constructor(e,r){if(r.secretHash=b.trim0x(r.secretHash),r.secretHash.length!==64)throw new Error(yo.INVALID_SECRET_HASH);this.wallet=e,this.swap=r}id(){return this.swap.scriptAddress}async init(){return this.wallet.send(this.swap.scriptAddress,+this.swap.amount.toString())}async redeem(e,r){e=b.trim0x(e);const n=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),Buffer.from(e,"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 Jf(i)?i.message.includes("OP_EQUALVERIFY")?new Error(yo.INVALID_PUBKEY_OR_SECRET):new Error(i.message):new Error(String(i))}}async refund(e){const r=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),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:e,witness:r,nSequence:this.swap.expiryBlocks})}catch(n){throw Jf(n)?n.message.includes("OP_EQUALVERIFY")?new Error(yo.INVALID_PUBKEY):n.message.includes("BIP")?new Error(yo.ORDER_NOT_EXPIRED):new Error(n.message):new Error(String(n))}}}const ff=(t,e,r,n)=>`m/${t}'/${e===xr.Mainnet?0:1}'/${r}'/0/${n??0}`,Ov={bip44:(t,e,r)=>ff("44",t,r??0,e),bip49:(t,e,r)=>ff("49",t,r??0,e),bip84:(t,e,r)=>ff("84",t,r??0,e)};function df(t){if(t===xr.Mainnet)return pe.networks.bitcoin;if(t===xr.Testnet)return pe.networks.testnet;if(t===xr.Regtest)return pe.networks.regtest;throw new Error("Invalid network")}function XB(t,e,r){if(!Wh.validateMnemonic(t))throw new Error("Invalid mnemonic");const n=(r==null?void 0:r.path)??Ov.bip44(e,(r==null?void 0:r.index)??0),s=jv.BIP32Factory(or).fromSeed(Wh.mnemonicToSeedSync(t));return YB(s,n)}const YB=(t,e)=>{const r=t.derivePath(e).privateKey;if(!r)throw new Error("Unable to derive private key from mnemonic");return r.toString("hex")};pe.initEccLib(or);class xs extends KB{constructor({privateKey:e,provider:r,pkPath:n,pkType:s}){const i=Xa.ECPairFactory(or),o=df(r.getNetwork()),a=Buffer.from(e,"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(e,r,n){const s=Ov.bip84(r.getNetwork(),n==null?void 0:n.index),i=XB(e,r.getNetwork(),{path:s});return new xs({privateKey:i,provider:r,pkType:ao.p2wpkh,pkPath:s})}static fromPrivateKey(e,r,n){return new xs({privateKey:e,provider:r,pkType:(n==null?void 0:n.pkType)??ao.p2wpkh,pkPath:(n==null?void 0:n.pkPath)??"unknown"})}static createRandom(e){const r=Xa.ECPairFactory(or),n=df(e.getNetwork()),s=r.makeRandom({network:n});if(!s.privateKey)throw new Error("Failed to create random key");return new xs({privateKey:s.privateKey.toString("hex"),provider:e,pkType:ao.p2wpkh,pkPath:"unknown"})}static fromWIF(e,r,n){const s=Xa.ECPairFactory(or),i=df(r.getNetwork()),o=s.fromWIF(e,i);if(!o.privateKey)throw new Error("Invalid WIF");return xs.fromPrivateKey(o.privateKey.toString("hex"),r,n)}walletConfig(){return{network:this.provider.getNetwork(),path:this.path,addressType:this.pkType}}async spend(e,r,{toAddress:n,fee:s,nSequence:i,unlockScript:o,witness:a}){var h;const c=this.getScriptType(r,this.network),u=await this.provider.getBalance(r);if(u===0)throw new Error(ys.SCRIPT_NOT_FUNDED);let l=new pe.Transaction;if(l.version=2,s??(s=await this.provider.suggestFee(r,u,vi.FAST)),s>u)throw new Error(ys.FEE_EXCEEDS_AMOUNT(s,u));const d=await this.provider.getUTXOs(r);l=await this.addAllInputs(l,r,this.provider,{nSequence:i,utxos:d}),l.addOutput(await this.toOutputScript(n??await this.getAddress()),u-s);for(let f=0;f<l.ins.length;f++)if(c===Ao.P2SH){if(!o)throw new Error("Unlock script is required for p2sh");const m=[];for(const v of o)if(v instanceof Os){const S=v.sigHashType,_=l.hashForSignature(f,e,S);m.push(pe.script.signature.encode(Buffer.from(await this.sign(_.toString("hex")),"hex"),S))}else m.push(v);const g=(h=pe.payments.p2sh({redeem:{input:pe.script.compile(m),output:e},network:this.network}).redeem)==null?void 0:h.input;l.setInputScript(f,g)}else if(c===Ao.P2WSH){if(!a)throw new Error("Witness is required for p2wsh");const m=[];for(const g of a)if(g instanceof Os){const v=g.sigHashType,S=l.hashForWitnessV0(f,e,d[f].value,v);m.push(pe.script.signature.encode(Buffer.from(await this.sign(S.toString("hex")),"hex"),v))}else m.push(g);l.setWitness(f,m)}else throw new Error("Invalid script type "+c);return this.provider.broadcast(l.toHex())}async getAddress(){if(this.pkType===ao["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:e}=pe.payments[this.pkType]({pubkey:this.signer.publicKey,network:this.network});if(!e)throw new Error("failed to get the p2wpkh address");return e}getProvider(){return Promise.resolve(this.provider)}async getBalance(){return this.provider.getBalance(await this.getAddress())}getPublicKey(){return this.signer.publicKey.toString("hex")}getNetwork(){return Promise.resolve(this.network)}static async generateUnsignedPSBT(e,r,n,s,i,o){if(o||(o=await e.suggestFee(n,i,vi.FAST)),o>i)throw new Error(ys.FEE_EXCEEDS_AMOUNT(o,i));const a=await e.getUTXOs(n,i+o),c=a.reduce((d,h)=>d+h.value,0);if(c<i+o)throw new Error(ys.INSUFFICIENT_FUNDS(c,i+o));const u=new pe.Psbt({network:r});for(const d of a){const h=await e.getTransactionHex(d.txid);u.addInput({hash:Yf(d.txid),index:d.vout,nonWitnessUtxo:Buffer.from(h,"hex")})}const l=c-i-o;return u.addOutput({address:s,value:i}),l>546&&u.addOutput({address:n,value:l}),{txHex:u.toHex(),utxoCount:a.length}}async _send(e,r,n){var u;if(n||(n=await this.provider.suggestFee(await this.getAddress(),r,vi.FAST)),n>r)throw new Error(ys.FEE_EXCEEDS_AMOUNT(n,r));if(r<this.minAmt)throw new Error(ys.MIN_AMOUNT(this.minAmt));const s=await this.getAddress(),i=await this.provider.getUTXOs(s,r+n),o=i.reduce((l,d)=>l+d.value,0),a=new pe.Psbt({network:this.network});for(const l of i){const d=await this.provider.getTransactionHex(l.txid),h=await this.provider.getTransaction(l.txid);let f;this.pkType===ao["p2wpkh-p2sh"]&&(f={witnessUtxo:{script:Buffer.from(h.vout[l.vout].scriptpubkey,"hex"),value:l.value},redeemScript:(u=pe.payments.p2sh({redeem:pe.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network}).redeem)==null?void 0:u.output}),a.addInput({hash:Yf(l.txid),index:l.vout,nonWitnessUtxo:Buffer.from(d,"hex"),...f})}const c=o-r-n;return a.addOutput({address:e,value:r}),c>0&&a.addOutput({address:s,value:c}),a.signAllInputs(this.signer).finalizeAllInputs(),a.extractTransaction().toHex()}async send(e,r,n){const s=await this._send(e,r,n);return this.provider.broadcast(s)}async sign(e){return e=e.startsWith("0x")?e.slice(2):e,this.signer.sign(Buffer.from(e,"hex")).toString("hex")}async signSchnorr(e){return this.signer.signSchnorr(e)}}const JB=t=>t.map(e=>e),QB=t=>{if(t===b.Network.TESTNET)return e8;if(t===b.Network.MAINNET)return t8;throw new Error("Invalid network")},e8=["https://mempool.space/testnet4/api"],t8=["https://mempool.space/api","https://blockstream.info/api"],qm=t=>t.sort((e,r)=>e.status.confirmed!=r.status.confirmed?e.status.confirmed?-1:1:r.value-e.value);class Bv{constructor(e,r){this.cacheTimeout=2e3,this.utxosCache=new Map,this.APIs=r?JB([r]):QB(e),this.network=j_(e)}async getTxIndex(e,r){const n=this.APIs.map(i=>`${i}/tx/${e}`),{vout:s}=await b.Fetcher.getWithFallback(n);for(let i=0;i<s.length;i++)if(s[i].scriptpubkey_address===r)return i;throw new Error("failed to get tx index")}async broadcast(e){if(!/^[0-9a-fA-F]+$/.test(e))throw new Error("invalid tx hex");for(let r=0;r<5;r++)try{return b.Fetcher.postWithFallback(this.APIs.map(n=>`${n}/tx`),{body:e})}catch(n){if(r===4)throw n;await new Promise(s=>setTimeout(s,500))}throw new Error("failed to broadcast tx")}async getBalance(e){return(await this.getUTXOs(e)).reduce((r,n)=>r+n.value,0)}setTimeoutForCache(e){this.cacheTimeout=e}async getUTXOs(e,r){const n=this.utxosCache.get(e);if(n&&Date.now()-n.timestamp<this.cacheTimeout)return Gm(n.utxos,r);const s=await b.Fetcher.getWithFallback(this.APIs.map(i=>`${i}/address/${e}/utxo`),{signal:AbortSignal.timeout(5e3)});return this.utxosCache.set(e,{timestamp:Date.now(),utxos:s}),Gm(s,r)}async getTransactionHex(e){return b.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${e}/hex`))}async getTransaction(e){return b.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${e}`))}async getConfirmations(e){const r=await this.getTransaction(e);return!r.status.confirmed||!r.status.block_height?0:await this.getLatestTip()-r.status.block_height+1}async getFeeRates(){if(this.network===xr.Regtest)return{fastestFee:8,halfHourFee:7,hourFee:6,economyFee:4,minimumFee:2};let e="";this.network===xr.Testnet&&(e="testnet4/");const r=`https://mempool.space/${e}api/v1/fees/recommended`,n=`https://blockstream.info/${e}api/fee-estimates`,s=await b.Fetcher.getWithFallback([r,n],{signal:AbortSignal.timeout(5e3)});return"fastestFee"in s?s.fastestFee===1?{fastestFee:2,halfHourFee:2,hourFee:2,economyFee:2,minimumFee:2}:s:{fastestFee:s[1],halfHourFee:s[5],hourFee:s[10],economyFee:s[20],minimumFee:s[25]}}async getTransactions(e,r){const n=await b.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/address/${e}/txs`));if(r===ec.ALL)return n;if(r===ec.IN)return n.filter(s=>s.vout.find(i=>i.scriptpubkey_address===e));if(r===ec.OUT)return n.filter(s=>s.vin.find(i=>i.prevout.scriptpubkey_address===e));throw new Error("failed to get transactions: invalid bitcoin tx type")}getNetwork(){return this.network}async getLatestTip(){return b.Fetcher.getWithFallback(this.APIs.map(e=>`${e}/blocks/tip/height`))}async suggestFee(e,r,n){const i=(await this.getUTXOs(e,r)).length,o=2,a=await this.getFeeRates();return Math.floor(a[C_[n]]*1.05)*(i*70+o*31+10)}async getTransactionTimes(e){const r=e.map(s=>`txId[]=${s}`).join("&");return(await b.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/v1/transaction-times?${r}`))).map(s=>s*1e3)}}const Gm=(t,e)=>{if(Array.isArray(t)){if(e){const r=t.reduce((i,o)=>i+o.value,0);if(r<e)throw new Error(ys.INSUFFICIENT_FUNDS(r,e));let n=BigInt(0);t.sort((i,o)=>o.value-i.value);const s=[];for(const i of t)if(n+=BigInt(i.value),s.push(i),n>=e)break;return qm(s)}return qm(t)}return[]};class r8 extends b.EventBroker{emit(e,...r){super.emit(e,...r)}}class Hh extends ee.Orderbook{constructor(e){const{api:r,network:n}=Xf(e.environment);super(new b.Url(r.baseurl)),this._redeemServiceEnabled=!0,this.executeInterval=5e3,this.network=n,this._api=r,this._digestKey=VB(e.digestKey),this._auth=Vm(e.apiKey),this._quote=e.quote??new Uw(this._api.baseurl),this._htlcs=e.htlc??{},this._events=new r8,this._executor=this._digestKey?new GB(this._digestKey,this.htlcs,this,this._auth,this._api,this._events):void 0}setRedeemServiceEnabled(e){var r,n;if(this._redeemServiceEnabled=e,e)(r=this._executor)==null||r.stop();else{if(!this._digestKey)throw new Error("Digest key is required for manual secret management");if(this._secretManager=Ri.fromDigestKey(this._digestKey.digestKey),!this._htlcs.bitcoin){const s=new Bv(this.network);this._htlcs.bitcoin=new vy(xs.fromPrivateKey(this._digestKey.digestKey,s),this.network)}(n=this._executor)==null||n.start(this.executeInterval,this._redeemServiceEnabled)}return this}static fromWallets(e){const r=Vm(e.apiKey),{api:n,network:s}=Xf(e.environment);if(!n)throw new Error("API not found, invalid environment "+e.environment);const i=e.wallets?{evm:e.wallets.evm?new zw(n.baseurl,e.wallets.evm,r):void 0,starknet:e.wallets.starknet?new Kw(n.baseurl,e.wallets.starknet,s,r):void 0,solana:e.wallets.solana?new u1(e.wallets.solana,new b.Url(n.baseurl),s,r,{programAddress:e.solanaProgramAddress}):void 0,sui:e.wallets.sui?new zB(n.baseurl,e.wallets.sui,s):void 0,bitcoin:e.wallets.bitcoin?new vy(e.wallets.bitcoin,s):void 0}:{};return new Hh({htlc:i,...e})}get htlcs(){return{evm:this._htlcs.evm,starknet:this._htlcs.starknet,solana:this._htlcs.solana,sui:this._htlcs.sui,bitcoin:this._htlcs.bitcoin}}get quote(){return this._quote}get secretManager(){if(this._redeemServiceEnabled||!this._secretManager)throw new Error("Secret manager is not available");return this._secretManager}get auth(){return this._auth}get digestKey(){return this._digestKey}get executor(){return this._executor}get redeemServiceEnabled(){return this._redeemServiceEnabled}async createSwap(e){const r=ee.ChainAsset.from(e.fromAsset).blockchainType,n=await z_(r,this._htlcs);if(!n.ok)return b.Err(n.error);const s=await this.createOrder(e);if(!s.ok)return b.Err(s.error);const i=s.val;switch(r){case ee.BlockchainType.evm:if(!this._htlcs.evm||!ee.isEvmOrderResponse(i))return b.Err("Order type does not match EVM blockchain type");{const o=await this._htlcs.evm.initiate(i);if(!o.ok)return b.Err(`EVM HTLC initiation failed: ${o.error}`)}break;case ee.BlockchainType.solana:if(!this._htlcs.solana||!ee.isSolanaOrderResponse(i))return b.Err("Order type does not match Solana blockchain type");{const o=await this._htlcs.solana.initiate(i);if(!o.ok)return b.Err(`Solana HTLC initiation failed: ${o.error}`)}break;case ee.BlockchainType.starknet:if(!this._htlcs.starknet||!ee.isStarknetOrderResponse(i))return b.Err("Order type does not match Starknet blockchain type");{const o=await this._htlcs.starknet.initiate(i);if(!o.ok)return b.Err(`Starknet HTLC initiation failed: ${o.error}`)}break;case ee.BlockchainType.sui:if(!this._htlcs.sui||!ee.isSuiOrderResponse(i))return b.Err("Order type does not match Sui blockchain type");{const o=await this._htlcs.sui.initiate(i);if(!o.ok)return b.Err(`Sui HTLC initiation failed: ${o.error}`)}break;default:return b.Err("Unsupported blockchain type for swap initiation")}return b.Ok(i.order_id)}async createOrder(e){var S;if(b.hasKeys(e,["source","destination","nonce"]))return super.createOrder(e,this._auth);const r=e,n=await this.validateAndFillParams(r);if(!n.ok)return b.Err(n.error);const{sendAddress:s,receiveAddress:i,fromAsset:o,toAsset:a}=n.val,c=Date.now().toString();let u;if(!this.redeemServiceEnabled){const _=await this.secretManager.generateSecret(c);if(!_.ok)return b.Err(_.error);u=_.val.secretHash}const l=(S=r.addresses)==null?void 0:S.bitcoin,d=ee.isBitcoin(ee.ChainAsset.from(r.fromAsset).chain),h=ee.isBitcoin(ee.ChainAsset.from(r.toAsset).chain),f=!d&&!h||!!u,m={source:{asset:o.toString(),owner:d?l??s:s,delegate:f&&d?s:null,amount:r.sendAmount},destination:{asset:a.toString(),owner:h?l??i:i,delegate:f&&h?i:null,amount:r.receiveAmount},nonce:Number(c),...!this.redeemServiceEnabled&&u?{secret_hash:b.trim0x(u)}:{},affiliate_fees:D_(r.affiliateFee),slippage:50},g=await super.createOrder(m,this._auth);if(!g.ok)return b.Err(g.error);const v=ee.ChainAsset.from(r.fromAsset).blockchainType;return g.val.type!==v?b.Err("Order response type does not match source blockchain type"):b.Ok(g.val)}async validateAndFillParams(e){var c;if(!e.fromAsset||!e.toAsset)return b.Err("Source and destination assets are required for swap");const r=ee.ChainAsset.from(e.fromAsset),n=ee.ChainAsset.from(e.toAsset);if(r.network!==n.network)return b.Err("Both assets should be on the same network (either mainnet or testnet)");const s=Wp(e.sendAmount);if(!s.ok)return b.Err(s.error);const i=Wp(e.receiveAmount);if(!i.ok)return b.Err(i.error);if(s<i)return b.Err("Send amount should be greater than receive amount");if((ee.isBitcoin(ee.ChainAsset.from(e.fromAsset).chain)||ee.isBitcoin(ee.ChainAsset.from(e.toAsset).chain))&&!((c=e.addresses)!=null&&c.bitcoin))return b.Err("Bitcoin address in addresses is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const o=await Kp(r.blockchainType,this._htlcs);if(!o.ok)return b.Err(o.error);const a=await Kp(n.blockchainType,this._htlcs);return a.ok?b.Ok({sendAddress:o.val,receiveAddress:a.val,fromAsset:r,toAsset:n}):b.Err(a.error)}on(e,r){return this._events.on(e,r),this}off(e,r){return this._events.off(e,r),this}}class n8{constructor(e,r,n){this.callData=new Ye.CallData(Vw),this.account=e,this.starknetProvider=new Ye.RpcProvider({nodeUrl:r||(n?Go[n].nodeUrl:Go.mainnet.nodeUrl)})}get htlcActorAddress(){return this.account.address}async getHTLCContract(e,r=!1){const n=r?e.destination_swap.asset:e.source_swap.asset;return new Ye.Contract(Ww,n,this.account)}async initiate(e){try{const n=await(await this.getHTLCContract(e)).token();if(!n)throw new Error("Token address retrieval failed");const s=Ye.num.toHex(n),i=Ye.cairo.uint256(BigInt(e.source_swap.amount));try{const c=await qw(this.account,s,e.source_swap.asset,BigInt(e.source_swap.amount),this.starknetProvider);if(c.error)return b.Err(c.error)}catch(c){return b.Err(`Allowance check failed: ${c}`)}const o=e.source_swap.secret_hash;if(!o)return b.Err("Invalid order: secret_hash is undefined");const a=await this.account.execute({contractAddress:e.source_swap.asset,entrypoint:"initiate",calldata:[e.source_swap.redeemer,BigInt(e.source_swap.timelock),i.low,i.high,...b.hexToU32Array(o)]});if(!a.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return b.Ok(a.transaction_hash)}catch(r){return b.Err(`HTLC Initiation Error: ${r}`)}}async redeem(e,r){try{const n=await this.getHTLCContract(e,!0),s=e.source_swap.chain.includes("starknet")?e.source_swap.swap_id:e.destination_swap.swap_id,i=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:Ye.CallData.compile({swap_id:s,secret:b.hexToU32Array(r)})});return i.transaction_hash?b.Ok(i.transaction_hash):b.Err("Failed to redeem HTLC transaction")}catch{return b.Err("HTLC Redeem Error")}}async refund(e){try{const r=e.source_swap.chain.includes("starknet")?e.source_swap.swap_id:e.destination_swap.swap_id,n=await this.getHTLCContract(e),s=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return s.transaction_hash?b.Ok(s.transaction_hash):b.Err("Failed to refund HTLC transaction")}catch{return b.Err("HTLC Refund Error")}}}class s8{constructor(e){if(this.provider=e,!e)throw new Error("Provider is required");this.provider=e,this.program=new zt.Program(nd,e)}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async initiate(e){if(!e)return b.Err("Order is required");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=Jn.from(e),o=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=zt.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?b.Ok(c):b.Err("Failed to initiate HTLC transaction")}catch(r){return b.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(e,r){if(!e)return b.Err("Order is required");if(!r)return b.Err("Secret is required");const{secretHash:n}=Jn.from(e),s=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=zt.web3.PublicKey.findProgramAddressSync(s,this.program.programId)[0];try{const{redeemer:i}=Jn.from(e);if(!this.swapAccount)return b.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const o=await this.program.methods.redeem(c1(r)).accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey,redeemer:i}).transaction(),a=await this.provider.sendAndConfirm(o);return a?b.Ok(a):b.Err("Failed to redeem HTLC transaction")}catch(i){return b.Err(`Error redeeming swap: ${i instanceof Error?i.message:String(i)}`)}}async refund(e){if(!e)return b.Err("Order is required");const{secretHash:r}=Jn.from(e),n=[Buffer.from("swap_account"),Buffer.from(r)];this.swapAccount=zt.web3.PublicKey.findProgramAddressSync(n,this.program.programId)[0];try{if(console.log("Initiating refund for ::",e.source_swap.swap_id),!this.swapAccount)return b.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?b.Ok(i):b.Err("Failed to refund HTLC transaction")}catch(s){return b.Err(`Error refunding swap: ${s instanceof Error?s.message:String(s)}`)}}}class i8{constructor(e,r){this.apiBaseUrl=e,this.apiKey=r,this.policy=null}async loadPolicy(){try{const r=await(await fetch(`${this.apiBaseUrl}/policy`,{headers:{"garden-app-id":this.apiKey,accept:"application/json"}})).json();if(r.status==="Ok")this.policy=r.result;else throw new Error(`API Error: ${r.error}`)}catch(e){throw new Error(`Failed to load policy: ${e}`)}}isValidRoute(e,r){if(!this.policy)throw new Error("Policy not loaded. Call loadPolicy() first.");return e===r?!1:this.isInIsolationGroup(e,r)?this.isValidIsolationGroup(e,r):this.isWhitelistOverride(e,r)?!0:this.isBlacklisted(e,r)?!1:this.policy.default==="open"}getValidDestinations(e,r){return r.filter(n=>this.isValidRoute(e,n))}getAllValidRoutes(e){const r=[];for(const n of e)for(const s of e)this.isValidRoute(n,s)&&r.push({from:n,to:s});return r}isInIsolationGroup(e,r){return this.policy.isolation_groups.some(n=>{const s=this.parseIsolationGroup(n);return s.includes(e)||s.includes(r)})}isValidIsolationGroup(e,r){return this.policy.isolation_groups.some(n=>{const s=this.parseIsolationGroup(n);return s.includes(e)&&s.includes(r)})}isWhitelistOverride(e,r){return this.policy.whitelist_overrides.some(n=>this.matchesPattern(e,r,n))}isBlacklisted(e,r){return this.policy.blacklist_pairs.some(n=>this.matchesPattern(e,r,n))}parseIsolationGroup(e){return e.split("<->").map(n=>ee.ChainAsset.from(n))}matchesPattern(e,r,n){const[s,i]=n.split("->").map(o=>o.trim());return this.matchesAssetPattern(e,s)&&this.matchesAssetPattern(r,i)}matchesAssetPattern(e,r){if(r==="*")return!0;if(r.includes("*")){if(r.endsWith(":*")){const n=r.slice(0,-2);return e.toString().startsWith(n+":")}if(r.startsWith("*:")){const n=r.slice(2);return e.toString().endsWith(":"+n)}}return e.toString()===r}}function o8(t,e){const r={};for(const n of t)r[n.toString()]=e.getValidDestinations(n,t);return r}exports.API=Qa;exports.BaseError=D;exports.BitcoinNetwork=xr;exports.BitcoinProvider=Bv;exports.BitcoinWallet=xs;exports.DEFAULT_AFFILIATE_ASSET=sw;exports.EvmRelay=zw;exports.Garden=Hh;exports.HttpRequestError=gi;exports.Quote=Uw;exports.RouteValidator=i8;exports.STARKNET_CONFIG=Go;exports.SUI_CONFIG=Zf;exports.SecretManager=Ri;exports.SolanaHTLC=s8;exports.SolanaRelay=u1;exports.SolanaRelayerAddress=nw;exports.StarknetHTLC=n8;exports.StarknetRelay=Kw;exports.botanixMainnet=jw;exports.buildRouteMatrix=o8;exports.call=da;exports.checkAllowance=bo;exports.checkAllowanceAndApprove=qw;exports.concat=Wt;exports.constructOrderPair=iw;exports.decodeErrorResult=z0;exports.encodeAbiParameters=Pn;exports.evmToViemChainMap=iu;exports.getChainNameFromChainId=Dw;exports.getUrl=Rc;exports.hyperliquid=Hw;exports.hyperliquidTestnet=Lw;exports.isAddressEqual=fa;exports.isAllowanceSufficient=Gw;exports.isHex=_r;exports.localBatchGatewayRequest=zg;exports.localBatchGatewayUrl=pa;exports.resolveApiConfig=Xf;exports.solanaProgramAddress=Kf;exports.stringify=Je;exports.switchOrAddNetwork=rd;exports.toXOnly=Me;exports.validateBTCAddress=F_;