@gardenfi/core 2.1.12 → 2.1.13-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.
@@ -0,0 +1,81 @@
1
+ "use strict";var W0=Object.defineProperty;var K0=(e,t,r)=>t in e?W0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var tn=(e,t,r)=>K0(e,typeof t!="symbol"?t+"":t,r);const U=require("@catalogfi/utils"),me=require("@gardenfi/orderbook"),J=require("@gardenfi/utils"),Hr=require("@catalogfi/wallets"),vd=require("varuint-bitcoin"),Y0=require("tiny-secp256k1"),_d=require("bitcoinjs-lib"),X0=require("bignumber.js"),Le=require("starknet"),It=require("@coral-xyz/anchor");function Vc(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const qu=Vc(vd),Gr=Vc(Y0),ge=Vc(_d);var Te=(e=>(e.Idle="Idle",e.Initiate="Initiate",e.Redeem="Redeem",e.Refund="Refund",e))(Te||{});const J0="1.0.8";let xt=class uc extends Error{constructor(t,r={}){var s;const n=r.cause instanceof uc?r.cause.details:(s=r.cause)!=null&&s.message?r.cause.message:r.details,i=r.cause instanceof uc&&r.cause.docsPath||r.docsPath,o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${J0}`].join(`
2
+ `);super(o),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.shortMessage=t}};function dr(e,t){const r=e.exec(t);return r==null?void 0:r.groups}const Ed=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,xd=/^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)?$/,Ad=/^\(.+?\).*?$/,Gu=/^tuple(?<array>(\[(\d*)\])*)$/;function fc(e){let t=e.type;if(Gu.test(e.type)&&"components"in e){t="(";const r=e.components.length;for(let i=0;i<r;i++){const o=e.components[i];t+=fc(o),i<r-1&&(t+=", ")}const n=dr(Gu,e.type);return t+=`)${(n==null?void 0:n.array)??""}`,fc({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}function Gn(e){let t="";const r=e.length;for(let n=0;n<r;n++){const i=e[n];t+=fc(i),n!==r-1&&(t+=", ")}return t}function Q0(e){var t;return e.type==="function"?`function ${e.name}(${Gn(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${(t=e.outputs)!=null&&t.length?` returns (${Gn(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${Gn(e.inputs)})`:e.type==="error"?`error ${e.name}(${Gn(e.inputs)})`:e.type==="constructor"?`constructor(${Gn(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const Sd=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function Z0(e){return Sd.test(e)}function ey(e){return dr(Sd,e)}const Pd=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function ty(e){return Pd.test(e)}function ry(e){return dr(Pd,e)}const Td=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function ny(e){return Td.test(e)}function iy(e){return dr(Td,e)}const Id=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function Bd(e){return Id.test(e)}function oy(e){return dr(Id,e)}const kd=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function sy(e){return kd.test(e)}function ay(e){return dr(kd,e)}const Od=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function cy(e){return Od.test(e)}function uy(e){return dr(Od,e)}const fy=/^receive\(\) external payable$/;function ly(e){return fy.test(e)}const dy=new Set(["indexed"]),lc=new Set(["calldata","memory","storage"]);class hy extends xt{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}}class py extends xt{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}class yy extends xt{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}}class my extends xt{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}}class by extends xt{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}}class gy extends xt{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}}class wy extends xt{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}class Un extends xt{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}}class vy extends xt{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}}class _y extends xt{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}class Ey extends xt{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}class xy extends xt{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}function Ay(e,t,r){let n="";if(r)for(const i of Object.entries(r)){if(!i)continue;let o="";for(const s of i[1])o+=`[${s.type}${s.name?`:${s.name}`:""}]`;n+=`(${i[0]}{${o}})`}return t?`${t}:${e}${n}`:e}const Ss=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 Sy(e,t={}){if(ny(e))return Py(e,t);if(ty(e))return Ty(e,t);if(Z0(e))return Iy(e,t);if(sy(e))return By(e,t);if(cy(e))return ky(e);if(ly(e))return{type:"receive",stateMutability:"payable"};throw new vy({signature:e})}function Py(e,t={}){const r=iy(e);if(!r)throw new Un({signature:e,type:"function"});const n=Tt(r.parameters),i=[],o=n.length;for(let a=0;a<o;a++)i.push(zr(n[a],{modifiers:lc,structs:t,type:"function"}));const s=[];if(r.returns){const a=Tt(r.returns),c=a.length;for(let u=0;u<c;u++)s.push(zr(a[u],{modifiers:lc,structs:t,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:i,outputs:s}}function Ty(e,t={}){const r=ry(e);if(!r)throw new Un({signature:e,type:"event"});const n=Tt(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(zr(n[s],{modifiers:dy,structs:t,type:"event"}));return{name:r.name,type:"event",inputs:i}}function Iy(e,t={}){const r=ey(e);if(!r)throw new Un({signature:e,type:"error"});const n=Tt(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(zr(n[s],{structs:t,type:"error"}));return{name:r.name,type:"error",inputs:i}}function By(e,t={}){const r=ay(e);if(!r)throw new Un({signature:e,type:"constructor"});const n=Tt(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(zr(n[s],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:i}}function ky(e){const t=uy(e);if(!t)throw new Un({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}const Oy=/^(?<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$_]*))?$/,Ry=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,Cy=/^u?int$/;function zr(e,t){var h,y;const r=Ay(e,t==null?void 0:t.type,t==null?void 0:t.structs);if(Ss.has(r))return Ss.get(r);const n=Ad.test(e),i=dr(n?Ry:Oy,e);if(!i)throw new yy({param:e});if(i.name&&Uy(i.name))throw new my({param:e,name:i.name});const o=i.name?{name:i.name}:{},s=i.modifier==="indexed"?{indexed:!0}:{},a=(t==null?void 0:t.structs)??{};let c,u={};if(n){c="tuple";const p=Tt(i.type),b=[],v=p.length;for(let E=0;E<v;E++)b.push(zr(p[E],{structs:a}));u={components:b}}else if(i.type in a)c="tuple",u={components:a[i.type]};else if(Cy.test(i.type))c=`${i.type}256`;else if(c=i.type,(t==null?void 0:t.type)!=="struct"&&!Rd(c))throw new py({type:c});if(i.modifier){if(!((y=(h=t==null?void 0:t.modifiers)==null?void 0:h.has)!=null&&y.call(h,i.modifier)))throw new by({param:e,type:t==null?void 0:t.type,modifier:i.modifier});if(lc.has(i.modifier)&&!Ny(c,!!i.array))throw new gy({param:e,type:t==null?void 0:t.type,modifier:i.modifier})}const l={type:`${c}${i.array??""}`,...o,...s,...u};return Ss.set(r,l),l}function Tt(e,t=[],r="",n=0){const i=e.trim().length;for(let o=0;o<i;o++){const s=e[o],a=e.slice(o+1);switch(s){case",":return n===0?Tt(a,[...t,r.trim()]):Tt(a,t,`${r}${s}`,n);case"(":return Tt(a,t,`${r}${s}`,n+1);case")":return Tt(a,t,`${r}${s}`,n-1);default:return Tt(a,t,`${r}${s}`,n)}}if(r==="")return t;if(n!==0)throw new xy({current:r,depth:n});return t.push(r.trim()),t}function Rd(e){return e==="address"||e==="bool"||e==="function"||e==="string"||Ed.test(e)||xd.test(e)}const Fy=/^(?: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 Uy(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||Ed.test(e)||xd.test(e)||Fy.test(e)}function Ny(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}function $y(e){const t={},r=e.length;for(let s=0;s<r;s++){const a=e[s];if(!Bd(a))continue;const c=oy(a);if(!c)throw new Un({signature:a,type:"struct"});const u=c.properties.split(";"),l=[],h=u.length;for(let y=0;y<h;y++){const b=u[y].trim();if(!b)continue;const v=zr(b,{type:"struct"});l.push(v)}if(!l.length)throw new _y({signature:a});t[c.name]=l}const n={},i=Object.entries(t),o=i.length;for(let s=0;s<o;s++){const[a,c]=i[s];n[a]=Cd(c,t)}return n}const Ly=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function Cd(e,t,r=new Set){const n=[],i=e.length;for(let o=0;o<i;o++){const s=e[o];if(Ad.test(s.type))n.push(s);else{const c=dr(Ly,s.type);if(!(c!=null&&c.type))throw new wy({abiParameter:s});const{array:u,type:l}=c;if(l in t){if(r.has(l))throw new Ey({type:l});n.push({...s,type:`tuple${u??""}`,components:Cd(t[l]??[],t,new Set([...r,l]))})}else if(Rd(l))n.push(s);else throw new hy({type:l})}}return n}function Fd(e){const t=$y(e),r=[],n=e.length;for(let i=0;i<n;i++){const o=e[i];Bd(o)||r.push(Sy(o,t))}return r}function pe(e,t,r){const n=e[t.name];if(typeof n=="function")return n;const i=e[r];return typeof i=="function"?i:o=>t(e,o)}function Gt(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new Qy(e.type);return`${e.name}(${Mo(e.inputs,{includeName:t})})`}function Mo(e,{includeName:t=!1}={}){return e?e.map(r=>My(r,{includeName:t})).join(t?", ":","):""}function My(e,{includeName:t}){return e.type.startsWith("tuple")?`(${Mo(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}function sr(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}function Re(e){return sr(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}const Ud="2.31.6";let zn={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${Ud}`},z=class dc extends Error{constructor(t,r={}){var a;const n=(()=>{var c;return r.cause instanceof dc?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),i=r.cause instanceof dc&&r.cause.docsPath||r.docsPath,o=(a=zn.getDocsUrl)==null?void 0:a.call(zn,{...r,docsPath:i}),s=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...o?[`Docs: ${o}`]:[],...n?[`Details: ${n}`]:[],...zn.version?[`Version: ${zn.version}`]:[]].join(`
3
+ `);super(s,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=Ud}walk(t){return Nd(this,t)}};function Nd(e,t){return t!=null&&t(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?Nd(e.cause,t):t?null:e}class Hy extends z{constructor({docsPath:t}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
4
+ `),{docsPath:t,name:"AbiConstructorNotFoundError"})}}class zu extends z{constructor({docsPath:t}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
5
+ `),{docsPath:t,name:"AbiConstructorParamsNotFoundError"})}}class $d extends z{constructor({data:t,params:r,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join(`
6
+ `),{metaMessages:[`Params: (${Mo(r,{includeName:!0})})`,`Data: ${t} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t,this.params=r,this.size=n}}class Wc extends z{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError"})}}class Dy extends z{constructor({expectedLength:t,givenLength:r,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${t}`,`Given length: ${r}`].join(`
7
+ `),{name:"AbiEncodingArrayLengthMismatchError"})}}class jy extends z{constructor({expectedSize:t,value:r}){super(`Size of bytes "${r}" (bytes${Re(r)}) does not match expected size (bytes${t}).`,{name:"AbiEncodingBytesSizeMismatchError"})}}class qy extends z{constructor({expectedLength:t,givenLength:r}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${t}`,`Given length (values): ${r}`].join(`
8
+ `),{name:"AbiEncodingLengthMismatchError"})}}class Gy extends z{constructor(t,{docsPath:r}){super([`Arguments (\`args\`) were provided to "${t}", but "${t}" on the ABI does not contain any parameters (\`inputs\`).`,"Cannot encode error result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the inputs exist on it."].join(`
9
+ `),{docsPath:r,name:"AbiErrorInputsNotFoundError"})}}class zy extends z{constructor(t,{docsPath:r}={}){super([`Error ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it."].join(`
10
+ `),{docsPath:r,name:"AbiErrorNotFoundError"})}}class Ld extends z{constructor(t,{docsPath:r}){super([`Encoded error signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${t}.`].join(`
11
+ `),{docsPath:r,name:"AbiErrorSignatureNotFoundError"}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=t}}class Vy extends z{constructor({docsPath:t}){super("Cannot extract event signature from empty topics.",{docsPath:t,name:"AbiEventSignatureEmptyTopicsError"})}}class Md extends z{constructor(t,{docsPath:r}){super([`Encoded event signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${t}.`].join(`
12
+ `),{docsPath:r,name:"AbiEventSignatureNotFoundError"})}}class Vu extends z{constructor(t,{docsPath:r}={}){super([`Event ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it."].join(`
13
+ `),{docsPath:r,name:"AbiEventNotFoundError"})}}class fi extends z{constructor(t,{docsPath:r}={}){super([`Function ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join(`
14
+ `),{docsPath:r,name:"AbiFunctionNotFoundError"})}}class Hd extends z{constructor(t,{docsPath:r}){super([`Function "${t}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join(`
15
+ `),{docsPath:r,name:"AbiFunctionOutputsNotFoundError"})}}class Wy extends z{constructor(t,{docsPath:r}){super([`Encoded function signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${t}.`].join(`
16
+ `),{docsPath:r,name:"AbiFunctionSignatureNotFoundError"})}}class Ky extends z{constructor(t,r){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${t.type}\` in \`${Gt(t.abiItem)}\`, and`,`\`${r.type}\` in \`${Gt(r.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}}class Yy extends z{constructor({expectedSize:t,givenSize:r}){super(`Expected bytes${t}, got bytes${r}.`,{name:"BytesSizeMismatchError"})}}class ko extends z{constructor({abiItem:t,data:r,params:n,size:i}){super([`Data size of ${i} bytes is too small for non-indexed event parameters.`].join(`
17
+ `),{metaMessages:[`Params: (${Mo(n,{includeName:!0})})`,`Data: ${r} (${i} bytes)`],name:"DecodeLogDataMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=t,this.data=r,this.params=n,this.size=i}}class Kc extends z{constructor({abiItem:t,param:r}){super([`Expected a topic for indexed event parameter${r.name?` "${r.name}"`:""} on event "${Gt(t,{includeName:!0})}".`].join(`
18
+ `),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=t}}class Xy extends z{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid encoding type.`,"Please provide a valid ABI type."].join(`
19
+ `),{docsPath:r,name:"InvalidAbiEncodingType"})}}class Jy extends z{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(`
20
+ `),{docsPath:r,name:"InvalidAbiDecodingType"})}}class Dd extends z{constructor(t){super([`Value "${t}" is not a valid array.`].join(`
21
+ `),{name:"InvalidArrayError"})}}class Qy extends z{constructor(t){super([`"${t}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(`
22
+ `),{name:"InvalidDefinitionTypeError"})}}class Zy extends z{constructor(t){super(`Filter type "${t}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}class jd extends z{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}}let qd=class extends z{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}};class Wu extends z{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${t} ${n} long.`,{name:"InvalidBytesLengthError"})}}function Nn(e,{dir:t,size:r=32}={}){return typeof e=="string"?Ar(e,{dir:t,size:r}):em(e,{dir:t,size:r})}function Ar(e,{dir:t,size:r=32}={}){if(r===null)return e;const n=e.replace("0x","");if(n.length>r*2)throw new qd({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function em(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new qd({size:e.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let i=0;i<r;i++){const o=t==="right";n[o?i:r-i-1]=e[o?i:e.length-i-1]}return n}let Gd=class extends z{constructor({max:t,min:r,signed:n,size:i,value:o}){super(`Number "${o}" is not in safe ${i?`${i*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}};class tm extends z{constructor(t){super(`Bytes value "${t}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}}class rm extends z{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}}function Ir(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let i=0;i<r.length-1&&r[t==="left"?i:r.length-i-1].toString()==="0";i++)n++;return r=t==="left"?r.slice(n):r.slice(0,r.length-n),typeof e=="string"?(r.length===1&&t==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}function Vt(e,{size:t}){if(Re(e)>t)throw new rm({givenSize:Re(e),maxSize:t})}function yt(e,t={}){const{signed:r}=t;t.size&&Vt(e,{size:t.size});const n=BigInt(e);if(!r)return n;const i=(e.length-2)/2,o=(1n<<BigInt(i)*8n-1n)-1n;return n<=o?n:n-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function zt(e,t={}){return Number(yt(e,t))}const nm=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function qt(e,t={}){return typeof e=="number"||typeof e=="bigint"?Q(e,t):typeof e=="string"?Ho(e,t):typeof e=="boolean"?zd(e,t):at(e,t)}function zd(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?(Vt(r,{size:t.size}),Nn(r,{size:t.size})):r}function at(e,t={}){let r="";for(let i=0;i<e.length;i++)r+=nm[e[i]];const n=`0x${r}`;return typeof t.size=="number"?(Vt(n,{size:t.size}),Nn(n,{dir:"right",size:t.size})):n}function Q(e,t={}){const{signed:r,size:n}=t,i=BigInt(e);let o;n?r?o=(1n<<BigInt(n)*8n-1n)-1n:o=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(o=BigInt(Number.MAX_SAFE_INTEGER));const s=typeof o=="bigint"&&r?-o-1n:0;if(o&&i>o||i<s){const c=typeof e=="bigint"?"n":"";throw new Gd({max:o?`${o}${c}`:void 0,min:`${s}${c}`,signed:r,size:n,value:`${e}${c}`})}const a=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?Nn(a,{size:n}):a}const im=new TextEncoder;function Ho(e,t={}){const r=im.encode(e);return at(r,t)}const om=new TextEncoder;function Di(e,t={}){return typeof e=="number"||typeof e=="bigint"?am(e,t):typeof e=="boolean"?sm(e,t):sr(e)?ar(e,t):Vd(e,t)}function sm(e,t={}){const r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?(Vt(r,{size:t.size}),Nn(r,{size:t.size})):r}const Kt={zero:48,nine:57,A:65,F:70,a:97,f:102};function Ku(e){if(e>=Kt.zero&&e<=Kt.nine)return e-Kt.zero;if(e>=Kt.A&&e<=Kt.F)return e-(Kt.A-10);if(e>=Kt.a&&e<=Kt.f)return e-(Kt.a-10)}function ar(e,t={}){let r=e;t.size&&(Vt(r,{size:t.size}),r=Nn(r,{dir:"right",size:t.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const i=n.length/2,o=new Uint8Array(i);for(let s=0,a=0;s<i;s++){const c=Ku(n.charCodeAt(a++)),u=Ku(n.charCodeAt(a++));if(c===void 0||u===void 0)throw new z(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);o[s]=c*16+u}return o}function am(e,t){const r=Q(e,t);return ar(r)}function Vd(e,t={}){const r=om.encode(e);return typeof t.size=="number"?(Vt(r,{size:t.size}),Nn(r,{dir:"right",size:t.size})):r}const no=BigInt(2**32-1),Yu=BigInt(32);function cm(e,t=!1){return t?{h:Number(e&no),l:Number(e>>Yu&no)}:{h:Number(e>>Yu&no)|0,l:Number(e&no)|0}}function um(e,t=!1){const r=e.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let o=0;o<r;o++){const{h:s,l:a}=cm(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}const fm=(e,t,r)=>e<<r|t>>>32-r,lm=(e,t,r)=>t<<r|e>>>32-r,dm=(e,t,r)=>t<<r-32|e>>>64-r,hm=(e,t,r)=>e<<r-32|t>>>64-r,rn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Wd(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function li(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Br(e,...t){if(!Wd(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function pm(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");li(e.outputLen),li(e.blockLen)}function di(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Kd(e,t){Br(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function ym(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function kr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ps(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Rt(e,t){return e<<32-t|e>>>t}function io(e,t){return e<<t|e>>>32-t>>>0}const mm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function bm(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function gm(e){for(let t=0;t<e.length;t++)e[t]=bm(e[t]);return e}const Xu=mm?e=>e:gm,Yd=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",wm=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function vm(e){if(Br(e),Yd)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=wm[e[r]];return t}const Yt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ju(e){if(e>=Yt._0&&e<=Yt._9)return e-Yt._0;if(e>=Yt.A&&e<=Yt.F)return e-(Yt.A-10);if(e>=Yt.a&&e<=Yt.f)return e-(Yt.a-10)}function _m(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(Yd)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){const s=Ju(e.charCodeAt(o)),a=Ju(e.charCodeAt(o+1));if(s===void 0||a===void 0){const c=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[i]=s*16+a}return n}function Em(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Do(e){return typeof e=="string"&&(e=Em(e)),Br(e),e}function xm(...e){let t=0;for(let n=0;n<e.length;n++){const i=e[n];Br(i),t+=i.length}const r=new Uint8Array(t);for(let n=0,i=0;n<e.length;n++){const o=e[n];r.set(o,i),i+=o.length}return r}let Yc=class{};function jo(e){const t=n=>e().update(Do(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Am(e=32){if(rn&&typeof rn.getRandomValues=="function")return rn.getRandomValues(new Uint8Array(e));if(rn&&typeof rn.randomBytes=="function")return Uint8Array.from(rn.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const Sm=BigInt(0),Vn=BigInt(1),Pm=BigInt(2),Tm=BigInt(7),Im=BigInt(256),Bm=BigInt(113),Xd=[],Jd=[],Qd=[];for(let e=0,t=Vn,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Xd.push(2*(5*n+r)),Jd.push((e+1)*(e+2)/2%64);let i=Sm;for(let o=0;o<7;o++)t=(t<<Vn^(t>>Tm)*Bm)%Im,t&Pm&&(i^=Vn<<(Vn<<BigInt(o))-Vn);Qd.push(i)}const Zd=um(Qd,!0),km=Zd[0],Om=Zd[1],Qu=(e,t,r)=>r>32?dm(e,t,r):fm(e,t,r),Zu=(e,t,r)=>r>32?hm(e,t,r):lm(e,t,r);function Rm(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let s=0;s<10;s++)r[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){const a=(s+8)%10,c=(s+2)%10,u=r[c],l=r[c+1],h=Qu(u,l,1)^r[a],y=Zu(u,l,1)^r[a+1];for(let p=0;p<50;p+=10)e[s+p]^=h,e[s+p+1]^=y}let i=e[2],o=e[3];for(let s=0;s<24;s++){const a=Jd[s],c=Qu(i,o,a),u=Zu(i,o,a),l=Xd[s];i=e[l],o=e[l+1],e[l]=c,e[l+1]=u}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)r[a]=e[s+a];for(let a=0;a<10;a++)e[s+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=km[n],e[1]^=Om[n]}kr(r)}class Xc extends Yc{constructor(t,r,n,i=!1,o=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=o,li(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ym(this.state)}clone(){return this._cloneInto()}keccak(){Xu(this.state32),Rm(this.state32,this.rounds),Xu(this.state32),this.posOut=0,this.pos=0}update(t){di(this),t=Do(t),Br(t);const{blockLen:r,state:n}=this,i=t.length;for(let o=0;o<i;){const s=Math.min(r-this.pos,i-o);for(let a=0;a<s;a++)n[this.pos++]^=t[o++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:r,pos:n,blockLen:i}=this;t[n]^=r,r&128&&n===i-1&&this.keccak(),t[i-1]^=128,this.keccak()}writeInto(t){di(this,!1),Br(t),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,o=t.length;i<o;){this.posOut>=n&&this.keccak();const s=Math.min(n-this.posOut,o-i);t.set(r.subarray(this.posOut,this.posOut+s),i),this.posOut+=s,i+=s}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return li(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(Kd(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,kr(this.state)}_cloneInto(t){const{blockLen:r,suffix:n,outputLen:i,rounds:o,enableXOF:s}=this;return t||(t=new Xc(r,n,i,s,o)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=o,t.suffix=n,t.outputLen=i,t.enableXOF=s,t.destroyed=this.destroyed,t}}const Cm=(e,t,r)=>jo(()=>new Xc(t,e,r)),Fm=Cm(1,136,256/8);function $n(e,t){const r=t||"hex",n=Fm(sr(e,{strict:!1})?Di(e):e);return r==="bytes"?n:qt(n)}const Um=e=>$n(Di(e));function Nm(e){return Um(e)}function $m(e){let t=!0,r="",n=0,i="",o=!1;for(let s=0;s<e.length;s++){const a=e[s];if(["(",")",","].includes(a)&&(t=!0),a==="("&&n++,a===")"&&n--,!!t){if(n===0){if(a===" "&&["event","function",""].includes(i))i="";else if(i+=a,a===")"){o=!0;break}continue}if(a===" "){e[s-1]!==","&&r!==","&&r!==",("&&(r="",t=!1);continue}i+=a,r+=a}}if(!o)throw new z("Unable to normalize signature.");return i}const Lm=e=>{const t=typeof e=="string"?e:Q0(e);return $m(t)};function eh(e){return Nm(Lm(e))}const qo=eh;class ct extends z{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}class Go extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){const r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const Ts=new Go(8192);function ji(e,t){if(Ts.has(`${e}.${t}`))return Ts.get(`${e}.${t}`);const r=e.substring(2).toLowerCase(),n=$n(Vd(r),"bytes"),i=r.split("");for(let s=0;s<40;s+=2)n[s>>1]>>4>=8&&i[s]&&(i[s]=i[s].toUpperCase()),(n[s>>1]&15)>=8&&i[s+1]&&(i[s+1]=i[s+1].toUpperCase());const o=`0x${i.join("")}`;return Ts.set(`${e}.${t}`,o),o}function Mm(e,t){if(!Me(e,{strict:!1}))throw new ct({address:e});return ji(e,t)}const Hm=/^0x[a-fA-F0-9]{40}$/,Is=new Go(8192);function Me(e,t){const{strict:r=!0}=t??{},n=`${e}.${r}`;if(Is.has(n))return Is.get(n);const i=Hm.test(e)?e.toLowerCase()===e?!0:r?ji(e)===e:!0:!1;return Is.set(n,i),i}function cr(e){return typeof e[0]=="string"?Wt(e):Dm(e)}function Dm(e){let t=0;for(const i of e)t+=i.length;const r=new Uint8Array(t);let n=0;for(const i of e)r.set(i,n),n+=i.length;return r}function Wt(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function vn(e,t,r,{strict:n}={}){return sr(e,{strict:!1})?hc(e,t,r,{strict:n}):nh(e,t,r,{strict:n})}function th(e,t){if(typeof t=="number"&&t>0&&t>Re(e)-1)throw new jd({offset:t,position:"start",size:Re(e)})}function rh(e,t,r){if(typeof t=="number"&&typeof r=="number"&&Re(e)!==r-t)throw new jd({offset:r,position:"end",size:Re(e)})}function nh(e,t,r,{strict:n}={}){th(e,t);const i=e.slice(t,r);return n&&rh(i,t,r),i}function hc(e,t,r,{strict:n}={}){th(e,t);const i=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return n&&rh(i,t,r),i}const jm=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,ih=/^(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 zo(e,t){if(e.length!==t.length)throw new qy({expectedLength:e.length,givenLength:t.length});const r=qm({params:e,values:t}),n=Qc(r);return n.length===0?"0x":n}function qm({params:e,values:t}){const r=[];for(let n=0;n<e.length;n++)r.push(Jc({param:e[n],value:t[n]}));return r}function Jc({param:e,value:t}){const r=Zc(e.type);if(r){const[n,i]=r;return zm(t,{length:n,param:{...e,type:i}})}if(e.type==="tuple")return Xm(t,{param:e});if(e.type==="address")return Gm(t);if(e.type==="bool")return Wm(t);if(e.type.startsWith("uint")||e.type.startsWith("int")){const n=e.type.startsWith("int"),[,,i="256"]=ih.exec(e.type)??[];return Km(t,{signed:n,size:Number(i)})}if(e.type.startsWith("bytes"))return Vm(t,{param:e});if(e.type==="string")return Ym(t);throw new Xy(e.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function Qc(e){let t=0;for(let o=0;o<e.length;o++){const{dynamic:s,encoded:a}=e[o];s?t+=32:t+=Re(a)}const r=[],n=[];let i=0;for(let o=0;o<e.length;o++){const{dynamic:s,encoded:a}=e[o];s?(r.push(Q(t+i,{size:32})),n.push(a),i+=Re(a)):r.push(a)}return cr([...r,...n])}function Gm(e){if(!Me(e))throw new ct({address:e});return{dynamic:!1,encoded:Ar(e.toLowerCase())}}function zm(e,{length:t,param:r}){const n=t===null;if(!Array.isArray(e))throw new Dd(e);if(!n&&e.length!==t)throw new Dy({expectedLength:t,givenLength:e.length,type:`${r.type}[${t}]`});let i=!1;const o=[];for(let s=0;s<e.length;s++){const a=Jc({param:r,value:e[s]});a.dynamic&&(i=!0),o.push(a)}if(n||i){const s=Qc(o);if(n){const a=Q(o.length,{size:32});return{dynamic:!0,encoded:o.length>0?cr([a,s]):a}}if(i)return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:cr(o.map(({encoded:s})=>s))}}function Vm(e,{param:t}){const[,r]=t.type.split("bytes"),n=Re(e);if(!r){let i=e;return n%32!==0&&(i=Ar(i,{dir:"right",size:Math.ceil((e.length-2)/2/32)*32})),{dynamic:!0,encoded:cr([Ar(Q(n,{size:32})),i])}}if(n!==Number.parseInt(r))throw new jy({expectedSize:Number.parseInt(r),value:e});return{dynamic:!1,encoded:Ar(e,{dir:"right"})}}function Wm(e){if(typeof e!="boolean")throw new z(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Ar(zd(e))}}function Km(e,{signed:t,size:r=256}){if(typeof r=="number"){const n=2n**(BigInt(r)-(t?1n:0n))-1n,i=t?-n-1n:0n;if(e>n||e<i)throw new Gd({max:n.toString(),min:i.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:Q(e,{size:32,signed:t})}}function Ym(e){const t=Ho(e),r=Math.ceil(Re(t)/32),n=[];for(let i=0;i<r;i++)n.push(Ar(vn(t,i*32,(i+1)*32),{dir:"right"}));return{dynamic:!0,encoded:cr([Ar(Q(Re(t),{size:32})),...n])}}function Xm(e,{param:t}){let r=!1;const n=[];for(let i=0;i<t.components.length;i++){const o=t.components[i],s=Array.isArray(e)?i:o.name,a=Jc({param:o,value:e[s]});n.push(a),a.dynamic&&(r=!0)}return{dynamic:r,encoded:r?Qc(n):cr(n.map(({encoded:i})=>i))}}function Zc(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}const Vo=e=>vn(eh(e),0,4);function Ln(e){const{abi:t,args:r=[],name:n}=e,i=sr(n,{strict:!1}),o=t.filter(a=>i?a.type==="function"?Vo(a)===n:a.type==="event"?qo(a)===n:!1:"name"in a&&a.name===n);if(o.length===0)return;if(o.length===1)return o[0];let s;for(const a of o){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 h="inputs"in a&&a.inputs[l];return h?pc(u,h):!1})){if(s&&"inputs"in s&&s.inputs){const u=oh(a.inputs,s.inputs,r);if(u)throw new Ky({abiItem:a,type:u[0]},{abiItem:s,type:u[1]})}s=a}}return s||o[0]}function pc(e,t){const r=typeof e,n=t.type;switch(n){case"address":return Me(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in t?Object.values(t.components).every((i,o)=>pc(Object.values(e)[o],i)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(e)&&e.every(i=>pc(i,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function oh(e,t,r){for(const n in e){const i=e[n],o=t[n];if(i.type==="tuple"&&o.type==="tuple"&&"components"in i&&"components"in o)return oh(i.components,o.components,r[n]);const s=[i.type,o.type];if(s.includes("address")&&s.includes("bytes20")?!0:s.includes("address")&&s.includes("string")?Me(r[n],{strict:!1}):s.includes("address")&&s.includes("bytes")?Me(r[n],{strict:!1}):!1)return s}}const ef="/docs/contract/encodeEventTopics";function eu(e){var c;const{abi:t,eventName:r,args:n}=e;let i=t[0];if(r){const u=Ln({abi:t,name:r});if(!u)throw new Vu(r,{docsPath:ef});i=u}if(i.type!=="event")throw new Vu(void 0,{docsPath:ef});const o=Gt(i),s=qo(o);let a=[];if(n&&"inputs"in i){const u=(c=i.inputs)==null?void 0:c.filter(h=>"indexed"in h&&h.indexed),l=Array.isArray(n)?n:Object.values(n).length>0?(u==null?void 0:u.map(h=>n[h.name]))??[]:[];l.length>0&&(a=(u==null?void 0:u.map((h,y)=>Array.isArray(l[y])?l[y].map((p,b)=>tf({param:h,value:l[y][b]})):typeof l[y]<"u"&&l[y]!==null?tf({param:h,value:l[y]}):null))??[])}return[s,...a]}function tf({param:e,value:t}){if(e.type==="string"||e.type==="bytes")return $n(Di(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new Zy(e.type);return zo([e],[t])}function Jm(e,{method:t}){var n,i;const r={};return e.transport.type==="fallback"&&((i=(n=e.transport).onResponse)==null||i.call(n,({method:o,response:s,status:a,transport:c})=>{a==="success"&&t===o&&(r[s]=c.request)})),o=>r[o]||e.request}async function sh(e,t){const{address:r,abi:n,args:i,eventName:o,fromBlock:s,strict:a,toBlock:c}=t,u=Jm(e,{method:"eth_newFilter"}),l=o?eu({abi:n,args:i,eventName:o}):void 0,h=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof s=="bigint"?Q(s):s,toBlock:typeof c=="bigint"?Q(c):c,topics:l}]});return{abi:n,args:i,eventName:o,id:h,request:u(h),strict:!!a,type:"event"}}function He(e){return typeof e=="string"?{address:e,type:"json-rpc"}:e}const rf="/docs/contract/encodeFunctionData";function Qm(e){const{abi:t,args:r,functionName:n}=e;let i=t[0];if(n){const o=Ln({abi:t,args:r,name:n});if(!o)throw new fi(n,{docsPath:rf});i=o}if(i.type!=="function")throw new fi(void 0,{docsPath:rf});return{abi:[i],functionName:Vo(Gt(i))}}function Mn(e){const{args:t}=e,{abi:r,functionName:n}=(()=>{var a;return e.abi.length===1&&((a=e.functionName)!=null&&a.startsWith("0x"))?e:Qm(e)})(),i=r[0],o=n,s="inputs"in i&&i.inputs?zo(i.inputs,t??[]):void 0;return Wt([o,s??"0x"])}const Zm={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."},ah={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},eb={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};class nf extends z{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class ch extends z{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}}class tb extends z{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}}const rb={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 tb({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new ch({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new nf({offset:e});const t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new nf({offset:e});const t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){const r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){const t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){const t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){const t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();const r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();const e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();const e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();const e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();const e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){const t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function tu(e,{recursiveReadLimit:t=8192}={}){const r=Object.create(rb);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}function nb(e,t={}){typeof t.size<"u"&&Vt(e,{size:t.size});const r=at(e,t);return yt(r,t)}function ib(e,t={}){let r=e;if(typeof t.size<"u"&&(Vt(r,{size:t.size}),r=Ir(r)),r.length>1||r[0]>1)throw new tm(r);return!!r[0]}function ir(e,t={}){typeof t.size<"u"&&Vt(e,{size:t.size});const r=at(e,t);return zt(r,t)}function ob(e,t={}){let r=e;return typeof t.size<"u"&&(Vt(r,{size:t.size}),r=Ir(r,{dir:"right"})),new TextDecoder().decode(r)}function qi(e,t){const r=typeof t=="string"?ar(t):t,n=tu(r);if(Re(r)===0&&e.length>0)throw new Wc;if(Re(t)&&Re(t)<32)throw new $d({data:typeof t=="string"?t:at(t),params:e,size:Re(t)});let i=0;const o=[];for(let s=0;s<e.length;++s){const a=e[s];n.setPosition(i);const[c,u]=hn(n,a,{staticPosition:0});i+=u,o.push(c)}return o}function hn(e,t,{staticPosition:r}){const n=Zc(t.type);if(n){const[i,o]=n;return ab(e,{...t,type:o},{length:i,staticPosition:r})}if(t.type==="tuple")return lb(e,t,{staticPosition:r});if(t.type==="address")return sb(e);if(t.type==="bool")return cb(e);if(t.type.startsWith("bytes"))return ub(e,t,{staticPosition:r});if(t.type.startsWith("uint")||t.type.startsWith("int"))return fb(e,t);if(t.type==="string")return db(e,{staticPosition:r});throw new Jy(t.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const of=32,yc=32;function sb(e){const t=e.readBytes(32);return[ji(at(nh(t,-20))),32]}function ab(e,t,{length:r,staticPosition:n}){if(!r){const s=ir(e.readBytes(yc)),a=n+s,c=a+of;e.setPosition(a);const u=ir(e.readBytes(of)),l=hi(t);let h=0;const y=[];for(let p=0;p<u;++p){e.setPosition(c+(l?p*32:h));const[b,v]=hn(e,t,{staticPosition:c});h+=v,y.push(b)}return e.setPosition(n+32),[y,32]}if(hi(t)){const s=ir(e.readBytes(yc)),a=n+s,c=[];for(let u=0;u<r;++u){e.setPosition(a+u*32);const[l]=hn(e,t,{staticPosition:a});c.push(l)}return e.setPosition(n+32),[c,32]}let i=0;const o=[];for(let s=0;s<r;++s){const[a,c]=hn(e,t,{staticPosition:n+i});i+=c,o.push(a)}return[o,i]}function cb(e){return[ib(e.readBytes(32),{size:32}),32]}function ub(e,t,{staticPosition:r}){const[n,i]=t.type.split("bytes");if(!i){const s=ir(e.readBytes(32));e.setPosition(r+s);const a=ir(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];const c=e.readBytes(a);return e.setPosition(r+32),[at(c),32]}return[at(e.readBytes(Number.parseInt(i),32)),32]}function fb(e,t){const r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256"),i=e.readBytes(32);return[n>48?nb(i,{signed:r}):ir(i,{signed:r}),32]}function lb(e,t,{staticPosition:r}){const n=t.components.length===0||t.components.some(({name:s})=>!s),i=n?[]:{};let o=0;if(hi(t)){const s=ir(e.readBytes(yc)),a=r+s;for(let c=0;c<t.components.length;++c){const u=t.components[c];e.setPosition(a+o);const[l,h]=hn(e,u,{staticPosition:a});o+=h,i[n?c:u==null?void 0:u.name]=l}return e.setPosition(r+32),[i,32]}for(let s=0;s<t.components.length;++s){const a=t.components[s],[c,u]=hn(e,a,{staticPosition:r});i[n?s:a==null?void 0:a.name]=c,o+=u}return[i,o]}function db(e,{staticPosition:t}){const r=ir(e.readBytes(32)),n=t+r;e.setPosition(n);const i=ir(e.readBytes(32));if(i===0)return e.setPosition(t+32),["",32];const o=e.readBytes(i,32),s=ob(Ir(o));return e.setPosition(t+32),[s,32]}function hi(e){var n;const{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return(n=e.components)==null?void 0:n.some(hi);const r=Zc(e.type);return!!(r&&hi({...e,type:r[1]}))}function uh(e){const{abi:t,data:r}=e,n=vn(r,0,4);if(n==="0x")throw new Wc;const o=[...t||[],ah,eb].find(s=>s.type==="error"&&n===Vo(Gt(s)));if(!o)throw new Ld(n,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:o,args:"inputs"in o&&o.inputs&&o.inputs.length>0?qi(o.inputs,vn(r,4)):void 0,errorName:o.name}}const lt=(e,t,r)=>JSON.stringify(e,(n,i)=>typeof i=="bigint"?i.toString():i,r);function fh({abiItem:e,args:t,includeFunctionName:r=!0,includeName:n=!1}){if("name"in e&&"inputs"in e&&e.inputs)return`${r?e.name:""}(${e.inputs.map((i,o)=>`${n&&i.name?`${i.name}: `:""}${typeof t[o]=="object"?lt(t[o]):t[o]}`).join(", ")})`}const hb={gwei:9,wei:18},pb={ether:-9,wei:9};function lh(e,t){let r=e.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[i,o]=[r.slice(0,r.length-t),r.slice(r.length-t)];return o=o.replace(/(0+)$/,""),`${n?"-":""}${i||"0"}${o?`.${o}`:""}`}function ru(e,t="wei"){return lh(e,hb[t])}function dt(e,t="wei"){return lh(e,pb[t])}class yb extends z{constructor({address:t}){super(`State for account "${t}" is set multiple times.`,{name:"AccountStateConflictError"})}}class mb extends z{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function sf(e){return e.reduce((t,{slot:r,value:n})=>`${t} ${r}: ${n}
23
+ `,"")}function bb(e){return e.reduce((t,{address:r,...n})=>{let i=`${t} ${r}:
24
+ `;return n.nonce&&(i+=` nonce: ${n.nonce}
25
+ `),n.balance&&(i+=` balance: ${n.balance}
26
+ `),n.code&&(i+=` code: ${n.code}
27
+ `),n.state&&(i+=` state:
28
+ `,i+=sf(n.state)),n.stateDiff&&(i+=` stateDiff:
29
+ `,i+=sf(n.stateDiff)),i},` State Override:
30
+ `).slice(0,-1)}function Gi(e){const t=Object.entries(e).map(([n,i])=>i===void 0||i===!1?null:[n,i]).filter(Boolean),r=t.reduce((n,[i])=>Math.max(n,i.length),0);return t.map(([n,i])=>` ${`${n}:`.padEnd(r+1)} ${i}`).join(`
31
+ `)}class gb extends z{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 wb extends z{constructor({v:t}){super(`Invalid \`v\` value "${t}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class vb extends z{constructor({transaction:t}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",Gi(t),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class _b extends z{constructor({storageKey:t}){super(`Size for storage key "${t}" is invalid. Expected 32 bytes. Got ${Math.floor((t.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}class Eb extends z{constructor(t,{account:r,docsPath:n,chain:i,data:o,gas:s,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:l,to:h,value:y}){var b;const p=Gi({chain:i&&`${i==null?void 0:i.name} (id: ${i==null?void 0:i.id})`,from:r==null?void 0:r.address,to:h,value:typeof y<"u"&&`${ru(y)} ${((b=i==null?void 0:i.nativeCurrency)==null?void 0:b.symbol)||"ETH"}`,data:o,gas:s,gasPrice:typeof a<"u"&&`${dt(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${dt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${dt(u)} gwei`,nonce:l});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Request Arguments:",p].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}const xb=e=>e,Wo=e=>e;class Ab extends z{constructor(t,{account:r,docsPath:n,chain:i,data:o,gas:s,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:l,to:h,value:y,stateOverride:p}){var E;const b=r?He(r):void 0;let v=Gi({from:b==null?void 0:b.address,to:h,value:typeof y<"u"&&`${ru(y)} ${((E=i==null?void 0:i.nativeCurrency)==null?void 0:E.symbol)||"ETH"}`,data:o,gas:s,gasPrice:typeof a<"u"&&`${dt(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${dt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${dt(u)} gwei`,nonce:l});p&&(v+=`
33
+ ${bb(p)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Raw Call Arguments:",v].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}class Sb extends z{constructor(t,{abi:r,args:n,contractAddress:i,docsPath:o,functionName:s,sender:a}){const c=Ln({abi:r,args:n,name:s}),u=c?fh({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,l=c?Gt(c,{includeName:!0}):void 0,h=Gi({address:i&&xb(i),function:l,args:u&&u!=="()"&&`${[...Array((s==null?void 0:s.length)??0).keys()].map(()=>" ").join("")}${u}`,sender:a});super(t.shortMessage||`An unknown error occurred while executing the contract function "${s}".`,{cause:t,docsPath:o,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],h&&"Contract Call:",h].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=r,this.args=n,this.cause=t,this.contractAddress=i,this.functionName=s,this.sender=a}}class Pb extends z{constructor({abi:t,data:r,functionName:n,message:i}){let o,s,a,c;if(r&&r!=="0x")try{s=uh({abi:t,data:r});const{abiItem:l,errorName:h,args:y}=s;if(h==="Error")c=y[0];else if(h==="Panic"){const[p]=y;c=Zm[p]}else{const p=l?Gt(l,{includeName:!0}):void 0,b=l&&y?fh({abiItem:l,args:y,includeFunctionName:!1,includeName:!1}):void 0;a=[p?`Error: ${p}`:"",b&&b!=="()"?` ${[...Array((h==null?void 0:h.length)??0).keys()].map(()=>" ").join("")}${b}`:""]}}catch(l){o=l}else i&&(c=i);let u;o instanceof Ld&&(u=o.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:o,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=s,this.raw=r,this.reason=c,this.signature=u}}class Tb extends z{constructor({functionName:t}){super(`The contract function "${t}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${t}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError"})}}class Ib extends z{constructor({factory:t}){super(`Deployment for counterfactual contract call failed${t?` for factory "${t}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}}class dh extends z{constructor({data:t,message:r}){super(r||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t}}class pn extends z{constructor({body:t,cause:r,details:n,headers:i,status:o,url:s}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[o&&`Status: ${o}`,`URL: ${Wo(s)}`,t&&`Request body: ${lt(t)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=t,this.headers=i,this.status=o,this.url=s}}class nu extends z{constructor({body:t,error:r,url:n}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[`URL: ${Wo(n)}`,`Request body: ${lt(t)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=r.code,this.data=r.data}}class af extends z{constructor({body:t,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${Wo(r)}`,`Request body: ${lt(t)}`],name:"TimeoutError"})}}const Bb=-1;class ht extends z{constructor(t,{code:r,docsPath:n,metaMessages:i,name:o,shortMessage:s}){super(s,{cause:t,docsPath:n,metaMessages:i||(t==null?void 0:t.metaMessages),name:o||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=o||t.name,this.code=t instanceof nu?t.code:r??Bb}}class bt extends ht{constructor(t,r){super(t,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}}class pi extends ht{constructor(t){super(t,{code:pi.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(pi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class yi extends ht{constructor(t){super(t,{code:yi.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(yi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class mi extends ht{constructor(t,{method:r}={}){super(t,{code:mi.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}}Object.defineProperty(mi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class bi extends ht{constructor(t){super(t,{code:bi.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
35
+ `)})}}Object.defineProperty(bi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class Vr extends ht{constructor(t){super(t,{code:Vr.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(Vr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class _n extends ht{constructor(t){super(t,{code:_n.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
36
+ `)})}}Object.defineProperty(_n,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class gi extends ht{constructor(t){super(t,{code:gi.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(gi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class wi extends ht{constructor(t){super(t,{code:wi.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(wi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class vi extends ht{constructor(t){super(t,{code:vi.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(vi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class Mr extends ht{constructor(t,{method:r}={}){super(t,{code:Mr.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}}Object.defineProperty(Mr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class En extends ht{constructor(t){super(t,{code:En.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(En,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class _i extends ht{constructor(t){super(t,{code:_i.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(_i,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class yn extends bt{constructor(t){super(t,{code:yn.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(yn,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class Ei extends bt{constructor(t){super(t,{code:Ei.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(Ei,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class xi extends bt{constructor(t,{method:r}={}){super(t,{code:xi.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}}Object.defineProperty(xi,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Ai extends bt{constructor(t){super(t,{code:Ai.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Ai,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class Si extends bt{constructor(t){super(t,{code:Si.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Si,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class Pi extends bt{constructor(t){super(t,{code:Pi.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(Pi,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class xn extends bt{constructor(t){super(t,{code:xn.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(xn,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class Ti extends bt{constructor(t){super(t,{code:Ti.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(Ti,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class Ii extends bt{constructor(t){super(t,{code:Ii.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(Ii,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class Bi extends bt{constructor(t){super(t,{code:Bi.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(Bi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class ki extends bt{constructor(t){super(t,{code:ki.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(ki,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class Oi extends bt{constructor(t){super(t,{code:Oi.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(Oi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class An extends bt{constructor(t){super(t,{code:An.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(An,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class kb extends ht{constructor(t){super(t,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const Ob=3;function Ko(e,{abi:t,address:r,args:n,docsPath:i,functionName:o,sender:s}){const a=e instanceof dh?e:e instanceof z?e.walk(b=>"data"in b)||e.walk():{},{code:c,data:u,details:l,message:h,shortMessage:y}=a,p=e instanceof Wc?new Tb({functionName:o}):[Ob,Vr.code].includes(c)&&(u||l||h||y)?new Pb({abi:t,data:typeof u=="object"?u.data:u,functionName:o,message:a instanceof nu?l:y??h}):e;return new Sb(p,{abi:t,args:n,contractAddress:r,docsPath:i,functionName:o,sender:s})}function Rb(e){const t=$n(`0x${e.substring(4)}`).substring(26);return ji(`0x${t}`)}async function Cb({hash:e,signature:t}){const r=sr(e)?e:qt(e),{secp256k1:n}=await Promise.resolve().then(()=>require("./secp256k1-CS4jLSmJ.cjs"));return`0x${(()=>{if(typeof t=="object"&&"r"in t&&"s"in t){const{r:u,s:l,v:h,yParity:y}=t,p=Number(y??h),b=cf(p);return new n.Signature(yt(u),yt(l)).addRecoveryBit(b)}const s=sr(t)?t:qt(t);if(Re(s)!==65)throw new Error("invalid signature length");const a=zt(`0x${s.slice(130)}`),c=cf(a);return n.Signature.fromCompact(s.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function cf(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw new Error("Invalid yParityOrV value")}async function Fb({hash:e,signature:t}){return Rb(await Cb({hash:e,signature:t}))}function Or(e,t="hex"){const r=hh(e),n=tu(new Uint8Array(r.length));return r.encode(n),t==="hex"?at(n.bytes):n.bytes}function hh(e){return Array.isArray(e)?Ub(e.map(t=>hh(t))):Nb(e)}function Ub(e){const t=e.reduce((i,o)=>i+o.length,0),r=ph(t);return{length:t<=55?1+t:1+r+t,encode(i){t<=55?i.pushByte(192+t):(i.pushByte(247+r),r===1?i.pushUint8(t):r===2?i.pushUint16(t):r===3?i.pushUint24(t):i.pushUint32(t));for(const{encode:o}of e)o(i)}}}function Nb(e){const t=typeof e=="string"?ar(e):e,r=ph(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(i){t.length===1&&t[0]<128?i.pushBytes(t):t.length<=55?(i.pushByte(128+t.length),i.pushBytes(t)):(i.pushByte(183+r),r===1?i.pushUint8(t.length):r===2?i.pushUint16(t.length):r===3?i.pushUint24(t.length):i.pushUint32(t.length),i.pushBytes(t))}}}function ph(e){if(e<2**8)return 1;if(e<2**16)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new z("Length is too large.")}function $b(e){const{chainId:t,nonce:r,to:n}=e,i=e.contractAddress??e.address,o=$n(Wt(["0x05",Or([t?Q(t):"0x",i,r?Q(r):"0x"])]));return n==="bytes"?ar(o):o}async function yh(e){const{authorization:t,signature:r}=e;return Fb({hash:$b(t),signature:r??t})}class Lb extends z{constructor(t,{account:r,docsPath:n,chain:i,data:o,gas:s,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:l,to:h,value:y}){var b;const p=Gi({from:r==null?void 0:r.address,to:h,value:typeof y<"u"&&`${ru(y)} ${((b=i==null?void 0:i.nativeCurrency)==null?void 0:b.symbol)||"ETH"}`,data:o,gas:s,gasPrice:typeof a<"u"&&`${dt(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${dt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${dt(u)} gwei`,nonce:l});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Estimate Gas Arguments:",p].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}class dn extends z{constructor({cause:t,message:r}={}){var i;const n=(i=r==null?void 0:r.replace("execution reverted: ",""))==null?void 0:i.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:t,name:"ExecutionRevertedError"})}}Object.defineProperty(dn,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(dn,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});class Wr extends z{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${dt(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}}Object.defineProperty(Wr,"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 mc extends z{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${dt(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:t,name:"FeeCapTooLowError"})}}Object.defineProperty(mc,"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 bc extends z{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:t,name:"NonceTooHighError"})}}Object.defineProperty(bc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class gc extends z{constructor({cause:t,nonce:r}={}){super([`Nonce provided for the transaction ${r?`(${r}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
37
+ `),{cause:t,name:"NonceTooLowError"})}}Object.defineProperty(gc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class wc extends z{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:t,name:"NonceMaxValueError"})}}Object.defineProperty(wc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class vc extends z{constructor({cause:t}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
38
+ `),{cause:t,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}}Object.defineProperty(vc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class _c extends z{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:t,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(_c,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class Ec extends z{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction is too low.`,{cause:t,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(Ec,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class xc extends z{constructor({cause:t}){super("The transaction type is not supported for this chain.",{cause:t,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(xc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class Ri extends z{constructor({cause:t,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${dt(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${dt(n)} gwei`:""}).`].join(`
39
+ `),{cause:t,name:"TipAboveFeeCapError"})}}Object.defineProperty(Ri,"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 Yo extends z{constructor({cause:t}){super(`An error occurred while executing: ${t==null?void 0:t.shortMessage}`,{cause:t,name:"UnknownNodeError"})}}function iu(e,t){const r=(e.details||"").toLowerCase(),n=e instanceof z?e.walk(i=>(i==null?void 0:i.code)===dn.code):e;return n instanceof z?new dn({cause:e,message:n.details}):dn.nodeMessage.test(r)?new dn({cause:e,message:e.details}):Wr.nodeMessage.test(r)?new Wr({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):mc.nodeMessage.test(r)?new mc({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):bc.nodeMessage.test(r)?new bc({cause:e,nonce:t==null?void 0:t.nonce}):gc.nodeMessage.test(r)?new gc({cause:e,nonce:t==null?void 0:t.nonce}):wc.nodeMessage.test(r)?new wc({cause:e,nonce:t==null?void 0:t.nonce}):vc.nodeMessage.test(r)?new vc({cause:e}):_c.nodeMessage.test(r)?new _c({cause:e,gas:t==null?void 0:t.gas}):Ec.nodeMessage.test(r)?new Ec({cause:e,gas:t==null?void 0:t.gas}):xc.nodeMessage.test(r)?new xc({cause:e}):Ri.nodeMessage.test(r)?new Ri({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas,maxPriorityFeePerGas:t==null?void 0:t.maxPriorityFeePerGas}):new Yo({cause:e})}function Mb(e,{docsPath:t,...r}){const n=(()=>{const i=iu(e,r);return i instanceof Yo?e:i})();return new Lb(n,{docsPath:t,...r})}function ou(e,{format:t}){if(!t)return{};const r={};function n(o){const s=Object.keys(o);for(const a of s)a in e&&(r[a]=e[a]),o[a]&&typeof o[a]=="object"&&!Array.isArray(o[a])&&n(o[a])}const i=t(e||{});return n(i),r}function su(e,t){return({exclude:r,format:n})=>({exclude:r,format:i=>{const o=t(i);if(r)for(const s of r)delete o[s];return{...o,...n(i)}},type:e})}const Hb={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function Xo(e){const t={};return typeof e.authorizationList<"u"&&(t.authorizationList=Db(e.authorizationList)),typeof e.accessList<"u"&&(t.accessList=e.accessList),typeof e.blobVersionedHashes<"u"&&(t.blobVersionedHashes=e.blobVersionedHashes),typeof e.blobs<"u"&&(typeof e.blobs[0]!="string"?t.blobs=e.blobs.map(r=>at(r)):t.blobs=e.blobs),typeof e.data<"u"&&(t.data=e.data),typeof e.from<"u"&&(t.from=e.from),typeof e.gas<"u"&&(t.gas=Q(e.gas)),typeof e.gasPrice<"u"&&(t.gasPrice=Q(e.gasPrice)),typeof e.maxFeePerBlobGas<"u"&&(t.maxFeePerBlobGas=Q(e.maxFeePerBlobGas)),typeof e.maxFeePerGas<"u"&&(t.maxFeePerGas=Q(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(t.maxPriorityFeePerGas=Q(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(t.nonce=Q(e.nonce)),typeof e.to<"u"&&(t.to=e.to),typeof e.type<"u"&&(t.type=Hb[e.type]),typeof e.value<"u"&&(t.value=Q(e.value)),t}function Db(e){return e.map(t=>({address:t.address,r:t.r?Q(BigInt(t.r)):t.r,s:t.s?Q(BigInt(t.s)):t.s,chainId:Q(t.chainId),nonce:Q(t.nonce),...typeof t.yParity<"u"?{yParity:Q(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:Q(t.v)}:{}}))}function uf(e){if(!(!e||e.length===0))return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new Wu({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new Wu({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function jb(e){const{balance:t,nonce:r,state:n,stateDiff:i,code:o}=e,s={};if(o!==void 0&&(s.code=o),t!==void 0&&(s.balance=Q(t)),r!==void 0&&(s.nonce=Q(r)),n!==void 0&&(s.state=uf(n)),i!==void 0){if(s.state)throw new mb;s.stateDiff=uf(i)}return s}function mh(e){if(!e)return;const t={};for(const{address:r,...n}of e){if(!Me(r,{strict:!1}))throw new ct({address:r});if(t[r])throw new yb({address:r});t[r]=jb(n)}return t}const Jo=2n**256n-1n;function zi(e){const{account:t,gasPrice:r,maxFeePerGas:n,maxPriorityFeePerGas:i,to:o}=e,s=t?He(t):void 0;if(s&&!Me(s.address))throw new ct({address:s.address});if(o&&!Me(o))throw new ct({address:o});if(typeof r<"u"&&(typeof n<"u"||typeof i<"u"))throw new gb;if(n&&n>Jo)throw new Wr({maxFeePerGas:n});if(i&&n&&i>n)throw new Ri({maxFeePerGas:n,maxPriorityFeePerGas:i})}class qb extends z{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class au extends z{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class Gb extends z{constructor({maxPriorityFeePerGas:t}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${dt(t)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class zb extends z{constructor({blockHash:t,blockNumber:r}){let n="Block";t&&(n=`Block at hash "${t}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}const bh={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function cu(e){const t={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?zt(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?zt(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?bh[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(t.authorizationList=Wb(e.authorizationList)),t.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof t.v=="bigint"){if(t.v===0n||t.v===27n)return 0;if(t.v===1n||t.v===28n)return 1;if(t.v>=35n)return t.v%2n===0n?1:0}})(),t.type==="legacy"&&(delete t.accessList,delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas,delete t.yParity),t.type==="eip2930"&&(delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas),t.type==="eip1559"&&delete t.maxFeePerBlobGas,t}const Vb=su("transaction",cu);function Wb(e){return e.map(t=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}function gh(e){const t=(e.transactions??[]).map(r=>typeof r=="string"?r:cu(r));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:t,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}const Kb=su("block",gh);async function Oo(e,{blockHash:t,blockNumber:r,blockTag:n,includeTransactions:i}={}){var l,h,y;const o=n??"latest",s=i??!1,a=r!==void 0?Q(r):void 0;let c=null;if(t?c=await e.request({method:"eth_getBlockByHash",params:[t,s]},{dedupe:!0}):c=await e.request({method:"eth_getBlockByNumber",params:[a||o,s]},{dedupe:!!a}),!c)throw new zb({blockHash:t,blockNumber:r});return(((y=(h=(l=e.chain)==null?void 0:l.formatters)==null?void 0:h.block)==null?void 0:y.format)||gh)(c)}async function wh(e){const t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function Yb(e,t){var o,s;const{block:r,chain:n=e.chain,request:i}=t||{};try{const a=((o=n==null?void 0:n.fees)==null?void 0:o.maxPriorityFeePerGas)??((s=n==null?void 0:n.fees)==null?void 0:s.defaultPriorityFee);if(typeof a=="function"){const u=r||await pe(e,Oo,"getBlock")({}),l=await a({block:u,client:e,request:i});if(l===null)throw new Error;return l}if(typeof a<"u")return a;const c=await e.request({method:"eth_maxPriorityFeePerGas"});return yt(c)}catch{const[a,c]=await Promise.all([r?Promise.resolve(r):pe(e,Oo,"getBlock")({}),pe(e,wh,"getGasPrice")({})]);if(typeof a.baseFeePerGas!="bigint")throw new au;const u=c-a.baseFeePerGas;return u<0n?0n:u}}async function ff(e,t){var y,p;const{block:r,chain:n=e.chain,request:i,type:o="eip1559"}=t||{},s=await(async()=>{var b,v;return typeof((b=n==null?void 0:n.fees)==null?void 0:b.baseFeeMultiplier)=="function"?n.fees.baseFeeMultiplier({block:r,client:e,request:i}):((v=n==null?void 0:n.fees)==null?void 0:v.baseFeeMultiplier)??1.2})();if(s<1)throw new qb;const c=10**(((y=s.toString().split(".")[1])==null?void 0:y.length)??0),u=b=>b*BigInt(Math.ceil(s*c))/BigInt(c),l=r||await pe(e,Oo,"getBlock")({});if(typeof((p=n==null?void 0:n.fees)==null?void 0:p.estimateFeesPerGas)=="function"){const b=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:u,request:i,type:o});if(b!==null)return b}if(o==="eip1559"){if(typeof l.baseFeePerGas!="bigint")throw new au;const b=typeof(i==null?void 0:i.maxPriorityFeePerGas)=="bigint"?i.maxPriorityFeePerGas:await Yb(e,{block:l,chain:n,request:i}),v=u(l.baseFeePerGas);return{maxFeePerGas:(i==null?void 0:i.maxFeePerGas)??v+b,maxPriorityFeePerGas:b}}return{gasPrice:(i==null?void 0:i.gasPrice)??u(await pe(e,wh,"getGasPrice")({}))}}async function vh(e,{address:t,blockTag:r="latest",blockNumber:n}){const i=await e.request({method:"eth_getTransactionCount",params:[t,typeof n=="bigint"?Q(n):r]},{dedupe:!!n});return zt(i)}function uu(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(o=>ar(o)):e.blobs,i=[];for(const o of n)i.push(Uint8Array.from(t.blobToKzgCommitment(o)));return r==="bytes"?i:i.map(o=>at(o))}function fu(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(s=>ar(s)):e.blobs,i=typeof e.commitments[0]=="string"?e.commitments.map(s=>ar(s)):e.commitments,o=[];for(let s=0;s<n.length;s++){const a=n[s],c=i[s];o.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?o:o.map(s=>at(s))}function Xb(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),a=Number(r&o),c=n?4:0,u=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+u,a,n)}function Jb(e,t,r){return e&t^~e&r}function Qb(e,t,r){return e&t^e&r^t&r}let _h=class extends Yc{constructor(t,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Ps(this.buffer)}update(t){di(this),t=Do(t),Br(t);const{view:r,buffer:n,blockLen:i}=this,o=t.length;for(let s=0;s<o;){const a=Math.min(i-this.pos,o-s);if(a===i){const c=Ps(t);for(;i<=o-s;s+=i)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){di(this),Kd(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:o}=this;let{pos:s}=this;r[s++]=128,kr(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let h=s;h<i;h++)r[h]=0;Xb(n,i-8,BigInt(this.length*8),o),this.process(n,0);const a=Ps(t),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 h=0;h<u;h++)a.setUint32(4*h,l[h],o)}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=o,t.length=i,t.pos=a,i%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}};const hr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),pr=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),Zb=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]),yr=new Uint32Array(64);let lu=class extends _h{constructor(t=32){super(64,t,8,!1),this.A=hr[0]|0,this.B=hr[1]|0,this.C=hr[2]|0,this.D=hr[3]|0,this.E=hr[4]|0,this.F=hr[5]|0,this.G=hr[6]|0,this.H=hr[7]|0}get(){const{A:t,B:r,C:n,D:i,E:o,F:s,G:a,H:c}=this;return[t,r,n,i,o,s,a,c]}set(t,r,n,i,o,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,r){for(let h=0;h<16;h++,r+=4)yr[h]=t.getUint32(r,!1);for(let h=16;h<64;h++){const y=yr[h-15],p=yr[h-2],b=Rt(y,7)^Rt(y,18)^y>>>3,v=Rt(p,17)^Rt(p,19)^p>>>10;yr[h]=v+yr[h-7]+b+yr[h-16]|0}let{A:n,B:i,C:o,D:s,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){const y=Rt(a,6)^Rt(a,11)^Rt(a,25),p=l+y+Jb(a,c,u)+Zb[h]+yr[h]|0,v=(Rt(n,2)^Rt(n,13)^Rt(n,22))+Qb(n,i,o)|0;l=u,u=c,c=a,a=s+p|0,s=o,o=i,i=n,n=p+v|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+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,i,o,s,a,c,u,l)}roundClean(){kr(yr)}destroy(){this.set(0,0,0,0,0,0,0,0),kr(this.buffer)}},Eh=class extends lu{constructor(){super(28),this.A=pr[0]|0,this.B=pr[1]|0,this.C=pr[2]|0,this.D=pr[3]|0,this.E=pr[4]|0,this.F=pr[5]|0,this.G=pr[6]|0,this.H=pr[7]|0}};const xh=jo(()=>new lu),eg=jo(()=>new Eh),tg=lu,Ah=xh,rg=Eh,ng=eg,ig=Object.freeze(Object.defineProperty({__proto__:null,SHA224:rg,SHA256:tg,sha224:ng,sha256:Ah},Symbol.toStringTag,{value:"Module"}));function ii(e,t){const r=t||"hex",n=Ah(sr(e,{strict:!1})?Di(e):e);return r==="bytes"?n:qt(n)}function og(e){const{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),i=ii(t,"bytes");return i.set([r],0),n==="bytes"?i:at(i)}function Sh(e){const{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),i=[];for(const o of t)i.push(og({commitment:o,to:n,version:r}));return i}const lf=6,Ph=32,du=4096,Th=Ph*du,df=Th*lf-1-1*du*lf,Ih=1;class sg extends z{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class Bh extends z{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class ag extends z{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class cg extends z{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${Ih}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function ug(e){const t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?ar(e.data):e.data,n=Re(r);if(!n)throw new Bh;if(n>df)throw new sg({maxSize:df,size:n});const i=[];let o=!0,s=0;for(;o;){const a=tu(new Uint8Array(Th));let c=0;for(;c<du;){const u=r.slice(s,s+(Ph-1));if(a.pushByte(0),a.pushBytes(u),u.length<31){a.pushByte(128),o=!1;break}c++,s+=31}i.push(a)}return t==="bytes"?i.map(a=>a.bytes):i.map(a=>at(a.bytes))}function kh(e){const{data:t,kzg:r,to:n}=e,i=e.blobs??ug({data:t,to:n}),o=e.commitments??uu({blobs:i,kzg:r,to:n}),s=e.proofs??fu({blobs:i,commitments:o,kzg:r,to:n}),a=[];for(let c=0;c<i.length;c++)a.push({blob:i[c],commitment:o[c],proof:s[c]});return a}function Oh(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u")return typeof e.accessList<"u"?"eip2930":"legacy";throw new vb({transaction:e})}async function Vi(e){const t=await e.request({method:"eth_chainId"},{dedupe:!0});return zt(t)}const Rh=["blobVersionedHashes","chainId","fees","gas","nonce","type"],hf=new Map;async function hu(e,t){const{account:r=e.account,blobs:n,chain:i,gas:o,kzg:s,nonce:a,nonceManager:c,parameters:u=Rh,type:l}=t,h=r&&He(r),y={...t,...h?{from:h==null?void 0:h.address}:{}};let p;async function b(){return p||(p=await pe(e,Oo,"getBlock")({blockTag:"latest"}),p)}let v;async function E(){return v||(i?i.id:typeof t.chainId<"u"?t.chainId:(v=await pe(e,Vi,"getChainId")({}),v))}if(u.includes("nonce")&&typeof a>"u"&&h)if(c){const S=await E();y.nonce=await c.consume({address:h.address,chainId:S,client:e})}else y.nonce=await pe(e,vh,"getTransactionCount")({address:h.address,blockTag:"pending"});if((u.includes("blobVersionedHashes")||u.includes("sidecars"))&&n&&s){const S=uu({blobs:n,kzg:s});if(u.includes("blobVersionedHashes")){const P=Sh({commitments:S,to:"hex"});y.blobVersionedHashes=P}if(u.includes("sidecars")){const P=fu({blobs:n,commitments:S,kzg:s}),A=kh({blobs:n,commitments:S,proofs:P,to:"hex"});y.sidecars=A}}if(u.includes("chainId")&&(y.chainId=await E()),(u.includes("fees")||u.includes("type"))&&typeof l>"u")try{y.type=Oh(y)}catch{let S=hf.get(e.uid);if(typeof S>"u"){const P=await b();S=typeof(P==null?void 0:P.baseFeePerGas)=="bigint",hf.set(e.uid,S)}y.type=S?"eip1559":"legacy"}if(u.includes("fees"))if(y.type!=="legacy"&&y.type!=="eip2930"){if(typeof y.maxFeePerGas>"u"||typeof y.maxPriorityFeePerGas>"u"){const S=await b(),{maxFeePerGas:P,maxPriorityFeePerGas:A}=await ff(e,{block:S,chain:i,request:y});if(typeof t.maxPriorityFeePerGas>"u"&&t.maxFeePerGas&&t.maxFeePerGas<A)throw new Gb({maxPriorityFeePerGas:A});y.maxPriorityFeePerGas=A,y.maxFeePerGas=P}}else{if(typeof t.maxFeePerGas<"u"||typeof t.maxPriorityFeePerGas<"u")throw new au;if(typeof t.gasPrice>"u"){const S=await b(),{gasPrice:P}=await ff(e,{block:S,chain:i,request:y,type:"legacy"});y.gasPrice=P}}return u.includes("gas")&&typeof o>"u"&&(y.gas=await pe(e,Ch,"estimateGas")({...y,account:h&&{address:h.address,type:"json-rpc"}})),zi(y),delete y.parameters,y}async function fg(e,{address:t,blockNumber:r,blockTag:n="latest"}){const i=typeof r=="bigint"?Q(r):void 0,o=await e.request({method:"eth_getBalance",params:[t,i||n]});return BigInt(o)}async function Ch(e,t){var i,o,s;const{account:r=e.account}=t,n=r?He(r):void 0;try{let ee=function(be){const{block:ye,request:ce,rpcStateOverride:F}=be;return e.request({method:"eth_estimateGas",params:F?[ce,ye??"latest",F]:ye?[ce,ye]:[ce]})};const{accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:l,blockNumber:h,blockTag:y,data:p,gas:b,gasPrice:v,maxFeePerBlobGas:E,maxFeePerGas:S,maxPriorityFeePerGas:P,nonce:A,value:w,stateOverride:B,...T}=await hu(e,{...t,parameters:(n==null?void 0:n.type)==="local"?void 0:["blobVersionedHashes"]}),D=(typeof h=="bigint"?Q(h):void 0)||y,C=mh(B),X=await(async()=>{if(T.to)return T.to;if(c&&c.length>0)return await yh({authorization:c[0]}).catch(()=>{throw new z("`to` is required. Could not infer from `authorizationList`")})})();zi(t);const Z=(s=(o=(i=e.chain)==null?void 0:i.formatters)==null?void 0:o.transactionRequest)==null?void 0:s.format,te=(Z||Xo)({...ou(T,{format:Z}),from:n==null?void 0:n.address,accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:l,data:p,gas:b,gasPrice:v,maxFeePerBlobGas:E,maxFeePerGas:S,maxPriorityFeePerGas:P,nonce:A,to:X,value:w});let ae=BigInt(await ee({block:D,request:te,rpcStateOverride:C}));if(c){const be=await fg(e,{address:te.from}),ye=await Promise.all(c.map(async ce=>{const{address:F}=ce,Y=await ee({block:D,request:{authorizationList:void 0,data:p,from:n==null?void 0:n.address,to:F,value:Q(be)},rpcStateOverride:C}).catch(()=>100000n);return 2n*BigInt(Y)}));ae+=ye.reduce((ce,F)=>ce+F,0n)}return ae}catch(a){throw Mb(a,{...t,account:n,chain:e.chain})}}async function lg(e,t){const{abi:r,address:n,args:i,functionName:o,dataSuffix:s,...a}=t,c=Mn({abi:r,args:i,functionName:o});try{return await pe(e,Ch,"estimateGas")({data:`${c}${s?s.replace("0x",""):""}`,to:n,...a})}catch(u){const l=a.account?He(a.account):void 0;throw Ko(u,{abi:r,address:n,args:i,docsPath:"/docs/contract/estimateContractGas",functionName:o,sender:l==null?void 0:l.address})}}function pu(e,t){if(!Me(e,{strict:!1}))throw new ct({address:e});if(!Me(t,{strict:!1}))throw new ct({address:t});return e.toLowerCase()===t.toLowerCase()}const pf="/docs/contract/decodeEventLog";function Fh(e){const{abi:t,data:r,strict:n,topics:i}=e,o=n??!0,[s,...a]=i;if(!s)throw new Vy({docsPath:pf});const c=t.find(v=>v.type==="event"&&s===qo(Gt(v)));if(!(c&&"name"in c)||c.type!=="event")throw new Md(s,{docsPath:pf});const{name:u,inputs:l}=c,h=l==null?void 0:l.some(v=>!("name"in v&&v.name)),y=h?[]:{},p=l.map((v,E)=>[v,E]).filter(([v])=>"indexed"in v&&v.indexed);for(let v=0;v<p.length;v++){const[E,S]=p[v],P=a[v];if(!P)throw new Kc({abiItem:c,param:E});y[h?S:E.name||S]=dg({param:E,value:P})}const b=l.filter(v=>!("indexed"in v&&v.indexed));if(b.length>0){if(r&&r!=="0x")try{const v=qi(b,r);if(v)if(h)for(let E=0;E<l.length;E++)y[E]=y[E]??v.shift();else for(let E=0;E<b.length;E++)y[b[E].name]=v[E]}catch(v){if(o)throw v instanceof $d||v instanceof ch?new ko({abiItem:c,data:r,params:b,size:Re(r)}):v}else if(o)throw new ko({abiItem:c,data:"0x",params:b,size:0})}return{eventName:u,args:Object.values(y).length>0?y:void 0}}function dg({param:e,value:t}){return e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/)?t:(qi([e],t)||[])[0]}function Uh(e){const{abi:t,args:r,logs:n,strict:i=!0}=e,o=(()=>{if(e.eventName)return Array.isArray(e.eventName)?e.eventName:[e.eventName]})();return n.map(s=>{var a;try{const c=t.find(l=>l.type==="event"&&s.topics[0]===qo(l));if(!c)return null;const u=Fh({...s,abi:[c],strict:i});return o&&!o.includes(u.eventName)||!hg({args:u.args,inputs:c.inputs,matchArgs:r})?null:{...u,...s}}catch(c){let u,l;if(c instanceof Md)return null;if(c instanceof ko||c instanceof Kc){if(i)return null;u=c.abiItem.name,l=(a=c.abiItem.inputs)==null?void 0:a.some(h=>!("name"in h&&h.name))}return{...s,args:l?[]:{},eventName:u}}}).filter(Boolean)}function hg(e){const{args:t,inputs:r,matchArgs:n}=e;if(!n)return!0;if(!t)return!1;function i(o,s,a){try{return o.type==="address"?pu(s,a):o.type==="string"||o.type==="bytes"?$n(Di(s))===a:s===a}catch{return!1}}return Array.isArray(t)&&Array.isArray(n)?n.every((o,s)=>{if(o==null)return!0;const a=r[s];return a?(Array.isArray(o)?o:[o]).some(u=>i(a,u,t[s])):!1}):typeof t=="object"&&!Array.isArray(t)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([o,s])=>{if(s==null)return!0;const a=r.find(u=>u.name===o);return a?(Array.isArray(s)?s:[s]).some(u=>i(a,u,t[o])):!1}):!1}function Ci(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}async function pg(e,{address:t,blockHash:r,fromBlock:n,toBlock:i,event:o,events:s,args:a,strict:c}={}){const u=c??!1,l=s??(o?[o]:void 0);let h=[];l&&(h=[l.flatMap(v=>eu({abi:[v],eventName:v.name,args:s?void 0:a}))],o&&(h=h[0]));let y;r?y=await e.request({method:"eth_getLogs",params:[{address:t,topics:h,blockHash:r}]}):y=await e.request({method:"eth_getLogs",params:[{address:t,topics:h,fromBlock:typeof n=="bigint"?Q(n):n,toBlock:typeof i=="bigint"?Q(i):i}]});const p=y.map(b=>Ci(b));return l?Uh({abi:l,args:a,logs:p,strict:u}):p}async function Nh(e,t){const{abi:r,address:n,args:i,blockHash:o,eventName:s,fromBlock:a,toBlock:c,strict:u}=t,l=s?Ln({abi:r,name:s}):void 0,h=l?void 0:r.filter(y=>y.type==="event");return pe(e,pg,"getLogs")({address:n,args:i,blockHash:o,event:l,events:h,fromBlock:a,toBlock:c,strict:u})}const Bs="/docs/contract/decodeFunctionResult";function yu(e){const{abi:t,args:r,functionName:n,data:i}=e;let o=t[0];if(n){const a=Ln({abi:t,args:r,name:n});if(!a)throw new fi(n,{docsPath:Bs});o=a}if(o.type!=="function")throw new fi(void 0,{docsPath:Bs});if(!o.outputs)throw new Hd(o.name,{docsPath:Bs});const s=qi(o.outputs,i);if(s&&s.length>1)return s;if(s&&s.length===1)return s[0]}const yg="0.1.1";function mg(){return yg}class Fi extends Error{constructor(t,r={}){const n=(()=>{var c;if(r.cause instanceof Fi){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})(),i=r.cause instanceof Fi&&r.cause.docsPath||r.docsPath,s=`https://oxlib.sh${i??""}`,a=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||i?["",n?`Details: ${n}`:void 0,i?`See: ${s}`: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@${mg()}`}),this.cause=r.cause,this.details=n,this.docs=s,this.docsPath=i,this.shortMessage=t}walk(t){return $h(this,t)}}function $h(e,t){return t!=null&&t(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?$h(e.cause,t):t?null:e}function bg(e,t={}){const{dir:r,size:n=32}=t;if(n===0)return e;const i=e.replace("0x","");if(i.length>n*2)throw new vg({size:Math.ceil(i.length/2),targetSize:n,type:"Hex"});return`0x${i[r==="right"?"padEnd":"padStart"](n*2,"0")}`}function tr(e,t={}){const{signed:r,size:n}=t,i=BigInt(e);let o;n?r?o=(1n<<BigInt(n)*8n-1n)-1n:o=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(o=BigInt(Number.MAX_SAFE_INTEGER));const s=typeof o=="bigint"&&r?-o-1n:0;if(o&&i>o||i<s){const u=typeof e=="bigint"?"n":"";throw new wg({max:o?`${o}${u}`:void 0,min:`${s}${u}`,signed:r,size:n,value:`${e}${u}`})}const c=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?gg(c,n):c}function gg(e,t){return bg(e,{dir:"left",size:t})}class wg extends Fi{constructor({max:t,min:r,signed:n,size:i,value:o}){super(`Number \`${o}\` is not in safe${i?` ${i*8}-bit`:""}${n?" signed":" unsigned"} integer range ${t?`(\`${r}\` to \`${t}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class vg extends Fi{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}function _g(e){return{address:e.address,amount:tr(e.amount),index:tr(e.index),validatorIndex:tr(e.validatorIndex)}}function Eg(e){return{...typeof e.baseFeePerGas=="bigint"&&{baseFeePerGas:tr(e.baseFeePerGas)},...typeof e.blobBaseFee=="bigint"&&{blobBaseFee:tr(e.blobBaseFee)},...typeof e.feeRecipient=="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit=="bigint"&&{gasLimit:tr(e.gasLimit)},...typeof e.number=="bigint"&&{number:tr(e.number)},...typeof e.prevRandao=="bigint"&&{prevRandao:tr(e.prevRandao)},...typeof e.time=="bigint"&&{time:tr(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(_g)}}}const yf=[{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"}],xg=[{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="0x82ad56cb",Sg="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",Pg="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe";class Ac extends z{constructor({blockNumber:t,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...t&&n.blockCreated&&n.blockCreated>t?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${t}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class Tg extends z{constructor({chain:t,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${t.id} – ${t.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${t.id} – ${t.name}`],name:"ChainMismatchError"})}}class Ig extends z{constructor(){super(["No chain was provided to the request.","Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."].join(`
41
+ `),{name:"ChainNotFoundError"})}}class Lh extends z{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class Qo extends z{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const ks="/docs/contract/encodeDeployData";function mu(e){const{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;const i=t.find(s=>"type"in s&&s.type==="constructor");if(!i)throw new Hy({docsPath:ks});if(!("inputs"in i))throw new zu({docsPath:ks});if(!i.inputs||i.inputs.length===0)throw new zu({docsPath:ks});const o=zo(i.inputs,r);return Wt([n,o])}function Bg({blockNumber:e,chain:t,contract:r}){var i;const n=(i=t==null?void 0:t.contracts)==null?void 0:i[r];if(!n)throw new Ac({chain:t,contract:{name:r}});if(e&&n.blockCreated&&n.blockCreated>e)throw new Ac({blockNumber:e,chain:t,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function kg(e,{docsPath:t,...r}){const n=(()=>{const i=iu(e,r);return i instanceof Yo?e:i})();return new Ab(n,{docsPath:t,...r})}function Mh(){let e=()=>{},t=()=>{};return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}}const Os=new Map;function Hh({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:i}){const o=async()=>{const l=c();s();const h=l.map(({args:y})=>y);h.length!==0&&e(h).then(y=>{i&&Array.isArray(y)&&y.sort(i);for(let p=0;p<l.length;p++){const{resolve:b}=l[p];b==null||b([y[p],y])}}).catch(y=>{for(let p=0;p<l.length;p++){const{reject:b}=l[p];b==null||b(y)}})},s=()=>Os.delete(t),a=()=>c().map(({args:l})=>l),c=()=>Os.get(t)||[],u=l=>Os.set(t,[...c(),l]);return{flush:s,async schedule(l){const{promise:h,resolve:y,reject:p}=Mh();return(r==null?void 0:r([...a(),l]))&&o(),c().length>0?(u({args:l,resolve:y,reject:p}),h):(u({args:l,resolve:y,reject:p}),setTimeout(o,n),h)}}}async function bu(e,t){var te,ee,ae,be;const{account:r=e.account,authorizationList:n,batch:i=!!((te=e.batch)!=null&&te.multicall),blockNumber:o,blockTag:s="latest",accessList:a,blobs:c,blockOverrides:u,code:l,data:h,factory:y,factoryData:p,gas:b,gasPrice:v,maxFeePerBlobGas:E,maxFeePerGas:S,maxPriorityFeePerGas:P,nonce:A,to:w,value:B,stateOverride:T,...L}=t,D=r?He(r):void 0;if(l&&(y||p))throw new z("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(l&&w)throw new z("Cannot provide both `code` & `to` as parameters.");const C=l&&h,X=y&&p&&w&&h,Z=C||X,oe=C?Cg({code:l,data:h}):X?Fg({data:h,factory:y,factoryData:p,to:w}):h;try{zi(t);const ce=(typeof o=="bigint"?Q(o):void 0)||s,F=u?Eg(u):void 0,Y=mh(T),re=(be=(ae=(ee=e.chain)==null?void 0:ee.formatters)==null?void 0:ae.transactionRequest)==null?void 0:be.format,N=(re||Xo)({...ou(L,{format:re}),from:D==null?void 0:D.address,accessList:a,authorizationList:n,blobs:c,data:oe,gas:b,gasPrice:v,maxFeePerBlobGas:E,maxFeePerGas:S,maxPriorityFeePerGas:P,nonce:A,to:Z?void 0:w,value:B});if(i&&Og({request:N})&&!Y&&!F)try{return await Rg(e,{...N,blockNumber:o,blockTag:s})}catch(I){if(!(I instanceof Lh)&&!(I instanceof Ac))throw I}const q=(()=>{const I=[N,ce];return Y&&F?[...I,Y,F]:Y?[...I,Y]:F?[...I,{},F]:I})(),ne=await e.request({method:"eth_call",params:q});return ne==="0x"?{data:void 0}:{data:ne}}catch(ye){const ce=Ug(ye),{offchainLookup:F,offchainLookupSignature:Y}=await Promise.resolve().then(()=>require("./ccip-BCmQ-ZNT.cjs"));if(e.ccipRead!==!1&&(ce==null?void 0:ce.slice(0,10))===Y&&w)return{data:await F(e,{data:ce,to:w})};throw Z&&(ce==null?void 0:ce.slice(0,10))==="0x101bb98d"?new Ib({factory:y}):kg(ye,{...t,account:D,chain:e.chain})}}function Og({request:e}){const{data:t,to:r,...n}=e;return!(!t||t.startsWith(Ag)||!r||Object.values(n).filter(i=>typeof i<"u").length>0)}async function Rg(e,t){var v;const{batchSize:r=1024,wait:n=0}=typeof((v=e.batch)==null?void 0:v.multicall)=="object"?e.batch.multicall:{},{blockNumber:i,blockTag:o="latest",data:s,multicallAddress:a,to:c}=t;let u=a;if(!u){if(!e.chain)throw new Lh;u=Bg({blockNumber:i,chain:e.chain,contract:"multicall3"})}const h=(typeof i=="bigint"?Q(i):void 0)||o,{schedule:y}=Hh({id:`${e.uid}.${h}`,wait:n,shouldSplitBatch(E){return E.reduce((P,{data:A})=>P+(A.length-2),0)>r*2},fn:async E=>{const S=E.map(w=>({allowFailure:!0,callData:w.data,target:w.to})),P=Mn({abi:yf,args:[S],functionName:"aggregate3"}),A=await e.request({method:"eth_call",params:[{data:P,to:u},h]});return yu({abi:yf,args:[S],functionName:"aggregate3",data:A||"0x"})}}),[{returnData:p,success:b}]=await y({data:s,to:c});if(!b)throw new dh({data:p});return p==="0x"?{data:void 0}:{data:p}}function Cg(e){const{code:t,data:r}=e;return mu({abi:Fd(["constructor(bytes, bytes)"]),bytecode:Sg,args:[t,r]})}function Fg(e){const{data:t,factory:r,factoryData:n,to:i}=e;return mu({abi:Fd(["constructor(address, bytes, address, bytes)"]),bytecode:Pg,args:[i,t,r,n]})}function Ug(e){var r;if(!(e instanceof z))return;const t=e.walk();return typeof(t==null?void 0:t.data)=="object"?(r=t.data)==null?void 0:r.data:t.data}async function Ng(e,t){const{abi:r,address:n,args:i,functionName:o,...s}=t,a=Mn({abi:r,args:i,functionName:o});try{const{data:c}=await pe(e,bu,"call")({...s,data:a,to:n});return yu({abi:r,args:i,functionName:o,data:c||"0x"})}catch(c){throw Ko(c,{abi:r,address:n,args:i,docsPath:"/docs/contract/readContract",functionName:o})}}async function $g(e,t){const{abi:r,address:n,args:i,dataSuffix:o,functionName:s,...a}=t,c=a.account?He(a.account):e.account,u=Mn({abi:r,args:i,functionName:s});try{const{data:l}=await pe(e,bu,"call")({batch:!1,data:`${u}${o?o.replace("0x",""):""}`,to:n,...a,account:c}),h=yu({abi:r,args:i,functionName:s,data:l||"0x"}),y=r.filter(p=>"name"in p&&p.name===t.functionName);return{result:h,request:{abi:y,address:n,args:i,dataSuffix:o,functionName:s,...a,account:c}}}catch(l){throw Ko(l,{abi:r,address:n,args:i,docsPath:"/docs/contract/simulateContract",functionName:s,sender:c==null?void 0:c.address})}}const Rs=new Map,mf=new Map;let Lg=0;function Sc(e,t,r){const n=++Lg,i=()=>Rs.get(e)||[],o=()=>{const l=i();Rs.set(e,l.filter(h=>h.id!==n))},s=()=>{const l=i();if(!l.some(y=>y.id===n))return;const h=mf.get(e);if(l.length===1&&h){const y=h();y instanceof Promise&&y.catch(()=>{})}o()},a=i();if(Rs.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return s;const c={};for(const l in t)c[l]=(...h)=>{var p,b;const y=i();if(y.length!==0)for(const v of y)(b=(p=v.fns)[l])==null||b.call(p,...h)};const u=r(c);return typeof u=="function"&&mf.set(e,u),s}async function Pc(e){return new Promise(t=>setTimeout(t,e))}function Dh(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let i=!0;const o=()=>i=!1;return(async()=>{let a;a=await e({unpoll:o});const c=await(r==null?void 0:r(a))??n;await Pc(c);const u=async()=>{i&&(await e({unpoll:o}),await Pc(n),u())};u()})(),o}const Mg=new Map,Hg=new Map;function Dg(e){const t=(i,o)=>({clear:()=>o.delete(i),get:()=>o.get(i),set:s=>o.set(i,s)}),r=t(e,Mg),n=t(e,Hg);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function jg(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){const n=Dg(t),i=n.response.get();if(i&&r>0&&new Date().getTime()-i.created.getTime()<r)return i.data;let o=n.promise.get();o||(o=e(),n.promise.set(o));try{const s=await o;return n.response.set({created:new Date,data:s}),s}finally{n.promise.clear()}}const qg=e=>`blockNumber.${e}`;async function Gg(e,{cacheTime:t=e.cacheTime}={}){const r=await jg(()=>e.request({method:"eth_blockNumber"}),{cacheKey:qg(e.uid),cacheTime:t});return BigInt(r)}async function zg(e,{filter:t}){const r="strict"in t&&t.strict,n=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof n[0]=="string")return n;const i=n.map(o=>Ci(o));return!("abi"in t)||!t.abi?i:Uh({abi:t.abi,logs:i,strict:r})}async function Vg(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}function Wg(e,t){const{abi:r,address:n,args:i,batch:o=!0,eventName:s,fromBlock:a,onError:c,onLogs:u,poll:l,pollingInterval:h=e.pollingInterval,strict:y}=t;return(typeof l<"u"?l:typeof a=="bigint"?!0:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")))?(()=>{const E=y??!1,S=lt(["watchContractEvent",n,i,o,e.uid,s,h,E,a]);return Sc(S,{onLogs:u,onError:c},P=>{let A;a!==void 0&&(A=a-1n);let w,B=!1;const T=Dh(async()=>{var L;if(!B){try{w=await pe(e,sh,"createContractEventFilter")({abi:r,address:n,args:i,eventName:s,strict:E,fromBlock:a})}catch{}B=!0;return}try{let D;if(w)D=await pe(e,zg,"getFilterChanges")({filter:w});else{const C=await pe(e,Gg,"getBlockNumber")({});A&&A<C?D=await pe(e,Nh,"getContractEvents")({abi:r,address:n,args:i,eventName:s,fromBlock:A+1n,toBlock:C,strict:E}):D=[],A=C}if(D.length===0)return;if(o)P.onLogs(D);else for(const C of D)P.onLogs([C])}catch(D){w&&D instanceof _n&&(B=!1),(L=P.onError)==null||L.call(P,D)}},{emitOnBegin:!0,interval:h});return async()=>{w&&await pe(e,Vg,"uninstallFilter")({filter:w}),T()}})})():(()=>{const E=y??!1,S=lt(["watchContractEvent",n,i,o,e.uid,s,h,E]);let P=!0,A=()=>P=!1;return Sc(S,{onLogs:u,onError:c},w=>((async()=>{try{const B=(()=>{if(e.transport.type==="fallback"){const D=e.transport.transports.find(C=>C.config.type==="webSocket"||C.config.type==="ipc");return D?D.value:e.transport}return e.transport})(),T=s?eu({abi:r,eventName:s,args:i}):[],{unsubscribe:L}=await B.subscribe({params:["logs",{address:n,topics:T}],onData(D){var X;if(!P)return;const C=D.result;try{const{eventName:Z,args:oe}=Fh({abi:r,data:C.data,topics:C.topics,strict:y}),te=Ci(C,{args:oe,eventName:Z});w.onLogs([te])}catch(Z){let oe,te;if(Z instanceof ko||Z instanceof Kc){if(y)return;oe=Z.abiItem.name,te=(X=Z.abiItem.inputs)==null?void 0:X.some(ae=>!("name"in ae&&ae.name))}const ee=Ci(C,{args:te?[]:{},eventName:oe});w.onLogs([ee])}},onError(D){var C;(C=w.onError)==null||C.call(w,D)}});A=L,P||A()}catch(B){c==null||c(B)}})(),()=>A()))})()}class Jr extends z{constructor({docsPath:t}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
42
+ `),{docsPath:t,docsSlug:"account",name:"AccountNotFoundError"})}}class _o extends z{constructor({docsPath:t,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:t,metaMessages:r,name:"AccountTypeNotSupportedError"})}}function jh({chain:e,currentChainId:t}){if(!e)throw new Ig;if(t!==e.id)throw new Tg({chain:e,currentChainId:t})}function qh(e,{docsPath:t,...r}){const n=(()=>{const i=iu(e,r);return i instanceof Yo?e:i})();return new Eb(n,{docsPath:t,...r})}async function Gh(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}const Cs=new Go(128);async function Zo(e,t){var P,A,w,B;const{account:r=e.account,chain:n=e.chain,accessList:i,authorizationList:o,blobs:s,data:a,gas:c,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:p,type:b,value:v,...E}=t;if(typeof r>"u")throw new Jr({docsPath:"/docs/actions/wallet/sendTransaction"});const S=r?He(r):null;try{zi(t);const T=await(async()=>{if(t.to)return t.to;if(t.to!==null&&o&&o.length>0)return await yh({authorization:o[0]}).catch(()=>{throw new z("`to` is required. Could not infer from `authorizationList`.")})})();if((S==null?void 0:S.type)==="json-rpc"||S===null){let L;n!==null&&(L=await pe(e,Vi,"getChainId")({}),jh({currentChainId:L,chain:n}));const D=(w=(A=(P=e.chain)==null?void 0:P.formatters)==null?void 0:A.transactionRequest)==null?void 0:w.format,X=(D||Xo)({...ou(E,{format:D}),accessList:i,authorizationList:o,blobs:s,chainId:L,data:a,from:S==null?void 0:S.address,gas:c,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:p,to:T,type:b,value:v}),Z=Cs.get(e.uid),oe=Z?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:oe,params:[X]},{retryCount:0})}catch(te){if(Z===!1)throw te;const ee=te;if(ee.name==="InvalidInputRpcError"||ee.name==="InvalidParamsRpcError"||ee.name==="MethodNotFoundRpcError"||ee.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[X]},{retryCount:0}).then(ae=>(Cs.set(e.uid,!0),ae)).catch(ae=>{const be=ae;throw be.name==="MethodNotFoundRpcError"||be.name==="MethodNotSupportedRpcError"?(Cs.set(e.uid,!1),ee):be});throw ee}}if((S==null?void 0:S.type)==="local"){const L=await pe(e,hu,"prepareTransactionRequest")({account:S,accessList:i,authorizationList:o,blobs:s,chain:n,data:a,gas:c,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:p,nonceManager:S.nonceManager,parameters:[...Rh,"sidecars"],type:b,value:v,...E,to:T}),D=(B=n==null?void 0:n.serializers)==null?void 0:B.transaction,C=await S.signTransaction(L,{serializer:D});return await pe(e,Gh,"sendRawTransaction")({serializedTransaction:C})}throw(S==null?void 0:S.type)==="smart"?new _o({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new _o({docsPath:"/docs/actions/wallet/sendTransaction",type:S==null?void 0:S.type})}catch(T){throw T instanceof _o?T:qh(T,{...t,account:S,chain:t.chain||void 0})}}async function zh(e,t){const{abi:r,account:n=e.account,address:i,args:o,dataSuffix:s,functionName:a,...c}=t;if(typeof n>"u")throw new Jr({docsPath:"/docs/contract/writeContract"});const u=n?He(n):null,l=Mn({abi:r,args:o,functionName:a});try{return await pe(e,Zo,"sendTransaction")({data:`${l}${s?s.replace("0x",""):""}`,to:i,account:u,...c})}catch(h){throw Ko(h,{abi:r,address:i,args:o,docsPath:"/docs/contract/writeContract",functionName:a,sender:u==null?void 0:u.address})}}function Fs({abi:e,address:t,client:r}){const n=r,[i,o]=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],s=i!=null,a=o!=null,c={};let u=!1,l=!1,h=!1;for(const y of e)if(y.type==="function"?y.stateMutability==="view"||y.stateMutability==="pure"?u=!0:l=!0:y.type==="event"&&(h=!0),u&&l&&h)break;return s&&(u&&(c.read=new Proxy({},{get(y,p){return(...b)=>{const{args:v,options:E}=oo(b);return pe(i,Ng,"readContract")({abi:e,address:t,functionName:p,args:v,...E})}}})),l&&(c.simulate=new Proxy({},{get(y,p){return(...b)=>{const{args:v,options:E}=oo(b);return pe(i,$g,"simulateContract")({abi:e,address:t,functionName:p,args:v,...E})}}})),h&&(c.createEventFilter=new Proxy({},{get(y,p){return(...b)=>{const v=e.find(P=>P.type==="event"&&P.name===p),{args:E,options:S}=Us(b,v);return pe(i,sh,"createContractEventFilter")({abi:e,address:t,eventName:p,args:E,...S})}}}),c.getEvents=new Proxy({},{get(y,p){return(...b)=>{const v=e.find(P=>P.type==="event"&&P.name===p),{args:E,options:S}=Us(b,v);return pe(i,Nh,"getContractEvents")({abi:e,address:t,eventName:p,args:E,...S})}}}),c.watchEvent=new Proxy({},{get(y,p){return(...b)=>{const v=e.find(P=>P.type==="event"&&P.name===p),{args:E,options:S}=Us(b,v);return pe(i,Wg,"watchContractEvent")({abi:e,address:t,eventName:p,args:E,...S})}}}))),a&&l&&(c.write=new Proxy({},{get(y,p){return(...b)=>{const{args:v,options:E}=oo(b);return pe(o,zh,"writeContract")({abi:e,address:t,functionName:p,args:v,...E})}}})),(s||a)&&l&&(c.estimateGas=new Proxy({},{get(y,p){return(...b)=>{const{args:v,options:E}=oo(b);return pe(i??o,lg,"estimateContractGas")({abi:e,address:t,functionName:p,args:v,...E,account:E.account??o.account})}}})),c.address=t,c.abi=e,c}function oo(e){const t=e.length&&Array.isArray(e[0]),r=t?e[0]:[],n=(t?e[1]:e[0])??{};return{args:r,options:n}}function Us(e,t){let r=!1;Array.isArray(e[0])?r=!0:e.length===1?r=t.inputs.some(o=>o.indexed):e.length===2&&(r=!0);const n=r?e[0]:void 0,i=(r?e[1]:e[0])??{};return{args:n,options:i}}const Vh={"0x0":"reverted","0x1":"success"};function Kg(e){const t={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(r=>Ci(r)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?zt(e.transactionIndex):null,status:e.status?Vh[e.status]:null,type:e.type?bh[e.type]||e.type:null};return e.blobGasPrice&&(t.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(t.blobGasUsed=BigInt(e.blobGasUsed)),t}const Yg=su("transactionReceipt",Kg),Wh="0x5792579257925792579257925792579257925792579257925792579257925792",Kh=Q(0,{size:32});async function Xg(e,t){const{account:r=e.account,capabilities:n,chain:i=e.chain,experimental_fallback:o,experimental_fallbackDelay:s=32,forceAtomic:a=!1,id:c,version:u="2.0.0"}=t,l=r?He(r):null,h=t.calls.map(y=>{const p=y,b=p.abi?Mn({abi:p.abi,functionName:p.functionName,args:p.args}):p.data;return{data:p.dataSuffix&&b?cr([b,p.dataSuffix]):b,to:p.to,value:p.value?Q(p.value):void 0}});try{const y=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:a,calls:h,capabilities:n,chainId:Q(i.id),from:l==null?void 0:l.address,id:c,version:u}]},{retryCount:0});return typeof y=="string"?{id:y}:y}catch(y){const p=y;if(o&&(p.name==="MethodNotFoundRpcError"||p.name==="MethodNotSupportedRpcError"||p.name==="UnknownRpcError"||p.details.toLowerCase().includes("does not exist / is not available")||p.details.toLowerCase().includes("missing or invalid. request()")||p.details.toLowerCase().includes("did not match any variant of untagged enum")||p.details.toLowerCase().includes("account upgraded to unsupported contract")||p.details.toLowerCase().includes("eip-7702 not supported")||p.details.toLowerCase().includes("unsupported wc_ method"))){if(n&&Object.values(n).some(P=>!P.optional)){const P="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new xn(new z(P,{details:P}))}if(a&&h.length>1){const S="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new An(new z(S,{details:S}))}const b=[];for(const S of h){const P=Zo(e,{account:l,chain:i,data:S.data,to:S.to,value:S.value?yt(S.value):void 0});b.push(P),s>0&&await new Promise(A=>setTimeout(A,s))}const v=await Promise.allSettled(b);if(v.every(S=>S.status==="rejected"))throw v[0].reason;const E=v.map(S=>S.status==="fulfilled"?S.value:Kh);return{id:cr([...E,Q(i.id,{size:32}),Wh])}}throw qh(y,{...t,account:l,chain:t.chain})}}async function Yh(e,t){async function r(l){if(l.endsWith(Wh.slice(2))){const y=Ir(hc(l,-64,-32)),p=hc(l,0,-64).slice(2).match(/.{1,64}/g),b=await Promise.all(p.map(E=>Kh.slice(2)!==E?e.request({method:"eth_getTransactionReceipt",params:[`0x${E}`]},{dedupe:!0}):void 0)),v=b.some(E=>E===null)?100:b.every(E=>(E==null?void 0:E.status)==="0x1")?200:b.every(E=>(E==null?void 0:E.status)==="0x0")?500:600;return{atomic:!1,chainId:zt(y),receipts:b.filter(Boolean),status:v,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[l]})}const{atomic:n=!1,chainId:i,receipts:o,version:s="2.0.0",...a}=await r(t.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:i?zt(i):void 0,receipts:(o==null?void 0:o.map(l=>({...l,blockNumber:yt(l.blockNumber),gasUsed:yt(l.gasUsed),status:Vh[l.status]})))??[],statusCode:u,status:c,version:s}}async function Jg(e,t){const{id:r,pollingInterval:n=e.pollingInterval,status:i=({statusCode:y})=>y>=200,timeout:o=6e4}=t,s=lt(["waitForCallsStatus",e.uid,r]),{promise:a,resolve:c,reject:u}=Mh();let l;const h=Sc(s,{resolve:c,reject:u},y=>{const p=Dh(async()=>{const b=v=>{clearTimeout(l),p(),v(),h()};try{const v=await Yh(e,{id:r});if(!i(v))return;b(()=>y.resolve(v))}catch(v){b(()=>y.reject(v))}},{interval:n,emitOnBegin:!0});return p});return l=o?setTimeout(()=>{h(),clearTimeout(l),u(new Qg({id:r}))},o):void 0,await a}class Qg extends z{constructor({id:t}){super(`Timed out while waiting for call bundle with id "${t}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}const Tc=256;let so=Tc,ao;function Xh(e=11){if(!ao||so+e>Tc*2){ao="",so=0;for(let t=0;t<Tc;t++)ao+=(256+Math.random()*256|0).toString(16).substring(1)}return ao.substring(so,so+++e)}function Zg(e){const{batch:t,chain:r,ccipRead:n,key:i="base",name:o="Base Client",type:s="base"}=e,a=(r==null?void 0:r.blockTime)??12e3,c=Math.min(Math.max(Math.floor(a/2),500),4e3),u=e.pollingInterval??c,l=e.cacheTime??u,h=e.account?He(e.account):void 0,{config:y,request:p,value:b}=e.transport({chain:r,pollingInterval:u}),v={...y,...b},E={account:h,batch:t,cacheTime:l,ccipRead:n,chain:r,key:i,name:o,pollingInterval:u,request:p,transport:v,type:s,uid:Xh()};function S(P){return A=>{const w=A(P);for(const T in E)delete w[T];const B={...P,...w};return Object.assign(B,{extend:S(B)})}}return Object.assign(E,{extend:S(E)})}const co=new Go(8192);function e1(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(co.get(r))return co.get(r);const n=e().finally(()=>co.delete(r));return co.set(r,n),n}function t1(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0}={}){return new Promise((i,o)=>{const s=async({count:a=0}={})=>{const c=async({error:u})=>{const l=typeof t=="function"?t({count:a,error:u}):t;l&&await Pc(l),s({count:a+1})};try{const u=await e();i(u)}catch(u){if(a<r&&await n({count:a,error:u}))return c({error:u});o(u)}};s()})}function r1(e,t={}){return async(r,n={})=>{var h;const{dedupe:i=!1,methods:o,retryDelay:s=150,retryCount:a=3,uid:c}={...t,...n},{method:u}=r;if((h=o==null?void 0:o.exclude)!=null&&h.includes(u))throw new Mr(new Error("method not supported"),{method:u});if(o!=null&&o.include&&!o.include.includes(u))throw new Mr(new Error("method not supported"),{method:u});const l=i?Ho(`${c}.${lt(r)}`):void 0;return e1(()=>t1(async()=>{try{return await e(r)}catch(y){const p=y;switch(p.code){case pi.code:throw new pi(p);case yi.code:throw new yi(p);case mi.code:throw new mi(p,{method:r.method});case bi.code:throw new bi(p);case Vr.code:throw new Vr(p);case _n.code:throw new _n(p);case gi.code:throw new gi(p);case wi.code:throw new wi(p);case vi.code:throw new vi(p);case Mr.code:throw new Mr(p,{method:r.method});case En.code:throw new En(p);case _i.code:throw new _i(p);case yn.code:throw new yn(p);case Ei.code:throw new Ei(p);case xi.code:throw new xi(p);case Ai.code:throw new Ai(p);case Si.code:throw new Si(p);case Pi.code:throw new Pi(p);case xn.code:throw new xn(p);case Ti.code:throw new Ti(p);case Ii.code:throw new Ii(p);case Bi.code:throw new Bi(p);case ki.code:throw new ki(p);case Oi.code:throw new Oi(p);case An.code:throw new An(p);case 5e3:throw new yn(p);default:throw y instanceof z?y:new kb(p)}}},{delay:({count:y,error:p})=>{var b;if(p&&p instanceof pn){const v=(b=p==null?void 0:p.headers)==null?void 0:b.get("Retry-After");if(v!=null&&v.match(/\d/))return Number.parseInt(v)*1e3}return~~(1<<y)*s},retryCount:a,shouldRetry:({error:y})=>n1(y)}),{enabled:i,id:l})}}function n1(e){return"code"in e&&typeof e.code=="number"?e.code===-1||e.code===En.code||e.code===Vr.code:e instanceof pn&&e.status?e.status===403||e.status===408||e.status===413||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504:!0}function Jh({key:e,methods:t,name:r,request:n,retryCount:i=3,retryDelay:o=150,timeout:s,type:a},c){const u=Xh();return{config:{key:e,methods:t,name:r,request:n,retryCount:i,retryDelay:o,timeout:s,type:a},request:r1(n,{methods:t,retryCount:i,retryDelay:o,uid:u}),value:c}}function bf(e,t={}){const{key:r="custom",methods:n,name:i="Custom Provider",retryDelay:o}=t;return({retryCount:s})=>Jh({key:r,methods:n,name:i,request:e.request.bind(e),retryCount:t.retryCount??s,retryDelay:o,type:"custom"})}class i1 extends z{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}function o1(e,{errorInstance:t=new Error("timed out"),timeout:r,signal:n}){return new Promise((i,o)=>{(async()=>{let s;try{const a=new AbortController;r>0&&(s=setTimeout(()=>{n&&a.abort()},r)),i(await e({signal:(a==null?void 0:a.signal)||null}))}catch(a){(a==null?void 0:a.name)==="AbortError"&&o(t),o(a)}finally{clearTimeout(s)}})()})}function s1(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const gf=s1();function a1(e,t={}){return{async request(r){var h;const{body:n,onRequest:i=t.onRequest,onResponse:o=t.onResponse,timeout:s=t.timeout??1e4}=r,a={...t.fetchOptions??{},...r.fetchOptions??{}},{headers:c,method:u,signal:l}=a;try{const y=await o1(async({signal:b})=>{const v={...a,body:Array.isArray(n)?lt(n.map(A=>({jsonrpc:"2.0",id:A.id??gf.take(),...A}))):lt({jsonrpc:"2.0",id:n.id??gf.take(),...n}),headers:{"Content-Type":"application/json",...c},method:u||"POST",signal:l||(s>0?b:null)},E=new Request(e,v),S=await(i==null?void 0:i(E,v))??{...v,url:e};return await fetch(S.url??e,S)},{errorInstance:new af({body:n,url:e}),timeout:s,signal:!0});o&&await o(y);let p;if((h=y.headers.get("Content-Type"))!=null&&h.startsWith("application/json"))p=await y.json();else{p=await y.text();try{p=JSON.parse(p||"{}")}catch(b){if(y.ok)throw b;p={error:p}}}if(!y.ok)throw new pn({body:n,details:lt(p.error)||y.statusText,headers:y.headers,status:y.status,url:e});return p}catch(y){throw y instanceof pn||y instanceof af?y:new pn({body:n,cause:y,url:e})}}}}function c1(e,t={}){const{batch:r,fetchOptions:n,key:i="http",methods:o,name:s="HTTP JSON-RPC",onFetchRequest:a,onFetchResponse:c,retryDelay:u,raw:l}=t;return({chain:h,retryCount:y,timeout:p})=>{const{batchSize:b=1e3,wait:v=0}=typeof r=="object"?r:{},E=t.retryCount??y,S=p??t.timeout??1e4,P=h==null?void 0:h.rpcUrls.default.http[0];if(!P)throw new i1;const A=a1(P,{fetchOptions:n,onRequest:a,onResponse:c,timeout:S});return Jh({key:i,methods:o,name:s,async request({method:w,params:B}){const T={method:w,params:B},{schedule:L}=Hh({id:P,wait:v,shouldSplitBatch(Z){return Z.length>b},fn:Z=>A.request({body:Z}),sort:(Z,oe)=>Z.id-oe.id}),D=async Z=>r?L(Z):[await A.request({body:Z})],[{error:C,result:X}]=await D(T);if(l)return{error:C,result:X};if(C)throw new nu({body:T,error:C,url:P});return X},retryCount:E,retryDelay:u,timeout:S,type:"http"},{fetchOptions:n,url:P})}}function At(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}class u1 extends z{constructor({domain:t}){super(`Invalid domain "${lt(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class f1 extends z{constructor({primaryType:t,types:r}){super(`Invalid primary type \`${t}\` must be one of \`${JSON.stringify(Object.keys(r))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class l1 extends z{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function d1(e){const{domain:t,message:r,primaryType:n,types:i}=e,o=(c,u)=>{const l={...u};for(const h of c){const{name:y,type:p}=h;p==="address"&&(l[y]=l[y].toLowerCase())}return l},s=i.EIP712Domain?t?o(i.EIP712Domain,t):{}:{},a=(()=>{if(n!=="EIP712Domain")return o(i[n],r)})();return lt({domain:s,message:a,primaryType:n,types:i})}function h1(e){const{domain:t,message:r,primaryType:n,types:i}=e,o=(s,a)=>{for(const c of s){const{name:u,type:l}=c,h=a[u],y=l.match(ih);if(y&&(typeof h=="number"||typeof h=="bigint")){const[v,E,S]=y;Q(h,{signed:E==="int",size:Number.parseInt(S)/8})}if(l==="address"&&typeof h=="string"&&!Me(h))throw new ct({address:h});const p=l.match(jm);if(p){const[v,E]=p;if(E&&Re(h)!==Number.parseInt(E))throw new Yy({expectedSize:Number.parseInt(E),givenSize:Re(h)})}const b=i[l];b&&(y1(l),o(b,h))}};if(i.EIP712Domain&&t){if(typeof t!="object")throw new u1({domain:t});o(i.EIP712Domain,t)}if(n!=="EIP712Domain")if(i[n])o(i[n],r);else throw new f1({primaryType:n,types:i})}function p1({domain:e}){return[typeof(e==null?void 0:e.name)=="string"&&{name:"name",type:"string"},(e==null?void 0:e.version)&&{name:"version",type:"string"},(typeof(e==null?void 0:e.chainId)=="number"||typeof(e==null?void 0:e.chainId)=="bigint")&&{name:"chainId",type:"uint256"},(e==null?void 0:e.verifyingContract)&&{name:"verifyingContract",type:"address"},(e==null?void 0:e.salt)&&{name:"salt",type:"bytes32"}].filter(Boolean)}function y1(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new l1({type:e})}function m1(e){const{authorizationList:t}=e;if(t)for(const r of t){const{chainId:n}=r,i=r.address;if(!Me(i))throw new ct({address:i});if(n<0)throw new Qo({chainId:n})}gu(e)}function b1(e){const{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new Bh;for(const r of t){const n=Re(r),i=zt(vn(r,0,1));if(n!==32)throw new ag({hash:r,size:n});if(i!==Ih)throw new cg({hash:r,version:i})}}gu(e)}function gu(e){const{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:i}=e;if(t<=0)throw new Qo({chainId:t});if(i&&!Me(i))throw new ct({address:i});if(n&&n>Jo)throw new Wr({maxFeePerGas:n});if(r&&n&&r>n)throw new Ri({maxFeePerGas:n,maxPriorityFeePerGas:r})}function g1(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:o}=e;if(t<=0)throw new Qo({chainId:t});if(o&&!Me(o))throw new ct({address:o});if(r||i)throw new z("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Jo)throw new Wr({maxFeePerGas:n})}function w1(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:o}=e;if(o&&!Me(o))throw new ct({address:o});if(typeof t<"u"&&t<=0)throw new Qo({chainId:t});if(r||i)throw new z("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Jo)throw new Wr({maxFeePerGas:n})}function es(e){if(!e||e.length===0)return[];const t=[];for(let r=0;r<e.length;r++){const{address:n,storageKeys:i}=e[r];for(let o=0;o<i.length;o++)if(i[o].length-2!==64)throw new _b({storageKey:i[o]});if(!Me(n,{strict:!1}))throw new ct({address:n});t.push([n,i])}return t}function v1(e,t){const r=Oh(e);return r==="eip1559"?x1(e,t):r==="eip2930"?A1(e,t):r==="eip4844"?E1(e,t):r==="eip7702"?_1(e,t):S1(e,t)}function _1(e,t){const{authorizationList:r,chainId:n,gas:i,nonce:o,to:s,value:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:l,data:h}=e;m1(e);const y=es(l),p=P1(r);return Wt(["0x04",Or([Q(n),o?Q(o):"0x",u?Q(u):"0x",c?Q(c):"0x",i?Q(i):"0x",s??"0x",a?Q(a):"0x",h??"0x",y,p,...Wi(e,t)])])}function E1(e,t){const{chainId:r,gas:n,nonce:i,to:o,value:s,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:l,data:h}=e;b1(e);let y=e.blobVersionedHashes,p=e.sidecars;if(e.blobs&&(typeof y>"u"||typeof p>"u")){const A=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(T=>at(T)),w=e.kzg,B=uu({blobs:A,kzg:w});if(typeof y>"u"&&(y=Sh({commitments:B})),typeof p>"u"){const T=fu({blobs:A,commitments:B,kzg:w});p=kh({blobs:A,commitments:B,proofs:T})}}const b=es(l),v=[Q(r),i?Q(i):"0x",u?Q(u):"0x",c?Q(c):"0x",n?Q(n):"0x",o??"0x",s?Q(s):"0x",h??"0x",b,a?Q(a):"0x",y??[],...Wi(e,t)],E=[],S=[],P=[];if(p)for(let A=0;A<p.length;A++){const{blob:w,commitment:B,proof:T}=p[A];E.push(w),S.push(B),P.push(T)}return Wt(["0x03",Or(p?[v,E,S,P]:v)])}function x1(e,t){const{chainId:r,gas:n,nonce:i,to:o,value:s,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:u,data:l}=e;gu(e);const h=es(u),y=[Q(r),i?Q(i):"0x",c?Q(c):"0x",a?Q(a):"0x",n?Q(n):"0x",o??"0x",s?Q(s):"0x",l??"0x",h,...Wi(e,t)];return Wt(["0x02",Or(y)])}function A1(e,t){const{chainId:r,gas:n,data:i,nonce:o,to:s,value:a,accessList:c,gasPrice:u}=e;g1(e);const l=es(c),h=[Q(r),o?Q(o):"0x",u?Q(u):"0x",n?Q(n):"0x",s??"0x",a?Q(a):"0x",i??"0x",l,...Wi(e,t)];return Wt(["0x01",Or(h)])}function S1(e,t){const{chainId:r=0,gas:n,data:i,nonce:o,to:s,value:a,gasPrice:c}=e;w1(e);let u=[o?Q(o):"0x",c?Q(c):"0x",n?Q(n):"0x",s??"0x",a?Q(a):"0x",i??"0x"];if(t){const l=(()=>{if(t.v>=35n)return(t.v-35n)/2n>0?t.v:27n+(t.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);const p=27n+(t.v===27n?0n:1n);if(t.v!==p)throw new wb({v:t.v});return p})(),h=Ir(t.r),y=Ir(t.s);u=[...u,Q(l),h==="0x00"?"0x":h,y==="0x00"?"0x":y]}else r>0&&(u=[...u,Q(r),"0x","0x"]);return Or(u)}function Wi(e,t){const r=t??e,{v:n,yParity:i}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof i>"u")return[];const o=Ir(r.r),s=Ir(r.s);return[typeof i=="number"?i?Q(1):"0x":n===0n?"0x":n===1n?Q(1):n===27n?"0x":Q(1),o==="0x00"?"0x":o,s==="0x00"?"0x":s]}function P1(e){if(!e||e.length===0)return[];const t=[];for(const r of e){const{chainId:n,nonce:i,...o}=r,s=r.address;t.push([n?qt(n):"0x",s,i?qt(i):"0x",...Wi({},o)])}return t}const T1=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Qh=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),I1=Qh.map(e=>(9*e+5)%16),Zh=(()=>{const r=[[Qh],[I1]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(o=>T1[o]));return r})(),ep=Zh[0],tp=Zh[1],rp=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>Uint8Array.from(e)),B1=ep.map((e,t)=>e.map(r=>rp[t][r])),k1=tp.map((e,t)=>e.map(r=>rp[t][r])),O1=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),R1=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function wf(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}const uo=new Uint32Array(16);let np=class extends _h{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:r,h2:n,h3:i,h4:o}=this;return[t,r,n,i,o]}set(t,r,n,i,o){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=o|0}process(t,r){for(let p=0;p<16;p++,r+=4)uo[p]=t.getUint32(r,!0);let n=this.h0|0,i=n,o=this.h1|0,s=o,a=this.h2|0,c=a,u=this.h3|0,l=u,h=this.h4|0,y=h;for(let p=0;p<5;p++){const b=4-p,v=O1[p],E=R1[p],S=ep[p],P=tp[p],A=B1[p],w=k1[p];for(let B=0;B<16;B++){const T=io(n+wf(p,o,a,u)+uo[S[B]]+v,A[B])+h|0;n=h,h=u,u=io(a,10)|0,a=o,o=T}for(let B=0;B<16;B++){const T=io(i+wf(b,s,c,l)+uo[P[B]]+E,w[B])+y|0;i=y,y=l,l=io(c,10)|0,c=s,s=T}}this.set(this.h1+a+l|0,this.h2+u+y|0,this.h3+h+i|0,this.h4+n+s|0,this.h0+o+c|0)}roundClean(){kr(uo)}destroy(){this.destroyed=!0,kr(this.buffer),this.set(0,0,0,0,0)}};const C1=jo(()=>new np),F1=np,U1=C1,N1=Object.freeze(Object.defineProperty({__proto__:null,RIPEMD160:F1,ripemd160:U1},Symbol.toStringTag,{value:"Module"}));async function $1(e,{chain:t}){const{id:r,name:n,nativeCurrency:i,rpcUrls:o,blockExplorers:s}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:Q(r),chainName:n,nativeCurrency:i,rpcUrls:o.default.http,blockExplorerUrls:s?Object.values(s).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}function L1(e,t){const{abi:r,args:n,bytecode:i,...o}=t,s=mu({abi:r,args:n,bytecode:i});return Zo(e,{...o,...o.authorizationList?{to:null}:{},data:s})}async function M1(e){var r;return((r=e.account)==null?void 0:r.type)==="local"?[e.account.address]:(await e.request({method:"eth_accounts"},{dedupe:!0})).map(n=>ji(n))}async function H1(e,t={}){const{account:r=e.account,chainId:n}=t,i=r?He(r):void 0,o=n?[i==null?void 0:i.address,[Q(n)]]:[i==null?void 0:i.address],s=await e.request({method:"wallet_getCapabilities",params:o}),a={};for(const[c,u]of Object.entries(s)){a[Number(c)]={};for(let[l,h]of Object.entries(u))l==="addSubAccount"&&(l="unstable_addSubAccount"),a[Number(c)][l]=h}return typeof n=="number"?a[n]:a}async function D1(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}async function ip(e,t){var c;const{account:r=e.account,chainId:n,nonce:i}=t;if(!r)throw new Jr({docsPath:"/docs/eip7702/prepareAuthorization"});const o=He(r),s=(()=>{if(t.executor)return t.executor==="self"?t.executor:He(t.executor)})(),a={address:t.contractAddress??t.address,chainId:n,nonce:i};return typeof a.chainId>"u"&&(a.chainId=((c=e.chain)==null?void 0:c.id)??await pe(e,Vi,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await pe(e,vh,"getTransactionCount")({address:o.address,blockTag:"pending"}),(s==="self"||s!=null&&s.address&&pu(s.address,o.address))&&(a.nonce+=1)),a}async function j1(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>Mm(r))}async function q1(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}async function G1(e,t){const{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]})}async function z1(e,t){const{account:r=e.account}=t;if(!r)throw new Jr({docsPath:"/docs/eip7702/signAuthorization"});const n=He(r);if(!n.signAuthorization)throw new _o({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});const i=await ip(e,t);return n.signAuthorization(i)}async function V1(e,{account:t=e.account,message:r}){if(!t)throw new Jr({docsPath:"/docs/actions/wallet/signMessage"});const n=He(t);if(n.signMessage)return n.signMessage({message:r});const i=typeof r=="string"?Ho(r):r.raw instanceof Uint8Array?qt(r.raw):r.raw;return e.request({method:"personal_sign",params:[i,n.address]},{retryCount:0})}async function W1(e,t){var u,l,h,y;const{account:r=e.account,chain:n=e.chain,...i}=t;if(!r)throw new Jr({docsPath:"/docs/actions/wallet/signTransaction"});const o=He(r);zi({account:o,...t});const s=await pe(e,Vi,"getChainId")({});n!==null&&jh({currentChainId:s,chain:n});const a=(n==null?void 0:n.formatters)||((u=e.chain)==null?void 0:u.formatters),c=((l=a==null?void 0:a.transactionRequest)==null?void 0:l.format)||Xo;return o.signTransaction?o.signTransaction({...i,chainId:s},{serializer:(y=(h=e.chain)==null?void 0:h.serializers)==null?void 0:y.transaction}):await e.request({method:"eth_signTransaction",params:[{...c(i),chainId:Q(s),from:o.address}]},{retryCount:0})}async function K1(e,t){const{account:r=e.account,domain:n,message:i,primaryType:o}=t;if(!r)throw new Jr({docsPath:"/docs/actions/wallet/signTypedData"});const s=He(r),a={EIP712Domain:p1({domain:n}),...t.types};if(h1({domain:n,message:i,primaryType:o,types:a}),s.signTypedData)return s.signTypedData({domain:n,message:i,primaryType:o,types:a});const c=d1({domain:n,message:i,primaryType:o,types:a});return e.request({method:"eth_signTypedData_v4",params:[s.address,c]},{retryCount:0})}async function Y1(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:Q(t)}]},{retryCount:0})}async function X1(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}function J1(e){return{addChain:t=>$1(e,t),deployContract:t=>L1(e,t),getAddresses:()=>M1(e),getCallsStatus:t=>Yh(e,t),getCapabilities:t=>H1(e,t),getChainId:()=>Vi(e),getPermissions:()=>D1(e),prepareAuthorization:t=>ip(e,t),prepareTransactionRequest:t=>hu(e,t),requestAddresses:()=>j1(e),requestPermissions:t=>q1(e,t),sendCalls:t=>Xg(e,t),sendRawTransaction:t=>Gh(e,t),sendTransaction:t=>Zo(e,t),showCallsStatus:t=>G1(e,t),signAuthorization:t=>z1(e,t),signMessage:t=>V1(e,t),signTransaction:t=>W1(e,t),signTypedData:t=>K1(e,t),switchChain:t=>Y1(e,t),waitForCallsStatus:t=>Jg(e,t),watchAsset:t=>X1(e,t),writeContract:t=>zh(e,t)}}function Ns(e){const{key:t="wallet",name:r="Wallet Client",transport:n}=e;return Zg({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(J1)}const Eo={mainnet:{orderbook:"https://api.garden.finance",auth:"https://api.garden.finance/auth",quote:"https://api.garden.finance/quote",info:"https://api.garden.finance/info",evmRelay:"https://api.garden.finance/relayer",solanaRelay:"https://solana-relayer.garden.finance/",starknetRelay:"https://api.garden.finance/starknet"},testnet:{orderbook:"https://testnet.api.garden.finance",auth:"https://testnet.api.garden.finance/auth",quote:"https://testnet.api.garden.finance/quote",info:"https://testnet.api.garden.finance/info",evmRelay:"https://testnet.api.garden.finance/relayer",solanaRelay:"https://solana-relay.garden.finance",starknetRelay:"https://testnet.api.garden.finance/starknet"},localnet:{orderbook:"",auth:"",quote:"",info:"",evmRelay:"",starknetRelay:"",solanaRelay:""}},Ui={[J.Network.MAINNET]:{chainId:"0x534e5f4d41494e",nodeUrl:"https://starknet-mainnet.public.blastapi.io/rpc/v0_8"},[J.Network.TESTNET]:{chainId:"0x534e5f5345504f4c4941",nodeUrl:"https://starknet-sepolia.public.blastapi.io/rpc/v0_8"},[J.Network.LOCALNET]:{chainId:"",nodeUrl:""}},Ic={[J.Network.MAINNET]:"9cBuPNiHXiMNg3Fin8xLCGJQBTXjYQTFtyaFQv2uiM1H",[J.Network.TESTNET]:"ANUVKxeqaec3bf4DVPqLTnG1PT3Fng56wPcE7LXAb46Q",[J.Network.LOCALNET]:"AKnL4NNf3DGWZJS6cPknBuEGnVsV4A4m5tgebLHaRSZ9"},op={mainnet:"2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",staging:"6eksgdCnSjUaGQWZ6iYvauv1qzvYPF33RTGTM1ZuyENx"},vf={chain:me.SupportedAssets.mainnet.base_cbBTC.chain,asset:me.SupportedAssets.mainnet.base_cbBTC.atomicSwapAddress};function Bc(e){const t=typeof e=="string"?e:e.environment,r=t===J.Environment.MAINNET?Eo.mainnet:J.Environment.TESTNET?Eo.testnet:Eo.localnet;return{api:typeof e=="string"?r:{...r,...e},environment:t}}function kc(e){return typeof e=="string"&&(e=Buffer.from(e,"hex")),e.length===32?e:e.subarray(1,33)}function $r(e,t){if(!e)throw new Error(t)}function Q1(e){return Buffer.concat([Uint8Array.from([192]),Z1(e)])}function Z1(e){const t=qu.encodingLength(e.length),r=Buffer.allocUnsafe(t);return qu.encode(e.length,r),Buffer.concat([r,e])}function ew(e,t){if(e.compare(t)>0){const r=e;e=t,t=r}return[e,t]}const vr=e=>e.length===64?e:e.slice(2),tw=e=>{if(!e)return!1;try{const t=Buffer.from(e,"hex");return Gr.isPoint(t)}catch{return!1}},Oc=(e,t,r,n)=>e+":"+t.toLowerCase()+"::"+r+":"+n.toLowerCase();function rw(e,t){if(!e)return!1;const r=t===J.Environment.MAINNET?ge.networks.bitcoin:t===J.Environment.TESTNET?ge.networks.testnet:ge.networks.regtest;if(!r)return!1;ge.initEccLib(Gr);try{return ge.address.toOutputScript(e,r),!0}catch{return!1}}const nw=e=>{switch(e){case J.Environment.MAINNET:return Hr.BitcoinNetwork.Mainnet;case J.Environment.TESTNET:return Hr.BitcoinNetwork.Testnet;case J.Environment.LOCALNET:return Hr.BitcoinNetwork.Regtest;default:throw new Error(`Invalid bitcoin network ${e}`)}},iw=e=>{const t=e.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(t)},ow=e=>{if(typeof e=="object"&&"r"in e&&"s"in e)return J.Ok([e.r.toString(),e.s.toString()]);if(Array.isArray(e)){const t=e.map(r=>typeof r=="string"&&r.startsWith("0x")&&iw(r)?BigInt(r).toString():r);return J.Ok(t)}return J.Err("Invalid signature format")};var Se=(e=>(e.Created="Created",e.Matched="Matched",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.CounterPartyInitiateDetected="CounterPartyInitiateDetected",e.CounterPartyInitiated="CounterPartyInitiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.CounterPartyRedeemDetected="CounterPartyRedeemDetected",e.CounterPartyRedeemed="CounterPartyRedeemed",e.Completed="Completed",e.CounterPartySwapExpired="CounterPartySwapExpired",e.Expired="Expired",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.CounterPartyRefundDetected="CounterPartyRefundDetected",e.CounterPartyRefunded="CounterPartyRefunded",e.Cancelled="Cancelled",e.DeadLineExceeded="DeadLineExceeded",e))(Se||{}),Ie=(e=>(e.Idle="Idle",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.Expired="Expired",e))(Ie||{});const wu=(e,t,r)=>{const n=Rc(e.source_swap,t),i=Rc(e.destination_swap,r);if(i===Ie.RedeemDetected)return Se.RedeemDetected;if(i===Ie.Redeemed)return Se.Redeemed;if(n===Ie.Refunded)return Se.Refunded;if(n===Ie.RefundDetected)return Se.RefundDetected;if(i===Ie.Expired)return Se.CounterPartySwapExpired;if(n===Ie.Expired)return Se.Expired;if(i===Ie.Refunded)return Se.CounterPartyRefunded;if(i===Ie.RefundDetected)return Se.CounterPartyRefundDetected;const o=Number(e.create_order.additional_data.deadline);return i===Ie.Initiated?Se.CounterPartyInitiated:i===Ie.InitiateDetected?Se.CounterPartyInitiateDetected:Ni(o,12)?Se.DeadLineExceeded:n===Ie.Initiated?Se.Initiated:Ni(o,1)?Se.DeadLineExceeded:n===Ie.InitiateDetected?Se.InitiateDetected:n===Ie.Redeemed?Se.CounterPartyRedeemed:n===Ie.RedeemDetected?Se.CounterPartyRedeemDetected:Se.Matched},Rc=(e,t)=>{if(e.redeem_tx_hash)return Number(e.redeem_block_number)?Ie.Redeemed:Ie.RedeemDetected;if(e.refund_tx_hash)return Number(e.refund_block_number)?Ie.Refunded:Ie.RefundDetected;if(Number(e.initiate_block_number)){const r=Number(e.initiate_block_number)+e.timelock;if(t>r)return Ie.Expired}return e.initiate_tx_hash?Number(e.initiate_block_number)?Ie.Initiated:Ie.InitiateDetected:Ie.Idle},sw=(e,t,r)=>{const n=wu(e,t,r);return vu(n)},vu=e=>{switch(e){case Se.Matched:return Te.Initiate;case Se.CounterPartyInitiated:case Se.CounterPartyInitiateDetected:case Se.RedeemDetected:return Te.Redeem;case Se.Expired:return Te.Refund;default:return Te.Idle}},Ni=(e,t=0)=>{const r=Date.now(),n=e*1e3+t*36e5;return r>=n},aw=e=>e.filter(t=>!sp(t)),sp=e=>{const{source_swap:t,create_order:r}=e,{initiate_tx_hash:n,initiate_block_number:i}=t,{deadline:o}=r.additional_data;return n&&Number(i)?!1:n&&!Number(i)?Ni(Number(o),12):n?!1:Ni(Number(o),1)},cw=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),uw=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),fw=Buffer.concat([cw,uw]),lw=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),_f={failedToCreateInternalPubkey:"failed to create internal pubkey"};function dw(){const e=_d.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),t=Gr.pointMultiply(Buffer.concat([Buffer.from("04","hex"),fw]),e);if(!t)throw new Error(_f.failedToCreateInternalPubkey);const r=Gr.pointAdd(lw,t);if(!r)throw new Error(_f.failedToCreateInternalPubkey);return kc(Buffer.from(r))}var De=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function hw(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function _u(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}),r}var Be={},Ze={},Bt={},ts={};ts.byteLength=mw;ts.toByteArray=gw;ts.fromByteArray=_w;var jt=[],Et=[],pw=typeof Uint8Array<"u"?Uint8Array:Array,$s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var nn=0,yw=$s.length;nn<yw;++nn)jt[nn]=$s[nn],Et[$s.charCodeAt(nn)]=nn;Et[45]=62;Et[95]=63;function ap(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function mw(e){var t=ap(e),r=t[0],n=t[1];return(r+n)*3/4-n}function bw(e,t,r){return(t+r)*3/4-r}function gw(e){var t,r=ap(e),n=r[0],i=r[1],o=new pw(bw(e,n,i)),s=0,a=i>0?n-4:n,c;for(c=0;c<a;c+=4)t=Et[e.charCodeAt(c)]<<18|Et[e.charCodeAt(c+1)]<<12|Et[e.charCodeAt(c+2)]<<6|Et[e.charCodeAt(c+3)],o[s++]=t>>16&255,o[s++]=t>>8&255,o[s++]=t&255;return i===2&&(t=Et[e.charCodeAt(c)]<<2|Et[e.charCodeAt(c+1)]>>4,o[s++]=t&255),i===1&&(t=Et[e.charCodeAt(c)]<<10|Et[e.charCodeAt(c+1)]<<4|Et[e.charCodeAt(c+2)]>>2,o[s++]=t>>8&255,o[s++]=t&255),o}function ww(e){return jt[e>>18&63]+jt[e>>12&63]+jt[e>>6&63]+jt[e&63]}function vw(e,t,r){for(var n,i=[],o=t;o<r;o+=3)n=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(e[o+2]&255),i.push(ww(n));return i.join("")}function _w(e){for(var t,r=e.length,n=r%3,i=[],o=16383,s=0,a=r-n;s<a;s+=o)i.push(vw(e,s,s+o>a?a:s+o));return n===1?(t=e[r-1],i.push(jt[t>>2]+jt[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push(jt[t>>10]+jt[t>>4&63]+jt[t<<2&63]+"=")),i.join("")}var Eu={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Eu.read=function(e,t,r,n,i){var o,s,a=i*8-n-1,c=(1<<a)-1,u=c>>1,l=-7,h=r?i-1:0,y=r?-1:1,p=e[t+h];for(h+=y,o=p&(1<<-l)-1,p>>=-l,l+=a;l>0;o=o*256+e[t+h],h+=y,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=n;l>0;s=s*256+e[t+h],h+=y,l-=8);if(o===0)o=1-u;else{if(o===c)return s?NaN:(p?-1:1)*(1/0);s=s+Math.pow(2,n),o=o-u}return(p?-1:1)*s*Math.pow(2,o-n)};Eu.write=function(e,t,r,n,i,o){var s,a,c,u=o*8-i-1,l=(1<<u)-1,h=l>>1,y=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,b=n?1:-1,v=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),s+h>=1?t+=y/c:t+=y*Math.pow(2,1-h),t*c>=2&&(s++,c/=2),s+h>=l?(a=0,s=l):s+h>=1?(a=(t*c-1)*Math.pow(2,i),s=s+h):(a=t*Math.pow(2,h-1)*Math.pow(2,i),s=0));i>=8;e[r+p]=a&255,p+=b,a/=256,i-=8);for(s=s<<i|a,u+=i;u>0;e[r+p]=s&255,p+=b,s/=256,u-=8);e[r+p-b]|=v*128};/*!
43
+ * The buffer module from node.js, for the browser.
44
+ *
45
+ * @author Feross Aboukhadijeh <https://feross.org>
46
+ * @license MIT
47
+ */(function(e){const t=ts,r=Eu,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=a,e.SlowBuffer=P,e.INSPECT_MAX_BYTES=50;const i=2147483647;e.kMaxLength=i,a.TYPED_ARRAY_SUPPORT=o(),!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 o(){try{const m=new Uint8Array(1),f={foo:function(){return 42}};return Object.setPrototypeOf(f,Uint8Array.prototype),Object.setPrototypeOf(m,f),m.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 s(m){if(m>i)throw new RangeError('The value "'+m+'" is invalid for option "size"');const f=new Uint8Array(m);return Object.setPrototypeOf(f,a.prototype),f}function a(m,f,d){if(typeof m=="number"){if(typeof f=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return h(m)}return c(m,f,d)}a.poolSize=8192;function c(m,f,d){if(typeof m=="string")return y(m,f);if(ArrayBuffer.isView(m))return b(m);if(m==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof m);if(Ne(m,ArrayBuffer)||m&&Ne(m.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ne(m,SharedArrayBuffer)||m&&Ne(m.buffer,SharedArrayBuffer)))return v(m,f,d);if(typeof m=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const x=m.valueOf&&m.valueOf();if(x!=null&&x!==m)return a.from(x,f,d);const R=E(m);if(R)return R;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof m[Symbol.toPrimitive]=="function")return a.from(m[Symbol.toPrimitive]("string"),f,d);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof m)}a.from=function(m,f,d){return c(m,f,d)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function u(m){if(typeof m!="number")throw new TypeError('"size" argument must be of type number');if(m<0)throw new RangeError('The value "'+m+'" is invalid for option "size"')}function l(m,f,d){return u(m),m<=0?s(m):f!==void 0?typeof d=="string"?s(m).fill(f,d):s(m).fill(f):s(m)}a.alloc=function(m,f,d){return l(m,f,d)};function h(m){return u(m),s(m<0?0:S(m)|0)}a.allocUnsafe=function(m){return h(m)},a.allocUnsafeSlow=function(m){return h(m)};function y(m,f){if((typeof f!="string"||f==="")&&(f="utf8"),!a.isEncoding(f))throw new TypeError("Unknown encoding: "+f);const d=A(m,f)|0;let x=s(d);const R=x.write(m,f);return R!==d&&(x=x.slice(0,R)),x}function p(m){const f=m.length<0?0:S(m.length)|0,d=s(f);for(let x=0;x<f;x+=1)d[x]=m[x]&255;return d}function b(m){if(Ne(m,Uint8Array)){const f=new Uint8Array(m);return v(f.buffer,f.byteOffset,f.byteLength)}return p(m)}function v(m,f,d){if(f<0||m.byteLength<f)throw new RangeError('"offset" is outside of buffer bounds');if(m.byteLength<f+(d||0))throw new RangeError('"length" is outside of buffer bounds');let x;return f===void 0&&d===void 0?x=new Uint8Array(m):d===void 0?x=new Uint8Array(m,f):x=new Uint8Array(m,f,d),Object.setPrototypeOf(x,a.prototype),x}function E(m){if(a.isBuffer(m)){const f=S(m.length)|0,d=s(f);return d.length===0||m.copy(d,0,0,f),d}if(m.length!==void 0)return typeof m.length!="number"||wt(m.length)?s(0):p(m);if(m.type==="Buffer"&&Array.isArray(m.data))return p(m.data)}function S(m){if(m>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return m|0}function P(m){return+m!=m&&(m=0),a.alloc(+m)}a.isBuffer=function(f){return f!=null&&f._isBuffer===!0&&f!==a.prototype},a.compare=function(f,d){if(Ne(f,Uint8Array)&&(f=a.from(f,f.offset,f.byteLength)),Ne(d,Uint8Array)&&(d=a.from(d,d.offset,d.byteLength)),!a.isBuffer(f)||!a.isBuffer(d))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(f===d)return 0;let x=f.length,R=d.length;for(let $=0,G=Math.min(x,R);$<G;++$)if(f[$]!==d[$]){x=f[$],R=d[$];break}return x<R?-1:R<x?1:0},a.isEncoding=function(f){switch(String(f).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(f,d){if(!Array.isArray(f))throw new TypeError('"list" argument must be an Array of Buffers');if(f.length===0)return a.alloc(0);let x;if(d===void 0)for(d=0,x=0;x<f.length;++x)d+=f[x].length;const R=a.allocUnsafe(d);let $=0;for(x=0;x<f.length;++x){let G=f[x];if(Ne(G,Uint8Array))$+G.length>R.length?(a.isBuffer(G)||(G=a.from(G)),G.copy(R,$)):Uint8Array.prototype.set.call(R,G,$);else if(a.isBuffer(G))G.copy(R,$);else throw new TypeError('"list" argument must be an Array of Buffers');$+=G.length}return R};function A(m,f){if(a.isBuffer(m))return m.length;if(ArrayBuffer.isView(m)||Ne(m,ArrayBuffer))return m.byteLength;if(typeof m!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof m);const d=m.length,x=arguments.length>2&&arguments[2]===!0;if(!x&&d===0)return 0;let R=!1;for(;;)switch(f){case"ascii":case"latin1":case"binary":return d;case"utf8":case"utf-8":return fe(m).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return d*2;case"hex":return d>>>1;case"base64":return pt(m).length;default:if(R)return x?-1:fe(m).length;f=(""+f).toLowerCase(),R=!0}}a.byteLength=A;function w(m,f,d){let x=!1;if((f===void 0||f<0)&&(f=0),f>this.length||((d===void 0||d>this.length)&&(d=this.length),d<=0)||(d>>>=0,f>>>=0,d<=f))return"";for(m||(m="utf8");;)switch(m){case"hex":return F(this,f,d);case"utf8":case"utf-8":return ee(this,f,d);case"ascii":return ye(this,f,d);case"latin1":case"binary":return ce(this,f,d);case"base64":return te(this,f,d);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Y(this,f,d);default:if(x)throw new TypeError("Unknown encoding: "+m);m=(m+"").toLowerCase(),x=!0}}a.prototype._isBuffer=!0;function B(m,f,d){const x=m[f];m[f]=m[d],m[d]=x}a.prototype.swap16=function(){const f=this.length;if(f%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let d=0;d<f;d+=2)B(this,d,d+1);return this},a.prototype.swap32=function(){const f=this.length;if(f%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let d=0;d<f;d+=4)B(this,d,d+3),B(this,d+1,d+2);return this},a.prototype.swap64=function(){const f=this.length;if(f%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let d=0;d<f;d+=8)B(this,d,d+7),B(this,d+1,d+6),B(this,d+2,d+5),B(this,d+3,d+4);return this},a.prototype.toString=function(){const f=this.length;return f===0?"":arguments.length===0?ee(this,0,f):w.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(f){if(!a.isBuffer(f))throw new TypeError("Argument must be a Buffer");return this===f?!0:a.compare(this,f)===0},a.prototype.inspect=function(){let f="";const d=e.INSPECT_MAX_BYTES;return f=this.toString("hex",0,d).replace(/(.{2})/g,"$1 ").trim(),this.length>d&&(f+=" ... "),"<Buffer "+f+">"},n&&(a.prototype[n]=a.prototype.inspect),a.prototype.compare=function(f,d,x,R,$){if(Ne(f,Uint8Array)&&(f=a.from(f,f.offset,f.byteLength)),!a.isBuffer(f))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof f);if(d===void 0&&(d=0),x===void 0&&(x=f?f.length:0),R===void 0&&(R=0),$===void 0&&($=this.length),d<0||x>f.length||R<0||$>this.length)throw new RangeError("out of range index");if(R>=$&&d>=x)return 0;if(R>=$)return-1;if(d>=x)return 1;if(d>>>=0,x>>>=0,R>>>=0,$>>>=0,this===f)return 0;let G=$-R,le=x-d;const ke=Math.min(G,le),Pe=this.slice(R,$),Oe=f.slice(d,x);for(let ve=0;ve<ke;++ve)if(Pe[ve]!==Oe[ve]){G=Pe[ve],le=Oe[ve];break}return G<le?-1:le<G?1:0};function T(m,f,d,x,R){if(m.length===0)return-1;if(typeof d=="string"?(x=d,d=0):d>2147483647?d=2147483647:d<-2147483648&&(d=-2147483648),d=+d,wt(d)&&(d=R?0:m.length-1),d<0&&(d=m.length+d),d>=m.length){if(R)return-1;d=m.length-1}else if(d<0)if(R)d=0;else return-1;if(typeof f=="string"&&(f=a.from(f,x)),a.isBuffer(f))return f.length===0?-1:L(m,f,d,x,R);if(typeof f=="number")return f=f&255,typeof Uint8Array.prototype.indexOf=="function"?R?Uint8Array.prototype.indexOf.call(m,f,d):Uint8Array.prototype.lastIndexOf.call(m,f,d):L(m,[f],d,x,R);throw new TypeError("val must be string, number or Buffer")}function L(m,f,d,x,R){let $=1,G=m.length,le=f.length;if(x!==void 0&&(x=String(x).toLowerCase(),x==="ucs2"||x==="ucs-2"||x==="utf16le"||x==="utf-16le")){if(m.length<2||f.length<2)return-1;$=2,G/=2,le/=2,d/=2}function ke(Oe,ve){return $===1?Oe[ve]:Oe.readUInt16BE(ve*$)}let Pe;if(R){let Oe=-1;for(Pe=d;Pe<G;Pe++)if(ke(m,Pe)===ke(f,Oe===-1?0:Pe-Oe)){if(Oe===-1&&(Oe=Pe),Pe-Oe+1===le)return Oe*$}else Oe!==-1&&(Pe-=Pe-Oe),Oe=-1}else for(d+le>G&&(d=G-le),Pe=d;Pe>=0;Pe--){let Oe=!0;for(let ve=0;ve<le;ve++)if(ke(m,Pe+ve)!==ke(f,ve)){Oe=!1;break}if(Oe)return Pe}return-1}a.prototype.includes=function(f,d,x){return this.indexOf(f,d,x)!==-1},a.prototype.indexOf=function(f,d,x){return T(this,f,d,x,!0)},a.prototype.lastIndexOf=function(f,d,x){return T(this,f,d,x,!1)};function D(m,f,d,x){d=Number(d)||0;const R=m.length-d;x?(x=Number(x),x>R&&(x=R)):x=R;const $=f.length;x>$/2&&(x=$/2);let G;for(G=0;G<x;++G){const le=parseInt(f.substr(G*2,2),16);if(wt(le))return G;m[d+G]=le}return G}function C(m,f,d,x){return qe(fe(f,m.length-d),m,d,x)}function X(m,f,d,x){return qe(ut(f),m,d,x)}function Z(m,f,d,x){return qe(pt(f),m,d,x)}function oe(m,f,d,x){return qe(j(f,m.length-d),m,d,x)}a.prototype.write=function(f,d,x,R){if(d===void 0)R="utf8",x=this.length,d=0;else if(x===void 0&&typeof d=="string")R=d,x=this.length,d=0;else if(isFinite(d))d=d>>>0,isFinite(x)?(x=x>>>0,R===void 0&&(R="utf8")):(R=x,x=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const $=this.length-d;if((x===void 0||x>$)&&(x=$),f.length>0&&(x<0||d<0)||d>this.length)throw new RangeError("Attempt to write outside buffer bounds");R||(R="utf8");let G=!1;for(;;)switch(R){case"hex":return D(this,f,d,x);case"utf8":case"utf-8":return C(this,f,d,x);case"ascii":case"latin1":case"binary":return X(this,f,d,x);case"base64":return Z(this,f,d,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return oe(this,f,d,x);default:if(G)throw new TypeError("Unknown encoding: "+R);R=(""+R).toLowerCase(),G=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function te(m,f,d){return f===0&&d===m.length?t.fromByteArray(m):t.fromByteArray(m.slice(f,d))}function ee(m,f,d){d=Math.min(m.length,d);const x=[];let R=f;for(;R<d;){const $=m[R];let G=null,le=$>239?4:$>223?3:$>191?2:1;if(R+le<=d){let ke,Pe,Oe,ve;switch(le){case 1:$<128&&(G=$);break;case 2:ke=m[R+1],(ke&192)===128&&(ve=($&31)<<6|ke&63,ve>127&&(G=ve));break;case 3:ke=m[R+1],Pe=m[R+2],(ke&192)===128&&(Pe&192)===128&&(ve=($&15)<<12|(ke&63)<<6|Pe&63,ve>2047&&(ve<55296||ve>57343)&&(G=ve));break;case 4:ke=m[R+1],Pe=m[R+2],Oe=m[R+3],(ke&192)===128&&(Pe&192)===128&&(Oe&192)===128&&(ve=($&15)<<18|(ke&63)<<12|(Pe&63)<<6|Oe&63,ve>65535&&ve<1114112&&(G=ve))}}G===null?(G=65533,le=1):G>65535&&(G-=65536,x.push(G>>>10&1023|55296),G=56320|G&1023),x.push(G),R+=le}return be(x)}const ae=4096;function be(m){const f=m.length;if(f<=ae)return String.fromCharCode.apply(String,m);let d="",x=0;for(;x<f;)d+=String.fromCharCode.apply(String,m.slice(x,x+=ae));return d}function ye(m,f,d){let x="";d=Math.min(m.length,d);for(let R=f;R<d;++R)x+=String.fromCharCode(m[R]&127);return x}function ce(m,f,d){let x="";d=Math.min(m.length,d);for(let R=f;R<d;++R)x+=String.fromCharCode(m[R]);return x}function F(m,f,d){const x=m.length;(!f||f<0)&&(f=0),(!d||d<0||d>x)&&(d=x);let R="";for(let $=f;$<d;++$)R+=Ot[m[$]];return R}function Y(m,f,d){const x=m.slice(f,d);let R="";for(let $=0;$<x.length-1;$+=2)R+=String.fromCharCode(x[$]+x[$+1]*256);return R}a.prototype.slice=function(f,d){const x=this.length;f=~~f,d=d===void 0?x:~~d,f<0?(f+=x,f<0&&(f=0)):f>x&&(f=x),d<0?(d+=x,d<0&&(d=0)):d>x&&(d=x),d<f&&(d=f);const R=this.subarray(f,d);return Object.setPrototypeOf(R,a.prototype),R};function re(m,f,d){if(m%1!==0||m<0)throw new RangeError("offset is not uint");if(m+f>d)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(f,d,x){f=f>>>0,d=d>>>0,x||re(f,d,this.length);let R=this[f],$=1,G=0;for(;++G<d&&($*=256);)R+=this[f+G]*$;return R},a.prototype.readUintBE=a.prototype.readUIntBE=function(f,d,x){f=f>>>0,d=d>>>0,x||re(f,d,this.length);let R=this[f+--d],$=1;for(;d>0&&($*=256);)R+=this[f+--d]*$;return R},a.prototype.readUint8=a.prototype.readUInt8=function(f,d){return f=f>>>0,d||re(f,1,this.length),this[f]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(f,d){return f=f>>>0,d||re(f,2,this.length),this[f]|this[f+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(f,d){return f=f>>>0,d||re(f,2,this.length),this[f]<<8|this[f+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(f,d){return f=f>>>0,d||re(f,4,this.length),(this[f]|this[f+1]<<8|this[f+2]<<16)+this[f+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(f,d){return f=f>>>0,d||re(f,4,this.length),this[f]*16777216+(this[f+1]<<16|this[f+2]<<8|this[f+3])},a.prototype.readBigUInt64LE=vt(function(f){f=f>>>0,H(f,"offset");const d=this[f],x=this[f+7];(d===void 0||x===void 0)&&K(f,this.length-8);const R=d+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24,$=this[++f]+this[++f]*2**8+this[++f]*2**16+x*2**24;return BigInt(R)+(BigInt($)<<BigInt(32))}),a.prototype.readBigUInt64BE=vt(function(f){f=f>>>0,H(f,"offset");const d=this[f],x=this[f+7];(d===void 0||x===void 0)&&K(f,this.length-8);const R=d*2**24+this[++f]*2**16+this[++f]*2**8+this[++f],$=this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+x;return(BigInt(R)<<BigInt(32))+BigInt($)}),a.prototype.readIntLE=function(f,d,x){f=f>>>0,d=d>>>0,x||re(f,d,this.length);let R=this[f],$=1,G=0;for(;++G<d&&($*=256);)R+=this[f+G]*$;return $*=128,R>=$&&(R-=Math.pow(2,8*d)),R},a.prototype.readIntBE=function(f,d,x){f=f>>>0,d=d>>>0,x||re(f,d,this.length);let R=d,$=1,G=this[f+--R];for(;R>0&&($*=256);)G+=this[f+--R]*$;return $*=128,G>=$&&(G-=Math.pow(2,8*d)),G},a.prototype.readInt8=function(f,d){return f=f>>>0,d||re(f,1,this.length),this[f]&128?(255-this[f]+1)*-1:this[f]},a.prototype.readInt16LE=function(f,d){f=f>>>0,d||re(f,2,this.length);const x=this[f]|this[f+1]<<8;return x&32768?x|4294901760:x},a.prototype.readInt16BE=function(f,d){f=f>>>0,d||re(f,2,this.length);const x=this[f+1]|this[f]<<8;return x&32768?x|4294901760:x},a.prototype.readInt32LE=function(f,d){return f=f>>>0,d||re(f,4,this.length),this[f]|this[f+1]<<8|this[f+2]<<16|this[f+3]<<24},a.prototype.readInt32BE=function(f,d){return f=f>>>0,d||re(f,4,this.length),this[f]<<24|this[f+1]<<16|this[f+2]<<8|this[f+3]},a.prototype.readBigInt64LE=vt(function(f){f=f>>>0,H(f,"offset");const d=this[f],x=this[f+7];(d===void 0||x===void 0)&&K(f,this.length-8);const R=this[f+4]+this[f+5]*2**8+this[f+6]*2**16+(x<<24);return(BigInt(R)<<BigInt(32))+BigInt(d+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24)}),a.prototype.readBigInt64BE=vt(function(f){f=f>>>0,H(f,"offset");const d=this[f],x=this[f+7];(d===void 0||x===void 0)&&K(f,this.length-8);const R=(d<<24)+this[++f]*2**16+this[++f]*2**8+this[++f];return(BigInt(R)<<BigInt(32))+BigInt(this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+x)}),a.prototype.readFloatLE=function(f,d){return f=f>>>0,d||re(f,4,this.length),r.read(this,f,!0,23,4)},a.prototype.readFloatBE=function(f,d){return f=f>>>0,d||re(f,4,this.length),r.read(this,f,!1,23,4)},a.prototype.readDoubleLE=function(f,d){return f=f>>>0,d||re(f,8,this.length),r.read(this,f,!0,52,8)},a.prototype.readDoubleBE=function(f,d){return f=f>>>0,d||re(f,8,this.length),r.read(this,f,!1,52,8)};function O(m,f,d,x,R,$){if(!a.isBuffer(m))throw new TypeError('"buffer" argument must be a Buffer instance');if(f>R||f<$)throw new RangeError('"value" argument is out of bounds');if(d+x>m.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(f,d,x,R){if(f=+f,d=d>>>0,x=x>>>0,!R){const le=Math.pow(2,8*x)-1;O(this,f,d,x,le,0)}let $=1,G=0;for(this[d]=f&255;++G<x&&($*=256);)this[d+G]=f/$&255;return d+x},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(f,d,x,R){if(f=+f,d=d>>>0,x=x>>>0,!R){const le=Math.pow(2,8*x)-1;O(this,f,d,x,le,0)}let $=x-1,G=1;for(this[d+$]=f&255;--$>=0&&(G*=256);)this[d+$]=f/G&255;return d+x},a.prototype.writeUint8=a.prototype.writeUInt8=function(f,d,x){return f=+f,d=d>>>0,x||O(this,f,d,1,255,0),this[d]=f&255,d+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(f,d,x){return f=+f,d=d>>>0,x||O(this,f,d,2,65535,0),this[d]=f&255,this[d+1]=f>>>8,d+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(f,d,x){return f=+f,d=d>>>0,x||O(this,f,d,2,65535,0),this[d]=f>>>8,this[d+1]=f&255,d+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(f,d,x){return f=+f,d=d>>>0,x||O(this,f,d,4,4294967295,0),this[d+3]=f>>>24,this[d+2]=f>>>16,this[d+1]=f>>>8,this[d]=f&255,d+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(f,d,x){return f=+f,d=d>>>0,x||O(this,f,d,4,4294967295,0),this[d]=f>>>24,this[d+1]=f>>>16,this[d+2]=f>>>8,this[d+3]=f&255,d+4};function N(m,f,d,x,R){_(f,x,R,m,d,7);let $=Number(f&BigInt(4294967295));m[d++]=$,$=$>>8,m[d++]=$,$=$>>8,m[d++]=$,$=$>>8,m[d++]=$;let G=Number(f>>BigInt(32)&BigInt(4294967295));return m[d++]=G,G=G>>8,m[d++]=G,G=G>>8,m[d++]=G,G=G>>8,m[d++]=G,d}function q(m,f,d,x,R){_(f,x,R,m,d,7);let $=Number(f&BigInt(4294967295));m[d+7]=$,$=$>>8,m[d+6]=$,$=$>>8,m[d+5]=$,$=$>>8,m[d+4]=$;let G=Number(f>>BigInt(32)&BigInt(4294967295));return m[d+3]=G,G=G>>8,m[d+2]=G,G=G>>8,m[d+1]=G,G=G>>8,m[d]=G,d+8}a.prototype.writeBigUInt64LE=vt(function(f,d=0){return N(this,f,d,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=vt(function(f,d=0){return q(this,f,d,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(f,d,x,R){if(f=+f,d=d>>>0,!R){const ke=Math.pow(2,8*x-1);O(this,f,d,x,ke-1,-ke)}let $=0,G=1,le=0;for(this[d]=f&255;++$<x&&(G*=256);)f<0&&le===0&&this[d+$-1]!==0&&(le=1),this[d+$]=(f/G>>0)-le&255;return d+x},a.prototype.writeIntBE=function(f,d,x,R){if(f=+f,d=d>>>0,!R){const ke=Math.pow(2,8*x-1);O(this,f,d,x,ke-1,-ke)}let $=x-1,G=1,le=0;for(this[d+$]=f&255;--$>=0&&(G*=256);)f<0&&le===0&&this[d+$+1]!==0&&(le=1),this[d+$]=(f/G>>0)-le&255;return d+x},a.prototype.writeInt8=function(f,d,x){return f=+f,d=d>>>0,x||O(this,f,d,1,127,-128),f<0&&(f=255+f+1),this[d]=f&255,d+1},a.prototype.writeInt16LE=function(f,d,x){return f=+f,d=d>>>0,x||O(this,f,d,2,32767,-32768),this[d]=f&255,this[d+1]=f>>>8,d+2},a.prototype.writeInt16BE=function(f,d,x){return f=+f,d=d>>>0,x||O(this,f,d,2,32767,-32768),this[d]=f>>>8,this[d+1]=f&255,d+2},a.prototype.writeInt32LE=function(f,d,x){return f=+f,d=d>>>0,x||O(this,f,d,4,2147483647,-2147483648),this[d]=f&255,this[d+1]=f>>>8,this[d+2]=f>>>16,this[d+3]=f>>>24,d+4},a.prototype.writeInt32BE=function(f,d,x){return f=+f,d=d>>>0,x||O(this,f,d,4,2147483647,-2147483648),f<0&&(f=4294967295+f+1),this[d]=f>>>24,this[d+1]=f>>>16,this[d+2]=f>>>8,this[d+3]=f&255,d+4},a.prototype.writeBigInt64LE=vt(function(f,d=0){return N(this,f,d,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=vt(function(f,d=0){return q(this,f,d,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ne(m,f,d,x,R,$){if(d+x>m.length)throw new RangeError("Index out of range");if(d<0)throw new RangeError("Index out of range")}function I(m,f,d,x,R){return f=+f,d=d>>>0,R||ne(m,f,d,4),r.write(m,f,d,x,23,4),d+4}a.prototype.writeFloatLE=function(f,d,x){return I(this,f,d,!0,x)},a.prototype.writeFloatBE=function(f,d,x){return I(this,f,d,!1,x)};function k(m,f,d,x,R){return f=+f,d=d>>>0,R||ne(m,f,d,8),r.write(m,f,d,x,52,8),d+8}a.prototype.writeDoubleLE=function(f,d,x){return k(this,f,d,!0,x)},a.prototype.writeDoubleBE=function(f,d,x){return k(this,f,d,!1,x)},a.prototype.copy=function(f,d,x,R){if(!a.isBuffer(f))throw new TypeError("argument should be a Buffer");if(x||(x=0),!R&&R!==0&&(R=this.length),d>=f.length&&(d=f.length),d||(d=0),R>0&&R<x&&(R=x),R===x||f.length===0||this.length===0)return 0;if(d<0)throw new RangeError("targetStart out of bounds");if(x<0||x>=this.length)throw new RangeError("Index out of range");if(R<0)throw new RangeError("sourceEnd out of bounds");R>this.length&&(R=this.length),f.length-d<R-x&&(R=f.length-d+x);const $=R-x;return this===f&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(d,x,R):Uint8Array.prototype.set.call(f,this.subarray(x,R),d),$},a.prototype.fill=function(f,d,x,R){if(typeof f=="string"){if(typeof d=="string"?(R=d,d=0,x=this.length):typeof x=="string"&&(R=x,x=this.length),R!==void 0&&typeof R!="string")throw new TypeError("encoding must be a string");if(typeof R=="string"&&!a.isEncoding(R))throw new TypeError("Unknown encoding: "+R);if(f.length===1){const G=f.charCodeAt(0);(R==="utf8"&&G<128||R==="latin1")&&(f=G)}}else typeof f=="number"?f=f&255:typeof f=="boolean"&&(f=Number(f));if(d<0||this.length<d||this.length<x)throw new RangeError("Out of range index");if(x<=d)return this;d=d>>>0,x=x===void 0?this.length:x>>>0,f||(f=0);let $;if(typeof f=="number")for($=d;$<x;++$)this[$]=f;else{const G=a.isBuffer(f)?f:a.from(f,R),le=G.length;if(le===0)throw new TypeError('The value "'+f+'" is invalid for argument "value"');for($=0;$<x-d;++$)this[$+d]=G[$%le]}return this};const M={};function V(m,f,d){M[m]=class extends d{constructor(){super(),Object.defineProperty(this,"message",{value:f.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${m}]`,this.stack,delete this.name}get code(){return m}set code(R){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:R,writable:!0})}toString(){return`${this.name} [${m}]: ${this.message}`}}}V("ERR_BUFFER_OUT_OF_BOUNDS",function(m){return m?`${m} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),V("ERR_INVALID_ARG_TYPE",function(m,f){return`The "${m}" argument must be of type number. Received type ${typeof f}`},TypeError),V("ERR_OUT_OF_RANGE",function(m,f,d){let x=`The value of "${m}" is out of range.`,R=d;return Number.isInteger(d)&&Math.abs(d)>2**32?R=W(String(d)):typeof d=="bigint"&&(R=String(d),(d>BigInt(2)**BigInt(32)||d<-(BigInt(2)**BigInt(32)))&&(R=W(R)),R+="n"),x+=` It must be ${f}. Received ${R}`,x},RangeError);function W(m){let f="",d=m.length;const x=m[0]==="-"?1:0;for(;d>=x+4;d-=3)f=`_${m.slice(d-3,d)}${f}`;return`${m.slice(0,d)}${f}`}function g(m,f,d){H(f,"offset"),(m[f]===void 0||m[f+d]===void 0)&&K(f,m.length-(d+1))}function _(m,f,d,x,R,$){if(m>d||m<f){const G=typeof f=="bigint"?"n":"";let le;throw f===0||f===BigInt(0)?le=`>= 0${G} and < 2${G} ** ${($+1)*8}${G}`:le=`>= -(2${G} ** ${($+1)*8-1}${G}) and < 2 ** ${($+1)*8-1}${G}`,new M.ERR_OUT_OF_RANGE("value",le,m)}g(x,R,$)}function H(m,f){if(typeof m!="number")throw new M.ERR_INVALID_ARG_TYPE(f,"number",m)}function K(m,f,d){throw Math.floor(m)!==m?(H(m,d),new M.ERR_OUT_OF_RANGE("offset","an integer",m)):f<0?new M.ERR_BUFFER_OUT_OF_BOUNDS:new M.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${f}`,m)}const de=/[^+/0-9A-Za-z-_]/g;function ie(m){if(m=m.split("=")[0],m=m.trim().replace(de,""),m.length<2)return"";for(;m.length%4!==0;)m=m+"=";return m}function fe(m,f){f=f||1/0;let d;const x=m.length;let R=null;const $=[];for(let G=0;G<x;++G){if(d=m.charCodeAt(G),d>55295&&d<57344){if(!R){if(d>56319){(f-=3)>-1&&$.push(239,191,189);continue}else if(G+1===x){(f-=3)>-1&&$.push(239,191,189);continue}R=d;continue}if(d<56320){(f-=3)>-1&&$.push(239,191,189),R=d;continue}d=(R-55296<<10|d-56320)+65536}else R&&(f-=3)>-1&&$.push(239,191,189);if(R=null,d<128){if((f-=1)<0)break;$.push(d)}else if(d<2048){if((f-=2)<0)break;$.push(d>>6|192,d&63|128)}else if(d<65536){if((f-=3)<0)break;$.push(d>>12|224,d>>6&63|128,d&63|128)}else if(d<1114112){if((f-=4)<0)break;$.push(d>>18|240,d>>12&63|128,d>>6&63|128,d&63|128)}else throw new Error("Invalid code point")}return $}function ut(m){const f=[];for(let d=0;d<m.length;++d)f.push(m.charCodeAt(d)&255);return f}function j(m,f){let d,x,R;const $=[];for(let G=0;G<m.length&&!((f-=2)<0);++G)d=m.charCodeAt(G),x=d>>8,R=d%256,$.push(R),$.push(x);return $}function pt(m){return t.toByteArray(ie(m))}function qe(m,f,d,x){let R;for(R=0;R<x&&!(R+d>=f.length||R>=m.length);++R)f[R+d]=m[R];return R}function Ne(m,f){return m instanceof f||m!=null&&m.constructor!=null&&m.constructor.name!=null&&m.constructor.name===f.name}function wt(m){return m!==m}const Ot=function(){const m="0123456789abcdef",f=new Array(256);for(let d=0;d<16;++d){const x=d*16;for(let R=0;R<16;++R)f[x+R]=m[d]+m[R]}return f}();function vt(m){return typeof BigInt>"u"?Nr:m}function Nr(){throw new Error("BigInt not supported")}})(Bt);var $i={Array:function(e){return e!=null&&e.constructor===Array},Boolean:function(e){return typeof e=="boolean"},Function:function(e){return typeof e=="function"},Nil:function(e){return e==null},Number:function(e){return typeof e=="number"},Object:function(e){return typeof e=="object"},String:function(e){return typeof e=="string"},"":function(){return!0}};$i.Null=$i.Nil;for(var Ef in $i)$i[Ef].toJSON=(function(e){return e}).bind(null,Ef);var xu=$i,Dr=xu;function cp(e){return e.name||e.toString().match(/function (.*?)\s*\(/)[1]}function Au(e){return Dr.Nil(e)?"":cp(e.constructor)}function Ew(e){return Dr.Function(e)?"":Dr.String(e)?JSON.stringify(e):e&&Dr.Object(e)?"":e}function Su(e,t){Error.captureStackTrace&&Error.captureStackTrace(e,t)}function Ro(e){return Dr.Function(e)?e.toJSON?e.toJSON():cp(e):Dr.Array(e)?"Array":e&&Dr.Object(e)?"Object":e!==void 0?e:""}function up(e,t,r){var n=Ew(t);return"Expected "+Ro(e)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function ur(e,t,r){r=r||Au(t),this.message=up(e,t,r),Su(this,ur),this.__type=e,this.__value=t,this.__valueTypeName=r}ur.prototype=Object.create(Error.prototype);ur.prototype.constructor=ur;function xw(e,t,r,n,i){var o='" of type ';return t==="key"&&(o='" with key type '),up('property "'+Ro(r)+o+Ro(e),n,i)}function mn(e,t,r,n,i){e?(i=i||Au(n),this.message=xw(e,r,t,n,i)):this.message='Unexpected property "'+t+'"',Su(this,ur),this.__label=r,this.__property=t,this.__type=e,this.__value=n,this.__valueTypeName=i}mn.prototype=Object.create(Error.prototype);mn.prototype.constructor=ur;function Aw(e,t){return new ur(e,{},t)}function Sw(e,t,r){return e instanceof mn?(t=t+"."+e.__property,e=new mn(e.__type,t,e.__label,e.__value,e.__valueTypeName)):e instanceof ur&&(e=new mn(e.__type,t,r,e.__value,e.__valueTypeName)),Su(e),e}var fp={TfTypeError:ur,TfPropertyTypeError:mn,tfCustomError:Aw,tfSubError:Sw,tfJSON:Ro,getValueTypeName:Au},Ls,xf;function Pw(){if(xf)return Ls;xf=1;var e=xu,t=fp;function r(T){return Buffer.isBuffer(T)}function n(T){return typeof T=="string"&&/^([0-9a-f]{2})+$/i.test(T)}function i(T,L){var D=T.toJSON();function C(X){if(!T(X))return!1;if(X.length===L)return!0;throw t.tfCustomError(D+"(Length: "+L+")",D+"(Length: "+X.length+")")}return C.toJSON=function(){return D},C}var o=i.bind(null,e.Array),s=i.bind(null,r),a=i.bind(null,n),c=i.bind(null,e.String);function u(T,L,D){D=D||e.Number;function C(X,Z){return D(X,Z)&&X>T&&X<L}return C.toJSON=function(){return`${D.toJSON()} between [${T}, ${L}]`},C}var l=Math.pow(2,53)-1;function h(T){return typeof T=="number"&&isFinite(T)}function y(T){return T<<24>>24===T}function p(T){return T<<16>>16===T}function b(T){return(T|0)===T}function v(T){return typeof T=="number"&&T>=-l&&T<=l&&Math.floor(T)===T}function E(T){return(T&255)===T}function S(T){return(T&65535)===T}function P(T){return T>>>0===T}function A(T){return typeof T=="number"&&T>=0&&T<=l&&Math.floor(T)===T}var w={ArrayN:o,Buffer:r,BufferN:s,Finite:h,Hex:n,HexN:a,Int8:y,Int16:p,Int32:b,Int53:v,Range:u,StringN:c,UInt8:E,UInt16:S,UInt32:P,UInt53:A};for(var B in w)w[B].toJSON=(function(T){return T}).bind(null,B);return Ls=w,Ls}var Ki=fp,ze=xu,Xt=Ki.tfJSON,lp=Ki.TfTypeError,dp=Ki.TfPropertyTypeError,Wn=Ki.tfSubError,Tw=Ki.getValueTypeName,rr={arrayOf:function(t,r){t=Mt(t),r=r||{};function n(i,o){return!ze.Array(i)||ze.Nil(i)||r.minLength!==void 0&&i.length<r.minLength||r.maxLength!==void 0&&i.length>r.maxLength||r.length!==void 0&&i.length!==r.length?!1:i.every(function(s,a){try{return ot(t,s,o)}catch(c){throw Wn(c,a)}})}return n.toJSON=function(){var i="["+Xt(t)+"]";return r.length!==void 0?i+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(i+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),i},n},maybe:function e(t){t=Mt(t);function r(n,i){return ze.Nil(n)||t(n,i,e)}return r.toJSON=function(){return"?"+Xt(t)},r},map:function(t,r){t=Mt(t),r&&(r=Mt(r));function n(i,o){if(!ze.Object(i)||ze.Nil(i))return!1;for(var s in i){try{r&&ot(r,s,o)}catch(c){throw Wn(c,s,"key")}try{var a=i[s];ot(t,a,o)}catch(c){throw Wn(c,s)}}return!0}return r?n.toJSON=function(){return"{"+Xt(r)+": "+Xt(t)+"}"}:n.toJSON=function(){return"{"+Xt(t)+"}"},n},object:function(t){var r={};for(var n in t)r[n]=Mt(t[n]);function i(o,s){if(!ze.Object(o)||ze.Nil(o))return!1;var a;try{for(a in r){var c=r[a],u=o[a];ot(c,u,s)}}catch(l){throw Wn(l,a)}if(s){for(a in o)if(!r[a])throw new dp(void 0,a)}return!0}return i.toJSON=function(){return Xt(r)},i},anyOf:function(){var t=[].slice.call(arguments).map(Mt);function r(n,i){return t.some(function(o){try{return ot(o,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(Xt).join("|")},r},allOf:function(){var t=[].slice.call(arguments).map(Mt);function r(n,i){return t.every(function(o){try{return ot(o,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(Xt).join(" & ")},r},quacksLike:function(t){function r(n){return t===Tw(n)}return r.toJSON=function(){return t},r},tuple:function(){var t=[].slice.call(arguments).map(Mt);function r(n,i){return ze.Nil(n)||ze.Nil(n.length)||i&&n.length!==t.length?!1:t.every(function(o,s){try{return ot(o,n[s],i)}catch(a){throw Wn(a,s)}})}return r.toJSON=function(){return"("+t.map(Xt).join(", ")+")"},r},value:function(t){function r(n){return n===t}return r.toJSON=function(){return t},r}};rr.oneOf=rr.anyOf;function Mt(e){if(ze.String(e))return e[0]==="?"?rr.maybe(e.slice(1)):ze[e]||rr.quacksLike(e);if(e&&ze.Object(e)){if(ze.Array(e)){if(e.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return rr.arrayOf(e[0])}return rr.object(e)}else if(ze.Function(e))return e;return rr.value(e)}function ot(e,t,r,n){if(ze.Function(e)){if(e(t,r))return!0;throw new lp(n||e,t)}return ot(Mt(e),t,r)}for(var Sr in ze)ot[Sr]=ze[Sr];for(Sr in rr)ot[Sr]=rr[Sr];var Af=Pw();for(Sr in Af)ot[Sr]=Af[Sr];ot.compile=Mt;ot.TfTypeError=lp;ot.TfPropertyTypeError=dp;var hp=ot;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.oneOf=e.Null=e.BufferN=e.Function=e.UInt32=e.UInt8=e.tuple=e.maybe=e.Hex=e.Buffer=e.String=e.Boolean=e.Array=e.Number=e.Hash256bit=e.Hash160bit=e.Buffer256bit=e.isTaptree=e.isTapleaf=e.TAPLEAF_VERSION_MASK=e.Satoshi=e.isPoint=e.stacksEqual=e.typeforce=void 0;const t=Bt;e.typeforce=hp;const r=t.Buffer.alloc(32,0),n=t.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function i(l,h){return l.length!==h.length?!1:l.every((y,p)=>y.equals(h[p]))}e.stacksEqual=i;function o(l){if(!t.Buffer.isBuffer(l)||l.length<33)return!1;const h=l[0],y=l.slice(1,33);if(y.compare(r)===0||y.compare(n)>=0)return!1;if((h===2||h===3)&&l.length===33)return!0;const p=l.slice(33);return p.compare(r)===0||p.compare(n)>=0?!1:h===4&&l.length===65}e.isPoint=o;const s=21*1e14;function a(l){return e.typeforce.UInt53(l)&&l<=s}e.Satoshi=a,e.TAPLEAF_VERSION_MASK=254;function c(l){return!l||!("output"in l)||!t.Buffer.isBuffer(l.output)?!1:l.version!==void 0?(l.version&e.TAPLEAF_VERSION_MASK)===l.version:!0}e.isTapleaf=c;function u(l){return(0,e.Array)(l)?l.length!==2?!1:l.every(h=>u(h)):c(l)}e.isTaptree=u,e.Buffer256bit=e.typeforce.BufferN(32),e.Hash160bit=e.typeforce.BufferN(20),e.Hash256bit=e.typeforce.BufferN(32),e.Number=e.typeforce.Number,e.Array=e.typeforce.Array,e.Boolean=e.typeforce.Boolean,e.String=e.typeforce.String,e.Buffer=e.typeforce.Buffer,e.Hex=e.typeforce.Hex,e.maybe=e.typeforce.maybe,e.tuple=e.typeforce.tuple,e.UInt8=e.typeforce.UInt8,e.UInt32=e.typeforce.UInt32,e.Function=e.typeforce.Function,e.BufferN=e.typeforce.BufferN,e.Null=e.typeforce.Null,e.oneOf=e.typeforce.oneOf})(Ze);var Yi={},Ve={};Object.defineProperty(Ve,"__esModule",{value:!0});Ve.BufferReader=Ve.BufferWriter=Ve.cloneBuffer=Ve.reverseBuffer=Ve.writeUInt64LE=Ve.readUInt64LE=Ve.varuint=void 0;const jr=Ze,{typeforce:pp}=jr,Li=vd;Ve.varuint=Li;function yp(e,t){if(typeof e!="number")throw new Error("cannot write a non-number as a number");if(e<0)throw new Error("specified a negative value for writing an unsigned value");if(e>t)throw new Error("RangeError: value out of range");if(Math.floor(e)!==e)throw new Error("value has a fractional component")}function mp(e,t){const r=e.readUInt32LE(t);let n=e.readUInt32LE(t+4);return n*=4294967296,yp(n+r,9007199254740991),n+r}Ve.readUInt64LE=mp;function bp(e,t,r){return yp(t,9007199254740991),e.writeInt32LE(t&-1,r),e.writeUInt32LE(Math.floor(t/4294967296),r+4),r+8}Ve.writeUInt64LE=bp;function Iw(e){if(e.length<1)return e;let t=e.length-1,r=0;for(let n=0;n<e.length/2;n++)r=e[n],e[n]=e[t],e[t]=r,t--;return e}Ve.reverseBuffer=Iw;function Bw(e){const t=Buffer.allocUnsafe(e.length);return e.copy(t),t}Ve.cloneBuffer=Bw;class Pu{static withCapacity(t){return new Pu(Buffer.alloc(t))}constructor(t,r=0){this.buffer=t,this.offset=r,pp(jr.tuple(jr.Buffer,jr.UInt32),[t,r])}writeUInt8(t){this.offset=this.buffer.writeUInt8(t,this.offset)}writeInt32(t){this.offset=this.buffer.writeInt32LE(t,this.offset)}writeUInt32(t){this.offset=this.buffer.writeUInt32LE(t,this.offset)}writeUInt64(t){this.offset=bp(this.buffer,t,this.offset)}writeVarInt(t){Li.encode(t,this.buffer,this.offset),this.offset+=Li.encode.bytes}writeSlice(t){if(this.buffer.length<this.offset+t.length)throw new Error("Cannot write slice out of bounds");this.offset+=t.copy(this.buffer,this.offset)}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}writeVector(t){this.writeVarInt(t.length),t.forEach(r=>this.writeVarSlice(r))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}Ve.BufferWriter=Pu;class kw{constructor(t,r=0){this.buffer=t,this.offset=r,pp(jr.tuple(jr.Buffer,jr.UInt32),[t,r])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=mp(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Li.decode(this.buffer,this.offset);return this.offset+=Li.decode.bytes,t}readSlice(t){if(this.buffer.length<this.offset+t)throw new Error("Cannot read slice out of bounds");const r=this.buffer.slice(this.offset,this.offset+t);return this.offset+=t,r}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const t=this.readVarInt(),r=[];for(let n=0;n<t;n++)r.push(this.readVarSlice());return r}}Ve.BufferReader=kw;var Cr={};const Ow=_u(N1);var Sn={},ft={},st={},Tu={},rs={};Object.defineProperty(rs,"__esModule",{value:!0});rs.crypto=void 0;rs.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;(function(e){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(e,"__esModule",{value:!0}),e.wrapXOFConstructorWithOpts=e.wrapConstructorWithOpts=e.wrapConstructor=e.Hash=e.nextTick=e.swap32IfBE=e.byteSwapIfBE=e.swap8IfBE=e.isLE=void 0,e.isBytes=r,e.anumber=n,e.abytes=i,e.ahash=o,e.aexists=s,e.aoutput=a,e.u8=c,e.u32=u,e.clean=l,e.createView=h,e.rotr=y,e.rotl=p,e.byteSwap=b,e.byteSwap32=v,e.bytesToHex=P,e.hexToBytes=B,e.asyncLoop=L,e.utf8ToBytes=D,e.bytesToUtf8=C,e.toBytes=X,e.kdfInputToBytes=Z,e.concatBytes=oe,e.checkOpts=te,e.createHasher=ae,e.createOptHasher=be,e.createXOFer=ye,e.randomBytes=ce;const t=rs;function r(F){return F instanceof Uint8Array||ArrayBuffer.isView(F)&&F.constructor.name==="Uint8Array"}function n(F){if(!Number.isSafeInteger(F)||F<0)throw new Error("positive integer expected, got "+F)}function i(F,...Y){if(!r(F))throw new Error("Uint8Array expected");if(Y.length>0&&!Y.includes(F.length))throw new Error("Uint8Array expected of length "+Y+", got length="+F.length)}function o(F){if(typeof F!="function"||typeof F.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");n(F.outputLen),n(F.blockLen)}function s(F,Y=!0){if(F.destroyed)throw new Error("Hash instance has been destroyed");if(Y&&F.finished)throw new Error("Hash#digest() has already been called")}function a(F,Y){i(F);const re=Y.outputLen;if(F.length<re)throw new Error("digestInto() expects output buffer of length at least "+re)}function c(F){return new Uint8Array(F.buffer,F.byteOffset,F.byteLength)}function u(F){return new Uint32Array(F.buffer,F.byteOffset,Math.floor(F.byteLength/4))}function l(...F){for(let Y=0;Y<F.length;Y++)F[Y].fill(0)}function h(F){return new DataView(F.buffer,F.byteOffset,F.byteLength)}function y(F,Y){return F<<32-Y|F>>>Y}function p(F,Y){return F<<Y|F>>>32-Y>>>0}e.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function b(F){return F<<24&4278190080|F<<8&16711680|F>>>8&65280|F>>>24&255}e.swap8IfBE=e.isLE?F=>F:F=>b(F),e.byteSwapIfBE=e.swap8IfBE;function v(F){for(let Y=0;Y<F.length;Y++)F[Y]=b(F[Y]);return F}e.swap32IfBE=e.isLE?F=>F:v;const E=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",S=Array.from({length:256},(F,Y)=>Y.toString(16).padStart(2,"0"));function P(F){if(i(F),E)return F.toHex();let Y="";for(let re=0;re<F.length;re++)Y+=S[F[re]];return Y}const A={_0:48,_9:57,A:65,F:70,a:97,f:102};function w(F){if(F>=A._0&&F<=A._9)return F-A._0;if(F>=A.A&&F<=A.F)return F-(A.A-10);if(F>=A.a&&F<=A.f)return F-(A.a-10)}function B(F){if(typeof F!="string")throw new Error("hex string expected, got "+typeof F);if(E)return Uint8Array.fromHex(F);const Y=F.length,re=Y/2;if(Y%2)throw new Error("hex string expected, got unpadded hex of length "+Y);const O=new Uint8Array(re);for(let N=0,q=0;N<re;N++,q+=2){const ne=w(F.charCodeAt(q)),I=w(F.charCodeAt(q+1));if(ne===void 0||I===void 0){const k=F[q]+F[q+1];throw new Error('hex string expected, got non-hex character "'+k+'" at index '+q)}O[N]=ne*16+I}return O}const T=async()=>{};e.nextTick=T;async function L(F,Y,re){let O=Date.now();for(let N=0;N<F;N++){re(N);const q=Date.now()-O;q>=0&&q<Y||(await(0,e.nextTick)(),O+=q)}}function D(F){if(typeof F!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(F))}function C(F){return new TextDecoder().decode(F)}function X(F){return typeof F=="string"&&(F=D(F)),i(F),F}function Z(F){return typeof F=="string"&&(F=D(F)),i(F),F}function oe(...F){let Y=0;for(let O=0;O<F.length;O++){const N=F[O];i(N),Y+=N.length}const re=new Uint8Array(Y);for(let O=0,N=0;O<F.length;O++){const q=F[O];re.set(q,N),N+=q.length}return re}function te(F,Y){if(Y!==void 0&&{}.toString.call(Y)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(F,Y)}class ee{}e.Hash=ee;function ae(F){const Y=O=>F().update(X(O)).digest(),re=F();return Y.outputLen=re.outputLen,Y.blockLen=re.blockLen,Y.create=()=>F(),Y}function be(F){const Y=(O,N)=>F(N).update(X(O)).digest(),re=F({});return Y.outputLen=re.outputLen,Y.blockLen=re.blockLen,Y.create=O=>F(O),Y}function ye(F){const Y=(O,N)=>F(N).update(X(O)).digest(),re=F({});return Y.outputLen=re.outputLen,Y.blockLen=re.blockLen,Y.create=O=>F(O),Y}e.wrapConstructor=ae,e.wrapConstructorWithOpts=be,e.wrapXOFConstructorWithOpts=ye;function ce(F=32){if(t.crypto&&typeof t.crypto.getRandomValues=="function")return t.crypto.getRandomValues(new Uint8Array(F));if(t.crypto&&typeof t.crypto.randomBytes=="function")return Uint8Array.from(t.crypto.randomBytes(F));throw new Error("crypto.getRandomValues must be defined")}})(Tu);Object.defineProperty(st,"__esModule",{value:!0});st.SHA512_IV=st.SHA384_IV=st.SHA224_IV=st.SHA256_IV=st.HashMD=void 0;st.setBigUint64=gp;st.Chi=Rw;st.Maj=Cw;const Ct=Tu;function gp(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),a=Number(r&o),c=n?4:0,u=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+u,a,n)}function Rw(e,t,r){return e&t^~e&r}function Cw(e,t,r){return e&t^e&r^t&r}class Fw extends Ct.Hash{constructor(t,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(t),this.view=(0,Ct.createView)(this.buffer)}update(t){(0,Ct.aexists)(this),t=(0,Ct.toBytes)(t),(0,Ct.abytes)(t);const{view:r,buffer:n,blockLen:i}=this,o=t.length;for(let s=0;s<o;){const a=Math.min(i-this.pos,o-s);if(a===i){const c=(0,Ct.createView)(t);for(;i<=o-s;s+=i)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){(0,Ct.aexists)(this),(0,Ct.aoutput)(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:o}=this;let{pos:s}=this;r[s++]=128,(0,Ct.clean)(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let h=s;h<i;h++)r[h]=0;gp(n,i-8,BigInt(this.length*8),o),this.process(n,0);const a=(0,Ct.createView)(t),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 h=0;h<u;h++)a.setUint32(4*h,l[h],o)}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=o,t.length=i,t.pos=a,i%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}}st.HashMD=Fw;st.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);st.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);st.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);st.SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);Object.defineProperty(ft,"__esModule",{value:!0});ft.ripemd160=ft.RIPEMD160=ft.md5=ft.MD5=ft.sha1=ft.SHA1=void 0;const qr=st,We=Tu,an=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),mr=new Uint32Array(80);class wp extends qr.HashMD{constructor(){super(64,20,8,!1),this.A=an[0]|0,this.B=an[1]|0,this.C=an[2]|0,this.D=an[3]|0,this.E=an[4]|0}get(){const{A:t,B:r,C:n,D:i,E:o}=this;return[t,r,n,i,o]}set(t,r,n,i,o){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0}process(t,r){for(let c=0;c<16;c++,r+=4)mr[c]=t.getUint32(r,!1);for(let c=16;c<80;c++)mr[c]=(0,We.rotl)(mr[c-3]^mr[c-8]^mr[c-14]^mr[c-16],1);let{A:n,B:i,C:o,D:s,E:a}=this;for(let c=0;c<80;c++){let u,l;c<20?(u=(0,qr.Chi)(i,o,s),l=1518500249):c<40?(u=i^o^s,l=1859775393):c<60?(u=(0,qr.Maj)(i,o,s),l=2400959708):(u=i^o^s,l=3395469782);const h=(0,We.rotl)(n,5)+u+a+l+mr[c]|0;a=s,s=o,o=(0,We.rotl)(i,30),i=n,n=h}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,i,o,s,a)}roundClean(){(0,We.clean)(mr)}destroy(){this.set(0,0,0,0,0),(0,We.clean)(this.buffer)}}ft.SHA1=wp;ft.sha1=(0,We.createHasher)(()=>new wp);const Uw=Math.pow(2,32),Nw=Array.from({length:64},(e,t)=>Math.floor(Uw*Math.abs(Math.sin(t+1)))),fo=an.slice(0,4),Ms=new Uint32Array(16);let vp=class extends qr.HashMD{constructor(){super(64,16,8,!0),this.A=fo[0]|0,this.B=fo[1]|0,this.C=fo[2]|0,this.D=fo[3]|0}get(){const{A:t,B:r,C:n,D:i}=this;return[t,r,n,i]}set(t,r,n,i){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0}process(t,r){for(let a=0;a<16;a++,r+=4)Ms[a]=t.getUint32(r,!0);let{A:n,B:i,C:o,D:s}=this;for(let a=0;a<64;a++){let c,u,l;a<16?(c=(0,qr.Chi)(i,o,s),u=a,l=[7,12,17,22]):a<32?(c=(0,qr.Chi)(s,i,o),u=(5*a+1)%16,l=[5,9,14,20]):a<48?(c=i^o^s,u=(3*a+5)%16,l=[4,11,16,23]):(c=o^(i|~s),u=7*a%16,l=[6,10,15,21]),c=c+n+Nw[a]+Ms[u],n=s,s=o,o=i,i=i+(0,We.rotl)(c,l[a%4])}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,this.set(n,i,o,s)}roundClean(){(0,We.clean)(Ms)}destroy(){this.set(0,0,0,0),(0,We.clean)(this.buffer)}};ft.MD5=vp;ft.md5=(0,We.createHasher)(()=>new vp);const $w=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),_p=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),Lw=_p.map(e=>(9*e+5)%16),Ep=(()=>{const r=[[_p],[Lw]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(o=>$w[o]));return r})(),xp=Ep[0],Ap=Ep[1],Sp=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>Uint8Array.from(e)),Mw=xp.map((e,t)=>e.map(r=>Sp[t][r])),Hw=Ap.map((e,t)=>e.map(r=>Sp[t][r])),Dw=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),jw=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Sf(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}const lo=new Uint32Array(16);let Pp=class extends qr.HashMD{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:r,h2:n,h3:i,h4:o}=this;return[t,r,n,i,o]}set(t,r,n,i,o){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=o|0}process(t,r){for(let p=0;p<16;p++,r+=4)lo[p]=t.getUint32(r,!0);let n=this.h0|0,i=n,o=this.h1|0,s=o,a=this.h2|0,c=a,u=this.h3|0,l=u,h=this.h4|0,y=h;for(let p=0;p<5;p++){const b=4-p,v=Dw[p],E=jw[p],S=xp[p],P=Ap[p],A=Mw[p],w=Hw[p];for(let B=0;B<16;B++){const T=(0,We.rotl)(n+Sf(p,o,a,u)+lo[S[B]]+v,A[B])+h|0;n=h,h=u,u=(0,We.rotl)(a,10)|0,a=o,o=T}for(let B=0;B<16;B++){const T=(0,We.rotl)(i+Sf(b,s,c,l)+lo[P[B]]+E,w[B])+y|0;i=y,y=l,l=(0,We.rotl)(c,10)|0,c=s,s=T}}this.set(this.h1+a+l|0,this.h2+u+y|0,this.h3+h+i|0,this.h4+n+s|0,this.h0+o+c|0)}roundClean(){(0,We.clean)(lo)}destroy(){this.destroyed=!0,(0,We.clean)(this.buffer),this.set(0,0,0,0,0)}};ft.RIPEMD160=Pp;ft.ripemd160=(0,We.createHasher)(()=>new Pp);Object.defineProperty(Sn,"__esModule",{value:!0});Sn.sha1=Sn.SHA1=void 0;const Tp=ft;Sn.SHA1=Tp.SHA1;Sn.sha1=Tp.sha1;const Ip=_u(ig);(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.taggedHash=e.TAGGED_HASH_PREFIXES=e.TAGS=e.hash256=e.hash160=e.sha256=e.sha1=e.ripemd160=void 0;const t=Ow,r=Sn,n=Ip;function i(l){return Buffer.from((0,t.ripemd160)(Uint8Array.from(l)))}e.ripemd160=i;function o(l){return Buffer.from((0,r.sha1)(Uint8Array.from(l)))}e.sha1=o;function s(l){return Buffer.from((0,n.sha256)(Uint8Array.from(l)))}e.sha256=s;function a(l){return Buffer.from((0,t.ripemd160)((0,n.sha256)(Uint8Array.from(l))))}e.hash160=a;function c(l){return Buffer.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(l))))}e.hash256=c,e.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],e.TAGGED_HASH_PREFIXES={"BIP0340/challenge":Buffer.from([123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124,123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124]),"BIP0340/aux":Buffer.from([241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144,241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144]),"BIP0340/nonce":Buffer.from([7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47,7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47]),TapLeaf:Buffer.from([174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238,174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238]),TapBranch:Buffer.from([25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21,25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21]),TapSighash:Buffer.from([244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49,244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49]),TapTweak:Buffer.from([232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233,232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233]),"KeyAgg list":Buffer.from([72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240,72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240]),"KeyAgg coefficient":Buffer.from([191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129,191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129])};function u(l,h){return s(Buffer.concat([e.TAGGED_HASH_PREFIXES[l],h]))}e.taggedHash=u})(Cr);var Hs={},or={};Object.defineProperty(or,"__esModule",{value:!0});or.encode=or.decode=or.check=void 0;function qw(e){if(e.length<8||e.length>72||e[0]!==48||e[1]!==e.length-2||e[2]!==2)return!1;const t=e[3];if(t===0||5+t>=e.length||e[4+t]!==2)return!1;const r=e[5+t];return!(r===0||6+t+r!==e.length||e[4]&128||t>1&&e[4]===0&&!(e[5]&128)||e[t+6]&128||r>1&&e[t+6]===0&&!(e[t+7]&128))}or.check=qw;function Gw(e){if(e.length<8)throw new Error("DER sequence length is too short");if(e.length>72)throw new Error("DER sequence length is too long");if(e[0]!==48)throw new Error("Expected DER sequence");if(e[1]!==e.length-2)throw new Error("DER sequence length is invalid");if(e[2]!==2)throw new Error("Expected DER integer");const t=e[3];if(t===0)throw new Error("R length is zero");if(5+t>=e.length)throw new Error("R length is too long");if(e[4+t]!==2)throw new Error("Expected DER integer (2)");const r=e[5+t];if(r===0)throw new Error("S length is zero");if(6+t+r!==e.length)throw new Error("S length is invalid");if(e[4]&128)throw new Error("R value is negative");if(t>1&&e[4]===0&&!(e[5]&128))throw new Error("R value excessively padded");if(e[t+6]&128)throw new Error("S value is negative");if(r>1&&e[t+6]===0&&!(e[t+7]&128))throw new Error("S value excessively padded");return{r:e.slice(4,4+t),s:e.slice(6+t)}}or.decode=Gw;function zw(e,t){const r=e.length,n=t.length;if(r===0)throw new Error("R length is zero");if(n===0)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(e[0]&128)throw new Error("R value is negative");if(t[0]&128)throw new Error("S value is negative");if(r>1&&e[0]===0&&!(e[1]&128))throw new Error("R value excessively padded");if(n>1&&t[0]===0&&!(t[1]&128))throw new Error("S value excessively padded");const i=Buffer.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=e.length,e.copy(i,4),i[4+r]=2,i[5+r]=t.length,t.copy(i,6+r),i}or.encode=zw;var Kr={};Object.defineProperty(Kr,"__esModule",{value:!0});Kr.REVERSE_OPS=Kr.OPS=void 0;const Cc={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};Kr.OPS=Cc;const Bp={};Kr.REVERSE_OPS=Bp;for(const e of Object.keys(Cc)){const t=Cc[e];Bp[t]=e}var Pr={};Object.defineProperty(Pr,"__esModule",{value:!0});Pr.decode=Pr.encode=Pr.encodingLength=void 0;const Er=Kr;function kp(e){return e<Er.OPS.OP_PUSHDATA1?1:e<=255?2:e<=65535?3:5}Pr.encodingLength=kp;function Vw(e,t,r){const n=kp(t);return n===1?e.writeUInt8(t,r):n===2?(e.writeUInt8(Er.OPS.OP_PUSHDATA1,r),e.writeUInt8(t,r+1)):n===3?(e.writeUInt8(Er.OPS.OP_PUSHDATA2,r),e.writeUInt16LE(t,r+1)):(e.writeUInt8(Er.OPS.OP_PUSHDATA4,r),e.writeUInt32LE(t,r+1)),n}Pr.encode=Vw;function Ww(e,t){const r=e.readUInt8(t);let n,i;if(r<Er.OPS.OP_PUSHDATA1)n=r,i=1;else if(r===Er.OPS.OP_PUSHDATA1){if(t+2>e.length)return null;n=e.readUInt8(t+1),i=2}else if(r===Er.OPS.OP_PUSHDATA2){if(t+3>e.length)return null;n=e.readUInt16LE(t+1),i=3}else{if(t+5>e.length)return null;if(r!==Er.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=e.readUInt32LE(t+1),i=5}return{opcode:r,number:n,size:i}}Pr.decode=Ww;var Pn={};Object.defineProperty(Pn,"__esModule",{value:!0});Pn.encode=Pn.decode=void 0;function Kw(e,t,r){t=t||4,r=r===void 0?!0:r;const n=e.length;if(n===0)return 0;if(n>t)throw new TypeError("Script number overflow");if(r&&!(e[n-1]&127)&&(n<=1||!(e[n-2]&128)))throw new Error("Non-minimally encoded script number");if(n===5){const o=e.readUInt32LE(0),s=e.readUInt8(4);return s&128?-((s&-129)*4294967296+o):s*4294967296+o}let i=0;for(let o=0;o<n;++o)i|=e[o]<<8*o;return e[n-1]&128?-(i&~(128<<8*(n-1))):i}Pn.decode=Kw;function Yw(e){return e>2147483647?5:e>8388607?4:e>32767?3:e>127?2:e>0?1:0}function Xw(e){let t=Math.abs(e);const r=Yw(t),n=Buffer.allocUnsafe(r),i=e<0;for(let o=0;o<r;++o)n.writeUInt8(t&255,o),t>>=8;return n[r-1]&128?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n}Pn.encode=Xw;var Lr={},Pf;function Jw(){if(Pf)return Lr;Pf=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.encode=Lr.decode=void 0;const e=or,t=gt(),r=Ze,{typeforce:n}=r,i=Buffer.alloc(1,0);function o(u){let l=0;for(;u[l]===0;)++l;return l===u.length?i:(u=u.slice(l),u[0]&128?Buffer.concat([i,u],1+u.length):u)}function s(u){u[0]===0&&(u=u.slice(1));const l=Buffer.alloc(32,0),h=Math.max(0,32-u.length);return u.copy(l,h),l}function a(u){const l=u.readUInt8(u.length-1);if(!(0,t.isDefinedHashType)(l))throw new Error("Invalid hashType "+l);const h=e.decode(u.slice(0,-1)),y=s(h.r),p=s(h.s);return{signature:Buffer.concat([y,p],64),hashType:l}}Lr.decode=a;function c(u,l){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:u,hashType:l}),!(0,t.isDefinedHashType)(l))throw new Error("Invalid hashType "+l);const h=Buffer.allocUnsafe(1);h.writeUInt8(l,0);const y=o(u.slice(0,32)),p=o(u.slice(32,64));return Buffer.concat([e.encode(y,p),h])}return Lr.encode=c,Lr}var Tf;function gt(){return Tf||(Tf=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.signature=e.number=e.isCanonicalScriptSignature=e.isDefinedHashType=e.isCanonicalPubKey=e.toStack=e.fromASM=e.toASM=e.decompile=e.compile=e.countNonPushOnlyOPs=e.isPushOnly=e.OPS=void 0;const t=or,r=Kr;Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=Pr,i=Pn,o=Jw(),s=Ze,{typeforce:a}=s,c=r.OPS.OP_RESERVED;function u(C){return s.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 s.Buffer(C)||u(C)}function h(C){return s.Array(C)&&C.every(l)}e.isPushOnly=h;function y(C){return C.length-C.filter(l).length}e.countNonPushOnlyOPs=y;function p(C){if(C.length===0)return r.OPS.OP_0;if(C.length===1){if(C[0]>=1&&C[0]<=16)return c+C[0];if(C[0]===129)return r.OPS.OP_1NEGATE}}function b(C){return Buffer.isBuffer(C)}function v(C){return s.Array(C)}function E(C){return Buffer.isBuffer(C)}function S(C){if(b(C))return C;a(s.Array,C);const X=C.reduce((te,ee)=>E(ee)?ee.length===1&&p(ee)!==void 0?te+1:te+n.encodingLength(ee.length)+ee.length:te+1,0),Z=Buffer.allocUnsafe(X);let oe=0;if(C.forEach(te=>{if(E(te)){const ee=p(te);if(ee!==void 0){Z.writeUInt8(ee,oe),oe+=1;return}oe+=n.encode(Z,te.length,oe),te.copy(Z,oe),oe+=te.length}else Z.writeUInt8(te,oe),oe+=1}),oe!==Z.length)throw new Error("Could not decode chunks");return Z}e.compile=S;function P(C){if(v(C))return C;a(s.Buffer,C);const X=[];let Z=0;for(;Z<C.length;){const oe=C[Z];if(oe>r.OPS.OP_0&&oe<=r.OPS.OP_PUSHDATA4){const te=n.decode(C,Z);if(te===null||(Z+=te.size,Z+te.number>C.length))return null;const ee=C.slice(Z,Z+te.number);Z+=te.number;const ae=p(ee);ae!==void 0?X.push(ae):X.push(ee)}else X.push(oe),Z+=1}return X}e.decompile=P;function A(C){if(b(C)&&(C=P(C)),!C)throw new Error("Could not convert invalid chunks to ASM");return C.map(X=>{if(E(X)){const Z=p(X);if(Z===void 0)return X.toString("hex");X=Z}return r.REVERSE_OPS[X]}).join(" ")}e.toASM=A;function w(C){return a(s.String,C),S(C.split(" ").map(X=>r.OPS[X]!==void 0?r.OPS[X]:(a(s.Hex,X),Buffer.from(X,"hex"))))}e.fromASM=w;function B(C){return C=P(C),a(h,C),C.map(X=>E(X)?X:X===r.OPS.OP_0?Buffer.allocUnsafe(0):i.encode(X-c))}e.toStack=B;function T(C){return s.isPoint(C)}e.isCanonicalPubKey=T;function L(C){const X=C&-129;return X>0&&X<4}e.isDefinedHashType=L;function D(C){return!Buffer.isBuffer(C)||!L(C[C.length-1])?!1:t.check(C.slice(0,-1))}e.isCanonicalScriptSignature=D,e.number=i,e.signature=o}(Hs)),Hs}Object.defineProperty(Yi,"__esModule",{value:!0});Yi.Transaction=void 0;const Fe=Ve,tt=Cr,If=gt(),Qw=gt(),he=Ze,{typeforce:Ft}=he;function $t(e){const t=e.length;return Fe.varuint.encodingLength(t)+t}function Zw(e){const t=e.length;return Fe.varuint.encodingLength(t)+e.reduce((r,n)=>r+$t(n),0)}const _r=Buffer.allocUnsafe(0),Ds=[],js=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),Bf=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),e2=Buffer.from("ffffffffffffffff","hex"),t2={script:_r,valueBuffer:e2};function r2(e){return e.value!==void 0}class ue{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(t,r){const n=new Fe.BufferReader(t),i=new ue;i.version=n.readInt32();const o=n.readUInt8(),s=n.readUInt8();let a=!1;o===ue.ADVANCED_TRANSACTION_MARKER&&s===ue.ADVANCED_TRANSACTION_FLAG?a=!0:n.offset-=2;const c=n.readVarInt();for(let l=0;l<c;++l)i.ins.push({hash:n.readSlice(32),index:n.readUInt32(),script:n.readVarSlice(),sequence:n.readUInt32(),witness:Ds});const u=n.readVarInt();for(let l=0;l<u;++l)i.outs.push({value:n.readUInt64(),script:n.readVarSlice()});if(a){for(let l=0;l<c;++l)i.ins[l].witness=n.readVector();if(!i.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(i.locktime=n.readUInt32(),r)return i;if(n.offset!==t.length)throw new Error("Transaction has unexpected data");return i}static fromHex(t){return ue.fromBuffer(Buffer.from(t,"hex"),!1)}static isCoinbaseHash(t){Ft(he.Hash256bit,t);for(let r=0;r<32;++r)if(t[r]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&ue.isCoinbaseHash(this.ins[0].hash)}addInput(t,r,n,i){return Ft(he.tuple(he.Hash256bit,he.UInt32,he.maybe(he.UInt32),he.maybe(he.Buffer)),arguments),he.Null(n)&&(n=ue.DEFAULT_SEQUENCE),this.ins.push({hash:t,index:r,script:i||_r,sequence:n,witness:Ds})-1}addOutput(t,r){return Ft(he.tuple(he.Buffer,he.Satoshi),arguments),this.outs.push({script:t,value:r})-1}hasWitnesses(){return this.ins.some(t=>t.witness.length!==0)}stripWitnesses(){this.ins.forEach(t=>{t.witness=Ds})}weight(){const t=this.byteLength(!1),r=this.byteLength(!0);return t*3+r}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const r=t&&this.hasWitnesses();return(r?10:8)+Fe.varuint.encodingLength(this.ins.length)+Fe.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,i)=>n+40+$t(i.script),0)+this.outs.reduce((n,i)=>n+8+$t(i.script),0)+(r?this.ins.reduce((n,i)=>n+Zw(i.witness),0):0)}clone(){const t=new ue;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map(r=>({hash:r.hash,index:r.index,script:r.script,sequence:r.sequence,witness:r.witness})),t.outs=this.outs.map(r=>({script:r.script,value:r.value})),t}hashForSignature(t,r,n){if(Ft(he.tuple(he.UInt32,he.Buffer,he.Number),arguments),t>=this.ins.length)return Bf;const i=If.compile(If.decompile(r).filter(a=>a!==Qw.OPS.OP_CODESEPARATOR)),o=this.clone();if((n&31)===ue.SIGHASH_NONE)o.outs=[],o.ins.forEach((a,c)=>{c!==t&&(a.sequence=0)});else if((n&31)===ue.SIGHASH_SINGLE){if(t>=this.outs.length)return Bf;o.outs.length=t+1;for(let a=0;a<t;a++)o.outs[a]=t2;o.ins.forEach((a,c)=>{c!==t&&(a.sequence=0)})}n&ue.SIGHASH_ANYONECANPAY?(o.ins=[o.ins[t]],o.ins[0].script=i):(o.ins.forEach(a=>{a.script=_r}),o.ins[t].script=i);const s=Buffer.allocUnsafe(o.byteLength(!1)+4);return s.writeInt32LE(n,s.length-4),o.__toBuffer(s,0,!1),tt.hash256(s)}hashForWitnessV1(t,r,n,i,o,s){if(Ft(he.tuple(he.UInt32,Ft.arrayOf(he.Buffer),Ft.arrayOf(he.Satoshi),he.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=i===ue.SIGHASH_DEFAULT?ue.SIGHASH_ALL:i&ue.SIGHASH_OUTPUT_MASK,u=(i&ue.SIGHASH_INPUT_MASK)===ue.SIGHASH_ANYONECANPAY,l=a===ue.SIGHASH_NONE,h=a===ue.SIGHASH_SINGLE;let y=_r,p=_r,b=_r,v=_r,E=_r;if(!u){let w=Fe.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(B=>{w.writeSlice(B.hash),w.writeUInt32(B.index)}),y=tt.sha256(w.end()),w=Fe.BufferWriter.withCapacity(8*this.ins.length),n.forEach(B=>w.writeUInt64(B)),p=tt.sha256(w.end()),w=Fe.BufferWriter.withCapacity(r.map($t).reduce((B,T)=>B+T)),r.forEach(B=>w.writeVarSlice(B)),b=tt.sha256(w.end()),w=Fe.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(B=>w.writeUInt32(B.sequence)),v=tt.sha256(w.end())}if(l||h){if(h&&t<this.outs.length){const w=this.outs[t],B=Fe.BufferWriter.withCapacity(8+$t(w.script));B.writeUInt64(w.value),B.writeVarSlice(w.script),E=tt.sha256(B.end())}}else{const w=this.outs.map(T=>8+$t(T.script)).reduce((T,L)=>T+L),B=Fe.BufferWriter.withCapacity(w);this.outs.forEach(T=>{B.writeUInt64(T.value),B.writeVarSlice(T.script)}),E=tt.sha256(B.end())}const S=(o?2:0)+(s?1:0),P=174-(u?49:0)-(l?32:0)+(s?32:0)+(o?37:0),A=Fe.BufferWriter.withCapacity(P);if(A.writeUInt8(i),A.writeInt32(this.version),A.writeUInt32(this.locktime),A.writeSlice(y),A.writeSlice(p),A.writeSlice(b),A.writeSlice(v),l||h||A.writeSlice(E),A.writeUInt8(S),u){const w=this.ins[t];A.writeSlice(w.hash),A.writeUInt32(w.index),A.writeUInt64(n[t]),A.writeVarSlice(r[t]),A.writeUInt32(w.sequence)}else A.writeUInt32(t);if(s){const w=Fe.BufferWriter.withCapacity($t(s));w.writeVarSlice(s),A.writeSlice(tt.sha256(w.end()))}return h&&A.writeSlice(E),o&&(A.writeSlice(o),A.writeUInt8(0),A.writeUInt32(4294967295)),tt.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),A.end()]))}hashForWitnessV0(t,r,n,i){Ft(he.tuple(he.UInt32,he.Buffer,he.Satoshi,he.UInt32),arguments);let o=Buffer.from([]),s,a=js,c=js,u=js;if(i&ue.SIGHASH_ANYONECANPAY||(o=Buffer.allocUnsafe(36*this.ins.length),s=new Fe.BufferWriter(o,0),this.ins.forEach(h=>{s.writeSlice(h.hash),s.writeUInt32(h.index)}),c=tt.hash256(o)),!(i&ue.SIGHASH_ANYONECANPAY)&&(i&31)!==ue.SIGHASH_SINGLE&&(i&31)!==ue.SIGHASH_NONE&&(o=Buffer.allocUnsafe(4*this.ins.length),s=new Fe.BufferWriter(o,0),this.ins.forEach(h=>{s.writeUInt32(h.sequence)}),u=tt.hash256(o)),(i&31)!==ue.SIGHASH_SINGLE&&(i&31)!==ue.SIGHASH_NONE){const h=this.outs.reduce((y,p)=>y+8+$t(p.script),0);o=Buffer.allocUnsafe(h),s=new Fe.BufferWriter(o,0),this.outs.forEach(y=>{s.writeUInt64(y.value),s.writeVarSlice(y.script)}),a=tt.hash256(o)}else if((i&31)===ue.SIGHASH_SINGLE&&t<this.outs.length){const h=this.outs[t];o=Buffer.allocUnsafe(8+$t(h.script)),s=new Fe.BufferWriter(o,0),s.writeUInt64(h.value),s.writeVarSlice(h.script),a=tt.hash256(o)}o=Buffer.allocUnsafe(156+$t(r)),s=new Fe.BufferWriter(o,0);const l=this.ins[t];return s.writeInt32(this.version),s.writeSlice(c),s.writeSlice(u),s.writeSlice(l.hash),s.writeUInt32(l.index),s.writeVarSlice(r),s.writeUInt64(n),s.writeUInt32(l.sequence),s.writeSlice(a),s.writeUInt32(this.locktime),s.writeUInt32(i),tt.hash256(o)}getHash(t){return t&&this.isCoinbase()?Buffer.alloc(32,0):tt.hash256(this.__toBuffer(void 0,void 0,t))}getId(){return(0,Fe.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(t,r){return this.__toBuffer(t,r,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(t,r){Ft(he.tuple(he.Number,he.Buffer),arguments),this.ins[t].script=r}setWitness(t,r){Ft(he.tuple(he.Number,[he.Buffer]),arguments),this.ins[t].witness=r}__toBuffer(t,r,n=!1){t||(t=Buffer.allocUnsafe(this.byteLength(n)));const i=new Fe.BufferWriter(t,r||0);i.writeInt32(this.version);const o=n&&this.hasWitnesses();return o&&(i.writeUInt8(ue.ADVANCED_TRANSACTION_MARKER),i.writeUInt8(ue.ADVANCED_TRANSACTION_FLAG)),i.writeVarInt(this.ins.length),this.ins.forEach(s=>{i.writeSlice(s.hash),i.writeUInt32(s.index),i.writeVarSlice(s.script),i.writeUInt32(s.sequence)}),i.writeVarInt(this.outs.length),this.outs.forEach(s=>{r2(s)?i.writeUInt64(s.value):i.writeSlice(s.valueBuffer),i.writeVarSlice(s.script)}),o&&this.ins.forEach(s=>{i.writeVector(s.witness)}),i.writeUInt32(this.locktime),r!==void 0?t.slice(r,i.offset):t}}Yi.Transaction=ue;ue.DEFAULT_SEQUENCE=4294967295;ue.SIGHASH_DEFAULT=0;ue.SIGHASH_ALL=1;ue.SIGHASH_NONE=2;ue.SIGHASH_SINGLE=3;ue.SIGHASH_ANYONECANPAY=128;ue.SIGHASH_OUTPUT_MASK=3;ue.SIGHASH_INPUT_MASK=128;ue.ADVANCED_TRANSACTION_MARKER=0;ue.ADVANCED_TRANSACTION_FLAG=1;var _e={},Xi={};Object.defineProperty(Xi,"__esModule",{value:!0});const n2=9007199254740991;function Iu(e){if(e<0||e>n2||e%1!==0)throw new RangeError("value out of range")}function oi(e,t,r){if(Iu(e),t||(t=Buffer.allocUnsafe(Op(e))),!Buffer.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),e<253?(t.writeUInt8(e,r),Object.assign(oi,{bytes:1})):e<=65535?(t.writeUInt8(253,r),t.writeUInt16LE(e,r+1),Object.assign(oi,{bytes:3})):e<=4294967295?(t.writeUInt8(254,r),t.writeUInt32LE(e,r+1),Object.assign(oi,{bytes:5})):(t.writeUInt8(255,r),t.writeUInt32LE(e>>>0,r+1),t.writeUInt32LE(e/4294967296|0,r+5),Object.assign(oi,{bytes:9})),t}Xi.encode=oi;function si(e,t){if(!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");t||(t=0);const r=e.readUInt8(t);if(r<253)return Object.assign(si,{bytes:1}),r;if(r===253)return Object.assign(si,{bytes:3}),e.readUInt16LE(t+1);if(r===254)return Object.assign(si,{bytes:5}),e.readUInt32LE(t+1);{Object.assign(si,{bytes:9});const n=e.readUInt32LE(t+1),o=e.readUInt32LE(t+5)*4294967296+n;return Iu(o),o}}Xi.decode=si;function Op(e){return Iu(e),e<253?1:e<=65535?3:e<=4294967295?5:9}Xi.encodingLength=Op;var qs={},ns={},Qe={};Object.defineProperty(Qe,"__esModule",{value:!0});Qe.testnet=Qe.regtest=Qe.bitcoin=void 0;Qe.bitcoin={messagePrefix:`Bitcoin Signed Message:
48
+ `,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};Qe.regtest={messagePrefix:`Bitcoin Signed Message:
49
+ `,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};Qe.testnet={messagePrefix:`Bitcoin Signed Message:
50
+ `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var mt={};Object.defineProperty(mt,"__esModule",{value:!0});mt.value=mt.prop=void 0;function i2(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){const n=r.call(this);return this[t]=n,n},set(n){Object.defineProperty(this,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}})}mt.prop=i2;function o2(e){let t;return()=>(t!==void 0||(t=e()),t)}mt.value=o2;Object.defineProperty(ns,"__esModule",{value:!0});ns.p2data=void 0;const s2=Qe,xo=gt(),Ut=Ze,kf=mt,Of=xo.OPS;function a2(e,t){if(!e.data&&!e.output)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Ut.typeforce)({network:Ut.typeforce.maybe(Ut.typeforce.Object),output:Ut.typeforce.maybe(Ut.typeforce.Buffer),data:Ut.typeforce.maybe(Ut.typeforce.arrayOf(Ut.typeforce.Buffer))},e);const n={name:"embed",network:e.network||s2.bitcoin};if(kf.prop(n,"output",()=>{if(e.data)return xo.compile([Of.OP_RETURN].concat(e.data))}),kf.prop(n,"data",()=>{if(e.output)return xo.decompile(e.output).slice(1)}),t.validate&&e.output){const i=xo.decompile(e.output);if(i[0]!==Of.OP_RETURN)throw new TypeError("Output is invalid");if(!i.slice(1).every(Ut.typeforce.Buffer))throw new TypeError("Output is invalid");if(e.data&&!(0,Ut.stacksEqual)(e.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,e)}ns.p2data=a2;var is={};Object.defineProperty(is,"__esModule",{value:!0});is.p2ms=void 0;const c2=Qe,cn=gt(),Ce=Ze,br=mt,un=cn.OPS,ho=un.OP_RESERVED;function u2(e,t){if(!e.input&&!e.output&&!(e.pubkeys&&e.m!==void 0)&&!e.signatures)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{});function r(c){return cn.isCanonicalScriptSignature(c)||(t.allowIncomplete&&c===un.OP_0)!==void 0}(0,Ce.typeforce)({network:Ce.typeforce.maybe(Ce.typeforce.Object),m:Ce.typeforce.maybe(Ce.typeforce.Number),n:Ce.typeforce.maybe(Ce.typeforce.Number),output:Ce.typeforce.maybe(Ce.typeforce.Buffer),pubkeys:Ce.typeforce.maybe(Ce.typeforce.arrayOf(Ce.isPoint)),signatures:Ce.typeforce.maybe(Ce.typeforce.arrayOf(r)),input:Ce.typeforce.maybe(Ce.typeforce.Buffer)},e);const i={network:e.network||c2.bitcoin};let o=[],s=!1;function a(c){s||(s=!0,o=cn.decompile(c),i.m=o[0]-ho,i.n=o[o.length-2]-ho,i.pubkeys=o.slice(1,-2))}if(br.prop(i,"output",()=>{if(e.m&&i.n&&e.pubkeys)return cn.compile([].concat(ho+e.m,e.pubkeys,ho+i.n,un.OP_CHECKMULTISIG))}),br.prop(i,"m",()=>{if(i.output)return a(i.output),i.m}),br.prop(i,"n",()=>{if(i.pubkeys)return i.pubkeys.length}),br.prop(i,"pubkeys",()=>{if(e.output)return a(e.output),i.pubkeys}),br.prop(i,"signatures",()=>{if(e.input)return cn.decompile(e.input).slice(1)}),br.prop(i,"input",()=>{if(e.signatures)return cn.compile([un.OP_0].concat(e.signatures))}),br.prop(i,"witness",()=>{if(i.input)return[]}),br.prop(i,"name",()=>{if(!(!i.m||!i.n))return`p2ms(${i.m} of ${i.n})`}),t.validate){if(e.output){if(a(e.output),!Ce.typeforce.Number(o[0]))throw new TypeError("Output is invalid");if(!Ce.typeforce.Number(o[o.length-2]))throw new TypeError("Output is invalid");if(o[o.length-1]!==un.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(i.m<=0||i.n>16||i.m>i.n||i.n!==o.length-3)throw new TypeError("Output is invalid");if(!i.pubkeys.every(c=>(0,Ce.isPoint)(c)))throw new TypeError("Output is invalid");if(e.m!==void 0&&e.m!==i.m)throw new TypeError("m mismatch");if(e.n!==void 0&&e.n!==i.n)throw new TypeError("n mismatch");if(e.pubkeys&&!(0,Ce.stacksEqual)(e.pubkeys,i.pubkeys))throw new TypeError("Pubkeys mismatch")}if(e.pubkeys){if(e.n!==void 0&&e.n!==e.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(i.n=e.pubkeys.length,i.n<i.m)throw new TypeError("Pubkey count cannot be less than m")}if(e.signatures){if(e.signatures.length<i.m)throw new TypeError("Not enough signatures provided");if(e.signatures.length>i.m)throw new TypeError("Too many signatures provided")}if(e.input){if(e.input[0]!==un.OP_0)throw new TypeError("Input is invalid");if(i.signatures.length===0||!i.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(e.signatures&&!(0,Ce.stacksEqual)(e.signatures,i.signatures))throw new TypeError("Signature mismatch");if(e.m!==void 0&&e.m!==e.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(i,e)}is.p2ms=u2;var os={};Object.defineProperty(os,"__esModule",{value:!0});os.p2pk=void 0;const f2=Qe,fn=gt(),Pt=Ze,on=mt,Rf=fn.OPS;function l2(e,t){if(!e.input&&!e.output&&!e.pubkey&&!e.input&&!e.signature)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Pt.typeforce)({network:Pt.typeforce.maybe(Pt.typeforce.Object),output:Pt.typeforce.maybe(Pt.typeforce.Buffer),pubkey:Pt.typeforce.maybe(Pt.isPoint),signature:Pt.typeforce.maybe(fn.isCanonicalScriptSignature),input:Pt.typeforce.maybe(Pt.typeforce.Buffer)},e);const r=on.value(()=>fn.decompile(e.input)),i={name:"p2pk",network:e.network||f2.bitcoin};if(on.prop(i,"output",()=>{if(e.pubkey)return fn.compile([e.pubkey,Rf.OP_CHECKSIG])}),on.prop(i,"pubkey",()=>{if(e.output)return e.output.slice(1,-1)}),on.prop(i,"signature",()=>{if(e.input)return r()[0]}),on.prop(i,"input",()=>{if(e.signature)return fn.compile([e.signature])}),on.prop(i,"witness",()=>{if(i.input)return[]}),t.validate){if(e.output){if(e.output[e.output.length-1]!==Rf.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,Pt.isPoint)(i.pubkey))throw new TypeError("Output pubkey is invalid");if(e.pubkey&&!e.pubkey.equals(i.pubkey))throw new TypeError("Pubkey mismatch")}if(e.signature&&e.input&&!e.input.equals(i.input))throw new TypeError("Signature mismatch");if(e.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!fn.isCanonicalScriptSignature(i.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(i,e)}os.p2pk=l2;var ss={};function d2(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),o=i.charCodeAt(0);if(t[o]!==255)throw new TypeError(i+" is ambiguous");t[o]=n}var s=e.length,a=e.charAt(0),c=Math.log(s)/Math.log(256),u=Math.log(256)/Math.log(s);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,v=0,E=0,S=p.length;E!==S&&p[E]===0;)E++,b++;for(var P=(S-E)*u+1>>>0,A=new Uint8Array(P);E!==S;){for(var w=p[E],B=0,T=P-1;(w!==0||B<v)&&T!==-1;T--,B++)w+=256*A[T]>>>0,A[T]=w%s>>>0,w=w/s>>>0;if(w!==0)throw new Error("Non-zero carry");v=B,E++}for(var L=P-v;L!==P&&A[L]===0;)L++;for(var D=a.repeat(b);L<P;++L)D+=e.charAt(A[L]);return D}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;for(var b=0,v=0,E=0;p[b]===a;)v++,b++;for(var S=(p.length-b)*c+1>>>0,P=new Uint8Array(S);p[b];){var A=p.charCodeAt(b);if(A>255)return;var w=t[A];if(w===255)return;for(var B=0,T=S-1;(w!==0||B<E)&&T!==-1;T--,B++)w+=s*P[T]>>>0,P[T]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");E=B,b++}for(var L=S-E;L!==S&&P[L]===0;)L++;for(var D=new Uint8Array(v+(S-L)),C=v;L!==S;)D[C++]=P[L++];return D}function y(p){var b=h(p);if(b)return b;throw new Error("Non-base"+s+" character")}return{encode:l,decodeUnsafe:h,decode:y}}var h2=d2;const p2=h2,y2="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var m2=p2(y2),Gs=m2,b2=function(e){function t(o){var s=Uint8Array.from(o),a=e(s),c=s.length+4,u=new Uint8Array(c);return u.set(s,0),u.set(a.subarray(0,4),s.length),Gs.encode(u,c)}function r(o){var s=o.slice(0,-4),a=o.slice(-4),c=e(s);if(!(a[0]^c[0]|a[1]^c[1]|a[2]^c[2]|a[3]^c[3]))return s}function n(o){var s=Gs.decodeUnsafe(o);if(s)return r(s)}function i(o){var s=Gs.decode(o),a=r(s);if(!a)throw new Error("Invalid checksum");return a}return{encode:t,decode:i,decodeUnsafe:n}},{sha256:Cf}=Ip,g2=b2;function w2(e){return Cf(Cf(e))}var Bu=g2(w2);Object.defineProperty(ss,"__esModule",{value:!0});ss.p2pkh=void 0;const zs=Cr,v2=Qe,ln=gt(),rt=Ze,Jt=mt,Ff=Bu,gr=ln.OPS;function _2(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,rt.typeforce)({network:rt.typeforce.maybe(rt.typeforce.Object),address:rt.typeforce.maybe(rt.typeforce.String),hash:rt.typeforce.maybe(rt.typeforce.BufferN(20)),output:rt.typeforce.maybe(rt.typeforce.BufferN(25)),pubkey:rt.typeforce.maybe(rt.isPoint),signature:rt.typeforce.maybe(ln.isCanonicalScriptSignature),input:rt.typeforce.maybe(rt.typeforce.Buffer)},e);const r=Jt.value(()=>{const s=Buffer.from(Ff.decode(e.address)),a=s.readUInt8(0),c=s.slice(1);return{version:a,hash:c}}),n=Jt.value(()=>ln.decompile(e.input)),i=e.network||v2.bitcoin,o={name:"p2pkh",network:i};if(Jt.prop(o,"address",()=>{if(!o.hash)return;const s=Buffer.allocUnsafe(21);return s.writeUInt8(i.pubKeyHash,0),o.hash.copy(s,1),Ff.encode(s)}),Jt.prop(o,"hash",()=>{if(e.output)return e.output.slice(3,23);if(e.address)return r().hash;if(e.pubkey||o.pubkey)return zs.hash160(e.pubkey||o.pubkey)}),Jt.prop(o,"output",()=>{if(o.hash)return ln.compile([gr.OP_DUP,gr.OP_HASH160,o.hash,gr.OP_EQUALVERIFY,gr.OP_CHECKSIG])}),Jt.prop(o,"pubkey",()=>{if(e.input)return n()[1]}),Jt.prop(o,"signature",()=>{if(e.input)return n()[0]}),Jt.prop(o,"input",()=>{if(e.pubkey&&e.signature)return ln.compile([e.signature,e.pubkey])}),Jt.prop(o,"witness",()=>{if(o.input)return[]}),t.validate){let s=Buffer.from([]);if(e.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");s=r().hash}if(e.hash){if(s.length>0&&!s.equals(e.hash))throw new TypeError("Hash mismatch");s=e.hash}if(e.output){if(e.output.length!==25||e.output[0]!==gr.OP_DUP||e.output[1]!==gr.OP_HASH160||e.output[2]!==20||e.output[23]!==gr.OP_EQUALVERIFY||e.output[24]!==gr.OP_CHECKSIG)throw new TypeError("Output is invalid");const a=e.output.slice(3,23);if(s.length>0&&!s.equals(a))throw new TypeError("Hash mismatch");s=a}if(e.pubkey){const a=zs.hash160(e.pubkey);if(s.length>0&&!s.equals(a))throw new TypeError("Hash mismatch");s=a}if(e.input){const a=n();if(a.length!==2)throw new TypeError("Input is invalid");if(!ln.isCanonicalScriptSignature(a[0]))throw new TypeError("Input has invalid signature");if(!(0,rt.isPoint)(a[1]))throw new TypeError("Input has invalid pubkey");if(e.signature&&!e.signature.equals(a[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(a[1]))throw new TypeError("Pubkey mismatch");const c=zs.hash160(a[1]);if(s.length>0&&!s.equals(c))throw new TypeError("Hash mismatch")}}return Object.assign(o,e)}ss.p2pkh=_2;var as={};Object.defineProperty(as,"__esModule",{value:!0});as.p2sh=void 0;const Uf=Cr,E2=Qe,Lt=gt(),xe=Ze,Nt=mt,Nf=Bu,Kn=Lt.OPS;function x2(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,xe.typeforce)({network:xe.typeforce.maybe(xe.typeforce.Object),address:xe.typeforce.maybe(xe.typeforce.String),hash:xe.typeforce.maybe(xe.typeforce.BufferN(20)),output:xe.typeforce.maybe(xe.typeforce.BufferN(23)),redeem:xe.typeforce.maybe({network:xe.typeforce.maybe(xe.typeforce.Object),output:xe.typeforce.maybe(xe.typeforce.Buffer),input:xe.typeforce.maybe(xe.typeforce.Buffer),witness:xe.typeforce.maybe(xe.typeforce.arrayOf(xe.typeforce.Buffer))}),input:xe.typeforce.maybe(xe.typeforce.Buffer),witness:xe.typeforce.maybe(xe.typeforce.arrayOf(xe.typeforce.Buffer))},e);let r=e.network;r||(r=e.redeem&&e.redeem.network||E2.bitcoin);const n={network:r},i=Nt.value(()=>{const a=Buffer.from(Nf.decode(e.address)),c=a.readUInt8(0),u=a.slice(1);return{version:c,hash:u}}),o=Nt.value(()=>Lt.decompile(e.input)),s=Nt.value(()=>{const a=o(),c=a[a.length-1];return{network:r,output:c===Kn.OP_FALSE?Buffer.from([]):c,input:Lt.compile(a.slice(0,-1)),witness:e.witness||[]}});if(Nt.prop(n,"address",()=>{if(!n.hash)return;const a=Buffer.allocUnsafe(21);return a.writeUInt8(n.network.scriptHash,0),n.hash.copy(a,1),Nf.encode(a)}),Nt.prop(n,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return i().hash;if(n.redeem&&n.redeem.output)return Uf.hash160(n.redeem.output)}),Nt.prop(n,"output",()=>{if(n.hash)return Lt.compile([Kn.OP_HASH160,n.hash,Kn.OP_EQUAL])}),Nt.prop(n,"redeem",()=>{if(e.input)return s()}),Nt.prop(n,"input",()=>{if(!(!e.redeem||!e.redeem.input||!e.redeem.output))return Lt.compile([].concat(Lt.decompile(e.redeem.input),e.redeem.output))}),Nt.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),Nt.prop(n,"name",()=>{const a=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&a.push(n.redeem.name),a.join("-")}),t.validate){let a=Buffer.from([]);if(e.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(i().hash.length!==20)throw new TypeError("Invalid address");a=i().hash}if(e.hash){if(a.length>0&&!a.equals(e.hash))throw new TypeError("Hash mismatch");a=e.hash}if(e.output){if(e.output.length!==23||e.output[0]!==Kn.OP_HASH160||e.output[1]!==20||e.output[22]!==Kn.OP_EQUAL)throw new TypeError("Output is invalid");const u=e.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=Lt.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(Lt.countNonPushOnlyOPs(l)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const h=Uf.hash160(u.output);if(a.length>0&&!a.equals(h))throw new TypeError("Hash mismatch");a=h}if(u.input){const l=u.input.length>0,h=u.witness&&u.witness.length>0;if(!l&&!h)throw new TypeError("Empty input");if(l&&h)throw new TypeError("Input and witness provided");if(l){const y=Lt.decompile(u.input);if(!Lt.isPushOnly(y))throw new TypeError("Non push-only scriptSig")}}};if(e.input){const u=o();if(!u||u.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(s().output))throw new TypeError("Input is invalid");c(s())}if(e.redeem){if(e.redeem.network&&e.redeem.network!==r)throw new TypeError("Network mismatch");if(e.input){const u=s();if(e.redeem.output&&!e.redeem.output.equals(u.output))throw new TypeError("Redeem.output mismatch");if(e.redeem.input&&!e.redeem.input.equals(u.input))throw new TypeError("Redeem.input mismatch")}c(e.redeem)}if(e.witness&&e.redeem&&e.redeem.witness&&!(0,xe.stacksEqual)(e.redeem.witness,e.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,e)}as.p2sh=x2;var cs={},fr={};Object.defineProperty(fr,"__esModule",{value:!0});fr.bech32m=fr.bech32=void 0;const Co="qpzry9x8gf2tvdw0s3jn54khce6mua7l",Rp={};for(let e=0;e<Co.length;e++){const t=Co.charAt(e);Rp[t]=e}function bn(e){const t=e>>25;return(e&33554431)<<5^-(t>>0&1)&996825010^-(t>>1&1)&642813549^-(t>>2&1)&513874426^-(t>>3&1)&1027748829^-(t>>4&1)&705979059}function $f(e){let t=1;for(let r=0;r<e.length;++r){const n=e.charCodeAt(r);if(n<33||n>126)return"Invalid prefix ("+e+")";t=bn(t)^n>>5}t=bn(t);for(let r=0;r<e.length;++r){const n=e.charCodeAt(r);t=bn(t)^n&31}return t}function ku(e,t,r,n){let i=0,o=0;const s=(1<<r)-1,a=[];for(let c=0;c<e.length;++c)for(i=i<<t|e[c],o+=t;o>=r;)o-=r,a.push(i>>o&s);if(n)o>0&&a.push(i<<r-o&s);else{if(o>=t)return"Excess padding";if(i<<r-o&s)return"Non-zero padding"}return a}function A2(e){return ku(e,8,5,!0)}function S2(e){const t=ku(e,5,8,!1);if(Array.isArray(t))return t}function P2(e){const t=ku(e,5,8,!1);if(Array.isArray(t))return t;throw new Error(t)}function Cp(e){let t;e==="bech32"?t=1:t=734539939;function r(s,a,c){if(c=c||90,s.length+7+a.length>c)throw new TypeError("Exceeds length limit");s=s.toLowerCase();let u=$f(s);if(typeof u=="string")throw new Error(u);let l=s+"1";for(let h=0;h<a.length;++h){const y=a[h];if(y>>5)throw new Error("Non 5-bit word");u=bn(u)^y,l+=Co.charAt(y)}for(let h=0;h<6;++h)u=bn(u);u^=t;for(let h=0;h<6;++h){const y=u>>(5-h)*5&31;l+=Co.charAt(y)}return l}function n(s,a){if(a=a||90,s.length<8)return s+" too short";if(s.length>a)return"Exceeds length limit";const c=s.toLowerCase(),u=s.toUpperCase();if(s!==c&&s!==u)return"Mixed-case string "+s;s=c;const l=s.lastIndexOf("1");if(l===-1)return"No separator character for "+s;if(l===0)return"Missing prefix for "+s;const h=s.slice(0,l),y=s.slice(l+1);if(y.length<6)return"Data too short";let p=$f(h);if(typeof p=="string")return p;const b=[];for(let v=0;v<y.length;++v){const E=y.charAt(v),S=Rp[E];if(S===void 0)return"Unknown character "+E;p=bn(p)^S,!(v+6>=y.length)&&b.push(S)}return p!==t?"Invalid checksum for "+s:{prefix:h,words:b}}function i(s,a){const c=n(s,a);if(typeof c=="object")return c}function o(s,a){const c=n(s,a);if(typeof c=="object")return c;throw new Error(c)}return{decodeUnsafe:i,decode:o,encode:r,toWords:A2,fromWordsUnsafe:S2,fromWords:P2}}fr.bech32=Cp("bech32");fr.bech32m=Cp("bech32m");Object.defineProperty(cs,"__esModule",{value:!0});cs.p2wpkh=void 0;const Vs=Cr,T2=Qe,Ao=gt(),Ue=Ze,wr=mt,po=fr,Lf=Ao.OPS,I2=Buffer.alloc(0);function B2(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Ue.typeforce)({address:Ue.typeforce.maybe(Ue.typeforce.String),hash:Ue.typeforce.maybe(Ue.typeforce.BufferN(20)),input:Ue.typeforce.maybe(Ue.typeforce.BufferN(0)),network:Ue.typeforce.maybe(Ue.typeforce.Object),output:Ue.typeforce.maybe(Ue.typeforce.BufferN(22)),pubkey:Ue.typeforce.maybe(Ue.isPoint),signature:Ue.typeforce.maybe(Ao.isCanonicalScriptSignature),witness:Ue.typeforce.maybe(Ue.typeforce.arrayOf(Ue.typeforce.Buffer))},e);const r=wr.value(()=>{const o=po.bech32.decode(e.address),s=o.words.shift(),a=po.bech32.fromWords(o.words);return{version:s,prefix:o.prefix,data:Buffer.from(a)}}),n=e.network||T2.bitcoin,i={name:"p2wpkh",network:n};if(wr.prop(i,"address",()=>{if(!i.hash)return;const o=po.bech32.toWords(i.hash);return o.unshift(0),po.bech32.encode(n.bech32,o)}),wr.prop(i,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return r().data;if(e.pubkey||i.pubkey)return Vs.hash160(e.pubkey||i.pubkey)}),wr.prop(i,"output",()=>{if(i.hash)return Ao.compile([Lf.OP_0,i.hash])}),wr.prop(i,"pubkey",()=>{if(e.pubkey)return e.pubkey;if(e.witness)return e.witness[1]}),wr.prop(i,"signature",()=>{if(e.witness)return e.witness[0]}),wr.prop(i,"input",()=>{if(i.witness)return I2}),wr.prop(i,"witness",()=>{if(e.pubkey&&e.signature)return[e.signature,e.pubkey]}),t.validate){let o=Buffer.from([]);if(e.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==20)throw new TypeError("Invalid address data");o=r().data}if(e.hash){if(o.length>0&&!o.equals(e.hash))throw new TypeError("Hash mismatch");o=e.hash}if(e.output){if(e.output.length!==22||e.output[0]!==Lf.OP_0||e.output[1]!==20)throw new TypeError("Output is invalid");if(o.length>0&&!o.equals(e.output.slice(2)))throw new TypeError("Hash mismatch");o=e.output.slice(2)}if(e.pubkey){const s=Vs.hash160(e.pubkey);if(o.length>0&&!o.equals(s))throw new TypeError("Hash mismatch");if(o=s,!(0,Ue.isPoint)(e.pubkey)||e.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(e.witness){if(e.witness.length!==2)throw new TypeError("Witness is invalid");if(!Ao.isCanonicalScriptSignature(e.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,Ue.isPoint)(e.witness[1])||e.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(e.signature&&!e.signature.equals(e.witness[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(e.witness[1]))throw new TypeError("Pubkey mismatch");const s=Vs.hash160(e.witness[1]);if(o.length>0&&!o.equals(s))throw new TypeError("Hash mismatch")}}return Object.assign(i,e)}cs.p2wpkh=B2;var us={};Object.defineProperty(us,"__esModule",{value:!0});us.p2wsh=void 0;const Mf=Cr,k2=Qe,er=gt(),Ee=Ze,Qt=mt,yo=fr,Hf=er.OPS,Ws=Buffer.alloc(0);function mo(e){return!!(Buffer.isBuffer(e)&&e.length===65&&e[0]===4&&(0,Ee.isPoint)(e))}function O2(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Ee.typeforce)({network:Ee.typeforce.maybe(Ee.typeforce.Object),address:Ee.typeforce.maybe(Ee.typeforce.String),hash:Ee.typeforce.maybe(Ee.typeforce.BufferN(32)),output:Ee.typeforce.maybe(Ee.typeforce.BufferN(34)),redeem:Ee.typeforce.maybe({input:Ee.typeforce.maybe(Ee.typeforce.Buffer),network:Ee.typeforce.maybe(Ee.typeforce.Object),output:Ee.typeforce.maybe(Ee.typeforce.Buffer),witness:Ee.typeforce.maybe(Ee.typeforce.arrayOf(Ee.typeforce.Buffer))}),input:Ee.typeforce.maybe(Ee.typeforce.BufferN(0)),witness:Ee.typeforce.maybe(Ee.typeforce.arrayOf(Ee.typeforce.Buffer))},e);const r=Qt.value(()=>{const s=yo.bech32.decode(e.address),a=s.words.shift(),c=yo.bech32.fromWords(s.words);return{version:a,prefix:s.prefix,data:Buffer.from(c)}}),n=Qt.value(()=>er.decompile(e.redeem.input));let i=e.network;i||(i=e.redeem&&e.redeem.network||k2.bitcoin);const o={network:i};if(Qt.prop(o,"address",()=>{if(!o.hash)return;const s=yo.bech32.toWords(o.hash);return s.unshift(0),yo.bech32.encode(i.bech32,s)}),Qt.prop(o,"hash",()=>{if(e.output)return e.output.slice(2);if(e.address)return r().data;if(o.redeem&&o.redeem.output)return Mf.sha256(o.redeem.output)}),Qt.prop(o,"output",()=>{if(o.hash)return er.compile([Hf.OP_0,o.hash])}),Qt.prop(o,"redeem",()=>{if(e.witness)return{output:e.witness[e.witness.length-1],input:Ws,witness:e.witness.slice(0,-1)}}),Qt.prop(o,"input",()=>{if(o.witness)return Ws}),Qt.prop(o,"witness",()=>{if(e.redeem&&e.redeem.input&&e.redeem.input.length>0&&e.redeem.output&&e.redeem.output.length>0){const s=er.toStack(n());return o.redeem=Object.assign({witness:s},e.redeem),o.redeem.input=Ws,[].concat(s,e.redeem.output)}if(e.redeem&&e.redeem.output&&e.redeem.witness)return[].concat(e.redeem.witness,e.redeem.output)}),Qt.prop(o,"name",()=>{const s=["p2wsh"];return o.redeem!==void 0&&o.redeem.name!==void 0&&s.push(o.redeem.name),s.join("-")}),t.validate){let s=Buffer.from([]);if(e.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==32)throw new TypeError("Invalid address data");s=r().data}if(e.hash){if(s.length>0&&!s.equals(e.hash))throw new TypeError("Hash mismatch");s=e.hash}if(e.output){if(e.output.length!==34||e.output[0]!==Hf.OP_0||e.output[1]!==32)throw new TypeError("Output is invalid");const a=e.output.slice(2);if(s.length>0&&!s.equals(a))throw new TypeError("Hash mismatch");s=a}if(e.redeem){if(e.redeem.network&&e.redeem.network!==i)throw new TypeError("Network mismatch");if(e.redeem.input&&e.redeem.input.length>0&&e.redeem.witness&&e.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(e.redeem.output){const a=er.decompile(e.redeem.output);if(!a||a.length<1)throw new TypeError("Redeem.output is invalid");if(e.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(er.countNonPushOnlyOPs(a)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const c=Mf.sha256(e.redeem.output);if(s.length>0&&!s.equals(c))throw new TypeError("Hash mismatch");s=c}if(e.redeem.input&&!er.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(e.witness&&e.redeem.witness&&!(0,Ee.stacksEqual)(e.witness,e.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(e.redeem.input&&n().some(mo)||e.redeem.output&&(er.decompile(e.redeem.output)||[]).some(mo))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(e.witness&&e.witness.length>0){const a=e.witness[e.witness.length-1];if(e.redeem&&e.redeem.output&&!e.redeem.output.equals(a))throw new TypeError("Witness and redeem.output mismatch");if(e.witness.some(mo)||(er.decompile(a)||[]).some(mo))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(o,e)}us.p2wsh=O2;var Yn={},Yr={};Object.defineProperty(Yr,"__esModule",{value:!0});Yr.getEccLib=Yr.initEccLib=void 0;const ai={};function R2(e,t){e?e!==ai.eccLib&&(t!=null&&t.DANGER_DO_NOT_VERIFY_ECCLIB||F2(e),ai.eccLib=e):ai.eccLib=e}Yr.initEccLib=R2;function C2(){if(!ai.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return ai.eccLib}Yr.getEccLib=C2;const Zt=e=>Buffer.from(e,"hex");function F2(e){_t(typeof e.isXOnlyPoint=="function"),_t(e.isXOnlyPoint(Zt("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),_t(e.isXOnlyPoint(Zt("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),_t(e.isXOnlyPoint(Zt("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),_t(e.isXOnlyPoint(Zt("0000000000000000000000000000000000000000000000000000000000000001"))),_t(!e.isXOnlyPoint(Zt("0000000000000000000000000000000000000000000000000000000000000000"))),_t(!e.isXOnlyPoint(Zt("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),_t(typeof e.xOnlyPointAddTweak=="function"),U2.forEach(t=>{const r=e.xOnlyPointAddTweak(Zt(t.pubkey),Zt(t.tweak));t.result===null?_t(r===null):(_t(r!==null),_t(r.parity===t.parity),_t(Buffer.from(r.xOnlyPubkey).equals(Zt(t.result))))})}function _t(e){if(!e)throw new Error("ecc library invalid")}const U2=[{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 Ou={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.tweakKey=e.tapTweakHash=e.tapleafHash=e.findScriptPath=e.toHashTree=e.rootHashFromPath=e.MAX_TAPTREE_DEPTH=e.LEAF_VERSION_TAPSCRIPT=void 0;const t=Bt,r=Yr,n=Cr,i=Ve,o=Ze;e.LEAF_VERSION_TAPSCRIPT=192,e.MAX_TAPTREE_DEPTH=128;const s=v=>"left"in v&&"right"in v;function a(v,E){if(v.length<33)throw new TypeError(`The control-block length is too small. Got ${v.length}, expected min 33.`);const S=(v.length-33)/32;let P=E;for(let A=0;A<S;A++){const w=v.slice(33+32*A,65+32*A);P.compare(w)<0?P=p(P,w):P=p(w,P)}return P}e.rootHashFromPath=a;function c(v){if((0,o.isTapleaf)(v))return{hash:l(v)};const E=[c(v[0]),c(v[1])];E.sort((A,w)=>A.hash.compare(w.hash));const[S,P]=E;return{hash:p(S.hash,P.hash),left:S,right:P}}e.toHashTree=c;function u(v,E){if(s(v)){const S=u(v.left,E);if(S!==void 0)return[...S,v.right.hash];const P=u(v.right,E);if(P!==void 0)return[...P,v.left.hash]}else if(v.hash.equals(E))return[]}e.findScriptPath=u;function l(v){const E=v.version||e.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",t.Buffer.concat([t.Buffer.from([E]),b(v.output)]))}e.tapleafHash=l;function h(v,E){return n.taggedHash("TapTweak",t.Buffer.concat(E?[v,E]:[v]))}e.tapTweakHash=h;function y(v,E){if(!t.Buffer.isBuffer(v)||v.length!==32||E&&E.length!==32)return null;const S=h(v,E),P=(0,r.getEccLib)().xOnlyPointAddTweak(v,S);return!P||P.xOnlyPubkey===null?null:{parity:P.parity,x:t.Buffer.from(P.xOnlyPubkey)}}e.tweakKey=y;function p(v,E){return n.taggedHash("TapBranch",t.Buffer.concat([v,E]))}function b(v){const E=i.varuint.encodingLength(v.length),S=t.Buffer.allocUnsafe(E);return i.varuint.encode(v.length,S),t.Buffer.concat([S,v])}})(Ou);var nt={},Df;function N2(){if(Df)return nt;Df=1,Object.defineProperty(nt,"__esModule",{value:!0}),nt.toOutputScript=nt.fromOutputScript=nt.toBech32=nt.toBase58Check=nt.fromBech32=nt.fromBase58Check=void 0;const e=Qe,t=Ru(),r=gt(),n=Ze,i=fr,o=Bu,s=40,a=2,c=16,u=2,l=80,h="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 y(A,w){const B=A.slice(2);if(B.length<a||B.length>s)throw new TypeError("Invalid program length for segwit address");const T=A[0]-l;if(T<u||T>c)throw new TypeError("Invalid version for segwit address");if(A[1]!==B.length)throw new TypeError("Invalid script for segwit address");return console.warn(h),E(B,T,w.bech32)}function p(A){const w=Buffer.from(o.decode(A));if(w.length<21)throw new TypeError(A+" is too short");if(w.length>21)throw new TypeError(A+" is too long");const B=w.readUInt8(0),T=w.slice(1);return{version:B,hash:T}}nt.fromBase58Check=p;function b(A){let w,B;try{w=i.bech32.decode(A)}catch{}if(w){if(B=w.words[0],B!==0)throw new TypeError(A+" uses wrong encoding")}else if(w=i.bech32m.decode(A),B=w.words[0],B===0)throw new TypeError(A+" uses wrong encoding");const T=i.bech32.fromWords(w.words.slice(1));return{version:B,prefix:w.prefix,data:Buffer.from(T)}}nt.fromBech32=b;function v(A,w){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const B=Buffer.allocUnsafe(21);return B.writeUInt8(w,0),A.copy(B,1),o.encode(B)}nt.toBase58Check=v;function E(A,w,B){const T=i.bech32.toWords(A);return T.unshift(w),w===0?i.bech32.encode(B,T):i.bech32m.encode(B,T)}nt.toBech32=E;function S(A,w){w=w||e.bitcoin;try{return t.p2pkh({output:A,network:w}).address}catch{}try{return t.p2sh({output:A,network:w}).address}catch{}try{return t.p2wpkh({output:A,network:w}).address}catch{}try{return t.p2wsh({output:A,network:w}).address}catch{}try{return t.p2tr({output:A,network:w}).address}catch{}try{return y(A,w)}catch{}throw new Error(r.toASM(A)+" has no matching Address")}nt.fromOutputScript=S;function P(A,w){w=w||e.bitcoin;let B,T;try{B=p(A)}catch{}if(B){if(B.version===w.pubKeyHash)return t.p2pkh({hash:B.hash}).output;if(B.version===w.scriptHash)return t.p2sh({hash:B.hash}).output}else{try{T=b(A)}catch{}if(T){if(T.prefix!==w.bech32)throw new Error(A+" has an invalid prefix");if(T.version===0){if(T.data.length===20)return t.p2wpkh({hash:T.data}).output;if(T.data.length===32)return t.p2wsh({hash:T.data}).output}else if(T.version===1){if(T.data.length===32)return t.p2tr({pubkey:T.data}).output}else if(T.version>=u&&T.version<=c&&T.data.length>=a&&T.data.length<=s)return console.warn(h),r.compile([T.version+l,T.data])}}throw new Error(A+" has no matching Script")}return nt.toOutputScript=P,nt}var jf;function $2(){if(jf)return Yn;jf=1,Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.p2tr=void 0;const e=Bt,t=Qe,r=gt(),n=Ze,i=Yr,o=Ou,s=mt,a=fr,c=N2(),u=r.OPS,l=1,h=80;function y(p,b){if(!p.address&&!p.output&&!p.pubkey&&!p.internalPubkey&&!(p.witness&&p.witness.length>1))throw new TypeError("Not enough data");b=Object.assign({validate:!0},b||{}),(0,n.typeforce)({address:n.typeforce.maybe(n.typeforce.String),input:n.typeforce.maybe(n.typeforce.BufferN(0)),network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.BufferN(34)),internalPubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),hash:n.typeforce.maybe(n.typeforce.BufferN(32)),pubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),signature:n.typeforce.maybe(n.typeforce.anyOf(n.typeforce.BufferN(64),n.typeforce.BufferN(65))),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer)),scriptTree:n.typeforce.maybe(n.isTaptree),redeem:n.typeforce.maybe({output:n.typeforce.maybe(n.typeforce.Buffer),redeemVersion:n.typeforce.maybe(n.typeforce.Number),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer))}),redeemVersion:n.typeforce.maybe(n.typeforce.Number)},p);const v=s.value(()=>(0,c.fromBech32)(p.address)),E=s.value(()=>{if(!(!p.witness||!p.witness.length))return p.witness.length>=2&&p.witness[p.witness.length-1][0]===h?p.witness.slice(0,-1):p.witness.slice()}),S=s.value(()=>{if(p.scriptTree)return(0,o.toHashTree)(p.scriptTree);if(p.hash)return{hash:p.hash}}),P=p.network||t.bitcoin,A={name:"p2tr",network:P};if(s.prop(A,"address",()=>{if(!A.pubkey)return;const w=a.bech32m.toWords(A.pubkey);return w.unshift(l),a.bech32m.encode(P.bech32,w)}),s.prop(A,"hash",()=>{const w=S();if(w)return w.hash;const B=E();if(B&&B.length>1){const T=B[B.length-1],L=T[0]&n.TAPLEAF_VERSION_MASK,D=B[B.length-2],C=(0,o.tapleafHash)({output:D,version:L});return(0,o.rootHashFromPath)(T,C)}return null}),s.prop(A,"output",()=>{if(A.pubkey)return r.compile([u.OP_1,A.pubkey])}),s.prop(A,"redeemVersion",()=>p.redeemVersion?p.redeemVersion:p.redeem&&p.redeem.redeemVersion!==void 0&&p.redeem.redeemVersion!==null?p.redeem.redeemVersion:o.LEAF_VERSION_TAPSCRIPT),s.prop(A,"redeem",()=>{const w=E();if(!(!w||w.length<2))return{output:w[w.length-2],witness:w.slice(0,-2),redeemVersion:w[w.length-1][0]&n.TAPLEAF_VERSION_MASK}}),s.prop(A,"pubkey",()=>{if(p.pubkey)return p.pubkey;if(p.output)return p.output.slice(2);if(p.address)return v().data;if(A.internalPubkey){const w=(0,o.tweakKey)(A.internalPubkey,A.hash);if(w)return w.x}}),s.prop(A,"internalPubkey",()=>{if(p.internalPubkey)return p.internalPubkey;const w=E();if(w&&w.length>1)return w[w.length-1].slice(1,33)}),s.prop(A,"signature",()=>{if(p.signature)return p.signature;const w=E();if(!(!w||w.length!==1))return w[0]}),s.prop(A,"witness",()=>{if(p.witness)return p.witness;const w=S();if(w&&p.redeem&&p.redeem.output&&p.internalPubkey){const B=(0,o.tapleafHash)({output:p.redeem.output,version:A.redeemVersion}),T=(0,o.findScriptPath)(w,B);if(!T)return;const L=(0,o.tweakKey)(p.internalPubkey,w.hash);if(!L)return;const D=e.Buffer.concat([e.Buffer.from([A.redeemVersion|L.parity]),p.internalPubkey].concat(T));return[p.redeem.output,D]}if(p.signature)return[p.signature]}),b.validate){let w=e.Buffer.from([]);if(p.address){if(P&&P.bech32!==v().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(v().version!==l)throw new TypeError("Invalid address version");if(v().data.length!==32)throw new TypeError("Invalid address data");w=v().data}if(p.pubkey){if(w.length>0&&!w.equals(p.pubkey))throw new TypeError("Pubkey mismatch");w=p.pubkey}if(p.output){if(p.output.length!==34||p.output[0]!==u.OP_1||p.output[1]!==32)throw new TypeError("Output is invalid");if(w.length>0&&!w.equals(p.output.slice(2)))throw new TypeError("Pubkey mismatch");w=p.output.slice(2)}if(p.internalPubkey){const L=(0,o.tweakKey)(p.internalPubkey,A.hash);if(w.length>0&&!w.equals(L.x))throw new TypeError("Pubkey mismatch");w=L.x}if(w&&w.length&&!(0,i.getEccLib)().isXOnlyPoint(w))throw new TypeError("Invalid pubkey for p2tr");const B=S();if(p.hash&&B&&!p.hash.equals(B.hash))throw new TypeError("Hash mismatch");if(p.redeem&&p.redeem.output&&B){const L=(0,o.tapleafHash)({output:p.redeem.output,version:A.redeemVersion});if(!(0,o.findScriptPath)(B,L))throw new TypeError("Redeem script not in tree")}const T=E();if(p.redeem&&A.redeem){if(p.redeem.redeemVersion&&p.redeem.redeemVersion!==A.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(p.redeem.output){if(r.decompile(p.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(A.redeem.output&&!p.redeem.output.equals(A.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(p.redeem.witness&&A.redeem.witness&&!(0,n.stacksEqual)(p.redeem.witness,A.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(T&&T.length)if(T.length===1){if(p.signature&&!p.signature.equals(T[0]))throw new TypeError("Signature mismatch")}else{const L=T[T.length-1];if(L.length<33)throw new TypeError(`The control-block length is too small. Got ${L.length}, expected min 33.`);if((L.length-33)%32!==0)throw new TypeError(`The control-block length of ${L.length} is incorrect!`);const D=(L.length-33)/32;if(D>128)throw new TypeError(`The script path is too long. Got ${D}, expected max 128.`);const C=L.slice(1,33);if(p.internalPubkey&&!p.internalPubkey.equals(C))throw new TypeError("Internal pubkey mismatch");if(!(0,i.getEccLib)().isXOnlyPoint(C))throw new TypeError("Invalid internalPubkey for p2tr witness");const X=L[0]&n.TAPLEAF_VERSION_MASK,Z=T[T.length-2],oe=(0,o.tapleafHash)({output:Z,version:X}),te=(0,o.rootHashFromPath)(L,oe),ee=(0,o.tweakKey)(C,te);if(!ee)throw new TypeError("Invalid outputKey for p2tr witness");if(w.length&&!w.equals(ee.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(ee.parity!==(L[0]&1))throw new Error("Incorrect parity")}}return Object.assign(A,p)}return Yn.p2tr=y,Yn}var qf;function Ru(){return qf||(qf=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.p2tr=e.p2wsh=e.p2wpkh=e.p2sh=e.p2pkh=e.p2pk=e.p2ms=e.embed=void 0;const t=ns;Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const r=is;Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=os;Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const i=ss;Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return i.p2pkh}});const o=as;Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return o.p2sh}});const s=cs;Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return s.p2wpkh}});const a=us;Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return a.p2wsh}});const c=$2();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return c.p2tr}})}(qs)),qs}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 Gf=Xi,ci=gt(),bo=Yi,L2=Cr,Qr=Ru();function Zr(e){return t=>{try{return e({output:t}),!0}catch{return!1}}}_e.isP2MS=Zr(Qr.p2ms);_e.isP2PK=Zr(Qr.p2pk);_e.isP2PKH=Zr(Qr.p2pkh);_e.isP2WPKH=Zr(Qr.p2wpkh);_e.isP2WSHScript=Zr(Qr.p2wsh);_e.isP2SHScript=Zr(Qr.p2sh);_e.isP2TR=Zr(Qr.p2tr);function M2(e){let t=Buffer.allocUnsafe(0);function r(s){t=Buffer.concat([t,Buffer.from(s)])}function n(s){const a=t.length,c=Gf.encodingLength(s);t=Buffer.concat([t,Buffer.allocUnsafe(c)]),Gf.encode(s,t,a)}function i(s){n(s.length),r(s)}function o(s){n(s.length),s.forEach(i)}return o(e),t}_e.witnessStackToScriptWitness=M2;function Fp(e,t){const r=(0,L2.hash160)(e),n=e.slice(1,33),i=ci.decompile(t);if(i===null)throw new Error("Unknown script error");return i.findIndex(o=>typeof o=="number"?!1:o.equals(e)||o.equals(r)||o.equals(n))}_e.pubkeyPositionInScript=Fp;function H2(e,t){return Fp(e,t)!==-1}_e.pubkeyInScript=H2;function D2(e,t){return j2(e).some(n=>Up(n,ci.signature.decode,t))}_e.checkInputForSig=D2;function Up(e,t,r){const{hashType:n}=t(e),i=[];switch(n&bo.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput"),n&31){case bo.Transaction.SIGHASH_ALL:break;case bo.Transaction.SIGHASH_SINGLE:case bo.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence");break}return i.indexOf(r)===-1}_e.signatureBlocksAction=Up;function j2(e){let t=[];if((e.partialSig||[]).length===0){if(!e.finalScriptSig&&!e.finalScriptWitness)return[];t=q2(e)}else t=e.partialSig;return t.map(r=>r.signature)}function q2(e){const t=e.finalScriptSig?ci.decompile(e.finalScriptSig)||[]:[],r=e.finalScriptWitness?ci.decompile(e.finalScriptWitness)||[]:[];return t.concat(r).filter(n=>Buffer.isBuffer(n)&&ci.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(Be,"__esModule",{value:!0});Be.checkTaprootInputForSigs=Be.tapTreeFromList=Be.tapTreeToList=Be.tweakInternalPubKey=Be.checkTaprootOutputFields=Be.checkTaprootInputFields=Be.isTaprootOutput=Be.isTaprootInput=So=Be.serializeTaprootSignature=Be.tapScriptFinalizer=Be.toXOnly=void 0;const Cu=Ze,G2=Yi,fs=_e,Rr=Ou,z2=Ru(),V2=_e,W2=e=>e.length===32?e:e.slice(1,33);Be.toXOnly=W2;function K2(e,t,r){const n=dv(t,e,r);try{const o=fv(t,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,fs.witnessStackToScriptWitness)(o)}}catch(i){throw new Error(`Can not finalize taproot input #${e}: ${i}`)}}Be.tapScriptFinalizer=K2;function Y2(e,t){const r=t?Buffer.from([t]):Buffer.from([]);return Buffer.concat([e,r])}var So=Be.serializeTaprootSignature=Y2;function Po(e){return e&&!!(e.tapInternalKey||e.tapMerkleRoot||e.tapLeafScript&&e.tapLeafScript.length||e.tapBip32Derivation&&e.tapBip32Derivation.length||e.witnessUtxo&&(0,fs.isP2TR)(e.witnessUtxo.script))}Be.isTaprootInput=Po;function To(e,t){return e&&!!(e.tapInternalKey||e.tapTree||e.tapBip32Derivation&&e.tapBip32Derivation.length||t&&(0,fs.isP2TR)(t))}Be.isTaprootOutput=To;function X2(e,t,r){av(e,t,r),uv(e,t,r)}Be.checkTaprootInputFields=X2;function J2(e,t,r){cv(e,t,r),Q2(e,t)}Be.checkTaprootOutputFields=J2;function Q2(e,t){if(!t.tapTree&&!t.tapInternalKey)return;const r=t.tapInternalKey||e.tapInternalKey,n=t.tapTree||e.tapTree;if(r){const{script:i}=e,o=Z2(r,n);if(i&&!i.equals(o))throw new Error("Error adding output. Script or address missmatch.")}}function Z2(e,t){const r=t&&Np(t.leaves),{output:n}=(0,z2.p2tr)({internalPubkey:e,scriptTree:r});return n}function ev(e,t){const r=t.tapInternalKey,n=r&&(0,Rr.tweakKey)(r,t.tapMerkleRoot);if(!n)throw new Error(`Cannot tweak tap internal key for input #${e}. Public key: ${r&&r.toString("hex")}`);return n.x}Be.tweakInternalPubKey=ev;function tv(e){if(!(0,Cu.isTaptree)(e))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return Fc(e)}Be.tapTreeToList=tv;function Np(e=[]){return e.length===1&&e[0].depth===0?{output:e[0].script,version:e[0].leafVersion}:sv(e)}Be.tapTreeFromList=Np;function rv(e,t){return iv(e).some(n=>(0,V2.signatureBlocksAction)(n,nv,t))}Be.checkTaprootInputForSigs=rv;function nv(e){return{signature:e.slice(0,64),hashType:e.slice(64)[0]||G2.Transaction.SIGHASH_DEFAULT}}function iv(e){const t=[];if(e.tapKeySig&&t.push(e.tapKeySig),e.tapScriptSig&&t.push(...e.tapScriptSig.map(r=>r.signature)),!t.length){const r=ov(e.finalScriptWitness);r&&t.push(r)}return t}function ov(e){if(!e)return;const t=e.slice(2);if(t.length===64||t.length===65)return t}function Fc(e,t=[],r=0){if(r>Rr.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return e?(0,Cu.isTapleaf)(e)?(t.push({depth:r,leafVersion:e.version||Rr.LEAF_VERSION_TAPSCRIPT,script:e.output}),t):(e[0]&&Fc(e[0],t,r+1),e[1]&&Fc(e[1],t,r+1),t):[]}function sv(e){let t;for(const r of e)if(t=Uc(r,t),!t)throw new Error("No room left to insert tapleaf in tree");return t}function Uc(e,t,r=0){if(r>Rr.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(e.depth===r)return t?void 0:{output:e.script,version:e.leafVersion};if((0,Cu.isTapleaf)(t))return;const n=Uc(e,t&&t[0],r+1);if(n)return[n,t&&t[1]];const i=Uc(e,t&&t[1],r+1);if(i)return[t&&t[0],i]}function av(e,t,r){const n=Po(e)&&gn(t),i=gn(e)&&Po(t),o=e===t&&Po(t)&&gn(t);if(n||i||o)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function cv(e,t,r){const n=To(e)&&gn(t),i=gn(e)&&To(t),o=e===t&&To(t)&&gn(t);if(n||i||o)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function uv(e,t,r){if(t.tapMerkleRoot){const n=(t.tapLeafScript||[]).every(o=>Ks(o,t.tapMerkleRoot)),i=(e.tapLeafScript||[]).every(o=>Ks(o,t.tapMerkleRoot));if(!n||!i)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(e.tapMerkleRoot&&!(t.tapLeafScript||[]).every(i=>Ks(i,e.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function Ks(e,t){if(!t)return!0;const r=(0,Rr.tapleafHash)({output:e.script,version:e.leafVersion});return(0,Rr.rootHashFromPath)(e.controlBlock,r).equals(t)}function fv(e,t){const r=(0,Rr.tapleafHash)({output:t.script,version:t.leafVersion});return(e.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>lv(t.script,n)).sort((n,i)=>i.positionInScript-n.positionInScript).map(n=>n.signature)}function lv(e,t){return Object.assign({positionInScript:(0,fs.pubkeyPositionInScript)(t.pubkey,e)},t)}function dv(e,t,r){if(!e.tapScriptSig||!e.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${t}. No tapleaf script signature provided.`);const n=(e.tapLeafScript||[]).sort((i,o)=>i.controlBlock.length-o.controlBlock.length).find(i=>hv(i,e.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${t}. Signature for tapleaf script not found.`);return n}function hv(e,t,r){const n=(0,Rr.tapleafHash)({output:e.script,version:e.leafVersion});return(!r||r.equals(n))&&t.find(o=>o.leafHash.equals(n))!==void 0}function gn(e){return e&&!!(e.redeemScript||e.witnessScript||e.bip32Derivation&&e.bip32Derivation.length)}const Ge={secretMismatch:"invalid secret",secretHashLenMismatch:"secret hash should be 32 bytes",pubkeyLenMismatch:"pubkey should be 32 bytes",zeroOrNegativeExpiry:"expiry should be greater than 0",htlcAddressGenerationFailed:"failed to generate htlc address",notFunded:"address not funded",noCounterpartySigs:"counterparty signatures are required",counterPartySigNotFound:e=>"counterparty signature not found for utxo "+e,invalidCounterpartySigForUTXO:e=>"invalid counterparty signature for utxo "+e,htlcNotExpired:e=>`HTLC not expired, need more ${e} blocks`,controlBlockGenerationFailed:"failed to generate control block",invalidLeaf:"invalid leaf"},go=192;ge.initEccLib(Gr);class ui{constructor(t,r,n,i,o,s,a,c){this.secretHash=n,this.redeemerPubkey=i,this.initiatorPubkey=o,this.expiry=s,this.signer=t,this.network=a,this.internalPubkey=dw(),this.initiateAmount=r,this.utxoHashes=c}static async from(t,r,n,i,o,s,a){n=n.startsWith("0x")?n.slice(2):n,$r(n.length===64,Ge.secretHashLenMismatch),$r(i.length===64||i.length===66,`initiator ${Ge.pubkeyLenMismatch}`),$r(o.length===64||o.length===66,`redeemer ${Ge.pubkeyLenMismatch}`),$r(s>0,Ge.zeroOrNegativeExpiry);const c=await t.getNetwork();return new ui(t,r,n,kc(o).toString("hex"),kc(i).toString("hex"),s,c,a)}address(){const{address:t}=ge.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves()});if(!t)throw new Error(Ge.htlcAddressGenerationFailed);return t}id(){return this.address()}async _buildRawTx(t,r){const n=new ge.Transaction;n.version=2;const i=this.address(),o=await this.signer.getProvider();let s=[];if(this.utxoHashes&&this.utxoHashes.length>0)for(const c of this.utxoHashes){const u=await o.getTransaction(c);for(let l=0;l<u.vout.length;l++){const h=u.vout[l];h.scriptpubkey_address===i&&s.push({txid:u.txid,vout:l,value:h.value,status:{confirmed:!1}})}}else s=await o.getUTXOs(i);const a=s.reduce((c,u)=>c+u.value,0);if(a===0)throw new Error(`${i} ${Ge.notFunded}`);for(let c=0;c<s.length;c++)n.addInput(Buffer.from(s[c].txid,"hex").reverse(),s[c].vout);return r??(r=await o.suggestFee(i,a,Hr.Urgency.MEDIUM)),n.addOutput(ge.address.toOutputScript(t,this.network),a-r),{tx:n,usedUtxos:s}}async _tempBuildRawTx(t,r){const n=new ge.Transaction;n.version=2;const i=this.address(),o=await this.signer.getProvider();let s=[];if(this.utxoHashes&&this.utxoHashes.length>0)for(const c of this.utxoHashes){const u=await o.getTransaction(c);for(let l=0;l<u.vout.length;l++){const h=u.vout[l];h.scriptpubkey_address===i&&s.push({txid:u.txid,vout:l,value:h.value,status:{confirmed:!1}})}}else s=await o.getUTXOs(i);const a=s.reduce((c,u)=>c+u.value,0);if(a===0)throw new Error(`${i} ${Ge.notFunded}`);for(let c=0;c<s.length;c++)n.addInput(Buffer.from(s[c].txid,"hex").reverse(),s[c].vout);if(n.addOutput(ge.address.toOutputScript(t,this.network),a),r){const c=await o.getFeeRates(),u=Math.ceil(c.hourFee*r),l=a-u;n.outs[0].value=l}return{tx:n,usedUtxos:s}}async buildRawTx(t){return await this._buildRawTx(await this.signer.getAddress(),t)}getOutputScript(){return ge.address.toOutputScript(this.address(),this.network)}async init(t){return t??(t=await(await this.signer.getProvider()).suggestFee(await this.signer.getAddress(),this.initiateAmount,Hr.Urgency.MEDIUM)),await this.signer.send(this.address(),this.initiateAmount,t)}async generateRedeemSACP(t,r,n){const{tx:i,usedUtxos:o}=await this._buildRawTx(r,n),s=this.getOutputScript(),a=ge.Transaction.SIGHASH_SINGLE|ge.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(1),u=o.map(h=>h.value),l=sn(s,o.length);for(let h=0;h<i.ins.length;h++){const y=i.hashForWitnessV1(h,l,u,a,c),p=await this.signer.signSchnorr(y);i.setWitness(h,[So(p,a),Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return i.toHex()}async generateInstantRefundSACP(t,r){const{tx:n,usedUtxos:i}=await this._buildRawTx(t,r),o=this.getOutputScript(),s=ge.Transaction.SIGHASH_SINGLE|ge.Transaction.SIGHASH_ANYONECANPAY,a=this.leafHash(2),c=i.map(l=>l.value),u=sn(o,i.length);for(let l=0;l<n.ins.length;l++){const h=n.hashForWitnessV1(l,u,c,s,a),y=await this.signer.signSchnorr(h);n.setWitness(l,[So(y,s),So(y,s),this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return n.toHex()}async instantRefund(t,r){$r(t.length>0,Ge.noCounterpartySigs);const{tx:n,usedUtxos:i}=await this.buildRawTx(r);for(const h of i)if(!t.find(y=>y.utxo===h.txid))throw new Error(Ge.counterPartySigNotFound(h.txid));const o=this.getOutputScript(),s=ge.Transaction.SIGHASH_DEFAULT,a=this.leafHash(2),c=i.map(h=>h.value),u=sn(o,i.length);for(let h=0;h<n.ins.length;h++){const y=n.hashForWitnessV1(h,u,c,s,a);if(!Gr.verifySchnorr(y,Buffer.from(this.redeemerPubkey,"hex"),Buffer.from(t[h].sig,"hex")))throw new Error(Ge.invalidCounterpartySigForUTXO(t[h].utxo));const p=await this.signer.signSchnorr(y),b=Buffer.from(n.ins[h].hash).reverse().toString("hex"),v=t.find(E=>E.utxo===b);if(!v)throw new Error(Ge.counterPartySigNotFound(b));n.setWitness(h,[Buffer.from(v.sig,"hex"),p,this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async redeem(t,r){$r(ge.crypto.sha256(Buffer.from(t,"hex")).toString("hex")===this.secretHash,Ge.secretMismatch);const n=r??await this.signer.getAddress(),{tx:i,usedUtxos:o}=await this._tempBuildRawTx(n),s=this.leafHash(1),a=o.map(y=>y.value),c=sn(this.getOutputScript(),o.length),u=ge.Transaction.SIGHASH_DEFAULT;for(let y=0;y<i.ins.length;y++){const p=i.hashForWitnessV1(y,c,a,u,s),b=await this.signer.signSchnorr(p);i.setWitness(y,[b,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}const{tx:l}=await this._tempBuildRawTx(n,i.virtualSize());for(let y=0;y<l.ins.length;y++){const p=l.hashForWitnessV1(y,c,a,u,s),b=await this.signer.signSchnorr(p);l.setWitness(y,[b,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return await(await this.signer.getProvider()).broadcast(l.toHex())}async getRedeemHex(t,r){$r(ge.crypto.sha256(Buffer.from(t,"hex")).toString("hex")===this.secretHash,Ge.secretMismatch);const n=r??await this.signer.getAddress(),{tx:i,usedUtxos:o}=await this._tempBuildRawTx(n),s=this.leafHash(1),a=o.map(h=>h.value),c=sn(this.getOutputScript(),o.length),u=ge.Transaction.SIGHASH_DEFAULT;for(let h=0;h<i.ins.length;h++){const y=i.hashForWitnessV1(h,c,a,u,s),p=await this.signer.signSchnorr(y);i.setWitness(h,[p,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}const{tx:l}=await this._tempBuildRawTx(n,i.virtualSize());for(let h=0;h<l.ins.length;h++){const y=l.hashForWitnessV1(h,c,a,u,s),p=await this.signer.signSchnorr(y);l.setWitness(h,[p,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return l.toHex()}async refund(t,r){const{tx:n,usedUtxos:i}=await this._buildRawTx(t??await this.signer.getAddress(),r),[o,s]=await this.canRefund(i);if(!o)throw new Error(Ge.htlcNotExpired(s));const a=this.leafHash(0),c=i.map(y=>y.value),u=sn(this.getOutputScript(),i.length),l=ge.Transaction.SIGHASH_DEFAULT;for(let y=0;y<n.ins.length;y++){n.ins[y].sequence=this.expiry;const p=n.hashForWitnessV1(y,u,c,l,a),b=await this.signer.signSchnorr(p);n.setWitness(y,[b,this.refundLeaf(),this.generateControlBlockFor(0)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async canRefund(t){const n=await(await this.signer.getProvider()).getLatestTip();for(const i of t){let o=0;if(i.status.confirmed&&i.status.block_height+this.expiry>n?o=i.status.block_height+this.expiry-n+1:i.status.confirmed||(o=this.expiry+1),o>0)return[!1,o]}return[!0,0]}generateControlBlockFor(t){let r;switch(t){case 1:r=this.redeemLeaf();break;case 0:r=this.refundLeaf();break;case 2:r=this.instantRefundLeaf();break;default:throw new Error(Ge.invalidLeaf)}const n=ge.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves(),redeem:{output:r,redeemVersion:go}});if(!n.witness)throw new Error(Ge.controlBlockGenerationFailed);return n.witness[n.witness.length-1]}leafHash(t){let r=this.redeemLeaf();return t===0&&(r=this.refundLeaf()),t===2&&(r=this.instantRefundLeaf()),ge.crypto.taggedHash("TapLeaf",Q1(r))}refundLeaf(){return ge.script.fromASM(`
51
+ ${ge.script.number.encode(this.expiry).toString("hex")}
52
+ OP_CHECKSEQUENCEVERIFY
53
+ OP_DROP
54
+ ${this.initiatorPubkey}
55
+ OP_CHECKSIG
56
+ `.trim().replace(/\s+/g," "))}redeemLeaf(){return ge.script.fromASM(`
57
+ OP_SHA256
58
+ ${this.secretHash}
59
+ OP_EQUALVERIFY
60
+ ${this.redeemerPubkey}
61
+ OP_CHECKSIG
62
+ `.trim().replace(/\s+/g," "))}instantRefundLeaf(){return ge.script.fromASM(`
63
+ ${this.initiatorPubkey}
64
+ OP_CHECKSIG
65
+ ${this.redeemerPubkey}
66
+ OP_CHECKSIGADD
67
+ OP_2
68
+ OP_NUMEQUAL
69
+ `.trim().replace(/\s+/g," "))}leaves(){return[{version:go,output:this.redeemLeaf()},[{version:go,output:this.refundLeaf()},{version:go,output:this.instantRefundLeaf()}]]}generateMerkleProofFor(t){const r=this.leafHash(1),n=this.leafHash(2),i=this.leafHash(0);switch(t){case 1:{const o=ew(i,n);return[ge.crypto.taggedHash("TapBranch",Buffer.concat(o))]}case 0:return[n,r];case 2:return[i,r];default:throw new Error(Ge.invalidLeaf)}}}function sn(e,t){const r=[];for(let n=0;n<t;n++)r.push(e);return r}class pv{constructor(){this.cache={}}set(t,r,n,i){const o={txHash:n,timeStamp:Date.now(),btcRedeemUTXO:i};this.cache[`${r}_${t.create_order.create_id}`]=o}get(t,r){return this.cache[`${r}_${t.create_order.create_id}`]||null}remove(t,r){delete this.cache[`${r}_${t.create_order.create_id}`]}}class yv{constructor(){this.cache={}}set(t,r){this.cache[t]=r}get(t){return this.cache[t]||null}}class $p{constructor(t,r){this.url=new J.Url(t).endpoint("blocknumbers").endpoint(r)}async fetchBlockNumbers(){try{const t=await U.Fetcher.get(this.url);return U.Ok(t)}catch(t){return U.Err("Failed to fetch block numbers",t)}}}class Lp{constructor(t){this.quoteUrl=new J.Url(t)}async getQuoteFromAssets(t,r,n,i=!1,o){const s=Oc(t.chain,t.atomicSwapAddress,r.chain,r.atomicSwapAddress);return this.getQuote(s,n,i,o)}async getQuote(t,r,n=!1,i){try{const o={order_pair:t,amount:r.toString(),exact_out:n.toString(),...(i==null?void 0:i.affiliateFee)!==void 0&&{affiliate_fee:i.affiliateFee.toString()}},s=this.quoteUrl.endpoint("/").addSearchParams(o),a=await U.Fetcher.get(s,{retryCount:0,...i==null?void 0:i.request});return a.error?U.Err(a.error):a.result?U.Ok(a.result):U.Err("GetQuote: Unexpected error, result is undefined")}catch(o){return U.Err("GetQuote:",String(o))}}async getAttestedQuote(t){try{const r=await U.Fetcher.post(this.quoteUrl.endpoint("/attested").toString(),{body:JSON.stringify(t),headers:{"Content-Type":"application/json"}});return r.error?U.Err(r.error):r.result?U.Ok(r.result):U.Err("GetAttestedQuote: Unexpected error, result is undefined")}catch(r){return console.log("error :",r),U.Err("GetAttestedQuote:",String(r))}}async getStrategies(){try{const t=await U.Fetcher.get(this.quoteUrl.endpoint("/strategies"));if(t.error)return U.Err(t.error);if(!t.result)return U.Err("GetStrategies: Unexpected error, result is undefined");const r={};for(const n of Object.values(t.result)){const i=Oc(n.source_chain,n.source_asset.asset,n.dest_chain,n.dest_asset.asset);r[i]={id:n.id,minAmount:n.min_amount,maxAmount:n.max_amount,fee:n.fee}}return U.Ok(r)}catch(t){return U.Err("GetStrategies:",String(t))}}}var Mp={},Tn={},In={};Object.defineProperty(In,"__esModule",{value:!0});In.testnet=In.bitcoin=void 0;In.bitcoin={messagePrefix:`Bitcoin Signed Message:
70
+ `,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};In.testnet={messagePrefix:`Bitcoin Signed Message:
71
+ `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var Hp={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.maybe=e.Boolean=e.Array=e.Buffer256bit=e.Network=e.typeforce=void 0,e.typeforce=hp,e.Network=e.typeforce.compile({messagePrefix:e.typeforce.oneOf(e.typeforce.Buffer,e.typeforce.String),bip32:{public:e.typeforce.UInt32,private:e.typeforce.UInt32},pubKeyHash:e.typeforce.UInt8,scriptHash:e.typeforce.UInt8,wif:e.typeforce.UInt8}),e.Buffer256bit=e.typeforce.BufferN(32),e.Array=e.typeforce.Array,e.Boolean=e.typeforce.Boolean,e.maybe=e.typeforce.maybe})(Hp);var Nc={exports:{}},$c={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(e,t){var r=Bt,n=r.Buffer;function i(s,a){for(var c in s)a[c]=s[c]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=o);function o(s,a,c){return n(s,a,c)}o.prototype=Object.create(n.prototype),i(n,o),o.from=function(s,a,c){if(typeof s=="number")throw new TypeError("Argument must not be a number");return n(s,a,c)},o.alloc=function(s,a,c){if(typeof s!="number")throw new TypeError("Argument must be a number");var u=n(s);return a!==void 0?typeof c=="string"?u.fill(a,c):u.fill(a):u.fill(0),u},o.allocUnsafe=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return n(s)},o.allocUnsafeSlow=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(s)}})($c,$c.exports);var et=$c.exports,Ys=65536,mv=4294967295;function bv(){throw new Error(`Secure random number generation is not supported by this browser.
72
+ Use Chrome, Firefox or Internet Explorer 11`)}var gv=et.Buffer,Fo=De.crypto||De.msCrypto;Fo&&Fo.getRandomValues?Nc.exports=wv:Nc.exports=bv;function wv(e,t){if(e>mv)throw new RangeError("requested too many random bytes");var r=gv.allocUnsafe(e);if(e>0)if(e>Ys)for(var n=0;n<e;n+=Ys)Fo.getRandomValues(r.slice(n,n+Ys));else Fo.getRandomValues(r);return typeof t=="function"?process.nextTick(function(){t(null,r)}):r}var vv=Nc.exports,Lc={exports:{}};typeof Object.create=="function"?Lc.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:Lc.exports=function(t,r){if(r){t.super_=r;var n=function(){};n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t}};var je=Lc.exports,Mc={exports:{}},Fu={exports:{}},wn=typeof Reflect=="object"?Reflect:null,zf=wn&&typeof wn.apply=="function"?wn.apply:function(t,r,n){return Function.prototype.apply.call(t,r,n)},Io;wn&&typeof wn.ownKeys=="function"?Io=wn.ownKeys:Object.getOwnPropertySymbols?Io=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Io=function(t){return Object.getOwnPropertyNames(t)};function _v(e){console&&console.warn&&console.warn(e)}var Dp=Number.isNaN||function(t){return t!==t};function we(){we.init.call(this)}Fu.exports=we;Fu.exports.once=Sv;we.EventEmitter=we;we.prototype._events=void 0;we.prototype._eventsCount=0;we.prototype._maxListeners=void 0;var Vf=10;function ls(e){if(typeof e!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}Object.defineProperty(we,"defaultMaxListeners",{enumerable:!0,get:function(){return Vf},set:function(e){if(typeof e!="number"||e<0||Dp(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Vf=e}});we.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};we.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Dp(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function jp(e){return e._maxListeners===void 0?we.defaultMaxListeners:e._maxListeners}we.prototype.getMaxListeners=function(){return jp(this)};we.prototype.emit=function(t){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=t==="error",o=this._events;if(o!==void 0)i=i&&o.error===void 0;else if(!i)return!1;if(i){var s;if(r.length>0&&(s=r[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=o[t];if(c===void 0)return!1;if(typeof c=="function")zf(c,this,r);else for(var u=c.length,l=Wp(c,u),n=0;n<u;++n)zf(l[n],this,r);return!0};function qp(e,t,r,n){var i,o,s;if(ls(r),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),s=o[t]),s===void 0)s=o[t]=r,++e._eventsCount;else if(typeof s=="function"?s=o[t]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),i=jp(e),i>0&&s.length>i&&!s.warned){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=s.length,_v(a)}return e}we.prototype.addListener=function(t,r){return qp(this,t,r,!1)};we.prototype.on=we.prototype.addListener;we.prototype.prependListener=function(t,r){return qp(this,t,r,!0)};function Ev(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Gp(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=Ev.bind(n);return i.listener=r,n.wrapFn=i,i}we.prototype.once=function(t,r){return ls(r),this.on(t,Gp(this,t,r)),this};we.prototype.prependOnceListener=function(t,r){return ls(r),this.prependListener(t,Gp(this,t,r)),this};we.prototype.removeListener=function(t,r){var n,i,o,s,a;if(ls(r),i=this._events,i===void 0)return this;if(n=i[t],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,n.listener||r));else if(typeof n!="function"){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===r||n[s].listener===r){a=n[s].listener,o=s;break}if(o<0)return this;o===0?n.shift():xv(n,o),n.length===1&&(i[t]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",t,a||r)}return this};we.prototype.off=we.prototype.removeListener;we.prototype.removeAllListeners=function(t){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var o=Object.keys(n),s;for(i=0;i<o.length;++i)s=o[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[t],typeof r=="function")this.removeListener(t,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(t,r[i]);return this};function zp(e,t,r){var n=e._events;if(n===void 0)return[];var i=n[t];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?Av(i):Wp(i,i.length)}we.prototype.listeners=function(t){return zp(this,t,!0)};we.prototype.rawListeners=function(t){return zp(this,t,!1)};we.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):Vp.call(e,t)};we.prototype.listenerCount=Vp;function Vp(e){var t=this._events;if(t!==void 0){var r=t[e];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}we.prototype.eventNames=function(){return this._eventsCount>0?Io(this._events):[]};function Wp(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function xv(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function Av(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}function Sv(e,t){return new Promise(function(r,n){function i(s){e.removeListener(t,o),n(s)}function o(){typeof e.removeListener=="function"&&e.removeListener("error",i),r([].slice.call(arguments))}Kp(e,t,o,{once:!0}),t!=="error"&&Pv(e,i,{once:!0})})}function Pv(e,t,r){typeof e.on=="function"&&Kp(e,"error",t,r)}function Kp(e,t,r,n){if(typeof e.on=="function")n.once?e.once(t,r):e.on(t,r);else if(typeof e.addEventListener=="function")e.addEventListener(t,function i(o){n.once&&e.removeEventListener(t,i),r(o)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}var Yp=Fu.exports,Xp=Yp.EventEmitter;const Tv={},Iv=Object.freeze(Object.defineProperty({__proto__:null,default:Tv},Symbol.toStringTag,{value:"Module"})),Uu=_u(Iv);var Xs,Wf;function Bv(){if(Wf)return Xs;Wf=1;function e(b,v){var E=Object.keys(b);if(Object.getOwnPropertySymbols){var S=Object.getOwnPropertySymbols(b);v&&(S=S.filter(function(P){return Object.getOwnPropertyDescriptor(b,P).enumerable})),E.push.apply(E,S)}return E}function t(b){for(var v=1;v<arguments.length;v++){var E=arguments[v]!=null?arguments[v]:{};v%2?e(Object(E),!0).forEach(function(S){r(b,S,E[S])}):Object.getOwnPropertyDescriptors?Object.defineProperties(b,Object.getOwnPropertyDescriptors(E)):e(Object(E)).forEach(function(S){Object.defineProperty(b,S,Object.getOwnPropertyDescriptor(E,S))})}return b}function r(b,v,E){return v=s(v),v in b?Object.defineProperty(b,v,{value:E,enumerable:!0,configurable:!0,writable:!0}):b[v]=E,b}function n(b,v){if(!(b instanceof v))throw new TypeError("Cannot call a class as a function")}function i(b,v){for(var E=0;E<v.length;E++){var S=v[E];S.enumerable=S.enumerable||!1,S.configurable=!0,"value"in S&&(S.writable=!0),Object.defineProperty(b,s(S.key),S)}}function o(b,v,E){return v&&i(b.prototype,v),Object.defineProperty(b,"prototype",{writable:!1}),b}function s(b){var v=a(b,"string");return typeof v=="symbol"?v:String(v)}function a(b,v){if(typeof b!="object"||b===null)return b;var E=b[Symbol.toPrimitive];if(E!==void 0){var S=E.call(b,v);if(typeof S!="object")return S;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(b)}var c=Bt,u=c.Buffer,l=Uu,h=l.inspect,y=h&&h.custom||"inspect";function p(b,v,E){u.prototype.copy.call(b,v,E)}return Xs=function(){function b(){n(this,b),this.head=null,this.tail=null,this.length=0}return o(b,[{key:"push",value:function(E){var S={data:E,next:null};this.length>0?this.tail.next=S:this.head=S,this.tail=S,++this.length}},{key:"unshift",value:function(E){var S={data:E,next:this.head};this.length===0&&(this.tail=S),this.head=S,++this.length}},{key:"shift",value:function(){if(this.length!==0){var E=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,E}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(E){if(this.length===0)return"";for(var S=this.head,P=""+S.data;S=S.next;)P+=E+S.data;return P}},{key:"concat",value:function(E){if(this.length===0)return u.alloc(0);for(var S=u.allocUnsafe(E>>>0),P=this.head,A=0;P;)p(P.data,S,A),A+=P.data.length,P=P.next;return S}},{key:"consume",value:function(E,S){var P;return E<this.head.data.length?(P=this.head.data.slice(0,E),this.head.data=this.head.data.slice(E)):E===this.head.data.length?P=this.shift():P=S?this._getString(E):this._getBuffer(E),P}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(E){var S=this.head,P=1,A=S.data;for(E-=A.length;S=S.next;){var w=S.data,B=E>w.length?w.length:E;if(B===w.length?A+=w:A+=w.slice(0,E),E-=B,E===0){B===w.length?(++P,S.next?this.head=S.next:this.head=this.tail=null):(this.head=S,S.data=w.slice(B));break}++P}return this.length-=P,A}},{key:"_getBuffer",value:function(E){var S=u.allocUnsafe(E),P=this.head,A=1;for(P.data.copy(S),E-=P.data.length;P=P.next;){var w=P.data,B=E>w.length?w.length:E;if(w.copy(S,S.length-E,0,B),E-=B,E===0){B===w.length?(++A,P.next?this.head=P.next:this.head=this.tail=null):(this.head=P,P.data=w.slice(B));break}++A}return this.length-=A,S}},{key:y,value:function(E,S){return h(this,t(t({},S),{},{depth:0,customInspect:!1}))}}]),b}(),Xs}function kv(e,t){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(Hc,this,e)):process.nextTick(Hc,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(o){!t&&o?r._writableState?r._writableState.errorEmitted?process.nextTick(Bo,r):(r._writableState.errorEmitted=!0,process.nextTick(Kf,r,o)):process.nextTick(Kf,r,o):t?(process.nextTick(Bo,r),t(o)):process.nextTick(Bo,r)}),this)}function Kf(e,t){Hc(e,t),Bo(e)}function Bo(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function Ov(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function Hc(e,t){e.emit("error",t)}function Rv(e,t){var r=e._readableState,n=e._writableState;r&&r.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}var Jp={destroy:kv,undestroy:Ov,errorOrDestroy:Rv},en={};function Cv(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var Qp={};function St(e,t,r){r||(r=Error);function n(o,s,a){return typeof t=="string"?t:t(o,s,a)}var i=function(o){Cv(s,o);function s(a,c,u){return o.call(this,n(a,c,u))||this}return s}(r);i.prototype.name=r.name,i.prototype.code=e,Qp[e]=i}function Yf(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map(function(n){return String(n)}),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:r===2?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}else return"of ".concat(t," ").concat(String(e))}function Fv(e,t,r){return e.substr(0,t.length)===t}function Uv(e,t,r){return(r===void 0||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}function Nv(e,t,r){return typeof r!="number"&&(r=0),r+t.length>e.length?!1:e.indexOf(t,r)!==-1}St("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError);St("ERR_INVALID_ARG_TYPE",function(e,t,r){var n;typeof t=="string"&&Fv(t,"not ")?(n="must not be",t=t.replace(/^not /,"")):n="must be";var i;if(Uv(e," argument"))i="The ".concat(e," ").concat(n," ").concat(Yf(t,"type"));else{var o=Nv(e,".")?"property":"argument";i='The "'.concat(e,'" ').concat(o," ").concat(n," ").concat(Yf(t,"type"))}return i+=". Received type ".concat(typeof r),i},TypeError);St("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");St("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"});St("ERR_STREAM_PREMATURE_CLOSE","Premature close");St("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"});St("ERR_MULTIPLE_CALLBACK","Callback called multiple times");St("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");St("ERR_STREAM_WRITE_AFTER_END","write after end");St("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);St("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError);St("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");en.codes=Qp;var $v=en.codes.ERR_INVALID_OPT_VALUE;function Lv(e,t,r){return e.highWaterMark!=null?e.highWaterMark:t?e[r]:null}function Mv(e,t,r,n){var i=Lv(t,n,r);if(i!=null){if(!(isFinite(i)&&Math.floor(i)===i)||i<0){var o=n?r:"highWaterMark";throw new $v(o,i)}return Math.floor(i)}return e.objectMode?16:16*1024}var Zp={getHighWaterMark:Mv},Hv=Dv;function Dv(e,t){if(Js("noDeprecation"))return e;var r=!1;function n(){if(!r){if(Js("throwDeprecation"))throw new Error(t);Js("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}return n}function Js(e){try{if(!De.localStorage)return!1}catch{return!1}var t=De.localStorage[e];return t==null?!1:String(t).toLowerCase()==="true"}var Qs,Xf;function e0(){if(Xf)return Qs;Xf=1,Qs=D;function e(I){var k=this;this.next=null,this.entry=null,this.finish=function(){ne(k,I)}}var t;D.WritableState=T;var r={deprecate:Hv},n=Xp,i=Bt.Buffer,o=(typeof De<"u"?De:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function s(I){return i.from(I)}function a(I){return i.isBuffer(I)||I instanceof o}var c=Jp,u=Zp,l=u.getHighWaterMark,h=en.codes,y=h.ERR_INVALID_ARG_TYPE,p=h.ERR_METHOD_NOT_IMPLEMENTED,b=h.ERR_MULTIPLE_CALLBACK,v=h.ERR_STREAM_CANNOT_PIPE,E=h.ERR_STREAM_DESTROYED,S=h.ERR_STREAM_NULL_VALUES,P=h.ERR_STREAM_WRITE_AFTER_END,A=h.ERR_UNKNOWN_ENCODING,w=c.errorOrDestroy;je(D,n);function B(){}function T(I,k,M){t=t||Bn(),I=I||{},typeof M!="boolean"&&(M=k instanceof t),this.objectMode=!!I.objectMode,M&&(this.objectMode=this.objectMode||!!I.writableObjectMode),this.highWaterMark=l(this,I,"writableHighWaterMark",M),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var V=I.decodeStrings===!1;this.decodeStrings=!V,this.defaultEncoding=I.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(W){be(k,W)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=I.emitClose!==!1,this.autoDestroy=!!I.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new e(this)}T.prototype.getBuffer=function(){for(var k=this.bufferedRequest,M=[];k;)M.push(k),k=k.next;return M},function(){try{Object.defineProperty(T.prototype,"buffer",{get:r.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}}();var L;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(L=Function.prototype[Symbol.hasInstance],Object.defineProperty(D,Symbol.hasInstance,{value:function(k){return L.call(this,k)?!0:this!==D?!1:k&&k._writableState instanceof T}})):L=function(k){return k instanceof this};function D(I){t=t||Bn();var k=this instanceof t;if(!k&&!L.call(D,this))return new D(I);this._writableState=new T(I,this,k),this.writable=!0,I&&(typeof I.write=="function"&&(this._write=I.write),typeof I.writev=="function"&&(this._writev=I.writev),typeof I.destroy=="function"&&(this._destroy=I.destroy),typeof I.final=="function"&&(this._final=I.final)),n.call(this)}D.prototype.pipe=function(){w(this,new v)};function C(I,k){var M=new P;w(I,M),process.nextTick(k,M)}function X(I,k,M,V){var W;return M===null?W=new S:typeof M!="string"&&!k.objectMode&&(W=new y("chunk",["string","Buffer"],M)),W?(w(I,W),process.nextTick(V,W),!1):!0}D.prototype.write=function(I,k,M){var V=this._writableState,W=!1,g=!V.objectMode&&a(I);return g&&!i.isBuffer(I)&&(I=s(I)),typeof k=="function"&&(M=k,k=null),g?k="buffer":k||(k=V.defaultEncoding),typeof M!="function"&&(M=B),V.ending?C(this,M):(g||X(this,V,I,M))&&(V.pendingcb++,W=oe(this,V,g,I,k,M)),W},D.prototype.cork=function(){this._writableState.corked++},D.prototype.uncork=function(){var I=this._writableState;I.corked&&(I.corked--,!I.writing&&!I.corked&&!I.bufferProcessing&&I.bufferedRequest&&F(this,I))},D.prototype.setDefaultEncoding=function(k){if(typeof k=="string"&&(k=k.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((k+"").toLowerCase())>-1))throw new A(k);return this._writableState.defaultEncoding=k,this},Object.defineProperty(D.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function Z(I,k,M){return!I.objectMode&&I.decodeStrings!==!1&&typeof k=="string"&&(k=i.from(k,M)),k}Object.defineProperty(D.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function oe(I,k,M,V,W,g){if(!M){var _=Z(k,V,W);V!==_&&(M=!0,W="buffer",V=_)}var H=k.objectMode?1:V.length;k.length+=H;var K=k.length<k.highWaterMark;if(K||(k.needDrain=!0),k.writing||k.corked){var de=k.lastBufferedRequest;k.lastBufferedRequest={chunk:V,encoding:W,isBuf:M,callback:g,next:null},de?de.next=k.lastBufferedRequest:k.bufferedRequest=k.lastBufferedRequest,k.bufferedRequestCount+=1}else te(I,k,!1,H,V,W,g);return K}function te(I,k,M,V,W,g,_){k.writelen=V,k.writecb=_,k.writing=!0,k.sync=!0,k.destroyed?k.onwrite(new E("write")):M?I._writev(W,k.onwrite):I._write(W,g,k.onwrite),k.sync=!1}function ee(I,k,M,V,W){--k.pendingcb,M?(process.nextTick(W,V),process.nextTick(N,I,k),I._writableState.errorEmitted=!0,w(I,V)):(W(V),I._writableState.errorEmitted=!0,w(I,V),N(I,k))}function ae(I){I.writing=!1,I.writecb=null,I.length-=I.writelen,I.writelen=0}function be(I,k){var M=I._writableState,V=M.sync,W=M.writecb;if(typeof W!="function")throw new b;if(ae(M),k)ee(I,M,V,k,W);else{var g=Y(M)||I.destroyed;!g&&!M.corked&&!M.bufferProcessing&&M.bufferedRequest&&F(I,M),V?process.nextTick(ye,I,M,g,W):ye(I,M,g,W)}}function ye(I,k,M,V){M||ce(I,k),k.pendingcb--,V(),N(I,k)}function ce(I,k){k.length===0&&k.needDrain&&(k.needDrain=!1,I.emit("drain"))}function F(I,k){k.bufferProcessing=!0;var M=k.bufferedRequest;if(I._writev&&M&&M.next){var V=k.bufferedRequestCount,W=new Array(V),g=k.corkedRequestsFree;g.entry=M;for(var _=0,H=!0;M;)W[_]=M,M.isBuf||(H=!1),M=M.next,_+=1;W.allBuffers=H,te(I,k,!0,k.length,W,"",g.finish),k.pendingcb++,k.lastBufferedRequest=null,g.next?(k.corkedRequestsFree=g.next,g.next=null):k.corkedRequestsFree=new e(k),k.bufferedRequestCount=0}else{for(;M;){var K=M.chunk,de=M.encoding,ie=M.callback,fe=k.objectMode?1:K.length;if(te(I,k,!1,fe,K,de,ie),M=M.next,k.bufferedRequestCount--,k.writing)break}M===null&&(k.lastBufferedRequest=null)}k.bufferedRequest=M,k.bufferProcessing=!1}D.prototype._write=function(I,k,M){M(new p("_write()"))},D.prototype._writev=null,D.prototype.end=function(I,k,M){var V=this._writableState;return typeof I=="function"?(M=I,I=null,k=null):typeof k=="function"&&(M=k,k=null),I!=null&&this.write(I,k),V.corked&&(V.corked=1,this.uncork()),V.ending||q(this,V,M),this},Object.defineProperty(D.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function Y(I){return I.ending&&I.length===0&&I.bufferedRequest===null&&!I.finished&&!I.writing}function re(I,k){I._final(function(M){k.pendingcb--,M&&w(I,M),k.prefinished=!0,I.emit("prefinish"),N(I,k)})}function O(I,k){!k.prefinished&&!k.finalCalled&&(typeof I._final=="function"&&!k.destroyed?(k.pendingcb++,k.finalCalled=!0,process.nextTick(re,I,k)):(k.prefinished=!0,I.emit("prefinish")))}function N(I,k){var M=Y(k);if(M&&(O(I,k),k.pendingcb===0&&(k.finished=!0,I.emit("finish"),k.autoDestroy))){var V=I._readableState;(!V||V.autoDestroy&&V.endEmitted)&&I.destroy()}return M}function q(I,k,M){k.ending=!0,N(I,k),M&&(k.finished?process.nextTick(M):I.once("finish",M)),k.ended=!0,I.writable=!1}function ne(I,k,M){var V=I.entry;for(I.entry=null;V;){var W=V.callback;k.pendingcb--,W(M),V=V.next}k.corkedRequestsFree.next=I}return Object.defineProperty(D.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(k){this._writableState&&(this._writableState.destroyed=k)}}),D.prototype.destroy=c.destroy,D.prototype._undestroy=c.undestroy,D.prototype._destroy=function(I,k){k(I)},Qs}var Zs,Jf;function Bn(){if(Jf)return Zs;Jf=1;var e=Object.keys||function(u){var l=[];for(var h in u)l.push(h);return l};Zs=s;var t=r0(),r=e0();je(s,t);for(var n=e(r.prototype),i=0;i<n.length;i++){var o=n[i];s.prototype[o]||(s.prototype[o]=r.prototype[o])}function s(u){if(!(this instanceof s))return new s(u);t.call(this,u),r.call(this,u),this.allowHalfOpen=!0,u&&(u.readable===!1&&(this.readable=!1),u.writable===!1&&(this.writable=!1),u.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",a)))}Object.defineProperty(s.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(s.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(s.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function a(){this._writableState.ended||process.nextTick(c,this)}function c(u){u.end()}return Object.defineProperty(s.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(l){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=l,this._writableState.destroyed=l)}}),Zs}var Uo={},Nu=et.Buffer,Qf=Nu.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function jv(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function qv(e){var t=jv(e);if(typeof t!="string"&&(Nu.isEncoding===Qf||!Qf(e)))throw new Error("Unknown encoding: "+e);return t||e}Uo.StringDecoder=Ji;function Ji(e){this.encoding=qv(e);var t;switch(this.encoding){case"utf16le":this.text=Yv,this.end=Xv,t=4;break;case"utf8":this.fillLast=Vv,t=4;break;case"base64":this.text=Jv,this.end=Qv,t=3;break;default:this.write=Zv,this.end=e_;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Nu.allocUnsafe(t)}Ji.prototype.write=function(e){if(e.length===0)return"";var t,r;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""};Ji.prototype.end=Kv;Ji.prototype.text=Wv;Ji.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function ea(e){return e<=127?0:e>>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}function Gv(e,t,r){var n=t.length-1;if(n<r)return 0;var i=ea(t[n]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--n<r||i===-2?0:(i=ea(t[n]),i>=0?(i>0&&(e.lastNeed=i-2),i):--n<r||i===-2?0:(i=ea(t[n]),i>=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}function zv(e,t,r){if((t[0]&192)!==128)return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"�"}}function Vv(e){var t=this.lastTotal-this.lastNeed,r=zv(this,e);if(r!==void 0)return r;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function Wv(e,t){var r=Gv(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}function Kv(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function Yv(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function Xv(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function Jv(e,t){var r=(e.length-t)%3;return r===0?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function Qv(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function Zv(e){return e.toString(this.encoding)}function e_(e){return e&&e.length?this.write(e):""}var Zf=en.codes.ERR_STREAM_PREMATURE_CLOSE;function t_(e){var t=!1;return function(){if(!t){t=!0;for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];e.apply(this,n)}}}function r_(){}function n_(e){return e.setHeader&&typeof e.abort=="function"}function t0(e,t,r){if(typeof t=="function")return t0(e,null,t);t||(t={}),r=t_(r||r_);var n=t.readable||t.readable!==!1&&e.readable,i=t.writable||t.writable!==!1&&e.writable,o=function(){e.writable||a()},s=e._writableState&&e._writableState.finished,a=function(){i=!1,s=!0,n||r.call(e)},c=e._readableState&&e._readableState.endEmitted,u=function(){n=!1,c=!0,i||r.call(e)},l=function(b){r.call(e,b)},h=function(){var b;if(n&&!c)return(!e._readableState||!e._readableState.ended)&&(b=new Zf),r.call(e,b);if(i&&!s)return(!e._writableState||!e._writableState.ended)&&(b=new Zf),r.call(e,b)},y=function(){e.req.on("finish",a)};return n_(e)?(e.on("complete",a),e.on("abort",h),e.req?y():e.on("request",y)):i&&!e._writableState&&(e.on("end",o),e.on("close",o)),e.on("end",u),e.on("finish",a),t.error!==!1&&e.on("error",l),e.on("close",h),function(){e.removeListener("complete",a),e.removeListener("abort",h),e.removeListener("request",y),e.req&&e.req.removeListener("finish",a),e.removeListener("end",o),e.removeListener("close",o),e.removeListener("finish",a),e.removeListener("end",u),e.removeListener("error",l),e.removeListener("close",h)}}var $u=t0,ta,el;function i_(){if(el)return ta;el=1;var e;function t(A,w,B){return w=r(w),w in A?Object.defineProperty(A,w,{value:B,enumerable:!0,configurable:!0,writable:!0}):A[w]=B,A}function r(A){var w=n(A,"string");return typeof w=="symbol"?w:String(w)}function n(A,w){if(typeof A!="object"||A===null)return A;var B=A[Symbol.toPrimitive];if(B!==void 0){var T=B.call(A,w);if(typeof T!="object")return T;throw new TypeError("@@toPrimitive must return a primitive value.")}return(w==="string"?String:Number)(A)}var i=$u,o=Symbol("lastResolve"),s=Symbol("lastReject"),a=Symbol("error"),c=Symbol("ended"),u=Symbol("lastPromise"),l=Symbol("handlePromise"),h=Symbol("stream");function y(A,w){return{value:A,done:w}}function p(A){var w=A[o];if(w!==null){var B=A[h].read();B!==null&&(A[u]=null,A[o]=null,A[s]=null,w(y(B,!1)))}}function b(A){process.nextTick(p,A)}function v(A,w){return function(B,T){A.then(function(){if(w[c]){B(y(void 0,!0));return}w[l](B,T)},T)}}var E=Object.getPrototypeOf(function(){}),S=Object.setPrototypeOf((e={get stream(){return this[h]},next:function(){var w=this,B=this[a];if(B!==null)return Promise.reject(B);if(this[c])return Promise.resolve(y(void 0,!0));if(this[h].destroyed)return new Promise(function(C,X){process.nextTick(function(){w[a]?X(w[a]):C(y(void 0,!0))})});var T=this[u],L;if(T)L=new Promise(v(T,this));else{var D=this[h].read();if(D!==null)return Promise.resolve(y(D,!1));L=new Promise(this[l])}return this[u]=L,L}},t(e,Symbol.asyncIterator,function(){return this}),t(e,"return",function(){var w=this;return new Promise(function(B,T){w[h].destroy(null,function(L){if(L){T(L);return}B(y(void 0,!0))})})}),e),E),P=function(w){var B,T=Object.create(S,(B={},t(B,h,{value:w,writable:!0}),t(B,o,{value:null,writable:!0}),t(B,s,{value:null,writable:!0}),t(B,a,{value:null,writable:!0}),t(B,c,{value:w._readableState.endEmitted,writable:!0}),t(B,l,{value:function(D,C){var X=T[h].read();X?(T[u]=null,T[o]=null,T[s]=null,D(y(X,!1))):(T[o]=D,T[s]=C)},writable:!0}),B));return T[u]=null,i(w,function(L){if(L&&L.code!=="ERR_STREAM_PREMATURE_CLOSE"){var D=T[s];D!==null&&(T[u]=null,T[o]=null,T[s]=null,D(L)),T[a]=L;return}var C=T[o];C!==null&&(T[u]=null,T[o]=null,T[s]=null,C(y(void 0,!0))),T[c]=!0}),w.on("readable",b.bind(null,T)),T};return ta=P,ta}var ra,tl;function o_(){return tl||(tl=1,ra=function(){throw new Error("Readable.from is not available in the browser")}),ra}var na,rl;function r0(){if(rl)return na;rl=1,na=C;var e;C.ReadableState=D,Yp.EventEmitter;var t=function(_,H){return _.listeners(H).length},r=Xp,n=Bt.Buffer,i=(typeof De<"u"?De:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function o(g){return n.from(g)}function s(g){return n.isBuffer(g)||g instanceof i}var a=Uu,c;a&&a.debuglog?c=a.debuglog("stream"):c=function(){};var u=Bv(),l=Jp,h=Zp,y=h.getHighWaterMark,p=en.codes,b=p.ERR_INVALID_ARG_TYPE,v=p.ERR_STREAM_PUSH_AFTER_EOF,E=p.ERR_METHOD_NOT_IMPLEMENTED,S=p.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,P,A,w;je(C,r);var B=l.errorOrDestroy,T=["error","close","destroy","pause","resume"];function L(g,_,H){if(typeof g.prependListener=="function")return g.prependListener(_,H);!g._events||!g._events[_]?g.on(_,H):Array.isArray(g._events[_])?g._events[_].unshift(H):g._events[_]=[H,g._events[_]]}function D(g,_,H){e=e||Bn(),g=g||{},typeof H!="boolean"&&(H=_ instanceof e),this.objectMode=!!g.objectMode,H&&(this.objectMode=this.objectMode||!!g.readableObjectMode),this.highWaterMark=y(this,g,"readableHighWaterMark",H),this.buffer=new u,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=g.emitClose!==!1,this.autoDestroy=!!g.autoDestroy,this.destroyed=!1,this.defaultEncoding=g.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,g.encoding&&(P||(P=Uo.StringDecoder),this.decoder=new P(g.encoding),this.encoding=g.encoding)}function C(g){if(e=e||Bn(),!(this instanceof C))return new C(g);var _=this instanceof e;this._readableState=new D(g,this,_),this.readable=!0,g&&(typeof g.read=="function"&&(this._read=g.read),typeof g.destroy=="function"&&(this._destroy=g.destroy)),r.call(this)}Object.defineProperty(C.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(_){this._readableState&&(this._readableState.destroyed=_)}}),C.prototype.destroy=l.destroy,C.prototype._undestroy=l.undestroy,C.prototype._destroy=function(g,_){_(g)},C.prototype.push=function(g,_){var H=this._readableState,K;return H.objectMode?K=!0:typeof g=="string"&&(_=_||H.defaultEncoding,_!==H.encoding&&(g=n.from(g,_),_=""),K=!0),X(this,g,_,!1,K)},C.prototype.unshift=function(g){return X(this,g,null,!0,!1)};function X(g,_,H,K,de){c("readableAddChunk",_);var ie=g._readableState;if(_===null)ie.reading=!1,be(g,ie);else{var fe;if(de||(fe=oe(ie,_)),fe)B(g,fe);else if(ie.objectMode||_&&_.length>0)if(typeof _!="string"&&!ie.objectMode&&Object.getPrototypeOf(_)!==n.prototype&&(_=o(_)),K)ie.endEmitted?B(g,new S):Z(g,ie,_,!0);else if(ie.ended)B(g,new v);else{if(ie.destroyed)return!1;ie.reading=!1,ie.decoder&&!H?(_=ie.decoder.write(_),ie.objectMode||_.length!==0?Z(g,ie,_,!1):F(g,ie)):Z(g,ie,_,!1)}else K||(ie.reading=!1,F(g,ie))}return!ie.ended&&(ie.length<ie.highWaterMark||ie.length===0)}function Z(g,_,H,K){_.flowing&&_.length===0&&!_.sync?(_.awaitDrain=0,g.emit("data",H)):(_.length+=_.objectMode?1:H.length,K?_.buffer.unshift(H):_.buffer.push(H),_.needReadable&&ye(g)),F(g,_)}function oe(g,_){var H;return!s(_)&&typeof _!="string"&&_!==void 0&&!g.objectMode&&(H=new b("chunk",["string","Buffer","Uint8Array"],_)),H}C.prototype.isPaused=function(){return this._readableState.flowing===!1},C.prototype.setEncoding=function(g){P||(P=Uo.StringDecoder);var _=new P(g);this._readableState.decoder=_,this._readableState.encoding=this._readableState.decoder.encoding;for(var H=this._readableState.buffer.head,K="";H!==null;)K+=_.write(H.data),H=H.next;return this._readableState.buffer.clear(),K!==""&&this._readableState.buffer.push(K),this._readableState.length=K.length,this};var te=1073741824;function ee(g){return g>=te?g=te:(g--,g|=g>>>1,g|=g>>>2,g|=g>>>4,g|=g>>>8,g|=g>>>16,g++),g}function ae(g,_){return g<=0||_.length===0&&_.ended?0:_.objectMode?1:g!==g?_.flowing&&_.length?_.buffer.head.data.length:_.length:(g>_.highWaterMark&&(_.highWaterMark=ee(g)),g<=_.length?g:_.ended?_.length:(_.needReadable=!0,0))}C.prototype.read=function(g){c("read",g),g=parseInt(g,10);var _=this._readableState,H=g;if(g!==0&&(_.emittedReadable=!1),g===0&&_.needReadable&&((_.highWaterMark!==0?_.length>=_.highWaterMark:_.length>0)||_.ended))return c("read: emitReadable",_.length,_.ended),_.length===0&&_.ended?M(this):ye(this),null;if(g=ae(g,_),g===0&&_.ended)return _.length===0&&M(this),null;var K=_.needReadable;c("need readable",K),(_.length===0||_.length-g<_.highWaterMark)&&(K=!0,c("length less than watermark",K)),_.ended||_.reading?(K=!1,c("reading or ended",K)):K&&(c("do read"),_.reading=!0,_.sync=!0,_.length===0&&(_.needReadable=!0),this._read(_.highWaterMark),_.sync=!1,_.reading||(g=ae(H,_)));var de;return g>0?de=k(g,_):de=null,de===null?(_.needReadable=_.length<=_.highWaterMark,g=0):(_.length-=g,_.awaitDrain=0),_.length===0&&(_.ended||(_.needReadable=!0),H!==g&&_.ended&&M(this)),de!==null&&this.emit("data",de),de};function be(g,_){if(c("onEofChunk"),!_.ended){if(_.decoder){var H=_.decoder.end();H&&H.length&&(_.buffer.push(H),_.length+=_.objectMode?1:H.length)}_.ended=!0,_.sync?ye(g):(_.needReadable=!1,_.emittedReadable||(_.emittedReadable=!0,ce(g)))}}function ye(g){var _=g._readableState;c("emitReadable",_.needReadable,_.emittedReadable),_.needReadable=!1,_.emittedReadable||(c("emitReadable",_.flowing),_.emittedReadable=!0,process.nextTick(ce,g))}function ce(g){var _=g._readableState;c("emitReadable_",_.destroyed,_.length,_.ended),!_.destroyed&&(_.length||_.ended)&&(g.emit("readable"),_.emittedReadable=!1),_.needReadable=!_.flowing&&!_.ended&&_.length<=_.highWaterMark,I(g)}function F(g,_){_.readingMore||(_.readingMore=!0,process.nextTick(Y,g,_))}function Y(g,_){for(;!_.reading&&!_.ended&&(_.length<_.highWaterMark||_.flowing&&_.length===0);){var H=_.length;if(c("maybeReadMore read 0"),g.read(0),H===_.length)break}_.readingMore=!1}C.prototype._read=function(g){B(this,new E("_read()"))},C.prototype.pipe=function(g,_){var H=this,K=this._readableState;switch(K.pipesCount){case 0:K.pipes=g;break;case 1:K.pipes=[K.pipes,g];break;default:K.pipes.push(g);break}K.pipesCount+=1,c("pipe count=%d opts=%j",K.pipesCount,_);var de=(!_||_.end!==!1)&&g!==process.stdout&&g!==process.stderr,ie=de?ut:Nr;K.endEmitted?process.nextTick(ie):H.once("end",ie),g.on("unpipe",fe);function fe(m,f){c("onunpipe"),m===H&&f&&f.hasUnpiped===!1&&(f.hasUnpiped=!0,qe())}function ut(){c("onend"),g.end()}var j=re(H);g.on("drain",j);var pt=!1;function qe(){c("cleanup"),g.removeListener("close",Ot),g.removeListener("finish",vt),g.removeListener("drain",j),g.removeListener("error",wt),g.removeListener("unpipe",fe),H.removeListener("end",ut),H.removeListener("end",Nr),H.removeListener("data",Ne),pt=!0,K.awaitDrain&&(!g._writableState||g._writableState.needDrain)&&j()}H.on("data",Ne);function Ne(m){c("ondata");var f=g.write(m);c("dest.write",f),f===!1&&((K.pipesCount===1&&K.pipes===g||K.pipesCount>1&&W(K.pipes,g)!==-1)&&!pt&&(c("false write response, pause",K.awaitDrain),K.awaitDrain++),H.pause())}function wt(m){c("onerror",m),Nr(),g.removeListener("error",wt),t(g,"error")===0&&B(g,m)}L(g,"error",wt);function Ot(){g.removeListener("finish",vt),Nr()}g.once("close",Ot);function vt(){c("onfinish"),g.removeListener("close",Ot),Nr()}g.once("finish",vt);function Nr(){c("unpipe"),H.unpipe(g)}return g.emit("pipe",H),K.flowing||(c("pipe resume"),H.resume()),g};function re(g){return function(){var H=g._readableState;c("pipeOnDrain",H.awaitDrain),H.awaitDrain&&H.awaitDrain--,H.awaitDrain===0&&t(g,"data")&&(H.flowing=!0,I(g))}}C.prototype.unpipe=function(g){var _=this._readableState,H={hasUnpiped:!1};if(_.pipesCount===0)return this;if(_.pipesCount===1)return g&&g!==_.pipes?this:(g||(g=_.pipes),_.pipes=null,_.pipesCount=0,_.flowing=!1,g&&g.emit("unpipe",this,H),this);if(!g){var K=_.pipes,de=_.pipesCount;_.pipes=null,_.pipesCount=0,_.flowing=!1;for(var ie=0;ie<de;ie++)K[ie].emit("unpipe",this,{hasUnpiped:!1});return this}var fe=W(_.pipes,g);return fe===-1?this:(_.pipes.splice(fe,1),_.pipesCount-=1,_.pipesCount===1&&(_.pipes=_.pipes[0]),g.emit("unpipe",this,H),this)},C.prototype.on=function(g,_){var H=r.prototype.on.call(this,g,_),K=this._readableState;return g==="data"?(K.readableListening=this.listenerCount("readable")>0,K.flowing!==!1&&this.resume()):g==="readable"&&!K.endEmitted&&!K.readableListening&&(K.readableListening=K.needReadable=!0,K.flowing=!1,K.emittedReadable=!1,c("on readable",K.length,K.reading),K.length?ye(this):K.reading||process.nextTick(N,this)),H},C.prototype.addListener=C.prototype.on,C.prototype.removeListener=function(g,_){var H=r.prototype.removeListener.call(this,g,_);return g==="readable"&&process.nextTick(O,this),H},C.prototype.removeAllListeners=function(g){var _=r.prototype.removeAllListeners.apply(this,arguments);return(g==="readable"||g===void 0)&&process.nextTick(O,this),_};function O(g){var _=g._readableState;_.readableListening=g.listenerCount("readable")>0,_.resumeScheduled&&!_.paused?_.flowing=!0:g.listenerCount("data")>0&&g.resume()}function N(g){c("readable nexttick read 0"),g.read(0)}C.prototype.resume=function(){var g=this._readableState;return g.flowing||(c("resume"),g.flowing=!g.readableListening,q(this,g)),g.paused=!1,this};function q(g,_){_.resumeScheduled||(_.resumeScheduled=!0,process.nextTick(ne,g,_))}function ne(g,_){c("resume",_.reading),_.reading||g.read(0),_.resumeScheduled=!1,g.emit("resume"),I(g),_.flowing&&!_.reading&&g.read(0)}C.prototype.pause=function(){return c("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(c("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function I(g){var _=g._readableState;for(c("flow",_.flowing);_.flowing&&g.read()!==null;);}C.prototype.wrap=function(g){var _=this,H=this._readableState,K=!1;g.on("end",function(){if(c("wrapped end"),H.decoder&&!H.ended){var fe=H.decoder.end();fe&&fe.length&&_.push(fe)}_.push(null)}),g.on("data",function(fe){if(c("wrapped data"),H.decoder&&(fe=H.decoder.write(fe)),!(H.objectMode&&fe==null)&&!(!H.objectMode&&(!fe||!fe.length))){var ut=_.push(fe);ut||(K=!0,g.pause())}});for(var de in g)this[de]===void 0&&typeof g[de]=="function"&&(this[de]=function(ut){return function(){return g[ut].apply(g,arguments)}}(de));for(var ie=0;ie<T.length;ie++)g.on(T[ie],this.emit.bind(this,T[ie]));return this._read=function(fe){c("wrapped _read",fe),K&&(K=!1,g.resume())},this},typeof Symbol=="function"&&(C.prototype[Symbol.asyncIterator]=function(){return A===void 0&&(A=i_()),A(this)}),Object.defineProperty(C.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(C.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(C.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(_){this._readableState&&(this._readableState.flowing=_)}}),C._fromList=k,Object.defineProperty(C.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function k(g,_){if(_.length===0)return null;var H;return _.objectMode?H=_.buffer.shift():!g||g>=_.length?(_.decoder?H=_.buffer.join(""):_.buffer.length===1?H=_.buffer.first():H=_.buffer.concat(_.length),_.buffer.clear()):H=_.buffer.consume(g,_.decoder),H}function M(g){var _=g._readableState;c("endReadable",_.endEmitted),_.endEmitted||(_.ended=!0,process.nextTick(V,_,g))}function V(g,_){if(c("endReadableNT",g.endEmitted,g.length),!g.endEmitted&&g.length===0&&(g.endEmitted=!0,_.readable=!1,_.emit("end"),g.autoDestroy)){var H=_._writableState;(!H||H.autoDestroy&&H.finished)&&_.destroy()}}typeof Symbol=="function"&&(C.from=function(g,_){return w===void 0&&(w=o_()),w(C,g,_)});function W(g,_){for(var H=0,K=g.length;H<K;H++)if(g[H]===_)return H;return-1}return na}var n0=lr,ds=en.codes,s_=ds.ERR_METHOD_NOT_IMPLEMENTED,a_=ds.ERR_MULTIPLE_CALLBACK,c_=ds.ERR_TRANSFORM_ALREADY_TRANSFORMING,u_=ds.ERR_TRANSFORM_WITH_LENGTH_0,hs=Bn();je(lr,hs);function f_(e,t){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(n===null)return this.emit("error",new a_);r.writechunk=null,r.writecb=null,t!=null&&this.push(t),n(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}function lr(e){if(!(this instanceof lr))return new lr(e);hs.call(this,e),this._transformState={afterTransform:f_.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)),this.on("prefinish",l_)}function l_(){var e=this;typeof this._flush=="function"&&!this._readableState.destroyed?this._flush(function(t,r){nl(e,t,r)}):nl(this,null,null)}lr.prototype.push=function(e,t){return this._transformState.needTransform=!1,hs.prototype.push.call(this,e,t)};lr.prototype._transform=function(e,t,r){r(new s_("_transform()"))};lr.prototype._write=function(e,t,r){var n=this._transformState;if(n.writecb=r,n.writechunk=e,n.writeencoding=t,!n.transforming){var i=this._readableState;(n.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}};lr.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0};lr.prototype._destroy=function(e,t){hs.prototype._destroy.call(this,e,function(r){t(r)})};function nl(e,t,r){if(t)return e.emit("error",t);if(r!=null&&e.push(r),e._writableState.length)throw new u_;if(e._transformState.transforming)throw new c_;return e.push(null)}var d_=Mi,i0=n0;je(Mi,i0);function Mi(e){if(!(this instanceof Mi))return new Mi(e);i0.call(this,e)}Mi.prototype._transform=function(e,t,r){r(null,e)};var ia;function h_(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var o0=en.codes,p_=o0.ERR_MISSING_ARGS,y_=o0.ERR_STREAM_DESTROYED;function il(e){if(e)throw e}function m_(e){return e.setHeader&&typeof e.abort=="function"}function b_(e,t,r,n){n=h_(n);var i=!1;e.on("close",function(){i=!0}),ia===void 0&&(ia=$u),ia(e,{readable:t,writable:r},function(s){if(s)return n(s);i=!0,n()});var o=!1;return function(s){if(!i&&!o){if(o=!0,m_(e))return e.abort();if(typeof e.destroy=="function")return e.destroy();n(s||new y_("pipe"))}}}function ol(e){e()}function g_(e,t){return e.pipe(t)}function w_(e){return!e.length||typeof e[e.length-1]!="function"?il:e.pop()}function v_(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=w_(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new p_("streams");var i,o=t.map(function(s,a){var c=a<t.length-1,u=a>0;return b_(s,c,u,function(l){i||(i=l),l&&o.forEach(ol),!c&&(o.forEach(ol),n(i))})});return t.reduce(g_)}var __=v_;(function(e,t){t=e.exports=r0(),t.Stream=t,t.Readable=t,t.Writable=e0(),t.Duplex=Bn(),t.Transform=n0,t.PassThrough=d_,t.finished=$u,t.pipeline=__})(Mc,Mc.exports);var s0=Mc.exports,No=et.Buffer,a0=s0.Transform,E_=je;function x_(e,t){if(!No.isBuffer(e)&&typeof e!="string")throw new TypeError(t+" must be a string or a buffer")}function Fr(e){a0.call(this),this._block=No.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}E_(Fr,a0);Fr.prototype._transform=function(e,t,r){var n=null;try{this.update(e,t)}catch(i){n=i}r(n)};Fr.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(r){t=r}e(t)};Fr.prototype.update=function(e,t){if(x_(e,"Data"),this._finalized)throw new Error("Digest already called");No.isBuffer(e)||(e=No.from(e,t));for(var r=this._block,n=0;this._blockOffset+e.length-n>=this._blockSize;){for(var i=this._blockOffset;i<this._blockSize;)r[i++]=e[n++];this._update(),this._blockOffset=0}for(;n<e.length;)r[this._blockOffset++]=e[n++];for(var o=0,s=e.length*8;s>0;++o)this._length[o]+=s,s=this._length[o]/4294967296|0,s>0&&(this._length[o]-=4294967296*s);return this};Fr.prototype._update=function(){throw new Error("_update is not implemented")};Fr.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();e!==void 0&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t};Fr.prototype._digest=function(){throw new Error("_digest is not implemented")};var A_=Fr,S_=je,c0=A_,P_=et.Buffer,T_=new Array(16);function ps(){c0.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}S_(ps,c0);ps.prototype._update=function(){for(var e=T_,t=0;t<16;++t)e[t]=this._block.readInt32LE(t*4);var r=this._a,n=this._b,i=this._c,o=this._d;r=Ke(r,n,i,o,e[0],3614090360,7),o=Ke(o,r,n,i,e[1],3905402710,12),i=Ke(i,o,r,n,e[2],606105819,17),n=Ke(n,i,o,r,e[3],3250441966,22),r=Ke(r,n,i,o,e[4],4118548399,7),o=Ke(o,r,n,i,e[5],1200080426,12),i=Ke(i,o,r,n,e[6],2821735955,17),n=Ke(n,i,o,r,e[7],4249261313,22),r=Ke(r,n,i,o,e[8],1770035416,7),o=Ke(o,r,n,i,e[9],2336552879,12),i=Ke(i,o,r,n,e[10],4294925233,17),n=Ke(n,i,o,r,e[11],2304563134,22),r=Ke(r,n,i,o,e[12],1804603682,7),o=Ke(o,r,n,i,e[13],4254626195,12),i=Ke(i,o,r,n,e[14],2792965006,17),n=Ke(n,i,o,r,e[15],1236535329,22),r=Ye(r,n,i,o,e[1],4129170786,5),o=Ye(o,r,n,i,e[6],3225465664,9),i=Ye(i,o,r,n,e[11],643717713,14),n=Ye(n,i,o,r,e[0],3921069994,20),r=Ye(r,n,i,o,e[5],3593408605,5),o=Ye(o,r,n,i,e[10],38016083,9),i=Ye(i,o,r,n,e[15],3634488961,14),n=Ye(n,i,o,r,e[4],3889429448,20),r=Ye(r,n,i,o,e[9],568446438,5),o=Ye(o,r,n,i,e[14],3275163606,9),i=Ye(i,o,r,n,e[3],4107603335,14),n=Ye(n,i,o,r,e[8],1163531501,20),r=Ye(r,n,i,o,e[13],2850285829,5),o=Ye(o,r,n,i,e[2],4243563512,9),i=Ye(i,o,r,n,e[7],1735328473,14),n=Ye(n,i,o,r,e[12],2368359562,20),r=Xe(r,n,i,o,e[5],4294588738,4),o=Xe(o,r,n,i,e[8],2272392833,11),i=Xe(i,o,r,n,e[11],1839030562,16),n=Xe(n,i,o,r,e[14],4259657740,23),r=Xe(r,n,i,o,e[1],2763975236,4),o=Xe(o,r,n,i,e[4],1272893353,11),i=Xe(i,o,r,n,e[7],4139469664,16),n=Xe(n,i,o,r,e[10],3200236656,23),r=Xe(r,n,i,o,e[13],681279174,4),o=Xe(o,r,n,i,e[0],3936430074,11),i=Xe(i,o,r,n,e[3],3572445317,16),n=Xe(n,i,o,r,e[6],76029189,23),r=Xe(r,n,i,o,e[9],3654602809,4),o=Xe(o,r,n,i,e[12],3873151461,11),i=Xe(i,o,r,n,e[15],530742520,16),n=Xe(n,i,o,r,e[2],3299628645,23),r=Je(r,n,i,o,e[0],4096336452,6),o=Je(o,r,n,i,e[7],1126891415,10),i=Je(i,o,r,n,e[14],2878612391,15),n=Je(n,i,o,r,e[5],4237533241,21),r=Je(r,n,i,o,e[12],1700485571,6),o=Je(o,r,n,i,e[3],2399980690,10),i=Je(i,o,r,n,e[10],4293915773,15),n=Je(n,i,o,r,e[1],2240044497,21),r=Je(r,n,i,o,e[8],1873313359,6),o=Je(o,r,n,i,e[15],4264355552,10),i=Je(i,o,r,n,e[6],2734768916,15),n=Je(n,i,o,r,e[13],1309151649,21),r=Je(r,n,i,o,e[4],4149444226,6),o=Je(o,r,n,i,e[11],3174756917,10),i=Je(i,o,r,n,e[2],718787259,15),n=Je(n,i,o,r,e[9],3951481745,21),this._a=this._a+r|0,this._b=this._b+n|0,this._c=this._c+i|0,this._d=this._d+o|0};ps.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=P_.allocUnsafe(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e};function ys(e,t){return e<<t|e>>>32-t}function Ke(e,t,r,n,i,o,s){return ys(e+(t&r|~t&n)+i+o|0,s)+t|0}function Ye(e,t,r,n,i,o,s){return ys(e+(t&n|r&~n)+i+o|0,s)+t|0}function Xe(e,t,r,n,i,o,s){return ys(e+(t^r^n)+i+o|0,s)+t|0}function Je(e,t,r,n,i,o,s){return ys(e+(r^(t|~n))+i+o|0,s)+t|0}var I_=ps,$o=et.Buffer,u0=s0.Transform,B_=je;function k_(e,t){if(!$o.isBuffer(e)&&typeof e!="string")throw new TypeError(t+" must be a string or a buffer")}function Ur(e){u0.call(this),this._block=$o.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}B_(Ur,u0);Ur.prototype._transform=function(e,t,r){var n=null;try{this.update(e,t)}catch(i){n=i}r(n)};Ur.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(r){t=r}e(t)};Ur.prototype.update=function(e,t){if(k_(e,"Data"),this._finalized)throw new Error("Digest already called");$o.isBuffer(e)||(e=$o.from(e,t));for(var r=this._block,n=0;this._blockOffset+e.length-n>=this._blockSize;){for(var i=this._blockOffset;i<this._blockSize;)r[i++]=e[n++];this._update(),this._blockOffset=0}for(;n<e.length;)r[this._blockOffset++]=e[n++];for(var o=0,s=e.length*8;s>0;++o)this._length[o]+=s,s=this._length[o]/4294967296|0,s>0&&(this._length[o]-=4294967296*s);return this};Ur.prototype._update=function(){throw new Error("_update is not implemented")};Ur.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();e!==void 0&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t};Ur.prototype._digest=function(){throw new Error("_digest is not implemented")};var O_=Ur,oa=Bt.Buffer,R_=je,f0=O_,C_=new Array(16),Xn=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],Jn=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],Qn=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],Zn=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],ei=[0,1518500249,1859775393,2400959708,2840853838],ti=[1352829926,1548603684,1836072691,2053994217,0];function ms(){f0.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}R_(ms,f0);ms.prototype._update=function(){for(var e=C_,t=0;t<16;++t)e[t]=this._block.readInt32LE(t*4);for(var r=this._a|0,n=this._b|0,i=this._c|0,o=this._d|0,s=this._e|0,a=this._a|0,c=this._b|0,u=this._c|0,l=this._d|0,h=this._e|0,y=0;y<80;y+=1){var p,b;y<16?(p=sl(r,n,i,o,s,e[Xn[y]],ei[0],Qn[y]),b=fl(a,c,u,l,h,e[Jn[y]],ti[0],Zn[y])):y<32?(p=al(r,n,i,o,s,e[Xn[y]],ei[1],Qn[y]),b=ul(a,c,u,l,h,e[Jn[y]],ti[1],Zn[y])):y<48?(p=cl(r,n,i,o,s,e[Xn[y]],ei[2],Qn[y]),b=cl(a,c,u,l,h,e[Jn[y]],ti[2],Zn[y])):y<64?(p=ul(r,n,i,o,s,e[Xn[y]],ei[3],Qn[y]),b=al(a,c,u,l,h,e[Jn[y]],ti[3],Zn[y])):(p=fl(r,n,i,o,s,e[Xn[y]],ei[4],Qn[y]),b=sl(a,c,u,l,h,e[Jn[y]],ti[4],Zn[y])),r=s,s=o,o=Xr(i,10),i=n,n=p,a=h,h=l,l=Xr(u,10),u=c,c=b}var v=this._b+i+l|0;this._b=this._c+o+h|0,this._c=this._d+s+a|0,this._d=this._e+r+c|0,this._e=this._a+n+u|0,this._a=v};ms.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=oa.alloc?oa.alloc(20):new oa(20);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e.writeInt32LE(this._e,16),e};function Xr(e,t){return e<<t|e>>>32-t}function sl(e,t,r,n,i,o,s,a){return Xr(e+(t^r^n)+o+s|0,a)+i|0}function al(e,t,r,n,i,o,s,a){return Xr(e+(t&r|~t&n)+o+s|0,a)+i|0}function cl(e,t,r,n,i,o,s,a){return Xr(e+((t|~r)^n)+o+s|0,a)+i|0}function ul(e,t,r,n,i,o,s,a){return Xr(e+(t&n|r&~n)+o+s|0,a)+i|0}function fl(e,t,r,n,i,o,s,a){return Xr(e+(t^(r|~n))+o+s|0,a)+i|0}var F_=ms,l0={exports:{}},U_={}.toString,N_=Array.isArray||function(e){return U_.call(e)=="[object Array]"},sa,ll;function Hn(){return ll||(ll=1,sa=TypeError),sa}var aa,dl;function d0(){return dl||(dl=1,aa=Object),aa}var ca,hl;function $_(){return hl||(hl=1,ca=Error),ca}var ua,pl;function L_(){return pl||(pl=1,ua=EvalError),ua}var fa,yl;function M_(){return yl||(yl=1,fa=RangeError),fa}var la,ml;function H_(){return ml||(ml=1,la=ReferenceError),la}var da,bl;function h0(){return bl||(bl=1,da=SyntaxError),da}var ha,gl;function D_(){return gl||(gl=1,ha=URIError),ha}var pa,wl;function j_(){return wl||(wl=1,pa=Math.abs),pa}var ya,vl;function q_(){return vl||(vl=1,ya=Math.floor),ya}var ma,_l;function G_(){return _l||(_l=1,ma=Math.max),ma}var ba,El;function z_(){return El||(El=1,ba=Math.min),ba}var ga,xl;function V_(){return xl||(xl=1,ga=Math.pow),ga}var wa,Al;function W_(){return Al||(Al=1,wa=Math.round),wa}var va,Sl;function K_(){return Sl||(Sl=1,va=Number.isNaN||function(t){return t!==t}),va}var _a,Pl;function Y_(){if(Pl)return _a;Pl=1;var e=K_();return _a=function(r){return e(r)||r===0?r:r<0?-1:1},_a}var Ea,Tl;function X_(){return Tl||(Tl=1,Ea=Object.getOwnPropertyDescriptor),Ea}var xa,Il;function Dn(){if(Il)return xa;Il=1;var e=X_();if(e)try{e([],"length")}catch{e=null}return xa=e,xa}var Aa,Bl;function bs(){if(Bl)return Aa;Bl=1;var e=Object.defineProperty||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Aa=e,Aa}var Sa,kl;function p0(){return kl||(kl=1,Sa=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var t={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var i=42;t[r]=i;for(var o in t)return!1;if(typeof Object.keys=="function"&&Object.keys(t).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(t).length!==0)return!1;var s=Object.getOwnPropertySymbols(t);if(s.length!==1||s[0]!==r||!Object.prototype.propertyIsEnumerable.call(t,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var a=Object.getOwnPropertyDescriptor(t,r);if(a.value!==i||a.enumerable!==!0)return!1}return!0}),Sa}var Pa,Ol;function J_(){if(Ol)return Pa;Ol=1;var e=typeof Symbol<"u"&&Symbol,t=p0();return Pa=function(){return typeof e!="function"||typeof Symbol!="function"||typeof e("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:t()},Pa}var Ta,Rl;function y0(){return Rl||(Rl=1,Ta=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),Ta}var Ia,Cl;function m0(){if(Cl)return Ia;Cl=1;var e=d0();return Ia=e.getPrototypeOf||null,Ia}var Ba,Fl;function Q_(){if(Fl)return Ba;Fl=1;var e="Function.prototype.bind called on incompatible ",t=Object.prototype.toString,r=Math.max,n="[object Function]",i=function(c,u){for(var l=[],h=0;h<c.length;h+=1)l[h]=c[h];for(var y=0;y<u.length;y+=1)l[y+c.length]=u[y];return l},o=function(c,u){for(var l=[],h=u,y=0;h<c.length;h+=1,y+=1)l[y]=c[h];return l},s=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 Ba=function(c){var u=this;if(typeof u!="function"||t.apply(u)!==n)throw new TypeError(e+u);for(var l=o(arguments,1),h,y=function(){if(this instanceof h){var S=u.apply(this,i(l,arguments));return Object(S)===S?S:this}return u.apply(c,i(l,arguments))},p=r(0,u.length-l.length),b=[],v=0;v<p;v++)b[v]="$"+v;if(h=Function("binder","return function ("+s(b,",")+"){ return binder.apply(this,arguments); }")(y),u.prototype){var E=function(){};E.prototype=u.prototype,h.prototype=new E,E.prototype=null}return h},Ba}var ka,Ul;function Qi(){if(Ul)return ka;Ul=1;var e=Q_();return ka=Function.prototype.bind||e,ka}var Oa,Nl;function Lu(){return Nl||(Nl=1,Oa=Function.prototype.call),Oa}var Ra,$l;function Mu(){return $l||($l=1,Ra=Function.prototype.apply),Ra}var Ca,Ll;function Z_(){return Ll||(Ll=1,Ca=typeof Reflect<"u"&&Reflect&&Reflect.apply),Ca}var Fa,Ml;function b0(){if(Ml)return Fa;Ml=1;var e=Qi(),t=Mu(),r=Lu(),n=Z_();return Fa=n||e.call(r,t),Fa}var Ua,Hl;function Hu(){if(Hl)return Ua;Hl=1;var e=Qi(),t=Hn(),r=Lu(),n=b0();return Ua=function(o){if(o.length<1||typeof o[0]!="function")throw new t("a function is required");return n(e,r,o)},Ua}var Na,Dl;function eE(){if(Dl)return Na;Dl=1;var e=Hu(),t=Dn(),r;try{r=[].__proto__===Array.prototype}catch(s){if(!s||typeof s!="object"||!("code"in s)||s.code!=="ERR_PROTO_ACCESS")throw s}var n=!!r&&t&&t(Object.prototype,"__proto__"),i=Object,o=i.getPrototypeOf;return Na=n&&typeof n.get=="function"?e([n.get]):typeof o=="function"?function(a){return o(a==null?a:i(a))}:!1,Na}var $a,jl;function Du(){if(jl)return $a;jl=1;var e=y0(),t=m0(),r=eE();return $a=e?function(i){return e(i)}:t?function(i){if(!i||typeof i!="object"&&typeof i!="function")throw new TypeError("getProto: not an object");return t(i)}:r?function(i){return r(i)}:null,$a}var La,ql;function g0(){if(ql)return La;ql=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=Qi();return La=r.call(e,t),La}var Ma,Gl;function w0(){if(Gl)return Ma;Gl=1;var e,t=d0(),r=$_(),n=L_(),i=M_(),o=H_(),s=h0(),a=Hn(),c=D_(),u=j_(),l=q_(),h=G_(),y=z_(),p=V_(),b=W_(),v=Y_(),E=Function,S=function(V){try{return E('"use strict"; return ('+V+").constructor;")()}catch{}},P=Dn(),A=bs(),w=function(){throw new a},B=P?function(){try{return arguments.callee,w}catch{try{return P(arguments,"callee").get}catch{return w}}}():w,T=J_()(),L=Du(),D=m0(),C=y0(),X=Mu(),Z=Lu(),oe={},te=typeof Uint8Array>"u"||!L?e:L(Uint8Array),ee={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?e:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?e:ArrayBuffer,"%ArrayIteratorPrototype%":T&&L?L([][Symbol.iterator]()):e,"%AsyncFromSyncIteratorPrototype%":e,"%AsyncFunction%":oe,"%AsyncGenerator%":oe,"%AsyncGeneratorFunction%":oe,"%AsyncIteratorPrototype%":oe,"%Atomics%":typeof Atomics>"u"?e:Atomics,"%BigInt%":typeof BigInt>"u"?e:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?e:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?e:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?e:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":typeof Float16Array>"u"?e:Float16Array,"%Float32Array%":typeof Float32Array>"u"?e:Float32Array,"%Float64Array%":typeof Float64Array>"u"?e:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?e:FinalizationRegistry,"%Function%":E,"%GeneratorFunction%":oe,"%Int8Array%":typeof Int8Array>"u"?e:Int8Array,"%Int16Array%":typeof Int16Array>"u"?e:Int16Array,"%Int32Array%":typeof Int32Array>"u"?e:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":T&&L?L(L([][Symbol.iterator]())):e,"%JSON%":typeof JSON=="object"?JSON:e,"%Map%":typeof Map>"u"?e:Map,"%MapIteratorPrototype%":typeof Map>"u"||!T||!L?e:L(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":t,"%Object.getOwnPropertyDescriptor%":P,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?e:Promise,"%Proxy%":typeof Proxy>"u"?e:Proxy,"%RangeError%":i,"%ReferenceError%":o,"%Reflect%":typeof Reflect>"u"?e:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?e:Set,"%SetIteratorPrototype%":typeof Set>"u"||!T||!L?e:L(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?e:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":T&&L?L(""[Symbol.iterator]()):e,"%Symbol%":T?Symbol:e,"%SyntaxError%":s,"%ThrowTypeError%":B,"%TypedArray%":te,"%TypeError%":a,"%Uint8Array%":typeof Uint8Array>"u"?e:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?e:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?e:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?e:Uint32Array,"%URIError%":c,"%WeakMap%":typeof WeakMap>"u"?e:WeakMap,"%WeakRef%":typeof WeakRef>"u"?e:WeakRef,"%WeakSet%":typeof WeakSet>"u"?e:WeakSet,"%Function.prototype.call%":Z,"%Function.prototype.apply%":X,"%Object.defineProperty%":A,"%Object.getPrototypeOf%":D,"%Math.abs%":u,"%Math.floor%":l,"%Math.max%":h,"%Math.min%":y,"%Math.pow%":p,"%Math.round%":b,"%Math.sign%":v,"%Reflect.getPrototypeOf%":C};if(L)try{null.error}catch(V){var ae=L(L(V));ee["%Error.prototype%"]=ae}var be=function V(W){var g;if(W==="%AsyncFunction%")g=S("async function () {}");else if(W==="%GeneratorFunction%")g=S("function* () {}");else if(W==="%AsyncGeneratorFunction%")g=S("async function* () {}");else if(W==="%AsyncGenerator%"){var _=V("%AsyncGeneratorFunction%");_&&(g=_.prototype)}else if(W==="%AsyncIteratorPrototype%"){var H=V("%AsyncGenerator%");H&&L&&(g=L(H.prototype))}return ee[W]=g,g},ye={__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"]},ce=Qi(),F=g0(),Y=ce.call(Z,Array.prototype.concat),re=ce.call(X,Array.prototype.splice),O=ce.call(Z,String.prototype.replace),N=ce.call(Z,String.prototype.slice),q=ce.call(Z,RegExp.prototype.exec),ne=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,I=/\\(\\)?/g,k=function(W){var g=N(W,0,1),_=N(W,-1);if(g==="%"&&_!=="%")throw new s("invalid intrinsic syntax, expected closing `%`");if(_==="%"&&g!=="%")throw new s("invalid intrinsic syntax, expected opening `%`");var H=[];return O(W,ne,function(K,de,ie,fe){H[H.length]=ie?O(fe,I,"$1"):de||K}),H},M=function(W,g){var _=W,H;if(F(ye,_)&&(H=ye[_],_="%"+H[0]+"%"),F(ee,_)){var K=ee[_];if(K===oe&&(K=be(_)),typeof K>"u"&&!g)throw new a("intrinsic "+W+" exists, but is not available. Please file an issue!");return{alias:H,name:_,value:K}}throw new s("intrinsic "+W+" does not exist!")};return Ma=function(W,g){if(typeof W!="string"||W.length===0)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof g!="boolean")throw new a('"allowMissing" argument must be a boolean');if(q(/^%?[^%]*%?$/,W)===null)throw new s("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var _=k(W),H=_.length>0?_[0]:"",K=M("%"+H+"%",g),de=K.name,ie=K.value,fe=!1,ut=K.alias;ut&&(H=ut[0],re(_,Y([0,1],ut)));for(var j=1,pt=!0;j<_.length;j+=1){var qe=_[j],Ne=N(qe,0,1),wt=N(qe,-1);if((Ne==='"'||Ne==="'"||Ne==="`"||wt==='"'||wt==="'"||wt==="`")&&Ne!==wt)throw new s("property names with quotes must have matching quotes");if((qe==="constructor"||!pt)&&(fe=!0),H+="."+qe,de="%"+H+"%",F(ee,de))ie=ee[de];else if(ie!=null){if(!(qe in ie)){if(!g)throw new a("base intrinsic for "+W+" exists, but the property is not available.");return}if(P&&j+1>=_.length){var Ot=P(ie,qe);pt=!!Ot,pt&&"get"in Ot&&!("originalValue"in Ot.get)?ie=Ot.get:ie=ie[qe]}else pt=F(ie,qe),ie=ie[qe];pt&&!fe&&(ee[de]=ie)}}return ie},Ma}var Ha,zl;function jn(){if(zl)return Ha;zl=1;var e=w0(),t=Hu(),r=t([e("%String.prototype.indexOf%")]);return Ha=function(i,o){var s=e(i,!!o);return typeof s=="function"&&r(i,".prototype.")>-1?t([s]):s},Ha}var Da,Vl;function tE(){if(Vl)return Da;Vl=1;var e=Function.prototype.toString,t=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,r,n;if(typeof t=="function"&&typeof Object.defineProperty=="function")try{r=Object.defineProperty({},"length",{get:function(){throw n}}),n={},t(function(){throw 42},null,r)}catch(P){P!==n&&(t=null)}else t=null;var i=/^\s*class\b/,o=function(A){try{var w=e.call(A);return i.test(w)}catch{return!1}},s=function(A){try{return o(A)?!1:(e.call(A),!0)}catch{return!1}},a=Object.prototype.toString,c="[object Object]",u="[object Function]",l="[object GeneratorFunction]",h="[object HTMLAllCollection]",y="[object HTML document.all class]",p="[object HTMLCollection]",b=typeof Symbol=="function"&&!!Symbol.toStringTag,v=!(0 in[,]),E=function(){return!1};if(typeof document=="object"){var S=document.all;a.call(S)===a.call(document.all)&&(E=function(A){if((v||!A)&&(typeof A>"u"||typeof A=="object"))try{var w=a.call(A);return(w===h||w===y||w===p||w===c)&&A("")==null}catch{}return!1})}return Da=t?function(A){if(E(A))return!0;if(!A||typeof A!="function"&&typeof A!="object")return!1;try{t(A,null,r)}catch(w){if(w!==n)return!1}return!o(A)&&s(A)}:function(A){if(E(A))return!0;if(!A||typeof A!="function"&&typeof A!="object")return!1;if(b)return s(A);if(o(A))return!1;var w=a.call(A);return w!==u&&w!==l&&!/^\[object HTML/.test(w)?!1:s(A)},Da}var ja,Wl;function rE(){if(Wl)return ja;Wl=1;var e=tE(),t=Object.prototype.toString,r=Object.prototype.hasOwnProperty,n=function(c,u,l){for(var h=0,y=c.length;h<y;h++)r.call(c,h)&&(l==null?u(c[h],h,c):u.call(l,c[h],h,c))},i=function(c,u,l){for(var h=0,y=c.length;h<y;h++)l==null?u(c.charAt(h),h,c):u.call(l,c.charAt(h),h,c)},o=function(c,u,l){for(var h in c)r.call(c,h)&&(l==null?u(c[h],h,c):u.call(l,c[h],h,c))};function s(a){return t.call(a)==="[object Array]"}return ja=function(c,u,l){if(!e(u))throw new TypeError("iterator must be a function");var h;arguments.length>=3&&(h=l),s(c)?n(c,u,h):typeof c=="string"?i(c,u,h):o(c,u,h)},ja}var qa,Kl;function nE(){return Kl||(Kl=1,qa=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),qa}var Ga,Yl;function iE(){if(Yl)return Ga;Yl=1;var e=nE(),t=typeof globalThis>"u"?De:globalThis;return Ga=function(){for(var n=[],i=0;i<e.length;i++)typeof t[e[i]]=="function"&&(n[n.length]=e[i]);return n},Ga}var za={exports:{}},Va,Xl;function oE(){if(Xl)return Va;Xl=1;var e=bs(),t=h0(),r=Hn(),n=Dn();return Va=function(o,s,a){if(!o||typeof o!="object"&&typeof o!="function")throw new r("`obj` must be an object or a function`");if(typeof s!="string"&&typeof s!="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,h=arguments.length>6?arguments[6]:!1,y=!!n&&n(o,s);if(e)e(o,s,{configurable:l===null&&y?y.configurable:!l,enumerable:c===null&&y?y.enumerable:!c,value:a,writable:u===null&&y?y.writable:!u});else if(h||!c&&!u&&!l)o[s]=a;else throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Va}var Wa,Jl;function sE(){if(Jl)return Wa;Jl=1;var e=bs(),t=function(){return!!e};return t.hasArrayLengthDefineBug=function(){if(!e)return null;try{return e([],"length",{value:1}).length!==1}catch{return!0}},Wa=t,Wa}var Ka,Ql;function aE(){if(Ql)return Ka;Ql=1;var e=w0(),t=oE(),r=sE()(),n=Dn(),i=Hn(),o=e("%Math.floor%");return Ka=function(a,c){if(typeof a!="function")throw new i("`fn` is not a function");if(typeof c!="number"||c<0||c>4294967295||o(c)!==c)throw new i("`length` must be a positive 32-bit integer");var u=arguments.length>2&&!!arguments[2],l=!0,h=!0;if("length"in a&&n){var y=n(a,"length");y&&!y.configurable&&(l=!1),y&&!y.writable&&(h=!1)}return(l||h||!u)&&(r?t(a,"length",c,!0,!0):t(a,"length",c)),a},Ka}var Ya,Zl;function cE(){if(Zl)return Ya;Zl=1;var e=Qi(),t=Mu(),r=b0();return Ya=function(){return r(e,t,arguments)},Ya}var ed;function uE(){return ed||(ed=1,function(e){var t=aE(),r=bs(),n=Hu(),i=cE();e.exports=function(s){var a=n(arguments),c=s.length-(arguments.length-1);return t(a,1+(c>0?c:0),!0)},r?r(e.exports,"apply",{value:i}):e.exports.apply=i}(za)),za.exports}var Xa,td;function gs(){if(td)return Xa;td=1;var e=p0();return Xa=function(){return e()&&!!Symbol.toStringTag},Xa}var Ja,rd;function v0(){if(rd)return Ja;rd=1;var e=rE(),t=iE(),r=uE(),n=jn(),i=Dn(),o=Du(),s=n("Object.prototype.toString"),a=gs()(),c=typeof globalThis>"u"?De:globalThis,u=t(),l=n("String.prototype.slice"),h=n("Array.prototype.indexOf",!0)||function(E,S){for(var P=0;P<E.length;P+=1)if(E[P]===S)return P;return-1},y={__proto__:null};a&&i&&o?e(u,function(v){var E=new c[v];if(Symbol.toStringTag in E&&o){var S=o(E),P=i(S,Symbol.toStringTag);if(!P&&S){var A=o(S);P=i(A,Symbol.toStringTag)}y["$"+v]=r(P.get)}}):e(u,function(v){var E=new c[v],S=E.slice||E.set;S&&(y["$"+v]=r(S))});var p=function(E){var S=!1;return e(y,function(P,A){if(!S)try{"$"+P(E)===A&&(S=l(A,1))}catch{}}),S},b=function(E){var S=!1;return e(y,function(P,A){if(!S)try{P(E),S=l(A,1)}catch{}}),S};return Ja=function(E){if(!E||typeof E!="object")return!1;if(!a){var S=l(s(E),8,-1);return h(u,S)>-1?S:S!=="Object"?!1:b(E)}return i?p(E):null},Ja}var Qa,nd;function _0(){if(nd)return Qa;nd=1;var e=v0();return Qa=function(r){return!!e(r)},Qa}var fE=Hn(),lE=jn(),dE=lE("TypedArray.prototype.buffer",!0),hE=_0(),pE=dE||function(t){if(!hE(t))throw new fE("Not a Typed Array");return t.buffer},Ht=et.Buffer,yE=N_,mE=pE,bE=ArrayBuffer.isView||function(t){try{return mE(t),!0}catch{return!1}},gE=typeof Uint8Array<"u",E0=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",wE=E0&&(Ht.prototype instanceof Uint8Array||Ht.TYPED_ARRAY_SUPPORT),vE=function(t,r){if(t instanceof Ht)return t;if(typeof t=="string")return Ht.from(t,r);if(E0&&bE(t)){if(t.byteLength===0)return Ht.alloc(0);if(wE){var n=Ht.from(t.buffer,t.byteOffset,t.byteLength);if(n.byteLength===t.byteLength)return n}var i=t instanceof Uint8Array?t:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),o=Ht.from(i);if(o.length===t.byteLength)return o}if(gE&&t instanceof Uint8Array)return Ht.from(t);var s=yE(t);if(s)for(var a=0;a<t.length;a+=1){var c=t[a];if(typeof c!="number"||c<0||c>255||~~c!==c)throw new RangeError("Array items must be numbers in the range 0-255.")}if(s||Ht.isBuffer(t)&&t.constructor&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t))return Ht.from(t);throw new TypeError('The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.')},_E=et.Buffer,EE=vE;function ws(e,t){this._block=_E.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}ws.prototype.update=function(e,t){e=EE(e,t||"utf8");for(var r=this._block,n=this._blockSize,i=e.length,o=this._len,s=0;s<i;){for(var a=o%n,c=Math.min(i-s,n-a),u=0;u<c;u++)r[a+u]=e[s+u];o+=c,s+=c,o%n===0&&this._update(r)}return this._len+=i,this};ws.prototype.digest=function(e){var t=this._len%this._blockSize;this._block[t]=128,this._block.fill(0,t+1),t>=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=this._len*8;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(r&4294967295)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return e?o.toString(e):o};ws.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var qn=ws,xE=je,x0=qn,AE=et.Buffer,SE=[1518500249,1859775393,-1894007588,-899497514],PE=new Array(80);function Zi(){this.init(),this._w=PE,x0.call(this,64,56)}xE(Zi,x0);Zi.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function TE(e){return e<<5|e>>>27}function IE(e){return e<<30|e>>>2}function BE(e,t,r,n){return e===0?t&r|~t&n:e===2?t&r|t&n|r&n:t^r^n}Zi.prototype._update=function(e){for(var t=this._w,r=this._a|0,n=this._b|0,i=this._c|0,o=this._d|0,s=this._e|0,a=0;a<16;++a)t[a]=e.readInt32BE(a*4);for(;a<80;++a)t[a]=t[a-3]^t[a-8]^t[a-14]^t[a-16];for(var c=0;c<80;++c){var u=~~(c/20),l=TE(r)+BE(u,n,i,o)+s+t[c]+SE[u]|0;s=o,o=i,i=IE(n),n=r,r=l}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0};Zi.prototype._hash=function(){var e=AE.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e};var kE=Zi,OE=je,A0=qn,RE=et.Buffer,CE=[1518500249,1859775393,-1894007588,-899497514],FE=new Array(80);function eo(){this.init(),this._w=FE,A0.call(this,64,56)}OE(eo,A0);eo.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function UE(e){return e<<1|e>>>31}function NE(e){return e<<5|e>>>27}function $E(e){return e<<30|e>>>2}function LE(e,t,r,n){return e===0?t&r|~t&n:e===2?t&r|t&n|r&n:t^r^n}eo.prototype._update=function(e){for(var t=this._w,r=this._a|0,n=this._b|0,i=this._c|0,o=this._d|0,s=this._e|0,a=0;a<16;++a)t[a]=e.readInt32BE(a*4);for(;a<80;++a)t[a]=UE(t[a-3]^t[a-8]^t[a-14]^t[a-16]);for(var c=0;c<80;++c){var u=~~(c/20),l=NE(r)+LE(u,n,i,o)+s+t[c]+CE[u]|0;s=o,o=i,i=$E(n),n=r,r=l}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0};eo.prototype._hash=function(){var e=RE.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e};var ME=eo,HE=je,S0=qn,DE=et.Buffer,jE=[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],qE=new Array(64);function to(){this.init(),this._w=qE,S0.call(this,64,56)}HE(to,S0);to.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this};function GE(e,t,r){return r^e&(t^r)}function zE(e,t,r){return e&t|r&(e|t)}function VE(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function WE(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function KE(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}function YE(e){return(e>>>17|e<<15)^(e>>>19|e<<13)^e>>>10}to.prototype._update=function(e){for(var t=this._w,r=this._a|0,n=this._b|0,i=this._c|0,o=this._d|0,s=this._e|0,a=this._f|0,c=this._g|0,u=this._h|0,l=0;l<16;++l)t[l]=e.readInt32BE(l*4);for(;l<64;++l)t[l]=YE(t[l-2])+t[l-7]+KE(t[l-15])+t[l-16]|0;for(var h=0;h<64;++h){var y=u+WE(s)+GE(s,a,c)+jE[h]+t[h]|0,p=VE(r)+zE(r,n,i)|0;u=c,c=a,a=s,s=o+y|0,o=i,i=n,n=r,r=y+p|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0,this._f=a+this._f|0,this._g=c+this._g|0,this._h=u+this._h|0};to.prototype._hash=function(){var e=DE.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e};var P0=to,XE=je,JE=P0,QE=qn,ZE=et.Buffer,ex=new Array(64);function vs(){this.init(),this._w=ex,QE.call(this,64,56)}XE(vs,JE);vs.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this};vs.prototype._hash=function(){var e=ZE.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e};var tx=vs,rx=je,T0=qn,nx=et.Buffer,id=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],ix=new Array(160);function ro(){this.init(),this._w=ix,T0.call(this,128,112)}rx(ro,T0);ro.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this};function od(e,t,r){return r^e&(t^r)}function sd(e,t,r){return e&t|r&(e|t)}function ad(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function cd(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function ox(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function sx(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function ax(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function cx(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function $e(e,t){return e>>>0<t>>>0?1:0}ro.prototype._update=function(e){for(var t=this._w,r=this._ah|0,n=this._bh|0,i=this._ch|0,o=this._dh|0,s=this._eh|0,a=this._fh|0,c=this._gh|0,u=this._hh|0,l=this._al|0,h=this._bl|0,y=this._cl|0,p=this._dl|0,b=this._el|0,v=this._fl|0,E=this._gl|0,S=this._hl|0,P=0;P<32;P+=2)t[P]=e.readInt32BE(P*4),t[P+1]=e.readInt32BE(P*4+4);for(;P<160;P+=2){var A=t[P-30],w=t[P-15*2+1],B=ox(A,w),T=sx(w,A);A=t[P-2*2],w=t[P-2*2+1];var L=ax(A,w),D=cx(w,A),C=t[P-7*2],X=t[P-7*2+1],Z=t[P-16*2],oe=t[P-16*2+1],te=T+X|0,ee=B+C+$e(te,T)|0;te=te+D|0,ee=ee+L+$e(te,D)|0,te=te+oe|0,ee=ee+Z+$e(te,oe)|0,t[P]=ee,t[P+1]=te}for(var ae=0;ae<160;ae+=2){ee=t[ae],te=t[ae+1];var be=sd(r,n,i),ye=sd(l,h,y),ce=ad(r,l),F=ad(l,r),Y=cd(s,b),re=cd(b,s),O=id[ae],N=id[ae+1],q=od(s,a,c),ne=od(b,v,E),I=S+re|0,k=u+Y+$e(I,S)|0;I=I+ne|0,k=k+q+$e(I,ne)|0,I=I+N|0,k=k+O+$e(I,N)|0,I=I+te|0,k=k+ee+$e(I,te)|0;var M=F+ye|0,V=ce+be+$e(M,F)|0;u=c,S=E,c=a,E=v,a=s,v=b,b=p+I|0,s=o+k+$e(b,p)|0,o=i,p=y,i=n,y=h,n=r,h=l,l=I+M|0,r=k+V+$e(l,I)|0}this._al=this._al+l|0,this._bl=this._bl+h|0,this._cl=this._cl+y|0,this._dl=this._dl+p|0,this._el=this._el+b|0,this._fl=this._fl+v|0,this._gl=this._gl+E|0,this._hl=this._hl+S|0,this._ah=this._ah+r+$e(this._al,l)|0,this._bh=this._bh+n+$e(this._bl,h)|0,this._ch=this._ch+i+$e(this._cl,y)|0,this._dh=this._dh+o+$e(this._dl,p)|0,this._eh=this._eh+s+$e(this._el,b)|0,this._fh=this._fh+a+$e(this._fl,v)|0,this._gh=this._gh+c+$e(this._gl,E)|0,this._hh=this._hh+u+$e(this._hl,S)|0};ro.prototype._hash=function(){var e=nx.allocUnsafe(64);function t(r,n,i){e.writeInt32BE(r,i),e.writeInt32BE(n,i+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e};var I0=ro,ux=je,fx=I0,lx=qn,dx=et.Buffer,hx=new Array(160);function _s(){this.init(),this._w=hx,lx.call(this,128,112)}ux(_s,fx);_s.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this};_s.prototype._hash=function(){var e=dx.allocUnsafe(48);function t(r,n,i){e.writeInt32BE(r,i),e.writeInt32BE(n,i+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e};var px=_s;(function(e){e.exports=function(r){var n=r.toLowerCase(),i=e.exports[n];if(!i)throw new Error(n+" is not supported (we accept pull requests)");return new i},e.exports.sha=kE,e.exports.sha1=ME,e.exports.sha224=tx,e.exports.sha256=P0,e.exports.sha384=px,e.exports.sha512=I0})(l0);var yx=l0.exports,Dt=et.Buffer,B0=Uu.Transform,mx=Uo.StringDecoder,bx=je;function kt(e){B0.call(this),this.hashMode=typeof e=="string",this.hashMode?this[e]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}bx(kt,B0);var gx=typeof Uint8Array<"u",wx=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&ArrayBuffer.isView&&(Dt.prototype instanceof Uint8Array||Dt.TYPED_ARRAY_SUPPORT);function vx(e,t){if(e instanceof Dt)return e;if(typeof e=="string")return Dt.from(e,t);if(wx&&ArrayBuffer.isView(e)){if(e.byteLength===0)return Dt.alloc(0);var r=Dt.from(e.buffer,e.byteOffset,e.byteLength);if(r.byteLength===e.byteLength)return r}if(gx&&e instanceof Uint8Array||Dt.isBuffer(e)&&e.constructor&&typeof e.constructor.isBuffer=="function"&&e.constructor.isBuffer(e))return Dt.from(e);throw new TypeError('The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.')}kt.prototype.update=function(e,t,r){var n=vx(e,t),i=this._update(n);return this.hashMode?this:(r&&(i=this._toString(i,r)),i)};kt.prototype.setAutoPadding=function(){};kt.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")};kt.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")};kt.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")};kt.prototype._transform=function(e,t,r){var n;try{this.hashMode?this._update(e):this.push(this._update(e))}catch(i){n=i}finally{r(n)}};kt.prototype._flush=function(e){var t;try{this.push(this.__final())}catch(r){t=r}e(t)};kt.prototype._finalOrDigest=function(e){var t=this.__final()||Dt.alloc(0);return e&&(t=this._toString(t,e,!0)),t};kt.prototype._toString=function(e,t,r){if(this._decoder||(this._decoder=new mx(t),this._encoding=t),this._encoding!==t)throw new Error("can’t switch encodings");var n=this._decoder.write(e);return r&&(n+=this._decoder.end()),n};var _x=kt,Ex=je,xx=I_,Ax=F_,Sx=yx,k0=_x;function Es(e){k0.call(this,"digest"),this._hash=e}Ex(Es,k0);Es.prototype._update=function(e){this._hash.update(e)};Es.prototype._final=function(){return this._hash.digest()};var Px=function(t){return t=t.toLowerCase(),t==="md5"?new xx:t==="rmd160"||t==="ripemd160"?new Ax:new Es(Sx(t))},wo=et.Buffer;function Tx(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),o=i.charCodeAt(0);if(t[o]!==255)throw new TypeError(i+" is ambiguous");t[o]=n}var s=e.length,a=e.charAt(0),c=Math.log(s)/Math.log(256),u=Math.log(256)/Math.log(s);function l(p){if((Array.isArray(p)||p instanceof Uint8Array)&&(p=wo.from(p)),!wo.isBuffer(p))throw new TypeError("Expected Buffer");if(p.length===0)return"";for(var b=0,v=0,E=0,S=p.length;E!==S&&p[E]===0;)E++,b++;for(var P=(S-E)*u+1>>>0,A=new Uint8Array(P);E!==S;){for(var w=p[E],B=0,T=P-1;(w!==0||B<v)&&T!==-1;T--,B++)w+=256*A[T]>>>0,A[T]=w%s>>>0,w=w/s>>>0;if(w!==0)throw new Error("Non-zero carry");v=B,E++}for(var L=P-v;L!==P&&A[L]===0;)L++;for(var D=a.repeat(b);L<P;++L)D+=e.charAt(A[L]);return D}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return wo.alloc(0);for(var b=0,v=0,E=0;p[b]===a;)v++,b++;for(var S=(p.length-b)*c+1>>>0,P=new Uint8Array(S);b<p.length;){var A=p.charCodeAt(b);if(A>255)return;var w=t[A];if(w===255)return;for(var B=0,T=S-1;(w!==0||B<E)&&T!==-1;T--,B++)w+=s*P[T]>>>0,P[T]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");E=B,b++}for(var L=S-E;L!==S&&P[L]===0;)L++;var D=wo.allocUnsafe(v+(S-L));D.fill(0,0,v);for(var C=v;L!==S;)D[C++]=P[L++];return D}function y(p){var b=h(p);if(b)return b;throw new Error("Non-base"+s+" character")}return{encode:l,decodeUnsafe:h,decode:y}}var O0=Tx,Ix=O0,Bx="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",kx=Ix(Bx),Za=kx,Ox=et.Buffer,Rx=function(e){function t(o){var s=e(o);return Za.encode(Ox.concat([o,s],o.length+4))}function r(o){var s=o.slice(0,-4),a=o.slice(-4),c=e(s);if(!(a[0]^c[0]|a[1]^c[1]|a[2]^c[2]|a[3]^c[3]))return s}function n(o){var s=Za.decodeUnsafe(o);if(s)return r(s)}function i(o){var s=Za.decode(o),a=r(s);if(!a)throw new Error("Invalid checksum");return a}return{encode:t,decode:i,decodeUnsafe:n}},ud=Px,Cx=Rx;function Fx(e){var t=ud("sha256").update(e).digest();return ud("sha256").update(t).digest()}var Ux=Cx(Fx),Dc=Ux;function R0(e,t){if(t!==void 0&&e[0]!==t)throw new Error("Invalid network version");if(e.length===33)return{version:e[0],privateKey:e.slice(1,33),compressed:!1};if(e.length!==34)throw new Error("Invalid WIF length");if(e[33]!==1)throw new Error("Invalid compression flag");return{version:e[0],privateKey:e.slice(1,33),compressed:!0}}function jc(e,t,r){var n=new Buffer(r?34:33);return n.writeUInt8(e,0),t.copy(n,1),r&&(n[33]=1),n}function Nx(e,t){return R0(Dc.decode(e),t)}function $x(e,t,r){return typeof e=="number"?Dc.encode(jc(e,t,r)):Dc.encode(jc(e.version,e.privateKey,e.compressed))}var Lx={decode:Nx,decodeRaw:R0,encode:$x,encodeRaw:jc},xs={};Object.defineProperty(xs,"__esModule",{value:!0});xs.testEcc=void 0;const se=e=>Buffer.from(e,"hex");function Mx(e){Ae(e.isPoint(se("0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),Ae(!e.isPoint(se("030000000000000000000000000000000000000000000000000000000000000005"))),Ae(e.isPrivate(se("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),Ae(e.isPrivate(se("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"))),Ae(!e.isPrivate(se("0000000000000000000000000000000000000000000000000000000000000000"))),Ae(!e.isPrivate(se("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"))),Ae(!e.isPrivate(se("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364142"))),Ae(Buffer.from(e.privateAdd(se("0000000000000000000000000000000000000000000000000000000000000001"),se("0000000000000000000000000000000000000000000000000000000000000000"))).equals(se("0000000000000000000000000000000000000000000000000000000000000001"))),Ae(e.privateAdd(se("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036413e"),se("0000000000000000000000000000000000000000000000000000000000000003"))===null),Ae(Buffer.from(e.privateAdd(se("e211078564db65c3ce7704f08262b1f38f1ef412ad15b5ac2d76657a63b2c500"),se("b51fbb69051255d1becbd683de5848242a89c229348dd72896a87ada94ae8665"))).equals(se("9730c2ee69edbb958d42db7460bafa18fef9d955325aec99044c81c8282b0a24"))),Ae(Buffer.from(e.privateNegate(se("0000000000000000000000000000000000000000000000000000000000000001"))).equals(se("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"))),Ae(Buffer.from(e.privateNegate(se("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036413e"))).equals(se("0000000000000000000000000000000000000000000000000000000000000003"))),Ae(Buffer.from(e.privateNegate(se("b1121e4088a66a28f5b6b0f5844943ecd9f610196d7bb83b25214b60452c09af"))).equals(se("4eede1bf775995d70a494f0a7bb6bc11e0b8cccd41cce8009ab1132c8b0a3792"))),Ae(Buffer.from(e.pointCompress(se("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),!0)).equals(se("0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),Ae(Buffer.from(e.pointCompress(se("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),!1)).equals(se("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"))),Ae(Buffer.from(e.pointCompress(se("0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),!0)).equals(se("0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),Ae(Buffer.from(e.pointCompress(se("0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),!1)).equals(se("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"))),Ae(Buffer.from(e.pointFromScalar(se("b1121e4088a66a28f5b6b0f5844943ecd9f610196d7bb83b25214b60452c09af"))).equals(se("02b07ba9dca9523b7ef4bd97703d43d20399eb698e194704791a25ce77a400df99"))),Ae(e.xOnlyPointAddTweak(se("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),se("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"))===null);let t=e.xOnlyPointAddTweak(se("1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b"),se("a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac"));Ae(Buffer.from(t.xOnlyPubkey).equals(se("e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"))&&t.parity===1),t=e.xOnlyPointAddTweak(se("2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991"),se("823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47")),Ae(Buffer.from(t.xOnlyPubkey).equals(se("9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"))&&t.parity===0),Ae(Buffer.from(e.sign(se("5e9f0a0d593efdcf78ac923bc3313e4e7d408d574354ee2b3288c0da9fbba6ed"),se("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"))).equals(se("54c4a33c6423d689378f160a7ff8b61330444abb58fb470f96ea16d99d4a2fed07082304410efa6b2943111b6a4e0aaa7b7db55a07e9861d1fb3cb1f421044a5"))),Ae(e.verify(se("5e9f0a0d593efdcf78ac923bc3313e4e7d408d574354ee2b3288c0da9fbba6ed"),se("0379be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),se("54c4a33c6423d689378f160a7ff8b61330444abb58fb470f96ea16d99d4a2fed07082304410efa6b2943111b6a4e0aaa7b7db55a07e9861d1fb3cb1f421044a5"))),e.signSchnorr&&Ae(Buffer.from(e.signSchnorr(se("7e2d58d8b3bcdf1abadec7829054f90dda9805aab56c77333024b9d0a508b75c"),se("c90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b14e5c9"),se("c87aa53824b4d7ae2eb035a2b5bbbccc080e76cdc6d1692c4b0b62d798e6d906"))).equals(se("5831aaeed7b44bb74e5eab94ba9d4294c49bcf2a60728d8b4c200f50dd313c1bab745879a5ad954a72c45a91c3a51d3c7adea98d82f8481e0e1e03674a6f3fb7"))),e.verifySchnorr&&Ae(e.verifySchnorr(se("7e2d58d8b3bcdf1abadec7829054f90dda9805aab56c77333024b9d0a508b75c"),se("dd308afec5777e13121fa72b9cc1b7cc0139715309b086c960e18fd969774eb8"),se("5831aaeed7b44bb74e5eab94ba9d4294c49bcf2a60728d8b4c200f50dd313c1bab745879a5ad954a72c45a91c3a51d3c7adea98d82f8481e0e1e03674a6f3fb7")))}xs.testEcc=Mx;function Ae(e){if(!e)throw new Error("ecc library invalid")}Object.defineProperty(Tn,"__esModule",{value:!0});Tn.ECPairFactory=Tn.networks=void 0;const qc=In;Tn.networks=qc;const it=Hp,Hx=vv,fd=Lx,Dx=xs,ec=it.typeforce.maybe(it.typeforce.compile({compressed:it.maybe(it.Boolean),network:it.maybe(it.Network)})),jx=e=>e.length===32?e:e.slice(1,33);function qx(e){(0,Dx.testEcc)(e);function t(a){return e.isPoint(a)}function r(a,c){if(it.typeforce(it.Buffer256bit,a),!e.isPrivate(a))throw new TypeError("Private key not in range [1, n)");return it.typeforce(ec,c),new s(a,void 0,c)}function n(a,c){return it.typeforce(e.isPoint,a),it.typeforce(ec,c),new s(void 0,a,c)}function i(a,c){const u=fd.decode(a),l=u.version;if(it.Array(c)){if(c=c.filter(h=>l===h.wif).pop(),!c)throw new Error("Unknown network version")}else if(c=c||qc.bitcoin,l!==c.wif)throw new Error("Invalid network version");return r(u.privateKey,{compressed:u.compressed,network:c})}function o(a){it.typeforce(ec,a),a===void 0&&(a={});const c=a.rng||Hx;let u;do u=c(32),it.typeforce(it.Buffer256bit,u);while(!e.isPrivate(u));return r(u,a)}class s{constructor(c,u,l){tn(this,"__D");tn(this,"__Q");tn(this,"compressed");tn(this,"network");tn(this,"lowR");this.__D=c,this.__Q=u,this.lowR=!1,l===void 0&&(l={}),this.compressed=l.compressed===void 0?!0:l.compressed,this.network=l.network||qc.bitcoin,u!==void 0&&(this.__Q=Buffer.from(e.pointCompress(u,this.compressed)))}get privateKey(){return this.__D}get publicKey(){if(!this.__Q){const c=e.pointFromScalar(this.__D,this.compressed);this.__Q=Buffer.from(c)}return this.__Q}toWIF(){if(!this.__D)throw new Error("Missing private key");return fd.encode(this.network.wif,this.__D,this.compressed)}tweak(c){return this.privateKey?this.tweakFromPrivateKey(c):this.tweakFromPublicKey(c)}sign(c,u){if(!this.__D)throw new Error("Missing private key");if(u===void 0&&(u=this.lowR),u===!1)return Buffer.from(e.sign(c,this.__D));{let l=e.sign(c,this.__D);const h=Buffer.alloc(32,0);let y=0;for(;l[0]>127;)y++,h.writeUIntLE(y,0,6),l=e.sign(c,this.__D,h);return Buffer.from(l)}}signSchnorr(c){if(!this.privateKey)throw new Error("Missing private key");if(!e.signSchnorr)throw new Error("signSchnorr not supported by ecc library");return Buffer.from(e.signSchnorr(c,this.privateKey))}verify(c,u){return e.verify(c,this.publicKey,u)}verifySchnorr(c,u){if(!e.verifySchnorr)throw new Error("verifySchnorr not supported by ecc library");return e.verifySchnorr(c,this.publicKey.subarray(1,33),u)}tweakFromPublicKey(c){const u=jx(this.publicKey),l=e.xOnlyPointAddTweak(u,c);if(!l||l.xOnlyPubkey===null)throw new Error("Cannot tweak public key!");const h=Buffer.from([l.parity===0?2:3]);return n(Buffer.concat([h,l.xOnlyPubkey]),{network:this.network,compressed:this.compressed})}tweakFromPrivateKey(c){const l=this.publicKey[0]===3||this.publicKey[0]===4&&(this.publicKey[64]&1)===1?e.privateNegate(this.privateKey):this.privateKey,h=e.privateAdd(l,c);if(!h)throw new Error("Invalid tweaked private key!");return r(Buffer.from(h),{network:this.network,compressed:this.compressed})}}return{isPoint:t,fromPrivateKey:r,fromPublicKey:n,fromWIF:i,makeRandom:o}}Tn.ECPairFactory=qx;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.networks=e.ECPairFactory=e.default=void 0;var t=Tn;Object.defineProperty(e,"default",{enumerable:!0,get:function(){return t.ECPairFactory}}),Object.defineProperty(e,"ECPairFactory",{enumerable:!0,get:function(){return t.ECPairFactory}}),Object.defineProperty(e,"networks",{enumerable:!0,get:function(){return t.networks}})})(Mp);const Gx=hw(Mp);class Hi extends J.EventBroker{get isInitialized(){return!!this.digestKey}constructor(t,r){super(),this.digestKey=t,this.walletClient=r}static fromDigestKey(t){return new Hi(U.trim0x(t))}static fromWalletClient(t){return new Hi(void 0,t)}async initialize(){if(this.digestKey)return U.Ok("Already initialized");const t=await this.deriveDigestKeyFromWalletClient();return t.error?U.Err(t.error):(this.emit("initialized",!0),U.Ok("Initialized"))}async deriveDigestKeyFromWalletClient(){if(!this.walletClient)return U.Err("No walletClient found");if(!this.walletClient.account)return U.Err("No account found");try{const t=await this.walletClient.signTypedData({account:this.walletClient.account,types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"}],Data:[{name:"Message",type:"string"},{name:"Version",type:"string"},{name:"Nonce",type:"uint256"}]},domain:{name:"GARDEN FINANCE",version:"1"},primaryType:"Data",message:{Message:"Initialize your account",Version:"1.0.2",Nonce:1n}});return this.digestKey=U.trim0x(ii(t)),this.emit("initialized",!0),U.Ok(this.digestKey)}catch(t){return U.Err("Failed to initialize: "+t)}}async getDigestKey(){if(!this.digestKey&&!this.walletClient)return U.Err("No private key or wallet client found");if(!this.digestKey&&this.walletClient){const t=await this.deriveDigestKeyFromWalletClient();if(t.error)return U.Err(t.error)}return this.digestKey?U.Ok(this.digestKey):U.Err("No private key found")}async generateSecret(t){const r=await this.signMessage(t);if(r.error)return U.Err(r.error);const n=ii(J.with0x(r.val)),i=ii(n);return U.Ok({secret:n,secretHash:i})}async signMessage(t){if(!this.digestKey){const u=await this.getDigestKey();if(u.error)return U.Err(u.error);this.digestKey=u.val}const r=Gx(Gr),n="Garden.fi"+t.toString(),i=Buffer.from(n,"utf8"),o=ii(i),s=Buffer.from(U.trim0x(this.digestKey),"hex");if(s.length!==32)return U.Err("Invalid private key length. Expected 32 bytes.");const c=r.fromPrivateKey(s).sign(Buffer.from(U.trim0x(o),"hex"));return U.Ok(c.toString("hex"))}}const ld=[{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"}],zx={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},Vx={block:Kb({format(e){var r;return{transactions:(r=e.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const i=cu(n);return i.typeHex==="0x7e"&&(i.isSystemTx=n.isSystemTx,i.mint=n.mint?yt(n.mint):void 0,i.sourceHash=n.sourceHash,i.type="deposit"),i}),stateRoot:e.stateRoot}}}),transaction:Vb({format(e){const t={};return e.type==="0x7e"&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?yt(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:Yg({format(e){return{l1GasPrice:e.l1GasPrice?yt(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?yt(e.l1GasUsed):null,l1Fee:e.l1Fee?yt(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null}}})};function Wx(e,t){return Xx(e)?Yx(e):v1(e,t)}const Kx={transaction:Wx};function Yx(e){Jx(e);const{sourceHash:t,data:r,from:n,gas:i,isSystemTx:o,mint:s,to:a,value:c}=e,u=[t,n,a??"0x",s?qt(s):"0x",c?qt(c):"0x",i?qt(i):"0x",o?"0x1":"0x",r??"0x"];return Wt(["0x7e",Or(u)])}function Xx(e){return e.type==="deposit"||typeof e.sourceHash<"u"}function Jx(e){const{from:t,to:r}=e;if(t&&!Me(t))throw new ct({address:t});if(r&&!Me(r))throw new ct({address:r})}const kn={blockTime:2e3,contracts:zx,formatters:Vx,serializers:Kx},Qx=At({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),Zx=At({id:421614,name:"Arbitrum Sepolia",nativeCurrency:{name:"Arbitrum Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://sepolia.arbiscan.io",apiUrl:"https://api-sepolia.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:81930}},testnet:!0}),ri=1,e6=At({...kn,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:{...kn.contracts,disputeGameFactory:{[ri]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[ri]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[ri]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[ri]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:ri}),ni=11155111,t6=At({...kn,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:{...kn.contracts,disputeGameFactory:{[ni]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[ni]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[ni]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[ni]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:ni}),r6=At({id:80094,name:"Berachain",nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},ensRegistry:{address:"0x5b22280886a2f5e09a49bea7e320eab0e5320e28",blockCreated:877007},ensUniversalResolver:{address:"0xddfb18888a9466688235887dec2a10c4f5effee9",blockCreated:877008}},rpcUrls:{default:{http:["https://rpc.berachain.com"]}},blockExplorers:{default:{name:"Berascan",url:"https://berascan.com"}},ensTlds:[".bera"],testnet:!1}),n6=At({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}),i6=At({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}),o6=1,s6=At({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:o6}),a6=At({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xce01f8eee7E479C928F8919abD53E553a36CeF67",blockCreated:19258213},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),c6=At({id:10143,name:"Monad Testnet",nativeCurrency:{name:"Testnet MON Token",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://testnet-rpc.monad.xyz"]}},blockExplorers:{default:{name:"Monad Testnet explorer",url:"https://testnet.monadexplorer.com"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:251449}},testnet:!0}),u6=At({id:11155111,name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.drpc.org"]}},blockExplorers:{default:{name:"Etherscan",url:"https://sepolia.etherscan.io",apiUrl:"https://api-sepolia.etherscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:751532},ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xc8Af999e38273D658BE1b921b88A9Ddf005769cC",blockCreated:5317080}},testnet:!0}),vo=1,f6=At({...kn,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:{...kn.contracts,multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:0},disputeGameFactory:{[vo]:{address:"0x2F12d621a16e2d3285929C9996f478508951dFe4"}},portal:{[vo]:{address:"0x0bd48f6B86a26D3a217d0Fa6FfE2B491B956A7a2"}},l1StandardBridge:{[vo]:{address:"0x81014F44b0a345033bB2b3B21C7a1A308B35fEeA"}}},sourceId:vo}),l6={...u6,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},C0={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/"]}}},F0={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"]}}},U0={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"]}}},N0={ethereum:a6,arbitrum:Qx,ethereum_sepolia:l6,arbitrum_sepolia:Zx,ethereum_localnet:me.EthereumLocalnet,arbitrum_localnet:me.ArbitrumLocalnet,base_sepolia:t6,base:e6,bera_testnet:n6,citrea_testnet:i6,bera:r6,monad_testnet:c6,hyperliquid_testnet:F0,hyperliquid:U0,unichain:f6,corn:s6,botanix:C0},$0=async(e,t)=>{var i,o,s;const r=N0[e],n=await t.getChainId();if(r)try{if(r.id===n)return U.Ok({message:"Already on the network",walletClient:t});await t.switchChain({id:r.id});const a=Ns({account:t.account,chain:r,transport:bf(t.transport)});return U.Ok({message:"Switched chain",walletClient:a})}catch(a){if(d6(a))if(a.code===4902)try{await t.addChain({chain:r});const c=Ns({account:t.account,chain:r,transport:bf(t.transport)});return U.Ok({message:"Added network",walletClient:c})}catch{return U.Err("Failed to add network")}else if((o=(i=a.body)==null?void 0:i.method)!=null&&o.includes("wallet_switchEthereumChain")||(s=a.message)!=null&&s.includes("wallet_switchEthereumChain")){const c=Ns({account:t.account,chain:r,transport:c1()});return U.Ok({message:"Added network",walletClient:c})}else return U.Err("Failed to switch network");else return U.Err("Failed to switch network")}else return U.Err("Chain not supported")},d6=e=>typeof e=="object"&&e!=null&&("code"in e||"message"in e||"body"in e),h6=[{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 L0{constructor(t,r,n){this.url=new J.Url("/relayer",t),this.auth=n,this.wallet=r}get htlcActorAddress(){if(!this.wallet.account)throw new Error("No account found");return this.wallet.account.address}async initiate(t){if(!this.wallet.account)return J.Err("No account found");if(this.wallet.account.address.toLowerCase()!==t.source_swap.initiator.toLowerCase())return J.Err("Account address and order initiator mismatch");if(!me.isEVM(t.source_swap.chain))return J.Err("Source chain is not an EVM chain");const r=await $0(t.source_swap.chain,this.wallet);if(r.error)return J.Err(r.error);if(this.wallet=r.val.walletClient,!this.wallet.account)return J.Err("No account found");const{create_order:n,source_swap:i}=t;if(!i.amount||!i.redeemer||!n.timelock||!n.secret_hash)return J.Err("Invalid order");const o=J.with0x(n.secret_hash),s=BigInt(n.timelock),a=J.with0x(i.redeemer),c=BigInt(i.amount),u=await this.getTokenAddress(t.source_swap.asset);return u.ok?me.isEvmNativeToken(t.source_swap.chain,u.val)?this._initiateOnNativeHTLC(o,s,c,a,t.source_swap.asset):this._initiateOnErc20HTLC(o,s,c,a,t.source_swap.asset,u.val,n.create_id):J.Err(u.error)}async getTokenAddress(t){try{const n=await Fs({address:J.with0x(t),abi:ld,client:this.wallet}).read.token();return J.Ok(n)}catch(r){return J.Err("Failed to get token address",String(r))}}async _initiateOnNativeHTLC(t,r,n,i,o){if(!this.wallet.account)return J.Err("No account found");try{const a=await Fs({address:J.with0x(o),abi:h6,client:this.wallet}).write.initiate([i,r,n,t],{account:this.wallet.account,chain:this.wallet.chain,value:n});return J.Ok(a)}catch(s){return J.Err("Failed to initiate on native HTLC",String(s))}}async _initiateOnErc20HTLC(t,r,n,i,o,s,a){if(!this.wallet.account)return J.Err("No account found");try{const c=await this.auth.getAuthHeaders();if(c.error)return J.Err(c.error);const u=Fs({address:J.with0x(o),abi:ld,client:this.wallet}),l=await J.checkAllowanceAndApprove(Number(n),s,o,this.wallet);if(l.error)return J.Err(l.error);const h=await u.read.eip712Domain(),y=await this.wallet.signTypedData({account:this.wallet.account,domain:{name:h[1],version:h[2],chainId:Number(h[3]),verifyingContract:h[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:i,timelock:r,amount:n,secretHash:t}}),p={...c.val,"Content-Type":"application/json"},b=await U.Fetcher.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:a,signature:y,perform_on:"Source"}),headers:p});return b.error?J.Err(b.error):b.result?J.Ok(b.result):J.Err("Init: No result found")}catch(c){return console.log("init error :",c),J.Err(String(c))}}async redeem(t,r){try{const n=await this.auth.getAuthHeaders();if(n.error)return J.Err(n.error);const i=await U.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:U.trim0x(r),perform_on:"Destination"}),headers:{...n.val,"Content-Type":"application/json"}});return i.error?J.Err(i.error):i.result?J.Ok(i.result):J.Err("Redeem: No result found")}catch(n){return J.Err(String(n))}}async refund(){return J.Err("Refund not supported")}}const M0=[{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"}]}],p6=async(e,t,r,n,i)=>{try{const o=await Gc(e.address,t,r,i);if(o.error)return U.Err(o.error);if(o.val>=n)return U.Ok("Allowance already approved");const a=Le.cairo.uint256(BigInt(n)),c=await e.execute([{contractAddress:U.with0x(t),entrypoint:"approve",calldata:[U.with0x(r),a.low,a.high]}]);await i.waitForTransaction(c.transaction_hash,{retryInterval:3e3,successStates:[Le.TransactionExecutionStatus.SUCCEEDED]}),await J.sleep(2e3);for(let u=0;u<20;u++){const l=await Gc(e.address,t,r,i);if(l.error)return U.Err(l.error);if(l.val>=n)return U.Ok(c.transaction_hash);await J.sleep(2e3)}return U.Err("Allowance not approved after transaction.")}catch(o){return U.Err(`Failed to check or approve allowance: ${o instanceof Error?o.message:String(o)}`)}},Gc=async(e,t,r,n)=>{try{const o=await new Le.Contract(M0,U.with0x(t),n).call("allowance",[U.with0x(e),U.with0x(r)]);return U.Ok(BigInt((o==null?void 0:o.toString())||"0"))}catch(i){return U.Err(`Failed to check allowance: ${i instanceof Error?i.message:String(i)}`)}},y6=async(e,t,r,n,i)=>{const o=await Gc(e,t,r,n);return o.error?U.Err(o.error):U.Ok(o.val>=i)},H0=[{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"}]}],m6={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 D0{constructor(t,r,n,i){this.url=t instanceof J.Url?t:new J.Url(t),this.account=r,this.starknetProvider=new Le.RpcProvider({nodeUrl:i||Ui[n].nodeUrl}),this.chainId=Ui[n].chainId}get htlcActorAddress(){if(!this.account.address)throw new Error("No account found");return this.account.address}async initiate(t){if(!this.account.address)return U.Err("No account address");const{create_order:r,source_swap:n}=t,{redeemer:i,amount:o}=n;if(!o||!i||!r.secret_hash||!r.timelock)return U.Err("Invalid order");try{const s=new Le.Contract(H0,t.source_swap.asset,this.account),a=await(s==null?void 0:s.token()),c=Le.num.toHex(a),u=await y6(this.account.address,c,n.asset,this.starknetProvider,BigInt(o));return u.error?U.Err(u.error):u.val?this.initiateRelay(t):this.approveAndInitiate(c,t)}catch(s){return U.Err(String(s))}}async approveAndInitiate(t,r){const{create_order:n,source_swap:i}=r,{redeemer:o,amount:s}=i,{secret_hash:a,timelock:c}=n,u=i.asset;try{const l=Le.cairo.uint256(BigInt(s)),h={contractAddress:U.with0x(t),entrypoint:"approve",calldata:[u,l.low,l.high]},y=Le.cairo.uint256(s),p={contractAddress:U.with0x(u),entrypoint:"initiate",calldata:[o,c.toString(),y.low.toString(),y.high.toString(),...J.hexToU32Array(a)]},b=await this.account.execute([h,p]);return await this.starknetProvider.waitForTransaction(b.transaction_hash,{retryInterval:2e3,successStates:[Le.TransactionExecutionStatus.SUCCEEDED]}),U.Ok(b.transaction_hash)}catch(l){return U.Err(`Failed to approve and initiate: ${String(l)}`)}}async initiateRelay(t){const{create_order:r,source_swap:n}=t,{redeemer:i,amount:o}=n,a={domain:{name:"HTLC",version:Le.shortString.encodeShortString("1"),chainId:this.chainId,revision:Le.TypedDataRevision.ACTIVE},primaryType:"Initiate",types:m6,message:{redeemer:i,amount:Le.cairo.uint256(o),timelock:r.timelock,secretHash:J.hexToU32Array(r.secret_hash)}};try{const c=await this.account.signMessage(a),u=ow(c);if(u.error)return U.Err(u.error);const l=await U.Fetcher.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:r.create_id,signature:u.val,perform_on:"Source"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return l.error?U.Err(l.error):l.result?U.Ok(l.result):U.Err("Init: No result found")}catch(c){return U.Err(`Failed to initiate relayer: ${String(c)}`)}}async redeem(t,r){try{const n=await U.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:r,perform_on:"Destination"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return n.error?U.Err(n.error):n.result?U.Ok(n.result):U.Err("Redeem: No result found")}catch(n){return U.Err(String(n))}}async refund(){return U.Err("Refund is taken care of by the relayer")}}const b6="2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",g6={name:"solana_native_swaps",version:"0.3.0",spec:"0.1.0",description:"Created with Anchor"},w6=[{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:[]}],v6=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],_6=[{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]}],E6=[{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"}],x6=[{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]}}]}}],zc={address:b6,metadata:g6,instructions:w6,accounts:v6,events:_6,errors:E6,types:x6};var nr={},On={};Object.defineProperty(On,"__esModule",{value:!0});On.decode=On.encode=void 0;const dd=Bt;function A6(e){return e.reduce((t,r)=>t+r.toString(16).padStart(2,"0"),"0x")}On.encode=A6;function S6(e){e.indexOf("0x")===0&&(e=e.substr(2)),e.length%2===1&&(e="0"+e);let t=e.match(/.{2}/g);return t===null?dd.Buffer.from([]):dd.Buffer.from(t.map(r=>parseInt(r,16)))}On.decode=S6;var Rn={},Tr={},tc;Object.defineProperty(Tr,"__esModule",{value:!0});Tr.isVersionedTransaction=Tr.chunks=Tr.isBrowser=void 0;Tr.isBrowser=process.env.ANCHOR_BROWSER||typeof window<"u"&&!(!((tc=window.process)===null||tc===void 0)&&tc.hasOwnProperty("type"));function P6(e,t){return Array.apply(0,new Array(Math.ceil(e.length/t))).map((r,n)=>e.slice(n*t,(n+1)*t))}Tr.chunks=P6;const T6=e=>"version"in e;Tr.isVersionedTransaction=T6;var rc={},nc={},ic,hd;function I6(){if(hd)return ic;hd=1;var e=gs()(),t=jn(),r=t("Object.prototype.toString"),n=function(a){return e&&a&&typeof a=="object"&&Symbol.toStringTag in a?!1:r(a)==="[object Arguments]"},i=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]"},o=function(){return n(arguments)}();return n.isLegacyArguments=i,ic=o?n:i,ic}var oc,pd;function B6(){if(pd)return oc;pd=1;var e=jn(),t=gs()(),r=g0(),n=Dn(),i;if(t){var o=e("RegExp.prototype.exec"),s={},a=function(){throw s},c={toString:a,valueOf:a};typeof Symbol.toPrimitive=="symbol"&&(c[Symbol.toPrimitive]=a),i=function(y){if(!y||typeof y!="object")return!1;var p=n(y,"lastIndex"),b=p&&r(p,"value");if(!b)return!1;try{o(y,c)}catch(v){return v===s}}}else{var u=e("Object.prototype.toString"),l="[object RegExp]";i=function(y){return!y||typeof y!="object"&&typeof y!="function"?!1:u(y)===l}}return oc=i,oc}var sc,yd;function k6(){if(yd)return sc;yd=1;var e=jn(),t=B6(),r=e("RegExp.prototype.exec"),n=Hn();return sc=function(o){if(!t(o))throw new n("`regex` must be a RegExp");return function(a){return r(o,a)!==null}},sc}var ac,md;function O6(){if(md)return ac;md=1;var e=jn(),t=k6(),r=t(/^\s*(?:function)?\*/),n=gs()(),i=Du(),o=e("Object.prototype.toString"),s=e("Function.prototype.toString"),a=function(){if(!n)return!1;try{return Function("return function*() {}")()}catch{}},c;return ac=function(l){if(typeof l!="function")return!1;if(r(s(l)))return!0;if(!n){var h=o(l);return h==="[object GeneratorFunction]"}if(!i)return!1;if(typeof c>"u"){var y=a();c=y?i(y):!1}return i(l)===c},ac}var bd;function R6(){return bd||(bd=1,function(e){var t=I6(),r=O6(),n=v0(),i=_0();function o(j){return j.call.bind(j)}var s=typeof BigInt<"u",a=typeof Symbol<"u",c=o(Object.prototype.toString),u=o(Number.prototype.valueOf),l=o(String.prototype.valueOf),h=o(Boolean.prototype.valueOf);if(s)var y=o(BigInt.prototype.valueOf);if(a)var p=o(Symbol.prototype.valueOf);function b(j,pt){if(typeof j!="object")return!1;try{return pt(j),!0}catch{return!1}}e.isArgumentsObject=t,e.isGeneratorFunction=r,e.isTypedArray=i;function v(j){return typeof Promise<"u"&&j instanceof Promise||j!==null&&typeof j=="object"&&typeof j.then=="function"&&typeof j.catch=="function"}e.isPromise=v;function E(j){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(j):i(j)||N(j)}e.isArrayBufferView=E;function S(j){return n(j)==="Uint8Array"}e.isUint8Array=S;function P(j){return n(j)==="Uint8ClampedArray"}e.isUint8ClampedArray=P;function A(j){return n(j)==="Uint16Array"}e.isUint16Array=A;function w(j){return n(j)==="Uint32Array"}e.isUint32Array=w;function B(j){return n(j)==="Int8Array"}e.isInt8Array=B;function T(j){return n(j)==="Int16Array"}e.isInt16Array=T;function L(j){return n(j)==="Int32Array"}e.isInt32Array=L;function D(j){return n(j)==="Float32Array"}e.isFloat32Array=D;function C(j){return n(j)==="Float64Array"}e.isFloat64Array=C;function X(j){return n(j)==="BigInt64Array"}e.isBigInt64Array=X;function Z(j){return n(j)==="BigUint64Array"}e.isBigUint64Array=Z;function oe(j){return c(j)==="[object Map]"}oe.working=typeof Map<"u"&&oe(new Map);function te(j){return typeof Map>"u"?!1:oe.working?oe(j):j instanceof Map}e.isMap=te;function ee(j){return c(j)==="[object Set]"}ee.working=typeof Set<"u"&&ee(new Set);function ae(j){return typeof Set>"u"?!1:ee.working?ee(j):j instanceof Set}e.isSet=ae;function be(j){return c(j)==="[object WeakMap]"}be.working=typeof WeakMap<"u"&&be(new WeakMap);function ye(j){return typeof WeakMap>"u"?!1:be.working?be(j):j instanceof WeakMap}e.isWeakMap=ye;function ce(j){return c(j)==="[object WeakSet]"}ce.working=typeof WeakSet<"u"&&ce(new WeakSet);function F(j){return ce(j)}e.isWeakSet=F;function Y(j){return c(j)==="[object ArrayBuffer]"}Y.working=typeof ArrayBuffer<"u"&&Y(new ArrayBuffer);function re(j){return typeof ArrayBuffer>"u"?!1:Y.working?Y(j):j instanceof ArrayBuffer}e.isArrayBuffer=re;function O(j){return c(j)==="[object DataView]"}O.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&O(new DataView(new ArrayBuffer(1),0,1));function N(j){return typeof DataView>"u"?!1:O.working?O(j):j instanceof DataView}e.isDataView=N;var q=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function ne(j){return c(j)==="[object SharedArrayBuffer]"}function I(j){return typeof q>"u"?!1:(typeof ne.working>"u"&&(ne.working=ne(new q)),ne.working?ne(j):j instanceof q)}e.isSharedArrayBuffer=I;function k(j){return c(j)==="[object AsyncFunction]"}e.isAsyncFunction=k;function M(j){return c(j)==="[object Map Iterator]"}e.isMapIterator=M;function V(j){return c(j)==="[object Set Iterator]"}e.isSetIterator=V;function W(j){return c(j)==="[object Generator]"}e.isGeneratorObject=W;function g(j){return c(j)==="[object WebAssembly.Module]"}e.isWebAssemblyCompiledModule=g;function _(j){return b(j,u)}e.isNumberObject=_;function H(j){return b(j,l)}e.isStringObject=H;function K(j){return b(j,h)}e.isBooleanObject=K;function de(j){return s&&b(j,y)}e.isBigIntObject=de;function ie(j){return a&&b(j,p)}e.isSymbolObject=ie;function fe(j){return _(j)||H(j)||K(j)||de(j)||ie(j)}e.isBoxedPrimitive=fe;function ut(j){return typeof Uint8Array<"u"&&(re(j)||I(j))}e.isAnyArrayBuffer=ut,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(j){Object.defineProperty(e,j,{enumerable:!1,value:function(){throw new Error(j+" is not supported in userland")}})})}(nc)),nc}var cc,gd;function C6(){return gd||(gd=1,cc=function(t){return t&&typeof t=="object"&&typeof t.copy=="function"&&typeof t.fill=="function"&&typeof t.readUInt8=="function"}),cc}var wd;function j0(){return wd||(wd=1,function(e){var t=Object.getOwnPropertyDescriptors||function(N){for(var q=Object.keys(N),ne={},I=0;I<q.length;I++)ne[q[I]]=Object.getOwnPropertyDescriptor(N,q[I]);return ne},r=/%[sdj%]/g;e.format=function(O){if(!B(O)){for(var N=[],q=0;q<arguments.length;q++)N.push(s(arguments[q]));return N.join(" ")}for(var q=1,ne=arguments,I=ne.length,k=String(O).replace(r,function(V){if(V==="%%")return"%";if(q>=I)return V;switch(V){case"%s":return String(ne[q++]);case"%d":return Number(ne[q++]);case"%j":try{return JSON.stringify(ne[q++])}catch{return"[Circular]"}default:return V}}),M=ne[q];q<I;M=ne[++q])P(M)||!C(M)?k+=" "+M:k+=" "+s(M);return k},e.deprecate=function(O,N){if(typeof process<"u"&&process.noDeprecation===!0)return O;if(typeof process>"u")return function(){return e.deprecate(O,N).apply(this,arguments)};var q=!1;function ne(){if(!q){if(process.throwDeprecation)throw new Error(N);process.traceDeprecation?console.trace(N):console.error(N),q=!0}return O.apply(this,arguments)}return ne};var n={},i=/^$/;if(process.env.NODE_DEBUG){var o=process.env.NODE_DEBUG;o=o.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),i=new RegExp("^"+o+"$","i")}e.debuglog=function(O){if(O=O.toUpperCase(),!n[O])if(i.test(O)){var N=process.pid;n[O]=function(){var q=e.format.apply(e,arguments);console.error("%s %d: %s",O,N,q)}}else n[O]=function(){};return n[O]};function s(O,N){var q={seen:[],stylize:c};return arguments.length>=3&&(q.depth=arguments[2]),arguments.length>=4&&(q.colors=arguments[3]),S(N)?q.showHidden=N:N&&e._extend(q,N),L(q.showHidden)&&(q.showHidden=!1),L(q.depth)&&(q.depth=2),L(q.colors)&&(q.colors=!1),L(q.customInspect)&&(q.customInspect=!0),q.colors&&(q.stylize=a),l(q,O,q.depth)}e.inspect=s,s.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]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function a(O,N){var q=s.styles[N];return q?"\x1B["+s.colors[q][0]+"m"+O+"\x1B["+s.colors[q][1]+"m":O}function c(O,N){return O}function u(O){var N={};return O.forEach(function(q,ne){N[q]=!0}),N}function l(O,N,q){if(O.customInspect&&N&&oe(N.inspect)&&N.inspect!==e.inspect&&!(N.constructor&&N.constructor.prototype===N)){var ne=N.inspect(q,O);return B(ne)||(ne=l(O,ne,q)),ne}var I=h(O,N);if(I)return I;var k=Object.keys(N),M=u(k);if(O.showHidden&&(k=Object.getOwnPropertyNames(N)),Z(N)&&(k.indexOf("message")>=0||k.indexOf("description")>=0))return y(N);if(k.length===0){if(oe(N)){var V=N.name?": "+N.name:"";return O.stylize("[Function"+V+"]","special")}if(D(N))return O.stylize(RegExp.prototype.toString.call(N),"regexp");if(X(N))return O.stylize(Date.prototype.toString.call(N),"date");if(Z(N))return y(N)}var W="",g=!1,_=["{","}"];if(E(N)&&(g=!0,_=["[","]"]),oe(N)){var H=N.name?": "+N.name:"";W=" [Function"+H+"]"}if(D(N)&&(W=" "+RegExp.prototype.toString.call(N)),X(N)&&(W=" "+Date.prototype.toUTCString.call(N)),Z(N)&&(W=" "+y(N)),k.length===0&&(!g||N.length==0))return _[0]+W+_[1];if(q<0)return D(N)?O.stylize(RegExp.prototype.toString.call(N),"regexp"):O.stylize("[Object]","special");O.seen.push(N);var K;return g?K=p(O,N,q,M,k):K=k.map(function(de){return b(O,N,q,M,de,g)}),O.seen.pop(),v(K,W,_)}function h(O,N){if(L(N))return O.stylize("undefined","undefined");if(B(N)){var q="'"+JSON.stringify(N).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return O.stylize(q,"string")}if(w(N))return O.stylize(""+N,"number");if(S(N))return O.stylize(""+N,"boolean");if(P(N))return O.stylize("null","null")}function y(O){return"["+Error.prototype.toString.call(O)+"]"}function p(O,N,q,ne,I){for(var k=[],M=0,V=N.length;M<V;++M)ce(N,String(M))?k.push(b(O,N,q,ne,String(M),!0)):k.push("");return I.forEach(function(W){W.match(/^\d+$/)||k.push(b(O,N,q,ne,W,!0))}),k}function b(O,N,q,ne,I,k){var M,V,W;if(W=Object.getOwnPropertyDescriptor(N,I)||{value:N[I]},W.get?W.set?V=O.stylize("[Getter/Setter]","special"):V=O.stylize("[Getter]","special"):W.set&&(V=O.stylize("[Setter]","special")),ce(ne,I)||(M="["+I+"]"),V||(O.seen.indexOf(W.value)<0?(P(q)?V=l(O,W.value,null):V=l(O,W.value,q-1),V.indexOf(`
73
+ `)>-1&&(k?V=V.split(`
74
+ `).map(function(g){return" "+g}).join(`
75
+ `).slice(2):V=`
76
+ `+V.split(`
77
+ `).map(function(g){return" "+g}).join(`
78
+ `))):V=O.stylize("[Circular]","special")),L(M)){if(k&&I.match(/^\d+$/))return V;M=JSON.stringify(""+I),M.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(M=M.slice(1,-1),M=O.stylize(M,"name")):(M=M.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),M=O.stylize(M,"string"))}return M+": "+V}function v(O,N,q){var ne=O.reduce(function(I,k){return k.indexOf(`
79
+ `)>=0,I+k.replace(/\u001b\[\d\d?m/g,"").length+1},0);return ne>60?q[0]+(N===""?"":N+`
80
+ `)+" "+O.join(`,
81
+ `)+" "+q[1]:q[0]+N+" "+O.join(", ")+" "+q[1]}e.types=R6();function E(O){return Array.isArray(O)}e.isArray=E;function S(O){return typeof O=="boolean"}e.isBoolean=S;function P(O){return O===null}e.isNull=P;function A(O){return O==null}e.isNullOrUndefined=A;function w(O){return typeof O=="number"}e.isNumber=w;function B(O){return typeof O=="string"}e.isString=B;function T(O){return typeof O=="symbol"}e.isSymbol=T;function L(O){return O===void 0}e.isUndefined=L;function D(O){return C(O)&&ee(O)==="[object RegExp]"}e.isRegExp=D,e.types.isRegExp=D;function C(O){return typeof O=="object"&&O!==null}e.isObject=C;function X(O){return C(O)&&ee(O)==="[object Date]"}e.isDate=X,e.types.isDate=X;function Z(O){return C(O)&&(ee(O)==="[object Error]"||O instanceof Error)}e.isError=Z,e.types.isNativeError=Z;function oe(O){return typeof O=="function"}e.isFunction=oe;function te(O){return O===null||typeof O=="boolean"||typeof O=="number"||typeof O=="string"||typeof O=="symbol"||typeof O>"u"}e.isPrimitive=te,e.isBuffer=C6();function ee(O){return Object.prototype.toString.call(O)}function ae(O){return O<10?"0"+O.toString(10):O.toString(10)}var be=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ye(){var O=new Date,N=[ae(O.getHours()),ae(O.getMinutes()),ae(O.getSeconds())].join(":");return[O.getDate(),be[O.getMonth()],N].join(" ")}e.log=function(){console.log("%s - %s",ye(),e.format.apply(e,arguments))},e.inherits=je,e._extend=function(O,N){if(!N||!C(N))return O;for(var q=Object.keys(N),ne=q.length;ne--;)O[q[ne]]=N[q[ne]];return O};function ce(O,N){return Object.prototype.hasOwnProperty.call(O,N)}var F=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;e.promisify=function(N){if(typeof N!="function")throw new TypeError('The "original" argument must be of type Function');if(F&&N[F]){var q=N[F];if(typeof q!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(q,F,{value:q,enumerable:!1,writable:!1,configurable:!0}),q}function q(){for(var ne,I,k=new Promise(function(W,g){ne=W,I=g}),M=[],V=0;V<arguments.length;V++)M.push(arguments[V]);M.push(function(W,g){W?I(W):ne(g)});try{N.apply(this,M)}catch(W){I(W)}return k}return Object.setPrototypeOf(q,Object.getPrototypeOf(N)),F&&Object.defineProperty(q,F,{value:q,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(q,t(N))},e.promisify.custom=F;function Y(O,N){if(!O){var q=new Error("Promise was rejected with a falsy value");q.reason=O,O=q}return N(O)}function re(O){if(typeof O!="function")throw new TypeError('The "original" argument must be of type Function');function N(){for(var q=[],ne=0;ne<arguments.length;ne++)q.push(arguments[ne]);var I=q.pop();if(typeof I!="function")throw new TypeError("The last argument must be of type Function");var k=this,M=function(){return I.apply(k,arguments)};O.apply(this,q).then(function(V){process.nextTick(M.bind(null,null,V))},function(V){process.nextTick(Y.bind(null,V,M))})}return Object.setPrototypeOf(N,Object.getPrototypeOf(O)),Object.defineProperties(N,t(O)),N}e.callbackify=re}(rc)),rc}Object.defineProperty(Rn,"__esModule",{value:!0});Rn.encode=Rn.decode=void 0;const q0=Tr;function F6(e){return(q0.isBrowser?new TextDecoder("utf-8"):new(j0()).TextDecoder("utf-8")).decode(e)}Rn.decode=F6;function U6(e){return(q0.isBrowser?new TextEncoder:new(j0()).TextEncoder("utf-8")).encode(e)}Rn.encode=U6;var Cn={},N6=O0,$6="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",L6=N6($6),M6=De&&De.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Cn,"__esModule",{value:!0});Cn.decode=Cn.encode=void 0;const G0=M6(L6);function H6(e){return G0.default.encode(e)}Cn.encode=H6;function D6(e){return G0.default.decode(e)}Cn.decode=D6;var Fn={};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.decode=Fn.encode=void 0;const j6=Bt;function q6(e){return e.toString("base64")}Fn.encode=q6;function G6(e){return j6.Buffer.from(e,"base64")}Fn.decode=G6;var z6=De&&De.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),V6=De&&De.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),As=De&&De.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&z6(t,e,r);return V6(t,e),t};Object.defineProperty(nr,"__esModule",{value:!0});nr.base64=nr.bs58=nr.utf8=Lo=nr.hex=void 0;var Lo=nr.hex=As(On);nr.utf8=As(Rn);nr.bs58=As(Cn);nr.base64=As(Fn);class xr{constructor(t,r,n,i,o){try{this.swapId=[...Lo.decode(t)],this.secretHash=[...Lo.decode(n)]}catch(s){throw new Error("Error decoding swapId or secretHash",{cause:s})}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 It.web3.PublicKey(r)}catch(s){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:s})}try{this.amount=new It.BN(i.toString(10),10),this.expiresIn=new It.BN(o)}catch(s){throw new Error("Error decoding amount. Invalid value for amount",{cause:s})}if(!(Number.isInteger(o)&&o>0))throw new Error("expiresIn must be a positive integer.")}static from(t){let r;if(t.source_swap.chain.includes("solana"))r=t.source_swap;else if(t.destination_swap.chain.includes("solana"))r=t.destination_swap;else throw new Error("Expected source_swap or destination_swap to be one of 'solana', 'solana_localnet', 'solana_devnet'");const{swap_id:n,redeemer:i,secret_hash:o,timelock:s}=r,a=BigInt(r.amount);return new xr(n,i,o,a,s)}}function z0(e){let t;try{t=[...Lo.decode(e)]}catch(r){throw new Error("Error decoding secret. Ensure it is a hex string",{cause:r})}if(t.length!=32)throw new Error("Invalid Secret size. Expected 32 bytes, got "+t.length);return t}class V0{constructor(t,r,n,i){if(this.provider=t,this.url=r,!t)throw new Error("Provider is required");if(!r)throw new Error("Endpoint URL is required");if(!n)throw new Error("Relayer address is required");if(!i)throw new Error("Program address is required");try{this.relayer=new It.web3.PublicKey(n)}catch(s){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:s})}const o={...zc,metadata:{...zc.metadata??{}},address:i};try{this.program=new It.Program(o,this.provider)}catch(s){throw new Error("Error creating Program instance. Ensure the IDL and provider are correct.",{cause:s})}}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async sendViaRelayer(t,r){try{t.recentBlockhash=(await this.provider.connection.getLatestBlockhash()).blockhash,t.feePayer=this.relayer;const i=(await this.provider.wallet.signTransaction(t)).serialize({requireAllSignatures:!1}).toString("base64"),o={order_id:r,serialized_tx:i,perform_on:"source"},s=await U.Fetcher.post(this.url.endpoint("/spl-initiate"),{body:JSON.stringify(o),headers:{"Content-Type":"application/json"}});return s.error?U.Err(`Error from Relayer: ${s.error}`):s.result?U.Ok(s.result):U.Err("No result returned from relayer")}catch(n){return U.Err(`Failed to send transaction: ${n instanceof Error?n.message:String(n)}`)}}async initiateViaHTLC(t,r){if(!r)return U.Err("Order is required");try{const n=await this.provider.sendAndConfirm(t);return n?U.Ok(n):U.Err("Failed to initiate HTLC transaction")}catch(n){return U.Err(`Error initiating swap: ${n instanceof Error?n.message:String(n)}`)}}async initiate(t){const{redeemer:r,secretHash:n,amount:i,expiresIn:o}=xr.from(t),s=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=It.web3.PublicKey.findProgramAddressSync(s,this.program.programId)[0];try{const a=await this.program.methods.initiate(i,o,r,n).accounts({initiator:this.provider.publicKey}).transaction();return me.isSolanaNativeToken(t.source_swap.chain,t.source_swap.asset)?this.initiateViaHTLC(a,t):this.sendViaRelayer(a,t.create_order.create_id)}catch(a){return U.Err("Error initiating swap: ",a)}}async redeem(t,r){const{secretHash:n}=xr.from(t),i=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=It.web3.PublicKey.findProgramAddressSync(i,this.program.programId)[0];try{const o=z0(r),s={order_id:t.create_order.create_id,secret:Buffer.from(o).toString("hex"),perform_on:"destination"},a=await U.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify(s),headers:{"Content-Type":"application/json"}});return a.error?U.Err(`Error from Relayer: ${a.error}`):a.result?U.Ok(a.result):U.Err("Redeem: No result found")}catch(o){return U.Err("Error redeeming: ",o)}}async refund(){return U.Err("Refund is automatically handled by the relayer.")}}class ju extends J.EventBroker{constructor(t){super(),this.environment=J.Environment.TESTNET,this.getOrderThreshold=20,this.refundSacpCache=new Map,this.bitcoinRedeemCache=new yv;const{api:r,environment:n}=Bc(t.environment);if(this.environment=n,this._api=r,typeof t.digestKey=="string"){const o=J.DigestKey.from(t.digestKey);if(!o.ok)throw new Error(o.error);this._digestKey=o.val}else this._digestKey=t.digestKey;this._quote=t.quote??new Lp(this._api.quote),this._auth=t.auth??J.Siwe.fromDigestKey(new J.Url(this._api.auth),this._digestKey),this._orderbook=t.orderbook??new me.Orderbook(new J.Url(this._api.orderbook)),this._evmHTLC=t.htlc.evm,this._starknetHTLC=t.htlc.starknet,this._solanaHTLC=t.htlc.solana,this._secretManager=t.secretManager??Hi.fromDigestKey(this._digestKey.digestKey),this.orderExecutorCache=new pv,this._blockNumberFetcher=t.blockNumberFetcher??new $p(this._api.info,this.environment);const i=new Hr.BitcoinProvider(nw(this.environment));this._btcWallet=Hr.BitcoinWallet.fromPrivateKey(this._digestKey.digestKey,i)}static fromWallets(t){let r;if(typeof t.digestKey=="string"){const o=J.DigestKey.from(t.digestKey);if(!o.ok)throw new Error(o.error);r=o.val}else r=t.digestKey;const{api:n}=Bc(t.environment);if(!n)throw new Error("API not found, invalid environment "+t.environment);const i={evm:t.wallets.evm?new L0(n.evmRelay,t.wallets.evm,J.Siwe.fromDigestKey(new J.Url(n.auth),r)):void 0,starknet:t.wallets.starknet?new D0(n.starknetRelay,t.wallets.starknet,t.environment===J.Environment.MAINNET?J.Network.MAINNET:J.Network.TESTNET):void 0,solana:t.wallets.solana?new V0(t.wallets.solana,new J.Url(n.solanaRelay),t.environment===J.Environment.MAINNET?Ic.mainnet:Ic.testnet,t.solanaProgramAddress?t.solanaProgramAddress:op.mainnet):void 0};return new ju({htlc:i,...t})}get evmHTLC(){return this._evmHTLC}get starknetHTLC(){return this._starknetHTLC}get solanaHTLC(){return this._solanaHTLC}get quote(){return this._quote}get btcWallet(){return this._btcWallet}get orderbook(){return this._orderbook}get blockNumberFetcher(){return this._blockNumberFetcher}get secretManager(){return this._secretManager}get auth(){return this._auth}get digestKey(){return this._digestKey}async swap(t){const r=await this.validateAndFillParams(t);if(r.error)return U.Err(r.error);const{sendAddress:n,receiveAddress:i,timelock:o}=r.val,s=Date.now().toString(),a=await this._secretManager.generateSecret(s);if(a.error)return U.Err(a.error);const{strategyId:c,btcAddress:u}=t.additionalData,l={strategy_id:c,...u&&{bitcoin_optional_recipient:u}},h={source_chain:t.fromAsset.chain,destination_chain:t.toAsset.chain,source_asset:t.fromAsset.atomicSwapAddress,destination_asset:t.toAsset.atomicSwapAddress,initiator_source_address:n,initiator_destination_address:i,source_amount:t.sendAmount,destination_amount:t.receiveAmount,fee:"1",nonce:s,timelock:o,secret_hash:U.trim0x(a.val.secretHash),min_destination_confirmations:t.minDestinationConfirmations??0,additional_data:l,affiliate_fees:this.withDefaultAffiliateFees(t.affiliateFee)},y=await this._quote.getAttestedQuote(h);if(y.error)return U.Err(y.error);const p=await this._orderbook.createOrder(y.val,this._auth);if(p.error)return U.Err(p.error);const b=await this.pollOrder(p.val);return b.error?U.Err(b.error):U.Ok(b.val)}withDefaultAffiliateFees(t){return(t??[]).map(r=>({fee:r.fee,address:r.address,chain:r.chain??vf.chain,asset:r.asset??vf.asset}))}async validateAndFillParams(t){if(!t.additionalData.strategyId)return U.Err("StrategyId is required");if(!t.fromAsset||!t.toAsset)return U.Err("Source and destination assets are required for swap");if(t.fromAsset.chain===t.toAsset.chain&&t.fromAsset.atomicSwapAddress===t.toAsset.atomicSwapAddress)return U.Err("Source and destination assets cannot be the same");if(me.isMainnet(t.fromAsset.chain)&&!me.isMainnet(t.toAsset.chain)||!me.isMainnet(t.fromAsset.chain)&&me.isMainnet(t.toAsset.chain))return U.Err("Both assets should be on the same network (either mainnet or testnet)");const r=this.validateAmount(t.sendAmount);if(r.error)return U.Err(r.error);const n=this.validateAmount(t.receiveAmount);if(n.error)return U.Err(n.error);if(r<n)return U.Err("Send amount should be greater than receive amount");const i=me.getTimeLock(t.fromAsset.chain);if(!i)return U.Err("Unsupported chain for timelock");if((me.isBitcoin(t.fromAsset.chain)||me.isBitcoin(t.toAsset.chain))&&!t.additionalData.btcAddress)return U.Err("btcAddress in additionalData is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const o=await this.getAddresses(t.fromAsset.chain);if(o.error)return U.Err(o.error);const s=await this.getAddresses(t.toAsset.chain);return s.error?U.Err(s.error):U.Ok({sendAddress:o.val,receiveAddress:s.val,timelock:t.timelock??i})}async getAddresses(t){var n;switch(me.getBlockchainType(t)){case me.BlockchainType.EVM:return this._evmHTLC?U.Ok(this._evmHTLC.htlcActorAddress):U.Err("Please provide evmHTLC when initializing garden");case me.BlockchainType.Bitcoin:{const i=await((n=this._btcWallet)==null?void 0:n.getPublicKey());return!i||!tw(i)?U.Err("Invalid btc public key"):U.Ok(vr(i))}case me.BlockchainType.Solana:return this._solanaHTLC?U.Ok(this._solanaHTLC.htlcActorAddress):U.Err("Please provide solanaHTLC when initializing garden");case me.BlockchainType.Starknet:return this._starknetHTLC?U.Ok(this._starknetHTLC.htlcActorAddress):U.Err("Please provide starknetHTLC when initializing garden");default:return U.Err("Unsupported chain")}}validateAmount(t){if(t==null||t.includes("."))return U.Err("Invalid amount ",t);const r=new X0(t);return!r.isInteger()||r.isNaN()||r.lt(0)||r.isLessThanOrEqualTo(0)?U.Err("Invalid amount ",t):U.Ok(r)}async pollOrder(t){let r=await this._orderbook.getOrder(t,!0),n=0;for(;n<this.getOrderThreshold;){if(await J.sleep(1e3),n++,r.error){if(!r.error.includes("result is undefined"))return U.Err(r.error)}else if(r.val&&r.val.create_order.create_id.toLowerCase()===t.toLowerCase())return U.Ok(r.val);r=await this._orderbook.getOrder(t,!0)}return U.Err(`Order not found, createOrder id: ${t}`)}async execute(t=5e3){return await this._orderbook.subscribeOrders(this._digestKey.userId,!0,t,async r=>{const n=await this.filterExpiredAndAssignStatus(r.data);if(this.emit("onPendingOrdersChanged",n.val),r.data.length!==0)for(let i=0;i<n.val.length;i++){const o=n.val[i],s=vu(o.status);if(me.isBitcoin(o.source_swap.chain)&&o.status===Se.InitiateDetected){const a=this._btcWallet;if(!a){this.emit("error",o,"BTC wallet not found");continue}await this.postRefundSACP(o,a)}switch(s){case Te.Redeem:{const a=await this._secretManager.generateSecret(o.create_order.nonce);if(a.error){this.emit("error",o,a.error);return}switch(me.getBlockchainType(o.destination_swap.chain)){case me.BlockchainType.EVM:{await this.evmRedeem(o,a.val.secret);break}case me.BlockchainType.Bitcoin:{const c=this.btcWallet;if(!c){this.emit("error",o,"BTC wallet not found");return}await this.btcRedeem(c,o,a.val.secret);break}case me.BlockchainType.Starknet:{await this.starknetRedeem(o,a.val.secret);break}case me.BlockchainType.Solana:await this.solRedeem(o,a.val.secret);break;default:this.emit("error",o,"Unsupported chain: "+o.destination_swap.chain)}break}case Te.Refund:{switch(me.getBlockchainType(o.source_swap.chain)){case me.BlockchainType.Solana:{this.emit("error",o,"Solana refund is automatically done by relay service");break}case me.BlockchainType.EVM:{this.emit("error",o,"EVM refund is automatically done by relay service");break}case me.BlockchainType.Bitcoin:{const a=this.btcWallet;if(!a){this.emit("error",o,"BTC wallet not found");return}await this.btcRefund(a,o);break}case me.BlockchainType.Starknet:{this.emit("error",o,"Starknet refund is automatically done by relay service");break}default:this.emit("error",o,"Unsupported chain: "+o.source_swap.chain)}break}}}},"pending",{per_page:500})}async solRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing sol redeem"),this.orderExecutorCache.get(t,Te.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._solanaHTLC){this.emit("error",t,"Solana HTLC is required");return}const i=await this._solanaHTLC.redeem(t,r);if(i.error){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,Te.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(this.orderExecutorCache.set(t,Te.Redeem,i.val),this.emit("success",t,Te.Redeem,i.val))}async evmRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing evm redeem"),this.orderExecutorCache.get(t,Te.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._evmHTLC){this.emit("error",t,"EVMHTLC is required");return}const i=await this._evmHTLC.redeem(t,r);if(!i.ok){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,Te.Redeem,t.destination_swap.redeem_tx_hash);return}this.orderExecutorCache.set(t,Te.Redeem,i.val),this.emit("success",t,Te.Redeem,i.val)}async starknetRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing starknet redeem"),this.orderExecutorCache.get(t,Te.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._starknetHTLC){this.emit("error",t,"StarknetHTLC is required");return}const i=await this._starknetHTLC.redeem(t,r);if(i.error){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,Te.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(this.orderExecutorCache.set(t,Te.Redeem,i.val),this.emit("success",t,Te.Redeem,i.val))}async btcRedeem(t,r,n){var a,c;const i=this.bitcoinRedeemCache.get(r.create_order.create_id),o=(a=r.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:a.split(":").at(0);if(!o){this.emit("error",r,"Failed to get initiate_tx_hash");return}let s=!1;if(i)if(i.redeemedFromUTXO&&i.redeemedFromUTXO!==o)s=!0,this.emit("log",r.create_order.create_id,"rbf btc redeem");else if(i.redeemedAt&&Date.now()-i.redeemedAt>1e3*60*15)this.emit("log",r.create_order.create_id,"redeem not confirmed in last 15 minutes"),s=!0;else{this.emit("log",r.create_order.create_id,"btcRedeem: already redeemed");return}else if(r.destination_swap.redeem_tx_hash&&!Number(r.destination_swap.redeem_block_number))try{const u=await(await t.getProvider()).getTransaction(r.destination_swap.redeem_tx_hash);let l=!1;for(const h of u.vin)if(h.txid===o){l=!0;break}if(l){this.emit("log",r.create_order.create_id,"already a valid redeem");let h=0;try{const[y]=await(await t.getProvider()).getTransactionTimes([r.destination_swap.redeem_tx_hash]);y!==0&&(h=y)}catch{h=Date.now()}this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:o,redeemedAt:h,redeemTxHash:r.destination_swap.redeem_tx_hash});return}s=!0}catch(u){if(u.message.includes("Transaction not found"))s=!0;else{this.emit("error",r,"Failed to get redeem tx: "+u);return}}this.emit("log",r.create_order.create_id,"executing btc redeem");try{const l=await(await ui.from(t,Number(r.destination_swap.amount),r.create_order.secret_hash,vr(r.destination_swap.initiator),vr(r.destination_swap.redeemer),r.destination_swap.timelock,s?[o]:[])).getRedeemHex(U.trim0x(n),(c=r.create_order.additional_data)==null?void 0:c.bitcoin_optional_recipient),h=await this.broadcastRedeemTx(l,r.create_order.create_id);if(h.error||!h.val){this.emit("error",r,h.error||"Failed to broadcast redeem tx");return}s?(this.emit("log",r.create_order.create_id,"rbf: btc redeem success"),this.emit("rbf",r,h.val)):this.emit("success",r,Te.Redeem,h.val),this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:o,redeemedAt:Date.now(),redeemTxHash:h.val})}catch(u){this.emit("error",r,"Failed btc redeem: "+u)}}async btcRefund(t,r){var n;if(!this.orderExecutorCache.get(r,Te.Refund)){this.emit("log",r.create_order.create_id,"executing btc refund");try{const o=await(await ui.from(t,Number(r.source_swap.amount),r.create_order.secret_hash,vr(r.source_swap.initiator),vr(r.source_swap.redeemer),r.source_swap.timelock)).refund((n=r.create_order.additional_data)==null?void 0:n.bitcoin_optional_recipient);this.orderExecutorCache.set(r,Te.Refund,o),this.emit("success",r,Te.Refund,o)}catch(i){this.emit("error",r,"Failed btc refund: "+i)}}}async postRefundSACP(t,r){const n=this.refundSacpCache.get(t.create_order.create_id);if((n==null?void 0:n.initTxHash)===t.source_swap.initiate_tx_hash)return;const i=await ui.from(r,Number(t.source_swap.amount),t.create_order.secret_hash,vr(t.source_swap.initiator),vr(t.source_swap.redeemer),t.source_swap.timelock),o=t.create_order.additional_data.bitcoin_optional_recipient;if(o)try{const s=await i.generateInstantRefundSACP(o);if(!this._api)return;const a=new J.Url(this._api.orderbook).endpoint("orders/bitcoin/"+t.create_order.create_id+"/instant-refund");(await U.Fetcher.post(a,{headers:{"Content-Type":"application/json"},body:JSON.stringify({instant_refund_tx_bytes:s})})).status==="Ok"&&this.refundSacpCache.set(t.create_order.create_id,{initTxHash:t.source_swap.initiate_tx_hash})}catch(s){this.emit("error",t,"Failed to generate and post SACP: "+s);return}}async filterExpiredAndAssignStatus(t){var i;if(t.length===0)return U.Ok([]);const r=await((i=this._blockNumberFetcher)==null?void 0:i.fetchBlockNumbers());if(r.error)return U.Err(r.error);const n=[];for(let o=0;o<t.length;o++){const s=t[o];if(sp(s))continue;const a=s.source_swap.chain,c=s.destination_swap.chain,u=r==null?void 0:r.val[a],l=r==null?void 0:r.val[c];if(!u||!l){this.emit("error",s,"Error while fetching CurrentBlockNumbers");continue}const h=wu(s,u,l);n.push({...s,status:h})}return U.Ok(n)}async broadcastRedeemTx(t,r){try{if(!this._api)return U.Err("API not found");const n=new J.Url(this._api.evmRelay).endpoint("/bitcoin/redeem "),i=await this._auth.getAuthHeaders(),s=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...i.val},body:JSON.stringify({redeem_tx_bytes:t,order_id:r})})).json();return s.status==="Ok"&&s.result?U.Ok(s.result):U.Err(s.error)}catch(n){return U.Err("Failed to broadcast redeem tx: "+n)}}}class W6{constructor(t,r,n){this.callData=new Le.CallData(M0),this.account=t,this.starknetProvider=new Le.RpcProvider({nodeUrl:r||(n?Ui[n].nodeUrl:Ui.mainnet.nodeUrl)})}get htlcActorAddress(){return this.account.address}async getHTLCContract(t,r=!1){const n=r?t.destination_swap.asset:t.source_swap.asset;return new Le.Contract(H0,n,this.account)}async initiate(t){try{const n=await(await this.getHTLCContract(t)).token();if(!n)throw new Error("Token address retrieval failed");const i=Le.num.toHex(n),o=Le.cairo.uint256(BigInt(t.source_swap.amount));try{const a=await p6(this.account,i,t.source_swap.asset,BigInt(t.source_swap.amount),this.starknetProvider);if(a.error)return U.Err(a.error)}catch(a){return U.Err(`Allowance check failed: ${a}`)}const s=await this.account.execute({contractAddress:t.source_swap.asset,entrypoint:"initiate",calldata:[t.source_swap.redeemer,BigInt(t.source_swap.timelock),o.low,o.high,...J.hexToU32Array(t.create_order.secret_hash)]});if(!s.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return U.Ok(s.transaction_hash)}catch(r){return U.Err(`HTLC Initiation Error: ${r}`)}}async redeem(t,r){try{const n=await this.getHTLCContract(t,!0),i=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,o=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:Le.CallData.compile({swap_id:i,secret:J.hexToU32Array(r)})});return o.transaction_hash?U.Ok(o.transaction_hash):U.Err("Failed to redeem HTLC transaction")}catch{return U.Err("HTLC Redeem Error")}}async refund(t){try{const r=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,n=await this.getHTLCContract(t),i=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return i.transaction_hash?U.Ok(i.transaction_hash):U.Err("Failed to refund HTLC transaction")}catch{return U.Err("HTLC Refund Error")}}}class K6{constructor(t){if(this.provider=t,!t)throw new Error("Provider is required");this.provider=t,this.program=new It.Program(zc,t)}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async initiate(t){if(!t)return U.Err("Order is required");try{const{redeemer:r,secretHash:n,amount:i,expiresIn:o}=xr.from(t),s=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=It.web3.PublicKey.findProgramAddressSync(s,this.program.programId)[0];const a=await this.program.methods.initiate(i,o,r,n).accounts({initiator:this.provider.publicKey}).transaction(),c=await this.provider.sendAndConfirm(a);return c?U.Ok(c):U.Err("Failed to initiate HTLC transaction")}catch(r){return U.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(t,r){if(!t)return U.Err("Order is required");if(!r)return U.Err("Secret is required");const{secretHash:n}=xr.from(t),i=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=It.web3.PublicKey.findProgramAddressSync(i,this.program.programId)[0];try{const{redeemer:o}=xr.from(t);if(!this.swapAccount)return U.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const s=await this.program.methods.redeem(z0(r)).accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey,redeemer:o}).transaction(),a=await this.provider.sendAndConfirm(s);return a?U.Ok(a):U.Err("Failed to redeem HTLC transaction")}catch(o){return U.Err(`Error redeeming swap: ${o instanceof Error?o.message:String(o)}`)}}async refund(t){if(!t)return U.Err("Order is required");const{secretHash:r}=xr.from(t),n=[Buffer.from("swap_account"),Buffer.from(r)];this.swapAccount=It.web3.PublicKey.findProgramAddressSync(n,this.program.programId)[0];try{if(console.log("Initiating refund for ::",t.source_swap.swap_id),!this.swapAccount)return U.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const i=await this.program.methods.refund().accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey}).transaction(),o=await this.provider.sendAndConfirm(i);return o?U.Ok(o):U.Err("Failed to refund HTLC transaction")}catch(i){return U.Err(`Error refunding swap: ${i instanceof Error?i.message:String(i)}`)}}}exports.API=Eo;exports.AbiErrorInputsNotFoundError=Gy;exports.AbiErrorNotFoundError=zy;exports.AbiFunctionNotFoundError=fi;exports.AbiFunctionOutputsNotFoundError=Hd;exports.AbiFunctionSignatureNotFoundError=Wy;exports.BaseError=z;exports.BlockNumberFetcher=$p;exports.EvmRelay=L0;exports.Garden=ju;exports.Hash=Yc;exports.HttpRequestError=pn;exports.InvalidArrayError=Dd;exports.OrderActions=Te;exports.OrderStatus=Se;exports.ParseOrderStatus=wu;exports.ParseSwapStatus=Rc;exports.Quote=Lp;exports.STARKNET_CONFIG=Ui;exports.SecretManager=Hi;exports.SolanaHTLC=K6;exports.SolanaRelay=V0;exports.SolanaRelayerAddress=Ic;exports.StarknetHTLC=W6;exports.StarknetRelay=D0;exports.SwapStatus=Ie;exports.abytes=Br;exports.aexists=di;exports.ahash=pm;exports.anumber=li;exports.batchGatewayAbi=xg;exports.botanixMainnet=C0;exports.bytesToHex=vm;exports.call=bu;exports.clean=kr;exports.concat=cr;exports.concatBytes=xm;exports.concatHex=Wt;exports.constructOrderPair=Oc;exports.decodeAbiParameters=qi;exports.decodeErrorResult=uh;exports.encodeAbiParameters=zo;exports.evmToViemChainMap=N0;exports.filterDeadlineExpiredOrders=aw;exports.formatAbiItem=Gt;exports.getAbiItem=Ln;exports.getUrl=Wo;exports.hexToBytes=_m;exports.hyperliquid=U0;exports.hyperliquidTestnet=F0;exports.isAddressEqual=pu;exports.isBytes=Wd;exports.isExpired=Ni;exports.isHex=sr;exports.parseAction=sw;exports.parseActionFromStatus=vu;exports.randomBytes=Am;exports.resolveApiConfig=Bc;exports.sha256=xh;exports.slice=vn;exports.solanaProgramAddress=op;exports.solidityError=ah;exports.stringify=lt;exports.switchOrAddNetwork=$0;exports.toBytes=Do;exports.toFunctionSelector=Vo;exports.toXOnly=vr;exports.validateBTCAddress=rw;