@gardenfi/core 2.5.3-beta.2 → 2.5.3-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ccip-BE4ehdw2.js → ccip-BsQtD5CP.js} +1 -1
- package/dist/{ccip-CWyEeg1d.cjs → ccip-p2JXyi8a.cjs} +1 -1
- package/dist/{index-Cnz5kiIK.cjs → index-DA_3GuuU.cjs} +36 -36
- package/dist/{index-3Y2kQfE0.js → index-LmAfXTaz.js} +4802 -4780
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/src/lib/garden/garden.d.ts +2 -1
- package/dist/src/lib/garden/garden.types.d.ts +2 -2
- package/dist/src/lib/utils.d.ts +1 -2
- package/package.json +3 -3
|
@@ -1,57 +1,57 @@
|
|
|
1
|
-
"use strict";var r6=Object.defineProperty;var
|
|
2
|
-
`);super(i),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=s,this.metaMessages=r.metaMessages,this.shortMessage=e}};function Cn(t,e){const r=t.exec(e);return r==null?void 0:r.groups}const ym=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,mm=/^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)?$/,bm=/^\(.+?\).*?$/,hp=/^tuple(?<array>(\[(\d*)\])*)$/;function Al(t){let e=t.type;if(hp.test(t.type)&&"components"in t){e="(";const r=t.components.length;for(let s=0;s<r;s++){const i=t.components[s];e+=Al(i),s<r-1&&(e+=", ")}const n=Cn(hp,t.type);return e+=`)${(n==null?void 0:n.array)??""}`,Al({...t,type:e})}return"indexed"in t&&t.indexed&&(e=`${e} indexed`),t.name?`${e} ${t.name}`:e}function Qi(t){let e="";const r=t.length;for(let n=0;n<r;n++){const s=t[n];e+=Al(s),n!==r-1&&(e+=", ")}return e}function l6(t){var e;return t.type==="function"?`function ${t.name}(${Qi(t.inputs)})${t.stateMutability&&t.stateMutability!=="nonpayable"?` ${t.stateMutability}`:""}${(e=t.outputs)!=null&&e.length?` returns (${Qi(t.outputs)})`:""}`:t.type==="event"?`event ${t.name}(${Qi(t.inputs)})`:t.type==="error"?`error ${t.name}(${Qi(t.inputs)})`:t.type==="constructor"?`constructor(${Qi(t.inputs)})${t.stateMutability==="payable"?" payable":""}`:t.type==="fallback"?`fallback() external${t.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const gm=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function d6(t){return gm.test(t)}function h6(t){return Cn(gm,t)}const wm=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function p6(t){return wm.test(t)}function y6(t){return Cn(wm,t)}const vm=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function m6(t){return vm.test(t)}function b6(t){return Cn(vm,t)}const Em=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function Sm(t){return Em.test(t)}function g6(t){return Cn(Em,t)}const Am=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function w6(t){return Am.test(t)}function v6(t){return Cn(Am,t)}const xm=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function E6(t){return xm.test(t)}function S6(t){return Cn(xm,t)}const A6=/^receive\(\) external payable$/;function x6(t){return A6.test(t)}const k6=new Set(["indexed"]),xl=new Set(["calldata","memory","storage"]);let T6=class extends pr{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}},_6=class extends pr{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}},P6=class extends pr{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}},I6=class extends pr{constructor({param:e,name:r}){super("Invalid ABI parameter.",{details:e,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}},O6=class extends pr{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}},B6=class extends pr{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}},C6=class extends pr{constructor({abiParameter:e}){super("Invalid ABI parameter.",{details:JSON.stringify(e,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}},Di=class extends pr{constructor({signature:e,type:r}){super(`Invalid ${r} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}},$6=class extends pr{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}},R6=class extends pr{constructor({signature:e}){super("Invalid struct signature.",{details:e,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}},N6=class extends pr{constructor({type:e}){super("Circular reference detected.",{metaMessages:[`Struct "${e}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}},U6=class extends pr{constructor({current:e,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${e.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}};function M6(t,e,r){let n="";if(r)for(const s of Object.entries(r)){if(!s)continue;let i="";for(const o of s[1])i+=`[${o.type}${o.name?`:${o.name}`:""}]`;n+=`(${s[0]}{${i}})`}return e?`${e}:${t}${n}`:t}const ku=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 F6(t,e={}){if(m6(t))return j6(t,e);if(p6(t))return L6(t,e);if(d6(t))return D6(t,e);if(w6(t))return H6(t,e);if(E6(t))return z6(t);if(x6(t))return{type:"receive",stateMutability:"payable"};throw new $6({signature:t})}function j6(t,e={}){const r=b6(t);if(!r)throw new Di({signature:t,type:"function"});const n=Er(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push(Rs(n[a],{modifiers:xl,structs:e,type:"function"}));const o=[];if(r.returns){const a=Er(r.returns),c=a.length;for(let u=0;u<c;u++)o.push(Rs(a[u],{modifiers:xl,structs:e,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:s,outputs:o}}function L6(t,e={}){const r=y6(t);if(!r)throw new Di({signature:t,type:"event"});const n=Er(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Rs(n[o],{modifiers:k6,structs:e,type:"event"}));return{name:r.name,type:"event",inputs:s}}function D6(t,e={}){const r=h6(t);if(!r)throw new Di({signature:t,type:"error"});const n=Er(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Rs(n[o],{structs:e,type:"error"}));return{name:r.name,type:"error",inputs:s}}function H6(t,e={}){const r=v6(t);if(!r)throw new Di({signature:t,type:"constructor"});const n=Er(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Rs(n[o],{structs:e,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:s}}function z6(t){const e=S6(t);if(!e)throw new Di({signature:t,type:"fallback"});return{type:"fallback",stateMutability:e.stateMutability??"nonpayable"}}const V6=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,q6=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,G6=/^u?int$/;function Rs(t,e){var l,p;const r=M6(t,e==null?void 0:e.type,e==null?void 0:e.structs);if(ku.has(r))return ku.get(r);const n=bm.test(t),s=Cn(n?q6:V6,t);if(!s)throw new P6({param:t});if(s.name&&K6(s.name))throw new I6({param:t,name:s.name});const i=s.name?{name:s.name}:{},o=s.modifier==="indexed"?{indexed:!0}:{},a=(e==null?void 0:e.structs)??{};let c,u={};if(n){c="tuple";const d=Er(s.type),m=[],b=d.length;for(let E=0;E<b;E++)m.push(Rs(d[E],{structs:a}));u={components:m}}else if(s.type in a)c="tuple",u={components:a[s.type]};else if(G6.test(s.type))c=`${s.type}256`;else if(s.type==="address payable")c="address";else if(c=s.type,(e==null?void 0:e.type)!=="struct"&&!km(c))throw new _6({type:c});if(s.modifier){if(!((p=(l=e==null?void 0:e.modifiers)==null?void 0:l.has)!=null&&p.call(l,s.modifier)))throw new O6({param:t,type:e==null?void 0:e.type,modifier:s.modifier});if(xl.has(s.modifier)&&!Z6(c,!!s.array))throw new B6({param:t,type:e==null?void 0:e.type,modifier:s.modifier})}const f={type:`${c}${s.array??""}`,...i,...o,...u};return ku.set(r,f),f}function Er(t,e=[],r="",n=0){const s=t.trim().length;for(let i=0;i<s;i++){const o=t[i],a=t.slice(i+1);switch(o){case",":return n===0?Er(a,[...e,r.trim()]):Er(a,e,`${r}${o}`,n);case"(":return Er(a,e,`${r}${o}`,n+1);case")":return Er(a,e,`${r}${o}`,n-1);default:return Er(a,e,`${r}${o}`,n)}}if(r==="")return e;if(n!==0)throw new U6({current:r,depth:n});return e.push(r.trim()),e}function km(t){return t==="address"||t==="bool"||t==="function"||t==="string"||ym.test(t)||mm.test(t)}const W6=/^(?: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 K6(t){return t==="address"||t==="bool"||t==="function"||t==="string"||t==="tuple"||ym.test(t)||mm.test(t)||W6.test(t)}function Z6(t,e){return e||t==="bytes"||t==="string"||t==="tuple"}function Y6(t){const e={},r=t.length;for(let o=0;o<r;o++){const a=t[o];if(!Sm(a))continue;const c=g6(a);if(!c)throw new Di({signature:a,type:"struct"});const u=c.properties.split(";"),f=[],l=u.length;for(let p=0;p<l;p++){const m=u[p].trim();if(!m)continue;const b=Rs(m,{type:"struct"});f.push(b)}if(!f.length)throw new R6({signature:a});e[c.name]=f}const n={},s=Object.entries(e),i=s.length;for(let o=0;o<i;o++){const[a,c]=s[o];n[a]=Tm(c,e)}return n}const X6=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function Tm(t,e,r=new Set){const n=[],s=t.length;for(let i=0;i<s;i++){const o=t[i];if(bm.test(o.type))n.push(o);else{const c=Cn(X6,o.type);if(!(c!=null&&c.type))throw new C6({abiParameter:o});const{array:u,type:f}=c;if(f in e){if(r.has(f))throw new N6({type:f});n.push({...o,type:`tuple${u??""}`,components:Tm(e[f]??[],e,new Set([...r,f]))})}else if(km(f))n.push(o);else throw new T6({type:f})}}return n}function _m(t){const e=Y6(t),r=[],n=t.length;for(let s=0;s<n;s++){const i=t[s];Sm(i)||r.push(F6(i,e))}return r}function se(t,e,r){const n=t[e.name];if(typeof n=="function")return n;const s=t[r];return typeof s=="function"?s:i=>e(t,i)}function _r(t,{includeName:e=!1}={}){if(t.type!=="function"&&t.type!=="event"&&t.type!=="error")throw new fv(t.type);return`${t.name}(${Bc(t.inputs,{includeName:e})})`}function Bc(t,{includeName:e=!1}={}){return t?t.map(r=>J6(r,{includeName:e})).join(e?", ":","):""}function J6(t,{includeName:e}){return t.type.startsWith("tuple")?`(${Bc(t.components,{includeName:e})})${t.type.slice(5)}`:t.type+(e&&t.name?` ${t.name}`:"")}function Pr(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function He(t){return Pr(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Pm="2.37.6";let eo={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:r})=>e?`${t??"https://viem.sh"}${e}${r?`#${r}`:""}`:void 0,version:`viem@${Pm}`},L=class kl extends Error{constructor(e,r={}){var a;const n=(()=>{var c;return r.cause instanceof kl?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),s=r.cause instanceof kl&&r.cause.docsPath||r.docsPath,i=(a=eo.getDocsUrl)==null?void 0:a.call(eo,{...r,docsPath:s}),o=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...eo.version?[`Version: ${eo.version}`]:[]].join(`
|
|
3
|
-
`);super(o,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=s,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=e,this.version=
|
|
4
|
-
`),{docsPath:e,name:"AbiConstructorNotFoundError"})}}class
|
|
5
|
-
`),{docsPath:e,name:"AbiConstructorParamsNotFoundError"})}}class
|
|
6
|
-
`),{metaMessages:[`Params: (${
|
|
1
|
+
"use strict";var r6=Object.defineProperty;var ap=t=>{throw TypeError(t)};var n6=(t,e,r)=>e in t?r6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var cp=(t,e,r)=>n6(t,typeof e!="symbol"?e+"":e,r),up=(t,e,r)=>e.has(t)||ap("Cannot "+r);var Be=(t,e,r)=>(up(t,e,"read from private field"),r?r.call(t):e.get(t)),hs=(t,e,r)=>e.has(t)?ap("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),ps=(t,e,r,n)=>(up(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r);const Y=require("@gardenfi/orderbook"),g=require("@gardenfi/utils"),pe=require("bitcoinjs-lib"),s6=require("tiny-secp256k1"),ym=require("varuint-bitcoin"),i6=require("bignumber.js"),rc=require("ecpair"),Je=require("starknet"),Vt=require("@coral-xyz/anchor"),o6=require("@solana/spl-token"),fp=require("@mysten/wallet-standard"),a6=require("node-cache"),lp=require("yup"),dp=require("bip39"),c6=require("bip32");function Bc(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const Ae=Bc(pe),fr=Bc(s6),hp=Bc(ym),u6=Bc(o6),f6="1.1.0";let pr=class xl extends Error{constructor(e,r={}){var o;const n=r.cause instanceof xl?r.cause.details:(o=r.cause)!=null&&o.message?r.cause.message:r.details,s=r.cause instanceof xl&&r.cause.docsPath||r.docsPath,i=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: https://abitype.dev${s}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${f6}`].join(`
|
|
2
|
+
`);super(i),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=s,this.metaMessages=r.metaMessages,this.shortMessage=e}};function Cn(t,e){const r=t.exec(e);return r==null?void 0:r.groups}const mm=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,bm=/^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)?$/,gm=/^\(.+?\).*?$/,pp=/^tuple(?<array>(\[(\d*)\])*)$/;function kl(t){let e=t.type;if(pp.test(t.type)&&"components"in t){e="(";const r=t.components.length;for(let s=0;s<r;s++){const i=t.components[s];e+=kl(i),s<r-1&&(e+=", ")}const n=Cn(pp,t.type);return e+=`)${(n==null?void 0:n.array)??""}`,kl({...t,type:e})}return"indexed"in t&&t.indexed&&(e=`${e} indexed`),t.name?`${e} ${t.name}`:e}function Qi(t){let e="";const r=t.length;for(let n=0;n<r;n++){const s=t[n];e+=kl(s),n!==r-1&&(e+=", ")}return e}function l6(t){var e;return t.type==="function"?`function ${t.name}(${Qi(t.inputs)})${t.stateMutability&&t.stateMutability!=="nonpayable"?` ${t.stateMutability}`:""}${(e=t.outputs)!=null&&e.length?` returns (${Qi(t.outputs)})`:""}`:t.type==="event"?`event ${t.name}(${Qi(t.inputs)})`:t.type==="error"?`error ${t.name}(${Qi(t.inputs)})`:t.type==="constructor"?`constructor(${Qi(t.inputs)})${t.stateMutability==="payable"?" payable":""}`:t.type==="fallback"?`fallback() external${t.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const wm=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function d6(t){return wm.test(t)}function h6(t){return Cn(wm,t)}const vm=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function p6(t){return vm.test(t)}function y6(t){return Cn(vm,t)}const Em=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function m6(t){return Em.test(t)}function b6(t){return Cn(Em,t)}const Sm=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function Am(t){return Sm.test(t)}function g6(t){return Cn(Sm,t)}const xm=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function w6(t){return xm.test(t)}function v6(t){return Cn(xm,t)}const km=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function E6(t){return km.test(t)}function S6(t){return Cn(km,t)}const A6=/^receive\(\) external payable$/;function x6(t){return A6.test(t)}const k6=new Set(["indexed"]),Tl=new Set(["calldata","memory","storage"]);let T6=class extends pr{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}},_6=class extends pr{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}},P6=class extends pr{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}},I6=class extends pr{constructor({param:e,name:r}){super("Invalid ABI parameter.",{details:e,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}},O6=class extends pr{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}},B6=class extends pr{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}},C6=class extends pr{constructor({abiParameter:e}){super("Invalid ABI parameter.",{details:JSON.stringify(e,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}},Di=class extends pr{constructor({signature:e,type:r}){super(`Invalid ${r} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}},$6=class extends pr{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}},R6=class extends pr{constructor({signature:e}){super("Invalid struct signature.",{details:e,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}},N6=class extends pr{constructor({type:e}){super("Circular reference detected.",{metaMessages:[`Struct "${e}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}},U6=class extends pr{constructor({current:e,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${e.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}};function M6(t,e,r){let n="";if(r)for(const s of Object.entries(r)){if(!s)continue;let i="";for(const o of s[1])i+=`[${o.type}${o.name?`:${o.name}`:""}]`;n+=`(${s[0]}{${i}})`}return e?`${e}:${t}${n}`:t}const _u=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 F6(t,e={}){if(m6(t))return j6(t,e);if(p6(t))return L6(t,e);if(d6(t))return D6(t,e);if(w6(t))return H6(t,e);if(E6(t))return z6(t);if(x6(t))return{type:"receive",stateMutability:"payable"};throw new $6({signature:t})}function j6(t,e={}){const r=b6(t);if(!r)throw new Di({signature:t,type:"function"});const n=Er(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push(Rs(n[a],{modifiers:Tl,structs:e,type:"function"}));const o=[];if(r.returns){const a=Er(r.returns),c=a.length;for(let u=0;u<c;u++)o.push(Rs(a[u],{modifiers:Tl,structs:e,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:s,outputs:o}}function L6(t,e={}){const r=y6(t);if(!r)throw new Di({signature:t,type:"event"});const n=Er(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Rs(n[o],{modifiers:k6,structs:e,type:"event"}));return{name:r.name,type:"event",inputs:s}}function D6(t,e={}){const r=h6(t);if(!r)throw new Di({signature:t,type:"error"});const n=Er(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Rs(n[o],{structs:e,type:"error"}));return{name:r.name,type:"error",inputs:s}}function H6(t,e={}){const r=v6(t);if(!r)throw new Di({signature:t,type:"constructor"});const n=Er(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Rs(n[o],{structs:e,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:s}}function z6(t){const e=S6(t);if(!e)throw new Di({signature:t,type:"fallback"});return{type:"fallback",stateMutability:e.stateMutability??"nonpayable"}}const V6=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,q6=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,G6=/^u?int$/;function Rs(t,e){var l,p;const r=M6(t,e==null?void 0:e.type,e==null?void 0:e.structs);if(_u.has(r))return _u.get(r);const n=gm.test(t),s=Cn(n?q6:V6,t);if(!s)throw new P6({param:t});if(s.name&&K6(s.name))throw new I6({param:t,name:s.name});const i=s.name?{name:s.name}:{},o=s.modifier==="indexed"?{indexed:!0}:{},a=(e==null?void 0:e.structs)??{};let c,u={};if(n){c="tuple";const d=Er(s.type),m=[],b=d.length;for(let E=0;E<b;E++)m.push(Rs(d[E],{structs:a}));u={components:m}}else if(s.type in a)c="tuple",u={components:a[s.type]};else if(G6.test(s.type))c=`${s.type}256`;else if(s.type==="address payable")c="address";else if(c=s.type,(e==null?void 0:e.type)!=="struct"&&!Tm(c))throw new _6({type:c});if(s.modifier){if(!((p=(l=e==null?void 0:e.modifiers)==null?void 0:l.has)!=null&&p.call(l,s.modifier)))throw new O6({param:t,type:e==null?void 0:e.type,modifier:s.modifier});if(Tl.has(s.modifier)&&!Z6(c,!!s.array))throw new B6({param:t,type:e==null?void 0:e.type,modifier:s.modifier})}const f={type:`${c}${s.array??""}`,...i,...o,...u};return _u.set(r,f),f}function Er(t,e=[],r="",n=0){const s=t.trim().length;for(let i=0;i<s;i++){const o=t[i],a=t.slice(i+1);switch(o){case",":return n===0?Er(a,[...e,r.trim()]):Er(a,e,`${r}${o}`,n);case"(":return Er(a,e,`${r}${o}`,n+1);case")":return Er(a,e,`${r}${o}`,n-1);default:return Er(a,e,`${r}${o}`,n)}}if(r==="")return e;if(n!==0)throw new U6({current:r,depth:n});return e.push(r.trim()),e}function Tm(t){return t==="address"||t==="bool"||t==="function"||t==="string"||mm.test(t)||bm.test(t)}const W6=/^(?: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 K6(t){return t==="address"||t==="bool"||t==="function"||t==="string"||t==="tuple"||mm.test(t)||bm.test(t)||W6.test(t)}function Z6(t,e){return e||t==="bytes"||t==="string"||t==="tuple"}function Y6(t){const e={},r=t.length;for(let o=0;o<r;o++){const a=t[o];if(!Am(a))continue;const c=g6(a);if(!c)throw new Di({signature:a,type:"struct"});const u=c.properties.split(";"),f=[],l=u.length;for(let p=0;p<l;p++){const m=u[p].trim();if(!m)continue;const b=Rs(m,{type:"struct"});f.push(b)}if(!f.length)throw new R6({signature:a});e[c.name]=f}const n={},s=Object.entries(e),i=s.length;for(let o=0;o<i;o++){const[a,c]=s[o];n[a]=_m(c,e)}return n}const X6=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function _m(t,e,r=new Set){const n=[],s=t.length;for(let i=0;i<s;i++){const o=t[i];if(gm.test(o.type))n.push(o);else{const c=Cn(X6,o.type);if(!(c!=null&&c.type))throw new C6({abiParameter:o});const{array:u,type:f}=c;if(f in e){if(r.has(f))throw new N6({type:f});n.push({...o,type:`tuple${u??""}`,components:_m(e[f]??[],e,new Set([...r,f]))})}else if(Tm(f))n.push(o);else throw new T6({type:f})}}return n}function Pm(t){const e=Y6(t),r=[],n=t.length;for(let s=0;s<n;s++){const i=t[s];Am(i)||r.push(F6(i,e))}return r}function se(t,e,r){const n=t[e.name];if(typeof n=="function")return n;const s=t[r];return typeof s=="function"?s:i=>e(t,i)}function _r(t,{includeName:e=!1}={}){if(t.type!=="function"&&t.type!=="event"&&t.type!=="error")throw new fv(t.type);return`${t.name}(${Cc(t.inputs,{includeName:e})})`}function Cc(t,{includeName:e=!1}={}){return t?t.map(r=>J6(r,{includeName:e})).join(e?", ":","):""}function J6(t,{includeName:e}){return t.type.startsWith("tuple")?`(${Cc(t.components,{includeName:e})})${t.type.slice(5)}`:t.type+(e&&t.name?` ${t.name}`:"")}function Pr(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function He(t){return Pr(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Im="2.37.8";let eo={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:r})=>e?`${t??"https://viem.sh"}${e}${r?`#${r}`:""}`:void 0,version:`viem@${Im}`},L=class _l extends Error{constructor(e,r={}){var a;const n=(()=>{var c;return r.cause instanceof _l?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),s=r.cause instanceof _l&&r.cause.docsPath||r.docsPath,i=(a=eo.getDocsUrl)==null?void 0:a.call(eo,{...r,docsPath:s}),o=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...eo.version?[`Version: ${eo.version}`]:[]].join(`
|
|
3
|
+
`);super(o,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=s,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=e,this.version=Im}walk(e){return Om(this,e)}};function Om(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Om(t.cause,e):e?null:t}class Q6 extends L{constructor({docsPath:e}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
|
|
4
|
+
`),{docsPath:e,name:"AbiConstructorNotFoundError"})}}class yp extends L{constructor({docsPath:e}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
|
|
5
|
+
`),{docsPath:e,name:"AbiConstructorParamsNotFoundError"})}}class Bm extends L{constructor({data:e,params:r,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join(`
|
|
6
|
+
`),{metaMessages:[`Params: (${Cc(r,{includeName:!0})})`,`Data: ${e} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e,this.params=r,this.size=n}}class la extends L{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError"})}}class ev extends L{constructor({expectedLength:e,givenLength:r,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${e}`,`Given length: ${r}`].join(`
|
|
7
7
|
`),{name:"AbiEncodingArrayLengthMismatchError"})}}class tv extends L{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${He(r)}) does not match expected size (bytes${e}).`,{name:"AbiEncodingBytesSizeMismatchError"})}}class rv extends L{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${e}`,`Given length (values): ${r}`].join(`
|
|
8
8
|
`),{name:"AbiEncodingLengthMismatchError"})}}class nv extends L{constructor(e,{docsPath:r}){super([`Arguments (\`args\`) were provided to "${e}", but "${e}" on the ABI does not contain any parameters (\`inputs\`).`,"Cannot encode error result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the inputs exist on it."].join(`
|
|
9
|
-
`),{docsPath:r,name:"AbiErrorInputsNotFoundError"})}}class
|
|
10
|
-
`),{docsPath:r,name:"AbiErrorNotFoundError"})}}class
|
|
11
|
-
`),{docsPath:r,name:"AbiErrorSignatureNotFoundError"}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=e}}class sv extends L{constructor({docsPath:e}){super("Cannot extract event signature from empty topics.",{docsPath:e,name:"AbiEventSignatureEmptyTopicsError"})}}class
|
|
12
|
-
`),{docsPath:r,name:"AbiEventSignatureNotFoundError"})}}class
|
|
9
|
+
`),{docsPath:r,name:"AbiErrorInputsNotFoundError"})}}class mp extends L{constructor(e,{docsPath:r}={}){super([`Error ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it."].join(`
|
|
10
|
+
`),{docsPath:r,name:"AbiErrorNotFoundError"})}}class Cm extends L{constructor(e,{docsPath:r}){super([`Encoded error signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
|
|
11
|
+
`),{docsPath:r,name:"AbiErrorSignatureNotFoundError"}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=e}}class sv extends L{constructor({docsPath:e}){super("Cannot extract event signature from empty topics.",{docsPath:e,name:"AbiEventSignatureEmptyTopicsError"})}}class $m extends L{constructor(e,{docsPath:r}){super([`Encoded event signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
|
|
12
|
+
`),{docsPath:r,name:"AbiEventSignatureNotFoundError"})}}class bp extends L{constructor(e,{docsPath:r}={}){super([`Event ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it."].join(`
|
|
13
13
|
`),{docsPath:r,name:"AbiEventNotFoundError"})}}class Oi extends L{constructor(e,{docsPath:r}={}){super([`Function ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join(`
|
|
14
|
-
`),{docsPath:r,name:"AbiFunctionNotFoundError"})}}class
|
|
14
|
+
`),{docsPath:r,name:"AbiFunctionNotFoundError"})}}class Rm extends L{constructor(e,{docsPath:r}){super([`Function "${e}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join(`
|
|
15
15
|
`),{docsPath:r,name:"AbiFunctionOutputsNotFoundError"})}}class iv extends L{constructor(e,{docsPath:r}){super([`Encoded function signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
|
|
16
16
|
`),{docsPath:r,name:"AbiFunctionSignatureNotFoundError"})}}class ov extends L{constructor(e,r){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${e.type}\` in \`${_r(e.abiItem)}\`, and`,`\`${r.type}\` in \`${_r(r.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}}let av=class extends L{constructor({expectedSize:e,givenSize:r}){super(`Expected bytes${e}, got bytes${r}.`,{name:"BytesSizeMismatchError"})}};class Po extends L{constructor({abiItem:e,data:r,params:n,size:s}){super([`Data size of ${s} bytes is too small for non-indexed event parameters.`].join(`
|
|
17
|
-
`),{metaMessages:[`Params: (${
|
|
17
|
+
`),{metaMessages:[`Params: (${Cc(n,{includeName:!0})})`,`Data: ${r} (${s} bytes)`],name:"DecodeLogDataMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e,this.data=r,this.params=n,this.size=s}}class $c extends L{constructor({abiItem:e,param:r}){super([`Expected a topic for indexed event parameter${r.name?` "${r.name}"`:""} on event "${_r(e,{includeName:!0})}".`].join(`
|
|
18
18
|
`),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e}}class cv extends L{constructor(e,{docsPath:r}){super([`Type "${e}" is not a valid encoding type.`,"Please provide a valid ABI type."].join(`
|
|
19
19
|
`),{docsPath:r,name:"InvalidAbiEncodingType"})}}class uv extends L{constructor(e,{docsPath:r}){super([`Type "${e}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(`
|
|
20
|
-
`),{docsPath:r,name:"InvalidAbiDecodingType"})}}let
|
|
20
|
+
`),{docsPath:r,name:"InvalidAbiDecodingType"})}}let Nm=class extends L{constructor(e){super([`Value "${e}" is not a valid array.`].join(`
|
|
21
21
|
`),{name:"InvalidArrayError"})}};class fv extends L{constructor(e){super([`"${e}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(`
|
|
22
|
-
`),{name:"InvalidDefinitionTypeError"})}}class lv extends L{constructor(e){super(`Filter type "${e}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}let Nm=class extends L{constructor({offset:e,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},Um=class extends L{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}};class bp extends L{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${e} ${n} long.`,{name:"InvalidBytesLengthError"})}}function Hi(t,{dir:e,size:r=32}={}){return typeof t=="string"?ts(t,{dir:e,size:r}):dv(t,{dir:e,size:r})}function ts(t,{dir:e,size:r=32}={}){if(r===null)return t;const n=t.replace("0x","");if(n.length>r*2)throw new Um({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function dv(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new Um({size:t.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let s=0;s<r;s++){const i=e==="right";n[i?s:r-s-1]=t[i?s:t.length-s-1]}return n}let Mm=class extends L{constructor({max:e,min:r,signed:n,size:s,value:i}){super(`Number "${i}" is not in safe ${s?`${s*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}},hv=class extends L{constructor(e){super(`Bytes value "${e}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}};class pv extends L{constructor(e){super(`Hex value "${e}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}let yv=class extends L{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function lr(t,{dir:e="left"}={}){let r=typeof t=="string"?t.replace("0x",""):t,n=0;for(let s=0;s<r.length-1&&r[e==="left"?s:r.length-s-1].toString()==="0";s++)n++;return r=e==="left"?r.slice(n):r.slice(0,r.length-n),typeof t=="string"?(r.length===1&&e==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}function Cr(t,{size:e}){if(He(t)>e)throw new yv({givenSize:He(t),maxSize:e})}function ut(t,e={}){const{signed:r}=e;e.size&&Cr(t,{size:e.size});const n=BigInt(t);if(!r)return n;const s=(t.length-2)/2,i=(1n<<BigInt(s)*8n-1n)-1n;return n<=i?n:n-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function mv(t,e={}){let r=t;if(e.size&&(Cr(r,{size:e.size}),r=lr(r)),lr(r)==="0x00")return!1;if(lr(r)==="0x01")return!0;throw new pv(r)}function dr(t,e={}){return Number(ut(t,e))}const bv=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Bt(t,e={}){return typeof t=="number"||typeof t=="bigint"?Z(t,e):typeof t=="string"?Bi(t,e):typeof t=="boolean"?Fm(t,e):et(t,e)}function Fm(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(Cr(r,{size:e.size}),Hi(r,{size:e.size})):r}function et(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=bv[t[s]];const n=`0x${r}`;return typeof e.size=="number"?(Cr(n,{size:e.size}),Hi(n,{dir:"right",size:e.size})):n}function Z(t,e={}){const{signed:r,size:n}=e,s=BigInt(t);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<o){const c=typeof t=="bigint"?"n":"";throw new Mm({max:i?`${i}${c}`:void 0,min:`${o}${c}`,signed:r,size:n,value:`${t}${c}`})}const a=`0x${(r&&s<0?(1n<<BigInt(n*8))+BigInt(s):s).toString(16)}`;return n?Hi(a,{size:n}):a}const gv=new TextEncoder;function Bi(t,e={}){const r=gv.encode(t);return et(r,e)}const wv=new TextEncoder;function zi(t,e={}){return typeof t=="number"||typeof t=="bigint"?Ev(t,e):typeof t=="boolean"?vv(t,e):Pr(t)?Jr(t,e):_s(t,e)}function vv(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?(Cr(r,{size:e.size}),Hi(r,{size:e.size})):r}const tn={zero:48,nine:57,A:65,F:70,a:97,f:102};function gp(t){if(t>=tn.zero&&t<=tn.nine)return t-tn.zero;if(t>=tn.A&&t<=tn.F)return t-(tn.A-10);if(t>=tn.a&&t<=tn.f)return t-(tn.a-10)}function Jr(t,e={}){let r=t;e.size&&(Cr(r,{size:e.size}),r=Hi(r,{dir:"right",size:e.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const s=n.length/2,i=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=gp(n.charCodeAt(a++)),u=gp(n.charCodeAt(a++));if(c===void 0||u===void 0)throw new L(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);i[o]=c*16+u}return i}function Ev(t,e){const r=Z(t,e);return Jr(r)}function _s(t,e={}){const r=wv.encode(t);return typeof e.size=="number"?(Cr(r,{size:e.size}),Hi(r,{dir:"right",size:e.size})):r}const $a=BigInt(2**32-1),wp=BigInt(32);function jm(t,e=!1){return e?{h:Number(t&$a),l:Number(t>>wp&$a)}:{h:Number(t>>wp&$a)|0,l:Number(t&$a)|0}}function Sv(t,e=!1){const r=t.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=jm(t[i],e);[n[i],s[i]]=[o,a]}return[n,s]}const Lm=(t,e,r)=>t>>>r|e<<32-r,Dm=(t,e,r)=>t<<32-r|e>>>r,Av=(t,e,r)=>t<<64-r|e>>>r-32,xv=(t,e,r)=>t>>>r-32|e<<64-r,kv=(t,e)=>e,Tv=(t,e)=>t,_v=(t,e,r)=>t<<r|e>>>32-r,Pv=(t,e,r)=>e<<r|t>>>32-r,Iv=(t,e,r)=>e<<r-32|t>>>64-r,Ov=(t,e,r)=>t<<r-32|e>>>64-r;function Hm(t,e,r,n){const s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const zm=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Vm=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,si=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Bv(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ss(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function is(t,...e){if(!Bv(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Cv(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ss(t.outputLen),ss(t.blockLen)}function os(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Rd(t,e){is(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Io(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ir(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Tu(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Mr(t,e){return t<<32-e|t>>>e}function Ra(t,e){return t<<e|t>>>32-e>>>0}const qm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Gm(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const dn=qm?t=>t:t=>Gm(t);function $v(t){for(let e=0;e<t.length;e++)t[e]=Gm(t[e]);return t}const Kn=qm?t=>t:$v;function Rv(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function En(t){return typeof t=="string"&&(t=Rv(t)),is(t),t}function Nv(...t){let e=0;for(let n=0;n<t.length;n++){const s=t[n];is(s),e+=s.length}const r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){const i=t[n];r.set(i,s),s+=i.length}return r}class $c{}function Rc(t){const e=n=>t().update(En(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Uv(t){const e=(n,s)=>t(s).update(En(n)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}function Mv(t=32){if(si&&typeof si.getRandomValues=="function")return si.getRandomValues(new Uint8Array(t));if(si&&typeof si.randomBytes=="function")return Uint8Array.from(si.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const Fv=BigInt(0),to=BigInt(1),jv=BigInt(2),Lv=BigInt(7),Dv=BigInt(256),Hv=BigInt(113),Wm=[],Km=[],Zm=[];for(let t=0,e=to,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],Wm.push(2*(5*n+r)),Km.push((t+1)*(t+2)/2%64);let s=Fv;for(let i=0;i<7;i++)e=(e<<to^(e>>Lv)*Hv)%Dv,e&jv&&(s^=to<<(to<<BigInt(i))-to);Zm.push(s)}const Ym=Sv(Zm,!0),zv=Ym[0],Vv=Ym[1],vp=(t,e,r)=>r>32?Iv(t,e,r):_v(t,e,r),Ep=(t,e,r)=>r>32?Ov(t,e,r):Pv(t,e,r);function qv(t,e=24){const r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=r[c],f=r[c+1],l=vp(u,f,1)^r[a],p=Ep(u,f,1)^r[a+1];for(let d=0;d<50;d+=10)t[o+d]^=l,t[o+d+1]^=p}let s=t[2],i=t[3];for(let o=0;o<24;o++){const a=Km[o],c=vp(s,i,a),u=Ep(s,i,a),f=Wm[o];s=t[f],i=t[f+1],t[f]=c,t[f+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=zv[n],t[1]^=Vv[n]}Ir(r)}class Nd extends $c{constructor(e,r,n,s=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=s,this.rounds=i,ss(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Io(this.state)}clone(){return this._cloneInto()}keccak(){Kn(this.state32),qv(this.state32,this.rounds),Kn(this.state32),this.posOut=0,this.pos=0}update(e){os(this),e=En(e),is(e);const{blockLen:r,state:n}=this,s=e.length;for(let i=0;i<s;){const o=Math.min(r-this.pos,s-i);for(let a=0;a<o;a++)n[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:n,blockLen:s}=this;e[n]^=r,r&128&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){os(this,!1),is(e),this.finish();const r=this.state,{blockLen:n}=this;for(let s=0,i=e.length;s<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ss(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Rd(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Ir(this.state)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:s,rounds:i,enableXOF:o}=this;return e||(e=new Nd(r,n,s,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Gv=(t,e,r)=>Rc(()=>new Nd(e,t,r)),Xm=Gv(1,136,256/8);function ht(t,e){const r=e||"hex",n=Xm(Pr(t,{strict:!1})?zi(t):t);return r==="bytes"?n:Bt(n)}const Wv=t=>ht(zi(t));function Kv(t){return Wv(t)}function Zv(t){let e=!0,r="",n=0,s="",i=!1;for(let o=0;o<t.length;o++){const a=t[o];if(["(",")",","].includes(a)&&(e=!0),a==="("&&n++,a===")"&&n--,!!e){if(n===0){if(a===" "&&["event","function",""].includes(s))s="";else if(s+=a,a===")"){i=!0;break}continue}if(a===" "){t[o-1]!==","&&r!==","&&r!==",("&&(r="",e=!1);continue}s+=a,r+=a}}if(!i)throw new L("Unable to normalize signature.");return s}const Yv=t=>{const e=typeof t=="string"?t:l6(t);return Zv(e)};function Jm(t){return Kv(Yv(t))}const Nc=Jm;let $t=class extends L{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}},Uc=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}};const _u=new Uc(8192);function da(t,e){if(_u.has(`${t}.${e}`))return _u.get(`${t}.${e}`);const r=t.substring(2).toLowerCase(),n=ht(_s(r),"bytes"),s=r.split("");for(let o=0;o<40;o+=2)n[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(n[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const i=`0x${s.join("")}`;return _u.set(`${t}.${e}`,i),i}function Ud(t,e){if(!at(t,{strict:!1}))throw new $t({address:t});return da(t,e)}const Xv=/^0x[a-fA-F0-9]{40}$/,Pu=new Uc(8192);function at(t,e){const{strict:r=!0}=e??{},n=`${t}.${r}`;if(Pu.has(n))return Pu.get(n);const s=Xv.test(t)?t.toLowerCase()===t?!0:r?da(t)===t:!0:!1;return Pu.set(n,s),s}function Kt(t){return typeof t[0]=="string"?$r(t):Jv(t)}function Jv(t){let e=0;for(const s of t)e+=s.length;const r=new Uint8Array(e);let n=0;for(const s of t)r.set(s,n),n+=s.length;return r}function $r(t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function Ns(t,e,r,{strict:n}={}){return Pr(t,{strict:!1})?Tl(t,e,r,{strict:n}):tb(t,e,r,{strict:n})}function Qm(t,e){if(typeof e=="number"&&e>0&&e>He(t)-1)throw new Nm({offset:e,position:"start",size:He(t)})}function eb(t,e,r){if(typeof e=="number"&&typeof r=="number"&&He(t)!==r-e)throw new Nm({offset:r,position:"end",size:He(t)})}function tb(t,e,r,{strict:n}={}){Qm(t,e);const s=t.slice(e,r);return n&&eb(s,e,r),s}function Tl(t,e,r,{strict:n}={}){Qm(t,e);const s=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return n&&eb(s,e,r),s}const Qv=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,rb=/^(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 fs(t,e){if(t.length!==e.length)throw new rv({expectedLength:t.length,givenLength:e.length});const r=e5({params:t,values:e}),n=Fd(r);return n.length===0?"0x":n}function e5({params:t,values:e}){const r=[];for(let n=0;n<t.length;n++)r.push(Md({param:t[n],value:e[n]}));return r}function Md({param:t,value:e}){const r=jd(t.type);if(r){const[n,s]=r;return r5(e,{length:n,param:{...t,type:s}})}if(t.type==="tuple")return a5(e,{param:t});if(t.type==="address")return t5(e);if(t.type==="bool")return s5(e);if(t.type.startsWith("uint")||t.type.startsWith("int")){const n=t.type.startsWith("int"),[,,s="256"]=rb.exec(t.type)??[];return i5(e,{signed:n,size:Number(s)})}if(t.type.startsWith("bytes"))return n5(e,{param:t});if(t.type==="string")return o5(e);throw new cv(t.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function Fd(t){let e=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?e+=32:e+=He(a)}const r=[],n=[];let s=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?(r.push(Z(e+s,{size:32})),n.push(a),s+=He(a)):r.push(a)}return Kt([...r,...n])}function t5(t){if(!at(t))throw new $t({address:t});return{dynamic:!1,encoded:ts(t.toLowerCase())}}function r5(t,{length:e,param:r}){const n=e===null;if(!Array.isArray(t))throw new Rm(t);if(!n&&t.length!==e)throw new ev({expectedLength:e,givenLength:t.length,type:`${r.type}[${e}]`});let s=!1;const i=[];for(let o=0;o<t.length;o++){const a=Md({param:r,value:t[o]});a.dynamic&&(s=!0),i.push(a)}if(n||s){const o=Fd(i);if(n){const a=Z(i.length,{size:32});return{dynamic:!0,encoded:i.length>0?Kt([a,o]):a}}if(s)return{dynamic:!0,encoded:o}}return{dynamic:!1,encoded:Kt(i.map(({encoded:o})=>o))}}function n5(t,{param:e}){const[,r]=e.type.split("bytes"),n=He(t);if(!r){let s=t;return n%32!==0&&(s=ts(s,{dir:"right",size:Math.ceil((t.length-2)/2/32)*32})),{dynamic:!0,encoded:Kt([ts(Z(n,{size:32})),s])}}if(n!==Number.parseInt(r,10))throw new tv({expectedSize:Number.parseInt(r,10),value:t});return{dynamic:!1,encoded:ts(t,{dir:"right"})}}function s5(t){if(typeof t!="boolean")throw new L(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:ts(Fm(t))}}function i5(t,{signed:e,size:r=256}){if(typeof r=="number"){const n=2n**(BigInt(r)-(e?1n:0n))-1n,s=e?-n-1n:0n;if(t>n||t<s)throw new Mm({max:n.toString(),min:s.toString(),signed:e,size:r/8,value:t.toString()})}return{dynamic:!1,encoded:Z(t,{size:32,signed:e})}}function o5(t){const e=Bi(t),r=Math.ceil(He(e)/32),n=[];for(let s=0;s<r;s++)n.push(ts(Ns(e,s*32,(s+1)*32),{dir:"right"}));return{dynamic:!0,encoded:Kt([ts(Z(He(e),{size:32})),...n])}}function a5(t,{param:e}){let r=!1;const n=[];for(let s=0;s<e.components.length;s++){const i=e.components[s],o=Array.isArray(t)?s:i.name,a=Md({param:i,value:t[o]});n.push(a),a.dynamic&&(r=!0)}return{dynamic:r,encoded:r?Fd(n):Kt(n.map(({encoded:s})=>s))}}function jd(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}const ha=t=>Ns(Jm(t),0,4);function Zs(t){const{abi:e,args:r=[],name:n}=t,s=Pr(n,{strict:!1}),i=e.filter(a=>s?a.type==="function"?ha(a)===n:a.type==="event"?Nc(a)===n:!1:"name"in a&&a.name===n);if(i.length===0)return;if(i.length===1)return i[0];let o;for(const a of i){if(!("inputs"in a))continue;if(!r||r.length===0){if(!a.inputs||a.inputs.length===0)return a;continue}if(!a.inputs||a.inputs.length===0||a.inputs.length!==r.length)continue;if(r.every((u,f)=>{const l="inputs"in a&&a.inputs[f];return l?_l(u,l):!1})){if(o&&"inputs"in o&&o.inputs){const u=nb(a.inputs,o.inputs,r);if(u)throw new ov({abiItem:a,type:u[0]},{abiItem:o,type:u[1]})}o=a}}return o||i[0]}function _l(t,e){const r=typeof t,n=e.type;switch(n){case"address":return at(t,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in e?Object.values(e.components).every((s,i)=>_l(Object.values(t)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||t instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(t)&&t.every(s=>_l(s,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function nb(t,e,r){for(const n in t){const s=t[n],i=e[n];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return nb(s.components,i.components,r[n]);const o=[s.type,i.type];if(o.includes("address")&&o.includes("bytes20")?!0:o.includes("address")&&o.includes("string")?at(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?at(r[n],{strict:!1}):!1)return o}}const Sp="/docs/contract/encodeEventTopics";function pa(t){var c;const{abi:e,eventName:r,args:n}=t;let s=e[0];if(r){const u=Zs({abi:e,name:r});if(!u)throw new mp(r,{docsPath:Sp});s=u}if(s.type!=="event")throw new mp(void 0,{docsPath:Sp});const i=_r(s),o=Nc(i);let a=[];if(n&&"inputs"in s){const u=(c=s.inputs)==null?void 0:c.filter(l=>"indexed"in l&&l.indexed),f=Array.isArray(n)?n:Object.values(n).length>0?(u==null?void 0:u.map(l=>n[l.name]))??[]:[];f.length>0&&(a=(u==null?void 0:u.map((l,p)=>Array.isArray(f[p])?f[p].map((d,m)=>Ap({param:l,value:f[p][m]})):typeof f[p]<"u"&&f[p]!==null?Ap({param:l,value:f[p]}):null))??[])}return[o,...a]}function Ap({param:t,value:e}){if(t.type==="string"||t.type==="bytes")return ht(zi(e));if(t.type==="tuple"||t.type.match(/^(.*)\[(\d+)?\]$/))throw new lv(t.type);return fs([t],[e])}function Mc(t,{method:e}){var n,s;const r={};return t.transport.type==="fallback"&&((s=(n=t.transport).onResponse)==null||s.call(n,({method:i,response:o,status:a,transport:c})=>{a==="success"&&e===i&&(r[o]=c.request)})),i=>r[i]||t.request}async function Ld(t,e){const{address:r,abi:n,args:s,eventName:i,fromBlock:o,strict:a,toBlock:c}=e,u=Mc(t,{method:"eth_newFilter"}),f=i?pa({abi:n,args:s,eventName:i}):void 0,l=await t.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof o=="bigint"?Z(o):o,toBlock:typeof c=="bigint"?Z(c):c,topics:f}]});return{abi:n,args:s,eventName:i,id:l,request:u(l),strict:!!a,type:"event"}}function Ze(t){return typeof t=="string"?{address:t,type:"json-rpc"}:t}const xp="/docs/contract/encodeFunctionData";function c5(t){const{abi:e,args:r,functionName:n}=t;let s=e[0];if(n){const i=Zs({abi:e,args:r,name:n});if(!i)throw new Oi(n,{docsPath:xp});s=i}if(s.type!=="function")throw new Oi(void 0,{docsPath:xp});return{abi:[s],functionName:ha(_r(s))}}function Jt(t){const{args:e}=t,{abi:r,functionName:n}=(()=>{var a;return t.abi.length===1&&((a=t.functionName)!=null&&a.startsWith("0x"))?t:c5(t)})(),s=r[0],i=n,o="inputs"in s&&s.inputs?fs(s.inputs,e??[]):void 0;return $r([i,o??"0x"])}const u5={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."},sb={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},f5={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};let kp=class extends L{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`,{name:"NegativeOffsetError"})}},ib=class extends L{constructor({length:e,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${e}\`).`,{name:"PositionOutOfBoundsError"})}},l5=class extends L{constructor({count:e,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${e}\`).`,{name:"RecursiveReadLimitExceededError"})}};const d5={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 l5({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(t){if(t<0||t>this.bytes.length-1)throw new ib({length:this.bytes.length,position:t})},decrementPosition(t){if(t<0)throw new kp({offset:t});const e=this.position-t;this.assertPosition(e),this.position=e},getReadCount(t){return this.positionReadCount.get(t||this.position)||0},incrementPosition(t){if(t<0)throw new kp({offset:t});const e=this.position+t;this.assertPosition(e),this.position=e},inspectByte(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectBytes(t,e){const r=e??this.position;return this.assertPosition(r+t-1),this.bytes.subarray(r,r+t)},inspectUint8(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectUint16(t){const e=t??this.position;return this.assertPosition(e+1),this.dataView.getUint16(e)},inspectUint24(t){const e=t??this.position;return this.assertPosition(e+2),(this.dataView.getUint16(e)<<8)+this.dataView.getUint8(e+2)},inspectUint32(t){const e=t??this.position;return this.assertPosition(e+3),this.dataView.getUint32(e)},pushByte(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushBytes(t){this.assertPosition(this.position+t.length-1),this.bytes.set(t,this.position),this.position+=t.length},pushUint8(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushUint16(t){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,t),this.position+=2},pushUint24(t){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,t>>8),this.dataView.setUint8(this.position+2,t&255),this.position+=3},pushUint32(t){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,t),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const t=this.inspectByte();return this.position++,t},readBytes(t,e){this.assertReadLimit(),this._touch();const r=this.inspectBytes(t);return this.position+=e??t,r},readUint8(){this.assertReadLimit(),this._touch();const t=this.inspectUint8();return this.position+=1,t},readUint16(){this.assertReadLimit(),this._touch();const t=this.inspectUint16();return this.position+=2,t},readUint24(){this.assertReadLimit(),this._touch();const t=this.inspectUint24();return this.position+=3,t},readUint32(){this.assertReadLimit(),this._touch();const t=this.inspectUint32();return this.position+=4,t},get remaining(){return this.bytes.length-this.position},setPosition(t){const e=this.position;return this.assertPosition(t),this.position=t,()=>this.position=e},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const t=this.getReadCount();this.positionReadCount.set(this.position,t+1),t>0&&this.recursiveReadCount++}};function Dd(t,{recursiveReadLimit:e=8192}={}){const r=Object.create(d5);return r.bytes=t,r.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=e,r}function h5(t,e={}){typeof e.size<"u"&&Cr(t,{size:e.size});const r=et(t,e);return ut(r,e)}function p5(t,e={}){let r=t;if(typeof e.size<"u"&&(Cr(r,{size:e.size}),r=lr(r)),r.length>1||r[0]>1)throw new hv(r);return!!r[0]}function Sn(t,e={}){typeof e.size<"u"&&Cr(t,{size:e.size});const r=et(t,e);return dr(r,e)}function y5(t,e={}){let r=t;return typeof e.size<"u"&&(Cr(r,{size:e.size}),r=lr(r,{dir:"right"})),new TextDecoder().decode(r)}function ya(t,e){const r=typeof e=="string"?Jr(e):e,n=Dd(r);if(He(r)===0&&t.length>0)throw new la;if(He(e)&&He(e)<32)throw new Om({data:typeof e=="string"?e:et(e),params:t,size:He(e)});let s=0;const i=[];for(let o=0;o<t.length;++o){const a=t[o];n.setPosition(s);const[c,u]=wi(n,a,{staticPosition:0});s+=u,i.push(c)}return i}function wi(t,e,{staticPosition:r}){const n=jd(e.type);if(n){const[s,i]=n;return b5(t,{...e,type:i},{length:s,staticPosition:r})}if(e.type==="tuple")return E5(t,e,{staticPosition:r});if(e.type==="address")return m5(t);if(e.type==="bool")return g5(t);if(e.type.startsWith("bytes"))return w5(t,e,{staticPosition:r});if(e.type.startsWith("uint")||e.type.startsWith("int"))return v5(t,e);if(e.type==="string")return S5(t,{staticPosition:r});throw new uv(e.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const Tp=32,Pl=32;function m5(t){const e=t.readBytes(32);return[da(et(tb(e,-20))),32]}function b5(t,e,{length:r,staticPosition:n}){if(!r){const o=Sn(t.readBytes(Pl)),a=n+o,c=a+Tp;t.setPosition(a);const u=Sn(t.readBytes(Tp)),f=Oo(e);let l=0;const p=[];for(let d=0;d<u;++d){t.setPosition(c+(f?d*32:l));const[m,b]=wi(t,e,{staticPosition:c});l+=b,p.push(m)}return t.setPosition(n+32),[p,32]}if(Oo(e)){const o=Sn(t.readBytes(Pl)),a=n+o,c=[];for(let u=0;u<r;++u){t.setPosition(a+u*32);const[f]=wi(t,e,{staticPosition:a});c.push(f)}return t.setPosition(n+32),[c,32]}let s=0;const i=[];for(let o=0;o<r;++o){const[a,c]=wi(t,e,{staticPosition:n+s});s+=c,i.push(a)}return[i,s]}function g5(t){return[p5(t.readBytes(32),{size:32}),32]}function w5(t,e,{staticPosition:r}){const[n,s]=e.type.split("bytes");if(!s){const o=Sn(t.readBytes(32));t.setPosition(r+o);const a=Sn(t.readBytes(32));if(a===0)return t.setPosition(r+32),["0x",32];const c=t.readBytes(a);return t.setPosition(r+32),[et(c),32]}return[et(t.readBytes(Number.parseInt(s,10),32)),32]}function v5(t,e){const r=e.type.startsWith("int"),n=Number.parseInt(e.type.split("int")[1]||"256",10),s=t.readBytes(32);return[n>48?h5(s,{signed:r}):Sn(s,{signed:r}),32]}function E5(t,e,{staticPosition:r}){const n=e.components.length===0||e.components.some(({name:o})=>!o),s=n?[]:{};let i=0;if(Oo(e)){const o=Sn(t.readBytes(Pl)),a=r+o;for(let c=0;c<e.components.length;++c){const u=e.components[c];t.setPosition(a+i);const[f,l]=wi(t,u,{staticPosition:a});i+=l,s[n?c:u==null?void 0:u.name]=f}return t.setPosition(r+32),[s,32]}for(let o=0;o<e.components.length;++o){const a=e.components[o],[c,u]=wi(t,a,{staticPosition:r});s[n?o:a==null?void 0:a.name]=c,i+=u}return[s,i]}function S5(t,{staticPosition:e}){const r=Sn(t.readBytes(32)),n=e+r;t.setPosition(n);const s=Sn(t.readBytes(32));if(s===0)return t.setPosition(e+32),["",32];const i=t.readBytes(s,32),o=y5(lr(i));return t.setPosition(e+32),[o,32]}function Oo(t){var n;const{type:e}=t;if(e==="string"||e==="bytes"||e.endsWith("[]"))return!0;if(e==="tuple")return(n=t.components)==null?void 0:n.some(Oo);const r=jd(t.type);return!!(r&&Oo({...t,type:r[1]}))}function ob(t){const{abi:e,data:r}=t,n=Ns(r,0,4);if(n==="0x")throw new la;const i=[...e||[],sb,f5].find(o=>o.type==="error"&&n===ha(_r(o)));if(!i)throw new Bm(n,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:i,args:"inputs"in i&&i.inputs&&i.inputs.length>0?ya(i.inputs,Ns(r,4)):void 0,errorName:i.name}}const Qe=(t,e,r)=>JSON.stringify(t,(n,s)=>typeof s=="bigint"?s.toString():s,r);function ab({abiItem:t,args:e,includeFunctionName:r=!0,includeName:n=!1}){if("name"in t&&"inputs"in t&&t.inputs)return`${r?t.name:""}(${t.inputs.map((s,i)=>`${n&&s.name?`${s.name}: `:""}${typeof e[i]=="object"?Qe(e[i]):e[i]}`).join(", ")})`}const A5={gwei:9,wei:18},x5={ether:-9,wei:9};function cb(t,e){let r=t.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(e,"0");let[s,i]=[r.slice(0,r.length-e),r.slice(r.length-e)];return i=i.replace(/(0+)$/,""),`${n?"-":""}${s||"0"}${i?`.${i}`:""}`}function Hd(t,e="wei"){return cb(t,A5[e])}function jt(t,e="wei"){return cb(t,x5[e])}class k5 extends L{constructor({address:e}){super(`State for account "${e}" is set multiple times.`,{name:"AccountStateConflictError"})}}class T5 extends L{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function _p(t){return t.reduce((e,{slot:r,value:n})=>`${e} ${r}: ${n}
|
|
22
|
+
`),{name:"InvalidDefinitionTypeError"})}}class lv extends L{constructor(e){super(`Filter type "${e}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}let Um=class extends L{constructor({offset:e,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},Mm=class extends L{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}};class gp extends L{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${e} ${n} long.`,{name:"InvalidBytesLengthError"})}}function Hi(t,{dir:e,size:r=32}={}){return typeof t=="string"?ts(t,{dir:e,size:r}):dv(t,{dir:e,size:r})}function ts(t,{dir:e,size:r=32}={}){if(r===null)return t;const n=t.replace("0x","");if(n.length>r*2)throw new Mm({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function dv(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new Mm({size:t.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let s=0;s<r;s++){const i=e==="right";n[i?s:r-s-1]=t[i?s:t.length-s-1]}return n}let Fm=class extends L{constructor({max:e,min:r,signed:n,size:s,value:i}){super(`Number "${i}" is not in safe ${s?`${s*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}},hv=class extends L{constructor(e){super(`Bytes value "${e}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}};class pv extends L{constructor(e){super(`Hex value "${e}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}let yv=class extends L{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function lr(t,{dir:e="left"}={}){let r=typeof t=="string"?t.replace("0x",""):t,n=0;for(let s=0;s<r.length-1&&r[e==="left"?s:r.length-s-1].toString()==="0";s++)n++;return r=e==="left"?r.slice(n):r.slice(0,r.length-n),typeof t=="string"?(r.length===1&&e==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}function Cr(t,{size:e}){if(He(t)>e)throw new yv({givenSize:He(t),maxSize:e})}function ut(t,e={}){const{signed:r}=e;e.size&&Cr(t,{size:e.size});const n=BigInt(t);if(!r)return n;const s=(t.length-2)/2,i=(1n<<BigInt(s)*8n-1n)-1n;return n<=i?n:n-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function mv(t,e={}){let r=t;if(e.size&&(Cr(r,{size:e.size}),r=lr(r)),lr(r)==="0x00")return!1;if(lr(r)==="0x01")return!0;throw new pv(r)}function dr(t,e={}){return Number(ut(t,e))}const bv=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Bt(t,e={}){return typeof t=="number"||typeof t=="bigint"?Z(t,e):typeof t=="string"?Bi(t,e):typeof t=="boolean"?jm(t,e):et(t,e)}function jm(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(Cr(r,{size:e.size}),Hi(r,{size:e.size})):r}function et(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=bv[t[s]];const n=`0x${r}`;return typeof e.size=="number"?(Cr(n,{size:e.size}),Hi(n,{dir:"right",size:e.size})):n}function Z(t,e={}){const{signed:r,size:n}=e,s=BigInt(t);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<o){const c=typeof t=="bigint"?"n":"";throw new Fm({max:i?`${i}${c}`:void 0,min:`${o}${c}`,signed:r,size:n,value:`${t}${c}`})}const a=`0x${(r&&s<0?(1n<<BigInt(n*8))+BigInt(s):s).toString(16)}`;return n?Hi(a,{size:n}):a}const gv=new TextEncoder;function Bi(t,e={}){const r=gv.encode(t);return et(r,e)}const wv=new TextEncoder;function zi(t,e={}){return typeof t=="number"||typeof t=="bigint"?Ev(t,e):typeof t=="boolean"?vv(t,e):Pr(t)?Jr(t,e):_s(t,e)}function vv(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?(Cr(r,{size:e.size}),Hi(r,{size:e.size})):r}const tn={zero:48,nine:57,A:65,F:70,a:97,f:102};function wp(t){if(t>=tn.zero&&t<=tn.nine)return t-tn.zero;if(t>=tn.A&&t<=tn.F)return t-(tn.A-10);if(t>=tn.a&&t<=tn.f)return t-(tn.a-10)}function Jr(t,e={}){let r=t;e.size&&(Cr(r,{size:e.size}),r=Hi(r,{dir:"right",size:e.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const s=n.length/2,i=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=wp(n.charCodeAt(a++)),u=wp(n.charCodeAt(a++));if(c===void 0||u===void 0)throw new L(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);i[o]=c*16+u}return i}function Ev(t,e){const r=Z(t,e);return Jr(r)}function _s(t,e={}){const r=wv.encode(t);return typeof e.size=="number"?(Cr(r,{size:e.size}),Hi(r,{dir:"right",size:e.size})):r}const $a=BigInt(2**32-1),vp=BigInt(32);function Lm(t,e=!1){return e?{h:Number(t&$a),l:Number(t>>vp&$a)}:{h:Number(t>>vp&$a)|0,l:Number(t&$a)|0}}function Sv(t,e=!1){const r=t.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=Lm(t[i],e);[n[i],s[i]]=[o,a]}return[n,s]}const Dm=(t,e,r)=>t>>>r|e<<32-r,Hm=(t,e,r)=>t<<32-r|e>>>r,Av=(t,e,r)=>t<<64-r|e>>>r-32,xv=(t,e,r)=>t>>>r-32|e<<64-r,kv=(t,e)=>e,Tv=(t,e)=>t,_v=(t,e,r)=>t<<r|e>>>32-r,Pv=(t,e,r)=>e<<r|t>>>32-r,Iv=(t,e,r)=>e<<r-32|t>>>64-r,Ov=(t,e,r)=>t<<r-32|e>>>64-r;function zm(t,e,r,n){const s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const Vm=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),qm=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,si=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Bv(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ss(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function is(t,...e){if(!Bv(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Cv(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ss(t.outputLen),ss(t.blockLen)}function os(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Nd(t,e){is(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Io(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ir(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Pu(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Mr(t,e){return t<<32-e|t>>>e}function Ra(t,e){return t<<e|t>>>32-e>>>0}const Gm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Wm(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const dn=Gm?t=>t:t=>Wm(t);function $v(t){for(let e=0;e<t.length;e++)t[e]=Wm(t[e]);return t}const Kn=Gm?t=>t:$v;function Rv(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function En(t){return typeof t=="string"&&(t=Rv(t)),is(t),t}function Nv(...t){let e=0;for(let n=0;n<t.length;n++){const s=t[n];is(s),e+=s.length}const r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){const i=t[n];r.set(i,s),s+=i.length}return r}class Rc{}function Nc(t){const e=n=>t().update(En(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Uv(t){const e=(n,s)=>t(s).update(En(n)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}function Mv(t=32){if(si&&typeof si.getRandomValues=="function")return si.getRandomValues(new Uint8Array(t));if(si&&typeof si.randomBytes=="function")return Uint8Array.from(si.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const Fv=BigInt(0),to=BigInt(1),jv=BigInt(2),Lv=BigInt(7),Dv=BigInt(256),Hv=BigInt(113),Km=[],Zm=[],Ym=[];for(let t=0,e=to,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],Km.push(2*(5*n+r)),Zm.push((t+1)*(t+2)/2%64);let s=Fv;for(let i=0;i<7;i++)e=(e<<to^(e>>Lv)*Hv)%Dv,e&jv&&(s^=to<<(to<<BigInt(i))-to);Ym.push(s)}const Xm=Sv(Ym,!0),zv=Xm[0],Vv=Xm[1],Ep=(t,e,r)=>r>32?Iv(t,e,r):_v(t,e,r),Sp=(t,e,r)=>r>32?Ov(t,e,r):Pv(t,e,r);function qv(t,e=24){const r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=r[c],f=r[c+1],l=Ep(u,f,1)^r[a],p=Sp(u,f,1)^r[a+1];for(let d=0;d<50;d+=10)t[o+d]^=l,t[o+d+1]^=p}let s=t[2],i=t[3];for(let o=0;o<24;o++){const a=Zm[o],c=Ep(s,i,a),u=Sp(s,i,a),f=Km[o];s=t[f],i=t[f+1],t[f]=c,t[f+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=zv[n],t[1]^=Vv[n]}Ir(r)}class Ud extends Rc{constructor(e,r,n,s=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=s,this.rounds=i,ss(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Io(this.state)}clone(){return this._cloneInto()}keccak(){Kn(this.state32),qv(this.state32,this.rounds),Kn(this.state32),this.posOut=0,this.pos=0}update(e){os(this),e=En(e),is(e);const{blockLen:r,state:n}=this,s=e.length;for(let i=0;i<s;){const o=Math.min(r-this.pos,s-i);for(let a=0;a<o;a++)n[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:n,blockLen:s}=this;e[n]^=r,r&128&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){os(this,!1),is(e),this.finish();const r=this.state,{blockLen:n}=this;for(let s=0,i=e.length;s<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ss(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Nd(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Ir(this.state)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:s,rounds:i,enableXOF:o}=this;return e||(e=new Ud(r,n,s,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Gv=(t,e,r)=>Nc(()=>new Ud(e,t,r)),Jm=Gv(1,136,256/8);function ht(t,e){const r=e||"hex",n=Jm(Pr(t,{strict:!1})?zi(t):t);return r==="bytes"?n:Bt(n)}const Wv=t=>ht(zi(t));function Kv(t){return Wv(t)}function Zv(t){let e=!0,r="",n=0,s="",i=!1;for(let o=0;o<t.length;o++){const a=t[o];if(["(",")",","].includes(a)&&(e=!0),a==="("&&n++,a===")"&&n--,!!e){if(n===0){if(a===" "&&["event","function",""].includes(s))s="";else if(s+=a,a===")"){i=!0;break}continue}if(a===" "){t[o-1]!==","&&r!==","&&r!==",("&&(r="",e=!1);continue}s+=a,r+=a}}if(!i)throw new L("Unable to normalize signature.");return s}const Yv=t=>{const e=typeof t=="string"?t:l6(t);return Zv(e)};function Qm(t){return Kv(Yv(t))}const Uc=Qm;let $t=class extends L{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}},Mc=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}};const Iu=new Mc(8192);function da(t,e){if(Iu.has(`${t}.${e}`))return Iu.get(`${t}.${e}`);const r=t.substring(2).toLowerCase(),n=ht(_s(r),"bytes"),s=r.split("");for(let o=0;o<40;o+=2)n[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(n[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const i=`0x${s.join("")}`;return Iu.set(`${t}.${e}`,i),i}function Md(t,e){if(!at(t,{strict:!1}))throw new $t({address:t});return da(t,e)}const Xv=/^0x[a-fA-F0-9]{40}$/,Ou=new Mc(8192);function at(t,e){const{strict:r=!0}=e??{},n=`${t}.${r}`;if(Ou.has(n))return Ou.get(n);const s=Xv.test(t)?t.toLowerCase()===t?!0:r?da(t)===t:!0:!1;return Ou.set(n,s),s}function Kt(t){return typeof t[0]=="string"?$r(t):Jv(t)}function Jv(t){let e=0;for(const s of t)e+=s.length;const r=new Uint8Array(e);let n=0;for(const s of t)r.set(s,n),n+=s.length;return r}function $r(t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function Ns(t,e,r,{strict:n}={}){return Pr(t,{strict:!1})?Pl(t,e,r,{strict:n}):rb(t,e,r,{strict:n})}function eb(t,e){if(typeof e=="number"&&e>0&&e>He(t)-1)throw new Um({offset:e,position:"start",size:He(t)})}function tb(t,e,r){if(typeof e=="number"&&typeof r=="number"&&He(t)!==r-e)throw new Um({offset:r,position:"end",size:He(t)})}function rb(t,e,r,{strict:n}={}){eb(t,e);const s=t.slice(e,r);return n&&tb(s,e,r),s}function Pl(t,e,r,{strict:n}={}){eb(t,e);const s=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return n&&tb(s,e,r),s}const Qv=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,nb=/^(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 fs(t,e){if(t.length!==e.length)throw new rv({expectedLength:t.length,givenLength:e.length});const r=e5({params:t,values:e}),n=jd(r);return n.length===0?"0x":n}function e5({params:t,values:e}){const r=[];for(let n=0;n<t.length;n++)r.push(Fd({param:t[n],value:e[n]}));return r}function Fd({param:t,value:e}){const r=Ld(t.type);if(r){const[n,s]=r;return r5(e,{length:n,param:{...t,type:s}})}if(t.type==="tuple")return a5(e,{param:t});if(t.type==="address")return t5(e);if(t.type==="bool")return s5(e);if(t.type.startsWith("uint")||t.type.startsWith("int")){const n=t.type.startsWith("int"),[,,s="256"]=nb.exec(t.type)??[];return i5(e,{signed:n,size:Number(s)})}if(t.type.startsWith("bytes"))return n5(e,{param:t});if(t.type==="string")return o5(e);throw new cv(t.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function jd(t){let e=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?e+=32:e+=He(a)}const r=[],n=[];let s=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?(r.push(Z(e+s,{size:32})),n.push(a),s+=He(a)):r.push(a)}return Kt([...r,...n])}function t5(t){if(!at(t))throw new $t({address:t});return{dynamic:!1,encoded:ts(t.toLowerCase())}}function r5(t,{length:e,param:r}){const n=e===null;if(!Array.isArray(t))throw new Nm(t);if(!n&&t.length!==e)throw new ev({expectedLength:e,givenLength:t.length,type:`${r.type}[${e}]`});let s=!1;const i=[];for(let o=0;o<t.length;o++){const a=Fd({param:r,value:t[o]});a.dynamic&&(s=!0),i.push(a)}if(n||s){const o=jd(i);if(n){const a=Z(i.length,{size:32});return{dynamic:!0,encoded:i.length>0?Kt([a,o]):a}}if(s)return{dynamic:!0,encoded:o}}return{dynamic:!1,encoded:Kt(i.map(({encoded:o})=>o))}}function n5(t,{param:e}){const[,r]=e.type.split("bytes"),n=He(t);if(!r){let s=t;return n%32!==0&&(s=ts(s,{dir:"right",size:Math.ceil((t.length-2)/2/32)*32})),{dynamic:!0,encoded:Kt([ts(Z(n,{size:32})),s])}}if(n!==Number.parseInt(r,10))throw new tv({expectedSize:Number.parseInt(r,10),value:t});return{dynamic:!1,encoded:ts(t,{dir:"right"})}}function s5(t){if(typeof t!="boolean")throw new L(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:ts(jm(t))}}function i5(t,{signed:e,size:r=256}){if(typeof r=="number"){const n=2n**(BigInt(r)-(e?1n:0n))-1n,s=e?-n-1n:0n;if(t>n||t<s)throw new Fm({max:n.toString(),min:s.toString(),signed:e,size:r/8,value:t.toString()})}return{dynamic:!1,encoded:Z(t,{size:32,signed:e})}}function o5(t){const e=Bi(t),r=Math.ceil(He(e)/32),n=[];for(let s=0;s<r;s++)n.push(ts(Ns(e,s*32,(s+1)*32),{dir:"right"}));return{dynamic:!0,encoded:Kt([ts(Z(He(e),{size:32})),...n])}}function a5(t,{param:e}){let r=!1;const n=[];for(let s=0;s<e.components.length;s++){const i=e.components[s],o=Array.isArray(t)?s:i.name,a=Fd({param:i,value:t[o]});n.push(a),a.dynamic&&(r=!0)}return{dynamic:r,encoded:r?jd(n):Kt(n.map(({encoded:s})=>s))}}function Ld(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}const ha=t=>Ns(Qm(t),0,4);function Zs(t){const{abi:e,args:r=[],name:n}=t,s=Pr(n,{strict:!1}),i=e.filter(a=>s?a.type==="function"?ha(a)===n:a.type==="event"?Uc(a)===n:!1:"name"in a&&a.name===n);if(i.length===0)return;if(i.length===1)return i[0];let o;for(const a of i){if(!("inputs"in a))continue;if(!r||r.length===0){if(!a.inputs||a.inputs.length===0)return a;continue}if(!a.inputs||a.inputs.length===0||a.inputs.length!==r.length)continue;if(r.every((u,f)=>{const l="inputs"in a&&a.inputs[f];return l?Il(u,l):!1})){if(o&&"inputs"in o&&o.inputs){const u=sb(a.inputs,o.inputs,r);if(u)throw new ov({abiItem:a,type:u[0]},{abiItem:o,type:u[1]})}o=a}}return o||i[0]}function Il(t,e){const r=typeof t,n=e.type;switch(n){case"address":return at(t,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in e?Object.values(e.components).every((s,i)=>Il(Object.values(t)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||t instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(t)&&t.every(s=>Il(s,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function sb(t,e,r){for(const n in t){const s=t[n],i=e[n];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return sb(s.components,i.components,r[n]);const o=[s.type,i.type];if(o.includes("address")&&o.includes("bytes20")?!0:o.includes("address")&&o.includes("string")?at(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?at(r[n],{strict:!1}):!1)return o}}const Ap="/docs/contract/encodeEventTopics";function pa(t){var c;const{abi:e,eventName:r,args:n}=t;let s=e[0];if(r){const u=Zs({abi:e,name:r});if(!u)throw new bp(r,{docsPath:Ap});s=u}if(s.type!=="event")throw new bp(void 0,{docsPath:Ap});const i=_r(s),o=Uc(i);let a=[];if(n&&"inputs"in s){const u=(c=s.inputs)==null?void 0:c.filter(l=>"indexed"in l&&l.indexed),f=Array.isArray(n)?n:Object.values(n).length>0?(u==null?void 0:u.map(l=>n[l.name]))??[]:[];f.length>0&&(a=(u==null?void 0:u.map((l,p)=>Array.isArray(f[p])?f[p].map((d,m)=>xp({param:l,value:f[p][m]})):typeof f[p]<"u"&&f[p]!==null?xp({param:l,value:f[p]}):null))??[])}return[o,...a]}function xp({param:t,value:e}){if(t.type==="string"||t.type==="bytes")return ht(zi(e));if(t.type==="tuple"||t.type.match(/^(.*)\[(\d+)?\]$/))throw new lv(t.type);return fs([t],[e])}function Fc(t,{method:e}){var n,s;const r={};return t.transport.type==="fallback"&&((s=(n=t.transport).onResponse)==null||s.call(n,({method:i,response:o,status:a,transport:c})=>{a==="success"&&e===i&&(r[o]=c.request)})),i=>r[i]||t.request}async function Dd(t,e){const{address:r,abi:n,args:s,eventName:i,fromBlock:o,strict:a,toBlock:c}=e,u=Fc(t,{method:"eth_newFilter"}),f=i?pa({abi:n,args:s,eventName:i}):void 0,l=await t.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof o=="bigint"?Z(o):o,toBlock:typeof c=="bigint"?Z(c):c,topics:f}]});return{abi:n,args:s,eventName:i,id:l,request:u(l),strict:!!a,type:"event"}}function Ze(t){return typeof t=="string"?{address:t,type:"json-rpc"}:t}const kp="/docs/contract/encodeFunctionData";function c5(t){const{abi:e,args:r,functionName:n}=t;let s=e[0];if(n){const i=Zs({abi:e,args:r,name:n});if(!i)throw new Oi(n,{docsPath:kp});s=i}if(s.type!=="function")throw new Oi(void 0,{docsPath:kp});return{abi:[s],functionName:ha(_r(s))}}function Jt(t){const{args:e}=t,{abi:r,functionName:n}=(()=>{var a;return t.abi.length===1&&((a=t.functionName)!=null&&a.startsWith("0x"))?t:c5(t)})(),s=r[0],i=n,o="inputs"in s&&s.inputs?fs(s.inputs,e??[]):void 0;return $r([i,o??"0x"])}const u5={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."},ib={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},f5={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};let Tp=class extends L{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`,{name:"NegativeOffsetError"})}},ob=class extends L{constructor({length:e,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${e}\`).`,{name:"PositionOutOfBoundsError"})}},l5=class extends L{constructor({count:e,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${e}\`).`,{name:"RecursiveReadLimitExceededError"})}};const d5={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 l5({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(t){if(t<0||t>this.bytes.length-1)throw new ob({length:this.bytes.length,position:t})},decrementPosition(t){if(t<0)throw new Tp({offset:t});const e=this.position-t;this.assertPosition(e),this.position=e},getReadCount(t){return this.positionReadCount.get(t||this.position)||0},incrementPosition(t){if(t<0)throw new Tp({offset:t});const e=this.position+t;this.assertPosition(e),this.position=e},inspectByte(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectBytes(t,e){const r=e??this.position;return this.assertPosition(r+t-1),this.bytes.subarray(r,r+t)},inspectUint8(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectUint16(t){const e=t??this.position;return this.assertPosition(e+1),this.dataView.getUint16(e)},inspectUint24(t){const e=t??this.position;return this.assertPosition(e+2),(this.dataView.getUint16(e)<<8)+this.dataView.getUint8(e+2)},inspectUint32(t){const e=t??this.position;return this.assertPosition(e+3),this.dataView.getUint32(e)},pushByte(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushBytes(t){this.assertPosition(this.position+t.length-1),this.bytes.set(t,this.position),this.position+=t.length},pushUint8(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushUint16(t){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,t),this.position+=2},pushUint24(t){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,t>>8),this.dataView.setUint8(this.position+2,t&255),this.position+=3},pushUint32(t){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,t),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const t=this.inspectByte();return this.position++,t},readBytes(t,e){this.assertReadLimit(),this._touch();const r=this.inspectBytes(t);return this.position+=e??t,r},readUint8(){this.assertReadLimit(),this._touch();const t=this.inspectUint8();return this.position+=1,t},readUint16(){this.assertReadLimit(),this._touch();const t=this.inspectUint16();return this.position+=2,t},readUint24(){this.assertReadLimit(),this._touch();const t=this.inspectUint24();return this.position+=3,t},readUint32(){this.assertReadLimit(),this._touch();const t=this.inspectUint32();return this.position+=4,t},get remaining(){return this.bytes.length-this.position},setPosition(t){const e=this.position;return this.assertPosition(t),this.position=t,()=>this.position=e},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const t=this.getReadCount();this.positionReadCount.set(this.position,t+1),t>0&&this.recursiveReadCount++}};function Hd(t,{recursiveReadLimit:e=8192}={}){const r=Object.create(d5);return r.bytes=t,r.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=e,r}function h5(t,e={}){typeof e.size<"u"&&Cr(t,{size:e.size});const r=et(t,e);return ut(r,e)}function p5(t,e={}){let r=t;if(typeof e.size<"u"&&(Cr(r,{size:e.size}),r=lr(r)),r.length>1||r[0]>1)throw new hv(r);return!!r[0]}function Sn(t,e={}){typeof e.size<"u"&&Cr(t,{size:e.size});const r=et(t,e);return dr(r,e)}function y5(t,e={}){let r=t;return typeof e.size<"u"&&(Cr(r,{size:e.size}),r=lr(r,{dir:"right"})),new TextDecoder().decode(r)}function ya(t,e){const r=typeof e=="string"?Jr(e):e,n=Hd(r);if(He(r)===0&&t.length>0)throw new la;if(He(e)&&He(e)<32)throw new Bm({data:typeof e=="string"?e:et(e),params:t,size:He(e)});let s=0;const i=[];for(let o=0;o<t.length;++o){const a=t[o];n.setPosition(s);const[c,u]=wi(n,a,{staticPosition:0});s+=u,i.push(c)}return i}function wi(t,e,{staticPosition:r}){const n=Ld(e.type);if(n){const[s,i]=n;return b5(t,{...e,type:i},{length:s,staticPosition:r})}if(e.type==="tuple")return E5(t,e,{staticPosition:r});if(e.type==="address")return m5(t);if(e.type==="bool")return g5(t);if(e.type.startsWith("bytes"))return w5(t,e,{staticPosition:r});if(e.type.startsWith("uint")||e.type.startsWith("int"))return v5(t,e);if(e.type==="string")return S5(t,{staticPosition:r});throw new uv(e.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const _p=32,Ol=32;function m5(t){const e=t.readBytes(32);return[da(et(rb(e,-20))),32]}function b5(t,e,{length:r,staticPosition:n}){if(!r){const o=Sn(t.readBytes(Ol)),a=n+o,c=a+_p;t.setPosition(a);const u=Sn(t.readBytes(_p)),f=Oo(e);let l=0;const p=[];for(let d=0;d<u;++d){t.setPosition(c+(f?d*32:l));const[m,b]=wi(t,e,{staticPosition:c});l+=b,p.push(m)}return t.setPosition(n+32),[p,32]}if(Oo(e)){const o=Sn(t.readBytes(Ol)),a=n+o,c=[];for(let u=0;u<r;++u){t.setPosition(a+u*32);const[f]=wi(t,e,{staticPosition:a});c.push(f)}return t.setPosition(n+32),[c,32]}let s=0;const i=[];for(let o=0;o<r;++o){const[a,c]=wi(t,e,{staticPosition:n+s});s+=c,i.push(a)}return[i,s]}function g5(t){return[p5(t.readBytes(32),{size:32}),32]}function w5(t,e,{staticPosition:r}){const[n,s]=e.type.split("bytes");if(!s){const o=Sn(t.readBytes(32));t.setPosition(r+o);const a=Sn(t.readBytes(32));if(a===0)return t.setPosition(r+32),["0x",32];const c=t.readBytes(a);return t.setPosition(r+32),[et(c),32]}return[et(t.readBytes(Number.parseInt(s,10),32)),32]}function v5(t,e){const r=e.type.startsWith("int"),n=Number.parseInt(e.type.split("int")[1]||"256",10),s=t.readBytes(32);return[n>48?h5(s,{signed:r}):Sn(s,{signed:r}),32]}function E5(t,e,{staticPosition:r}){const n=e.components.length===0||e.components.some(({name:o})=>!o),s=n?[]:{};let i=0;if(Oo(e)){const o=Sn(t.readBytes(Ol)),a=r+o;for(let c=0;c<e.components.length;++c){const u=e.components[c];t.setPosition(a+i);const[f,l]=wi(t,u,{staticPosition:a});i+=l,s[n?c:u==null?void 0:u.name]=f}return t.setPosition(r+32),[s,32]}for(let o=0;o<e.components.length;++o){const a=e.components[o],[c,u]=wi(t,a,{staticPosition:r});s[n?o:a==null?void 0:a.name]=c,i+=u}return[s,i]}function S5(t,{staticPosition:e}){const r=Sn(t.readBytes(32)),n=e+r;t.setPosition(n);const s=Sn(t.readBytes(32));if(s===0)return t.setPosition(e+32),["",32];const i=t.readBytes(s,32),o=y5(lr(i));return t.setPosition(e+32),[o,32]}function Oo(t){var n;const{type:e}=t;if(e==="string"||e==="bytes"||e.endsWith("[]"))return!0;if(e==="tuple")return(n=t.components)==null?void 0:n.some(Oo);const r=Ld(t.type);return!!(r&&Oo({...t,type:r[1]}))}function ab(t){const{abi:e,data:r}=t,n=Ns(r,0,4);if(n==="0x")throw new la;const i=[...e||[],ib,f5].find(o=>o.type==="error"&&n===ha(_r(o)));if(!i)throw new Cm(n,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:i,args:"inputs"in i&&i.inputs&&i.inputs.length>0?ya(i.inputs,Ns(r,4)):void 0,errorName:i.name}}const Qe=(t,e,r)=>JSON.stringify(t,(n,s)=>typeof s=="bigint"?s.toString():s,r);function cb({abiItem:t,args:e,includeFunctionName:r=!0,includeName:n=!1}){if("name"in t&&"inputs"in t&&t.inputs)return`${r?t.name:""}(${t.inputs.map((s,i)=>`${n&&s.name?`${s.name}: `:""}${typeof e[i]=="object"?Qe(e[i]):e[i]}`).join(", ")})`}const A5={gwei:9,wei:18},x5={ether:-9,wei:9};function ub(t,e){let r=t.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(e,"0");let[s,i]=[r.slice(0,r.length-e),r.slice(r.length-e)];return i=i.replace(/(0+)$/,""),`${n?"-":""}${s||"0"}${i?`.${i}`:""}`}function zd(t,e="wei"){return ub(t,A5[e])}function jt(t,e="wei"){return ub(t,x5[e])}class k5 extends L{constructor({address:e}){super(`State for account "${e}" is set multiple times.`,{name:"AccountStateConflictError"})}}class T5 extends L{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function Pp(t){return t.reduce((e,{slot:r,value:n})=>`${e} ${r}: ${n}
|
|
23
23
|
`,"")}function _5(t){return t.reduce((e,{address:r,...n})=>{let s=`${e} ${r}:
|
|
24
24
|
`;return n.nonce&&(s+=` nonce: ${n.nonce}
|
|
25
25
|
`),n.balance&&(s+=` balance: ${n.balance}
|
|
26
26
|
`),n.code&&(s+=` code: ${n.code}
|
|
27
27
|
`),n.state&&(s+=` state:
|
|
28
|
-
`,s+=
|
|
29
|
-
`,s+=
|
|
28
|
+
`,s+=Pp(n.state)),n.stateDiff&&(s+=` stateDiff:
|
|
29
|
+
`,s+=Pp(n.stateDiff)),s},` State Override:
|
|
30
30
|
`).slice(0,-1)}function ma(t){const e=Object.entries(t).map(([n,s])=>s===void 0||s===!1?null:[n,s]).filter(Boolean),r=e.reduce((n,[s])=>Math.max(n,s.length),0);return e.map(([n,s])=>` ${`${n}:`.padEnd(r+1)} ${s}`).join(`
|
|
31
31
|
`)}class P5 extends L{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 I5 extends L{constructor({v:e}){super(`Invalid \`v\` value "${e}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class O5 extends L{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",ma(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class B5 extends L{constructor({storageKey:e}){super(`Size for storage key "${e}" is invalid. Expected 32 bytes. Got ${Math.floor((e.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}class C5 extends L{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:f,to:l,value:p}){var m;const d=ma({chain:s&&`${s==null?void 0:s.name} (id: ${s==null?void 0:s.id})`,from:r==null?void 0:r.address,to:l,value:typeof p<"u"&&`${
|
|
33
|
-
${_5(d)}`),super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Raw Call Arguments:",b].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class
|
|
34
|
-
`):`The contract function "${n}" reverted.`,{cause:i,metaMessages:a,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=o,this.raw=r,this.reason=c,this.signature=u}}class N5 extends L{constructor({functionName:e}){super(`The contract function "${e}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${e}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError"})}}class U5 extends L{constructor({factory:e}){super(`Deployment for counterfactual contract call failed${e?` for factory "${e}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}}class
|
|
32
|
+
`),{name:"FeeConflictError"})}}class I5 extends L{constructor({v:e}){super(`Invalid \`v\` value "${e}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class O5 extends L{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",ma(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class B5 extends L{constructor({storageKey:e}){super(`Size for storage key "${e}" is invalid. Expected 32 bytes. Got ${Math.floor((e.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}class C5 extends L{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:f,to:l,value:p}){var m;const d=ma({chain:s&&`${s==null?void 0:s.name} (id: ${s==null?void 0:s.id})`,from:r==null?void 0:r.address,to:l,value:typeof p<"u"&&`${zd(p)} ${((m=s==null?void 0:s.nativeCurrency)==null?void 0:m.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${jt(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${jt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${jt(u)} gwei`,nonce:f});super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Request Arguments:",d].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class fb extends L{constructor({blockHash:e,blockNumber:r,blockTag:n,hash:s,index:i}){let o="Transaction";n&&i!==void 0&&(o=`Transaction at block time "${n}" at index "${i}"`),e&&i!==void 0&&(o=`Transaction at block hash "${e}" at index "${i}"`),r&&i!==void 0&&(o=`Transaction at block number "${r}" at index "${i}"`),s&&(o=`Transaction with hash "${s}"`),super(`${o} could not be found.`,{name:"TransactionNotFoundError"})}}class lb extends L{constructor({hash:e}){super(`Transaction receipt with hash "${e}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class $5 extends L{constructor({hash:e}){super(`Timed out while waiting for transaction with hash "${e}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}const R5=t=>t,jc=t=>t;class db extends L{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:f,to:l,value:p,stateOverride:d}){var E;const m=r?Ze(r):void 0;let b=ma({from:m==null?void 0:m.address,to:l,value:typeof p<"u"&&`${zd(p)} ${((E=s==null?void 0:s.nativeCurrency)==null?void 0:E.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${jt(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${jt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${jt(u)} gwei`,nonce:f});d&&(b+=`
|
|
33
|
+
${_5(d)}`),super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Raw Call Arguments:",b].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class hb extends L{constructor(e,{abi:r,args:n,contractAddress:s,docsPath:i,functionName:o,sender:a}){const c=Zs({abi:r,args:n,name:o}),u=c?cb({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,f=c?_r(c,{includeName:!0}):void 0,l=ma({address:s&&R5(s),function:f,args:u&&u!=="()"&&`${[...Array((o==null?void 0:o.length)??0).keys()].map(()=>" ").join("")}${u}`,sender:a});super(e.shortMessage||`An unknown error occurred while executing the contract function "${o}".`,{cause:e,docsPath:i,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],l&&"Contract Call:",l].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=r,this.args=n,this.cause=e,this.contractAddress=s,this.functionName=o,this.sender=a}}class Bl extends L{constructor({abi:e,data:r,functionName:n,message:s}){let i,o,a,c;if(r&&r!=="0x")try{o=ab({abi:e,data:r});const{abiItem:f,errorName:l,args:p}=o;if(l==="Error")c=p[0];else if(l==="Panic"){const[d]=p;c=u5[d]}else{const d=f?_r(f,{includeName:!0}):void 0,m=f&&p?cb({abiItem:f,args:p,includeFunctionName:!1,includeName:!1}):void 0;a=[d?`Error: ${d}`:"",m&&m!=="()"?` ${[...Array((l==null?void 0:l.length)??0).keys()].map(()=>" ").join("")}${m}`:""]}}catch(f){i=f}else s&&(c=s);let u;i instanceof Cm&&(u=i.signature,a=[`Unable to decode signature "${u}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${u}.`]),super(c&&c!=="execution reverted"||u?[`The contract function "${n}" reverted with the following ${u?"signature":"reason"}:`,c||u].join(`
|
|
34
|
+
`):`The contract function "${n}" reverted.`,{cause:i,metaMessages:a,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=o,this.raw=r,this.reason=c,this.signature=u}}class N5 extends L{constructor({functionName:e}){super(`The contract function "${e}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${e}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError"})}}class U5 extends L{constructor({factory:e}){super(`Deployment for counterfactual contract call failed${e?` for factory "${e}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}}class Lc extends L{constructor({data:e,message:r}){super(r||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e}}class vi extends L{constructor({body:e,cause:r,details:n,headers:s,status:i,url:o}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[i&&`Status: ${i}`,`URL: ${jc(o)}`,e&&`Request body: ${Qe(e)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=e,this.headers=s,this.status=i,this.url=o}}class Vd extends L{constructor({body:e,error:r,url:n}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[`URL: ${jc(n)}`,`Request body: ${Qe(e)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=r.code,this.data=r.data}}class Ip extends L{constructor({body:e,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${jc(r)}`,`Request body: ${Qe(e)}`],name:"TimeoutError"})}}const M5=-1;class Dt extends L{constructor(e,{code:r,docsPath:n,metaMessages:s,name:i,shortMessage:o}){super(o,{cause:e,docsPath:n,metaMessages:s||(e==null?void 0:e.metaMessages),name:i||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i||e.name,this.code=e instanceof Vd?e.code:r??M5}}class Qt extends Dt{constructor(e,r){super(e,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}}class Bo extends Dt{constructor(e){super(e,{code:Bo.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(Bo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class Co extends Dt{constructor(e){super(e,{code:Co.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(Co,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class $o extends Dt{constructor(e,{method:r}={}){super(e,{code:$o.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}}Object.defineProperty($o,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class Ro extends Dt{constructor(e){super(e,{code:Ro.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
|
|
35
35
|
`)})}}Object.defineProperty(Ro,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class Us extends Dt{constructor(e){super(e,{code:Us.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(Us,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class Ms extends Dt{constructor(e){super(e,{code:Ms.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
|
|
36
|
-
`)})}}Object.defineProperty(Ms,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class No extends Dt{constructor(e){super(e,{code:No.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(No,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class Uo extends Dt{constructor(e){super(e,{code:Uo.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(Uo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class Mo extends Dt{constructor(e){super(e,{code:Mo.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(Mo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class vs extends Dt{constructor(e,{method:r}={}){super(e,{code:vs.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}}Object.defineProperty(vs,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class Ci extends Dt{constructor(e){super(e,{code:Ci.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(Ci,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class Fo extends Dt{constructor(e){super(e,{code:Fo.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(Fo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Ei extends Qt{constructor(e){super(e,{code:Ei.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Ei,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class jo extends Qt{constructor(e){super(e,{code:jo.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(jo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class Lo extends Qt{constructor(e,{method:r}={}){super(e,{code:Lo.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}}Object.defineProperty(Lo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Do extends Qt{constructor(e){super(e,{code:Do.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Do,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class Ho extends Qt{constructor(e){super(e,{code:Ho.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Ho,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class zo extends Qt{constructor(e){super(e,{code:zo.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(zo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class $i extends Qt{constructor(e){super(e,{code:$i.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty($i,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class Vo extends Qt{constructor(e){super(e,{code:Vo.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(Vo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class qo extends Qt{constructor(e){super(e,{code:qo.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(qo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class Go extends Qt{constructor(e){super(e,{code:Go.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(Go,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class Wo extends Qt{constructor(e){super(e,{code:Wo.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(Wo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class Ko extends Qt{constructor(e){super(e,{code:Ko.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(Ko,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class Ri extends Qt{constructor(e){super(e,{code:Ri.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(Ri,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class F5 extends Dt{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const j5=3;function Fs(t,{abi:e,address:r,args:n,docsPath:s,functionName:i,sender:o}){const a=t instanceof jc?t:t instanceof L?t.walk(m=>"data"in m)||t.walk():{},{code:c,data:u,details:f,message:l,shortMessage:p}=a,d=t instanceof la?new N5({functionName:i}):[j5,Us.code].includes(c)&&(u||f||l||p)?new Il({abi:e,data:typeof u=="object"?u.data:u,functionName:i,message:a instanceof zd?f:p??l}):t;return new db(d,{abi:e,args:n,contractAddress:r,docsPath:s,functionName:i,sender:o})}function L5(t){const e=ht(`0x${t.substring(4)}`).substring(26);return da(`0x${e}`)}async function D5({hash:t,signature:e}){const r=Pr(t)?t:Bt(t),{secp256k1:n}=await Promise.resolve().then(()=>vx);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:f,v:l,yParity:p}=e,d=Number(p??l),m=Ip(d);return new n.Signature(ut(u),ut(f)).addRecoveryBit(m)}const o=Pr(e)?e:Bt(e);if(He(o)!==65)throw new Error("invalid signature length");const a=dr(`0x${o.slice(130)}`),c=Ip(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Ip(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function hb({hash:t,signature:e}){return L5(await D5({hash:t,signature:e}))}function as(t,e="hex"){const r=pb(t),n=Dd(new Uint8Array(r.length));return r.encode(n),e==="hex"?et(n.bytes):n.bytes}function pb(t){return Array.isArray(t)?H5(t.map(e=>pb(e))):z5(t)}function H5(t){const e=t.reduce((s,i)=>s+i.length,0),r=yb(e);return{length:e<=55?1+e:1+r+e,encode(s){e<=55?s.pushByte(192+e):(s.pushByte(247+r),r===1?s.pushUint8(e):r===2?s.pushUint16(e):r===3?s.pushUint24(e):s.pushUint32(e));for(const{encode:i}of t)i(s)}}}function z5(t){const e=typeof t=="string"?Jr(t):t,r=yb(e.length);return{length:e.length===1&&e[0]<128?1:e.length<=55?1+e.length:1+r+e.length,encode(s){e.length===1&&e[0]<128?s.pushBytes(e):e.length<=55?(s.pushByte(128+e.length),s.pushBytes(e)):(s.pushByte(183+r),r===1?s.pushUint8(e.length):r===2?s.pushUint16(e.length):r===3?s.pushUint24(e.length):s.pushUint32(e.length),s.pushBytes(e))}}}function yb(t){if(t<2**8)return 1;if(t<2**16)return 2;if(t<2**24)return 3;if(t<2**32)return 4;throw new L("Length is too large.")}function V5(t){const{chainId:e,nonce:r,to:n}=t,s=t.contractAddress??t.address,i=ht($r(["0x05",as([e?Z(e):"0x",s,r?Z(r):"0x"])]));return n==="bytes"?Jr(i):i}async function Vd(t){const{authorization:e,signature:r}=t;return hb({hash:V5(e),signature:r??e})}class q5 extends L{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:f,to:l,value:p}){var m;const d=ma({from:r==null?void 0:r.address,to:l,value:typeof p<"u"&&`${Hd(p)} ${((m=s==null?void 0:s.nativeCurrency)==null?void 0:m.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${jt(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${jt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${jt(u)} gwei`,nonce:f});super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",d].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class mi extends L{constructor({cause:e,message:r}={}){var s;const n=(s=r==null?void 0:r.replace("execution reverted: ",""))==null?void 0:s.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(mi,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(mi,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});class js extends L{constructor({cause:e,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${jt(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(js,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class Ol extends L{constructor({cause:e,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${jt(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}}Object.defineProperty(Ol,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});class Bl extends L{constructor({cause:e,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:e,name:"NonceTooHighError"})}}Object.defineProperty(Bl,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class Cl extends L{constructor({cause:e,nonce:r}={}){super([`Nonce provided for the transaction ${r?`(${r}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
|
|
37
|
-
`),{cause:e,name:"NonceTooLowError"})}}Object.defineProperty(
|
|
38
|
-
`),{cause:e,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}}Object.defineProperty(
|
|
39
|
-
`),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(Zo,"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 ba extends L{constructor({cause:e}){super(`An error occurred while executing: ${e==null?void 0:e.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}function Lc(t,e){const r=(t.details||"").toLowerCase(),n=t instanceof L?t.walk(s=>(s==null?void 0:s.code)===mi.code):t;return n instanceof L?new mi({cause:t,message:n.details}):mi.nodeMessage.test(r)?new mi({cause:t,message:t.details}):js.nodeMessage.test(r)?new js({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas}):Ol.nodeMessage.test(r)?new Ol({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas}):Bl.nodeMessage.test(r)?new Bl({cause:t,nonce:e==null?void 0:e.nonce}):Cl.nodeMessage.test(r)?new Cl({cause:t,nonce:e==null?void 0:e.nonce}):$l.nodeMessage.test(r)?new $l({cause:t,nonce:e==null?void 0:e.nonce}):Rl.nodeMessage.test(r)?new Rl({cause:t}):Nl.nodeMessage.test(r)?new Nl({cause:t,gas:e==null?void 0:e.gas}):Ul.nodeMessage.test(r)?new Ul({cause:t,gas:e==null?void 0:e.gas}):Ml.nodeMessage.test(r)?new Ml({cause:t}):Zo.nodeMessage.test(r)?new Zo({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas,maxPriorityFeePerGas:e==null?void 0:e.maxPriorityFeePerGas}):new ba({cause:t})}function G5(t,{docsPath:e,...r}){const n=(()=>{const s=Lc(t,r);return s instanceof ba?t:s})();return new q5(n,{docsPath:e,...r})}function Dc(t,{format:e}){if(!e)return{};const r={};function n(i){const o=Object.keys(i);for(const a of o)a in t&&(r[a]=t[a]),i[a]&&typeof i[a]=="object"&&!Array.isArray(i[a])&&n(i[a])}const s=e(t||{});return n(s),r}function qd(t,e){return({exclude:r,format:n})=>({exclude:r,format:s=>{const i=e(s);if(r)for(const o of r)delete i[o];return{...i,...n(s)}},type:t})}const W5={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function Vi(t){const e={};return typeof t.authorizationList<"u"&&(e.authorizationList=K5(t.authorizationList)),typeof t.accessList<"u"&&(e.accessList=t.accessList),typeof t.blobVersionedHashes<"u"&&(e.blobVersionedHashes=t.blobVersionedHashes),typeof t.blobs<"u"&&(typeof t.blobs[0]!="string"?e.blobs=t.blobs.map(r=>et(r)):e.blobs=t.blobs),typeof t.data<"u"&&(e.data=t.data),typeof t.from<"u"&&(e.from=t.from),typeof t.gas<"u"&&(e.gas=Z(t.gas)),typeof t.gasPrice<"u"&&(e.gasPrice=Z(t.gasPrice)),typeof t.maxFeePerBlobGas<"u"&&(e.maxFeePerBlobGas=Z(t.maxFeePerBlobGas)),typeof t.maxFeePerGas<"u"&&(e.maxFeePerGas=Z(t.maxFeePerGas)),typeof t.maxPriorityFeePerGas<"u"&&(e.maxPriorityFeePerGas=Z(t.maxPriorityFeePerGas)),typeof t.nonce<"u"&&(e.nonce=Z(t.nonce)),typeof t.to<"u"&&(e.to=t.to),typeof t.type<"u"&&(e.type=W5[t.type]),typeof t.value<"u"&&(e.value=Z(t.value)),e}function K5(t){return t.map(e=>({address:e.address,r:e.r?Z(BigInt(e.r)):e.r,s:e.s?Z(BigInt(e.s)):e.s,chainId:Z(e.chainId),nonce:Z(e.nonce),...typeof e.yParity<"u"?{yParity:Z(e.yParity)}:{},...typeof e.v<"u"&&typeof e.yParity>"u"?{v:Z(e.v)}:{}}))}function Op(t){if(!(!t||t.length===0))return t.reduce((e,{slot:r,value:n})=>{if(r.length!==66)throw new bp({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new bp({size:n.length,targetSize:66,type:"hex"});return e[r]=n,e},{})}function Z5(t){const{balance:e,nonce:r,state:n,stateDiff:s,code:i}=t,o={};if(i!==void 0&&(o.code=i),e!==void 0&&(o.balance=Z(e)),r!==void 0&&(o.nonce=Z(r)),n!==void 0&&(o.state=Op(n)),s!==void 0){if(o.state)throw new T5;o.stateDiff=Op(s)}return o}function Gd(t){if(!t)return;const e={};for(const{address:r,...n}of t){if(!at(r,{strict:!1}))throw new $t({address:r});if(e[r])throw new k5({address:r});e[r]=Z5(n)}return e}const Hc=2n**256n-1n;function Ys(t){const{account:e,gasPrice:r,maxFeePerGas:n,maxPriorityFeePerGas:s,to:i}=t,o=e?Ze(e):void 0;if(o&&!at(o.address))throw new $t({address:o.address});if(i&&!at(i))throw new $t({address:i});if(typeof r<"u"&&(typeof n<"u"||typeof s<"u"))throw new P5;if(n&&n>Hc)throw new js({maxFeePerGas:n});if(s&&n&&s>n)throw new Zo({maxFeePerGas:n,maxPriorityFeePerGas:s})}class Y5 extends L{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class Wd extends L{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class X5 extends L{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${jt(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class mb extends L{constructor({blockHash:e,blockNumber:r}){let n="Block";e&&(n=`Block at hash "${e}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}const bb={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function zc(t){const e={...t,blockHash:t.blockHash?t.blockHash:null,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,chainId:t.chainId?dr(t.chainId):void 0,gas:t.gas?BigInt(t.gas):void 0,gasPrice:t.gasPrice?BigInt(t.gasPrice):void 0,maxFeePerBlobGas:t.maxFeePerBlobGas?BigInt(t.maxFeePerBlobGas):void 0,maxFeePerGas:t.maxFeePerGas?BigInt(t.maxFeePerGas):void 0,maxPriorityFeePerGas:t.maxPriorityFeePerGas?BigInt(t.maxPriorityFeePerGas):void 0,nonce:t.nonce?dr(t.nonce):void 0,to:t.to?t.to:null,transactionIndex:t.transactionIndex?Number(t.transactionIndex):null,type:t.type?bb[t.type]:void 0,typeHex:t.type?t.type:void 0,value:t.value?BigInt(t.value):void 0,v:t.v?BigInt(t.v):void 0};return t.authorizationList&&(e.authorizationList=Q5(t.authorizationList)),e.yParity=(()=>{if(t.yParity)return Number(t.yParity);if(typeof e.v=="bigint"){if(e.v===0n||e.v===27n)return 0;if(e.v===1n||e.v===28n)return 1;if(e.v>=35n)return e.v%2n===0n?1:0}})(),e.type==="legacy"&&(delete e.accessList,delete e.maxFeePerBlobGas,delete e.maxFeePerGas,delete e.maxPriorityFeePerGas,delete e.yParity),e.type==="eip2930"&&(delete e.maxFeePerBlobGas,delete e.maxFeePerGas,delete e.maxPriorityFeePerGas),e.type==="eip1559"&&delete e.maxFeePerBlobGas,e}const J5=qd("transaction",zc);function Q5(t){return t.map(e=>({address:e.address,chainId:Number(e.chainId),nonce:Number(e.nonce),r:e.r,s:e.s,yParity:Number(e.yParity)}))}function Kd(t){const e=(t.transactions??[]).map(r=>typeof r=="string"?r:zc(r));return{...t,baseFeePerGas:t.baseFeePerGas?BigInt(t.baseFeePerGas):null,blobGasUsed:t.blobGasUsed?BigInt(t.blobGasUsed):void 0,difficulty:t.difficulty?BigInt(t.difficulty):void 0,excessBlobGas:t.excessBlobGas?BigInt(t.excessBlobGas):void 0,gasLimit:t.gasLimit?BigInt(t.gasLimit):void 0,gasUsed:t.gasUsed?BigInt(t.gasUsed):void 0,hash:t.hash?t.hash:null,logsBloom:t.logsBloom?t.logsBloom:null,nonce:t.nonce?t.nonce:null,number:t.number?BigInt(t.number):null,size:t.size?BigInt(t.size):void 0,timestamp:t.timestamp?BigInt(t.timestamp):void 0,transactions:e,totalDifficulty:t.totalDifficulty?BigInt(t.totalDifficulty):null}}const eE=qd("block",Kd);async function Zr(t,{blockHash:e,blockNumber:r,blockTag:n=t.experimental_blockTag??"latest",includeTransactions:s}={}){var u,f,l;const i=s??!1,o=r!==void 0?Z(r):void 0;let a=null;if(e?a=await t.request({method:"eth_getBlockByHash",params:[e,i]},{dedupe:!0}):a=await t.request({method:"eth_getBlockByNumber",params:[o||n,i]},{dedupe:!!o}),!a)throw new mb({blockHash:e,blockNumber:r});return(((l=(f=(u=t.chain)==null?void 0:u.formatters)==null?void 0:f.block)==null?void 0:l.format)||Kd)(a)}async function Zd(t){const e=await t.request({method:"eth_gasPrice"});return BigInt(e)}async function tE(t,e){return gb(t,e)}async function gb(t,e){var i,o;const{block:r,chain:n=t.chain,request:s}=e||{};try{const a=((i=n==null?void 0:n.fees)==null?void 0:i.maxPriorityFeePerGas)??((o=n==null?void 0:n.fees)==null?void 0:o.defaultPriorityFee);if(typeof a=="function"){const u=r||await se(t,Zr,"getBlock")({}),f=await a({block:u,client:t,request:s});if(f===null)throw new Error;return f}if(typeof a<"u")return a;const c=await t.request({method:"eth_maxPriorityFeePerGas"});return ut(c)}catch{const[a,c]=await Promise.all([r?Promise.resolve(r):se(t,Zr,"getBlock")({}),se(t,Zd,"getGasPrice")({})]);if(typeof a.baseFeePerGas!="bigint")throw new Wd;const u=c-a.baseFeePerGas;return u<0n?0n:u}}async function rE(t,e){return Fl(t,e)}async function Fl(t,e){var p,d;const{block:r,chain:n=t.chain,request:s,type:i="eip1559"}=e||{},o=await(async()=>{var m,b;return typeof((m=n==null?void 0:n.fees)==null?void 0:m.baseFeeMultiplier)=="function"?n.fees.baseFeeMultiplier({block:r,client:t,request:s}):((b=n==null?void 0:n.fees)==null?void 0:b.baseFeeMultiplier)??1.2})();if(o<1)throw new Y5;const c=10**(((p=o.toString().split(".")[1])==null?void 0:p.length)??0),u=m=>m*BigInt(Math.ceil(o*c))/BigInt(c),f=r||await se(t,Zr,"getBlock")({});if(typeof((d=n==null?void 0:n.fees)==null?void 0:d.estimateFeesPerGas)=="function"){const m=await n.fees.estimateFeesPerGas({block:r,client:t,multiply:u,request:s,type:i});if(m!==null)return m}if(i==="eip1559"){if(typeof f.baseFeePerGas!="bigint")throw new Wd;const m=typeof(s==null?void 0:s.maxPriorityFeePerGas)=="bigint"?s.maxPriorityFeePerGas:await gb(t,{block:f,chain:n,request:s}),b=u(f.baseFeePerGas);return{maxFeePerGas:(s==null?void 0:s.maxFeePerGas)??b+m,maxPriorityFeePerGas:m}}return{gasPrice:(s==null?void 0:s.gasPrice)??u(await se(t,Zd,"getGasPrice")({}))}}async function Yd(t,{address:e,blockTag:r="latest",blockNumber:n}){const s=await t.request({method:"eth_getTransactionCount",params:[e,typeof n=="bigint"?Z(n):r]},{dedupe:!!n});return dr(s)}function Xd(t){const{kzg:e}=t,r=t.to??(typeof t.blobs[0]=="string"?"hex":"bytes"),n=typeof t.blobs[0]=="string"?t.blobs.map(i=>Jr(i)):t.blobs,s=[];for(const i of n)s.push(Uint8Array.from(e.blobToKzgCommitment(i)));return r==="bytes"?s:s.map(i=>et(i))}function Jd(t){const{kzg:e}=t,r=t.to??(typeof t.blobs[0]=="string"?"hex":"bytes"),n=typeof t.blobs[0]=="string"?t.blobs.map(o=>Jr(o)):t.blobs,s=typeof t.commitments[0]=="string"?t.commitments.map(o=>Jr(o)):t.commitments,i=[];for(let o=0;o<n.length;o++){const a=n[o],c=s[o];i.push(Uint8Array.from(e.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map(o=>et(o))}function nE(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function sE(t,e,r){return t&e^~t&r}function iE(t,e,r){return t&e^t&r^e&r}let wb=class extends $c{constructor(e,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Tu(this.buffer)}update(e){os(this),e=En(e),is(e);const{view:r,buffer:n,blockLen:s}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=Tu(e);for(;s<=i-o;o+=s)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){os(this),Rd(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:o}=this;r[o++]=128,Ir(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let l=o;l<s;l++)r[l]=0;nE(n,s-8,BigInt(this.length*8),i),this.process(n,0);const a=Tu(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:s,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=s,e.pos=a,s%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const Un=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Mn=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),oE=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]),Fn=new Uint32Array(64);let Qd=class extends wb{constructor(e=32){super(64,e,8,!1),this.A=Un[0]|0,this.B=Un[1]|0,this.C=Un[2]|0,this.D=Un[3]|0,this.E=Un[4]|0,this.F=Un[5]|0,this.G=Un[6]|0,this.H=Un[7]|0}get(){const{A:e,B:r,C:n,D:s,E:i,F:o,G:a,H:c}=this;return[e,r,n,s,i,o,a,c]}set(e,r,n,s,i,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let l=0;l<16;l++,r+=4)Fn[l]=e.getUint32(r,!1);for(let l=16;l<64;l++){const p=Fn[l-15],d=Fn[l-2],m=Mr(p,7)^Mr(p,18)^p>>>3,b=Mr(d,17)^Mr(d,19)^d>>>10;Fn[l]=b+Fn[l-7]+m+Fn[l-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){const p=Mr(a,6)^Mr(a,11)^Mr(a,25),d=f+p+sE(a,c,u)+oE[l]+Fn[l]|0,b=(Mr(n,2)^Mr(n,13)^Mr(n,22))+iE(n,s,i)|0;f=u,u=c,c=a,a=o+d|0,o=i,i=s,s=n,n=d+b|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,s,i,o,a,c,u,f)}roundClean(){Ir(Fn)}destroy(){this.set(0,0,0,0,0,0,0,0),Ir(this.buffer)}},vb=class extends Qd{constructor(){super(28),this.A=Mn[0]|0,this.B=Mn[1]|0,this.C=Mn[2]|0,this.D=Mn[3]|0,this.E=Mn[4]|0,this.F=Mn[5]|0,this.G=Mn[6]|0,this.H=Mn[7]|0}};const Eb=Rc(()=>new Qd),aE=Rc(()=>new vb),cE=Qd,Sb=Eb,uE=vb,fE=aE,lE=Object.freeze(Object.defineProperty({__proto__:null,SHA224:uE,SHA256:cE,sha224:fE,sha256:Sb},Symbol.toStringTag,{value:"Module"}));function ho(t,e){const r=e||"hex",n=Sb(Pr(t,{strict:!1})?zi(t):t);return r==="bytes"?n:Bt(n)}function dE(t){const{commitment:e,version:r=1}=t,n=t.to??(typeof e=="string"?"hex":"bytes"),s=ho(e,"bytes");return s.set([r],0),n==="bytes"?s:et(s)}function Ab(t){const{commitments:e,version:r}=t,n=t.to??(typeof e[0]=="string"?"hex":"bytes"),s=[];for(const i of e)s.push(dE({commitment:i,to:n,version:r}));return s}const Bp=6,xb=32,eh=4096,kb=xb*eh,Cp=kb*Bp-1-1*eh*Bp,Tb=1;class hE extends L{constructor({maxSize:e,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class _b extends L{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class pE extends L{constructor({hash:e,size:r}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class yE extends L{constructor({hash:e,version:r}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:[`Expected: ${Tb}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function mE(t){const e=t.to??(typeof t.data=="string"?"hex":"bytes"),r=typeof t.data=="string"?Jr(t.data):t.data,n=He(r);if(!n)throw new _b;if(n>Cp)throw new hE({maxSize:Cp,size:n});const s=[];let i=!0,o=0;for(;i;){const a=Dd(new Uint8Array(kb));let c=0;for(;c<eh;){const u=r.slice(o,o+(xb-1));if(a.pushByte(0),a.pushBytes(u),u.length<31){a.pushByte(128),i=!1;break}c++,o+=31}s.push(a)}return e==="bytes"?s.map(a=>a.bytes):s.map(a=>et(a.bytes))}function Pb(t){const{data:e,kzg:r,to:n}=t,s=t.blobs??mE({data:e,to:n}),i=t.commitments??Xd({blobs:s,kzg:r,to:n}),o=t.proofs??Jd({blobs:s,commitments:i,kzg:r,to:n}),a=[];for(let c=0;c<s.length;c++)a.push({blob:s[c],commitment:i[c],proof:o[c]});return a}function Ib(t){if(t.type)return t.type;if(typeof t.authorizationList<"u")return"eip7702";if(typeof t.blobs<"u"||typeof t.blobVersionedHashes<"u"||typeof t.maxFeePerBlobGas<"u"||typeof t.sidecars<"u")return"eip4844";if(typeof t.maxFeePerGas<"u"||typeof t.maxPriorityFeePerGas<"u")return"eip1559";if(typeof t.gasPrice<"u")return typeof t.accessList<"u"?"eip2930":"legacy";throw new O5({transaction:t})}async function qi(t){const e=await t.request({method:"eth_chainId"},{dedupe:!0});return dr(e)}const Ob=["blobVersionedHashes","chainId","fees","gas","nonce","type"],$p=new Map;async function Vc(t,e){const{account:r=t.account,blobs:n,chain:s,gas:i,kzg:o,nonce:a,nonceManager:c,parameters:u=Ob,type:f}=e,l=r&&Ze(r),p={...e,...l?{from:l==null?void 0:l.address}:{}};let d;async function m(){return d||(d=await se(t,Zr,"getBlock")({blockTag:"latest"}),d)}let b;async function E(){return b||(s?s.id:typeof e.chainId<"u"?e.chainId:(b=await se(t,qi,"getChainId")({}),b))}if(u.includes("nonce")&&typeof a>"u"&&l)if(c){const A=await E();p.nonce=await c.consume({address:l.address,chainId:A,client:t})}else p.nonce=await se(t,Yd,"getTransactionCount")({address:l.address,blockTag:"pending"});if((u.includes("blobVersionedHashes")||u.includes("sidecars"))&&n&&o){const A=Xd({blobs:n,kzg:o});if(u.includes("blobVersionedHashes")){const P=Ab({commitments:A,to:"hex"});p.blobVersionedHashes=P}if(u.includes("sidecars")){const P=Jd({blobs:n,commitments:A,kzg:o}),S=Pb({blobs:n,commitments:A,proofs:P,to:"hex"});p.sidecars=S}}if(u.includes("chainId")&&(p.chainId=await E()),(u.includes("fees")||u.includes("type"))&&typeof f>"u")try{p.type=Ib(p)}catch{let A=$p.get(t.uid);if(typeof A>"u"){const P=await m();A=typeof(P==null?void 0:P.baseFeePerGas)=="bigint",$p.set(t.uid,A)}p.type=A?"eip1559":"legacy"}if(u.includes("fees"))if(p.type!=="legacy"&&p.type!=="eip2930"){if(typeof p.maxFeePerGas>"u"||typeof p.maxPriorityFeePerGas>"u"){const A=await m(),{maxFeePerGas:P,maxPriorityFeePerGas:S}=await Fl(t,{block:A,chain:s,request:p});if(typeof e.maxPriorityFeePerGas>"u"&&e.maxFeePerGas&&e.maxFeePerGas<S)throw new X5({maxPriorityFeePerGas:S});p.maxPriorityFeePerGas=S,p.maxFeePerGas=P}}else{if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")throw new Wd;if(typeof e.gasPrice>"u"){const A=await m(),{gasPrice:P}=await Fl(t,{block:A,chain:s,request:p,type:"legacy"});p.gasPrice=P}}return u.includes("gas")&&typeof i>"u"&&(p.gas=await se(t,th,"estimateGas")({...p,account:l&&{address:l.address,type:"json-rpc"}})),Ys(p),delete p.parameters,p}async function Bb(t,{address:e,blockNumber:r,blockTag:n=t.experimental_blockTag??"latest"}){const s=typeof r=="bigint"?Z(r):void 0,i=await t.request({method:"eth_getBalance",params:[e,s||n]});return BigInt(i)}async function th(t,e){var s,i,o;const{account:r=t.account}=e,n=r?Ze(r):void 0;try{let Q=function(W){const{block:ee,request:H,rpcStateOverride:I}=W;return t.request({method:"eth_estimateGas",params:I?[H,ee??t.experimental_blockTag??"latest",I]:ee?[H,ee]:[H]})};const{accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:f,blockNumber:l,blockTag:p,data:d,gas:m,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:S,value:w,stateOverride:k,...T}=await Vc(t,{...e,parameters:(n==null?void 0:n.type)==="local"?void 0:["blobVersionedHashes"]}),U=(typeof l=="bigint"?Z(l):void 0)||p,$=Gd(k),D=await(async()=>{if(T.to)return T.to;if(c&&c.length>0)return await Vd({authorization:c[0]}).catch(()=>{throw new L("`to` is required. Could not infer from `authorizationList`")})})();Ys(e);const M=(o=(i=(s=t.chain)==null?void 0:s.formatters)==null?void 0:i.transactionRequest)==null?void 0:o.format,K=(M||Vi)({...Dc(T,{format:M}),from:n==null?void 0:n.address,accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:f,data:d,gas:m,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:S,to:D,value:w});let G=BigInt(await Q({block:U,request:K,rpcStateOverride:$}));if(c){const W=await Bb(t,{address:K.from}),ee=await Promise.all(c.map(async H=>{const{address:I}=H,j=await Q({block:U,request:{authorizationList:void 0,data:d,from:n==null?void 0:n.address,to:I,value:Z(W)},rpcStateOverride:$}).catch(()=>100000n);return 2n*BigInt(j)}));G+=ee.reduce((H,I)=>H+I,0n)}return G}catch(a){throw G5(a,{...e,account:n,chain:t.chain})}}async function Cb(t,e){const{abi:r,address:n,args:s,functionName:i,dataSuffix:o,...a}=e,c=Jt({abi:r,args:s,functionName:i});try{return await se(t,th,"estimateGas")({data:`${c}${o?o.replace("0x",""):""}`,to:n,...a})}catch(u){const f=a.account?Ze(a.account):void 0;throw Fs(u,{abi:r,address:n,args:s,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:f==null?void 0:f.address})}}function Gi(t,e){if(!at(t,{strict:!1}))throw new $t({address:t});if(!at(e,{strict:!1}))throw new $t({address:e});return t.toLowerCase()===e.toLowerCase()}const Rp="/docs/contract/decodeEventLog";function rh(t){const{abi:e,data:r,strict:n,topics:s}=t,i=n??!0,[o,...a]=s;if(!o)throw new sv({docsPath:Rp});const c=e.find(b=>b.type==="event"&&o===Nc(_r(b)));if(!(c&&"name"in c)||c.type!=="event")throw new Cm(o,{docsPath:Rp});const{name:u,inputs:f}=c,l=f==null?void 0:f.some(b=>!("name"in b&&b.name)),p=l?[]:{},d=f.map((b,E)=>[b,E]).filter(([b])=>"indexed"in b&&b.indexed);for(let b=0;b<d.length;b++){const[E,A]=d[b],P=a[b];if(!P)throw new Cc({abiItem:c,param:E});p[l?A:E.name||A]=bE({param:E,value:P})}const m=f.filter(b=>!("indexed"in b&&b.indexed));if(m.length>0){if(r&&r!=="0x")try{const b=ya(m,r);if(b)if(l)for(let E=0;E<f.length;E++)p[E]=p[E]??b.shift();else for(let E=0;E<m.length;E++)p[m[E].name]=b[E]}catch(b){if(i)throw b instanceof Om||b instanceof ib?new Po({abiItem:c,data:r,params:m,size:He(r)}):b}else if(i)throw new Po({abiItem:c,data:"0x",params:m,size:0})}return{eventName:u,args:Object.values(p).length>0?p:void 0}}function bE({param:t,value:e}){return t.type==="string"||t.type==="bytes"||t.type==="tuple"||t.type.match(/^(.*)\[(\d+)?\]$/)?e:(ya([t],e)||[])[0]}function nh(t){const{abi:e,args:r,logs:n,strict:s=!0}=t,i=(()=>{if(t.eventName)return Array.isArray(t.eventName)?t.eventName:[t.eventName]})();return n.map(o=>{var a;try{const c=e.find(f=>f.type==="event"&&o.topics[0]===Nc(f));if(!c)return null;const u=rh({...o,abi:[c],strict:s});return i&&!i.includes(u.eventName)||!gE({args:u.args,inputs:c.inputs,matchArgs:r})?null:{...u,...o}}catch(c){let u,f;if(c instanceof Cm)return null;if(c instanceof Po||c instanceof Cc){if(s)return null;u=c.abiItem.name,f=(a=c.abiItem.inputs)==null?void 0:a.some(l=>!("name"in l&&l.name))}return{...o,args:f?[]:{},eventName:u}}}).filter(Boolean)}function gE(t){const{args:e,inputs:r,matchArgs:n}=t;if(!n)return!0;if(!e)return!1;function s(i,o,a){try{return i.type==="address"?Gi(o,a):i.type==="string"||i.type==="bytes"?ht(zi(o))===a:o===a}catch{return!1}}return Array.isArray(e)&&Array.isArray(n)?n.every((i,o)=>{if(i==null)return!0;const a=r[o];return a?(Array.isArray(i)?i:[i]).some(u=>s(a,u,e[o])):!1}):typeof e=="object"&&!Array.isArray(e)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([i,o])=>{if(o==null)return!0;const a=r.find(u=>u.name===i);return a?(Array.isArray(o)?o:[o]).some(u=>s(a,u,e[i])):!1}):!1}function kn(t,{args:e,eventName:r}={}){return{...t,blockHash:t.blockHash?t.blockHash:null,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,logIndex:t.logIndex?Number(t.logIndex):null,transactionHash:t.transactionHash?t.transactionHash:null,transactionIndex:t.transactionIndex?Number(t.transactionIndex):null,...r?{args:e,eventName:r}:{}}}async function sh(t,{address:e,blockHash:r,fromBlock:n,toBlock:s,event:i,events:o,args:a,strict:c}={}){const u=c??!1,f=o??(i?[i]:void 0);let l=[];f&&(l=[f.flatMap(b=>pa({abi:[b],eventName:b.name,args:o?void 0:a}))],i&&(l=l[0]));let p;r?p=await t.request({method:"eth_getLogs",params:[{address:e,topics:l,blockHash:r}]}):p=await t.request({method:"eth_getLogs",params:[{address:e,topics:l,fromBlock:typeof n=="bigint"?Z(n):n,toBlock:typeof s=="bigint"?Z(s):s}]});const d=p.map(m=>kn(m));return f?nh({abi:f,args:a,logs:d,strict:u}):d}async function ih(t,e){const{abi:r,address:n,args:s,blockHash:i,eventName:o,fromBlock:a,toBlock:c,strict:u}=e,f=o?Zs({abi:r,name:o}):void 0,l=f?void 0:r.filter(p=>p.type==="event");return se(t,sh,"getLogs")({address:n,args:s,blockHash:i,event:f,events:l,fromBlock:a,toBlock:c,strict:u})}const Iu="/docs/contract/decodeFunctionResult";function Xs(t){const{abi:e,args:r,functionName:n,data:s}=t;let i=e[0];if(n){const a=Zs({abi:e,args:r,name:n});if(!a)throw new Oi(n,{docsPath:Iu});i=a}if(i.type!=="function")throw new Oi(void 0,{docsPath:Iu});if(!i.outputs)throw new $m(i.name,{docsPath:Iu});const o=ya(i.outputs,s);if(o&&o.length>1)return o;if(o&&o.length===1)return o[0]}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const oh=BigInt(0),jl=BigInt(1);function ga(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ah(t){if(!ga(t))throw new Error("Uint8Array expected")}function Yo(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function Na(t){const e=t.toString(16);return e.length&1?"0"+e:e}function $b(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?oh:BigInt("0x"+t)}const Rb=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",wE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Xo(t){if(ah(t),Rb)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=wE[t[r]];return e}const rn={_0:48,_9:57,A:65,F:70,a:97,f:102};function Np(t){if(t>=rn._0&&t<=rn._9)return t-rn._0;if(t>=rn.A&&t<=rn.F)return t-(rn.A-10);if(t>=rn.a&&t<=rn.f)return t-(rn.a-10)}function bc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Rb)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let s=0,i=0;s<r;s++,i+=2){const o=Np(t.charCodeAt(i)),a=Np(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[s]=o*16+a}return n}function Ps(t){return $b(Xo(t))}function Nb(t){return ah(t),$b(Xo(Uint8Array.from(t).reverse()))}function wa(t,e){return bc(t.toString(16).padStart(e*2,"0"))}function Ub(t,e){return wa(t,e).reverse()}function sr(t,e,r){let n;if(typeof e=="string")try{n=bc(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(ga(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=n.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return n}function gc(...t){let e=0;for(let n=0;n<t.length;n++){const s=t[n];ah(s),e+=s.length}const r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){const i=t[n];r.set(i,s),s+=i.length}return r}const Ou=t=>typeof t=="bigint"&&oh<=t;function ch(t,e,r){return Ou(t)&&Ou(e)&&Ou(r)&&e<=t&&t<r}function Si(t,e,r,n){if(!ch(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function vE(t){let e;for(e=0;t>oh;t>>=jl,e+=1);return e}const qc=t=>(jl<<BigInt(t))-jl,Bu=t=>new Uint8Array(t),Up=t=>Uint8Array.from(t);function EE(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=Bu(t),s=Bu(t),i=0;const o=()=>{n.fill(1),s.fill(0),i=0},a=(...l)=>r(s,n,...l),c=(l=Bu(0))=>{s=a(Up([0]),l),n=a(),l.length!==0&&(s=a(Up([1]),l),n=a())},u=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const p=[];for(;l<e;){n=a();const d=n.slice();p.push(d),l+=n.length}return gc(...p)};return(l,p)=>{o(),c(l);let d;for(;!(d=p(u()));)c();return o(),d}}const SE={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||ga(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function Gc(t,e,r={}){const n=(s,i,o)=>{const a=SE[i];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+i+", got "+c)};for(const[s,i]of Object.entries(e))n(s,i,!1);for(const[s,i]of Object.entries(r))n(s,i,!0);return t}function Mp(t){const e=new WeakMap;return(r,...n)=>{const s=e.get(r);if(s!==void 0)return s;const i=t(r,...n);return e.set(r,i),i}}const AE="0.1.1";function xE(){return AE}let ve=class Ll extends Error{constructor(e,r={}){const n=(()=>{var c;if(r.cause instanceof Ll){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),s=r.cause instanceof Ll&&r.cause.docsPath||r.docsPath,o=`https://oxlib.sh${s??""}`,a=[e||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||s?["",n?`Details: ${n}`:void 0,s?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
|
|
40
|
-
`);super(a,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${xE()}`}),this.cause=r.cause,this.details=n,this.docs=o,this.docsPath=s,this.shortMessage=e}walk(e){return Mb(this,e)}};function Mb(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Mb(t.cause,e):e?null:t}function va(t,e){if(bi(t)>e)throw new DE({givenSize:bi(t),maxSize:e})}const nn={zero:48,nine:57,A:65,F:70,a:97,f:102};function Fp(t){if(t>=nn.zero&&t<=nn.nine)return t-nn.zero;if(t>=nn.A&&t<=nn.F)return t-(nn.A-10);if(t>=nn.a&&t<=nn.f)return t-(nn.a-10)}function kE(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;if(t.length>n)throw new HE({size:t.length,targetSize:n,type:"Bytes"});const s=new Uint8Array(n);for(let i=0;i<n;i++){const o=r==="right";s[o?i:n-i-1]=t[o?i:t.length-i-1]}return s}function Fb(t,e={}){const{dir:r="left"}=e;let n=t,s=0;for(let i=0;i<n.length-1&&n[r==="left"?i:n.length-i-1].toString()==="0";i++)s++;return n=r==="left"?n.slice(s):n.slice(0,n.length-s),n}function Wc(t,e){if(Zt(t)>e)throw new KE({givenSize:Zt(t),maxSize:e})}function TE(t,e){if(typeof e=="number"&&e>0&&e>Zt(t)-1)throw new Wb({offset:e,position:"start",size:Zt(t)})}function _E(t,e,r){if(typeof e=="number"&&typeof r=="number"&&Zt(t)!==r-e)throw new Wb({offset:r,position:"end",size:Zt(t)})}function jb(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;const s=t.replace("0x","");if(s.length>n*2)throw new ZE({size:Math.ceil(s.length/2),targetSize:n,type:"Hex"});return`0x${s[r==="right"?"padEnd":"padStart"](n*2,"0")}`}const PE="#__bigint";function Lb(t,e,r){return JSON.stringify(t,(n,s)=>typeof s=="bigint"?s.toString()+PE:s,r)}const IE=new TextDecoder,OE=new TextEncoder;function BE(t){return t instanceof Uint8Array?t:typeof t=="string"?Db(t):CE(t)}function CE(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function Db(t,e={}){const{size:r}=e;let n=t;r&&(Wc(t,r),n=Ds(t,r));let s=n.slice(2);s.length%2&&(s=`0${s}`);const i=s.length/2,o=new Uint8Array(i);for(let a=0,c=0;a<i;a++){const u=Fp(s.charCodeAt(c++)),f=Fp(s.charCodeAt(c++));if(u===void 0||f===void 0)throw new ve(`Invalid byte sequence ("${s[c-2]}${s[c-1]}" in "${s}").`);o[a]=u*16+f}return o}function $E(t,e={}){const{size:r}=e,n=OE.encode(t);return typeof r=="number"?(va(n,r),RE(n,r)):n}function RE(t,e){return kE(t,{dir:"right",size:e})}function bi(t){return t.length}function NE(t,e,r,n={}){const{strict:s}=n;return t.slice(e,r)}function UE(t,e={}){const{size:r}=e;typeof r<"u"&&va(t,r);const n=Br(t,e);return Vb(n,e)}function ME(t,e={}){const{size:r}=e;let n=t;if(typeof r<"u"&&(va(n,r),n=Hb(n)),n.length>1||n[0]>1)throw new LE(n);return!!n[0]}function An(t,e={}){const{size:r}=e;typeof r<"u"&&va(t,r);const n=Br(t,e);return qb(n,e)}function FE(t,e={}){const{size:r}=e;let n=t;return typeof r<"u"&&(va(n,r),n=jE(n)),IE.decode(n)}function Hb(t){return Fb(t,{dir:"left"})}function jE(t){return Fb(t,{dir:"right"})}class LE extends ve{constructor(e){super(`Bytes value \`${e}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"})}}let DE=class extends ve{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},HE=class extends ve{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}};const zE=new TextEncoder,VE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function qE(t,e={}){const{strict:r=!1}=e;if(!t)throw new jp(t);if(typeof t!="string")throw new jp(t);if(r&&!/^0x[0-9a-fA-F]*$/.test(t))throw new Lp(t);if(!t.startsWith("0x"))throw new Lp(t)}function Or(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function GE(t){return t instanceof Uint8Array?Br(t):Array.isArray(t)?Br(new Uint8Array(t)):t}function zb(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(Wc(r,e.size),Ls(r,e.size)):r}function Br(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=VE[t[s]];const n=`0x${r}`;return typeof e.size=="number"?(Wc(n,e.size),Ds(n,e.size)):n}function It(t,e={}){const{signed:r,size:n}=e,s=BigInt(t);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<o){const u=typeof t=="bigint"?"n":"";throw new Gb({max:i?`${i}${u}`:void 0,min:`${o}${u}`,signed:r,size:n,value:`${t}${u}`})}const c=`0x${(r&&s<0?(1n<<BigInt(n*8))+BigInt(s):s).toString(16)}`;return n?Ls(c,n):c}function uh(t,e={}){return Br(zE.encode(t),e)}function Ls(t,e){return jb(t,{dir:"left",size:e})}function Ds(t,e){return jb(t,{dir:"right",size:e})}function Yr(t,e,r,n={}){const{strict:s}=n;TE(t,e);const i=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return s&&_E(i,e,r),i}function Zt(t){return Math.ceil((t.length-2)/2)}function Vb(t,e={}){const{signed:r}=e;e.size&&Wc(t,e.size);const n=BigInt(t);if(!r)return n;const s=(t.length-2)/2,i=(1n<<BigInt(s)*8n)-1n,o=i>>1n;return n<=o?n:n-i-1n}function qb(t,e={}){const{signed:r,size:n}=e;return Number(!r&&!n?t:Vb(t,e))}function WE(t,e={}){const{strict:r=!1}=e;try{return qE(t,{strict:r}),!0}catch{return!1}}class Gb extends ve{constructor({max:e,min:r,signed:n,size:s,value:i}){super(`Number \`${i}\` is not in safe${s?` ${s*8}-bit`:""}${n?" signed":" unsigned"} integer range ${e?`(\`${r}\` to \`${e}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class jp extends ve{constructor(e){super(`Value \`${typeof e=="object"?Lb(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class Lp extends ve{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class KE extends ve{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class Wb extends ve{constructor({offset:e,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class ZE extends ve{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}function YE(t){return{address:t.address,amount:It(t.amount),index:It(t.index),validatorIndex:It(t.validatorIndex)}}function Kb(t){return{...typeof t.baseFeePerGas=="bigint"&&{baseFeePerGas:It(t.baseFeePerGas)},...typeof t.blobBaseFee=="bigint"&&{blobBaseFee:It(t.blobBaseFee)},...typeof t.feeRecipient=="string"&&{feeRecipient:t.feeRecipient},...typeof t.gasLimit=="bigint"&&{gasLimit:It(t.gasLimit)},...typeof t.number=="bigint"&&{number:It(t.number)},...typeof t.prevRandao=="bigint"&&{prevRandao:It(t.prevRandao)},...typeof t.time=="bigint"&&{time:It(t.time)},...t.withdrawals&&{withdrawals:t.withdrawals.map(YE)}}}const wc=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],Dl=[{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"}]}],Zb=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],Yb=[...Zb,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],XE=[...Zb,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],Dp=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],Hp=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],Xb=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],zp=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],JE="0x82ad56cb",Jb="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",QE="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",eS="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",fh="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033";class Hl extends L{constructor({blockNumber:e,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...e&&n.blockCreated&&n.blockCreated>e?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${e}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class tS extends L{constructor({chain:e,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${e.id} – ${e.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${e.id} – ${e.name}`],name:"ChainMismatchError"})}}class rS extends L{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 Qb extends L{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class Kc extends L{constructor({chainId:e}){super(typeof e=="number"?`Chain ID "${e}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const Cu="/docs/contract/encodeDeployData";function Zc(t){const{abi:e,args:r,bytecode:n}=t;if(!r||r.length===0)return n;const s=e.find(o=>"type"in o&&o.type==="constructor");if(!s)throw new Q6({docsPath:Cu});if(!("inputs"in s))throw new pp({docsPath:Cu});if(!s.inputs||s.inputs.length===0)throw new pp({docsPath:Cu});const i=fs(s.inputs,r);return $r([n,i])}function Wi({blockNumber:t,chain:e,contract:r}){var s;const n=(s=e==null?void 0:e.contracts)==null?void 0:s[r];if(!n)throw new Hl({chain:e,contract:{name:r}});if(t&&n.blockCreated&&n.blockCreated>t)throw new Hl({blockNumber:t,chain:e,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function eg(t,{docsPath:e,...r}){const n=(()=>{const s=Lc(t,r);return s instanceof ba?t:s})();return new lb(n,{docsPath:e,...r})}function lh(){let t=()=>{},e=()=>{};return{promise:new Promise((n,s)=>{t=n,e=s}),resolve:t,reject:e}}const $u=new Map;function tg({fn:t,id:e,shouldSplitBatch:r,wait:n=0,sort:s}){const i=async()=>{const f=c();o();const l=f.map(({args:p})=>p);l.length!==0&&t(l).then(p=>{s&&Array.isArray(p)&&p.sort(s);for(let d=0;d<f.length;d++){const{resolve:m}=f[d];m==null||m([p[d],p])}}).catch(p=>{for(let d=0;d<f.length;d++){const{reject:m}=f[d];m==null||m(p)}})},o=()=>$u.delete(e),a=()=>c().map(({args:f})=>f),c=()=>$u.get(e)||[],u=f=>$u.set(e,[...c(),f]);return{flush:o,async schedule(f){const{promise:l,resolve:p,reject:d}=lh();return(r==null?void 0:r([...a(),f]))&&i(),c().length>0?(u({args:f,resolve:p,reject:d}),l):(u({args:f,resolve:p,reject:d}),setTimeout(i,n),l)}}}async function Ea(t,e){var K,Q,G,W;const{account:r=t.account,authorizationList:n,batch:s=!!((K=t.batch)!=null&&K.multicall),blockNumber:i,blockTag:o=t.experimental_blockTag??"latest",accessList:a,blobs:c,blockOverrides:u,code:f,data:l,factory:p,factoryData:d,gas:m,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:S,to:w,value:k,stateOverride:T,...B}=e,U=r?Ze(r):void 0;if(f&&(p||d))throw new L("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(f&&w)throw new L("Cannot provide both `code` & `to` as parameters.");const $=f&&l,D=p&&d&&w&&l,M=$||D,q=$?rg({code:f,data:l}):D?iS({data:l,factory:p,factoryData:d,to:w}):l;try{Ys(e);const H=(typeof i=="bigint"?Z(i):void 0)||o,I=u?Kb(u):void 0,j=Gd(T),J=(W=(G=(Q=t.chain)==null?void 0:Q.formatters)==null?void 0:G.transactionRequest)==null?void 0:W.format,R=(J||Vi)({...Dc(B,{format:J}),from:U==null?void 0:U.address,accessList:a,authorizationList:n,blobs:c,data:q,gas:m,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:S,to:M?void 0:w,value:k});if(s&&nS({request:R})&&!j&&!I)try{return await sS(t,{...R,blockNumber:i,blockTag:o})}catch(ae){if(!(ae instanceof Qb)&&!(ae instanceof Hl))throw ae}const F=(()=>{const ae=[R,H];return j&&I?[...ae,j,I]:j?[...ae,j]:I?[...ae,{},I]:ae})(),ne=await t.request({method:"eth_call",params:F});return ne==="0x"?{data:void 0}:{data:ne}}catch(ee){const H=oS(ee),{offchainLookup:I,offchainLookupSignature:j}=await Promise.resolve().then(()=>require("./ccip-CWyEeg1d.cjs"));if(t.ccipRead!==!1&&(H==null?void 0:H.slice(0,10))===j&&w)return{data:await I(t,{data:H,to:w})};throw M&&(H==null?void 0:H.slice(0,10))==="0x101bb98d"?new U5({factory:p}):eg(ee,{...e,account:U,chain:t.chain})}}function nS({request:t}){const{data:e,to:r,...n}=t;return!(!e||e.startsWith(JE)||!r||Object.values(n).filter(s=>typeof s<"u").length>0)}async function sS(t,e){var b;const{batchSize:r=1024,deployless:n=!1,wait:s=0}=typeof((b=t.batch)==null?void 0:b.multicall)=="object"?t.batch.multicall:{},{blockNumber:i,blockTag:o=t.experimental_blockTag??"latest",data:a,to:c}=e,u=(()=>{if(n)return null;if(e.multicallAddress)return e.multicallAddress;if(t.chain)return Wi({blockNumber:i,chain:t.chain,contract:"multicall3"});throw new Qb})(),l=(typeof i=="bigint"?Z(i):void 0)||o,{schedule:p}=tg({id:`${t.uid}.${l}`,wait:s,shouldSplitBatch(E){return E.reduce((P,{data:S})=>P+(S.length-2),0)>r*2},fn:async E=>{const A=E.map(w=>({allowFailure:!0,callData:w.data,target:w.to})),P=Jt({abi:wc,args:[A],functionName:"aggregate3"}),S=await t.request({method:"eth_call",params:[{...u===null?{data:rg({code:fh,data:P})}:{to:u,data:P}},l]});return Xs({abi:wc,args:[A],functionName:"aggregate3",data:S||"0x"})}}),[{returnData:d,success:m}]=await p({data:a,to:c});if(!m)throw new jc({data:d});return d==="0x"?{data:void 0}:{data:d}}function rg(t){const{code:e,data:r}=t;return Zc({abi:_m(["constructor(bytes, bytes)"]),bytecode:Jb,args:[e,r]})}function iS(t){const{data:e,factory:r,factoryData:n,to:s}=t;return Zc({abi:_m(["constructor(address, bytes, address, bytes)"]),bytecode:QE,args:[s,e,r,n]})}function oS(t){var r;if(!(t instanceof L))return;const e=t.walk();return typeof(e==null?void 0:e.data)=="object"?(r=e.data)==null?void 0:r.data:e.data}async function hr(t,e){const{abi:r,address:n,args:s,functionName:i,...o}=e,a=Jt({abi:r,args:s,functionName:i});try{const{data:c}=await se(t,Ea,"call")({...o,data:a,to:n});return Xs({abi:r,args:s,functionName:i,data:c||"0x"})}catch(c){throw Fs(c,{abi:r,address:n,args:s,docsPath:"/docs/contract/readContract",functionName:i})}}async function ng(t,e){const{abi:r,address:n,args:s,dataSuffix:i,functionName:o,...a}=e,c=a.account?Ze(a.account):t.account,u=Jt({abi:r,args:s,functionName:o});try{const{data:f}=await se(t,Ea,"call")({batch:!1,data:`${u}${i?i.replace("0x",""):""}`,to:n,...a,account:c}),l=Xs({abi:r,args:s,functionName:o,data:f||"0x"}),p=r.filter(d=>"name"in d&&d.name===e.functionName);return{result:l,request:{abi:p,address:n,args:s,dataSuffix:i,functionName:o,...a,account:c}}}catch(f){throw Fs(f,{abi:r,address:n,args:s,docsPath:"/docs/contract/simulateContract",functionName:o,sender:c==null?void 0:c.address})}}const Ru=new Map,Vp=new Map;let aS=0;function Tn(t,e,r){const n=++aS,s=()=>Ru.get(t)||[],i=()=>{const f=s();Ru.set(t,f.filter(l=>l.id!==n))},o=()=>{const f=s();if(!f.some(p=>p.id===n))return;const l=Vp.get(t);if(f.length===1&&l){const p=l();p instanceof Promise&&p.catch(()=>{})}i()},a=s();if(Ru.set(t,[...a,{id:n,fns:e}]),a&&a.length>0)return o;const c={};for(const f in e)c[f]=(...l)=>{var d,m;const p=s();if(p.length!==0)for(const b of p)(m=(d=b.fns)[f])==null||m.call(d,...l)};const u=r(c);return typeof u=="function"&&Vp.set(t,u),o}async function zl(t){return new Promise(e=>setTimeout(e,t))}function Ki(t,{emitOnBegin:e,initialWaitTime:r,interval:n}){let s=!0;const i=()=>s=!1;return(async()=>{let a;e&&(a=await t({unpoll:i}));const c=await(r==null?void 0:r(a))??n;await zl(c);const u=async()=>{s&&(await t({unpoll:i}),await zl(n),u())};u()})(),i}const cS=new Map,uS=new Map;function fS(t){const e=(s,i)=>({clear:()=>i.delete(s),get:()=>i.get(s),set:o=>i.set(s,o)}),r=e(t,cS),n=e(t,uS);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function lS(t,{cacheKey:e,cacheTime:r=Number.POSITIVE_INFINITY}){const n=fS(e),s=n.response.get();if(s&&r>0&&Date.now()-s.created.getTime()<r)return s.data;let i=n.promise.get();i||(i=t(),n.promise.set(i));try{const o=await i;return n.response.set({created:new Date,data:o}),o}finally{n.promise.clear()}}const dS=t=>`blockNumber.${t}`;async function Sa(t,{cacheTime:e=t.cacheTime}={}){const r=await lS(()=>t.request({method:"eth_blockNumber"}),{cacheKey:dS(t.uid),cacheTime:e});return BigInt(r)}async function Yc(t,{filter:e}){const r="strict"in e&&e.strict,n=await e.request({method:"eth_getFilterChanges",params:[e.id]});if(typeof n[0]=="string")return n;const s=n.map(i=>kn(i));return!("abi"in e)||!e.abi?s:nh({abi:e.abi,logs:s,strict:r})}async function Xc(t,{filter:e}){return e.request({method:"eth_uninstallFilter",params:[e.id]})}function sg(t,e){const{abi:r,address:n,args:s,batch:i=!0,eventName:o,fromBlock:a,onError:c,onLogs:u,poll:f,pollingInterval:l=t.pollingInterval,strict:p}=e;return(typeof f<"u"?f:typeof a=="bigint"?!0:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")))?(()=>{const E=p??!1,A=Qe(["watchContractEvent",n,s,i,t.uid,o,l,E,a]);return Tn(A,{onLogs:u,onError:c},P=>{let S;a!==void 0&&(S=a-1n);let w,k=!1;const T=Ki(async()=>{var B;if(!k){try{w=await se(t,Ld,"createContractEventFilter")({abi:r,address:n,args:s,eventName:o,strict:E,fromBlock:a})}catch{}k=!0;return}try{let U;if(w)U=await se(t,Yc,"getFilterChanges")({filter:w});else{const $=await se(t,Sa,"getBlockNumber")({});S&&S<$?U=await se(t,ih,"getContractEvents")({abi:r,address:n,args:s,eventName:o,fromBlock:S+1n,toBlock:$,strict:E}):U=[],S=$}if(U.length===0)return;if(i)P.onLogs(U);else for(const $ of U)P.onLogs([$])}catch(U){w&&U instanceof Ms&&(k=!1),(B=P.onError)==null||B.call(P,U)}},{emitOnBegin:!0,interval:l});return async()=>{w&&await se(t,Xc,"uninstallFilter")({filter:w}),T()}})})():(()=>{const E=p??!1,A=Qe(["watchContractEvent",n,s,i,t.uid,o,l,E]);let P=!0,S=()=>P=!1;return Tn(A,{onLogs:u,onError:c},w=>((async()=>{try{const k=(()=>{if(t.transport.type==="fallback"){const U=t.transport.transports.find($=>$.config.type==="webSocket"||$.config.type==="ipc");return U?U.value:t.transport}return t.transport})(),T=o?pa({abi:r,eventName:o,args:s}):[],{unsubscribe:B}=await k.subscribe({params:["logs",{address:n,topics:T}],onData(U){var D;if(!P)return;const $=U.result;try{const{eventName:M,args:q}=rh({abi:r,data:$.data,topics:$.topics,strict:p}),K=kn($,{args:q,eventName:M});w.onLogs([K])}catch(M){let q,K;if(M instanceof Po||M instanceof Cc){if(p)return;q=M.abiItem.name,K=(D=M.abiItem.inputs)==null?void 0:D.some(G=>!("name"in G&&G.name))}const Q=kn($,{args:K?[]:{},eventName:q});w.onLogs([Q])}},onError(U){var $;($=w.onError)==null||$.call(w,U)}});S=B,P||S()}catch(k){c==null||c(k)}})(),()=>S()))})()}class Js extends L{constructor({docsPath:e}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
|
|
42
|
-
`),{docsPath:e,docsSlug:"account",name:"AccountNotFoundError"})}}class nc extends L{constructor({docsPath:e,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:e,metaMessages:r,name:"AccountTypeNotSupportedError"})}}function ig({chain:t,currentChainId:e}){if(!t)throw new rS;if(e!==t.id)throw new tS({chain:t,currentChainId:e})}function og(t,{docsPath:e,...r}){const n=(()=>{const s=Lc(t,r);return s instanceof ba?t:s})();return new C5(n,{docsPath:e,...r})}async function dh(t,{serializedTransaction:e}){return t.request({method:"eth_sendRawTransaction",params:[e]},{retryCount:0})}const Nu=new Uc(128);async function Jc(t,e){var P,S,w,k;const{account:r=t.account,chain:n=t.chain,accessList:s,authorizationList:i,blobs:o,data:a,gas:c,gasPrice:u,maxFeePerBlobGas:f,maxFeePerGas:l,maxPriorityFeePerGas:p,nonce:d,type:m,value:b,...E}=e;if(typeof r>"u")throw new Js({docsPath:"/docs/actions/wallet/sendTransaction"});const A=r?Ze(r):null;try{Ys(e);const T=await(async()=>{if(e.to)return e.to;if(e.to!==null&&i&&i.length>0)return await Vd({authorization:i[0]}).catch(()=>{throw new L("`to` is required. Could not infer from `authorizationList`.")})})();if((A==null?void 0:A.type)==="json-rpc"||A===null){let B;n!==null&&(B=await se(t,qi,"getChainId")({}),ig({currentChainId:B,chain:n}));const U=(w=(S=(P=t.chain)==null?void 0:P.formatters)==null?void 0:S.transactionRequest)==null?void 0:w.format,D=(U||Vi)({...Dc(E,{format:U}),accessList:s,authorizationList:i,blobs:o,chainId:B,data:a,from:A==null?void 0:A.address,gas:c,gasPrice:u,maxFeePerBlobGas:f,maxFeePerGas:l,maxPriorityFeePerGas:p,nonce:d,to:T,type:m,value:b}),M=Nu.get(t.uid),q=M?"wallet_sendTransaction":"eth_sendTransaction";try{return await t.request({method:q,params:[D]},{retryCount:0})}catch(K){if(M===!1)throw K;const Q=K;if(Q.name==="InvalidInputRpcError"||Q.name==="InvalidParamsRpcError"||Q.name==="MethodNotFoundRpcError"||Q.name==="MethodNotSupportedRpcError")return await t.request({method:"wallet_sendTransaction",params:[D]},{retryCount:0}).then(G=>(Nu.set(t.uid,!0),G)).catch(G=>{const W=G;throw W.name==="MethodNotFoundRpcError"||W.name==="MethodNotSupportedRpcError"?(Nu.set(t.uid,!1),Q):W});throw Q}}if((A==null?void 0:A.type)==="local"){const B=await se(t,Vc,"prepareTransactionRequest")({account:A,accessList:s,authorizationList:i,blobs:o,chain:n,data:a,gas:c,gasPrice:u,maxFeePerBlobGas:f,maxFeePerGas:l,maxPriorityFeePerGas:p,nonce:d,nonceManager:A.nonceManager,parameters:[...Ob,"sidecars"],type:m,value:b,...E,to:T}),U=(k=n==null?void 0:n.serializers)==null?void 0:k.transaction,$=await A.signTransaction(B,{serializer:U});return await se(t,dh,"sendRawTransaction")({serializedTransaction:$})}throw(A==null?void 0:A.type)==="smart"?new nc({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new nc({docsPath:"/docs/actions/wallet/sendTransaction",type:A==null?void 0:A.type})}catch(T){throw T instanceof nc?T:og(T,{...e,account:A,chain:e.chain||void 0})}}async function ag(t,e){const{abi:r,account:n=t.account,address:s,args:i,dataSuffix:o,functionName:a,...c}=e;if(typeof n>"u")throw new Js({docsPath:"/docs/contract/writeContract"});const u=n?Ze(n):null,f=Jt({abi:r,args:i,functionName:a});try{return await se(t,Jc,"sendTransaction")({data:`${f}${o?o.replace("0x",""):""}`,to:s,account:u,...c})}catch(l){throw Fs(l,{abi:r,address:s,args:i,docsPath:"/docs/contract/writeContract",functionName:a,sender:u==null?void 0:u.address})}}function qp({abi:t,address:e,client:r}){const n=r,[s,i]=n?"public"in n&&"wallet"in n?[n.public,n.wallet]:"public"in n?[n.public,void 0]:"wallet"in n?[void 0,n.wallet]:[n,n]:[void 0,void 0],o=s!=null,a=i!=null,c={};let u=!1,f=!1,l=!1;for(const p of t)if(p.type==="function"?p.stateMutability==="view"||p.stateMutability==="pure"?u=!0:f=!0:p.type==="event"&&(l=!0),u&&f&&l)break;return o&&(u&&(c.read=new Proxy({},{get(p,d){return(...m)=>{const{args:b,options:E}=Ua(m);return se(s,hr,"readContract")({abi:t,address:e,functionName:d,args:b,...E})}}})),f&&(c.simulate=new Proxy({},{get(p,d){return(...m)=>{const{args:b,options:E}=Ua(m);return se(s,ng,"simulateContract")({abi:t,address:e,functionName:d,args:b,...E})}}})),l&&(c.createEventFilter=new Proxy({},{get(p,d){return(...m)=>{const b=t.find(P=>P.type==="event"&&P.name===d),{args:E,options:A}=Uu(m,b);return se(s,Ld,"createContractEventFilter")({abi:t,address:e,eventName:d,args:E,...A})}}}),c.getEvents=new Proxy({},{get(p,d){return(...m)=>{const b=t.find(P=>P.type==="event"&&P.name===d),{args:E,options:A}=Uu(m,b);return se(s,ih,"getContractEvents")({abi:t,address:e,eventName:d,args:E,...A})}}}),c.watchEvent=new Proxy({},{get(p,d){return(...m)=>{const b=t.find(P=>P.type==="event"&&P.name===d),{args:E,options:A}=Uu(m,b);return se(s,sg,"watchContractEvent")({abi:t,address:e,eventName:d,args:E,...A})}}}))),a&&f&&(c.write=new Proxy({},{get(p,d){return(...m)=>{const{args:b,options:E}=Ua(m);return se(i,ag,"writeContract")({abi:t,address:e,functionName:d,args:b,...E})}}})),(o||a)&&f&&(c.estimateGas=new Proxy({},{get(p,d){return(...m)=>{const{args:b,options:E}=Ua(m);return se(s??i,Cb,"estimateContractGas")({abi:t,address:e,functionName:d,args:b,...E,account:E.account??i.account})}}})),c.address=e,c.abi=t,c}function Ua(t){const e=t.length&&Array.isArray(t[0]),r=e?t[0]:[],n=(e?t[1]:t[0])??{};return{args:r,options:n}}function Uu(t,e){let r=!1;Array.isArray(t[0])?r=!0:t.length===1?r=e.inputs.some(i=>i.indexed):t.length===2&&(r=!0);const n=r?t[0]:void 0,s=(r?t[1]:t[0])??{};return{args:n,options:s}}class hS extends L{constructor(e){super(`Call bundle failed with status: ${e.statusCode}`,{name:"BundleFailedError"}),Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=e}}function vc(t,{delay:e=100,retryCount:r=2,shouldRetry:n=()=>!0}={}){return new Promise((s,i)=>{const o=async({count:a=0}={})=>{const c=async({error:u})=>{const f=typeof e=="function"?e({count:a,error:u}):e;f&&await zl(f),o({count:a+1})};try{const u=await t();s(u)}catch(u){if(a<r&&await n({count:a,error:u}))return c({error:u});i(u)}};o()})}const cg={"0x0":"reverted","0x1":"success"};function ug(t){const e={...t,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,contractAddress:t.contractAddress?t.contractAddress:null,cumulativeGasUsed:t.cumulativeGasUsed?BigInt(t.cumulativeGasUsed):null,effectiveGasPrice:t.effectiveGasPrice?BigInt(t.effectiveGasPrice):null,gasUsed:t.gasUsed?BigInt(t.gasUsed):null,logs:t.logs?t.logs.map(r=>kn(r)):null,to:t.to?t.to:null,transactionIndex:t.transactionIndex?dr(t.transactionIndex):null,status:t.status?cg[t.status]:null,type:t.type?bb[t.type]||t.type:null};return t.blobGasPrice&&(e.blobGasPrice=BigInt(t.blobGasPrice)),t.blobGasUsed&&(e.blobGasUsed=BigInt(t.blobGasUsed)),e}const pS=qd("transactionReceipt",ug),fg="0x5792579257925792579257925792579257925792579257925792579257925792",lg=Z(0,{size:32});async function yS(t,e){const{account:r=t.account,capabilities:n,chain:s=t.chain,experimental_fallback:i,experimental_fallbackDelay:o=32,forceAtomic:a=!1,id:c,version:u="2.0.0"}=e,f=r?Ze(r):null,l=e.calls.map(p=>{const d=p,m=d.abi?Jt({abi:d.abi,functionName:d.functionName,args:d.args}):d.data;return{data:d.dataSuffix&&m?Kt([m,d.dataSuffix]):m,to:d.to,value:d.value?Z(d.value):void 0}});try{const p=await t.request({method:"wallet_sendCalls",params:[{atomicRequired:a,calls:l,capabilities:n,chainId:Z(s.id),from:f==null?void 0:f.address,id:c,version:u}]},{retryCount:0});return typeof p=="string"?{id:p}:p}catch(p){const d=p;if(i&&(d.name==="MethodNotFoundRpcError"||d.name==="MethodNotSupportedRpcError"||d.name==="UnknownRpcError"||d.details.toLowerCase().includes("does not exist / is not available")||d.details.toLowerCase().includes("missing or invalid. request()")||d.details.toLowerCase().includes("did not match any variant of untagged enum")||d.details.toLowerCase().includes("account upgraded to unsupported contract")||d.details.toLowerCase().includes("eip-7702 not supported")||d.details.toLowerCase().includes("unsupported wc_ method")||d.details.toLowerCase().includes("feature toggled misconfigured"))){if(n&&Object.values(n).some(P=>!P.optional)){const P="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new $i(new L(P,{details:P}))}if(a&&l.length>1){const A="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new Ri(new L(A,{details:A}))}const m=[];for(const A of l){const P=Jc(t,{account:f,chain:s,data:A.data,to:A.to,value:A.value?ut(A.value):void 0});m.push(P),o>0&&await new Promise(S=>setTimeout(S,o))}const b=await Promise.allSettled(m);if(b.every(A=>A.status==="rejected"))throw b[0].reason;const E=b.map(A=>A.status==="fulfilled"?A.value:lg);return{id:Kt([...E,Z(s.id,{size:32}),fg])}}throw og(p,{...e,account:f,chain:e.chain})}}async function dg(t,e){async function r(f){if(f.endsWith(fg.slice(2))){const p=lr(Tl(f,-64,-32)),d=Tl(f,0,-64).slice(2).match(/.{1,64}/g),m=await Promise.all(d.map(E=>lg.slice(2)!==E?t.request({method:"eth_getTransactionReceipt",params:[`0x${E}`]},{dedupe:!0}):void 0)),b=m.some(E=>E===null)?100:m.every(E=>(E==null?void 0:E.status)==="0x1")?200:m.every(E=>(E==null?void 0:E.status)==="0x0")?500:600;return{atomic:!1,chainId:dr(p),receipts:m.filter(Boolean),status:b,version:"2.0.0"}}return t.request({method:"wallet_getCallsStatus",params:[f]})}const{atomic:n=!1,chainId:s,receipts:i,version:o="2.0.0",...a}=await r(e.id),[c,u]=(()=>{const f=a.status;return f>=100&&f<200?["pending",f]:f>=200&&f<300?["success",f]:f>=300&&f<700?["failure",f]:f==="CONFIRMED"?["success",200]:f==="PENDING"?["pending",100]:[void 0,f]})();return{...a,atomic:n,chainId:s?dr(s):void 0,receipts:(i==null?void 0:i.map(f=>({...f,blockNumber:ut(f.blockNumber),gasUsed:ut(f.gasUsed),status:cg[f.status]})))??[],statusCode:u,status:c,version:o}}async function mS(t,e){const{id:r,pollingInterval:n=t.pollingInterval,status:s=({statusCode:b})=>b===200||b>=300,retryCount:i=4,retryDelay:o=({count:b})=>~~(1<<b)*200,timeout:a=6e4,throwOnFailure:c=!1}=e,u=Qe(["waitForCallsStatus",t.uid,r]),{promise:f,resolve:l,reject:p}=lh();let d;const m=Tn(u,{resolve:l,reject:p},b=>{const E=Ki(async()=>{const A=P=>{clearTimeout(d),E(),P(),m()};try{const P=await vc(async()=>{const S=await se(t,dg,"getCallsStatus")({id:r});if(c&&S.status==="failure")throw new hS(S);return S},{retryCount:i,delay:o});if(!s(P))return;A(()=>b.resolve(P))}catch(P){A(()=>b.reject(P))}},{interval:n,emitOnBegin:!0});return E});return d=a?setTimeout(()=>{m(),clearTimeout(d),p(new bS({id:r}))},a):void 0,await f}class bS extends L{constructor({id:e}){super(`Timed out while waiting for call bundle with id "${e}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}const Vl=256;let Ma=Vl,Fa;function hg(t=11){if(!Fa||Ma+t>Vl*2){Fa="",Ma=0;for(let e=0;e<Vl;e++)Fa+=(256+Math.random()*256|0).toString(16).substring(1)}return Fa.substring(Ma,Ma+++t)}function pg(t){const{batch:e,chain:r,ccipRead:n,key:s="base",name:i="Base Client",type:o="base"}=t,a=t.experimental_blockTag??(typeof(r==null?void 0:r.experimental_preconfirmationTime)=="number"?"pending":void 0),c=(r==null?void 0:r.blockTime)??12e3,u=Math.min(Math.max(Math.floor(c/2),500),4e3),f=t.pollingInterval??u,l=t.cacheTime??f,p=t.account?Ze(t.account):void 0,{config:d,request:m,value:b}=t.transport({chain:r,pollingInterval:f}),E={...d,...b},A={account:p,batch:e,cacheTime:l,ccipRead:n,chain:r,key:s,name:i,pollingInterval:f,request:m,transport:E,type:o,uid:hg(),...a?{experimental_blockTag:a}:{}};function P(S){return w=>{const k=w(S);for(const B in A)delete k[B];const T={...S,...k};return Object.assign(T,{extend:P(T)})}}return Object.assign(A,{extend:P(A)})}function hh(t){var r,n,s,i,o,a;if(!(t instanceof L))return!1;const e=t.walk(c=>c instanceof Il);return e instanceof Il?((r=e.data)==null?void 0:r.errorName)==="HttpError"||((n=e.data)==null?void 0:n.errorName)==="ResolverError"||((s=e.data)==null?void 0:s.errorName)==="ResolverNotContract"||((i=e.data)==null?void 0:i.errorName)==="ResolverNotFound"||((o=e.data)==null?void 0:o.errorName)==="ReverseAddressMismatch"||((a=e.data)==null?void 0:a.errorName)==="UnsupportedResolverProfile":!1}function gS(t){const{abi:e,data:r}=t,n=Ns(r,0,4),s=e.find(i=>i.type==="function"&&n===ha(_r(i)));if(!s)throw new iv(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:s.name,args:"inputs"in s&&s.inputs&&s.inputs.length>0?ya(s.inputs,Ns(r,4)):void 0}}const Mu="/docs/contract/encodeErrorResult";function Gp(t){const{abi:e,errorName:r,args:n}=t;let s=e[0];if(r){const c=Zs({abi:e,args:n,name:r});if(!c)throw new yp(r,{docsPath:Mu});s=c}if(s.type!=="error")throw new yp(void 0,{docsPath:Mu});const i=_r(s),o=ha(i);let a="0x";if(n&&n.length>0){if(!s.inputs)throw new nv(s.name,{docsPath:Mu});a=fs(s.inputs,n)}return $r([o,a])}const Fu="/docs/contract/encodeFunctionResult";function wS(t){const{abi:e,functionName:r,result:n}=t;let s=e[0];if(r){const o=Zs({abi:e,name:r});if(!o)throw new Oi(r,{docsPath:Fu});s=o}if(s.type!=="function")throw new Oi(void 0,{docsPath:Fu});if(!s.outputs)throw new $m(s.name,{docsPath:Fu});const i=(()=>{if(s.outputs.length===0)return[];if(s.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new Rm(n)})();return fs(s.outputs,i)}const Aa="x-batch-gateway:true";async function yg(t){const{data:e,ccipRequest:r}=t,{args:[n]}=gS({abi:Dl,data:e}),s=[],i=[];return await Promise.all(n.map(async(o,a)=>{try{i[a]=o.urls.includes(Aa)?await yg({data:o.data,ccipRequest:r}):await r(o),s[a]=!1}catch(c){s[a]=!0,i[a]=vS(c)}})),wS({abi:Dl,functionName:"query",result:[s,i]})}function vS(t){return t.name==="HttpRequestError"&&t.status?Gp({abi:Dl,errorName:"HttpError",args:[t.status,t.shortMessage]}):Gp({abi:[sb],errorName:"Error",args:["shortMessage"in t?t.shortMessage:t.message]})}function mg(t){if(t.length!==66||t.indexOf("[")!==0||t.indexOf("]")!==65)return null;const e=`0x${t.slice(1,65)}`;return Pr(e)?e:null}function ql(t){let e=new Uint8Array(32).fill(0);if(!t)return et(e);const r=t.split(".");for(let n=r.length-1;n>=0;n-=1){const s=mg(r[n]),i=s?zi(s):ht(_s(r[n]),"bytes");e=ht(Kt([e,i]),"bytes")}return et(e)}function ES(t){return`[${t.slice(2)}]`}function SS(t){const e=new Uint8Array(32).fill(0);return t?mg(t)||ht(_s(t)):et(e)}function ph(t){const e=t.replace(/^\.|\.$/gm,"");if(e.length===0)return new Uint8Array(1);const r=new Uint8Array(_s(e).byteLength+2);let n=0;const s=e.split(".");for(let i=0;i<s.length;i++){let o=_s(s[i]);o.byteLength>255&&(o=_s(ES(SS(s[i])))),r[n]=o.length,r.set(o,n+1),n+=o.length+1}return r.byteLength!==n+1?r.slice(0,n+1):r}async function AS(t,e){const{blockNumber:r,blockTag:n,coinType:s,name:i,gatewayUrls:o,strict:a}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Wi({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),f=c==null?void 0:c.ensTlds;if(f&&!f.some(p=>i.endsWith(p)))return null;const l=s!=null?[ql(i),BigInt(s)]:[ql(i)];try{const p=Jt({abi:Hp,functionName:"addr",args:l}),d={address:u,abi:Yb,functionName:"resolveWithGateways",args:[Bt(ph(i)),p,o??[Aa]],blockNumber:r,blockTag:n},b=await se(t,hr,"readContract")(d);if(b[0]==="0x")return null;const E=Xs({abi:Hp,args:l,functionName:"addr",data:b[0]});return E==="0x"||lr(E)==="0x00"?null:E}catch(p){if(a)throw p;if(hh(p))return null;throw p}}class xS extends L{constructor({data:e}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(e)}`],name:"EnsAvatarInvalidMetadataError"})}}class ro extends L{constructor({reason:e}){super(`ENS NFT avatar URI is invalid. ${e}`,{name:"EnsAvatarInvalidNftUriError"})}}class yh extends L{constructor({uri:e}){super(`Unable to resolve ENS avatar URI "${e}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class kS extends L{constructor({namespace:e}){super(`ENS NFT avatar namespace "${e}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const TS=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,_S=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,PS=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,IS=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function OS(t){try{const e=await fetch(t,{method:"HEAD"});if(e.status===200){const r=e.headers.get("content-type");return r==null?void 0:r.startsWith("image/")}return!1}catch(e){return typeof e=="object"&&typeof e.response<"u"||!Object.hasOwn(globalThis,"Image")?!1:new Promise(r=>{const n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=t})}}function Wp(t,e){return t?t.endsWith("/")?t.slice(0,-1):t:e}function bg({uri:t,gatewayUrls:e}){const r=PS.test(t);if(r)return{uri:t,isOnChain:!0,isEncoded:r};const n=Wp(e==null?void 0:e.ipfs,"https://ipfs.io"),s=Wp(e==null?void 0:e.arweave,"https://arweave.net"),i=t.match(TS),{protocol:o,subpath:a,target:c,subtarget:u=""}=(i==null?void 0:i.groups)||{},f=o==="ipns:/"||a==="ipns/",l=o==="ipfs:/"||a==="ipfs/"||_S.test(t);if(t.startsWith("http")&&!f&&!l){let d=t;return e!=null&&e.arweave&&(d=t.replace(/https:\/\/arweave.net/g,e==null?void 0:e.arweave)),{uri:d,isOnChain:!1,isEncoded:!1}}if((f||l)&&c)return{uri:`${n}/${f?"ipns":"ipfs"}/${c}${u}`,isOnChain:!1,isEncoded:!1};if(o==="ar:/"&&c)return{uri:`${s}/${c}${u||""}`,isOnChain:!1,isEncoded:!1};let p=t.replace(IS,"");if(p.startsWith("<svg")&&(p=`data:image/svg+xml;base64,${btoa(p)}`),p.startsWith("data:")||p.startsWith("{"))return{uri:p,isOnChain:!0,isEncoded:!1};throw new yh({uri:t})}function gg(t){if(typeof t!="object"||!("image"in t)&&!("image_url"in t)&&!("image_data"in t))throw new xS({data:t});return t.image||t.image_url||t.image_data}async function BS({gatewayUrls:t,uri:e}){try{const r=await fetch(e).then(s=>s.json());return await mh({gatewayUrls:t,uri:gg(r)})}catch{throw new yh({uri:e})}}async function mh({gatewayUrls:t,uri:e}){const{uri:r,isOnChain:n}=bg({uri:e,gatewayUrls:t});if(n||await OS(r))return r;throw new yh({uri:e})}function CS(t){let e=t;e.startsWith("did:nft:")&&(e=e.replace("did:nft:","").replace(/_/g,"/"));const[r,n,s]=e.split("/"),[i,o]=r.split(":"),[a,c]=n.split(":");if(!i||i.toLowerCase()!=="eip155")throw new ro({reason:"Only EIP-155 supported"});if(!o)throw new ro({reason:"Chain ID not found"});if(!c)throw new ro({reason:"Contract address not found"});if(!s)throw new ro({reason:"Token ID not found"});if(!a)throw new ro({reason:"ERC namespace not found"});return{chainID:Number.parseInt(o,10),namespace:a.toLowerCase(),contractAddress:c,tokenID:s}}async function $S(t,{nft:e}){if(e.namespace==="erc721")return hr(t,{address:e.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(e.tokenID)]});if(e.namespace==="erc1155")return hr(t,{address:e.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(e.tokenID)]});throw new kS({namespace:e.namespace})}async function RS(t,{gatewayUrls:e,record:r}){return/eip155:/i.test(r)?NS(t,{gatewayUrls:e,record:r}):mh({uri:r,gatewayUrls:e})}async function NS(t,{gatewayUrls:e,record:r}){const n=CS(r),s=await $S(t,{nft:n}),{uri:i,isOnChain:o,isEncoded:a}=bg({uri:s,gatewayUrls:e});if(o&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){const u=a?atob(i.replace("data:application/json;base64,","")):i,f=JSON.parse(u);return mh({uri:gg(f),gatewayUrls:e})}let c=n.tokenID;return n.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),BS({gatewayUrls:e,uri:i.replace(/(?:0x)?{id}/,c)})}async function wg(t,e){const{blockNumber:r,blockTag:n,key:s,name:i,gatewayUrls:o,strict:a}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Wi({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),f=c==null?void 0:c.ensTlds;if(f&&!f.some(l=>i.endsWith(l)))return null;try{const l={address:u,abi:Yb,args:[Bt(ph(i)),Jt({abi:Dp,functionName:"text",args:[ql(i),s]}),o??[Aa]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},d=await se(t,hr,"readContract")(l);if(d[0]==="0x")return null;const m=Xs({abi:Dp,functionName:"text",data:d[0]});return m===""?null:m}catch(l){if(a)throw l;if(hh(l))return null;throw l}}async function US(t,{blockNumber:e,blockTag:r,assetGatewayUrls:n,name:s,gatewayUrls:i,strict:o,universalResolverAddress:a}){const c=await se(t,wg,"getEnsText")({blockNumber:e,blockTag:r,key:"avatar",name:s,universalResolverAddress:a,gatewayUrls:i,strict:o});if(!c)return null;try{return await RS(t,{record:c,gatewayUrls:n})}catch{return null}}async function MS(t,e){const{address:r,blockNumber:n,blockTag:s,coinType:i=60n,gatewayUrls:o,strict:a}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Wi({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{const f={address:u,abi:XE,args:[r,i,o??[Aa]],functionName:"reverseWithGateways",blockNumber:n,blockTag:s},l=se(t,hr,"readContract"),[p]=await l(f);return p||null}catch(f){if(a)throw f;if(hh(f))return null;throw f}}async function FS(t,e){const{blockNumber:r,blockTag:n,name:s}=e,{chain:i}=t,o=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!i)throw new Error("client chain not configured. universalResolverAddress is required.");return Wi({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),a=i==null?void 0:i.ensTlds;if(a&&!a.some(u=>s.endsWith(u)))throw new Error(`${s} is not a valid ENS TLD (${a==null?void 0:a.join(", ")}) for chain "${i.name}" (id: ${i.id}).`);const[c]=await se(t,hr,"readContract")({address:o,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[Bt(ph(s))],blockNumber:r,blockTag:n});return c}async function vg(t,e){var E,A,P;const{account:r=t.account,blockNumber:n,blockTag:s="latest",blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:f,maxPriorityFeePerGas:l,to:p,value:d,...m}=e,b=r?Ze(r):void 0;try{Ys(e);const w=(typeof n=="bigint"?Z(n):void 0)||s,k=(P=(A=(E=t.chain)==null?void 0:E.formatters)==null?void 0:A.transactionRequest)==null?void 0:P.format,B=(k||Vi)({...Dc(m,{format:k}),from:b==null?void 0:b.address,blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:f,maxPriorityFeePerGas:l,to:p,value:d}),U=await t.request({method:"eth_createAccessList",params:[B,w]});return{accessList:U.accessList,gasUsed:BigInt(U.gasUsed)}}catch(S){throw eg(S,{...e,account:b,chain:t.chain})}}async function jS(t){const e=Mc(t,{method:"eth_newBlockFilter"}),r=await t.request({method:"eth_newBlockFilter"});return{id:r,request:e(r),type:"block"}}async function Eg(t,{address:e,args:r,event:n,events:s,fromBlock:i,strict:o,toBlock:a}={}){const c=s??(n?[n]:void 0),u=Mc(t,{method:"eth_newFilter"});let f=[];c&&(f=[c.flatMap(d=>pa({abi:[d],eventName:d.name,args:r}))],n&&(f=f[0]));const l=await t.request({method:"eth_newFilter",params:[{address:e,fromBlock:typeof i=="bigint"?Z(i):i,toBlock:typeof a=="bigint"?Z(a):a,...f.length?{topics:f}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:i,id:l,request:u(l),strict:!!o,toBlock:a,type:"event"}}async function Sg(t){const e=Mc(t,{method:"eth_newPendingTransactionFilter"}),r=await t.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:e(r),type:"transaction"}}async function LS(t){const e=await t.request({method:"eth_blobBaseFee"});return BigInt(e)}async function DS(t,{blockHash:e,blockNumber:r,blockTag:n="latest"}={}){const s=r!==void 0?Z(r):void 0;let i;return e?i=await t.request({method:"eth_getBlockTransactionCountByHash",params:[e]},{dedupe:!0}):i=await t.request({method:"eth_getBlockTransactionCountByNumber",params:[s||n]},{dedupe:!!s}),dr(i)}async function Gl(t,{address:e,blockNumber:r,blockTag:n="latest"}){const s=r!==void 0?Z(r):void 0,i=await t.request({method:"eth_getCode",params:[e,s||n]},{dedupe:!!s});if(i!=="0x")return i}class HS extends L{constructor({address:e}){super(`No EIP-712 domain found on contract "${e}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${e}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function zS(t,e){const{address:r,factory:n,factoryData:s}=e;try{const[i,o,a,c,u,f,l]=await se(t,hr,"readContract")({abi:VS,address:r,functionName:"eip712Domain",factory:n,factoryData:s});return{domain:{name:o,version:a,chainId:Number(c),verifyingContract:u,salt:f},extensions:l,fields:i}}catch(i){const o=i;throw o.name==="ContractFunctionExecutionError"&&o.cause.name==="ContractFunctionZeroDataError"?new HS({address:r}):o}}const VS=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];function qS(t){var e;return{baseFeePerGas:t.baseFeePerGas.map(r=>BigInt(r)),gasUsedRatio:t.gasUsedRatio,oldestBlock:BigInt(t.oldestBlock),reward:(e=t.reward)==null?void 0:e.map(r=>r.map(n=>BigInt(n)))}}async function GS(t,{blockCount:e,blockNumber:r,blockTag:n="latest",rewardPercentiles:s}){const i=typeof r=="bigint"?Z(r):void 0,o=await t.request({method:"eth_feeHistory",params:[Z(e),i||n,s]},{dedupe:!!i});return qS(o)}async function WS(t,{filter:e}){const r=e.strict??!1,s=(await e.request({method:"eth_getFilterLogs",params:[e.id]})).map(i=>kn(i));return e.abi?nh({abi:e.abi,logs:s,strict:r}):s}function KS(t){const{authorizationList:e}=t;if(e)for(const r of e){const{chainId:n}=r,s=r.address;if(!at(s))throw new $t({address:s});if(n<0)throw new Kc({chainId:n})}bh(t)}function ZS(t){const{blobVersionedHashes:e}=t;if(e){if(e.length===0)throw new _b;for(const r of e){const n=He(r),s=dr(Ns(r,0,1));if(n!==32)throw new pE({hash:r,size:n});if(s!==Tb)throw new yE({hash:r,version:s})}}bh(t)}function bh(t){const{chainId:e,maxPriorityFeePerGas:r,maxFeePerGas:n,to:s}=t;if(e<=0)throw new Kc({chainId:e});if(s&&!at(s))throw new $t({address:s});if(n&&n>Hc)throw new js({maxFeePerGas:n});if(r&&n&&r>n)throw new Zo({maxFeePerGas:n,maxPriorityFeePerGas:r})}function YS(t){const{chainId:e,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=t;if(e<=0)throw new Kc({chainId:e});if(i&&!at(i))throw new $t({address:i});if(r||s)throw new L("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Hc)throw new js({maxFeePerGas:n})}function XS(t){const{chainId:e,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=t;if(i&&!at(i))throw new $t({address:i});if(typeof e<"u"&&e<=0)throw new Kc({chainId:e});if(r||s)throw new L("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Hc)throw new js({maxFeePerGas:n})}function Qc(t){if(!t||t.length===0)return[];const e=[];for(let r=0;r<t.length;r++){const{address:n,storageKeys:s}=t[r];for(let i=0;i<s.length;i++)if(s[i].length-2!==64)throw new B5({storageKey:s[i]});if(!at(n,{strict:!1}))throw new $t({address:n});e.push([n,s])}return e}function JS(t,e){const r=Ib(t);return r==="eip1559"?t8(t,e):r==="eip2930"?r8(t,e):r==="eip4844"?e8(t,e):r==="eip7702"?QS(t,e):n8(t,e)}function QS(t,e){const{authorizationList:r,chainId:n,gas:s,nonce:i,to:o,value:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:f,data:l}=t;KS(t);const p=Qc(f),d=s8(r);return $r(["0x04",as([Z(n),i?Z(i):"0x",u?Z(u):"0x",c?Z(c):"0x",s?Z(s):"0x",o??"0x",a?Z(a):"0x",l??"0x",p,d,...xa(t,e)])])}function e8(t,e){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:f,data:l}=t;ZS(t);let p=t.blobVersionedHashes,d=t.sidecars;if(t.blobs&&(typeof p>"u"||typeof d>"u")){const S=typeof t.blobs[0]=="string"?t.blobs:t.blobs.map(T=>et(T)),w=t.kzg,k=Xd({blobs:S,kzg:w});if(typeof p>"u"&&(p=Ab({commitments:k})),typeof d>"u"){const T=Jd({blobs:S,commitments:k,kzg:w});d=Pb({blobs:S,commitments:k,proofs:T})}}const m=Qc(f),b=[Z(r),s?Z(s):"0x",u?Z(u):"0x",c?Z(c):"0x",n?Z(n):"0x",i??"0x",o?Z(o):"0x",l??"0x",m,a?Z(a):"0x",p??[],...xa(t,e)],E=[],A=[],P=[];if(d)for(let S=0;S<d.length;S++){const{blob:w,commitment:k,proof:T}=d[S];E.push(w),A.push(k),P.push(T)}return $r(["0x03",as(d?[b,E,A,P]:b)])}function t8(t,e){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:u,data:f}=t;bh(t);const l=Qc(u),p=[Z(r),s?Z(s):"0x",c?Z(c):"0x",a?Z(a):"0x",n?Z(n):"0x",i??"0x",o?Z(o):"0x",f??"0x",l,...xa(t,e)];return $r(["0x02",as(p)])}function r8(t,e){const{chainId:r,gas:n,data:s,nonce:i,to:o,value:a,accessList:c,gasPrice:u}=t;YS(t);const f=Qc(c),l=[Z(r),i?Z(i):"0x",u?Z(u):"0x",n?Z(n):"0x",o??"0x",a?Z(a):"0x",s??"0x",f,...xa(t,e)];return $r(["0x01",as(l)])}function n8(t,e){const{chainId:r=0,gas:n,data:s,nonce:i,to:o,value:a,gasPrice:c}=t;XS(t);let u=[i?Z(i):"0x",c?Z(c):"0x",n?Z(n):"0x",o??"0x",a?Z(a):"0x",s??"0x"];if(e){const f=(()=>{if(e.v>=35n)return(e.v-35n)/2n>0?e.v:27n+(e.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+e.v-27n);const d=27n+(e.v===27n?0n:1n);if(e.v!==d)throw new I5({v:e.v});return d})(),l=lr(e.r),p=lr(e.s);u=[...u,Z(f),l==="0x00"?"0x":l,p==="0x00"?"0x":p]}else r>0&&(u=[...u,Z(r),"0x","0x"]);return as(u)}function xa(t,e){const r=e??t,{v:n,yParity:s}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof s>"u")return[];const i=lr(r.r),o=lr(r.s);return[typeof s=="number"?s?Z(1):"0x":n===0n?"0x":n===1n?Z(1):n===27n?"0x":Z(1),i==="0x00"?"0x":i,o==="0x00"?"0x":o]}function s8(t){if(!t||t.length===0)return[];const e=[];for(const r of t){const{chainId:n,nonce:s,...i}=r,o=r.address;e.push([n?Bt(n):"0x",o,s?Bt(s):"0x",...xa({},i)])}return e}async function i8({address:t,authorization:e,signature:r}){return Gi(Ud(t),await Vd({authorization:e,signature:r}))}const ja=new Uc(8192);function o8(t,{enabled:e=!0,id:r}){if(!e||!r)return t();if(ja.get(r))return ja.get(r);const n=t().finally(()=>ja.delete(r));return ja.set(r,n),n}function a8(t,e={}){return async(r,n={})=>{var l;const{dedupe:s=!1,methods:i,retryDelay:o=150,retryCount:a=3,uid:c}={...e,...n},{method:u}=r;if((l=i==null?void 0:i.exclude)!=null&&l.includes(u))throw new vs(new Error("method not supported"),{method:u});if(i!=null&&i.include&&!i.include.includes(u))throw new vs(new Error("method not supported"),{method:u});const f=s?Bi(`${c}.${Qe(r)}`):void 0;return o8(()=>vc(async()=>{try{return await t(r)}catch(p){const d=p;switch(d.code){case Bo.code:throw new Bo(d);case Co.code:throw new Co(d);case $o.code:throw new $o(d,{method:r.method});case Ro.code:throw new Ro(d);case Us.code:throw new Us(d);case Ms.code:throw new Ms(d);case No.code:throw new No(d);case Uo.code:throw new Uo(d);case Mo.code:throw new Mo(d);case vs.code:throw new vs(d,{method:r.method});case Ci.code:throw new Ci(d);case Fo.code:throw new Fo(d);case Ei.code:throw new Ei(d);case jo.code:throw new jo(d);case Lo.code:throw new Lo(d);case Do.code:throw new Do(d);case Ho.code:throw new Ho(d);case zo.code:throw new zo(d);case $i.code:throw new $i(d);case Vo.code:throw new Vo(d);case qo.code:throw new qo(d);case Go.code:throw new Go(d);case Wo.code:throw new Wo(d);case Ko.code:throw new Ko(d);case Ri.code:throw new Ri(d);case 5e3:throw new Ei(d);default:throw p instanceof L?p:new F5(d)}}},{delay:({count:p,error:d})=>{var m;if(d&&d instanceof vi){const b=(m=d==null?void 0:d.headers)==null?void 0:m.get("Retry-After");if(b!=null&&b.match(/\d/))return Number.parseInt(b,10)*1e3}return~~(1<<p)*o},retryCount:a,shouldRetry:({error:p})=>c8(p)}),{enabled:s,id:f})}}function c8(t){return"code"in t&&typeof t.code=="number"?t.code===-1||t.code===Ci.code||t.code===Us.code:t instanceof vi&&t.status?t.status===403||t.status===408||t.status===413||t.status===429||t.status===500||t.status===502||t.status===503||t.status===504:!0}function yt(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}const u8=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Ag=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),f8=Ag.map(t=>(9*t+5)%16),xg=(()=>{const r=[[Ag],[f8]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>u8[i]));return r})(),kg=xg[0],Tg=xg[1],_g=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),l8=kg.map((t,e)=>t.map(r=>_g[e][r])),d8=Tg.map((t,e)=>t.map(r=>_g[e][r])),h8=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),p8=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Kp(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}const La=new Uint32Array(16);let Pg=class extends wb{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:r,h2:n,h3:s,h4:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=s|0,this.h4=i|0}process(e,r){for(let d=0;d<16;d++,r+=4)La[d]=e.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,o=i,a=this.h2|0,c=a,u=this.h3|0,f=u,l=this.h4|0,p=l;for(let d=0;d<5;d++){const m=4-d,b=h8[d],E=p8[d],A=kg[d],P=Tg[d],S=l8[d],w=d8[d];for(let k=0;k<16;k++){const T=Ra(n+Kp(d,i,a,u)+La[A[k]]+b,S[k])+l|0;n=l,l=u,u=Ra(a,10)|0,a=i,i=T}for(let k=0;k<16;k++){const T=Ra(s+Kp(m,o,c,f)+La[P[k]]+E,w[k])+p|0;s=p,p=f,f=Ra(c,10)|0,c=o,o=T}}this.set(this.h1+a+f|0,this.h2+u+p|0,this.h3+l+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){Ir(La)}destroy(){this.destroyed=!0,Ir(this.buffer),this.set(0,0,0,0,0)}};const y8=Rc(()=>new Pg),m8=Pg,b8=y8,g8=Object.freeze(Object.defineProperty({__proto__:null,RIPEMD160:m8,ripemd160:b8},Symbol.toStringTag,{value:"Module"}));function w8(t,{errorInstance:e=new Error("timed out"),timeout:r,signal:n}){return new Promise((s,i)=>{(async()=>{let o;try{const a=new AbortController;r>0&&(o=setTimeout(()=>{n&&a.abort()},r)),s(await t({signal:(a==null?void 0:a.signal)||null}))}catch(a){(a==null?void 0:a.name)==="AbortError"&&i(e),i(a)}finally{clearTimeout(o)}})()})}function v8(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const Zp=v8();function E8(t,e={}){return{async request(r){var p;const{body:n,fetchFn:s=e.fetchFn??fetch,onRequest:i=e.onRequest,onResponse:o=e.onResponse,timeout:a=e.timeout??1e4}=r,c={...e.fetchOptions??{},...r.fetchOptions??{}},{headers:u,method:f,signal:l}=c;try{const d=await w8(async({signal:b})=>{const E={...c,body:Array.isArray(n)?Qe(n.map(w=>({jsonrpc:"2.0",id:w.id??Zp.take(),...w}))):Qe({jsonrpc:"2.0",id:n.id??Zp.take(),...n}),headers:{"Content-Type":"application/json",...u},method:f||"POST",signal:l||(a>0?b:null)},A=new Request(t,E),P=await(i==null?void 0:i(A,E))??{...E,url:t};return await s(P.url??t,P)},{errorInstance:new Pp({body:n,url:t}),timeout:a,signal:!0});o&&await o(d);let m;if((p=d.headers.get("Content-Type"))!=null&&p.startsWith("application/json"))m=await d.json();else{m=await d.text();try{m=JSON.parse(m||"{}")}catch(b){if(d.ok)throw b;m={error:m}}}if(!d.ok)throw new vi({body:n,details:Qe(m.error)||d.statusText,headers:d.headers,status:d.status,url:t});return m}catch(d){throw d instanceof vi||d instanceof Pp?d:new vi({body:n,cause:d,url:t})}}}}const S8=`Ethereum Signed Message:
|
|
43
|
-
`;function
|
|
44
|
-
`);super(i),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=s,this.metaMessages=r.metaMessages,this.shortMessage=e}}function $n(t,e){const r=t.exec(e);return r==null?void 0:r.groups}const Ug=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Mg=/^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)?$/,Fg=/^\(.+?\).*?$/,Yp=/^tuple(?<array>(\[(\d*)\])*)$/;function Wl(t){let e=t.type;if(Yp.test(t.type)&&"components"in t){e="(";const r=t.components.length;for(let s=0;s<r;s++){const i=t.components[s];e+=Wl(i),s<r-1&&(e+=", ")}const n=$n(Yp,t.type);return e+=`)${(n==null?void 0:n.array)??""}`,Wl({...t,type:e})}return"indexed"in t&&t.indexed&&(e=`${e} indexed`),t.name?`${e} ${t.name}`:e}function ci(t){let e="";const r=t.length;for(let n=0;n<r;n++){const s=t[n];e+=Wl(s),n!==r-1&&(e+=", ")}return e}function Kl(t){var e;return t.type==="function"?`function ${t.name}(${ci(t.inputs)})${t.stateMutability&&t.stateMutability!=="nonpayable"?` ${t.stateMutability}`:""}${(e=t.outputs)!=null&&e.length?` returns (${ci(t.outputs)})`:""}`:t.type==="event"?`event ${t.name}(${ci(t.inputs)})`:t.type==="error"?`error ${t.name}(${ci(t.inputs)})`:t.type==="constructor"?`constructor(${ci(t.inputs)})${t.stateMutability==="payable"?" payable":""}`:t.type==="fallback"?`fallback() external${t.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const jg=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function R8(t){return jg.test(t)}function N8(t){return $n(jg,t)}const Lg=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function U8(t){return Lg.test(t)}function M8(t){return $n(Lg,t)}const Dg=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function F8(t){return Dg.test(t)}function j8(t){return $n(Dg,t)}const Hg=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function gh(t){return Hg.test(t)}function L8(t){return $n(Hg,t)}const zg=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function D8(t){return zg.test(t)}function H8(t){return $n(zg,t)}const Vg=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function z8(t){return Vg.test(t)}function V8(t){return $n(Vg,t)}const q8=/^receive\(\) external payable$/;function G8(t){return q8.test(t)}const Xp=new Set(["memory","indexed","storage","calldata"]),W8=new Set(["indexed"]),Zl=new Set(["calldata","memory","storage"]);class K8 extends pt{constructor({signature:e}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}}class Z8 extends pt{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}}class Y8 extends pt{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}class X8 extends pt{constructor({params:e}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}}class J8 extends pt{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}}class Q8 extends pt{constructor({param:e,name:r}){super("Invalid ABI parameter.",{details:e,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}}class eA extends pt{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}}class tA extends pt{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}}class rA extends pt{constructor({abiParameter:e}){super("Invalid ABI parameter.",{details:JSON.stringify(e,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}class Zi extends pt{constructor({signature:e,type:r}){super(`Invalid ${r} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}}class nA extends pt{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}}class sA extends pt{constructor({signature:e}){super("Invalid struct signature.",{details:e,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}class iA extends pt{constructor({type:e}){super("Circular reference detected.",{metaMessages:[`Struct "${e}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}class oA extends pt{constructor({current:e,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${e.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}function aA(t,e,r){let n="";if(r)for(const s of Object.entries(r)){if(!s)continue;let i="";for(const o of s[1])i+=`[${o.type}${o.name?`:${o.name}`:""}]`;n+=`(${s[0]}{${i}})`}return e?`${e}:${t}${n}`:t}const ju=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 Jp(t,e={}){if(F8(t))return cA(t,e);if(U8(t))return uA(t,e);if(R8(t))return fA(t,e);if(D8(t))return lA(t,e);if(z8(t))return dA(t);if(G8(t))return{type:"receive",stateMutability:"payable"};throw new nA({signature:t})}function cA(t,e={}){const r=j8(t);if(!r)throw new Zi({signature:t,type:"function"});const n=qt(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push(_n(n[a],{modifiers:Zl,structs:e,type:"function"}));const o=[];if(r.returns){const a=qt(r.returns),c=a.length;for(let u=0;u<c;u++)o.push(_n(a[u],{modifiers:Zl,structs:e,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:s,outputs:o}}function uA(t,e={}){const r=M8(t);if(!r)throw new Zi({signature:t,type:"event"});const n=qt(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(_n(n[o],{modifiers:W8,structs:e,type:"event"}));return{name:r.name,type:"event",inputs:s}}function fA(t,e={}){const r=N8(t);if(!r)throw new Zi({signature:t,type:"error"});const n=qt(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(_n(n[o],{structs:e,type:"error"}));return{name:r.name,type:"error",inputs:s}}function lA(t,e={}){const r=H8(t);if(!r)throw new Zi({signature:t,type:"constructor"});const n=qt(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(_n(n[o],{structs:e,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:s}}function dA(t){const e=V8(t);if(!e)throw new Zi({signature:t,type:"fallback"});return{type:"fallback",stateMutability:e.stateMutability??"nonpayable"}}const hA=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,pA=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,yA=/^u?int$/;function _n(t,e){var l,p;const r=aA(t,e==null?void 0:e.type,e==null?void 0:e.structs);if(ju.has(r))return ju.get(r);const n=Fg.test(t),s=$n(n?pA:hA,t);if(!s)throw new J8({param:t});if(s.name&&bA(s.name))throw new Q8({param:t,name:s.name});const i=s.name?{name:s.name}:{},o=s.modifier==="indexed"?{indexed:!0}:{},a=(e==null?void 0:e.structs)??{};let c,u={};if(n){c="tuple";const d=qt(s.type),m=[],b=d.length;for(let E=0;E<b;E++)m.push(_n(d[E],{structs:a}));u={components:m}}else if(s.type in a)c="tuple",u={components:a[s.type]};else if(yA.test(s.type))c=`${s.type}256`;else if(s.type==="address payable")c="address";else if(c=s.type,(e==null?void 0:e.type)!=="struct"&&!qg(c))throw new Y8({type:c});if(s.modifier){if(!((p=(l=e==null?void 0:e.modifiers)==null?void 0:l.has)!=null&&p.call(l,s.modifier)))throw new eA({param:t,type:e==null?void 0:e.type,modifier:s.modifier});if(Zl.has(s.modifier)&&!gA(c,!!s.array))throw new tA({param:t,type:e==null?void 0:e.type,modifier:s.modifier})}const f={type:`${c}${s.array??""}`,...i,...o,...u};return ju.set(r,f),f}function qt(t,e=[],r="",n=0){const s=t.trim().length;for(let i=0;i<s;i++){const o=t[i],a=t.slice(i+1);switch(o){case",":return n===0?qt(a,[...e,r.trim()]):qt(a,e,`${r}${o}`,n);case"(":return qt(a,e,`${r}${o}`,n+1);case")":return qt(a,e,`${r}${o}`,n-1);default:return qt(a,e,`${r}${o}`,n)}}if(r==="")return e;if(n!==0)throw new oA({current:r,depth:n});return e.push(r.trim()),e}function qg(t){return t==="address"||t==="bool"||t==="function"||t==="string"||Ug.test(t)||Mg.test(t)}const mA=/^(?: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 bA(t){return t==="address"||t==="bool"||t==="function"||t==="string"||t==="tuple"||Ug.test(t)||Mg.test(t)||mA.test(t)}function gA(t,e){return e||t==="bytes"||t==="string"||t==="tuple"}function Gg(t){const e={},r=t.length;for(let o=0;o<r;o++){const a=t[o];if(!gh(a))continue;const c=L8(a);if(!c)throw new Zi({signature:a,type:"struct"});const u=c.properties.split(";"),f=[],l=u.length;for(let p=0;p<l;p++){const m=u[p].trim();if(!m)continue;const b=_n(m,{type:"struct"});f.push(b)}if(!f.length)throw new sA({signature:a});e[c.name]=f}const n={},s=Object.entries(e),i=s.length;for(let o=0;o<i;o++){const[a,c]=s[o];n[a]=Wg(c,e)}return n}const wA=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function Wg(t,e,r=new Set){const n=[],s=t.length;for(let i=0;i<s;i++){const o=t[i];if(Fg.test(o.type))n.push(o);else{const c=$n(wA,o.type);if(!(c!=null&&c.type))throw new rA({abiParameter:o});const{array:u,type:f}=c;if(f in e){if(r.has(f))throw new iA({type:f});n.push({...o,type:`tuple${u??""}`,components:Wg(e[f]??[],e,new Set([...r,f]))})}else if(qg(f))n.push(o);else throw new Z8({type:f})}}return n}function Qp(t){let e;if(typeof t=="string")e=Jp(t);else{const r=Gg(t),n=t.length;for(let s=0;s<n;s++){const i=t[s];if(!gh(i)){e=Jp(i,r);break}}}if(!e)throw new K8({signature:t});return e}function e0(t){const e=[];if(typeof t=="string"){const r=qt(t),n=r.length;for(let s=0;s<n;s++)e.push(_n(r[s],{modifiers:Xp}))}else{const r=Gg(t),n=t.length;for(let s=0;s<n;s++){const i=t[s];if(gh(i))continue;const o=qt(i),a=o.length;for(let c=0;c<a;c++)e.push(_n(o[c],{modifiers:Xp,structs:r}))}}if(e.length===0)throw new X8({params:t});return e}class vA extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const EA={checksum:new vA(8192)},Lu=EA.checksum;function Kg(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,n=Xm(BE(t));return r==="Bytes"?n:Br(n)}const SA=/^0x[a-fA-F0-9]{40}$/;function eu(t,e={}){const{strict:r=!0}=e;if(!SA.test(t))throw new t0({address:t,cause:new AA});if(r){if(t.toLowerCase()===t)return;if(Zg(t)!==t)throw new t0({address:t,cause:new xA})}}function Zg(t){if(Lu.has(t))return Lu.get(t);eu(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=Kg($E(e),{as:"Bytes"}),n=e.split("");for(let i=0;i<40;i+=2)r[i>>1]>>4>=8&&n[i]&&(n[i]=n[i].toUpperCase()),(r[i>>1]&15)>=8&&n[i+1]&&(n[i+1]=n[i+1].toUpperCase());const s=`0x${n.join("")}`;return Lu.set(t,s),s}function Yl(t,e={}){const{strict:r=!0}=e??{};try{return eu(t,{strict:r}),!0}catch{return!1}}class t0 extends ve{constructor({address:e,cause:r}){super(`Address "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class AA extends ve{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class xA extends ve{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const kA=/^(.*)\[([0-9]*)\]$/,TA=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Yg=/^(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)?$/,r0=2n**256n-1n;function Ai(t,e,r){const{checksumAddress:n,staticPosition:s}=r,i=Eh(e.type);if(i){const[o,a]=i;return PA(t,{...e,type:a},{checksumAddress:n,length:o,staticPosition:s})}if(e.type==="tuple")return CA(t,e,{checksumAddress:n,staticPosition:s});if(e.type==="address")return _A(t,{checksum:n});if(e.type==="bool")return IA(t);if(e.type.startsWith("bytes"))return OA(t,e,{staticPosition:s});if(e.type.startsWith("uint")||e.type.startsWith("int"))return BA(t,e);if(e.type==="string")return $A(t,{staticPosition:s});throw new Ah(e.type)}const n0=32,Xl=32;function _A(t,e={}){const{checksum:r=!1}=e,n=t.readBytes(32);return[(i=>r?Zg(i):i)(Br(NE(n,-20))),32]}function PA(t,e,r){const{checksumAddress:n,length:s,staticPosition:i}=r;if(!s){const c=An(t.readBytes(Xl)),u=i+c,f=u+n0;t.setPosition(u);const l=An(t.readBytes(n0)),p=Jo(e);let d=0;const m=[];for(let b=0;b<l;++b){t.setPosition(f+(p?b*32:d));const[E,A]=Ai(t,e,{checksumAddress:n,staticPosition:f});d+=A,m.push(E)}return t.setPosition(i+32),[m,32]}if(Jo(e)){const c=An(t.readBytes(Xl)),u=i+c,f=[];for(let l=0;l<s;++l){t.setPosition(u+l*32);const[p]=Ai(t,e,{checksumAddress:n,staticPosition:u});f.push(p)}return t.setPosition(i+32),[f,32]}let o=0;const a=[];for(let c=0;c<s;++c){const[u,f]=Ai(t,e,{checksumAddress:n,staticPosition:i+o});o+=f,a.push(u)}return[a,o]}function IA(t){return[ME(t.readBytes(32),{size:32}),32]}function OA(t,e,{staticPosition:r}){const[n,s]=e.type.split("bytes");if(!s){const o=An(t.readBytes(32));t.setPosition(r+o);const a=An(t.readBytes(32));if(a===0)return t.setPosition(r+32),["0x",32];const c=t.readBytes(a);return t.setPosition(r+32),[Br(c),32]}return[Br(t.readBytes(Number.parseInt(s,10),32)),32]}function BA(t,e){const r=e.type.startsWith("int"),n=Number.parseInt(e.type.split("int")[1]||"256",10),s=t.readBytes(32);return[n>48?UE(s,{signed:r}):An(s,{signed:r}),32]}function CA(t,e,r){const{checksumAddress:n,staticPosition:s}=r,i=e.components.length===0||e.components.some(({name:c})=>!c),o=i?[]:{};let a=0;if(Jo(e)){const c=An(t.readBytes(Xl)),u=s+c;for(let f=0;f<e.components.length;++f){const l=e.components[f];t.setPosition(u+a);const[p,d]=Ai(t,l,{checksumAddress:n,staticPosition:u});a+=d,o[i?f:l==null?void 0:l.name]=p}return t.setPosition(s+32),[o,32]}for(let c=0;c<e.components.length;++c){const u=e.components[c],[f,l]=Ai(t,u,{checksumAddress:n,staticPosition:s});o[i?c:u==null?void 0:u.name]=f,a+=l}return[o,a]}function $A(t,{staticPosition:e}){const r=An(t.readBytes(32)),n=e+r;t.setPosition(n);const s=An(t.readBytes(32));if(s===0)return t.setPosition(e+32),["",32];const i=t.readBytes(s,32),o=FE(Hb(i));return t.setPosition(e+32),[o,32]}function RA({checksumAddress:t,parameters:e,values:r}){const n=[];for(let s=0;s<e.length;s++)n.push(wh({checksumAddress:t,parameter:e[s],value:r[s]}));return n}function wh({checksumAddress:t=!1,parameter:e,value:r}){const n=e,s=Eh(n.type);if(s){const[i,o]=s;return UA(r,{checksumAddress:t,length:i,parameter:{...n,type:o}})}if(n.type==="tuple")return DA(r,{checksumAddress:t,parameter:n});if(n.type==="address")return NA(r,{checksum:t});if(n.type==="bool")return FA(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){const i=n.type.startsWith("int"),[,,o="256"]=Yg.exec(n.type)??[];return jA(r,{signed:i,size:Number(o)})}if(n.type.startsWith("bytes"))return MA(r,{type:n.type});if(n.type==="string")return LA(r);throw new Ah(n.type)}function vh(t){let e=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?e+=32:e+=Zt(a)}const r=[],n=[];let s=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?(r.push(It(e+s,{size:32})),n.push(a),s+=Zt(a)):r.push(a)}return Or(...r,...n)}function NA(t,e){const{checksum:r=!1}=e;return eu(t,{strict:r}),{dynamic:!1,encoded:Ls(t.toLowerCase())}}function UA(t,e){const{checksumAddress:r,length:n,parameter:s}=e,i=n===null;if(!Array.isArray(t))throw new YA(t);if(!i&&t.length!==n)throw new ZA({expectedLength:n,givenLength:t.length,type:`${s.type}[${n}]`});let o=!1;const a=[];for(let c=0;c<t.length;c++){const u=wh({checksumAddress:r,parameter:s,value:t[c]});u.dynamic&&(o=!0),a.push(u)}if(i||o){const c=vh(a);if(i){const u=It(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?Or(u,c):u}}if(o)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Or(...a.map(({encoded:c})=>c))}}function MA(t,{type:e}){const[,r]=e.split("bytes"),n=Zt(t);if(!r){let s=t;return n%32!==0&&(s=Ds(s,Math.ceil((t.length-2)/2/32)*32)),{dynamic:!0,encoded:Or(Ls(It(n,{size:32})),s)}}if(n!==Number.parseInt(r,10))throw new Jg({expectedSize:Number.parseInt(r,10),value:t});return{dynamic:!1,encoded:Ds(t)}}function FA(t){if(typeof t!="boolean")throw new ve(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Ls(zb(t))}}function jA(t,{signed:e,size:r}){if(typeof r=="number"){const n=2n**(BigInt(r)-(e?1n:0n))-1n,s=e?-n-1n:0n;if(t>n||t<s)throw new Gb({max:n.toString(),min:s.toString(),signed:e,size:r/8,value:t.toString()})}return{dynamic:!1,encoded:It(t,{size:32,signed:e})}}function LA(t){const e=uh(t),r=Math.ceil(Zt(e)/32),n=[];for(let s=0;s<r;s++)n.push(Ds(Yr(e,s*32,(s+1)*32)));return{dynamic:!0,encoded:Or(Ds(It(Zt(e),{size:32})),...n)}}function DA(t,e){const{checksumAddress:r,parameter:n}=e;let s=!1;const i=[];for(let o=0;o<n.components.length;o++){const a=n.components[o],c=Array.isArray(t)?o:a.name,u=wh({checksumAddress:r,parameter:a,value:t[c]});i.push(u),u.dynamic&&(s=!0)}return{dynamic:s,encoded:s?vh(i):Or(...i.map(({encoded:o})=>o))}}function Eh(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function Jo(t){var n;const{type:e}=t;if(e==="string"||e==="bytes"||e.endsWith("[]"))return!0;if(e==="tuple")return(n=t.components)==null?void 0:n.some(Jo);const r=Eh(t.type);return!!(r&&Jo({...t,type:r[1]}))}const HA={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 qA({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(t){if(t<0||t>this.bytes.length-1)throw new VA({length:this.bytes.length,position:t})},decrementPosition(t){if(t<0)throw new s0({offset:t});const e=this.position-t;this.assertPosition(e),this.position=e},getReadCount(t){return this.positionReadCount.get(t||this.position)||0},incrementPosition(t){if(t<0)throw new s0({offset:t});const e=this.position+t;this.assertPosition(e),this.position=e},inspectByte(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectBytes(t,e){const r=e??this.position;return this.assertPosition(r+t-1),this.bytes.subarray(r,r+t)},inspectUint8(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectUint16(t){const e=t??this.position;return this.assertPosition(e+1),this.dataView.getUint16(e)},inspectUint24(t){const e=t??this.position;return this.assertPosition(e+2),(this.dataView.getUint16(e)<<8)+this.dataView.getUint8(e+2)},inspectUint32(t){const e=t??this.position;return this.assertPosition(e+3),this.dataView.getUint32(e)},pushByte(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushBytes(t){this.assertPosition(this.position+t.length-1),this.bytes.set(t,this.position),this.position+=t.length},pushUint8(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushUint16(t){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,t),this.position+=2},pushUint24(t){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,t>>8),this.dataView.setUint8(this.position+2,t&255),this.position+=3},pushUint32(t){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,t),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const t=this.inspectByte();return this.position++,t},readBytes(t,e){this.assertReadLimit(),this._touch();const r=this.inspectBytes(t);return this.position+=e??t,r},readUint8(){this.assertReadLimit(),this._touch();const t=this.inspectUint8();return this.position+=1,t},readUint16(){this.assertReadLimit(),this._touch();const t=this.inspectUint16();return this.position+=2,t},readUint24(){this.assertReadLimit(),this._touch();const t=this.inspectUint24();return this.position+=3,t},readUint32(){this.assertReadLimit(),this._touch();const t=this.inspectUint32();return this.position+=4,t},get remaining(){return this.bytes.length-this.position},setPosition(t){const e=this.position;return this.assertPosition(t),this.position=t,()=>this.position=e},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const t=this.getReadCount();this.positionReadCount.set(this.position,t+1),t>0&&this.recursiveReadCount++}};function zA(t,{recursiveReadLimit:e=8192}={}){const r=Object.create(HA);return r.bytes=t,r.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=e,r}class s0 extends ve{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class VA extends ve{constructor({length:e,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class qA extends ve{constructor({count:e,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function GA(t,e,r={}){const{as:n="Array",checksumAddress:s=!1}=r,i=typeof e=="string"?Db(e):e,o=zA(i);if(bi(i)===0&&t.length>0)throw new KA;if(bi(i)&&bi(i)<32)throw new WA({data:typeof e=="string"?e:Br(e),parameters:t,size:bi(i)});let a=0;const c=n==="Array"?[]:{};for(let u=0;u<t.length;++u){const f=t[u];o.setPosition(a);const[l,p]=Ai(o,f,{checksumAddress:s,staticPosition:0});a+=p,n==="Array"?c.push(l):c[f.name??u]=l}return c}function Sh(t,e,r){const{checksumAddress:n=!1}={};if(t.length!==e.length)throw new Qg({expectedLength:t.length,givenLength:e.length});const s=RA({checksumAddress:n,parameters:t,values:e}),i=vh(s);return i.length===0?"0x":i}function Jl(t,e){if(t.length!==e.length)throw new Qg({expectedLength:t.length,givenLength:e.length});const r=[];for(let n=0;n<t.length;n++){const s=t[n],i=e[n];r.push(Jl.encode(s,i))}return Or(...r)}(function(t){function e(r,n,s=!1){if(r==="address"){const c=n;return eu(c),Ls(c.toLowerCase(),s?32:0)}if(r==="string")return uh(n);if(r==="bytes")return n;if(r==="bool")return Ls(zb(n),s?32:1);const i=r.match(Yg);if(i){const[c,u,f="256"]=i,l=Number.parseInt(f,10)/8;return It(n,{size:s?32:l,signed:u==="int"})}const o=r.match(TA);if(o){const[c,u]=o;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new Jg({expectedSize:Number.parseInt(u,10),value:n});return Ds(n,s?32:0)}const a=r.match(kA);if(a&&Array.isArray(n)){const[c,u]=a,f=[];for(let l=0;l<n.length;l++)f.push(e(u,n[l],!0));return f.length===0?"0x":Or(...f)}throw new Ah(r)}t.encode=e})(Jl||(Jl={}));function Xg(t){return Array.isArray(t)&&typeof t[0]=="string"||typeof t=="string"?e0(t):t}class WA extends ve{constructor({data:e,parameters:r,size:n}){super(`Data size of ${n} bytes is too small for given parameters.`,{metaMessages:[`Params: (${ci(r)})`,`Data: ${e} (${n} bytes)`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class KA extends ve{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.'),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}}class ZA extends ve{constructor({expectedLength:e,givenLength:r,type:n}){super(`Array length mismatch for type \`${n}\`. Expected: \`${e}\`. Given: \`${r}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class Jg extends ve{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${Zt(r)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class Qg extends ve{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${r}`].join(`
|
|
45
|
-
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class YA extends ve{constructor(e){super(`Value \`${e}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class Ah extends ve{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}class e1 extends $c{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Cv(e);const n=En(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,i=new Uint8Array(s);i.set(n.length>s?e.create().update(n).digest():n);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Ir(i)}update(e){return os(this),this.iHash.update(e),this}digestInto(e){os(this),is(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:n,finished:s,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const t1=(t,e,r)=>new e1(t,e).update(r).digest();t1.create=(t,e)=>new e1(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ft=BigInt(0),Ct=BigInt(1),Es=BigInt(2),XA=BigInt(3),r1=BigInt(4),n1=BigInt(5),s1=BigInt(8);function Rt(t,e){const r=t%e;return r>=Ft?r:e+r}function tr(t,e,r){let n=t;for(;e-- >Ft;)n*=n,n%=r;return n}function Ql(t,e){if(t===Ft)throw new Error("invert: expected non-zero number");if(e<=Ft)throw new Error("invert: expected positive modulus, got "+e);let r=Rt(t,e),n=e,s=Ft,i=Ct;for(;r!==Ft;){const a=n/r,c=n%r,u=s-i*a;n=r,r=c,s=i,i=u}if(n!==Ct)throw new Error("invert: does not exist");return Rt(s,e)}function i1(t,e){const r=(t.ORDER+Ct)/r1,n=t.pow(e,r);if(!t.eql(t.sqr(n),e))throw new Error("Cannot find square root");return n}function JA(t,e){const r=(t.ORDER-n1)/s1,n=t.mul(e,Es),s=t.pow(n,r),i=t.mul(e,s),o=t.mul(t.mul(i,Es),s),a=t.mul(i,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function QA(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Ct,r=0;for(;e%Es===Ft;)e/=Es,r++;let n=Es;const s=xh(t);for(;i0(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return i1;let i=s.pow(n,e);const o=(e+Ct)/Es;return function(c,u){if(c.is0(u))return u;if(i0(c,u)!==1)throw new Error("Cannot find square root");let f=r,l=c.mul(c.ONE,i),p=c.pow(u,e),d=c.pow(u,o);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let m=1,b=c.sqr(p);for(;!c.eql(b,c.ONE);)if(m++,b=c.sqr(b),m===f)throw new Error("Cannot find square root");const E=Ct<<BigInt(f-m-1),A=c.pow(l,E);f=m,l=c.sqr(A),p=c.mul(p,l),d=c.mul(d,A)}return d}}function ex(t){return t%r1===XA?i1:t%s1===n1?JA:QA(t)}const tx=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function rx(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=tx.reduce((n,s)=>(n[s]="function",n),e);return Gc(t,r)}function nx(t,e,r){if(r<Ft)throw new Error("invalid exponent, negatives unsupported");if(r===Ft)return t.ONE;if(r===Ct)return e;let n=t.ONE,s=e;for(;r>Ft;)r&Ct&&(n=t.mul(n,s)),s=t.sqr(s),r>>=Ct;return n}function o1(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),i=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),i),n}function i0(t,e){const r=(t.ORDER-Ct)/Es,n=t.pow(e,r),s=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function a1(t,e){e!==void 0&&ss(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function xh(t,e,r=!1,n={}){if(t<=Ft)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:i}=a1(t,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:i,MASK:qc(s),ZERO:Ft,ONE:Ct,create:c=>Rt(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ft<=c&&c<t},is0:c=>c===Ft,isOdd:c=>(c&Ct)===Ct,neg:c=>Rt(-c,t),eql:(c,u)=>c===u,sqr:c=>Rt(c*c,t),add:(c,u)=>Rt(c+u,t),sub:(c,u)=>Rt(c-u,t),mul:(c,u)=>Rt(c*u,t),pow:(c,u)=>nx(a,c,u),div:(c,u)=>Rt(c*Ql(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Ql(c,t),sqrt:n.sqrt||(c=>(o||(o=ex(t)),o(a,c))),toBytes:c=>r?Ub(c,i):wa(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return r?Nb(c):Ps(c)},invertBatch:c=>o1(a,c),cmov:(c,u,f)=>f?u:c});return Object.freeze(a)}function c1(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function u1(t){const e=c1(t);return e+Math.ceil(e/2)}function sx(t,e,r=!1){const n=t.length,s=c1(e),i=u1(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=r?Nb(t):Ps(t),a=Rt(o,e-Ct)+Ct;return r?Ub(a,s):wa(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const o0=BigInt(0),ed=BigInt(1);function Du(t,e){const r=e.negate();return t?r:e}function f1(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Hu(t,e){f1(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),s=2**t,i=qc(t),o=BigInt(t);return{windows:r,windowSize:n,mask:i,maxNumber:s,shiftBy:o}}function a0(t,e,r){const{windowSize:n,mask:s,maxNumber:i,shiftBy:o}=r;let a=Number(t&s),c=t>>o;a>n&&(a-=i,c+=ed);const u=e*n,f=u+Math.abs(a)-1,l=a===0,p=a<0,d=e%2!==0;return{nextN:c,offset:f,isZero:l,isNeg:p,isNegF:d,offsetF:u}}function ix(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function ox(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const zu=new WeakMap,l1=new WeakMap;function Vu(t){return l1.get(t)||1}function ax(t,e){return{constTimeNegate:Du,hasPrecomputes(r){return Vu(r)!==1},unsafeLadder(r,n,s=t.ZERO){let i=r;for(;n>o0;)n&ed&&(s=s.add(i)),i=i.double(),n>>=ed;return s},precomputeWindow(r,n){const{windows:s,windowSize:i}=Hu(n,e),o=[];let a=r,c=a;for(let u=0;u<s;u++){c=a,o.push(c);for(let f=1;f<i;f++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,n,s){let i=t.ZERO,o=t.BASE;const a=Hu(r,e);for(let c=0;c<a.windows;c++){const{nextN:u,offset:f,isZero:l,isNeg:p,isNegF:d,offsetF:m}=a0(s,c,a);s=u,l?o=o.add(Du(d,n[m])):i=i.add(Du(p,n[f]))}return{p:i,f:o}},wNAFUnsafe(r,n,s,i=t.ZERO){const o=Hu(r,e);for(let a=0;a<o.windows&&s!==o0;a++){const{nextN:c,offset:u,isZero:f,isNeg:l}=a0(s,a,o);if(s=c,!f){const p=n[u];i=i.add(l?p.negate():p)}}return i},getPrecomputes(r,n,s){let i=zu.get(n);return i||(i=this.precomputeWindow(n,r),r!==1&&zu.set(n,s(i))),i},wNAFCached(r,n,s){const i=Vu(r);return this.wNAF(i,this.getPrecomputes(i,r,s),n)},wNAFCachedUnsafe(r,n,s,i){const o=Vu(r);return o===1?this.unsafeLadder(r,n,i):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),n,i)},setWindowSize(r,n){f1(n,e),l1.set(r,n),zu.delete(r)}}}function cx(t,e,r,n){ix(r,t),ox(n,e);const s=r.length,i=n.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=vE(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=qc(c),f=new Array(Number(u)+1).fill(o),l=Math.floor((e.BITS-1)/c)*c;let p=o;for(let d=l;d>=0;d-=c){f.fill(o);for(let b=0;b<i;b++){const E=n[b],A=Number(E>>BigInt(d)&u);f[A]=f[A].add(r[b])}let m=o;for(let b=f.length-1,E=o;b>0;b--)E=E.add(f[b]),m=m.add(E);if(p=p.add(m),d!==0)for(let b=0;b<c;b++)p=p.double()}return p}function d1(t){return rx(t.Fp),Gc(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...a1(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function c0(t){t.lowS!==void 0&&Yo("lowS",t.lowS),t.prehash!==void 0&&Yo("prehash",t.prehash)}function ux(t){const e=d1(t);Gc(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:r,Fp:n,a:s}=e;if(r){if(!n.eql(s,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class fx extends Error{constructor(e=""){super(e)}}const pn={Err:fx,_tlv:{encode:(t,e)=>{const{Err:r}=pn;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,s=Na(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const i=n>127?Na(s.length/2|128):"";return Na(t)+i+s+e},decode(t,e){const{Err:r}=pn;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const s=e[n++],i=!!(s&128);let o=0;if(!i)o=s;else{const c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const u=e.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const f of u)o=o<<8|f;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=pn;if(t<bn)throw new e("integer: negative integers are not allowed");let r=Na(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=pn;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ps(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=pn,s=sr("signature",t),{v:i,l:o}=n.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:u,l:f}=n.decode(2,c);if(f.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=pn,n=e.encode(2,r.encode(t.r)),s=e.encode(2,r.encode(t.s)),i=n+s;return e.encode(48,i)}};function qu(t,e){return Xo(wa(t,e))}const bn=BigInt(0),ct=BigInt(1);BigInt(2);const Gu=BigInt(3),lx=BigInt(4);function dx(t){const e=ux(t),{Fp:r}=e,n=xh(e.n,e.nBitLength),s=e.toBytes||((S,w,k)=>{const T=w.toAffine();return gc(Uint8Array.from([4]),r.toBytes(T.x),r.toBytes(T.y))}),i=e.fromBytes||(S=>{const w=S.subarray(1),k=r.fromBytes(w.subarray(0,r.BYTES)),T=r.fromBytes(w.subarray(r.BYTES,2*r.BYTES));return{x:k,y:T}});function o(S){const{a:w,b:k}=e,T=r.sqr(S),B=r.mul(T,S);return r.add(r.add(B,r.mul(S,w)),k)}function a(S,w){const k=r.sqr(w),T=o(S);return r.eql(k,T)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=r.mul(r.pow(e.a,Gu),lx),u=r.mul(r.sqr(e.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function f(S){return ch(S,ct,e.n)}function l(S){const{allowedPrivateKeyLengths:w,nByteLength:k,wrapPrivateKey:T,n:B}=e;if(w&&typeof S!="bigint"){if(ga(S)&&(S=Xo(S)),typeof S!="string"||!w.includes(S.length))throw new Error("invalid private key");S=S.padStart(k*2,"0")}let U;try{U=typeof S=="bigint"?S:Ps(sr("private key",S,k))}catch{throw new Error("invalid private key, expected hex or "+k+" bytes, got "+typeof S)}return T&&(U=Rt(U,B)),Si("private key",U,ct,B),U}function p(S){if(!(S instanceof b))throw new Error("ProjectivePoint expected")}const d=Mp((S,w)=>{const{px:k,py:T,pz:B}=S;if(r.eql(B,r.ONE))return{x:k,y:T};const U=S.is0();w==null&&(w=U?r.ONE:r.inv(B));const $=r.mul(k,w),D=r.mul(T,w),M=r.mul(B,w);if(U)return{x:r.ZERO,y:r.ZERO};if(!r.eql(M,r.ONE))throw new Error("invZ was invalid");return{x:$,y:D}}),m=Mp(S=>{if(S.is0()){if(e.allowInfinityPoint&&!r.is0(S.py))return;throw new Error("bad point: ZERO")}const{x:w,y:k}=S.toAffine();if(!r.isValid(w)||!r.isValid(k))throw new Error("bad point: x or y not FE");if(!a(w,k))throw new Error("bad point: equation left != right");if(!S.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class b{constructor(w,k,T){if(w==null||!r.isValid(w))throw new Error("x required");if(k==null||!r.isValid(k)||r.is0(k))throw new Error("y required");if(T==null||!r.isValid(T))throw new Error("z required");this.px=w,this.py=k,this.pz=T,Object.freeze(this)}static fromAffine(w){const{x:k,y:T}=w||{};if(!w||!r.isValid(k)||!r.isValid(T))throw new Error("invalid affine point");if(w instanceof b)throw new Error("projective point not allowed");const B=U=>r.eql(U,r.ZERO);return B(k)&&B(T)?b.ZERO:new b(k,T,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){const k=o1(r,w.map(T=>T.pz));return w.map((T,B)=>T.toAffine(k[B])).map(b.fromAffine)}static fromHex(w){const k=b.fromAffine(i(sr("pointHex",w)));return k.assertValidity(),k}static fromPrivateKey(w){return b.BASE.multiply(l(w))}static msm(w,k){return cx(b,n,w,k)}_setWindowSize(w){P.setWindowSize(this,w)}assertValidity(){m(this)}hasEvenY(){const{y:w}=this.toAffine();if(r.isOdd)return!r.isOdd(w);throw new Error("Field doesn't support isOdd")}equals(w){p(w);const{px:k,py:T,pz:B}=this,{px:U,py:$,pz:D}=w,M=r.eql(r.mul(k,D),r.mul(U,B)),q=r.eql(r.mul(T,D),r.mul($,B));return M&&q}negate(){return new b(this.px,r.neg(this.py),this.pz)}double(){const{a:w,b:k}=e,T=r.mul(k,Gu),{px:B,py:U,pz:$}=this;let D=r.ZERO,M=r.ZERO,q=r.ZERO,K=r.mul(B,B),Q=r.mul(U,U),G=r.mul($,$),W=r.mul(B,U);return W=r.add(W,W),q=r.mul(B,$),q=r.add(q,q),D=r.mul(w,q),M=r.mul(T,G),M=r.add(D,M),D=r.sub(Q,M),M=r.add(Q,M),M=r.mul(D,M),D=r.mul(W,D),q=r.mul(T,q),G=r.mul(w,G),W=r.sub(K,G),W=r.mul(w,W),W=r.add(W,q),q=r.add(K,K),K=r.add(q,K),K=r.add(K,G),K=r.mul(K,W),M=r.add(M,K),G=r.mul(U,$),G=r.add(G,G),K=r.mul(G,W),D=r.sub(D,K),q=r.mul(G,Q),q=r.add(q,q),q=r.add(q,q),new b(D,M,q)}add(w){p(w);const{px:k,py:T,pz:B}=this,{px:U,py:$,pz:D}=w;let M=r.ZERO,q=r.ZERO,K=r.ZERO;const Q=e.a,G=r.mul(e.b,Gu);let W=r.mul(k,U),ee=r.mul(T,$),H=r.mul(B,D),I=r.add(k,T),j=r.add(U,$);I=r.mul(I,j),j=r.add(W,ee),I=r.sub(I,j),j=r.add(k,B);let J=r.add(U,D);return j=r.mul(j,J),J=r.add(W,H),j=r.sub(j,J),J=r.add(T,B),M=r.add($,D),J=r.mul(J,M),M=r.add(ee,H),J=r.sub(J,M),K=r.mul(Q,j),M=r.mul(G,H),K=r.add(M,K),M=r.sub(ee,K),K=r.add(ee,K),q=r.mul(M,K),ee=r.add(W,W),ee=r.add(ee,W),H=r.mul(Q,H),j=r.mul(G,j),ee=r.add(ee,H),H=r.sub(W,H),H=r.mul(Q,H),j=r.add(j,H),W=r.mul(ee,j),q=r.add(q,W),W=r.mul(J,j),M=r.mul(I,M),M=r.sub(M,W),W=r.mul(I,ee),K=r.mul(J,K),K=r.add(K,W),new b(M,q,K)}subtract(w){return this.add(w.negate())}is0(){return this.equals(b.ZERO)}wNAF(w){return P.wNAFCached(this,w,b.normalizeZ)}multiplyUnsafe(w){const{endo:k,n:T}=e;Si("scalar",w,bn,T);const B=b.ZERO;if(w===bn)return B;if(this.is0()||w===ct)return this;if(!k||P.hasPrecomputes(this))return P.wNAFCachedUnsafe(this,w,b.normalizeZ);let{k1neg:U,k1:$,k2neg:D,k2:M}=k.splitScalar(w),q=B,K=B,Q=this;for(;$>bn||M>bn;)$&ct&&(q=q.add(Q)),M&ct&&(K=K.add(Q)),Q=Q.double(),$>>=ct,M>>=ct;return U&&(q=q.negate()),D&&(K=K.negate()),K=new b(r.mul(K.px,k.beta),K.py,K.pz),q.add(K)}multiply(w){const{endo:k,n:T}=e;Si("scalar",w,ct,T);let B,U;if(k){const{k1neg:$,k1:D,k2neg:M,k2:q}=k.splitScalar(w);let{p:K,f:Q}=this.wNAF(D),{p:G,f:W}=this.wNAF(q);K=P.constTimeNegate($,K),G=P.constTimeNegate(M,G),G=new b(r.mul(G.px,k.beta),G.py,G.pz),B=K.add(G),U=Q.add(W)}else{const{p:$,f:D}=this.wNAF(w);B=$,U=D}return b.normalizeZ([B,U])[0]}multiplyAndAddUnsafe(w,k,T){const B=b.BASE,U=(D,M)=>M===bn||M===ct||!D.equals(B)?D.multiplyUnsafe(M):D.multiply(M),$=U(this,k).add(U(w,T));return $.is0()?void 0:$}toAffine(w){return d(this,w)}isTorsionFree(){const{h:w,isTorsionFree:k}=e;if(w===ct)return!0;if(k)return k(b,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:w,clearCofactor:k}=e;return w===ct?this:k?k(b,this):this.multiplyUnsafe(e.h)}toRawBytes(w=!0){return Yo("isCompressed",w),this.assertValidity(),s(b,this,w)}toHex(w=!0){return Yo("isCompressed",w),Xo(this.toRawBytes(w))}}b.BASE=new b(e.Gx,e.Gy,r.ONE),b.ZERO=new b(r.ZERO,r.ONE,r.ZERO);const{endo:E,nBitLength:A}=e,P=ax(b,E?Math.ceil(A/2):A);return{CURVE:e,ProjectivePoint:b,normPrivateKeyToScalar:l,weierstrassEquation:o,isWithinCurveOrder:f}}function hx(t){const e=d1(t);return Gc(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function px(t){const e=hx(t),{Fp:r,n,nByteLength:s,nBitLength:i}=e,o=r.BYTES+1,a=2*r.BYTES+1;function c(G){return Rt(G,n)}function u(G){return Ql(G,n)}const{ProjectivePoint:f,normPrivateKeyToScalar:l,weierstrassEquation:p,isWithinCurveOrder:d}=dx({...e,toBytes(G,W,ee){const H=W.toAffine(),I=r.toBytes(H.x),j=gc;return Yo("isCompressed",ee),ee?j(Uint8Array.from([W.hasEvenY()?2:3]),I):j(Uint8Array.from([4]),I,r.toBytes(H.y))},fromBytes(G){const W=G.length,ee=G[0],H=G.subarray(1);if(W===o&&(ee===2||ee===3)){const I=Ps(H);if(!ch(I,ct,r.ORDER))throw new Error("Point is not on curve");const j=p(I);let J;try{J=r.sqrt(j)}catch(F){const ne=F instanceof Error?": "+F.message:"";throw new Error("Point is not on curve"+ne)}const O=(J&ct)===ct;return(ee&1)===1!==O&&(J=r.neg(J)),{x:I,y:J}}else if(W===a&&ee===4){const I=r.fromBytes(H.subarray(0,r.BYTES)),j=r.fromBytes(H.subarray(r.BYTES,2*r.BYTES));return{x:I,y:j}}else{const I=o,j=a;throw new Error("invalid Point, expected length of "+I+", or uncompressed "+j+", got "+W)}}});function m(G){const W=n>>ct;return G>W}function b(G){return m(G)?c(-G):G}const E=(G,W,ee)=>Ps(G.slice(W,ee));class A{constructor(W,ee,H){Si("r",W,ct,n),Si("s",ee,ct,n),this.r=W,this.s=ee,H!=null&&(this.recovery=H),Object.freeze(this)}static fromCompact(W){const ee=s;return W=sr("compactSignature",W,ee*2),new A(E(W,0,ee),E(W,ee,2*ee))}static fromDER(W){const{r:ee,s:H}=pn.toSig(sr("DER",W));return new A(ee,H)}assertValidity(){}addRecoveryBit(W){return new A(this.r,this.s,W)}recoverPublicKey(W){const{r:ee,s:H,recovery:I}=this,j=B(sr("msgHash",W));if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");const J=I===2||I===3?ee+e.n:ee;if(J>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const O=I&1?"03":"02",R=f.fromHex(O+qu(J,r.BYTES)),F=u(J),ne=c(-j*F),ae=c(H*F),le=f.BASE.multiplyAndAddUnsafe(R,ne,ae);if(!le)throw new Error("point at infinify");return le.assertValidity(),le}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new A(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return bc(this.toDERHex())}toDERHex(){return pn.hexFromSig(this)}toCompactRawBytes(){return bc(this.toCompactHex())}toCompactHex(){const W=s;return qu(this.r,W)+qu(this.s,W)}}const P={isValidPrivateKey(G){try{return l(G),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const G=u1(e.n);return sx(e.randomBytes(G),e.n)},precompute(G=8,W=f.BASE){return W._setWindowSize(G),W.multiply(BigInt(3)),W}};function S(G,W=!0){return f.fromPrivateKey(G).toRawBytes(W)}function w(G){if(typeof G=="bigint")return!1;if(G instanceof f)return!0;const ee=sr("key",G).length,H=r.BYTES,I=H+1,j=2*H+1;if(!(e.allowedPrivateKeyLengths||s===I))return ee===I||ee===j}function k(G,W,ee=!0){if(w(G)===!0)throw new Error("first arg must be private key");if(w(W)===!1)throw new Error("second arg must be public key");return f.fromHex(W).multiply(l(G)).toRawBytes(ee)}const T=e.bits2int||function(G){if(G.length>8192)throw new Error("input is too large");const W=Ps(G),ee=G.length*8-i;return ee>0?W>>BigInt(ee):W},B=e.bits2int_modN||function(G){return c(T(G))},U=qc(i);function $(G){return Si("num < 2^"+i,G,bn,U),wa(G,s)}function D(G,W,ee=M){if(["recovered","canonical"].some(oe=>oe in ee))throw new Error("sign() legacy options not supported");const{hash:H,randomBytes:I}=e;let{lowS:j,prehash:J,extraEntropy:O}=ee;j==null&&(j=!0),G=sr("msgHash",G),c0(ee),J&&(G=sr("prehashed msgHash",H(G)));const R=B(G),F=l(W),ne=[$(F),$(R)];if(O!=null&&O!==!1){const oe=O===!0?I(r.BYTES):O;ne.push(sr("extraEntropy",oe))}const ae=gc(...ne),le=R;function ue(oe){const ie=T(oe);if(!d(ie))return;const me=u(ie),be=f.BASE.multiply(ie).toAffine(),we=c(be.x);if(we===bn)return;const ke=c(me*c(le+we*F));if(ke===bn)return;let tt=(be.x===we?0:2)|Number(be.y&ct),Oe=ke;return j&&m(ke)&&(Oe=b(ke),tt^=1),new A(we,Oe,tt)}return{seed:ae,k2sig:ue}}const M={lowS:e.lowS,prehash:!1},q={lowS:e.lowS,prehash:!1};function K(G,W,ee=M){const{seed:H,k2sig:I}=D(G,W,ee),j=e;return EE(j.hash.outputLen,j.nByteLength,j.hmac)(H,I)}f.BASE._setWindowSize(8);function Q(G,W,ee,H=q){var tt;const I=G;W=sr("msgHash",W),ee=sr("publicKey",ee);const{lowS:j,prehash:J,format:O}=H;if(c0(H),"strict"in H)throw new Error("options.strict was renamed to lowS");if(O!==void 0&&O!=="compact"&&O!=="der")throw new Error("format must be compact or der");const R=typeof I=="string"||ga(I),F=!R&&!O&&typeof I=="object"&&I!==null&&typeof I.r=="bigint"&&typeof I.s=="bigint";if(!R&&!F)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let ne,ae;try{if(F&&(ne=new A(I.r,I.s)),R){try{O!=="compact"&&(ne=A.fromDER(I))}catch(Oe){if(!(Oe instanceof pn.Err))throw Oe}!ne&&O!=="der"&&(ne=A.fromCompact(I))}ae=f.fromHex(ee)}catch{return!1}if(!ne||j&&ne.hasHighS())return!1;J&&(W=e.hash(W));const{r:le,s:ue}=ne,oe=B(W),ie=u(ue),me=c(oe*ie),be=c(le*ie),we=(tt=f.BASE.multiplyAndAddUnsafe(ae,me,be))==null?void 0:tt.toAffine();return we?c(we.x)===le:!1}return{CURVE:e,getPublicKey:S,getSharedSecret:k,sign:K,verify:Q,ProjectivePoint:f,Signature:A,utils:P}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function yx(t){return{hash:t,hmac:(e,...r)=>t1(t,e,Nv(...r)),randomBytes:Mv}}function mx(t,e){const r=n=>px({...t,...yx(n)});return{...r(e),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const h1=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),u0=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),bx=BigInt(0),gx=BigInt(1),td=BigInt(2),f0=(t,e)=>(t+e/td)/e;function wx(t){const e=h1,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,f=u*u*t%e,l=tr(f,r,e)*f%e,p=tr(l,r,e)*f%e,d=tr(p,td,e)*u%e,m=tr(d,s,e)*d%e,b=tr(m,i,e)*m%e,E=tr(b,a,e)*b%e,A=tr(E,c,e)*E%e,P=tr(A,a,e)*b%e,S=tr(P,r,e)*f%e,w=tr(S,o,e)*m%e,k=tr(w,n,e)*u%e,T=tr(k,td,e);if(!rd.eql(rd.sqr(T),t))throw new Error("Cannot find square root");return T}const rd=xh(h1,void 0,void 0,{sqrt:wx}),p1=mx({a:bx,b:BigInt(7),Fp:rd,n:u0,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=u0,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-gx*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=f0(i*t,e),c=f0(-n*t,e);let u=Rt(t-a*r-c*s,e),f=Rt(-a*n-c*i,e);const l=u>o,p=f>o;if(l&&(u=e-u),p&&(f=e-f),u>o||f>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:l,k1:u,k2neg:p,k2:f}}}},Eb),vx=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:p1},Symbol.toStringTag,{value:"Module"}));function y1(t,e={}){const{recovered:r}=e;if(typeof t.r>"u")throw new Wu({signature:t});if(typeof t.s>"u")throw new Wu({signature:t});if(r&&typeof t.yParity>"u")throw new Wu({signature:t});if(t.r<0n||t.r>r0)throw new _x({value:t.r});if(t.s<0n||t.s>r0)throw new Px({value:t.s});if(typeof t.yParity=="number"&&t.yParity!==0&&t.yParity!==1)throw new Th({value:t.yParity})}function Ex(t){return m1(Br(t))}function m1(t){if(t.length!==130&&t.length!==132)throw new Tx({signature:t});const e=BigInt(Yr(t,0,32)),r=BigInt(Yr(t,32,64)),n=(()=>{const s=+`0x${t.slice(130)}`;if(!Number.isNaN(s))try{return kh(s)}catch{throw new Th({value:s})}})();return typeof n>"u"?{r:e,s:r}:{r:e,s:r,yParity:n}}function Sx(t){if(!(typeof t.r>"u")&&!(typeof t.s>"u"))return Ax(t)}function Ax(t){const e=typeof t=="string"?m1(t):t instanceof Uint8Array?Ex(t):typeof t.r=="string"?kx(t):t.v?xx(t):{r:t.r,s:t.s,...typeof t.yParity<"u"?{yParity:t.yParity}:{}};return y1(e),e}function xx(t){return{r:t.r,s:t.s,yParity:kh(t.v)}}function kx(t){const e=(()=>{const r=t.v?Number(t.v):void 0;let n=t.yParity?Number(t.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=kh(r)),typeof n!="number")throw new Th({value:t.yParity});return n})();return{r:BigInt(t.r),s:BigInt(t.s),yParity:e}}function kh(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new Ix({value:t})}class Tx extends ve{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Zt(GE(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class Wu extends ve{constructor({signature:e}){super(`Signature \`${Lb(e)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class _x extends ve{constructor({value:e}){super(`Value \`${e}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}}class Px extends ve{constructor({value:e}){super(`Value \`${e}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}}class Th extends ve{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class Ix extends ve{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function Ox(t,e={}){return typeof t.chainId=="string"?Bx(t):{...t,...e.signature}}function Bx(t){const{address:e,chainId:r,nonce:n}=t,s=Sx(t);return{address:e,chainId:Number(r),nonce:BigInt(n),...s}}const Cx="0x8010801080108010801080108010801080108010801080108010801080108010",$x=Xg("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");function b1(t){if(typeof t=="string"){if(Yr(t,-32)!==Cx)throw new Ux(t)}else y1(t.authorization)}function Rx(t){b1(t);const e=qb(Yr(t,-64,-32)),r=Yr(t,-e-64,-64),n=Yr(t,0,-e-64),[s,i,o]=GA($x,r);return{authorization:Ox({address:s.delegation,chainId:Number(s.chainId),nonce:s.nonce,yParity:s.yParity,r:s.r,s:s.s}),signature:n,...o&&o!=="0x"?{data:o,to:i}:{}}}function Nx(t){try{return b1(t),!0}catch{return!1}}let Ux=class extends ve{constructor(e){super(`Value \`${e}\` is an invalid ERC-8010 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}};function Mx(t){return t.map(e=>({...e,value:BigInt(e.value)}))}function Fx(t){return{...t,balance:t.balance?BigInt(t.balance):void 0,nonce:t.nonce?dr(t.nonce):void 0,storageProof:t.storageProof?Mx(t.storageProof):void 0}}async function jx(t,{address:e,blockNumber:r,blockTag:n,storageKeys:s}){const i=n??"latest",o=r!==void 0?Z(r):void 0,a=await t.request({method:"eth_getProof",params:[e,s,o||i]});return Fx(a)}async function Lx(t,{address:e,blockNumber:r,blockTag:n="latest",slot:s}){const i=r!==void 0?Z(r):void 0;return await t.request({method:"eth_getStorageAt",params:[e,s,i||n]})}async function _h(t,{blockHash:e,blockNumber:r,blockTag:n,hash:s,index:i}){var f,l,p;const o=n||"latest",a=r!==void 0?Z(r):void 0;let c=null;if(s?c=await t.request({method:"eth_getTransactionByHash",params:[s]},{dedupe:!0}):e?c=await t.request({method:"eth_getTransactionByBlockHashAndIndex",params:[e,Z(i)]},{dedupe:!0}):c=await t.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[a||o,Z(i)]},{dedupe:!!a}),!c)throw new ub({blockHash:e,blockNumber:r,blockTag:o,hash:s,index:i});return(((p=(l=(f=t.chain)==null?void 0:f.formatters)==null?void 0:l.transaction)==null?void 0:p.format)||zc)(c)}async function Dx(t,{hash:e,transactionReceipt:r}){const[n,s]=await Promise.all([se(t,Sa,"getBlockNumber")({}),e?se(t,_h,"getTransaction")({hash:e}):void 0]),i=(r==null?void 0:r.blockNumber)||(s==null?void 0:s.blockNumber);return i?n-i+1n:0n}async function sc(t,{hash:e}){var s,i,o;const r=await t.request({method:"eth_getTransactionReceipt",params:[e]},{dedupe:!0});if(!r)throw new fb({hash:e});return(((o=(i=(s=t.chain)==null?void 0:s.formatters)==null?void 0:i.transactionReceipt)==null?void 0:o.format)||ug)(r)}async function Hx(t,e){var P;const{account:r,authorizationList:n,allowFailure:s=!0,blockNumber:i,blockOverrides:o,blockTag:a,stateOverride:c}=e,u=e.contracts,{batchSize:f=e.batchSize??1024,deployless:l=e.deployless??!1}=typeof((P=t.batch)==null?void 0:P.multicall)=="object"?t.batch.multicall:{},p=(()=>{if(e.multicallAddress)return e.multicallAddress;if(l)return null;if(t.chain)return Wi({blockNumber:i,chain:t.chain,contract:"multicall3"});throw new Error("client chain not configured. multicallAddress is required.")})(),d=[[]];let m=0,b=0;for(let S=0;S<u.length;S++){const{abi:w,address:k,args:T,functionName:B}=u[S];try{const U=Jt({abi:w,args:T,functionName:B});b+=(U.length-2)/2,f>0&&b>f&&d[m].length>0&&(m++,b=(U.length-2)/2,d[m]=[]),d[m]=[...d[m],{allowFailure:!0,callData:U,target:k}]}catch(U){const $=Fs(U,{abi:w,address:k,args:T,docsPath:"/docs/contract/multicall",functionName:B,sender:r});if(!s)throw $;d[m]=[...d[m],{allowFailure:!0,callData:"0x",target:k}]}}const E=await Promise.allSettled(d.map(S=>se(t,hr,"readContract")({...p===null?{code:fh}:{address:p},abi:wc,account:r,args:[S],authorizationList:n,blockNumber:i,blockOverrides:o,blockTag:a,functionName:"aggregate3",stateOverride:c}))),A=[];for(let S=0;S<E.length;S++){const w=E[S];if(w.status==="rejected"){if(!s)throw w.reason;for(let T=0;T<d[S].length;T++)A.push({status:"failure",error:w.reason,result:void 0});continue}const k=w.value;for(let T=0;T<k.length;T++){const{returnData:B,success:U}=k[T],{callData:$}=d[S][T],{abi:D,address:M,functionName:q,args:K}=u[A.length];try{if($==="0x")throw new la;if(!U)throw new jc({data:B});const Q=Xs({abi:D,args:K,data:B,functionName:q});A.push(s?{result:Q,status:"success"}:Q)}catch(Q){const G=Fs(Q,{abi:D,address:M,args:K,docsPath:"/docs/contract/multicall",functionName:q});if(!s)throw G;A.push({error:G,result:void 0,status:"failure"})}}}if(A.length!==u.length)throw new L("multicall results mismatch");return A}async function nd(t,e){const{blockNumber:r,blockTag:n=t.experimental_blockTag??"latest",blocks:s,returnFullTransactions:i,traceTransfers:o,validation:a}=e;try{const c=[];for(const p of s){const d=p.blockOverrides?Kb(p.blockOverrides):void 0,m=p.calls.map(E=>{const A=E,P=A.account?Ze(A.account):void 0,S=A.abi?Jt(A):A.data,w={...A,data:A.dataSuffix?Kt([S||"0x",A.dataSuffix]):S,from:A.from??(P==null?void 0:P.address)};return Ys(w),Vi(w)}),b=p.stateOverrides?Gd(p.stateOverrides):void 0;c.push({blockOverrides:d,calls:m,stateOverrides:b})}const f=(typeof r=="bigint"?Z(r):void 0)||n;return(await t.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:i,traceTransfers:o,validation:a},f]})).map((p,d)=>({...Kd(p),calls:p.calls.map((m,b)=>{var D,M;const{abi:E,args:A,functionName:P,to:S}=s[d].calls[b],w=((D=m.error)==null?void 0:D.data)??m.returnData,k=BigInt(m.gasUsed),T=(M=m.logs)==null?void 0:M.map(q=>kn(q)),B=m.status==="0x1"?"success":"failure",U=E&&B==="success"&&w!=="0x"?Xs({abi:E,data:w,functionName:P}):null,$=(()=>{var K;if(B==="success")return;let q;if(((K=m.error)==null?void 0:K.data)==="0x"?q=new la:m.error&&(q=new jc(m.error)),!!q)return Fs(q,{abi:E??[],address:S??"0x",args:A,functionName:P??"<unknown>"})})();return{data:w,gasUsed:k,logs:T,status:B,...B==="success"?{result:U}:{error:$}}})}))}catch(c){const u=c,f=Lc(u,{});throw f instanceof ba?u:f}}function sd(t){let e=!0,r="",n=0,s="",i=!1;for(let o=0;o<t.length;o++){const a=t[o];if(["(",")",","].includes(a)&&(e=!0),a==="("&&n++,a===")"&&n--,!!e){if(n===0){if(a===" "&&["event","function","error",""].includes(s))s="";else if(s+=a,a===")"){i=!0;break}continue}if(a===" "){t[o-1]!==","&&r!==","&&r!==",("&&(r="",e=!1);continue}s+=a,r+=a}}if(!i)throw new ve("Unable to normalize signature.");return s}function id(t,e){const r=typeof t,n=e.type;switch(n){case"address":return Yl(t,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in e?Object.values(e.components).every((s,i)=>id(Object.values(t)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||t instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(t)&&t.every(s=>id(s,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function g1(t,e,r){for(const n in t){const s=t[n],i=e[n];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return g1(s.components,i.components,r[n]);const o=[s.type,i.type];if(o.includes("address")&&o.includes("bytes20")?!0:o.includes("address")&&o.includes("string")?Yl(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?Yl(r[n],{strict:!1}):!1)return o}}function w1(t,e={}){const{prepare:r=!0}=e,n=Array.isArray(t)||typeof t=="string"?Qp(t):t;return{...n,...r?{hash:gi(n)}:{}}}function zx(t,e,r){const{args:n=[],prepare:s=!0}=r??{},i=WE(e,{strict:!1}),o=t.filter(u=>i?u.type==="function"||u.type==="error"?v1(u)===Yr(e,0,4):u.type==="event"?gi(u)===e:!1:"name"in u&&u.name===e);if(o.length===0)throw new od({name:e});if(o.length===1)return{...o[0],...s?{hash:gi(o[0])}:{}};let a;for(const u of o){if(!("inputs"in u))continue;if(!n||n.length===0){if(!u.inputs||u.inputs.length===0)return{...u,...s?{hash:gi(u)}:{}};continue}if(!u.inputs||u.inputs.length===0||u.inputs.length!==n.length)continue;if(n.every((l,p)=>{const d="inputs"in u&&u.inputs[p];return d?id(l,d):!1})){if(a&&"inputs"in a&&a.inputs){const l=g1(u.inputs,a.inputs,n);if(l)throw new qx({abiItem:u,type:l[0]},{abiItem:a,type:l[1]})}a=u}}const c=(()=>{if(a)return a;const[u,...f]=o;return{...u,overloads:f}})();if(!c)throw new od({name:e});return{...c,...s?{hash:gi(c)}:{}}}function v1(t){return Yr(gi(t),0,4)}function Vx(t){const e=typeof t=="string"?t:Kl(t);return sd(e)}function gi(t){return typeof t!="string"&&"hash"in t&&t.hash?t.hash:Kg(uh(Vx(t)))}class qx extends ve{constructor(e,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${e.type}\` in \`${sd(Kl(e.abiItem))}\`, and`,`\`${r.type}\` in \`${sd(Kl(r.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}}class od extends ve{constructor({name:e,data:r,type:n="item"}){const s=e?` with name "${e}"`:r?` with data "${r}"`:"";super(`ABI ${n}${s} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}function Gx(t,e){var s;const{bytecode:r,args:n}=e;return Or(r,(s=t.inputs)!=null&&s.length&&(n!=null&&n.length)?Sh(t.inputs,n):"0x")}function Wx(t){return w1(t)}function Kx(t,...e){const{overloads:r}=t,n=r?Zx([t,...r],t.name,{args:e[0]}):t,s=Yx(n),i=e.length>0?Sh(n.inputs,e[0]):void 0;return i?Or(s,i):s}function ii(t,e={}){return w1(t,e)}function Zx(t,e,r){const n=zx(t,e,r);if(n.type!=="function")throw new od({name:e,type:"function"});return n}function Yx(t){return v1(t)}const Xx="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Fr="0x0000000000000000000000000000000000000000",Jx="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function Qx(t,e){const{blockNumber:r,blockTag:n,calls:s,stateOverrides:i,traceAssetChanges:o,traceTransfers:a,validation:c}=e,u=e.account?Ze(e.account):void 0;if(o&&!u)throw new L("`account` is required when `traceAssetChanges` is true");const f=u?Gx(Wx("constructor(bytes, bytes)"),{bytecode:Jb,args:[Jx,Kx(ii("function getBalance(address)"),[u.address])]}):void 0,l=o?await Promise.all(e.calls.map(async H=>{if(!H.data&&!H.abi)return;const{accessList:I}=await vg(t,{account:u.address,...H,data:H.abi?Jt(H):H.data});return I.map(({address:j,storageKeys:J})=>J.length>0?j:null)})).then(H=>H.flat().filter(Boolean)):[],p=await nd(t,{blockNumber:r,blockTag:n,blocks:[...o?[{calls:[{data:f}],stateOverrides:i},{calls:l.map((H,I)=>({abi:[ii("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:H,from:Fr,nonce:I})),stateOverrides:[{address:Fr,nonce:0}]}]:[],{calls:[...s,{}].map(H=>({...H,from:u==null?void 0:u.address})),stateOverrides:i},...o?[{calls:[{data:f}]},{calls:l.map((H,I)=>({abi:[ii("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:H,from:Fr,nonce:I})),stateOverrides:[{address:Fr,nonce:0}]},{calls:l.map((H,I)=>({to:H,abi:[ii("function decimals() returns (uint256)")],functionName:"decimals",from:Fr,nonce:I})),stateOverrides:[{address:Fr,nonce:0}]},{calls:l.map((H,I)=>({to:H,abi:[ii("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:Fr,nonce:I})),stateOverrides:[{address:Fr,nonce:0}]},{calls:l.map((H,I)=>({to:H,abi:[ii("function symbol() returns (string)")],functionName:"symbol",from:Fr,nonce:I})),stateOverrides:[{address:Fr,nonce:0}]}]:[]],traceTransfers:a,validation:c}),d=o?p[2]:p[0],[m,b,,E,A,P,S,w]=o?p:[],{calls:k,...T}=d,B=k.slice(0,-1)??[],U=(m==null?void 0:m.calls)??[],$=(b==null?void 0:b.calls)??[],D=[...U,...$].map(H=>H.status==="success"?ut(H.data):null),M=(E==null?void 0:E.calls)??[],q=(A==null?void 0:A.calls)??[],K=[...M,...q].map(H=>H.status==="success"?ut(H.data):null),Q=((P==null?void 0:P.calls)??[]).map(H=>H.status==="success"?H.result:null),G=((w==null?void 0:w.calls)??[]).map(H=>H.status==="success"?H.result:null),W=((S==null?void 0:S.calls)??[]).map(H=>H.status==="success"?H.result:null),ee=[];for(const[H,I]of K.entries()){const j=D[H];if(typeof I!="bigint"||typeof j!="bigint")continue;const J=Q[H-1],O=G[H-1],R=W[H-1],F=H===0?{address:Xx,decimals:18,symbol:"ETH"}:{address:l[H-1],decimals:R||J?Number(J??1):void 0,symbol:O??void 0};ee.some(ne=>ne.token.address===F.address)||ee.push({token:F,value:{pre:j,post:I,diff:I-j}})}return{assetChanges:ee,block:T,results:B}}const E1="0x6492649264926492649264926492649264926492649264926492649264926492";function e3(t){if(Yr(t,-32)!==E1)throw new n3(t)}function t3(t){const{data:e,signature:r,to:n}=t;return Or(Sh(Xg("address, bytes, bytes"),[n,e,r]),E1)}function r3(t){try{return e3(t),!0}catch{return!1}}class n3 extends ve{constructor(e){super(`Value \`${e}\` is an invalid ERC-6492 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}}function s3({r:t,s:e,to:r="hex",v:n,yParity:s}){const i=(()=>{if(s===0||s===1)return s;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),o=`0x${new p1.Signature(ut(t),ut(e)).toCompactHex()}${i===0?"1b":"1c"}`;return r==="hex"?o:Jr(o)}async function tu(t,e){var a,c,u,f,l,p;const{address:r,hash:n,erc6492VerifierAddress:s=e.universalSignatureVerifierAddress??((u=(c=(a=t.chain)==null?void 0:a.contracts)==null?void 0:c.erc6492Verifier)==null?void 0:u.address),multicallAddress:i=e.multicallAddress??((p=(l=(f=t.chain)==null?void 0:f.contracts)==null?void 0:l.multicall3)==null?void 0:p.address)}=e,o=(()=>{const d=e.signature;return Pr(d)?d:typeof d=="object"&&"r"in d&&"s"in d?s3(d):et(d)})();try{return Nx(o)?await i3(t,{...e,multicallAddress:i,signature:o}):await o3(t,{...e,verifierAddress:s,signature:o})}catch(d){try{if(Gi(Ud(r),await hb({hash:n,signature:o})))return!0}catch{}if(d instanceof Hs)return!1;throw d}}async function i3(t,e){var E;const{address:r,blockNumber:n,blockTag:s,hash:i,multicallAddress:o}=e,{authorization:a,data:c,signature:u,to:f}=Rx(e.signature);if(await Gl(t,{address:r,blockNumber:n,blockTag:s})===$r(["0xef0100",a.address]))return await a3(t,{address:r,blockNumber:n,blockTag:s,hash:i,signature:u});const p={address:a.address,chainId:Number(a.chainId),nonce:Number(a.nonce),r:Z(a.r,{size:32}),s:Z(a.s,{size:32}),yParity:a.yParity};if(!await i8({address:r,authorization:p}))throw new Hs;const m=await se(t,hr,"readContract")({...o?{address:o}:{code:fh},authorizationList:[p],abi:wc,blockNumber:n,blockTag:"pending",functionName:"aggregate3",args:[[...c?[{allowFailure:!0,target:f??r,callData:c}]:[],{allowFailure:!0,target:r,callData:Jt({abi:Xb,functionName:"isValidSignature",args:[i,u]})}]]}),b=(E=m[m.length-1])==null?void 0:E.returnData;if(b!=null&&b.startsWith("0x1626ba7e"))return!0;throw new Hs}async function o3(t,e){const{address:r,factory:n,factoryData:s,hash:i,signature:o,verifierAddress:a,...c}=e,u=await(async()=>!n&&!s||r3(o)?o:t3({data:s,signature:o,to:n}))(),f=a?{to:a,data:Jt({abi:zp,functionName:"isValidSig",args:[r,i,u]}),...c}:{data:Zc({abi:zp,args:[r,i,u],bytecode:eS}),...c},{data:l}=await se(t,Ea,"call")(f).catch(p=>{throw p instanceof lb?new Hs:p});if(mv(l??"0x0"))return!0;throw new Hs}async function a3(t,e){const{address:r,blockNumber:n,blockTag:s,hash:i,signature:o}=e;if((await se(t,hr,"readContract")({address:r,abi:Xb,args:[i,o],blockNumber:n,blockTag:s,functionName:"isValidSignature"}).catch(c=>{throw c instanceof db?new Hs:c})).startsWith("0x1626ba7e"))return!0;throw new Hs}class Hs extends Error{}async function c3(t,{address:e,message:r,factory:n,factoryData:s,signature:i,...o}){const a=Ig(r);return tu(t,{address:e,factory:n,factoryData:s,hash:a,signature:i,...o})}async function u3(t,e){const{address:r,factory:n,factoryData:s,signature:i,message:o,primaryType:a,types:c,domain:u,...f}=e,l=I8({message:o,primaryType:a,types:c,domain:u});return tu(t,{address:r,factory:n,factoryData:s,hash:l,signature:i,...f})}function S1(t,{emitOnBegin:e=!1,emitMissed:r=!1,onBlockNumber:n,onError:s,poll:i,pollingInterval:o=t.pollingInterval}){const a=typeof i<"u"?i:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc"));let c;return a?(()=>{const l=Qe(["watchBlockNumber",t.uid,e,r,o]);return Tn(l,{onBlockNumber:n,onError:s},p=>Ki(async()=>{var d;try{const m=await se(t,Sa,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(m===c)return;if(m-c>1&&r)for(let b=c+1n;b<m;b++)p.onBlockNumber(b,c),c=b}(c===void 0||m>c)&&(p.onBlockNumber(m,c),c=m)}catch(m){(d=p.onError)==null||d.call(p,m)}},{emitOnBegin:e,interval:o}))})():(()=>{const l=Qe(["watchBlockNumber",t.uid,e,r]);return Tn(l,{onBlockNumber:n,onError:s},p=>{let d=!0,m=()=>d=!1;return(async()=>{try{const b=(()=>{if(t.transport.type==="fallback"){const A=t.transport.transports.find(P=>P.config.type==="webSocket"||P.config.type==="ipc");return A?A.value:t.transport}return t.transport})(),{unsubscribe:E}=await b.subscribe({params:["newHeads"],onData(A){var S;if(!d)return;const P=ut((S=A.result)==null?void 0:S.number);p.onBlockNumber(P,c),c=P},onError(A){var P;(P=p.onError)==null||P.call(p,A)}});m=E,d||m()}catch(b){s==null||s(b)}})(),()=>m()})})()}async function f3(t,e){const{checkReplacement:r=!0,confirmations:n=1,hash:s,onReplaced:i,retryCount:o=6,retryDelay:a=({count:k})=>~~(1<<k)*200,timeout:c=18e4}=e,u=Qe(["waitForTransactionReceipt",t.uid,s]),f=(()=>{var k;return e.pollingInterval?e.pollingInterval:(k=t.chain)!=null&&k.experimental_preconfirmationTime?t.chain.experimental_preconfirmationTime:t.pollingInterval})();let l,p,d,m=!1,b,E;const{promise:A,resolve:P,reject:S}=lh(),w=c?setTimeout(()=>{E==null||E(),b==null||b(),S(new $5({hash:s}))},c):void 0;return b=Tn(u,{onReplaced:i,resolve:P,reject:S},async k=>{if(d=await se(t,sc,"getTransactionReceipt")({hash:s}).catch(()=>{}),d&&n<=1){clearTimeout(w),k.resolve(d),b==null||b();return}E=se(t,S1,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:f,async onBlockNumber(T){const B=$=>{clearTimeout(w),E==null||E(),$(),b==null||b()};let U=T;if(!m)try{if(d){if(n>1&&(!d.blockNumber||U-d.blockNumber+1n<n))return;B(()=>k.resolve(d));return}if(r&&!l&&(m=!0,await vc(async()=>{l=await se(t,_h,"getTransaction")({hash:s}),l.blockNumber&&(U=l.blockNumber)},{delay:a,retryCount:o}),m=!1),d=await se(t,sc,"getTransactionReceipt")({hash:s}),n>1&&(!d.blockNumber||U-d.blockNumber+1n<n))return;B(()=>k.resolve(d))}catch($){if($ instanceof ub||$ instanceof fb){if(!l){m=!1;return}try{p=l,m=!0;const D=await vc(()=>se(t,Zr,"getBlock")({blockNumber:U,includeTransactions:!0}),{delay:a,retryCount:o,shouldRetry:({error:K})=>K instanceof mb});m=!1;const M=D.transactions.find(({from:K,nonce:Q})=>K===p.from&&Q===p.nonce);if(!M||(d=await se(t,sc,"getTransactionReceipt")({hash:M.hash}),n>1&&(!d.blockNumber||U-d.blockNumber+1n<n)))return;let q="replaced";M.to===p.to&&M.value===p.value&&M.input===p.input?q="repriced":M.from===M.to&&M.value===0n&&(q="cancelled"),B(()=>{var K;(K=k.onReplaced)==null||K.call(k,{reason:q,replacedTransaction:p,transaction:M,transactionReceipt:d}),k.resolve(d)})}catch(D){B(()=>k.reject(D))}}else B(()=>k.reject($))}}})}),A}function l3(t,{blockTag:e=t.experimental_blockTag??"latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:s,onError:i,includeTransactions:o,poll:a,pollingInterval:c=t.pollingInterval}){const u=typeof a<"u"?a:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")),f=o??!1;let l;return u?(()=>{const m=Qe(["watchBlocks",t.uid,e,r,n,f,c]);return Tn(m,{onBlock:s,onError:i},b=>Ki(async()=>{var E;try{const A=await se(t,Zr,"getBlock")({blockTag:e,includeTransactions:f});if(A.number!==null&&(l==null?void 0:l.number)!=null){if(A.number===l.number)return;if(A.number-l.number>1&&r)for(let P=(l==null?void 0:l.number)+1n;P<A.number;P++){const S=await se(t,Zr,"getBlock")({blockNumber:P,includeTransactions:f});b.onBlock(S,l),l=S}}((l==null?void 0:l.number)==null||e==="pending"&&(A==null?void 0:A.number)==null||A.number!==null&&A.number>l.number)&&(b.onBlock(A,l),l=A)}catch(A){(E=b.onError)==null||E.call(b,A)}},{emitOnBegin:n,interval:c}))})():(()=>{let m=!0,b=!0,E=()=>m=!1;return(async()=>{try{n&&se(t,Zr,"getBlock")({blockTag:e,includeTransactions:f}).then(S=>{m&&b&&(s(S,void 0),b=!1)}).catch(i);const A=(()=>{if(t.transport.type==="fallback"){const S=t.transport.transports.find(w=>w.config.type==="webSocket"||w.config.type==="ipc");return S?S.value:t.transport}return t.transport})(),{unsubscribe:P}=await A.subscribe({params:["newHeads"],async onData(S){var k;if(!m)return;const w=await se(t,Zr,"getBlock")({blockNumber:(k=S.result)==null?void 0:k.number,includeTransactions:f}).catch(()=>{});m&&(s(w,l),b=!1,l=w)},onError(S){i==null||i(S)}});E=P,m||E()}catch(A){i==null||i(A)}})(),()=>E()})()}function d3(t,{address:e,args:r,batch:n=!0,event:s,events:i,fromBlock:o,onError:a,onLogs:c,poll:u,pollingInterval:f=t.pollingInterval,strict:l}){const p=typeof u<"u"?u:typeof o=="bigint"?!0:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")),d=l??!1;return p?(()=>{const E=Qe(["watchEvent",e,r,n,t.uid,s,f,o]);return Tn(E,{onLogs:c,onError:a},A=>{let P;o!==void 0&&(P=o-1n);let S,w=!1;const k=Ki(async()=>{var T;if(!w){try{S=await se(t,Eg,"createEventFilter")({address:e,args:r,event:s,events:i,strict:d,fromBlock:o})}catch{}w=!0;return}try{let B;if(S)B=await se(t,Yc,"getFilterChanges")({filter:S});else{const U=await se(t,Sa,"getBlockNumber")({});P&&P!==U?B=await se(t,sh,"getLogs")({address:e,args:r,event:s,events:i,fromBlock:P+1n,toBlock:U}):B=[],P=U}if(B.length===0)return;if(n)A.onLogs(B);else for(const U of B)A.onLogs([U])}catch(B){S&&B instanceof Ms&&(w=!1),(T=A.onError)==null||T.call(A,B)}},{emitOnBegin:!0,interval:f});return async()=>{S&&await se(t,Xc,"uninstallFilter")({filter:S}),k()}})})():(()=>{let E=!0,A=()=>E=!1;return(async()=>{try{const P=(()=>{if(t.transport.type==="fallback"){const T=t.transport.transports.find(B=>B.config.type==="webSocket"||B.config.type==="ipc");return T?T.value:t.transport}return t.transport})(),S=i??(s?[s]:void 0);let w=[];S&&(w=[S.flatMap(B=>pa({abi:[B],eventName:B.name,args:r}))],s&&(w=w[0]));const{unsubscribe:k}=await P.subscribe({params:["logs",{address:e,topics:w}],onData(T){var U;if(!E)return;const B=T.result;try{const{eventName:$,args:D}=rh({abi:S??[],data:B.data,topics:B.topics,strict:d}),M=kn(B,{args:D,eventName:$});c([M])}catch($){let D,M;if($ instanceof Po||$ instanceof Cc){if(l)return;D=$.abiItem.name,M=(U=$.abiItem.inputs)==null?void 0:U.some(K=>!("name"in K&&K.name))}const q=kn(B,{args:M?[]:{},eventName:D});c([q])}},onError(T){a==null||a(T)}});A=k,E||A()}catch(P){a==null||a(P)}})(),()=>A()})()}function h3(t,{batch:e=!0,onError:r,onTransactions:n,poll:s,pollingInterval:i=t.pollingInterval}){return(typeof s<"u"?s:t.transport.type!=="webSocket"&&t.transport.type!=="ipc")?(()=>{const u=Qe(["watchPendingTransactions",t.uid,e,i]);return Tn(u,{onTransactions:n,onError:r},f=>{let l;const p=Ki(async()=>{var d;try{if(!l)try{l=await se(t,Sg,"createPendingTransactionFilter")({});return}catch(b){throw p(),b}const m=await se(t,Yc,"getFilterChanges")({filter:l});if(m.length===0)return;if(e)f.onTransactions(m);else for(const b of m)f.onTransactions([b])}catch(m){(d=f.onError)==null||d.call(f,m)}},{emitOnBegin:!0,interval:i});return async()=>{l&&await se(t,Xc,"uninstallFilter")({filter:l}),p()}})})():(()=>{let u=!0,f=()=>u=!1;return(async()=>{try{const{unsubscribe:l}=await t.transport.subscribe({params:["newPendingTransactions"],onData(p){if(!u)return;const d=p.result;n([d])},onError(p){r==null||r(p)}});f=l,u||f()}catch(l){r==null||r(l)}})(),()=>f()})()}function p3(t){var l,p,d;const{scheme:e,statement:r,...n}=((l=t.match(y3))==null?void 0:l.groups)??{},{chainId:s,expirationTime:i,issuedAt:o,notBefore:a,requestId:c,...u}=((p=t.match(m3))==null?void 0:p.groups)??{},f=(d=t.split("Resources:")[1])==null?void 0:d.split(`
|
|
46
|
-
- `).slice(1);return{...n,...u,...s?{chainId:Number(s)}:{},...i?{expirationTime:new Date(i)}:{},...o?{issuedAt:new Date(o)}:{},...a?{notBefore:new Date(a)}:{},...c?{requestId:c}:{},...f?{resources:f}:{},...e?{scheme:e}:{},...r?{statement:r}:{}}}const y3=/^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?<address>0x[a-fA-F0-9]{40})\n\n(?:(?<statement>.*)\n\n)?/,m3=/(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.+))?/;function b3(t){const{address:e,domain:r,message:n,nonce:s,scheme:i,time:o=new Date}=t;if(r&&n.domain!==r||s&&n.nonce!==s||i&&n.scheme!==i||n.expirationTime&&o>=n.expirationTime||n.notBefore&&o<n.notBefore)return!1;try{if(!n.address||!at(n.address,{strict:!1})||e&&!Gi(n.address,e))return!1}catch{return!1}return!0}async function g3(t,e){const{address:r,domain:n,message:s,nonce:i,scheme:o,signature:a,time:c=new Date,...u}=e,f=p3(s);if(!f.address||!b3({address:r,domain:n,message:f,nonce:i,scheme:o,time:c}))return!1;const p=Ig(s);return tu(t,{address:f.address,hash:p,signature:a,...u})}function w3(t){return{call:e=>Ea(t,e),createAccessList:e=>vg(t,e),createBlockFilter:()=>jS(t),createContractEventFilter:e=>Ld(t,e),createEventFilter:e=>Eg(t,e),createPendingTransactionFilter:()=>Sg(t),estimateContractGas:e=>Cb(t,e),estimateGas:e=>th(t,e),getBalance:e=>Bb(t,e),getBlobBaseFee:()=>LS(t),getBlock:e=>Zr(t,e),getBlockNumber:e=>Sa(t,e),getBlockTransactionCount:e=>DS(t,e),getBytecode:e=>Gl(t,e),getChainId:()=>qi(t),getCode:e=>Gl(t,e),getContractEvents:e=>ih(t,e),getEip712Domain:e=>zS(t,e),getEnsAddress:e=>AS(t,e),getEnsAvatar:e=>US(t,e),getEnsName:e=>MS(t,e),getEnsResolver:e=>FS(t,e),getEnsText:e=>wg(t,e),getFeeHistory:e=>GS(t,e),estimateFeesPerGas:e=>rE(t,e),getFilterChanges:e=>Yc(t,e),getFilterLogs:e=>WS(t,e),getGasPrice:()=>Zd(t),getLogs:e=>sh(t,e),getProof:e=>jx(t,e),estimateMaxPriorityFeePerGas:e=>tE(t,e),getStorageAt:e=>Lx(t,e),getTransaction:e=>_h(t,e),getTransactionConfirmations:e=>Dx(t,e),getTransactionCount:e=>Yd(t,e),getTransactionReceipt:e=>sc(t,e),multicall:e=>Hx(t,e),prepareTransactionRequest:e=>Vc(t,e),readContract:e=>hr(t,e),sendRawTransaction:e=>dh(t,e),simulate:e=>nd(t,e),simulateBlocks:e=>nd(t,e),simulateCalls:e=>Qx(t,e),simulateContract:e=>ng(t,e),verifyHash:e=>tu(t,e),verifyMessage:e=>c3(t,e),verifySiweMessage:e=>g3(t,e),verifyTypedData:e=>u3(t,e),uninstallFilter:e=>Xc(t,e),waitForTransactionReceipt:e=>f3(t,e),watchBlocks:e=>l3(t,e),watchBlockNumber:e=>S1(t,e),watchContractEvent:e=>sg(t,e),watchEvent:e=>d3(t,e),watchPendingTransactions:e=>h3(t,e)}}function v3(t){const{key:e="public",name:r="Public Client"}=t;return pg({...t,key:e,name:r,type:"publicClient"}).extend(w3)}async function E3(t,{chain:e}){const{id:r,name:n,nativeCurrency:s,rpcUrls:i,blockExplorers:o}=e;await t.request({method:"wallet_addEthereumChain",params:[{chainId:Z(r),chainName:n,nativeCurrency:s,rpcUrls:i.default.http,blockExplorerUrls:o?Object.values(o).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}function S3(t,e){const{abi:r,args:n,bytecode:s,...i}=e,o=Zc({abi:r,args:n,bytecode:s});return Jc(t,{...i,...i.authorizationList?{to:null}:{},data:o})}async function A3(t){var r;return((r=t.account)==null?void 0:r.type)==="local"?[t.account.address]:(await t.request({method:"eth_accounts"},{dedupe:!0})).map(n=>da(n))}async function x3(t,e={}){const{account:r=t.account,chainId:n}=e,s=r?Ze(r):void 0,i=n?[s==null?void 0:s.address,[Z(n)]]:[s==null?void 0:s.address],o=await t.request({method:"wallet_getCapabilities",params:i}),a={};for(const[c,u]of Object.entries(o)){a[Number(c)]={};for(let[f,l]of Object.entries(u))f==="addSubAccount"&&(f="unstable_addSubAccount"),a[Number(c)][f]=l}return typeof n=="number"?a[n]:a}async function k3(t){return await t.request({method:"wallet_getPermissions"},{dedupe:!0})}async function A1(t,e){var c;const{account:r=t.account,chainId:n,nonce:s}=e;if(!r)throw new Js({docsPath:"/docs/eip7702/prepareAuthorization"});const i=Ze(r),o=(()=>{if(e.executor)return e.executor==="self"?e.executor:Ze(e.executor)})(),a={address:e.contractAddress??e.address,chainId:n,nonce:s};return typeof a.chainId>"u"&&(a.chainId=((c=t.chain)==null?void 0:c.id)??await se(t,qi,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await se(t,Yd,"getTransactionCount")({address:i.address,blockTag:"pending"}),(o==="self"||o!=null&&o.address&&Gi(o.address,i.address))&&(a.nonce+=1)),a}async function T3(t){return(await t.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>Ud(r))}async function _3(t,e){return t.request({method:"wallet_requestPermissions",params:[e]},{retryCount:0})}async function P3(t,e){const{id:r}=e;await t.request({method:"wallet_showCallsStatus",params:[r]})}async function I3(t,e){const{account:r=t.account}=e;if(!r)throw new Js({docsPath:"/docs/eip7702/signAuthorization"});const n=Ze(r);if(!n.signAuthorization)throw new nc({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});const s=await A1(t,e);return n.signAuthorization(s)}async function O3(t,{account:e=t.account,message:r}){if(!e)throw new Js({docsPath:"/docs/actions/wallet/signMessage"});const n=Ze(e);if(n.signMessage)return n.signMessage({message:r});const s=typeof r=="string"?Bi(r):r.raw instanceof Uint8Array?Bt(r.raw):r.raw;return t.request({method:"personal_sign",params:[s,n.address]},{retryCount:0})}async function B3(t,e){var u,f,l,p;const{account:r=t.account,chain:n=t.chain,...s}=e;if(!r)throw new Js({docsPath:"/docs/actions/wallet/signTransaction"});const i=Ze(r);Ys({account:i,...e});const o=await se(t,qi,"getChainId")({});n!==null&&ig({currentChainId:o,chain:n});const a=(n==null?void 0:n.formatters)||((u=t.chain)==null?void 0:u.formatters),c=((f=a==null?void 0:a.transactionRequest)==null?void 0:f.format)||Vi;return i.signTransaction?i.signTransaction({...s,chainId:o},{serializer:(p=(l=t.chain)==null?void 0:l.serializers)==null?void 0:p.transaction}):await t.request({method:"eth_signTransaction",params:[{...c(s),chainId:Z(o),from:i.address}]},{retryCount:0})}async function C3(t,e){const{account:r=t.account,domain:n,message:s,primaryType:i}=e;if(!r)throw new Js({docsPath:"/docs/actions/wallet/signTypedData"});const o=Ze(r),a={EIP712Domain:Bg({domain:n}),...e.types};if(Og({domain:n,message:s,primaryType:i,types:a}),o.signTypedData)return o.signTypedData({domain:n,message:s,primaryType:i,types:a});const c=_8({domain:n,message:s,primaryType:i,types:a});return t.request({method:"eth_signTypedData_v4",params:[o.address,c]},{retryCount:0})}async function $3(t,{id:e}){await t.request({method:"wallet_switchEthereumChain",params:[{chainId:Z(e)}]},{retryCount:0})}async function R3(t,e){return await t.request({method:"wallet_watchAsset",params:e},{retryCount:0})}function N3(t){return{addChain:e=>E3(t,e),deployContract:e=>S3(t,e),getAddresses:()=>A3(t),getCallsStatus:e=>dg(t,e),getCapabilities:e=>x3(t,e),getChainId:()=>qi(t),getPermissions:()=>k3(t),prepareAuthorization:e=>A1(t,e),prepareTransactionRequest:e=>Vc(t,e),requestAddresses:()=>T3(t),requestPermissions:e=>_3(t,e),sendCalls:e=>yS(t,e),sendRawTransaction:e=>dh(t,e),sendTransaction:e=>Jc(t,e),showCallsStatus:e=>P3(t,e),signAuthorization:e=>I3(t,e),signMessage:e=>O3(t,e),signTransaction:e=>B3(t,e),signTypedData:e=>C3(t,e),switchChain:e=>$3(t,e),waitForCallsStatus:e=>mS(t,e),watchAsset:e=>R3(t,e),writeContract:e=>ag(t,e)}}function Ku(t){const{key:e="wallet",name:r="Wallet Client",transport:n}=t;return pg({...t,key:e,name:r,transport:n,type:"walletClient"}).extend(N3)}function x1({key:t,methods:e,name:r,request:n,retryCount:s=3,retryDelay:i=150,timeout:o,type:a},c){const u=hg();return{config:{key:t,methods:e,name:r,request:n,retryCount:s,retryDelay:i,timeout:o,type:a},request:a8(n,{methods:e,retryCount:s,retryDelay:i,uid:u}),value:c}}function l0(t,e={}){const{key:r="custom",methods:n,name:s="Custom Provider",retryDelay:i}=e;return({retryCount:o})=>x1({key:r,methods:n,name:s,request:t.request.bind(t),retryCount:e.retryCount??o,retryDelay:i,type:"custom"})}class U3 extends L{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 k1(t,e={}){const{batch:r,fetchFn:n,fetchOptions:s,key:i="http",methods:o,name:a="HTTP JSON-RPC",onFetchRequest:c,onFetchResponse:u,retryDelay:f,raw:l}=e;return({chain:p,retryCount:d,timeout:m})=>{const{batchSize:b=1e3,wait:E=0}=typeof r=="object"?r:{},A=e.retryCount??d,P=m??e.timeout??1e4,S=p==null?void 0:p.rpcUrls.default.http[0];if(!S)throw new U3;const w=E8(S,{fetchFn:n,fetchOptions:s,onRequest:c,onResponse:u,timeout:P});return x1({key:i,methods:o,name:a,async request({method:k,params:T}){const B={method:k,params:T},{schedule:U}=tg({id:S,wait:E,shouldSplitBatch(q){return q.length>b},fn:q=>w.request({body:q}),sort:(q,K)=>q.id-K.id}),$=async q=>r?U(q):[await w.request({body:q})],[{error:D,result:M}]=await $(B);if(l)return{error:D,result:M};if(D)throw new zd({body:B,error:D,url:S});return M},retryCount:A,retryDelay:f,timeout:P,type:"http"},{fetchOptions:s,url:S})}}const ic={mainnet:{baseurl:"https://api.garden.finance",auth:"https://api.garden.finance/auth",info:"https://api.garden.finance/info",relayer:"https://relayer.garden.finance"},testnet:{baseurl:"https://testnet.api.garden.finance",auth:"https://testnet.api.garden.finance/auth",info:"https://testnet.api.garden.finance/info",relayer:"https://testnet.api.garden.finance/relayer"},localnet:{baseurl:"",auth:"",info:"",relayer:""}},Qo={[g.Network.MAINNET]:{chainId:"0x534e5f4d41494e",nodeUrl:"https://starknet-mainnet.public.blastapi.io/rpc/v0_8"},[g.Network.TESTNET]:{chainId:"0x534e5f5345504f4c4941",nodeUrl:"https://starknet-sepolia.public.blastapi.io/rpc/v0_8"},[g.Network.LOCALNET]:{chainId:"",nodeUrl:""}},T1={[g.Network.MAINNET]:"9cBuPNiHXiMNg3Fin8xLCGJQBTXjYQTFtyaFQv2uiM1H",[g.Network.TESTNET]:"ANUVKxeqaec3bf4DVPqLTnG1PT3Fng56wPcE7LXAb46Q",[g.Network.LOCALNET]:"AKnL4NNf3DGWZJS6cPknBuEGnVsV4A4m5tgebLHaRSZ9"},ad={mainnet:{native:"2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",spl:"gdnvdMCHJgnidtU7SL8RkRshHPvDJU1pdfZEpoLvqdU"},staging:{native:"6eksgdCnSjUaGQWZ6iYvauv1qzvYPF33RTGTM1ZuyENx",spl:"2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC"}},cd={[g.Network.TESTNET]:{packageId:"0x99865b03dd1bc03d0a6a805c454ea257c464f7abcccae9cd4b621b91e7ca04de",moduleName:"AtomicSwap"},[g.Network.MAINNET]:{packageId:"0xbfb5728aab0dd117747ef4574af6d3540ea6093109c22856e3ae201dfd58c0fc",moduleName:"AtomicSwap"},[g.Network.LOCALNET]:{packageId:"",moduleName:""}},_1={asset:X.ChainAsset.from(X.Assets.base.cBBTC)};var xi=(t=>(t.SLOW="SLOW",t.MEDIUM="MEDIUM",t.FAST="FAST",t))(xi||{}),Tr=(t=>(t.Mainnet="Mainnet",t.Testnet="Testnet",t.Regtest="Regtest",t))(Tr||{}),oc=(t=>(t.ALL="ALL",t.IN="IN",t.OUT="OUT",t))(oc||{});const M3={SLOW:"economyFee",MEDIUM:"hourFee",FAST:"fastestFee"};function ud(t){const e=typeof t=="string"?t:t.network,r=e===g.Network.MAINNET?ic.mainnet:g.Network.TESTNET?ic.testnet:ic.localnet;return{api:typeof t=="string"?r:{...r,...t},network:e}}function F3(t){return typeof t=="string"&&(t=Buffer.from(t,"hex")),t.length===32?t:t.subarray(1,33)}function d0(t,e){if(!t)throw new Error(e)}function j3(t){return Buffer.concat([Uint8Array.from([192]),L3(t)])}function L3(t){const e=dp.encodingLength(t.length),r=Buffer.allocUnsafe(e);return dp.encode(t.length,r),Buffer.concat([r,t])}function D3(t,e){if(t.compare(e)>0){const r=t;t=e,e=r}return[t,e]}const je=t=>t.length===64?t:t.slice(2),H3=t=>{if(!t)return!1;try{const e=Buffer.from(t,"hex");return fr.isPoint(e)}catch{return!1}},P1=(t,e,r,n)=>t+":"+e.toLowerCase()+"::"+r+":"+n.toLowerCase();function z3(t,e){if(!t)return!1;const r=e===g.Environment.MAINNET?Ae.networks.bitcoin:e===g.Environment.TESTNET?Ae.networks.testnet:Ae.networks.regtest;if(!r)return!1;Ae.initEccLib(fr);try{return Ae.address.toOutputScript(t,r),!0}catch{return!1}}function no(t,e){const r=[];for(let n=0;n<e;n++)r.push(t);return r}const V3=t=>{switch(t){case g.Network.MAINNET:return Tr.Mainnet;case g.Network.TESTNET:return Tr.Testnet;case g.Network.LOCALNET:return Tr.Regtest;default:throw new Error(`Invalid bitcoin network ${t}`)}},q3=t=>{switch(t){case g.Network.MAINNET:return Ae.networks.bitcoin;case g.Network.TESTNET:return Ae.networks.testnet;case g.Network.LOCALNET:return Ae.networks.regtest;default:throw new Error(`Invalid bitcoin network ${t}`)}},G3=t=>{const e=t.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(e)},h0=t=>{if(typeof t=="object"&&"r"in t&&"s"in t)return g.Ok([t.r.toString(),t.s.toString()]);if(Array.isArray(t)){const e=t.map(r=>typeof r=="string"&&r.startsWith("0x")&&G3(r)?BigInt(r).toString():r);return g.Ok(e)}return g.Err("Invalid signature format")};function fd(t){return Buffer.from(t,"hex").reverse()}function ld(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"}const Da=async(t,e)=>{const r=Date.now(),n=3e4,s=2e3;for(;Date.now()-r<n;){const i=await t.getLatestBlockhash(),o=await t.confirmTransaction({signature:e,blockhash:i.blockhash,lastValidBlockHeight:i.lastValidBlockHeight},"confirmed");if(o.value&&o.value.err==null)return console.log("Tx Confirmed ✅",e),!0;console.log("Tx not confirmed yet. Retrying in 2 seconds..."),await new Promise(a=>setTimeout(a,s))}return!1},Ph=async(t,e)=>{var a,c;const r=await g.Fetcher.get(e+"/v2/assets");if(r.error)return g.Err("Failed to fetch asset info: "+r.error);const s=(r.result||[]).find(u=>u.id===t);if(!s)return g.Err(`Asset info not found for asset id: ${t}`);const i=((a=s.htlc)==null?void 0:a.address)||"",o=((c=s.token)==null?void 0:c.address)||"";return g.Ok({htlcAddress:i,tokenAddress:o})},p0=t=>{if(t==null||t.includes("."))return g.Err("Invalid amount ",t);const e=new i6.BigNumber(t);return!e.isInteger()||e.isNaN()||e.lt(0)||e.isLessThanOrEqualTo(0)?g.Err("Invalid amount ",t):g.Ok(e)},W3=t=>(t??[]).map(e=>({fee:e.fee,address:e.address,asset:e.asset??_1.asset})),y0=async(t,e,r)=>{var n;if(r&&r[t])return g.Ok(r[t]);switch(t){case X.BlockchainType.evm:return e.evm?g.Ok(e.evm.htlcActorAddress):g.Err("Please provide evmHTLC when initializing garden or pass EVM address in SwapParams");case X.BlockchainType.bitcoin:{const s=(n=e.bitcoin)==null?void 0:n.getPublicKey;return!s||!H3(s)?g.Err("Invalid btc public key or pass Bitcoin address in SwapParams"):g.Ok(je(s))}case X.BlockchainType.solana:return e.solana?g.Ok(e.solana.htlcActorAddress):g.Err("Please provide solanaHTLC when initializing garden or pass Solana address in SwapParams");case X.BlockchainType.starknet:return e.starknet?g.Ok(e.starknet.htlcActorAddress):g.Err("Please provide starknetHTLC when initializing garden or pass Starknet address in SwapParams");case X.BlockchainType.sui:return e.sui?g.Ok(e.sui.htlcActorAddress):g.Err("Please provide suiHTLC when initializing garden or pass Sui address in SwapParams");default:return g.Err("Unsupported chain")}},K3=async(t,e)=>{const n={[X.BlockchainType.evm]:{htlc:e.evm,name:"EVM"},[X.BlockchainType.solana]:{htlc:e.solana,name:"Solana"},[X.BlockchainType.starknet]:{htlc:e.starknet,name:"Starknet"},[X.BlockchainType.sui]:{htlc:e.sui,name:"Sui"},[X.BlockchainType.bitcoin]:{htlc:e.bitcoin,name:"Bitcoin"}}[t];return n?n.htlc?g.Ok(void 0):g.Err(`${n.name} HTLC is required for swap initiation. Please provide ${n.name.toLowerCase()}HTLC when initializing garden.`):g.Err(`Unsupported blockchain type for swap initiation: ${t}`)},Z3=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),Y3=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),X3=Buffer.concat([Z3,Y3]),J3=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),m0={failedToCreateInternalPubkey:"failed to create internal pubkey"};function b0(){const t=pe.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),e=fr.pointMultiply(Buffer.concat([Buffer.from("04","hex"),X3]),t);if(!e)throw new Error(m0.failedToCreateInternalPubkey);const r=fr.pointAdd(J3,e);if(!r)throw new Error(m0.failedToCreateInternalPubkey);return F3(Buffer.from(r))}var Qr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function I1(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}),r}var Le={},Et={},Qs={},ru={};ru.byteLength=tk;ru.toByteArray=nk;ru.fromByteArray=ok;var Wr=[],ir=[],Q3=typeof Uint8Array<"u"?Uint8Array:Array,Zu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var oi=0,ek=Zu.length;oi<ek;++oi)Wr[oi]=Zu[oi],ir[Zu.charCodeAt(oi)]=oi;ir[45]=62;ir[95]=63;function O1(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function tk(t){var e=O1(t),r=e[0],n=e[1];return(r+n)*3/4-n}function rk(t,e,r){return(e+r)*3/4-r}function nk(t){var e,r=O1(t),n=r[0],s=r[1],i=new Q3(rk(t,n,s)),o=0,a=s>0?n-4:n,c;for(c=0;c<a;c+=4)e=ir[t.charCodeAt(c)]<<18|ir[t.charCodeAt(c+1)]<<12|ir[t.charCodeAt(c+2)]<<6|ir[t.charCodeAt(c+3)],i[o++]=e>>16&255,i[o++]=e>>8&255,i[o++]=e&255;return s===2&&(e=ir[t.charCodeAt(c)]<<2|ir[t.charCodeAt(c+1)]>>4,i[o++]=e&255),s===1&&(e=ir[t.charCodeAt(c)]<<10|ir[t.charCodeAt(c+1)]<<4|ir[t.charCodeAt(c+2)]>>2,i[o++]=e>>8&255,i[o++]=e&255),i}function sk(t){return Wr[t>>18&63]+Wr[t>>12&63]+Wr[t>>6&63]+Wr[t&63]}function ik(t,e,r){for(var n,s=[],i=e;i<r;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(sk(n));return s.join("")}function ok(t){for(var e,r=t.length,n=r%3,s=[],i=16383,o=0,a=r-n;o<a;o+=i)s.push(ik(t,o,o+i>a?a:o+i));return n===1?(e=t[r-1],s.push(Wr[e>>2]+Wr[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],s.push(Wr[e>>10]+Wr[e>>4&63]+Wr[e<<2&63]+"=")),s.join("")}var Ih={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Ih.read=function(t,e,r,n,s){var i,o,a=s*8-n-1,c=(1<<a)-1,u=c>>1,f=-7,l=r?s-1:0,p=r?-1:1,d=t[e+l];for(l+=p,i=d&(1<<-f)-1,d>>=-f,f+=a;f>0;i=i*256+t[e+l],l+=p,f-=8);for(o=i&(1<<-f)-1,i>>=-f,f+=n;f>0;o=o*256+t[e+l],l+=p,f-=8);if(i===0)i=1-u;else{if(i===c)return o?NaN:(d?-1:1)*(1/0);o=o+Math.pow(2,n),i=i-u}return(d?-1:1)*o*Math.pow(2,i-n)};Ih.write=function(t,e,r,n,s,i){var o,a,c,u=i*8-s-1,f=(1<<u)-1,l=f>>1,p=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,m=n?1:-1,b=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=f):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+l>=1?e+=p/c:e+=p*Math.pow(2,1-l),e*c>=2&&(o++,c/=2),o+l>=f?(a=0,o=f):o+l>=1?(a=(e*c-1)*Math.pow(2,s),o=o+l):(a=e*Math.pow(2,l-1)*Math.pow(2,s),o=0));s>=8;t[r+d]=a&255,d+=m,a/=256,s-=8);for(o=o<<s|a,u+=s;u>0;t[r+d]=o&255,d+=m,o/=256,u-=8);t[r+d-m]|=b*128};/*!
|
|
36
|
+
`)})}}Object.defineProperty(Ms,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class No extends Dt{constructor(e){super(e,{code:No.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(No,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class Uo extends Dt{constructor(e){super(e,{code:Uo.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(Uo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class Mo extends Dt{constructor(e){super(e,{code:Mo.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(Mo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class vs extends Dt{constructor(e,{method:r}={}){super(e,{code:vs.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}}Object.defineProperty(vs,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class Ci extends Dt{constructor(e){super(e,{code:Ci.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(Ci,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class Fo extends Dt{constructor(e){super(e,{code:Fo.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(Fo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Ei extends Qt{constructor(e){super(e,{code:Ei.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Ei,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class jo extends Qt{constructor(e){super(e,{code:jo.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(jo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class Lo extends Qt{constructor(e,{method:r}={}){super(e,{code:Lo.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}}Object.defineProperty(Lo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Do extends Qt{constructor(e){super(e,{code:Do.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Do,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class Ho extends Qt{constructor(e){super(e,{code:Ho.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Ho,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class zo extends Qt{constructor(e){super(e,{code:zo.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(zo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class $i extends Qt{constructor(e){super(e,{code:$i.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty($i,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class Vo extends Qt{constructor(e){super(e,{code:Vo.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(Vo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class qo extends Qt{constructor(e){super(e,{code:qo.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(qo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class Go extends Qt{constructor(e){super(e,{code:Go.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(Go,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class Wo extends Qt{constructor(e){super(e,{code:Wo.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(Wo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class Ko extends Qt{constructor(e){super(e,{code:Ko.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(Ko,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class Ri extends Qt{constructor(e){super(e,{code:Ri.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(Ri,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class F5 extends Dt{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const j5=3;function Fs(t,{abi:e,address:r,args:n,docsPath:s,functionName:i,sender:o}){const a=t instanceof Lc?t:t instanceof L?t.walk(m=>"data"in m)||t.walk():{},{code:c,data:u,details:f,message:l,shortMessage:p}=a,d=t instanceof la?new N5({functionName:i}):[j5,Us.code].includes(c)&&(u||f||l||p)?new Bl({abi:e,data:typeof u=="object"?u.data:u,functionName:i,message:a instanceof Vd?f:p??l}):t;return new hb(d,{abi:e,args:n,contractAddress:r,docsPath:s,functionName:i,sender:o})}function L5(t){const e=ht(`0x${t.substring(4)}`).substring(26);return da(`0x${e}`)}async function D5({hash:t,signature:e}){const r=Pr(t)?t:Bt(t),{secp256k1:n}=await Promise.resolve().then(()=>n3);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:f,v:l,yParity:p}=e,d=Number(p??l),m=Op(d);return new n.Signature(ut(u),ut(f)).addRecoveryBit(m)}const o=Pr(e)?e:Bt(e);if(He(o)!==65)throw new Error("invalid signature length");const a=dr(`0x${o.slice(130)}`),c=Op(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Op(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function pb({hash:t,signature:e}){return L5(await D5({hash:t,signature:e}))}function as(t,e="hex"){const r=yb(t),n=Hd(new Uint8Array(r.length));return r.encode(n),e==="hex"?et(n.bytes):n.bytes}function yb(t){return Array.isArray(t)?H5(t.map(e=>yb(e))):z5(t)}function H5(t){const e=t.reduce((s,i)=>s+i.length,0),r=mb(e);return{length:e<=55?1+e:1+r+e,encode(s){e<=55?s.pushByte(192+e):(s.pushByte(247+r),r===1?s.pushUint8(e):r===2?s.pushUint16(e):r===3?s.pushUint24(e):s.pushUint32(e));for(const{encode:i}of t)i(s)}}}function z5(t){const e=typeof t=="string"?Jr(t):t,r=mb(e.length);return{length:e.length===1&&e[0]<128?1:e.length<=55?1+e.length:1+r+e.length,encode(s){e.length===1&&e[0]<128?s.pushBytes(e):e.length<=55?(s.pushByte(128+e.length),s.pushBytes(e)):(s.pushByte(183+r),r===1?s.pushUint8(e.length):r===2?s.pushUint16(e.length):r===3?s.pushUint24(e.length):s.pushUint32(e.length),s.pushBytes(e))}}}function mb(t){if(t<2**8)return 1;if(t<2**16)return 2;if(t<2**24)return 3;if(t<2**32)return 4;throw new L("Length is too large.")}function V5(t){const{chainId:e,nonce:r,to:n}=t,s=t.contractAddress??t.address,i=ht($r(["0x05",as([e?Z(e):"0x",s,r?Z(r):"0x"])]));return n==="bytes"?Jr(i):i}async function qd(t){const{authorization:e,signature:r}=t;return pb({hash:V5(e),signature:r??e})}class q5 extends L{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:f,to:l,value:p}){var m;const d=ma({from:r==null?void 0:r.address,to:l,value:typeof p<"u"&&`${zd(p)} ${((m=s==null?void 0:s.nativeCurrency)==null?void 0:m.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${jt(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${jt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${jt(u)} gwei`,nonce:f});super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",d].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class mi extends L{constructor({cause:e,message:r}={}){var s;const n=(s=r==null?void 0:r.replace("execution reverted: ",""))==null?void 0:s.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(mi,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(mi,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});class js extends L{constructor({cause:e,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${jt(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(js,"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 Cl extends L{constructor({cause:e,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${jt(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}}Object.defineProperty(Cl,"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 $l extends L{constructor({cause:e,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:e,name:"NonceTooHighError"})}}Object.defineProperty($l,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class Rl extends L{constructor({cause:e,nonce:r}={}){super([`Nonce provided for the transaction ${r?`(${r}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
|
|
37
|
+
`),{cause:e,name:"NonceTooLowError"})}}Object.defineProperty(Rl,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class Nl extends L{constructor({cause:e,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:e,name:"NonceMaxValueError"})}}Object.defineProperty(Nl,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class Ul extends L{constructor({cause:e}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
|
|
38
|
+
`),{cause:e,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}}Object.defineProperty(Ul,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class Ml extends L{constructor({cause:e,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:e,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(Ml,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class Fl extends L{constructor({cause:e,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction is too low.`,{cause:e,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(Fl,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class jl extends L{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(jl,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class Zo extends L{constructor({cause:e,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${jt(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${jt(n)} gwei`:""}).`].join(`
|
|
39
|
+
`),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(Zo,"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 ba extends L{constructor({cause:e}){super(`An error occurred while executing: ${e==null?void 0:e.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}function Dc(t,e){const r=(t.details||"").toLowerCase(),n=t instanceof L?t.walk(s=>(s==null?void 0:s.code)===mi.code):t;return n instanceof L?new mi({cause:t,message:n.details}):mi.nodeMessage.test(r)?new mi({cause:t,message:t.details}):js.nodeMessage.test(r)?new js({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas}):Cl.nodeMessage.test(r)?new Cl({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas}):$l.nodeMessage.test(r)?new $l({cause:t,nonce:e==null?void 0:e.nonce}):Rl.nodeMessage.test(r)?new Rl({cause:t,nonce:e==null?void 0:e.nonce}):Nl.nodeMessage.test(r)?new Nl({cause:t,nonce:e==null?void 0:e.nonce}):Ul.nodeMessage.test(r)?new Ul({cause:t}):Ml.nodeMessage.test(r)?new Ml({cause:t,gas:e==null?void 0:e.gas}):Fl.nodeMessage.test(r)?new Fl({cause:t,gas:e==null?void 0:e.gas}):jl.nodeMessage.test(r)?new jl({cause:t}):Zo.nodeMessage.test(r)?new Zo({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas,maxPriorityFeePerGas:e==null?void 0:e.maxPriorityFeePerGas}):new ba({cause:t})}function G5(t,{docsPath:e,...r}){const n=(()=>{const s=Dc(t,r);return s instanceof ba?t:s})();return new q5(n,{docsPath:e,...r})}function Hc(t,{format:e}){if(!e)return{};const r={};function n(i){const o=Object.keys(i);for(const a of o)a in t&&(r[a]=t[a]),i[a]&&typeof i[a]=="object"&&!Array.isArray(i[a])&&n(i[a])}const s=e(t||{});return n(s),r}function Gd(t,e){return({exclude:r,format:n})=>({exclude:r,format:s=>{const i=e(s);if(r)for(const o of r)delete i[o];return{...i,...n(s)}},type:t})}const W5={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function Vi(t){const e={};return typeof t.authorizationList<"u"&&(e.authorizationList=K5(t.authorizationList)),typeof t.accessList<"u"&&(e.accessList=t.accessList),typeof t.blobVersionedHashes<"u"&&(e.blobVersionedHashes=t.blobVersionedHashes),typeof t.blobs<"u"&&(typeof t.blobs[0]!="string"?e.blobs=t.blobs.map(r=>et(r)):e.blobs=t.blobs),typeof t.data<"u"&&(e.data=t.data),typeof t.from<"u"&&(e.from=t.from),typeof t.gas<"u"&&(e.gas=Z(t.gas)),typeof t.gasPrice<"u"&&(e.gasPrice=Z(t.gasPrice)),typeof t.maxFeePerBlobGas<"u"&&(e.maxFeePerBlobGas=Z(t.maxFeePerBlobGas)),typeof t.maxFeePerGas<"u"&&(e.maxFeePerGas=Z(t.maxFeePerGas)),typeof t.maxPriorityFeePerGas<"u"&&(e.maxPriorityFeePerGas=Z(t.maxPriorityFeePerGas)),typeof t.nonce<"u"&&(e.nonce=Z(t.nonce)),typeof t.to<"u"&&(e.to=t.to),typeof t.type<"u"&&(e.type=W5[t.type]),typeof t.value<"u"&&(e.value=Z(t.value)),e}function K5(t){return t.map(e=>({address:e.address,r:e.r?Z(BigInt(e.r)):e.r,s:e.s?Z(BigInt(e.s)):e.s,chainId:Z(e.chainId),nonce:Z(e.nonce),...typeof e.yParity<"u"?{yParity:Z(e.yParity)}:{},...typeof e.v<"u"&&typeof e.yParity>"u"?{v:Z(e.v)}:{}}))}function Bp(t){if(!(!t||t.length===0))return t.reduce((e,{slot:r,value:n})=>{if(r.length!==66)throw new gp({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new gp({size:n.length,targetSize:66,type:"hex"});return e[r]=n,e},{})}function Z5(t){const{balance:e,nonce:r,state:n,stateDiff:s,code:i}=t,o={};if(i!==void 0&&(o.code=i),e!==void 0&&(o.balance=Z(e)),r!==void 0&&(o.nonce=Z(r)),n!==void 0&&(o.state=Bp(n)),s!==void 0){if(o.state)throw new T5;o.stateDiff=Bp(s)}return o}function Wd(t){if(!t)return;const e={};for(const{address:r,...n}of t){if(!at(r,{strict:!1}))throw new $t({address:r});if(e[r])throw new k5({address:r});e[r]=Z5(n)}return e}const zc=2n**256n-1n;function Ys(t){const{account:e,gasPrice:r,maxFeePerGas:n,maxPriorityFeePerGas:s,to:i}=t,o=e?Ze(e):void 0;if(o&&!at(o.address))throw new $t({address:o.address});if(i&&!at(i))throw new $t({address:i});if(typeof r<"u"&&(typeof n<"u"||typeof s<"u"))throw new P5;if(n&&n>zc)throw new js({maxFeePerGas:n});if(s&&n&&s>n)throw new Zo({maxFeePerGas:n,maxPriorityFeePerGas:s})}class Y5 extends L{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class Kd extends L{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class X5 extends L{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${jt(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class bb extends L{constructor({blockHash:e,blockNumber:r}){let n="Block";e&&(n=`Block at hash "${e}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}const gb={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Vc(t){const e={...t,blockHash:t.blockHash?t.blockHash:null,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,chainId:t.chainId?dr(t.chainId):void 0,gas:t.gas?BigInt(t.gas):void 0,gasPrice:t.gasPrice?BigInt(t.gasPrice):void 0,maxFeePerBlobGas:t.maxFeePerBlobGas?BigInt(t.maxFeePerBlobGas):void 0,maxFeePerGas:t.maxFeePerGas?BigInt(t.maxFeePerGas):void 0,maxPriorityFeePerGas:t.maxPriorityFeePerGas?BigInt(t.maxPriorityFeePerGas):void 0,nonce:t.nonce?dr(t.nonce):void 0,to:t.to?t.to:null,transactionIndex:t.transactionIndex?Number(t.transactionIndex):null,type:t.type?gb[t.type]:void 0,typeHex:t.type?t.type:void 0,value:t.value?BigInt(t.value):void 0,v:t.v?BigInt(t.v):void 0};return t.authorizationList&&(e.authorizationList=Q5(t.authorizationList)),e.yParity=(()=>{if(t.yParity)return Number(t.yParity);if(typeof e.v=="bigint"){if(e.v===0n||e.v===27n)return 0;if(e.v===1n||e.v===28n)return 1;if(e.v>=35n)return e.v%2n===0n?1:0}})(),e.type==="legacy"&&(delete e.accessList,delete e.maxFeePerBlobGas,delete e.maxFeePerGas,delete e.maxPriorityFeePerGas,delete e.yParity),e.type==="eip2930"&&(delete e.maxFeePerBlobGas,delete e.maxFeePerGas,delete e.maxPriorityFeePerGas),e.type==="eip1559"&&delete e.maxFeePerBlobGas,e}const J5=Gd("transaction",Vc);function Q5(t){return t.map(e=>({address:e.address,chainId:Number(e.chainId),nonce:Number(e.nonce),r:e.r,s:e.s,yParity:Number(e.yParity)}))}function Zd(t){const e=(t.transactions??[]).map(r=>typeof r=="string"?r:Vc(r));return{...t,baseFeePerGas:t.baseFeePerGas?BigInt(t.baseFeePerGas):null,blobGasUsed:t.blobGasUsed?BigInt(t.blobGasUsed):void 0,difficulty:t.difficulty?BigInt(t.difficulty):void 0,excessBlobGas:t.excessBlobGas?BigInt(t.excessBlobGas):void 0,gasLimit:t.gasLimit?BigInt(t.gasLimit):void 0,gasUsed:t.gasUsed?BigInt(t.gasUsed):void 0,hash:t.hash?t.hash:null,logsBloom:t.logsBloom?t.logsBloom:null,nonce:t.nonce?t.nonce:null,number:t.number?BigInt(t.number):null,size:t.size?BigInt(t.size):void 0,timestamp:t.timestamp?BigInt(t.timestamp):void 0,transactions:e,totalDifficulty:t.totalDifficulty?BigInt(t.totalDifficulty):null}}const eE=Gd("block",Zd);async function Zr(t,{blockHash:e,blockNumber:r,blockTag:n=t.experimental_blockTag??"latest",includeTransactions:s}={}){var u,f,l;const i=s??!1,o=r!==void 0?Z(r):void 0;let a=null;if(e?a=await t.request({method:"eth_getBlockByHash",params:[e,i]},{dedupe:!0}):a=await t.request({method:"eth_getBlockByNumber",params:[o||n,i]},{dedupe:!!o}),!a)throw new bb({blockHash:e,blockNumber:r});return(((l=(f=(u=t.chain)==null?void 0:u.formatters)==null?void 0:f.block)==null?void 0:l.format)||Zd)(a)}async function Yd(t){const e=await t.request({method:"eth_gasPrice"});return BigInt(e)}async function tE(t,e){return wb(t,e)}async function wb(t,e){var i,o;const{block:r,chain:n=t.chain,request:s}=e||{};try{const a=((i=n==null?void 0:n.fees)==null?void 0:i.maxPriorityFeePerGas)??((o=n==null?void 0:n.fees)==null?void 0:o.defaultPriorityFee);if(typeof a=="function"){const u=r||await se(t,Zr,"getBlock")({}),f=await a({block:u,client:t,request:s});if(f===null)throw new Error;return f}if(typeof a<"u")return a;const c=await t.request({method:"eth_maxPriorityFeePerGas"});return ut(c)}catch{const[a,c]=await Promise.all([r?Promise.resolve(r):se(t,Zr,"getBlock")({}),se(t,Yd,"getGasPrice")({})]);if(typeof a.baseFeePerGas!="bigint")throw new Kd;const u=c-a.baseFeePerGas;return u<0n?0n:u}}async function rE(t,e){return Ll(t,e)}async function Ll(t,e){var p,d;const{block:r,chain:n=t.chain,request:s,type:i="eip1559"}=e||{},o=await(async()=>{var m,b;return typeof((m=n==null?void 0:n.fees)==null?void 0:m.baseFeeMultiplier)=="function"?n.fees.baseFeeMultiplier({block:r,client:t,request:s}):((b=n==null?void 0:n.fees)==null?void 0:b.baseFeeMultiplier)??1.2})();if(o<1)throw new Y5;const c=10**(((p=o.toString().split(".")[1])==null?void 0:p.length)??0),u=m=>m*BigInt(Math.ceil(o*c))/BigInt(c),f=r||await se(t,Zr,"getBlock")({});if(typeof((d=n==null?void 0:n.fees)==null?void 0:d.estimateFeesPerGas)=="function"){const m=await n.fees.estimateFeesPerGas({block:r,client:t,multiply:u,request:s,type:i});if(m!==null)return m}if(i==="eip1559"){if(typeof f.baseFeePerGas!="bigint")throw new Kd;const m=typeof(s==null?void 0:s.maxPriorityFeePerGas)=="bigint"?s.maxPriorityFeePerGas:await wb(t,{block:f,chain:n,request:s}),b=u(f.baseFeePerGas);return{maxFeePerGas:(s==null?void 0:s.maxFeePerGas)??b+m,maxPriorityFeePerGas:m}}return{gasPrice:(s==null?void 0:s.gasPrice)??u(await se(t,Yd,"getGasPrice")({}))}}async function Xd(t,{address:e,blockTag:r="latest",blockNumber:n}){const s=await t.request({method:"eth_getTransactionCount",params:[e,typeof n=="bigint"?Z(n):r]},{dedupe:!!n});return dr(s)}function Jd(t){const{kzg:e}=t,r=t.to??(typeof t.blobs[0]=="string"?"hex":"bytes"),n=typeof t.blobs[0]=="string"?t.blobs.map(i=>Jr(i)):t.blobs,s=[];for(const i of n)s.push(Uint8Array.from(e.blobToKzgCommitment(i)));return r==="bytes"?s:s.map(i=>et(i))}function Qd(t){const{kzg:e}=t,r=t.to??(typeof t.blobs[0]=="string"?"hex":"bytes"),n=typeof t.blobs[0]=="string"?t.blobs.map(o=>Jr(o)):t.blobs,s=typeof t.commitments[0]=="string"?t.commitments.map(o=>Jr(o)):t.commitments,i=[];for(let o=0;o<n.length;o++){const a=n[o],c=s[o];i.push(Uint8Array.from(e.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map(o=>et(o))}function nE(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function sE(t,e,r){return t&e^~t&r}function iE(t,e,r){return t&e^t&r^e&r}let vb=class extends Rc{constructor(e,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Pu(this.buffer)}update(e){os(this),e=En(e),is(e);const{view:r,buffer:n,blockLen:s}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=Pu(e);for(;s<=i-o;o+=s)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){os(this),Nd(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:o}=this;r[o++]=128,Ir(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let l=o;l<s;l++)r[l]=0;nE(n,s-8,BigInt(this.length*8),i),this.process(n,0);const a=Pu(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:s,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=s,e.pos=a,s%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const Un=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Mn=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),oE=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]),Fn=new Uint32Array(64);let eh=class extends vb{constructor(e=32){super(64,e,8,!1),this.A=Un[0]|0,this.B=Un[1]|0,this.C=Un[2]|0,this.D=Un[3]|0,this.E=Un[4]|0,this.F=Un[5]|0,this.G=Un[6]|0,this.H=Un[7]|0}get(){const{A:e,B:r,C:n,D:s,E:i,F:o,G:a,H:c}=this;return[e,r,n,s,i,o,a,c]}set(e,r,n,s,i,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let l=0;l<16;l++,r+=4)Fn[l]=e.getUint32(r,!1);for(let l=16;l<64;l++){const p=Fn[l-15],d=Fn[l-2],m=Mr(p,7)^Mr(p,18)^p>>>3,b=Mr(d,17)^Mr(d,19)^d>>>10;Fn[l]=b+Fn[l-7]+m+Fn[l-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){const p=Mr(a,6)^Mr(a,11)^Mr(a,25),d=f+p+sE(a,c,u)+oE[l]+Fn[l]|0,b=(Mr(n,2)^Mr(n,13)^Mr(n,22))+iE(n,s,i)|0;f=u,u=c,c=a,a=o+d|0,o=i,i=s,s=n,n=d+b|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,s,i,o,a,c,u,f)}roundClean(){Ir(Fn)}destroy(){this.set(0,0,0,0,0,0,0,0),Ir(this.buffer)}},Eb=class extends eh{constructor(){super(28),this.A=Mn[0]|0,this.B=Mn[1]|0,this.C=Mn[2]|0,this.D=Mn[3]|0,this.E=Mn[4]|0,this.F=Mn[5]|0,this.G=Mn[6]|0,this.H=Mn[7]|0}};const Sb=Nc(()=>new eh),aE=Nc(()=>new Eb),cE=eh,Ab=Sb,uE=Eb,fE=aE,lE=Object.freeze(Object.defineProperty({__proto__:null,SHA224:uE,SHA256:cE,sha224:fE,sha256:Ab},Symbol.toStringTag,{value:"Module"}));function ho(t,e){const r=e||"hex",n=Ab(Pr(t,{strict:!1})?zi(t):t);return r==="bytes"?n:Bt(n)}function dE(t){const{commitment:e,version:r=1}=t,n=t.to??(typeof e=="string"?"hex":"bytes"),s=ho(e,"bytes");return s.set([r],0),n==="bytes"?s:et(s)}function xb(t){const{commitments:e,version:r}=t,n=t.to??(typeof e[0]=="string"?"hex":"bytes"),s=[];for(const i of e)s.push(dE({commitment:i,to:n,version:r}));return s}const Cp=6,kb=32,th=4096,Tb=kb*th,$p=Tb*Cp-1-1*th*Cp,_b=1;class hE extends L{constructor({maxSize:e,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class Pb extends L{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class pE extends L{constructor({hash:e,size:r}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class yE extends L{constructor({hash:e,version:r}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:[`Expected: ${_b}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function mE(t){const e=t.to??(typeof t.data=="string"?"hex":"bytes"),r=typeof t.data=="string"?Jr(t.data):t.data,n=He(r);if(!n)throw new Pb;if(n>$p)throw new hE({maxSize:$p,size:n});const s=[];let i=!0,o=0;for(;i;){const a=Hd(new Uint8Array(Tb));let c=0;for(;c<th;){const u=r.slice(o,o+(kb-1));if(a.pushByte(0),a.pushBytes(u),u.length<31){a.pushByte(128),i=!1;break}c++,o+=31}s.push(a)}return e==="bytes"?s.map(a=>a.bytes):s.map(a=>et(a.bytes))}function Ib(t){const{data:e,kzg:r,to:n}=t,s=t.blobs??mE({data:e,to:n}),i=t.commitments??Jd({blobs:s,kzg:r,to:n}),o=t.proofs??Qd({blobs:s,commitments:i,kzg:r,to:n}),a=[];for(let c=0;c<s.length;c++)a.push({blob:s[c],commitment:i[c],proof:o[c]});return a}function Ob(t){if(t.type)return t.type;if(typeof t.authorizationList<"u")return"eip7702";if(typeof t.blobs<"u"||typeof t.blobVersionedHashes<"u"||typeof t.maxFeePerBlobGas<"u"||typeof t.sidecars<"u")return"eip4844";if(typeof t.maxFeePerGas<"u"||typeof t.maxPriorityFeePerGas<"u")return"eip1559";if(typeof t.gasPrice<"u")return typeof t.accessList<"u"?"eip2930":"legacy";throw new O5({transaction:t})}async function qi(t){const e=await t.request({method:"eth_chainId"},{dedupe:!0});return dr(e)}const Bb=["blobVersionedHashes","chainId","fees","gas","nonce","type"],Rp=new Map;async function qc(t,e){const{account:r=t.account,blobs:n,chain:s,gas:i,kzg:o,nonce:a,nonceManager:c,parameters:u=Bb,type:f}=e,l=r&&Ze(r),p={...e,...l?{from:l==null?void 0:l.address}:{}};let d;async function m(){return d||(d=await se(t,Zr,"getBlock")({blockTag:"latest"}),d)}let b;async function E(){return b||(s?s.id:typeof e.chainId<"u"?e.chainId:(b=await se(t,qi,"getChainId")({}),b))}if(u.includes("nonce")&&typeof a>"u"&&l)if(c){const A=await E();p.nonce=await c.consume({address:l.address,chainId:A,client:t})}else p.nonce=await se(t,Xd,"getTransactionCount")({address:l.address,blockTag:"pending"});if((u.includes("blobVersionedHashes")||u.includes("sidecars"))&&n&&o){const A=Jd({blobs:n,kzg:o});if(u.includes("blobVersionedHashes")){const P=xb({commitments:A,to:"hex"});p.blobVersionedHashes=P}if(u.includes("sidecars")){const P=Qd({blobs:n,commitments:A,kzg:o}),S=Ib({blobs:n,commitments:A,proofs:P,to:"hex"});p.sidecars=S}}if(u.includes("chainId")&&(p.chainId=await E()),(u.includes("fees")||u.includes("type"))&&typeof f>"u")try{p.type=Ob(p)}catch{let A=Rp.get(t.uid);if(typeof A>"u"){const P=await m();A=typeof(P==null?void 0:P.baseFeePerGas)=="bigint",Rp.set(t.uid,A)}p.type=A?"eip1559":"legacy"}if(u.includes("fees"))if(p.type!=="legacy"&&p.type!=="eip2930"){if(typeof p.maxFeePerGas>"u"||typeof p.maxPriorityFeePerGas>"u"){const A=await m(),{maxFeePerGas:P,maxPriorityFeePerGas:S}=await Ll(t,{block:A,chain:s,request:p});if(typeof e.maxPriorityFeePerGas>"u"&&e.maxFeePerGas&&e.maxFeePerGas<S)throw new X5({maxPriorityFeePerGas:S});p.maxPriorityFeePerGas=S,p.maxFeePerGas=P}}else{if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")throw new Kd;if(typeof e.gasPrice>"u"){const A=await m(),{gasPrice:P}=await Ll(t,{block:A,chain:s,request:p,type:"legacy"});p.gasPrice=P}}return u.includes("gas")&&typeof i>"u"&&(p.gas=await se(t,rh,"estimateGas")({...p,account:l&&{address:l.address,type:"json-rpc"}})),Ys(p),delete p.parameters,p}async function rh(t,e){var s,i,o;const{account:r=t.account}=e,n=r?Ze(r):void 0;try{const{accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:f,blockNumber:l,blockTag:p,data:d,gas:m,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:S,value:w,stateOverride:k,...T}=await qc(t,{...e,parameters:(n==null?void 0:n.type)==="local"?void 0:["blobVersionedHashes"]}),N=(typeof l=="bigint"?Z(l):void 0)||p,$=Wd(k),D=await(async()=>{if(T.to)return T.to;if(c&&c.length>0)return await qd({authorization:c[0]}).catch(()=>{throw new L("`to` is required. Could not infer from `authorizationList`")})})();Ys(e);const M=(o=(i=(s=t.chain)==null?void 0:s.formatters)==null?void 0:i.transactionRequest)==null?void 0:o.format,G=(M||Vi)({...Hc(T,{format:M}),from:n==null?void 0:n.address,accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:f,data:d,gas:m,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:S,to:D,value:w});return BigInt(await t.request({method:"eth_estimateGas",params:$?[G,N??t.experimental_blockTag??"latest",$]:N?[G,N]:[G]}))}catch(a){throw G5(a,{...e,account:n,chain:t.chain})}}async function Cb(t,e){const{abi:r,address:n,args:s,functionName:i,dataSuffix:o,...a}=e,c=Jt({abi:r,args:s,functionName:i});try{return await se(t,rh,"estimateGas")({data:`${c}${o?o.replace("0x",""):""}`,to:n,...a})}catch(u){const f=a.account?Ze(a.account):void 0;throw Fs(u,{abi:r,address:n,args:s,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:f==null?void 0:f.address})}}function Gi(t,e){if(!at(t,{strict:!1}))throw new $t({address:t});if(!at(e,{strict:!1}))throw new $t({address:e});return t.toLowerCase()===e.toLowerCase()}const Np="/docs/contract/decodeEventLog";function nh(t){const{abi:e,data:r,strict:n,topics:s}=t,i=n??!0,[o,...a]=s;if(!o)throw new sv({docsPath:Np});const c=e.find(b=>b.type==="event"&&o===Uc(_r(b)));if(!(c&&"name"in c)||c.type!=="event")throw new $m(o,{docsPath:Np});const{name:u,inputs:f}=c,l=f==null?void 0:f.some(b=>!("name"in b&&b.name)),p=l?[]:{},d=f.map((b,E)=>[b,E]).filter(([b])=>"indexed"in b&&b.indexed);for(let b=0;b<d.length;b++){const[E,A]=d[b],P=a[b];if(!P)throw new $c({abiItem:c,param:E});p[l?A:E.name||A]=bE({param:E,value:P})}const m=f.filter(b=>!("indexed"in b&&b.indexed));if(m.length>0){if(r&&r!=="0x")try{const b=ya(m,r);if(b)if(l)for(let E=0;E<f.length;E++)p[E]=p[E]??b.shift();else for(let E=0;E<m.length;E++)p[m[E].name]=b[E]}catch(b){if(i)throw b instanceof Bm||b instanceof ob?new Po({abiItem:c,data:r,params:m,size:He(r)}):b}else if(i)throw new Po({abiItem:c,data:"0x",params:m,size:0})}return{eventName:u,args:Object.values(p).length>0?p:void 0}}function bE({param:t,value:e}){return t.type==="string"||t.type==="bytes"||t.type==="tuple"||t.type.match(/^(.*)\[(\d+)?\]$/)?e:(ya([t],e)||[])[0]}function sh(t){const{abi:e,args:r,logs:n,strict:s=!0}=t,i=(()=>{if(t.eventName)return Array.isArray(t.eventName)?t.eventName:[t.eventName]})();return n.map(o=>{var a;try{const c=e.find(f=>f.type==="event"&&o.topics[0]===Uc(f));if(!c)return null;const u=nh({...o,abi:[c],strict:s});return i&&!i.includes(u.eventName)||!gE({args:u.args,inputs:c.inputs,matchArgs:r})?null:{...u,...o}}catch(c){let u,f;if(c instanceof $m)return null;if(c instanceof Po||c instanceof $c){if(s)return null;u=c.abiItem.name,f=(a=c.abiItem.inputs)==null?void 0:a.some(l=>!("name"in l&&l.name))}return{...o,args:f?[]:{},eventName:u}}}).filter(Boolean)}function gE(t){const{args:e,inputs:r,matchArgs:n}=t;if(!n)return!0;if(!e)return!1;function s(i,o,a){try{return i.type==="address"?Gi(o,a):i.type==="string"||i.type==="bytes"?ht(zi(o))===a:o===a}catch{return!1}}return Array.isArray(e)&&Array.isArray(n)?n.every((i,o)=>{if(i==null)return!0;const a=r[o];return a?(Array.isArray(i)?i:[i]).some(u=>s(a,u,e[o])):!1}):typeof e=="object"&&!Array.isArray(e)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([i,o])=>{if(o==null)return!0;const a=r.find(u=>u.name===i);return a?(Array.isArray(o)?o:[o]).some(u=>s(a,u,e[i])):!1}):!1}function kn(t,{args:e,eventName:r}={}){return{...t,blockHash:t.blockHash?t.blockHash:null,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,logIndex:t.logIndex?Number(t.logIndex):null,transactionHash:t.transactionHash?t.transactionHash:null,transactionIndex:t.transactionIndex?Number(t.transactionIndex):null,...r?{args:e,eventName:r}:{}}}async function ih(t,{address:e,blockHash:r,fromBlock:n,toBlock:s,event:i,events:o,args:a,strict:c}={}){const u=c??!1,f=o??(i?[i]:void 0);let l=[];f&&(l=[f.flatMap(b=>pa({abi:[b],eventName:b.name,args:o?void 0:a}))],i&&(l=l[0]));let p;r?p=await t.request({method:"eth_getLogs",params:[{address:e,topics:l,blockHash:r}]}):p=await t.request({method:"eth_getLogs",params:[{address:e,topics:l,fromBlock:typeof n=="bigint"?Z(n):n,toBlock:typeof s=="bigint"?Z(s):s}]});const d=p.map(m=>kn(m));return f?sh({abi:f,args:a,logs:d,strict:u}):d}async function oh(t,e){const{abi:r,address:n,args:s,blockHash:i,eventName:o,fromBlock:a,toBlock:c,strict:u}=e,f=o?Zs({abi:r,name:o}):void 0,l=f?void 0:r.filter(p=>p.type==="event");return se(t,ih,"getLogs")({address:n,args:s,blockHash:i,event:f,events:l,fromBlock:a,toBlock:c,strict:u})}const Bu="/docs/contract/decodeFunctionResult";function Xs(t){const{abi:e,args:r,functionName:n,data:s}=t;let i=e[0];if(n){const a=Zs({abi:e,args:r,name:n});if(!a)throw new Oi(n,{docsPath:Bu});i=a}if(i.type!=="function")throw new Oi(void 0,{docsPath:Bu});if(!i.outputs)throw new Rm(i.name,{docsPath:Bu});const o=ya(i.outputs,s);if(o&&o.length>1)return o;if(o&&o.length===1)return o[0]}const wE="0.1.1";function vE(){return wE}let ve=class Dl extends Error{constructor(e,r={}){const n=(()=>{var c;if(r.cause instanceof Dl){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),s=r.cause instanceof Dl&&r.cause.docsPath||r.docsPath,o=`https://oxlib.sh${s??""}`,a=[e||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||s?["",n?`Details: ${n}`:void 0,s?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
|
|
40
|
+
`);super(a,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${vE()}`}),this.cause=r.cause,this.details=n,this.docs=o,this.docsPath=s,this.shortMessage=e}walk(e){return $b(this,e)}};function $b(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?$b(t.cause,e):e?null:t}function ga(t,e){if(bi(t)>e)throw new ME({givenSize:bi(t),maxSize:e})}const rn={zero:48,nine:57,A:65,F:70,a:97,f:102};function Up(t){if(t>=rn.zero&&t<=rn.nine)return t-rn.zero;if(t>=rn.A&&t<=rn.F)return t-(rn.A-10);if(t>=rn.a&&t<=rn.f)return t-(rn.a-10)}function EE(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;if(t.length>n)throw new FE({size:t.length,targetSize:n,type:"Bytes"});const s=new Uint8Array(n);for(let i=0;i<n;i++){const o=r==="right";s[o?i:n-i-1]=t[o?i:t.length-i-1]}return s}function Rb(t,e={}){const{dir:r="left"}=e;let n=t,s=0;for(let i=0;i<n.length-1&&n[r==="left"?i:n.length-i-1].toString()==="0";i++)s++;return n=r==="left"?n.slice(s):n.slice(0,n.length-s),n}function Gc(t,e){if(Zt(t)>e)throw new VE({givenSize:Zt(t),maxSize:e})}function SE(t,e){if(typeof e=="number"&&e>0&&e>Zt(t)-1)throw new zb({offset:e,position:"start",size:Zt(t)})}function AE(t,e,r){if(typeof e=="number"&&typeof r=="number"&&Zt(t)!==r-e)throw new zb({offset:r,position:"end",size:Zt(t)})}function Nb(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;const s=t.replace("0x","");if(s.length>n*2)throw new qE({size:Math.ceil(s.length/2),targetSize:n,type:"Hex"});return`0x${s[r==="right"?"padEnd":"padStart"](n*2,"0")}`}const xE="#__bigint";function Ub(t,e,r){return JSON.stringify(t,(n,s)=>typeof s=="bigint"?s.toString()+xE:s,r)}const kE=new TextDecoder,TE=new TextEncoder;function _E(t){return t instanceof Uint8Array?t:typeof t=="string"?Mb(t):PE(t)}function PE(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function Mb(t,e={}){const{size:r}=e;let n=t;r&&(Gc(t,r),n=Ds(t,r));let s=n.slice(2);s.length%2&&(s=`0${s}`);const i=s.length/2,o=new Uint8Array(i);for(let a=0,c=0;a<i;a++){const u=Up(s.charCodeAt(c++)),f=Up(s.charCodeAt(c++));if(u===void 0||f===void 0)throw new ve(`Invalid byte sequence ("${s[c-2]}${s[c-1]}" in "${s}").`);o[a]=u*16+f}return o}function IE(t,e={}){const{size:r}=e,n=TE.encode(t);return typeof r=="number"?(ga(n,r),OE(n,r)):n}function OE(t,e){return EE(t,{dir:"right",size:e})}function bi(t){return t.length}function BE(t,e,r,n={}){const{strict:s}=n;return t.slice(e,r)}function CE(t,e={}){const{size:r}=e;typeof r<"u"&&ga(t,r);const n=Br(t,e);return Lb(n,e)}function $E(t,e={}){const{size:r}=e;let n=t;if(typeof r<"u"&&(ga(n,r),n=Fb(n)),n.length>1||n[0]>1)throw new UE(n);return!!n[0]}function An(t,e={}){const{size:r}=e;typeof r<"u"&&ga(t,r);const n=Br(t,e);return Db(n,e)}function RE(t,e={}){const{size:r}=e;let n=t;return typeof r<"u"&&(ga(n,r),n=NE(n)),kE.decode(n)}function Fb(t){return Rb(t,{dir:"left"})}function NE(t){return Rb(t,{dir:"right"})}class UE extends ve{constructor(e){super(`Bytes value \`${e}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"})}}let ME=class extends ve{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},FE=class extends ve{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}};const jE=new TextEncoder,LE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function DE(t,e={}){const{strict:r=!1}=e;if(!t)throw new Mp(t);if(typeof t!="string")throw new Mp(t);if(r&&!/^0x[0-9a-fA-F]*$/.test(t))throw new Fp(t);if(!t.startsWith("0x"))throw new Fp(t)}function Or(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function HE(t){return t instanceof Uint8Array?Br(t):Array.isArray(t)?Br(new Uint8Array(t)):t}function jb(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(Gc(r,e.size),Ls(r,e.size)):r}function Br(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=LE[t[s]];const n=`0x${r}`;return typeof e.size=="number"?(Gc(n,e.size),Ds(n,e.size)):n}function It(t,e={}){const{signed:r,size:n}=e,s=BigInt(t);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<o){const u=typeof t=="bigint"?"n":"";throw new Hb({max:i?`${i}${u}`:void 0,min:`${o}${u}`,signed:r,size:n,value:`${t}${u}`})}const c=`0x${(r&&s<0?(1n<<BigInt(n*8))+BigInt(s):s).toString(16)}`;return n?Ls(c,n):c}function ah(t,e={}){return Br(jE.encode(t),e)}function Ls(t,e){return Nb(t,{dir:"left",size:e})}function Ds(t,e){return Nb(t,{dir:"right",size:e})}function Yr(t,e,r,n={}){const{strict:s}=n;SE(t,e);const i=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return s&&AE(i,e,r),i}function Zt(t){return Math.ceil((t.length-2)/2)}function Lb(t,e={}){const{signed:r}=e;e.size&&Gc(t,e.size);const n=BigInt(t);if(!r)return n;const s=(t.length-2)/2,i=(1n<<BigInt(s)*8n)-1n,o=i>>1n;return n<=o?n:n-i-1n}function Db(t,e={}){const{signed:r,size:n}=e;return Number(!r&&!n?t:Lb(t,e))}function zE(t,e={}){const{strict:r=!1}=e;try{return DE(t,{strict:r}),!0}catch{return!1}}class Hb extends ve{constructor({max:e,min:r,signed:n,size:s,value:i}){super(`Number \`${i}\` is not in safe${s?` ${s*8}-bit`:""}${n?" signed":" unsigned"} integer range ${e?`(\`${r}\` to \`${e}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class Mp extends ve{constructor(e){super(`Value \`${typeof e=="object"?Ub(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class Fp extends ve{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class VE extends ve{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class zb extends ve{constructor({offset:e,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class qE extends ve{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}function GE(t){return{address:t.address,amount:It(t.amount),index:It(t.index),validatorIndex:It(t.validatorIndex)}}function Vb(t){return{...typeof t.baseFeePerGas=="bigint"&&{baseFeePerGas:It(t.baseFeePerGas)},...typeof t.blobBaseFee=="bigint"&&{blobBaseFee:It(t.blobBaseFee)},...typeof t.feeRecipient=="string"&&{feeRecipient:t.feeRecipient},...typeof t.gasLimit=="bigint"&&{gasLimit:It(t.gasLimit)},...typeof t.number=="bigint"&&{number:It(t.number)},...typeof t.prevRandao=="bigint"&&{prevRandao:It(t.prevRandao)},...typeof t.time=="bigint"&&{time:It(t.time)},...t.withdrawals&&{withdrawals:t.withdrawals.map(GE)}}}const bc=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],Hl=[{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"}]}],qb=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],Gb=[...qb,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],WE=[...qb,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],jp=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],Lp=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],Wb=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],Dp=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],KE="0x82ad56cb",Kb="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",ZE="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",YE="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",ch="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033";class zl extends L{constructor({blockNumber:e,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...e&&n.blockCreated&&n.blockCreated>e?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${e}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class XE extends L{constructor({chain:e,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${e.id} – ${e.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${e.id} – ${e.name}`],name:"ChainMismatchError"})}}class JE extends L{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 Zb extends L{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class Wc extends L{constructor({chainId:e}){super(typeof e=="number"?`Chain ID "${e}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const Cu="/docs/contract/encodeDeployData";function Kc(t){const{abi:e,args:r,bytecode:n}=t;if(!r||r.length===0)return n;const s=e.find(o=>"type"in o&&o.type==="constructor");if(!s)throw new Q6({docsPath:Cu});if(!("inputs"in s))throw new yp({docsPath:Cu});if(!s.inputs||s.inputs.length===0)throw new yp({docsPath:Cu});const i=fs(s.inputs,r);return $r([n,i])}function Wi({blockNumber:t,chain:e,contract:r}){var s;const n=(s=e==null?void 0:e.contracts)==null?void 0:s[r];if(!n)throw new zl({chain:e,contract:{name:r}});if(t&&n.blockCreated&&n.blockCreated>t)throw new zl({blockNumber:t,chain:e,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function Yb(t,{docsPath:e,...r}){const n=(()=>{const s=Dc(t,r);return s instanceof ba?t:s})();return new db(n,{docsPath:e,...r})}function uh(){let t=()=>{},e=()=>{};return{promise:new Promise((n,s)=>{t=n,e=s}),resolve:t,reject:e}}const $u=new Map;function Xb({fn:t,id:e,shouldSplitBatch:r,wait:n=0,sort:s}){const i=async()=>{const f=c();o();const l=f.map(({args:p})=>p);l.length!==0&&t(l).then(p=>{s&&Array.isArray(p)&&p.sort(s);for(let d=0;d<f.length;d++){const{resolve:m}=f[d];m==null||m([p[d],p])}}).catch(p=>{for(let d=0;d<f.length;d++){const{reject:m}=f[d];m==null||m(p)}})},o=()=>$u.delete(e),a=()=>c().map(({args:f})=>f),c=()=>$u.get(e)||[],u=f=>$u.set(e,[...c(),f]);return{flush:o,async schedule(f){const{promise:l,resolve:p,reject:d}=uh();return(r==null?void 0:r([...a(),f]))&&i(),c().length>0?(u({args:f,resolve:p,reject:d}),l):(u({args:f,resolve:p,reject:d}),setTimeout(i,n),l)}}}async function wa(t,e){var G,Q,W,K;const{account:r=t.account,authorizationList:n,batch:s=!!((G=t.batch)!=null&&G.multicall),blockNumber:i,blockTag:o=t.experimental_blockTag??"latest",accessList:a,blobs:c,blockOverrides:u,code:f,data:l,factory:p,factoryData:d,gas:m,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:S,to:w,value:k,stateOverride:T,...B}=e,N=r?Ze(r):void 0;if(f&&(p||d))throw new L("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(f&&w)throw new L("Cannot provide both `code` & `to` as parameters.");const $=f&&l,D=p&&d&&w&&l,M=$||D,V=$?Jb({code:f,data:l}):D?tS({data:l,factory:p,factoryData:d,to:w}):l;try{Ys(e);const q=(typeof i=="bigint"?Z(i):void 0)||o,I=u?Vb(u):void 0,j=Wd(T),J=(K=(W=(Q=t.chain)==null?void 0:Q.formatters)==null?void 0:W.transactionRequest)==null?void 0:K.format,R=(J||Vi)({...Hc(B,{format:J}),from:N==null?void 0:N.address,accessList:a,authorizationList:n,blobs:c,data:V,gas:m,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:S,to:M?void 0:w,value:k});if(s&&QE({request:R})&&!j&&!I)try{return await eS(t,{...R,blockNumber:i,blockTag:o})}catch(ae){if(!(ae instanceof Zb)&&!(ae instanceof zl))throw ae}const F=(()=>{const ae=[R,q];return j&&I?[...ae,j,I]:j?[...ae,j]:I?[...ae,{},I]:ae})(),ne=await t.request({method:"eth_call",params:F});return ne==="0x"?{data:void 0}:{data:ne}}catch(re){const q=rS(re),{offchainLookup:I,offchainLookupSignature:j}=await Promise.resolve().then(()=>require("./ccip-p2JXyi8a.cjs"));if(t.ccipRead!==!1&&(q==null?void 0:q.slice(0,10))===j&&w)return{data:await I(t,{data:q,to:w})};throw M&&(q==null?void 0:q.slice(0,10))==="0x101bb98d"?new U5({factory:p}):Yb(re,{...e,account:N,chain:t.chain})}}function QE({request:t}){const{data:e,to:r,...n}=t;return!(!e||e.startsWith(KE)||!r||Object.values(n).filter(s=>typeof s<"u").length>0)}async function eS(t,e){var b;const{batchSize:r=1024,deployless:n=!1,wait:s=0}=typeof((b=t.batch)==null?void 0:b.multicall)=="object"?t.batch.multicall:{},{blockNumber:i,blockTag:o=t.experimental_blockTag??"latest",data:a,to:c}=e,u=(()=>{if(n)return null;if(e.multicallAddress)return e.multicallAddress;if(t.chain)return Wi({blockNumber:i,chain:t.chain,contract:"multicall3"});throw new Zb})(),l=(typeof i=="bigint"?Z(i):void 0)||o,{schedule:p}=Xb({id:`${t.uid}.${l}`,wait:s,shouldSplitBatch(E){return E.reduce((P,{data:S})=>P+(S.length-2),0)>r*2},fn:async E=>{const A=E.map(w=>({allowFailure:!0,callData:w.data,target:w.to})),P=Jt({abi:bc,args:[A],functionName:"aggregate3"}),S=await t.request({method:"eth_call",params:[{...u===null?{data:Jb({code:ch,data:P})}:{to:u,data:P}},l]});return Xs({abi:bc,args:[A],functionName:"aggregate3",data:S||"0x"})}}),[{returnData:d,success:m}]=await p({data:a,to:c});if(!m)throw new Lc({data:d});return d==="0x"?{data:void 0}:{data:d}}function Jb(t){const{code:e,data:r}=t;return Kc({abi:Pm(["constructor(bytes, bytes)"]),bytecode:Kb,args:[e,r]})}function tS(t){const{data:e,factory:r,factoryData:n,to:s}=t;return Kc({abi:Pm(["constructor(address, bytes, address, bytes)"]),bytecode:ZE,args:[s,e,r,n]})}function rS(t){var r;if(!(t instanceof L))return;const e=t.walk();return typeof(e==null?void 0:e.data)=="object"?(r=e.data)==null?void 0:r.data:e.data}async function hr(t,e){const{abi:r,address:n,args:s,functionName:i,...o}=e,a=Jt({abi:r,args:s,functionName:i});try{const{data:c}=await se(t,wa,"call")({...o,data:a,to:n});return Xs({abi:r,args:s,functionName:i,data:c||"0x"})}catch(c){throw Fs(c,{abi:r,address:n,args:s,docsPath:"/docs/contract/readContract",functionName:i})}}async function Qb(t,e){const{abi:r,address:n,args:s,dataSuffix:i,functionName:o,...a}=e,c=a.account?Ze(a.account):t.account,u=Jt({abi:r,args:s,functionName:o});try{const{data:f}=await se(t,wa,"call")({batch:!1,data:`${u}${i?i.replace("0x",""):""}`,to:n,...a,account:c}),l=Xs({abi:r,args:s,functionName:o,data:f||"0x"}),p=r.filter(d=>"name"in d&&d.name===e.functionName);return{result:l,request:{abi:p,address:n,args:s,dataSuffix:i,functionName:o,...a,account:c}}}catch(f){throw Fs(f,{abi:r,address:n,args:s,docsPath:"/docs/contract/simulateContract",functionName:o,sender:c==null?void 0:c.address})}}const Ru=new Map,Hp=new Map;let nS=0;function Tn(t,e,r){const n=++nS,s=()=>Ru.get(t)||[],i=()=>{const f=s();Ru.set(t,f.filter(l=>l.id!==n))},o=()=>{const f=s();if(!f.some(p=>p.id===n))return;const l=Hp.get(t);if(f.length===1&&l){const p=l();p instanceof Promise&&p.catch(()=>{})}i()},a=s();if(Ru.set(t,[...a,{id:n,fns:e}]),a&&a.length>0)return o;const c={};for(const f in e)c[f]=(...l)=>{var d,m;const p=s();if(p.length!==0)for(const b of p)(m=(d=b.fns)[f])==null||m.call(d,...l)};const u=r(c);return typeof u=="function"&&Hp.set(t,u),o}async function Vl(t){return new Promise(e=>setTimeout(e,t))}function Ki(t,{emitOnBegin:e,initialWaitTime:r,interval:n}){let s=!0;const i=()=>s=!1;return(async()=>{let a;e&&(a=await t({unpoll:i}));const c=await(r==null?void 0:r(a))??n;await Vl(c);const u=async()=>{s&&(await t({unpoll:i}),await Vl(n),u())};u()})(),i}const sS=new Map,iS=new Map;function oS(t){const e=(s,i)=>({clear:()=>i.delete(s),get:()=>i.get(s),set:o=>i.set(s,o)}),r=e(t,sS),n=e(t,iS);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function aS(t,{cacheKey:e,cacheTime:r=Number.POSITIVE_INFINITY}){const n=oS(e),s=n.response.get();if(s&&r>0&&Date.now()-s.created.getTime()<r)return s.data;let i=n.promise.get();i||(i=t(),n.promise.set(i));try{const o=await i;return n.response.set({created:new Date,data:o}),o}finally{n.promise.clear()}}const cS=t=>`blockNumber.${t}`;async function va(t,{cacheTime:e=t.cacheTime}={}){const r=await aS(()=>t.request({method:"eth_blockNumber"}),{cacheKey:cS(t.uid),cacheTime:e});return BigInt(r)}async function Zc(t,{filter:e}){const r="strict"in e&&e.strict,n=await e.request({method:"eth_getFilterChanges",params:[e.id]});if(typeof n[0]=="string")return n;const s=n.map(i=>kn(i));return!("abi"in e)||!e.abi?s:sh({abi:e.abi,logs:s,strict:r})}async function Yc(t,{filter:e}){return e.request({method:"eth_uninstallFilter",params:[e.id]})}function eg(t,e){const{abi:r,address:n,args:s,batch:i=!0,eventName:o,fromBlock:a,onError:c,onLogs:u,poll:f,pollingInterval:l=t.pollingInterval,strict:p}=e;return(typeof f<"u"?f:typeof a=="bigint"?!0:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")))?(()=>{const E=p??!1,A=Qe(["watchContractEvent",n,s,i,t.uid,o,l,E,a]);return Tn(A,{onLogs:u,onError:c},P=>{let S;a!==void 0&&(S=a-1n);let w,k=!1;const T=Ki(async()=>{var B;if(!k){try{w=await se(t,Dd,"createContractEventFilter")({abi:r,address:n,args:s,eventName:o,strict:E,fromBlock:a})}catch{}k=!0;return}try{let N;if(w)N=await se(t,Zc,"getFilterChanges")({filter:w});else{const $=await se(t,va,"getBlockNumber")({});S&&S<$?N=await se(t,oh,"getContractEvents")({abi:r,address:n,args:s,eventName:o,fromBlock:S+1n,toBlock:$,strict:E}):N=[],S=$}if(N.length===0)return;if(i)P.onLogs(N);else for(const $ of N)P.onLogs([$])}catch(N){w&&N instanceof Ms&&(k=!1),(B=P.onError)==null||B.call(P,N)}},{emitOnBegin:!0,interval:l});return async()=>{w&&await se(t,Yc,"uninstallFilter")({filter:w}),T()}})})():(()=>{const E=p??!1,A=Qe(["watchContractEvent",n,s,i,t.uid,o,l,E]);let P=!0,S=()=>P=!1;return Tn(A,{onLogs:u,onError:c},w=>((async()=>{try{const k=(()=>{if(t.transport.type==="fallback"){const N=t.transport.transports.find($=>$.config.type==="webSocket"||$.config.type==="ipc");return N?N.value:t.transport}return t.transport})(),T=o?pa({abi:r,eventName:o,args:s}):[],{unsubscribe:B}=await k.subscribe({params:["logs",{address:n,topics:T}],onData(N){var D;if(!P)return;const $=N.result;try{const{eventName:M,args:V}=nh({abi:r,data:$.data,topics:$.topics,strict:p}),G=kn($,{args:V,eventName:M});w.onLogs([G])}catch(M){let V,G;if(M instanceof Po||M instanceof $c){if(p)return;V=M.abiItem.name,G=(D=M.abiItem.inputs)==null?void 0:D.some(W=>!("name"in W&&W.name))}const Q=kn($,{args:G?[]:{},eventName:V});w.onLogs([Q])}},onError(N){var $;($=w.onError)==null||$.call(w,N)}});S=B,P||S()}catch(k){c==null||c(k)}})(),()=>S()))})()}class Js extends L{constructor({docsPath:e}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
|
|
42
|
+
`),{docsPath:e,docsSlug:"account",name:"AccountNotFoundError"})}}class nc extends L{constructor({docsPath:e,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:e,metaMessages:r,name:"AccountTypeNotSupportedError"})}}function tg({chain:t,currentChainId:e}){if(!t)throw new JE;if(e!==t.id)throw new XE({chain:t,currentChainId:e})}function rg(t,{docsPath:e,...r}){const n=(()=>{const s=Dc(t,r);return s instanceof ba?t:s})();return new C5(n,{docsPath:e,...r})}async function fh(t,{serializedTransaction:e}){return t.request({method:"eth_sendRawTransaction",params:[e]},{retryCount:0})}const Nu=new Mc(128);async function Xc(t,e){var P,S,w,k;const{account:r=t.account,chain:n=t.chain,accessList:s,authorizationList:i,blobs:o,data:a,gas:c,gasPrice:u,maxFeePerBlobGas:f,maxFeePerGas:l,maxPriorityFeePerGas:p,nonce:d,type:m,value:b,...E}=e;if(typeof r>"u")throw new Js({docsPath:"/docs/actions/wallet/sendTransaction"});const A=r?Ze(r):null;try{Ys(e);const T=await(async()=>{if(e.to)return e.to;if(e.to!==null&&i&&i.length>0)return await qd({authorization:i[0]}).catch(()=>{throw new L("`to` is required. Could not infer from `authorizationList`.")})})();if((A==null?void 0:A.type)==="json-rpc"||A===null){let B;n!==null&&(B=await se(t,qi,"getChainId")({}),tg({currentChainId:B,chain:n}));const N=(w=(S=(P=t.chain)==null?void 0:P.formatters)==null?void 0:S.transactionRequest)==null?void 0:w.format,D=(N||Vi)({...Hc(E,{format:N}),accessList:s,authorizationList:i,blobs:o,chainId:B,data:a,from:A==null?void 0:A.address,gas:c,gasPrice:u,maxFeePerBlobGas:f,maxFeePerGas:l,maxPriorityFeePerGas:p,nonce:d,to:T,type:m,value:b}),M=Nu.get(t.uid),V=M?"wallet_sendTransaction":"eth_sendTransaction";try{return await t.request({method:V,params:[D]},{retryCount:0})}catch(G){if(M===!1)throw G;const Q=G;if(Q.name==="InvalidInputRpcError"||Q.name==="InvalidParamsRpcError"||Q.name==="MethodNotFoundRpcError"||Q.name==="MethodNotSupportedRpcError")return await t.request({method:"wallet_sendTransaction",params:[D]},{retryCount:0}).then(W=>(Nu.set(t.uid,!0),W)).catch(W=>{const K=W;throw K.name==="MethodNotFoundRpcError"||K.name==="MethodNotSupportedRpcError"?(Nu.set(t.uid,!1),Q):K});throw Q}}if((A==null?void 0:A.type)==="local"){const B=await se(t,qc,"prepareTransactionRequest")({account:A,accessList:s,authorizationList:i,blobs:o,chain:n,data:a,gas:c,gasPrice:u,maxFeePerBlobGas:f,maxFeePerGas:l,maxPriorityFeePerGas:p,nonce:d,nonceManager:A.nonceManager,parameters:[...Bb,"sidecars"],type:m,value:b,...E,to:T}),N=(k=n==null?void 0:n.serializers)==null?void 0:k.transaction,$=await A.signTransaction(B,{serializer:N});return await se(t,fh,"sendRawTransaction")({serializedTransaction:$})}throw(A==null?void 0:A.type)==="smart"?new nc({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new nc({docsPath:"/docs/actions/wallet/sendTransaction",type:A==null?void 0:A.type})}catch(T){throw T instanceof nc?T:rg(T,{...e,account:A,chain:e.chain||void 0})}}async function ng(t,e){const{abi:r,account:n=t.account,address:s,args:i,dataSuffix:o,functionName:a,...c}=e;if(typeof n>"u")throw new Js({docsPath:"/docs/contract/writeContract"});const u=n?Ze(n):null,f=Jt({abi:r,args:i,functionName:a});try{return await se(t,Xc,"sendTransaction")({data:`${f}${o?o.replace("0x",""):""}`,to:s,account:u,...c})}catch(l){throw Fs(l,{abi:r,address:s,args:i,docsPath:"/docs/contract/writeContract",functionName:a,sender:u==null?void 0:u.address})}}function zp({abi:t,address:e,client:r}){const n=r,[s,i]=n?"public"in n&&"wallet"in n?[n.public,n.wallet]:"public"in n?[n.public,void 0]:"wallet"in n?[void 0,n.wallet]:[n,n]:[void 0,void 0],o=s!=null,a=i!=null,c={};let u=!1,f=!1,l=!1;for(const p of t)if(p.type==="function"?p.stateMutability==="view"||p.stateMutability==="pure"?u=!0:f=!0:p.type==="event"&&(l=!0),u&&f&&l)break;return o&&(u&&(c.read=new Proxy({},{get(p,d){return(...m)=>{const{args:b,options:E}=Na(m);return se(s,hr,"readContract")({abi:t,address:e,functionName:d,args:b,...E})}}})),f&&(c.simulate=new Proxy({},{get(p,d){return(...m)=>{const{args:b,options:E}=Na(m);return se(s,Qb,"simulateContract")({abi:t,address:e,functionName:d,args:b,...E})}}})),l&&(c.createEventFilter=new Proxy({},{get(p,d){return(...m)=>{const b=t.find(P=>P.type==="event"&&P.name===d),{args:E,options:A}=Uu(m,b);return se(s,Dd,"createContractEventFilter")({abi:t,address:e,eventName:d,args:E,...A})}}}),c.getEvents=new Proxy({},{get(p,d){return(...m)=>{const b=t.find(P=>P.type==="event"&&P.name===d),{args:E,options:A}=Uu(m,b);return se(s,oh,"getContractEvents")({abi:t,address:e,eventName:d,args:E,...A})}}}),c.watchEvent=new Proxy({},{get(p,d){return(...m)=>{const b=t.find(P=>P.type==="event"&&P.name===d),{args:E,options:A}=Uu(m,b);return se(s,eg,"watchContractEvent")({abi:t,address:e,eventName:d,args:E,...A})}}}))),a&&f&&(c.write=new Proxy({},{get(p,d){return(...m)=>{const{args:b,options:E}=Na(m);return se(i,ng,"writeContract")({abi:t,address:e,functionName:d,args:b,...E})}}})),(o||a)&&f&&(c.estimateGas=new Proxy({},{get(p,d){return(...m)=>{const{args:b,options:E}=Na(m);return se(s??i,Cb,"estimateContractGas")({abi:t,address:e,functionName:d,args:b,...E,account:E.account??i.account})}}})),c.address=e,c.abi=t,c}function Na(t){const e=t.length&&Array.isArray(t[0]),r=e?t[0]:[],n=(e?t[1]:t[0])??{};return{args:r,options:n}}function Uu(t,e){let r=!1;Array.isArray(t[0])?r=!0:t.length===1?r=e.inputs.some(i=>i.indexed):t.length===2&&(r=!0);const n=r?t[0]:void 0,s=(r?t[1]:t[0])??{};return{args:n,options:s}}class uS extends L{constructor(e){super(`Call bundle failed with status: ${e.statusCode}`,{name:"BundleFailedError"}),Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=e}}function gc(t,{delay:e=100,retryCount:r=2,shouldRetry:n=()=>!0}={}){return new Promise((s,i)=>{const o=async({count:a=0}={})=>{const c=async({error:u})=>{const f=typeof e=="function"?e({count:a,error:u}):e;f&&await Vl(f),o({count:a+1})};try{const u=await t();s(u)}catch(u){if(a<r&&await n({count:a,error:u}))return c({error:u});i(u)}};o()})}const sg={"0x0":"reverted","0x1":"success"};function ig(t){const e={...t,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,contractAddress:t.contractAddress?t.contractAddress:null,cumulativeGasUsed:t.cumulativeGasUsed?BigInt(t.cumulativeGasUsed):null,effectiveGasPrice:t.effectiveGasPrice?BigInt(t.effectiveGasPrice):null,gasUsed:t.gasUsed?BigInt(t.gasUsed):null,logs:t.logs?t.logs.map(r=>kn(r)):null,to:t.to?t.to:null,transactionIndex:t.transactionIndex?dr(t.transactionIndex):null,status:t.status?sg[t.status]:null,type:t.type?gb[t.type]||t.type:null};return t.blobGasPrice&&(e.blobGasPrice=BigInt(t.blobGasPrice)),t.blobGasUsed&&(e.blobGasUsed=BigInt(t.blobGasUsed)),e}const fS=Gd("transactionReceipt",ig),og="0x5792579257925792579257925792579257925792579257925792579257925792",ag=Z(0,{size:32});async function lS(t,e){const{account:r=t.account,capabilities:n,chain:s=t.chain,experimental_fallback:i,experimental_fallbackDelay:o=32,forceAtomic:a=!1,id:c,version:u="2.0.0"}=e,f=r?Ze(r):null,l=e.calls.map(p=>{const d=p,m=d.abi?Jt({abi:d.abi,functionName:d.functionName,args:d.args}):d.data;return{data:d.dataSuffix&&m?Kt([m,d.dataSuffix]):m,to:d.to,value:d.value?Z(d.value):void 0}});try{const p=await t.request({method:"wallet_sendCalls",params:[{atomicRequired:a,calls:l,capabilities:n,chainId:Z(s.id),from:f==null?void 0:f.address,id:c,version:u}]},{retryCount:0});return typeof p=="string"?{id:p}:p}catch(p){const d=p;if(i&&(d.name==="MethodNotFoundRpcError"||d.name==="MethodNotSupportedRpcError"||d.name==="UnknownRpcError"||d.details.toLowerCase().includes("does not exist / is not available")||d.details.toLowerCase().includes("missing or invalid. request()")||d.details.toLowerCase().includes("did not match any variant of untagged enum")||d.details.toLowerCase().includes("account upgraded to unsupported contract")||d.details.toLowerCase().includes("eip-7702 not supported")||d.details.toLowerCase().includes("unsupported wc_ method")||d.details.toLowerCase().includes("feature toggled misconfigured"))){if(n&&Object.values(n).some(P=>!P.optional)){const P="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new $i(new L(P,{details:P}))}if(a&&l.length>1){const A="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new Ri(new L(A,{details:A}))}const m=[];for(const A of l){const P=Xc(t,{account:f,chain:s,data:A.data,to:A.to,value:A.value?ut(A.value):void 0});m.push(P),o>0&&await new Promise(S=>setTimeout(S,o))}const b=await Promise.allSettled(m);if(b.every(A=>A.status==="rejected"))throw b[0].reason;const E=b.map(A=>A.status==="fulfilled"?A.value:ag);return{id:Kt([...E,Z(s.id,{size:32}),og])}}throw rg(p,{...e,account:f,chain:e.chain})}}async function cg(t,e){async function r(f){if(f.endsWith(og.slice(2))){const p=lr(Pl(f,-64,-32)),d=Pl(f,0,-64).slice(2).match(/.{1,64}/g),m=await Promise.all(d.map(E=>ag.slice(2)!==E?t.request({method:"eth_getTransactionReceipt",params:[`0x${E}`]},{dedupe:!0}):void 0)),b=m.some(E=>E===null)?100:m.every(E=>(E==null?void 0:E.status)==="0x1")?200:m.every(E=>(E==null?void 0:E.status)==="0x0")?500:600;return{atomic:!1,chainId:dr(p),receipts:m.filter(Boolean),status:b,version:"2.0.0"}}return t.request({method:"wallet_getCallsStatus",params:[f]})}const{atomic:n=!1,chainId:s,receipts:i,version:o="2.0.0",...a}=await r(e.id),[c,u]=(()=>{const f=a.status;return f>=100&&f<200?["pending",f]:f>=200&&f<300?["success",f]:f>=300&&f<700?["failure",f]:f==="CONFIRMED"?["success",200]:f==="PENDING"?["pending",100]:[void 0,f]})();return{...a,atomic:n,chainId:s?dr(s):void 0,receipts:(i==null?void 0:i.map(f=>({...f,blockNumber:ut(f.blockNumber),gasUsed:ut(f.gasUsed),status:sg[f.status]})))??[],statusCode:u,status:c,version:o}}async function dS(t,e){const{id:r,pollingInterval:n=t.pollingInterval,status:s=({statusCode:b})=>b===200||b>=300,retryCount:i=4,retryDelay:o=({count:b})=>~~(1<<b)*200,timeout:a=6e4,throwOnFailure:c=!1}=e,u=Qe(["waitForCallsStatus",t.uid,r]),{promise:f,resolve:l,reject:p}=uh();let d;const m=Tn(u,{resolve:l,reject:p},b=>{const E=Ki(async()=>{const A=P=>{clearTimeout(d),E(),P(),m()};try{const P=await gc(async()=>{const S=await se(t,cg,"getCallsStatus")({id:r});if(c&&S.status==="failure")throw new uS(S);return S},{retryCount:i,delay:o});if(!s(P))return;A(()=>b.resolve(P))}catch(P){A(()=>b.reject(P))}},{interval:n,emitOnBegin:!0});return E});return d=a?setTimeout(()=>{m(),clearTimeout(d),p(new hS({id:r}))},a):void 0,await f}class hS extends L{constructor({id:e}){super(`Timed out while waiting for call bundle with id "${e}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}const ql=256;let Ua=ql,Ma;function ug(t=11){if(!Ma||Ua+t>ql*2){Ma="",Ua=0;for(let e=0;e<ql;e++)Ma+=(256+Math.random()*256|0).toString(16).substring(1)}return Ma.substring(Ua,Ua+++t)}function fg(t){const{batch:e,chain:r,ccipRead:n,key:s="base",name:i="Base Client",type:o="base"}=t,a=t.experimental_blockTag??(typeof(r==null?void 0:r.experimental_preconfirmationTime)=="number"?"pending":void 0),c=(r==null?void 0:r.blockTime)??12e3,u=Math.min(Math.max(Math.floor(c/2),500),4e3),f=t.pollingInterval??u,l=t.cacheTime??f,p=t.account?Ze(t.account):void 0,{config:d,request:m,value:b}=t.transport({chain:r,pollingInterval:f}),E={...d,...b},A={account:p,batch:e,cacheTime:l,ccipRead:n,chain:r,key:s,name:i,pollingInterval:f,request:m,transport:E,type:o,uid:ug(),...a?{experimental_blockTag:a}:{}};function P(S){return w=>{const k=w(S);for(const B in A)delete k[B];const T={...S,...k};return Object.assign(T,{extend:P(T)})}}return Object.assign(A,{extend:P(A)})}function lh(t){var r,n,s,i,o,a;if(!(t instanceof L))return!1;const e=t.walk(c=>c instanceof Bl);return e instanceof Bl?((r=e.data)==null?void 0:r.errorName)==="HttpError"||((n=e.data)==null?void 0:n.errorName)==="ResolverError"||((s=e.data)==null?void 0:s.errorName)==="ResolverNotContract"||((i=e.data)==null?void 0:i.errorName)==="ResolverNotFound"||((o=e.data)==null?void 0:o.errorName)==="ReverseAddressMismatch"||((a=e.data)==null?void 0:a.errorName)==="UnsupportedResolverProfile":!1}function pS(t){const{abi:e,data:r}=t,n=Ns(r,0,4),s=e.find(i=>i.type==="function"&&n===ha(_r(i)));if(!s)throw new iv(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:s.name,args:"inputs"in s&&s.inputs&&s.inputs.length>0?ya(s.inputs,Ns(r,4)):void 0}}const Mu="/docs/contract/encodeErrorResult";function Vp(t){const{abi:e,errorName:r,args:n}=t;let s=e[0];if(r){const c=Zs({abi:e,args:n,name:r});if(!c)throw new mp(r,{docsPath:Mu});s=c}if(s.type!=="error")throw new mp(void 0,{docsPath:Mu});const i=_r(s),o=ha(i);let a="0x";if(n&&n.length>0){if(!s.inputs)throw new nv(s.name,{docsPath:Mu});a=fs(s.inputs,n)}return $r([o,a])}const Fu="/docs/contract/encodeFunctionResult";function yS(t){const{abi:e,functionName:r,result:n}=t;let s=e[0];if(r){const o=Zs({abi:e,name:r});if(!o)throw new Oi(r,{docsPath:Fu});s=o}if(s.type!=="function")throw new Oi(void 0,{docsPath:Fu});if(!s.outputs)throw new Rm(s.name,{docsPath:Fu});const i=(()=>{if(s.outputs.length===0)return[];if(s.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new Nm(n)})();return fs(s.outputs,i)}const Ea="x-batch-gateway:true";async function lg(t){const{data:e,ccipRequest:r}=t,{args:[n]}=pS({abi:Hl,data:e}),s=[],i=[];return await Promise.all(n.map(async(o,a)=>{try{i[a]=o.urls.includes(Ea)?await lg({data:o.data,ccipRequest:r}):await r(o),s[a]=!1}catch(c){s[a]=!0,i[a]=mS(c)}})),yS({abi:Hl,functionName:"query",result:[s,i]})}function mS(t){return t.name==="HttpRequestError"&&t.status?Vp({abi:Hl,errorName:"HttpError",args:[t.status,t.shortMessage]}):Vp({abi:[ib],errorName:"Error",args:["shortMessage"in t?t.shortMessage:t.message]})}function dg(t){if(t.length!==66||t.indexOf("[")!==0||t.indexOf("]")!==65)return null;const e=`0x${t.slice(1,65)}`;return Pr(e)?e:null}function Gl(t){let e=new Uint8Array(32).fill(0);if(!t)return et(e);const r=t.split(".");for(let n=r.length-1;n>=0;n-=1){const s=dg(r[n]),i=s?zi(s):ht(_s(r[n]),"bytes");e=ht(Kt([e,i]),"bytes")}return et(e)}function bS(t){return`[${t.slice(2)}]`}function gS(t){const e=new Uint8Array(32).fill(0);return t?dg(t)||ht(_s(t)):et(e)}function dh(t){const e=t.replace(/^\.|\.$/gm,"");if(e.length===0)return new Uint8Array(1);const r=new Uint8Array(_s(e).byteLength+2);let n=0;const s=e.split(".");for(let i=0;i<s.length;i++){let o=_s(s[i]);o.byteLength>255&&(o=_s(bS(gS(s[i])))),r[n]=o.length,r.set(o,n+1),n+=o.length+1}return r.byteLength!==n+1?r.slice(0,n+1):r}async function wS(t,e){const{blockNumber:r,blockTag:n,coinType:s,name:i,gatewayUrls:o,strict:a}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Wi({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),f=c==null?void 0:c.ensTlds;if(f&&!f.some(p=>i.endsWith(p)))return null;const l=s!=null?[Gl(i),BigInt(s)]:[Gl(i)];try{const p=Jt({abi:Lp,functionName:"addr",args:l}),d={address:u,abi:Gb,functionName:"resolveWithGateways",args:[Bt(dh(i)),p,o??[Ea]],blockNumber:r,blockTag:n},b=await se(t,hr,"readContract")(d);if(b[0]==="0x")return null;const E=Xs({abi:Lp,args:l,functionName:"addr",data:b[0]});return E==="0x"||lr(E)==="0x00"?null:E}catch(p){if(a)throw p;if(lh(p))return null;throw p}}class vS extends L{constructor({data:e}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(e)}`],name:"EnsAvatarInvalidMetadataError"})}}class ro extends L{constructor({reason:e}){super(`ENS NFT avatar URI is invalid. ${e}`,{name:"EnsAvatarInvalidNftUriError"})}}class hh extends L{constructor({uri:e}){super(`Unable to resolve ENS avatar URI "${e}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class ES extends L{constructor({namespace:e}){super(`ENS NFT avatar namespace "${e}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const SS=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,AS=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,xS=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,kS=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function TS(t){try{const e=await fetch(t,{method:"HEAD"});if(e.status===200){const r=e.headers.get("content-type");return r==null?void 0:r.startsWith("image/")}return!1}catch(e){return typeof e=="object"&&typeof e.response<"u"||!Object.hasOwn(globalThis,"Image")?!1:new Promise(r=>{const n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=t})}}function qp(t,e){return t?t.endsWith("/")?t.slice(0,-1):t:e}function hg({uri:t,gatewayUrls:e}){const r=xS.test(t);if(r)return{uri:t,isOnChain:!0,isEncoded:r};const n=qp(e==null?void 0:e.ipfs,"https://ipfs.io"),s=qp(e==null?void 0:e.arweave,"https://arweave.net"),i=t.match(SS),{protocol:o,subpath:a,target:c,subtarget:u=""}=(i==null?void 0:i.groups)||{},f=o==="ipns:/"||a==="ipns/",l=o==="ipfs:/"||a==="ipfs/"||AS.test(t);if(t.startsWith("http")&&!f&&!l){let d=t;return e!=null&&e.arweave&&(d=t.replace(/https:\/\/arweave.net/g,e==null?void 0:e.arweave)),{uri:d,isOnChain:!1,isEncoded:!1}}if((f||l)&&c)return{uri:`${n}/${f?"ipns":"ipfs"}/${c}${u}`,isOnChain:!1,isEncoded:!1};if(o==="ar:/"&&c)return{uri:`${s}/${c}${u||""}`,isOnChain:!1,isEncoded:!1};let p=t.replace(kS,"");if(p.startsWith("<svg")&&(p=`data:image/svg+xml;base64,${btoa(p)}`),p.startsWith("data:")||p.startsWith("{"))return{uri:p,isOnChain:!0,isEncoded:!1};throw new hh({uri:t})}function pg(t){if(typeof t!="object"||!("image"in t)&&!("image_url"in t)&&!("image_data"in t))throw new vS({data:t});return t.image||t.image_url||t.image_data}async function _S({gatewayUrls:t,uri:e}){try{const r=await fetch(e).then(s=>s.json());return await ph({gatewayUrls:t,uri:pg(r)})}catch{throw new hh({uri:e})}}async function ph({gatewayUrls:t,uri:e}){const{uri:r,isOnChain:n}=hg({uri:e,gatewayUrls:t});if(n||await TS(r))return r;throw new hh({uri:e})}function PS(t){let e=t;e.startsWith("did:nft:")&&(e=e.replace("did:nft:","").replace(/_/g,"/"));const[r,n,s]=e.split("/"),[i,o]=r.split(":"),[a,c]=n.split(":");if(!i||i.toLowerCase()!=="eip155")throw new ro({reason:"Only EIP-155 supported"});if(!o)throw new ro({reason:"Chain ID not found"});if(!c)throw new ro({reason:"Contract address not found"});if(!s)throw new ro({reason:"Token ID not found"});if(!a)throw new ro({reason:"ERC namespace not found"});return{chainID:Number.parseInt(o,10),namespace:a.toLowerCase(),contractAddress:c,tokenID:s}}async function IS(t,{nft:e}){if(e.namespace==="erc721")return hr(t,{address:e.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(e.tokenID)]});if(e.namespace==="erc1155")return hr(t,{address:e.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(e.tokenID)]});throw new ES({namespace:e.namespace})}async function OS(t,{gatewayUrls:e,record:r}){return/eip155:/i.test(r)?BS(t,{gatewayUrls:e,record:r}):ph({uri:r,gatewayUrls:e})}async function BS(t,{gatewayUrls:e,record:r}){const n=PS(r),s=await IS(t,{nft:n}),{uri:i,isOnChain:o,isEncoded:a}=hg({uri:s,gatewayUrls:e});if(o&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){const u=a?atob(i.replace("data:application/json;base64,","")):i,f=JSON.parse(u);return ph({uri:pg(f),gatewayUrls:e})}let c=n.tokenID;return n.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),_S({gatewayUrls:e,uri:i.replace(/(?:0x)?{id}/,c)})}async function yg(t,e){const{blockNumber:r,blockTag:n,key:s,name:i,gatewayUrls:o,strict:a}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Wi({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),f=c==null?void 0:c.ensTlds;if(f&&!f.some(l=>i.endsWith(l)))return null;try{const l={address:u,abi:Gb,args:[Bt(dh(i)),Jt({abi:jp,functionName:"text",args:[Gl(i),s]}),o??[Ea]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},d=await se(t,hr,"readContract")(l);if(d[0]==="0x")return null;const m=Xs({abi:jp,functionName:"text",data:d[0]});return m===""?null:m}catch(l){if(a)throw l;if(lh(l))return null;throw l}}async function CS(t,{blockNumber:e,blockTag:r,assetGatewayUrls:n,name:s,gatewayUrls:i,strict:o,universalResolverAddress:a}){const c=await se(t,yg,"getEnsText")({blockNumber:e,blockTag:r,key:"avatar",name:s,universalResolverAddress:a,gatewayUrls:i,strict:o});if(!c)return null;try{return await OS(t,{record:c,gatewayUrls:n})}catch{return null}}async function $S(t,e){const{address:r,blockNumber:n,blockTag:s,coinType:i=60n,gatewayUrls:o,strict:a}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Wi({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{const f={address:u,abi:WE,args:[r,i,o??[Ea]],functionName:"reverseWithGateways",blockNumber:n,blockTag:s},l=se(t,hr,"readContract"),[p]=await l(f);return p||null}catch(f){if(a)throw f;if(lh(f))return null;throw f}}async function RS(t,e){const{blockNumber:r,blockTag:n,name:s}=e,{chain:i}=t,o=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!i)throw new Error("client chain not configured. universalResolverAddress is required.");return Wi({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),a=i==null?void 0:i.ensTlds;if(a&&!a.some(u=>s.endsWith(u)))throw new Error(`${s} is not a valid ENS TLD (${a==null?void 0:a.join(", ")}) for chain "${i.name}" (id: ${i.id}).`);const[c]=await se(t,hr,"readContract")({address:o,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[Bt(dh(s))],blockNumber:r,blockTag:n});return c}async function mg(t,e){var E,A,P;const{account:r=t.account,blockNumber:n,blockTag:s="latest",blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:f,maxPriorityFeePerGas:l,to:p,value:d,...m}=e,b=r?Ze(r):void 0;try{Ys(e);const w=(typeof n=="bigint"?Z(n):void 0)||s,k=(P=(A=(E=t.chain)==null?void 0:E.formatters)==null?void 0:A.transactionRequest)==null?void 0:P.format,B=(k||Vi)({...Hc(m,{format:k}),from:b==null?void 0:b.address,blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:f,maxPriorityFeePerGas:l,to:p,value:d}),N=await t.request({method:"eth_createAccessList",params:[B,w]});return{accessList:N.accessList,gasUsed:BigInt(N.gasUsed)}}catch(S){throw Yb(S,{...e,account:b,chain:t.chain})}}async function NS(t){const e=Fc(t,{method:"eth_newBlockFilter"}),r=await t.request({method:"eth_newBlockFilter"});return{id:r,request:e(r),type:"block"}}async function bg(t,{address:e,args:r,event:n,events:s,fromBlock:i,strict:o,toBlock:a}={}){const c=s??(n?[n]:void 0),u=Fc(t,{method:"eth_newFilter"});let f=[];c&&(f=[c.flatMap(d=>pa({abi:[d],eventName:d.name,args:r}))],n&&(f=f[0]));const l=await t.request({method:"eth_newFilter",params:[{address:e,fromBlock:typeof i=="bigint"?Z(i):i,toBlock:typeof a=="bigint"?Z(a):a,...f.length?{topics:f}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:i,id:l,request:u(l),strict:!!o,toBlock:a,type:"event"}}async function gg(t){const e=Fc(t,{method:"eth_newPendingTransactionFilter"}),r=await t.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:e(r),type:"transaction"}}async function US(t,{address:e,blockNumber:r,blockTag:n=t.experimental_blockTag??"latest"}){const s=typeof r=="bigint"?Z(r):void 0,i=await t.request({method:"eth_getBalance",params:[e,s||n]});return BigInt(i)}async function MS(t){const e=await t.request({method:"eth_blobBaseFee"});return BigInt(e)}async function FS(t,{blockHash:e,blockNumber:r,blockTag:n="latest"}={}){const s=r!==void 0?Z(r):void 0;let i;return e?i=await t.request({method:"eth_getBlockTransactionCountByHash",params:[e]},{dedupe:!0}):i=await t.request({method:"eth_getBlockTransactionCountByNumber",params:[s||n]},{dedupe:!!s}),dr(i)}async function Wl(t,{address:e,blockNumber:r,blockTag:n="latest"}){const s=r!==void 0?Z(r):void 0,i=await t.request({method:"eth_getCode",params:[e,s||n]},{dedupe:!!s});if(i!=="0x")return i}class jS extends L{constructor({address:e}){super(`No EIP-712 domain found on contract "${e}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${e}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function LS(t,e){const{address:r,factory:n,factoryData:s}=e;try{const[i,o,a,c,u,f,l]=await se(t,hr,"readContract")({abi:DS,address:r,functionName:"eip712Domain",factory:n,factoryData:s});return{domain:{name:o,version:a,chainId:Number(c),verifyingContract:u,salt:f},extensions:l,fields:i}}catch(i){const o=i;throw o.name==="ContractFunctionExecutionError"&&o.cause.name==="ContractFunctionZeroDataError"?new jS({address:r}):o}}const DS=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];function HS(t){var e;return{baseFeePerGas:t.baseFeePerGas.map(r=>BigInt(r)),gasUsedRatio:t.gasUsedRatio,oldestBlock:BigInt(t.oldestBlock),reward:(e=t.reward)==null?void 0:e.map(r=>r.map(n=>BigInt(n)))}}async function zS(t,{blockCount:e,blockNumber:r,blockTag:n="latest",rewardPercentiles:s}){const i=typeof r=="bigint"?Z(r):void 0,o=await t.request({method:"eth_feeHistory",params:[Z(e),i||n,s]},{dedupe:!!i});return HS(o)}async function VS(t,{filter:e}){const r=e.strict??!1,s=(await e.request({method:"eth_getFilterLogs",params:[e.id]})).map(i=>kn(i));return e.abi?sh({abi:e.abi,logs:s,strict:r}):s}function qS(t){const{authorizationList:e}=t;if(e)for(const r of e){const{chainId:n}=r,s=r.address;if(!at(s))throw new $t({address:s});if(n<0)throw new Wc({chainId:n})}yh(t)}function GS(t){const{blobVersionedHashes:e}=t;if(e){if(e.length===0)throw new Pb;for(const r of e){const n=He(r),s=dr(Ns(r,0,1));if(n!==32)throw new pE({hash:r,size:n});if(s!==_b)throw new yE({hash:r,version:s})}}yh(t)}function yh(t){const{chainId:e,maxPriorityFeePerGas:r,maxFeePerGas:n,to:s}=t;if(e<=0)throw new Wc({chainId:e});if(s&&!at(s))throw new $t({address:s});if(n&&n>zc)throw new js({maxFeePerGas:n});if(r&&n&&r>n)throw new Zo({maxFeePerGas:n,maxPriorityFeePerGas:r})}function WS(t){const{chainId:e,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=t;if(e<=0)throw new Wc({chainId:e});if(i&&!at(i))throw new $t({address:i});if(r||s)throw new L("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>zc)throw new js({maxFeePerGas:n})}function KS(t){const{chainId:e,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=t;if(i&&!at(i))throw new $t({address:i});if(typeof e<"u"&&e<=0)throw new Wc({chainId:e});if(r||s)throw new L("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>zc)throw new js({maxFeePerGas:n})}function Jc(t){if(!t||t.length===0)return[];const e=[];for(let r=0;r<t.length;r++){const{address:n,storageKeys:s}=t[r];for(let i=0;i<s.length;i++)if(s[i].length-2!==64)throw new B5({storageKey:s[i]});if(!at(n,{strict:!1}))throw new $t({address:n});e.push([n,s])}return e}function ZS(t,e){const r=Ob(t);return r==="eip1559"?JS(t,e):r==="eip2930"?QS(t,e):r==="eip4844"?XS(t,e):r==="eip7702"?YS(t,e):eA(t,e)}function YS(t,e){const{authorizationList:r,chainId:n,gas:s,nonce:i,to:o,value:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:f,data:l}=t;qS(t);const p=Jc(f),d=tA(r);return $r(["0x04",as([Z(n),i?Z(i):"0x",u?Z(u):"0x",c?Z(c):"0x",s?Z(s):"0x",o??"0x",a?Z(a):"0x",l??"0x",p,d,...Sa(t,e)])])}function XS(t,e){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:f,data:l}=t;GS(t);let p=t.blobVersionedHashes,d=t.sidecars;if(t.blobs&&(typeof p>"u"||typeof d>"u")){const S=typeof t.blobs[0]=="string"?t.blobs:t.blobs.map(T=>et(T)),w=t.kzg,k=Jd({blobs:S,kzg:w});if(typeof p>"u"&&(p=xb({commitments:k})),typeof d>"u"){const T=Qd({blobs:S,commitments:k,kzg:w});d=Ib({blobs:S,commitments:k,proofs:T})}}const m=Jc(f),b=[Z(r),s?Z(s):"0x",u?Z(u):"0x",c?Z(c):"0x",n?Z(n):"0x",i??"0x",o?Z(o):"0x",l??"0x",m,a?Z(a):"0x",p??[],...Sa(t,e)],E=[],A=[],P=[];if(d)for(let S=0;S<d.length;S++){const{blob:w,commitment:k,proof:T}=d[S];E.push(w),A.push(k),P.push(T)}return $r(["0x03",as(d?[b,E,A,P]:b)])}function JS(t,e){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:u,data:f}=t;yh(t);const l=Jc(u),p=[Z(r),s?Z(s):"0x",c?Z(c):"0x",a?Z(a):"0x",n?Z(n):"0x",i??"0x",o?Z(o):"0x",f??"0x",l,...Sa(t,e)];return $r(["0x02",as(p)])}function QS(t,e){const{chainId:r,gas:n,data:s,nonce:i,to:o,value:a,accessList:c,gasPrice:u}=t;WS(t);const f=Jc(c),l=[Z(r),i?Z(i):"0x",u?Z(u):"0x",n?Z(n):"0x",o??"0x",a?Z(a):"0x",s??"0x",f,...Sa(t,e)];return $r(["0x01",as(l)])}function eA(t,e){const{chainId:r=0,gas:n,data:s,nonce:i,to:o,value:a,gasPrice:c}=t;KS(t);let u=[i?Z(i):"0x",c?Z(c):"0x",n?Z(n):"0x",o??"0x",a?Z(a):"0x",s??"0x"];if(e){const f=(()=>{if(e.v>=35n)return(e.v-35n)/2n>0?e.v:27n+(e.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+e.v-27n);const d=27n+(e.v===27n?0n:1n);if(e.v!==d)throw new I5({v:e.v});return d})(),l=lr(e.r),p=lr(e.s);u=[...u,Z(f),l==="0x00"?"0x":l,p==="0x00"?"0x":p]}else r>0&&(u=[...u,Z(r),"0x","0x"]);return as(u)}function Sa(t,e){const r=e??t,{v:n,yParity:s}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof s>"u")return[];const i=lr(r.r),o=lr(r.s);return[typeof s=="number"?s?Z(1):"0x":n===0n?"0x":n===1n?Z(1):n===27n?"0x":Z(1),i==="0x00"?"0x":i,o==="0x00"?"0x":o]}function tA(t){if(!t||t.length===0)return[];const e=[];for(const r of t){const{chainId:n,nonce:s,...i}=r,o=r.address;e.push([n?Bt(n):"0x",o,s?Bt(s):"0x",...Sa({},i)])}return e}async function rA({address:t,authorization:e,signature:r}){return Gi(Md(t),await qd({authorization:e,signature:r}))}const Fa=new Mc(8192);function nA(t,{enabled:e=!0,id:r}){if(!e||!r)return t();if(Fa.get(r))return Fa.get(r);const n=t().finally(()=>Fa.delete(r));return Fa.set(r,n),n}function sA(t,e={}){return async(r,n={})=>{var l;const{dedupe:s=!1,methods:i,retryDelay:o=150,retryCount:a=3,uid:c}={...e,...n},{method:u}=r;if((l=i==null?void 0:i.exclude)!=null&&l.includes(u))throw new vs(new Error("method not supported"),{method:u});if(i!=null&&i.include&&!i.include.includes(u))throw new vs(new Error("method not supported"),{method:u});const f=s?Bi(`${c}.${Qe(r)}`):void 0;return nA(()=>gc(async()=>{try{return await t(r)}catch(p){const d=p;switch(d.code){case Bo.code:throw new Bo(d);case Co.code:throw new Co(d);case $o.code:throw new $o(d,{method:r.method});case Ro.code:throw new Ro(d);case Us.code:throw new Us(d);case Ms.code:throw new Ms(d);case No.code:throw new No(d);case Uo.code:throw new Uo(d);case Mo.code:throw new Mo(d);case vs.code:throw new vs(d,{method:r.method});case Ci.code:throw new Ci(d);case Fo.code:throw new Fo(d);case Ei.code:throw new Ei(d);case jo.code:throw new jo(d);case Lo.code:throw new Lo(d);case Do.code:throw new Do(d);case Ho.code:throw new Ho(d);case zo.code:throw new zo(d);case $i.code:throw new $i(d);case Vo.code:throw new Vo(d);case qo.code:throw new qo(d);case Go.code:throw new Go(d);case Wo.code:throw new Wo(d);case Ko.code:throw new Ko(d);case Ri.code:throw new Ri(d);case 5e3:throw new Ei(d);default:throw p instanceof L?p:new F5(d)}}},{delay:({count:p,error:d})=>{var m;if(d&&d instanceof vi){const b=(m=d==null?void 0:d.headers)==null?void 0:m.get("Retry-After");if(b!=null&&b.match(/\d/))return Number.parseInt(b,10)*1e3}return~~(1<<p)*o},retryCount:a,shouldRetry:({error:p})=>iA(p)}),{enabled:s,id:f})}}function iA(t){return"code"in t&&typeof t.code=="number"?t.code===-1||t.code===Ci.code||t.code===Us.code:t instanceof vi&&t.status?t.status===403||t.status===408||t.status===413||t.status===429||t.status===500||t.status===502||t.status===503||t.status===504:!0}function yt(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}const oA=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),wg=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),aA=wg.map(t=>(9*t+5)%16),vg=(()=>{const r=[[wg],[aA]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>oA[i]));return r})(),Eg=vg[0],Sg=vg[1],Ag=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),cA=Eg.map((t,e)=>t.map(r=>Ag[e][r])),uA=Sg.map((t,e)=>t.map(r=>Ag[e][r])),fA=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),lA=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Gp(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}const ja=new Uint32Array(16);let xg=class extends vb{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:r,h2:n,h3:s,h4:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=s|0,this.h4=i|0}process(e,r){for(let d=0;d<16;d++,r+=4)ja[d]=e.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,o=i,a=this.h2|0,c=a,u=this.h3|0,f=u,l=this.h4|0,p=l;for(let d=0;d<5;d++){const m=4-d,b=fA[d],E=lA[d],A=Eg[d],P=Sg[d],S=cA[d],w=uA[d];for(let k=0;k<16;k++){const T=Ra(n+Gp(d,i,a,u)+ja[A[k]]+b,S[k])+l|0;n=l,l=u,u=Ra(a,10)|0,a=i,i=T}for(let k=0;k<16;k++){const T=Ra(s+Gp(m,o,c,f)+ja[P[k]]+E,w[k])+p|0;s=p,p=f,f=Ra(c,10)|0,c=o,o=T}}this.set(this.h1+a+f|0,this.h2+u+p|0,this.h3+l+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){Ir(ja)}destroy(){this.destroyed=!0,Ir(this.buffer),this.set(0,0,0,0,0)}};const dA=Nc(()=>new xg),hA=xg,pA=dA,yA=Object.freeze(Object.defineProperty({__proto__:null,RIPEMD160:hA,ripemd160:pA},Symbol.toStringTag,{value:"Module"}));function mA(t,{errorInstance:e=new Error("timed out"),timeout:r,signal:n}){return new Promise((s,i)=>{(async()=>{let o;try{const a=new AbortController;r>0&&(o=setTimeout(()=>{n&&a.abort()},r)),s(await t({signal:(a==null?void 0:a.signal)||null}))}catch(a){(a==null?void 0:a.name)==="AbortError"&&i(e),i(a)}finally{clearTimeout(o)}})()})}function bA(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const Wp=bA();function gA(t,e={}){return{async request(r){var p;const{body:n,fetchFn:s=e.fetchFn??fetch,onRequest:i=e.onRequest,onResponse:o=e.onResponse,timeout:a=e.timeout??1e4}=r,c={...e.fetchOptions??{},...r.fetchOptions??{}},{headers:u,method:f,signal:l}=c;try{const d=await mA(async({signal:b})=>{const E={...c,body:Array.isArray(n)?Qe(n.map(w=>({jsonrpc:"2.0",id:w.id??Wp.take(),...w}))):Qe({jsonrpc:"2.0",id:n.id??Wp.take(),...n}),headers:{"Content-Type":"application/json",...u},method:f||"POST",signal:l||(a>0?b:null)},A=new Request(t,E),P=await(i==null?void 0:i(A,E))??{...E,url:t};return await s(P.url??t,P)},{errorInstance:new Ip({body:n,url:t}),timeout:a,signal:!0});o&&await o(d);let m;if((p=d.headers.get("Content-Type"))!=null&&p.startsWith("application/json"))m=await d.json();else{m=await d.text();try{m=JSON.parse(m||"{}")}catch(b){if(d.ok)throw b;m={error:m}}}if(!d.ok)throw new vi({body:n,details:Qe(m.error)||d.statusText,headers:d.headers,status:d.status,url:t});return m}catch(d){throw d instanceof vi||d instanceof Ip?d:new vi({body:n,cause:d,url:t})}}}}const wA=`Ethereum Signed Message:
|
|
43
|
+
`;function vA(t){const e=typeof t=="string"?Bi(t):typeof t.raw=="string"?t.raw:et(t.raw),r=Bi(`${wA}${He(e)}`);return Kt([r,e])}function kg(t,e){return ht(vA(t),e)}class EA extends L{constructor({domain:e}){super(`Invalid domain "${Qe(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class SA extends L{constructor({primaryType:e,types:r}){super(`Invalid primary type \`${e}\` must be one of \`${JSON.stringify(Object.keys(r))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class AA extends L{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function xA(t){const{domain:e,message:r,primaryType:n,types:s}=t,i=(c,u)=>{const f={...u};for(const l of c){const{name:p,type:d}=l;d==="address"&&(f[p]=f[p].toLowerCase())}return f},o=s.EIP712Domain?e?i(s.EIP712Domain,e):{}:{},a=(()=>{if(n!=="EIP712Domain")return i(s[n],r)})();return Qe({domain:o,message:a,primaryType:n,types:s})}function Tg(t){const{domain:e,message:r,primaryType:n,types:s}=t,i=(o,a)=>{for(const c of o){const{name:u,type:f}=c,l=a[u],p=f.match(nb);if(p&&(typeof l=="number"||typeof l=="bigint")){const[b,E,A]=p;Z(l,{signed:E==="int",size:Number.parseInt(A,10)/8})}if(f==="address"&&typeof l=="string"&&!at(l))throw new $t({address:l});const d=f.match(Qv);if(d){const[b,E]=d;if(E&&He(l)!==Number.parseInt(E,10))throw new av({expectedSize:Number.parseInt(E,10),givenSize:He(l)})}const m=s[f];m&&(kA(f),i(m,l))}};if(s.EIP712Domain&&e){if(typeof e!="object")throw new EA({domain:e});i(s.EIP712Domain,e)}if(n!=="EIP712Domain")if(s[n])i(s[n],r);else throw new SA({primaryType:n,types:s})}function _g({domain:t}){return[typeof(t==null?void 0:t.name)=="string"&&{name:"name",type:"string"},(t==null?void 0:t.version)&&{name:"version",type:"string"},(typeof(t==null?void 0:t.chainId)=="number"||typeof(t==null?void 0:t.chainId)=="bigint")&&{name:"chainId",type:"uint256"},(t==null?void 0:t.verifyingContract)&&{name:"verifyingContract",type:"address"},(t==null?void 0:t.salt)&&{name:"salt",type:"bytes32"}].filter(Boolean)}function kA(t){if(t==="address"||t==="bool"||t==="string"||t.startsWith("bytes")||t.startsWith("uint")||t.startsWith("int"))throw new AA({type:t})}function TA(t){const{domain:e={},message:r,primaryType:n}=t,s={EIP712Domain:_g({domain:e}),...t.types};Tg({domain:e,message:r,primaryType:n,types:s});const i=["0x1901"];return e&&i.push(_A({domain:e,types:s})),n!=="EIP712Domain"&&i.push(Pg({data:r,primaryType:n,types:s})),ht(Kt(i))}function _A({domain:t,types:e}){return Pg({data:t,primaryType:"EIP712Domain",types:e})}function Pg({data:t,primaryType:e,types:r}){const n=Ig({data:t,primaryType:e,types:r});return ht(n)}function Ig({data:t,primaryType:e,types:r}){const n=[{type:"bytes32"}],s=[PA({primaryType:e,types:r})];for(const i of r[e]){const[o,a]=Bg({types:r,name:i.name,type:i.type,value:t[i.name]});n.push(o),s.push(a)}return fs(n,s)}function PA({primaryType:t,types:e}){const r=Bt(IA({primaryType:t,types:e}));return ht(r)}function IA({primaryType:t,types:e}){let r="";const n=Og({primaryType:t,types:e});n.delete(t);const s=[t,...Array.from(n).sort()];for(const i of s)r+=`${i}(${e[i].map(({name:o,type:a})=>`${a} ${o}`).join(",")})`;return r}function Og({primaryType:t,types:e},r=new Set){const n=t.match(/^\w*/u),s=n==null?void 0:n[0];if(r.has(s)||e[s]===void 0)return r;r.add(s);for(const i of e[s])Og({primaryType:i.type,types:e},r);return r}function Bg({types:t,name:e,type:r,value:n}){if(t[r]!==void 0)return[{type:"bytes32"},ht(Ig({data:n,primaryType:r,types:t}))];if(r==="bytes")return n=`0x${(n.length%2?"0":"")+n.slice(2)}`,[{type:"bytes32"},ht(n)];if(r==="string")return[{type:"bytes32"},ht(Bt(n))];if(r.lastIndexOf("]")===r.length-1){const s=r.slice(0,r.lastIndexOf("[")),i=n.map(o=>Bg({name:e,type:s,types:t,value:o}));return[{type:"bytes32"},ht(fs(i.map(([o])=>o),i.map(([,o])=>o)))]}return[{type:r},n]}const OA="1.1.1";class pt extends Error{constructor(e,r={}){var o;const n=r.cause instanceof pt?r.cause.details:(o=r.cause)!=null&&o.message?r.cause.message:r.details,s=r.cause instanceof pt&&r.cause.docsPath||r.docsPath,i=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: https://abitype.dev${s}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${OA}`].join(`
|
|
44
|
+
`);super(i),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=s,this.metaMessages=r.metaMessages,this.shortMessage=e}}function $n(t,e){const r=t.exec(e);return r==null?void 0:r.groups}const Cg=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,$g=/^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)?$/,Rg=/^\(.+?\).*?$/,Kp=/^tuple(?<array>(\[(\d*)\])*)$/;function Kl(t){let e=t.type;if(Kp.test(t.type)&&"components"in t){e="(";const r=t.components.length;for(let s=0;s<r;s++){const i=t.components[s];e+=Kl(i),s<r-1&&(e+=", ")}const n=$n(Kp,t.type);return e+=`)${(n==null?void 0:n.array)??""}`,Kl({...t,type:e})}return"indexed"in t&&t.indexed&&(e=`${e} indexed`),t.name?`${e} ${t.name}`:e}function ci(t){let e="";const r=t.length;for(let n=0;n<r;n++){const s=t[n];e+=Kl(s),n!==r-1&&(e+=", ")}return e}function Zl(t){var e;return t.type==="function"?`function ${t.name}(${ci(t.inputs)})${t.stateMutability&&t.stateMutability!=="nonpayable"?` ${t.stateMutability}`:""}${(e=t.outputs)!=null&&e.length?` returns (${ci(t.outputs)})`:""}`:t.type==="event"?`event ${t.name}(${ci(t.inputs)})`:t.type==="error"?`error ${t.name}(${ci(t.inputs)})`:t.type==="constructor"?`constructor(${ci(t.inputs)})${t.stateMutability==="payable"?" payable":""}`:t.type==="fallback"?`fallback() external${t.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const Ng=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function BA(t){return Ng.test(t)}function CA(t){return $n(Ng,t)}const Ug=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function $A(t){return Ug.test(t)}function RA(t){return $n(Ug,t)}const Mg=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function NA(t){return Mg.test(t)}function UA(t){return $n(Mg,t)}const Fg=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function mh(t){return Fg.test(t)}function MA(t){return $n(Fg,t)}const jg=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function FA(t){return jg.test(t)}function jA(t){return $n(jg,t)}const Lg=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function LA(t){return Lg.test(t)}function DA(t){return $n(Lg,t)}const HA=/^receive\(\) external payable$/;function zA(t){return HA.test(t)}const Zp=new Set(["memory","indexed","storage","calldata"]),VA=new Set(["indexed"]),Yl=new Set(["calldata","memory","storage"]);class qA extends pt{constructor({signature:e}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}}class GA extends pt{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}}class WA extends pt{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}class KA extends pt{constructor({params:e}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}}class ZA extends pt{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}}class YA extends pt{constructor({param:e,name:r}){super("Invalid ABI parameter.",{details:e,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}}class XA extends pt{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}}class JA extends pt{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}}class QA extends pt{constructor({abiParameter:e}){super("Invalid ABI parameter.",{details:JSON.stringify(e,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}class Zi extends pt{constructor({signature:e,type:r}){super(`Invalid ${r} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}}class e8 extends pt{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}}class t8 extends pt{constructor({signature:e}){super("Invalid struct signature.",{details:e,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}class r8 extends pt{constructor({type:e}){super("Circular reference detected.",{metaMessages:[`Struct "${e}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}class n8 extends pt{constructor({current:e,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${e.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}function s8(t,e,r){let n="";if(r)for(const s of Object.entries(r)){if(!s)continue;let i="";for(const o of s[1])i+=`[${o.type}${o.name?`:${o.name}`:""}]`;n+=`(${s[0]}{${i}})`}return e?`${e}:${t}${n}`:t}const ju=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 Yp(t,e={}){if(NA(t))return i8(t,e);if($A(t))return o8(t,e);if(BA(t))return a8(t,e);if(FA(t))return c8(t,e);if(LA(t))return u8(t);if(zA(t))return{type:"receive",stateMutability:"payable"};throw new e8({signature:t})}function i8(t,e={}){const r=UA(t);if(!r)throw new Zi({signature:t,type:"function"});const n=qt(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push(_n(n[a],{modifiers:Yl,structs:e,type:"function"}));const o=[];if(r.returns){const a=qt(r.returns),c=a.length;for(let u=0;u<c;u++)o.push(_n(a[u],{modifiers:Yl,structs:e,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:s,outputs:o}}function o8(t,e={}){const r=RA(t);if(!r)throw new Zi({signature:t,type:"event"});const n=qt(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(_n(n[o],{modifiers:VA,structs:e,type:"event"}));return{name:r.name,type:"event",inputs:s}}function a8(t,e={}){const r=CA(t);if(!r)throw new Zi({signature:t,type:"error"});const n=qt(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(_n(n[o],{structs:e,type:"error"}));return{name:r.name,type:"error",inputs:s}}function c8(t,e={}){const r=jA(t);if(!r)throw new Zi({signature:t,type:"constructor"});const n=qt(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(_n(n[o],{structs:e,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:s}}function u8(t){const e=DA(t);if(!e)throw new Zi({signature:t,type:"fallback"});return{type:"fallback",stateMutability:e.stateMutability??"nonpayable"}}const f8=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,l8=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,d8=/^u?int$/;function _n(t,e){var l,p;const r=s8(t,e==null?void 0:e.type,e==null?void 0:e.structs);if(ju.has(r))return ju.get(r);const n=Rg.test(t),s=$n(n?l8:f8,t);if(!s)throw new ZA({param:t});if(s.name&&p8(s.name))throw new YA({param:t,name:s.name});const i=s.name?{name:s.name}:{},o=s.modifier==="indexed"?{indexed:!0}:{},a=(e==null?void 0:e.structs)??{};let c,u={};if(n){c="tuple";const d=qt(s.type),m=[],b=d.length;for(let E=0;E<b;E++)m.push(_n(d[E],{structs:a}));u={components:m}}else if(s.type in a)c="tuple",u={components:a[s.type]};else if(d8.test(s.type))c=`${s.type}256`;else if(s.type==="address payable")c="address";else if(c=s.type,(e==null?void 0:e.type)!=="struct"&&!Dg(c))throw new WA({type:c});if(s.modifier){if(!((p=(l=e==null?void 0:e.modifiers)==null?void 0:l.has)!=null&&p.call(l,s.modifier)))throw new XA({param:t,type:e==null?void 0:e.type,modifier:s.modifier});if(Yl.has(s.modifier)&&!y8(c,!!s.array))throw new JA({param:t,type:e==null?void 0:e.type,modifier:s.modifier})}const f={type:`${c}${s.array??""}`,...i,...o,...u};return ju.set(r,f),f}function qt(t,e=[],r="",n=0){const s=t.trim().length;for(let i=0;i<s;i++){const o=t[i],a=t.slice(i+1);switch(o){case",":return n===0?qt(a,[...e,r.trim()]):qt(a,e,`${r}${o}`,n);case"(":return qt(a,e,`${r}${o}`,n+1);case")":return qt(a,e,`${r}${o}`,n-1);default:return qt(a,e,`${r}${o}`,n)}}if(r==="")return e;if(n!==0)throw new n8({current:r,depth:n});return e.push(r.trim()),e}function Dg(t){return t==="address"||t==="bool"||t==="function"||t==="string"||Cg.test(t)||$g.test(t)}const h8=/^(?: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 p8(t){return t==="address"||t==="bool"||t==="function"||t==="string"||t==="tuple"||Cg.test(t)||$g.test(t)||h8.test(t)}function y8(t,e){return e||t==="bytes"||t==="string"||t==="tuple"}function Hg(t){const e={},r=t.length;for(let o=0;o<r;o++){const a=t[o];if(!mh(a))continue;const c=MA(a);if(!c)throw new Zi({signature:a,type:"struct"});const u=c.properties.split(";"),f=[],l=u.length;for(let p=0;p<l;p++){const m=u[p].trim();if(!m)continue;const b=_n(m,{type:"struct"});f.push(b)}if(!f.length)throw new t8({signature:a});e[c.name]=f}const n={},s=Object.entries(e),i=s.length;for(let o=0;o<i;o++){const[a,c]=s[o];n[a]=zg(c,e)}return n}const m8=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function zg(t,e,r=new Set){const n=[],s=t.length;for(let i=0;i<s;i++){const o=t[i];if(Rg.test(o.type))n.push(o);else{const c=$n(m8,o.type);if(!(c!=null&&c.type))throw new QA({abiParameter:o});const{array:u,type:f}=c;if(f in e){if(r.has(f))throw new r8({type:f});n.push({...o,type:`tuple${u??""}`,components:zg(e[f]??[],e,new Set([...r,f]))})}else if(Dg(f))n.push(o);else throw new GA({type:f})}}return n}function Xp(t){let e;if(typeof t=="string")e=Yp(t);else{const r=Hg(t),n=t.length;for(let s=0;s<n;s++){const i=t[s];if(!mh(i)){e=Yp(i,r);break}}}if(!e)throw new qA({signature:t});return e}function Jp(t){const e=[];if(typeof t=="string"){const r=qt(t),n=r.length;for(let s=0;s<n;s++)e.push(_n(r[s],{modifiers:Zp}))}else{const r=Hg(t),n=t.length;for(let s=0;s<n;s++){const i=t[s];if(mh(i))continue;const o=qt(i),a=o.length;for(let c=0;c<a;c++)e.push(_n(o[c],{modifiers:Zp,structs:r}))}}if(e.length===0)throw new KA({params:t});return e}class b8 extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const g8={checksum:new b8(8192)},Lu=g8.checksum;function Vg(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,n=Jm(_E(t));return r==="Bytes"?n:Br(n)}const w8=/^0x[a-fA-F0-9]{40}$/;function Qc(t,e={}){const{strict:r=!0}=e;if(!w8.test(t))throw new Qp({address:t,cause:new v8});if(r){if(t.toLowerCase()===t)return;if(qg(t)!==t)throw new Qp({address:t,cause:new E8})}}function qg(t){if(Lu.has(t))return Lu.get(t);Qc(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=Vg(IE(e),{as:"Bytes"}),n=e.split("");for(let i=0;i<40;i+=2)r[i>>1]>>4>=8&&n[i]&&(n[i]=n[i].toUpperCase()),(r[i>>1]&15)>=8&&n[i+1]&&(n[i+1]=n[i+1].toUpperCase());const s=`0x${n.join("")}`;return Lu.set(t,s),s}function Xl(t,e={}){const{strict:r=!0}=e??{};try{return Qc(t,{strict:r}),!0}catch{return!1}}class Qp extends ve{constructor({address:e,cause:r}){super(`Address "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class v8 extends ve{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class E8 extends ve{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const S8=/^(.*)\[([0-9]*)\]$/,A8=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Gg=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,e0=2n**256n-1n;function Si(t,e,r){const{checksumAddress:n,staticPosition:s}=r,i=wh(e.type);if(i){const[o,a]=i;return k8(t,{...e,type:a},{checksumAddress:n,length:o,staticPosition:s})}if(e.type==="tuple")return I8(t,e,{checksumAddress:n,staticPosition:s});if(e.type==="address")return x8(t,{checksum:n});if(e.type==="bool")return T8(t);if(e.type.startsWith("bytes"))return _8(t,e,{staticPosition:s});if(e.type.startsWith("uint")||e.type.startsWith("int"))return P8(t,e);if(e.type==="string")return O8(t,{staticPosition:s});throw new Eh(e.type)}const t0=32,Jl=32;function x8(t,e={}){const{checksum:r=!1}=e,n=t.readBytes(32);return[(i=>r?qg(i):i)(Br(BE(n,-20))),32]}function k8(t,e,r){const{checksumAddress:n,length:s,staticPosition:i}=r;if(!s){const c=An(t.readBytes(Jl)),u=i+c,f=u+t0;t.setPosition(u);const l=An(t.readBytes(t0)),p=Yo(e);let d=0;const m=[];for(let b=0;b<l;++b){t.setPosition(f+(p?b*32:d));const[E,A]=Si(t,e,{checksumAddress:n,staticPosition:f});d+=A,m.push(E)}return t.setPosition(i+32),[m,32]}if(Yo(e)){const c=An(t.readBytes(Jl)),u=i+c,f=[];for(let l=0;l<s;++l){t.setPosition(u+l*32);const[p]=Si(t,e,{checksumAddress:n,staticPosition:u});f.push(p)}return t.setPosition(i+32),[f,32]}let o=0;const a=[];for(let c=0;c<s;++c){const[u,f]=Si(t,e,{checksumAddress:n,staticPosition:i+o});o+=f,a.push(u)}return[a,o]}function T8(t){return[$E(t.readBytes(32),{size:32}),32]}function _8(t,e,{staticPosition:r}){const[n,s]=e.type.split("bytes");if(!s){const o=An(t.readBytes(32));t.setPosition(r+o);const a=An(t.readBytes(32));if(a===0)return t.setPosition(r+32),["0x",32];const c=t.readBytes(a);return t.setPosition(r+32),[Br(c),32]}return[Br(t.readBytes(Number.parseInt(s,10),32)),32]}function P8(t,e){const r=e.type.startsWith("int"),n=Number.parseInt(e.type.split("int")[1]||"256",10),s=t.readBytes(32);return[n>48?CE(s,{signed:r}):An(s,{signed:r}),32]}function I8(t,e,r){const{checksumAddress:n,staticPosition:s}=r,i=e.components.length===0||e.components.some(({name:c})=>!c),o=i?[]:{};let a=0;if(Yo(e)){const c=An(t.readBytes(Jl)),u=s+c;for(let f=0;f<e.components.length;++f){const l=e.components[f];t.setPosition(u+a);const[p,d]=Si(t,l,{checksumAddress:n,staticPosition:u});a+=d,o[i?f:l==null?void 0:l.name]=p}return t.setPosition(s+32),[o,32]}for(let c=0;c<e.components.length;++c){const u=e.components[c],[f,l]=Si(t,u,{checksumAddress:n,staticPosition:s});o[i?c:u==null?void 0:u.name]=f,a+=l}return[o,a]}function O8(t,{staticPosition:e}){const r=An(t.readBytes(32)),n=e+r;t.setPosition(n);const s=An(t.readBytes(32));if(s===0)return t.setPosition(e+32),["",32];const i=t.readBytes(s,32),o=RE(Fb(i));return t.setPosition(e+32),[o,32]}function B8({checksumAddress:t,parameters:e,values:r}){const n=[];for(let s=0;s<e.length;s++)n.push(bh({checksumAddress:t,parameter:e[s],value:r[s]}));return n}function bh({checksumAddress:t=!1,parameter:e,value:r}){const n=e,s=wh(n.type);if(s){const[i,o]=s;return $8(r,{checksumAddress:t,length:i,parameter:{...n,type:o}})}if(n.type==="tuple")return F8(r,{checksumAddress:t,parameter:n});if(n.type==="address")return C8(r,{checksum:t});if(n.type==="bool")return N8(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){const i=n.type.startsWith("int"),[,,o="256"]=Gg.exec(n.type)??[];return U8(r,{signed:i,size:Number(o)})}if(n.type.startsWith("bytes"))return R8(r,{type:n.type});if(n.type==="string")return M8(r);throw new Eh(n.type)}function gh(t){let e=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?e+=32:e+=Zt(a)}const r=[],n=[];let s=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?(r.push(It(e+s,{size:32})),n.push(a),s+=Zt(a)):r.push(a)}return Or(...r,...n)}function C8(t,e){const{checksum:r=!1}=e;return Qc(t,{strict:r}),{dynamic:!1,encoded:Ls(t.toLowerCase())}}function $8(t,e){const{checksumAddress:r,length:n,parameter:s}=e,i=n===null;if(!Array.isArray(t))throw new W8(t);if(!i&&t.length!==n)throw new G8({expectedLength:n,givenLength:t.length,type:`${s.type}[${n}]`});let o=!1;const a=[];for(let c=0;c<t.length;c++){const u=bh({checksumAddress:r,parameter:s,value:t[c]});u.dynamic&&(o=!0),a.push(u)}if(i||o){const c=gh(a);if(i){const u=It(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?Or(u,c):u}}if(o)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Or(...a.map(({encoded:c})=>c))}}function R8(t,{type:e}){const[,r]=e.split("bytes"),n=Zt(t);if(!r){let s=t;return n%32!==0&&(s=Ds(s,Math.ceil((t.length-2)/2/32)*32)),{dynamic:!0,encoded:Or(Ls(It(n,{size:32})),s)}}if(n!==Number.parseInt(r,10))throw new Kg({expectedSize:Number.parseInt(r,10),value:t});return{dynamic:!1,encoded:Ds(t)}}function N8(t){if(typeof t!="boolean")throw new ve(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Ls(jb(t))}}function U8(t,{signed:e,size:r}){if(typeof r=="number"){const n=2n**(BigInt(r)-(e?1n:0n))-1n,s=e?-n-1n:0n;if(t>n||t<s)throw new Hb({max:n.toString(),min:s.toString(),signed:e,size:r/8,value:t.toString()})}return{dynamic:!1,encoded:It(t,{size:32,signed:e})}}function M8(t){const e=ah(t),r=Math.ceil(Zt(e)/32),n=[];for(let s=0;s<r;s++)n.push(Ds(Yr(e,s*32,(s+1)*32)));return{dynamic:!0,encoded:Or(Ds(It(Zt(e),{size:32})),...n)}}function F8(t,e){const{checksumAddress:r,parameter:n}=e;let s=!1;const i=[];for(let o=0;o<n.components.length;o++){const a=n.components[o],c=Array.isArray(t)?o:a.name,u=bh({checksumAddress:r,parameter:a,value:t[c]});i.push(u),u.dynamic&&(s=!0)}return{dynamic:s,encoded:s?gh(i):Or(...i.map(({encoded:o})=>o))}}function wh(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function Yo(t){var n;const{type:e}=t;if(e==="string"||e==="bytes"||e.endsWith("[]"))return!0;if(e==="tuple")return(n=t.components)==null?void 0:n.some(Yo);const r=wh(t.type);return!!(r&&Yo({...t,type:r[1]}))}const j8={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 H8({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(t){if(t<0||t>this.bytes.length-1)throw new D8({length:this.bytes.length,position:t})},decrementPosition(t){if(t<0)throw new r0({offset:t});const e=this.position-t;this.assertPosition(e),this.position=e},getReadCount(t){return this.positionReadCount.get(t||this.position)||0},incrementPosition(t){if(t<0)throw new r0({offset:t});const e=this.position+t;this.assertPosition(e),this.position=e},inspectByte(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectBytes(t,e){const r=e??this.position;return this.assertPosition(r+t-1),this.bytes.subarray(r,r+t)},inspectUint8(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectUint16(t){const e=t??this.position;return this.assertPosition(e+1),this.dataView.getUint16(e)},inspectUint24(t){const e=t??this.position;return this.assertPosition(e+2),(this.dataView.getUint16(e)<<8)+this.dataView.getUint8(e+2)},inspectUint32(t){const e=t??this.position;return this.assertPosition(e+3),this.dataView.getUint32(e)},pushByte(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushBytes(t){this.assertPosition(this.position+t.length-1),this.bytes.set(t,this.position),this.position+=t.length},pushUint8(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushUint16(t){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,t),this.position+=2},pushUint24(t){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,t>>8),this.dataView.setUint8(this.position+2,t&255),this.position+=3},pushUint32(t){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,t),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const t=this.inspectByte();return this.position++,t},readBytes(t,e){this.assertReadLimit(),this._touch();const r=this.inspectBytes(t);return this.position+=e??t,r},readUint8(){this.assertReadLimit(),this._touch();const t=this.inspectUint8();return this.position+=1,t},readUint16(){this.assertReadLimit(),this._touch();const t=this.inspectUint16();return this.position+=2,t},readUint24(){this.assertReadLimit(),this._touch();const t=this.inspectUint24();return this.position+=3,t},readUint32(){this.assertReadLimit(),this._touch();const t=this.inspectUint32();return this.position+=4,t},get remaining(){return this.bytes.length-this.position},setPosition(t){const e=this.position;return this.assertPosition(t),this.position=t,()=>this.position=e},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const t=this.getReadCount();this.positionReadCount.set(this.position,t+1),t>0&&this.recursiveReadCount++}};function L8(t,{recursiveReadLimit:e=8192}={}){const r=Object.create(j8);return r.bytes=t,r.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=e,r}class r0 extends ve{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class D8 extends ve{constructor({length:e,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class H8 extends ve{constructor({count:e,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function z8(t,e,r={}){const{as:n="Array",checksumAddress:s=!1}=r,i=typeof e=="string"?Mb(e):e,o=L8(i);if(bi(i)===0&&t.length>0)throw new q8;if(bi(i)&&bi(i)<32)throw new V8({data:typeof e=="string"?e:Br(e),parameters:t,size:bi(i)});let a=0;const c=n==="Array"?[]:{};for(let u=0;u<t.length;++u){const f=t[u];o.setPosition(a);const[l,p]=Si(o,f,{checksumAddress:s,staticPosition:0});a+=p,n==="Array"?c.push(l):c[f.name??u]=l}return c}function vh(t,e,r){const{checksumAddress:n=!1}={};if(t.length!==e.length)throw new Zg({expectedLength:t.length,givenLength:e.length});const s=B8({checksumAddress:n,parameters:t,values:e}),i=gh(s);return i.length===0?"0x":i}function Ql(t,e){if(t.length!==e.length)throw new Zg({expectedLength:t.length,givenLength:e.length});const r=[];for(let n=0;n<t.length;n++){const s=t[n],i=e[n];r.push(Ql.encode(s,i))}return Or(...r)}(function(t){function e(r,n,s=!1){if(r==="address"){const c=n;return Qc(c),Ls(c.toLowerCase(),s?32:0)}if(r==="string")return ah(n);if(r==="bytes")return n;if(r==="bool")return Ls(jb(n),s?32:1);const i=r.match(Gg);if(i){const[c,u,f="256"]=i,l=Number.parseInt(f,10)/8;return It(n,{size:s?32:l,signed:u==="int"})}const o=r.match(A8);if(o){const[c,u]=o;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new Kg({expectedSize:Number.parseInt(u,10),value:n});return Ds(n,s?32:0)}const a=r.match(S8);if(a&&Array.isArray(n)){const[c,u]=a,f=[];for(let l=0;l<n.length;l++)f.push(e(u,n[l],!0));return f.length===0?"0x":Or(...f)}throw new Eh(r)}t.encode=e})(Ql||(Ql={}));function Wg(t){return Array.isArray(t)&&typeof t[0]=="string"||typeof t=="string"?Jp(t):t}class V8 extends ve{constructor({data:e,parameters:r,size:n}){super(`Data size of ${n} bytes is too small for given parameters.`,{metaMessages:[`Params: (${ci(r)})`,`Data: ${e} (${n} bytes)`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class q8 extends ve{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.'),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}}class G8 extends ve{constructor({expectedLength:e,givenLength:r,type:n}){super(`Array length mismatch for type \`${n}\`. Expected: \`${e}\`. Given: \`${r}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class Kg extends ve{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${Zt(r)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class Zg extends ve{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${r}`].join(`
|
|
45
|
+
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class W8 extends ve{constructor(e){super(`Value \`${e}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class Eh extends ve{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}class Yg extends Rc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Cv(e);const n=En(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,i=new Uint8Array(s);i.set(n.length>s?e.create().update(n).digest():n);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Ir(i)}update(e){return os(this),this.iHash.update(e),this}digestInto(e){os(this),is(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:n,finished:s,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Xg=(t,e,r)=>new Yg(t,e).update(r).digest();Xg.create=(t,e)=>new Yg(t,e);function Jg(t,e={}){const{recovered:r}=e;if(typeof t.r>"u")throw new Du({signature:t});if(typeof t.s>"u")throw new Du({signature:t});if(r&&typeof t.yParity>"u")throw new Du({signature:t});if(t.r<0n||t.r>e0)throw new ex({value:t.r});if(t.s<0n||t.s>e0)throw new tx({value:t.s});if(typeof t.yParity=="number"&&t.yParity!==0&&t.yParity!==1)throw new Ah({value:t.yParity})}function K8(t){return Qg(Br(t))}function Qg(t){if(t.length!==130&&t.length!==132)throw new Q8({signature:t});const e=BigInt(Yr(t,0,32)),r=BigInt(Yr(t,32,64)),n=(()=>{const s=+`0x${t.slice(130)}`;if(!Number.isNaN(s))try{return Sh(s)}catch{throw new Ah({value:s})}})();return typeof n>"u"?{r:e,s:r}:{r:e,s:r,yParity:n}}function Z8(t){if(!(typeof t.r>"u")&&!(typeof t.s>"u"))return Y8(t)}function Y8(t){const e=typeof t=="string"?Qg(t):t instanceof Uint8Array?K8(t):typeof t.r=="string"?J8(t):t.v?X8(t):{r:t.r,s:t.s,...typeof t.yParity<"u"?{yParity:t.yParity}:{}};return Jg(e),e}function X8(t){return{r:t.r,s:t.s,yParity:Sh(t.v)}}function J8(t){const e=(()=>{const r=t.v?Number(t.v):void 0;let n=t.yParity?Number(t.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=Sh(r)),typeof n!="number")throw new Ah({value:t.yParity});return n})();return{r:BigInt(t.r),s:BigInt(t.s),yParity:e}}function Sh(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new rx({value:t})}class Q8 extends ve{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Zt(HE(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class Du extends ve{constructor({signature:e}){super(`Signature \`${Ub(e)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class ex extends ve{constructor({value:e}){super(`Value \`${e}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}}class tx extends ve{constructor({value:e}){super(`Value \`${e}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}}class Ah extends ve{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class rx extends ve{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function nx(t,e={}){return typeof t.chainId=="string"?sx(t):{...t,...e.signature}}function sx(t){const{address:e,chainId:r,nonce:n}=t,s=Z8(t);return{address:e,chainId:Number(r),nonce:BigInt(n),...s}}const ix="0x8010801080108010801080108010801080108010801080108010801080108010",ox=Wg("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");function e1(t){if(typeof t=="string"){if(Yr(t,-32)!==ix)throw new ux(t)}else Jg(t.authorization)}function ax(t){e1(t);const e=Db(Yr(t,-64,-32)),r=Yr(t,-e-64,-64),n=Yr(t,0,-e-64),[s,i,o]=z8(ox,r);return{authorization:nx({address:s.delegation,chainId:Number(s.chainId),nonce:s.nonce,yParity:s.yParity,r:s.r,s:s.s}),signature:n,...o&&o!=="0x"?{data:o,to:i}:{}}}function cx(t){try{return e1(t),!0}catch{return!1}}let ux=class extends ve{constructor(e){super(`Value \`${e}\` is an invalid ERC-8010 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}};function fx(t){return t.map(e=>({...e,value:BigInt(e.value)}))}function lx(t){return{...t,balance:t.balance?BigInt(t.balance):void 0,nonce:t.nonce?dr(t.nonce):void 0,storageProof:t.storageProof?fx(t.storageProof):void 0}}async function dx(t,{address:e,blockNumber:r,blockTag:n,storageKeys:s}){const i=n??"latest",o=r!==void 0?Z(r):void 0,a=await t.request({method:"eth_getProof",params:[e,s,o||i]});return lx(a)}async function hx(t,{address:e,blockNumber:r,blockTag:n="latest",slot:s}){const i=r!==void 0?Z(r):void 0;return await t.request({method:"eth_getStorageAt",params:[e,s,i||n]})}async function xh(t,{blockHash:e,blockNumber:r,blockTag:n,hash:s,index:i}){var f,l,p;const o=n||"latest",a=r!==void 0?Z(r):void 0;let c=null;if(s?c=await t.request({method:"eth_getTransactionByHash",params:[s]},{dedupe:!0}):e?c=await t.request({method:"eth_getTransactionByBlockHashAndIndex",params:[e,Z(i)]},{dedupe:!0}):c=await t.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[a||o,Z(i)]},{dedupe:!!a}),!c)throw new fb({blockHash:e,blockNumber:r,blockTag:o,hash:s,index:i});return(((p=(l=(f=t.chain)==null?void 0:f.formatters)==null?void 0:l.transaction)==null?void 0:p.format)||Vc)(c)}async function px(t,{hash:e,transactionReceipt:r}){const[n,s]=await Promise.all([se(t,va,"getBlockNumber")({}),e?se(t,xh,"getTransaction")({hash:e}):void 0]),i=(r==null?void 0:r.blockNumber)||(s==null?void 0:s.blockNumber);return i?n-i+1n:0n}async function sc(t,{hash:e}){var s,i,o;const r=await t.request({method:"eth_getTransactionReceipt",params:[e]},{dedupe:!0});if(!r)throw new lb({hash:e});return(((o=(i=(s=t.chain)==null?void 0:s.formatters)==null?void 0:i.transactionReceipt)==null?void 0:o.format)||ig)(r)}async function yx(t,e){var P;const{account:r,authorizationList:n,allowFailure:s=!0,blockNumber:i,blockOverrides:o,blockTag:a,stateOverride:c}=e,u=e.contracts,{batchSize:f=e.batchSize??1024,deployless:l=e.deployless??!1}=typeof((P=t.batch)==null?void 0:P.multicall)=="object"?t.batch.multicall:{},p=(()=>{if(e.multicallAddress)return e.multicallAddress;if(l)return null;if(t.chain)return Wi({blockNumber:i,chain:t.chain,contract:"multicall3"});throw new Error("client chain not configured. multicallAddress is required.")})(),d=[[]];let m=0,b=0;for(let S=0;S<u.length;S++){const{abi:w,address:k,args:T,functionName:B}=u[S];try{const N=Jt({abi:w,args:T,functionName:B});b+=(N.length-2)/2,f>0&&b>f&&d[m].length>0&&(m++,b=(N.length-2)/2,d[m]=[]),d[m]=[...d[m],{allowFailure:!0,callData:N,target:k}]}catch(N){const $=Fs(N,{abi:w,address:k,args:T,docsPath:"/docs/contract/multicall",functionName:B,sender:r});if(!s)throw $;d[m]=[...d[m],{allowFailure:!0,callData:"0x",target:k}]}}const E=await Promise.allSettled(d.map(S=>se(t,hr,"readContract")({...p===null?{code:ch}:{address:p},abi:bc,account:r,args:[S],authorizationList:n,blockNumber:i,blockOverrides:o,blockTag:a,functionName:"aggregate3",stateOverride:c}))),A=[];for(let S=0;S<E.length;S++){const w=E[S];if(w.status==="rejected"){if(!s)throw w.reason;for(let T=0;T<d[S].length;T++)A.push({status:"failure",error:w.reason,result:void 0});continue}const k=w.value;for(let T=0;T<k.length;T++){const{returnData:B,success:N}=k[T],{callData:$}=d[S][T],{abi:D,address:M,functionName:V,args:G}=u[A.length];try{if($==="0x")throw new la;if(!N)throw new Lc({data:B});const Q=Xs({abi:D,args:G,data:B,functionName:V});A.push(s?{result:Q,status:"success"}:Q)}catch(Q){const W=Fs(Q,{abi:D,address:M,args:G,docsPath:"/docs/contract/multicall",functionName:V});if(!s)throw W;A.push({error:W,result:void 0,status:"failure"})}}}if(A.length!==u.length)throw new L("multicall results mismatch");return A}async function ed(t,e){const{blockNumber:r,blockTag:n=t.experimental_blockTag??"latest",blocks:s,returnFullTransactions:i,traceTransfers:o,validation:a}=e;try{const c=[];for(const p of s){const d=p.blockOverrides?Vb(p.blockOverrides):void 0,m=p.calls.map(E=>{const A=E,P=A.account?Ze(A.account):void 0,S=A.abi?Jt(A):A.data,w={...A,data:A.dataSuffix?Kt([S||"0x",A.dataSuffix]):S,from:A.from??(P==null?void 0:P.address)};return Ys(w),Vi(w)}),b=p.stateOverrides?Wd(p.stateOverrides):void 0;c.push({blockOverrides:d,calls:m,stateOverrides:b})}const f=(typeof r=="bigint"?Z(r):void 0)||n;return(await t.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:i,traceTransfers:o,validation:a},f]})).map((p,d)=>({...Zd(p),calls:p.calls.map((m,b)=>{var D,M;const{abi:E,args:A,functionName:P,to:S}=s[d].calls[b],w=((D=m.error)==null?void 0:D.data)??m.returnData,k=BigInt(m.gasUsed),T=(M=m.logs)==null?void 0:M.map(V=>kn(V)),B=m.status==="0x1"?"success":"failure",N=E&&B==="success"&&w!=="0x"?Xs({abi:E,data:w,functionName:P}):null,$=(()=>{var G;if(B==="success")return;let V;if(((G=m.error)==null?void 0:G.data)==="0x"?V=new la:m.error&&(V=new Lc(m.error)),!!V)return Fs(V,{abi:E??[],address:S??"0x",args:A,functionName:P??"<unknown>"})})();return{data:w,gasUsed:k,logs:T,status:B,...B==="success"?{result:N}:{error:$}}})}))}catch(c){const u=c,f=Dc(u,{});throw f instanceof ba?u:f}}function td(t){let e=!0,r="",n=0,s="",i=!1;for(let o=0;o<t.length;o++){const a=t[o];if(["(",")",","].includes(a)&&(e=!0),a==="("&&n++,a===")"&&n--,!!e){if(n===0){if(a===" "&&["event","function","error",""].includes(s))s="";else if(s+=a,a===")"){i=!0;break}continue}if(a===" "){t[o-1]!==","&&r!==","&&r!==",("&&(r="",e=!1);continue}s+=a,r+=a}}if(!i)throw new ve("Unable to normalize signature.");return s}function rd(t,e){const r=typeof t,n=e.type;switch(n){case"address":return Xl(t,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in e?Object.values(e.components).every((s,i)=>rd(Object.values(t)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||t instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(t)&&t.every(s=>rd(s,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function t1(t,e,r){for(const n in t){const s=t[n],i=e[n];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return t1(s.components,i.components,r[n]);const o=[s.type,i.type];if(o.includes("address")&&o.includes("bytes20")?!0:o.includes("address")&&o.includes("string")?Xl(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?Xl(r[n],{strict:!1}):!1)return o}}function r1(t,e={}){const{prepare:r=!0}=e,n=Array.isArray(t)||typeof t=="string"?Xp(t):t;return{...n,...r?{hash:gi(n)}:{}}}function eu(t,e,r){const{args:n=[],prepare:s=!0}=r??{},i=zE(e,{strict:!1}),o=t.filter(u=>i?u.type==="function"||u.type==="error"?n1(u)===Yr(e,0,4):u.type==="event"?gi(u)===e:!1:"name"in u&&u.name===e);if(o.length===0)throw new wc({name:e});if(o.length===1)return{...o[0],...s?{hash:gi(o[0])}:{}};let a;for(const u of o){if(!("inputs"in u))continue;if(!n||n.length===0){if(!u.inputs||u.inputs.length===0)return{...u,...s?{hash:gi(u)}:{}};continue}if(!u.inputs||u.inputs.length===0||u.inputs.length!==n.length)continue;if(n.every((l,p)=>{const d="inputs"in u&&u.inputs[p];return d?rd(l,d):!1})){if(a&&"inputs"in a&&a.inputs){const l=t1(u.inputs,a.inputs,n);if(l)throw new bx({abiItem:u,type:l[0]},{abiItem:a,type:l[1]})}a=u}}const c=(()=>{if(a)return a;const[u,...f]=o;return{...u,overloads:f}})();if(!c)throw new wc({name:e});return{...c,...s?{hash:gi(c)}:{}}}function n1(...t){const e=(()=>{if(Array.isArray(t[0])){const[r,n]=t;return eu(r,n)}return t[0]})();return Yr(gi(e),0,4)}function mx(...t){const e=(()=>{if(Array.isArray(t[0])){const[n,s]=t;return eu(n,s)}return t[0]})(),r=typeof e=="string"?e:Zl(e);return td(r)}function gi(...t){const e=(()=>{if(Array.isArray(t[0])){const[r,n]=t;return eu(r,n)}return t[0]})();return typeof e!="string"&&"hash"in e&&e.hash?e.hash:Vg(ah(mx(e)))}class bx extends ve{constructor(e,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${e.type}\` in \`${td(Zl(e.abiItem))}\`, and`,`\`${r.type}\` in \`${td(Zl(r.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}}class wc extends ve{constructor({name:e,data:r,type:n="item"}){const s=e?` with name "${e}"`:r?` with data "${r}"`:"";super(`ABI ${n}${s} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}function gx(...t){var i;const[e,r]=(()=>{if(Array.isArray(t[0])){const[o,a]=t;return[vx(o),a]}return t})(),{bytecode:n,args:s}=r;return Or(n,(i=e.inputs)!=null&&i.length&&(s!=null&&s.length)?vh(e.inputs,s):"0x")}function wx(t){return r1(t)}function vx(t){const e=t.find(r=>r.type==="constructor");if(!e)throw new wc({name:"constructor"});return e}function Ex(...t){const[e,r=[]]=(()=>{if(Array.isArray(t[0])){const[u,f,l]=t;return[n0(u,f,{args:l}),l]}const[a,c]=t;return[a,c]})(),{overloads:n}=e,s=n?n0([e,...n],e.name,{args:r}):e,i=Sx(s),o=r.length>0?vh(s.inputs,r):void 0;return o?Or(i,o):i}function ii(t,e={}){return r1(t,e)}function n0(t,e,r){const n=eu(t,e,r);if(n.type!=="function")throw new wc({name:e,type:"function"});return n}function Sx(t){return n1(t)}const Ax="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Fr="0x0000000000000000000000000000000000000000",xx="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function kx(t,e){const{blockNumber:r,blockTag:n,calls:s,stateOverrides:i,traceAssetChanges:o,traceTransfers:a,validation:c}=e,u=e.account?Ze(e.account):void 0;if(o&&!u)throw new L("`account` is required when `traceAssetChanges` is true");const f=u?gx(wx("constructor(bytes, bytes)"),{bytecode:Kb,args:[xx,Ex(ii("function getBalance(address)"),[u.address])]}):void 0,l=o?await Promise.all(e.calls.map(async q=>{if(!q.data&&!q.abi)return;const{accessList:I}=await mg(t,{account:u.address,...q,data:q.abi?Jt(q):q.data});return I.map(({address:j,storageKeys:J})=>J.length>0?j:null)})).then(q=>q.flat().filter(Boolean)):[],p=await ed(t,{blockNumber:r,blockTag:n,blocks:[...o?[{calls:[{data:f}],stateOverrides:i},{calls:l.map((q,I)=>({abi:[ii("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:q,from:Fr,nonce:I})),stateOverrides:[{address:Fr,nonce:0}]}]:[],{calls:[...s,{}].map(q=>({...q,from:u==null?void 0:u.address})),stateOverrides:i},...o?[{calls:[{data:f}]},{calls:l.map((q,I)=>({abi:[ii("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:q,from:Fr,nonce:I})),stateOverrides:[{address:Fr,nonce:0}]},{calls:l.map((q,I)=>({to:q,abi:[ii("function decimals() returns (uint256)")],functionName:"decimals",from:Fr,nonce:I})),stateOverrides:[{address:Fr,nonce:0}]},{calls:l.map((q,I)=>({to:q,abi:[ii("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:Fr,nonce:I})),stateOverrides:[{address:Fr,nonce:0}]},{calls:l.map((q,I)=>({to:q,abi:[ii("function symbol() returns (string)")],functionName:"symbol",from:Fr,nonce:I})),stateOverrides:[{address:Fr,nonce:0}]}]:[]],traceTransfers:a,validation:c}),d=o?p[2]:p[0],[m,b,,E,A,P,S,w]=o?p:[],{calls:k,...T}=d,B=k.slice(0,-1)??[],N=(m==null?void 0:m.calls)??[],$=(b==null?void 0:b.calls)??[],D=[...N,...$].map(q=>q.status==="success"?ut(q.data):null),M=(E==null?void 0:E.calls)??[],V=(A==null?void 0:A.calls)??[],G=[...M,...V].map(q=>q.status==="success"?ut(q.data):null),Q=((P==null?void 0:P.calls)??[]).map(q=>q.status==="success"?q.result:null),W=((w==null?void 0:w.calls)??[]).map(q=>q.status==="success"?q.result:null),K=((S==null?void 0:S.calls)??[]).map(q=>q.status==="success"?q.result:null),re=[];for(const[q,I]of G.entries()){const j=D[q];if(typeof I!="bigint"||typeof j!="bigint")continue;const J=Q[q-1],O=W[q-1],R=K[q-1],F=q===0?{address:Ax,decimals:18,symbol:"ETH"}:{address:l[q-1],decimals:R||J?Number(J??1):void 0,symbol:O??void 0};re.some(ne=>ne.token.address===F.address)||re.push({token:F,value:{pre:j,post:I,diff:I-j}})}return{assetChanges:re,block:T,results:B}}const s1="0x6492649264926492649264926492649264926492649264926492649264926492";function Tx(t){if(Yr(t,-32)!==s1)throw new Ix(t)}function _x(t){const{data:e,signature:r,to:n}=t;return Or(vh(Wg("address, bytes, bytes"),[n,e,r]),s1)}function Px(t){try{return Tx(t),!0}catch{return!1}}class Ix extends ve{constructor(e){super(`Value \`${e}\` is an invalid ERC-6492 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const kh=BigInt(0),nd=BigInt(1);function Aa(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Th(t){if(!Aa(t))throw new Error("Uint8Array expected")}function Xo(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function La(t){const e=t.toString(16);return e.length&1?"0"+e:e}function i1(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?kh:BigInt("0x"+t)}const o1=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ox=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Jo(t){if(Th(t),o1)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Ox[t[r]];return e}const nn={_0:48,_9:57,A:65,F:70,a:97,f:102};function s0(t){if(t>=nn._0&&t<=nn._9)return t-nn._0;if(t>=nn.A&&t<=nn.F)return t-(nn.A-10);if(t>=nn.a&&t<=nn.f)return t-(nn.a-10)}function vc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(o1)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let s=0,i=0;s<r;s++,i+=2){const o=s0(t.charCodeAt(i)),a=s0(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[s]=o*16+a}return n}function Ps(t){return i1(Jo(t))}function a1(t){return Th(t),i1(Jo(Uint8Array.from(t).reverse()))}function xa(t,e){return vc(t.toString(16).padStart(e*2,"0"))}function c1(t,e){return xa(t,e).reverse()}function sr(t,e,r){let n;if(typeof e=="string")try{n=vc(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(Aa(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=n.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return n}function Ec(...t){let e=0;for(let n=0;n<t.length;n++){const s=t[n];Th(s),e+=s.length}const r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){const i=t[n];r.set(i,s),s+=i.length}return r}const Hu=t=>typeof t=="bigint"&&kh<=t;function _h(t,e,r){return Hu(t)&&Hu(e)&&Hu(r)&&e<=t&&t<r}function Ai(t,e,r,n){if(!_h(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Bx(t){let e;for(e=0;t>kh;t>>=nd,e+=1);return e}const tu=t=>(nd<<BigInt(t))-nd,zu=t=>new Uint8Array(t),i0=t=>Uint8Array.from(t);function Cx(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=zu(t),s=zu(t),i=0;const o=()=>{n.fill(1),s.fill(0),i=0},a=(...l)=>r(s,n,...l),c=(l=zu(0))=>{s=a(i0([0]),l),n=a(),l.length!==0&&(s=a(i0([1]),l),n=a())},u=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const p=[];for(;l<e;){n=a();const d=n.slice();p.push(d),l+=n.length}return Ec(...p)};return(l,p)=>{o(),c(l);let d;for(;!(d=p(u()));)c();return o(),d}}const $x={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||Aa(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function ru(t,e,r={}){const n=(s,i,o)=>{const a=$x[i];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+i+", got "+c)};for(const[s,i]of Object.entries(e))n(s,i,!1);for(const[s,i]of Object.entries(r))n(s,i,!0);return t}function o0(t){const e=new WeakMap;return(r,...n)=>{const s=e.get(r);if(s!==void 0)return s;const i=t(r,...n);return e.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ft=BigInt(0),Ct=BigInt(1),Es=BigInt(2),Rx=BigInt(3),u1=BigInt(4),f1=BigInt(5),l1=BigInt(8);function Rt(t,e){const r=t%e;return r>=Ft?r:e+r}function tr(t,e,r){let n=t;for(;e-- >Ft;)n*=n,n%=r;return n}function sd(t,e){if(t===Ft)throw new Error("invert: expected non-zero number");if(e<=Ft)throw new Error("invert: expected positive modulus, got "+e);let r=Rt(t,e),n=e,s=Ft,i=Ct;for(;r!==Ft;){const a=n/r,c=n%r,u=s-i*a;n=r,r=c,s=i,i=u}if(n!==Ct)throw new Error("invert: does not exist");return Rt(s,e)}function d1(t,e){const r=(t.ORDER+Ct)/u1,n=t.pow(e,r);if(!t.eql(t.sqr(n),e))throw new Error("Cannot find square root");return n}function Nx(t,e){const r=(t.ORDER-f1)/l1,n=t.mul(e,Es),s=t.pow(n,r),i=t.mul(e,s),o=t.mul(t.mul(i,Es),s),a=t.mul(i,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function Ux(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Ct,r=0;for(;e%Es===Ft;)e/=Es,r++;let n=Es;const s=Ph(t);for(;a0(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return d1;let i=s.pow(n,e);const o=(e+Ct)/Es;return function(c,u){if(c.is0(u))return u;if(a0(c,u)!==1)throw new Error("Cannot find square root");let f=r,l=c.mul(c.ONE,i),p=c.pow(u,e),d=c.pow(u,o);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let m=1,b=c.sqr(p);for(;!c.eql(b,c.ONE);)if(m++,b=c.sqr(b),m===f)throw new Error("Cannot find square root");const E=Ct<<BigInt(f-m-1),A=c.pow(l,E);f=m,l=c.sqr(A),p=c.mul(p,l),d=c.mul(d,A)}return d}}function Mx(t){return t%u1===Rx?d1:t%l1===f1?Nx:Ux(t)}const Fx=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function jx(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Fx.reduce((n,s)=>(n[s]="function",n),e);return ru(t,r)}function Lx(t,e,r){if(r<Ft)throw new Error("invalid exponent, negatives unsupported");if(r===Ft)return t.ONE;if(r===Ct)return e;let n=t.ONE,s=e;for(;r>Ft;)r&Ct&&(n=t.mul(n,s)),s=t.sqr(s),r>>=Ct;return n}function h1(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),i=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),i),n}function a0(t,e){const r=(t.ORDER-Ct)/Es,n=t.pow(e,r),s=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function p1(t,e){e!==void 0&&ss(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Ph(t,e,r=!1,n={}){if(t<=Ft)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:i}=p1(t,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:i,MASK:tu(s),ZERO:Ft,ONE:Ct,create:c=>Rt(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ft<=c&&c<t},is0:c=>c===Ft,isOdd:c=>(c&Ct)===Ct,neg:c=>Rt(-c,t),eql:(c,u)=>c===u,sqr:c=>Rt(c*c,t),add:(c,u)=>Rt(c+u,t),sub:(c,u)=>Rt(c-u,t),mul:(c,u)=>Rt(c*u,t),pow:(c,u)=>Lx(a,c,u),div:(c,u)=>Rt(c*sd(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>sd(c,t),sqrt:n.sqrt||(c=>(o||(o=Mx(t)),o(a,c))),toBytes:c=>r?c1(c,i):xa(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return r?a1(c):Ps(c)},invertBatch:c=>h1(a,c),cmov:(c,u,f)=>f?u:c});return Object.freeze(a)}function y1(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function m1(t){const e=y1(t);return e+Math.ceil(e/2)}function Dx(t,e,r=!1){const n=t.length,s=y1(e),i=m1(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=r?a1(t):Ps(t),a=Rt(o,e-Ct)+Ct;return r?c1(a,s):xa(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const c0=BigInt(0),id=BigInt(1);function Vu(t,e){const r=e.negate();return t?r:e}function b1(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function qu(t,e){b1(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),s=2**t,i=tu(t),o=BigInt(t);return{windows:r,windowSize:n,mask:i,maxNumber:s,shiftBy:o}}function u0(t,e,r){const{windowSize:n,mask:s,maxNumber:i,shiftBy:o}=r;let a=Number(t&s),c=t>>o;a>n&&(a-=i,c+=id);const u=e*n,f=u+Math.abs(a)-1,l=a===0,p=a<0,d=e%2!==0;return{nextN:c,offset:f,isZero:l,isNeg:p,isNegF:d,offsetF:u}}function Hx(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function zx(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const Gu=new WeakMap,g1=new WeakMap;function Wu(t){return g1.get(t)||1}function Vx(t,e){return{constTimeNegate:Vu,hasPrecomputes(r){return Wu(r)!==1},unsafeLadder(r,n,s=t.ZERO){let i=r;for(;n>c0;)n&id&&(s=s.add(i)),i=i.double(),n>>=id;return s},precomputeWindow(r,n){const{windows:s,windowSize:i}=qu(n,e),o=[];let a=r,c=a;for(let u=0;u<s;u++){c=a,o.push(c);for(let f=1;f<i;f++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,n,s){let i=t.ZERO,o=t.BASE;const a=qu(r,e);for(let c=0;c<a.windows;c++){const{nextN:u,offset:f,isZero:l,isNeg:p,isNegF:d,offsetF:m}=u0(s,c,a);s=u,l?o=o.add(Vu(d,n[m])):i=i.add(Vu(p,n[f]))}return{p:i,f:o}},wNAFUnsafe(r,n,s,i=t.ZERO){const o=qu(r,e);for(let a=0;a<o.windows&&s!==c0;a++){const{nextN:c,offset:u,isZero:f,isNeg:l}=u0(s,a,o);if(s=c,!f){const p=n[u];i=i.add(l?p.negate():p)}}return i},getPrecomputes(r,n,s){let i=Gu.get(n);return i||(i=this.precomputeWindow(n,r),r!==1&&Gu.set(n,s(i))),i},wNAFCached(r,n,s){const i=Wu(r);return this.wNAF(i,this.getPrecomputes(i,r,s),n)},wNAFCachedUnsafe(r,n,s,i){const o=Wu(r);return o===1?this.unsafeLadder(r,n,i):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),n,i)},setWindowSize(r,n){b1(n,e),g1.set(r,n),Gu.delete(r)}}}function qx(t,e,r,n){Hx(r,t),zx(n,e);const s=r.length,i=n.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=Bx(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=tu(c),f=new Array(Number(u)+1).fill(o),l=Math.floor((e.BITS-1)/c)*c;let p=o;for(let d=l;d>=0;d-=c){f.fill(o);for(let b=0;b<i;b++){const E=n[b],A=Number(E>>BigInt(d)&u);f[A]=f[A].add(r[b])}let m=o;for(let b=f.length-1,E=o;b>0;b--)E=E.add(f[b]),m=m.add(E);if(p=p.add(m),d!==0)for(let b=0;b<c;b++)p=p.double()}return p}function w1(t){return jx(t.Fp),ru(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...p1(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function f0(t){t.lowS!==void 0&&Xo("lowS",t.lowS),t.prehash!==void 0&&Xo("prehash",t.prehash)}function Gx(t){const e=w1(t);ru(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:r,Fp:n,a:s}=e;if(r){if(!n.eql(s,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class Wx extends Error{constructor(e=""){super(e)}}const pn={Err:Wx,_tlv:{encode:(t,e)=>{const{Err:r}=pn;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,s=La(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const i=n>127?La(s.length/2|128):"";return La(t)+i+s+e},decode(t,e){const{Err:r}=pn;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const s=e[n++],i=!!(s&128);let o=0;if(!i)o=s;else{const c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const u=e.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const f of u)o=o<<8|f;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=pn;if(t<bn)throw new e("integer: negative integers are not allowed");let r=La(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=pn;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ps(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=pn,s=sr("signature",t),{v:i,l:o}=n.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:u,l:f}=n.decode(2,c);if(f.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=pn,n=e.encode(2,r.encode(t.r)),s=e.encode(2,r.encode(t.s)),i=n+s;return e.encode(48,i)}};function Ku(t,e){return Jo(xa(t,e))}const bn=BigInt(0),ct=BigInt(1);BigInt(2);const Zu=BigInt(3),Kx=BigInt(4);function Zx(t){const e=Gx(t),{Fp:r}=e,n=Ph(e.n,e.nBitLength),s=e.toBytes||((S,w,k)=>{const T=w.toAffine();return Ec(Uint8Array.from([4]),r.toBytes(T.x),r.toBytes(T.y))}),i=e.fromBytes||(S=>{const w=S.subarray(1),k=r.fromBytes(w.subarray(0,r.BYTES)),T=r.fromBytes(w.subarray(r.BYTES,2*r.BYTES));return{x:k,y:T}});function o(S){const{a:w,b:k}=e,T=r.sqr(S),B=r.mul(T,S);return r.add(r.add(B,r.mul(S,w)),k)}function a(S,w){const k=r.sqr(w),T=o(S);return r.eql(k,T)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=r.mul(r.pow(e.a,Zu),Kx),u=r.mul(r.sqr(e.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function f(S){return _h(S,ct,e.n)}function l(S){const{allowedPrivateKeyLengths:w,nByteLength:k,wrapPrivateKey:T,n:B}=e;if(w&&typeof S!="bigint"){if(Aa(S)&&(S=Jo(S)),typeof S!="string"||!w.includes(S.length))throw new Error("invalid private key");S=S.padStart(k*2,"0")}let N;try{N=typeof S=="bigint"?S:Ps(sr("private key",S,k))}catch{throw new Error("invalid private key, expected hex or "+k+" bytes, got "+typeof S)}return T&&(N=Rt(N,B)),Ai("private key",N,ct,B),N}function p(S){if(!(S instanceof b))throw new Error("ProjectivePoint expected")}const d=o0((S,w)=>{const{px:k,py:T,pz:B}=S;if(r.eql(B,r.ONE))return{x:k,y:T};const N=S.is0();w==null&&(w=N?r.ONE:r.inv(B));const $=r.mul(k,w),D=r.mul(T,w),M=r.mul(B,w);if(N)return{x:r.ZERO,y:r.ZERO};if(!r.eql(M,r.ONE))throw new Error("invZ was invalid");return{x:$,y:D}}),m=o0(S=>{if(S.is0()){if(e.allowInfinityPoint&&!r.is0(S.py))return;throw new Error("bad point: ZERO")}const{x:w,y:k}=S.toAffine();if(!r.isValid(w)||!r.isValid(k))throw new Error("bad point: x or y not FE");if(!a(w,k))throw new Error("bad point: equation left != right");if(!S.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class b{constructor(w,k,T){if(w==null||!r.isValid(w))throw new Error("x required");if(k==null||!r.isValid(k)||r.is0(k))throw new Error("y required");if(T==null||!r.isValid(T))throw new Error("z required");this.px=w,this.py=k,this.pz=T,Object.freeze(this)}static fromAffine(w){const{x:k,y:T}=w||{};if(!w||!r.isValid(k)||!r.isValid(T))throw new Error("invalid affine point");if(w instanceof b)throw new Error("projective point not allowed");const B=N=>r.eql(N,r.ZERO);return B(k)&&B(T)?b.ZERO:new b(k,T,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){const k=h1(r,w.map(T=>T.pz));return w.map((T,B)=>T.toAffine(k[B])).map(b.fromAffine)}static fromHex(w){const k=b.fromAffine(i(sr("pointHex",w)));return k.assertValidity(),k}static fromPrivateKey(w){return b.BASE.multiply(l(w))}static msm(w,k){return qx(b,n,w,k)}_setWindowSize(w){P.setWindowSize(this,w)}assertValidity(){m(this)}hasEvenY(){const{y:w}=this.toAffine();if(r.isOdd)return!r.isOdd(w);throw new Error("Field doesn't support isOdd")}equals(w){p(w);const{px:k,py:T,pz:B}=this,{px:N,py:$,pz:D}=w,M=r.eql(r.mul(k,D),r.mul(N,B)),V=r.eql(r.mul(T,D),r.mul($,B));return M&&V}negate(){return new b(this.px,r.neg(this.py),this.pz)}double(){const{a:w,b:k}=e,T=r.mul(k,Zu),{px:B,py:N,pz:$}=this;let D=r.ZERO,M=r.ZERO,V=r.ZERO,G=r.mul(B,B),Q=r.mul(N,N),W=r.mul($,$),K=r.mul(B,N);return K=r.add(K,K),V=r.mul(B,$),V=r.add(V,V),D=r.mul(w,V),M=r.mul(T,W),M=r.add(D,M),D=r.sub(Q,M),M=r.add(Q,M),M=r.mul(D,M),D=r.mul(K,D),V=r.mul(T,V),W=r.mul(w,W),K=r.sub(G,W),K=r.mul(w,K),K=r.add(K,V),V=r.add(G,G),G=r.add(V,G),G=r.add(G,W),G=r.mul(G,K),M=r.add(M,G),W=r.mul(N,$),W=r.add(W,W),G=r.mul(W,K),D=r.sub(D,G),V=r.mul(W,Q),V=r.add(V,V),V=r.add(V,V),new b(D,M,V)}add(w){p(w);const{px:k,py:T,pz:B}=this,{px:N,py:$,pz:D}=w;let M=r.ZERO,V=r.ZERO,G=r.ZERO;const Q=e.a,W=r.mul(e.b,Zu);let K=r.mul(k,N),re=r.mul(T,$),q=r.mul(B,D),I=r.add(k,T),j=r.add(N,$);I=r.mul(I,j),j=r.add(K,re),I=r.sub(I,j),j=r.add(k,B);let J=r.add(N,D);return j=r.mul(j,J),J=r.add(K,q),j=r.sub(j,J),J=r.add(T,B),M=r.add($,D),J=r.mul(J,M),M=r.add(re,q),J=r.sub(J,M),G=r.mul(Q,j),M=r.mul(W,q),G=r.add(M,G),M=r.sub(re,G),G=r.add(re,G),V=r.mul(M,G),re=r.add(K,K),re=r.add(re,K),q=r.mul(Q,q),j=r.mul(W,j),re=r.add(re,q),q=r.sub(K,q),q=r.mul(Q,q),j=r.add(j,q),K=r.mul(re,j),V=r.add(V,K),K=r.mul(J,j),M=r.mul(I,M),M=r.sub(M,K),K=r.mul(I,re),G=r.mul(J,G),G=r.add(G,K),new b(M,V,G)}subtract(w){return this.add(w.negate())}is0(){return this.equals(b.ZERO)}wNAF(w){return P.wNAFCached(this,w,b.normalizeZ)}multiplyUnsafe(w){const{endo:k,n:T}=e;Ai("scalar",w,bn,T);const B=b.ZERO;if(w===bn)return B;if(this.is0()||w===ct)return this;if(!k||P.hasPrecomputes(this))return P.wNAFCachedUnsafe(this,w,b.normalizeZ);let{k1neg:N,k1:$,k2neg:D,k2:M}=k.splitScalar(w),V=B,G=B,Q=this;for(;$>bn||M>bn;)$&ct&&(V=V.add(Q)),M&ct&&(G=G.add(Q)),Q=Q.double(),$>>=ct,M>>=ct;return N&&(V=V.negate()),D&&(G=G.negate()),G=new b(r.mul(G.px,k.beta),G.py,G.pz),V.add(G)}multiply(w){const{endo:k,n:T}=e;Ai("scalar",w,ct,T);let B,N;if(k){const{k1neg:$,k1:D,k2neg:M,k2:V}=k.splitScalar(w);let{p:G,f:Q}=this.wNAF(D),{p:W,f:K}=this.wNAF(V);G=P.constTimeNegate($,G),W=P.constTimeNegate(M,W),W=new b(r.mul(W.px,k.beta),W.py,W.pz),B=G.add(W),N=Q.add(K)}else{const{p:$,f:D}=this.wNAF(w);B=$,N=D}return b.normalizeZ([B,N])[0]}multiplyAndAddUnsafe(w,k,T){const B=b.BASE,N=(D,M)=>M===bn||M===ct||!D.equals(B)?D.multiplyUnsafe(M):D.multiply(M),$=N(this,k).add(N(w,T));return $.is0()?void 0:$}toAffine(w){return d(this,w)}isTorsionFree(){const{h:w,isTorsionFree:k}=e;if(w===ct)return!0;if(k)return k(b,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:w,clearCofactor:k}=e;return w===ct?this:k?k(b,this):this.multiplyUnsafe(e.h)}toRawBytes(w=!0){return Xo("isCompressed",w),this.assertValidity(),s(b,this,w)}toHex(w=!0){return Xo("isCompressed",w),Jo(this.toRawBytes(w))}}b.BASE=new b(e.Gx,e.Gy,r.ONE),b.ZERO=new b(r.ZERO,r.ONE,r.ZERO);const{endo:E,nBitLength:A}=e,P=Vx(b,E?Math.ceil(A/2):A);return{CURVE:e,ProjectivePoint:b,normPrivateKeyToScalar:l,weierstrassEquation:o,isWithinCurveOrder:f}}function Yx(t){const e=w1(t);return ru(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Xx(t){const e=Yx(t),{Fp:r,n,nByteLength:s,nBitLength:i}=e,o=r.BYTES+1,a=2*r.BYTES+1;function c(W){return Rt(W,n)}function u(W){return sd(W,n)}const{ProjectivePoint:f,normPrivateKeyToScalar:l,weierstrassEquation:p,isWithinCurveOrder:d}=Zx({...e,toBytes(W,K,re){const q=K.toAffine(),I=r.toBytes(q.x),j=Ec;return Xo("isCompressed",re),re?j(Uint8Array.from([K.hasEvenY()?2:3]),I):j(Uint8Array.from([4]),I,r.toBytes(q.y))},fromBytes(W){const K=W.length,re=W[0],q=W.subarray(1);if(K===o&&(re===2||re===3)){const I=Ps(q);if(!_h(I,ct,r.ORDER))throw new Error("Point is not on curve");const j=p(I);let J;try{J=r.sqrt(j)}catch(F){const ne=F instanceof Error?": "+F.message:"";throw new Error("Point is not on curve"+ne)}const O=(J&ct)===ct;return(re&1)===1!==O&&(J=r.neg(J)),{x:I,y:J}}else if(K===a&&re===4){const I=r.fromBytes(q.subarray(0,r.BYTES)),j=r.fromBytes(q.subarray(r.BYTES,2*r.BYTES));return{x:I,y:j}}else{const I=o,j=a;throw new Error("invalid Point, expected length of "+I+", or uncompressed "+j+", got "+K)}}});function m(W){const K=n>>ct;return W>K}function b(W){return m(W)?c(-W):W}const E=(W,K,re)=>Ps(W.slice(K,re));class A{constructor(K,re,q){Ai("r",K,ct,n),Ai("s",re,ct,n),this.r=K,this.s=re,q!=null&&(this.recovery=q),Object.freeze(this)}static fromCompact(K){const re=s;return K=sr("compactSignature",K,re*2),new A(E(K,0,re),E(K,re,2*re))}static fromDER(K){const{r:re,s:q}=pn.toSig(sr("DER",K));return new A(re,q)}assertValidity(){}addRecoveryBit(K){return new A(this.r,this.s,K)}recoverPublicKey(K){const{r:re,s:q,recovery:I}=this,j=B(sr("msgHash",K));if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");const J=I===2||I===3?re+e.n:re;if(J>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const O=I&1?"03":"02",R=f.fromHex(O+Ku(J,r.BYTES)),F=u(J),ne=c(-j*F),ae=c(q*F),le=f.BASE.multiplyAndAddUnsafe(R,ne,ae);if(!le)throw new Error("point at infinify");return le.assertValidity(),le}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new A(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return vc(this.toDERHex())}toDERHex(){return pn.hexFromSig(this)}toCompactRawBytes(){return vc(this.toCompactHex())}toCompactHex(){const K=s;return Ku(this.r,K)+Ku(this.s,K)}}const P={isValidPrivateKey(W){try{return l(W),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const W=m1(e.n);return Dx(e.randomBytes(W),e.n)},precompute(W=8,K=f.BASE){return K._setWindowSize(W),K.multiply(BigInt(3)),K}};function S(W,K=!0){return f.fromPrivateKey(W).toRawBytes(K)}function w(W){if(typeof W=="bigint")return!1;if(W instanceof f)return!0;const re=sr("key",W).length,q=r.BYTES,I=q+1,j=2*q+1;if(!(e.allowedPrivateKeyLengths||s===I))return re===I||re===j}function k(W,K,re=!0){if(w(W)===!0)throw new Error("first arg must be private key");if(w(K)===!1)throw new Error("second arg must be public key");return f.fromHex(K).multiply(l(W)).toRawBytes(re)}const T=e.bits2int||function(W){if(W.length>8192)throw new Error("input is too large");const K=Ps(W),re=W.length*8-i;return re>0?K>>BigInt(re):K},B=e.bits2int_modN||function(W){return c(T(W))},N=tu(i);function $(W){return Ai("num < 2^"+i,W,bn,N),xa(W,s)}function D(W,K,re=M){if(["recovered","canonical"].some(oe=>oe in re))throw new Error("sign() legacy options not supported");const{hash:q,randomBytes:I}=e;let{lowS:j,prehash:J,extraEntropy:O}=re;j==null&&(j=!0),W=sr("msgHash",W),f0(re),J&&(W=sr("prehashed msgHash",q(W)));const R=B(W),F=l(K),ne=[$(F),$(R)];if(O!=null&&O!==!1){const oe=O===!0?I(r.BYTES):O;ne.push(sr("extraEntropy",oe))}const ae=Ec(...ne),le=R;function ue(oe){const ie=T(oe);if(!d(ie))return;const me=u(ie),be=f.BASE.multiply(ie).toAffine(),we=c(be.x);if(we===bn)return;const ke=c(me*c(le+we*F));if(ke===bn)return;let tt=(be.x===we?0:2)|Number(be.y&ct),Oe=ke;return j&&m(ke)&&(Oe=b(ke),tt^=1),new A(we,Oe,tt)}return{seed:ae,k2sig:ue}}const M={lowS:e.lowS,prehash:!1},V={lowS:e.lowS,prehash:!1};function G(W,K,re=M){const{seed:q,k2sig:I}=D(W,K,re),j=e;return Cx(j.hash.outputLen,j.nByteLength,j.hmac)(q,I)}f.BASE._setWindowSize(8);function Q(W,K,re,q=V){var tt;const I=W;K=sr("msgHash",K),re=sr("publicKey",re);const{lowS:j,prehash:J,format:O}=q;if(f0(q),"strict"in q)throw new Error("options.strict was renamed to lowS");if(O!==void 0&&O!=="compact"&&O!=="der")throw new Error("format must be compact or der");const R=typeof I=="string"||Aa(I),F=!R&&!O&&typeof I=="object"&&I!==null&&typeof I.r=="bigint"&&typeof I.s=="bigint";if(!R&&!F)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let ne,ae;try{if(F&&(ne=new A(I.r,I.s)),R){try{O!=="compact"&&(ne=A.fromDER(I))}catch(Oe){if(!(Oe instanceof pn.Err))throw Oe}!ne&&O!=="der"&&(ne=A.fromCompact(I))}ae=f.fromHex(re)}catch{return!1}if(!ne||j&&ne.hasHighS())return!1;J&&(K=e.hash(K));const{r:le,s:ue}=ne,oe=B(K),ie=u(ue),me=c(oe*ie),be=c(le*ie),we=(tt=f.BASE.multiplyAndAddUnsafe(ae,me,be))==null?void 0:tt.toAffine();return we?c(we.x)===le:!1}return{CURVE:e,getPublicKey:S,getSharedSecret:k,sign:G,verify:Q,ProjectivePoint:f,Signature:A,utils:P}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Jx(t){return{hash:t,hmac:(e,...r)=>Xg(t,e,Nv(...r)),randomBytes:Mv}}function Qx(t,e){const r=n=>Xx({...t,...Jx(n)});return{...r(e),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const v1=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),l0=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),e3=BigInt(0),t3=BigInt(1),od=BigInt(2),d0=(t,e)=>(t+e/od)/e;function r3(t){const e=v1,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,f=u*u*t%e,l=tr(f,r,e)*f%e,p=tr(l,r,e)*f%e,d=tr(p,od,e)*u%e,m=tr(d,s,e)*d%e,b=tr(m,i,e)*m%e,E=tr(b,a,e)*b%e,A=tr(E,c,e)*E%e,P=tr(A,a,e)*b%e,S=tr(P,r,e)*f%e,w=tr(S,o,e)*m%e,k=tr(w,n,e)*u%e,T=tr(k,od,e);if(!ad.eql(ad.sqr(T),t))throw new Error("Cannot find square root");return T}const ad=Ph(v1,void 0,void 0,{sqrt:r3}),E1=Qx({a:e3,b:BigInt(7),Fp:ad,n:l0,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=l0,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-t3*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=d0(i*t,e),c=d0(-n*t,e);let u=Rt(t-a*r-c*s,e),f=Rt(-a*n-c*i,e);const l=u>o,p=f>o;if(l&&(u=e-u),p&&(f=e-f),u>o||f>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:l,k1:u,k2neg:p,k2:f}}}},Sb),n3=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:E1},Symbol.toStringTag,{value:"Module"}));function s3({r:t,s:e,to:r="hex",v:n,yParity:s}){const i=(()=>{if(s===0||s===1)return s;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),o=`0x${new E1.Signature(ut(t),ut(e)).toCompactHex()}${i===0?"1b":"1c"}`;return r==="hex"?o:Jr(o)}async function nu(t,e){var a,c,u,f,l,p;const{address:r,hash:n,erc6492VerifierAddress:s=e.universalSignatureVerifierAddress??((u=(c=(a=t.chain)==null?void 0:a.contracts)==null?void 0:c.erc6492Verifier)==null?void 0:u.address),multicallAddress:i=e.multicallAddress??((p=(l=(f=t.chain)==null?void 0:f.contracts)==null?void 0:l.multicall3)==null?void 0:p.address)}=e,o=(()=>{const d=e.signature;return Pr(d)?d:typeof d=="object"&&"r"in d&&"s"in d?s3(d):et(d)})();try{return cx(o)?await i3(t,{...e,multicallAddress:i,signature:o}):await o3(t,{...e,verifierAddress:s,signature:o})}catch(d){try{if(Gi(Md(r),await pb({hash:n,signature:o})))return!0}catch{}if(d instanceof Hs)return!1;throw d}}async function i3(t,e){var E;const{address:r,blockNumber:n,blockTag:s,hash:i,multicallAddress:o}=e,{authorization:a,data:c,signature:u,to:f}=ax(e.signature);if(await Wl(t,{address:r,blockNumber:n,blockTag:s})===$r(["0xef0100",a.address]))return await a3(t,{address:r,blockNumber:n,blockTag:s,hash:i,signature:u});const p={address:a.address,chainId:Number(a.chainId),nonce:Number(a.nonce),r:Z(a.r,{size:32}),s:Z(a.s,{size:32}),yParity:a.yParity};if(!await rA({address:r,authorization:p}))throw new Hs;const m=await se(t,hr,"readContract")({...o?{address:o}:{code:ch},authorizationList:[p],abi:bc,blockNumber:n,blockTag:"pending",functionName:"aggregate3",args:[[...c?[{allowFailure:!0,target:f??r,callData:c}]:[],{allowFailure:!0,target:r,callData:Jt({abi:Wb,functionName:"isValidSignature",args:[i,u]})}]]}),b=(E=m[m.length-1])==null?void 0:E.returnData;if(b!=null&&b.startsWith("0x1626ba7e"))return!0;throw new Hs}async function o3(t,e){const{address:r,factory:n,factoryData:s,hash:i,signature:o,verifierAddress:a,...c}=e,u=await(async()=>!n&&!s||Px(o)?o:_x({data:s,signature:o,to:n}))(),f=a?{to:a,data:Jt({abi:Dp,functionName:"isValidSig",args:[r,i,u]}),...c}:{data:Kc({abi:Dp,args:[r,i,u],bytecode:YE}),...c},{data:l}=await se(t,wa,"call")(f).catch(p=>{throw p instanceof db?new Hs:p});if(mv(l??"0x0"))return!0;throw new Hs}async function a3(t,e){const{address:r,blockNumber:n,blockTag:s,hash:i,signature:o}=e;if((await se(t,hr,"readContract")({address:r,abi:Wb,args:[i,o],blockNumber:n,blockTag:s,functionName:"isValidSignature"}).catch(c=>{throw c instanceof hb?new Hs:c})).startsWith("0x1626ba7e"))return!0;throw new Hs}class Hs extends Error{}async function c3(t,{address:e,message:r,factory:n,factoryData:s,signature:i,...o}){const a=kg(r);return nu(t,{address:e,factory:n,factoryData:s,hash:a,signature:i,...o})}async function u3(t,e){const{address:r,factory:n,factoryData:s,signature:i,message:o,primaryType:a,types:c,domain:u,...f}=e,l=TA({message:o,primaryType:a,types:c,domain:u});return nu(t,{address:r,factory:n,factoryData:s,hash:l,signature:i,...f})}function S1(t,{emitOnBegin:e=!1,emitMissed:r=!1,onBlockNumber:n,onError:s,poll:i,pollingInterval:o=t.pollingInterval}){const a=typeof i<"u"?i:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc"));let c;return a?(()=>{const l=Qe(["watchBlockNumber",t.uid,e,r,o]);return Tn(l,{onBlockNumber:n,onError:s},p=>Ki(async()=>{var d;try{const m=await se(t,va,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(m===c)return;if(m-c>1&&r)for(let b=c+1n;b<m;b++)p.onBlockNumber(b,c),c=b}(c===void 0||m>c)&&(p.onBlockNumber(m,c),c=m)}catch(m){(d=p.onError)==null||d.call(p,m)}},{emitOnBegin:e,interval:o}))})():(()=>{const l=Qe(["watchBlockNumber",t.uid,e,r]);return Tn(l,{onBlockNumber:n,onError:s},p=>{let d=!0,m=()=>d=!1;return(async()=>{try{const b=(()=>{if(t.transport.type==="fallback"){const A=t.transport.transports.find(P=>P.config.type==="webSocket"||P.config.type==="ipc");return A?A.value:t.transport}return t.transport})(),{unsubscribe:E}=await b.subscribe({params:["newHeads"],onData(A){var S;if(!d)return;const P=ut((S=A.result)==null?void 0:S.number);p.onBlockNumber(P,c),c=P},onError(A){var P;(P=p.onError)==null||P.call(p,A)}});m=E,d||m()}catch(b){s==null||s(b)}})(),()=>m()})})()}async function f3(t,e){const{checkReplacement:r=!0,confirmations:n=1,hash:s,onReplaced:i,retryCount:o=6,retryDelay:a=({count:k})=>~~(1<<k)*200,timeout:c=18e4}=e,u=Qe(["waitForTransactionReceipt",t.uid,s]),f=(()=>{var k;return e.pollingInterval?e.pollingInterval:(k=t.chain)!=null&&k.experimental_preconfirmationTime?t.chain.experimental_preconfirmationTime:t.pollingInterval})();let l,p,d,m=!1,b,E;const{promise:A,resolve:P,reject:S}=uh(),w=c?setTimeout(()=>{E==null||E(),b==null||b(),S(new $5({hash:s}))},c):void 0;return b=Tn(u,{onReplaced:i,resolve:P,reject:S},async k=>{if(d=await se(t,sc,"getTransactionReceipt")({hash:s}).catch(()=>{}),d&&n<=1){clearTimeout(w),k.resolve(d),b==null||b();return}E=se(t,S1,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:f,async onBlockNumber(T){const B=$=>{clearTimeout(w),E==null||E(),$(),b==null||b()};let N=T;if(!m)try{if(d){if(n>1&&(!d.blockNumber||N-d.blockNumber+1n<n))return;B(()=>k.resolve(d));return}if(r&&!l&&(m=!0,await gc(async()=>{l=await se(t,xh,"getTransaction")({hash:s}),l.blockNumber&&(N=l.blockNumber)},{delay:a,retryCount:o}),m=!1),d=await se(t,sc,"getTransactionReceipt")({hash:s}),n>1&&(!d.blockNumber||N-d.blockNumber+1n<n))return;B(()=>k.resolve(d))}catch($){if($ instanceof fb||$ instanceof lb){if(!l){m=!1;return}try{p=l,m=!0;const D=await gc(()=>se(t,Zr,"getBlock")({blockNumber:N,includeTransactions:!0}),{delay:a,retryCount:o,shouldRetry:({error:G})=>G instanceof bb});m=!1;const M=D.transactions.find(({from:G,nonce:Q})=>G===p.from&&Q===p.nonce);if(!M||(d=await se(t,sc,"getTransactionReceipt")({hash:M.hash}),n>1&&(!d.blockNumber||N-d.blockNumber+1n<n)))return;let V="replaced";M.to===p.to&&M.value===p.value&&M.input===p.input?V="repriced":M.from===M.to&&M.value===0n&&(V="cancelled"),B(()=>{var G;(G=k.onReplaced)==null||G.call(k,{reason:V,replacedTransaction:p,transaction:M,transactionReceipt:d}),k.resolve(d)})}catch(D){B(()=>k.reject(D))}}else B(()=>k.reject($))}}})}),A}function l3(t,{blockTag:e=t.experimental_blockTag??"latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:s,onError:i,includeTransactions:o,poll:a,pollingInterval:c=t.pollingInterval}){const u=typeof a<"u"?a:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")),f=o??!1;let l;return u?(()=>{const m=Qe(["watchBlocks",t.uid,e,r,n,f,c]);return Tn(m,{onBlock:s,onError:i},b=>Ki(async()=>{var E;try{const A=await se(t,Zr,"getBlock")({blockTag:e,includeTransactions:f});if(A.number!==null&&(l==null?void 0:l.number)!=null){if(A.number===l.number)return;if(A.number-l.number>1&&r)for(let P=(l==null?void 0:l.number)+1n;P<A.number;P++){const S=await se(t,Zr,"getBlock")({blockNumber:P,includeTransactions:f});b.onBlock(S,l),l=S}}((l==null?void 0:l.number)==null||e==="pending"&&(A==null?void 0:A.number)==null||A.number!==null&&A.number>l.number)&&(b.onBlock(A,l),l=A)}catch(A){(E=b.onError)==null||E.call(b,A)}},{emitOnBegin:n,interval:c}))})():(()=>{let m=!0,b=!0,E=()=>m=!1;return(async()=>{try{n&&se(t,Zr,"getBlock")({blockTag:e,includeTransactions:f}).then(S=>{m&&b&&(s(S,void 0),b=!1)}).catch(i);const A=(()=>{if(t.transport.type==="fallback"){const S=t.transport.transports.find(w=>w.config.type==="webSocket"||w.config.type==="ipc");return S?S.value:t.transport}return t.transport})(),{unsubscribe:P}=await A.subscribe({params:["newHeads"],async onData(S){var k;if(!m)return;const w=await se(t,Zr,"getBlock")({blockNumber:(k=S.result)==null?void 0:k.number,includeTransactions:f}).catch(()=>{});m&&(s(w,l),b=!1,l=w)},onError(S){i==null||i(S)}});E=P,m||E()}catch(A){i==null||i(A)}})(),()=>E()})()}function d3(t,{address:e,args:r,batch:n=!0,event:s,events:i,fromBlock:o,onError:a,onLogs:c,poll:u,pollingInterval:f=t.pollingInterval,strict:l}){const p=typeof u<"u"?u:typeof o=="bigint"?!0:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")),d=l??!1;return p?(()=>{const E=Qe(["watchEvent",e,r,n,t.uid,s,f,o]);return Tn(E,{onLogs:c,onError:a},A=>{let P;o!==void 0&&(P=o-1n);let S,w=!1;const k=Ki(async()=>{var T;if(!w){try{S=await se(t,bg,"createEventFilter")({address:e,args:r,event:s,events:i,strict:d,fromBlock:o})}catch{}w=!0;return}try{let B;if(S)B=await se(t,Zc,"getFilterChanges")({filter:S});else{const N=await se(t,va,"getBlockNumber")({});P&&P!==N?B=await se(t,ih,"getLogs")({address:e,args:r,event:s,events:i,fromBlock:P+1n,toBlock:N}):B=[],P=N}if(B.length===0)return;if(n)A.onLogs(B);else for(const N of B)A.onLogs([N])}catch(B){S&&B instanceof Ms&&(w=!1),(T=A.onError)==null||T.call(A,B)}},{emitOnBegin:!0,interval:f});return async()=>{S&&await se(t,Yc,"uninstallFilter")({filter:S}),k()}})})():(()=>{let E=!0,A=()=>E=!1;return(async()=>{try{const P=(()=>{if(t.transport.type==="fallback"){const T=t.transport.transports.find(B=>B.config.type==="webSocket"||B.config.type==="ipc");return T?T.value:t.transport}return t.transport})(),S=i??(s?[s]:void 0);let w=[];S&&(w=[S.flatMap(B=>pa({abi:[B],eventName:B.name,args:r}))],s&&(w=w[0]));const{unsubscribe:k}=await P.subscribe({params:["logs",{address:e,topics:w}],onData(T){var N;if(!E)return;const B=T.result;try{const{eventName:$,args:D}=nh({abi:S??[],data:B.data,topics:B.topics,strict:d}),M=kn(B,{args:D,eventName:$});c([M])}catch($){let D,M;if($ instanceof Po||$ instanceof $c){if(l)return;D=$.abiItem.name,M=(N=$.abiItem.inputs)==null?void 0:N.some(G=>!("name"in G&&G.name))}const V=kn(B,{args:M?[]:{},eventName:D});c([V])}},onError(T){a==null||a(T)}});A=k,E||A()}catch(P){a==null||a(P)}})(),()=>A()})()}function h3(t,{batch:e=!0,onError:r,onTransactions:n,poll:s,pollingInterval:i=t.pollingInterval}){return(typeof s<"u"?s:t.transport.type!=="webSocket"&&t.transport.type!=="ipc")?(()=>{const u=Qe(["watchPendingTransactions",t.uid,e,i]);return Tn(u,{onTransactions:n,onError:r},f=>{let l;const p=Ki(async()=>{var d;try{if(!l)try{l=await se(t,gg,"createPendingTransactionFilter")({});return}catch(b){throw p(),b}const m=await se(t,Zc,"getFilterChanges")({filter:l});if(m.length===0)return;if(e)f.onTransactions(m);else for(const b of m)f.onTransactions([b])}catch(m){(d=f.onError)==null||d.call(f,m)}},{emitOnBegin:!0,interval:i});return async()=>{l&&await se(t,Yc,"uninstallFilter")({filter:l}),p()}})})():(()=>{let u=!0,f=()=>u=!1;return(async()=>{try{const{unsubscribe:l}=await t.transport.subscribe({params:["newPendingTransactions"],onData(p){if(!u)return;const d=p.result;n([d])},onError(p){r==null||r(p)}});f=l,u||f()}catch(l){r==null||r(l)}})(),()=>f()})()}function p3(t){var l,p,d;const{scheme:e,statement:r,...n}=((l=t.match(y3))==null?void 0:l.groups)??{},{chainId:s,expirationTime:i,issuedAt:o,notBefore:a,requestId:c,...u}=((p=t.match(m3))==null?void 0:p.groups)??{},f=(d=t.split("Resources:")[1])==null?void 0:d.split(`
|
|
46
|
+
- `).slice(1);return{...n,...u,...s?{chainId:Number(s)}:{},...i?{expirationTime:new Date(i)}:{},...o?{issuedAt:new Date(o)}:{},...a?{notBefore:new Date(a)}:{},...c?{requestId:c}:{},...f?{resources:f}:{},...e?{scheme:e}:{},...r?{statement:r}:{}}}const y3=/^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?<address>0x[a-fA-F0-9]{40})\n\n(?:(?<statement>.*)\n\n)?/,m3=/(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.+))?/;function b3(t){const{address:e,domain:r,message:n,nonce:s,scheme:i,time:o=new Date}=t;if(r&&n.domain!==r||s&&n.nonce!==s||i&&n.scheme!==i||n.expirationTime&&o>=n.expirationTime||n.notBefore&&o<n.notBefore)return!1;try{if(!n.address||!at(n.address,{strict:!1})||e&&!Gi(n.address,e))return!1}catch{return!1}return!0}async function g3(t,e){const{address:r,domain:n,message:s,nonce:i,scheme:o,signature:a,time:c=new Date,...u}=e,f=p3(s);if(!f.address||!b3({address:r,domain:n,message:f,nonce:i,scheme:o,time:c}))return!1;const p=kg(s);return nu(t,{address:f.address,hash:p,signature:a,...u})}function w3(t){return{call:e=>wa(t,e),createAccessList:e=>mg(t,e),createBlockFilter:()=>NS(t),createContractEventFilter:e=>Dd(t,e),createEventFilter:e=>bg(t,e),createPendingTransactionFilter:()=>gg(t),estimateContractGas:e=>Cb(t,e),estimateGas:e=>rh(t,e),getBalance:e=>US(t,e),getBlobBaseFee:()=>MS(t),getBlock:e=>Zr(t,e),getBlockNumber:e=>va(t,e),getBlockTransactionCount:e=>FS(t,e),getBytecode:e=>Wl(t,e),getChainId:()=>qi(t),getCode:e=>Wl(t,e),getContractEvents:e=>oh(t,e),getEip712Domain:e=>LS(t,e),getEnsAddress:e=>wS(t,e),getEnsAvatar:e=>CS(t,e),getEnsName:e=>$S(t,e),getEnsResolver:e=>RS(t,e),getEnsText:e=>yg(t,e),getFeeHistory:e=>zS(t,e),estimateFeesPerGas:e=>rE(t,e),getFilterChanges:e=>Zc(t,e),getFilterLogs:e=>VS(t,e),getGasPrice:()=>Yd(t),getLogs:e=>ih(t,e),getProof:e=>dx(t,e),estimateMaxPriorityFeePerGas:e=>tE(t,e),getStorageAt:e=>hx(t,e),getTransaction:e=>xh(t,e),getTransactionConfirmations:e=>px(t,e),getTransactionCount:e=>Xd(t,e),getTransactionReceipt:e=>sc(t,e),multicall:e=>yx(t,e),prepareTransactionRequest:e=>qc(t,e),readContract:e=>hr(t,e),sendRawTransaction:e=>fh(t,e),simulate:e=>ed(t,e),simulateBlocks:e=>ed(t,e),simulateCalls:e=>kx(t,e),simulateContract:e=>Qb(t,e),verifyHash:e=>nu(t,e),verifyMessage:e=>c3(t,e),verifySiweMessage:e=>g3(t,e),verifyTypedData:e=>u3(t,e),uninstallFilter:e=>Yc(t,e),waitForTransactionReceipt:e=>f3(t,e),watchBlocks:e=>l3(t,e),watchBlockNumber:e=>S1(t,e),watchContractEvent:e=>eg(t,e),watchEvent:e=>d3(t,e),watchPendingTransactions:e=>h3(t,e)}}function v3(t){const{key:e="public",name:r="Public Client"}=t;return fg({...t,key:e,name:r,type:"publicClient"}).extend(w3)}async function E3(t,{chain:e}){const{id:r,name:n,nativeCurrency:s,rpcUrls:i,blockExplorers:o}=e;await t.request({method:"wallet_addEthereumChain",params:[{chainId:Z(r),chainName:n,nativeCurrency:s,rpcUrls:i.default.http,blockExplorerUrls:o?Object.values(o).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}function S3(t,e){const{abi:r,args:n,bytecode:s,...i}=e,o=Kc({abi:r,args:n,bytecode:s});return Xc(t,{...i,...i.authorizationList?{to:null}:{},data:o})}async function A3(t){var r;return((r=t.account)==null?void 0:r.type)==="local"?[t.account.address]:(await t.request({method:"eth_accounts"},{dedupe:!0})).map(n=>da(n))}async function x3(t,e={}){const{account:r=t.account,chainId:n}=e,s=r?Ze(r):void 0,i=n?[s==null?void 0:s.address,[Z(n)]]:[s==null?void 0:s.address],o=await t.request({method:"wallet_getCapabilities",params:i}),a={};for(const[c,u]of Object.entries(o)){a[Number(c)]={};for(let[f,l]of Object.entries(u))f==="addSubAccount"&&(f="unstable_addSubAccount"),a[Number(c)][f]=l}return typeof n=="number"?a[n]:a}async function k3(t){return await t.request({method:"wallet_getPermissions"},{dedupe:!0})}async function A1(t,e){var c;const{account:r=t.account,chainId:n,nonce:s}=e;if(!r)throw new Js({docsPath:"/docs/eip7702/prepareAuthorization"});const i=Ze(r),o=(()=>{if(e.executor)return e.executor==="self"?e.executor:Ze(e.executor)})(),a={address:e.contractAddress??e.address,chainId:n,nonce:s};return typeof a.chainId>"u"&&(a.chainId=((c=t.chain)==null?void 0:c.id)??await se(t,qi,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await se(t,Xd,"getTransactionCount")({address:i.address,blockTag:"pending"}),(o==="self"||o!=null&&o.address&&Gi(o.address,i.address))&&(a.nonce+=1)),a}async function T3(t){return(await t.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>Md(r))}async function _3(t,e){return t.request({method:"wallet_requestPermissions",params:[e]},{retryCount:0})}async function P3(t,e){const{id:r}=e;await t.request({method:"wallet_showCallsStatus",params:[r]})}async function I3(t,e){const{account:r=t.account}=e;if(!r)throw new Js({docsPath:"/docs/eip7702/signAuthorization"});const n=Ze(r);if(!n.signAuthorization)throw new nc({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});const s=await A1(t,e);return n.signAuthorization(s)}async function O3(t,{account:e=t.account,message:r}){if(!e)throw new Js({docsPath:"/docs/actions/wallet/signMessage"});const n=Ze(e);if(n.signMessage)return n.signMessage({message:r});const s=typeof r=="string"?Bi(r):r.raw instanceof Uint8Array?Bt(r.raw):r.raw;return t.request({method:"personal_sign",params:[s,n.address]},{retryCount:0})}async function B3(t,e){var u,f,l,p;const{account:r=t.account,chain:n=t.chain,...s}=e;if(!r)throw new Js({docsPath:"/docs/actions/wallet/signTransaction"});const i=Ze(r);Ys({account:i,...e});const o=await se(t,qi,"getChainId")({});n!==null&&tg({currentChainId:o,chain:n});const a=(n==null?void 0:n.formatters)||((u=t.chain)==null?void 0:u.formatters),c=((f=a==null?void 0:a.transactionRequest)==null?void 0:f.format)||Vi;return i.signTransaction?i.signTransaction({...s,chainId:o},{serializer:(p=(l=t.chain)==null?void 0:l.serializers)==null?void 0:p.transaction}):await t.request({method:"eth_signTransaction",params:[{...c(s),chainId:Z(o),from:i.address}]},{retryCount:0})}async function C3(t,e){const{account:r=t.account,domain:n,message:s,primaryType:i}=e;if(!r)throw new Js({docsPath:"/docs/actions/wallet/signTypedData"});const o=Ze(r),a={EIP712Domain:_g({domain:n}),...e.types};if(Tg({domain:n,message:s,primaryType:i,types:a}),o.signTypedData)return o.signTypedData({domain:n,message:s,primaryType:i,types:a});const c=xA({domain:n,message:s,primaryType:i,types:a});return t.request({method:"eth_signTypedData_v4",params:[o.address,c]},{retryCount:0})}async function $3(t,{id:e}){await t.request({method:"wallet_switchEthereumChain",params:[{chainId:Z(e)}]},{retryCount:0})}async function R3(t,e){return await t.request({method:"wallet_watchAsset",params:e},{retryCount:0})}function N3(t){return{addChain:e=>E3(t,e),deployContract:e=>S3(t,e),getAddresses:()=>A3(t),getCallsStatus:e=>cg(t,e),getCapabilities:e=>x3(t,e),getChainId:()=>qi(t),getPermissions:()=>k3(t),prepareAuthorization:e=>A1(t,e),prepareTransactionRequest:e=>qc(t,e),requestAddresses:()=>T3(t),requestPermissions:e=>_3(t,e),sendCalls:e=>lS(t,e),sendRawTransaction:e=>fh(t,e),sendTransaction:e=>Xc(t,e),showCallsStatus:e=>P3(t,e),signAuthorization:e=>I3(t,e),signMessage:e=>O3(t,e),signTransaction:e=>B3(t,e),signTypedData:e=>C3(t,e),switchChain:e=>$3(t,e),waitForCallsStatus:e=>dS(t,e),watchAsset:e=>R3(t,e),writeContract:e=>ng(t,e)}}function Yu(t){const{key:e="wallet",name:r="Wallet Client",transport:n}=t;return fg({...t,key:e,name:r,transport:n,type:"walletClient"}).extend(N3)}function x1({key:t,methods:e,name:r,request:n,retryCount:s=3,retryDelay:i=150,timeout:o,type:a},c){const u=ug();return{config:{key:t,methods:e,name:r,request:n,retryCount:s,retryDelay:i,timeout:o,type:a},request:sA(n,{methods:e,retryCount:s,retryDelay:i,uid:u}),value:c}}function h0(t,e={}){const{key:r="custom",methods:n,name:s="Custom Provider",retryDelay:i}=e;return({retryCount:o})=>x1({key:r,methods:n,name:s,request:t.request.bind(t),retryCount:e.retryCount??o,retryDelay:i,type:"custom"})}class U3 extends L{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 k1(t,e={}){const{batch:r,fetchFn:n,fetchOptions:s,key:i="http",methods:o,name:a="HTTP JSON-RPC",onFetchRequest:c,onFetchResponse:u,retryDelay:f,raw:l}=e;return({chain:p,retryCount:d,timeout:m})=>{const{batchSize:b=1e3,wait:E=0}=typeof r=="object"?r:{},A=e.retryCount??d,P=m??e.timeout??1e4,S=p==null?void 0:p.rpcUrls.default.http[0];if(!S)throw new U3;const w=gA(S,{fetchFn:n,fetchOptions:s,onRequest:c,onResponse:u,timeout:P});return x1({key:i,methods:o,name:a,async request({method:k,params:T}){const B={method:k,params:T},{schedule:N}=Xb({id:S,wait:E,shouldSplitBatch(V){return V.length>b},fn:V=>w.request({body:V}),sort:(V,G)=>V.id-G.id}),$=async V=>r?N(V):[await w.request({body:V})],[{error:D,result:M}]=await $(B);if(l)return{error:D,result:M};if(D)throw new Vd({body:B,error:D,url:S});return M},retryCount:A,retryDelay:f,timeout:P,type:"http"},{fetchOptions:s,url:S})}}const ic={mainnet:{baseurl:"https://api.garden.finance",auth:"https://api.garden.finance/auth",info:"https://api.garden.finance/info",relayer:"https://relayer.garden.finance"},testnet:{baseurl:"https://testnet.api.garden.finance",auth:"https://testnet.api.garden.finance/auth",info:"https://testnet.api.garden.finance/info",relayer:"https://testnet.api.garden.finance/relayer"},localnet:{baseurl:"",auth:"",info:"",relayer:""}},Qo={[g.Network.MAINNET]:{chainId:"0x534e5f4d41494e",nodeUrl:"https://starknet-mainnet.public.blastapi.io/rpc/v0_8"},[g.Network.TESTNET]:{chainId:"0x534e5f5345504f4c4941",nodeUrl:"https://starknet-sepolia.public.blastapi.io/rpc/v0_8"},[g.Network.LOCALNET]:{chainId:"",nodeUrl:""}},T1={[g.Network.MAINNET]:"9cBuPNiHXiMNg3Fin8xLCGJQBTXjYQTFtyaFQv2uiM1H",[g.Network.TESTNET]:"ANUVKxeqaec3bf4DVPqLTnG1PT3Fng56wPcE7LXAb46Q",[g.Network.LOCALNET]:"AKnL4NNf3DGWZJS6cPknBuEGnVsV4A4m5tgebLHaRSZ9"},cd={mainnet:{native:"2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",spl:"gdnvdMCHJgnidtU7SL8RkRshHPvDJU1pdfZEpoLvqdU"},staging:{native:"6eksgdCnSjUaGQWZ6iYvauv1qzvYPF33RTGTM1ZuyENx",spl:"2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC"}},ud={[g.Network.TESTNET]:{packageId:"0x99865b03dd1bc03d0a6a805c454ea257c464f7abcccae9cd4b621b91e7ca04de",moduleName:"AtomicSwap"},[g.Network.MAINNET]:{packageId:"0xbfb5728aab0dd117747ef4574af6d3540ea6093109c22856e3ae201dfd58c0fc",moduleName:"AtomicSwap"},[g.Network.LOCALNET]:{packageId:"",moduleName:""}},_1={asset:Y.ChainAsset.from(Y.Assets.base.cBBTC)};var xi=(t=>(t.SLOW="SLOW",t.MEDIUM="MEDIUM",t.FAST="FAST",t))(xi||{}),Tr=(t=>(t.Mainnet="Mainnet",t.Testnet="Testnet",t.Regtest="Regtest",t))(Tr||{}),oc=(t=>(t.ALL="ALL",t.IN="IN",t.OUT="OUT",t))(oc||{});const M3={SLOW:"economyFee",MEDIUM:"hourFee",FAST:"fastestFee"};function fd(t){const e=typeof t=="string"?t:t.network,r=e===g.Network.MAINNET?ic.mainnet:g.Network.TESTNET?ic.testnet:ic.localnet;return{api:typeof t=="string"?r:{...r,...t},network:e}}function F3(t){return typeof t=="string"&&(t=Buffer.from(t,"hex")),t.length===32?t:t.subarray(1,33)}function p0(t,e){if(!t)throw new Error(e)}function j3(t){return Buffer.concat([Uint8Array.from([192]),L3(t)])}function L3(t){const e=hp.encodingLength(t.length),r=Buffer.allocUnsafe(e);return hp.encode(t.length,r),Buffer.concat([r,t])}function D3(t,e){if(t.compare(e)>0){const r=t;t=e,e=r}return[t,e]}const je=t=>t.length===64?t:t.slice(2),H3=t=>{if(!t)return!1;try{const e=Buffer.from(t,"hex");return fr.isPoint(e)}catch{return!1}},P1=(t,e,r,n)=>t+":"+e.toLowerCase()+"::"+r+":"+n.toLowerCase();function z3(t,e){if(!t)return!1;const r=e===g.Environment.MAINNET?Ae.networks.bitcoin:e===g.Environment.TESTNET?Ae.networks.testnet:Ae.networks.regtest;if(!r)return!1;Ae.initEccLib(fr);try{return Ae.address.toOutputScript(t,r),!0}catch{return!1}}function no(t,e){const r=[];for(let n=0;n<e;n++)r.push(t);return r}const V3=t=>{switch(t){case g.Network.MAINNET:return Tr.Mainnet;case g.Network.TESTNET:return Tr.Testnet;case g.Network.LOCALNET:return Tr.Regtest;default:throw new Error(`Invalid bitcoin network ${t}`)}},q3=t=>{switch(t){case g.Network.MAINNET:return Ae.networks.bitcoin;case g.Network.TESTNET:return Ae.networks.testnet;case g.Network.LOCALNET:return Ae.networks.regtest;default:throw new Error(`Invalid bitcoin network ${t}`)}},G3=t=>{const e=t.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(e)},y0=t=>{if(typeof t=="object"&&"r"in t&&"s"in t)return g.Ok([t.r.toString(),t.s.toString()]);if(Array.isArray(t)){const e=t.map(r=>typeof r=="string"&&r.startsWith("0x")&&G3(r)?BigInt(r).toString():r);return g.Ok(e)}return g.Err("Invalid signature format")};function ld(t){return Buffer.from(t,"hex").reverse()}function dd(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"}const Da=async(t,e)=>{const r=Date.now(),n=3e4,s=2e3;for(;Date.now()-r<n;){const i=await t.getLatestBlockhash(),o=await t.confirmTransaction({signature:e,blockhash:i.blockhash,lastValidBlockHeight:i.lastValidBlockHeight},"confirmed");if(o.value&&o.value.err==null)return console.log("Tx Confirmed ✅",e),!0;console.log("Tx not confirmed yet. Retrying in 2 seconds..."),await new Promise(a=>setTimeout(a,s))}return!1},Ih=async(t,e)=>{var a,c;const r=await g.Fetcher.get(e+"/v2/assets");if(r.error)return g.Err("Failed to fetch asset info: "+r.error);const s=(r.result||[]).find(u=>u.id===t);if(!s)return g.Err(`Asset info not found for asset id: ${t}`);const i=((a=s.htlc)==null?void 0:a.address)||"",o=((c=s.token)==null?void 0:c.address)||"";return g.Ok({htlcAddress:i,tokenAddress:o})},m0=t=>{if(t==null||t.includes("."))return g.Err("Invalid amount ",t);const e=new i6.BigNumber(t);return!e.isInteger()||e.isNaN()||e.lt(0)||e.isLessThanOrEqualTo(0)?g.Err("Invalid amount ",t):g.Ok(e)},W3=t=>(t??[]).map(e=>({fee:e.fee,address:e.address,asset:e.asset??_1.asset})),K3=async(t,e)=>{const r={[Y.BlockchainType.evm]:{htlc:e.evm,name:"EVM"},[Y.BlockchainType.solana]:{htlc:e.solana,name:"Solana"},[Y.BlockchainType.starknet]:{htlc:e.starknet,name:"Starknet"},[Y.BlockchainType.sui]:{htlc:e.sui,name:"Sui"},[Y.BlockchainType.bitcoin]:{htlc:e.bitcoin,name:"Bitcoin"}};if(t===Y.BlockchainType.bitcoin)return g.Ok(void 0);const n=r[t];return n?n.htlc?g.Ok(void 0):g.Err(`${n.name} HTLC is required for swap initiation. Please provide ${n.name.toLowerCase()}HTLC when initializing garden.`):g.Err(`Unsupported blockchain type for swap initiation: ${t}`)},Z3=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),Y3=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),X3=Buffer.concat([Z3,Y3]),J3=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),b0={failedToCreateInternalPubkey:"failed to create internal pubkey"};function g0(){const t=pe.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),e=fr.pointMultiply(Buffer.concat([Buffer.from("04","hex"),X3]),t);if(!e)throw new Error(b0.failedToCreateInternalPubkey);const r=fr.pointAdd(J3,e);if(!r)throw new Error(b0.failedToCreateInternalPubkey);return F3(Buffer.from(r))}var Qr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function I1(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}),r}var Le={},Et={},Qs={},su={};su.byteLength=tk;su.toByteArray=nk;su.fromByteArray=ok;var Wr=[],ir=[],Q3=typeof Uint8Array<"u"?Uint8Array:Array,Xu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var oi=0,ek=Xu.length;oi<ek;++oi)Wr[oi]=Xu[oi],ir[Xu.charCodeAt(oi)]=oi;ir[45]=62;ir[95]=63;function O1(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function tk(t){var e=O1(t),r=e[0],n=e[1];return(r+n)*3/4-n}function rk(t,e,r){return(e+r)*3/4-r}function nk(t){var e,r=O1(t),n=r[0],s=r[1],i=new Q3(rk(t,n,s)),o=0,a=s>0?n-4:n,c;for(c=0;c<a;c+=4)e=ir[t.charCodeAt(c)]<<18|ir[t.charCodeAt(c+1)]<<12|ir[t.charCodeAt(c+2)]<<6|ir[t.charCodeAt(c+3)],i[o++]=e>>16&255,i[o++]=e>>8&255,i[o++]=e&255;return s===2&&(e=ir[t.charCodeAt(c)]<<2|ir[t.charCodeAt(c+1)]>>4,i[o++]=e&255),s===1&&(e=ir[t.charCodeAt(c)]<<10|ir[t.charCodeAt(c+1)]<<4|ir[t.charCodeAt(c+2)]>>2,i[o++]=e>>8&255,i[o++]=e&255),i}function sk(t){return Wr[t>>18&63]+Wr[t>>12&63]+Wr[t>>6&63]+Wr[t&63]}function ik(t,e,r){for(var n,s=[],i=e;i<r;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(sk(n));return s.join("")}function ok(t){for(var e,r=t.length,n=r%3,s=[],i=16383,o=0,a=r-n;o<a;o+=i)s.push(ik(t,o,o+i>a?a:o+i));return n===1?(e=t[r-1],s.push(Wr[e>>2]+Wr[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],s.push(Wr[e>>10]+Wr[e>>4&63]+Wr[e<<2&63]+"=")),s.join("")}var Oh={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Oh.read=function(t,e,r,n,s){var i,o,a=s*8-n-1,c=(1<<a)-1,u=c>>1,f=-7,l=r?s-1:0,p=r?-1:1,d=t[e+l];for(l+=p,i=d&(1<<-f)-1,d>>=-f,f+=a;f>0;i=i*256+t[e+l],l+=p,f-=8);for(o=i&(1<<-f)-1,i>>=-f,f+=n;f>0;o=o*256+t[e+l],l+=p,f-=8);if(i===0)i=1-u;else{if(i===c)return o?NaN:(d?-1:1)*(1/0);o=o+Math.pow(2,n),i=i-u}return(d?-1:1)*o*Math.pow(2,i-n)};Oh.write=function(t,e,r,n,s,i){var o,a,c,u=i*8-s-1,f=(1<<u)-1,l=f>>1,p=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,m=n?1:-1,b=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=f):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+l>=1?e+=p/c:e+=p*Math.pow(2,1-l),e*c>=2&&(o++,c/=2),o+l>=f?(a=0,o=f):o+l>=1?(a=(e*c-1)*Math.pow(2,s),o=o+l):(a=e*Math.pow(2,l-1)*Math.pow(2,s),o=0));s>=8;t[r+d]=a&255,d+=m,a/=256,s-=8);for(o=o<<s|a,u+=s;u>0;t[r+d]=o&255,d+=m,o/=256,u-=8);t[r+d-m]|=b*128};/*!
|
|
47
47
|
* The buffer module from node.js, for the browser.
|
|
48
48
|
*
|
|
49
49
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
50
50
|
* @license MIT
|
|
51
|
-
*/(function(t){const e=ru,r=Ih,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=a,t.SlowBuffer=P,t.INSPECT_MAX_BYTES=50;const s=2147483647;t.kMaxLength=s,a.TYPED_ARRAY_SUPPORT=i(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function i(){try{const v=new Uint8Array(1),h={foo:function(){return 42}};return Object.setPrototypeOf(h,Uint8Array.prototype),Object.setPrototypeOf(v,h),v.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(v){if(v>s)throw new RangeError('The value "'+v+'" is invalid for option "size"');const h=new Uint8Array(v);return Object.setPrototypeOf(h,a.prototype),h}function a(v,h,y){if(typeof v=="number"){if(typeof h=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return l(v)}return c(v,h,y)}a.poolSize=8192;function c(v,h,y){if(typeof v=="string")return p(v,h);if(ArrayBuffer.isView(v))return m(v);if(v==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof v);if(At(v,ArrayBuffer)||v&&At(v.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(At(v,SharedArrayBuffer)||v&&At(v.buffer,SharedArrayBuffer)))return b(v,h,y);if(typeof v=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const x=v.valueOf&&v.valueOf();if(x!=null&&x!==v)return a.from(x,h,y);const C=E(v);if(C)return C;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof v[Symbol.toPrimitive]=="function")return a.from(v[Symbol.toPrimitive]("string"),h,y);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof v)}a.from=function(v,h,y){return c(v,h,y)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function u(v){if(typeof v!="number")throw new TypeError('"size" argument must be of type number');if(v<0)throw new RangeError('The value "'+v+'" is invalid for option "size"')}function f(v,h,y){return u(v),v<=0?o(v):h!==void 0?typeof y=="string"?o(v).fill(h,y):o(v).fill(h):o(v)}a.alloc=function(v,h,y){return f(v,h,y)};function l(v){return u(v),o(v<0?0:A(v)|0)}a.allocUnsafe=function(v){return l(v)},a.allocUnsafeSlow=function(v){return l(v)};function p(v,h){if((typeof h!="string"||h==="")&&(h="utf8"),!a.isEncoding(h))throw new TypeError("Unknown encoding: "+h);const y=S(v,h)|0;let x=o(y);const C=x.write(v,h);return C!==y&&(x=x.slice(0,C)),x}function d(v){const h=v.length<0?0:A(v.length)|0,y=o(h);for(let x=0;x<h;x+=1)y[x]=v[x]&255;return y}function m(v){if(At(v,Uint8Array)){const h=new Uint8Array(v);return b(h.buffer,h.byteOffset,h.byteLength)}return d(v)}function b(v,h,y){if(h<0||v.byteLength<h)throw new RangeError('"offset" is outside of buffer bounds');if(v.byteLength<h+(y||0))throw new RangeError('"length" is outside of buffer bounds');let x;return h===void 0&&y===void 0?x=new Uint8Array(v):y===void 0?x=new Uint8Array(v,h):x=new Uint8Array(v,h,y),Object.setPrototypeOf(x,a.prototype),x}function E(v){if(a.isBuffer(v)){const h=A(v.length)|0,y=o(h);return y.length===0||v.copy(y,0,0,h),y}if(v.length!==void 0)return typeof v.length!="number"||Rn(v.length)?o(0):d(v);if(v.type==="Buffer"&&Array.isArray(v.data))return d(v.data)}function A(v){if(v>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return v|0}function P(v){return+v!=v&&(v=0),a.alloc(+v)}a.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==a.prototype},a.compare=function(h,y){if(At(h,Uint8Array)&&(h=a.from(h,h.offset,h.byteLength)),At(y,Uint8Array)&&(y=a.from(y,y.offset,y.byteLength)),!a.isBuffer(h)||!a.isBuffer(y))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===y)return 0;let x=h.length,C=y.length;for(let N=0,z=Math.min(x,C);N<z;++N)if(h[N]!==y[N]){x=h[N],C=y[N];break}return x<C?-1:C<x?1:0},a.isEncoding=function(h){switch(String(h).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(h,y){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return a.alloc(0);let x;if(y===void 0)for(y=0,x=0;x<h.length;++x)y+=h[x].length;const C=a.allocUnsafe(y);let N=0;for(x=0;x<h.length;++x){let z=h[x];if(At(z,Uint8Array))N+z.length>C.length?(a.isBuffer(z)||(z=a.from(z)),z.copy(C,N)):Uint8Array.prototype.set.call(C,z,N);else if(a.isBuffer(z))z.copy(C,N);else throw new TypeError('"list" argument must be an Array of Buffers');N+=z.length}return C};function S(v,h){if(a.isBuffer(v))return v.length;if(ArrayBuffer.isView(v)||At(v,ArrayBuffer))return v.byteLength;if(typeof v!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof v);const y=v.length,x=arguments.length>2&&arguments[2]===!0;if(!x&&y===0)return 0;let C=!1;for(;;)switch(h){case"ascii":case"latin1":case"binary":return y;case"utf8":case"utf-8":return Nr(v).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return y*2;case"hex":return y>>>1;case"base64":return Ur(v).length;default:if(C)return x?-1:Nr(v).length;h=(""+h).toLowerCase(),C=!0}}a.byteLength=S;function w(v,h,y){let x=!1;if((h===void 0||h<0)&&(h=0),h>this.length||((y===void 0||y>this.length)&&(y=this.length),y<=0)||(y>>>=0,h>>>=0,y<=h))return"";for(v||(v="utf8");;)switch(v){case"hex":return I(this,h,y);case"utf8":case"utf-8":return Q(this,h,y);case"ascii":return ee(this,h,y);case"latin1":case"binary":return H(this,h,y);case"base64":return K(this,h,y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,h,y);default:if(x)throw new TypeError("Unknown encoding: "+v);v=(v+"").toLowerCase(),x=!0}}a.prototype._isBuffer=!0;function k(v,h,y){const x=v[h];v[h]=v[y],v[y]=x}a.prototype.swap16=function(){const h=this.length;if(h%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let y=0;y<h;y+=2)k(this,y,y+1);return this},a.prototype.swap32=function(){const h=this.length;if(h%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let y=0;y<h;y+=4)k(this,y,y+3),k(this,y+1,y+2);return this},a.prototype.swap64=function(){const h=this.length;if(h%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let y=0;y<h;y+=8)k(this,y,y+7),k(this,y+1,y+6),k(this,y+2,y+5),k(this,y+3,y+4);return this},a.prototype.toString=function(){const h=this.length;return h===0?"":arguments.length===0?Q(this,0,h):w.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(h){if(!a.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:a.compare(this,h)===0},a.prototype.inspect=function(){let h="";const y=t.INSPECT_MAX_BYTES;return h=this.toString("hex",0,y).replace(/(.{2})/g,"$1 ").trim(),this.length>y&&(h+=" ... "),"<Buffer "+h+">"},n&&(a.prototype[n]=a.prototype.inspect),a.prototype.compare=function(h,y,x,C,N){if(At(h,Uint8Array)&&(h=a.from(h,h.offset,h.byteLength)),!a.isBuffer(h))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof h);if(y===void 0&&(y=0),x===void 0&&(x=h?h.length:0),C===void 0&&(C=0),N===void 0&&(N=this.length),y<0||x>h.length||C<0||N>this.length)throw new RangeError("out of range index");if(C>=N&&y>=x)return 0;if(C>=N)return-1;if(y>=x)return 1;if(y>>>=0,x>>>=0,C>>>=0,N>>>=0,this===h)return 0;let z=N-C,ge=x-y;const ze=Math.min(z,ge),Ue=this.slice(C,N),Ve=h.slice(y,x);for(let Te=0;Te<ze;++Te)if(Ue[Te]!==Ve[Te]){z=Ue[Te],ge=Ve[Te];break}return z<ge?-1:ge<z?1:0};function T(v,h,y,x,C){if(v.length===0)return-1;if(typeof y=="string"?(x=y,y=0):y>2147483647?y=2147483647:y<-2147483648&&(y=-2147483648),y=+y,Rn(y)&&(y=C?0:v.length-1),y<0&&(y=v.length+y),y>=v.length){if(C)return-1;y=v.length-1}else if(y<0)if(C)y=0;else return-1;if(typeof h=="string"&&(h=a.from(h,x)),a.isBuffer(h))return h.length===0?-1:B(v,h,y,x,C);if(typeof h=="number")return h=h&255,typeof Uint8Array.prototype.indexOf=="function"?C?Uint8Array.prototype.indexOf.call(v,h,y):Uint8Array.prototype.lastIndexOf.call(v,h,y):B(v,[h],y,x,C);throw new TypeError("val must be string, number or Buffer")}function B(v,h,y,x,C){let N=1,z=v.length,ge=h.length;if(x!==void 0&&(x=String(x).toLowerCase(),x==="ucs2"||x==="ucs-2"||x==="utf16le"||x==="utf-16le")){if(v.length<2||h.length<2)return-1;N=2,z/=2,ge/=2,y/=2}function ze(Ve,Te){return N===1?Ve[Te]:Ve.readUInt16BE(Te*N)}let Ue;if(C){let Ve=-1;for(Ue=y;Ue<z;Ue++)if(ze(v,Ue)===ze(h,Ve===-1?0:Ue-Ve)){if(Ve===-1&&(Ve=Ue),Ue-Ve+1===ge)return Ve*N}else Ve!==-1&&(Ue-=Ue-Ve),Ve=-1}else for(y+ge>z&&(y=z-ge),Ue=y;Ue>=0;Ue--){let Ve=!0;for(let Te=0;Te<ge;Te++)if(ze(v,Ue+Te)!==ze(h,Te)){Ve=!1;break}if(Ve)return Ue}return-1}a.prototype.includes=function(h,y,x){return this.indexOf(h,y,x)!==-1},a.prototype.indexOf=function(h,y,x){return T(this,h,y,x,!0)},a.prototype.lastIndexOf=function(h,y,x){return T(this,h,y,x,!1)};function U(v,h,y,x){y=Number(y)||0;const C=v.length-y;x?(x=Number(x),x>C&&(x=C)):x=C;const N=h.length;x>N/2&&(x=N/2);let z;for(z=0;z<x;++z){const ge=parseInt(h.substr(z*2,2),16);if(Rn(ge))return z;v[y+z]=ge}return z}function $(v,h,y,x){return St(Nr(h,v.length-y),v,y,x)}function D(v,h,y,x){return St(ds(h),v,y,x)}function M(v,h,y,x){return St(Ur(h),v,y,x)}function q(v,h,y,x){return St(V(h,v.length-y),v,y,x)}a.prototype.write=function(h,y,x,C){if(y===void 0)C="utf8",x=this.length,y=0;else if(x===void 0&&typeof y=="string")C=y,x=this.length,y=0;else if(isFinite(y))y=y>>>0,isFinite(x)?(x=x>>>0,C===void 0&&(C="utf8")):(C=x,x=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const N=this.length-y;if((x===void 0||x>N)&&(x=N),h.length>0&&(x<0||y<0)||y>this.length)throw new RangeError("Attempt to write outside buffer bounds");C||(C="utf8");let z=!1;for(;;)switch(C){case"hex":return U(this,h,y,x);case"utf8":case"utf-8":return $(this,h,y,x);case"ascii":case"latin1":case"binary":return D(this,h,y,x);case"base64":return M(this,h,y,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,h,y,x);default:if(z)throw new TypeError("Unknown encoding: "+C);C=(""+C).toLowerCase(),z=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function K(v,h,y){return h===0&&y===v.length?e.fromByteArray(v):e.fromByteArray(v.slice(h,y))}function Q(v,h,y){y=Math.min(v.length,y);const x=[];let C=h;for(;C<y;){const N=v[C];let z=null,ge=N>239?4:N>223?3:N>191?2:1;if(C+ge<=y){let ze,Ue,Ve,Te;switch(ge){case 1:N<128&&(z=N);break;case 2:ze=v[C+1],(ze&192)===128&&(Te=(N&31)<<6|ze&63,Te>127&&(z=Te));break;case 3:ze=v[C+1],Ue=v[C+2],(ze&192)===128&&(Ue&192)===128&&(Te=(N&15)<<12|(ze&63)<<6|Ue&63,Te>2047&&(Te<55296||Te>57343)&&(z=Te));break;case 4:ze=v[C+1],Ue=v[C+2],Ve=v[C+3],(ze&192)===128&&(Ue&192)===128&&(Ve&192)===128&&(Te=(N&15)<<18|(ze&63)<<12|(Ue&63)<<6|Ve&63,Te>65535&&Te<1114112&&(z=Te))}}z===null?(z=65533,ge=1):z>65535&&(z-=65536,x.push(z>>>10&1023|55296),z=56320|z&1023),x.push(z),C+=ge}return W(x)}const G=4096;function W(v){const h=v.length;if(h<=G)return String.fromCharCode.apply(String,v);let y="",x=0;for(;x<h;)y+=String.fromCharCode.apply(String,v.slice(x,x+=G));return y}function ee(v,h,y){let x="";y=Math.min(v.length,y);for(let C=h;C<y;++C)x+=String.fromCharCode(v[C]&127);return x}function H(v,h,y){let x="";y=Math.min(v.length,y);for(let C=h;C<y;++C)x+=String.fromCharCode(v[C]);return x}function I(v,h,y){const x=v.length;(!h||h<0)&&(h=0),(!y||y<0||y>x)&&(y=x);let C="";for(let N=h;N<y;++N)C+=ni[v[N]];return C}function j(v,h,y){const x=v.slice(h,y);let C="";for(let N=0;N<x.length-1;N+=2)C+=String.fromCharCode(x[N]+x[N+1]*256);return C}a.prototype.slice=function(h,y){const x=this.length;h=~~h,y=y===void 0?x:~~y,h<0?(h+=x,h<0&&(h=0)):h>x&&(h=x),y<0?(y+=x,y<0&&(y=0)):y>x&&(y=x),y<h&&(y=h);const C=this.subarray(h,y);return Object.setPrototypeOf(C,a.prototype),C};function J(v,h,y){if(v%1!==0||v<0)throw new RangeError("offset is not uint");if(v+h>y)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(h,y,x){h=h>>>0,y=y>>>0,x||J(h,y,this.length);let C=this[h],N=1,z=0;for(;++z<y&&(N*=256);)C+=this[h+z]*N;return C},a.prototype.readUintBE=a.prototype.readUIntBE=function(h,y,x){h=h>>>0,y=y>>>0,x||J(h,y,this.length);let C=this[h+--y],N=1;for(;y>0&&(N*=256);)C+=this[h+--y]*N;return C},a.prototype.readUint8=a.prototype.readUInt8=function(h,y){return h=h>>>0,y||J(h,1,this.length),this[h]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(h,y){return h=h>>>0,y||J(h,2,this.length),this[h]|this[h+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(h,y){return h=h>>>0,y||J(h,2,this.length),this[h]<<8|this[h+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(h,y){return h=h>>>0,y||J(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(h,y){return h=h>>>0,y||J(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},a.prototype.readBigUInt64LE=Nn(function(h){h=h>>>0,we(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&ke(h,this.length-8);const C=y+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24,N=this[++h]+this[++h]*2**8+this[++h]*2**16+x*2**24;return BigInt(C)+(BigInt(N)<<BigInt(32))}),a.prototype.readBigUInt64BE=Nn(function(h){h=h>>>0,we(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&ke(h,this.length-8);const C=y*2**24+this[++h]*2**16+this[++h]*2**8+this[++h],N=this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+x;return(BigInt(C)<<BigInt(32))+BigInt(N)}),a.prototype.readIntLE=function(h,y,x){h=h>>>0,y=y>>>0,x||J(h,y,this.length);let C=this[h],N=1,z=0;for(;++z<y&&(N*=256);)C+=this[h+z]*N;return N*=128,C>=N&&(C-=Math.pow(2,8*y)),C},a.prototype.readIntBE=function(h,y,x){h=h>>>0,y=y>>>0,x||J(h,y,this.length);let C=y,N=1,z=this[h+--C];for(;C>0&&(N*=256);)z+=this[h+--C]*N;return N*=128,z>=N&&(z-=Math.pow(2,8*y)),z},a.prototype.readInt8=function(h,y){return h=h>>>0,y||J(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},a.prototype.readInt16LE=function(h,y){h=h>>>0,y||J(h,2,this.length);const x=this[h]|this[h+1]<<8;return x&32768?x|4294901760:x},a.prototype.readInt16BE=function(h,y){h=h>>>0,y||J(h,2,this.length);const x=this[h+1]|this[h]<<8;return x&32768?x|4294901760:x},a.prototype.readInt32LE=function(h,y){return h=h>>>0,y||J(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},a.prototype.readInt32BE=function(h,y){return h=h>>>0,y||J(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},a.prototype.readBigInt64LE=Nn(function(h){h=h>>>0,we(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&ke(h,this.length-8);const C=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(x<<24);return(BigInt(C)<<BigInt(32))+BigInt(y+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24)}),a.prototype.readBigInt64BE=Nn(function(h){h=h>>>0,we(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&ke(h,this.length-8);const C=(y<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt(C)<<BigInt(32))+BigInt(this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+x)}),a.prototype.readFloatLE=function(h,y){return h=h>>>0,y||J(h,4,this.length),r.read(this,h,!0,23,4)},a.prototype.readFloatBE=function(h,y){return h=h>>>0,y||J(h,4,this.length),r.read(this,h,!1,23,4)},a.prototype.readDoubleLE=function(h,y){return h=h>>>0,y||J(h,8,this.length),r.read(this,h,!0,52,8)},a.prototype.readDoubleBE=function(h,y){return h=h>>>0,y||J(h,8,this.length),r.read(this,h,!1,52,8)};function O(v,h,y,x,C,N){if(!a.isBuffer(v))throw new TypeError('"buffer" argument must be a Buffer instance');if(h>C||h<N)throw new RangeError('"value" argument is out of bounds');if(y+x>v.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(h,y,x,C){if(h=+h,y=y>>>0,x=x>>>0,!C){const ge=Math.pow(2,8*x)-1;O(this,h,y,x,ge,0)}let N=1,z=0;for(this[y]=h&255;++z<x&&(N*=256);)this[y+z]=h/N&255;return y+x},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(h,y,x,C){if(h=+h,y=y>>>0,x=x>>>0,!C){const ge=Math.pow(2,8*x)-1;O(this,h,y,x,ge,0)}let N=x-1,z=1;for(this[y+N]=h&255;--N>=0&&(z*=256);)this[y+N]=h/z&255;return y+x},a.prototype.writeUint8=a.prototype.writeUInt8=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,1,255,0),this[y]=h&255,y+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,65535,0),this[y]=h&255,this[y+1]=h>>>8,y+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,65535,0),this[y]=h>>>8,this[y+1]=h&255,y+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,4294967295,0),this[y+3]=h>>>24,this[y+2]=h>>>16,this[y+1]=h>>>8,this[y]=h&255,y+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,4294967295,0),this[y]=h>>>24,this[y+1]=h>>>16,this[y+2]=h>>>8,this[y+3]=h&255,y+4};function R(v,h,y,x,C){be(h,x,C,v,y,7);let N=Number(h&BigInt(4294967295));v[y++]=N,N=N>>8,v[y++]=N,N=N>>8,v[y++]=N,N=N>>8,v[y++]=N;let z=Number(h>>BigInt(32)&BigInt(4294967295));return v[y++]=z,z=z>>8,v[y++]=z,z=z>>8,v[y++]=z,z=z>>8,v[y++]=z,y}function F(v,h,y,x,C){be(h,x,C,v,y,7);let N=Number(h&BigInt(4294967295));v[y+7]=N,N=N>>8,v[y+6]=N,N=N>>8,v[y+5]=N,N=N>>8,v[y+4]=N;let z=Number(h>>BigInt(32)&BigInt(4294967295));return v[y+3]=z,z=z>>8,v[y+2]=z,z=z>>8,v[y+1]=z,z=z>>8,v[y]=z,y+8}a.prototype.writeBigUInt64LE=Nn(function(h,y=0){return R(this,h,y,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=Nn(function(h,y=0){return F(this,h,y,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(h,y,x,C){if(h=+h,y=y>>>0,!C){const ze=Math.pow(2,8*x-1);O(this,h,y,x,ze-1,-ze)}let N=0,z=1,ge=0;for(this[y]=h&255;++N<x&&(z*=256);)h<0&&ge===0&&this[y+N-1]!==0&&(ge=1),this[y+N]=(h/z>>0)-ge&255;return y+x},a.prototype.writeIntBE=function(h,y,x,C){if(h=+h,y=y>>>0,!C){const ze=Math.pow(2,8*x-1);O(this,h,y,x,ze-1,-ze)}let N=x-1,z=1,ge=0;for(this[y+N]=h&255;--N>=0&&(z*=256);)h<0&&ge===0&&this[y+N+1]!==0&&(ge=1),this[y+N]=(h/z>>0)-ge&255;return y+x},a.prototype.writeInt8=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,1,127,-128),h<0&&(h=255+h+1),this[y]=h&255,y+1},a.prototype.writeInt16LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,32767,-32768),this[y]=h&255,this[y+1]=h>>>8,y+2},a.prototype.writeInt16BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,32767,-32768),this[y]=h>>>8,this[y+1]=h&255,y+2},a.prototype.writeInt32LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,2147483647,-2147483648),this[y]=h&255,this[y+1]=h>>>8,this[y+2]=h>>>16,this[y+3]=h>>>24,y+4},a.prototype.writeInt32BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,2147483647,-2147483648),h<0&&(h=4294967295+h+1),this[y]=h>>>24,this[y+1]=h>>>16,this[y+2]=h>>>8,this[y+3]=h&255,y+4},a.prototype.writeBigInt64LE=Nn(function(h,y=0){return R(this,h,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=Nn(function(h,y=0){return F(this,h,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ne(v,h,y,x,C,N){if(y+x>v.length)throw new RangeError("Index out of range");if(y<0)throw new RangeError("Index out of range")}function ae(v,h,y,x,C){return h=+h,y=y>>>0,C||ne(v,h,y,4),r.write(v,h,y,x,23,4),y+4}a.prototype.writeFloatLE=function(h,y,x){return ae(this,h,y,!0,x)},a.prototype.writeFloatBE=function(h,y,x){return ae(this,h,y,!1,x)};function le(v,h,y,x,C){return h=+h,y=y>>>0,C||ne(v,h,y,8),r.write(v,h,y,x,52,8),y+8}a.prototype.writeDoubleLE=function(h,y,x){return le(this,h,y,!0,x)},a.prototype.writeDoubleBE=function(h,y,x){return le(this,h,y,!1,x)},a.prototype.copy=function(h,y,x,C){if(!a.isBuffer(h))throw new TypeError("argument should be a Buffer");if(x||(x=0),!C&&C!==0&&(C=this.length),y>=h.length&&(y=h.length),y||(y=0),C>0&&C<x&&(C=x),C===x||h.length===0||this.length===0)return 0;if(y<0)throw new RangeError("targetStart out of bounds");if(x<0||x>=this.length)throw new RangeError("Index out of range");if(C<0)throw new RangeError("sourceEnd out of bounds");C>this.length&&(C=this.length),h.length-y<C-x&&(C=h.length-y+x);const N=C-x;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(y,x,C):Uint8Array.prototype.set.call(h,this.subarray(x,C),y),N},a.prototype.fill=function(h,y,x,C){if(typeof h=="string"){if(typeof y=="string"?(C=y,y=0,x=this.length):typeof x=="string"&&(C=x,x=this.length),C!==void 0&&typeof C!="string")throw new TypeError("encoding must be a string");if(typeof C=="string"&&!a.isEncoding(C))throw new TypeError("Unknown encoding: "+C);if(h.length===1){const z=h.charCodeAt(0);(C==="utf8"&&z<128||C==="latin1")&&(h=z)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));if(y<0||this.length<y||this.length<x)throw new RangeError("Out of range index");if(x<=y)return this;y=y>>>0,x=x===void 0?this.length:x>>>0,h||(h=0);let N;if(typeof h=="number")for(N=y;N<x;++N)this[N]=h;else{const z=a.isBuffer(h)?h:a.from(h,C),ge=z.length;if(ge===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for(N=0;N<x-y;++N)this[N+y]=z[N%ge]}return this};const ue={};function oe(v,h,y){ue[v]=class extends y{constructor(){super(),Object.defineProperty(this,"message",{value:h.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${v}]`,this.stack,delete this.name}get code(){return v}set code(C){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:C,writable:!0})}toString(){return`${this.name} [${v}]: ${this.message}`}}}oe("ERR_BUFFER_OUT_OF_BOUNDS",function(v){return v?`${v} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),oe("ERR_INVALID_ARG_TYPE",function(v,h){return`The "${v}" argument must be of type number. Received type ${typeof h}`},TypeError),oe("ERR_OUT_OF_RANGE",function(v,h,y){let x=`The value of "${v}" is out of range.`,C=y;return Number.isInteger(y)&&Math.abs(y)>2**32?C=ie(String(y)):typeof y=="bigint"&&(C=String(y),(y>BigInt(2)**BigInt(32)||y<-(BigInt(2)**BigInt(32)))&&(C=ie(C)),C+="n"),x+=` It must be ${h}. Received ${C}`,x},RangeError);function ie(v){let h="",y=v.length;const x=v[0]==="-"?1:0;for(;y>=x+4;y-=3)h=`_${v.slice(y-3,y)}${h}`;return`${v.slice(0,y)}${h}`}function me(v,h,y){we(h,"offset"),(v[h]===void 0||v[h+y]===void 0)&&ke(h,v.length-(y+1))}function be(v,h,y,x,C,N){if(v>y||v<h){const z=typeof h=="bigint"?"n":"";let ge;throw h===0||h===BigInt(0)?ge=`>= 0${z} and < 2${z} ** ${(N+1)*8}${z}`:ge=`>= -(2${z} ** ${(N+1)*8-1}${z}) and < 2 ** ${(N+1)*8-1}${z}`,new ue.ERR_OUT_OF_RANGE("value",ge,v)}me(x,C,N)}function we(v,h){if(typeof v!="number")throw new ue.ERR_INVALID_ARG_TYPE(h,"number",v)}function ke(v,h,y){throw Math.floor(v)!==v?(we(v,y),new ue.ERR_OUT_OF_RANGE("offset","an integer",v)):h<0?new ue.ERR_BUFFER_OUT_OF_BOUNDS:new ue.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${h}`,v)}const tt=/[^+/0-9A-Za-z-_]/g;function Oe(v){if(v=v.split("=")[0],v=v.trim().replace(tt,""),v.length<2)return"";for(;v.length%4!==0;)v=v+"=";return v}function Nr(v,h){h=h||1/0;let y;const x=v.length;let C=null;const N=[];for(let z=0;z<x;++z){if(y=v.charCodeAt(z),y>55295&&y<57344){if(!C){if(y>56319){(h-=3)>-1&&N.push(239,191,189);continue}else if(z+1===x){(h-=3)>-1&&N.push(239,191,189);continue}C=y;continue}if(y<56320){(h-=3)>-1&&N.push(239,191,189),C=y;continue}y=(C-55296<<10|y-56320)+65536}else C&&(h-=3)>-1&&N.push(239,191,189);if(C=null,y<128){if((h-=1)<0)break;N.push(y)}else if(y<2048){if((h-=2)<0)break;N.push(y>>6|192,y&63|128)}else if(y<65536){if((h-=3)<0)break;N.push(y>>12|224,y>>6&63|128,y&63|128)}else if(y<1114112){if((h-=4)<0)break;N.push(y>>18|240,y>>12&63|128,y>>6&63|128,y&63|128)}else throw new Error("Invalid code point")}return N}function ds(v){const h=[];for(let y=0;y<v.length;++y)h.push(v.charCodeAt(y)&255);return h}function V(v,h){let y,x,C;const N=[];for(let z=0;z<v.length&&!((h-=2)<0);++z)y=v.charCodeAt(z),x=y>>8,C=y%256,N.push(C),N.push(x);return N}function Ur(v){return e.toByteArray(Oe(v))}function St(v,h,y,x){let C;for(C=0;C<x&&!(C+y>=h.length||C>=v.length);++C)h[C+y]=v[C];return C}function At(v,h){return v instanceof h||v!=null&&v.constructor!=null&&v.constructor.name!=null&&v.constructor.name===h.name}function Rn(v){return v!==v}const ni=function(){const v="0123456789abcdef",h=new Array(256);for(let y=0;y<16;++y){const x=y*16;for(let C=0;C<16;++C)h[x+C]=v[y]+v[C]}return h}();function Nn(v){return typeof BigInt>"u"?t6:v}function t6(){throw new Error("BigInt not supported")}})(Qs);var ea={Array:function(t){return t!=null&&t.constructor===Array},Boolean:function(t){return typeof t=="boolean"},Function:function(t){return typeof t=="function"},Nil:function(t){return t==null},Number:function(t){return typeof t=="number"},Object:function(t){return typeof t=="object"},String:function(t){return typeof t=="string"},"":function(){return!0}};ea.Null=ea.Nil;for(var g0 in ea)ea[g0].toJSON=(function(t){return t}).bind(null,g0);var Oh=ea,Is=Oh;function B1(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function Bh(t){return Is.Nil(t)?"":B1(t.constructor)}function ak(t){return Is.Function(t)?"":Is.String(t)?JSON.stringify(t):t&&Is.Object(t)?"":t}function Ch(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function Ec(t){return Is.Function(t)?t.toJSON?t.toJSON():B1(t):Is.Array(t)?"Array":t&&Is.Object(t)?"Object":t!==void 0?t:""}function C1(t,e,r){var n=ak(e);return"Expected "+Ec(t)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function Pn(t,e,r){r=r||Bh(e),this.message=C1(t,e,r),Ch(this,Pn),this.__type=t,this.__value=e,this.__valueTypeName=r}Pn.prototype=Object.create(Error.prototype);Pn.prototype.constructor=Pn;function ck(t,e,r,n,s){var i='" of type ';return e==="key"&&(i='" with key type '),C1('property "'+Ec(r)+i+Ec(t),n,s)}function ki(t,e,r,n,s){t?(s=s||Bh(n),this.message=ck(t,r,e,n,s)):this.message='Unexpected property "'+e+'"',Ch(this,Pn),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=s}ki.prototype=Object.create(Error.prototype);ki.prototype.constructor=Pn;function uk(t,e){return new Pn(t,{},e)}function fk(t,e,r){return t instanceof ki?(e=e+"."+t.__property,t=new ki(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof Pn&&(t=new ki(t.__type,e,r,t.__value,t.__valueTypeName)),Ch(t),t}var $1={TfTypeError:Pn,TfPropertyTypeError:ki,tfCustomError:uk,tfSubError:fk,tfJSON:Ec,getValueTypeName:Bh},Yu,w0;function lk(){if(w0)return Yu;w0=1;var t=Oh,e=$1;function r(T){return Buffer.isBuffer(T)}function n(T){return typeof T=="string"&&/^([0-9a-f]{2})+$/i.test(T)}function s(T,B){var U=T.toJSON();function $(D){if(!T(D))return!1;if(D.length===B)return!0;throw e.tfCustomError(U+"(Length: "+B+")",U+"(Length: "+D.length+")")}return $.toJSON=function(){return U},$}var i=s.bind(null,t.Array),o=s.bind(null,r),a=s.bind(null,n),c=s.bind(null,t.String);function u(T,B,U){U=U||t.Number;function $(D,M){return U(D,M)&&D>T&&D<B}return $.toJSON=function(){return`${U.toJSON()} between [${T}, ${B}]`},$}var f=Math.pow(2,53)-1;function l(T){return typeof T=="number"&&isFinite(T)}function p(T){return T<<24>>24===T}function d(T){return T<<16>>16===T}function m(T){return(T|0)===T}function b(T){return typeof T=="number"&&T>=-f&&T<=f&&Math.floor(T)===T}function E(T){return(T&255)===T}function A(T){return(T&65535)===T}function P(T){return T>>>0===T}function S(T){return typeof T=="number"&&T>=0&&T<=f&&Math.floor(T)===T}var w={ArrayN:i,Buffer:r,BufferN:o,Finite:l,Hex:n,HexN:a,Int8:p,Int16:d,Int32:m,Int53:b,Range:u,StringN:c,UInt8:E,UInt16:A,UInt32:P,UInt53:S};for(var k in w)w[k].toJSON=(function(T){return T}).bind(null,k);return Yu=w,Yu}var ka=$1,ft=Oh,sn=ka.tfJSON,R1=ka.TfTypeError,N1=ka.TfPropertyTypeError,so=ka.tfSubError,dk=ka.getValueTypeName,gn={arrayOf:function(e,r){e=qr(e),r=r||{};function n(s,i){return!ft.Array(s)||ft.Nil(s)||r.minLength!==void 0&&s.length<r.minLength||r.maxLength!==void 0&&s.length>r.maxLength||r.length!==void 0&&s.length!==r.length?!1:s.every(function(o,a){try{return Pt(e,o,i)}catch(c){throw so(c,a)}})}return n.toJSON=function(){var s="["+sn(e)+"]";return r.length!==void 0?s+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(s+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),s},n},maybe:function t(e){e=qr(e);function r(n,s){return ft.Nil(n)||e(n,s,t)}return r.toJSON=function(){return"?"+sn(e)},r},map:function(e,r){e=qr(e),r&&(r=qr(r));function n(s,i){if(!ft.Object(s)||ft.Nil(s))return!1;for(var o in s){try{r&&Pt(r,o,i)}catch(c){throw so(c,o,"key")}try{var a=s[o];Pt(e,a,i)}catch(c){throw so(c,o)}}return!0}return r?n.toJSON=function(){return"{"+sn(r)+": "+sn(e)+"}"}:n.toJSON=function(){return"{"+sn(e)+"}"},n},object:function(e){var r={};for(var n in e)r[n]=qr(e[n]);function s(i,o){if(!ft.Object(i)||ft.Nil(i))return!1;var a;try{for(a in r){var c=r[a],u=i[a];Pt(c,u,o)}}catch(f){throw so(f,a)}if(o){for(a in i)if(!r[a])throw new N1(void 0,a)}return!0}return s.toJSON=function(){return sn(r)},s},anyOf:function(){var e=[].slice.call(arguments).map(qr);function r(n,s){return e.some(function(i){try{return Pt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return e.map(sn).join("|")},r},allOf:function(){var e=[].slice.call(arguments).map(qr);function r(n,s){return e.every(function(i){try{return Pt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return e.map(sn).join(" & ")},r},quacksLike:function(e){function r(n){return e===dk(n)}return r.toJSON=function(){return e},r},tuple:function(){var e=[].slice.call(arguments).map(qr);function r(n,s){return ft.Nil(n)||ft.Nil(n.length)||s&&n.length!==e.length?!1:e.every(function(i,o){try{return Pt(i,n[o],s)}catch(a){throw so(a,o)}})}return r.toJSON=function(){return"("+e.map(sn).join(", ")+")"},r},value:function(e){function r(n){return n===e}return r.toJSON=function(){return e},r}};gn.oneOf=gn.anyOf;function qr(t){if(ft.String(t))return t[0]==="?"?gn.maybe(t.slice(1)):ft[t]||gn.quacksLike(t);if(t&&ft.Object(t)){if(ft.Array(t)){if(t.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return gn.arrayOf(t[0])}return gn.object(t)}else if(ft.Function(t))return t;return gn.value(t)}function Pt(t,e,r,n){if(ft.Function(t)){if(t(e,r))return!0;throw new R1(n||t,e)}return Pt(qr(t),e,r)}for(var rs in ft)Pt[rs]=ft[rs];for(rs in gn)Pt[rs]=gn[rs];var v0=lk();for(rs in v0)Pt[rs]=v0[rs];Pt.compile=qr;Pt.TfTypeError=R1;Pt.TfPropertyTypeError=N1;var hk=Pt;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.oneOf=t.Null=t.BufferN=t.Function=t.UInt32=t.UInt8=t.tuple=t.maybe=t.Hex=t.Buffer=t.String=t.Boolean=t.Array=t.Number=t.Hash256bit=t.Hash160bit=t.Buffer256bit=t.isTaptree=t.isTapleaf=t.TAPLEAF_VERSION_MASK=t.Satoshi=t.isPoint=t.stacksEqual=t.typeforce=void 0;const e=Qs;t.typeforce=hk;const r=e.Buffer.alloc(32,0),n=e.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function s(f,l){return f.length!==l.length?!1:f.every((p,d)=>p.equals(l[d]))}t.stacksEqual=s;function i(f){if(!e.Buffer.isBuffer(f)||f.length<33)return!1;const l=f[0],p=f.slice(1,33);if(p.compare(r)===0||p.compare(n)>=0)return!1;if((l===2||l===3)&&f.length===33)return!0;const d=f.slice(33);return d.compare(r)===0||d.compare(n)>=0?!1:l===4&&f.length===65}t.isPoint=i;const o=21*1e14;function a(f){return t.typeforce.UInt53(f)&&f<=o}t.Satoshi=a,t.TAPLEAF_VERSION_MASK=254;function c(f){return!f||!("output"in f)||!e.Buffer.isBuffer(f.output)?!1:f.version!==void 0?(f.version&t.TAPLEAF_VERSION_MASK)===f.version:!0}t.isTapleaf=c;function u(f){return(0,t.Array)(f)?f.length!==2?!1:f.every(l=>u(l)):c(f)}t.isTaptree=u,t.Buffer256bit=t.typeforce.BufferN(32),t.Hash160bit=t.typeforce.BufferN(20),t.Hash256bit=t.typeforce.BufferN(32),t.Number=t.typeforce.Number,t.Array=t.typeforce.Array,t.Boolean=t.typeforce.Boolean,t.String=t.typeforce.String,t.Buffer=t.typeforce.Buffer,t.Hex=t.typeforce.Hex,t.maybe=t.typeforce.maybe,t.tuple=t.typeforce.tuple,t.UInt8=t.typeforce.UInt8,t.UInt32=t.typeforce.UInt32,t.Function=t.typeforce.Function,t.BufferN=t.typeforce.BufferN,t.Null=t.typeforce.Null,t.oneOf=t.typeforce.oneOf})(Et);var Ta={},lt={};Object.defineProperty(lt,"__esModule",{value:!0});lt.BufferReader=lt.BufferWriter=lt.cloneBuffer=lt.reverseBuffer=lt.writeUInt64LE=lt.readUInt64LE=lt.varuint=void 0;const Os=Et,{typeforce:U1}=Os,ta=pm;lt.varuint=ta;function M1(t,e){if(typeof t!="number")throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function F1(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,M1(n+r,9007199254740991),n+r}lt.readUInt64LE=F1;function j1(t,e,r){return M1(e,9007199254740991),t.writeInt32LE(e&-1,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}lt.writeUInt64LE=j1;function pk(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n<t.length/2;n++)r=t[n],t[n]=t[e],t[e]=r,e--;return t}lt.reverseBuffer=pk;function yk(t){const e=Buffer.allocUnsafe(t.length);return t.copy(e),e}lt.cloneBuffer=yk;class $h{static withCapacity(e){return new $h(Buffer.alloc(e))}constructor(e,r=0){this.buffer=e,this.offset=r,U1(Os.tuple(Os.Buffer,Os.UInt32),[e,r])}writeUInt8(e){this.offset=this.buffer.writeUInt8(e,this.offset)}writeInt32(e){this.offset=this.buffer.writeInt32LE(e,this.offset)}writeUInt32(e){this.offset=this.buffer.writeUInt32LE(e,this.offset)}writeUInt64(e){this.offset=j1(this.buffer,e,this.offset)}writeVarInt(e){ta.encode(e,this.buffer,this.offset),this.offset+=ta.encode.bytes}writeSlice(e){if(this.buffer.length<this.offset+e.length)throw new Error("Cannot write slice out of bounds");this.offset+=e.copy(this.buffer,this.offset)}writeVarSlice(e){this.writeVarInt(e.length),this.writeSlice(e)}writeVector(e){this.writeVarInt(e.length),e.forEach(r=>this.writeVarSlice(r))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}lt.BufferWriter=$h;class mk{constructor(e,r=0){this.buffer=e,this.offset=r,U1(Os.tuple(Os.Buffer,Os.UInt32),[e,r])}readUInt8(){const e=this.buffer.readUInt8(this.offset);return this.offset++,e}readInt32(){const e=this.buffer.readInt32LE(this.offset);return this.offset+=4,e}readUInt32(){const e=this.buffer.readUInt32LE(this.offset);return this.offset+=4,e}readUInt64(){const e=F1(this.buffer,this.offset);return this.offset+=8,e}readVarInt(){const e=ta.decode(this.buffer,this.offset);return this.offset+=ta.decode.bytes,e}readSlice(e){if(this.buffer.length<this.offset+e)throw new Error("Cannot read slice out of bounds");const r=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,r}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const e=this.readVarInt(),r=[];for(let n=0;n<e;n++)r.push(this.readVarSlice());return r}}lt.BufferReader=mk;var ls={};const bk=I1(g8);var Ni={},Nt={},Ot={},Rh={},nu={};Object.defineProperty(nu,"__esModule",{value:!0});nu.crypto=void 0;nu.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;(function(t){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(t,"__esModule",{value:!0}),t.wrapXOFConstructorWithOpts=t.wrapConstructorWithOpts=t.wrapConstructor=t.Hash=t.nextTick=t.swap32IfBE=t.byteSwapIfBE=t.swap8IfBE=t.isLE=void 0,t.isBytes=r,t.anumber=n,t.abytes=s,t.ahash=i,t.aexists=o,t.aoutput=a,t.u8=c,t.u32=u,t.clean=f,t.createView=l,t.rotr=p,t.rotl=d,t.byteSwap=m,t.byteSwap32=b,t.bytesToHex=P,t.hexToBytes=k,t.asyncLoop=B,t.utf8ToBytes=U,t.bytesToUtf8=$,t.toBytes=D,t.kdfInputToBytes=M,t.concatBytes=q,t.checkOpts=K,t.createHasher=G,t.createOptHasher=W,t.createXOFer=ee,t.randomBytes=H;const e=nu;function r(I){return I instanceof Uint8Array||ArrayBuffer.isView(I)&&I.constructor.name==="Uint8Array"}function n(I){if(!Number.isSafeInteger(I)||I<0)throw new Error("positive integer expected, got "+I)}function s(I,...j){if(!r(I))throw new Error("Uint8Array expected");if(j.length>0&&!j.includes(I.length))throw new Error("Uint8Array expected of length "+j+", got length="+I.length)}function i(I){if(typeof I!="function"||typeof I.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");n(I.outputLen),n(I.blockLen)}function o(I,j=!0){if(I.destroyed)throw new Error("Hash instance has been destroyed");if(j&&I.finished)throw new Error("Hash#digest() has already been called")}function a(I,j){s(I);const J=j.outputLen;if(I.length<J)throw new Error("digestInto() expects output buffer of length at least "+J)}function c(I){return new Uint8Array(I.buffer,I.byteOffset,I.byteLength)}function u(I){return new Uint32Array(I.buffer,I.byteOffset,Math.floor(I.byteLength/4))}function f(...I){for(let j=0;j<I.length;j++)I[j].fill(0)}function l(I){return new DataView(I.buffer,I.byteOffset,I.byteLength)}function p(I,j){return I<<32-j|I>>>j}function d(I,j){return I<<j|I>>>32-j>>>0}t.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function m(I){return I<<24&4278190080|I<<8&16711680|I>>>8&65280|I>>>24&255}t.swap8IfBE=t.isLE?I=>I:I=>m(I),t.byteSwapIfBE=t.swap8IfBE;function b(I){for(let j=0;j<I.length;j++)I[j]=m(I[j]);return I}t.swap32IfBE=t.isLE?I=>I:b;const E=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",A=Array.from({length:256},(I,j)=>j.toString(16).padStart(2,"0"));function P(I){if(s(I),E)return I.toHex();let j="";for(let J=0;J<I.length;J++)j+=A[I[J]];return j}const S={_0:48,_9:57,A:65,F:70,a:97,f:102};function w(I){if(I>=S._0&&I<=S._9)return I-S._0;if(I>=S.A&&I<=S.F)return I-(S.A-10);if(I>=S.a&&I<=S.f)return I-(S.a-10)}function k(I){if(typeof I!="string")throw new Error("hex string expected, got "+typeof I);if(E)return Uint8Array.fromHex(I);const j=I.length,J=j/2;if(j%2)throw new Error("hex string expected, got unpadded hex of length "+j);const O=new Uint8Array(J);for(let R=0,F=0;R<J;R++,F+=2){const ne=w(I.charCodeAt(F)),ae=w(I.charCodeAt(F+1));if(ne===void 0||ae===void 0){const le=I[F]+I[F+1];throw new Error('hex string expected, got non-hex character "'+le+'" at index '+F)}O[R]=ne*16+ae}return O}const T=async()=>{};t.nextTick=T;async function B(I,j,J){let O=Date.now();for(let R=0;R<I;R++){J(R);const F=Date.now()-O;F>=0&&F<j||(await(0,t.nextTick)(),O+=F)}}function U(I){if(typeof I!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(I))}function $(I){return new TextDecoder().decode(I)}function D(I){return typeof I=="string"&&(I=U(I)),s(I),I}function M(I){return typeof I=="string"&&(I=U(I)),s(I),I}function q(...I){let j=0;for(let O=0;O<I.length;O++){const R=I[O];s(R),j+=R.length}const J=new Uint8Array(j);for(let O=0,R=0;O<I.length;O++){const F=I[O];J.set(F,R),R+=F.length}return J}function K(I,j){if(j!==void 0&&{}.toString.call(j)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(I,j)}class Q{}t.Hash=Q;function G(I){const j=O=>I().update(D(O)).digest(),J=I();return j.outputLen=J.outputLen,j.blockLen=J.blockLen,j.create=()=>I(),j}function W(I){const j=(O,R)=>I(R).update(D(O)).digest(),J=I({});return j.outputLen=J.outputLen,j.blockLen=J.blockLen,j.create=O=>I(O),j}function ee(I){const j=(O,R)=>I(R).update(D(O)).digest(),J=I({});return j.outputLen=J.outputLen,j.blockLen=J.blockLen,j.create=O=>I(O),j}t.wrapConstructor=G,t.wrapConstructorWithOpts=W,t.wrapXOFConstructorWithOpts=ee;function H(I=32){if(e.crypto&&typeof e.crypto.getRandomValues=="function")return e.crypto.getRandomValues(new Uint8Array(I));if(e.crypto&&typeof e.crypto.randomBytes=="function")return Uint8Array.from(e.crypto.randomBytes(I));throw new Error("crypto.getRandomValues must be defined")}})(Rh);Object.defineProperty(Ot,"__esModule",{value:!0});Ot.SHA512_IV=Ot.SHA384_IV=Ot.SHA224_IV=Ot.SHA256_IV=Ot.HashMD=void 0;Ot.setBigUint64=L1;Ot.Chi=gk;Ot.Maj=wk;const jr=Rh;function L1(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function gk(t,e,r){return t&e^~t&r}function wk(t,e,r){return t&e^t&r^e&r}class vk extends jr.Hash{constructor(e,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=(0,jr.createView)(this.buffer)}update(e){(0,jr.aexists)(this),e=(0,jr.toBytes)(e),(0,jr.abytes)(e);const{view:r,buffer:n,blockLen:s}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=(0,jr.createView)(e);for(;s<=i-o;o+=s)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){(0,jr.aexists)(this),(0,jr.aoutput)(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:o}=this;r[o++]=128,(0,jr.clean)(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let l=o;l<s;l++)r[l]=0;L1(n,s-8,BigInt(this.length*8),i),this.process(n,0);const a=(0,jr.createView)(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:s,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=s,e.pos=a,s%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}}Ot.HashMD=vk;Ot.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);Ot.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);Ot.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);Ot.SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);Object.defineProperty(Nt,"__esModule",{value:!0});Nt.ripemd160=Nt.RIPEMD160=Nt.md5=Nt.MD5=Nt.sha1=Nt.SHA1=void 0;const Bs=Ot,dt=Rh,ui=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),jn=new Uint32Array(80);class D1 extends Bs.HashMD{constructor(){super(64,20,8,!1),this.A=ui[0]|0,this.B=ui[1]|0,this.C=ui[2]|0,this.D=ui[3]|0,this.E=ui[4]|0}get(){const{A:e,B:r,C:n,D:s,E:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0}process(e,r){for(let c=0;c<16;c++,r+=4)jn[c]=e.getUint32(r,!1);for(let c=16;c<80;c++)jn[c]=(0,dt.rotl)(jn[c-3]^jn[c-8]^jn[c-14]^jn[c-16],1);let{A:n,B:s,C:i,D:o,E:a}=this;for(let c=0;c<80;c++){let u,f;c<20?(u=(0,Bs.Chi)(s,i,o),f=1518500249):c<40?(u=s^i^o,f=1859775393):c<60?(u=(0,Bs.Maj)(s,i,o),f=2400959708):(u=s^i^o,f=3395469782);const l=(0,dt.rotl)(n,5)+u+a+f+jn[c]|0;a=o,o=i,i=(0,dt.rotl)(s,30),s=n,n=l}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,this.set(n,s,i,o,a)}roundClean(){(0,dt.clean)(jn)}destroy(){this.set(0,0,0,0,0),(0,dt.clean)(this.buffer)}}Nt.SHA1=D1;Nt.sha1=(0,dt.createHasher)(()=>new D1);const Ek=Math.pow(2,32),Sk=Array.from({length:64},(t,e)=>Math.floor(Ek*Math.abs(Math.sin(e+1)))),Ha=ui.slice(0,4),Xu=new Uint32Array(16);class H1 extends Bs.HashMD{constructor(){super(64,16,8,!0),this.A=Ha[0]|0,this.B=Ha[1]|0,this.C=Ha[2]|0,this.D=Ha[3]|0}get(){const{A:e,B:r,C:n,D:s}=this;return[e,r,n,s]}set(e,r,n,s){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0}process(e,r){for(let a=0;a<16;a++,r+=4)Xu[a]=e.getUint32(r,!0);let{A:n,B:s,C:i,D:o}=this;for(let a=0;a<64;a++){let c,u,f;a<16?(c=(0,Bs.Chi)(s,i,o),u=a,f=[7,12,17,22]):a<32?(c=(0,Bs.Chi)(o,s,i),u=(5*a+1)%16,f=[5,9,14,20]):a<48?(c=s^i^o,u=(3*a+5)%16,f=[4,11,16,23]):(c=i^(s|~o),u=7*a%16,f=[6,10,15,21]),c=c+n+Sk[a]+Xu[u],n=o,o=i,i=s,s=s+(0,dt.rotl)(c,f[a%4])}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,this.set(n,s,i,o)}roundClean(){(0,dt.clean)(Xu)}destroy(){this.set(0,0,0,0),(0,dt.clean)(this.buffer)}}Nt.MD5=H1;Nt.md5=(0,dt.createHasher)(()=>new H1);const Ak=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),z1=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),xk=z1.map(t=>(9*t+5)%16),V1=(()=>{const r=[[z1],[xk]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>Ak[i]));return r})(),q1=V1[0],G1=V1[1],W1=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),kk=q1.map((t,e)=>t.map(r=>W1[e][r])),Tk=G1.map((t,e)=>t.map(r=>W1[e][r])),_k=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Pk=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function E0(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}const za=new Uint32Array(16);class K1 extends Bs.HashMD{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:r,h2:n,h3:s,h4:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=s|0,this.h4=i|0}process(e,r){for(let d=0;d<16;d++,r+=4)za[d]=e.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,o=i,a=this.h2|0,c=a,u=this.h3|0,f=u,l=this.h4|0,p=l;for(let d=0;d<5;d++){const m=4-d,b=_k[d],E=Pk[d],A=q1[d],P=G1[d],S=kk[d],w=Tk[d];for(let k=0;k<16;k++){const T=(0,dt.rotl)(n+E0(d,i,a,u)+za[A[k]]+b,S[k])+l|0;n=l,l=u,u=(0,dt.rotl)(a,10)|0,a=i,i=T}for(let k=0;k<16;k++){const T=(0,dt.rotl)(s+E0(m,o,c,f)+za[P[k]]+E,w[k])+p|0;s=p,p=f,f=(0,dt.rotl)(c,10)|0,c=o,o=T}}this.set(this.h1+a+f|0,this.h2+u+p|0,this.h3+l+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){(0,dt.clean)(za)}destroy(){this.destroyed=!0,(0,dt.clean)(this.buffer),this.set(0,0,0,0,0)}}Nt.RIPEMD160=K1;Nt.ripemd160=(0,dt.createHasher)(()=>new K1);Object.defineProperty(Ni,"__esModule",{value:!0});Ni.sha1=Ni.SHA1=void 0;const Z1=Nt;Ni.SHA1=Z1.SHA1;Ni.sha1=Z1.sha1;const Y1=I1(lE);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.taggedHash=t.TAGGED_HASH_PREFIXES=t.TAGS=t.hash256=t.hash160=t.sha256=t.sha1=t.ripemd160=void 0;const e=bk,r=Ni,n=Y1;function s(f){return Buffer.from((0,e.ripemd160)(Uint8Array.from(f)))}t.ripemd160=s;function i(f){return Buffer.from((0,r.sha1)(Uint8Array.from(f)))}t.sha1=i;function o(f){return Buffer.from((0,n.sha256)(Uint8Array.from(f)))}t.sha256=o;function a(f){return Buffer.from((0,e.ripemd160)((0,n.sha256)(Uint8Array.from(f))))}t.hash160=a;function c(f){return Buffer.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(f))))}t.hash256=c,t.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],t.TAGGED_HASH_PREFIXES={"BIP0340/challenge":Buffer.from([123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124,123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124]),"BIP0340/aux":Buffer.from([241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144,241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144]),"BIP0340/nonce":Buffer.from([7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47,7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47]),TapLeaf:Buffer.from([174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238,174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238]),TapBranch:Buffer.from([25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21,25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21]),TapSighash:Buffer.from([244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49,244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49]),TapTweak:Buffer.from([232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233,232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233]),"KeyAgg list":Buffer.from([72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240,72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240]),"KeyAgg coefficient":Buffer.from([191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129,191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129])};function u(f,l){return o(Buffer.concat([t.TAGGED_HASH_PREFIXES[f],l]))}t.taggedHash=u})(ls);var Ju={},xn={};Object.defineProperty(xn,"__esModule",{value:!0});xn.encode=xn.decode=xn.check=void 0;function Ik(t){if(t.length<8||t.length>72||t[0]!==48||t[1]!==t.length-2||t[2]!==2)return!1;const e=t[3];if(e===0||5+e>=t.length||t[4+e]!==2)return!1;const r=t[5+e];return!(r===0||6+e+r!==t.length||t[4]&128||e>1&&t[4]===0&&!(t[5]&128)||t[e+6]&128||r>1&&t[e+6]===0&&!(t[e+7]&128))}xn.check=Ik;function Ok(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(t[0]!==48)throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(t[2]!==2)throw new Error("Expected DER integer");const e=t[3];if(e===0)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(t[4+e]!==2)throw new Error("Expected DER integer (2)");const r=t[5+e];if(r===0)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(t[4]&128)throw new Error("R value is negative");if(e>1&&t[4]===0&&!(t[5]&128))throw new Error("R value excessively padded");if(t[e+6]&128)throw new Error("S value is negative");if(r>1&&t[e+6]===0&&!(t[e+7]&128))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}}xn.decode=Ok;function Bk(t,e){const r=t.length,n=e.length;if(r===0)throw new Error("R length is zero");if(n===0)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(t[0]&128)throw new Error("R value is negative");if(e[0]&128)throw new Error("S value is negative");if(r>1&&t[0]===0&&!(t[1]&128))throw new Error("R value excessively padded");if(n>1&&e[0]===0&&!(e[1]&128))throw new Error("S value excessively padded");const s=Buffer.allocUnsafe(6+r+n);return s[0]=48,s[1]=s.length-2,s[2]=2,s[3]=t.length,t.copy(s,4),s[4+r]=2,s[5+r]=e.length,e.copy(s,6+r),s}xn.encode=Bk;var zs={};Object.defineProperty(zs,"__esModule",{value:!0});zs.REVERSE_OPS=zs.OPS=void 0;const dd={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};zs.OPS=dd;const X1={};zs.REVERSE_OPS=X1;for(const t of Object.keys(dd)){const e=dd[t];X1[e]=t}var ns={};Object.defineProperty(ns,"__esModule",{value:!0});ns.decode=ns.encode=ns.encodingLength=void 0;const Qn=zs;function J1(t){return t<Qn.OPS.OP_PUSHDATA1?1:t<=255?2:t<=65535?3:5}ns.encodingLength=J1;function Ck(t,e,r){const n=J1(e);return n===1?t.writeUInt8(e,r):n===2?(t.writeUInt8(Qn.OPS.OP_PUSHDATA1,r),t.writeUInt8(e,r+1)):n===3?(t.writeUInt8(Qn.OPS.OP_PUSHDATA2,r),t.writeUInt16LE(e,r+1)):(t.writeUInt8(Qn.OPS.OP_PUSHDATA4,r),t.writeUInt32LE(e,r+1)),n}ns.encode=Ck;function $k(t,e){const r=t.readUInt8(e);let n,s;if(r<Qn.OPS.OP_PUSHDATA1)n=r,s=1;else if(r===Qn.OPS.OP_PUSHDATA1){if(e+2>t.length)return null;n=t.readUInt8(e+1),s=2}else if(r===Qn.OPS.OP_PUSHDATA2){if(e+3>t.length)return null;n=t.readUInt16LE(e+1),s=3}else{if(e+5>t.length)return null;if(r!==Qn.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=t.readUInt32LE(e+1),s=5}return{opcode:r,number:n,size:s}}ns.decode=$k;var Ui={};Object.defineProperty(Ui,"__esModule",{value:!0});Ui.encode=Ui.decode=void 0;function Rk(t,e,r){e=e||4,r=r===void 0?!0:r;const n=t.length;if(n===0)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&!(t[n-1]&127)&&(n<=1||!(t[n-2]&128)))throw new Error("Non-minimally encoded script number");if(n===5){const i=t.readUInt32LE(0),o=t.readUInt8(4);return o&128?-((o&-129)*4294967296+i):o*4294967296+i}let s=0;for(let i=0;i<n;++i)s|=t[i]<<8*i;return t[n-1]&128?-(s&~(128<<8*(n-1))):s}Ui.decode=Rk;function Nk(t){return t>2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}function Uk(t){let e=Math.abs(t);const r=Nk(e),n=Buffer.allocUnsafe(r),s=t<0;for(let i=0;i<r;++i)n.writeUInt8(e&255,i),e>>=8;return n[r-1]&128?n.writeUInt8(s?128:0,r-1):s&&(n[r-1]|=128),n}Ui.encode=Uk;var ys={},S0;function Mk(){if(S0)return ys;S0=1,Object.defineProperty(ys,"__esModule",{value:!0}),ys.encode=ys.decode=void 0;const t=xn,e=er(),r=Et,{typeforce:n}=r,s=Buffer.alloc(1,0);function i(u){let f=0;for(;u[f]===0;)++f;return f===u.length?s:(u=u.slice(f),u[0]&128?Buffer.concat([s,u],1+u.length):u)}function o(u){u[0]===0&&(u=u.slice(1));const f=Buffer.alloc(32,0),l=Math.max(0,32-u.length);return u.copy(f,l),f}function a(u){const f=u.readUInt8(u.length-1);if(!(0,e.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const l=t.decode(u.slice(0,-1)),p=o(l.r),d=o(l.s);return{signature:Buffer.concat([p,d],64),hashType:f}}ys.decode=a;function c(u,f){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:u,hashType:f}),!(0,e.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const l=Buffer.allocUnsafe(1);l.writeUInt8(f,0);const p=i(u.slice(0,32)),d=i(u.slice(32,64));return Buffer.concat([t.encode(p,d),l])}return ys.encode=c,ys}var A0;function er(){return A0||(A0=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.signature=t.number=t.isCanonicalScriptSignature=t.isDefinedHashType=t.isCanonicalPubKey=t.toStack=t.fromASM=t.toASM=t.decompile=t.compile=t.countNonPushOnlyOPs=t.isPushOnly=t.OPS=void 0;const e=xn,r=zs;Object.defineProperty(t,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=ns,s=Ui,i=Mk(),o=Et,{typeforce:a}=o,c=r.OPS.OP_RESERVED;function u($){return o.Number($)&&($===r.OPS.OP_0||$>=r.OPS.OP_1&&$<=r.OPS.OP_16||$===r.OPS.OP_1NEGATE)}function f($){return o.Buffer($)||u($)}function l($){return o.Array($)&&$.every(f)}t.isPushOnly=l;function p($){return $.length-$.filter(f).length}t.countNonPushOnlyOPs=p;function d($){if($.length===0)return r.OPS.OP_0;if($.length===1){if($[0]>=1&&$[0]<=16)return c+$[0];if($[0]===129)return r.OPS.OP_1NEGATE}}function m($){return Buffer.isBuffer($)}function b($){return o.Array($)}function E($){return Buffer.isBuffer($)}function A($){if(m($))return $;a(o.Array,$);const D=$.reduce((K,Q)=>E(Q)?Q.length===1&&d(Q)!==void 0?K+1:K+n.encodingLength(Q.length)+Q.length:K+1,0),M=Buffer.allocUnsafe(D);let q=0;if($.forEach(K=>{if(E(K)){const Q=d(K);if(Q!==void 0){M.writeUInt8(Q,q),q+=1;return}q+=n.encode(M,K.length,q),K.copy(M,q),q+=K.length}else M.writeUInt8(K,q),q+=1}),q!==M.length)throw new Error("Could not decode chunks");return M}t.compile=A;function P($){if(b($))return $;a(o.Buffer,$);const D=[];let M=0;for(;M<$.length;){const q=$[M];if(q>r.OPS.OP_0&&q<=r.OPS.OP_PUSHDATA4){const K=n.decode($,M);if(K===null||(M+=K.size,M+K.number>$.length))return null;const Q=$.slice(M,M+K.number);M+=K.number;const G=d(Q);G!==void 0?D.push(G):D.push(Q)}else D.push(q),M+=1}return D}t.decompile=P;function S($){if(m($)&&($=P($)),!$)throw new Error("Could not convert invalid chunks to ASM");return $.map(D=>{if(E(D)){const M=d(D);if(M===void 0)return D.toString("hex");D=M}return r.REVERSE_OPS[D]}).join(" ")}t.toASM=S;function w($){return a(o.String,$),A($.split(" ").map(D=>r.OPS[D]!==void 0?r.OPS[D]:(a(o.Hex,D),Buffer.from(D,"hex"))))}t.fromASM=w;function k($){return $=P($),a(l,$),$.map(D=>E(D)?D:D===r.OPS.OP_0?Buffer.allocUnsafe(0):s.encode(D-c))}t.toStack=k;function T($){return o.isPoint($)}t.isCanonicalPubKey=T;function B($){const D=$&-129;return D>0&&D<4}t.isDefinedHashType=B;function U($){return!Buffer.isBuffer($)||!B($[$.length-1])?!1:e.check($.slice(0,-1))}t.isCanonicalScriptSignature=U,t.number=s,t.signature=i}(Ju)),Ju}Object.defineProperty(Ta,"__esModule",{value:!0});Ta.Transaction=void 0;const Ye=lt,xt=ls,x0=er(),Fk=er(),Ee=Et,{typeforce:Lr}=Ee;function mr(t){const e=t.length;return Ye.varuint.encodingLength(e)+e}function jk(t){const e=t.length;return Ye.varuint.encodingLength(e)+t.reduce((r,n)=>r+mr(n),0)}const qn=Buffer.allocUnsafe(0),Qu=[],ef=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),k0=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),Lk=Buffer.from("ffffffffffffffff","hex"),Dk={script:qn,valueBuffer:Lk};function Hk(t){return t.value!==void 0}let Rr=class _e{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(e,r){const n=new Ye.BufferReader(e),s=new _e;s.version=n.readInt32();const i=n.readUInt8(),o=n.readUInt8();let a=!1;i===_e.ADVANCED_TRANSACTION_MARKER&&o===_e.ADVANCED_TRANSACTION_FLAG?a=!0:n.offset-=2;const c=n.readVarInt();for(let f=0;f<c;++f)s.ins.push({hash:n.readSlice(32),index:n.readUInt32(),script:n.readVarSlice(),sequence:n.readUInt32(),witness:Qu});const u=n.readVarInt();for(let f=0;f<u;++f)s.outs.push({value:n.readUInt64(),script:n.readVarSlice()});if(a){for(let f=0;f<c;++f)s.ins[f].witness=n.readVector();if(!s.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(s.locktime=n.readUInt32(),r)return s;if(n.offset!==e.length)throw new Error("Transaction has unexpected data");return s}static fromHex(e){return _e.fromBuffer(Buffer.from(e,"hex"),!1)}static isCoinbaseHash(e){Lr(Ee.Hash256bit,e);for(let r=0;r<32;++r)if(e[r]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&_e.isCoinbaseHash(this.ins[0].hash)}addInput(e,r,n,s){return Lr(Ee.tuple(Ee.Hash256bit,Ee.UInt32,Ee.maybe(Ee.UInt32),Ee.maybe(Ee.Buffer)),arguments),Ee.Null(n)&&(n=_e.DEFAULT_SEQUENCE),this.ins.push({hash:e,index:r,script:s||qn,sequence:n,witness:Qu})-1}addOutput(e,r){return Lr(Ee.tuple(Ee.Buffer,Ee.Satoshi),arguments),this.outs.push({script:e,value:r})-1}hasWitnesses(){return this.ins.some(e=>e.witness.length!==0)}stripWitnesses(){this.ins.forEach(e=>{e.witness=Qu})}weight(){const e=this.byteLength(!1),r=this.byteLength(!0);return e*3+r}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(e=!0){const r=e&&this.hasWitnesses();return(r?10:8)+Ye.varuint.encodingLength(this.ins.length)+Ye.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,s)=>n+40+mr(s.script),0)+this.outs.reduce((n,s)=>n+8+mr(s.script),0)+(r?this.ins.reduce((n,s)=>n+jk(s.witness),0):0)}clone(){const e=new _e;return e.version=this.version,e.locktime=this.locktime,e.ins=this.ins.map(r=>({hash:r.hash,index:r.index,script:r.script,sequence:r.sequence,witness:r.witness})),e.outs=this.outs.map(r=>({script:r.script,value:r.value})),e}hashForSignature(e,r,n){if(Lr(Ee.tuple(Ee.UInt32,Ee.Buffer,Ee.Number),arguments),e>=this.ins.length)return k0;const s=x0.compile(x0.decompile(r).filter(a=>a!==Fk.OPS.OP_CODESEPARATOR)),i=this.clone();if((n&31)===_e.SIGHASH_NONE)i.outs=[],i.ins.forEach((a,c)=>{c!==e&&(a.sequence=0)});else if((n&31)===_e.SIGHASH_SINGLE){if(e>=this.outs.length)return k0;i.outs.length=e+1;for(let a=0;a<e;a++)i.outs[a]=Dk;i.ins.forEach((a,c)=>{c!==e&&(a.sequence=0)})}n&_e.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[e]],i.ins[0].script=s):(i.ins.forEach(a=>{a.script=qn}),i.ins[e].script=s);const o=Buffer.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(n,o.length-4),i.__toBuffer(o,0,!1),xt.hash256(o)}hashForWitnessV1(e,r,n,s,i,o){if(console.log("hashForWitnessV1 :"),Lr(Ee.tuple(Ee.UInt32,Lr.arrayOf(Ee.Buffer),Lr.arrayOf(Ee.Satoshi),Ee.UInt32),arguments),n.length!==this.ins.length||r.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const a=s===_e.SIGHASH_DEFAULT?_e.SIGHASH_ALL:s&_e.SIGHASH_OUTPUT_MASK,u=(s&_e.SIGHASH_INPUT_MASK)===_e.SIGHASH_ANYONECANPAY,f=a===_e.SIGHASH_NONE,l=a===_e.SIGHASH_SINGLE;let p=qn,d=qn,m=qn,b=qn,E=qn;if(!u){let w=Ye.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(k=>{w.writeSlice(k.hash),w.writeUInt32(k.index)}),p=xt.sha256(w.end()),w=Ye.BufferWriter.withCapacity(8*this.ins.length),n.forEach(k=>w.writeUInt64(k)),d=xt.sha256(w.end()),console.log("prevOutScripts.map(varSliceSize).reduce((a, b) => a + b), :",r.map(mr).reduce((k,T)=>k+T)),w=Ye.BufferWriter.withCapacity(r.map(mr).reduce((k,T)=>k+T)),r.forEach(k=>w.writeVarSlice(k)),m=xt.sha256(w.end()),w=Ye.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(k=>w.writeUInt32(k.sequence)),b=xt.sha256(w.end())}if(f||l){if(l&&e<this.outs.length){const w=this.outs[e],k=Ye.BufferWriter.withCapacity(8+mr(w.script));k.writeUInt64(w.value),k.writeVarSlice(w.script),E=xt.sha256(k.end())}}else{const w=this.outs.map(T=>8+mr(T.script)).reduce((T,B)=>T+B),k=Ye.BufferWriter.withCapacity(w);this.outs.forEach(T=>{k.writeUInt64(T.value),k.writeVarSlice(T.script)}),E=xt.sha256(k.end())}const A=(i?2:0)+(o?1:0),P=174-(u?49:0)-(f?32:0)+(o?32:0)+(i?37:0),S=Ye.BufferWriter.withCapacity(P);if(S.writeUInt8(s),S.writeInt32(this.version),S.writeUInt32(this.locktime),S.writeSlice(p),S.writeSlice(d),S.writeSlice(m),S.writeSlice(b),f||l||S.writeSlice(E),S.writeUInt8(A),u){const w=this.ins[e];S.writeSlice(w.hash),S.writeUInt32(w.index),S.writeUInt64(n[e]),S.writeVarSlice(r[e]),S.writeUInt32(w.sequence)}else S.writeUInt32(e);if(o){const w=Ye.BufferWriter.withCapacity(mr(o));w.writeVarSlice(o),S.writeSlice(xt.sha256(w.end()))}return l&&S.writeSlice(E),i&&(S.writeSlice(i),S.writeUInt8(0),S.writeUInt32(4294967295)),xt.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),S.end()]))}hashForWitnessV0(e,r,n,s){Lr(Ee.tuple(Ee.UInt32,Ee.Buffer,Ee.Satoshi,Ee.UInt32),arguments);let i=Buffer.from([]),o,a=ef,c=ef,u=ef;if(s&_e.SIGHASH_ANYONECANPAY||(i=Buffer.allocUnsafe(36*this.ins.length),o=new Ye.BufferWriter(i,0),this.ins.forEach(l=>{o.writeSlice(l.hash),o.writeUInt32(l.index)}),c=xt.hash256(i)),!(s&_e.SIGHASH_ANYONECANPAY)&&(s&31)!==_e.SIGHASH_SINGLE&&(s&31)!==_e.SIGHASH_NONE&&(i=Buffer.allocUnsafe(4*this.ins.length),o=new Ye.BufferWriter(i,0),this.ins.forEach(l=>{o.writeUInt32(l.sequence)}),u=xt.hash256(i)),(s&31)!==_e.SIGHASH_SINGLE&&(s&31)!==_e.SIGHASH_NONE){const l=this.outs.reduce((p,d)=>p+8+mr(d.script),0);i=Buffer.allocUnsafe(l),o=new Ye.BufferWriter(i,0),this.outs.forEach(p=>{o.writeUInt64(p.value),o.writeVarSlice(p.script)}),a=xt.hash256(i)}else if((s&31)===_e.SIGHASH_SINGLE&&e<this.outs.length){const l=this.outs[e];i=Buffer.allocUnsafe(8+mr(l.script)),o=new Ye.BufferWriter(i,0),o.writeUInt64(l.value),o.writeVarSlice(l.script),a=xt.hash256(i)}i=Buffer.allocUnsafe(156+mr(r)),o=new Ye.BufferWriter(i,0);const f=this.ins[e];return o.writeInt32(this.version),o.writeSlice(c),o.writeSlice(u),o.writeSlice(f.hash),o.writeUInt32(f.index),o.writeVarSlice(r),o.writeUInt64(n),o.writeUInt32(f.sequence),o.writeSlice(a),o.writeUInt32(this.locktime),o.writeUInt32(s),xt.hash256(i)}getHash(e){return e&&this.isCoinbase()?Buffer.alloc(32,0):xt.hash256(this.__toBuffer(void 0,void 0,e))}getId(){return(0,Ye.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(e,r){return this.__toBuffer(e,r,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(e,r){Lr(Ee.tuple(Ee.Number,Ee.Buffer),arguments),this.ins[e].script=r}setWitness(e,r){Lr(Ee.tuple(Ee.Number,[Ee.Buffer]),arguments),this.ins[e].witness=r}__toBuffer(e,r,n=!1){e||(e=Buffer.allocUnsafe(this.byteLength(n)));const s=new Ye.BufferWriter(e,r||0);s.writeInt32(this.version);const i=n&&this.hasWitnesses();return i&&(s.writeUInt8(_e.ADVANCED_TRANSACTION_MARKER),s.writeUInt8(_e.ADVANCED_TRANSACTION_FLAG)),s.writeVarInt(this.ins.length),this.ins.forEach(o=>{s.writeSlice(o.hash),s.writeUInt32(o.index),s.writeVarSlice(o.script),s.writeUInt32(o.sequence)}),s.writeVarInt(this.outs.length),this.outs.forEach(o=>{Hk(o)?s.writeUInt64(o.value):s.writeSlice(o.valueBuffer),s.writeVarSlice(o.script)}),i&&this.ins.forEach(o=>{s.writeVector(o.witness)}),s.writeUInt32(this.locktime),r!==void 0?e.slice(r,s.offset):e}};Ta.Transaction=Rr;Rr.DEFAULT_SEQUENCE=4294967295;Rr.SIGHASH_DEFAULT=0;Rr.SIGHASH_ALL=1;Rr.SIGHASH_NONE=2;Rr.SIGHASH_SINGLE=3;Rr.SIGHASH_ANYONECANPAY=128;Rr.SIGHASH_OUTPUT_MASK=3;Rr.SIGHASH_INPUT_MASK=128;Rr.ADVANCED_TRANSACTION_MARKER=0;Rr.ADVANCED_TRANSACTION_FLAG=1;var Pe={},_a={};Object.defineProperty(_a,"__esModule",{value:!0});const zk=9007199254740991;function Nh(t){if(t<0||t>zk||t%1!==0)throw new RangeError("value out of range")}function po(t,e,r){if(Nh(t),e||(e=Buffer.allocUnsafe(Q1(t))),!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),t<253?(e.writeUInt8(t,r),Object.assign(po,{bytes:1})):t<=65535?(e.writeUInt8(253,r),e.writeUInt16LE(t,r+1),Object.assign(po,{bytes:3})):t<=4294967295?(e.writeUInt8(254,r),e.writeUInt32LE(t,r+1),Object.assign(po,{bytes:5})):(e.writeUInt8(255,r),e.writeUInt32LE(t>>>0,r+1),e.writeUInt32LE(t/4294967296|0,r+5),Object.assign(po,{bytes:9})),e}_a.encode=po;function yo(t,e){if(!Buffer.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");e||(e=0);const r=t.readUInt8(e);if(r<253)return Object.assign(yo,{bytes:1}),r;if(r===253)return Object.assign(yo,{bytes:3}),t.readUInt16LE(e+1);if(r===254)return Object.assign(yo,{bytes:5}),t.readUInt32LE(e+1);{Object.assign(yo,{bytes:9});const n=t.readUInt32LE(e+1),i=t.readUInt32LE(e+5)*4294967296+n;return Nh(i),i}}_a.decode=yo;function Q1(t){return Nh(t),t<253?1:t<=65535?3:t<=4294967295?5:9}_a.encodingLength=Q1;var tf={},su={},vt={};Object.defineProperty(vt,"__esModule",{value:!0});vt.testnet=vt.regtest=vt.bitcoin=void 0;vt.bitcoin={messagePrefix:`Bitcoin Signed Message:
|
|
51
|
+
*/(function(t){const e=su,r=Oh,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=a,t.SlowBuffer=P,t.INSPECT_MAX_BYTES=50;const s=2147483647;t.kMaxLength=s,a.TYPED_ARRAY_SUPPORT=i(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function i(){try{const v=new Uint8Array(1),h={foo:function(){return 42}};return Object.setPrototypeOf(h,Uint8Array.prototype),Object.setPrototypeOf(v,h),v.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(v){if(v>s)throw new RangeError('The value "'+v+'" is invalid for option "size"');const h=new Uint8Array(v);return Object.setPrototypeOf(h,a.prototype),h}function a(v,h,y){if(typeof v=="number"){if(typeof h=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return l(v)}return c(v,h,y)}a.poolSize=8192;function c(v,h,y){if(typeof v=="string")return p(v,h);if(ArrayBuffer.isView(v))return m(v);if(v==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof v);if(At(v,ArrayBuffer)||v&&At(v.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(At(v,SharedArrayBuffer)||v&&At(v.buffer,SharedArrayBuffer)))return b(v,h,y);if(typeof v=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const x=v.valueOf&&v.valueOf();if(x!=null&&x!==v)return a.from(x,h,y);const C=E(v);if(C)return C;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof v[Symbol.toPrimitive]=="function")return a.from(v[Symbol.toPrimitive]("string"),h,y);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof v)}a.from=function(v,h,y){return c(v,h,y)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function u(v){if(typeof v!="number")throw new TypeError('"size" argument must be of type number');if(v<0)throw new RangeError('The value "'+v+'" is invalid for option "size"')}function f(v,h,y){return u(v),v<=0?o(v):h!==void 0?typeof y=="string"?o(v).fill(h,y):o(v).fill(h):o(v)}a.alloc=function(v,h,y){return f(v,h,y)};function l(v){return u(v),o(v<0?0:A(v)|0)}a.allocUnsafe=function(v){return l(v)},a.allocUnsafeSlow=function(v){return l(v)};function p(v,h){if((typeof h!="string"||h==="")&&(h="utf8"),!a.isEncoding(h))throw new TypeError("Unknown encoding: "+h);const y=S(v,h)|0;let x=o(y);const C=x.write(v,h);return C!==y&&(x=x.slice(0,C)),x}function d(v){const h=v.length<0?0:A(v.length)|0,y=o(h);for(let x=0;x<h;x+=1)y[x]=v[x]&255;return y}function m(v){if(At(v,Uint8Array)){const h=new Uint8Array(v);return b(h.buffer,h.byteOffset,h.byteLength)}return d(v)}function b(v,h,y){if(h<0||v.byteLength<h)throw new RangeError('"offset" is outside of buffer bounds');if(v.byteLength<h+(y||0))throw new RangeError('"length" is outside of buffer bounds');let x;return h===void 0&&y===void 0?x=new Uint8Array(v):y===void 0?x=new Uint8Array(v,h):x=new Uint8Array(v,h,y),Object.setPrototypeOf(x,a.prototype),x}function E(v){if(a.isBuffer(v)){const h=A(v.length)|0,y=o(h);return y.length===0||v.copy(y,0,0,h),y}if(v.length!==void 0)return typeof v.length!="number"||Rn(v.length)?o(0):d(v);if(v.type==="Buffer"&&Array.isArray(v.data))return d(v.data)}function A(v){if(v>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return v|0}function P(v){return+v!=v&&(v=0),a.alloc(+v)}a.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==a.prototype},a.compare=function(h,y){if(At(h,Uint8Array)&&(h=a.from(h,h.offset,h.byteLength)),At(y,Uint8Array)&&(y=a.from(y,y.offset,y.byteLength)),!a.isBuffer(h)||!a.isBuffer(y))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===y)return 0;let x=h.length,C=y.length;for(let U=0,H=Math.min(x,C);U<H;++U)if(h[U]!==y[U]){x=h[U],C=y[U];break}return x<C?-1:C<x?1:0},a.isEncoding=function(h){switch(String(h).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(h,y){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return a.alloc(0);let x;if(y===void 0)for(y=0,x=0;x<h.length;++x)y+=h[x].length;const C=a.allocUnsafe(y);let U=0;for(x=0;x<h.length;++x){let H=h[x];if(At(H,Uint8Array))U+H.length>C.length?(a.isBuffer(H)||(H=a.from(H)),H.copy(C,U)):Uint8Array.prototype.set.call(C,H,U);else if(a.isBuffer(H))H.copy(C,U);else throw new TypeError('"list" argument must be an Array of Buffers');U+=H.length}return C};function S(v,h){if(a.isBuffer(v))return v.length;if(ArrayBuffer.isView(v)||At(v,ArrayBuffer))return v.byteLength;if(typeof v!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof v);const y=v.length,x=arguments.length>2&&arguments[2]===!0;if(!x&&y===0)return 0;let C=!1;for(;;)switch(h){case"ascii":case"latin1":case"binary":return y;case"utf8":case"utf-8":return Nr(v).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return y*2;case"hex":return y>>>1;case"base64":return Ur(v).length;default:if(C)return x?-1:Nr(v).length;h=(""+h).toLowerCase(),C=!0}}a.byteLength=S;function w(v,h,y){let x=!1;if((h===void 0||h<0)&&(h=0),h>this.length||((y===void 0||y>this.length)&&(y=this.length),y<=0)||(y>>>=0,h>>>=0,y<=h))return"";for(v||(v="utf8");;)switch(v){case"hex":return I(this,h,y);case"utf8":case"utf-8":return Q(this,h,y);case"ascii":return re(this,h,y);case"latin1":case"binary":return q(this,h,y);case"base64":return G(this,h,y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,h,y);default:if(x)throw new TypeError("Unknown encoding: "+v);v=(v+"").toLowerCase(),x=!0}}a.prototype._isBuffer=!0;function k(v,h,y){const x=v[h];v[h]=v[y],v[y]=x}a.prototype.swap16=function(){const h=this.length;if(h%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let y=0;y<h;y+=2)k(this,y,y+1);return this},a.prototype.swap32=function(){const h=this.length;if(h%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let y=0;y<h;y+=4)k(this,y,y+3),k(this,y+1,y+2);return this},a.prototype.swap64=function(){const h=this.length;if(h%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let y=0;y<h;y+=8)k(this,y,y+7),k(this,y+1,y+6),k(this,y+2,y+5),k(this,y+3,y+4);return this},a.prototype.toString=function(){const h=this.length;return h===0?"":arguments.length===0?Q(this,0,h):w.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(h){if(!a.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:a.compare(this,h)===0},a.prototype.inspect=function(){let h="";const y=t.INSPECT_MAX_BYTES;return h=this.toString("hex",0,y).replace(/(.{2})/g,"$1 ").trim(),this.length>y&&(h+=" ... "),"<Buffer "+h+">"},n&&(a.prototype[n]=a.prototype.inspect),a.prototype.compare=function(h,y,x,C,U){if(At(h,Uint8Array)&&(h=a.from(h,h.offset,h.byteLength)),!a.isBuffer(h))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof h);if(y===void 0&&(y=0),x===void 0&&(x=h?h.length:0),C===void 0&&(C=0),U===void 0&&(U=this.length),y<0||x>h.length||C<0||U>this.length)throw new RangeError("out of range index");if(C>=U&&y>=x)return 0;if(C>=U)return-1;if(y>=x)return 1;if(y>>>=0,x>>>=0,C>>>=0,U>>>=0,this===h)return 0;let H=U-C,ge=x-y;const ze=Math.min(H,ge),Ue=this.slice(C,U),Ve=h.slice(y,x);for(let Te=0;Te<ze;++Te)if(Ue[Te]!==Ve[Te]){H=Ue[Te],ge=Ve[Te];break}return H<ge?-1:ge<H?1:0};function T(v,h,y,x,C){if(v.length===0)return-1;if(typeof y=="string"?(x=y,y=0):y>2147483647?y=2147483647:y<-2147483648&&(y=-2147483648),y=+y,Rn(y)&&(y=C?0:v.length-1),y<0&&(y=v.length+y),y>=v.length){if(C)return-1;y=v.length-1}else if(y<0)if(C)y=0;else return-1;if(typeof h=="string"&&(h=a.from(h,x)),a.isBuffer(h))return h.length===0?-1:B(v,h,y,x,C);if(typeof h=="number")return h=h&255,typeof Uint8Array.prototype.indexOf=="function"?C?Uint8Array.prototype.indexOf.call(v,h,y):Uint8Array.prototype.lastIndexOf.call(v,h,y):B(v,[h],y,x,C);throw new TypeError("val must be string, number or Buffer")}function B(v,h,y,x,C){let U=1,H=v.length,ge=h.length;if(x!==void 0&&(x=String(x).toLowerCase(),x==="ucs2"||x==="ucs-2"||x==="utf16le"||x==="utf-16le")){if(v.length<2||h.length<2)return-1;U=2,H/=2,ge/=2,y/=2}function ze(Ve,Te){return U===1?Ve[Te]:Ve.readUInt16BE(Te*U)}let Ue;if(C){let Ve=-1;for(Ue=y;Ue<H;Ue++)if(ze(v,Ue)===ze(h,Ve===-1?0:Ue-Ve)){if(Ve===-1&&(Ve=Ue),Ue-Ve+1===ge)return Ve*U}else Ve!==-1&&(Ue-=Ue-Ve),Ve=-1}else for(y+ge>H&&(y=H-ge),Ue=y;Ue>=0;Ue--){let Ve=!0;for(let Te=0;Te<ge;Te++)if(ze(v,Ue+Te)!==ze(h,Te)){Ve=!1;break}if(Ve)return Ue}return-1}a.prototype.includes=function(h,y,x){return this.indexOf(h,y,x)!==-1},a.prototype.indexOf=function(h,y,x){return T(this,h,y,x,!0)},a.prototype.lastIndexOf=function(h,y,x){return T(this,h,y,x,!1)};function N(v,h,y,x){y=Number(y)||0;const C=v.length-y;x?(x=Number(x),x>C&&(x=C)):x=C;const U=h.length;x>U/2&&(x=U/2);let H;for(H=0;H<x;++H){const ge=parseInt(h.substr(H*2,2),16);if(Rn(ge))return H;v[y+H]=ge}return H}function $(v,h,y,x){return St(Nr(h,v.length-y),v,y,x)}function D(v,h,y,x){return St(ds(h),v,y,x)}function M(v,h,y,x){return St(Ur(h),v,y,x)}function V(v,h,y,x){return St(z(h,v.length-y),v,y,x)}a.prototype.write=function(h,y,x,C){if(y===void 0)C="utf8",x=this.length,y=0;else if(x===void 0&&typeof y=="string")C=y,x=this.length,y=0;else if(isFinite(y))y=y>>>0,isFinite(x)?(x=x>>>0,C===void 0&&(C="utf8")):(C=x,x=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const U=this.length-y;if((x===void 0||x>U)&&(x=U),h.length>0&&(x<0||y<0)||y>this.length)throw new RangeError("Attempt to write outside buffer bounds");C||(C="utf8");let H=!1;for(;;)switch(C){case"hex":return N(this,h,y,x);case"utf8":case"utf-8":return $(this,h,y,x);case"ascii":case"latin1":case"binary":return D(this,h,y,x);case"base64":return M(this,h,y,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,h,y,x);default:if(H)throw new TypeError("Unknown encoding: "+C);C=(""+C).toLowerCase(),H=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function G(v,h,y){return h===0&&y===v.length?e.fromByteArray(v):e.fromByteArray(v.slice(h,y))}function Q(v,h,y){y=Math.min(v.length,y);const x=[];let C=h;for(;C<y;){const U=v[C];let H=null,ge=U>239?4:U>223?3:U>191?2:1;if(C+ge<=y){let ze,Ue,Ve,Te;switch(ge){case 1:U<128&&(H=U);break;case 2:ze=v[C+1],(ze&192)===128&&(Te=(U&31)<<6|ze&63,Te>127&&(H=Te));break;case 3:ze=v[C+1],Ue=v[C+2],(ze&192)===128&&(Ue&192)===128&&(Te=(U&15)<<12|(ze&63)<<6|Ue&63,Te>2047&&(Te<55296||Te>57343)&&(H=Te));break;case 4:ze=v[C+1],Ue=v[C+2],Ve=v[C+3],(ze&192)===128&&(Ue&192)===128&&(Ve&192)===128&&(Te=(U&15)<<18|(ze&63)<<12|(Ue&63)<<6|Ve&63,Te>65535&&Te<1114112&&(H=Te))}}H===null?(H=65533,ge=1):H>65535&&(H-=65536,x.push(H>>>10&1023|55296),H=56320|H&1023),x.push(H),C+=ge}return K(x)}const W=4096;function K(v){const h=v.length;if(h<=W)return String.fromCharCode.apply(String,v);let y="",x=0;for(;x<h;)y+=String.fromCharCode.apply(String,v.slice(x,x+=W));return y}function re(v,h,y){let x="";y=Math.min(v.length,y);for(let C=h;C<y;++C)x+=String.fromCharCode(v[C]&127);return x}function q(v,h,y){let x="";y=Math.min(v.length,y);for(let C=h;C<y;++C)x+=String.fromCharCode(v[C]);return x}function I(v,h,y){const x=v.length;(!h||h<0)&&(h=0),(!y||y<0||y>x)&&(y=x);let C="";for(let U=h;U<y;++U)C+=ni[v[U]];return C}function j(v,h,y){const x=v.slice(h,y);let C="";for(let U=0;U<x.length-1;U+=2)C+=String.fromCharCode(x[U]+x[U+1]*256);return C}a.prototype.slice=function(h,y){const x=this.length;h=~~h,y=y===void 0?x:~~y,h<0?(h+=x,h<0&&(h=0)):h>x&&(h=x),y<0?(y+=x,y<0&&(y=0)):y>x&&(y=x),y<h&&(y=h);const C=this.subarray(h,y);return Object.setPrototypeOf(C,a.prototype),C};function J(v,h,y){if(v%1!==0||v<0)throw new RangeError("offset is not uint");if(v+h>y)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(h,y,x){h=h>>>0,y=y>>>0,x||J(h,y,this.length);let C=this[h],U=1,H=0;for(;++H<y&&(U*=256);)C+=this[h+H]*U;return C},a.prototype.readUintBE=a.prototype.readUIntBE=function(h,y,x){h=h>>>0,y=y>>>0,x||J(h,y,this.length);let C=this[h+--y],U=1;for(;y>0&&(U*=256);)C+=this[h+--y]*U;return C},a.prototype.readUint8=a.prototype.readUInt8=function(h,y){return h=h>>>0,y||J(h,1,this.length),this[h]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(h,y){return h=h>>>0,y||J(h,2,this.length),this[h]|this[h+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(h,y){return h=h>>>0,y||J(h,2,this.length),this[h]<<8|this[h+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(h,y){return h=h>>>0,y||J(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(h,y){return h=h>>>0,y||J(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},a.prototype.readBigUInt64LE=Nn(function(h){h=h>>>0,we(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&ke(h,this.length-8);const C=y+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24,U=this[++h]+this[++h]*2**8+this[++h]*2**16+x*2**24;return BigInt(C)+(BigInt(U)<<BigInt(32))}),a.prototype.readBigUInt64BE=Nn(function(h){h=h>>>0,we(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&ke(h,this.length-8);const C=y*2**24+this[++h]*2**16+this[++h]*2**8+this[++h],U=this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+x;return(BigInt(C)<<BigInt(32))+BigInt(U)}),a.prototype.readIntLE=function(h,y,x){h=h>>>0,y=y>>>0,x||J(h,y,this.length);let C=this[h],U=1,H=0;for(;++H<y&&(U*=256);)C+=this[h+H]*U;return U*=128,C>=U&&(C-=Math.pow(2,8*y)),C},a.prototype.readIntBE=function(h,y,x){h=h>>>0,y=y>>>0,x||J(h,y,this.length);let C=y,U=1,H=this[h+--C];for(;C>0&&(U*=256);)H+=this[h+--C]*U;return U*=128,H>=U&&(H-=Math.pow(2,8*y)),H},a.prototype.readInt8=function(h,y){return h=h>>>0,y||J(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},a.prototype.readInt16LE=function(h,y){h=h>>>0,y||J(h,2,this.length);const x=this[h]|this[h+1]<<8;return x&32768?x|4294901760:x},a.prototype.readInt16BE=function(h,y){h=h>>>0,y||J(h,2,this.length);const x=this[h+1]|this[h]<<8;return x&32768?x|4294901760:x},a.prototype.readInt32LE=function(h,y){return h=h>>>0,y||J(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},a.prototype.readInt32BE=function(h,y){return h=h>>>0,y||J(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},a.prototype.readBigInt64LE=Nn(function(h){h=h>>>0,we(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&ke(h,this.length-8);const C=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(x<<24);return(BigInt(C)<<BigInt(32))+BigInt(y+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24)}),a.prototype.readBigInt64BE=Nn(function(h){h=h>>>0,we(h,"offset");const y=this[h],x=this[h+7];(y===void 0||x===void 0)&&ke(h,this.length-8);const C=(y<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt(C)<<BigInt(32))+BigInt(this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+x)}),a.prototype.readFloatLE=function(h,y){return h=h>>>0,y||J(h,4,this.length),r.read(this,h,!0,23,4)},a.prototype.readFloatBE=function(h,y){return h=h>>>0,y||J(h,4,this.length),r.read(this,h,!1,23,4)},a.prototype.readDoubleLE=function(h,y){return h=h>>>0,y||J(h,8,this.length),r.read(this,h,!0,52,8)},a.prototype.readDoubleBE=function(h,y){return h=h>>>0,y||J(h,8,this.length),r.read(this,h,!1,52,8)};function O(v,h,y,x,C,U){if(!a.isBuffer(v))throw new TypeError('"buffer" argument must be a Buffer instance');if(h>C||h<U)throw new RangeError('"value" argument is out of bounds');if(y+x>v.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(h,y,x,C){if(h=+h,y=y>>>0,x=x>>>0,!C){const ge=Math.pow(2,8*x)-1;O(this,h,y,x,ge,0)}let U=1,H=0;for(this[y]=h&255;++H<x&&(U*=256);)this[y+H]=h/U&255;return y+x},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(h,y,x,C){if(h=+h,y=y>>>0,x=x>>>0,!C){const ge=Math.pow(2,8*x)-1;O(this,h,y,x,ge,0)}let U=x-1,H=1;for(this[y+U]=h&255;--U>=0&&(H*=256);)this[y+U]=h/H&255;return y+x},a.prototype.writeUint8=a.prototype.writeUInt8=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,1,255,0),this[y]=h&255,y+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,65535,0),this[y]=h&255,this[y+1]=h>>>8,y+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,65535,0),this[y]=h>>>8,this[y+1]=h&255,y+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,4294967295,0),this[y+3]=h>>>24,this[y+2]=h>>>16,this[y+1]=h>>>8,this[y]=h&255,y+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,4294967295,0),this[y]=h>>>24,this[y+1]=h>>>16,this[y+2]=h>>>8,this[y+3]=h&255,y+4};function R(v,h,y,x,C){be(h,x,C,v,y,7);let U=Number(h&BigInt(4294967295));v[y++]=U,U=U>>8,v[y++]=U,U=U>>8,v[y++]=U,U=U>>8,v[y++]=U;let H=Number(h>>BigInt(32)&BigInt(4294967295));return v[y++]=H,H=H>>8,v[y++]=H,H=H>>8,v[y++]=H,H=H>>8,v[y++]=H,y}function F(v,h,y,x,C){be(h,x,C,v,y,7);let U=Number(h&BigInt(4294967295));v[y+7]=U,U=U>>8,v[y+6]=U,U=U>>8,v[y+5]=U,U=U>>8,v[y+4]=U;let H=Number(h>>BigInt(32)&BigInt(4294967295));return v[y+3]=H,H=H>>8,v[y+2]=H,H=H>>8,v[y+1]=H,H=H>>8,v[y]=H,y+8}a.prototype.writeBigUInt64LE=Nn(function(h,y=0){return R(this,h,y,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=Nn(function(h,y=0){return F(this,h,y,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(h,y,x,C){if(h=+h,y=y>>>0,!C){const ze=Math.pow(2,8*x-1);O(this,h,y,x,ze-1,-ze)}let U=0,H=1,ge=0;for(this[y]=h&255;++U<x&&(H*=256);)h<0&&ge===0&&this[y+U-1]!==0&&(ge=1),this[y+U]=(h/H>>0)-ge&255;return y+x},a.prototype.writeIntBE=function(h,y,x,C){if(h=+h,y=y>>>0,!C){const ze=Math.pow(2,8*x-1);O(this,h,y,x,ze-1,-ze)}let U=x-1,H=1,ge=0;for(this[y+U]=h&255;--U>=0&&(H*=256);)h<0&&ge===0&&this[y+U+1]!==0&&(ge=1),this[y+U]=(h/H>>0)-ge&255;return y+x},a.prototype.writeInt8=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,1,127,-128),h<0&&(h=255+h+1),this[y]=h&255,y+1},a.prototype.writeInt16LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,32767,-32768),this[y]=h&255,this[y+1]=h>>>8,y+2},a.prototype.writeInt16BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,2,32767,-32768),this[y]=h>>>8,this[y+1]=h&255,y+2},a.prototype.writeInt32LE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,2147483647,-2147483648),this[y]=h&255,this[y+1]=h>>>8,this[y+2]=h>>>16,this[y+3]=h>>>24,y+4},a.prototype.writeInt32BE=function(h,y,x){return h=+h,y=y>>>0,x||O(this,h,y,4,2147483647,-2147483648),h<0&&(h=4294967295+h+1),this[y]=h>>>24,this[y+1]=h>>>16,this[y+2]=h>>>8,this[y+3]=h&255,y+4},a.prototype.writeBigInt64LE=Nn(function(h,y=0){return R(this,h,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=Nn(function(h,y=0){return F(this,h,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ne(v,h,y,x,C,U){if(y+x>v.length)throw new RangeError("Index out of range");if(y<0)throw new RangeError("Index out of range")}function ae(v,h,y,x,C){return h=+h,y=y>>>0,C||ne(v,h,y,4),r.write(v,h,y,x,23,4),y+4}a.prototype.writeFloatLE=function(h,y,x){return ae(this,h,y,!0,x)},a.prototype.writeFloatBE=function(h,y,x){return ae(this,h,y,!1,x)};function le(v,h,y,x,C){return h=+h,y=y>>>0,C||ne(v,h,y,8),r.write(v,h,y,x,52,8),y+8}a.prototype.writeDoubleLE=function(h,y,x){return le(this,h,y,!0,x)},a.prototype.writeDoubleBE=function(h,y,x){return le(this,h,y,!1,x)},a.prototype.copy=function(h,y,x,C){if(!a.isBuffer(h))throw new TypeError("argument should be a Buffer");if(x||(x=0),!C&&C!==0&&(C=this.length),y>=h.length&&(y=h.length),y||(y=0),C>0&&C<x&&(C=x),C===x||h.length===0||this.length===0)return 0;if(y<0)throw new RangeError("targetStart out of bounds");if(x<0||x>=this.length)throw new RangeError("Index out of range");if(C<0)throw new RangeError("sourceEnd out of bounds");C>this.length&&(C=this.length),h.length-y<C-x&&(C=h.length-y+x);const U=C-x;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(y,x,C):Uint8Array.prototype.set.call(h,this.subarray(x,C),y),U},a.prototype.fill=function(h,y,x,C){if(typeof h=="string"){if(typeof y=="string"?(C=y,y=0,x=this.length):typeof x=="string"&&(C=x,x=this.length),C!==void 0&&typeof C!="string")throw new TypeError("encoding must be a string");if(typeof C=="string"&&!a.isEncoding(C))throw new TypeError("Unknown encoding: "+C);if(h.length===1){const H=h.charCodeAt(0);(C==="utf8"&&H<128||C==="latin1")&&(h=H)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));if(y<0||this.length<y||this.length<x)throw new RangeError("Out of range index");if(x<=y)return this;y=y>>>0,x=x===void 0?this.length:x>>>0,h||(h=0);let U;if(typeof h=="number")for(U=y;U<x;++U)this[U]=h;else{const H=a.isBuffer(h)?h:a.from(h,C),ge=H.length;if(ge===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for(U=0;U<x-y;++U)this[U+y]=H[U%ge]}return this};const ue={};function oe(v,h,y){ue[v]=class extends y{constructor(){super(),Object.defineProperty(this,"message",{value:h.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${v}]`,this.stack,delete this.name}get code(){return v}set code(C){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:C,writable:!0})}toString(){return`${this.name} [${v}]: ${this.message}`}}}oe("ERR_BUFFER_OUT_OF_BOUNDS",function(v){return v?`${v} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),oe("ERR_INVALID_ARG_TYPE",function(v,h){return`The "${v}" argument must be of type number. Received type ${typeof h}`},TypeError),oe("ERR_OUT_OF_RANGE",function(v,h,y){let x=`The value of "${v}" is out of range.`,C=y;return Number.isInteger(y)&&Math.abs(y)>2**32?C=ie(String(y)):typeof y=="bigint"&&(C=String(y),(y>BigInt(2)**BigInt(32)||y<-(BigInt(2)**BigInt(32)))&&(C=ie(C)),C+="n"),x+=` It must be ${h}. Received ${C}`,x},RangeError);function ie(v){let h="",y=v.length;const x=v[0]==="-"?1:0;for(;y>=x+4;y-=3)h=`_${v.slice(y-3,y)}${h}`;return`${v.slice(0,y)}${h}`}function me(v,h,y){we(h,"offset"),(v[h]===void 0||v[h+y]===void 0)&&ke(h,v.length-(y+1))}function be(v,h,y,x,C,U){if(v>y||v<h){const H=typeof h=="bigint"?"n":"";let ge;throw h===0||h===BigInt(0)?ge=`>= 0${H} and < 2${H} ** ${(U+1)*8}${H}`:ge=`>= -(2${H} ** ${(U+1)*8-1}${H}) and < 2 ** ${(U+1)*8-1}${H}`,new ue.ERR_OUT_OF_RANGE("value",ge,v)}me(x,C,U)}function we(v,h){if(typeof v!="number")throw new ue.ERR_INVALID_ARG_TYPE(h,"number",v)}function ke(v,h,y){throw Math.floor(v)!==v?(we(v,y),new ue.ERR_OUT_OF_RANGE("offset","an integer",v)):h<0?new ue.ERR_BUFFER_OUT_OF_BOUNDS:new ue.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${h}`,v)}const tt=/[^+/0-9A-Za-z-_]/g;function Oe(v){if(v=v.split("=")[0],v=v.trim().replace(tt,""),v.length<2)return"";for(;v.length%4!==0;)v=v+"=";return v}function Nr(v,h){h=h||1/0;let y;const x=v.length;let C=null;const U=[];for(let H=0;H<x;++H){if(y=v.charCodeAt(H),y>55295&&y<57344){if(!C){if(y>56319){(h-=3)>-1&&U.push(239,191,189);continue}else if(H+1===x){(h-=3)>-1&&U.push(239,191,189);continue}C=y;continue}if(y<56320){(h-=3)>-1&&U.push(239,191,189),C=y;continue}y=(C-55296<<10|y-56320)+65536}else C&&(h-=3)>-1&&U.push(239,191,189);if(C=null,y<128){if((h-=1)<0)break;U.push(y)}else if(y<2048){if((h-=2)<0)break;U.push(y>>6|192,y&63|128)}else if(y<65536){if((h-=3)<0)break;U.push(y>>12|224,y>>6&63|128,y&63|128)}else if(y<1114112){if((h-=4)<0)break;U.push(y>>18|240,y>>12&63|128,y>>6&63|128,y&63|128)}else throw new Error("Invalid code point")}return U}function ds(v){const h=[];for(let y=0;y<v.length;++y)h.push(v.charCodeAt(y)&255);return h}function z(v,h){let y,x,C;const U=[];for(let H=0;H<v.length&&!((h-=2)<0);++H)y=v.charCodeAt(H),x=y>>8,C=y%256,U.push(C),U.push(x);return U}function Ur(v){return e.toByteArray(Oe(v))}function St(v,h,y,x){let C;for(C=0;C<x&&!(C+y>=h.length||C>=v.length);++C)h[C+y]=v[C];return C}function At(v,h){return v instanceof h||v!=null&&v.constructor!=null&&v.constructor.name!=null&&v.constructor.name===h.name}function Rn(v){return v!==v}const ni=function(){const v="0123456789abcdef",h=new Array(256);for(let y=0;y<16;++y){const x=y*16;for(let C=0;C<16;++C)h[x+C]=v[y]+v[C]}return h}();function Nn(v){return typeof BigInt>"u"?t6:v}function t6(){throw new Error("BigInt not supported")}})(Qs);var ea={Array:function(t){return t!=null&&t.constructor===Array},Boolean:function(t){return typeof t=="boolean"},Function:function(t){return typeof t=="function"},Nil:function(t){return t==null},Number:function(t){return typeof t=="number"},Object:function(t){return typeof t=="object"},String:function(t){return typeof t=="string"},"":function(){return!0}};ea.Null=ea.Nil;for(var w0 in ea)ea[w0].toJSON=(function(t){return t}).bind(null,w0);var Bh=ea,Is=Bh;function B1(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function Ch(t){return Is.Nil(t)?"":B1(t.constructor)}function ak(t){return Is.Function(t)?"":Is.String(t)?JSON.stringify(t):t&&Is.Object(t)?"":t}function $h(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function Sc(t){return Is.Function(t)?t.toJSON?t.toJSON():B1(t):Is.Array(t)?"Array":t&&Is.Object(t)?"Object":t!==void 0?t:""}function C1(t,e,r){var n=ak(e);return"Expected "+Sc(t)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function Pn(t,e,r){r=r||Ch(e),this.message=C1(t,e,r),$h(this,Pn),this.__type=t,this.__value=e,this.__valueTypeName=r}Pn.prototype=Object.create(Error.prototype);Pn.prototype.constructor=Pn;function ck(t,e,r,n,s){var i='" of type ';return e==="key"&&(i='" with key type '),C1('property "'+Sc(r)+i+Sc(t),n,s)}function ki(t,e,r,n,s){t?(s=s||Ch(n),this.message=ck(t,r,e,n,s)):this.message='Unexpected property "'+e+'"',$h(this,Pn),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=s}ki.prototype=Object.create(Error.prototype);ki.prototype.constructor=Pn;function uk(t,e){return new Pn(t,{},e)}function fk(t,e,r){return t instanceof ki?(e=e+"."+t.__property,t=new ki(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof Pn&&(t=new ki(t.__type,e,r,t.__value,t.__valueTypeName)),$h(t),t}var $1={TfTypeError:Pn,TfPropertyTypeError:ki,tfCustomError:uk,tfSubError:fk,tfJSON:Sc,getValueTypeName:Ch},Ju,v0;function lk(){if(v0)return Ju;v0=1;var t=Bh,e=$1;function r(T){return Buffer.isBuffer(T)}function n(T){return typeof T=="string"&&/^([0-9a-f]{2})+$/i.test(T)}function s(T,B){var N=T.toJSON();function $(D){if(!T(D))return!1;if(D.length===B)return!0;throw e.tfCustomError(N+"(Length: "+B+")",N+"(Length: "+D.length+")")}return $.toJSON=function(){return N},$}var i=s.bind(null,t.Array),o=s.bind(null,r),a=s.bind(null,n),c=s.bind(null,t.String);function u(T,B,N){N=N||t.Number;function $(D,M){return N(D,M)&&D>T&&D<B}return $.toJSON=function(){return`${N.toJSON()} between [${T}, ${B}]`},$}var f=Math.pow(2,53)-1;function l(T){return typeof T=="number"&&isFinite(T)}function p(T){return T<<24>>24===T}function d(T){return T<<16>>16===T}function m(T){return(T|0)===T}function b(T){return typeof T=="number"&&T>=-f&&T<=f&&Math.floor(T)===T}function E(T){return(T&255)===T}function A(T){return(T&65535)===T}function P(T){return T>>>0===T}function S(T){return typeof T=="number"&&T>=0&&T<=f&&Math.floor(T)===T}var w={ArrayN:i,Buffer:r,BufferN:o,Finite:l,Hex:n,HexN:a,Int8:p,Int16:d,Int32:m,Int53:b,Range:u,StringN:c,UInt8:E,UInt16:A,UInt32:P,UInt53:S};for(var k in w)w[k].toJSON=(function(T){return T}).bind(null,k);return Ju=w,Ju}var ka=$1,ft=Bh,sn=ka.tfJSON,R1=ka.TfTypeError,N1=ka.TfPropertyTypeError,so=ka.tfSubError,dk=ka.getValueTypeName,gn={arrayOf:function(e,r){e=qr(e),r=r||{};function n(s,i){return!ft.Array(s)||ft.Nil(s)||r.minLength!==void 0&&s.length<r.minLength||r.maxLength!==void 0&&s.length>r.maxLength||r.length!==void 0&&s.length!==r.length?!1:s.every(function(o,a){try{return Pt(e,o,i)}catch(c){throw so(c,a)}})}return n.toJSON=function(){var s="["+sn(e)+"]";return r.length!==void 0?s+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(s+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),s},n},maybe:function t(e){e=qr(e);function r(n,s){return ft.Nil(n)||e(n,s,t)}return r.toJSON=function(){return"?"+sn(e)},r},map:function(e,r){e=qr(e),r&&(r=qr(r));function n(s,i){if(!ft.Object(s)||ft.Nil(s))return!1;for(var o in s){try{r&&Pt(r,o,i)}catch(c){throw so(c,o,"key")}try{var a=s[o];Pt(e,a,i)}catch(c){throw so(c,o)}}return!0}return r?n.toJSON=function(){return"{"+sn(r)+": "+sn(e)+"}"}:n.toJSON=function(){return"{"+sn(e)+"}"},n},object:function(e){var r={};for(var n in e)r[n]=qr(e[n]);function s(i,o){if(!ft.Object(i)||ft.Nil(i))return!1;var a;try{for(a in r){var c=r[a],u=i[a];Pt(c,u,o)}}catch(f){throw so(f,a)}if(o){for(a in i)if(!r[a])throw new N1(void 0,a)}return!0}return s.toJSON=function(){return sn(r)},s},anyOf:function(){var e=[].slice.call(arguments).map(qr);function r(n,s){return e.some(function(i){try{return Pt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return e.map(sn).join("|")},r},allOf:function(){var e=[].slice.call(arguments).map(qr);function r(n,s){return e.every(function(i){try{return Pt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return e.map(sn).join(" & ")},r},quacksLike:function(e){function r(n){return e===dk(n)}return r.toJSON=function(){return e},r},tuple:function(){var e=[].slice.call(arguments).map(qr);function r(n,s){return ft.Nil(n)||ft.Nil(n.length)||s&&n.length!==e.length?!1:e.every(function(i,o){try{return Pt(i,n[o],s)}catch(a){throw so(a,o)}})}return r.toJSON=function(){return"("+e.map(sn).join(", ")+")"},r},value:function(e){function r(n){return n===e}return r.toJSON=function(){return e},r}};gn.oneOf=gn.anyOf;function qr(t){if(ft.String(t))return t[0]==="?"?gn.maybe(t.slice(1)):ft[t]||gn.quacksLike(t);if(t&&ft.Object(t)){if(ft.Array(t)){if(t.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return gn.arrayOf(t[0])}return gn.object(t)}else if(ft.Function(t))return t;return gn.value(t)}function Pt(t,e,r,n){if(ft.Function(t)){if(t(e,r))return!0;throw new R1(n||t,e)}return Pt(qr(t),e,r)}for(var rs in ft)Pt[rs]=ft[rs];for(rs in gn)Pt[rs]=gn[rs];var E0=lk();for(rs in E0)Pt[rs]=E0[rs];Pt.compile=qr;Pt.TfTypeError=R1;Pt.TfPropertyTypeError=N1;var hk=Pt;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.oneOf=t.Null=t.BufferN=t.Function=t.UInt32=t.UInt8=t.tuple=t.maybe=t.Hex=t.Buffer=t.String=t.Boolean=t.Array=t.Number=t.Hash256bit=t.Hash160bit=t.Buffer256bit=t.isTaptree=t.isTapleaf=t.TAPLEAF_VERSION_MASK=t.Satoshi=t.isPoint=t.stacksEqual=t.typeforce=void 0;const e=Qs;t.typeforce=hk;const r=e.Buffer.alloc(32,0),n=e.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function s(f,l){return f.length!==l.length?!1:f.every((p,d)=>p.equals(l[d]))}t.stacksEqual=s;function i(f){if(!e.Buffer.isBuffer(f)||f.length<33)return!1;const l=f[0],p=f.slice(1,33);if(p.compare(r)===0||p.compare(n)>=0)return!1;if((l===2||l===3)&&f.length===33)return!0;const d=f.slice(33);return d.compare(r)===0||d.compare(n)>=0?!1:l===4&&f.length===65}t.isPoint=i;const o=21*1e14;function a(f){return t.typeforce.UInt53(f)&&f<=o}t.Satoshi=a,t.TAPLEAF_VERSION_MASK=254;function c(f){return!f||!("output"in f)||!e.Buffer.isBuffer(f.output)?!1:f.version!==void 0?(f.version&t.TAPLEAF_VERSION_MASK)===f.version:!0}t.isTapleaf=c;function u(f){return(0,t.Array)(f)?f.length!==2?!1:f.every(l=>u(l)):c(f)}t.isTaptree=u,t.Buffer256bit=t.typeforce.BufferN(32),t.Hash160bit=t.typeforce.BufferN(20),t.Hash256bit=t.typeforce.BufferN(32),t.Number=t.typeforce.Number,t.Array=t.typeforce.Array,t.Boolean=t.typeforce.Boolean,t.String=t.typeforce.String,t.Buffer=t.typeforce.Buffer,t.Hex=t.typeforce.Hex,t.maybe=t.typeforce.maybe,t.tuple=t.typeforce.tuple,t.UInt8=t.typeforce.UInt8,t.UInt32=t.typeforce.UInt32,t.Function=t.typeforce.Function,t.BufferN=t.typeforce.BufferN,t.Null=t.typeforce.Null,t.oneOf=t.typeforce.oneOf})(Et);var Ta={},lt={};Object.defineProperty(lt,"__esModule",{value:!0});lt.BufferReader=lt.BufferWriter=lt.cloneBuffer=lt.reverseBuffer=lt.writeUInt64LE=lt.readUInt64LE=lt.varuint=void 0;const Os=Et,{typeforce:U1}=Os,ta=ym;lt.varuint=ta;function M1(t,e){if(typeof t!="number")throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function F1(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,M1(n+r,9007199254740991),n+r}lt.readUInt64LE=F1;function j1(t,e,r){return M1(e,9007199254740991),t.writeInt32LE(e&-1,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}lt.writeUInt64LE=j1;function pk(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n<t.length/2;n++)r=t[n],t[n]=t[e],t[e]=r,e--;return t}lt.reverseBuffer=pk;function yk(t){const e=Buffer.allocUnsafe(t.length);return t.copy(e),e}lt.cloneBuffer=yk;class Rh{static withCapacity(e){return new Rh(Buffer.alloc(e))}constructor(e,r=0){this.buffer=e,this.offset=r,U1(Os.tuple(Os.Buffer,Os.UInt32),[e,r])}writeUInt8(e){this.offset=this.buffer.writeUInt8(e,this.offset)}writeInt32(e){this.offset=this.buffer.writeInt32LE(e,this.offset)}writeUInt32(e){this.offset=this.buffer.writeUInt32LE(e,this.offset)}writeUInt64(e){this.offset=j1(this.buffer,e,this.offset)}writeVarInt(e){ta.encode(e,this.buffer,this.offset),this.offset+=ta.encode.bytes}writeSlice(e){if(this.buffer.length<this.offset+e.length)throw new Error("Cannot write slice out of bounds");this.offset+=e.copy(this.buffer,this.offset)}writeVarSlice(e){this.writeVarInt(e.length),this.writeSlice(e)}writeVector(e){this.writeVarInt(e.length),e.forEach(r=>this.writeVarSlice(r))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}lt.BufferWriter=Rh;class mk{constructor(e,r=0){this.buffer=e,this.offset=r,U1(Os.tuple(Os.Buffer,Os.UInt32),[e,r])}readUInt8(){const e=this.buffer.readUInt8(this.offset);return this.offset++,e}readInt32(){const e=this.buffer.readInt32LE(this.offset);return this.offset+=4,e}readUInt32(){const e=this.buffer.readUInt32LE(this.offset);return this.offset+=4,e}readUInt64(){const e=F1(this.buffer,this.offset);return this.offset+=8,e}readVarInt(){const e=ta.decode(this.buffer,this.offset);return this.offset+=ta.decode.bytes,e}readSlice(e){if(this.buffer.length<this.offset+e)throw new Error("Cannot read slice out of bounds");const r=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,r}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const e=this.readVarInt(),r=[];for(let n=0;n<e;n++)r.push(this.readVarSlice());return r}}lt.BufferReader=mk;var ls={};const bk=I1(yA);var Ni={},Nt={},Ot={},Nh={},iu={};Object.defineProperty(iu,"__esModule",{value:!0});iu.crypto=void 0;iu.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;(function(t){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(t,"__esModule",{value:!0}),t.wrapXOFConstructorWithOpts=t.wrapConstructorWithOpts=t.wrapConstructor=t.Hash=t.nextTick=t.swap32IfBE=t.byteSwapIfBE=t.swap8IfBE=t.isLE=void 0,t.isBytes=r,t.anumber=n,t.abytes=s,t.ahash=i,t.aexists=o,t.aoutput=a,t.u8=c,t.u32=u,t.clean=f,t.createView=l,t.rotr=p,t.rotl=d,t.byteSwap=m,t.byteSwap32=b,t.bytesToHex=P,t.hexToBytes=k,t.asyncLoop=B,t.utf8ToBytes=N,t.bytesToUtf8=$,t.toBytes=D,t.kdfInputToBytes=M,t.concatBytes=V,t.checkOpts=G,t.createHasher=W,t.createOptHasher=K,t.createXOFer=re,t.randomBytes=q;const e=iu;function r(I){return I instanceof Uint8Array||ArrayBuffer.isView(I)&&I.constructor.name==="Uint8Array"}function n(I){if(!Number.isSafeInteger(I)||I<0)throw new Error("positive integer expected, got "+I)}function s(I,...j){if(!r(I))throw new Error("Uint8Array expected");if(j.length>0&&!j.includes(I.length))throw new Error("Uint8Array expected of length "+j+", got length="+I.length)}function i(I){if(typeof I!="function"||typeof I.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");n(I.outputLen),n(I.blockLen)}function o(I,j=!0){if(I.destroyed)throw new Error("Hash instance has been destroyed");if(j&&I.finished)throw new Error("Hash#digest() has already been called")}function a(I,j){s(I);const J=j.outputLen;if(I.length<J)throw new Error("digestInto() expects output buffer of length at least "+J)}function c(I){return new Uint8Array(I.buffer,I.byteOffset,I.byteLength)}function u(I){return new Uint32Array(I.buffer,I.byteOffset,Math.floor(I.byteLength/4))}function f(...I){for(let j=0;j<I.length;j++)I[j].fill(0)}function l(I){return new DataView(I.buffer,I.byteOffset,I.byteLength)}function p(I,j){return I<<32-j|I>>>j}function d(I,j){return I<<j|I>>>32-j>>>0}t.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function m(I){return I<<24&4278190080|I<<8&16711680|I>>>8&65280|I>>>24&255}t.swap8IfBE=t.isLE?I=>I:I=>m(I),t.byteSwapIfBE=t.swap8IfBE;function b(I){for(let j=0;j<I.length;j++)I[j]=m(I[j]);return I}t.swap32IfBE=t.isLE?I=>I:b;const E=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",A=Array.from({length:256},(I,j)=>j.toString(16).padStart(2,"0"));function P(I){if(s(I),E)return I.toHex();let j="";for(let J=0;J<I.length;J++)j+=A[I[J]];return j}const S={_0:48,_9:57,A:65,F:70,a:97,f:102};function w(I){if(I>=S._0&&I<=S._9)return I-S._0;if(I>=S.A&&I<=S.F)return I-(S.A-10);if(I>=S.a&&I<=S.f)return I-(S.a-10)}function k(I){if(typeof I!="string")throw new Error("hex string expected, got "+typeof I);if(E)return Uint8Array.fromHex(I);const j=I.length,J=j/2;if(j%2)throw new Error("hex string expected, got unpadded hex of length "+j);const O=new Uint8Array(J);for(let R=0,F=0;R<J;R++,F+=2){const ne=w(I.charCodeAt(F)),ae=w(I.charCodeAt(F+1));if(ne===void 0||ae===void 0){const le=I[F]+I[F+1];throw new Error('hex string expected, got non-hex character "'+le+'" at index '+F)}O[R]=ne*16+ae}return O}const T=async()=>{};t.nextTick=T;async function B(I,j,J){let O=Date.now();for(let R=0;R<I;R++){J(R);const F=Date.now()-O;F>=0&&F<j||(await(0,t.nextTick)(),O+=F)}}function N(I){if(typeof I!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(I))}function $(I){return new TextDecoder().decode(I)}function D(I){return typeof I=="string"&&(I=N(I)),s(I),I}function M(I){return typeof I=="string"&&(I=N(I)),s(I),I}function V(...I){let j=0;for(let O=0;O<I.length;O++){const R=I[O];s(R),j+=R.length}const J=new Uint8Array(j);for(let O=0,R=0;O<I.length;O++){const F=I[O];J.set(F,R),R+=F.length}return J}function G(I,j){if(j!==void 0&&{}.toString.call(j)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(I,j)}class Q{}t.Hash=Q;function W(I){const j=O=>I().update(D(O)).digest(),J=I();return j.outputLen=J.outputLen,j.blockLen=J.blockLen,j.create=()=>I(),j}function K(I){const j=(O,R)=>I(R).update(D(O)).digest(),J=I({});return j.outputLen=J.outputLen,j.blockLen=J.blockLen,j.create=O=>I(O),j}function re(I){const j=(O,R)=>I(R).update(D(O)).digest(),J=I({});return j.outputLen=J.outputLen,j.blockLen=J.blockLen,j.create=O=>I(O),j}t.wrapConstructor=W,t.wrapConstructorWithOpts=K,t.wrapXOFConstructorWithOpts=re;function q(I=32){if(e.crypto&&typeof e.crypto.getRandomValues=="function")return e.crypto.getRandomValues(new Uint8Array(I));if(e.crypto&&typeof e.crypto.randomBytes=="function")return Uint8Array.from(e.crypto.randomBytes(I));throw new Error("crypto.getRandomValues must be defined")}})(Nh);Object.defineProperty(Ot,"__esModule",{value:!0});Ot.SHA512_IV=Ot.SHA384_IV=Ot.SHA224_IV=Ot.SHA256_IV=Ot.HashMD=void 0;Ot.setBigUint64=L1;Ot.Chi=gk;Ot.Maj=wk;const jr=Nh;function L1(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function gk(t,e,r){return t&e^~t&r}function wk(t,e,r){return t&e^t&r^e&r}class vk extends jr.Hash{constructor(e,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=(0,jr.createView)(this.buffer)}update(e){(0,jr.aexists)(this),e=(0,jr.toBytes)(e),(0,jr.abytes)(e);const{view:r,buffer:n,blockLen:s}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=(0,jr.createView)(e);for(;s<=i-o;o+=s)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){(0,jr.aexists)(this),(0,jr.aoutput)(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:o}=this;r[o++]=128,(0,jr.clean)(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let l=o;l<s;l++)r[l]=0;L1(n,s-8,BigInt(this.length*8),i),this.process(n,0);const a=(0,jr.createView)(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:s,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=s,e.pos=a,s%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}}Ot.HashMD=vk;Ot.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);Ot.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);Ot.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);Ot.SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);Object.defineProperty(Nt,"__esModule",{value:!0});Nt.ripemd160=Nt.RIPEMD160=Nt.md5=Nt.MD5=Nt.sha1=Nt.SHA1=void 0;const Bs=Ot,dt=Nh,ui=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),jn=new Uint32Array(80);class D1 extends Bs.HashMD{constructor(){super(64,20,8,!1),this.A=ui[0]|0,this.B=ui[1]|0,this.C=ui[2]|0,this.D=ui[3]|0,this.E=ui[4]|0}get(){const{A:e,B:r,C:n,D:s,E:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0}process(e,r){for(let c=0;c<16;c++,r+=4)jn[c]=e.getUint32(r,!1);for(let c=16;c<80;c++)jn[c]=(0,dt.rotl)(jn[c-3]^jn[c-8]^jn[c-14]^jn[c-16],1);let{A:n,B:s,C:i,D:o,E:a}=this;for(let c=0;c<80;c++){let u,f;c<20?(u=(0,Bs.Chi)(s,i,o),f=1518500249):c<40?(u=s^i^o,f=1859775393):c<60?(u=(0,Bs.Maj)(s,i,o),f=2400959708):(u=s^i^o,f=3395469782);const l=(0,dt.rotl)(n,5)+u+a+f+jn[c]|0;a=o,o=i,i=(0,dt.rotl)(s,30),s=n,n=l}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,this.set(n,s,i,o,a)}roundClean(){(0,dt.clean)(jn)}destroy(){this.set(0,0,0,0,0),(0,dt.clean)(this.buffer)}}Nt.SHA1=D1;Nt.sha1=(0,dt.createHasher)(()=>new D1);const Ek=Math.pow(2,32),Sk=Array.from({length:64},(t,e)=>Math.floor(Ek*Math.abs(Math.sin(e+1)))),Ha=ui.slice(0,4),Qu=new Uint32Array(16);class H1 extends Bs.HashMD{constructor(){super(64,16,8,!0),this.A=Ha[0]|0,this.B=Ha[1]|0,this.C=Ha[2]|0,this.D=Ha[3]|0}get(){const{A:e,B:r,C:n,D:s}=this;return[e,r,n,s]}set(e,r,n,s){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0}process(e,r){for(let a=0;a<16;a++,r+=4)Qu[a]=e.getUint32(r,!0);let{A:n,B:s,C:i,D:o}=this;for(let a=0;a<64;a++){let c,u,f;a<16?(c=(0,Bs.Chi)(s,i,o),u=a,f=[7,12,17,22]):a<32?(c=(0,Bs.Chi)(o,s,i),u=(5*a+1)%16,f=[5,9,14,20]):a<48?(c=s^i^o,u=(3*a+5)%16,f=[4,11,16,23]):(c=i^(s|~o),u=7*a%16,f=[6,10,15,21]),c=c+n+Sk[a]+Qu[u],n=o,o=i,i=s,s=s+(0,dt.rotl)(c,f[a%4])}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,this.set(n,s,i,o)}roundClean(){(0,dt.clean)(Qu)}destroy(){this.set(0,0,0,0),(0,dt.clean)(this.buffer)}}Nt.MD5=H1;Nt.md5=(0,dt.createHasher)(()=>new H1);const Ak=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),z1=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),xk=z1.map(t=>(9*t+5)%16),V1=(()=>{const r=[[z1],[xk]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>Ak[i]));return r})(),q1=V1[0],G1=V1[1],W1=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),kk=q1.map((t,e)=>t.map(r=>W1[e][r])),Tk=G1.map((t,e)=>t.map(r=>W1[e][r])),_k=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Pk=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function S0(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}const za=new Uint32Array(16);class K1 extends Bs.HashMD{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:r,h2:n,h3:s,h4:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=s|0,this.h4=i|0}process(e,r){for(let d=0;d<16;d++,r+=4)za[d]=e.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,o=i,a=this.h2|0,c=a,u=this.h3|0,f=u,l=this.h4|0,p=l;for(let d=0;d<5;d++){const m=4-d,b=_k[d],E=Pk[d],A=q1[d],P=G1[d],S=kk[d],w=Tk[d];for(let k=0;k<16;k++){const T=(0,dt.rotl)(n+S0(d,i,a,u)+za[A[k]]+b,S[k])+l|0;n=l,l=u,u=(0,dt.rotl)(a,10)|0,a=i,i=T}for(let k=0;k<16;k++){const T=(0,dt.rotl)(s+S0(m,o,c,f)+za[P[k]]+E,w[k])+p|0;s=p,p=f,f=(0,dt.rotl)(c,10)|0,c=o,o=T}}this.set(this.h1+a+f|0,this.h2+u+p|0,this.h3+l+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){(0,dt.clean)(za)}destroy(){this.destroyed=!0,(0,dt.clean)(this.buffer),this.set(0,0,0,0,0)}}Nt.RIPEMD160=K1;Nt.ripemd160=(0,dt.createHasher)(()=>new K1);Object.defineProperty(Ni,"__esModule",{value:!0});Ni.sha1=Ni.SHA1=void 0;const Z1=Nt;Ni.SHA1=Z1.SHA1;Ni.sha1=Z1.sha1;const Y1=I1(lE);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.taggedHash=t.TAGGED_HASH_PREFIXES=t.TAGS=t.hash256=t.hash160=t.sha256=t.sha1=t.ripemd160=void 0;const e=bk,r=Ni,n=Y1;function s(f){return Buffer.from((0,e.ripemd160)(Uint8Array.from(f)))}t.ripemd160=s;function i(f){return Buffer.from((0,r.sha1)(Uint8Array.from(f)))}t.sha1=i;function o(f){return Buffer.from((0,n.sha256)(Uint8Array.from(f)))}t.sha256=o;function a(f){return Buffer.from((0,e.ripemd160)((0,n.sha256)(Uint8Array.from(f))))}t.hash160=a;function c(f){return Buffer.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(f))))}t.hash256=c,t.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],t.TAGGED_HASH_PREFIXES={"BIP0340/challenge":Buffer.from([123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124,123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124]),"BIP0340/aux":Buffer.from([241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144,241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144]),"BIP0340/nonce":Buffer.from([7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47,7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47]),TapLeaf:Buffer.from([174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238,174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238]),TapBranch:Buffer.from([25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21,25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21]),TapSighash:Buffer.from([244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49,244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49]),TapTweak:Buffer.from([232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233,232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233]),"KeyAgg list":Buffer.from([72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240,72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240]),"KeyAgg coefficient":Buffer.from([191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129,191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129])};function u(f,l){return o(Buffer.concat([t.TAGGED_HASH_PREFIXES[f],l]))}t.taggedHash=u})(ls);var ef={},xn={};Object.defineProperty(xn,"__esModule",{value:!0});xn.encode=xn.decode=xn.check=void 0;function Ik(t){if(t.length<8||t.length>72||t[0]!==48||t[1]!==t.length-2||t[2]!==2)return!1;const e=t[3];if(e===0||5+e>=t.length||t[4+e]!==2)return!1;const r=t[5+e];return!(r===0||6+e+r!==t.length||t[4]&128||e>1&&t[4]===0&&!(t[5]&128)||t[e+6]&128||r>1&&t[e+6]===0&&!(t[e+7]&128))}xn.check=Ik;function Ok(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(t[0]!==48)throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(t[2]!==2)throw new Error("Expected DER integer");const e=t[3];if(e===0)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(t[4+e]!==2)throw new Error("Expected DER integer (2)");const r=t[5+e];if(r===0)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(t[4]&128)throw new Error("R value is negative");if(e>1&&t[4]===0&&!(t[5]&128))throw new Error("R value excessively padded");if(t[e+6]&128)throw new Error("S value is negative");if(r>1&&t[e+6]===0&&!(t[e+7]&128))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}}xn.decode=Ok;function Bk(t,e){const r=t.length,n=e.length;if(r===0)throw new Error("R length is zero");if(n===0)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(t[0]&128)throw new Error("R value is negative");if(e[0]&128)throw new Error("S value is negative");if(r>1&&t[0]===0&&!(t[1]&128))throw new Error("R value excessively padded");if(n>1&&e[0]===0&&!(e[1]&128))throw new Error("S value excessively padded");const s=Buffer.allocUnsafe(6+r+n);return s[0]=48,s[1]=s.length-2,s[2]=2,s[3]=t.length,t.copy(s,4),s[4+r]=2,s[5+r]=e.length,e.copy(s,6+r),s}xn.encode=Bk;var zs={};Object.defineProperty(zs,"__esModule",{value:!0});zs.REVERSE_OPS=zs.OPS=void 0;const hd={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};zs.OPS=hd;const X1={};zs.REVERSE_OPS=X1;for(const t of Object.keys(hd)){const e=hd[t];X1[e]=t}var ns={};Object.defineProperty(ns,"__esModule",{value:!0});ns.decode=ns.encode=ns.encodingLength=void 0;const Qn=zs;function J1(t){return t<Qn.OPS.OP_PUSHDATA1?1:t<=255?2:t<=65535?3:5}ns.encodingLength=J1;function Ck(t,e,r){const n=J1(e);return n===1?t.writeUInt8(e,r):n===2?(t.writeUInt8(Qn.OPS.OP_PUSHDATA1,r),t.writeUInt8(e,r+1)):n===3?(t.writeUInt8(Qn.OPS.OP_PUSHDATA2,r),t.writeUInt16LE(e,r+1)):(t.writeUInt8(Qn.OPS.OP_PUSHDATA4,r),t.writeUInt32LE(e,r+1)),n}ns.encode=Ck;function $k(t,e){const r=t.readUInt8(e);let n,s;if(r<Qn.OPS.OP_PUSHDATA1)n=r,s=1;else if(r===Qn.OPS.OP_PUSHDATA1){if(e+2>t.length)return null;n=t.readUInt8(e+1),s=2}else if(r===Qn.OPS.OP_PUSHDATA2){if(e+3>t.length)return null;n=t.readUInt16LE(e+1),s=3}else{if(e+5>t.length)return null;if(r!==Qn.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=t.readUInt32LE(e+1),s=5}return{opcode:r,number:n,size:s}}ns.decode=$k;var Ui={};Object.defineProperty(Ui,"__esModule",{value:!0});Ui.encode=Ui.decode=void 0;function Rk(t,e,r){e=e||4,r=r===void 0?!0:r;const n=t.length;if(n===0)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&!(t[n-1]&127)&&(n<=1||!(t[n-2]&128)))throw new Error("Non-minimally encoded script number");if(n===5){const i=t.readUInt32LE(0),o=t.readUInt8(4);return o&128?-((o&-129)*4294967296+i):o*4294967296+i}let s=0;for(let i=0;i<n;++i)s|=t[i]<<8*i;return t[n-1]&128?-(s&~(128<<8*(n-1))):s}Ui.decode=Rk;function Nk(t){return t>2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}function Uk(t){let e=Math.abs(t);const r=Nk(e),n=Buffer.allocUnsafe(r),s=t<0;for(let i=0;i<r;++i)n.writeUInt8(e&255,i),e>>=8;return n[r-1]&128?n.writeUInt8(s?128:0,r-1):s&&(n[r-1]|=128),n}Ui.encode=Uk;var ys={},A0;function Mk(){if(A0)return ys;A0=1,Object.defineProperty(ys,"__esModule",{value:!0}),ys.encode=ys.decode=void 0;const t=xn,e=er(),r=Et,{typeforce:n}=r,s=Buffer.alloc(1,0);function i(u){let f=0;for(;u[f]===0;)++f;return f===u.length?s:(u=u.slice(f),u[0]&128?Buffer.concat([s,u],1+u.length):u)}function o(u){u[0]===0&&(u=u.slice(1));const f=Buffer.alloc(32,0),l=Math.max(0,32-u.length);return u.copy(f,l),f}function a(u){const f=u.readUInt8(u.length-1);if(!(0,e.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const l=t.decode(u.slice(0,-1)),p=o(l.r),d=o(l.s);return{signature:Buffer.concat([p,d],64),hashType:f}}ys.decode=a;function c(u,f){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:u,hashType:f}),!(0,e.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const l=Buffer.allocUnsafe(1);l.writeUInt8(f,0);const p=i(u.slice(0,32)),d=i(u.slice(32,64));return Buffer.concat([t.encode(p,d),l])}return ys.encode=c,ys}var x0;function er(){return x0||(x0=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.signature=t.number=t.isCanonicalScriptSignature=t.isDefinedHashType=t.isCanonicalPubKey=t.toStack=t.fromASM=t.toASM=t.decompile=t.compile=t.countNonPushOnlyOPs=t.isPushOnly=t.OPS=void 0;const e=xn,r=zs;Object.defineProperty(t,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=ns,s=Ui,i=Mk(),o=Et,{typeforce:a}=o,c=r.OPS.OP_RESERVED;function u($){return o.Number($)&&($===r.OPS.OP_0||$>=r.OPS.OP_1&&$<=r.OPS.OP_16||$===r.OPS.OP_1NEGATE)}function f($){return o.Buffer($)||u($)}function l($){return o.Array($)&&$.every(f)}t.isPushOnly=l;function p($){return $.length-$.filter(f).length}t.countNonPushOnlyOPs=p;function d($){if($.length===0)return r.OPS.OP_0;if($.length===1){if($[0]>=1&&$[0]<=16)return c+$[0];if($[0]===129)return r.OPS.OP_1NEGATE}}function m($){return Buffer.isBuffer($)}function b($){return o.Array($)}function E($){return Buffer.isBuffer($)}function A($){if(m($))return $;a(o.Array,$);const D=$.reduce((G,Q)=>E(Q)?Q.length===1&&d(Q)!==void 0?G+1:G+n.encodingLength(Q.length)+Q.length:G+1,0),M=Buffer.allocUnsafe(D);let V=0;if($.forEach(G=>{if(E(G)){const Q=d(G);if(Q!==void 0){M.writeUInt8(Q,V),V+=1;return}V+=n.encode(M,G.length,V),G.copy(M,V),V+=G.length}else M.writeUInt8(G,V),V+=1}),V!==M.length)throw new Error("Could not decode chunks");return M}t.compile=A;function P($){if(b($))return $;a(o.Buffer,$);const D=[];let M=0;for(;M<$.length;){const V=$[M];if(V>r.OPS.OP_0&&V<=r.OPS.OP_PUSHDATA4){const G=n.decode($,M);if(G===null||(M+=G.size,M+G.number>$.length))return null;const Q=$.slice(M,M+G.number);M+=G.number;const W=d(Q);W!==void 0?D.push(W):D.push(Q)}else D.push(V),M+=1}return D}t.decompile=P;function S($){if(m($)&&($=P($)),!$)throw new Error("Could not convert invalid chunks to ASM");return $.map(D=>{if(E(D)){const M=d(D);if(M===void 0)return D.toString("hex");D=M}return r.REVERSE_OPS[D]}).join(" ")}t.toASM=S;function w($){return a(o.String,$),A($.split(" ").map(D=>r.OPS[D]!==void 0?r.OPS[D]:(a(o.Hex,D),Buffer.from(D,"hex"))))}t.fromASM=w;function k($){return $=P($),a(l,$),$.map(D=>E(D)?D:D===r.OPS.OP_0?Buffer.allocUnsafe(0):s.encode(D-c))}t.toStack=k;function T($){return o.isPoint($)}t.isCanonicalPubKey=T;function B($){const D=$&-129;return D>0&&D<4}t.isDefinedHashType=B;function N($){return!Buffer.isBuffer($)||!B($[$.length-1])?!1:e.check($.slice(0,-1))}t.isCanonicalScriptSignature=N,t.number=s,t.signature=i}(ef)),ef}Object.defineProperty(Ta,"__esModule",{value:!0});Ta.Transaction=void 0;const Ye=lt,xt=ls,k0=er(),Fk=er(),Ee=Et,{typeforce:Lr}=Ee;function mr(t){const e=t.length;return Ye.varuint.encodingLength(e)+e}function jk(t){const e=t.length;return Ye.varuint.encodingLength(e)+t.reduce((r,n)=>r+mr(n),0)}const qn=Buffer.allocUnsafe(0),tf=[],rf=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),T0=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),Lk=Buffer.from("ffffffffffffffff","hex"),Dk={script:qn,valueBuffer:Lk};function Hk(t){return t.value!==void 0}let Rr=class _e{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(e,r){const n=new Ye.BufferReader(e),s=new _e;s.version=n.readInt32();const i=n.readUInt8(),o=n.readUInt8();let a=!1;i===_e.ADVANCED_TRANSACTION_MARKER&&o===_e.ADVANCED_TRANSACTION_FLAG?a=!0:n.offset-=2;const c=n.readVarInt();for(let f=0;f<c;++f)s.ins.push({hash:n.readSlice(32),index:n.readUInt32(),script:n.readVarSlice(),sequence:n.readUInt32(),witness:tf});const u=n.readVarInt();for(let f=0;f<u;++f)s.outs.push({value:n.readUInt64(),script:n.readVarSlice()});if(a){for(let f=0;f<c;++f)s.ins[f].witness=n.readVector();if(!s.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(s.locktime=n.readUInt32(),r)return s;if(n.offset!==e.length)throw new Error("Transaction has unexpected data");return s}static fromHex(e){return _e.fromBuffer(Buffer.from(e,"hex"),!1)}static isCoinbaseHash(e){Lr(Ee.Hash256bit,e);for(let r=0;r<32;++r)if(e[r]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&_e.isCoinbaseHash(this.ins[0].hash)}addInput(e,r,n,s){return Lr(Ee.tuple(Ee.Hash256bit,Ee.UInt32,Ee.maybe(Ee.UInt32),Ee.maybe(Ee.Buffer)),arguments),Ee.Null(n)&&(n=_e.DEFAULT_SEQUENCE),this.ins.push({hash:e,index:r,script:s||qn,sequence:n,witness:tf})-1}addOutput(e,r){return Lr(Ee.tuple(Ee.Buffer,Ee.Satoshi),arguments),this.outs.push({script:e,value:r})-1}hasWitnesses(){return this.ins.some(e=>e.witness.length!==0)}stripWitnesses(){this.ins.forEach(e=>{e.witness=tf})}weight(){const e=this.byteLength(!1),r=this.byteLength(!0);return e*3+r}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(e=!0){const r=e&&this.hasWitnesses();return(r?10:8)+Ye.varuint.encodingLength(this.ins.length)+Ye.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,s)=>n+40+mr(s.script),0)+this.outs.reduce((n,s)=>n+8+mr(s.script),0)+(r?this.ins.reduce((n,s)=>n+jk(s.witness),0):0)}clone(){const e=new _e;return e.version=this.version,e.locktime=this.locktime,e.ins=this.ins.map(r=>({hash:r.hash,index:r.index,script:r.script,sequence:r.sequence,witness:r.witness})),e.outs=this.outs.map(r=>({script:r.script,value:r.value})),e}hashForSignature(e,r,n){if(Lr(Ee.tuple(Ee.UInt32,Ee.Buffer,Ee.Number),arguments),e>=this.ins.length)return T0;const s=k0.compile(k0.decompile(r).filter(a=>a!==Fk.OPS.OP_CODESEPARATOR)),i=this.clone();if((n&31)===_e.SIGHASH_NONE)i.outs=[],i.ins.forEach((a,c)=>{c!==e&&(a.sequence=0)});else if((n&31)===_e.SIGHASH_SINGLE){if(e>=this.outs.length)return T0;i.outs.length=e+1;for(let a=0;a<e;a++)i.outs[a]=Dk;i.ins.forEach((a,c)=>{c!==e&&(a.sequence=0)})}n&_e.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[e]],i.ins[0].script=s):(i.ins.forEach(a=>{a.script=qn}),i.ins[e].script=s);const o=Buffer.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(n,o.length-4),i.__toBuffer(o,0,!1),xt.hash256(o)}hashForWitnessV1(e,r,n,s,i,o){if(console.log("hashForWitnessV1 :"),Lr(Ee.tuple(Ee.UInt32,Lr.arrayOf(Ee.Buffer),Lr.arrayOf(Ee.Satoshi),Ee.UInt32),arguments),n.length!==this.ins.length||r.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const a=s===_e.SIGHASH_DEFAULT?_e.SIGHASH_ALL:s&_e.SIGHASH_OUTPUT_MASK,u=(s&_e.SIGHASH_INPUT_MASK)===_e.SIGHASH_ANYONECANPAY,f=a===_e.SIGHASH_NONE,l=a===_e.SIGHASH_SINGLE;let p=qn,d=qn,m=qn,b=qn,E=qn;if(!u){let w=Ye.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(k=>{w.writeSlice(k.hash),w.writeUInt32(k.index)}),p=xt.sha256(w.end()),w=Ye.BufferWriter.withCapacity(8*this.ins.length),n.forEach(k=>w.writeUInt64(k)),d=xt.sha256(w.end()),console.log("prevOutScripts.map(varSliceSize).reduce((a, b) => a + b), :",r.map(mr).reduce((k,T)=>k+T)),w=Ye.BufferWriter.withCapacity(r.map(mr).reduce((k,T)=>k+T)),r.forEach(k=>w.writeVarSlice(k)),m=xt.sha256(w.end()),w=Ye.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(k=>w.writeUInt32(k.sequence)),b=xt.sha256(w.end())}if(f||l){if(l&&e<this.outs.length){const w=this.outs[e],k=Ye.BufferWriter.withCapacity(8+mr(w.script));k.writeUInt64(w.value),k.writeVarSlice(w.script),E=xt.sha256(k.end())}}else{const w=this.outs.map(T=>8+mr(T.script)).reduce((T,B)=>T+B),k=Ye.BufferWriter.withCapacity(w);this.outs.forEach(T=>{k.writeUInt64(T.value),k.writeVarSlice(T.script)}),E=xt.sha256(k.end())}const A=(i?2:0)+(o?1:0),P=174-(u?49:0)-(f?32:0)+(o?32:0)+(i?37:0),S=Ye.BufferWriter.withCapacity(P);if(S.writeUInt8(s),S.writeInt32(this.version),S.writeUInt32(this.locktime),S.writeSlice(p),S.writeSlice(d),S.writeSlice(m),S.writeSlice(b),f||l||S.writeSlice(E),S.writeUInt8(A),u){const w=this.ins[e];S.writeSlice(w.hash),S.writeUInt32(w.index),S.writeUInt64(n[e]),S.writeVarSlice(r[e]),S.writeUInt32(w.sequence)}else S.writeUInt32(e);if(o){const w=Ye.BufferWriter.withCapacity(mr(o));w.writeVarSlice(o),S.writeSlice(xt.sha256(w.end()))}return l&&S.writeSlice(E),i&&(S.writeSlice(i),S.writeUInt8(0),S.writeUInt32(4294967295)),xt.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),S.end()]))}hashForWitnessV0(e,r,n,s){Lr(Ee.tuple(Ee.UInt32,Ee.Buffer,Ee.Satoshi,Ee.UInt32),arguments);let i=Buffer.from([]),o,a=rf,c=rf,u=rf;if(s&_e.SIGHASH_ANYONECANPAY||(i=Buffer.allocUnsafe(36*this.ins.length),o=new Ye.BufferWriter(i,0),this.ins.forEach(l=>{o.writeSlice(l.hash),o.writeUInt32(l.index)}),c=xt.hash256(i)),!(s&_e.SIGHASH_ANYONECANPAY)&&(s&31)!==_e.SIGHASH_SINGLE&&(s&31)!==_e.SIGHASH_NONE&&(i=Buffer.allocUnsafe(4*this.ins.length),o=new Ye.BufferWriter(i,0),this.ins.forEach(l=>{o.writeUInt32(l.sequence)}),u=xt.hash256(i)),(s&31)!==_e.SIGHASH_SINGLE&&(s&31)!==_e.SIGHASH_NONE){const l=this.outs.reduce((p,d)=>p+8+mr(d.script),0);i=Buffer.allocUnsafe(l),o=new Ye.BufferWriter(i,0),this.outs.forEach(p=>{o.writeUInt64(p.value),o.writeVarSlice(p.script)}),a=xt.hash256(i)}else if((s&31)===_e.SIGHASH_SINGLE&&e<this.outs.length){const l=this.outs[e];i=Buffer.allocUnsafe(8+mr(l.script)),o=new Ye.BufferWriter(i,0),o.writeUInt64(l.value),o.writeVarSlice(l.script),a=xt.hash256(i)}i=Buffer.allocUnsafe(156+mr(r)),o=new Ye.BufferWriter(i,0);const f=this.ins[e];return o.writeInt32(this.version),o.writeSlice(c),o.writeSlice(u),o.writeSlice(f.hash),o.writeUInt32(f.index),o.writeVarSlice(r),o.writeUInt64(n),o.writeUInt32(f.sequence),o.writeSlice(a),o.writeUInt32(this.locktime),o.writeUInt32(s),xt.hash256(i)}getHash(e){return e&&this.isCoinbase()?Buffer.alloc(32,0):xt.hash256(this.__toBuffer(void 0,void 0,e))}getId(){return(0,Ye.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(e,r){return this.__toBuffer(e,r,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(e,r){Lr(Ee.tuple(Ee.Number,Ee.Buffer),arguments),this.ins[e].script=r}setWitness(e,r){Lr(Ee.tuple(Ee.Number,[Ee.Buffer]),arguments),this.ins[e].witness=r}__toBuffer(e,r,n=!1){e||(e=Buffer.allocUnsafe(this.byteLength(n)));const s=new Ye.BufferWriter(e,r||0);s.writeInt32(this.version);const i=n&&this.hasWitnesses();return i&&(s.writeUInt8(_e.ADVANCED_TRANSACTION_MARKER),s.writeUInt8(_e.ADVANCED_TRANSACTION_FLAG)),s.writeVarInt(this.ins.length),this.ins.forEach(o=>{s.writeSlice(o.hash),s.writeUInt32(o.index),s.writeVarSlice(o.script),s.writeUInt32(o.sequence)}),s.writeVarInt(this.outs.length),this.outs.forEach(o=>{Hk(o)?s.writeUInt64(o.value):s.writeSlice(o.valueBuffer),s.writeVarSlice(o.script)}),i&&this.ins.forEach(o=>{s.writeVector(o.witness)}),s.writeUInt32(this.locktime),r!==void 0?e.slice(r,s.offset):e}};Ta.Transaction=Rr;Rr.DEFAULT_SEQUENCE=4294967295;Rr.SIGHASH_DEFAULT=0;Rr.SIGHASH_ALL=1;Rr.SIGHASH_NONE=2;Rr.SIGHASH_SINGLE=3;Rr.SIGHASH_ANYONECANPAY=128;Rr.SIGHASH_OUTPUT_MASK=3;Rr.SIGHASH_INPUT_MASK=128;Rr.ADVANCED_TRANSACTION_MARKER=0;Rr.ADVANCED_TRANSACTION_FLAG=1;var Pe={},_a={};Object.defineProperty(_a,"__esModule",{value:!0});const zk=9007199254740991;function Uh(t){if(t<0||t>zk||t%1!==0)throw new RangeError("value out of range")}function po(t,e,r){if(Uh(t),e||(e=Buffer.allocUnsafe(Q1(t))),!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),t<253?(e.writeUInt8(t,r),Object.assign(po,{bytes:1})):t<=65535?(e.writeUInt8(253,r),e.writeUInt16LE(t,r+1),Object.assign(po,{bytes:3})):t<=4294967295?(e.writeUInt8(254,r),e.writeUInt32LE(t,r+1),Object.assign(po,{bytes:5})):(e.writeUInt8(255,r),e.writeUInt32LE(t>>>0,r+1),e.writeUInt32LE(t/4294967296|0,r+5),Object.assign(po,{bytes:9})),e}_a.encode=po;function yo(t,e){if(!Buffer.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");e||(e=0);const r=t.readUInt8(e);if(r<253)return Object.assign(yo,{bytes:1}),r;if(r===253)return Object.assign(yo,{bytes:3}),t.readUInt16LE(e+1);if(r===254)return Object.assign(yo,{bytes:5}),t.readUInt32LE(e+1);{Object.assign(yo,{bytes:9});const n=t.readUInt32LE(e+1),i=t.readUInt32LE(e+5)*4294967296+n;return Uh(i),i}}_a.decode=yo;function Q1(t){return Uh(t),t<253?1:t<=65535?3:t<=4294967295?5:9}_a.encodingLength=Q1;var nf={},ou={},vt={};Object.defineProperty(vt,"__esModule",{value:!0});vt.testnet=vt.regtest=vt.bitcoin=void 0;vt.bitcoin={messagePrefix:`Bitcoin Signed Message:
|
|
52
52
|
`,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};vt.regtest={messagePrefix:`Bitcoin Signed Message:
|
|
53
53
|
`,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};vt.testnet={messagePrefix:`Bitcoin Signed Message:
|
|
54
|
-
`,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var Yt={};Object.defineProperty(Yt,"__esModule",{value:!0});Yt.value=Yt.prop=void 0;function Vk(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const n=r.call(this);return this[e]=n,n},set(n){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:n,writable:!0})}})}Yt.prop=Vk;function qk(t){let e;return()=>(e!==void 0||(e=t()),e)}Yt.value=qk;Object.defineProperty(su,"__esModule",{value:!0});su.p2data=void 0;const Gk=vt,ac=er(),Dr=Et,T0=Yt,_0=ac.OPS;function Wk(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Dr.typeforce)({network:Dr.typeforce.maybe(Dr.typeforce.Object),output:Dr.typeforce.maybe(Dr.typeforce.Buffer),data:Dr.typeforce.maybe(Dr.typeforce.arrayOf(Dr.typeforce.Buffer))},t);const n={name:"embed",network:t.network||Gk.bitcoin};if(T0.prop(n,"output",()=>{if(t.data)return ac.compile([_0.OP_RETURN].concat(t.data))}),T0.prop(n,"data",()=>{if(t.output)return ac.decompile(t.output).slice(1)}),e.validate&&t.output){const s=ac.decompile(t.output);if(s[0]!==_0.OP_RETURN)throw new TypeError("Output is invalid");if(!s.slice(1).every(Dr.typeforce.Buffer))throw new TypeError("Output is invalid");if(t.data&&!(0,Dr.stacksEqual)(t.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,t)}su.p2data=Wk;var iu={};Object.defineProperty(iu,"__esModule",{value:!0});iu.p2ms=void 0;const Kk=vt,fi=er(),We=Et,Ln=Yt,li=fi.OPS,Va=li.OP_RESERVED;function Zk(t,e){if(!t.input&&!t.output&&!(t.pubkeys&&t.m!==void 0)&&!t.signatures)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{});function r(c){return fi.isCanonicalScriptSignature(c)||(e.allowIncomplete&&c===li.OP_0)!==void 0}(0,We.typeforce)({network:We.typeforce.maybe(We.typeforce.Object),m:We.typeforce.maybe(We.typeforce.Number),n:We.typeforce.maybe(We.typeforce.Number),output:We.typeforce.maybe(We.typeforce.Buffer),pubkeys:We.typeforce.maybe(We.typeforce.arrayOf(We.isPoint)),signatures:We.typeforce.maybe(We.typeforce.arrayOf(r)),input:We.typeforce.maybe(We.typeforce.Buffer)},t);const s={network:t.network||Kk.bitcoin};let i=[],o=!1;function a(c){o||(o=!0,i=fi.decompile(c),s.m=i[0]-Va,s.n=i[i.length-2]-Va,s.pubkeys=i.slice(1,-2))}if(Ln.prop(s,"output",()=>{if(t.m&&s.n&&t.pubkeys)return fi.compile([].concat(Va+t.m,t.pubkeys,Va+s.n,li.OP_CHECKMULTISIG))}),Ln.prop(s,"m",()=>{if(s.output)return a(s.output),s.m}),Ln.prop(s,"n",()=>{if(s.pubkeys)return s.pubkeys.length}),Ln.prop(s,"pubkeys",()=>{if(t.output)return a(t.output),s.pubkeys}),Ln.prop(s,"signatures",()=>{if(t.input)return fi.decompile(t.input).slice(1)}),Ln.prop(s,"input",()=>{if(t.signatures)return fi.compile([li.OP_0].concat(t.signatures))}),Ln.prop(s,"witness",()=>{if(s.input)return[]}),Ln.prop(s,"name",()=>{if(!(!s.m||!s.n))return`p2ms(${s.m} of ${s.n})`}),e.validate){if(t.output){if(a(t.output),!We.typeforce.Number(i[0]))throw new TypeError("Output is invalid");if(!We.typeforce.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==li.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(s.m<=0||s.n>16||s.m>s.n||s.n!==i.length-3)throw new TypeError("Output is invalid");if(!s.pubkeys.every(c=>(0,We.isPoint)(c)))throw new TypeError("Output is invalid");if(t.m!==void 0&&t.m!==s.m)throw new TypeError("m mismatch");if(t.n!==void 0&&t.n!==s.n)throw new TypeError("n mismatch");if(t.pubkeys&&!(0,We.stacksEqual)(t.pubkeys,s.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(t.n!==void 0&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(s.n=t.pubkeys.length,s.n<s.m)throw new TypeError("Pubkey count cannot be less than m")}if(t.signatures){if(t.signatures.length<s.m)throw new TypeError("Not enough signatures provided");if(t.signatures.length>s.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==li.OP_0)throw new TypeError("Input is invalid");if(s.signatures.length===0||!s.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!(0,We.stacksEqual)(t.signatures,s.signatures))throw new TypeError("Signature mismatch");if(t.m!==void 0&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(s,t)}iu.p2ms=Zk;var ou={};Object.defineProperty(ou,"__esModule",{value:!0});ou.p2pk=void 0;const Yk=vt,di=er(),yr=Et,ai=Yt,P0=di.OPS;function Xk(t,e){if(!t.input&&!t.output&&!t.pubkey&&!t.input&&!t.signature)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,yr.typeforce)({network:yr.typeforce.maybe(yr.typeforce.Object),output:yr.typeforce.maybe(yr.typeforce.Buffer),pubkey:yr.typeforce.maybe(yr.isPoint),signature:yr.typeforce.maybe(di.isCanonicalScriptSignature),input:yr.typeforce.maybe(yr.typeforce.Buffer)},t);const r=ai.value(()=>di.decompile(t.input)),s={name:"p2pk",network:t.network||Yk.bitcoin};if(ai.prop(s,"output",()=>{if(t.pubkey)return di.compile([t.pubkey,P0.OP_CHECKSIG])}),ai.prop(s,"pubkey",()=>{if(t.output)return t.output.slice(1,-1)}),ai.prop(s,"signature",()=>{if(t.input)return r()[0]}),ai.prop(s,"input",()=>{if(t.signature)return di.compile([t.signature])}),ai.prop(s,"witness",()=>{if(s.input)return[]}),e.validate){if(t.output){if(t.output[t.output.length-1]!==P0.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,yr.isPoint)(s.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(s.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(s.input))throw new TypeError("Signature mismatch");if(t.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!di.isCanonicalScriptSignature(s.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(s,t)}ou.p2pk=Xk;var au={};function Jk(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r<e.length;r++)e[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=n}var o=t.length,a=t.charAt(0),c=Math.log(o)/Math.log(256),u=Math.log(256)/Math.log(o);function f(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,b=0,E=0,A=d.length;E!==A&&d[E]===0;)E++,m++;for(var P=(A-E)*u+1>>>0,S=new Uint8Array(P);E!==A;){for(var w=d[E],k=0,T=P-1;(w!==0||k<b)&&T!==-1;T--,k++)w+=256*S[T]>>>0,S[T]=w%o>>>0,w=w/o>>>0;if(w!==0)throw new Error("Non-zero carry");b=k,E++}for(var B=P-b;B!==P&&S[B]===0;)B++;for(var U=a.repeat(m);B<P;++B)U+=t.charAt(S[B]);return U}function l(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;for(var m=0,b=0,E=0;d[m]===a;)b++,m++;for(var A=(d.length-m)*c+1>>>0,P=new Uint8Array(A);d[m];){var S=d.charCodeAt(m);if(S>255)return;var w=e[S];if(w===255)return;for(var k=0,T=A-1;(w!==0||k<E)&&T!==-1;T--,k++)w+=o*P[T]>>>0,P[T]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");E=k,m++}for(var B=A-E;B!==A&&P[B]===0;)B++;for(var U=new Uint8Array(b+(A-B)),$=b;B!==A;)U[$++]=P[B++];return U}function p(d){var m=l(d);if(m)return m;throw new Error("Non-base"+o+" character")}return{encode:f,decodeUnsafe:l,decode:p}}var Qk=Jk;const eT=Qk,tT="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var rT=eT(tT),rf=rT,nT=function(t){function e(i){var o=Uint8Array.from(i),a=t(o),c=o.length+4,u=new Uint8Array(c);return u.set(o,0),u.set(a.subarray(0,4),o.length),rf.encode(u,c)}function r(i){var o=i.slice(0,-4),a=i.slice(-4),c=t(o);if(!(a[0]^c[0]|a[1]^c[1]|a[2]^c[2]|a[3]^c[3]))return o}function n(i){var o=rf.decodeUnsafe(i);if(o)return r(o)}function s(i){var o=rf.decode(i),a=r(o);if(!a)throw new Error("Invalid checksum");return a}return{encode:e,decode:s,decodeUnsafe:n}},{sha256:I0}=Y1,sT=nT;function iT(t){return I0(I0(t))}var Uh=sT(iT);Object.defineProperty(au,"__esModule",{value:!0});au.p2pkh=void 0;const nf=ls,oT=vt,hi=er(),kt=Et,on=Yt,O0=Uh,Dn=hi.OPS;function aT(t,e){if(!t.address&&!t.hash&&!t.output&&!t.pubkey&&!t.input)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,kt.typeforce)({network:kt.typeforce.maybe(kt.typeforce.Object),address:kt.typeforce.maybe(kt.typeforce.String),hash:kt.typeforce.maybe(kt.typeforce.BufferN(20)),output:kt.typeforce.maybe(kt.typeforce.BufferN(25)),pubkey:kt.typeforce.maybe(kt.isPoint),signature:kt.typeforce.maybe(hi.isCanonicalScriptSignature),input:kt.typeforce.maybe(kt.typeforce.Buffer)},t);const r=on.value(()=>{const o=Buffer.from(O0.decode(t.address)),a=o.readUInt8(0),c=o.slice(1);return{version:a,hash:c}}),n=on.value(()=>hi.decompile(t.input)),s=t.network||oT.bitcoin,i={name:"p2pkh",network:s};if(on.prop(i,"address",()=>{if(!i.hash)return;const o=Buffer.allocUnsafe(21);return o.writeUInt8(s.pubKeyHash,0),i.hash.copy(o,1),O0.encode(o)}),on.prop(i,"hash",()=>{if(t.output)return t.output.slice(3,23);if(t.address)return r().hash;if(t.pubkey||i.pubkey)return nf.hash160(t.pubkey||i.pubkey)}),on.prop(i,"output",()=>{if(i.hash)return hi.compile([Dn.OP_DUP,Dn.OP_HASH160,i.hash,Dn.OP_EQUALVERIFY,Dn.OP_CHECKSIG])}),on.prop(i,"pubkey",()=>{if(t.input)return n()[1]}),on.prop(i,"signature",()=>{if(t.input)return n()[0]}),on.prop(i,"input",()=>{if(t.pubkey&&t.signature)return hi.compile([t.signature,t.pubkey])}),on.prop(i,"witness",()=>{if(i.input)return[]}),e.validate){let o=Buffer.from([]);if(t.address){if(r().version!==s.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");o=r().hash}if(t.hash){if(o.length>0&&!o.equals(t.hash))throw new TypeError("Hash mismatch");o=t.hash}if(t.output){if(t.output.length!==25||t.output[0]!==Dn.OP_DUP||t.output[1]!==Dn.OP_HASH160||t.output[2]!==20||t.output[23]!==Dn.OP_EQUALVERIFY||t.output[24]!==Dn.OP_CHECKSIG)throw new TypeError("Output is invalid");const a=t.output.slice(3,23);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(t.pubkey){const a=nf.hash160(t.pubkey);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(t.input){const a=n();if(a.length!==2)throw new TypeError("Input is invalid");if(!hi.isCanonicalScriptSignature(a[0]))throw new TypeError("Input has invalid signature");if(!(0,kt.isPoint)(a[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(a[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(a[1]))throw new TypeError("Pubkey mismatch");const c=nf.hash160(a[1]);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)}au.p2pkh=aT;var cu={};Object.defineProperty(cu,"__esModule",{value:!0});cu.p2sh=void 0;const B0=ls,cT=vt,Vr=er(),Re=Et,Hr=Yt,C0=Uh,io=Vr.OPS;function uT(t,e){if(!t.address&&!t.hash&&!t.output&&!t.redeem&&!t.input)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Re.typeforce)({network:Re.typeforce.maybe(Re.typeforce.Object),address:Re.typeforce.maybe(Re.typeforce.String),hash:Re.typeforce.maybe(Re.typeforce.BufferN(20)),output:Re.typeforce.maybe(Re.typeforce.BufferN(23)),redeem:Re.typeforce.maybe({network:Re.typeforce.maybe(Re.typeforce.Object),output:Re.typeforce.maybe(Re.typeforce.Buffer),input:Re.typeforce.maybe(Re.typeforce.Buffer),witness:Re.typeforce.maybe(Re.typeforce.arrayOf(Re.typeforce.Buffer))}),input:Re.typeforce.maybe(Re.typeforce.Buffer),witness:Re.typeforce.maybe(Re.typeforce.arrayOf(Re.typeforce.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||cT.bitcoin);const n={network:r},s=Hr.value(()=>{const a=Buffer.from(C0.decode(t.address)),c=a.readUInt8(0),u=a.slice(1);return{version:c,hash:u}}),i=Hr.value(()=>Vr.decompile(t.input)),o=Hr.value(()=>{const a=i(),c=a[a.length-1];return{network:r,output:c===io.OP_FALSE?Buffer.from([]):c,input:Vr.compile(a.slice(0,-1)),witness:t.witness||[]}});if(Hr.prop(n,"address",()=>{if(!n.hash)return;const a=Buffer.allocUnsafe(21);return a.writeUInt8(n.network.scriptHash,0),n.hash.copy(a,1),C0.encode(a)}),Hr.prop(n,"hash",()=>{if(t.output)return t.output.slice(2,22);if(t.address)return s().hash;if(n.redeem&&n.redeem.output)return B0.hash160(n.redeem.output)}),Hr.prop(n,"output",()=>{if(n.hash)return Vr.compile([io.OP_HASH160,n.hash,io.OP_EQUAL])}),Hr.prop(n,"redeem",()=>{if(t.input)return o()}),Hr.prop(n,"input",()=>{if(!(!t.redeem||!t.redeem.input||!t.redeem.output))return Vr.compile([].concat(Vr.decompile(t.redeem.input),t.redeem.output))}),Hr.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),Hr.prop(n,"name",()=>{const a=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&a.push(n.redeem.name),a.join("-")}),e.validate){let a=Buffer.from([]);if(t.address){if(s().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(s().hash.length!==20)throw new TypeError("Invalid address");a=s().hash}if(t.hash){if(a.length>0&&!a.equals(t.hash))throw new TypeError("Hash mismatch");a=t.hash}if(t.output){if(t.output.length!==23||t.output[0]!==io.OP_HASH160||t.output[1]!==20||t.output[22]!==io.OP_EQUAL)throw new TypeError("Output is invalid");const u=t.output.slice(2,22);if(a.length>0&&!a.equals(u))throw new TypeError("Hash mismatch");a=u}const c=u=>{if(u.output){const f=Vr.decompile(u.output);if(!f||f.length<1)throw new TypeError("Redeem.output too short");if(u.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(Vr.countNonPushOnlyOPs(f)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const l=B0.hash160(u.output);if(a.length>0&&!a.equals(l))throw new TypeError("Hash mismatch");a=l}if(u.input){const f=u.input.length>0,l=u.witness&&u.witness.length>0;if(!f&&!l)throw new TypeError("Empty input");if(f&&l)throw new TypeError("Input and witness provided");if(f){const p=Vr.decompile(u.input);if(!Vr.isPushOnly(p))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const u=i();if(!u||u.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(o().output))throw new TypeError("Input is invalid");c(o())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const u=o();if(t.redeem.output&&!t.redeem.output.equals(u.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(u.input))throw new TypeError("Redeem.input mismatch")}c(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!(0,Re.stacksEqual)(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)}cu.p2sh=uT;var uu={},In={};Object.defineProperty(In,"__esModule",{value:!0});In.bech32m=In.bech32=void 0;const Sc="qpzry9x8gf2tvdw0s3jn54khce6mua7l",ew={};for(let t=0;t<Sc.length;t++){const e=Sc.charAt(t);ew[e]=t}function Ti(t){const e=t>>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function $0(t){let e=1;for(let r=0;r<t.length;++r){const n=t.charCodeAt(r);if(n<33||n>126)return"Invalid prefix ("+t+")";e=Ti(e)^n>>5}e=Ti(e);for(let r=0;r<t.length;++r){const n=t.charCodeAt(r);e=Ti(e)^n&31}return e}function Mh(t,e,r,n){let s=0,i=0;const o=(1<<r)-1,a=[];for(let c=0;c<t.length;++c)for(s=s<<e|t[c],i+=e;i>=r;)i-=r,a.push(s>>i&o);if(n)i>0&&a.push(s<<r-i&o);else{if(i>=e)return"Excess padding";if(s<<r-i&o)return"Non-zero padding"}return a}function fT(t){return Mh(t,8,5,!0)}function lT(t){const e=Mh(t,5,8,!1);if(Array.isArray(e))return e}function dT(t){const e=Mh(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}function tw(t){let e;t==="bech32"?e=1:e=734539939;function r(o,a,c){if(c=c||90,o.length+7+a.length>c)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let u=$0(o);if(typeof u=="string")throw new Error(u);let f=o+"1";for(let l=0;l<a.length;++l){const p=a[l];if(p>>5)throw new Error("Non 5-bit word");u=Ti(u)^p,f+=Sc.charAt(p)}for(let l=0;l<6;++l)u=Ti(u);u^=e;for(let l=0;l<6;++l){const p=u>>(5-l)*5&31;f+=Sc.charAt(p)}return f}function n(o,a){if(a=a||90,o.length<8)return o+" too short";if(o.length>a)return"Exceeds length limit";const c=o.toLowerCase(),u=o.toUpperCase();if(o!==c&&o!==u)return"Mixed-case string "+o;o=c;const f=o.lastIndexOf("1");if(f===-1)return"No separator character for "+o;if(f===0)return"Missing prefix for "+o;const l=o.slice(0,f),p=o.slice(f+1);if(p.length<6)return"Data too short";let d=$0(l);if(typeof d=="string")return d;const m=[];for(let b=0;b<p.length;++b){const E=p.charAt(b),A=ew[E];if(A===void 0)return"Unknown character "+E;d=Ti(d)^A,!(b+6>=p.length)&&m.push(A)}return d!==e?"Invalid checksum for "+o:{prefix:l,words:m}}function s(o,a){const c=n(o,a);if(typeof c=="object")return c}function i(o,a){const c=n(o,a);if(typeof c=="object")return c;throw new Error(c)}return{decodeUnsafe:s,decode:i,encode:r,toWords:fT,fromWordsUnsafe:lT,fromWords:dT}}In.bech32=tw("bech32");In.bech32m=tw("bech32m");Object.defineProperty(uu,"__esModule",{value:!0});uu.p2wpkh=void 0;const sf=ls,hT=vt,cc=er(),rt=Et,Hn=Yt,qa=In,R0=cc.OPS,pT=Buffer.alloc(0);function yT(t,e){if(!t.address&&!t.hash&&!t.output&&!t.pubkey&&!t.witness)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,rt.typeforce)({address:rt.typeforce.maybe(rt.typeforce.String),hash:rt.typeforce.maybe(rt.typeforce.BufferN(20)),input:rt.typeforce.maybe(rt.typeforce.BufferN(0)),network:rt.typeforce.maybe(rt.typeforce.Object),output:rt.typeforce.maybe(rt.typeforce.BufferN(22)),pubkey:rt.typeforce.maybe(rt.isPoint),signature:rt.typeforce.maybe(cc.isCanonicalScriptSignature),witness:rt.typeforce.maybe(rt.typeforce.arrayOf(rt.typeforce.Buffer))},t);const r=Hn.value(()=>{const i=qa.bech32.decode(t.address),o=i.words.shift(),a=qa.bech32.fromWords(i.words);return{version:o,prefix:i.prefix,data:Buffer.from(a)}}),n=t.network||hT.bitcoin,s={name:"p2wpkh",network:n};if(Hn.prop(s,"address",()=>{if(!s.hash)return;const i=qa.bech32.toWords(s.hash);return i.unshift(0),qa.bech32.encode(n.bech32,i)}),Hn.prop(s,"hash",()=>{if(t.output)return t.output.slice(2,22);if(t.address)return r().data;if(t.pubkey||s.pubkey)return sf.hash160(t.pubkey||s.pubkey)}),Hn.prop(s,"output",()=>{if(s.hash)return cc.compile([R0.OP_0,s.hash])}),Hn.prop(s,"pubkey",()=>{if(t.pubkey)return t.pubkey;if(t.witness)return t.witness[1]}),Hn.prop(s,"signature",()=>{if(t.witness)return t.witness[0]}),Hn.prop(s,"input",()=>{if(s.witness)return pT}),Hn.prop(s,"witness",()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]}),e.validate){let i=Buffer.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==20)throw new TypeError("Invalid address data");i=r().data}if(t.hash){if(i.length>0&&!i.equals(t.hash))throw new TypeError("Hash mismatch");i=t.hash}if(t.output){if(t.output.length!==22||t.output[0]!==R0.OP_0||t.output[1]!==20)throw new TypeError("Output is invalid");if(i.length>0&&!i.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");i=t.output.slice(2)}if(t.pubkey){const o=sf.hash160(t.pubkey);if(i.length>0&&!i.equals(o))throw new TypeError("Hash mismatch");if(i=o,!(0,rt.isPoint)(t.pubkey)||t.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(t.witness.length!==2)throw new TypeError("Witness is invalid");if(!cc.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,rt.isPoint)(t.witness[1])||t.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const o=sf.hash160(t.witness[1]);if(i.length>0&&!i.equals(o))throw new TypeError("Hash mismatch")}}return Object.assign(s,t)}uu.p2wpkh=yT;var fu={};Object.defineProperty(fu,"__esModule",{value:!0});fu.p2wsh=void 0;const N0=ls,mT=vt,hn=er(),Ce=Et,an=Yt,Ga=In,U0=hn.OPS,of=Buffer.alloc(0);function Wa(t){return!!(Buffer.isBuffer(t)&&t.length===65&&t[0]===4&&(0,Ce.isPoint)(t))}function bT(t,e){if(!t.address&&!t.hash&&!t.output&&!t.redeem&&!t.witness)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Ce.typeforce)({network:Ce.typeforce.maybe(Ce.typeforce.Object),address:Ce.typeforce.maybe(Ce.typeforce.String),hash:Ce.typeforce.maybe(Ce.typeforce.BufferN(32)),output:Ce.typeforce.maybe(Ce.typeforce.BufferN(34)),redeem:Ce.typeforce.maybe({input:Ce.typeforce.maybe(Ce.typeforce.Buffer),network:Ce.typeforce.maybe(Ce.typeforce.Object),output:Ce.typeforce.maybe(Ce.typeforce.Buffer),witness:Ce.typeforce.maybe(Ce.typeforce.arrayOf(Ce.typeforce.Buffer))}),input:Ce.typeforce.maybe(Ce.typeforce.BufferN(0)),witness:Ce.typeforce.maybe(Ce.typeforce.arrayOf(Ce.typeforce.Buffer))},t);const r=an.value(()=>{const o=Ga.bech32.decode(t.address),a=o.words.shift(),c=Ga.bech32.fromWords(o.words);return{version:a,prefix:o.prefix,data:Buffer.from(c)}}),n=an.value(()=>hn.decompile(t.redeem.input));let s=t.network;s||(s=t.redeem&&t.redeem.network||mT.bitcoin);const i={network:s};if(an.prop(i,"address",()=>{if(!i.hash)return;const o=Ga.bech32.toWords(i.hash);return o.unshift(0),Ga.bech32.encode(s.bech32,o)}),an.prop(i,"hash",()=>{if(t.output)return t.output.slice(2);if(t.address)return r().data;if(i.redeem&&i.redeem.output)return N0.sha256(i.redeem.output)}),an.prop(i,"output",()=>{if(i.hash)return hn.compile([U0.OP_0,i.hash])}),an.prop(i,"redeem",()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:of,witness:t.witness.slice(0,-1)}}),an.prop(i,"input",()=>{if(i.witness)return of}),an.prop(i,"witness",()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const o=hn.toStack(n());return i.redeem=Object.assign({witness:o},t.redeem),i.redeem.input=of,[].concat(o,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)}),an.prop(i,"name",()=>{const o=["p2wsh"];return i.redeem!==void 0&&i.redeem.name!==void 0&&o.push(i.redeem.name),o.join("-")}),e.validate){let o=Buffer.from([]);if(t.address){if(r().prefix!==s.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==32)throw new TypeError("Invalid address data");o=r().data}if(t.hash){if(o.length>0&&!o.equals(t.hash))throw new TypeError("Hash mismatch");o=t.hash}if(t.output){if(t.output.length!==34||t.output[0]!==U0.OP_0||t.output[1]!==32)throw new TypeError("Output is invalid");const a=t.output.slice(2);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(t.redeem){if(t.redeem.network&&t.redeem.network!==s)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){const a=hn.decompile(t.redeem.output);if(!a||a.length<1)throw new TypeError("Redeem.output is invalid");if(t.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(hn.countNonPushOnlyOPs(a)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const c=N0.sha256(t.redeem.output);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch");o=c}if(t.redeem.input&&!hn.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!(0,Ce.stacksEqual)(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Wa)||t.redeem.output&&(hn.decompile(t.redeem.output)||[]).some(Wa))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const a=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(a))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Wa)||(hn.decompile(a)||[]).some(Wa))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(i,t)}fu.p2wsh=bT;var oo={},Vs={};Object.defineProperty(Vs,"__esModule",{value:!0});Vs.getEccLib=Vs.initEccLib=void 0;const vo={};function gT(t,e){t?t!==vo.eccLib&&(e!=null&&e.DANGER_DO_NOT_VERIFY_ECCLIB||vT(t),vo.eccLib=t):vo.eccLib=t}Vs.initEccLib=gT;function wT(){if(!vo.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return vo.eccLib}Vs.getEccLib=wT;const cn=t=>Buffer.from(t,"hex");function vT(t){rr(typeof t.isXOnlyPoint=="function"),rr(t.isXOnlyPoint(cn("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),rr(t.isXOnlyPoint(cn("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),rr(t.isXOnlyPoint(cn("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),rr(t.isXOnlyPoint(cn("0000000000000000000000000000000000000000000000000000000000000001"))),rr(!t.isXOnlyPoint(cn("0000000000000000000000000000000000000000000000000000000000000000"))),rr(!t.isXOnlyPoint(cn("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),rr(typeof t.xOnlyPointAddTweak=="function"),ET.forEach(e=>{const r=t.xOnlyPointAddTweak(cn(e.pubkey),cn(e.tweak));e.result===null?rr(r===null):(rr(r!==null),rr(r.parity===e.parity),rr(Buffer.from(r.xOnlyPubkey).equals(cn(e.result))))})}function rr(t){if(!t)throw new Error("ecc library invalid")}const ET=[{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 Fh={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.tweakKey=t.tapTweakHash=t.tapleafHash=t.findScriptPath=t.toHashTree=t.rootHashFromPath=t.MAX_TAPTREE_DEPTH=t.LEAF_VERSION_TAPSCRIPT=void 0;const e=Qs,r=Vs,n=ls,s=lt,i=Et;t.LEAF_VERSION_TAPSCRIPT=192,t.MAX_TAPTREE_DEPTH=128;const o=b=>"left"in b&&"right"in b;function a(b,E){if(b.length<33)throw new TypeError(`The control-block length is too small. Got ${b.length}, expected min 33.`);const A=(b.length-33)/32;let P=E;for(let S=0;S<A;S++){const w=b.slice(33+32*S,65+32*S);P.compare(w)<0?P=d(P,w):P=d(w,P)}return P}t.rootHashFromPath=a;function c(b){if((0,i.isTapleaf)(b))return{hash:f(b)};const E=[c(b[0]),c(b[1])];E.sort((S,w)=>S.hash.compare(w.hash));const[A,P]=E;return{hash:d(A.hash,P.hash),left:A,right:P}}t.toHashTree=c;function u(b,E){if(o(b)){const A=u(b.left,E);if(A!==void 0)return[...A,b.right.hash];const P=u(b.right,E);if(P!==void 0)return[...P,b.left.hash]}else if(b.hash.equals(E))return[]}t.findScriptPath=u;function f(b){const E=b.version||t.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",e.Buffer.concat([e.Buffer.from([E]),m(b.output)]))}t.tapleafHash=f;function l(b,E){return n.taggedHash("TapTweak",e.Buffer.concat(E?[b,E]:[b]))}t.tapTweakHash=l;function p(b,E){if(!e.Buffer.isBuffer(b)||b.length!==32||E&&E.length!==32)return null;const A=l(b,E),P=(0,r.getEccLib)().xOnlyPointAddTweak(b,A);return!P||P.xOnlyPubkey===null?null:{parity:P.parity,x:e.Buffer.from(P.xOnlyPubkey)}}t.tweakKey=p;function d(b,E){return n.taggedHash("TapBranch",e.Buffer.concat([b,E]))}function m(b){const E=s.varuint.encodingLength(b.length),A=e.Buffer.allocUnsafe(E);return s.varuint.encode(b.length,A),e.Buffer.concat([A,b])}})(Fh);var Tt={},M0;function ST(){if(M0)return Tt;M0=1,Object.defineProperty(Tt,"__esModule",{value:!0}),Tt.toOutputScript=Tt.fromOutputScript=Tt.toBech32=Tt.toBase58Check=Tt.fromBech32=Tt.fromBase58Check=void 0;const t=vt,e=jh(),r=er(),n=Et,s=In,i=Uh,o=40,a=2,c=16,u=2,f=80,l="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function p(S,w){const k=S.slice(2);if(k.length<a||k.length>o)throw new TypeError("Invalid program length for segwit address");const T=S[0]-f;if(T<u||T>c)throw new TypeError("Invalid version for segwit address");if(S[1]!==k.length)throw new TypeError("Invalid script for segwit address");return console.warn(l),E(k,T,w.bech32)}function d(S){const w=Buffer.from(i.decode(S));if(w.length<21)throw new TypeError(S+" is too short");if(w.length>21)throw new TypeError(S+" is too long");const k=w.readUInt8(0),T=w.slice(1);return{version:k,hash:T}}Tt.fromBase58Check=d;function m(S){let w,k;try{w=s.bech32.decode(S)}catch{}if(w){if(k=w.words[0],k!==0)throw new TypeError(S+" uses wrong encoding")}else if(w=s.bech32m.decode(S),k=w.words[0],k===0)throw new TypeError(S+" uses wrong encoding");const T=s.bech32.fromWords(w.words.slice(1));return{version:k,prefix:w.prefix,data:Buffer.from(T)}}Tt.fromBech32=m;function b(S,w){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const k=Buffer.allocUnsafe(21);return k.writeUInt8(w,0),S.copy(k,1),i.encode(k)}Tt.toBase58Check=b;function E(S,w,k){const T=s.bech32.toWords(S);return T.unshift(w),w===0?s.bech32.encode(k,T):s.bech32m.encode(k,T)}Tt.toBech32=E;function A(S,w){w=w||t.bitcoin;try{return e.p2pkh({output:S,network:w}).address}catch{}try{return e.p2sh({output:S,network:w}).address}catch{}try{return e.p2wpkh({output:S,network:w}).address}catch{}try{return e.p2wsh({output:S,network:w}).address}catch{}try{return e.p2tr({output:S,network:w}).address}catch{}try{return p(S,w)}catch{}throw new Error(r.toASM(S)+" has no matching Address")}Tt.fromOutputScript=A;function P(S,w){w=w||t.bitcoin;let k,T;try{k=d(S)}catch{}if(k){if(k.version===w.pubKeyHash)return e.p2pkh({hash:k.hash}).output;if(k.version===w.scriptHash)return e.p2sh({hash:k.hash}).output}else{try{T=m(S)}catch{}if(T){if(T.prefix!==w.bech32)throw new Error(S+" has an invalid prefix");if(T.version===0){if(T.data.length===20)return e.p2wpkh({hash:T.data}).output;if(T.data.length===32)return e.p2wsh({hash:T.data}).output}else if(T.version===1){if(T.data.length===32)return e.p2tr({pubkey:T.data}).output}else if(T.version>=u&&T.version<=c&&T.data.length>=a&&T.data.length<=o)return console.warn(l),r.compile([T.version+f,T.data])}}throw new Error(S+" has no matching Script")}return Tt.toOutputScript=P,Tt}var F0;function AT(){if(F0)return oo;F0=1,Object.defineProperty(oo,"__esModule",{value:!0}),oo.p2tr=void 0;const t=Qs,e=vt,r=er(),n=Et,s=Vs,i=Fh,o=Yt,a=In,c=ST(),u=r.OPS,f=1,l=80;function p(d,m){if(!d.address&&!d.output&&!d.pubkey&&!d.internalPubkey&&!(d.witness&&d.witness.length>1))throw new TypeError("Not enough data");m=Object.assign({validate:!0},m||{}),(0,n.typeforce)({address:n.typeforce.maybe(n.typeforce.String),input:n.typeforce.maybe(n.typeforce.BufferN(0)),network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.BufferN(34)),internalPubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),hash:n.typeforce.maybe(n.typeforce.BufferN(32)),pubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),signature:n.typeforce.maybe(n.typeforce.anyOf(n.typeforce.BufferN(64),n.typeforce.BufferN(65))),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer)),scriptTree:n.typeforce.maybe(n.isTaptree),redeem:n.typeforce.maybe({output:n.typeforce.maybe(n.typeforce.Buffer),redeemVersion:n.typeforce.maybe(n.typeforce.Number),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer))}),redeemVersion:n.typeforce.maybe(n.typeforce.Number)},d);const b=o.value(()=>(0,c.fromBech32)(d.address)),E=o.value(()=>{if(!(!d.witness||!d.witness.length))return d.witness.length>=2&&d.witness[d.witness.length-1][0]===l?d.witness.slice(0,-1):d.witness.slice()}),A=o.value(()=>{if(d.scriptTree)return(0,i.toHashTree)(d.scriptTree);if(d.hash)return{hash:d.hash}}),P=d.network||e.bitcoin,S={name:"p2tr",network:P};if(o.prop(S,"address",()=>{if(!S.pubkey)return;const w=a.bech32m.toWords(S.pubkey);return w.unshift(f),a.bech32m.encode(P.bech32,w)}),o.prop(S,"hash",()=>{const w=A();if(w)return w.hash;const k=E();if(k&&k.length>1){const T=k[k.length-1],B=T[0]&n.TAPLEAF_VERSION_MASK,U=k[k.length-2],$=(0,i.tapleafHash)({output:U,version:B});return(0,i.rootHashFromPath)(T,$)}return null}),o.prop(S,"output",()=>{if(S.pubkey)return r.compile([u.OP_1,S.pubkey])}),o.prop(S,"redeemVersion",()=>d.redeemVersion?d.redeemVersion:d.redeem&&d.redeem.redeemVersion!==void 0&&d.redeem.redeemVersion!==null?d.redeem.redeemVersion:i.LEAF_VERSION_TAPSCRIPT),o.prop(S,"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}}),o.prop(S,"pubkey",()=>{if(d.pubkey)return d.pubkey;if(d.output)return d.output.slice(2);if(d.address)return b().data;if(S.internalPubkey){const w=(0,i.tweakKey)(S.internalPubkey,S.hash);if(w)return w.x}}),o.prop(S,"internalPubkey",()=>{if(d.internalPubkey)return d.internalPubkey;const w=E();if(w&&w.length>1)return w[w.length-1].slice(1,33)}),o.prop(S,"signature",()=>{if(d.signature)return d.signature;const w=E();if(!(!w||w.length!==1))return w[0]}),o.prop(S,"witness",()=>{if(d.witness)return d.witness;const w=A();if(w&&d.redeem&&d.redeem.output&&d.internalPubkey){const k=(0,i.tapleafHash)({output:d.redeem.output,version:S.redeemVersion}),T=(0,i.findScriptPath)(w,k);if(!T)return;const B=(0,i.tweakKey)(d.internalPubkey,w.hash);if(!B)return;const U=t.Buffer.concat([t.Buffer.from([S.redeemVersion|B.parity]),d.internalPubkey].concat(T));return[d.redeem.output,U]}if(d.signature)return[d.signature]}),m.validate){let w=t.Buffer.from([]);if(d.address){if(P&&P.bech32!==b().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(b().version!==f)throw new TypeError("Invalid address version");if(b().data.length!==32)throw new TypeError("Invalid address data");w=b().data}if(d.pubkey){if(w.length>0&&!w.equals(d.pubkey))throw new TypeError("Pubkey mismatch");w=d.pubkey}if(d.output){if(d.output.length!==34||d.output[0]!==u.OP_1||d.output[1]!==32)throw new TypeError("Output is invalid");if(w.length>0&&!w.equals(d.output.slice(2)))throw new TypeError("Pubkey mismatch");w=d.output.slice(2)}if(d.internalPubkey){const B=(0,i.tweakKey)(d.internalPubkey,S.hash);if(w.length>0&&!w.equals(B.x))throw new TypeError("Pubkey mismatch");w=B.x}if(w&&w.length&&!(0,s.getEccLib)().isXOnlyPoint(w))throw new TypeError("Invalid pubkey for p2tr");const k=A();if(d.hash&&k&&!d.hash.equals(k.hash))throw new TypeError("Hash mismatch");if(d.redeem&&d.redeem.output&&k){const B=(0,i.tapleafHash)({output:d.redeem.output,version:S.redeemVersion});if(!(0,i.findScriptPath)(k,B))throw new TypeError("Redeem script not in tree")}const T=E();if(d.redeem&&S.redeem){if(d.redeem.redeemVersion&&d.redeem.redeemVersion!==S.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(d.redeem.output){if(r.decompile(d.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(S.redeem.output&&!d.redeem.output.equals(S.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(d.redeem.witness&&S.redeem.witness&&!(0,n.stacksEqual)(d.redeem.witness,S.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(T&&T.length)if(T.length===1){if(d.signature&&!d.signature.equals(T[0]))throw new TypeError("Signature mismatch")}else{const B=T[T.length-1];if(B.length<33)throw new TypeError(`The control-block length is too small. Got ${B.length}, expected min 33.`);if((B.length-33)%32!==0)throw new TypeError(`The control-block length of ${B.length} is incorrect!`);const U=(B.length-33)/32;if(U>128)throw new TypeError(`The script path is too long. Got ${U}, expected max 128.`);const $=B.slice(1,33);if(d.internalPubkey&&!d.internalPubkey.equals($))throw new TypeError("Internal pubkey mismatch");if(!(0,s.getEccLib)().isXOnlyPoint($))throw new TypeError("Invalid internalPubkey for p2tr witness");const D=B[0]&n.TAPLEAF_VERSION_MASK,M=T[T.length-2],q=(0,i.tapleafHash)({output:M,version:D}),K=(0,i.rootHashFromPath)(B,q),Q=(0,i.tweakKey)($,K);if(!Q)throw new TypeError("Invalid outputKey for p2tr witness");if(w.length&&!w.equals(Q.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(Q.parity!==(B[0]&1))throw new Error("Incorrect parity")}}return Object.assign(S,d)}return oo.p2tr=p,oo}var j0;function jh(){return j0||(j0=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.p2tr=t.p2wsh=t.p2wpkh=t.p2sh=t.p2pkh=t.p2pk=t.p2ms=t.embed=void 0;const e=su;Object.defineProperty(t,"embed",{enumerable:!0,get:function(){return e.p2data}});const r=iu;Object.defineProperty(t,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=ou;Object.defineProperty(t,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const s=au;Object.defineProperty(t,"p2pkh",{enumerable:!0,get:function(){return s.p2pkh}});const i=cu;Object.defineProperty(t,"p2sh",{enumerable:!0,get:function(){return i.p2sh}});const o=uu;Object.defineProperty(t,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const a=fu;Object.defineProperty(t,"p2wsh",{enumerable:!0,get:function(){return a.p2wsh}});const c=AT();Object.defineProperty(t,"p2tr",{enumerable:!0,get:function(){return c.p2tr}})}(tf)),tf}Object.defineProperty(Pe,"__esModule",{value:!0});Pe.signatureBlocksAction=Pe.checkInputForSig=Pe.pubkeyInScript=Pe.pubkeyPositionInScript=Pe.witnessStackToScriptWitness=Pe.isP2TR=Pe.isP2SHScript=Pe.isP2WSHScript=Pe.isP2WPKH=Pe.isP2PKH=Pe.isP2PK=Pe.isP2MS=void 0;const L0=_a,Eo=er(),Ka=Ta,xT=ls,ei=jh();function ti(t){return e=>{try{return t({output:e}),!0}catch{return!1}}}Pe.isP2MS=ti(ei.p2ms);Pe.isP2PK=ti(ei.p2pk);Pe.isP2PKH=ti(ei.p2pkh);Pe.isP2WPKH=ti(ei.p2wpkh);Pe.isP2WSHScript=ti(ei.p2wsh);Pe.isP2SHScript=ti(ei.p2sh);Pe.isP2TR=ti(ei.p2tr);function kT(t){let e=Buffer.allocUnsafe(0);function r(o){e=Buffer.concat([e,Buffer.from(o)])}function n(o){const a=e.length,c=L0.encodingLength(o);e=Buffer.concat([e,Buffer.allocUnsafe(c)]),L0.encode(o,e,a)}function s(o){n(o.length),r(o)}function i(o){n(o.length),o.forEach(s)}return i(t),e}Pe.witnessStackToScriptWitness=kT;function rw(t,e){const r=(0,xT.hash160)(t),n=t.slice(1,33),s=Eo.decompile(e);if(s===null)throw new Error("Unknown script error");return s.findIndex(i=>typeof i=="number"?!1:i.equals(t)||i.equals(r)||i.equals(n))}Pe.pubkeyPositionInScript=rw;function TT(t,e){return rw(t,e)!==-1}Pe.pubkeyInScript=TT;function _T(t,e){return PT(t).some(n=>nw(n,Eo.signature.decode,e))}Pe.checkInputForSig=_T;function nw(t,e,r){const{hashType:n}=e(t),s=[];switch(n&Ka.Transaction.SIGHASH_ANYONECANPAY&&s.push("addInput"),n&31){case Ka.Transaction.SIGHASH_ALL:break;case Ka.Transaction.SIGHASH_SINGLE:case Ka.Transaction.SIGHASH_NONE:s.push("addOutput"),s.push("setInputSequence");break}return s.indexOf(r)===-1}Pe.signatureBlocksAction=nw;function PT(t){let e=[];if((t.partialSig||[]).length===0){if(!t.finalScriptSig&&!t.finalScriptWitness)return[];e=IT(t)}else e=t.partialSig;return e.map(r=>r.signature)}function IT(t){const e=t.finalScriptSig?Eo.decompile(t.finalScriptSig)||[]:[],r=t.finalScriptWitness?Eo.decompile(t.finalScriptWitness)||[]:[];return e.concat(r).filter(n=>Buffer.isBuffer(n)&&Eo.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(Le,"__esModule",{value:!0});Le.checkTaprootInputForSigs=Le.tapTreeFromList=Le.tapTreeToList=Le.tweakInternalPubKey=Le.checkTaprootOutputFields=Le.checkTaprootInputFields=Le.isTaprootOutput=Le.isTaprootInput=mo=Le.serializeTaprootSignature=Le.tapScriptFinalizer=Le.toXOnly=void 0;const Lh=Et,OT=Ta,lu=Pe,cs=Fh,BT=jh(),CT=Pe,$T=t=>t.length===32?t:t.slice(1,33);Le.toXOnly=$T;function RT(t,e,r){const n=JT(e,t,r);try{const i=YT(e,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,lu.witnessStackToScriptWitness)(i)}}catch(s){throw new Error(`Can not finalize taproot input #${t}: ${s}`)}}Le.tapScriptFinalizer=RT;function NT(t,e){const r=e?Buffer.from([e]):Buffer.from([]);return Buffer.concat([t,r])}var mo=Le.serializeTaprootSignature=NT;function uc(t){return t&&!!(t.tapInternalKey||t.tapMerkleRoot||t.tapLeafScript&&t.tapLeafScript.length||t.tapBip32Derivation&&t.tapBip32Derivation.length||t.witnessUtxo&&(0,lu.isP2TR)(t.witnessUtxo.script))}Le.isTaprootInput=uc;function fc(t,e){return t&&!!(t.tapInternalKey||t.tapTree||t.tapBip32Derivation&&t.tapBip32Derivation.length||e&&(0,lu.isP2TR)(e))}Le.isTaprootOutput=fc;function UT(t,e,r){WT(t,e,r),ZT(t,e,r)}Le.checkTaprootInputFields=UT;function MT(t,e,r){KT(t,e,r),FT(t,e)}Le.checkTaprootOutputFields=MT;function FT(t,e){if(!e.tapTree&&!e.tapInternalKey)return;const r=e.tapInternalKey||t.tapInternalKey,n=e.tapTree||t.tapTree;if(r){const{script:s}=t,i=jT(r,n);if(s&&!s.equals(i))throw new Error("Error adding output. Script or address missmatch.")}}function jT(t,e){const r=e&&sw(e.leaves),{output:n}=(0,BT.p2tr)({internalPubkey:t,scriptTree:r});return n}function LT(t,e){const r=e.tapInternalKey,n=r&&(0,cs.tweakKey)(r,e.tapMerkleRoot);if(!n)throw new Error(`Cannot tweak tap internal key for input #${t}. Public key: ${r&&r.toString("hex")}`);return n.x}Le.tweakInternalPubKey=LT;function DT(t){if(!(0,Lh.isTaptree)(t))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return hd(t)}Le.tapTreeToList=DT;function sw(t=[]){return t.length===1&&t[0].depth===0?{output:t[0].script,version:t[0].leafVersion}:GT(t)}Le.tapTreeFromList=sw;function HT(t,e){return VT(t).some(n=>(0,CT.signatureBlocksAction)(n,zT,e))}Le.checkTaprootInputForSigs=HT;function zT(t){return{signature:t.slice(0,64),hashType:t.slice(64)[0]||OT.Transaction.SIGHASH_DEFAULT}}function VT(t){const e=[];if(t.tapKeySig&&e.push(t.tapKeySig),t.tapScriptSig&&e.push(...t.tapScriptSig.map(r=>r.signature)),!e.length){const r=qT(t.finalScriptWitness);r&&e.push(r)}return e}function qT(t){if(!t)return;const e=t.slice(2);if(e.length===64||e.length===65)return e}function hd(t,e=[],r=0){if(r>cs.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return t?(0,Lh.isTapleaf)(t)?(e.push({depth:r,leafVersion:t.version||cs.LEAF_VERSION_TAPSCRIPT,script:t.output}),e):(t[0]&&hd(t[0],e,r+1),t[1]&&hd(t[1],e,r+1),e):[]}function GT(t){let e;for(const r of t)if(e=pd(r,e),!e)throw new Error("No room left to insert tapleaf in tree");return e}function pd(t,e,r=0){if(r>cs.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(t.depth===r)return e?void 0:{output:t.script,version:t.leafVersion};if((0,Lh.isTapleaf)(e))return;const n=pd(t,e&&e[0],r+1);if(n)return[n,e&&e[1]];const s=pd(t,e&&e[1],r+1);if(s)return[e&&e[0],s]}function WT(t,e,r){const n=uc(t)&&_i(e),s=_i(t)&&uc(e),i=t===e&&uc(e)&&_i(e);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function KT(t,e,r){const n=fc(t)&&_i(e),s=_i(t)&&fc(e),i=t===e&&fc(e)&&_i(e);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function ZT(t,e,r){if(e.tapMerkleRoot){const n=(e.tapLeafScript||[]).every(i=>af(i,e.tapMerkleRoot)),s=(t.tapLeafScript||[]).every(i=>af(i,e.tapMerkleRoot));if(!n||!s)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(t.tapMerkleRoot&&!(e.tapLeafScript||[]).every(s=>af(s,t.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function af(t,e){if(!e)return!0;const r=(0,cs.tapleafHash)({output:t.script,version:t.leafVersion});return(0,cs.rootHashFromPath)(t.controlBlock,r).equals(e)}function YT(t,e){const r=(0,cs.tapleafHash)({output:e.script,version:e.leafVersion});return(t.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>XT(e.script,n)).sort((n,s)=>s.positionInScript-n.positionInScript).map(n=>n.signature)}function XT(t,e){return Object.assign({positionInScript:(0,lu.pubkeyPositionInScript)(e.pubkey,t)},e)}function JT(t,e,r){if(!t.tapScriptSig||!t.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${e}. No tapleaf script signature provided.`);const n=(t.tapLeafScript||[]).sort((s,i)=>s.controlBlock.length-i.controlBlock.length).find(s=>QT(s,t.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${e}. Signature for tapleaf script not found.`);return n}function QT(t,e,r){const n=(0,cs.tapleafHash)({output:t.script,version:t.leafVersion});return(!r||r.equals(n))&&e.find(i=>i.leafHash.equals(n))!==void 0}function _i(t){return t&&!!(t.redeemScript||t.witnessScript||t.bip32Derivation&&t.bip32Derivation.length)}const nr={secretMismatch:"invalid secret",secretHashLenMismatch:"secret hash should be 32 bytes",pubkeyLenMismatch:"pubkey should be 32 bytes",zeroOrNegativeExpiry:"expiry should be greater than 0",htlcAddressGenerationFailed:"failed to generate htlc address",notFunded:"address not funded",noCounterpartySigs:"counterparty signatures are required",counterPartySigNotFound:t=>"counterparty signature not found for utxo "+t,invalidCounterpartySigForUTXO:t=>"invalid counterparty signature for utxo "+t,htlcNotExpired:t=>`HTLC not expired, need more ${t} blocks`,controlBlockGenerationFailed:"failed to generate control block",invalidLeaf:"invalid leaf"},Za=192;Ae.initEccLib(fr);let D0=class{constructor(e,r){this.signer=e,this.internalPubkey=b0(),this.network=q3(r)}address(e,r){const n=this.generateLeaves(e,r),{address:s}=Ae.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:n});if(!s)throw new Error(nr.htlcAddressGenerationFailed);return s}async _buildRawTx(e,r,n,s,i){const o=new Ae.Transaction;o.version=2;const a=this.address(e,n||"redeem"),c=await this.getProvider();let u=[];if(i&&i.length>0)for(const p of i){const d=await c.getTransaction(p);for(let m=0;m<d.vout.length;m++){const b=d.vout[m];b.scriptpubkey_address===a&&u.push({txid:d.txid,vout:m,value:b.value,status:{confirmed:!1}})}}else u=await c.getUTXOs(a);const f=u.reduce((p,d)=>p+d.value,0);if(f===0)throw new Error(`${a} ${nr.notFunded}`);for(let p=0;p<u.length;p++)o.addInput(Buffer.from(u[p].txid,"hex").reverse(),u[p].vout);if(s!=null&&s.vSize){const p=await c.getFeeRates(),d=Math.ceil(p.hourFee*s.vSize),m=f-d;return o.addOutput(Ae.address.toOutputScript(r,this.network),m),{tx:o,usedUtxos:u}}const l=(s==null?void 0:s.fee)??await c.suggestFee(a,f,xi.MEDIUM);return o.addOutput(Ae.address.toOutputScript(r,this.network),f-l),{tx:o,usedUtxos:u,fee:l,balance:f}}getOutputScript(e,r){return Ae.address.toOutputScript(this.address(e,r||"redeem"),this.network)}async initiate(e,r){const n=await this.getProvider(),s=await this.signer.getAddress();let i,o;X.isOrder(e)?(i=e.destination_swap.swap_id,o=Number(e.destination_swap.amount)):(i=e.to,o=Number(e.amount)),r===void 0&&(r=await n.suggestFee(s,o,xi.MEDIUM));const a=await this.signer.send(i,o,r);return g.Ok(a)}async generateRedeemSACP(e,r,n){const{tx:s,usedUtxos:i}=await this._buildRawTx(e,e.destination_swap.delegate,"redeem",{fee:n}),o=this.getOutputScript(e,"redeem"),a=Ae.Transaction.SIGHASH_SINGLE|Ae.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(1,e),u=i.map(l=>l.value),f=no(o,i.length);for(let l=0;l<s.ins.length;l++){const p=s.hashForWitnessV1(l,f,u,a,c),d=await this.signer.signSchnorr(p);s.setWitness(l,[mo(d,a),Buffer.from(r,"hex"),this.redeemLeaf(g.trim0x(e.destination_swap.secret_hash),je(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}return s.toHex()}async generateInstantRefundSACP(e){const r=this.getOutputScript(e,"instantRefund"),{tx:n,usedUtxos:s,fee:i}=await this._buildRawTx(e,e.destination_swap.delegate,"instantRefund",{fee:0});n.outs=[];const o=Math.max(...s.map(l=>l.value));s.forEach(({value:l})=>{n.addOutput(r,l-(l===o?i??0:0))});const a=Ae.Transaction.SIGHASH_SINGLE|Ae.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(2,e),u=s.map(l=>l.value),f=no(r,s.length);for(let l=0;l<n.ins.length;l++){const p=n.hashForWitnessV1(l,f,u,a,c),d=await this.signer.signSchnorr(p);n.setWitness(l,[mo(d,a),mo(d,a),this.instantRefundLeaf(je(e.source_swap.initiator),je(e.destination_swap.delegate)),await this.generateControlBlockFor(2,e)])}return n.toHex()}async generateInstantRefundSACPWithHash(e){const r=[],n=Ae.Transaction.SIGHASH_SINGLE|Ae.Transaction.SIGHASH_ANYONECANPAY;for(let s=0;s<e.length;s++){const i=Buffer.from(e[s],"hex"),o=await this.signer.signSchnorr(i);r.push(mo(o,n).toString("hex"))}return g.Ok(r)}async instantRefund(e,r,n){d0(r.length>0,nr.noCounterpartySigs);const{tx:s,usedUtxos:i}=await this._buildRawTx(e,await this.signer.getAddress(),"instantRefund",{fee:n});for(const p of i)if(!r.find(d=>d.utxo===p.txid))throw new Error(nr.counterPartySigNotFound(p.txid));const o=this.getOutputScript(e,"instantRefund"),a=Ae.Transaction.SIGHASH_DEFAULT,c=this.leafHash(2,e),u=i.map(p=>p.value),f=no(o,i.length);for(let p=0;p<s.ins.length;p++){const d=s.hashForWitnessV1(p,f,u,a,c);if(!fr.verifySchnorr(d,Buffer.from(je(e.destination_swap.delegate),"hex"),Buffer.from(r[p].sig,"hex")))throw new Error(nr.invalidCounterpartySigForUTXO(r[p].utxo));const m=await this.signer.signSchnorr(d),b=Buffer.from(s.ins[p].hash).reverse().toString("hex"),E=r.find(A=>A.utxo===b);if(!E)throw new Error(nr.counterPartySigNotFound(b));s.setWitness(p,[Buffer.from(E.sig,"hex"),m,this.instantRefundLeaf(je(e.source_swap.initiator),je(e.destination_swap.delegate)),await this.generateControlBlockFor(2,e)])}return await(await this.getProvider()).broadcast(s.toHex())}async redeem(e,r,n){const s=await this.getRedeemHex(e,r,n);if(!s.ok)return g.Err(s.error);const o=await(await this.getProvider()).broadcast(s.val);return g.Ok(o)}async getRedeemHex(e,r,n){d0(Ae.crypto.sha256(Buffer.from(r,"hex")).toString("hex")===g.trim0x(e.destination_swap.secret_hash),nr.secretMismatch);const o=(X.isBitcoin(e.source_swap.chain)?e.source_swap.redeemer:e.destination_swap.redeemer)??await this.signer.getAddress(),{tx:a,usedUtxos:c}=await this._buildRawTx(e,o,"redeem",{fee:0},n),u=this.leafHash(1,e),f=c.map(m=>m.value),l=no(this.getOutputScript(e,"redeem"),c.length),p=Ae.Transaction.SIGHASH_DEFAULT;for(let m=0;m<a.ins.length;m++){const b=a.hashForWitnessV1(m,l,f,p,u),E=await this.signer.signSchnorr(b);a.setWitness(m,[E,Buffer.from(r,"hex"),this.redeemLeaf(g.trim0x(e.destination_swap.secret_hash),je(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}const{tx:d}=await this._buildRawTx(e,o,"redeem",{vSize:a.virtualSize()},n);for(let m=0;m<d.ins.length;m++){const b=d.hashForWitnessV1(m,l,f,p,u),E=await this.signer.signSchnorr(b);d.setWitness(m,[E,Buffer.from(r,"hex"),this.redeemLeaf(g.trim0x(e.destination_swap.secret_hash),je(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}return g.Ok(d.toHex())}async refund(e,r){const{tx:n,usedUtxos:s}=await this._buildRawTx(e,e.source_swap.delegate??await this.signer.getAddress(),"refund",{fee:r}),[i,o]=await this.canRefund(e,s);if(!i)throw new Error(nr.htlcNotExpired(o));const a=this.leafHash(0,e),c=s.map(d=>d.value),u=no(this.getOutputScript(e,"refund"),s.length),f=Ae.Transaction.SIGHASH_DEFAULT;for(let d=0;d<n.ins.length;d++){n.ins[d].sequence=e.source_swap.timelock;const m=n.hashForWitnessV1(d,u,c,f,a),b=await this.signer.signSchnorr(m);n.setWitness(d,[b,this.refundLeaf(e.source_swap.timelock,je(e.source_swap.initiator)),await this.generateControlBlockFor(0,e)])}const p=await(await this.getProvider()).broadcast(n.toHex());return g.Ok(p)}async canRefund(e,r){const s=await(await this.getProvider()).getLatestTip();for(const i of r){let o=0;if(i.status.confirmed&&i.status.block_height+e.source_swap.timelock>s?o=i.status.block_height+e.source_swap.timelock-s+1:i.status.confirmed||(o=e.source_swap.timelock+1),o>0)return[!1,o]}return[!0,0]}async generateControlBlockFor(e,r){let n,s;switch(e){case 1:n=this.redeemLeaf(g.trim0x(r.destination_swap.secret_hash),je(r.destination_swap.delegate)),s=this.generateLeaves(r,"redeem");break;case 0:n=this.refundLeaf(r.source_swap.timelock,je(r.source_swap.initiator)),s=this.generateLeaves(r,"refund");break;case 2:n=this.instantRefundLeaf(je(r.source_swap.initiator),je(r.destination_swap.delegate)),s=this.generateLeaves(r,"instantRefund");break;default:throw new Error(nr.controlBlockGenerationFailed)}const i=await this.signer.getNetwork(),o=Ae.payments.p2tr({internalPubkey:b0(),network:i,scriptTree:s,redeem:{output:n,redeemVersion:Za}});if(!o.witness)throw new Error(nr.controlBlockGenerationFailed);return o.witness[o.witness.length-1]}leafHash(e,r){let n;switch(e){case 1:n=this.redeemLeaf(g.trim0x(r.destination_swap.secret_hash),je(r.destination_swap.delegate));break;case 0:n=this.refundLeaf(r.source_swap.timelock,je(r.source_swap.initiator));break;case 2:n=this.instantRefundLeaf(je(r.source_swap.initiator),je(r.destination_swap.redeemer));break;default:throw new Error(nr.invalidLeaf)}return Ae.crypto.taggedHash("TapLeaf",j3(n))}refundLeaf(e,r){return Ae.script.fromASM(`
|
|
54
|
+
`,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var Yt={};Object.defineProperty(Yt,"__esModule",{value:!0});Yt.value=Yt.prop=void 0;function Vk(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const n=r.call(this);return this[e]=n,n},set(n){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:n,writable:!0})}})}Yt.prop=Vk;function qk(t){let e;return()=>(e!==void 0||(e=t()),e)}Yt.value=qk;Object.defineProperty(ou,"__esModule",{value:!0});ou.p2data=void 0;const Gk=vt,ac=er(),Dr=Et,_0=Yt,P0=ac.OPS;function Wk(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Dr.typeforce)({network:Dr.typeforce.maybe(Dr.typeforce.Object),output:Dr.typeforce.maybe(Dr.typeforce.Buffer),data:Dr.typeforce.maybe(Dr.typeforce.arrayOf(Dr.typeforce.Buffer))},t);const n={name:"embed",network:t.network||Gk.bitcoin};if(_0.prop(n,"output",()=>{if(t.data)return ac.compile([P0.OP_RETURN].concat(t.data))}),_0.prop(n,"data",()=>{if(t.output)return ac.decompile(t.output).slice(1)}),e.validate&&t.output){const s=ac.decompile(t.output);if(s[0]!==P0.OP_RETURN)throw new TypeError("Output is invalid");if(!s.slice(1).every(Dr.typeforce.Buffer))throw new TypeError("Output is invalid");if(t.data&&!(0,Dr.stacksEqual)(t.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,t)}ou.p2data=Wk;var au={};Object.defineProperty(au,"__esModule",{value:!0});au.p2ms=void 0;const Kk=vt,fi=er(),We=Et,Ln=Yt,li=fi.OPS,Va=li.OP_RESERVED;function Zk(t,e){if(!t.input&&!t.output&&!(t.pubkeys&&t.m!==void 0)&&!t.signatures)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{});function r(c){return fi.isCanonicalScriptSignature(c)||(e.allowIncomplete&&c===li.OP_0)!==void 0}(0,We.typeforce)({network:We.typeforce.maybe(We.typeforce.Object),m:We.typeforce.maybe(We.typeforce.Number),n:We.typeforce.maybe(We.typeforce.Number),output:We.typeforce.maybe(We.typeforce.Buffer),pubkeys:We.typeforce.maybe(We.typeforce.arrayOf(We.isPoint)),signatures:We.typeforce.maybe(We.typeforce.arrayOf(r)),input:We.typeforce.maybe(We.typeforce.Buffer)},t);const s={network:t.network||Kk.bitcoin};let i=[],o=!1;function a(c){o||(o=!0,i=fi.decompile(c),s.m=i[0]-Va,s.n=i[i.length-2]-Va,s.pubkeys=i.slice(1,-2))}if(Ln.prop(s,"output",()=>{if(t.m&&s.n&&t.pubkeys)return fi.compile([].concat(Va+t.m,t.pubkeys,Va+s.n,li.OP_CHECKMULTISIG))}),Ln.prop(s,"m",()=>{if(s.output)return a(s.output),s.m}),Ln.prop(s,"n",()=>{if(s.pubkeys)return s.pubkeys.length}),Ln.prop(s,"pubkeys",()=>{if(t.output)return a(t.output),s.pubkeys}),Ln.prop(s,"signatures",()=>{if(t.input)return fi.decompile(t.input).slice(1)}),Ln.prop(s,"input",()=>{if(t.signatures)return fi.compile([li.OP_0].concat(t.signatures))}),Ln.prop(s,"witness",()=>{if(s.input)return[]}),Ln.prop(s,"name",()=>{if(!(!s.m||!s.n))return`p2ms(${s.m} of ${s.n})`}),e.validate){if(t.output){if(a(t.output),!We.typeforce.Number(i[0]))throw new TypeError("Output is invalid");if(!We.typeforce.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==li.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(s.m<=0||s.n>16||s.m>s.n||s.n!==i.length-3)throw new TypeError("Output is invalid");if(!s.pubkeys.every(c=>(0,We.isPoint)(c)))throw new TypeError("Output is invalid");if(t.m!==void 0&&t.m!==s.m)throw new TypeError("m mismatch");if(t.n!==void 0&&t.n!==s.n)throw new TypeError("n mismatch");if(t.pubkeys&&!(0,We.stacksEqual)(t.pubkeys,s.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(t.n!==void 0&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(s.n=t.pubkeys.length,s.n<s.m)throw new TypeError("Pubkey count cannot be less than m")}if(t.signatures){if(t.signatures.length<s.m)throw new TypeError("Not enough signatures provided");if(t.signatures.length>s.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==li.OP_0)throw new TypeError("Input is invalid");if(s.signatures.length===0||!s.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!(0,We.stacksEqual)(t.signatures,s.signatures))throw new TypeError("Signature mismatch");if(t.m!==void 0&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(s,t)}au.p2ms=Zk;var cu={};Object.defineProperty(cu,"__esModule",{value:!0});cu.p2pk=void 0;const Yk=vt,di=er(),yr=Et,ai=Yt,I0=di.OPS;function Xk(t,e){if(!t.input&&!t.output&&!t.pubkey&&!t.input&&!t.signature)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,yr.typeforce)({network:yr.typeforce.maybe(yr.typeforce.Object),output:yr.typeforce.maybe(yr.typeforce.Buffer),pubkey:yr.typeforce.maybe(yr.isPoint),signature:yr.typeforce.maybe(di.isCanonicalScriptSignature),input:yr.typeforce.maybe(yr.typeforce.Buffer)},t);const r=ai.value(()=>di.decompile(t.input)),s={name:"p2pk",network:t.network||Yk.bitcoin};if(ai.prop(s,"output",()=>{if(t.pubkey)return di.compile([t.pubkey,I0.OP_CHECKSIG])}),ai.prop(s,"pubkey",()=>{if(t.output)return t.output.slice(1,-1)}),ai.prop(s,"signature",()=>{if(t.input)return r()[0]}),ai.prop(s,"input",()=>{if(t.signature)return di.compile([t.signature])}),ai.prop(s,"witness",()=>{if(s.input)return[]}),e.validate){if(t.output){if(t.output[t.output.length-1]!==I0.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,yr.isPoint)(s.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(s.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(s.input))throw new TypeError("Signature mismatch");if(t.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!di.isCanonicalScriptSignature(s.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(s,t)}cu.p2pk=Xk;var uu={};function Jk(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r<e.length;r++)e[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=n}var o=t.length,a=t.charAt(0),c=Math.log(o)/Math.log(256),u=Math.log(256)/Math.log(o);function f(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,b=0,E=0,A=d.length;E!==A&&d[E]===0;)E++,m++;for(var P=(A-E)*u+1>>>0,S=new Uint8Array(P);E!==A;){for(var w=d[E],k=0,T=P-1;(w!==0||k<b)&&T!==-1;T--,k++)w+=256*S[T]>>>0,S[T]=w%o>>>0,w=w/o>>>0;if(w!==0)throw new Error("Non-zero carry");b=k,E++}for(var B=P-b;B!==P&&S[B]===0;)B++;for(var N=a.repeat(m);B<P;++B)N+=t.charAt(S[B]);return N}function l(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;for(var m=0,b=0,E=0;d[m]===a;)b++,m++;for(var A=(d.length-m)*c+1>>>0,P=new Uint8Array(A);d[m];){var S=d.charCodeAt(m);if(S>255)return;var w=e[S];if(w===255)return;for(var k=0,T=A-1;(w!==0||k<E)&&T!==-1;T--,k++)w+=o*P[T]>>>0,P[T]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");E=k,m++}for(var B=A-E;B!==A&&P[B]===0;)B++;for(var N=new Uint8Array(b+(A-B)),$=b;B!==A;)N[$++]=P[B++];return N}function p(d){var m=l(d);if(m)return m;throw new Error("Non-base"+o+" character")}return{encode:f,decodeUnsafe:l,decode:p}}var Qk=Jk;const eT=Qk,tT="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var rT=eT(tT),sf=rT,nT=function(t){function e(i){var o=Uint8Array.from(i),a=t(o),c=o.length+4,u=new Uint8Array(c);return u.set(o,0),u.set(a.subarray(0,4),o.length),sf.encode(u,c)}function r(i){var o=i.slice(0,-4),a=i.slice(-4),c=t(o);if(!(a[0]^c[0]|a[1]^c[1]|a[2]^c[2]|a[3]^c[3]))return o}function n(i){var o=sf.decodeUnsafe(i);if(o)return r(o)}function s(i){var o=sf.decode(i),a=r(o);if(!a)throw new Error("Invalid checksum");return a}return{encode:e,decode:s,decodeUnsafe:n}},{sha256:O0}=Y1,sT=nT;function iT(t){return O0(O0(t))}var Mh=sT(iT);Object.defineProperty(uu,"__esModule",{value:!0});uu.p2pkh=void 0;const of=ls,oT=vt,hi=er(),kt=Et,on=Yt,B0=Mh,Dn=hi.OPS;function aT(t,e){if(!t.address&&!t.hash&&!t.output&&!t.pubkey&&!t.input)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,kt.typeforce)({network:kt.typeforce.maybe(kt.typeforce.Object),address:kt.typeforce.maybe(kt.typeforce.String),hash:kt.typeforce.maybe(kt.typeforce.BufferN(20)),output:kt.typeforce.maybe(kt.typeforce.BufferN(25)),pubkey:kt.typeforce.maybe(kt.isPoint),signature:kt.typeforce.maybe(hi.isCanonicalScriptSignature),input:kt.typeforce.maybe(kt.typeforce.Buffer)},t);const r=on.value(()=>{const o=Buffer.from(B0.decode(t.address)),a=o.readUInt8(0),c=o.slice(1);return{version:a,hash:c}}),n=on.value(()=>hi.decompile(t.input)),s=t.network||oT.bitcoin,i={name:"p2pkh",network:s};if(on.prop(i,"address",()=>{if(!i.hash)return;const o=Buffer.allocUnsafe(21);return o.writeUInt8(s.pubKeyHash,0),i.hash.copy(o,1),B0.encode(o)}),on.prop(i,"hash",()=>{if(t.output)return t.output.slice(3,23);if(t.address)return r().hash;if(t.pubkey||i.pubkey)return of.hash160(t.pubkey||i.pubkey)}),on.prop(i,"output",()=>{if(i.hash)return hi.compile([Dn.OP_DUP,Dn.OP_HASH160,i.hash,Dn.OP_EQUALVERIFY,Dn.OP_CHECKSIG])}),on.prop(i,"pubkey",()=>{if(t.input)return n()[1]}),on.prop(i,"signature",()=>{if(t.input)return n()[0]}),on.prop(i,"input",()=>{if(t.pubkey&&t.signature)return hi.compile([t.signature,t.pubkey])}),on.prop(i,"witness",()=>{if(i.input)return[]}),e.validate){let o=Buffer.from([]);if(t.address){if(r().version!==s.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");o=r().hash}if(t.hash){if(o.length>0&&!o.equals(t.hash))throw new TypeError("Hash mismatch");o=t.hash}if(t.output){if(t.output.length!==25||t.output[0]!==Dn.OP_DUP||t.output[1]!==Dn.OP_HASH160||t.output[2]!==20||t.output[23]!==Dn.OP_EQUALVERIFY||t.output[24]!==Dn.OP_CHECKSIG)throw new TypeError("Output is invalid");const a=t.output.slice(3,23);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(t.pubkey){const a=of.hash160(t.pubkey);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(t.input){const a=n();if(a.length!==2)throw new TypeError("Input is invalid");if(!hi.isCanonicalScriptSignature(a[0]))throw new TypeError("Input has invalid signature");if(!(0,kt.isPoint)(a[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(a[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(a[1]))throw new TypeError("Pubkey mismatch");const c=of.hash160(a[1]);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)}uu.p2pkh=aT;var fu={};Object.defineProperty(fu,"__esModule",{value:!0});fu.p2sh=void 0;const C0=ls,cT=vt,Vr=er(),Re=Et,Hr=Yt,$0=Mh,io=Vr.OPS;function uT(t,e){if(!t.address&&!t.hash&&!t.output&&!t.redeem&&!t.input)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Re.typeforce)({network:Re.typeforce.maybe(Re.typeforce.Object),address:Re.typeforce.maybe(Re.typeforce.String),hash:Re.typeforce.maybe(Re.typeforce.BufferN(20)),output:Re.typeforce.maybe(Re.typeforce.BufferN(23)),redeem:Re.typeforce.maybe({network:Re.typeforce.maybe(Re.typeforce.Object),output:Re.typeforce.maybe(Re.typeforce.Buffer),input:Re.typeforce.maybe(Re.typeforce.Buffer),witness:Re.typeforce.maybe(Re.typeforce.arrayOf(Re.typeforce.Buffer))}),input:Re.typeforce.maybe(Re.typeforce.Buffer),witness:Re.typeforce.maybe(Re.typeforce.arrayOf(Re.typeforce.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||cT.bitcoin);const n={network:r},s=Hr.value(()=>{const a=Buffer.from($0.decode(t.address)),c=a.readUInt8(0),u=a.slice(1);return{version:c,hash:u}}),i=Hr.value(()=>Vr.decompile(t.input)),o=Hr.value(()=>{const a=i(),c=a[a.length-1];return{network:r,output:c===io.OP_FALSE?Buffer.from([]):c,input:Vr.compile(a.slice(0,-1)),witness:t.witness||[]}});if(Hr.prop(n,"address",()=>{if(!n.hash)return;const a=Buffer.allocUnsafe(21);return a.writeUInt8(n.network.scriptHash,0),n.hash.copy(a,1),$0.encode(a)}),Hr.prop(n,"hash",()=>{if(t.output)return t.output.slice(2,22);if(t.address)return s().hash;if(n.redeem&&n.redeem.output)return C0.hash160(n.redeem.output)}),Hr.prop(n,"output",()=>{if(n.hash)return Vr.compile([io.OP_HASH160,n.hash,io.OP_EQUAL])}),Hr.prop(n,"redeem",()=>{if(t.input)return o()}),Hr.prop(n,"input",()=>{if(!(!t.redeem||!t.redeem.input||!t.redeem.output))return Vr.compile([].concat(Vr.decompile(t.redeem.input),t.redeem.output))}),Hr.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),Hr.prop(n,"name",()=>{const a=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&a.push(n.redeem.name),a.join("-")}),e.validate){let a=Buffer.from([]);if(t.address){if(s().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(s().hash.length!==20)throw new TypeError("Invalid address");a=s().hash}if(t.hash){if(a.length>0&&!a.equals(t.hash))throw new TypeError("Hash mismatch");a=t.hash}if(t.output){if(t.output.length!==23||t.output[0]!==io.OP_HASH160||t.output[1]!==20||t.output[22]!==io.OP_EQUAL)throw new TypeError("Output is invalid");const u=t.output.slice(2,22);if(a.length>0&&!a.equals(u))throw new TypeError("Hash mismatch");a=u}const c=u=>{if(u.output){const f=Vr.decompile(u.output);if(!f||f.length<1)throw new TypeError("Redeem.output too short");if(u.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(Vr.countNonPushOnlyOPs(f)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const l=C0.hash160(u.output);if(a.length>0&&!a.equals(l))throw new TypeError("Hash mismatch");a=l}if(u.input){const f=u.input.length>0,l=u.witness&&u.witness.length>0;if(!f&&!l)throw new TypeError("Empty input");if(f&&l)throw new TypeError("Input and witness provided");if(f){const p=Vr.decompile(u.input);if(!Vr.isPushOnly(p))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const u=i();if(!u||u.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(o().output))throw new TypeError("Input is invalid");c(o())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const u=o();if(t.redeem.output&&!t.redeem.output.equals(u.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(u.input))throw new TypeError("Redeem.input mismatch")}c(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!(0,Re.stacksEqual)(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)}fu.p2sh=uT;var lu={},In={};Object.defineProperty(In,"__esModule",{value:!0});In.bech32m=In.bech32=void 0;const Ac="qpzry9x8gf2tvdw0s3jn54khce6mua7l",ew={};for(let t=0;t<Ac.length;t++){const e=Ac.charAt(t);ew[e]=t}function Ti(t){const e=t>>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function R0(t){let e=1;for(let r=0;r<t.length;++r){const n=t.charCodeAt(r);if(n<33||n>126)return"Invalid prefix ("+t+")";e=Ti(e)^n>>5}e=Ti(e);for(let r=0;r<t.length;++r){const n=t.charCodeAt(r);e=Ti(e)^n&31}return e}function Fh(t,e,r,n){let s=0,i=0;const o=(1<<r)-1,a=[];for(let c=0;c<t.length;++c)for(s=s<<e|t[c],i+=e;i>=r;)i-=r,a.push(s>>i&o);if(n)i>0&&a.push(s<<r-i&o);else{if(i>=e)return"Excess padding";if(s<<r-i&o)return"Non-zero padding"}return a}function fT(t){return Fh(t,8,5,!0)}function lT(t){const e=Fh(t,5,8,!1);if(Array.isArray(e))return e}function dT(t){const e=Fh(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}function tw(t){let e;t==="bech32"?e=1:e=734539939;function r(o,a,c){if(c=c||90,o.length+7+a.length>c)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let u=R0(o);if(typeof u=="string")throw new Error(u);let f=o+"1";for(let l=0;l<a.length;++l){const p=a[l];if(p>>5)throw new Error("Non 5-bit word");u=Ti(u)^p,f+=Ac.charAt(p)}for(let l=0;l<6;++l)u=Ti(u);u^=e;for(let l=0;l<6;++l){const p=u>>(5-l)*5&31;f+=Ac.charAt(p)}return f}function n(o,a){if(a=a||90,o.length<8)return o+" too short";if(o.length>a)return"Exceeds length limit";const c=o.toLowerCase(),u=o.toUpperCase();if(o!==c&&o!==u)return"Mixed-case string "+o;o=c;const f=o.lastIndexOf("1");if(f===-1)return"No separator character for "+o;if(f===0)return"Missing prefix for "+o;const l=o.slice(0,f),p=o.slice(f+1);if(p.length<6)return"Data too short";let d=R0(l);if(typeof d=="string")return d;const m=[];for(let b=0;b<p.length;++b){const E=p.charAt(b),A=ew[E];if(A===void 0)return"Unknown character "+E;d=Ti(d)^A,!(b+6>=p.length)&&m.push(A)}return d!==e?"Invalid checksum for "+o:{prefix:l,words:m}}function s(o,a){const c=n(o,a);if(typeof c=="object")return c}function i(o,a){const c=n(o,a);if(typeof c=="object")return c;throw new Error(c)}return{decodeUnsafe:s,decode:i,encode:r,toWords:fT,fromWordsUnsafe:lT,fromWords:dT}}In.bech32=tw("bech32");In.bech32m=tw("bech32m");Object.defineProperty(lu,"__esModule",{value:!0});lu.p2wpkh=void 0;const af=ls,hT=vt,cc=er(),rt=Et,Hn=Yt,qa=In,N0=cc.OPS,pT=Buffer.alloc(0);function yT(t,e){if(!t.address&&!t.hash&&!t.output&&!t.pubkey&&!t.witness)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,rt.typeforce)({address:rt.typeforce.maybe(rt.typeforce.String),hash:rt.typeforce.maybe(rt.typeforce.BufferN(20)),input:rt.typeforce.maybe(rt.typeforce.BufferN(0)),network:rt.typeforce.maybe(rt.typeforce.Object),output:rt.typeforce.maybe(rt.typeforce.BufferN(22)),pubkey:rt.typeforce.maybe(rt.isPoint),signature:rt.typeforce.maybe(cc.isCanonicalScriptSignature),witness:rt.typeforce.maybe(rt.typeforce.arrayOf(rt.typeforce.Buffer))},t);const r=Hn.value(()=>{const i=qa.bech32.decode(t.address),o=i.words.shift(),a=qa.bech32.fromWords(i.words);return{version:o,prefix:i.prefix,data:Buffer.from(a)}}),n=t.network||hT.bitcoin,s={name:"p2wpkh",network:n};if(Hn.prop(s,"address",()=>{if(!s.hash)return;const i=qa.bech32.toWords(s.hash);return i.unshift(0),qa.bech32.encode(n.bech32,i)}),Hn.prop(s,"hash",()=>{if(t.output)return t.output.slice(2,22);if(t.address)return r().data;if(t.pubkey||s.pubkey)return af.hash160(t.pubkey||s.pubkey)}),Hn.prop(s,"output",()=>{if(s.hash)return cc.compile([N0.OP_0,s.hash])}),Hn.prop(s,"pubkey",()=>{if(t.pubkey)return t.pubkey;if(t.witness)return t.witness[1]}),Hn.prop(s,"signature",()=>{if(t.witness)return t.witness[0]}),Hn.prop(s,"input",()=>{if(s.witness)return pT}),Hn.prop(s,"witness",()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]}),e.validate){let i=Buffer.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==20)throw new TypeError("Invalid address data");i=r().data}if(t.hash){if(i.length>0&&!i.equals(t.hash))throw new TypeError("Hash mismatch");i=t.hash}if(t.output){if(t.output.length!==22||t.output[0]!==N0.OP_0||t.output[1]!==20)throw new TypeError("Output is invalid");if(i.length>0&&!i.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");i=t.output.slice(2)}if(t.pubkey){const o=af.hash160(t.pubkey);if(i.length>0&&!i.equals(o))throw new TypeError("Hash mismatch");if(i=o,!(0,rt.isPoint)(t.pubkey)||t.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(t.witness.length!==2)throw new TypeError("Witness is invalid");if(!cc.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,rt.isPoint)(t.witness[1])||t.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const o=af.hash160(t.witness[1]);if(i.length>0&&!i.equals(o))throw new TypeError("Hash mismatch")}}return Object.assign(s,t)}lu.p2wpkh=yT;var du={};Object.defineProperty(du,"__esModule",{value:!0});du.p2wsh=void 0;const U0=ls,mT=vt,hn=er(),Ce=Et,an=Yt,Ga=In,M0=hn.OPS,cf=Buffer.alloc(0);function Wa(t){return!!(Buffer.isBuffer(t)&&t.length===65&&t[0]===4&&(0,Ce.isPoint)(t))}function bT(t,e){if(!t.address&&!t.hash&&!t.output&&!t.redeem&&!t.witness)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Ce.typeforce)({network:Ce.typeforce.maybe(Ce.typeforce.Object),address:Ce.typeforce.maybe(Ce.typeforce.String),hash:Ce.typeforce.maybe(Ce.typeforce.BufferN(32)),output:Ce.typeforce.maybe(Ce.typeforce.BufferN(34)),redeem:Ce.typeforce.maybe({input:Ce.typeforce.maybe(Ce.typeforce.Buffer),network:Ce.typeforce.maybe(Ce.typeforce.Object),output:Ce.typeforce.maybe(Ce.typeforce.Buffer),witness:Ce.typeforce.maybe(Ce.typeforce.arrayOf(Ce.typeforce.Buffer))}),input:Ce.typeforce.maybe(Ce.typeforce.BufferN(0)),witness:Ce.typeforce.maybe(Ce.typeforce.arrayOf(Ce.typeforce.Buffer))},t);const r=an.value(()=>{const o=Ga.bech32.decode(t.address),a=o.words.shift(),c=Ga.bech32.fromWords(o.words);return{version:a,prefix:o.prefix,data:Buffer.from(c)}}),n=an.value(()=>hn.decompile(t.redeem.input));let s=t.network;s||(s=t.redeem&&t.redeem.network||mT.bitcoin);const i={network:s};if(an.prop(i,"address",()=>{if(!i.hash)return;const o=Ga.bech32.toWords(i.hash);return o.unshift(0),Ga.bech32.encode(s.bech32,o)}),an.prop(i,"hash",()=>{if(t.output)return t.output.slice(2);if(t.address)return r().data;if(i.redeem&&i.redeem.output)return U0.sha256(i.redeem.output)}),an.prop(i,"output",()=>{if(i.hash)return hn.compile([M0.OP_0,i.hash])}),an.prop(i,"redeem",()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:cf,witness:t.witness.slice(0,-1)}}),an.prop(i,"input",()=>{if(i.witness)return cf}),an.prop(i,"witness",()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const o=hn.toStack(n());return i.redeem=Object.assign({witness:o},t.redeem),i.redeem.input=cf,[].concat(o,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)}),an.prop(i,"name",()=>{const o=["p2wsh"];return i.redeem!==void 0&&i.redeem.name!==void 0&&o.push(i.redeem.name),o.join("-")}),e.validate){let o=Buffer.from([]);if(t.address){if(r().prefix!==s.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==32)throw new TypeError("Invalid address data");o=r().data}if(t.hash){if(o.length>0&&!o.equals(t.hash))throw new TypeError("Hash mismatch");o=t.hash}if(t.output){if(t.output.length!==34||t.output[0]!==M0.OP_0||t.output[1]!==32)throw new TypeError("Output is invalid");const a=t.output.slice(2);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(t.redeem){if(t.redeem.network&&t.redeem.network!==s)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){const a=hn.decompile(t.redeem.output);if(!a||a.length<1)throw new TypeError("Redeem.output is invalid");if(t.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(hn.countNonPushOnlyOPs(a)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const c=U0.sha256(t.redeem.output);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch");o=c}if(t.redeem.input&&!hn.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!(0,Ce.stacksEqual)(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Wa)||t.redeem.output&&(hn.decompile(t.redeem.output)||[]).some(Wa))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const a=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(a))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Wa)||(hn.decompile(a)||[]).some(Wa))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(i,t)}du.p2wsh=bT;var oo={},Vs={};Object.defineProperty(Vs,"__esModule",{value:!0});Vs.getEccLib=Vs.initEccLib=void 0;const vo={};function gT(t,e){t?t!==vo.eccLib&&(e!=null&&e.DANGER_DO_NOT_VERIFY_ECCLIB||vT(t),vo.eccLib=t):vo.eccLib=t}Vs.initEccLib=gT;function wT(){if(!vo.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return vo.eccLib}Vs.getEccLib=wT;const cn=t=>Buffer.from(t,"hex");function vT(t){rr(typeof t.isXOnlyPoint=="function"),rr(t.isXOnlyPoint(cn("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),rr(t.isXOnlyPoint(cn("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),rr(t.isXOnlyPoint(cn("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),rr(t.isXOnlyPoint(cn("0000000000000000000000000000000000000000000000000000000000000001"))),rr(!t.isXOnlyPoint(cn("0000000000000000000000000000000000000000000000000000000000000000"))),rr(!t.isXOnlyPoint(cn("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),rr(typeof t.xOnlyPointAddTweak=="function"),ET.forEach(e=>{const r=t.xOnlyPointAddTweak(cn(e.pubkey),cn(e.tweak));e.result===null?rr(r===null):(rr(r!==null),rr(r.parity===e.parity),rr(Buffer.from(r.xOnlyPubkey).equals(cn(e.result))))})}function rr(t){if(!t)throw new Error("ecc library invalid")}const ET=[{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 jh={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.tweakKey=t.tapTweakHash=t.tapleafHash=t.findScriptPath=t.toHashTree=t.rootHashFromPath=t.MAX_TAPTREE_DEPTH=t.LEAF_VERSION_TAPSCRIPT=void 0;const e=Qs,r=Vs,n=ls,s=lt,i=Et;t.LEAF_VERSION_TAPSCRIPT=192,t.MAX_TAPTREE_DEPTH=128;const o=b=>"left"in b&&"right"in b;function a(b,E){if(b.length<33)throw new TypeError(`The control-block length is too small. Got ${b.length}, expected min 33.`);const A=(b.length-33)/32;let P=E;for(let S=0;S<A;S++){const w=b.slice(33+32*S,65+32*S);P.compare(w)<0?P=d(P,w):P=d(w,P)}return P}t.rootHashFromPath=a;function c(b){if((0,i.isTapleaf)(b))return{hash:f(b)};const E=[c(b[0]),c(b[1])];E.sort((S,w)=>S.hash.compare(w.hash));const[A,P]=E;return{hash:d(A.hash,P.hash),left:A,right:P}}t.toHashTree=c;function u(b,E){if(o(b)){const A=u(b.left,E);if(A!==void 0)return[...A,b.right.hash];const P=u(b.right,E);if(P!==void 0)return[...P,b.left.hash]}else if(b.hash.equals(E))return[]}t.findScriptPath=u;function f(b){const E=b.version||t.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",e.Buffer.concat([e.Buffer.from([E]),m(b.output)]))}t.tapleafHash=f;function l(b,E){return n.taggedHash("TapTweak",e.Buffer.concat(E?[b,E]:[b]))}t.tapTweakHash=l;function p(b,E){if(!e.Buffer.isBuffer(b)||b.length!==32||E&&E.length!==32)return null;const A=l(b,E),P=(0,r.getEccLib)().xOnlyPointAddTweak(b,A);return!P||P.xOnlyPubkey===null?null:{parity:P.parity,x:e.Buffer.from(P.xOnlyPubkey)}}t.tweakKey=p;function d(b,E){return n.taggedHash("TapBranch",e.Buffer.concat([b,E]))}function m(b){const E=s.varuint.encodingLength(b.length),A=e.Buffer.allocUnsafe(E);return s.varuint.encode(b.length,A),e.Buffer.concat([A,b])}})(jh);var Tt={},F0;function ST(){if(F0)return Tt;F0=1,Object.defineProperty(Tt,"__esModule",{value:!0}),Tt.toOutputScript=Tt.fromOutputScript=Tt.toBech32=Tt.toBase58Check=Tt.fromBech32=Tt.fromBase58Check=void 0;const t=vt,e=Lh(),r=er(),n=Et,s=In,i=Mh,o=40,a=2,c=16,u=2,f=80,l="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function p(S,w){const k=S.slice(2);if(k.length<a||k.length>o)throw new TypeError("Invalid program length for segwit address");const T=S[0]-f;if(T<u||T>c)throw new TypeError("Invalid version for segwit address");if(S[1]!==k.length)throw new TypeError("Invalid script for segwit address");return console.warn(l),E(k,T,w.bech32)}function d(S){const w=Buffer.from(i.decode(S));if(w.length<21)throw new TypeError(S+" is too short");if(w.length>21)throw new TypeError(S+" is too long");const k=w.readUInt8(0),T=w.slice(1);return{version:k,hash:T}}Tt.fromBase58Check=d;function m(S){let w,k;try{w=s.bech32.decode(S)}catch{}if(w){if(k=w.words[0],k!==0)throw new TypeError(S+" uses wrong encoding")}else if(w=s.bech32m.decode(S),k=w.words[0],k===0)throw new TypeError(S+" uses wrong encoding");const T=s.bech32.fromWords(w.words.slice(1));return{version:k,prefix:w.prefix,data:Buffer.from(T)}}Tt.fromBech32=m;function b(S,w){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const k=Buffer.allocUnsafe(21);return k.writeUInt8(w,0),S.copy(k,1),i.encode(k)}Tt.toBase58Check=b;function E(S,w,k){const T=s.bech32.toWords(S);return T.unshift(w),w===0?s.bech32.encode(k,T):s.bech32m.encode(k,T)}Tt.toBech32=E;function A(S,w){w=w||t.bitcoin;try{return e.p2pkh({output:S,network:w}).address}catch{}try{return e.p2sh({output:S,network:w}).address}catch{}try{return e.p2wpkh({output:S,network:w}).address}catch{}try{return e.p2wsh({output:S,network:w}).address}catch{}try{return e.p2tr({output:S,network:w}).address}catch{}try{return p(S,w)}catch{}throw new Error(r.toASM(S)+" has no matching Address")}Tt.fromOutputScript=A;function P(S,w){w=w||t.bitcoin;let k,T;try{k=d(S)}catch{}if(k){if(k.version===w.pubKeyHash)return e.p2pkh({hash:k.hash}).output;if(k.version===w.scriptHash)return e.p2sh({hash:k.hash}).output}else{try{T=m(S)}catch{}if(T){if(T.prefix!==w.bech32)throw new Error(S+" has an invalid prefix");if(T.version===0){if(T.data.length===20)return e.p2wpkh({hash:T.data}).output;if(T.data.length===32)return e.p2wsh({hash:T.data}).output}else if(T.version===1){if(T.data.length===32)return e.p2tr({pubkey:T.data}).output}else if(T.version>=u&&T.version<=c&&T.data.length>=a&&T.data.length<=o)return console.warn(l),r.compile([T.version+f,T.data])}}throw new Error(S+" has no matching Script")}return Tt.toOutputScript=P,Tt}var j0;function AT(){if(j0)return oo;j0=1,Object.defineProperty(oo,"__esModule",{value:!0}),oo.p2tr=void 0;const t=Qs,e=vt,r=er(),n=Et,s=Vs,i=jh,o=Yt,a=In,c=ST(),u=r.OPS,f=1,l=80;function p(d,m){if(!d.address&&!d.output&&!d.pubkey&&!d.internalPubkey&&!(d.witness&&d.witness.length>1))throw new TypeError("Not enough data");m=Object.assign({validate:!0},m||{}),(0,n.typeforce)({address:n.typeforce.maybe(n.typeforce.String),input:n.typeforce.maybe(n.typeforce.BufferN(0)),network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.BufferN(34)),internalPubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),hash:n.typeforce.maybe(n.typeforce.BufferN(32)),pubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),signature:n.typeforce.maybe(n.typeforce.anyOf(n.typeforce.BufferN(64),n.typeforce.BufferN(65))),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer)),scriptTree:n.typeforce.maybe(n.isTaptree),redeem:n.typeforce.maybe({output:n.typeforce.maybe(n.typeforce.Buffer),redeemVersion:n.typeforce.maybe(n.typeforce.Number),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer))}),redeemVersion:n.typeforce.maybe(n.typeforce.Number)},d);const b=o.value(()=>(0,c.fromBech32)(d.address)),E=o.value(()=>{if(!(!d.witness||!d.witness.length))return d.witness.length>=2&&d.witness[d.witness.length-1][0]===l?d.witness.slice(0,-1):d.witness.slice()}),A=o.value(()=>{if(d.scriptTree)return(0,i.toHashTree)(d.scriptTree);if(d.hash)return{hash:d.hash}}),P=d.network||e.bitcoin,S={name:"p2tr",network:P};if(o.prop(S,"address",()=>{if(!S.pubkey)return;const w=a.bech32m.toWords(S.pubkey);return w.unshift(f),a.bech32m.encode(P.bech32,w)}),o.prop(S,"hash",()=>{const w=A();if(w)return w.hash;const k=E();if(k&&k.length>1){const T=k[k.length-1],B=T[0]&n.TAPLEAF_VERSION_MASK,N=k[k.length-2],$=(0,i.tapleafHash)({output:N,version:B});return(0,i.rootHashFromPath)(T,$)}return null}),o.prop(S,"output",()=>{if(S.pubkey)return r.compile([u.OP_1,S.pubkey])}),o.prop(S,"redeemVersion",()=>d.redeemVersion?d.redeemVersion:d.redeem&&d.redeem.redeemVersion!==void 0&&d.redeem.redeemVersion!==null?d.redeem.redeemVersion:i.LEAF_VERSION_TAPSCRIPT),o.prop(S,"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}}),o.prop(S,"pubkey",()=>{if(d.pubkey)return d.pubkey;if(d.output)return d.output.slice(2);if(d.address)return b().data;if(S.internalPubkey){const w=(0,i.tweakKey)(S.internalPubkey,S.hash);if(w)return w.x}}),o.prop(S,"internalPubkey",()=>{if(d.internalPubkey)return d.internalPubkey;const w=E();if(w&&w.length>1)return w[w.length-1].slice(1,33)}),o.prop(S,"signature",()=>{if(d.signature)return d.signature;const w=E();if(!(!w||w.length!==1))return w[0]}),o.prop(S,"witness",()=>{if(d.witness)return d.witness;const w=A();if(w&&d.redeem&&d.redeem.output&&d.internalPubkey){const k=(0,i.tapleafHash)({output:d.redeem.output,version:S.redeemVersion}),T=(0,i.findScriptPath)(w,k);if(!T)return;const B=(0,i.tweakKey)(d.internalPubkey,w.hash);if(!B)return;const N=t.Buffer.concat([t.Buffer.from([S.redeemVersion|B.parity]),d.internalPubkey].concat(T));return[d.redeem.output,N]}if(d.signature)return[d.signature]}),m.validate){let w=t.Buffer.from([]);if(d.address){if(P&&P.bech32!==b().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(b().version!==f)throw new TypeError("Invalid address version");if(b().data.length!==32)throw new TypeError("Invalid address data");w=b().data}if(d.pubkey){if(w.length>0&&!w.equals(d.pubkey))throw new TypeError("Pubkey mismatch");w=d.pubkey}if(d.output){if(d.output.length!==34||d.output[0]!==u.OP_1||d.output[1]!==32)throw new TypeError("Output is invalid");if(w.length>0&&!w.equals(d.output.slice(2)))throw new TypeError("Pubkey mismatch");w=d.output.slice(2)}if(d.internalPubkey){const B=(0,i.tweakKey)(d.internalPubkey,S.hash);if(w.length>0&&!w.equals(B.x))throw new TypeError("Pubkey mismatch");w=B.x}if(w&&w.length&&!(0,s.getEccLib)().isXOnlyPoint(w))throw new TypeError("Invalid pubkey for p2tr");const k=A();if(d.hash&&k&&!d.hash.equals(k.hash))throw new TypeError("Hash mismatch");if(d.redeem&&d.redeem.output&&k){const B=(0,i.tapleafHash)({output:d.redeem.output,version:S.redeemVersion});if(!(0,i.findScriptPath)(k,B))throw new TypeError("Redeem script not in tree")}const T=E();if(d.redeem&&S.redeem){if(d.redeem.redeemVersion&&d.redeem.redeemVersion!==S.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(d.redeem.output){if(r.decompile(d.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(S.redeem.output&&!d.redeem.output.equals(S.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(d.redeem.witness&&S.redeem.witness&&!(0,n.stacksEqual)(d.redeem.witness,S.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(T&&T.length)if(T.length===1){if(d.signature&&!d.signature.equals(T[0]))throw new TypeError("Signature mismatch")}else{const B=T[T.length-1];if(B.length<33)throw new TypeError(`The control-block length is too small. Got ${B.length}, expected min 33.`);if((B.length-33)%32!==0)throw new TypeError(`The control-block length of ${B.length} is incorrect!`);const N=(B.length-33)/32;if(N>128)throw new TypeError(`The script path is too long. Got ${N}, expected max 128.`);const $=B.slice(1,33);if(d.internalPubkey&&!d.internalPubkey.equals($))throw new TypeError("Internal pubkey mismatch");if(!(0,s.getEccLib)().isXOnlyPoint($))throw new TypeError("Invalid internalPubkey for p2tr witness");const D=B[0]&n.TAPLEAF_VERSION_MASK,M=T[T.length-2],V=(0,i.tapleafHash)({output:M,version:D}),G=(0,i.rootHashFromPath)(B,V),Q=(0,i.tweakKey)($,G);if(!Q)throw new TypeError("Invalid outputKey for p2tr witness");if(w.length&&!w.equals(Q.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(Q.parity!==(B[0]&1))throw new Error("Incorrect parity")}}return Object.assign(S,d)}return oo.p2tr=p,oo}var L0;function Lh(){return L0||(L0=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.p2tr=t.p2wsh=t.p2wpkh=t.p2sh=t.p2pkh=t.p2pk=t.p2ms=t.embed=void 0;const e=ou;Object.defineProperty(t,"embed",{enumerable:!0,get:function(){return e.p2data}});const r=au;Object.defineProperty(t,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=cu;Object.defineProperty(t,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const s=uu;Object.defineProperty(t,"p2pkh",{enumerable:!0,get:function(){return s.p2pkh}});const i=fu;Object.defineProperty(t,"p2sh",{enumerable:!0,get:function(){return i.p2sh}});const o=lu;Object.defineProperty(t,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const a=du;Object.defineProperty(t,"p2wsh",{enumerable:!0,get:function(){return a.p2wsh}});const c=AT();Object.defineProperty(t,"p2tr",{enumerable:!0,get:function(){return c.p2tr}})}(nf)),nf}Object.defineProperty(Pe,"__esModule",{value:!0});Pe.signatureBlocksAction=Pe.checkInputForSig=Pe.pubkeyInScript=Pe.pubkeyPositionInScript=Pe.witnessStackToScriptWitness=Pe.isP2TR=Pe.isP2SHScript=Pe.isP2WSHScript=Pe.isP2WPKH=Pe.isP2PKH=Pe.isP2PK=Pe.isP2MS=void 0;const D0=_a,Eo=er(),Ka=Ta,xT=ls,ei=Lh();function ti(t){return e=>{try{return t({output:e}),!0}catch{return!1}}}Pe.isP2MS=ti(ei.p2ms);Pe.isP2PK=ti(ei.p2pk);Pe.isP2PKH=ti(ei.p2pkh);Pe.isP2WPKH=ti(ei.p2wpkh);Pe.isP2WSHScript=ti(ei.p2wsh);Pe.isP2SHScript=ti(ei.p2sh);Pe.isP2TR=ti(ei.p2tr);function kT(t){let e=Buffer.allocUnsafe(0);function r(o){e=Buffer.concat([e,Buffer.from(o)])}function n(o){const a=e.length,c=D0.encodingLength(o);e=Buffer.concat([e,Buffer.allocUnsafe(c)]),D0.encode(o,e,a)}function s(o){n(o.length),r(o)}function i(o){n(o.length),o.forEach(s)}return i(t),e}Pe.witnessStackToScriptWitness=kT;function rw(t,e){const r=(0,xT.hash160)(t),n=t.slice(1,33),s=Eo.decompile(e);if(s===null)throw new Error("Unknown script error");return s.findIndex(i=>typeof i=="number"?!1:i.equals(t)||i.equals(r)||i.equals(n))}Pe.pubkeyPositionInScript=rw;function TT(t,e){return rw(t,e)!==-1}Pe.pubkeyInScript=TT;function _T(t,e){return PT(t).some(n=>nw(n,Eo.signature.decode,e))}Pe.checkInputForSig=_T;function nw(t,e,r){const{hashType:n}=e(t),s=[];switch(n&Ka.Transaction.SIGHASH_ANYONECANPAY&&s.push("addInput"),n&31){case Ka.Transaction.SIGHASH_ALL:break;case Ka.Transaction.SIGHASH_SINGLE:case Ka.Transaction.SIGHASH_NONE:s.push("addOutput"),s.push("setInputSequence");break}return s.indexOf(r)===-1}Pe.signatureBlocksAction=nw;function PT(t){let e=[];if((t.partialSig||[]).length===0){if(!t.finalScriptSig&&!t.finalScriptWitness)return[];e=IT(t)}else e=t.partialSig;return e.map(r=>r.signature)}function IT(t){const e=t.finalScriptSig?Eo.decompile(t.finalScriptSig)||[]:[],r=t.finalScriptWitness?Eo.decompile(t.finalScriptWitness)||[]:[];return e.concat(r).filter(n=>Buffer.isBuffer(n)&&Eo.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(Le,"__esModule",{value:!0});Le.checkTaprootInputForSigs=Le.tapTreeFromList=Le.tapTreeToList=Le.tweakInternalPubKey=Le.checkTaprootOutputFields=Le.checkTaprootInputFields=Le.isTaprootOutput=Le.isTaprootInput=mo=Le.serializeTaprootSignature=Le.tapScriptFinalizer=Le.toXOnly=void 0;const Dh=Et,OT=Ta,hu=Pe,cs=jh,BT=Lh(),CT=Pe,$T=t=>t.length===32?t:t.slice(1,33);Le.toXOnly=$T;function RT(t,e,r){const n=JT(e,t,r);try{const i=YT(e,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,hu.witnessStackToScriptWitness)(i)}}catch(s){throw new Error(`Can not finalize taproot input #${t}: ${s}`)}}Le.tapScriptFinalizer=RT;function NT(t,e){const r=e?Buffer.from([e]):Buffer.from([]);return Buffer.concat([t,r])}var mo=Le.serializeTaprootSignature=NT;function uc(t){return t&&!!(t.tapInternalKey||t.tapMerkleRoot||t.tapLeafScript&&t.tapLeafScript.length||t.tapBip32Derivation&&t.tapBip32Derivation.length||t.witnessUtxo&&(0,hu.isP2TR)(t.witnessUtxo.script))}Le.isTaprootInput=uc;function fc(t,e){return t&&!!(t.tapInternalKey||t.tapTree||t.tapBip32Derivation&&t.tapBip32Derivation.length||e&&(0,hu.isP2TR)(e))}Le.isTaprootOutput=fc;function UT(t,e,r){WT(t,e,r),ZT(t,e,r)}Le.checkTaprootInputFields=UT;function MT(t,e,r){KT(t,e,r),FT(t,e)}Le.checkTaprootOutputFields=MT;function FT(t,e){if(!e.tapTree&&!e.tapInternalKey)return;const r=e.tapInternalKey||t.tapInternalKey,n=e.tapTree||t.tapTree;if(r){const{script:s}=t,i=jT(r,n);if(s&&!s.equals(i))throw new Error("Error adding output. Script or address missmatch.")}}function jT(t,e){const r=e&&sw(e.leaves),{output:n}=(0,BT.p2tr)({internalPubkey:t,scriptTree:r});return n}function LT(t,e){const r=e.tapInternalKey,n=r&&(0,cs.tweakKey)(r,e.tapMerkleRoot);if(!n)throw new Error(`Cannot tweak tap internal key for input #${t}. Public key: ${r&&r.toString("hex")}`);return n.x}Le.tweakInternalPubKey=LT;function DT(t){if(!(0,Dh.isTaptree)(t))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return pd(t)}Le.tapTreeToList=DT;function sw(t=[]){return t.length===1&&t[0].depth===0?{output:t[0].script,version:t[0].leafVersion}:GT(t)}Le.tapTreeFromList=sw;function HT(t,e){return VT(t).some(n=>(0,CT.signatureBlocksAction)(n,zT,e))}Le.checkTaprootInputForSigs=HT;function zT(t){return{signature:t.slice(0,64),hashType:t.slice(64)[0]||OT.Transaction.SIGHASH_DEFAULT}}function VT(t){const e=[];if(t.tapKeySig&&e.push(t.tapKeySig),t.tapScriptSig&&e.push(...t.tapScriptSig.map(r=>r.signature)),!e.length){const r=qT(t.finalScriptWitness);r&&e.push(r)}return e}function qT(t){if(!t)return;const e=t.slice(2);if(e.length===64||e.length===65)return e}function pd(t,e=[],r=0){if(r>cs.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return t?(0,Dh.isTapleaf)(t)?(e.push({depth:r,leafVersion:t.version||cs.LEAF_VERSION_TAPSCRIPT,script:t.output}),e):(t[0]&&pd(t[0],e,r+1),t[1]&&pd(t[1],e,r+1),e):[]}function GT(t){let e;for(const r of t)if(e=yd(r,e),!e)throw new Error("No room left to insert tapleaf in tree");return e}function yd(t,e,r=0){if(r>cs.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(t.depth===r)return e?void 0:{output:t.script,version:t.leafVersion};if((0,Dh.isTapleaf)(e))return;const n=yd(t,e&&e[0],r+1);if(n)return[n,e&&e[1]];const s=yd(t,e&&e[1],r+1);if(s)return[e&&e[0],s]}function WT(t,e,r){const n=uc(t)&&_i(e),s=_i(t)&&uc(e),i=t===e&&uc(e)&&_i(e);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function KT(t,e,r){const n=fc(t)&&_i(e),s=_i(t)&&fc(e),i=t===e&&fc(e)&&_i(e);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function ZT(t,e,r){if(e.tapMerkleRoot){const n=(e.tapLeafScript||[]).every(i=>uf(i,e.tapMerkleRoot)),s=(t.tapLeafScript||[]).every(i=>uf(i,e.tapMerkleRoot));if(!n||!s)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(t.tapMerkleRoot&&!(e.tapLeafScript||[]).every(s=>uf(s,t.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function uf(t,e){if(!e)return!0;const r=(0,cs.tapleafHash)({output:t.script,version:t.leafVersion});return(0,cs.rootHashFromPath)(t.controlBlock,r).equals(e)}function YT(t,e){const r=(0,cs.tapleafHash)({output:e.script,version:e.leafVersion});return(t.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>XT(e.script,n)).sort((n,s)=>s.positionInScript-n.positionInScript).map(n=>n.signature)}function XT(t,e){return Object.assign({positionInScript:(0,hu.pubkeyPositionInScript)(e.pubkey,t)},e)}function JT(t,e,r){if(!t.tapScriptSig||!t.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${e}. No tapleaf script signature provided.`);const n=(t.tapLeafScript||[]).sort((s,i)=>s.controlBlock.length-i.controlBlock.length).find(s=>QT(s,t.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${e}. Signature for tapleaf script not found.`);return n}function QT(t,e,r){const n=(0,cs.tapleafHash)({output:t.script,version:t.leafVersion});return(!r||r.equals(n))&&e.find(i=>i.leafHash.equals(n))!==void 0}function _i(t){return t&&!!(t.redeemScript||t.witnessScript||t.bip32Derivation&&t.bip32Derivation.length)}const nr={secretMismatch:"invalid secret",secretHashLenMismatch:"secret hash should be 32 bytes",pubkeyLenMismatch:"pubkey should be 32 bytes",zeroOrNegativeExpiry:"expiry should be greater than 0",htlcAddressGenerationFailed:"failed to generate htlc address",notFunded:"address not funded",noCounterpartySigs:"counterparty signatures are required",counterPartySigNotFound:t=>"counterparty signature not found for utxo "+t,invalidCounterpartySigForUTXO:t=>"invalid counterparty signature for utxo "+t,htlcNotExpired:t=>`HTLC not expired, need more ${t} blocks`,controlBlockGenerationFailed:"failed to generate control block",invalidLeaf:"invalid leaf"},Za=192;Ae.initEccLib(fr);let H0=class{constructor(e,r){this.signer=e,this.internalPubkey=g0(),this.network=q3(r)}address(e,r){const n=this.generateLeaves(e,r),{address:s}=Ae.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:n});if(!s)throw new Error(nr.htlcAddressGenerationFailed);return s}async _buildRawTx(e,r,n,s,i){const o=new Ae.Transaction;o.version=2;const a=this.address(e,n||"redeem"),c=await this.getProvider();let u=[];if(i&&i.length>0)for(const p of i){const d=await c.getTransaction(p);for(let m=0;m<d.vout.length;m++){const b=d.vout[m];b.scriptpubkey_address===a&&u.push({txid:d.txid,vout:m,value:b.value,status:{confirmed:!1}})}}else u=await c.getUTXOs(a);const f=u.reduce((p,d)=>p+d.value,0);if(f===0)throw new Error(`${a} ${nr.notFunded}`);for(let p=0;p<u.length;p++)o.addInput(Buffer.from(u[p].txid,"hex").reverse(),u[p].vout);if(s!=null&&s.vSize){const p=await c.getFeeRates(),d=Math.ceil(p.hourFee*s.vSize),m=f-d;return o.addOutput(Ae.address.toOutputScript(r,this.network),m),{tx:o,usedUtxos:u}}const l=(s==null?void 0:s.fee)??await c.suggestFee(a,f,xi.MEDIUM);return o.addOutput(Ae.address.toOutputScript(r,this.network),f-l),{tx:o,usedUtxos:u,fee:l,balance:f}}getOutputScript(e,r){return Ae.address.toOutputScript(this.address(e,r||"redeem"),this.network)}async initiate(e,r){const n=await this.getProvider(),s=await this.signer.getAddress();let i,o;Y.isOrder(e)?(i=e.destination_swap.swap_id,o=Number(e.destination_swap.amount)):(i=e.to,o=Number(e.amount)),r===void 0&&(r=await n.suggestFee(s,o,xi.MEDIUM));const a=await this.signer.send(i,o,r);return g.Ok(a)}async generateRedeemSACP(e,r,n){const{tx:s,usedUtxos:i}=await this._buildRawTx(e,e.destination_swap.delegate,"redeem",{fee:n}),o=this.getOutputScript(e,"redeem"),a=Ae.Transaction.SIGHASH_SINGLE|Ae.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(1,e),u=i.map(l=>l.value),f=no(o,i.length);for(let l=0;l<s.ins.length;l++){const p=s.hashForWitnessV1(l,f,u,a,c),d=await this.signer.signSchnorr(p);s.setWitness(l,[mo(d,a),Buffer.from(r,"hex"),this.redeemLeaf(g.trim0x(e.destination_swap.secret_hash),je(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}return s.toHex()}async generateInstantRefundSACP(e){const r=this.getOutputScript(e,"instantRefund"),{tx:n,usedUtxos:s,fee:i}=await this._buildRawTx(e,e.destination_swap.delegate,"instantRefund",{fee:0});n.outs=[];const o=Math.max(...s.map(l=>l.value));s.forEach(({value:l})=>{n.addOutput(r,l-(l===o?i??0:0))});const a=Ae.Transaction.SIGHASH_SINGLE|Ae.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(2,e),u=s.map(l=>l.value),f=no(r,s.length);for(let l=0;l<n.ins.length;l++){const p=n.hashForWitnessV1(l,f,u,a,c),d=await this.signer.signSchnorr(p);n.setWitness(l,[mo(d,a),mo(d,a),this.instantRefundLeaf(je(e.source_swap.initiator),je(e.destination_swap.delegate)),await this.generateControlBlockFor(2,e)])}return n.toHex()}async generateInstantRefundSACPWithHash(e){const r=[],n=Ae.Transaction.SIGHASH_SINGLE|Ae.Transaction.SIGHASH_ANYONECANPAY;for(let s=0;s<e.length;s++){const i=Buffer.from(e[s],"hex"),o=await this.signer.signSchnorr(i);r.push(mo(o,n).toString("hex"))}return g.Ok(r)}async instantRefund(e,r,n){p0(r.length>0,nr.noCounterpartySigs);const{tx:s,usedUtxos:i}=await this._buildRawTx(e,await this.signer.getAddress(),"instantRefund",{fee:n});for(const p of i)if(!r.find(d=>d.utxo===p.txid))throw new Error(nr.counterPartySigNotFound(p.txid));const o=this.getOutputScript(e,"instantRefund"),a=Ae.Transaction.SIGHASH_DEFAULT,c=this.leafHash(2,e),u=i.map(p=>p.value),f=no(o,i.length);for(let p=0;p<s.ins.length;p++){const d=s.hashForWitnessV1(p,f,u,a,c);if(!fr.verifySchnorr(d,Buffer.from(je(e.destination_swap.delegate),"hex"),Buffer.from(r[p].sig,"hex")))throw new Error(nr.invalidCounterpartySigForUTXO(r[p].utxo));const m=await this.signer.signSchnorr(d),b=Buffer.from(s.ins[p].hash).reverse().toString("hex"),E=r.find(A=>A.utxo===b);if(!E)throw new Error(nr.counterPartySigNotFound(b));s.setWitness(p,[Buffer.from(E.sig,"hex"),m,this.instantRefundLeaf(je(e.source_swap.initiator),je(e.destination_swap.delegate)),await this.generateControlBlockFor(2,e)])}return await(await this.getProvider()).broadcast(s.toHex())}async redeem(e,r,n){const s=await this.getRedeemHex(e,r,n);if(!s.ok)return g.Err(s.error);const o=await(await this.getProvider()).broadcast(s.val);return g.Ok(o)}async getRedeemHex(e,r,n){p0(Ae.crypto.sha256(Buffer.from(r,"hex")).toString("hex")===g.trim0x(e.destination_swap.secret_hash),nr.secretMismatch);const o=(Y.isBitcoin(e.source_swap.chain)?e.source_swap.redeemer:e.destination_swap.redeemer)??await this.signer.getAddress(),{tx:a,usedUtxos:c}=await this._buildRawTx(e,o,"redeem",{fee:0},n),u=this.leafHash(1,e),f=c.map(m=>m.value),l=no(this.getOutputScript(e,"redeem"),c.length),p=Ae.Transaction.SIGHASH_DEFAULT;for(let m=0;m<a.ins.length;m++){const b=a.hashForWitnessV1(m,l,f,p,u),E=await this.signer.signSchnorr(b);a.setWitness(m,[E,Buffer.from(r,"hex"),this.redeemLeaf(g.trim0x(e.destination_swap.secret_hash),je(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}const{tx:d}=await this._buildRawTx(e,o,"redeem",{vSize:a.virtualSize()},n);for(let m=0;m<d.ins.length;m++){const b=d.hashForWitnessV1(m,l,f,p,u),E=await this.signer.signSchnorr(b);d.setWitness(m,[E,Buffer.from(r,"hex"),this.redeemLeaf(g.trim0x(e.destination_swap.secret_hash),je(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}return g.Ok(d.toHex())}async refund(e,r){const{tx:n,usedUtxos:s}=await this._buildRawTx(e,e.source_swap.delegate??await this.signer.getAddress(),"refund",{fee:r}),[i,o]=await this.canRefund(e,s);if(!i)throw new Error(nr.htlcNotExpired(o));const a=this.leafHash(0,e),c=s.map(d=>d.value),u=no(this.getOutputScript(e,"refund"),s.length),f=Ae.Transaction.SIGHASH_DEFAULT;for(let d=0;d<n.ins.length;d++){n.ins[d].sequence=e.source_swap.timelock;const m=n.hashForWitnessV1(d,u,c,f,a),b=await this.signer.signSchnorr(m);n.setWitness(d,[b,this.refundLeaf(e.source_swap.timelock,je(e.source_swap.initiator)),await this.generateControlBlockFor(0,e)])}const p=await(await this.getProvider()).broadcast(n.toHex());return g.Ok(p)}async canRefund(e,r){const s=await(await this.getProvider()).getLatestTip();for(const i of r){let o=0;if(i.status.confirmed&&i.status.block_height+e.source_swap.timelock>s?o=i.status.block_height+e.source_swap.timelock-s+1:i.status.confirmed||(o=e.source_swap.timelock+1),o>0)return[!1,o]}return[!0,0]}async generateControlBlockFor(e,r){let n,s;switch(e){case 1:n=this.redeemLeaf(g.trim0x(r.destination_swap.secret_hash),je(r.destination_swap.delegate)),s=this.generateLeaves(r,"redeem");break;case 0:n=this.refundLeaf(r.source_swap.timelock,je(r.source_swap.initiator)),s=this.generateLeaves(r,"refund");break;case 2:n=this.instantRefundLeaf(je(r.source_swap.initiator),je(r.destination_swap.delegate)),s=this.generateLeaves(r,"instantRefund");break;default:throw new Error(nr.controlBlockGenerationFailed)}const i=await this.signer.getNetwork(),o=Ae.payments.p2tr({internalPubkey:g0(),network:i,scriptTree:s,redeem:{output:n,redeemVersion:Za}});if(!o.witness)throw new Error(nr.controlBlockGenerationFailed);return o.witness[o.witness.length-1]}leafHash(e,r){let n;switch(e){case 1:n=this.redeemLeaf(g.trim0x(r.destination_swap.secret_hash),je(r.destination_swap.delegate));break;case 0:n=this.refundLeaf(r.source_swap.timelock,je(r.source_swap.initiator));break;case 2:n=this.instantRefundLeaf(je(r.source_swap.initiator),je(r.destination_swap.redeemer));break;default:throw new Error(nr.invalidLeaf)}return Ae.crypto.taggedHash("TapLeaf",j3(n))}refundLeaf(e,r){return Ae.script.fromASM(`
|
|
55
55
|
${Ae.script.number.encode(e).toString("hex")}
|
|
56
56
|
OP_CHECKSEQUENCEVERIFY
|
|
57
57
|
OP_DROP
|
|
@@ -70,7 +70,7 @@ ${_5(d)}`),super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessa
|
|
|
70
70
|
OP_CHECKSIGADD
|
|
71
71
|
OP_2
|
|
72
72
|
OP_NUMEQUAL
|
|
73
|
-
`.trim().replace(/\s+/g," "))}generateLeaves(e,r){let n,s,i;switch(r){case"redeem":n=e.destination_swap,s=n.delegate,i=n.delegate;break;case"refund":n=e.source_swap,s=n.delegate,i=n.delegate;break;case"instantRefund":n=e.source_swap,s=n.redeemer,i=n.redeemer;break;default:throw new Error("Invalid leaf generation type")}return[{version:Za,output:this.redeemLeaf(n.secret_hash,je(s))},[{version:Za,output:this.refundLeaf(n.timelock,je(n.initiator))},{version:Za,output:this.instantRefundLeaf(je(n.initiator),je(i))}]]}generateMerkleProofFor(e,r){const n=this.leafHash(1,r),s=this.leafHash(2,r),i=this.leafHash(0,r);switch(e){case 1:{const o=D3(i,s);return[Ae.crypto.taggedHash("TapBranch",Buffer.concat(o))]}case 0:return[s,n];case 2:return[i,n];default:throw new Error(nr.invalidLeaf)}}getProvider(){return this.signer.getProvider()}get getPublicKey(){return this.signer.getPublicKey()}get htlcActorAddress(){return this.signer.getPublicKey()}};class iw{constructor(e){this.quoteUrl=new g.Url(e)}async getQuoteFromAssets({fromAsset:e,toAsset:r,amount:n,isExactOut:s=!1,options:i}){const o=X.ChainAsset.from(e),a=X.ChainAsset.from(r);return this.getQuote(o,a,n,s,i)}async getQuote(e,r,n,s=!1,i){try{const o={from:X.ChainAsset.from(e).toString(),to:X.ChainAsset.from(r).toString(),...s?{to_amount:n.toString()}:{from_amount:n.toString()},...(i==null?void 0:i.affiliateFee)!==void 0&&{affiliate_fee:i.affiliateFee.toString()}},a=this.quoteUrl.endpoint("/v2/quote").addSearchParams(o),c=await g.Fetcher.get(a,{retryCount:0,...i==null?void 0:i.request});return c.error?g.Err(c.error):c.result?g.Ok(c.result):g.Err("GetQuote: Unexpected error, result is undefined")}catch(o){return g.Err("GetQuote:",String(o))}}async getStrategies(){try{const e=await g.Fetcher.get(this.quoteUrl.endpoint("/strategies"));if(e.error)return g.Err(e.error);if(!e.result)return g.Err("GetStrategies: Unexpected error, result is undefined");const r={};for(const n of Object.values(e.result)){const s=P1(n.source_chain,n.source_asset.asset,n.dest_chain,n.dest_asset.asset);r[s]={id:n.id,minAmount:n.min_amount,maxAmount:n.max_amount,fee:n.fee,fixed_fee:Number(n.fixed_fee)}}return g.Ok(r)}catch(e){return g.Err("GetStrategies:",String(e))}}}class Mi extends g.EventBroker{get isInitialized(){return!!this.digestKey}constructor(e,r){super(),this.digestKey=e,this.walletClient=r}static fromDigestKey(e){return new Mi(g.trim0x(e))}static fromWalletClient(e){return new Mi(void 0,e)}async initialize(){if(this.digestKey)return g.Ok("Already initialized");const e=await this.deriveDigestKeyFromWalletClient();return e.error?g.Err(e.error):(this.emit("initialized",!0),g.Ok("Initialized"))}async deriveDigestKeyFromWalletClient(){if(!this.walletClient)return g.Err("No walletClient found");if(!this.walletClient.account)return g.Err("No account found");try{const e=await this.walletClient.signTypedData({account:this.walletClient.account,types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"}],Data:[{name:"Message",type:"string"},{name:"Version",type:"string"},{name:"Nonce",type:"uint256"}]},domain:{name:"GARDEN FINANCE",version:"1"},primaryType:"Data",message:{Message:"Initialize your account",Version:"1.0.2",Nonce:1n}});return this.digestKey=g.trim0x(ho(e)),this.emit("initialized",!0),g.Ok(this.digestKey)}catch(e){return g.Err("Failed to initialize: "+e)}}async getDigestKey(){if(!this.digestKey&&!this.walletClient)return g.Err("No private key or wallet client found");if(!this.digestKey&&this.walletClient){const e=await this.deriveDigestKeyFromWalletClient();if(e.error)return g.Err(e.error)}return this.digestKey?g.Ok(this.digestKey):g.Err("No private key found")}async generateSecret(e){const r=await this.signMessage(e);if(!r.ok)return g.Err(r.error);const n=ho(g.with0x(r.val)),s=ho(n);return g.Ok({secret:n,secretHash:s})}async signMessage(e){if(!this.digestKey){const u=await this.getDigestKey();if(!u.ok)return g.Err(u.error);this.digestKey=u.val}const r=rc.ECPairFactory(fr),n="Garden.fi"+e.toString(),s=Buffer.from(n,"utf8"),i=ho(s),o=Buffer.from(g.trim0x(this.digestKey),"hex");if(o.length!==32)return g.Err("Invalid private key length. Expected 32 bytes.");const c=r.fromPrivateKey(o).sign(Buffer.from(g.trim0x(i),"hex"));return g.Ok(c.toString("hex"))}}const e_=[{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"}],t_={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},r_={block:eE({format(t){var r;return{transactions:(r=t.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const s=zc(n);return s.typeHex==="0x7e"&&(s.isSystemTx=n.isSystemTx,s.mint=n.mint?ut(n.mint):void 0,s.sourceHash=n.sourceHash,s.type="deposit"),s}),stateRoot:t.stateRoot}}}),transaction:J5({format(t){const e={};return t.type==="0x7e"&&(e.isSystemTx=t.isSystemTx,e.mint=t.mint?ut(t.mint):void 0,e.sourceHash=t.sourceHash,e.type="deposit"),e}}),transactionReceipt:pS({format(t){return{l1GasPrice:t.l1GasPrice?ut(t.l1GasPrice):null,l1GasUsed:t.l1GasUsed?ut(t.l1GasUsed):null,l1Fee:t.l1Fee?ut(t.l1Fee):null,l1FeeScalar:t.l1FeeScalar?Number(t.l1FeeScalar):null}}})};function n_(t,e){return o_(t)?i_(t):JS(t,e)}const s_={transaction:n_};function i_(t){a_(t);const{sourceHash:e,data:r,from:n,gas:s,isSystemTx:i,mint:o,to:a,value:c}=t,u=[e,n,a??"0x",o?Bt(o):"0x",c?Bt(c):"0x",s?Bt(s):"0x",i?"0x1":"0x",r??"0x"];return $r(["0x7e",as(u)])}function o_(t){return t.type==="deposit"||typeof t.sourceHash<"u"}function a_(t){const{from:e,to:r}=t;if(e&&!at(e))throw new $t({address:e});if(r&&!at(r))throw new $t({address:r})}const Fi={blockTime:2e3,contracts:t_,formatters:r_,serializers:s_},c_=yt({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:250,rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),u_=yt({id:421614,name:"Arbitrum Sepolia",blockTime:250,nativeCurrency:{name:"Arbitrum Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://sepolia.arbiscan.io",apiUrl:"https://api-sepolia.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:81930}},testnet:!0}),ao=1,ow=yt({...Fi,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:{...Fi.contracts,disputeGameFactory:{[ao]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[ao]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[ao]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[ao]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:ao});({...ow});const co=11155111,aw=yt({...Fi,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:{...Fi.contracts,disputeGameFactory:{[co]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[co]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[co]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[co]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:co});({...aw});const f_=yt({id:80094,name:"Berachain",blockTime:2e3,nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},ensRegistry:{address:"0x5b22280886a2f5e09a49bea7e320eab0e5320e28",blockCreated:877007},ensUniversalResolver:{address:"0x4D41762915F83c76EcaF6776d9b08076aA32b492",blockCreated:9310021}},rpcUrls:{default:{http:["https://rpc.berachain.com"]}},blockExplorers:{default:{name:"Berascan",url:"https://berascan.com"}},ensTlds:[".bera"],testnet:!1}),l_=yt({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}),d_=yt({id:56,name:"BNB Smart Chain",blockTime:750,nativeCurrency:{decimals:18,name:"BNB",symbol:"BNB"},rpcUrls:{default:{http:["https://56.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"BscScan",url:"https://bscscan.com",apiUrl:"https://api.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:15921452}}}),h_=yt({id:97,name:"BNB Smart Chain Testnet",nativeCurrency:{decimals:18,name:"BNB",symbol:"tBNB"},rpcUrls:{default:{http:["https://data-seed-prebsc-1-s1.bnbchain.org:8545"]}},blockExplorers:{default:{name:"BscScan",url:"https://testnet.bscscan.com",apiUrl:"https://api-testnet.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:17422483}},testnet:!0}),p_=yt({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}),y_=yt({id:1116,name:"Core Dao",nativeCurrency:{decimals:18,name:"Core",symbol:"CORE"},rpcUrls:{default:{http:["https://rpc.coredao.org"]}},blockExplorers:{default:{name:"CoreDao",url:"https://scan.coredao.org"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:11907934}},testnet:!1}),m_=1,b_=yt({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:m_}),g_=yt({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:12e3,rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:23085558},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),w_=yt({id:10143,name:"Monad Testnet",blockTime:400,nativeCurrency:{name:"Testnet MON Token",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://testnet-rpc.monad.xyz"]}},blockExplorers:{default:{name:"Monad Testnet explorer",url:"https://testnet.monadexplorer.com"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:251449}},testnet:!0}),v_=yt({id:11155111,name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.drpc.org"]}},blockExplorers:{default:{name:"Etherscan",url:"https://sepolia.etherscan.io",apiUrl:"https://api-sepolia.etherscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:751532},ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:8928790}},testnet:!0}),Ya=1,E_=yt({...Fi,id:130,name:"Unichain",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:1e3,rpcUrls:{default:{http:["https://mainnet.unichain.org/"]}},blockExplorers:{default:{name:"Uniscan",url:"https://uniscan.xyz",apiUrl:"https://api.uniscan.xyz/api"}},contracts:{...Fi.contracts,multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:0},disputeGameFactory:{[Ya]:{address:"0x2F12d621a16e2d3285929C9996f478508951dFe4"}},portal:{[Ya]:{address:"0x0bd48f6B86a26D3a217d0Fa6FfE2B491B956A7a2"}},l1StandardBridge:{[Ya]:{address:"0x81014F44b0a345033bB2b3B21C7a1A308B35fEeA"}}},sourceId:Ya}),S_={...v_,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},cw={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/"]}}},uw={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"]}}},fw={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"]}}},du={ethereum:g_,arbitrum:c_,ethereum_sepolia:S_,arbitrum_sepolia:u_,ethereum_localnet:X.EthereumLocalnet,arbitrum_localnet:X.ArbitrumLocalnet,base_sepolia:aw,base:ow,bera_testnet:l_,citrea_testnet:p_,core:y_,bera:f_,monad_testnet:w_,hyperliquid_testnet:uw,hyperliquid:fw,unichain:E_,corn:b_,botanix:cw,bnbchain:d_,bnbchain_testnet:h_},lw=t=>{for(const[e,r]of Object.entries(du))if(r.id===t)return e;return null},yd=async(t,e)=>{var s,i,o;const r=du[t],n=await e.getChainId();if(r)try{if(r.id===n)return g.Ok({message:"Already on the network",walletClient:e});await e.switchChain({id:r.id});const a=Ku({account:e.account,chain:r,transport:l0(e.transport)});return g.Ok({message:"Switched chain",walletClient:a})}catch(a){if(A_(a))if(a.code===4902||a.code===-32603)try{await e.addChain({chain:r});const c=Ku({account:e.account,chain:r,transport:l0(e.transport)});return g.Ok({message:"Added network",walletClient:c})}catch{return g.Err("Failed to add network")}else if((i=(s=a.body)==null?void 0:s.method)!=null&&i.includes("wallet_switchEthereumChain")||(o=a.message)!=null&&o.includes("wallet_switchEthereumChain")){const c=Ku({account:e.account,chain:r,transport:k1()});return g.Ok({message:"Added network",walletClient:c})}else return g.Err("Failed to switch network");else return g.Err("Failed to switch network")}else return g.Err("Chain not supported")},A_=t=>typeof t=="object"&&t!=null&&("code"in t||"message"in t||"body"in t),x_=[{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 dw{constructor(e,r,n){this.url=new g.Url(e.toString()),this.auth=n,this.wallet=r}get htlcActorAddress(){if(!this.wallet.account)throw new Error("No account found");return this.wallet.account.address}async initiate(e){if(X.isEvmOrderResponse(e))return this.initiateWithCreateOrderResponse(e);if(!this.wallet.account)return g.Err("No account found");if(this.wallet.account.address.toLowerCase()!==e.source_swap.initiator.toLowerCase())return g.Err("Account address and order initiator mismatch");if(!X.isEVM(e.source_swap.chain))return g.Err("Source chain is not an EVM chain");const r=e.source_swap.chain,n=await yd(r,this.wallet);if(!n.ok)return g.Err(n.error);if(this.wallet=n.val.walletClient,!this.wallet.account)return g.Err("No account found");const{source_swap:s}=e;if(!s.amount||!s.redeemer||!s.timelock||!s.secret_hash)return g.Err("Invalid order");const i=g.with0x(s.secret_hash),o=BigInt(s.timelock),a=g.with0x(s.redeemer),c=BigInt(s.amount),u=await Ph(e.source_swap.asset,this.url);if(!u.ok)return g.Err(u.error);const{htlcAddress:f,tokenAddress:l}=u.val,p=X.ChainAsset.fromString(e.source_swap.asset);return X.isEvmNativeToken(p.chain,p.symbol)?this._initiateOnNativeHTLC(i,o,c,a,f):this._initiateOnErc20HTLC(i,o,c,a,f,l,e.order_id)}async _initiateOnNativeHTLC(e,r,n,s,i){if(!this.wallet.account)return g.Err("No account found");try{const a=await qp({address:g.with0x(i),abi:x_,client:this.wallet}).write.initiate([s,r,n,e],{account:this.wallet.account,chain:this.wallet.chain,value:n});return g.Ok(a)}catch(o){return g.Err("Failed to initiate on native HTLC",String(o))}}async _initiateOnErc20HTLC(e,r,n,s,i,o,a){if(!this.wallet.account)return g.Err("No account found");try{const c=await this.auth.getAuthHeaders();if(!c.ok)return g.Err(c.error);const u=qp({address:g.with0x(i),abi:e_,client:this.wallet}),f=await g.checkAllowanceAndApprove(Number(n),o,i,this.wallet);if(!f.ok)return g.Err(f.error);const l=await u.read.eip712Domain(),p=await this.wallet.signTypedData({account:this.wallet.account,domain:{name:l[1],version:l[2],chainId:Number(l[3]),verifyingContract:l[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:s,timelock:r,amount:n,secretHash:e}}),d={...c.val,"Content-Type":"application/json"},m=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(a).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:p}),headers:d});if(m.error)return g.Err(m.error);const b=await g.waitForTransactionReceipt(this.wallet,m.result);return b.val&&b.val.status==="success"?g.Ok(m.result?m.result:"Initiate hash not found"):g.Err("Init failed: Transaction receipt not successful")}catch(c){return console.log("init error :",c),g.Err(String(c))}}async initiateWithCreateOrderResponse(e){const r=e.initiate_transaction.chain_id,n=lw(r);if(!n)return g.Err(`Unsupported chain ID: ${r}`);const s=await yd(n,this.wallet);if(!s.ok)return g.Err(s.error);if(this.wallet=s.val.walletClient,!this.wallet.account)return g.Err("No account found");try{if(e.typed_data===null){const u=e.initiate_transaction;if(!u)return g.Err("No initiate_transaction found for native initiate");const f=await this.wallet.sendTransaction({account:this.wallet.account,to:g.with0x(u.to),value:BigInt(u.value),data:g.with0x(u.data),gas:BigInt(u.gas_limit),chain:this.wallet.chain}),l=await g.waitForTransactionReceipt(this.wallet,f);return l.val&&l.val.status!=="success"?g.Err("Native initiate transaction failed"):g.Ok(f)}if(e.approval_transaction){const u=await this.executeApprovalTransaction(e);if(u.error)return g.Err(`Approval failed: ${u.error}`);console.log("Approval transaction completed:",u.val)}const{typed_data:i}=e,o=await this.wallet.signTypedData({account:this.wallet.account,domain:i.domain,types:i.types,primaryType:i.primaryType,message:i.message}),a={...(await this.auth.getAuthHeaders()).val,"Content-Type":"application/json"},c=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:o}),headers:a});return c.error?g.Err(c.error):c.result?g.Ok(c.result):g.Err("Initiate failed: Result is undefined")}catch(i){return console.error("initiateWithCreateOrderResponse error:",i),g.Err("Failed to initiate: "+String(i))}}async executeApprovalTransaction(e){if(!this.wallet.account)return g.Err("No account found");if(!e.approval_transaction)return g.Ok("No approval transaction required");try{const r=e.approval_transaction,n=await this.wallet.sendTransaction({account:this.wallet.account,to:g.with0x(r.to),value:BigInt(r.value),data:g.with0x(r.data),gas:BigInt(r.gas_limit),chain:this.wallet.chain}),s=await g.waitForTransactionReceipt(this.wallet,n);return s.val&&s.val.status!=="success"?g.Err("Approval transaction failed"):g.Ok(n)}catch(r){return console.error("executeApprovalTransaction error:",r),g.Err("Failed to execute approval: "+((r==null?void 0:r.message)||String(r)))}}async redeem(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return g.Err(n.error);const s=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:g.trim0x(r)}),headers:{...n.val,"Content-Type":"application/json"}});if(s.error)return g.Err(s.error);const i=du[e.destination_swap.chain],a=await v3({chain:i,transport:k1()}).waitForTransactionReceipt({hash:s.result,confirmations:1,timeout:3e5});return a&&a.status==="success"?g.Ok(s.result?s.result:"Redeem hash not found"):g.Err("Redeem failed: Transaction receipt not successful")}catch(n){return g.Err(String(n))}}async refund(){return g.Err("Refund not supported")}}const hw=[{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"}]}],pw=async(t,e,r,n,s)=>{try{const i=await So(t.address,e,r,s);if(!i.ok)return g.Err(i.error);if(i.val>=n)return g.Ok("Allowance already approved");const a=Je.cairo.uint256(BigInt(n)),c=await t.execute([{contractAddress:g.with0x(e),entrypoint:"approve",calldata:[g.with0x(r),a.low,a.high]}]);await s.waitForTransaction(c.transaction_hash,{retryInterval:3e3,successStates:[Je.TransactionExecutionStatus.SUCCEEDED]}),await g.sleep(2e3);for(let u=0;u<20;u++){const f=await So(t.address,e,r,s);if(!f.ok)return g.Err(f.error);if(f.val>=n)return g.Ok(c.transaction_hash);await g.sleep(2e3);let l=0n;for(let p=0;p<20;p++){const d=await So(t.address,e,r,s);if(!d.ok)return g.Err(d.error);if(l=d.val,l>=n)break;await g.sleep(2e3)}return l<n?g.Err("Allowance not approved"):g.Ok(c.transaction_hash)}return g.Err("Allowance not approved after transaction.")}catch(i){return g.Err(`Failed to check or approve allowance: ${i instanceof Error?i.message:String(i)}`)}},So=async(t,e,r,n)=>{try{const i=await new Je.Contract(hw,g.with0x(e),n).call("allowance",[g.with0x(t),g.with0x(r)]);return g.Ok(BigInt((i==null?void 0:i.toString())||"0"))}catch(s){return g.Err(`Failed to check allowance: ${s instanceof Error?s.message:String(s)}`)}},yw=async(t,e,r,n,s)=>{const i=await So(t,e,r,n);return i.ok?g.Ok(i.val>=s):g.Err(i.error)},mw=[{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"}]}],k_={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 bw{constructor(e,r,n,s,i){this.url=e instanceof g.Url?e:new g.Url(e),this.account=r,this.starknetProvider=new Je.RpcProvider({nodeUrl:i||Qo[n].nodeUrl}),this.chainId=Qo[n].chainId,this.auth=s}get htlcActorAddress(){if(!this.account.address)throw new Error("No account found");return this.account.address}async initiate(e){if(X.isStarknetOrderResponse(e))return this.initiateWithCreateOrderResponse(e);if(!this.account.address)return g.Err("No account address");const{source_swap:r}=e,{redeemer:n,amount:s}=r;if(!s||!n||!r.secret_hash||!r.timelock)return g.Err("Invalid order");try{const i=new Je.Contract(mw,e.source_swap.asset,this.account),o=await(i==null?void 0:i.token()),a=Je.num.toHex(o),c=await yw(this.account.address,a,r.asset,this.starknetProvider,BigInt(r.amount));return c.error?g.Err(c.error):c.val?this.initiateRelay(e):this.approveAndInitiate(a,e)}catch(i){return g.Err(String(i))}}async approveAndInitiate(e,r){const{source_swap:n}=r,{redeemer:s,amount:i}=n,{secret_hash:o,timelock:a}=n,c=n.asset;try{const u=Je.cairo.uint256(BigInt(i)),f={contractAddress:g.with0x(e),entrypoint:"approve",calldata:[c,u.low,u.high]},l=Je.cairo.uint256(i),p={contractAddress:g.with0x(c),entrypoint:"initiate",calldata:[s,a.toString(),l.low.toString(),l.high.toString(),...g.hexToU32Array(o)]},d=await this.account.execute([f,p]);return await this.starknetProvider.waitForTransaction(d.transaction_hash,{retryInterval:2e3,successStates:[Je.TransactionExecutionStatus.SUCCEEDED]}),g.Ok(d.transaction_hash)}catch(u){return g.Err(`Failed to approve and initiate: ${String(u)}`)}}async initiateRelay(e){const{source_swap:r}=e,{redeemer:n,amount:s}=r;if(!r.secret_hash)return g.Err("Invalid order: secret_hash is undefined");const i=g.with0x(r.secret_hash),a={domain:{name:"HTLC",version:Je.shortString.encodeShortString("1"),chainId:this.chainId,revision:Je.TypedDataRevision.ACTIVE},primaryType:"Initiate",types:k_,message:{redeemer:n,amount:Je.cairo.uint256(s),timelock:e.source_swap.timelock,secretHash:g.hexToU32Array(i)}};try{const c=await this.account.signMessage(a),u=h0(c);if(u.error)return g.Err(u.error);const f=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:u.val}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return f.error?g.Err(f.error):f.result?g.Ok(f.result):g.Err("Init: No result found")}catch(c){return g.Err(`Failed to initiate relayer: ${String(c)}`)}}async redeem(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return g.Err(n.error);const s=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:g.trim0x(r)}),headers:{...n.val,"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return s.error?g.Err(s.error):s.result?g.Ok(s.result):g.Err("Redeem: No result found")}catch(n){return g.Err(String(n))}}async executeApprovalTransaction(e){if(!this.account.address)return g.Err("No account address");if(!e.approval_transaction)return g.Ok("No approval transaction required");try{const r=e.approval_transaction,n=await this.account.execute([{contractAddress:g.with0x(r.to),entrypoint:g.with0x(r.selector),calldata:r.calldata}]);return await this.starknetProvider.waitForTransaction(n.transaction_hash,{retryInterval:2e3,successStates:[Je.TransactionExecutionStatus.SUCCEEDED]}),g.Ok(n.transaction_hash)}catch(r){return console.error("executeApprovalTransaction error:",r),g.Err("Failed to execute approval: "+(r instanceof Error&&(r==null?void 0:r.message)||String(r)))}}async initiateWithCreateOrderResponse(e){const r=await this.auth.getAuthHeaders();if(!r.ok)return g.Err(r.error);if(!this.account.address)return g.Err("No account address");const n=await this.executeApprovalTransaction(e);if(n.error)return g.Err(n.error);const{typed_data:s}=e;if(s===null){const c=e.initiate_transaction;if(!c)return g.Err("No initiate_transaction found for native initiate");const u=await this.account.execute([{contractAddress:g.with0x(c.to),entrypoint:g.with0x(c.selector),calldata:c.calldata}]);return await this.starknetProvider.waitForTransaction(u.transaction_hash,{retryInterval:2e3,successStates:[Je.TransactionExecutionStatus.SUCCEEDED]}),g.Ok(u.transaction_hash)}const i=await this.account.signMessage(s),o=h0(i);if(o.error)return g.Err(o.error);const a=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:Array.isArray(o.val)?o.val.join(","):o.val}),headers:{...r.val,"Content-Type":"application/json"}});return a.error?g.Err(a.error):g.Ok(a.result)}async refund(){return g.Err("Refund is taken care of by the relayer")}}const T_="2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC",__={name:"solana_spl_swaps",version:"0.4.0",spec:"0.1.0",description:"Created with Anchor"},P_=[{name:"initiate",docs:["Initiates the atomic swap. Funds are transferred from the initiator to the token vault.","As such, the initiator's signature is required for this instruction.","A sponsor may be involved, who pays PDA rent and transaction fees in SOL, allowing for the","initiator to participate without holding SOL. As such, the sponsor must also sign this transaction.","`swap_amount` represents the quantity of tokens to be transferred through this atomic swap","in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals',"must be provided as 1,000,000.","`expires_in_slots` represents the number of slots after which (non-instant) refunds are allowed.","`destination_data` can hold optional information regarding the destination chain","in the atomic swap, to be emitted in the logs as-is."],discriminator:[5,63,123,113,153,75,148,14],accounts:[{name:"identity_pda",docs:["the token transfers of the `token_vault` PDA.","This PDA will be created during the first most invocation of the `initiate()` function","using the `init_if_needed` attribute, and be reused for all succeeding instructions."],writable:!0,pda:{seeds:[]}},{name:"swap_data",docs:["A PDA that maintains the on-chain state of the atomic swap throughout its lifecycle.","The choice of seeds ensure that any swap with equal `initiator` and","`secret_hash` wont be created until an existing one completes.","This PDA will be deleted upon completion of the swap."],writable:!0,pda:{seeds:[{kind:"account",path:"initiator"},{kind:"arg",path:"secret_hash"}]}},{name:"token_vault",docs:["A permanent PDA that is controlled by the program through the `identity_pda`, as implied",'by the value of the `authority` field below. As such, it serves as the "vault" by escrowing tokens',"of type `mint` for the atomic swap.","It is intended to be reused for all swaps involving the same mint.","Just like `identity_pda`, it will be created during the first most invocation of `initiate()`","of every distinct mint using the `init_if_needed` attribute."],writable:!0,pda:{seeds:[{kind:"account",path:"mint"}]}},{name:"initiator",docs:["The initiator of the atomic swap. They must sign this transaction."],signer:!0},{name:"initiator_token_account",docs:["The token account of the initiator"],writable:!0},{name:"mint",docs:["The mint of the tokens involved in this swap. As this is a parameter, this program can thus be reused","for atomic swaps with different mints."]},{name:"sponsor",docs:["Any entity that pays the PDA rent.","Upon completion of the swap, the PDA rent refund resulting from the","deletion of `swap_data` will be refunded to this address."],writable:!0,signer:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},{name:"system_program",address:"11111111111111111111111111111111"}],args:[{name:"expires_in_slots",type:"u64"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}},{name:"swap_amount",type:"u64"},{name:"destination_data",type:{option:"bytes"}}]},{name:"instant_refund",docs:["Funds are returned to the initiator, with the redeemer's consent.","As such, the redeemer's signature is required for this instruction.","This allows for refunds before the expiry slot."],discriminator:[211,202,103,41,183,147,59,251],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"initiator_token_account",writable:!0},{name:"redeemer",docs:["The redeemer of the atomic swap. They must sign this transaction."],writable:!0,signer:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[]},{name:"redeem",docs:["Funds are transferred to the redeemer. This instruction does not require any signatures."],discriminator:[184,12,86,149,70,196,97,225],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"redeemer_token_account",writable:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[{name:"secret",type:{array:["u8",32]}}]},{name:"refund",docs:["Funds are returned to the initiator, given that no redeems have occured","and the expiry slot has been reached.","This instruction does not require any signatures."],discriminator:[2,96,183,251,63,208,46,46],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"initiator_token_account",writable:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[]}],I_=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],O_=[{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]}],B_=[{code:6e3,name:"InvalidRedeemer",msg:"The provider redeemer is not the original redeemer of this swap"},{code:6001,name:"InvalidSecret",msg:"The provided secret does not correspond to the secret hash of this swap"},{code:6002,name:"InvalidSponsor",msg:"The provided sponsor is not the original sponsor of this swap"},{code:6003,name:"RefundBeforeExpiry",msg:"Attempt to perform a refund before expiry time"}],C_=[{name:"Initiated",docs:["Represents the initiated state of the swap where the initiator has deposited funds into the vault"],type:{kind:"struct",fields:[{name:"swap_amount",docs:["The quantity of tokens transferred through this atomic swap in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals will be represented as 1,000,000.'],type:"u64"},{name:"expires_in_slots",docs:["`expires_in_slots` represents the number of slots after which (non-instant) refunds are allowed"],type:"u64"},{name:"initiator",type:"pubkey"},{name:"mint",type:"pubkey"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}},{name:"destination_data",docs:["Information regarding the destination chain in the atomic swap"],type:{option:"bytes"}}]}},{name:"InstantRefunded",docs:["Represents the instant refund state of the swap, where the initiator has withdrawn funds the vault","with the redeemer's consent"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"Redeemed",docs:["Represents the redeemed state of the swap, where the redeemer has withdrawn funds from the vault"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret",type:{array:["u8",32]}}]}},{name:"Refunded",docs:["Represents the refund state of the swap, where the initiator has withdrawn funds from the vault past expiry"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"SwapAccount",docs:["Stores the state information of the atomic swap on-chain"],type:{kind:"struct",fields:[{name:"expiry_slot",docs:["The exact slot after which (non-instant) refunds are allowed"],type:"u64"},{name:"initiator",docs:["The initiator of the atomic swap"],type:"pubkey"},{name:"redeemer",docs:["The redeemer of the atomic swap"],type:"pubkey"},{name:"secret_hash",docs:["The secret hash associated with the atomic swap"],type:{array:["u8",32]}},{name:"swap_amount",docs:["The quantity tokens to be transferred through this atomic swap","in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals',"must be provided as 1,000,000."],type:"u64"},{name:"identity_pda_bump",docs:["The bump associated with the identity pda.","This is needed by the program to authorize token transfers via the token vault."],type:"u8"},{name:"sponsor",docs:["The entity that paid the rent fees for the creation of this PDA.","This will be referenced during the refund of the same upon closing this PDA."],type:"pubkey"}]}}],H0={address:T_,metadata:__,instructions:P_,accounts:I_,events:O_,errors:B_,types:C_},$_="2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",R_={name:"solana_native_swaps",version:"0.3.0",spec:"0.1.0",description:"Created with Anchor"},N_=[{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:[]}],U_=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],M_=[{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]}],F_=[{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"}],j_=[{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]}}]}}],md={address:$_,metadata:R_,instructions:N_,accounts:U_,events:M_,errors:F_,types:j_};var wn={},hu={};Object.defineProperty(hu,"__esModule",{value:!0});hu.encode=L_;hu.decode=D_;const z0=Qs;function L_(t){return t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),"0x")}function D_(t){t.indexOf("0x")===0&&(t=t.substr(2)),t.length%2===1&&(t="0"+t);let e=t.match(/.{2}/g);return e===null?z0.Buffer.from([]):z0.Buffer.from(e.map(r=>parseInt(r,16)))}var pu={},qs={},cf;Object.defineProperty(qs,"__esModule",{value:!0});qs.isVersionedTransaction=qs.isBrowser=void 0;qs.chunks=H_;qs.isBrowser=process.env.ANCHOR_BROWSER||typeof window<"u"&&!(!((cf=window.process)===null||cf===void 0)&&cf.hasOwnProperty("type"));function H_(t,e){return Array.apply(0,new Array(Math.ceil(t.length/e))).map((r,n)=>t.slice(n*e,(n+1)*e))}const z_=t=>"version"in t;qs.isVersionedTransaction=z_;var uf={},ff={},lf,V0;function gw(){return V0||(V0=1,lf=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var s=42;e[r]=s;for(var i in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var o=Object.getOwnPropertySymbols(e);if(o.length!==1||o[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var a=Object.getOwnPropertyDescriptor(e,r);if(a.value!==s||a.enumerable!==!0)return!1}return!0}),lf}var df,q0;function yu(){if(q0)return df;q0=1;var t=gw();return df=function(){return t()&&!!Symbol.toStringTag},df}var hf,G0;function ww(){return G0||(G0=1,hf=Object),hf}var pf,W0;function V_(){return W0||(W0=1,pf=Error),pf}var yf,K0;function q_(){return K0||(K0=1,yf=EvalError),yf}var mf,Z0;function G_(){return Z0||(Z0=1,mf=RangeError),mf}var bf,Y0;function W_(){return Y0||(Y0=1,bf=ReferenceError),bf}var gf,X0;function vw(){return X0||(X0=1,gf=SyntaxError),gf}var wf,J0;function Pa(){return J0||(J0=1,wf=TypeError),wf}var vf,Q0;function K_(){return Q0||(Q0=1,vf=URIError),vf}var Ef,ey;function Z_(){return ey||(ey=1,Ef=Math.abs),Ef}var Sf,ty;function Y_(){return ty||(ty=1,Sf=Math.floor),Sf}var Af,ry;function X_(){return ry||(ry=1,Af=Math.max),Af}var xf,ny;function J_(){return ny||(ny=1,xf=Math.min),xf}var kf,sy;function Q_(){return sy||(sy=1,kf=Math.pow),kf}var Tf,iy;function eP(){return iy||(iy=1,Tf=Math.round),Tf}var _f,oy;function tP(){return oy||(oy=1,_f=Number.isNaN||function(e){return e!==e}),_f}var Pf,ay;function rP(){if(ay)return Pf;ay=1;var t=tP();return Pf=function(r){return t(r)||r===0?r:r<0?-1:1},Pf}var If,cy;function nP(){return cy||(cy=1,If=Object.getOwnPropertyDescriptor),If}var Of,uy;function Yi(){if(uy)return Of;uy=1;var t=nP();if(t)try{t([],"length")}catch{t=null}return Of=t,Of}var Bf,fy;function mu(){if(fy)return Bf;fy=1;var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch{t=!1}return Bf=t,Bf}var Cf,ly;function sP(){if(ly)return Cf;ly=1;var t=typeof Symbol<"u"&&Symbol,e=gw();return Cf=function(){return typeof t!="function"||typeof Symbol!="function"||typeof t("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Cf}var $f,dy;function Ew(){return dy||(dy=1,$f=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),$f}var Rf,hy;function Sw(){if(hy)return Rf;hy=1;var t=ww();return Rf=t.getPrototypeOf||null,Rf}var Nf,py;function iP(){if(py)return Nf;py=1;var t="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,r=Math.max,n="[object Function]",s=function(c,u){for(var f=[],l=0;l<c.length;l+=1)f[l]=c[l];for(var p=0;p<u.length;p+=1)f[p+c.length]=u[p];return f},i=function(c,u){for(var f=[],l=u,p=0;l<c.length;l+=1,p+=1)f[p]=c[l];return f},o=function(a,c){for(var u="",f=0;f<a.length;f+=1)u+=a[f],f+1<a.length&&(u+=c);return u};return Nf=function(c){var u=this;if(typeof u!="function"||e.apply(u)!==n)throw new TypeError(t+u);for(var f=i(arguments,1),l,p=function(){if(this instanceof l){var A=u.apply(this,s(f,arguments));return Object(A)===A?A:this}return u.apply(c,s(f,arguments))},d=r(0,u.length-f.length),m=[],b=0;b<d;b++)m[b]="$"+b;if(l=Function("binder","return function ("+o(m,",")+"){ return binder.apply(this,arguments); }")(p),u.prototype){var E=function(){};E.prototype=u.prototype,l.prototype=new E,E.prototype=null}return l},Nf}var Uf,yy;function Ia(){if(yy)return Uf;yy=1;var t=iP();return Uf=Function.prototype.bind||t,Uf}var Mf,my;function Dh(){return my||(my=1,Mf=Function.prototype.call),Mf}var Ff,by;function Hh(){return by||(by=1,Ff=Function.prototype.apply),Ff}var jf,gy;function oP(){return gy||(gy=1,jf=typeof Reflect<"u"&&Reflect&&Reflect.apply),jf}var Lf,wy;function Aw(){if(wy)return Lf;wy=1;var t=Ia(),e=Hh(),r=Dh(),n=oP();return Lf=n||t.call(r,e),Lf}var Df,vy;function zh(){if(vy)return Df;vy=1;var t=Ia(),e=Pa(),r=Dh(),n=Aw();return Df=function(i){if(i.length<1||typeof i[0]!="function")throw new e("a function is required");return n(t,r,i)},Df}var Hf,Ey;function aP(){if(Ey)return Hf;Ey=1;var t=zh(),e=Yi(),r;try{r=[].__proto__===Array.prototype}catch(o){if(!o||typeof o!="object"||!("code"in o)||o.code!=="ERR_PROTO_ACCESS")throw o}var n=!!r&&e&&e(Object.prototype,"__proto__"),s=Object,i=s.getPrototypeOf;return Hf=n&&typeof n.get=="function"?t([n.get]):typeof i=="function"?function(a){return i(a==null?a:s(a))}:!1,Hf}var zf,Sy;function Vh(){if(Sy)return zf;Sy=1;var t=Ew(),e=Sw(),r=aP();return zf=t?function(s){return t(s)}:e?function(s){if(!s||typeof s!="object"&&typeof s!="function")throw new TypeError("getProto: not an object");return e(s)}:r?function(s){return r(s)}:null,zf}var Vf,Ay;function xw(){if(Ay)return Vf;Ay=1;var t=Function.prototype.call,e=Object.prototype.hasOwnProperty,r=Ia();return Vf=r.call(t,e),Vf}var qf,xy;function kw(){if(xy)return qf;xy=1;var t,e=ww(),r=V_(),n=q_(),s=G_(),i=W_(),o=vw(),a=Pa(),c=K_(),u=Z_(),f=Y_(),l=X_(),p=J_(),d=Q_(),m=eP(),b=rP(),E=Function,A=function(oe){try{return E('"use strict"; return ('+oe+").constructor;")()}catch{}},P=Yi(),S=mu(),w=function(){throw new a},k=P?function(){try{return arguments.callee,w}catch{try{return P(arguments,"callee").get}catch{return w}}}():w,T=sP()(),B=Vh(),U=Sw(),$=Ew(),D=Hh(),M=Dh(),q={},K=typeof Uint8Array>"u"||!B?t:B(Uint8Array),Q={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?t:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?t:ArrayBuffer,"%ArrayIteratorPrototype%":T&&B?B([][Symbol.iterator]()):t,"%AsyncFromSyncIteratorPrototype%":t,"%AsyncFunction%":q,"%AsyncGenerator%":q,"%AsyncGeneratorFunction%":q,"%AsyncIteratorPrototype%":q,"%Atomics%":typeof Atomics>"u"?t:Atomics,"%BigInt%":typeof BigInt>"u"?t:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?t:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?t:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?t:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":typeof Float16Array>"u"?t:Float16Array,"%Float32Array%":typeof Float32Array>"u"?t:Float32Array,"%Float64Array%":typeof Float64Array>"u"?t:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?t:FinalizationRegistry,"%Function%":E,"%GeneratorFunction%":q,"%Int8Array%":typeof Int8Array>"u"?t:Int8Array,"%Int16Array%":typeof Int16Array>"u"?t:Int16Array,"%Int32Array%":typeof Int32Array>"u"?t:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":T&&B?B(B([][Symbol.iterator]())):t,"%JSON%":typeof JSON=="object"?JSON:t,"%Map%":typeof Map>"u"?t:Map,"%MapIteratorPrototype%":typeof Map>"u"||!T||!B?t:B(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":e,"%Object.getOwnPropertyDescriptor%":P,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?t:Promise,"%Proxy%":typeof Proxy>"u"?t:Proxy,"%RangeError%":s,"%ReferenceError%":i,"%Reflect%":typeof Reflect>"u"?t:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?t:Set,"%SetIteratorPrototype%":typeof Set>"u"||!T||!B?t:B(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?t:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":T&&B?B(""[Symbol.iterator]()):t,"%Symbol%":T?Symbol:t,"%SyntaxError%":o,"%ThrowTypeError%":k,"%TypedArray%":K,"%TypeError%":a,"%Uint8Array%":typeof Uint8Array>"u"?t:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?t:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?t:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?t:Uint32Array,"%URIError%":c,"%WeakMap%":typeof WeakMap>"u"?t:WeakMap,"%WeakRef%":typeof WeakRef>"u"?t:WeakRef,"%WeakSet%":typeof WeakSet>"u"?t:WeakSet,"%Function.prototype.call%":M,"%Function.prototype.apply%":D,"%Object.defineProperty%":S,"%Object.getPrototypeOf%":U,"%Math.abs%":u,"%Math.floor%":f,"%Math.max%":l,"%Math.min%":p,"%Math.pow%":d,"%Math.round%":m,"%Math.sign%":b,"%Reflect.getPrototypeOf%":$};if(B)try{null.error}catch(oe){var G=B(B(oe));Q["%Error.prototype%"]=G}var W=function oe(ie){var me;if(ie==="%AsyncFunction%")me=A("async function () {}");else if(ie==="%GeneratorFunction%")me=A("function* () {}");else if(ie==="%AsyncGeneratorFunction%")me=A("async function* () {}");else if(ie==="%AsyncGenerator%"){var be=oe("%AsyncGeneratorFunction%");be&&(me=be.prototype)}else if(ie==="%AsyncIteratorPrototype%"){var we=oe("%AsyncGenerator%");we&&B&&(me=B(we.prototype))}return Q[ie]=me,me},ee={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},H=Ia(),I=xw(),j=H.call(M,Array.prototype.concat),J=H.call(D,Array.prototype.splice),O=H.call(M,String.prototype.replace),R=H.call(M,String.prototype.slice),F=H.call(M,RegExp.prototype.exec),ne=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,ae=/\\(\\)?/g,le=function(ie){var me=R(ie,0,1),be=R(ie,-1);if(me==="%"&&be!=="%")throw new o("invalid intrinsic syntax, expected closing `%`");if(be==="%"&&me!=="%")throw new o("invalid intrinsic syntax, expected opening `%`");var we=[];return O(ie,ne,function(ke,tt,Oe,Nr){we[we.length]=Oe?O(Nr,ae,"$1"):tt||ke}),we},ue=function(ie,me){var be=ie,we;if(I(ee,be)&&(we=ee[be],be="%"+we[0]+"%"),I(Q,be)){var ke=Q[be];if(ke===q&&(ke=W(be)),typeof ke>"u"&&!me)throw new a("intrinsic "+ie+" exists, but is not available. Please file an issue!");return{alias:we,name:be,value:ke}}throw new o("intrinsic "+ie+" does not exist!")};return qf=function(ie,me){if(typeof ie!="string"||ie.length===0)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof me!="boolean")throw new a('"allowMissing" argument must be a boolean');if(F(/^%?[^%]*%?$/,ie)===null)throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var be=le(ie),we=be.length>0?be[0]:"",ke=ue("%"+we+"%",me),tt=ke.name,Oe=ke.value,Nr=!1,ds=ke.alias;ds&&(we=ds[0],J(be,j([0,1],ds)));for(var V=1,Ur=!0;V<be.length;V+=1){var St=be[V],At=R(St,0,1),Rn=R(St,-1);if((At==='"'||At==="'"||At==="`"||Rn==='"'||Rn==="'"||Rn==="`")&&At!==Rn)throw new o("property names with quotes must have matching quotes");if((St==="constructor"||!Ur)&&(Nr=!0),we+="."+St,tt="%"+we+"%",I(Q,tt))Oe=Q[tt];else if(Oe!=null){if(!(St in Oe)){if(!me)throw new a("base intrinsic for "+ie+" exists, but the property is not available.");return}if(P&&V+1>=be.length){var ni=P(Oe,St);Ur=!!ni,Ur&&"get"in ni&&!("originalValue"in ni.get)?Oe=ni.get:Oe=Oe[St]}else Ur=I(Oe,St),Oe=Oe[St];Ur&&!Nr&&(Q[tt]=Oe)}}return Oe},qf}var Gf,ky;function Oa(){if(ky)return Gf;ky=1;var t=kw(),e=zh(),r=e([t("%String.prototype.indexOf%")]);return Gf=function(s,i){var o=t(s,!!i);return typeof o=="function"&&r(s,".prototype.")>-1?e([o]):o},Gf}var Wf,Ty;function cP(){if(Ty)return Wf;Ty=1;var t=yu()(),e=Oa(),r=e("Object.prototype.toString"),n=function(a){return t&&a&&typeof a=="object"&&Symbol.toStringTag in a?!1:r(a)==="[object Arguments]"},s=function(a){return n(a)?!0:a!==null&&typeof a=="object"&&"length"in a&&typeof a.length=="number"&&a.length>=0&&r(a)!=="[object Array]"&&"callee"in a&&r(a.callee)==="[object Function]"},i=function(){return n(arguments)}();return n.isLegacyArguments=s,Wf=i?n:s,Wf}var Kf,_y;function uP(){if(_y)return Kf;_y=1;var t=Oa(),e=yu()(),r=xw(),n=Yi(),s;if(e){var i=t("RegExp.prototype.exec"),o={},a=function(){throw o},c={toString:a,valueOf:a};typeof Symbol.toPrimitive=="symbol"&&(c[Symbol.toPrimitive]=a),s=function(p){if(!p||typeof p!="object")return!1;var d=n(p,"lastIndex"),m=d&&r(d,"value");if(!m)return!1;try{i(p,c)}catch(b){return b===o}}}else{var u=t("Object.prototype.toString"),f="[object RegExp]";s=function(p){return!p||typeof p!="object"&&typeof p!="function"?!1:u(p)===f}}return Kf=s,Kf}var Zf,Py;function fP(){if(Py)return Zf;Py=1;var t=Oa(),e=uP(),r=t("RegExp.prototype.exec"),n=Pa();return Zf=function(i){if(!e(i))throw new n("`regex` must be a RegExp");return function(a){return r(i,a)!==null}},Zf}var Yf,Iy;function lP(){if(Iy)return Yf;Iy=1;var t=Oa(),e=fP(),r=e(/^\s*(?:function)?\*/),n=yu()(),s=Vh(),i=t("Object.prototype.toString"),o=t("Function.prototype.toString"),a=function(){if(!n)return!1;try{return Function("return function*() {}")()}catch{}},c;return Yf=function(f){if(typeof f!="function")return!1;if(r(o(f)))return!0;if(!n){var l=i(f);return l==="[object GeneratorFunction]"}if(!s)return!1;if(typeof c>"u"){var p=a();c=p?s(p):!1}return s(f)===c},Yf}var Xf,Oy;function dP(){if(Oy)return Xf;Oy=1;var t=Function.prototype.toString,e=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,r,n;if(typeof e=="function"&&typeof Object.defineProperty=="function")try{r=Object.defineProperty({},"length",{get:function(){throw n}}),n={},e(function(){throw 42},null,r)}catch(P){P!==n&&(e=null)}else e=null;var s=/^\s*class\b/,i=function(S){try{var w=t.call(S);return s.test(w)}catch{return!1}},o=function(S){try{return i(S)?!1:(t.call(S),!0)}catch{return!1}},a=Object.prototype.toString,c="[object Object]",u="[object Function]",f="[object GeneratorFunction]",l="[object HTMLAllCollection]",p="[object HTML document.all class]",d="[object HTMLCollection]",m=typeof Symbol=="function"&&!!Symbol.toStringTag,b=!(0 in[,]),E=function(){return!1};if(typeof document=="object"){var A=document.all;a.call(A)===a.call(document.all)&&(E=function(S){if((b||!S)&&(typeof S>"u"||typeof S=="object"))try{var w=a.call(S);return(w===l||w===p||w===d||w===c)&&S("")==null}catch{}return!1})}return Xf=e?function(S){if(E(S))return!0;if(!S||typeof S!="function"&&typeof S!="object")return!1;try{e(S,null,r)}catch(w){if(w!==n)return!1}return!i(S)&&o(S)}:function(S){if(E(S))return!0;if(!S||typeof S!="function"&&typeof S!="object")return!1;if(m)return o(S);if(i(S))return!1;var w=a.call(S);return w!==u&&w!==f&&!/^\[object HTML/.test(w)?!1:o(S)},Xf}var Jf,By;function hP(){if(By)return Jf;By=1;var t=dP(),e=Object.prototype.toString,r=Object.prototype.hasOwnProperty,n=function(c,u,f){for(var l=0,p=c.length;l<p;l++)r.call(c,l)&&(f==null?u(c[l],l,c):u.call(f,c[l],l,c))},s=function(c,u,f){for(var l=0,p=c.length;l<p;l++)f==null?u(c.charAt(l),l,c):u.call(f,c.charAt(l),l,c)},i=function(c,u,f){for(var l in c)r.call(c,l)&&(f==null?u(c[l],l,c):u.call(f,c[l],l,c))};function o(a){return e.call(a)==="[object Array]"}return Jf=function(c,u,f){if(!t(u))throw new TypeError("iterator must be a function");var l;arguments.length>=3&&(l=f),o(c)?n(c,u,l):typeof c=="string"?s(c,u,l):i(c,u,l)},Jf}var Qf,Cy;function pP(){return Cy||(Cy=1,Qf=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),Qf}var el,$y;function yP(){if($y)return el;$y=1;var t=pP(),e=typeof globalThis>"u"?Qr:globalThis;return el=function(){for(var n=[],s=0;s<t.length;s++)typeof e[t[s]]=="function"&&(n[n.length]=t[s]);return n},el}var tl={exports:{}},rl,Ry;function mP(){if(Ry)return rl;Ry=1;var t=mu(),e=vw(),r=Pa(),n=Yi();return rl=function(i,o,a){if(!i||typeof i!="object"&&typeof i!="function")throw new r("`obj` must be an object or a function`");if(typeof o!="string"&&typeof o!="symbol")throw new r("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new r("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new r("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new r("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new r("`loose`, if provided, must be a boolean");var c=arguments.length>3?arguments[3]:null,u=arguments.length>4?arguments[4]:null,f=arguments.length>5?arguments[5]:null,l=arguments.length>6?arguments[6]:!1,p=!!n&&n(i,o);if(t)t(i,o,{configurable:f===null&&p?p.configurable:!f,enumerable:c===null&&p?p.enumerable:!c,value:a,writable:u===null&&p?p.writable:!u});else if(l||!c&&!u&&!f)i[o]=a;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},rl}var nl,Ny;function bP(){if(Ny)return nl;Ny=1;var t=mu(),e=function(){return!!t};return e.hasArrayLengthDefineBug=function(){if(!t)return null;try{return t([],"length",{value:1}).length!==1}catch{return!0}},nl=e,nl}var sl,Uy;function gP(){if(Uy)return sl;Uy=1;var t=kw(),e=mP(),r=bP()(),n=Yi(),s=Pa(),i=t("%Math.floor%");return sl=function(a,c){if(typeof a!="function")throw new s("`fn` is not a function");if(typeof c!="number"||c<0||c>4294967295||i(c)!==c)throw new s("`length` must be a positive 32-bit integer");var u=arguments.length>2&&!!arguments[2],f=!0,l=!0;if("length"in a&&n){var p=n(a,"length");p&&!p.configurable&&(f=!1),p&&!p.writable&&(l=!1)}return(f||l||!u)&&(r?e(a,"length",c,!0,!0):e(a,"length",c)),a},sl}var il,My;function wP(){if(My)return il;My=1;var t=Ia(),e=Hh(),r=Aw();return il=function(){return r(t,e,arguments)},il}var Fy;function vP(){return Fy||(Fy=1,function(t){var e=gP(),r=mu(),n=zh(),s=wP();t.exports=function(o){var a=n(arguments),c=o.length-(arguments.length-1);return e(a,1+(c>0?c:0),!0)},r?r(t.exports,"apply",{value:s}):t.exports.apply=s}(tl)),tl.exports}var ol,jy;function Tw(){if(jy)return ol;jy=1;var t=hP(),e=yP(),r=vP(),n=Oa(),s=Yi(),i=Vh(),o=n("Object.prototype.toString"),a=yu()(),c=typeof globalThis>"u"?Qr:globalThis,u=e(),f=n("String.prototype.slice"),l=n("Array.prototype.indexOf",!0)||function(E,A){for(var P=0;P<E.length;P+=1)if(E[P]===A)return P;return-1},p={__proto__:null};a&&s&&i?t(u,function(b){var E=new c[b];if(Symbol.toStringTag in E&&i){var A=i(E),P=s(A,Symbol.toStringTag);if(!P&&A){var S=i(A);P=s(S,Symbol.toStringTag)}p["$"+b]=r(P.get)}}):t(u,function(b){var E=new c[b],A=E.slice||E.set;A&&(p["$"+b]=r(A))});var d=function(E){var A=!1;return t(p,function(P,S){if(!A)try{"$"+P(E)===S&&(A=f(S,1))}catch{}}),A},m=function(E){var A=!1;return t(p,function(P,S){if(!A)try{P(E),A=f(S,1)}catch{}}),A};return ol=function(E){if(!E||typeof E!="object")return!1;if(!a){var A=f(o(E),8,-1);return l(u,A)>-1?A:A!=="Object"?!1:m(E)}return s?d(E):null},ol}var al,Ly;function EP(){if(Ly)return al;Ly=1;var t=Tw();return al=function(r){return!!t(r)},al}var Dy;function SP(){return Dy||(Dy=1,function(t){var e=cP(),r=lP(),n=Tw(),s=EP();function i(V){return V.call.bind(V)}var o=typeof BigInt<"u",a=typeof Symbol<"u",c=i(Object.prototype.toString),u=i(Number.prototype.valueOf),f=i(String.prototype.valueOf),l=i(Boolean.prototype.valueOf);if(o)var p=i(BigInt.prototype.valueOf);if(a)var d=i(Symbol.prototype.valueOf);function m(V,Ur){if(typeof V!="object")return!1;try{return Ur(V),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=r,t.isTypedArray=s;function b(V){return typeof Promise<"u"&&V instanceof Promise||V!==null&&typeof V=="object"&&typeof V.then=="function"&&typeof V.catch=="function"}t.isPromise=b;function E(V){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(V):s(V)||R(V)}t.isArrayBufferView=E;function A(V){return n(V)==="Uint8Array"}t.isUint8Array=A;function P(V){return n(V)==="Uint8ClampedArray"}t.isUint8ClampedArray=P;function S(V){return n(V)==="Uint16Array"}t.isUint16Array=S;function w(V){return n(V)==="Uint32Array"}t.isUint32Array=w;function k(V){return n(V)==="Int8Array"}t.isInt8Array=k;function T(V){return n(V)==="Int16Array"}t.isInt16Array=T;function B(V){return n(V)==="Int32Array"}t.isInt32Array=B;function U(V){return n(V)==="Float32Array"}t.isFloat32Array=U;function $(V){return n(V)==="Float64Array"}t.isFloat64Array=$;function D(V){return n(V)==="BigInt64Array"}t.isBigInt64Array=D;function M(V){return n(V)==="BigUint64Array"}t.isBigUint64Array=M;function q(V){return c(V)==="[object Map]"}q.working=typeof Map<"u"&&q(new Map);function K(V){return typeof Map>"u"?!1:q.working?q(V):V instanceof Map}t.isMap=K;function Q(V){return c(V)==="[object Set]"}Q.working=typeof Set<"u"&&Q(new Set);function G(V){return typeof Set>"u"?!1:Q.working?Q(V):V instanceof Set}t.isSet=G;function W(V){return c(V)==="[object WeakMap]"}W.working=typeof WeakMap<"u"&&W(new WeakMap);function ee(V){return typeof WeakMap>"u"?!1:W.working?W(V):V instanceof WeakMap}t.isWeakMap=ee;function H(V){return c(V)==="[object WeakSet]"}H.working=typeof WeakSet<"u"&&H(new WeakSet);function I(V){return H(V)}t.isWeakSet=I;function j(V){return c(V)==="[object ArrayBuffer]"}j.working=typeof ArrayBuffer<"u"&&j(new ArrayBuffer);function J(V){return typeof ArrayBuffer>"u"?!1:j.working?j(V):V instanceof ArrayBuffer}t.isArrayBuffer=J;function O(V){return c(V)==="[object DataView]"}O.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&O(new DataView(new ArrayBuffer(1),0,1));function R(V){return typeof DataView>"u"?!1:O.working?O(V):V instanceof DataView}t.isDataView=R;var F=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function ne(V){return c(V)==="[object SharedArrayBuffer]"}function ae(V){return typeof F>"u"?!1:(typeof ne.working>"u"&&(ne.working=ne(new F)),ne.working?ne(V):V instanceof F)}t.isSharedArrayBuffer=ae;function le(V){return c(V)==="[object AsyncFunction]"}t.isAsyncFunction=le;function ue(V){return c(V)==="[object Map Iterator]"}t.isMapIterator=ue;function oe(V){return c(V)==="[object Set Iterator]"}t.isSetIterator=oe;function ie(V){return c(V)==="[object Generator]"}t.isGeneratorObject=ie;function me(V){return c(V)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=me;function be(V){return m(V,u)}t.isNumberObject=be;function we(V){return m(V,f)}t.isStringObject=we;function ke(V){return m(V,l)}t.isBooleanObject=ke;function tt(V){return o&&m(V,p)}t.isBigIntObject=tt;function Oe(V){return a&&m(V,d)}t.isSymbolObject=Oe;function Nr(V){return be(V)||we(V)||ke(V)||tt(V)||Oe(V)}t.isBoxedPrimitive=Nr;function ds(V){return typeof Uint8Array<"u"&&(J(V)||ae(V))}t.isAnyArrayBuffer=ds,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(V){Object.defineProperty(t,V,{enumerable:!1,value:function(){throw new Error(V+" is not supported in userland")}})})}(ff)),ff}var cl,Hy;function AP(){return Hy||(Hy=1,cl=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"}),cl}var Xa={exports:{}},zy;function xP(){return zy||(zy=1,typeof Object.create=="function"?Xa.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Xa.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}),Xa.exports}var Vy;function _w(){return Vy||(Vy=1,function(t){var e=Object.getOwnPropertyDescriptors||function(R){for(var F=Object.keys(R),ne={},ae=0;ae<F.length;ae++)ne[F[ae]]=Object.getOwnPropertyDescriptor(R,F[ae]);return ne},r=/%[sdj%]/g;t.format=function(O){if(!k(O)){for(var R=[],F=0;F<arguments.length;F++)R.push(o(arguments[F]));return R.join(" ")}for(var F=1,ne=arguments,ae=ne.length,le=String(O).replace(r,function(oe){if(oe==="%%")return"%";if(F>=ae)return oe;switch(oe){case"%s":return String(ne[F++]);case"%d":return Number(ne[F++]);case"%j":try{return JSON.stringify(ne[F++])}catch{return"[Circular]"}default:return oe}}),ue=ne[F];F<ae;ue=ne[++F])P(ue)||!$(ue)?le+=" "+ue:le+=" "+o(ue);return le},t.deprecate=function(O,R){if(typeof process<"u"&&process.noDeprecation===!0)return O;if(typeof process>"u")return function(){return t.deprecate(O,R).apply(this,arguments)};var F=!1;function ne(){if(!F){if(process.throwDeprecation)throw new Error(R);process.traceDeprecation?console.trace(R):console.error(R),F=!0}return O.apply(this,arguments)}return ne};var n={},s=/^$/;if(process.env.NODE_DEBUG){var i=process.env.NODE_DEBUG;i=i.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),s=new RegExp("^"+i+"$","i")}t.debuglog=function(O){if(O=O.toUpperCase(),!n[O])if(s.test(O)){var R=process.pid;n[O]=function(){var F=t.format.apply(t,arguments);console.error("%s %d: %s",O,R,F)}}else n[O]=function(){};return n[O]};function o(O,R){var F={seen:[],stylize:c};return arguments.length>=3&&(F.depth=arguments[2]),arguments.length>=4&&(F.colors=arguments[3]),A(R)?F.showHidden=R:R&&t._extend(F,R),B(F.showHidden)&&(F.showHidden=!1),B(F.depth)&&(F.depth=2),B(F.colors)&&(F.colors=!1),B(F.customInspect)&&(F.customInspect=!0),F.colors&&(F.stylize=a),f(F,O,F.depth)}t.inspect=o,o.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},o.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function a(O,R){var F=o.styles[R];return F?"\x1B["+o.colors[F][0]+"m"+O+"\x1B["+o.colors[F][1]+"m":O}function c(O,R){return O}function u(O){var R={};return O.forEach(function(F,ne){R[F]=!0}),R}function f(O,R,F){if(O.customInspect&&R&&q(R.inspect)&&R.inspect!==t.inspect&&!(R.constructor&&R.constructor.prototype===R)){var ne=R.inspect(F,O);return k(ne)||(ne=f(O,ne,F)),ne}var ae=l(O,R);if(ae)return ae;var le=Object.keys(R),ue=u(le);if(O.showHidden&&(le=Object.getOwnPropertyNames(R)),M(R)&&(le.indexOf("message")>=0||le.indexOf("description")>=0))return p(R);if(le.length===0){if(q(R)){var oe=R.name?": "+R.name:"";return O.stylize("[Function"+oe+"]","special")}if(U(R))return O.stylize(RegExp.prototype.toString.call(R),"regexp");if(D(R))return O.stylize(Date.prototype.toString.call(R),"date");if(M(R))return p(R)}var ie="",me=!1,be=["{","}"];if(E(R)&&(me=!0,be=["[","]"]),q(R)){var we=R.name?": "+R.name:"";ie=" [Function"+we+"]"}if(U(R)&&(ie=" "+RegExp.prototype.toString.call(R)),D(R)&&(ie=" "+Date.prototype.toUTCString.call(R)),M(R)&&(ie=" "+p(R)),le.length===0&&(!me||R.length==0))return be[0]+ie+be[1];if(F<0)return U(R)?O.stylize(RegExp.prototype.toString.call(R),"regexp"):O.stylize("[Object]","special");O.seen.push(R);var ke;return me?ke=d(O,R,F,ue,le):ke=le.map(function(tt){return m(O,R,F,ue,tt,me)}),O.seen.pop(),b(ke,ie,be)}function l(O,R){if(B(R))return O.stylize("undefined","undefined");if(k(R)){var F="'"+JSON.stringify(R).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return O.stylize(F,"string")}if(w(R))return O.stylize(""+R,"number");if(A(R))return O.stylize(""+R,"boolean");if(P(R))return O.stylize("null","null")}function p(O){return"["+Error.prototype.toString.call(O)+"]"}function d(O,R,F,ne,ae){for(var le=[],ue=0,oe=R.length;ue<oe;++ue)H(R,String(ue))?le.push(m(O,R,F,ne,String(ue),!0)):le.push("");return ae.forEach(function(ie){ie.match(/^\d+$/)||le.push(m(O,R,F,ne,ie,!0))}),le}function m(O,R,F,ne,ae,le){var ue,oe,ie;if(ie=Object.getOwnPropertyDescriptor(R,ae)||{value:R[ae]},ie.get?ie.set?oe=O.stylize("[Getter/Setter]","special"):oe=O.stylize("[Getter]","special"):ie.set&&(oe=O.stylize("[Setter]","special")),H(ne,ae)||(ue="["+ae+"]"),oe||(O.seen.indexOf(ie.value)<0?(P(F)?oe=f(O,ie.value,null):oe=f(O,ie.value,F-1),oe.indexOf(`
|
|
73
|
+
`.trim().replace(/\s+/g," "))}generateLeaves(e,r){let n,s,i;switch(r){case"redeem":n=e.destination_swap,s=n.delegate,i=n.delegate;break;case"refund":n=e.source_swap,s=n.delegate,i=n.delegate;break;case"instantRefund":n=e.source_swap,s=n.redeemer,i=n.redeemer;break;default:throw new Error("Invalid leaf generation type")}return[{version:Za,output:this.redeemLeaf(n.secret_hash,je(s))},[{version:Za,output:this.refundLeaf(n.timelock,je(n.initiator))},{version:Za,output:this.instantRefundLeaf(je(n.initiator),je(i))}]]}generateMerkleProofFor(e,r){const n=this.leafHash(1,r),s=this.leafHash(2,r),i=this.leafHash(0,r);switch(e){case 1:{const o=D3(i,s);return[Ae.crypto.taggedHash("TapBranch",Buffer.concat(o))]}case 0:return[s,n];case 2:return[i,n];default:throw new Error(nr.invalidLeaf)}}getProvider(){return this.signer.getProvider()}get getPublicKey(){return this.signer.getPublicKey()}get htlcActorAddress(){return this.signer.getPublicKey()}};class iw{constructor(e){this.quoteUrl=new g.Url(e)}async getQuoteFromAssets({fromAsset:e,toAsset:r,amount:n,isExactOut:s=!1,options:i}){const o=Y.ChainAsset.from(e),a=Y.ChainAsset.from(r);return this.getQuote(o,a,n,s,i)}async getQuote(e,r,n,s=!1,i){try{const o={from:Y.ChainAsset.from(e).toString(),to:Y.ChainAsset.from(r).toString(),...s?{to_amount:n.toString()}:{from_amount:n.toString()},...(i==null?void 0:i.affiliateFee)!==void 0&&{affiliate_fee:i.affiliateFee.toString()}},a=this.quoteUrl.endpoint("/v2/quote").addSearchParams(o),c=await g.Fetcher.get(a,{retryCount:0,...i==null?void 0:i.request});return c.error?g.Err(c.error):c.result?g.Ok(c.result):g.Err("GetQuote: Unexpected error, result is undefined")}catch(o){return g.Err("GetQuote:",String(o))}}async getStrategies(){try{const e=await g.Fetcher.get(this.quoteUrl.endpoint("/strategies"));if(e.error)return g.Err(e.error);if(!e.result)return g.Err("GetStrategies: Unexpected error, result is undefined");const r={};for(const n of Object.values(e.result)){const s=P1(n.source_chain,n.source_asset.asset,n.dest_chain,n.dest_asset.asset);r[s]={id:n.id,minAmount:n.min_amount,maxAmount:n.max_amount,fee:n.fee,fixed_fee:Number(n.fixed_fee)}}return g.Ok(r)}catch(e){return g.Err("GetStrategies:",String(e))}}}class Mi extends g.EventBroker{get isInitialized(){return!!this.digestKey}constructor(e,r){super(),this.digestKey=e,this.walletClient=r}static fromDigestKey(e){return new Mi(g.trim0x(e))}static fromWalletClient(e){return new Mi(void 0,e)}async initialize(){if(this.digestKey)return g.Ok("Already initialized");const e=await this.deriveDigestKeyFromWalletClient();return e.error?g.Err(e.error):(this.emit("initialized",!0),g.Ok("Initialized"))}async deriveDigestKeyFromWalletClient(){if(!this.walletClient)return g.Err("No walletClient found");if(!this.walletClient.account)return g.Err("No account found");try{const e=await this.walletClient.signTypedData({account:this.walletClient.account,types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"}],Data:[{name:"Message",type:"string"},{name:"Version",type:"string"},{name:"Nonce",type:"uint256"}]},domain:{name:"GARDEN FINANCE",version:"1"},primaryType:"Data",message:{Message:"Initialize your account",Version:"1.0.2",Nonce:1n}});return this.digestKey=g.trim0x(ho(e)),this.emit("initialized",!0),g.Ok(this.digestKey)}catch(e){return g.Err("Failed to initialize: "+e)}}async getDigestKey(){if(!this.digestKey&&!this.walletClient)return g.Err("No private key or wallet client found");if(!this.digestKey&&this.walletClient){const e=await this.deriveDigestKeyFromWalletClient();if(e.error)return g.Err(e.error)}return this.digestKey?g.Ok(this.digestKey):g.Err("No private key found")}async generateSecret(e){const r=await this.signMessage(e);if(!r.ok)return g.Err(r.error);const n=ho(g.with0x(r.val)),s=ho(n);return g.Ok({secret:n,secretHash:s})}async signMessage(e){if(!this.digestKey){const u=await this.getDigestKey();if(!u.ok)return g.Err(u.error);this.digestKey=u.val}const r=rc.ECPairFactory(fr),n="Garden.fi"+e.toString(),s=Buffer.from(n,"utf8"),i=ho(s),o=Buffer.from(g.trim0x(this.digestKey),"hex");if(o.length!==32)return g.Err("Invalid private key length. Expected 32 bytes.");const c=r.fromPrivateKey(o).sign(Buffer.from(g.trim0x(i),"hex"));return g.Ok(c.toString("hex"))}}const e_=[{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"}],t_={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},r_={block:eE({format(t){var r;return{transactions:(r=t.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const s=Vc(n);return s.typeHex==="0x7e"&&(s.isSystemTx=n.isSystemTx,s.mint=n.mint?ut(n.mint):void 0,s.sourceHash=n.sourceHash,s.type="deposit"),s}),stateRoot:t.stateRoot}}}),transaction:J5({format(t){const e={};return t.type==="0x7e"&&(e.isSystemTx=t.isSystemTx,e.mint=t.mint?ut(t.mint):void 0,e.sourceHash=t.sourceHash,e.type="deposit"),e}}),transactionReceipt:fS({format(t){return{l1GasPrice:t.l1GasPrice?ut(t.l1GasPrice):null,l1GasUsed:t.l1GasUsed?ut(t.l1GasUsed):null,l1Fee:t.l1Fee?ut(t.l1Fee):null,l1FeeScalar:t.l1FeeScalar?Number(t.l1FeeScalar):null}}})};function n_(t,e){return o_(t)?i_(t):ZS(t,e)}const s_={transaction:n_};function i_(t){a_(t);const{sourceHash:e,data:r,from:n,gas:s,isSystemTx:i,mint:o,to:a,value:c}=t,u=[e,n,a??"0x",o?Bt(o):"0x",c?Bt(c):"0x",s?Bt(s):"0x",i?"0x1":"0x",r??"0x"];return $r(["0x7e",as(u)])}function o_(t){return t.type==="deposit"||typeof t.sourceHash<"u"}function a_(t){const{from:e,to:r}=t;if(e&&!at(e))throw new $t({address:e});if(r&&!at(r))throw new $t({address:r})}const Fi={blockTime:2e3,contracts:t_,formatters:r_,serializers:s_},c_=yt({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:250,rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),u_=yt({id:421614,name:"Arbitrum Sepolia",blockTime:250,nativeCurrency:{name:"Arbitrum Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://sepolia.arbiscan.io",apiUrl:"https://api-sepolia.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:81930}},testnet:!0}),ao=1,ow=yt({...Fi,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:{...Fi.contracts,disputeGameFactory:{[ao]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[ao]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[ao]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[ao]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:ao});({...ow});const co=11155111,aw=yt({...Fi,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:{...Fi.contracts,disputeGameFactory:{[co]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[co]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[co]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[co]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:co});({...aw});const f_=yt({id:80094,name:"Berachain",blockTime:2e3,nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},ensRegistry:{address:"0x5b22280886a2f5e09a49bea7e320eab0e5320e28",blockCreated:877007},ensUniversalResolver:{address:"0x4D41762915F83c76EcaF6776d9b08076aA32b492",blockCreated:9310021}},rpcUrls:{default:{http:["https://rpc.berachain.com"]}},blockExplorers:{default:{name:"Berascan",url:"https://berascan.com"}},ensTlds:[".bera"],testnet:!1}),l_=yt({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}),d_=yt({id:56,name:"BNB Smart Chain",blockTime:750,nativeCurrency:{decimals:18,name:"BNB",symbol:"BNB"},rpcUrls:{default:{http:["https://56.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"BscScan",url:"https://bscscan.com",apiUrl:"https://api.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:15921452}}}),h_=yt({id:97,name:"BNB Smart Chain Testnet",nativeCurrency:{decimals:18,name:"BNB",symbol:"tBNB"},rpcUrls:{default:{http:["https://data-seed-prebsc-1-s1.bnbchain.org:8545"]}},blockExplorers:{default:{name:"BscScan",url:"https://testnet.bscscan.com",apiUrl:"https://api-testnet.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:17422483}},testnet:!0}),p_=yt({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}),y_=yt({id:1116,name:"Core Dao",nativeCurrency:{decimals:18,name:"Core",symbol:"CORE"},rpcUrls:{default:{http:["https://rpc.coredao.org"]}},blockExplorers:{default:{name:"CoreDao",url:"https://scan.coredao.org"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:11907934}},testnet:!1}),m_=1,b_=yt({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:m_}),g_=yt({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:12e3,rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:23085558},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),w_=yt({id:10143,name:"Monad Testnet",blockTime:400,nativeCurrency:{name:"Testnet MON Token",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://testnet-rpc.monad.xyz"]}},blockExplorers:{default:{name:"Monad Testnet explorer",url:"https://testnet.monadexplorer.com"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:251449}},testnet:!0}),v_=yt({id:11155111,name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.drpc.org"]}},blockExplorers:{default:{name:"Etherscan",url:"https://sepolia.etherscan.io",apiUrl:"https://api-sepolia.etherscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:751532},ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:8928790}},testnet:!0}),Ya=1,E_=yt({...Fi,id:130,name:"Unichain",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:1e3,rpcUrls:{default:{http:["https://mainnet.unichain.org/"]}},blockExplorers:{default:{name:"Uniscan",url:"https://uniscan.xyz",apiUrl:"https://api.uniscan.xyz/api"}},contracts:{...Fi.contracts,multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:0},disputeGameFactory:{[Ya]:{address:"0x2F12d621a16e2d3285929C9996f478508951dFe4"}},portal:{[Ya]:{address:"0x0bd48f6B86a26D3a217d0Fa6FfE2B491B956A7a2"}},l1StandardBridge:{[Ya]:{address:"0x81014F44b0a345033bB2b3B21C7a1A308B35fEeA"}}},sourceId:Ya}),S_={...v_,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},cw={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/"]}}},uw={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"]}}},fw={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"]}}},pu={ethereum:g_,arbitrum:c_,ethereum_sepolia:S_,arbitrum_sepolia:u_,ethereum_localnet:Y.EthereumLocalnet,arbitrum_localnet:Y.ArbitrumLocalnet,base_sepolia:aw,base:ow,bera_testnet:l_,citrea_testnet:p_,core:y_,bera:f_,monad_testnet:w_,hyperliquid_testnet:uw,hyperliquid:fw,unichain:E_,corn:b_,botanix:cw,bnbchain:d_,bnbchain_testnet:h_},lw=t=>{for(const[e,r]of Object.entries(pu))if(r.id===t)return e;return null},md=async(t,e)=>{var s,i,o;const r=pu[t],n=await e.getChainId();if(r)try{if(r.id===n)return g.Ok({message:"Already on the network",walletClient:e});await e.switchChain({id:r.id});const a=Yu({account:e.account,chain:r,transport:h0(e.transport)});return g.Ok({message:"Switched chain",walletClient:a})}catch(a){if(A_(a))if(a.code===4902||a.code===-32603)try{await e.addChain({chain:r});const c=Yu({account:e.account,chain:r,transport:h0(e.transport)});return g.Ok({message:"Added network",walletClient:c})}catch{return g.Err("Failed to add network")}else if((i=(s=a.body)==null?void 0:s.method)!=null&&i.includes("wallet_switchEthereumChain")||(o=a.message)!=null&&o.includes("wallet_switchEthereumChain")){const c=Yu({account:e.account,chain:r,transport:k1()});return g.Ok({message:"Added network",walletClient:c})}else return g.Err("Failed to switch network");else return g.Err("Failed to switch network")}else return g.Err("Chain not supported")},A_=t=>typeof t=="object"&&t!=null&&("code"in t||"message"in t||"body"in t),x_=[{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 dw{constructor(e,r,n){this.url=new g.Url(e.toString()),this.auth=n,this.wallet=r}get htlcActorAddress(){if(!this.wallet.account)throw new Error("No account found");return this.wallet.account.address}async initiate(e){if(Y.isEvmOrderResponse(e))return this.initiateWithCreateOrderResponse(e);if(!this.wallet.account)return g.Err("No account found");if(this.wallet.account.address.toLowerCase()!==e.source_swap.initiator.toLowerCase())return g.Err("Account address and order initiator mismatch");if(!Y.isEVM(e.source_swap.chain))return g.Err("Source chain is not an EVM chain");const r=e.source_swap.chain,n=await md(r,this.wallet);if(!n.ok)return g.Err(n.error);if(this.wallet=n.val.walletClient,!this.wallet.account)return g.Err("No account found");const{source_swap:s}=e;if(!s.amount||!s.redeemer||!s.timelock||!s.secret_hash)return g.Err("Invalid order");const i=g.with0x(s.secret_hash),o=BigInt(s.timelock),a=g.with0x(s.redeemer),c=BigInt(s.amount),u=await Ih(e.source_swap.asset,this.url);if(!u.ok)return g.Err(u.error);const{htlcAddress:f,tokenAddress:l}=u.val,p=Y.ChainAsset.fromString(e.source_swap.asset);return Y.isEvmNativeToken(p.chain,p.symbol)?this._initiateOnNativeHTLC(i,o,c,a,f):this._initiateOnErc20HTLC(i,o,c,a,f,l,e.order_id)}async _initiateOnNativeHTLC(e,r,n,s,i){if(!this.wallet.account)return g.Err("No account found");try{const a=await zp({address:g.with0x(i),abi:x_,client:this.wallet}).write.initiate([s,r,n,e],{account:this.wallet.account,chain:this.wallet.chain,value:n});return g.Ok(a)}catch(o){return g.Err("Failed to initiate on native HTLC",String(o))}}async _initiateOnErc20HTLC(e,r,n,s,i,o,a){if(!this.wallet.account)return g.Err("No account found");try{const c=await this.auth.getAuthHeaders();if(!c.ok)return g.Err(c.error);const u=zp({address:g.with0x(i),abi:e_,client:this.wallet}),f=await g.checkAllowanceAndApprove(Number(n),o,i,this.wallet);if(!f.ok)return g.Err(f.error);const l=await u.read.eip712Domain(),p=await this.wallet.signTypedData({account:this.wallet.account,domain:{name:l[1],version:l[2],chainId:Number(l[3]),verifyingContract:l[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:s,timelock:r,amount:n,secretHash:e}}),d={...c.val,"Content-Type":"application/json"},m=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(a).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:p}),headers:d});if(m.error)return g.Err(m.error);const b=await g.waitForTransactionReceipt(this.wallet,m.result);return b.val&&b.val.status==="success"?g.Ok(m.result?m.result:"Initiate hash not found"):g.Err("Init failed: Transaction receipt not successful")}catch(c){return console.log("init error :",c),g.Err(String(c))}}async initiateWithCreateOrderResponse(e){const r=e.initiate_transaction.chain_id,n=lw(r);if(!n)return g.Err(`Unsupported chain ID: ${r}`);const s=await md(n,this.wallet);if(!s.ok)return g.Err(s.error);if(this.wallet=s.val.walletClient,!this.wallet.account)return g.Err("No account found");try{if(e.typed_data===null){const u=e.initiate_transaction;if(!u)return g.Err("No initiate_transaction found for native initiate");const f=await this.wallet.sendTransaction({account:this.wallet.account,to:g.with0x(u.to),value:BigInt(u.value),data:g.with0x(u.data),gas:BigInt(u.gas_limit),chain:this.wallet.chain}),l=await g.waitForTransactionReceipt(this.wallet,f);return l.val&&l.val.status!=="success"?g.Err("Native initiate transaction failed"):g.Ok(f)}if(e.approval_transaction){const u=await this.executeApprovalTransaction(e);if(u.error)return g.Err(`Approval failed: ${u.error}`);console.log("Approval transaction completed:",u.val)}const{typed_data:i}=e,o=await this.wallet.signTypedData({account:this.wallet.account,domain:i.domain,types:i.types,primaryType:i.primaryType,message:i.message}),a={...(await this.auth.getAuthHeaders()).val,"Content-Type":"application/json"},c=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:o}),headers:a});return c.error?g.Err(c.error):c.result?g.Ok(c.result):g.Err("Initiate failed: Result is undefined")}catch(i){return console.error("initiateWithCreateOrderResponse error:",i),g.Err("Failed to initiate: "+String(i))}}async executeApprovalTransaction(e){if(!this.wallet.account)return g.Err("No account found");if(!e.approval_transaction)return g.Ok("No approval transaction required");try{const r=e.approval_transaction,n=await this.wallet.sendTransaction({account:this.wallet.account,to:g.with0x(r.to),value:BigInt(r.value),data:g.with0x(r.data),gas:BigInt(r.gas_limit),chain:this.wallet.chain}),s=await g.waitForTransactionReceipt(this.wallet,n);return s.val&&s.val.status!=="success"?g.Err("Approval transaction failed"):g.Ok(n)}catch(r){return console.error("executeApprovalTransaction error:",r),g.Err("Failed to execute approval: "+((r==null?void 0:r.message)||String(r)))}}async redeem(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return g.Err(n.error);const s=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:g.trim0x(r)}),headers:{...n.val,"Content-Type":"application/json"}});if(s.error)return g.Err(s.error);const i=pu[e.destination_swap.chain],a=await v3({chain:i,transport:k1()}).waitForTransactionReceipt({hash:s.result,confirmations:1,timeout:3e5});return a&&a.status==="success"?g.Ok(s.result?s.result:"Redeem hash not found"):g.Err("Redeem failed: Transaction receipt not successful")}catch(n){return g.Err(String(n))}}async refund(){return g.Err("Refund not supported")}}const hw=[{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"}]}],pw=async(t,e,r,n,s)=>{try{const i=await So(t.address,e,r,s);if(!i.ok)return g.Err(i.error);if(i.val>=n)return g.Ok("Allowance already approved");const a=Je.cairo.uint256(BigInt(n)),c=await t.execute([{contractAddress:g.with0x(e),entrypoint:"approve",calldata:[g.with0x(r),a.low,a.high]}]);await s.waitForTransaction(c.transaction_hash,{retryInterval:3e3,successStates:[Je.TransactionExecutionStatus.SUCCEEDED]}),await g.sleep(2e3);for(let u=0;u<20;u++){const f=await So(t.address,e,r,s);if(!f.ok)return g.Err(f.error);if(f.val>=n)return g.Ok(c.transaction_hash);await g.sleep(2e3);let l=0n;for(let p=0;p<20;p++){const d=await So(t.address,e,r,s);if(!d.ok)return g.Err(d.error);if(l=d.val,l>=n)break;await g.sleep(2e3)}return l<n?g.Err("Allowance not approved"):g.Ok(c.transaction_hash)}return g.Err("Allowance not approved after transaction.")}catch(i){return g.Err(`Failed to check or approve allowance: ${i instanceof Error?i.message:String(i)}`)}},So=async(t,e,r,n)=>{try{const i=await new Je.Contract(hw,g.with0x(e),n).call("allowance",[g.with0x(t),g.with0x(r)]);return g.Ok(BigInt((i==null?void 0:i.toString())||"0"))}catch(s){return g.Err(`Failed to check allowance: ${s instanceof Error?s.message:String(s)}`)}},yw=async(t,e,r,n,s)=>{const i=await So(t,e,r,n);return i.ok?g.Ok(i.val>=s):g.Err(i.error)},mw=[{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"}]}],k_={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 bw{constructor(e,r,n,s,i){this.url=e instanceof g.Url?e:new g.Url(e),this.account=r,this.starknetProvider=new Je.RpcProvider({nodeUrl:i||Qo[n].nodeUrl}),this.chainId=Qo[n].chainId,this.auth=s}get htlcActorAddress(){if(!this.account.address)throw new Error("No account found");return this.account.address}async initiate(e){if(Y.isStarknetOrderResponse(e))return this.initiateWithCreateOrderResponse(e);if(!this.account.address)return g.Err("No account address");const{source_swap:r}=e,{redeemer:n,amount:s}=r;if(!s||!n||!r.secret_hash||!r.timelock)return g.Err("Invalid order");try{const i=new Je.Contract(mw,e.source_swap.asset,this.account),o=await(i==null?void 0:i.token()),a=Je.num.toHex(o),c=await yw(this.account.address,a,r.asset,this.starknetProvider,BigInt(r.amount));return c.error?g.Err(c.error):c.val?this.initiateRelay(e):this.approveAndInitiate(a,e)}catch(i){return g.Err(String(i))}}async approveAndInitiate(e,r){const{source_swap:n}=r,{redeemer:s,amount:i}=n,{secret_hash:o,timelock:a}=n,c=n.asset;try{const u=Je.cairo.uint256(BigInt(i)),f={contractAddress:g.with0x(e),entrypoint:"approve",calldata:[c,u.low,u.high]},l=Je.cairo.uint256(i),p={contractAddress:g.with0x(c),entrypoint:"initiate",calldata:[s,a.toString(),l.low.toString(),l.high.toString(),...g.hexToU32Array(o)]},d=await this.account.execute([f,p]);return await this.starknetProvider.waitForTransaction(d.transaction_hash,{retryInterval:2e3,successStates:[Je.TransactionExecutionStatus.SUCCEEDED]}),g.Ok(d.transaction_hash)}catch(u){return g.Err(`Failed to approve and initiate: ${String(u)}`)}}async initiateRelay(e){const{source_swap:r}=e,{redeemer:n,amount:s}=r;if(!r.secret_hash)return g.Err("Invalid order: secret_hash is undefined");const i=g.with0x(r.secret_hash),a={domain:{name:"HTLC",version:Je.shortString.encodeShortString("1"),chainId:this.chainId,revision:Je.TypedDataRevision.ACTIVE},primaryType:"Initiate",types:k_,message:{redeemer:n,amount:Je.cairo.uint256(s),timelock:e.source_swap.timelock,secretHash:g.hexToU32Array(i)}};try{const c=await this.account.signMessage(a),u=y0(c);if(u.error)return g.Err(u.error);const f=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:u.val}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return f.error?g.Err(f.error):f.result?g.Ok(f.result):g.Err("Init: No result found")}catch(c){return g.Err(`Failed to initiate relayer: ${String(c)}`)}}async redeem(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return g.Err(n.error);const s=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:g.trim0x(r)}),headers:{...n.val,"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return s.error?g.Err(s.error):s.result?g.Ok(s.result):g.Err("Redeem: No result found")}catch(n){return g.Err(String(n))}}async executeApprovalTransaction(e){if(!this.account.address)return g.Err("No account address");if(!e.approval_transaction)return g.Ok("No approval transaction required");try{const r=e.approval_transaction,n=await this.account.execute([{contractAddress:g.with0x(r.to),entrypoint:g.with0x(r.selector),calldata:r.calldata}]);return await this.starknetProvider.waitForTransaction(n.transaction_hash,{retryInterval:2e3,successStates:[Je.TransactionExecutionStatus.SUCCEEDED]}),g.Ok(n.transaction_hash)}catch(r){return console.error("executeApprovalTransaction error:",r),g.Err("Failed to execute approval: "+(r instanceof Error&&(r==null?void 0:r.message)||String(r)))}}async initiateWithCreateOrderResponse(e){const r=await this.auth.getAuthHeaders();if(!r.ok)return g.Err(r.error);if(!this.account.address)return g.Err("No account address");const n=await this.executeApprovalTransaction(e);if(n.error)return g.Err(n.error);const{typed_data:s}=e;if(s===null){const c=e.initiate_transaction;if(!c)return g.Err("No initiate_transaction found for native initiate");const u=await this.account.execute([{contractAddress:g.with0x(c.to),entrypoint:g.with0x(c.selector),calldata:c.calldata}]);return await this.starknetProvider.waitForTransaction(u.transaction_hash,{retryInterval:2e3,successStates:[Je.TransactionExecutionStatus.SUCCEEDED]}),g.Ok(u.transaction_hash)}const i=await this.account.signMessage(s),o=y0(i);if(o.error)return g.Err(o.error);const a=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:Array.isArray(o.val)?o.val.join(","):o.val}),headers:{...r.val,"Content-Type":"application/json"}});return a.error?g.Err(a.error):g.Ok(a.result)}async refund(){return g.Err("Refund is taken care of by the relayer")}}const T_="2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC",__={name:"solana_spl_swaps",version:"0.4.0",spec:"0.1.0",description:"Created with Anchor"},P_=[{name:"initiate",docs:["Initiates the atomic swap. Funds are transferred from the initiator to the token vault.","As such, the initiator's signature is required for this instruction.","A sponsor may be involved, who pays PDA rent and transaction fees in SOL, allowing for the","initiator to participate without holding SOL. As such, the sponsor must also sign this transaction.","`swap_amount` represents the quantity of tokens to be transferred through this atomic swap","in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals',"must be provided as 1,000,000.","`expires_in_slots` represents the number of slots after which (non-instant) refunds are allowed.","`destination_data` can hold optional information regarding the destination chain","in the atomic swap, to be emitted in the logs as-is."],discriminator:[5,63,123,113,153,75,148,14],accounts:[{name:"identity_pda",docs:["the token transfers of the `token_vault` PDA.","This PDA will be created during the first most invocation of the `initiate()` function","using the `init_if_needed` attribute, and be reused for all succeeding instructions."],writable:!0,pda:{seeds:[]}},{name:"swap_data",docs:["A PDA that maintains the on-chain state of the atomic swap throughout its lifecycle.","The choice of seeds ensure that any swap with equal `initiator` and","`secret_hash` wont be created until an existing one completes.","This PDA will be deleted upon completion of the swap."],writable:!0,pda:{seeds:[{kind:"account",path:"initiator"},{kind:"arg",path:"secret_hash"}]}},{name:"token_vault",docs:["A permanent PDA that is controlled by the program through the `identity_pda`, as implied",'by the value of the `authority` field below. As such, it serves as the "vault" by escrowing tokens',"of type `mint` for the atomic swap.","It is intended to be reused for all swaps involving the same mint.","Just like `identity_pda`, it will be created during the first most invocation of `initiate()`","of every distinct mint using the `init_if_needed` attribute."],writable:!0,pda:{seeds:[{kind:"account",path:"mint"}]}},{name:"initiator",docs:["The initiator of the atomic swap. They must sign this transaction."],signer:!0},{name:"initiator_token_account",docs:["The token account of the initiator"],writable:!0},{name:"mint",docs:["The mint of the tokens involved in this swap. As this is a parameter, this program can thus be reused","for atomic swaps with different mints."]},{name:"sponsor",docs:["Any entity that pays the PDA rent.","Upon completion of the swap, the PDA rent refund resulting from the","deletion of `swap_data` will be refunded to this address."],writable:!0,signer:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},{name:"system_program",address:"11111111111111111111111111111111"}],args:[{name:"expires_in_slots",type:"u64"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}},{name:"swap_amount",type:"u64"},{name:"destination_data",type:{option:"bytes"}}]},{name:"instant_refund",docs:["Funds are returned to the initiator, with the redeemer's consent.","As such, the redeemer's signature is required for this instruction.","This allows for refunds before the expiry slot."],discriminator:[211,202,103,41,183,147,59,251],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"initiator_token_account",writable:!0},{name:"redeemer",docs:["The redeemer of the atomic swap. They must sign this transaction."],writable:!0,signer:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[]},{name:"redeem",docs:["Funds are transferred to the redeemer. This instruction does not require any signatures."],discriminator:[184,12,86,149,70,196,97,225],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"redeemer_token_account",writable:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[{name:"secret",type:{array:["u8",32]}}]},{name:"refund",docs:["Funds are returned to the initiator, given that no redeems have occured","and the expiry slot has been reached.","This instruction does not require any signatures."],discriminator:[2,96,183,251,63,208,46,46],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"initiator_token_account",writable:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[]}],I_=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],O_=[{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]}],B_=[{code:6e3,name:"InvalidRedeemer",msg:"The provider redeemer is not the original redeemer of this swap"},{code:6001,name:"InvalidSecret",msg:"The provided secret does not correspond to the secret hash of this swap"},{code:6002,name:"InvalidSponsor",msg:"The provided sponsor is not the original sponsor of this swap"},{code:6003,name:"RefundBeforeExpiry",msg:"Attempt to perform a refund before expiry time"}],C_=[{name:"Initiated",docs:["Represents the initiated state of the swap where the initiator has deposited funds into the vault"],type:{kind:"struct",fields:[{name:"swap_amount",docs:["The quantity of tokens transferred through this atomic swap in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals will be represented as 1,000,000.'],type:"u64"},{name:"expires_in_slots",docs:["`expires_in_slots` represents the number of slots after which (non-instant) refunds are allowed"],type:"u64"},{name:"initiator",type:"pubkey"},{name:"mint",type:"pubkey"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}},{name:"destination_data",docs:["Information regarding the destination chain in the atomic swap"],type:{option:"bytes"}}]}},{name:"InstantRefunded",docs:["Represents the instant refund state of the swap, where the initiator has withdrawn funds the vault","with the redeemer's consent"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"Redeemed",docs:["Represents the redeemed state of the swap, where the redeemer has withdrawn funds from the vault"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret",type:{array:["u8",32]}}]}},{name:"Refunded",docs:["Represents the refund state of the swap, where the initiator has withdrawn funds from the vault past expiry"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"SwapAccount",docs:["Stores the state information of the atomic swap on-chain"],type:{kind:"struct",fields:[{name:"expiry_slot",docs:["The exact slot after which (non-instant) refunds are allowed"],type:"u64"},{name:"initiator",docs:["The initiator of the atomic swap"],type:"pubkey"},{name:"redeemer",docs:["The redeemer of the atomic swap"],type:"pubkey"},{name:"secret_hash",docs:["The secret hash associated with the atomic swap"],type:{array:["u8",32]}},{name:"swap_amount",docs:["The quantity tokens to be transferred through this atomic swap","in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals',"must be provided as 1,000,000."],type:"u64"},{name:"identity_pda_bump",docs:["The bump associated with the identity pda.","This is needed by the program to authorize token transfers via the token vault."],type:"u8"},{name:"sponsor",docs:["The entity that paid the rent fees for the creation of this PDA.","This will be referenced during the refund of the same upon closing this PDA."],type:"pubkey"}]}}],z0={address:T_,metadata:__,instructions:P_,accounts:I_,events:O_,errors:B_,types:C_},$_="2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",R_={name:"solana_native_swaps",version:"0.3.0",spec:"0.1.0",description:"Created with Anchor"},N_=[{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:[]}],U_=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],M_=[{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]}],F_=[{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"}],j_=[{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]}}]}}],bd={address:$_,metadata:R_,instructions:N_,accounts:U_,events:M_,errors:F_,types:j_};var wn={},yu={};Object.defineProperty(yu,"__esModule",{value:!0});yu.encode=L_;yu.decode=D_;const V0=Qs;function L_(t){return t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),"0x")}function D_(t){t.indexOf("0x")===0&&(t=t.substr(2)),t.length%2===1&&(t="0"+t);let e=t.match(/.{2}/g);return e===null?V0.Buffer.from([]):V0.Buffer.from(e.map(r=>parseInt(r,16)))}var mu={},qs={},ff;Object.defineProperty(qs,"__esModule",{value:!0});qs.isVersionedTransaction=qs.isBrowser=void 0;qs.chunks=H_;qs.isBrowser=process.env.ANCHOR_BROWSER||typeof window<"u"&&!(!((ff=window.process)===null||ff===void 0)&&ff.hasOwnProperty("type"));function H_(t,e){return Array.apply(0,new Array(Math.ceil(t.length/e))).map((r,n)=>t.slice(n*e,(n+1)*e))}const z_=t=>"version"in t;qs.isVersionedTransaction=z_;var lf={},df={},hf,q0;function gw(){return q0||(q0=1,hf=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var s=42;e[r]=s;for(var i in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var o=Object.getOwnPropertySymbols(e);if(o.length!==1||o[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var a=Object.getOwnPropertyDescriptor(e,r);if(a.value!==s||a.enumerable!==!0)return!1}return!0}),hf}var pf,G0;function bu(){if(G0)return pf;G0=1;var t=gw();return pf=function(){return t()&&!!Symbol.toStringTag},pf}var yf,W0;function ww(){return W0||(W0=1,yf=Object),yf}var mf,K0;function V_(){return K0||(K0=1,mf=Error),mf}var bf,Z0;function q_(){return Z0||(Z0=1,bf=EvalError),bf}var gf,Y0;function G_(){return Y0||(Y0=1,gf=RangeError),gf}var wf,X0;function W_(){return X0||(X0=1,wf=ReferenceError),wf}var vf,J0;function vw(){return J0||(J0=1,vf=SyntaxError),vf}var Ef,Q0;function Pa(){return Q0||(Q0=1,Ef=TypeError),Ef}var Sf,ey;function K_(){return ey||(ey=1,Sf=URIError),Sf}var Af,ty;function Z_(){return ty||(ty=1,Af=Math.abs),Af}var xf,ry;function Y_(){return ry||(ry=1,xf=Math.floor),xf}var kf,ny;function X_(){return ny||(ny=1,kf=Math.max),kf}var Tf,sy;function J_(){return sy||(sy=1,Tf=Math.min),Tf}var _f,iy;function Q_(){return iy||(iy=1,_f=Math.pow),_f}var Pf,oy;function eP(){return oy||(oy=1,Pf=Math.round),Pf}var If,ay;function tP(){return ay||(ay=1,If=Number.isNaN||function(e){return e!==e}),If}var Of,cy;function rP(){if(cy)return Of;cy=1;var t=tP();return Of=function(r){return t(r)||r===0?r:r<0?-1:1},Of}var Bf,uy;function nP(){return uy||(uy=1,Bf=Object.getOwnPropertyDescriptor),Bf}var Cf,fy;function Yi(){if(fy)return Cf;fy=1;var t=nP();if(t)try{t([],"length")}catch{t=null}return Cf=t,Cf}var $f,ly;function gu(){if(ly)return $f;ly=1;var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch{t=!1}return $f=t,$f}var Rf,dy;function sP(){if(dy)return Rf;dy=1;var t=typeof Symbol<"u"&&Symbol,e=gw();return Rf=function(){return typeof t!="function"||typeof Symbol!="function"||typeof t("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Rf}var Nf,hy;function Ew(){return hy||(hy=1,Nf=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),Nf}var Uf,py;function Sw(){if(py)return Uf;py=1;var t=ww();return Uf=t.getPrototypeOf||null,Uf}var Mf,yy;function iP(){if(yy)return Mf;yy=1;var t="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,r=Math.max,n="[object Function]",s=function(c,u){for(var f=[],l=0;l<c.length;l+=1)f[l]=c[l];for(var p=0;p<u.length;p+=1)f[p+c.length]=u[p];return f},i=function(c,u){for(var f=[],l=u,p=0;l<c.length;l+=1,p+=1)f[p]=c[l];return f},o=function(a,c){for(var u="",f=0;f<a.length;f+=1)u+=a[f],f+1<a.length&&(u+=c);return u};return Mf=function(c){var u=this;if(typeof u!="function"||e.apply(u)!==n)throw new TypeError(t+u);for(var f=i(arguments,1),l,p=function(){if(this instanceof l){var A=u.apply(this,s(f,arguments));return Object(A)===A?A:this}return u.apply(c,s(f,arguments))},d=r(0,u.length-f.length),m=[],b=0;b<d;b++)m[b]="$"+b;if(l=Function("binder","return function ("+o(m,",")+"){ return binder.apply(this,arguments); }")(p),u.prototype){var E=function(){};E.prototype=u.prototype,l.prototype=new E,E.prototype=null}return l},Mf}var Ff,my;function Ia(){if(my)return Ff;my=1;var t=iP();return Ff=Function.prototype.bind||t,Ff}var jf,by;function Hh(){return by||(by=1,jf=Function.prototype.call),jf}var Lf,gy;function zh(){return gy||(gy=1,Lf=Function.prototype.apply),Lf}var Df,wy;function oP(){return wy||(wy=1,Df=typeof Reflect<"u"&&Reflect&&Reflect.apply),Df}var Hf,vy;function Aw(){if(vy)return Hf;vy=1;var t=Ia(),e=zh(),r=Hh(),n=oP();return Hf=n||t.call(r,e),Hf}var zf,Ey;function Vh(){if(Ey)return zf;Ey=1;var t=Ia(),e=Pa(),r=Hh(),n=Aw();return zf=function(i){if(i.length<1||typeof i[0]!="function")throw new e("a function is required");return n(t,r,i)},zf}var Vf,Sy;function aP(){if(Sy)return Vf;Sy=1;var t=Vh(),e=Yi(),r;try{r=[].__proto__===Array.prototype}catch(o){if(!o||typeof o!="object"||!("code"in o)||o.code!=="ERR_PROTO_ACCESS")throw o}var n=!!r&&e&&e(Object.prototype,"__proto__"),s=Object,i=s.getPrototypeOf;return Vf=n&&typeof n.get=="function"?t([n.get]):typeof i=="function"?function(a){return i(a==null?a:s(a))}:!1,Vf}var qf,Ay;function qh(){if(Ay)return qf;Ay=1;var t=Ew(),e=Sw(),r=aP();return qf=t?function(s){return t(s)}:e?function(s){if(!s||typeof s!="object"&&typeof s!="function")throw new TypeError("getProto: not an object");return e(s)}:r?function(s){return r(s)}:null,qf}var Gf,xy;function xw(){if(xy)return Gf;xy=1;var t=Function.prototype.call,e=Object.prototype.hasOwnProperty,r=Ia();return Gf=r.call(t,e),Gf}var Wf,ky;function kw(){if(ky)return Wf;ky=1;var t,e=ww(),r=V_(),n=q_(),s=G_(),i=W_(),o=vw(),a=Pa(),c=K_(),u=Z_(),f=Y_(),l=X_(),p=J_(),d=Q_(),m=eP(),b=rP(),E=Function,A=function(oe){try{return E('"use strict"; return ('+oe+").constructor;")()}catch{}},P=Yi(),S=gu(),w=function(){throw new a},k=P?function(){try{return arguments.callee,w}catch{try{return P(arguments,"callee").get}catch{return w}}}():w,T=sP()(),B=qh(),N=Sw(),$=Ew(),D=zh(),M=Hh(),V={},G=typeof Uint8Array>"u"||!B?t:B(Uint8Array),Q={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?t:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?t:ArrayBuffer,"%ArrayIteratorPrototype%":T&&B?B([][Symbol.iterator]()):t,"%AsyncFromSyncIteratorPrototype%":t,"%AsyncFunction%":V,"%AsyncGenerator%":V,"%AsyncGeneratorFunction%":V,"%AsyncIteratorPrototype%":V,"%Atomics%":typeof Atomics>"u"?t:Atomics,"%BigInt%":typeof BigInt>"u"?t:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?t:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?t:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?t:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":typeof Float16Array>"u"?t:Float16Array,"%Float32Array%":typeof Float32Array>"u"?t:Float32Array,"%Float64Array%":typeof Float64Array>"u"?t:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?t:FinalizationRegistry,"%Function%":E,"%GeneratorFunction%":V,"%Int8Array%":typeof Int8Array>"u"?t:Int8Array,"%Int16Array%":typeof Int16Array>"u"?t:Int16Array,"%Int32Array%":typeof Int32Array>"u"?t:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":T&&B?B(B([][Symbol.iterator]())):t,"%JSON%":typeof JSON=="object"?JSON:t,"%Map%":typeof Map>"u"?t:Map,"%MapIteratorPrototype%":typeof Map>"u"||!T||!B?t:B(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":e,"%Object.getOwnPropertyDescriptor%":P,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?t:Promise,"%Proxy%":typeof Proxy>"u"?t:Proxy,"%RangeError%":s,"%ReferenceError%":i,"%Reflect%":typeof Reflect>"u"?t:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?t:Set,"%SetIteratorPrototype%":typeof Set>"u"||!T||!B?t:B(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?t:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":T&&B?B(""[Symbol.iterator]()):t,"%Symbol%":T?Symbol:t,"%SyntaxError%":o,"%ThrowTypeError%":k,"%TypedArray%":G,"%TypeError%":a,"%Uint8Array%":typeof Uint8Array>"u"?t:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?t:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?t:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?t:Uint32Array,"%URIError%":c,"%WeakMap%":typeof WeakMap>"u"?t:WeakMap,"%WeakRef%":typeof WeakRef>"u"?t:WeakRef,"%WeakSet%":typeof WeakSet>"u"?t:WeakSet,"%Function.prototype.call%":M,"%Function.prototype.apply%":D,"%Object.defineProperty%":S,"%Object.getPrototypeOf%":N,"%Math.abs%":u,"%Math.floor%":f,"%Math.max%":l,"%Math.min%":p,"%Math.pow%":d,"%Math.round%":m,"%Math.sign%":b,"%Reflect.getPrototypeOf%":$};if(B)try{null.error}catch(oe){var W=B(B(oe));Q["%Error.prototype%"]=W}var K=function oe(ie){var me;if(ie==="%AsyncFunction%")me=A("async function () {}");else if(ie==="%GeneratorFunction%")me=A("function* () {}");else if(ie==="%AsyncGeneratorFunction%")me=A("async function* () {}");else if(ie==="%AsyncGenerator%"){var be=oe("%AsyncGeneratorFunction%");be&&(me=be.prototype)}else if(ie==="%AsyncIteratorPrototype%"){var we=oe("%AsyncGenerator%");we&&B&&(me=B(we.prototype))}return Q[ie]=me,me},re={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},q=Ia(),I=xw(),j=q.call(M,Array.prototype.concat),J=q.call(D,Array.prototype.splice),O=q.call(M,String.prototype.replace),R=q.call(M,String.prototype.slice),F=q.call(M,RegExp.prototype.exec),ne=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,ae=/\\(\\)?/g,le=function(ie){var me=R(ie,0,1),be=R(ie,-1);if(me==="%"&&be!=="%")throw new o("invalid intrinsic syntax, expected closing `%`");if(be==="%"&&me!=="%")throw new o("invalid intrinsic syntax, expected opening `%`");var we=[];return O(ie,ne,function(ke,tt,Oe,Nr){we[we.length]=Oe?O(Nr,ae,"$1"):tt||ke}),we},ue=function(ie,me){var be=ie,we;if(I(re,be)&&(we=re[be],be="%"+we[0]+"%"),I(Q,be)){var ke=Q[be];if(ke===V&&(ke=K(be)),typeof ke>"u"&&!me)throw new a("intrinsic "+ie+" exists, but is not available. Please file an issue!");return{alias:we,name:be,value:ke}}throw new o("intrinsic "+ie+" does not exist!")};return Wf=function(ie,me){if(typeof ie!="string"||ie.length===0)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof me!="boolean")throw new a('"allowMissing" argument must be a boolean');if(F(/^%?[^%]*%?$/,ie)===null)throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var be=le(ie),we=be.length>0?be[0]:"",ke=ue("%"+we+"%",me),tt=ke.name,Oe=ke.value,Nr=!1,ds=ke.alias;ds&&(we=ds[0],J(be,j([0,1],ds)));for(var z=1,Ur=!0;z<be.length;z+=1){var St=be[z],At=R(St,0,1),Rn=R(St,-1);if((At==='"'||At==="'"||At==="`"||Rn==='"'||Rn==="'"||Rn==="`")&&At!==Rn)throw new o("property names with quotes must have matching quotes");if((St==="constructor"||!Ur)&&(Nr=!0),we+="."+St,tt="%"+we+"%",I(Q,tt))Oe=Q[tt];else if(Oe!=null){if(!(St in Oe)){if(!me)throw new a("base intrinsic for "+ie+" exists, but the property is not available.");return}if(P&&z+1>=be.length){var ni=P(Oe,St);Ur=!!ni,Ur&&"get"in ni&&!("originalValue"in ni.get)?Oe=ni.get:Oe=Oe[St]}else Ur=I(Oe,St),Oe=Oe[St];Ur&&!Nr&&(Q[tt]=Oe)}}return Oe},Wf}var Kf,Ty;function Oa(){if(Ty)return Kf;Ty=1;var t=kw(),e=Vh(),r=e([t("%String.prototype.indexOf%")]);return Kf=function(s,i){var o=t(s,!!i);return typeof o=="function"&&r(s,".prototype.")>-1?e([o]):o},Kf}var Zf,_y;function cP(){if(_y)return Zf;_y=1;var t=bu()(),e=Oa(),r=e("Object.prototype.toString"),n=function(a){return t&&a&&typeof a=="object"&&Symbol.toStringTag in a?!1:r(a)==="[object Arguments]"},s=function(a){return n(a)?!0:a!==null&&typeof a=="object"&&"length"in a&&typeof a.length=="number"&&a.length>=0&&r(a)!=="[object Array]"&&"callee"in a&&r(a.callee)==="[object Function]"},i=function(){return n(arguments)}();return n.isLegacyArguments=s,Zf=i?n:s,Zf}var Yf,Py;function uP(){if(Py)return Yf;Py=1;var t=Oa(),e=bu()(),r=xw(),n=Yi(),s;if(e){var i=t("RegExp.prototype.exec"),o={},a=function(){throw o},c={toString:a,valueOf:a};typeof Symbol.toPrimitive=="symbol"&&(c[Symbol.toPrimitive]=a),s=function(p){if(!p||typeof p!="object")return!1;var d=n(p,"lastIndex"),m=d&&r(d,"value");if(!m)return!1;try{i(p,c)}catch(b){return b===o}}}else{var u=t("Object.prototype.toString"),f="[object RegExp]";s=function(p){return!p||typeof p!="object"&&typeof p!="function"?!1:u(p)===f}}return Yf=s,Yf}var Xf,Iy;function fP(){if(Iy)return Xf;Iy=1;var t=Oa(),e=uP(),r=t("RegExp.prototype.exec"),n=Pa();return Xf=function(i){if(!e(i))throw new n("`regex` must be a RegExp");return function(a){return r(i,a)!==null}},Xf}var Jf,Oy;function lP(){if(Oy)return Jf;Oy=1;var t=Oa(),e=fP(),r=e(/^\s*(?:function)?\*/),n=bu()(),s=qh(),i=t("Object.prototype.toString"),o=t("Function.prototype.toString"),a=function(){if(!n)return!1;try{return Function("return function*() {}")()}catch{}},c;return Jf=function(f){if(typeof f!="function")return!1;if(r(o(f)))return!0;if(!n){var l=i(f);return l==="[object GeneratorFunction]"}if(!s)return!1;if(typeof c>"u"){var p=a();c=p?s(p):!1}return s(f)===c},Jf}var Qf,By;function dP(){if(By)return Qf;By=1;var t=Function.prototype.toString,e=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,r,n;if(typeof e=="function"&&typeof Object.defineProperty=="function")try{r=Object.defineProperty({},"length",{get:function(){throw n}}),n={},e(function(){throw 42},null,r)}catch(P){P!==n&&(e=null)}else e=null;var s=/^\s*class\b/,i=function(S){try{var w=t.call(S);return s.test(w)}catch{return!1}},o=function(S){try{return i(S)?!1:(t.call(S),!0)}catch{return!1}},a=Object.prototype.toString,c="[object Object]",u="[object Function]",f="[object GeneratorFunction]",l="[object HTMLAllCollection]",p="[object HTML document.all class]",d="[object HTMLCollection]",m=typeof Symbol=="function"&&!!Symbol.toStringTag,b=!(0 in[,]),E=function(){return!1};if(typeof document=="object"){var A=document.all;a.call(A)===a.call(document.all)&&(E=function(S){if((b||!S)&&(typeof S>"u"||typeof S=="object"))try{var w=a.call(S);return(w===l||w===p||w===d||w===c)&&S("")==null}catch{}return!1})}return Qf=e?function(S){if(E(S))return!0;if(!S||typeof S!="function"&&typeof S!="object")return!1;try{e(S,null,r)}catch(w){if(w!==n)return!1}return!i(S)&&o(S)}:function(S){if(E(S))return!0;if(!S||typeof S!="function"&&typeof S!="object")return!1;if(m)return o(S);if(i(S))return!1;var w=a.call(S);return w!==u&&w!==f&&!/^\[object HTML/.test(w)?!1:o(S)},Qf}var el,Cy;function hP(){if(Cy)return el;Cy=1;var t=dP(),e=Object.prototype.toString,r=Object.prototype.hasOwnProperty,n=function(c,u,f){for(var l=0,p=c.length;l<p;l++)r.call(c,l)&&(f==null?u(c[l],l,c):u.call(f,c[l],l,c))},s=function(c,u,f){for(var l=0,p=c.length;l<p;l++)f==null?u(c.charAt(l),l,c):u.call(f,c.charAt(l),l,c)},i=function(c,u,f){for(var l in c)r.call(c,l)&&(f==null?u(c[l],l,c):u.call(f,c[l],l,c))};function o(a){return e.call(a)==="[object Array]"}return el=function(c,u,f){if(!t(u))throw new TypeError("iterator must be a function");var l;arguments.length>=3&&(l=f),o(c)?n(c,u,l):typeof c=="string"?s(c,u,l):i(c,u,l)},el}var tl,$y;function pP(){return $y||($y=1,tl=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),tl}var rl,Ry;function yP(){if(Ry)return rl;Ry=1;var t=pP(),e=typeof globalThis>"u"?Qr:globalThis;return rl=function(){for(var n=[],s=0;s<t.length;s++)typeof e[t[s]]=="function"&&(n[n.length]=t[s]);return n},rl}var nl={exports:{}},sl,Ny;function mP(){if(Ny)return sl;Ny=1;var t=gu(),e=vw(),r=Pa(),n=Yi();return sl=function(i,o,a){if(!i||typeof i!="object"&&typeof i!="function")throw new r("`obj` must be an object or a function`");if(typeof o!="string"&&typeof o!="symbol")throw new r("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new r("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new r("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new r("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new r("`loose`, if provided, must be a boolean");var c=arguments.length>3?arguments[3]:null,u=arguments.length>4?arguments[4]:null,f=arguments.length>5?arguments[5]:null,l=arguments.length>6?arguments[6]:!1,p=!!n&&n(i,o);if(t)t(i,o,{configurable:f===null&&p?p.configurable:!f,enumerable:c===null&&p?p.enumerable:!c,value:a,writable:u===null&&p?p.writable:!u});else if(l||!c&&!u&&!f)i[o]=a;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},sl}var il,Uy;function bP(){if(Uy)return il;Uy=1;var t=gu(),e=function(){return!!t};return e.hasArrayLengthDefineBug=function(){if(!t)return null;try{return t([],"length",{value:1}).length!==1}catch{return!0}},il=e,il}var ol,My;function gP(){if(My)return ol;My=1;var t=kw(),e=mP(),r=bP()(),n=Yi(),s=Pa(),i=t("%Math.floor%");return ol=function(a,c){if(typeof a!="function")throw new s("`fn` is not a function");if(typeof c!="number"||c<0||c>4294967295||i(c)!==c)throw new s("`length` must be a positive 32-bit integer");var u=arguments.length>2&&!!arguments[2],f=!0,l=!0;if("length"in a&&n){var p=n(a,"length");p&&!p.configurable&&(f=!1),p&&!p.writable&&(l=!1)}return(f||l||!u)&&(r?e(a,"length",c,!0,!0):e(a,"length",c)),a},ol}var al,Fy;function wP(){if(Fy)return al;Fy=1;var t=Ia(),e=zh(),r=Aw();return al=function(){return r(t,e,arguments)},al}var jy;function vP(){return jy||(jy=1,function(t){var e=gP(),r=gu(),n=Vh(),s=wP();t.exports=function(o){var a=n(arguments),c=o.length-(arguments.length-1);return e(a,1+(c>0?c:0),!0)},r?r(t.exports,"apply",{value:s}):t.exports.apply=s}(nl)),nl.exports}var cl,Ly;function Tw(){if(Ly)return cl;Ly=1;var t=hP(),e=yP(),r=vP(),n=Oa(),s=Yi(),i=qh(),o=n("Object.prototype.toString"),a=bu()(),c=typeof globalThis>"u"?Qr:globalThis,u=e(),f=n("String.prototype.slice"),l=n("Array.prototype.indexOf",!0)||function(E,A){for(var P=0;P<E.length;P+=1)if(E[P]===A)return P;return-1},p={__proto__:null};a&&s&&i?t(u,function(b){var E=new c[b];if(Symbol.toStringTag in E&&i){var A=i(E),P=s(A,Symbol.toStringTag);if(!P&&A){var S=i(A);P=s(S,Symbol.toStringTag)}p["$"+b]=r(P.get)}}):t(u,function(b){var E=new c[b],A=E.slice||E.set;A&&(p["$"+b]=r(A))});var d=function(E){var A=!1;return t(p,function(P,S){if(!A)try{"$"+P(E)===S&&(A=f(S,1))}catch{}}),A},m=function(E){var A=!1;return t(p,function(P,S){if(!A)try{P(E),A=f(S,1)}catch{}}),A};return cl=function(E){if(!E||typeof E!="object")return!1;if(!a){var A=f(o(E),8,-1);return l(u,A)>-1?A:A!=="Object"?!1:m(E)}return s?d(E):null},cl}var ul,Dy;function EP(){if(Dy)return ul;Dy=1;var t=Tw();return ul=function(r){return!!t(r)},ul}var Hy;function SP(){return Hy||(Hy=1,function(t){var e=cP(),r=lP(),n=Tw(),s=EP();function i(z){return z.call.bind(z)}var o=typeof BigInt<"u",a=typeof Symbol<"u",c=i(Object.prototype.toString),u=i(Number.prototype.valueOf),f=i(String.prototype.valueOf),l=i(Boolean.prototype.valueOf);if(o)var p=i(BigInt.prototype.valueOf);if(a)var d=i(Symbol.prototype.valueOf);function m(z,Ur){if(typeof z!="object")return!1;try{return Ur(z),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=r,t.isTypedArray=s;function b(z){return typeof Promise<"u"&&z instanceof Promise||z!==null&&typeof z=="object"&&typeof z.then=="function"&&typeof z.catch=="function"}t.isPromise=b;function E(z){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(z):s(z)||R(z)}t.isArrayBufferView=E;function A(z){return n(z)==="Uint8Array"}t.isUint8Array=A;function P(z){return n(z)==="Uint8ClampedArray"}t.isUint8ClampedArray=P;function S(z){return n(z)==="Uint16Array"}t.isUint16Array=S;function w(z){return n(z)==="Uint32Array"}t.isUint32Array=w;function k(z){return n(z)==="Int8Array"}t.isInt8Array=k;function T(z){return n(z)==="Int16Array"}t.isInt16Array=T;function B(z){return n(z)==="Int32Array"}t.isInt32Array=B;function N(z){return n(z)==="Float32Array"}t.isFloat32Array=N;function $(z){return n(z)==="Float64Array"}t.isFloat64Array=$;function D(z){return n(z)==="BigInt64Array"}t.isBigInt64Array=D;function M(z){return n(z)==="BigUint64Array"}t.isBigUint64Array=M;function V(z){return c(z)==="[object Map]"}V.working=typeof Map<"u"&&V(new Map);function G(z){return typeof Map>"u"?!1:V.working?V(z):z instanceof Map}t.isMap=G;function Q(z){return c(z)==="[object Set]"}Q.working=typeof Set<"u"&&Q(new Set);function W(z){return typeof Set>"u"?!1:Q.working?Q(z):z instanceof Set}t.isSet=W;function K(z){return c(z)==="[object WeakMap]"}K.working=typeof WeakMap<"u"&&K(new WeakMap);function re(z){return typeof WeakMap>"u"?!1:K.working?K(z):z instanceof WeakMap}t.isWeakMap=re;function q(z){return c(z)==="[object WeakSet]"}q.working=typeof WeakSet<"u"&&q(new WeakSet);function I(z){return q(z)}t.isWeakSet=I;function j(z){return c(z)==="[object ArrayBuffer]"}j.working=typeof ArrayBuffer<"u"&&j(new ArrayBuffer);function J(z){return typeof ArrayBuffer>"u"?!1:j.working?j(z):z instanceof ArrayBuffer}t.isArrayBuffer=J;function O(z){return c(z)==="[object DataView]"}O.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&O(new DataView(new ArrayBuffer(1),0,1));function R(z){return typeof DataView>"u"?!1:O.working?O(z):z instanceof DataView}t.isDataView=R;var F=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function ne(z){return c(z)==="[object SharedArrayBuffer]"}function ae(z){return typeof F>"u"?!1:(typeof ne.working>"u"&&(ne.working=ne(new F)),ne.working?ne(z):z instanceof F)}t.isSharedArrayBuffer=ae;function le(z){return c(z)==="[object AsyncFunction]"}t.isAsyncFunction=le;function ue(z){return c(z)==="[object Map Iterator]"}t.isMapIterator=ue;function oe(z){return c(z)==="[object Set Iterator]"}t.isSetIterator=oe;function ie(z){return c(z)==="[object Generator]"}t.isGeneratorObject=ie;function me(z){return c(z)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=me;function be(z){return m(z,u)}t.isNumberObject=be;function we(z){return m(z,f)}t.isStringObject=we;function ke(z){return m(z,l)}t.isBooleanObject=ke;function tt(z){return o&&m(z,p)}t.isBigIntObject=tt;function Oe(z){return a&&m(z,d)}t.isSymbolObject=Oe;function Nr(z){return be(z)||we(z)||ke(z)||tt(z)||Oe(z)}t.isBoxedPrimitive=Nr;function ds(z){return typeof Uint8Array<"u"&&(J(z)||ae(z))}t.isAnyArrayBuffer=ds,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(z){Object.defineProperty(t,z,{enumerable:!1,value:function(){throw new Error(z+" is not supported in userland")}})})}(df)),df}var fl,zy;function AP(){return zy||(zy=1,fl=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"}),fl}var Xa={exports:{}},Vy;function xP(){return Vy||(Vy=1,typeof Object.create=="function"?Xa.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Xa.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}),Xa.exports}var qy;function _w(){return qy||(qy=1,function(t){var e=Object.getOwnPropertyDescriptors||function(R){for(var F=Object.keys(R),ne={},ae=0;ae<F.length;ae++)ne[F[ae]]=Object.getOwnPropertyDescriptor(R,F[ae]);return ne},r=/%[sdj%]/g;t.format=function(O){if(!k(O)){for(var R=[],F=0;F<arguments.length;F++)R.push(o(arguments[F]));return R.join(" ")}for(var F=1,ne=arguments,ae=ne.length,le=String(O).replace(r,function(oe){if(oe==="%%")return"%";if(F>=ae)return oe;switch(oe){case"%s":return String(ne[F++]);case"%d":return Number(ne[F++]);case"%j":try{return JSON.stringify(ne[F++])}catch{return"[Circular]"}default:return oe}}),ue=ne[F];F<ae;ue=ne[++F])P(ue)||!$(ue)?le+=" "+ue:le+=" "+o(ue);return le},t.deprecate=function(O,R){if(typeof process<"u"&&process.noDeprecation===!0)return O;if(typeof process>"u")return function(){return t.deprecate(O,R).apply(this,arguments)};var F=!1;function ne(){if(!F){if(process.throwDeprecation)throw new Error(R);process.traceDeprecation?console.trace(R):console.error(R),F=!0}return O.apply(this,arguments)}return ne};var n={},s=/^$/;if(process.env.NODE_DEBUG){var i=process.env.NODE_DEBUG;i=i.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),s=new RegExp("^"+i+"$","i")}t.debuglog=function(O){if(O=O.toUpperCase(),!n[O])if(s.test(O)){var R=process.pid;n[O]=function(){var F=t.format.apply(t,arguments);console.error("%s %d: %s",O,R,F)}}else n[O]=function(){};return n[O]};function o(O,R){var F={seen:[],stylize:c};return arguments.length>=3&&(F.depth=arguments[2]),arguments.length>=4&&(F.colors=arguments[3]),A(R)?F.showHidden=R:R&&t._extend(F,R),B(F.showHidden)&&(F.showHidden=!1),B(F.depth)&&(F.depth=2),B(F.colors)&&(F.colors=!1),B(F.customInspect)&&(F.customInspect=!0),F.colors&&(F.stylize=a),f(F,O,F.depth)}t.inspect=o,o.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},o.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function a(O,R){var F=o.styles[R];return F?"\x1B["+o.colors[F][0]+"m"+O+"\x1B["+o.colors[F][1]+"m":O}function c(O,R){return O}function u(O){var R={};return O.forEach(function(F,ne){R[F]=!0}),R}function f(O,R,F){if(O.customInspect&&R&&V(R.inspect)&&R.inspect!==t.inspect&&!(R.constructor&&R.constructor.prototype===R)){var ne=R.inspect(F,O);return k(ne)||(ne=f(O,ne,F)),ne}var ae=l(O,R);if(ae)return ae;var le=Object.keys(R),ue=u(le);if(O.showHidden&&(le=Object.getOwnPropertyNames(R)),M(R)&&(le.indexOf("message")>=0||le.indexOf("description")>=0))return p(R);if(le.length===0){if(V(R)){var oe=R.name?": "+R.name:"";return O.stylize("[Function"+oe+"]","special")}if(N(R))return O.stylize(RegExp.prototype.toString.call(R),"regexp");if(D(R))return O.stylize(Date.prototype.toString.call(R),"date");if(M(R))return p(R)}var ie="",me=!1,be=["{","}"];if(E(R)&&(me=!0,be=["[","]"]),V(R)){var we=R.name?": "+R.name:"";ie=" [Function"+we+"]"}if(N(R)&&(ie=" "+RegExp.prototype.toString.call(R)),D(R)&&(ie=" "+Date.prototype.toUTCString.call(R)),M(R)&&(ie=" "+p(R)),le.length===0&&(!me||R.length==0))return be[0]+ie+be[1];if(F<0)return N(R)?O.stylize(RegExp.prototype.toString.call(R),"regexp"):O.stylize("[Object]","special");O.seen.push(R);var ke;return me?ke=d(O,R,F,ue,le):ke=le.map(function(tt){return m(O,R,F,ue,tt,me)}),O.seen.pop(),b(ke,ie,be)}function l(O,R){if(B(R))return O.stylize("undefined","undefined");if(k(R)){var F="'"+JSON.stringify(R).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return O.stylize(F,"string")}if(w(R))return O.stylize(""+R,"number");if(A(R))return O.stylize(""+R,"boolean");if(P(R))return O.stylize("null","null")}function p(O){return"["+Error.prototype.toString.call(O)+"]"}function d(O,R,F,ne,ae){for(var le=[],ue=0,oe=R.length;ue<oe;++ue)q(R,String(ue))?le.push(m(O,R,F,ne,String(ue),!0)):le.push("");return ae.forEach(function(ie){ie.match(/^\d+$/)||le.push(m(O,R,F,ne,ie,!0))}),le}function m(O,R,F,ne,ae,le){var ue,oe,ie;if(ie=Object.getOwnPropertyDescriptor(R,ae)||{value:R[ae]},ie.get?ie.set?oe=O.stylize("[Getter/Setter]","special"):oe=O.stylize("[Getter]","special"):ie.set&&(oe=O.stylize("[Setter]","special")),q(ne,ae)||(ue="["+ae+"]"),oe||(O.seen.indexOf(ie.value)<0?(P(F)?oe=f(O,ie.value,null):oe=f(O,ie.value,F-1),oe.indexOf(`
|
|
74
74
|
`)>-1&&(le?oe=oe.split(`
|
|
75
75
|
`).map(function(me){return" "+me}).join(`
|
|
76
76
|
`).slice(2):oe=`
|
|
@@ -79,13 +79,13 @@ ${_5(d)}`),super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessa
|
|
|
79
79
|
`))):oe=O.stylize("[Circular]","special")),B(ue)){if(le&&ae.match(/^\d+$/))return oe;ue=JSON.stringify(""+ae),ue.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(ue=ue.slice(1,-1),ue=O.stylize(ue,"name")):(ue=ue.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),ue=O.stylize(ue,"string"))}return ue+": "+oe}function b(O,R,F){var ne=O.reduce(function(ae,le){return le.indexOf(`
|
|
80
80
|
`)>=0,ae+le.replace(/\u001b\[\d\d?m/g,"").length+1},0);return ne>60?F[0]+(R===""?"":R+`
|
|
81
81
|
`)+" "+O.join(`,
|
|
82
|
-
`)+" "+F[1]:F[0]+R+" "+O.join(", ")+" "+F[1]}t.types=SP();function E(O){return Array.isArray(O)}t.isArray=E;function A(O){return typeof O=="boolean"}t.isBoolean=A;function P(O){return O===null}t.isNull=P;function S(O){return O==null}t.isNullOrUndefined=S;function w(O){return typeof O=="number"}t.isNumber=w;function k(O){return typeof O=="string"}t.isString=k;function T(O){return typeof O=="symbol"}t.isSymbol=T;function B(O){return O===void 0}t.isUndefined=B;function U(O){return $(O)&&Q(O)==="[object RegExp]"}t.isRegExp=U,t.types.isRegExp=U;function $(O){return typeof O=="object"&&O!==null}t.isObject=$;function D(O){return $(O)&&Q(O)==="[object Date]"}t.isDate=D,t.types.isDate=D;function M(O){return $(O)&&(Q(O)==="[object Error]"||O instanceof Error)}t.isError=M,t.types.isNativeError=M;function q(O){return typeof O=="function"}t.isFunction=q;function K(O){return O===null||typeof O=="boolean"||typeof O=="number"||typeof O=="string"||typeof O=="symbol"||typeof O>"u"}t.isPrimitive=K,t.isBuffer=AP();function Q(O){return Object.prototype.toString.call(O)}function G(O){return O<10?"0"+O.toString(10):O.toString(10)}var W=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ee(){var O=new Date,R=[G(O.getHours()),G(O.getMinutes()),G(O.getSeconds())].join(":");return[O.getDate(),W[O.getMonth()],R].join(" ")}t.log=function(){console.log("%s - %s",ee(),t.format.apply(t,arguments))},t.inherits=xP(),t._extend=function(O,R){if(!R||!$(R))return O;for(var F=Object.keys(R),ne=F.length;ne--;)O[F[ne]]=R[F[ne]];return O};function H(O,R){return Object.prototype.hasOwnProperty.call(O,R)}var I=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;t.promisify=function(R){if(typeof R!="function")throw new TypeError('The "original" argument must be of type Function');if(I&&R[I]){var F=R[I];if(typeof F!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(F,I,{value:F,enumerable:!1,writable:!1,configurable:!0}),F}function F(){for(var ne,ae,le=new Promise(function(ie,me){ne=ie,ae=me}),ue=[],oe=0;oe<arguments.length;oe++)ue.push(arguments[oe]);ue.push(function(ie,me){ie?ae(ie):ne(me)});try{R.apply(this,ue)}catch(ie){ae(ie)}return le}return Object.setPrototypeOf(F,Object.getPrototypeOf(R)),I&&Object.defineProperty(F,I,{value:F,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(F,e(R))},t.promisify.custom=I;function j(O,R){if(!O){var F=new Error("Promise was rejected with a falsy value");F.reason=O,O=F}return R(O)}function J(O){if(typeof O!="function")throw new TypeError('The "original" argument must be of type Function');function R(){for(var F=[],ne=0;ne<arguments.length;ne++)F.push(arguments[ne]);var ae=F.pop();if(typeof ae!="function")throw new TypeError("The last argument must be of type Function");var le=this,ue=function(){return ae.apply(le,arguments)};O.apply(this,F).then(function(oe){process.nextTick(ue.bind(null,null,oe))},function(oe){process.nextTick(j.bind(null,oe,ue))})}return Object.setPrototypeOf(R,Object.getPrototypeOf(O)),Object.defineProperties(R,e(O)),R}t.callbackify=J}(uf)),uf}Object.defineProperty(pu,"__esModule",{value:!0});pu.decode=kP;pu.encode=TP;const Pw=qs;function kP(t){return(Pw.isBrowser?new TextDecoder("utf-8"):new(_w()).TextDecoder("utf-8")).decode(t)}function TP(t){return(Pw.isBrowser?new TextEncoder:new(_w()).TextEncoder("utf-8")).encode(t)}var bu={},bd={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(t,e){var r=Qs,n=r.Buffer;function s(o,a){for(var c in o)a[c]=o[c]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(s(r,e),e.Buffer=i);function i(o,a,c){return n(o,a,c)}i.prototype=Object.create(n.prototype),s(n,i),i.from=function(o,a,c){if(typeof o=="number")throw new TypeError("Argument must not be a number");return n(o,a,c)},i.alloc=function(o,a,c){if(typeof o!="number")throw new TypeError("Argument must be a number");var u=n(o);return a!==void 0?typeof c=="string"?u.fill(a,c):u.fill(a):u.fill(0),u},i.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return n(o)},i.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(o)}})(bd,bd.exports);var _P=bd.exports,Ja=_P.Buffer;function PP(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r<e.length;r++)e[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=n}var o=t.length,a=t.charAt(0),c=Math.log(o)/Math.log(256),u=Math.log(256)/Math.log(o);function f(d){if((Array.isArray(d)||d instanceof Uint8Array)&&(d=Ja.from(d)),!Ja.isBuffer(d))throw new TypeError("Expected Buffer");if(d.length===0)return"";for(var m=0,b=0,E=0,A=d.length;E!==A&&d[E]===0;)E++,m++;for(var P=(A-E)*u+1>>>0,S=new Uint8Array(P);E!==A;){for(var w=d[E],k=0,T=P-1;(w!==0||k<b)&&T!==-1;T--,k++)w+=256*S[T]>>>0,S[T]=w%o>>>0,w=w/o>>>0;if(w!==0)throw new Error("Non-zero carry");b=k,E++}for(var B=P-b;B!==P&&S[B]===0;)B++;for(var U=a.repeat(m);B<P;++B)U+=t.charAt(S[B]);return U}function l(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return Ja.alloc(0);for(var m=0,b=0,E=0;d[m]===a;)b++,m++;for(var A=(d.length-m)*c+1>>>0,P=new Uint8Array(A);m<d.length;){var S=d.charCodeAt(m);if(S>255)return;var w=e[S];if(w===255)return;for(var k=0,T=A-1;(w!==0||k<E)&&T!==-1;T--,k++)w+=o*P[T]>>>0,P[T]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");E=k,m++}for(var B=A-E;B!==A&&P[B]===0;)B++;var U=Ja.allocUnsafe(b+(A-B));U.fill(0,0,b);for(var $=b;B!==A;)U[$++]=P[B++];return U}function p(d){var m=l(d);if(m)return m;throw new Error("Non-base"+o+" character")}return{encode:f,decodeUnsafe:l,decode:p}}var IP=PP,OP=IP,BP="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",CP=OP(BP),$P=Qr&&Qr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(bu,"__esModule",{value:!0});bu.encode=RP;bu.decode=NP;const Iw=$P(CP);function RP(t){return Iw.default.encode(t)}function NP(t){return Iw.default.decode(t)}var gu={};Object.defineProperty(gu,"__esModule",{value:!0});gu.encode=MP;gu.decode=FP;const UP=Qs;function MP(t){return t.toString("base64")}function FP(t){return UP.Buffer.from(t,"base64")}var jP=Qr&&Qr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),LP=Qr&&Qr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),wu=Qr&&Qr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&jP(e,t,r);return LP(e,t),e};Object.defineProperty(wn,"__esModule",{value:!0});wn.base64=wn.bs58=wn.utf8=Ow=wn.hex=void 0;var Ow=wn.hex=wu(hu);wn.utf8=wu(pu);wn.bs58=wu(bu);wn.base64=wu(gu);class es{constructor(e,r,n,s,i){try{this.swapId=Array.from(Buffer.from(e,"hex")),this.secretHash=Array.from(Buffer.from(n,"hex"))}catch(o){throw new Error("Error decoding swapId or secretHash",{cause:o})}if(this.secretHash.length!=32||this.swapId.length!=32)throw new Error("swapId or secretHash must be exactly 32 bits in size");try{this.redeemer=new Vt.web3.PublicKey(r)}catch(o){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:o})}try{this.amount=new Vt.BN(s.toString(10),10),this.expiresIn=new Vt.BN(i)}catch(o){throw new Error("Error decoding amount. Invalid value for amount",{cause:o})}if(!(Number.isInteger(i)&&i>0))throw new Error("expiresIn must be a positive integer.")}static from(e){let r;if(e.source_swap.chain.includes("solana"))r=e.source_swap;else if(e.destination_swap.chain.includes("solana"))r=e.destination_swap;else throw new Error("Expected source_swap or destination_swap to be one of 'solana', 'solana_localnet', 'solana_devnet'");const{swap_id:n,redeemer:s,secret_hash:i,timelock:o}=r,a=BigInt(r.amount);return new es(n,s,i,a,o)}}function Bw(t){let e;try{e=[...Ow.decode(t)]}catch(r){throw new Error("Error decoding secret. Ensure it is a hex string",{cause:r})}if(e.length!=32)throw new Error("Invalid Secret size. Expected 32 bytes, got "+e.length);return e}class Cw{constructor(e,r,n,s,i){var l,p;if(this.provider=e,this.url=r,!e)throw new Error("Provider is required");if(!r)throw new Error("Endpoint URL is required");if(n==null)throw new Error("Network is required");const o=n===g.Network.MAINNET?ad.mainnet:ad.staging,a={native:((l=i==null?void 0:i.programAddress)==null?void 0:l.native)??o.native,spl:((p=i==null?void 0:i.programAddress)==null?void 0:p.spl)??o.spl},c=(i==null?void 0:i.relayer)??T1[n];try{this.relayer=new Vt.web3.PublicKey(c),this.auth=s}catch(d){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:d})}const u=a.spl?{...H0,metadata:{...H0.metadata??{}},address:a.spl}:void 0,f=a.native?{...md,metadata:{...md.metadata??{}},address:a.native}:void 0;try{this.splProgram=u?new Vt.Program(u,this.provider):void 0,this.nativeProgram=f?new Vt.Program(f,this.provider):void 0}catch(d){throw new Error("Error creating Program instances. Ensure the IDLs and provider are correct.",{cause:d})}}get htlcActorAddress(){if(!this.provider.publicKey)throw new Error("No provider public key found");return this.provider.publicKey.toBase58()}async initiate(e){if(!e)return g.Err("Order is required");if(X.isSolanaOrderResponse(e))return this.initiateWithCreateOrderResponse(e);try{const r=X.ChainAsset.fromString(e.source_swap.asset);return X.isSolanaNativeToken(r.chain,r.symbol)?this.nativeProgram?await this.initiateNativeSwap(e):g.Err("Native program is not initialized"):this.splProgram?await this.initiateSplSwap(e):g.Err("SPL program is not initialized")}catch(r){return g.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async sendSplViaRelayer(e,r){try{e.recentBlockhash=(await this.provider.connection.getLatestBlockhash()).blockhash,e.feePayer=this.relayer;const s=(await this.provider.wallet.signTransaction(e)).serialize({requireAllSignatures:!1}).toString("base64"),i=await g.Fetcher.post(this.url.endpoint("/initiate"),{body:JSON.stringify({order_id:r,serialized_tx:s}),headers:{"Content-Type":"application/json"}});return i.error||!i.result?g.Err(`Error from Relayer: ${i.error}`):await Da(this.provider.connection,i.result)?g.Ok(i.result):g.Err("Relayer: Failed to Initiate swap, confirmation timed out")}catch(n){return g.Err(`Failed to send SPL transaction: ${n instanceof Error?n.message:String(n)}`)}}async initiateViaHTLC(e,r){if(!r)return g.Err("Order is required");try{const n=await this.provider.sendAndConfirm(e);return n?await Da(this.provider.connection,n)?g.Ok(n):g.Err("HTLC: Failed to Initiate swap, confirmation timed out"):g.Err("Failed to initiate HTLC transaction")}catch(n){return g.Err(`Error initiating swap: ${n instanceof Error?n.message:String(n)}`)}}async initiateSplSwap(e){if(!this.splProgram)return g.Err("SPL program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=es.from(e),o=this.splProgram.methods.initiate(i,r,n,s,null),a=await Ph(e.source_swap.asset,this.url);if(!a.ok)return g.Err(a.error);const{tokenAddress:c}=a.val,u=new Vt.web3.PublicKey(c),f={initiator:this.provider.publicKey,mint:u,initiatorTokenAccount:u6.getAssociatedTokenAddressSync(u,this.provider.publicKey),sponsor:this.relayer},l=await o.accounts(f).transaction();return this.sendSplViaRelayer(l,e.order_id)}catch(r){return g.Err(`Error initiating SPL swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateNativeSwap(e){if(!this.nativeProgram)return g.Err("Native program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=es.from(e),o=await this.nativeProgram.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction();return this.initiateViaHTLC(o,e)}catch(r){return g.Err(`Error initiating native swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateWithCreateOrderResponse(e){if(!this.relayer)return g.Err("No relayer address");const{versioned_tx:r,versioned_tx_gasless:n}=e;if(n===null)try{const i=Buffer.from(r,"base64"),o=Vt.web3.VersionedTransaction.deserialize(i),a=await this.provider.sendAndConfirm(o);return await Da(this.provider.connection,a)?g.Ok(a):g.Err("Failed to initiate HTLC transaction")}catch(i){return g.Err(`Error in non-gasless flow: ${i}`)}const s=await this.auth.getAuthHeaders();if(!s.ok)return g.Err(s.error);try{const i=Vt.web3.VersionedTransaction.deserialize(Buffer.from(n,"base64")),o=await this.provider.wallet.signTransaction(i);if(!o.signatures[0])return g.Err("No signature found after signing transaction");const c=Buffer.from(o.serialize()).toString("base64"),u=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:c}),headers:{...s.val,"Content-Type":"application/json"}});return u.error?g.Err(`Initiate: Error from relayer: ${u.error}`):u.result?g.Ok(u.result):g.Err("Initiate: No transaction hash returned from relayer")}catch(i){return g.Err(`Error initiating with create order response: ${i}`)}}async redeem(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return g.Err(n.error);const s=Bw(r),i=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:Buffer.from(s).toString("hex")}),headers:{...n.val,"Content-Type":"application/json"}});if(i.error||!i.result)return g.Err(`Redeem: Error from relayer: ${i.error}`);const o=i.result;return await Da(this.provider.connection,o)?g.Ok(o):g.Err("Redeem: Timed out waiting for confirmation")}catch(n){return console.error("Redeem: Caught exception:",n),g.Err(`Error redeeming: ${n}`)}}async refund(){return g.Err("Refund is automatically handled by the relayer.")}}const $w="1.38.0",DP="1.57.0",HP={"-32700":"ParseError","-32701":"OversizedRequest","-32702":"OversizedResponse","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError","-32604":"ServerBusy","-32000":"CallExecutionFailed","-32001":"UnknownError","-32003":"SubscriptionClosed","-32004":"SubscriptionClosedWithError","-32005":"BatchesNotSupported","-32006":"TooManySubscriptions","-32050":"TransientError","-32002":"TransactionExecutionClientError"};class Rw extends Error{}class Nw extends Rw{constructor(e,r){super(e),this.code=r,this.type=HP[r]??"ServerError"}}class zP extends Rw{constructor(e,r,n){super(e),this.status=r,this.statusText=n}}var Uw=t=>{throw TypeError(t)},qh=(t,e,r)=>e.has(t)||Uw("Cannot "+r),Me=(t,e,r)=>(qh(t,e,"read from private field"),r?r.call(t):e.get(t)),ms=(t,e,r)=>e.has(t)?Uw("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Pi=(t,e,r,n)=>(qh(t,e,"write to private field"),e.set(t,r),r),Mw=(t,e,r)=>(qh(t,e,"access private method"),r),VP=(t,e,r,n)=>({set _(s){Pi(t,e,s)},get _(){return Me(t,e,n)}}),Gn,Ao,yn,Ss,ra,As,Ac,Fw,jw;function qP(t){const e=new URL(t);return e.protocol=e.protocol.replace("http","ws"),e.toString()}const GP={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5};class WP{constructor(e,r={}){if(ms(this,Ac),ms(this,Gn,0),ms(this,Ao,0),ms(this,yn,null),ms(this,Ss,null),ms(this,ra,new Set),ms(this,As,new Map),this.endpoint=e,this.options={...GP,...r},!this.options.WebSocketConstructor)throw new Error("Missing WebSocket constructor");this.endpoint.startsWith("http")&&(this.endpoint=qP(this.endpoint))}async makeRequest(e,r,n){const s=await Mw(this,Ac,Fw).call(this);return new Promise((i,o)=>{Pi(this,Gn,Me(this,Gn)+1),Me(this,As).set(Me(this,Gn),{resolve:i,reject:o,timeout:setTimeout(()=>{Me(this,As).delete(Me(this,Gn)),o(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n==null||n.addEventListener("abort",()=>{Me(this,As).delete(Me(this,Gn)),o(n.reason)}),s.send(JSON.stringify({jsonrpc:"2.0",id:Me(this,Gn),method:e,params:r}))}).then(({error:i,result:o})=>{if(i)throw new Nw(i.message,i.code);return o})}async subscribe(e){const r=new KP(e);return Me(this,ra).add(r),await r.subscribe(this),()=>r.unsubscribe(this)}}Gn=new WeakMap;Ao=new WeakMap;yn=new WeakMap;Ss=new WeakMap;ra=new WeakMap;As=new WeakMap;Ac=new WeakSet;Fw=function(){return Me(this,Ss)?Me(this,Ss):(Pi(this,Ss,new Promise(t=>{var e;(e=Me(this,yn))==null||e.close(),Pi(this,yn,new this.options.WebSocketConstructor(this.endpoint)),Me(this,yn).addEventListener("open",()=>{Pi(this,Ao,0),t(Me(this,yn))}),Me(this,yn).addEventListener("close",()=>{VP(this,Ao)._++,Me(this,Ao)<=this.options.maxReconnects&&setTimeout(()=>{Mw(this,Ac,jw).call(this)},this.options.reconnectTimeout)}),Me(this,yn).addEventListener("message",({data:r})=>{let n;try{n=JSON.parse(r)}catch(s){console.error(new Error(`Failed to parse RPC message: ${r}`,{cause:s}));return}if("id"in n&&n.id!=null&&Me(this,As).has(n.id)){const{resolve:s,timeout:i}=Me(this,As).get(n.id);clearTimeout(i),s(n)}else if("params"in n){const{params:s}=n;Me(this,ra).forEach(i=>{i.subscriptionId===s.subscription&&s.subscription===i.subscriptionId&&i.onMessage(s.result)})}})})),Me(this,Ss))};jw=async function(){var t;return(t=Me(this,yn))==null||t.close(),Pi(this,Ss,null),Promise.allSettled([...Me(this,ra)].map(e=>e.subscribe(this)))};class KP{constructor(e){this.subscriptionId=null,this.subscribed=!1,this.input=e}onMessage(e){this.subscribed&&this.input.onMessage(e)}async unsubscribe(e){const{subscriptionId:r}=this;return this.subscribed=!1,r==null?!1:(this.subscriptionId=null,e.makeRequest(this.input.unsubscribe,[r]))}async subscribe(e){this.subscriptionId=null,this.subscribed=!0;const r=await e.makeRequest(this.input.method,this.input.params,this.input.signal);this.subscribed&&(this.subscriptionId=r)}}var Lw=t=>{throw TypeError(t)},Gh=(t,e,r)=>e.has(t)||Lw("Cannot "+r),ar=(t,e,r)=>(Gh(t,e,"read from private field"),r?r.call(t):e.get(t)),Qa=(t,e,r)=>e.has(t)?Lw("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),gd=(t,e,r,n)=>(Gh(t,e,"write to private field"),e.set(t,r),r),ZP=(t,e,r)=>(Gh(t,e,"access private method"),r),bo,gr,xo,wd,Dw;class YP{constructor(e){Qa(this,wd),Qa(this,bo,0),Qa(this,gr),Qa(this,xo),gd(this,gr,e)}fetch(e,r){const n=ar(this,gr).fetch??fetch;if(!n)throw new Error("The current environment does not support fetch, you can provide a fetch implementation in the options for SuiHTTPTransport.");return n(e,r)}async request(e){var s,i;gd(this,bo,ar(this,bo)+1);const r=await this.fetch(((s=ar(this,gr).rpc)==null?void 0:s.url)??ar(this,gr).url,{method:"POST",signal:e.signal,headers:{"Content-Type":"application/json","Client-Sdk-Type":"typescript","Client-Sdk-Version":$w,"Client-Target-Api-Version":DP,"Client-Request-Method":e.method,...(i=ar(this,gr).rpc)==null?void 0:i.headers},body:JSON.stringify({jsonrpc:"2.0",id:ar(this,bo),method:e.method,params:e.params})});if(!r.ok)throw new zP(`Unexpected status code: ${r.status}`,r.status,r.statusText);const n=await r.json();if("error"in n&&n.error!=null)throw new Nw(n.error.message,n.error.code);return n.result}async subscribe(e){const r=await ZP(this,wd,Dw).call(this).subscribe(e);return e.signal&&(e.signal.throwIfAborted(),e.signal.addEventListener("abort",()=>{r()})),async()=>!!await r()}}bo=new WeakMap;gr=new WeakMap;xo=new WeakMap;wd=new WeakSet;Dw=function(){var t;if(!ar(this,xo)){const e=ar(this,gr).WebSocketConstructor??WebSocket;if(!e)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");gd(this,xo,new WP(((t=ar(this,gr).websocket)==null?void 0:t.url)??ar(this,gr).url,{WebSocketConstructor:e,...ar(this,gr).websocket}))}return ar(this,xo)};function qy(t){switch(t){case"mainnet":return"https://fullnode.mainnet.sui.io:443";case"testnet":return"https://fullnode.testnet.sui.io:443";case"devnet":return"https://fullnode.devnet.sui.io:443";case"localnet":return"http://127.0.0.1:9000";default:throw new Error(`Unknown network: ${t}`)}}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function XP(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Hw(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function vd(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function zw(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Ed(t){if(!Array.isArray(t))throw new Error("array expected")}function Vw(t,e){if(!Hw(!0,e))throw new Error(`${t}: array of strings expected`)}function JP(t,e){if(!Hw(!1,e))throw new Error(`${t}: array of numbers expected`)}function QP(...t){const e=i=>i,r=(i,o)=>a=>i(o(a)),n=t.map(i=>i.encode).reduceRight(r,e),s=t.map(i=>i.decode).reduce(r,e);return{encode:n,decode:s}}function eI(t){const e=typeof t=="string"?t.split(""):t,r=e.length;Vw("alphabet",e);const n=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(Ed(s),s.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${t}`);return e[i]})),decode:s=>(Ed(s),s.map(i=>{vd("alphabet.decode",i);const o=n.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${t}`);return o}))}}function tI(t=""){return vd("join",t),{encode:e=>(Vw("join.decode",e),e.join(t)),decode:e=>(vd("join.decode",e),e.split(t))}}function Gy(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(Ed(t),!t.length)return[];let n=0;const s=[],i=Array.from(t,a=>{if(zw(a),a<0||a>=e)throw new Error(`invalid integer: ${a}`);return a}),o=i.length;for(;;){let a=0,c=!0;for(let u=n;u<o;u++){const f=i[u],l=e*a,p=l+f;if(!Number.isSafeInteger(p)||l/e!==a||p-f!==l)throw new Error("convertRadix: carry overflow");const d=p/r;a=p%r;const m=Math.floor(d);if(i[u]=m,!Number.isSafeInteger(m)||m*r+a!==p)throw new Error("convertRadix: carry overflow");if(c)m?c=!1:n=u;else continue}if(s.push(a),c)break}for(let a=0;a<t.length-1&&t[a]===0;a++)s.push(0);return s.reverse()}function rI(t){zw(t);const e=2**8;return{encode:r=>{if(!XP(r))throw new Error("radix.encode input should be Uint8Array");return Gy(Array.from(r),e,t)},decode:r=>(JP("radix.decode",r),Uint8Array.from(Gy(r,t,e)))}}const nI=t=>QP(rI(58),eI(t),tI("")),qw=nI("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),vu=t=>qw.encode(t),na=t=>qw.decode(t);function Gt(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}const ul=8192;function wt(t){if(t.length<ul)return btoa(String.fromCharCode(...t));let e="";for(var r=0;r<t.length;r+=ul){const n=t.slice(r,r+ul);e+=String.fromCharCode(...n)}return btoa(e)}function Gw(t){var s;const e=t.startsWith("0x")?t.slice(2):t,r=e.length%2===0?e:`0${e}`,n=((s=r.match(/[0-9a-fA-F]{2}/g))==null?void 0:s.map(i=>parseInt(i,16)))??[];if(n.length!==r.length/2)throw new Error(`Invalid hex string ${t}`);return Uint8Array.from(n)}function ji(t){return t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),"")}function Eu(t,e){return Array.from({length:Math.ceil(t.length/e)},(r,n)=>t.slice(n*e,(n+1)*e))}class Ww{constructor(e,r){if(typeof e!="function")throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but got: ${e}.`);this._batchLoadFn=e,this._maxBatchSize=aI(r),this._batchScheduleFn=cI(r),this._cacheKeyFn=uI(r),this._cacheMap=fI(r),this._batch=null,this.name=lI(r)}load(e){if(e==null)throw new TypeError(`The loader.load() function must be called with a value, but got: ${String(e)}.`);const r=iI(this),n=this._cacheMap;let s;if(n){s=this._cacheKeyFn(e);const o=n.get(s);if(o){const a=r.cacheHits||(r.cacheHits=[]);return new Promise(c=>{a.push(()=>{c(o)})})}}r.keys.push(e);const i=new Promise((o,a)=>{r.callbacks.push({resolve:o,reject:a})});return n&&n.set(s,i),i}loadMany(e){if(!Kw(e))throw new TypeError(`The loader.loadMany() function must be called with Array<key>, but got: ${e}.`);const r=[];for(let n=0;n<e.length;n++)r.push(this.load(e[n]).catch(s=>s));return Promise.all(r)}clear(e){const r=this._cacheMap;if(r){const n=this._cacheKeyFn(e);r.delete(n)}return this}clearAll(){const e=this._cacheMap;return e&&e.clear(),this}prime(e,r){const n=this._cacheMap;if(n){const s=this._cacheKeyFn(e);if(n.get(s)===void 0){let i;r instanceof Error?(i=Promise.reject(r),i.catch(()=>{})):i=Promise.resolve(r),n.set(s,i)}}return this}}const sI=typeof process=="object"&&typeof process.nextTick=="function"?function(t){fl||(fl=Promise.resolve()),fl.then(()=>{process.nextTick(t)})}:typeof setImmediate=="function"?function(t){setImmediate(t)}:function(t){setTimeout(t)};let fl;function iI(t){const e=t._batch;if(e!==null&&!e.hasDispatched&&e.keys.length<t._maxBatchSize)return e;const r={hasDispatched:!1,keys:[],callbacks:[]};return t._batch=r,t._batchScheduleFn(()=>{oI(t,r)}),r}function oI(t,e){if(e.hasDispatched=!0,e.keys.length===0){Sd(e);return}let r;try{r=t._batchLoadFn(e.keys)}catch(n){return ll(t,e,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function errored synchronously: ${String(n)}.`))}if(!r||typeof r.then!="function")return ll(t,e,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise: ${String(r)}.`));Promise.resolve(r).then(n=>{if(!Kw(n))throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array: ${String(n)}.`);if(n.length!==e.keys.length)throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys.
|
|
82
|
+
`)+" "+F[1]:F[0]+R+" "+O.join(", ")+" "+F[1]}t.types=SP();function E(O){return Array.isArray(O)}t.isArray=E;function A(O){return typeof O=="boolean"}t.isBoolean=A;function P(O){return O===null}t.isNull=P;function S(O){return O==null}t.isNullOrUndefined=S;function w(O){return typeof O=="number"}t.isNumber=w;function k(O){return typeof O=="string"}t.isString=k;function T(O){return typeof O=="symbol"}t.isSymbol=T;function B(O){return O===void 0}t.isUndefined=B;function N(O){return $(O)&&Q(O)==="[object RegExp]"}t.isRegExp=N,t.types.isRegExp=N;function $(O){return typeof O=="object"&&O!==null}t.isObject=$;function D(O){return $(O)&&Q(O)==="[object Date]"}t.isDate=D,t.types.isDate=D;function M(O){return $(O)&&(Q(O)==="[object Error]"||O instanceof Error)}t.isError=M,t.types.isNativeError=M;function V(O){return typeof O=="function"}t.isFunction=V;function G(O){return O===null||typeof O=="boolean"||typeof O=="number"||typeof O=="string"||typeof O=="symbol"||typeof O>"u"}t.isPrimitive=G,t.isBuffer=AP();function Q(O){return Object.prototype.toString.call(O)}function W(O){return O<10?"0"+O.toString(10):O.toString(10)}var K=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function re(){var O=new Date,R=[W(O.getHours()),W(O.getMinutes()),W(O.getSeconds())].join(":");return[O.getDate(),K[O.getMonth()],R].join(" ")}t.log=function(){console.log("%s - %s",re(),t.format.apply(t,arguments))},t.inherits=xP(),t._extend=function(O,R){if(!R||!$(R))return O;for(var F=Object.keys(R),ne=F.length;ne--;)O[F[ne]]=R[F[ne]];return O};function q(O,R){return Object.prototype.hasOwnProperty.call(O,R)}var I=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;t.promisify=function(R){if(typeof R!="function")throw new TypeError('The "original" argument must be of type Function');if(I&&R[I]){var F=R[I];if(typeof F!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(F,I,{value:F,enumerable:!1,writable:!1,configurable:!0}),F}function F(){for(var ne,ae,le=new Promise(function(ie,me){ne=ie,ae=me}),ue=[],oe=0;oe<arguments.length;oe++)ue.push(arguments[oe]);ue.push(function(ie,me){ie?ae(ie):ne(me)});try{R.apply(this,ue)}catch(ie){ae(ie)}return le}return Object.setPrototypeOf(F,Object.getPrototypeOf(R)),I&&Object.defineProperty(F,I,{value:F,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(F,e(R))},t.promisify.custom=I;function j(O,R){if(!O){var F=new Error("Promise was rejected with a falsy value");F.reason=O,O=F}return R(O)}function J(O){if(typeof O!="function")throw new TypeError('The "original" argument must be of type Function');function R(){for(var F=[],ne=0;ne<arguments.length;ne++)F.push(arguments[ne]);var ae=F.pop();if(typeof ae!="function")throw new TypeError("The last argument must be of type Function");var le=this,ue=function(){return ae.apply(le,arguments)};O.apply(this,F).then(function(oe){process.nextTick(ue.bind(null,null,oe))},function(oe){process.nextTick(j.bind(null,oe,ue))})}return Object.setPrototypeOf(R,Object.getPrototypeOf(O)),Object.defineProperties(R,e(O)),R}t.callbackify=J}(lf)),lf}Object.defineProperty(mu,"__esModule",{value:!0});mu.decode=kP;mu.encode=TP;const Pw=qs;function kP(t){return(Pw.isBrowser?new TextDecoder("utf-8"):new(_w()).TextDecoder("utf-8")).decode(t)}function TP(t){return(Pw.isBrowser?new TextEncoder:new(_w()).TextEncoder("utf-8")).encode(t)}var wu={},gd={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(t,e){var r=Qs,n=r.Buffer;function s(o,a){for(var c in o)a[c]=o[c]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(s(r,e),e.Buffer=i);function i(o,a,c){return n(o,a,c)}i.prototype=Object.create(n.prototype),s(n,i),i.from=function(o,a,c){if(typeof o=="number")throw new TypeError("Argument must not be a number");return n(o,a,c)},i.alloc=function(o,a,c){if(typeof o!="number")throw new TypeError("Argument must be a number");var u=n(o);return a!==void 0?typeof c=="string"?u.fill(a,c):u.fill(a):u.fill(0),u},i.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return n(o)},i.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(o)}})(gd,gd.exports);var _P=gd.exports,Ja=_P.Buffer;function PP(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r<e.length;r++)e[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=n}var o=t.length,a=t.charAt(0),c=Math.log(o)/Math.log(256),u=Math.log(256)/Math.log(o);function f(d){if((Array.isArray(d)||d instanceof Uint8Array)&&(d=Ja.from(d)),!Ja.isBuffer(d))throw new TypeError("Expected Buffer");if(d.length===0)return"";for(var m=0,b=0,E=0,A=d.length;E!==A&&d[E]===0;)E++,m++;for(var P=(A-E)*u+1>>>0,S=new Uint8Array(P);E!==A;){for(var w=d[E],k=0,T=P-1;(w!==0||k<b)&&T!==-1;T--,k++)w+=256*S[T]>>>0,S[T]=w%o>>>0,w=w/o>>>0;if(w!==0)throw new Error("Non-zero carry");b=k,E++}for(var B=P-b;B!==P&&S[B]===0;)B++;for(var N=a.repeat(m);B<P;++B)N+=t.charAt(S[B]);return N}function l(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return Ja.alloc(0);for(var m=0,b=0,E=0;d[m]===a;)b++,m++;for(var A=(d.length-m)*c+1>>>0,P=new Uint8Array(A);m<d.length;){var S=d.charCodeAt(m);if(S>255)return;var w=e[S];if(w===255)return;for(var k=0,T=A-1;(w!==0||k<E)&&T!==-1;T--,k++)w+=o*P[T]>>>0,P[T]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");E=k,m++}for(var B=A-E;B!==A&&P[B]===0;)B++;var N=Ja.allocUnsafe(b+(A-B));N.fill(0,0,b);for(var $=b;B!==A;)N[$++]=P[B++];return N}function p(d){var m=l(d);if(m)return m;throw new Error("Non-base"+o+" character")}return{encode:f,decodeUnsafe:l,decode:p}}var IP=PP,OP=IP,BP="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",CP=OP(BP),$P=Qr&&Qr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(wu,"__esModule",{value:!0});wu.encode=RP;wu.decode=NP;const Iw=$P(CP);function RP(t){return Iw.default.encode(t)}function NP(t){return Iw.default.decode(t)}var vu={};Object.defineProperty(vu,"__esModule",{value:!0});vu.encode=MP;vu.decode=FP;const UP=Qs;function MP(t){return t.toString("base64")}function FP(t){return UP.Buffer.from(t,"base64")}var jP=Qr&&Qr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),LP=Qr&&Qr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Eu=Qr&&Qr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&jP(e,t,r);return LP(e,t),e};Object.defineProperty(wn,"__esModule",{value:!0});wn.base64=wn.bs58=wn.utf8=Ow=wn.hex=void 0;var Ow=wn.hex=Eu(yu);wn.utf8=Eu(mu);wn.bs58=Eu(wu);wn.base64=Eu(vu);class es{constructor(e,r,n,s,i){try{this.swapId=Array.from(Buffer.from(e,"hex")),this.secretHash=Array.from(Buffer.from(n,"hex"))}catch(o){throw new Error("Error decoding swapId or secretHash",{cause:o})}if(this.secretHash.length!=32||this.swapId.length!=32)throw new Error("swapId or secretHash must be exactly 32 bits in size");try{this.redeemer=new Vt.web3.PublicKey(r)}catch(o){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:o})}try{this.amount=new Vt.BN(s.toString(10),10),this.expiresIn=new Vt.BN(i)}catch(o){throw new Error("Error decoding amount. Invalid value for amount",{cause:o})}if(!(Number.isInteger(i)&&i>0))throw new Error("expiresIn must be a positive integer.")}static from(e){let r;if(e.source_swap.chain.includes("solana"))r=e.source_swap;else if(e.destination_swap.chain.includes("solana"))r=e.destination_swap;else throw new Error("Expected source_swap or destination_swap to be one of 'solana', 'solana_localnet', 'solana_devnet'");const{swap_id:n,redeemer:s,secret_hash:i,timelock:o}=r,a=BigInt(r.amount);return new es(n,s,i,a,o)}}function Bw(t){let e;try{e=[...Ow.decode(t)]}catch(r){throw new Error("Error decoding secret. Ensure it is a hex string",{cause:r})}if(e.length!=32)throw new Error("Invalid Secret size. Expected 32 bytes, got "+e.length);return e}class Cw{constructor(e,r,n,s,i){var l,p;if(this.provider=e,this.url=r,!e)throw new Error("Provider is required");if(!r)throw new Error("Endpoint URL is required");if(n==null)throw new Error("Network is required");const o=n===g.Network.MAINNET?cd.mainnet:cd.staging,a={native:((l=i==null?void 0:i.programAddress)==null?void 0:l.native)??o.native,spl:((p=i==null?void 0:i.programAddress)==null?void 0:p.spl)??o.spl},c=(i==null?void 0:i.relayer)??T1[n];try{this.relayer=new Vt.web3.PublicKey(c),this.auth=s}catch(d){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:d})}const u=a.spl?{...z0,metadata:{...z0.metadata??{}},address:a.spl}:void 0,f=a.native?{...bd,metadata:{...bd.metadata??{}},address:a.native}:void 0;try{this.splProgram=u?new Vt.Program(u,this.provider):void 0,this.nativeProgram=f?new Vt.Program(f,this.provider):void 0}catch(d){throw new Error("Error creating Program instances. Ensure the IDLs and provider are correct.",{cause:d})}}get htlcActorAddress(){if(!this.provider.publicKey)throw new Error("No provider public key found");return this.provider.publicKey.toBase58()}async initiate(e){if(!e)return g.Err("Order is required");if(Y.isSolanaOrderResponse(e))return this.initiateWithCreateOrderResponse(e);try{const r=Y.ChainAsset.fromString(e.source_swap.asset);return Y.isSolanaNativeToken(r.chain,r.symbol)?this.nativeProgram?await this.initiateNativeSwap(e):g.Err("Native program is not initialized"):this.splProgram?await this.initiateSplSwap(e):g.Err("SPL program is not initialized")}catch(r){return g.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async sendSplViaRelayer(e,r){try{e.recentBlockhash=(await this.provider.connection.getLatestBlockhash()).blockhash,e.feePayer=this.relayer;const s=(await this.provider.wallet.signTransaction(e)).serialize({requireAllSignatures:!1}).toString("base64"),i=await g.Fetcher.post(this.url.endpoint("/initiate"),{body:JSON.stringify({order_id:r,serialized_tx:s}),headers:{"Content-Type":"application/json"}});return i.error||!i.result?g.Err(`Error from Relayer: ${i.error}`):await Da(this.provider.connection,i.result)?g.Ok(i.result):g.Err("Relayer: Failed to Initiate swap, confirmation timed out")}catch(n){return g.Err(`Failed to send SPL transaction: ${n instanceof Error?n.message:String(n)}`)}}async initiateViaHTLC(e,r){if(!r)return g.Err("Order is required");try{const n=await this.provider.sendAndConfirm(e);return n?await Da(this.provider.connection,n)?g.Ok(n):g.Err("HTLC: Failed to Initiate swap, confirmation timed out"):g.Err("Failed to initiate HTLC transaction")}catch(n){return g.Err(`Error initiating swap: ${n instanceof Error?n.message:String(n)}`)}}async initiateSplSwap(e){if(!this.splProgram)return g.Err("SPL program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=es.from(e),o=this.splProgram.methods.initiate(i,r,n,s,null),a=await Ih(e.source_swap.asset,this.url);if(!a.ok)return g.Err(a.error);const{tokenAddress:c}=a.val,u=new Vt.web3.PublicKey(c),f={initiator:this.provider.publicKey,mint:u,initiatorTokenAccount:u6.getAssociatedTokenAddressSync(u,this.provider.publicKey),sponsor:this.relayer},l=await o.accounts(f).transaction();return this.sendSplViaRelayer(l,e.order_id)}catch(r){return g.Err(`Error initiating SPL swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateNativeSwap(e){if(!this.nativeProgram)return g.Err("Native program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=es.from(e),o=await this.nativeProgram.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction();return this.initiateViaHTLC(o,e)}catch(r){return g.Err(`Error initiating native swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateWithCreateOrderResponse(e){if(!this.relayer)return g.Err("No relayer address");const{versioned_tx:r,versioned_tx_gasless:n}=e;if(n===null)try{const i=Buffer.from(r,"base64"),o=Vt.web3.VersionedTransaction.deserialize(i),a=await this.provider.sendAndConfirm(o);return await Da(this.provider.connection,a)?g.Ok(a):g.Err("Failed to initiate HTLC transaction")}catch(i){return g.Err(`Error in non-gasless flow: ${i}`)}const s=await this.auth.getAuthHeaders();if(!s.ok)return g.Err(s.error);try{const i=Vt.web3.VersionedTransaction.deserialize(Buffer.from(n,"base64")),o=await this.provider.wallet.signTransaction(i);if(!o.signatures[0])return g.Err("No signature found after signing transaction");const c=Buffer.from(o.serialize()).toString("base64"),u=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:c}),headers:{...s.val,"Content-Type":"application/json"}});return u.error?g.Err(`Initiate: Error from relayer: ${u.error}`):u.result?g.Ok(u.result):g.Err("Initiate: No transaction hash returned from relayer")}catch(i){return g.Err(`Error initiating with create order response: ${i}`)}}async redeem(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return g.Err(n.error);const s=Bw(r),i=await g.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:Buffer.from(s).toString("hex")}),headers:{...n.val,"Content-Type":"application/json"}});if(i.error||!i.result)return g.Err(`Redeem: Error from relayer: ${i.error}`);const o=i.result;return await Da(this.provider.connection,o)?g.Ok(o):g.Err("Redeem: Timed out waiting for confirmation")}catch(n){return console.error("Redeem: Caught exception:",n),g.Err(`Error redeeming: ${n}`)}}async refund(){return g.Err("Refund is automatically handled by the relayer.")}}const $w="1.38.0",DP="1.57.0",HP={"-32700":"ParseError","-32701":"OversizedRequest","-32702":"OversizedResponse","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError","-32604":"ServerBusy","-32000":"CallExecutionFailed","-32001":"UnknownError","-32003":"SubscriptionClosed","-32004":"SubscriptionClosedWithError","-32005":"BatchesNotSupported","-32006":"TooManySubscriptions","-32050":"TransientError","-32002":"TransactionExecutionClientError"};class Rw extends Error{}class Nw extends Rw{constructor(e,r){super(e),this.code=r,this.type=HP[r]??"ServerError"}}class zP extends Rw{constructor(e,r,n){super(e),this.status=r,this.statusText=n}}var Uw=t=>{throw TypeError(t)},Gh=(t,e,r)=>e.has(t)||Uw("Cannot "+r),Me=(t,e,r)=>(Gh(t,e,"read from private field"),r?r.call(t):e.get(t)),ms=(t,e,r)=>e.has(t)?Uw("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Pi=(t,e,r,n)=>(Gh(t,e,"write to private field"),e.set(t,r),r),Mw=(t,e,r)=>(Gh(t,e,"access private method"),r),VP=(t,e,r,n)=>({set _(s){Pi(t,e,s)},get _(){return Me(t,e,n)}}),Gn,Ao,yn,Ss,ra,As,xc,Fw,jw;function qP(t){const e=new URL(t);return e.protocol=e.protocol.replace("http","ws"),e.toString()}const GP={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5};class WP{constructor(e,r={}){if(ms(this,xc),ms(this,Gn,0),ms(this,Ao,0),ms(this,yn,null),ms(this,Ss,null),ms(this,ra,new Set),ms(this,As,new Map),this.endpoint=e,this.options={...GP,...r},!this.options.WebSocketConstructor)throw new Error("Missing WebSocket constructor");this.endpoint.startsWith("http")&&(this.endpoint=qP(this.endpoint))}async makeRequest(e,r,n){const s=await Mw(this,xc,Fw).call(this);return new Promise((i,o)=>{Pi(this,Gn,Me(this,Gn)+1),Me(this,As).set(Me(this,Gn),{resolve:i,reject:o,timeout:setTimeout(()=>{Me(this,As).delete(Me(this,Gn)),o(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n==null||n.addEventListener("abort",()=>{Me(this,As).delete(Me(this,Gn)),o(n.reason)}),s.send(JSON.stringify({jsonrpc:"2.0",id:Me(this,Gn),method:e,params:r}))}).then(({error:i,result:o})=>{if(i)throw new Nw(i.message,i.code);return o})}async subscribe(e){const r=new KP(e);return Me(this,ra).add(r),await r.subscribe(this),()=>r.unsubscribe(this)}}Gn=new WeakMap;Ao=new WeakMap;yn=new WeakMap;Ss=new WeakMap;ra=new WeakMap;As=new WeakMap;xc=new WeakSet;Fw=function(){return Me(this,Ss)?Me(this,Ss):(Pi(this,Ss,new Promise(t=>{var e;(e=Me(this,yn))==null||e.close(),Pi(this,yn,new this.options.WebSocketConstructor(this.endpoint)),Me(this,yn).addEventListener("open",()=>{Pi(this,Ao,0),t(Me(this,yn))}),Me(this,yn).addEventListener("close",()=>{VP(this,Ao)._++,Me(this,Ao)<=this.options.maxReconnects&&setTimeout(()=>{Mw(this,xc,jw).call(this)},this.options.reconnectTimeout)}),Me(this,yn).addEventListener("message",({data:r})=>{let n;try{n=JSON.parse(r)}catch(s){console.error(new Error(`Failed to parse RPC message: ${r}`,{cause:s}));return}if("id"in n&&n.id!=null&&Me(this,As).has(n.id)){const{resolve:s,timeout:i}=Me(this,As).get(n.id);clearTimeout(i),s(n)}else if("params"in n){const{params:s}=n;Me(this,ra).forEach(i=>{i.subscriptionId===s.subscription&&s.subscription===i.subscriptionId&&i.onMessage(s.result)})}})})),Me(this,Ss))};jw=async function(){var t;return(t=Me(this,yn))==null||t.close(),Pi(this,Ss,null),Promise.allSettled([...Me(this,ra)].map(e=>e.subscribe(this)))};class KP{constructor(e){this.subscriptionId=null,this.subscribed=!1,this.input=e}onMessage(e){this.subscribed&&this.input.onMessage(e)}async unsubscribe(e){const{subscriptionId:r}=this;return this.subscribed=!1,r==null?!1:(this.subscriptionId=null,e.makeRequest(this.input.unsubscribe,[r]))}async subscribe(e){this.subscriptionId=null,this.subscribed=!0;const r=await e.makeRequest(this.input.method,this.input.params,this.input.signal);this.subscribed&&(this.subscriptionId=r)}}var Lw=t=>{throw TypeError(t)},Wh=(t,e,r)=>e.has(t)||Lw("Cannot "+r),ar=(t,e,r)=>(Wh(t,e,"read from private field"),r?r.call(t):e.get(t)),Qa=(t,e,r)=>e.has(t)?Lw("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),wd=(t,e,r,n)=>(Wh(t,e,"write to private field"),e.set(t,r),r),ZP=(t,e,r)=>(Wh(t,e,"access private method"),r),bo,gr,xo,vd,Dw;class YP{constructor(e){Qa(this,vd),Qa(this,bo,0),Qa(this,gr),Qa(this,xo),wd(this,gr,e)}fetch(e,r){const n=ar(this,gr).fetch??fetch;if(!n)throw new Error("The current environment does not support fetch, you can provide a fetch implementation in the options for SuiHTTPTransport.");return n(e,r)}async request(e){var s,i;wd(this,bo,ar(this,bo)+1);const r=await this.fetch(((s=ar(this,gr).rpc)==null?void 0:s.url)??ar(this,gr).url,{method:"POST",signal:e.signal,headers:{"Content-Type":"application/json","Client-Sdk-Type":"typescript","Client-Sdk-Version":$w,"Client-Target-Api-Version":DP,"Client-Request-Method":e.method,...(i=ar(this,gr).rpc)==null?void 0:i.headers},body:JSON.stringify({jsonrpc:"2.0",id:ar(this,bo),method:e.method,params:e.params})});if(!r.ok)throw new zP(`Unexpected status code: ${r.status}`,r.status,r.statusText);const n=await r.json();if("error"in n&&n.error!=null)throw new Nw(n.error.message,n.error.code);return n.result}async subscribe(e){const r=await ZP(this,vd,Dw).call(this).subscribe(e);return e.signal&&(e.signal.throwIfAborted(),e.signal.addEventListener("abort",()=>{r()})),async()=>!!await r()}}bo=new WeakMap;gr=new WeakMap;xo=new WeakMap;vd=new WeakSet;Dw=function(){var t;if(!ar(this,xo)){const e=ar(this,gr).WebSocketConstructor??WebSocket;if(!e)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");wd(this,xo,new WP(((t=ar(this,gr).websocket)==null?void 0:t.url)??ar(this,gr).url,{WebSocketConstructor:e,...ar(this,gr).websocket}))}return ar(this,xo)};function Gy(t){switch(t){case"mainnet":return"https://fullnode.mainnet.sui.io:443";case"testnet":return"https://fullnode.testnet.sui.io:443";case"devnet":return"https://fullnode.devnet.sui.io:443";case"localnet":return"http://127.0.0.1:9000";default:throw new Error(`Unknown network: ${t}`)}}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function XP(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Hw(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function Ed(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function zw(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Sd(t){if(!Array.isArray(t))throw new Error("array expected")}function Vw(t,e){if(!Hw(!0,e))throw new Error(`${t}: array of strings expected`)}function JP(t,e){if(!Hw(!1,e))throw new Error(`${t}: array of numbers expected`)}function QP(...t){const e=i=>i,r=(i,o)=>a=>i(o(a)),n=t.map(i=>i.encode).reduceRight(r,e),s=t.map(i=>i.decode).reduce(r,e);return{encode:n,decode:s}}function eI(t){const e=typeof t=="string"?t.split(""):t,r=e.length;Vw("alphabet",e);const n=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(Sd(s),s.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${t}`);return e[i]})),decode:s=>(Sd(s),s.map(i=>{Ed("alphabet.decode",i);const o=n.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${t}`);return o}))}}function tI(t=""){return Ed("join",t),{encode:e=>(Vw("join.decode",e),e.join(t)),decode:e=>(Ed("join.decode",e),e.split(t))}}function Wy(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(Sd(t),!t.length)return[];let n=0;const s=[],i=Array.from(t,a=>{if(zw(a),a<0||a>=e)throw new Error(`invalid integer: ${a}`);return a}),o=i.length;for(;;){let a=0,c=!0;for(let u=n;u<o;u++){const f=i[u],l=e*a,p=l+f;if(!Number.isSafeInteger(p)||l/e!==a||p-f!==l)throw new Error("convertRadix: carry overflow");const d=p/r;a=p%r;const m=Math.floor(d);if(i[u]=m,!Number.isSafeInteger(m)||m*r+a!==p)throw new Error("convertRadix: carry overflow");if(c)m?c=!1:n=u;else continue}if(s.push(a),c)break}for(let a=0;a<t.length-1&&t[a]===0;a++)s.push(0);return s.reverse()}function rI(t){zw(t);const e=2**8;return{encode:r=>{if(!XP(r))throw new Error("radix.encode input should be Uint8Array");return Wy(Array.from(r),e,t)},decode:r=>(JP("radix.decode",r),Uint8Array.from(Wy(r,t,e)))}}const nI=t=>QP(rI(58),eI(t),tI("")),qw=nI("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),Su=t=>qw.encode(t),na=t=>qw.decode(t);function Gt(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}const ll=8192;function wt(t){if(t.length<ll)return btoa(String.fromCharCode(...t));let e="";for(var r=0;r<t.length;r+=ll){const n=t.slice(r,r+ll);e+=String.fromCharCode(...n)}return btoa(e)}function Gw(t){var s;const e=t.startsWith("0x")?t.slice(2):t,r=e.length%2===0?e:`0${e}`,n=((s=r.match(/[0-9a-fA-F]{2}/g))==null?void 0:s.map(i=>parseInt(i,16)))??[];if(n.length!==r.length/2)throw new Error(`Invalid hex string ${t}`);return Uint8Array.from(n)}function ji(t){return t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),"")}function Au(t,e){return Array.from({length:Math.ceil(t.length/e)},(r,n)=>t.slice(n*e,(n+1)*e))}class Ww{constructor(e,r){if(typeof e!="function")throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but got: ${e}.`);this._batchLoadFn=e,this._maxBatchSize=aI(r),this._batchScheduleFn=cI(r),this._cacheKeyFn=uI(r),this._cacheMap=fI(r),this._batch=null,this.name=lI(r)}load(e){if(e==null)throw new TypeError(`The loader.load() function must be called with a value, but got: ${String(e)}.`);const r=iI(this),n=this._cacheMap;let s;if(n){s=this._cacheKeyFn(e);const o=n.get(s);if(o){const a=r.cacheHits||(r.cacheHits=[]);return new Promise(c=>{a.push(()=>{c(o)})})}}r.keys.push(e);const i=new Promise((o,a)=>{r.callbacks.push({resolve:o,reject:a})});return n&&n.set(s,i),i}loadMany(e){if(!Kw(e))throw new TypeError(`The loader.loadMany() function must be called with Array<key>, but got: ${e}.`);const r=[];for(let n=0;n<e.length;n++)r.push(this.load(e[n]).catch(s=>s));return Promise.all(r)}clear(e){const r=this._cacheMap;if(r){const n=this._cacheKeyFn(e);r.delete(n)}return this}clearAll(){const e=this._cacheMap;return e&&e.clear(),this}prime(e,r){const n=this._cacheMap;if(n){const s=this._cacheKeyFn(e);if(n.get(s)===void 0){let i;r instanceof Error?(i=Promise.reject(r),i.catch(()=>{})):i=Promise.resolve(r),n.set(s,i)}}return this}}const sI=typeof process=="object"&&typeof process.nextTick=="function"?function(t){dl||(dl=Promise.resolve()),dl.then(()=>{process.nextTick(t)})}:typeof setImmediate=="function"?function(t){setImmediate(t)}:function(t){setTimeout(t)};let dl;function iI(t){const e=t._batch;if(e!==null&&!e.hasDispatched&&e.keys.length<t._maxBatchSize)return e;const r={hasDispatched:!1,keys:[],callbacks:[]};return t._batch=r,t._batchScheduleFn(()=>{oI(t,r)}),r}function oI(t,e){if(e.hasDispatched=!0,e.keys.length===0){Ad(e);return}let r;try{r=t._batchLoadFn(e.keys)}catch(n){return hl(t,e,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function errored synchronously: ${String(n)}.`))}if(!r||typeof r.then!="function")return hl(t,e,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise: ${String(r)}.`));Promise.resolve(r).then(n=>{if(!Kw(n))throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array: ${String(n)}.`);if(n.length!==e.keys.length)throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys.
|
|
83
83
|
|
|
84
84
|
Keys:
|
|
85
85
|
${String(e.keys)}
|
|
86
86
|
|
|
87
87
|
Values:
|
|
88
|
-
${String(n)}`);Sd(e);for(let s=0;s<e.callbacks.length;s++){const i=n[s];i instanceof Error?e.callbacks[s].reject(i):e.callbacks[s].resolve(i)}}).catch(n=>{ll(t,e,n)})}function ll(t,e,r){Sd(e);for(let n=0;n<e.keys.length;n++)t.clear(e.keys[n]),e.callbacks[n].reject(r)}function Sd(t){if(t.cacheHits)for(let e=0;e<t.cacheHits.length;e++)t.cacheHits[e]()}function aI(t){if(!(!t||t.batch!==!1))return 1;const r=t&&t.maxBatchSize;if(r===void 0)return 1/0;if(typeof r!="number"||r<1)throw new TypeError(`maxBatchSize must be a positive number: ${r}`);return r}function cI(t){const e=t&&t.batchScheduleFn;if(e===void 0)return sI;if(typeof e!="function")throw new TypeError(`batchScheduleFn must be a function: ${e}`);return e}function uI(t){const e=t&&t.cacheKeyFn;if(e===void 0)return r=>r;if(typeof e!="function")throw new TypeError(`cacheKeyFn must be a function: ${e}`);return e}function fI(t){if(!(!t||t.cache!==!1))return null;const r=t&&t.cacheMap;if(r===void 0)return new Map;if(r!==null){const s=["get","set","delete","clear"].filter(i=>r&&typeof r[i]!="function");if(s.length!==0)throw new TypeError("Custom cacheMap missing methods: "+s.join(", "))}return r}function lI(t){return t&&t.name?t.name:null}function Kw(t){return typeof t=="object"&&t!==null&&"length"in t&&typeof t.length=="number"&&(t.length===0||t.length>0&&Object.prototype.hasOwnProperty.call(t,t.length-1))}function xc(t){const e=[];let r=0;if(t===0)return[0];for(;t>0;)e[r]=t&127,(t>>=7)&&(e[r]|=128),r+=1;return e}function dI(t){let e=0,r=0,n=0;for(;;){const s=t[n];if(n+=1,e|=(s&127)<<r,!(s&128))break;r+=7}return{value:e,length:n}}class hI{constructor(e){this.bytePosition=0,this.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)}shift(e){return this.bytePosition+=e,this}read8(){const e=this.dataView.getUint8(this.bytePosition);return this.shift(1),e}read16(){const e=this.dataView.getUint16(this.bytePosition,!0);return this.shift(2),e}read32(){const e=this.dataView.getUint32(this.bytePosition,!0);return this.shift(4),e}read64(){const e=this.read32(),n=this.read32().toString(16)+e.toString(16).padStart(8,"0");return BigInt("0x"+n).toString(10)}read128(){const e=BigInt(this.read64()),n=BigInt(this.read64()).toString(16)+e.toString(16).padStart(16,"0");return BigInt("0x"+n).toString(10)}read256(){const e=BigInt(this.read128()),n=BigInt(this.read128()).toString(16)+e.toString(16).padStart(32,"0");return BigInt("0x"+n).toString(10)}readBytes(e){const r=this.bytePosition+this.dataView.byteOffset,n=new Uint8Array(this.dataView.buffer,r,e);return this.shift(e),n}readULEB(){const e=this.bytePosition+this.dataView.byteOffset,r=new Uint8Array(this.dataView.buffer,e),{value:n,length:s}=dI(r);return this.shift(s),n}readVec(e){const r=this.readULEB(),n=[];for(let s=0;s<r;s++)n.push(e(this,s,r));return n}}function pI(t,e){switch(e){case"base58":return vu(t);case"base64":return wt(t);case"hex":return ji(t);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}function Zw(t,e=["<",">"]){const[r,n]=e,s=[];let i="",o=0;for(let a=0;a<t.length;a++){const c=t[a];if(c===r&&o++,c===n&&o--,o===0&&c===","){s.push(i.trim()),i="";continue}i+=c}return s.push(i.trim()),s}class yI{constructor({initialSize:e=1024,maxSize:r=1/0,allocateSize:n=1024}={}){this.bytePosition=0,this.size=e,this.maxSize=r,this.allocateSize=n,this.dataView=new DataView(new ArrayBuffer(e))}ensureSizeOrGrow(e){const r=this.bytePosition+e;if(r>this.size){const n=Math.min(this.maxSize,this.size+this.allocateSize);if(r>n)throw new Error(`Attempting to serialize to BCS, but buffer does not have enough size. Allocated size: ${this.size}, Max size: ${this.maxSize}, Required size: ${r}`);this.size=n;const s=new ArrayBuffer(this.size);new Uint8Array(s).set(new Uint8Array(this.dataView.buffer)),this.dataView=new DataView(s)}}shift(e){return this.bytePosition+=e,this}write8(e){return this.ensureSizeOrGrow(1),this.dataView.setUint8(this.bytePosition,Number(e)),this.shift(1)}write16(e){return this.ensureSizeOrGrow(2),this.dataView.setUint16(this.bytePosition,Number(e),!0),this.shift(2)}write32(e){return this.ensureSizeOrGrow(4),this.dataView.setUint32(this.bytePosition,Number(e),!0),this.shift(4)}write64(e){return dl(BigInt(e),8).forEach(r=>this.write8(r)),this}write128(e){return dl(BigInt(e),16).forEach(r=>this.write8(r)),this}write256(e){return dl(BigInt(e),32).forEach(r=>this.write8(r)),this}writeULEB(e){return xc(e).forEach(r=>this.write8(r)),this}writeVec(e,r){return this.writeULEB(e.length),Array.from(e).forEach((n,s)=>r(this,n,s,e.length)),this}*[Symbol.iterator](){for(let e=0;e<this.bytePosition;e++)yield this.dataView.getUint8(e);return this.toBytes()}toBytes(){return new Uint8Array(this.dataView.buffer.slice(0,this.bytePosition))}toString(e){return pI(this.toBytes(),e)}}function dl(t,e){const r=new Uint8Array(e);let n=0;for(;t>0;)r[n]=Number(t%BigInt(256)),t=t/BigInt(256),n+=1;return r}var Yw=t=>{throw TypeError(t)},Xw=(t,e,r)=>e.has(t)||Yw("Cannot "+r),wr=(t,e,r)=>(Xw(t,e,"read from private field"),r?r.call(t):e.get(t)),kc=(t,e,r)=>e.has(t)?Yw("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Tc=(t,e,r,n)=>(Xw(t,e,"write to private field"),e.set(t,r),r),pi,go,lc,Wn;const mI=class Jw{constructor(e){kc(this,pi),kc(this,go),this.name=e.name,this.read=e.read,this.serializedSize=e.serializedSize??(()=>null),Tc(this,pi,e.write),Tc(this,go,e.serialize??((r,n)=>{const s=new yI({initialSize:this.serializedSize(r)??void 0,...n});return wr(this,pi).call(this,r,s),s.toBytes()})),this.validate=e.validate??(()=>{})}write(e,r){this.validate(e),wr(this,pi).call(this,e,r)}serialize(e,r){return this.validate(e),new bI(this,wr(this,go).call(this,e,r))}parse(e){const r=new hI(e);return this.read(r)}fromHex(e){return this.parse(Gw(e))}fromBase58(e){return this.parse(na(e))}fromBase64(e){return this.parse(Gt(e))}transform({name:e,input:r,output:n,validate:s}){return new Jw({name:e??this.name,read:i=>n?n(this.read(i)):this.read(i),write:(i,o)=>wr(this,pi).call(this,r?r(i):i,o),serializedSize:i=>this.serializedSize(r?r(i):i),serialize:(i,o)=>wr(this,go).call(this,r?r(i):i,o),validate:i=>{s==null||s(i),this.validate(r?r(i):i)}})}};pi=new WeakMap;go=new WeakMap;let en=mI;const Qw=Symbol.for("@mysten/serialized-bcs");function Wh(t){return!!t&&typeof t=="object"&&t[Qw]===!0}class bI{constructor(e,r){kc(this,lc),kc(this,Wn),Tc(this,lc,e),Tc(this,Wn,r)}get[Qw](){return!0}toBytes(){return wr(this,Wn)}toHex(){return ji(wr(this,Wn))}toBase64(){return wt(wr(this,Wn))}toBase58(){return vu(wr(this,Wn))}parse(){return wr(this,lc).parse(wr(this,Wn))}}lc=new WeakMap;Wn=new WeakMap;function _c({size:t,...e}){return new en({...e,serializedSize:()=>t})}function hl({readMethod:t,writeMethod:e,...r}){return _c({...r,read:n=>n[t](),write:(n,s)=>s[e](n),validate:n=>{var s;if(n<0||n>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${n}. Expected value in range 0-${r.maxValue}`);(s=r.validate)==null||s.call(r,n)}})}function pl({readMethod:t,writeMethod:e,...r}){return _c({...r,read:n=>n[t](),write:(n,s)=>s[e](BigInt(n)),validate:n=>{var i;const s=BigInt(n);if(s<0||s>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${s}. Expected value in range 0-${r.maxValue}`);(i=r.validate)==null||i.call(r,s)}})}function gI({serialize:t,...e}){const r=new en({...e,serialize:t,write:(n,s)=>{for(const i of r.serialize(n).toBytes())s.write8(i)}});return r}function wI({toBytes:t,fromBytes:e,...r}){return new en({...r,read:n=>{const s=n.readULEB(),i=n.readBytes(s);return e(i)},write:(n,s)=>{const i=t(n);s.writeULEB(i.length);for(let o=0;o<i.length;o++)s.write8(i[o])},serialize:n=>{const s=t(n),i=xc(s.length),o=new Uint8Array(i.length+s.length);return o.set(i,0),o.set(s,i.length),o},validate:n=>{var s;if(typeof n!="string")throw new TypeError(`Invalid ${r.name} value: ${n}. Expected string`);(s=r.validate)==null||s.call(r,n)}})}function vI(t){let e=null;function r(){return e||(e=t()),e}return new en({name:"lazy",read:n=>r().read(n),serializedSize:n=>r().serializedSize(n),write:(n,s)=>r().write(n,s),serialize:(n,s)=>r().serialize(n,s).toBytes()})}class EI extends en{constructor({name:e,fields:r,...n}){const s=Object.entries(r);super({name:e,serializedSize:i=>{let o=0;for(const[a,c]of s){const u=c.serializedSize(i[a]);if(u==null)return null;o+=u}return o},read:i=>{const o={};for(const[a,c]of s)o[a]=c.read(i);return o},write:(i,o)=>{for(const[a,c]of s)c.write(i[a],o)},...n,validate:i=>{var o;if((o=n==null?void 0:n.validate)==null||o.call(n,i),typeof i!="object"||i==null)throw new TypeError(`Expected object, found ${typeof i}`)}})}}class SI extends en{constructor({fields:e,...r}){const n=Object.entries(e);super({read:s=>{const i=s.readULEB(),o=n[i];if(!o)throw new TypeError(`Unknown value ${i} for enum ${name}`);const[a,c]=o;return{[a]:(c==null?void 0:c.read(s))??!0,$kind:a}},write:(s,i)=>{const[o,a]=Object.entries(s).filter(([c])=>Object.hasOwn(e,c))[0];for(let c=0;c<n.length;c++){const[u,f]=n[c];if(u===o){i.writeULEB(c),f==null||f.write(a,i);return}}},...r,validate:s=>{var a;if((a=r==null?void 0:r.validate)==null||a.call(r,s),typeof s!="object"||s==null)throw new TypeError(`Expected object, found ${typeof s}`);const i=Object.keys(s).filter(c=>s[c]!==void 0&&Object.hasOwn(e,c));if(i.length!==1)throw new TypeError(`Expected object with one key, but found ${i.length} for type ${name}}`);const[o]=i;if(!Object.hasOwn(e,o))throw new TypeError(`Invalid enum variant ${o}`)}})}}class AI extends en{constructor({fields:e,name:r,...n}){super({name:r??`(${e.map(s=>s.name).join(", ")})`,serializedSize:s=>{let i=0;for(let o=0;o<e.length;o++){const a=e[o].serializedSize(s[o]);if(a==null)return null;i+=a}return i},read:s=>{const i=[];for(const o of e)i.push(o.read(s));return i},write:(s,i)=>{for(let o=0;o<e.length;o++)e[o].write(s[o],i)},...n,validate:s=>{var i;if((i=n==null?void 0:n.validate)==null||i.call(n,s),!Array.isArray(s))throw new TypeError(`Expected array, found ${typeof s}`);if(s.length!==e.length)throw new TypeError(`Expected array of length ${e.length}, found ${s.length}`)}})}}function xI(t,e,r){return new en({read:n=>{const s=new Array(t);for(let i=0;i<t;i++)s[i]=e.read(n);return s},write:(n,s)=>{for(const i of n)e.write(i,s)},...r,name:(r==null?void 0:r.name)??`${e.name}[${t}]`,validate:n=>{var s;if((s=r==null?void 0:r.validate)==null||s.call(r,n),!n||typeof n!="object"||!("length"in n))throw new TypeError(`Expected array, found ${typeof n}`);if(n.length!==t)throw new TypeError(`Expected array of length ${t}, found ${n.length}`)}})}function kI(t){return _.enum(`Option<${t.name}>`,{None:null,Some:t}).transform({input:e=>e==null?{None:!0}:{Some:e},output:e=>e.$kind==="Some"?e.Some:null})}function TI(t,e){return new en({read:r=>{const n=r.readULEB(),s=new Array(n);for(let i=0;i<n;i++)s[i]=t.read(r);return s},write:(r,n)=>{n.writeULEB(r.length);for(const s of r)t.write(s,n)},...e,name:(e==null?void 0:e.name)??`vector<${t.name}>`,validate:r=>{var n;if((n=e==null?void 0:e.validate)==null||n.call(e,r),!r||typeof r!="object"||!("length"in r))throw new TypeError(`Expected array, found ${typeof r}`)}})}function _I(t,e){return _.vector(_.tuple([t,e])).transform({name:`Map<${t.name}, ${e.name}>`,input:r=>[...r.entries()],output:r=>{const n=new Map;for(const[s,i]of r)n.set(s,i);return n}})}const _={u8(t){return hl({readMethod:"read8",writeMethod:"write8",size:1,maxValue:2**8-1,...t,name:(t==null?void 0:t.name)??"u8"})},u16(t){return hl({readMethod:"read16",writeMethod:"write16",size:2,maxValue:2**16-1,...t,name:(t==null?void 0:t.name)??"u16"})},u32(t){return hl({readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...t,name:(t==null?void 0:t.name)??"u32"})},u64(t){return pl({readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...t,name:(t==null?void 0:t.name)??"u64"})},u128(t){return pl({readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...t,name:(t==null?void 0:t.name)??"u128"})},u256(t){return pl({readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...t,name:(t==null?void 0:t.name)??"u256"})},bool(t){return _c({size:1,read:e=>e.read8()===1,write:(e,r)=>r.write8(e?1:0),...t,name:(t==null?void 0:t.name)??"bool",validate:e=>{var r;if((r=t==null?void 0:t.validate)==null||r.call(t,e),typeof e!="boolean")throw new TypeError(`Expected boolean, found ${typeof e}`)}})},uleb128(t){return gI({read:e=>e.readULEB(),serialize:e=>Uint8Array.from(xc(e)),...t,name:(t==null?void 0:t.name)??"uleb128"})},bytes(t,e){return _c({size:t,read:r=>r.readBytes(t),write:(r,n)=>{const s=new Uint8Array(r);for(let i=0;i<t;i++)n.write8(s[i]??0)},...e,name:(e==null?void 0:e.name)??`bytes[${t}]`,validate:r=>{var n;if((n=e==null?void 0:e.validate)==null||n.call(e,r),!r||typeof r!="object"||!("length"in r))throw new TypeError(`Expected array, found ${typeof r}`);if(r.length!==t)throw new TypeError(`Expected array of length ${t}, found ${r.length}`)}})},byteVector(t){return new en({read:e=>{const r=e.readULEB();return e.readBytes(r)},write:(e,r)=>{const n=new Uint8Array(e);r.writeULEB(n.length);for(let s=0;s<n.length;s++)r.write8(n[s]??0)},...t,name:(t==null?void 0:t.name)??"vector<u8>",serializedSize:e=>{const r="length"in e?e.length:null;return r==null?null:xc(r).length+r},validate:e=>{var r;if((r=t==null?void 0:t.validate)==null||r.call(t,e),!e||typeof e!="object"||!("length"in e))throw new TypeError(`Expected array, found ${typeof e}`)}})},string(t){return wI({toBytes:e=>new TextEncoder().encode(e),fromBytes:e=>new TextDecoder().decode(e),...t,name:(t==null?void 0:t.name)??"string"})},fixedArray:xI,option:kI,vector:TI,tuple(t,e){return new AI({fields:t,...e})},struct(t,e,r){return new EI({name:t,fields:e,...r})},enum(t,e,r){return new SI({name:t,fields:e,...r})},map:_I,lazy(t){return vI(t)}};var e2=t=>{throw TypeError(t)},t2=(t,e,r)=>e.has(t)||e2("Cannot "+r),bt=(t,e,r)=>(t2(t,e,"read from private field"),e.get(t)),Wy=(t,e,r)=>e.has(t)?e2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Ky=(t,e,r,n)=>(t2(t,e,"write to private field"),e.set(t,r),r),gs,_t;const PI=class r2{constructor({prefix:e,cache:r}={}){Wy(this,gs),Wy(this,_t),Ky(this,gs,e??[]),Ky(this,_t,r??new Map)}read(e,r){const n=[bt(this,gs),...e].join(":");if(bt(this,_t).has(n))return bt(this,_t).get(n);const s=r();return bt(this,_t).set(n,s),typeof s=="object"&&s!==null&&"then"in s?Promise.resolve(s).then(i=>(bt(this,_t).set(n,i),i)).catch(i=>{throw bt(this,_t).delete(n),i}):s}readSync(e,r){const n=[bt(this,gs),...e].join(":");if(bt(this,_t).has(n))return bt(this,_t).get(n);const s=r();return bt(this,_t).set(n,s),s}clear(e){const r=[...bt(this,gs),...e??[]].join(":");if(!r){bt(this,_t).clear();return}for(const n of bt(this,_t).keys())n.startsWith(r)&&bt(this,_t).delete(n)}scope(e){return new r2({prefix:[...bt(this,gs),...Array.isArray(e)?e:[e]],cache:bt(this,_t)})}};gs=new WeakMap;_t=new WeakMap;let II=PI;class n2{constructor({network:e,base:r,cache:n=(r==null?void 0:r.cache)??new II}){this.network=e,this.base=r??this,this.cache=n}$extend(...e){return Object.create(this,Object.fromEntries(e.map(r=>{if("experimental_asClientExtension"in r){const{name:n,register:s}=r.experimental_asClientExtension();return[n,{value:s(this)}]}return[r.name,{value:r.register(this)}]})))}}const s2=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,i2=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i,OI=235;function BI(t){return t.length>OI?!1:t.includes("@")?s2.test(t):i2.test(t)}function CI(t,e="at"){const r=t.toLowerCase();let n;if(r.includes("@")){if(!s2.test(r))throw new Error(`Invalid SuiNS name ${t}`);const[s,i]=r.split("@");n=[...s?s.split("."):[],i]}else{if(!i2.test(r))throw new Error(`Invalid SuiNS name ${t}`);n=r.split(".").slice(0,-1)}return e==="dot"?`${n.join(".")}.sui`:`${n.slice(0,-1).join(".")}@${n[n.length-1]}`}const $I=/^([a-z0-9]+(?:-[a-z0-9]+)*)$/,RI=/^\d+$/,NI=64,o2="/",zt=t=>{const e=t.split(o2);if(e.length<2||e.length>3)return!1;const[r,n,s]=e;return s!==void 0&&!RI.test(s)||!BI(r)?!1:$I.test(n)&&n.length<NI},UI=t=>{const e=t.split(/::|<|>|,/);for(const r of e)if(r.includes(o2)&&!zt(r))return!1;return!0},MI=32;function Zy(t){try{return na(t).length===MI}catch{return!1}}const Su=32;function vr(t){return jI(t)&&LI(t)===Su}function ec(t){return vr(t)}function FI(t){return t.includes("::")?Gs(t):t}function Gs(t){const[e,r]=t.split("::"),n=zt(e),s=t.slice(e.length+r.length+4),i=s.includes("<")?s.slice(0,s.indexOf("<")):s,o=s.includes("<")?Zw(s.slice(s.indexOf("<")+1,s.lastIndexOf(">"))).map(a=>FI(a.trim())):[];return{address:n?e:xe(e),module:r,name:i,typeParams:o}}function Pc(t){const{address:e,module:r,name:n,typeParams:s}=typeof t=="string"?Gs(t):t,i=(s==null?void 0:s.length)>0?`<${s.map(o=>typeof o=="string"?o:Pc(o)).join(",")}>`:"";return`${e}::${r}::${n}${i}`}function xe(t,e=!1){let r=t.toLowerCase();return!e&&r.startsWith("0x")&&(r=r.slice(2)),`0x${r.padStart(Su*2,"0")}`}function vn(t,e=!1){return xe(t,e)}function jI(t){return/^(0x|0X)?[a-fA-F0-9]+$/.test(t)&&t.length%2===0}function LI(t){return/^(0x|0X)/.test(t)?(t.length-2)/2:t.length/2}const DI=/^vector<(.+)>$/,HI=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class Sr{static parseFromStr(e,r=!1){if(e==="address")return{address:null};if(e==="bool")return{bool:null};if(e==="u8")return{u8:null};if(e==="u16")return{u16:null};if(e==="u32")return{u32:null};if(e==="u64")return{u64:null};if(e==="u128")return{u128:null};if(e==="u256")return{u256:null};if(e==="signer")return{signer:null};const n=e.match(DI);if(n)return{vector:Sr.parseFromStr(n[1],r)};const s=e.match(HI);if(s)return{struct:{address:r?xe(s[1]):s[1],module:s[2],name:s[3],typeParams:s[5]===void 0?[]:Sr.parseStructTypeArgs(s[5],r)}};throw new Error(`Encountered unexpected token when parsing type args for ${e}`)}static parseStructTypeArgs(e,r=!1){return Zw(e).map(n=>Sr.parseFromStr(n,r))}static tagToString(e){if("bool"in e)return"bool";if("u8"in e)return"u8";if("u16"in e)return"u16";if("u32"in e)return"u32";if("u64"in e)return"u64";if("u128"in e)return"u128";if("u256"in e)return"u256";if("address"in e)return"address";if("signer"in e)return"signer";if("vector"in e)return`vector<${Sr.tagToString(e.vector)}>`;if("struct"in e){const r=e.struct,n=r.typeParams.map(Sr.tagToString).join(", ");return`${r.address}::${r.module}::${r.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}function zI(t){return _.u64({name:"unsafe_u64",...t}).transform({input:e=>e,output:e=>Number(e)})}function VI(t){return _.enum("Option",{None:null,Some:t})}const Ne=_.bytes(Su).transform({validate:t=>{const e=typeof t=="string"?t:ji(t);if(!e||!vr(xe(e)))throw new Error(`Invalid Sui address ${e}`)},input:t=>typeof t=="string"?Gw(xe(t)):t,output:t=>xe(ji(t))}),xr=_.vector(_.u8()).transform({name:"ObjectDigest",input:t=>na(t),output:t=>vu(new Uint8Array(t)),validate:t=>{if(na(t).length!==32)throw new Error("ObjectDigest must be 32 bytes")}}),or=_.struct("SuiObjectRef",{objectId:Ne,version:_.u64(),digest:xr}),a2=_.struct("SharedObjectRef",{objectId:Ne,initialSharedVersion:_.u64(),mutable:_.bool()}),c2=_.enum("ObjectArg",{ImmOrOwnedObject:or,SharedObject:a2,Receiving:or}),xs=_.enum("Owner",{AddressOwner:Ne,ObjectOwner:Ne,Shared:_.struct("Shared",{initialSharedVersion:_.u64()}),Immutable:null,ConsensusAddressOwner:_.struct("ConsensusAddressOwner",{owner:Ne,startVersion:_.u64()})}),u2=_.enum("CallArg",{Pure:_.struct("Pure",{bytes:_.vector(_.u8()).transform({input:t=>typeof t=="string"?Gt(t):t,output:t=>wt(new Uint8Array(t))})}),Object:c2}),Kh=_.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:_.lazy(()=>Kh),struct:_.lazy(()=>y2),u16:null,u32:null,u256:null}),Zh=Kh.transform({input:t=>typeof t=="string"?Sr.parseFromStr(t,!0):t,output:t=>Sr.tagToString(t)}),Gr=_.enum("Argument",{GasCoin:null,Input:_.u16(),Result:_.u16(),NestedResult:_.tuple([_.u16(),_.u16()])}),f2=_.struct("ProgrammableMoveCall",{package:Ne,module:_.string(),function:_.string(),typeArguments:_.vector(Zh),arguments:_.vector(Gr)}),l2=_.enum("Command",{MoveCall:f2,TransferObjects:_.struct("TransferObjects",{objects:_.vector(Gr),address:Gr}),SplitCoins:_.struct("SplitCoins",{coin:Gr,amounts:_.vector(Gr)}),MergeCoins:_.struct("MergeCoins",{destination:Gr,sources:_.vector(Gr)}),Publish:_.struct("Publish",{modules:_.vector(_.vector(_.u8()).transform({input:t=>typeof t=="string"?Gt(t):t,output:t=>wt(new Uint8Array(t))})),dependencies:_.vector(Ne)}),MakeMoveVec:_.struct("MakeMoveVec",{type:VI(Zh).transform({input:t=>t===null?{None:!0}:{Some:t},output:t=>t.Some??null}),elements:_.vector(Gr)}),Upgrade:_.struct("Upgrade",{modules:_.vector(_.vector(_.u8()).transform({input:t=>typeof t=="string"?Gt(t):t,output:t=>wt(new Uint8Array(t))})),dependencies:_.vector(Ne),package:Ne,ticket:Gr})}),d2=_.struct("ProgrammableTransaction",{inputs:_.vector(u2),commands:_.vector(l2)}),h2=_.enum("TransactionKind",{ProgrammableTransaction:d2,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),p2=_.enum("TransactionExpiration",{None:null,Epoch:zI()}),y2=_.struct("StructTag",{address:Ne,module:_.string(),name:_.string(),typeParams:_.vector(Kh)}),m2=_.struct("GasData",{payment:_.vector(or),owner:Ne,price:_.u64(),budget:_.u64()}),b2=_.struct("TransactionDataV1",{kind:h2,sender:Ne,gasData:m2,expiration:p2}),g2=_.enum("TransactionData",{V1:b2}),w2=_.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),v2=_.enum("IntentVersion",{V0:null}),E2=_.enum("AppId",{Sui:null}),S2=_.struct("Intent",{scope:w2,version:v2,appId:E2});function A2(t){return _.struct(`IntentMessage<${t.name}>`,{intent:S2,value:t})}const x2=_.enum("CompressedSignature",{ED25519:_.fixedArray(64,_.u8()),Secp256k1:_.fixedArray(64,_.u8()),Secp256r1:_.fixedArray(64,_.u8()),ZkLogin:_.vector(_.u8()),Passkey:_.vector(_.u8())}),k2=_.enum("PublicKey",{ED25519:_.fixedArray(32,_.u8()),Secp256k1:_.fixedArray(33,_.u8()),Secp256r1:_.fixedArray(33,_.u8()),ZkLogin:_.vector(_.u8()),Passkey:_.fixedArray(33,_.u8())}),T2=_.struct("MultiSigPkMap",{pubKey:k2,weight:_.u8()}),_2=_.struct("MultiSigPublicKey",{pk_map:_.vector(T2),threshold:_.u16()}),qI=_.struct("MultiSig",{sigs:_.vector(x2),bitmap:_.u16(),multisig_pk:_2}),GI=_.vector(_.u8()).transform({input:t=>typeof t=="string"?Gt(t):t,output:t=>wt(new Uint8Array(t))}),P2=_.struct("SenderSignedTransaction",{intentMessage:A2(g2),txSignatures:_.vector(GI)}),WI=_.vector(P2,{name:"SenderSignedData"}),KI=_.struct("PasskeyAuthenticator",{authenticatorData:_.vector(_.u8()),clientDataJson:_.string(),userSignature:_.vector(_.u8())}),ZI=_.enum("PackageUpgradeError",{UnableToFetchPackage:_.struct("UnableToFetchPackage",{packageId:Ne}),NotAPackage:_.struct("NotAPackage",{objectId:Ne}),IncompatibleUpgrade:null,DigestDoesNotMatch:_.struct("DigestDoesNotMatch",{digest:_.vector(_.u8())}),UnknownUpgradePolicy:_.struct("UnknownUpgradePolicy",{policy:_.u8()}),PackageIDDoesNotMatch:_.struct("PackageIDDoesNotMatch",{packageId:Ne,ticketId:Ne})}),YI=_.struct("ModuleId",{address:Ne,name:_.string()}),Yy=_.struct("MoveLocation",{module:YI,function:_.u16(),instruction:_.u16(),functionName:_.option(_.string())}),XI=_.enum("CommandArgumentError",{TypeMismatch:null,InvalidBCSBytes:null,InvalidUsageOfPureArg:null,InvalidArgumentToPrivateEntryFunction:null,IndexOutOfBounds:_.struct("IndexOutOfBounds",{idx:_.u16()}),SecondaryIndexOutOfBounds:_.struct("SecondaryIndexOutOfBounds",{resultIdx:_.u16(),secondaryIdx:_.u16()}),InvalidResultArity:_.struct("InvalidResultArity",{resultIdx:_.u16()}),InvalidGasCoinUsage:null,InvalidValueUsage:null,InvalidObjectByValue:null,InvalidObjectByMutRef:null,SharedObjectOperationNotAllowed:null}),JI=_.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),QI=_.enum("ExecutionFailureStatus",{InsufficientGas:null,InvalidGasObject:null,InvariantViolation:null,FeatureNotYetSupported:null,MoveObjectTooBig:_.struct("MoveObjectTooBig",{objectSize:_.u64(),maxObjectSize:_.u64()}),MovePackageTooBig:_.struct("MovePackageTooBig",{objectSize:_.u64(),maxObjectSize:_.u64()}),CircularObjectOwnership:_.struct("CircularObjectOwnership",{object:Ne}),InsufficientCoinBalance:null,CoinBalanceOverflow:null,PublishErrorNonZeroAddress:null,SuiMoveVerificationError:null,MovePrimitiveRuntimeError:_.option(Yy),MoveAbort:_.tuple([Yy,_.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:_.struct("CommandArgumentError",{argIdx:_.u16(),kind:XI}),TypeArgumentError:_.struct("TypeArgumentError",{argumentIdx:_.u16(),kind:JI}),UnusedValueWithoutDrop:_.struct("UnusedValueWithoutDrop",{resultIdx:_.u16(),secondaryIdx:_.u16()}),InvalidPublicFunctionReturnType:_.struct("InvalidPublicFunctionReturnType",{idx:_.u16()}),InvalidTransferObject:null,EffectsTooLarge:_.struct("EffectsTooLarge",{currentSize:_.u64(),maxSize:_.u64()}),PublishUpgradeMissingDependency:null,PublishUpgradeDependencyDowngrade:null,PackageUpgradeError:_.struct("PackageUpgradeError",{upgradeError:ZI}),WrittenObjectsTooLarge:_.struct("WrittenObjectsTooLarge",{currentSize:_.u64(),maxSize:_.u64()}),CertificateDenied:null,SuiMoveVerificationTimedout:null,SharedObjectOperationNotAllowed:null,InputObjectDeleted:null,ExecutionCancelledDueToSharedObjectCongestion:_.struct("ExecutionCancelledDueToSharedObjectCongestion",{congestedObjects:_.vector(Ne)}),AddressDeniedForCoin:_.struct("AddressDeniedForCoin",{address:Ne,coinType:_.string()}),CoinTypeGlobalPause:_.struct("CoinTypeGlobalPause",{coinType:_.string()}),ExecutionCancelledDueToRandomnessUnavailable:null}),I2=_.enum("ExecutionStatus",{Success:null,Failed:_.struct("ExecutionFailed",{error:QI,command:_.option(_.u64())})}),O2=_.struct("GasCostSummary",{computationCost:_.u64(),storageCost:_.u64(),storageRebate:_.u64(),nonRefundableStorageFee:_.u64()}),eO=_.struct("TransactionEffectsV1",{status:I2,executedEpoch:_.u64(),gasUsed:O2,modifiedAtVersions:_.vector(_.tuple([Ne,_.u64()])),sharedObjects:_.vector(or),transactionDigest:xr,created:_.vector(_.tuple([or,xs])),mutated:_.vector(_.tuple([or,xs])),unwrapped:_.vector(_.tuple([or,xs])),deleted:_.vector(or),unwrappedThenDeleted:_.vector(or),wrapped:_.vector(or),gasObject:_.tuple([or,xs]),eventsDigest:_.option(xr),dependencies:_.vector(xr)}),Yh=_.tuple([_.u64(),xr]),tO=_.enum("ObjectIn",{NotExist:null,Exist:_.tuple([Yh,xs])}),rO=_.enum("ObjectOut",{NotExist:null,ObjectWrite:_.tuple([xr,xs]),PackageWrite:Yh}),nO=_.enum("IDOperation",{None:null,Created:null,Deleted:null}),sO=_.struct("EffectsObjectChange",{inputState:tO,outputState:rO,idOperation:nO}),iO=_.enum("UnchangedSharedKind",{ReadOnlyRoot:Yh,MutateDeleted:_.u64(),ReadDeleted:_.u64(),Cancelled:_.u64(),PerEpochConfig:null}),oO=_.struct("TransactionEffectsV2",{status:I2,executedEpoch:_.u64(),gasUsed:O2,transactionDigest:xr,gasObjectIndex:_.option(_.u32()),eventsDigest:_.option(xr),dependencies:_.vector(xr),lamportVersion:_.u64(),changedObjects:_.vector(_.tuple([Ne,sO])),unchangedSharedObjects:_.vector(_.tuple([Ne,iO])),auxDataDigest:_.option(xr)}),aO=_.enum("TransactionEffects",{V1:eO,V2:oO});function ko(t){switch(t){case"u8":return _.u8();case"u16":return _.u16();case"u32":return _.u32();case"u64":return _.u64();case"u128":return _.u128();case"u256":return _.u256();case"bool":return _.bool();case"string":return _.string();case"id":case"address":return Ne}const e=t.match(/^(vector|option)<(.+)>$/);if(e){const[r,n]=e.slice(1);return r==="vector"?_.vector(ko(n)):_.option(ko(n))}throw new Error(`Invalid Pure type name: ${t}`)}const he={..._,U8:_.u8(),U16:_.u16(),U32:_.u32(),U64:_.u64(),U128:_.u128(),U256:_.u256(),ULEB128:_.uleb128(),Bool:_.bool(),String:_.string(),Address:Ne,AppId:E2,Argument:Gr,CallArg:u2,Command:l2,CompressedSignature:x2,GasData:m2,Intent:S2,IntentMessage:A2,IntentScope:w2,IntentVersion:v2,MultiSig:qI,MultiSigPkMap:T2,MultiSigPublicKey:_2,ObjectArg:c2,ObjectDigest:xr,Owner:xs,PasskeyAuthenticator:KI,ProgrammableMoveCall:f2,ProgrammableTransaction:d2,PublicKey:k2,SenderSignedData:WI,SenderSignedTransaction:P2,SharedObjectRef:a2,StructTag:y2,SuiObjectRef:or,TransactionData:g2,TransactionDataV1:b2,TransactionEffects:aO,TransactionExpiration:p2,TransactionKind:h2,TypeTag:Zh};var un;function cO(t){return{lang:(t==null?void 0:t.lang)??(un==null?void 0:un.lang),message:t==null?void 0:t.message,abortEarly:(t==null?void 0:t.abortEarly)??(un==null?void 0:un.abortEarly),abortPipeEarly:(t==null?void 0:t.abortPipeEarly)??(un==null?void 0:un.abortPipeEarly)}}var yl;function uO(t){return yl==null?void 0:yl.get(t)}var ml;function fO(t){return ml==null?void 0:ml.get(t)}var bl;function lO(t,e){var r;return(r=bl==null?void 0:bl.get(t))==null?void 0:r.get(e)}function B2(t){var r,n;const e=typeof t;return e==="string"?`"${t}"`:e==="number"||e==="bigint"||e==="boolean"?`${t}`:e==="object"||e==="function"?(t&&((n=(r=Object.getPrototypeOf(t))==null?void 0:r.constructor)==null?void 0:n.name))??"null":e}function Xt(t,e,r,n,s){const i=s&&"input"in s?s.input:r.value,o=(s==null?void 0:s.expected)??t.expects??null,a=(s==null?void 0:s.received)??B2(i),c={kind:t.kind,type:t.type,input:i,expected:o,received:a,message:`Invalid ${e}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:t.requirement,path:s==null?void 0:s.path,issues:s==null?void 0:s.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},u=t.kind==="schema",f=(s==null?void 0:s.message)??t.message??lO(t.reference,c.lang)??(u?fO(c.lang):null)??n.message??uO(c.lang);f&&(c.message=typeof f=="function"?f(c):f),u&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function dO(t,e){return Object.hasOwn(t,e)&&e!=="__proto__"&&e!=="prototype"&&e!=="constructor"}var hO=class extends Error{constructor(e){super(e[0].message);ap(this,"issues");this.name="ValiError",this.issues=e}};function Ba(t,e){return{kind:"validation",type:"check",reference:Ba,async:!1,expects:null,requirement:t,message:e,_run(r,n){return r.typed&&!this.requirement(r.value)&&Xt(this,"input",r,n),r}}}function Ge(t){return{kind:"validation",type:"integer",reference:Ge,async:!1,expects:null,requirement:Number.isInteger,message:t,_run(e,r){return e.typed&&!this.requirement(e.value)&&Xt(this,"integer",e,r),e}}}function Au(t){return{kind:"transformation",type:"transform",reference:Au,async:!1,operation:t,_run(e){return e.value=this.operation(e.value),e}}}function Xh(t,e,r){return typeof t.default=="function"?t.default(e,r):t.default}function Ad(t,e){return!t._run({typed:!1,value:e},{abortEarly:!0}).issues}function fe(t,e){return{kind:"schema",type:"array",reference:fe,expects:"Array",async:!1,item:t,message:e,_run(r,n){var i;const s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let o=0;o<s.length;o++){const a=s[o],c=this.item._run({typed:!1,value:a},n);if(c.issues){const u={type:"array",origin:"value",input:s,key:o,value:a};for(const f of c.issues)f.path?f.path.unshift(u):f.path=[u],(i=r.issues)==null||i.push(f);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else Xt(this,"type",r,n);return r}}}function Jh(t){return{kind:"schema",type:"bigint",reference:Jh,expects:"bigint",async:!1,message:t,_run(e,r){return typeof e.value=="bigint"?e.typed=!0:Xt(this,"type",e,r),e}}}function Xi(t){return{kind:"schema",type:"boolean",reference:Xi,expects:"boolean",async:!1,message:t,_run(e,r){return typeof e.value=="boolean"?e.typed=!0:Xt(this,"type",e,r),e}}}function sa(t){return{kind:"schema",type:"lazy",reference:sa,expects:"unknown",async:!1,getter:t,_run(e,r){return this.getter(e.value)._run(e,r)}}}function de(t,e){return{kind:"schema",type:"literal",reference:de,expects:B2(t),async:!1,literal:t,message:e,_run(r,n){return r.value===this.literal?r.typed=!0:Xt(this,"type",r,n),r}}}function Se(t,...e){const r={kind:"schema",type:"nullable",reference:Se,expects:`${t.expects} | null`,async:!1,wrapped:t,_run(n,s){return n.value===null&&("default"in this&&(n.value=Xh(this,n,s)),n.value===null)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in e&&(r.default=e[0]),r}function Li(t,...e){const r={kind:"schema",type:"nullish",reference:Li,expects:`${t.expects} | null | undefined`,async:!1,wrapped:t,_run(n,s){return(n.value===null||n.value===void 0)&&("default"in this&&(n.value=Xh(this,n,s)),n.value===null||n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in e&&(r.default=e[0]),r}function De(t){return{kind:"schema",type:"number",reference:De,expects:"number",async:!1,message:t,_run(e,r){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:Xt(this,"type",e,r),e}}}function te(t,e){return{kind:"schema",type:"object",reference:te,expects:"Object",async:!1,entries:t,message:e,_run(r,n){var i;const s=r.value;if(s&&typeof s=="object"){r.typed=!0,r.value={};for(const o in this.entries){const a=s[o],c=this.entries[o]._run({typed:!1,value:a},n);if(c.issues){const u={type:"object",origin:"value",input:s,key:o,value:a};for(const f of c.issues)f.path?f.path.unshift(u):f.path=[u],(i=r.issues)==null||i.push(f);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),(c.value!==void 0||o in s)&&(r.value[o]=c.value)}}else Xt(this,"type",r,n);return r}}}function ot(t,...e){const r={kind:"schema",type:"optional",reference:ot,expects:`${t.expects} | undefined`,async:!1,wrapped:t,_run(n,s){return n.value===void 0&&("default"in this&&(n.value=Xh(this,n,s)),n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in e&&(r.default=e[0]),r}function ia(t,e,r){return{kind:"schema",type:"record",reference:ia,expects:"Object",async:!1,key:t,value:e,message:r,_run(n,s){var o,a;const i=n.value;if(i&&typeof i=="object"){n.typed=!0,n.value={};for(const c in i)if(dO(i,c)){const u=i[c],f=this.key._run({typed:!1,value:c},s);if(f.issues){const p={type:"object",origin:"key",input:i,key:c,value:u};for(const d of f.issues)d.path=[p],(o=n.issues)==null||o.push(d);if(n.issues||(n.issues=f.issues),s.abortEarly){n.typed=!1;break}}const l=this.value._run({typed:!1,value:u},s);if(l.issues){const p={type:"object",origin:"value",input:i,key:c,value:u};for(const d of l.issues)d.path?d.path.unshift(p):d.path=[p],(a=n.issues)==null||a.push(d);if(n.issues||(n.issues=l.issues),s.abortEarly){n.typed=!1;break}}(!f.typed||!l.typed)&&(n.typed=!1),f.typed&&(n.value[f.value]=l.value)}}else Xt(this,"type",n,s);return n}}}function ye(t){return{kind:"schema",type:"string",reference:ye,expects:"string",async:!1,message:t,_run(e,r){return typeof e.value=="string"?e.typed=!0:Xt(this,"type",e,r),e}}}function Qh(t,e){return{kind:"schema",type:"tuple",reference:Qh,expects:"Array",async:!1,items:t,message:e,_run(r,n){var i;const s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let o=0;o<this.items.length;o++){const a=s[o],c=this.items[o]._run({typed:!1,value:a},n);if(c.issues){const u={type:"array",origin:"value",input:s,key:o,value:a};for(const f of c.issues)f.path?f.path.unshift(u):f.path=[u],(i=r.issues)==null||i.push(f);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else Xt(this,"type",r,n);return r}}}function Xy(t){let e;if(t)for(const r of t)e?e.push(...r.issues):e=r.issues;return e}function mt(t,e){return{kind:"schema",type:"union",reference:mt,expects:[...new Set(t.map(r=>r.expects))].join(" | ")||"never",async:!1,options:t,message:e,_run(r,n){let s,i,o;for(const a of this.options){const c=a._run({typed:!1,value:r.value},n);if(c.typed)if(c.issues)i?i.push(c):i=[c];else{s=c;break}else o?o.push(c):o=[c]}if(s)return s;if(i){if(i.length===1)return i[0];Xt(this,"type",r,n,{issues:Xy(i)}),r.typed=!0}else{if((o==null?void 0:o.length)===1)return o[0];Xt(this,"type",r,n,{issues:Xy(o)})}return r}}}function Ws(){return{kind:"schema",type:"unknown",reference:Ws,expects:"unknown",async:!1,_run(t){return t.typed=!0,t}}}function qe(t,e,r){const n=t._run({typed:!1,value:e},cO(r));if(n.issues)throw new hO(n.issues);return n.value}function Ie(...t){return{...t[0],pipe:t,_run(e,r){for(let n=0;n<t.length;n++){if(e.issues&&(t[n].kind==="schema"||t[n].kind==="transformation")){e.typed=!1;break}(!e.issues||!r.abortEarly&&!r.abortPipeEarly)&&(e=t[n]._run(e,r))}return e}}}function ri(t){const e=Object.entries(t).map(([r,n])=>te({[r]:n}));return Ie(mt(e),Au(r=>({...r,$kind:Object.keys(r)[0]})))}const Ji=Ie(ye(),Au(t=>xe(t)),Ba(vr)),Wt=Ji,Ks=ye(),Lt=Ie(mt([ye(),Ie(De(),Ge())]),Ba(t=>{try{return BigInt(t),BigInt(t)>=0&&BigInt(t)<=18446744073709551615n}catch{return!1}},"Invalid u64")),us=te({objectId:Ji,version:Lt,digest:ye()}),Fe=Ie(mt([te({GasCoin:de(!0)}),te({Input:Ie(De(),Ge()),type:ot(de("pure"))}),te({Input:Ie(De(),Ge()),type:ot(de("object"))}),te({Result:Ie(De(),Ge())}),te({NestedResult:Qh([Ie(De(),Ge()),Ie(De(),Ge())])})]),Au(t=>({...t,$kind:Object.keys(t)[0]}))),pO=te({budget:Se(Lt),price:Se(Lt),owner:Se(Ji),payment:Se(fe(us))}),xd=mt([de("address"),de("bool"),de("u8"),de("u16"),de("u32"),de("u64"),de("u128"),de("u256"),te({vector:sa(()=>xd)}),te({datatype:te({package:ye(),module:ye(),type:ye(),typeParameters:fe(sa(()=>xd))})}),te({typeParameter:Ie(De(),Ge())})]),yO=te({ref:Se(mt([de("&"),de("&mut")])),body:xd}),mO=te({package:Wt,module:ye(),function:ye(),typeArguments:fe(ye()),arguments:fe(Fe),_argumentTypes:ot(Se(fe(yO)))}),bO=te({name:ye(),inputs:ia(ye(),mt([Fe,fe(Fe)])),data:ia(ye(),Ws())}),gO=ri({MoveCall:mO,TransferObjects:te({objects:fe(Fe),address:Fe}),SplitCoins:te({coin:Fe,amounts:fe(Fe)}),MergeCoins:te({destination:Fe,sources:fe(Fe)}),Publish:te({modules:fe(Ks),dependencies:fe(Wt)}),MakeMoveVec:te({type:Se(ye()),elements:fe(Fe)}),Upgrade:te({modules:fe(Ks),dependencies:fe(Wt),package:Wt,ticket:Fe}),$Intent:bO}),C2=ri({ImmOrOwnedObject:us,SharedObject:te({objectId:Wt,initialSharedVersion:Lt,mutable:Xi()}),Receiving:us}),wO=ri({Object:C2,Pure:te({bytes:Ks}),UnresolvedPure:te({value:Ws()}),UnresolvedObject:te({objectId:Wt,version:ot(Se(Lt)),digest:ot(Se(ye())),initialSharedVersion:ot(Se(Lt)),mutable:ot(Se(Xi()))})}),Jy=ri({Object:C2,Pure:te({bytes:Ks})}),$2=ri({None:de(!0),Epoch:Lt}),dc=te({version:de(2),sender:Li(Ji),expiration:Li($2),gasData:pO,inputs:fe(wO),commands:fe(gO)}),bs={MoveCall(t){const[e,r="",n=""]="target"in t?t.target.split("::"):[t.package,t.module,t.function];return{$kind:"MoveCall",MoveCall:{package:e,module:r,function:n,typeArguments:t.typeArguments??[],arguments:t.arguments??[]}}},TransferObjects(t,e){return{$kind:"TransferObjects",TransferObjects:{objects:t.map(r=>qe(Fe,r)),address:qe(Fe,e)}}},SplitCoins(t,e){return{$kind:"SplitCoins",SplitCoins:{coin:qe(Fe,t),amounts:e.map(r=>qe(Fe,r))}}},MergeCoins(t,e){return{$kind:"MergeCoins",MergeCoins:{destination:qe(Fe,t),sources:e.map(r=>qe(Fe,r))}}},Publish({modules:t,dependencies:e}){return{$kind:"Publish",Publish:{modules:t.map(r=>typeof r=="string"?r:wt(new Uint8Array(r))),dependencies:e.map(r=>vn(r))}}},Upgrade({modules:t,dependencies:e,package:r,ticket:n}){return{$kind:"Upgrade",Upgrade:{modules:t.map(s=>typeof s=="string"?s:wt(new Uint8Array(s))),dependencies:e.map(s=>vn(s)),package:r,ticket:qe(Fe,n)}}},MakeMoveVec({type:t,elements:e}){return{$kind:"MakeMoveVec",MakeMoveVec:{type:t??null,elements:e.map(r=>qe(Fe,r))}}},Intent({name:t,inputs:e={},data:r={}}){return{$kind:"$Intent",$Intent:{name:t,inputs:Object.fromEntries(Object.entries(e).map(([n,s])=>[n,Array.isArray(s)?s.map(i=>qe(Fe,i)):qe(Fe,s)])),data:r}}}},kd=te({digest:ye(),objectId:ye(),version:mt([Ie(De(),Ge()),ye(),Jh()])}),vO=ri({ImmOrOwned:kd,Shared:te({objectId:Wt,initialSharedVersion:Lt,mutable:Xi()}),Receiving:kd}),Qy=ri({Object:vO,Pure:fe(Ie(De(),Ge()))}),R2=mt([te({kind:de("Input"),index:Ie(De(),Ge()),value:Ws(),type:ot(de("object"))}),te({kind:de("Input"),index:Ie(De(),Ge()),value:Ws(),type:de("pure")})]),EO=mt([te({Epoch:Ie(De(),Ge())}),te({None:Se(de(!0))})]),em=Ie(mt([De(),ye(),Jh()]),Ba(t=>{if(!["string","number","bigint"].includes(typeof t))return!1;try{return BigInt(t),!0}catch{return!1}})),ep=mt([te({bool:Se(de(!0))}),te({u8:Se(de(!0))}),te({u64:Se(de(!0))}),te({u128:Se(de(!0))}),te({address:Se(de(!0))}),te({signer:Se(de(!0))}),te({vector:sa(()=>ep)}),te({struct:sa(()=>SO)}),te({u16:Se(de(!0))}),te({u32:Se(de(!0))}),te({u256:Se(de(!0))})]),SO=te({address:ye(),module:ye(),name:ye(),typeParams:fe(ep)}),AO=te({budget:ot(em),price:ot(em),payment:ot(fe(kd)),owner:ot(ye())}),xO=[R2,te({kind:de("GasCoin")}),te({kind:de("Result"),index:Ie(De(),Ge())}),te({kind:de("NestedResult"),index:Ie(De(),Ge()),resultIndex:Ie(De(),Ge())})],On=mt([...xO]),kO=te({kind:de("MoveCall"),target:Ie(ye(),Ba(t=>t.split("::").length===3)),typeArguments:fe(ye()),arguments:fe(On)}),TO=te({kind:de("TransferObjects"),objects:fe(On),address:On}),_O=te({kind:de("SplitCoins"),coin:On,amounts:fe(On)}),PO=te({kind:de("MergeCoins"),destination:On,sources:fe(On)}),IO=te({kind:de("MakeMoveVec"),type:mt([te({Some:ep}),te({None:Se(de(!0))})]),objects:fe(On)}),OO=te({kind:de("Publish"),modules:fe(fe(Ie(De(),Ge()))),dependencies:fe(ye())}),BO=te({kind:de("Upgrade"),modules:fe(fe(Ie(De(),Ge()))),dependencies:fe(ye()),packageId:ye(),ticket:On}),CO=[kO,TO,_O,PO,OO,BO,IO],$O=mt([...CO]);te({version:de(1),sender:ot(ye()),expiration:Li(EO),gasConfig:AO,inputs:fe(R2),transactions:fe($O)});function tm(t){var r;const e=t.inputs.map((n,s)=>{if(n.Object)return{kind:"Input",index:s,value:{Object:n.Object.ImmOrOwnedObject?{ImmOrOwned:n.Object.ImmOrOwnedObject}:n.Object.Receiving?{Receiving:{digest:n.Object.Receiving.digest,version:n.Object.Receiving.version,objectId:n.Object.Receiving.objectId}}:{Shared:{mutable:n.Object.SharedObject.mutable,initialSharedVersion:n.Object.SharedObject.initialSharedVersion,objectId:n.Object.SharedObject.objectId}}},type:"object"};if(n.Pure)return{kind:"Input",index:s,value:{Pure:Array.from(Gt(n.Pure.bytes))},type:"pure"};if(n.UnresolvedPure)return{kind:"Input",type:"pure",index:s,value:n.UnresolvedPure.value};if(n.UnresolvedObject)return{kind:"Input",type:"object",index:s,value:n.UnresolvedObject.objectId};throw new Error("Invalid input")});return{version:1,sender:t.sender??void 0,expiration:((r=t.expiration)==null?void 0:r.$kind)==="Epoch"?{Epoch:Number(t.expiration.Epoch)}:t.expiration?{None:!0}:null,gasConfig:{owner:t.gasData.owner??void 0,budget:t.gasData.budget??void 0,price:t.gasData.price??void 0,payment:t.gasData.payment??void 0},inputs:e,transactions:t.commands.map(n=>{if(n.MakeMoveVec)return{kind:"MakeMoveVec",type:n.MakeMoveVec.type===null?{None:!0}:{Some:Sr.parseFromStr(n.MakeMoveVec.type)},objects:n.MakeMoveVec.elements.map(s=>fn(s,e))};if(n.MergeCoins)return{kind:"MergeCoins",destination:fn(n.MergeCoins.destination,e),sources:n.MergeCoins.sources.map(s=>fn(s,e))};if(n.MoveCall)return{kind:"MoveCall",target:`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`,typeArguments:n.MoveCall.typeArguments,arguments:n.MoveCall.arguments.map(s=>fn(s,e))};if(n.Publish)return{kind:"Publish",modules:n.Publish.modules.map(s=>Array.from(Gt(s))),dependencies:n.Publish.dependencies};if(n.SplitCoins)return{kind:"SplitCoins",coin:fn(n.SplitCoins.coin,e),amounts:n.SplitCoins.amounts.map(s=>fn(s,e))};if(n.TransferObjects)return{kind:"TransferObjects",objects:n.TransferObjects.objects.map(s=>fn(s,e)),address:fn(n.TransferObjects.address,e)};if(n.Upgrade)return{kind:"Upgrade",modules:n.Upgrade.modules.map(s=>Array.from(Gt(s))),dependencies:n.Upgrade.dependencies,packageId:n.Upgrade.package,ticket:fn(n.Upgrade.ticket,e)};throw new Error(`Unknown transaction ${Object.keys(n)}`)})}}function fn(t,e){if(t.$kind==="GasCoin")return{kind:"GasCoin"};if(t.$kind==="Result")return{kind:"Result",index:t.Result};if(t.$kind==="NestedResult")return{kind:"NestedResult",index:t.NestedResult[0],resultIndex:t.NestedResult[1]};if(t.$kind==="Input")return e[t.Input];throw new Error(`Invalid argument ${Object.keys(t)}`)}function RO(t){var e,r,n;return qe(dc,{version:2,sender:t.sender??null,expiration:t.expiration?"Epoch"in t.expiration?{Epoch:t.expiration.Epoch}:{None:!0}:null,gasData:{owner:t.gasConfig.owner??null,budget:((e=t.gasConfig.budget)==null?void 0:e.toString())??null,price:((r=t.gasConfig.price)==null?void 0:r.toString())??null,payment:((n=t.gasConfig.payment)==null?void 0:n.map(s=>({digest:s.digest,objectId:s.objectId,version:s.version.toString()})))??null},inputs:t.inputs.map(s=>{if(s.kind==="Input"){if(Ad(Qy,s.value)){const i=qe(Qy,s.value);if(i.Object){if(i.Object.ImmOrOwned)return{Object:{ImmOrOwnedObject:{objectId:i.Object.ImmOrOwned.objectId,version:String(i.Object.ImmOrOwned.version),digest:i.Object.ImmOrOwned.digest}}};if(i.Object.Shared)return{Object:{SharedObject:{mutable:i.Object.Shared.mutable??null,initialSharedVersion:i.Object.Shared.initialSharedVersion,objectId:i.Object.Shared.objectId}}};if(i.Object.Receiving)return{Object:{Receiving:{digest:i.Object.Receiving.digest,version:String(i.Object.Receiving.version),objectId:i.Object.Receiving.objectId}}};throw new Error("Invalid object input")}return{Pure:{bytes:wt(new Uint8Array(i.Pure))}}}return s.type==="object"?{UnresolvedObject:{objectId:s.value}}:{UnresolvedPure:{value:s.value}}}throw new Error("Invalid input")}),commands:t.transactions.map(s=>{switch(s.kind){case"MakeMoveVec":return{MakeMoveVec:{type:"Some"in s.type?Sr.tagToString(s.type.Some):null,elements:s.objects.map(i=>ln(i))}};case"MergeCoins":return{MergeCoins:{destination:ln(s.destination),sources:s.sources.map(i=>ln(i))}};case"MoveCall":{const[i,o,a]=s.target.split("::");return{MoveCall:{package:i,module:o,function:a,typeArguments:s.typeArguments,arguments:s.arguments.map(c=>ln(c))}}}case"Publish":return{Publish:{modules:s.modules.map(i=>wt(Uint8Array.from(i))),dependencies:s.dependencies}};case"SplitCoins":return{SplitCoins:{coin:ln(s.coin),amounts:s.amounts.map(i=>ln(i))}};case"TransferObjects":return{TransferObjects:{objects:s.objects.map(i=>ln(i)),address:ln(s.address)}};case"Upgrade":return{Upgrade:{modules:s.modules.map(i=>wt(Uint8Array.from(i))),dependencies:s.dependencies,package:s.packageId,ticket:ln(s.ticket)}}}throw new Error(`Unknown transaction ${Object.keys(s)}`)})})}function ln(t){switch(t.kind){case"GasCoin":return{GasCoin:!0};case"Result":return{Result:t.index};case"NestedResult":return{NestedResult:[t.index,t.resultIndex]};case"Input":return{Input:t.index}}}function Ca(t){return mt(Object.entries(t).map(([e,r])=>te({[e]:r})))}const br=Ca({GasCoin:de(!0),Input:Ie(De(),Ge()),Result:Ie(De(),Ge()),NestedResult:Qh([Ie(De(),Ge()),Ie(De(),Ge())])}),NO=te({budget:Se(Lt),price:Se(Lt),owner:Se(Ji),payment:Se(fe(us))}),UO=te({package:Wt,module:ye(),function:ye(),typeArguments:fe(ye()),arguments:fe(br)}),MO=te({name:ye(),inputs:ia(ye(),mt([br,fe(br)])),data:ia(ye(),Ws())}),FO=Ca({MoveCall:UO,TransferObjects:te({objects:fe(br),address:br}),SplitCoins:te({coin:br,amounts:fe(br)}),MergeCoins:te({destination:br,sources:fe(br)}),Publish:te({modules:fe(Ks),dependencies:fe(Wt)}),MakeMoveVec:te({type:Se(ye()),elements:fe(br)}),Upgrade:te({modules:fe(Ks),dependencies:fe(Wt),package:Wt,ticket:br}),$Intent:MO}),jO=Ca({ImmOrOwnedObject:us,SharedObject:te({objectId:Wt,initialSharedVersion:Lt,mutable:Xi()}),Receiving:us}),LO=Ca({Object:jO,Pure:te({bytes:Ks}),UnresolvedPure:te({value:Ws()}),UnresolvedObject:te({objectId:Wt,version:ot(Se(Lt)),digest:ot(Se(ye())),initialSharedVersion:ot(Se(Lt)),mutable:ot(Se(Xi()))})}),DO=Ca({None:de(!0),Epoch:Lt}),HO=te({version:de(2),sender:Li(Ji),expiration:Li(DO),gasData:NO,inputs:fe(LO),commands:fe(FO),digest:ot(Se(ye()))});function zO(t){return{$kind:"Pure",Pure:{bytes:t instanceof Uint8Array?wt(t):t.toBase64()}}}const kr={Pure:zO,ObjectRef({objectId:t,digest:e,version:r}){return{$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{digest:e,version:r,objectId:xe(t)}}}},SharedObjectRef({objectId:t,mutable:e,initialSharedVersion:r}){return{$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{mutable:e,initialSharedVersion:r,objectId:xe(t)}}}},ReceivingRef({objectId:t,digest:e,version:r}){return{$kind:"Object",Object:{$kind:"Receiving",Receiving:{digest:e,version:r,objectId:xe(t)}}}}};BigInt(1e9);const VO="0x1",N2="0x2",qO=vn("0x6"),GO=`${N2}::sui::SUI`;vn("0x5");const WO=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),nt=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),re=new Uint32Array(32);function zn(t,e,r,n,s,i){const o=s[i],a=s[i+1];let c=re[2*t],u=re[2*t+1],f=re[2*e],l=re[2*e+1],p=re[2*r],d=re[2*r+1],m=re[2*n],b=re[2*n+1],E=zm(c,f,o);u=Vm(E,u,l,a),c=E|0,{Dh:b,Dl:m}={Dh:b^u,Dl:m^c},{Dh:b,Dl:m}={Dh:kv(b,m),Dl:Tv(b)},{h:d,l:p}=Hm(d,p,b,m),{Bh:l,Bl:f}={Bh:l^d,Bl:f^p},{Bh:l,Bl:f}={Bh:Lm(l,f,24),Bl:Dm(l,f,24)},re[2*t]=c,re[2*t+1]=u,re[2*e]=f,re[2*e+1]=l,re[2*r]=p,re[2*r+1]=d,re[2*n]=m,re[2*n+1]=b}function Vn(t,e,r,n,s,i){const o=s[i],a=s[i+1];let c=re[2*t],u=re[2*t+1],f=re[2*e],l=re[2*e+1],p=re[2*r],d=re[2*r+1],m=re[2*n],b=re[2*n+1],E=zm(c,f,o);u=Vm(E,u,l,a),c=E|0,{Dh:b,Dl:m}={Dh:b^u,Dl:m^c},{Dh:b,Dl:m}={Dh:Lm(b,m,16),Dl:Dm(b,m,16)},{h:d,l:p}=Hm(d,p,b,m),{Bh:l,Bl:f}={Bh:l^d,Bl:f^p},{Bh:l,Bl:f}={Bh:Av(l,f,63),Bl:xv(l,f,63)},re[2*t]=c,re[2*t+1]=u,re[2*e]=f,re[2*e+1]=l,re[2*r]=p,re[2*r+1]=d,re[2*n]=m,re[2*n+1]=b}function KO(t,e={},r,n,s){if(ss(r),t<0||t>r)throw new Error("outputLen bigger than keyLen");const{key:i,salt:o,personalization:a}=e;if(i!==void 0&&(i.length<1||i.length>r))throw new Error("key length must be undefined or 1.."+r);if(o!==void 0&&o.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==s)throw new Error("personalization must be undefined or "+s)}class ZO extends $c{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,ss(e),ss(r),this.blockLen=e,this.outputLen=r,this.buffer=new Uint8Array(e),this.buffer32=Io(this.buffer)}update(e){os(this),e=En(e),is(e);const{blockLen:r,buffer:n,buffer32:s}=this,i=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<i;){this.pos===r&&(Kn(s),this.compress(s,0,!1),Kn(s),this.pos=0);const u=Math.min(r-this.pos,i-c),f=o+c;if(u===r&&!(f%4)&&c+u<i){const l=new Uint32Array(a,f,Math.floor((i-c)/4));Kn(l);for(let p=0;c+r<i;p+=s.length,c+=r)this.length+=r,this.compress(l,p,!1);Kn(l);continue}n.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){os(this),Rd(e,this);const{pos:r,buffer32:n}=this;this.finished=!0,Ir(this.buffer.subarray(r)),Kn(n),this.compress(n,0,!0),Kn(n);const s=Io(e);this.get().forEach((i,o)=>s[o]=dn(i))}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){const{buffer:r,length:n,finished:s,destroyed:i,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(r),e.destroyed=i,e.finished=s,e.length=n,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class YO extends ZO{constructor(e={}){const r=e.dkLen===void 0?64:e.dkLen;super(128,r),this.v0l=nt[0]|0,this.v0h=nt[1]|0,this.v1l=nt[2]|0,this.v1h=nt[3]|0,this.v2l=nt[4]|0,this.v2h=nt[5]|0,this.v3l=nt[6]|0,this.v3h=nt[7]|0,this.v4l=nt[8]|0,this.v4h=nt[9]|0,this.v5l=nt[10]|0,this.v5h=nt[11]|0,this.v6l=nt[12]|0,this.v6h=nt[13]|0,this.v7l=nt[14]|0,this.v7h=nt[15]|0,KO(r,e,64,16,16);let{key:n,personalization:s,salt:i}=e,o=0;if(n!==void 0&&(n=En(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=En(i);const a=Io(i);this.v4l^=dn(a[0]),this.v4h^=dn(a[1]),this.v5l^=dn(a[2]),this.v5h^=dn(a[3])}if(s!==void 0){s=En(s);const a=Io(s);this.v6l^=dn(a[0]),this.v6h^=dn(a[1]),this.v7l^=dn(a[2]),this.v7h^=dn(a[3])}if(n!==void 0){const a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:e,v0h:r,v1l:n,v1h:s,v2l:i,v2h:o,v3l:a,v3h:c,v4l:u,v4h:f,v5l:l,v5h:p,v6l:d,v6h:m,v7l:b,v7h:E}=this;return[e,r,n,s,i,o,a,c,u,f,l,p,d,m,b,E]}set(e,r,n,s,i,o,a,c,u,f,l,p,d,m,b,E){this.v0l=e|0,this.v0h=r|0,this.v1l=n|0,this.v1h=s|0,this.v2l=i|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=f|0,this.v5l=l|0,this.v5h=p|0,this.v6l=d|0,this.v6h=m|0,this.v7l=b|0,this.v7h=E|0}compress(e,r,n){this.get().forEach((c,u)=>re[u]=c),re.set(nt,16);let{h:s,l:i}=jm(BigInt(this.length));re[24]=nt[8]^i,re[25]=nt[9]^s,n&&(re[28]=~re[28],re[29]=~re[29]);let o=0;const a=WO;for(let c=0;c<12;c++)zn(0,4,8,12,e,r+2*a[o++]),Vn(0,4,8,12,e,r+2*a[o++]),zn(1,5,9,13,e,r+2*a[o++]),Vn(1,5,9,13,e,r+2*a[o++]),zn(2,6,10,14,e,r+2*a[o++]),Vn(2,6,10,14,e,r+2*a[o++]),zn(3,7,11,15,e,r+2*a[o++]),Vn(3,7,11,15,e,r+2*a[o++]),zn(0,5,10,15,e,r+2*a[o++]),Vn(0,5,10,15,e,r+2*a[o++]),zn(1,6,11,12,e,r+2*a[o++]),Vn(1,6,11,12,e,r+2*a[o++]),zn(2,7,8,13,e,r+2*a[o++]),Vn(2,7,8,13,e,r+2*a[o++]),zn(3,4,9,14,e,r+2*a[o++]),Vn(3,4,9,14,e,r+2*a[o++]);this.v0l^=re[0]^re[16],this.v0h^=re[1]^re[17],this.v1l^=re[2]^re[18],this.v1h^=re[3]^re[19],this.v2l^=re[4]^re[20],this.v2h^=re[5]^re[21],this.v3l^=re[6]^re[22],this.v3h^=re[7]^re[23],this.v4l^=re[8]^re[24],this.v4h^=re[9]^re[25],this.v5l^=re[10]^re[26],this.v5h^=re[11]^re[27],this.v6l^=re[12]^re[28],this.v6h^=re[13]^re[29],this.v7l^=re[14]^re[30],this.v7h^=re[15]^re[31],Ir(re)}destroy(){this.destroyed=!0,Ir(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const XO=Uv(t=>new YO(t)),U2=XO;function JO(t,e,r){const n=he.Address.serialize(t).toBytes(),s=he.TypeTag.serialize(e).toBytes(),i=he.u64().serialize(r.length).toBytes(),o=U2.create({dkLen:32});return o.update(new Uint8Array([240])),o.update(n),o.update(i),o.update(r),o.update(s),`0x${ji(o.digest().slice(0,32))}`}const QO="object",e4="ID",t4="ascii",r4="String",n4="string",s4="String",i4="option",o4="Option";function a4(t){const e=typeof t.body=="object"&&"datatype"in t.body?t.body.datatype:null;return!!e&&xe(e.package)===xe("0x2")&&e.module==="tx_context"&&e.type==="TxContext"}function Td(t){if(typeof t=="string")switch(t){case"address":return he.Address;case"bool":return he.Bool;case"u8":return he.U8;case"u16":return he.U16;case"u32":return he.U32;case"u64":return he.U64;case"u128":return he.U128;case"u256":return he.U256;default:throw new Error(`Unknown type signature ${t}`)}if("vector"in t){if(t.vector==="u8")return he.vector(he.U8).transform({input:r=>typeof r=="string"?new TextEncoder().encode(r):r,output:r=>r});const e=Td(t.vector);return e?he.vector(e):null}if("datatype"in t){const e=xe(t.datatype.package);if(e===xe(VO)){if(t.datatype.module===t4&&t.datatype.type===r4||t.datatype.module===n4&&t.datatype.type===s4)return he.String;if(t.datatype.module===i4&&t.datatype.type===o4){const r=Td(t.datatype.typeParameters[0]);return r?he.vector(r):null}}if(e===xe(N2)&&t.datatype.module===QO&&t.datatype.type===e4)return he.Address}return null}function c4(t){return typeof t=="object"&&"Reference"in t?{ref:"&",body:To(t.Reference)}:typeof t=="object"&&"MutableReference"in t?{ref:"&mut",body:To(t.MutableReference)}:{ref:null,body:To(t)}}function To(t){if(typeof t=="string")switch(t){case"Address":return"address";case"Bool":return"bool";case"U8":return"u8";case"U16":return"u16";case"U32":return"u32";case"U64":return"u64";case"U128":return"u128";case"U256":return"u256";default:throw new Error(`Unexpected type ${t}`)}if("Vector"in t)return{vector:To(t.Vector)};if("Struct"in t)return{datatype:{package:t.Struct.address,module:t.Struct.module,type:t.Struct.name,typeParameters:t.Struct.typeArguments.map(To)}};if("TypeParameter"in t)return{typeParameter:t.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(t)}`)}const u4=50,f4=1000n,l4=5e10;function M2(t){return async function(r,n,s){return await m4(r,t),await y4(r,t),n.onlyTransactionKind||(await d4(r,t),await h4(r,t),await p4(r,t)),await s()}}async function d4(t,e){t.gasConfig.price||(t.gasConfig.price=String(await e.getReferenceGasPrice()))}async function h4(t,e){if(t.gasConfig.budget)return;const r=await e.dryRunTransactionBlock({transactionBlock:t.build({overrides:{gasData:{budget:String(l4),payment:[]}}})});if(r.effects.status.status!=="success")throw new Error(`Dry run failed, could not automatically determine a budget: ${r.effects.status.error}`,{cause:r});const n=f4*BigInt(t.gasConfig.price||1n),s=BigInt(r.effects.gasUsed.computationCost)+n,i=s+BigInt(r.effects.gasUsed.storageCost)-BigInt(r.effects.gasUsed.storageRebate);t.gasConfig.budget=String(i>s?i:s)}async function p4(t,e){if(!t.gasConfig.payment){const n=(await e.getCoins({owner:t.gasConfig.owner||t.sender,coinType:GO})).data.filter(s=>!t.inputs.find(o=>{var a;return(a=o.Object)!=null&&a.ImmOrOwnedObject?s.coinObjectId===o.Object.ImmOrOwnedObject.objectId:!1})).map(s=>({objectId:s.coinObjectId,digest:s.digest,version:s.version}));if(!n.length)throw new Error("No valid gas coins found for the transaction.");t.gasConfig.payment=n.map(s=>qe(us,s))}}async function y4(t,e){const r=t.inputs.filter(f=>{var l;return f.UnresolvedObject&&!(f.UnresolvedObject.version||(l=f.UnresolvedObject)!=null&&l.initialSharedVersion)}),n=[...new Set(r.map(f=>vn(f.UnresolvedObject.objectId)))],s=n.length?Eu(n,u4):[],i=(await Promise.all(s.map(f=>e.multiGetObjects({ids:f,options:{showOwner:!0}})))).flat(),o=new Map(n.map((f,l)=>[f,i[l]])),a=Array.from(o).filter(([f,l])=>l.error).map(([f,l])=>JSON.stringify(l.error));if(a.length)throw new Error(`The following input objects are invalid: ${a.join(", ")}`);const c=i.map(f=>{if(f.error||!f.data)throw new Error(`Failed to fetch object: ${f.error}`);const l=f.data.owner,p=l&&typeof l=="object"?"Shared"in l?l.Shared.initial_shared_version:"ConsensusAddressOwner"in l?l.ConsensusAddressOwner.start_version:null:null;return{objectId:f.data.objectId,digest:f.data.digest,version:f.data.version,initialSharedVersion:p}}),u=new Map(n.map((f,l)=>[f,c[l]]));for(const[f,l]of t.inputs.entries()){if(!l.UnresolvedObject)continue;let p;const d=xe(l.UnresolvedObject.objectId),m=u.get(d);l.UnresolvedObject.initialSharedVersion??(m==null?void 0:m.initialSharedVersion)?p=kr.SharedObjectRef({objectId:d,initialSharedVersion:l.UnresolvedObject.initialSharedVersion||(m==null?void 0:m.initialSharedVersion),mutable:l.UnresolvedObject.mutable||b4(t,f)}):g4(t,f)&&(p=kr.ReceivingRef({objectId:d,digest:l.UnresolvedObject.digest??(m==null?void 0:m.digest),version:l.UnresolvedObject.version??(m==null?void 0:m.version)})),t.inputs[t.inputs.indexOf(l)]=p??kr.ObjectRef({objectId:d,digest:l.UnresolvedObject.digest??(m==null?void 0:m.digest),version:l.UnresolvedObject.version??(m==null?void 0:m.version)})}}async function m4(t,e){const{inputs:r,commands:n}=t,s=[],i=new Set;n.forEach(a=>{if(a.MoveCall){if(a.MoveCall._argumentTypes)return;if(a.MoveCall.arguments.map(f=>f.$kind==="Input"?t.inputs[f.Input]:null).some(f=>(f==null?void 0:f.UnresolvedPure)||(f==null?void 0:f.UnresolvedObject)&&typeof(f==null?void 0:f.UnresolvedObject.mutable)!="boolean")){const f=`${a.MoveCall.package}::${a.MoveCall.module}::${a.MoveCall.function}`;i.add(f),s.push(a.MoveCall)}}});const o=new Map;i.size>0&&await Promise.all([...i].map(async a=>{const[c,u,f]=a.split("::"),l=await e.getNormalizedMoveFunction({package:c,module:u,function:f});o.set(a,l.parameters.map(p=>c4(p)))})),s.length&&await Promise.all(s.map(async a=>{const c=o.get(`${a.package}::${a.module}::${a.function}`);if(!c)return;const f=c.length>0&&a4(c.at(-1))?c.slice(0,c.length-1):c;a._argumentTypes=f})),n.forEach(a=>{if(!a.MoveCall)return;const c=a.MoveCall,u=`${c.package}::${c.module}::${c.function}`,f=c._argumentTypes;if(f){if(f.length!==a.MoveCall.arguments.length)throw new Error(`Incorrect number of arguments for ${u}`);f.forEach((l,p)=>{var P,S;const d=c.arguments[p];if(d.$kind!=="Input")return;const m=r[d.Input];if(!m.UnresolvedPure&&!m.UnresolvedObject)return;const b=((P=m.UnresolvedPure)==null?void 0:P.value)??((S=m.UnresolvedObject)==null?void 0:S.objectId),E=Td(l.body);if(E){d.type="pure",r[r.indexOf(m)]=kr.Pure(E.serialize(b));return}if(typeof b!="string")throw new Error(`Expect the argument to be an object id string, got ${JSON.stringify(b,null,2)}`);d.type="object";const A=m.UnresolvedPure?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:b}}:m;r[d.Input]=A})}})}function b4(t,e){let r=!1;return t.getInputUses(e,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=s.MoveCall._argumentTypes[i].ref!=="&"||r}(s.$kind==="MakeMoveVec"||s.$kind==="MergeCoins"||s.$kind==="SplitCoins"||s.$kind==="TransferObjects")&&(r=!0)}),r}function g4(t,e){let r=!1;return t.getInputUses(e,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=w4(s.MoveCall._argumentTypes[i])||r}}),r}function w4(t){return typeof t.body!="object"||!("datatype"in t.body)?!1:t.body.datatype.package==="0x2"&&t.body.datatype.module==="transfer"&&t.body.datatype.type==="Receiving"}function F2(t,e){return!!(t.inputs.some(r=>r.UnresolvedObject||r.UnresolvedPure)||!e.onlyTransactionKind&&(!t.gasConfig.price||!t.gasConfig.budget||!t.gasConfig.payment))}async function v4(t,e,r){var i;if(S4(t),!F2(t,e))return await rm(t),r();const n=E4(e);return(((i=n.core)==null?void 0:i.resolveTransactionPlugin())??M2(n))(t,e,async()=>{await rm(t),await r()})}function rm(t){t.inputs.forEach((e,r)=>{if(e.$kind!=="Object"&&e.$kind!=="Pure")throw new Error(`Input at index ${r} has not been resolved. Expected a Pure or Object input, but found ${JSON.stringify(e)}`)})}function E4(t){if(!t.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return t.client}function S4(t){for(const e of t.commands)switch(e.$kind){case"SplitCoins":e.SplitCoins.amounts.forEach(r=>{nm(r,he.U64,t)});break;case"TransferObjects":nm(e.TransferObjects.address,he.Address,t);break}}function nm(t,e,r){if(t.$kind!=="Input")return;const n=r.inputs[t.Input];n.$kind==="UnresolvedPure"&&(r.inputs[t.Input]=kr.Pure(e.serialize(n.UnresolvedPure.value)))}function A4(t){function e(r){return t(r)}return e.system=r=>{const n=r==null?void 0:r.mutable;return e(n!==void 0?kr.SharedObjectRef({objectId:"0x5",initialSharedVersion:1,mutable:n}):{$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x5",initialSharedVersion:1}})},e.clock=()=>e(kr.SharedObjectRef({objectId:"0x6",initialSharedVersion:1,mutable:!1})),e.random=()=>e({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x8",mutable:!1}}),e.denyList=r=>e({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x403",mutable:r==null?void 0:r.mutable}}),e.option=({type:r,value:n})=>s=>s.moveCall({typeArguments:[r],target:`0x1::option::${n===null?"none":"some"}`,arguments:n===null?[]:[s.object(n)]}),e}function x4(t){function e(r,n){if(typeof r=="string")return t(ko(r).serialize(n));if(r instanceof Uint8Array||Wh(r))return t(r);throw new Error("tx.pure must be called either a bcs type name, or a serialized bcs value")}return e.u8=r=>t(he.U8.serialize(r)),e.u16=r=>t(he.U16.serialize(r)),e.u32=r=>t(he.U32.serialize(r)),e.u64=r=>t(he.U64.serialize(r)),e.u128=r=>t(he.U128.serialize(r)),e.u256=r=>t(he.U256.serialize(r)),e.bool=r=>t(he.Bool.serialize(r)),e.string=r=>t(he.String.serialize(r)),e.address=r=>t(he.Address.serialize(r)),e.id=e.address,e.vector=(r,n)=>t(he.vector(ko(r)).serialize(n)),e.option=(r,n)=>t(he.option(ko(r)).serialize(n)),e}function k4(t,e){const r=Array.from(`${t}::`).map(s=>s.charCodeAt(0)),n=new Uint8Array(r.length+e.length);return n.set(r),n.set(e,r.length),U2(n,{dkLen:32})}function sm(t){return xe(t).replace("0x","")}class Ut{constructor(e){this.version=2,this.sender=(e==null?void 0:e.sender)??null,this.expiration=(e==null?void 0:e.expiration)??null,this.inputs=(e==null?void 0:e.inputs)??[],this.commands=(e==null?void 0:e.commands)??[],this.gasData=(e==null?void 0:e.gasData)??{budget:null,price:null,owner:null,payment:null}}static fromKindBytes(e){const n=he.TransactionKind.parse(e).ProgrammableTransaction;if(!n)throw new Error("Unable to deserialize from bytes.");return Ut.restore({version:2,sender:null,expiration:null,gasData:{budget:null,owner:null,payment:null,price:null},inputs:n.inputs,commands:n.commands})}static fromBytes(e){const r=he.TransactionData.parse(e),n=r==null?void 0:r.V1,s=n.kind.ProgrammableTransaction;if(!n||!s)throw new Error("Unable to deserialize from bytes.");return Ut.restore({version:2,sender:n.sender,expiration:n.expiration,gasData:n.gasData,inputs:s.inputs,commands:s.commands})}static restore(e){return e.version===2?new Ut(qe(dc,e)):new Ut(qe(dc,RO(e)))}static getDigestFromBytes(e){const r=k4("TransactionData",e);return vu(r)}get gasConfig(){return this.gasData}set gasConfig(e){this.gasData=e}build({maxSizeBytes:e=1/0,overrides:r,onlyTransactionKind:n}={}){const s=this.inputs,i=this.commands,o={ProgrammableTransaction:{inputs:s,commands:i}};if(n)return he.TransactionKind.serialize(o,{maxSize:e}).toBytes();const a=(r==null?void 0:r.expiration)??this.expiration,c=(r==null?void 0:r.sender)??this.sender,u={...this.gasData,...r==null?void 0:r.gasConfig,...r==null?void 0:r.gasData};if(!c)throw new Error("Missing transaction sender");if(!u.budget)throw new Error("Missing gas budget");if(!u.payment)throw new Error("Missing gas payment");if(!u.price)throw new Error("Missing gas price");const f={sender:sm(c),expiration:a||{None:!0},gasData:{payment:u.payment,owner:sm(this.gasData.owner??c),price:BigInt(u.price),budget:BigInt(u.budget)},kind:{ProgrammableTransaction:{inputs:s,commands:i}}};return he.TransactionData.serialize({V1:f},{maxSize:e}).toBytes()}addInput(e,r){const n=this.inputs.length;return this.inputs.push(r),{Input:n,type:e,$kind:"Input"}}getInputUses(e,r){this.mapArguments((n,s)=>(n.$kind==="Input"&&n.Input===e&&r(n,s),n))}mapCommandArguments(e,r){const n=this.commands[e];switch(n.$kind){case"MoveCall":n.MoveCall.arguments=n.MoveCall.arguments.map(i=>r(i,n,e));break;case"TransferObjects":n.TransferObjects.objects=n.TransferObjects.objects.map(i=>r(i,n,e)),n.TransferObjects.address=r(n.TransferObjects.address,n,e);break;case"SplitCoins":n.SplitCoins.coin=r(n.SplitCoins.coin,n,e),n.SplitCoins.amounts=n.SplitCoins.amounts.map(i=>r(i,n,e));break;case"MergeCoins":n.MergeCoins.destination=r(n.MergeCoins.destination,n,e),n.MergeCoins.sources=n.MergeCoins.sources.map(i=>r(i,n,e));break;case"MakeMoveVec":n.MakeMoveVec.elements=n.MakeMoveVec.elements.map(i=>r(i,n,e));break;case"Upgrade":n.Upgrade.ticket=r(n.Upgrade.ticket,n,e);break;case"$Intent":const s=n.$Intent.inputs;n.$Intent.inputs={};for(const[i,o]of Object.entries(s))n.$Intent.inputs[i]=Array.isArray(o)?o.map(a=>r(a,n,e)):r(o,n,e);break;case"Publish":break;default:throw new Error(`Unexpected transaction kind: ${n.$kind}`)}}mapArguments(e){for(const r of this.commands.keys())this.mapCommandArguments(r,e)}replaceCommand(e,r,n=e){if(!Array.isArray(r)){this.commands[e]=r;return}const s=r.length-1;this.commands.splice(e,1,...r),s!==0&&this.mapArguments((i,o,a)=>{if(a<e+r.length)return i;switch(i.$kind){case"Result":i.Result===e&&(i.Result=n),i.Result>e&&(i.Result+=s);break;case"NestedResult":i.NestedResult[0]===e&&(i.NestedResult[0]=n),i.NestedResult[0]>e&&(i.NestedResult[0]+=s);break}return i})}getDigest(){const e=this.build({onlyTransactionKind:!1});return Ut.getDigestFromBytes(e)}snapshot(){return qe(dc,this)}shallowClone(){return new Ut({version:this.version,sender:this.sender,expiration:this.expiration,gasData:{...this.gasData},inputs:[...this.inputs],commands:[...this.commands]})}}function im(t){if(typeof t=="string")return xe(t);if(t.Object)return t.Object.ImmOrOwnedObject?xe(t.Object.ImmOrOwnedObject.objectId):t.Object.Receiving?xe(t.Object.Receiving.objectId):xe(t.Object.SharedObject.objectId);if(t.UnresolvedObject)return xe(t.UnresolvedObject.objectId)}var j2=t=>{throw TypeError(t)},tp=(t,e,r)=>e.has(t)||j2("Cannot "+r),it=(t,e,r)=>(tp(t,e,"read from private field"),r?r.call(t):e.get(t)),uo=(t,e,r)=>e.has(t)?j2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),tc=(t,e,r,n)=>(tp(t,e,"write to private field"),e.set(t,r),r),xu=(t,e,r)=>(tp(t,e,"access private method"),r),oa,Bn,aa,Zn,Kr,_d,Pd,L2,D2,rp;const T4="/",_4={"Mvr-Source":`@mysten/sui@${$w}`};class P4{constructor({cache:e,url:r,pageSize:n=50,overrides:s}){uo(this,Kr),uo(this,oa),uo(this,Bn),uo(this,aa),uo(this,Zn),tc(this,oa,e),tc(this,Bn,r),tc(this,aa,n),tc(this,Zn,{packages:s==null?void 0:s.packages,types:s==null?void 0:s.types}),I4(it(this,Zn))}async resolvePackage({package:e}){return{package:await it(this,Kr,_d).load(e)}}async resolveType({type:e}){const r=[...Id(e)],n=await it(this,Kr,Pd).loadMany(r),s={};for(let i=0;i<r.length;i++){const o=n[i];if(o instanceof Error)throw o;s[r[i]]=o}return{type:Od(e,s)}}async resolve({types:e=[],packages:r=[]}){var f,l,p;const n=new Set;for(const d of e??[])Id(d,n);const s=[...n],[i,o]=await Promise.all([s.length>0?it(this,Kr,Pd).loadMany(s):[],r.length>0?it(this,Kr,_d).loadMany(r):[]]),a={...(f=it(this,Zn))==null?void 0:f.types};for(const[d,m]of s.entries()){const b=i[d];if(b instanceof Error)throw b;a[m]=b}const c={};for(const d of e??[]){const m=Od(d,a);c[d]={type:m}}const u={};for(const[d,m]of(r??[]).entries()){const b=((p=(l=it(this,Zn))==null?void 0:l.packages)==null?void 0:p[m])??o[d];if(b instanceof Error)throw b;u[m]={package:b}}return{types:c,packages:u}}}oa=new WeakMap;Bn=new WeakMap;aa=new WeakMap;Zn=new WeakMap;Kr=new WeakSet;_d=function(){return it(this,oa).readSync(["#mvrPackageDataLoader",it(this,Bn)??""],()=>{var r;const t=new Ww(async n=>{if(!it(this,Bn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await xu(this,Kr,L2).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve package: ${i}`))}),e=(r=it(this,Zn))==null?void 0:r.packages;if(e)for(const[n,s]of Object.entries(e))t.prime(n,s);return t})};Pd=function(){return it(this,oa).readSync(["#mvrTypeDataLoader",it(this,Bn)??""],()=>{var r;const t=new Ww(async n=>{if(!it(this,Bn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await xu(this,Kr,D2).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve type: ${i}`))}),e=(r=it(this,Zn))==null?void 0:r.types;if(e)for(const[n,s]of Object.entries(e))t.prime(n,s);return t})};L2=async function(t){if(t.length===0)return{};const e=Eu(t,it(this,aa)),r={};return await Promise.all(e.map(async n=>{var i;const s=await xu(this,Kr,rp).call(this,"/v1/resolution/bulk",{names:n});if(s!=null&&s.resolution)for(const o of Object.keys(s==null?void 0:s.resolution)){const a=(i=s.resolution[o])==null?void 0:i.package_id;a&&(r[o]=a)}})),r};D2=async function(t){if(t.length===0)return{};const e=Eu(t,it(this,aa)),r={};return await Promise.all(e.map(async n=>{var i;const s=await xu(this,Kr,rp).call(this,"/v1/struct-definition/bulk",{types:n});if(s!=null&&s.resolution)for(const o of Object.keys(s==null?void 0:s.resolution)){const a=(i=s.resolution[o])==null?void 0:i.type_tag;a&&(r[o]=a)}})),r};rp=async function(t,e){if(!it(this,Bn))throw new Error("MVR Api URL is not set for the current client");const r=await fetch(`${it(this,Bn)}${t}`,{method:"POST",headers:{"Content-Type":"application/json",..._4},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(`Failed to resolve types: ${n==null?void 0:n.message}`)}return r.json()};function I4(t){if(t!=null&&t.packages)for(const[e,r]of Object.entries(t.packages)){if(!zt(e))throw new Error(`Invalid package name: ${e}`);if(!vr(xe(r)))throw new Error(`Invalid package ID: ${r}`)}if(t!=null&&t.types)for(const[e,r]of Object.entries(t.types)){if(Gs(e).typeParams.length>0)throw new Error("Type overrides must be first-level only. If you want to supply generic types, just pass each type individually.");const n=Gs(r);if(!vr(n.address))throw new Error(`Invalid type: ${r}`)}}function Id(t,e=new Set){if(typeof t=="string"&&!Mt(t))return e;const r=H2(t)?t:Gs(t);Mt(r.address)&&e.add(`${r.address}::${r.module}::${r.name}`);for(const n of r.typeParams)Id(n,e);return e}function Od(t,e){const r=H2(t)?t:Gs(t),n=`${r.address}::${r.module}::${r.name}`,s=e[n];return Pc({...r,address:s?s.split("::")[0]:r.address,typeParams:r.typeParams.map(i=>Od(i,e))})}function Mt(t){return t.includes(T4)||t.includes("@")||t.includes(".sui")}function H2(t){return typeof t=="object"&&"address"in t&&"module"in t&&"name"in t&&"typeParams"in t}function O4(t){const e=new Set,r=new Set;for(const n of t.commands)switch(n.$kind){case"MakeMoveVec":n.MakeMoveVec.type&&om([n.MakeMoveVec.type]).forEach(o=>{r.add(o)});break;case"MoveCall":const s=n.MoveCall,i=s.package.split("::")[0];if(Mt(i)){if(!zt(i))throw new Error(`Invalid package name: ${i}`);e.add(i)}om(s.typeArguments??[]).forEach(o=>{r.add(o)});break}return{packages:[...e],types:[...r]}}function B4(t,e){var r;for(const n of t.commands){if((r=n.MakeMoveVec)!=null&&r.type){if(!Mt(n.MakeMoveVec.type))continue;if(!e.types[n.MakeMoveVec.type])throw new Error(`No resolution found for type: ${n.MakeMoveVec.type}`);n.MakeMoveVec.type=e.types[n.MakeMoveVec.type].type}const s=n.MoveCall;if(!s)continue;const i=s.package.split("::"),o=i[0];if(Mt(o)&&!e.packages[o])throw new Error(`No address found for package: ${o}`);Mt(o)&&(i[0]=e.packages[o].package,s.package=i.join("::"));const a=s.typeArguments;if(a){for(let c=0;c<a.length;c++)if(Mt(a[c])){if(!e.types[a[c]])throw new Error(`No resolution found for type: ${a[c]}`);a[c]=e.types[a[c]].type}s.typeArguments=a}}}function om(t){const e=new Set;for(const r of t)if(Mt(r)){if(!UI(r))throw new Error(`Invalid type with names: ${r}`);e.add(r)}return e}const C4=t=>async(e,r,n)=>{const s=O4(e);if(s.types.length===0&&s.packages.length===0)return n();const i=await $4(r).core.mvr.resolve({types:s.types,packages:s.packages});B4(e,i),await n()};function $4(t){if(!t.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return t.client}var z2=t=>{throw TypeError(t)},np=(t,e,r)=>e.has(t)||z2("Cannot "+r),Y=(t,e,r)=>(np(t,e,"read from private field"),r?r.call(t):e.get(t)),zr=(t,e,r)=>e.has(t)?z2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),$e=(t,e,r,n)=>(np(t,e,"write to private field"),e.set(t,r),r),st=(t,e,r)=>(np(t,e,"access private method"),r),ks,Cs,mn,Xr,cr,ur,Ar,Yn,ce,Ke,V2,hc,pc,yc,Ic,Bd,sp,q2,G2;function gl(t,e=1/0){const r={$kind:"Result",get Result(){return typeof t=="function"?t():t}},n=[],s=i=>n[i]??(n[i]={$kind:"NestedResult",get NestedResult(){return[typeof t=="function"?t():t,i]}});return new Proxy(r,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(i,o){if(o in i)return Reflect.get(i,o);if(o===Symbol.iterator)return function*(){let c=0;for(;c<e;)yield s(c),c++};if(typeof o=="symbol")return;const a=parseInt(o,10);if(!(Number.isNaN(a)||a<0))return s(a)}})}const W2=Symbol.for("@mysten/transaction");function K2(t){return!!t&&typeof t=="object"&&t[W2]===!0}const am={buildPlugins:new Map,serializationPlugins:new Map},wl=Symbol.for("@mysten/transaction/registry");function fo(){try{const t=globalThis;return t[wl]||(t[wl]=am),t[wl]}catch{return am}}const Z2=class Cd{constructor(){zr(this,Ke),zr(this,ks),zr(this,Cs),zr(this,mn,new Map),zr(this,Xr,[]),zr(this,cr,[]),zr(this,ur,new Set),zr(this,Ar,new Set),zr(this,Yn,new Map),zr(this,ce),this.object=A4(r=>{var i,o;if(typeof r=="function")return this.object(this.add(r));if(typeof r=="object"&&Ad(Fe,r))return r;const n=im(r),s=Y(this,ce).inputs.find(a=>n===im(a));return(i=s==null?void 0:s.Object)!=null&&i.SharedObject&&typeof r=="object"&&((o=r.Object)!=null&&o.SharedObject)&&(s.Object.SharedObject.mutable=s.Object.SharedObject.mutable||r.Object.SharedObject.mutable),s?{$kind:"Input",Input:Y(this,ce).inputs.indexOf(s),type:"object"}:st(this,Ke,pc).call(this,"object",typeof r=="string"?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:xe(r)}}:r)});const e=fo();$e(this,ce,new Ut),$e(this,Cs,[...e.buildPlugins.values()]),$e(this,ks,[...e.serializationPlugins.values()])}static fromKind(e){const r=new Cd;return $e(r,ce,Ut.fromKindBytes(typeof e=="string"?Gt(e):e)),$e(r,Xr,Y(r,ce).inputs.slice()),$e(r,cr,Y(r,ce).commands.slice()),$e(r,ur,new Set(Y(r,cr).map((n,s)=>s))),r}static from(e){const r=new Cd;return K2(e)?$e(r,ce,new Ut(e.getData())):typeof e!="string"||!e.startsWith("{")?$e(r,ce,Ut.fromBytes(typeof e=="string"?Gt(e):e)):$e(r,ce,Ut.restore(JSON.parse(e))),$e(r,Xr,Y(r,ce).inputs.slice()),$e(r,cr,Y(r,ce).commands.slice()),$e(r,ur,new Set(Y(r,cr).map((n,s)=>s))),r}static registerGlobalSerializationPlugin(e,r){fo().serializationPlugins.set(e,r??e)}static unregisterGlobalSerializationPlugin(e){fo().serializationPlugins.delete(e)}static registerGlobalBuildPlugin(e,r){fo().buildPlugins.set(e,r??e)}static unregisterGlobalBuildPlugin(e){fo().buildPlugins.delete(e)}addSerializationPlugin(e){Y(this,ks).push(e)}addBuildPlugin(e){Y(this,Cs).push(e)}addIntentResolver(e,r){if(Y(this,mn).has(e)&&Y(this,mn).get(e)!==r)throw new Error(`Intent resolver for ${e} already exists`);Y(this,mn).set(e,r)}setSender(e){Y(this,ce).sender=e}setSenderIfNotSet(e){Y(this,ce).sender||(Y(this,ce).sender=e)}setExpiration(e){Y(this,ce).expiration=e?qe($2,e):null}setGasPrice(e){Y(this,ce).gasConfig.price=String(e)}setGasBudget(e){Y(this,ce).gasConfig.budget=String(e)}setGasBudgetIfNotSet(e){Y(this,ce).gasData.budget==null&&(Y(this,ce).gasConfig.budget=String(e))}setGasOwner(e){Y(this,ce).gasConfig.owner=e}setGasPayment(e){Y(this,ce).gasConfig.payment=e.map(r=>qe(us,r))}get blockData(){return tm(Y(this,ce).snapshot())}getData(){return Y(this,ce).snapshot()}get[W2](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:x4(e=>Wh(e)?st(this,Ke,pc).call(this,"pure",{$kind:"Pure",Pure:{bytes:e.toBase64()}}):st(this,Ke,pc).call(this,"pure",Ad(Jy,e)?qe(Jy,e):e instanceof Uint8Array?kr.Pure(e):{$kind:"UnresolvedPure",UnresolvedPure:{value:e}}))}),this.pure}get gas(){return{$kind:"GasCoin",GasCoin:!0}}objectRef(...e){return this.object(kr.ObjectRef(...e))}receivingRef(...e){return this.object(kr.ReceivingRef(...e))}sharedObjectRef(...e){return this.object(kr.SharedObjectRef(...e))}add(e){if(typeof e=="function"){if(Y(this,Yn).has(e))return Y(this,Yn).get(e);const r=st(this,Ke,V2).call(this),n=e(r);if(!(n&&typeof n=="object"&&"then"in n))return $e(this,ur,Y(r,ur)),Y(this,Yn).set(e,n),n;const s=st(this,Ke,hc).call(this,{$kind:"$Intent",$Intent:{name:"AsyncTransactionThunk",inputs:{},data:{resultIndex:Y(this,ce).commands.length,result:null}}});Y(this,Ar).add(Promise.resolve(n).then(o=>{s.$Intent.data.result=o}));const i=gl(()=>s.$Intent.data.resultIndex);return Y(this,Yn).set(e,i),i}else st(this,Ke,hc).call(this,e);return gl(Y(this,ce).commands.length-1)}splitCoins(e,r){const n=bs.SplitCoins(typeof e=="string"?this.object(e):st(this,Ke,Ic).call(this,e),r.map(s=>typeof s=="number"||typeof s=="bigint"||typeof s=="string"?this.pure.u64(s):st(this,Ke,yc).call(this,s)));return st(this,Ke,hc).call(this,n),gl(Y(this,ce).commands.length-1,r.length)}mergeCoins(e,r){return this.add(bs.MergeCoins(this.object(e),r.map(n=>this.object(n))))}publish({modules:e,dependencies:r}){return this.add(bs.Publish({modules:e,dependencies:r}))}upgrade({modules:e,dependencies:r,package:n,ticket:s}){return this.add(bs.Upgrade({modules:e,dependencies:r,package:n,ticket:this.object(s)}))}moveCall({arguments:e,...r}){return this.add(bs.MoveCall({...r,arguments:e==null?void 0:e.map(n=>st(this,Ke,yc).call(this,n))}))}transferObjects(e,r){return this.add(bs.TransferObjects(e.map(n=>this.object(n)),typeof r=="string"?this.pure.address(r):st(this,Ke,yc).call(this,r)))}makeMoveVec({type:e,elements:r}){return this.add(bs.MakeMoveVec({type:e,elements:r.map(n=>this.object(n))}))}serialize(){return JSON.stringify(tm(Y(this,ce).snapshot()))}async toJSON(e={}){await this.prepareForSerialization(e);const r=this.isFullyResolved();return JSON.stringify(qe(HO,r?{...Y(this,ce).snapshot(),digest:Y(this,ce).getDigest()}:Y(this,ce).snapshot()),(n,s)=>typeof s=="bigint"?s.toString():s,2)}async sign(e){const{signer:r,...n}=e,s=await this.build(n);return r.signTransaction(s)}isFullyResolved(){return!(!Y(this,ce).sender||Y(this,Ar).size>0||Y(this,ce).commands.some(e=>e.$Intent)||F2(Y(this,ce),{}))}async build(e={}){return await this.prepareForSerialization(e),await st(this,Ke,Bd).call(this,e),Y(this,ce).build({onlyTransactionKind:e.onlyTransactionKind})}async getDigest(e={}){return await this.prepareForSerialization(e),await st(this,Ke,Bd).call(this,e),Y(this,ce).getDigest()}async prepareForSerialization(e){var s;await st(this,Ke,q2).call(this),st(this,Ke,G2).call(this);const r=new Set;for(const i of Y(this,ce).commands)i.$Intent&&r.add(i.$Intent.name);const n=[...Y(this,ks)];for(const i of r)if(!((s=e.supportedIntents)!=null&&s.includes(i))){if(!Y(this,mn).has(i))throw new Error(`Missing intent resolver for ${i}`);n.push(Y(this,mn).get(i))}n.push(C4()),await st(this,Ke,sp).call(this,n,e)}};ks=new WeakMap;Cs=new WeakMap;mn=new WeakMap;Xr=new WeakMap;cr=new WeakMap;ur=new WeakMap;Ar=new WeakMap;Yn=new WeakMap;ce=new WeakMap;Ke=new WeakSet;V2=function(){const t=new Z2;return $e(t,ce,Y(this,ce)),$e(t,ks,Y(this,ks)),$e(t,Cs,Y(this,Cs)),$e(t,mn,Y(this,mn)),$e(t,Ar,Y(this,Ar)),$e(t,ur,new Set(Y(this,ur))),$e(t,Yn,Y(this,Yn)),Y(this,Xr).push(Y(t,Xr)),Y(this,cr).push(Y(t,cr)),t};hc=function(t){const e=Y(this,ce).commands.length;return Y(this,cr).push(t),Y(this,ur).add(e),Y(this,ce).commands.push(t),Y(this,ce).mapCommandArguments(e,r=>{if(r.$kind==="Result"&&!Y(this,ur).has(r.Result))throw new Error(`Result { Result: ${r.Result} } is not available to use the current transaction`);if(r.$kind==="NestedResult"&&!Y(this,ur).has(r.NestedResult[0]))throw new Error(`Result { NestedResult: [${r.NestedResult[0]}, ${r.NestedResult[1]}] } is not available to use the current transaction`);if(r.$kind==="Input"&&r.Input>=Y(this,ce).inputs.length)throw new Error(`Input { Input: ${r.Input} } references an input that does not exist in the current transaction`);return r}),t};pc=function(t,e){return Y(this,Xr).push(e),Y(this,ce).addInput(t,e)};yc=function(t){return Wh(t)?this.pure(t):st(this,Ke,Ic).call(this,t)};Ic=function(t){if(typeof t=="function"){const e=this.add(t);return typeof e=="function"?st(this,Ke,Ic).call(this,e):qe(Fe,e)}return qe(Fe,t)};Bd=async function(t){if(!t.onlyTransactionKind&&!Y(this,ce).sender)throw new Error("Missing transaction sender");await st(this,Ke,sp).call(this,[...Y(this,Cs),v4],t)};sp=async function(t,e){try{const r=n=>{if(n>=t.length)return()=>{};const s=t[n];return async()=>{const i=r(n+1);let o=!1,a=!1;if(await s(Y(this,ce),e,async()=>{if(o)throw new Error(`next() was call multiple times in TransactionPlugin ${n}`);o=!0,await i(),a=!0}),!o)throw new Error(`next() was not called in TransactionPlugin ${n}`);if(!a)throw new Error(`next() was not awaited in TransactionPlugin ${n}`)}};await r(0)()}finally{$e(this,Xr,Y(this,ce).inputs.slice()),$e(this,cr,Y(this,ce).commands.slice())}};q2=async function(){for(;Y(this,Ar).size>0;){const t=Promise.all(Y(this,Ar));Y(this,Ar).clear(),Y(this,Ar).add(t),await t,Y(this,Ar).delete(t)}};G2=function(){var o;const t=Y(this,ce).commands,e=Y(this,ce).inputs,r=Y(this,cr).flat(1/0),n=Y(this,Xr).flat(1/0);if(r.length!==t.length)throw new Error("Unexpected number of commands found in transaction data");if(n.length!==e.length)throw new Error("Unexpected number of inputs found in transaction data");const s=r.filter(a=>{var c;return((c=a.$Intent)==null?void 0:c.name)!=="AsyncTransactionThunk"});Y(this,ce).commands=s,Y(this,ce).inputs=n,$e(this,cr,s),$e(this,Xr,n),$e(this,ur,new Set(s.map((a,c)=>c)));function i(a){var f;const c=t[a];if(((f=c.$Intent)==null?void 0:f.name)==="AsyncTransactionThunk"){const l=c.$Intent.data.result;if(l==null)throw new Error("AsyncTransactionThunk has not been resolved");return i(l.Result)}const u=s.indexOf(c);if(u===-1)throw new Error("Unable to find original index for command");return u}Y(this,ce).mapArguments(a=>{if(a.$kind==="Input"){const c=n.indexOf(e[a.Input]);if(c===-1)throw new Error("Input has not been resolved");return{...a,Input:c}}else if(a.$kind==="Result"){const c=i(a.Result);return{...a,Result:c}}else if(a.$kind==="NestedResult"){const c=i(a.NestedResult[0]);return{...a,NestedResult:[c,a.NestedResult[1]]}}return a});for(const[a,c]of t.entries())if(((o=c.$Intent)==null?void 0:o.name)==="AsyncTransactionThunk")try{c.$Intent.data.resultIndex=i(a)}catch{}};let $d=Z2;const R4={mainnet:"https://mainnet.mvr.mystenlabs.com",testnet:"https://testnet.mvr.mystenlabs.com"};class N4 extends n2{constructor(e){var r,n,s;super(e),this.core=this,this.mvr=new P4({cache:this.cache.scope("core.mvr"),url:((r=e.mvr)==null?void 0:r.url)??R4[this.network],pageSize:(n=e.mvr)==null?void 0:n.pageSize,overrides:(s=e.mvr)==null?void 0:s.overrides})}async getObject(e){const{objectId:r}=e,{objects:[n]}=await this.getObjects({objectIds:[r],signal:e.signal});if(n instanceof Error)throw n;return{object:n}}async getDynamicField(e){const r=JO(e.parentId,Sr.parseFromStr(e.name.type),e.name.bcs),{objects:[n]}=await this.getObjects({objectIds:[r],signal:e.signal});if(n instanceof Error)throw n;const s=Gs(n.type),i=await n.content;return{dynamicField:{id:n.id,digest:n.digest,version:n.version,type:n.type,name:{type:typeof s.typeParams[0]=="string"?s.typeParams[0]:Pc(s.typeParams[0]),bcs:e.name.bcs},value:{type:typeof s.typeParams[1]=="string"?s.typeParams[1]:Pc(s.typeParams[1]),bcs:i.slice(Su+e.name.bcs.length)}}}}async waitForTransaction({signal:e,timeout:r=60*1e3,...n}){const s=e?AbortSignal.any([AbortSignal.timeout(r),e]):AbortSignal.timeout(r),i=new Promise((o,a)=>{s.addEventListener("abort",()=>a(s.reason))});for(i.catch(()=>{});;){s.throwIfAborted();try{return await this.getTransaction({...n,signal:s})}catch{await Promise.race([new Promise(a=>setTimeout(a,2e3)),i])}}}}class U4 extends Error{}class Xn extends U4{constructor(e,r){super(r),this.code=e}static fromResponse(e,r){switch(e.code){case"notExists":return new Xn(e.code,`Object ${e.object_id} does not exist`);case"dynamicFieldNotFound":return new Xn(e.code,`Dynamic field not found for object ${e.parent_object_id}`);case"deleted":return new Xn(e.code,`Object ${e.object_id} has been deleted`);case"displayError":return new Xn(e.code,`Display error: ${e.error}`);case"unknown":default:return new Xn(e.code,`Unknown error while loading object${r?` ${r}`:""}`)}}}function M4(t){return{...Ut.fromBytes(t).snapshot(),bcs:t}}function F4(t){const e=he.TransactionEffects.parse(t);switch(e.$kind){case"V1":return j4({effects:e.V1});case"V2":return L4({bytes:t,effects:e.V2});default:throw new Error(`Unknown transaction effects version: ${e.$kind}`)}}function j4(t){throw new Error("V1 effects are not supported yet")}function L4({bytes:t,effects:e}){const r=e.changedObjects.map(([n,s])=>{var i,o,a,c,u,f;return{id:n,inputState:s.inputState.$kind==="Exist"?"Exists":"DoesNotExist",inputVersion:((i=s.inputState.Exist)==null?void 0:i[0][0])??null,inputDigest:((o=s.inputState.Exist)==null?void 0:o[0][1])??null,inputOwner:((a=s.inputState.Exist)==null?void 0:a[1])??null,outputState:s.outputState.$kind==="NotExist"?"DoesNotExist":s.outputState.$kind,outputVersion:s.outputState.$kind==="PackageWrite"?(c=s.outputState.PackageWrite)==null?void 0:c[0]:s.outputState.ObjectWrite?e.lamportVersion:null,outputDigest:s.outputState.$kind==="PackageWrite"?(u=s.outputState.PackageWrite)==null?void 0:u[1]:((f=s.outputState.ObjectWrite)==null?void 0:f[0])??null,outputOwner:s.outputState.ObjectWrite?s.outputState.ObjectWrite[1]:null,idOperation:s.idOperation.$kind}});return{bcs:t,digest:e.transactionDigest,version:2,status:e.status.$kind==="Success"?{success:!0,error:null}:{success:!1,error:e.status.Failed.error.$kind},gasUsed:e.gasUsed,transactionDigest:e.transactionDigest,gasObject:e.gasObjectIndex===null?null:r[e.gasObjectIndex]??null,eventsDigest:e.eventsDigest,dependencies:e.dependencies,lamportVersion:e.lamportVersion,changedObjects:r,unchangedSharedObjects:e.unchangedSharedObjects.map(([n,s])=>({kind:s.$kind==="MutateDeleted"?"MutateConsensusStreamEnded":s.$kind==="ReadDeleted"?"ReadConsensusStreamEnded":s.$kind,objectId:n,version:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[0]:s[s.$kind],digest:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[1]:null})),auxiliaryDataDigest:e.auxDataDigest}}var Y2=t=>{throw TypeError(t)},X2=(t,e,r)=>e.has(t)||Y2("Cannot "+r),Ht=(t,e,r)=>(X2(t,e,"read from private field"),r?r.call(t):e.get(t)),D4=(t,e,r)=>e.has(t)?Y2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),H4=(t,e,r,n)=>(X2(t,e,"write to private field"),e.set(t,r),r),gt;class z4 extends N4{constructor({jsonRpcClient:e,mvr:r}){super({network:e.network,base:e,mvr:r}),D4(this,gt),H4(this,gt,e)}async getObjects(e){const r=Eu(e.objectIds,50),n=[];for(const s of r){const i=await Ht(this,gt).multiGetObjects({ids:s,options:{showOwner:!0,showType:!0,showBcs:!0},signal:e.signal});for(const[o,a]of i.entries())a.error?n.push(Xn.fromResponse(a.error,s[o])):n.push(cm(a.data))}return{objects:n}}async getOwnedObjects(e){const r=await Ht(this,gt).getOwnedObjects({owner:e.address,limit:e.limit,cursor:e.cursor,options:{showOwner:!0,showType:!0,showBcs:!0},filter:e.type?{StructType:e.type}:null,signal:e.signal});return{objects:r.data.map(n=>{if(n.error)throw Xn.fromResponse(n.error);return cm(n.data)}),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getCoins(e){const r=await Ht(this,gt).getCoins({owner:e.address,coinType:e.coinType,limit:e.limit,cursor:e.cursor,signal:e.signal});return{objects:r.data.map(n=>({id:n.coinObjectId,version:n.version,digest:n.digest,balance:n.balance,type:`0x2::coin::Coin<${n.coinType}>`,content:Promise.resolve(G4.serialize({id:n.coinObjectId,balance:{value:n.balance}}).toBytes()),owner:{$kind:"ObjectOwner",ObjectOwner:e.address}})),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getBalance(e){const r=await Ht(this,gt).getBalance({owner:e.address,coinType:e.coinType,signal:e.signal});return{balance:{coinType:r.coinType,balance:r.totalBalance}}}async getAllBalances(e){return{balances:(await Ht(this,gt).getAllBalances({owner:e.address,signal:e.signal})).map(n=>({coinType:n.coinType,balance:n.totalBalance})),hasNextPage:!1,cursor:null}}async getTransaction(e){const r=await Ht(this,gt).getTransactionBlock({digest:e.digest,options:{showRawInput:!0,showObjectChanges:!0,showRawEffects:!0,showEvents:!0,showEffects:!0},signal:e.signal});return{transaction:um(r)}}async executeTransaction(e){const r=await Ht(this,gt).executeTransactionBlock({transactionBlock:e.transaction,signature:e.signatures,options:{showRawEffects:!0,showEvents:!0,showObjectChanges:!0,showRawInput:!0,showEffects:!0},signal:e.signal});return{transaction:um(r)}}async dryRunTransaction(e){const r=$d.from(e.transaction),n=await Ht(this,gt).dryRunTransactionBlock({transactionBlock:e.transaction,signal:e.signal}),{effects:s,objectTypes:i}=V4({effects:n.effects,objectChanges:n.objectChanges});return{transaction:{digest:await r.getDigest(),epoch:null,effects:s,objectTypes:Promise.resolve(i),signatures:[],transaction:M4(e.transaction)}}}async getReferenceGasPrice(e){const r=await Ht(this,gt).getReferenceGasPrice({signal:e==null?void 0:e.signal});return{referenceGasPrice:String(r)}}async getDynamicFields(e){const r=await Ht(this,gt).getDynamicFields({parentId:e.parentId,limit:e.limit,cursor:e.cursor});return{dynamicFields:r.data.map(n=>({id:n.objectId,type:n.objectType,name:{type:n.name.type,bcs:Gt(n.bcsName)}})),hasNextPage:r.hasNextPage,cursor:r.nextCursor}}async verifyZkLoginSignature(e){const r=await Ht(this,gt).verifyZkLoginSignature({bytes:e.bytes,signature:e.signature,intentScope:e.intentScope,author:e.author});return{success:r.success,errors:r.errors}}resolveNameServiceNames(e){return Ht(this,gt).resolveNameServiceNames(e)}resolveTransactionPlugin(){return M2(Ht(this,gt))}}gt=new WeakMap;function cm(t){var e;return{id:t.objectId,version:t.version,digest:t.digest,type:t.type,content:Promise.resolve(((e=t.bcs)==null?void 0:e.dataType)==="moveObject"?Gt(t.bcs.bcsBytes):new Uint8Array),owner:yi(t.owner)}}function yi(t){if(t==="Immutable")return{$kind:"Immutable",Immutable:!0};if("ConsensusAddressOwner"in t)return{$kind:"ConsensusAddressOwner",ConsensusAddressOwner:{owner:t.ConsensusAddressOwner.owner,startVersion:t.ConsensusAddressOwner.start_version}};if("AddressOwner"in t)return{$kind:"AddressOwner",AddressOwner:t.AddressOwner};if("ObjectOwner"in t)return{$kind:"ObjectOwner",ObjectOwner:t.ObjectOwner};if("Shared"in t)return{$kind:"Shared",Shared:{initialSharedVersion:t.Shared.initial_shared_version}};throw new Error(`Unknown owner type: ${JSON.stringify(t)}`)}function um(t){var i,o;const e=he.SenderSignedData.parse(Gt(t.rawTransaction))[0],r={};(i=t.objectChanges)==null||i.forEach(a=>{a.type!=="published"&&(r[a.objectId]=a.objectType)});const n=he.TransactionData.serialize(e.intentMessage.value).toBytes(),s=Ut.restore({version:2,sender:e.intentMessage.value.V1.sender,expiration:e.intentMessage.value.V1.expiration,gasData:e.intentMessage.value.V1.gasData,inputs:e.intentMessage.value.V1.kind.ProgrammableTransaction.inputs,commands:e.intentMessage.value.V1.kind.ProgrammableTransaction.commands});return{digest:t.digest,epoch:((o=t.effects)==null?void 0:o.executedEpoch)??null,effects:F4(new Uint8Array(t.rawEffects)),objectTypes:Promise.resolve(r),transaction:{...s,bcs:n},signatures:e.txSignatures}}function V4({bytes:t,effects:e,objectChanges:r}){var o;const n=[],s=[],i={};return r==null||r.forEach(a=>{var c,u,f,l;switch(a.type){case"published":n.push({id:a.packageId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"PackageWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:null,idOperation:"Created"});break;case"transferred":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:a.digest,inputOwner:{$kind:"AddressOwner",AddressOwner:a.sender},outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:yi(a.recipient),idOperation:"None"}),i[a.objectId]=a.objectType;break;case"mutated":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.previousVersion,inputDigest:null,inputOwner:yi(a.owner),outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:yi(a.owner),idOperation:"None"}),i[a.objectId]=a.objectType;break;case"deleted":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:((u=(c=e.deleted)==null?void 0:c.find(p=>p.objectId===a.objectId))==null?void 0:u.digest)??null,inputOwner:null,outputState:"DoesNotExist",outputVersion:null,outputDigest:null,outputOwner:null,idOperation:"Deleted"}),i[a.objectId]=a.objectType;break;case"wrapped":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:null,inputOwner:{$kind:"AddressOwner",AddressOwner:a.sender},outputState:"ObjectWrite",outputVersion:a.version,outputDigest:((l=(f=e.wrapped)==null?void 0:f.find(p=>p.objectId===a.objectId))==null?void 0:l.digest)??null,outputOwner:{$kind:"ObjectOwner",ObjectOwner:a.sender},idOperation:"None"}),i[a.objectId]=a.objectType;break;case"created":n.push({id:a.objectId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:yi(a.owner),idOperation:"Created"}),i[a.objectId]=a.objectType;break}}),{objectTypes:i,effects:{bcs:t??null,digest:e.transactionDigest,version:2,status:e.status.status==="success"?{success:!0,error:null}:{success:!1,error:e.status.error},gasUsed:e.gasUsed,transactionDigest:e.transactionDigest,gasObject:{id:(o=e.gasObject)==null?void 0:o.reference.objectId,inputState:"Exists",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:e.gasObject.reference.version,outputDigest:e.gasObject.reference.digest,outputOwner:yi(e.gasObject.owner),idOperation:"None"},eventsDigest:e.eventsDigest??null,dependencies:e.dependencies??[],lamportVersion:e.gasObject.reference.version,changedObjects:n,unchangedSharedObjects:s,auxiliaryDataDigest:null}}}const q4=he.struct("Balance",{value:he.u64()}),G4=he.struct("Coin",{id:he.Address,balance:q4}),W4=Symbol.for("@mysten/SuiClient");class fm extends n2{constructor(e){super({network:e.network??"unknown"}),this.jsonRpc=this,this.transport=e.transport??new YP({url:e.url}),this.core=new z4({jsonRpcClient:this,mvr:e.mvr})}get[W4](){return!0}async getRpcApiVersion({signal:e}={}){return(await this.transport.request({method:"rpc.discover",params:[],signal:e})).info.version}async getCoins({coinType:e,owner:r,cursor:n,limit:s,signal:i}){if(!r||!vr(xe(r)))throw new Error("Invalid Sui address");return e&&Mt(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoins",params:[r,e,n,s],signal:i})}async getAllCoins(e){if(!e.owner||!vr(xe(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllCoins",params:[e.owner,e.cursor,e.limit],signal:e.signal})}async getBalance({owner:e,coinType:r,signal:n}){if(!e||!vr(xe(e)))throw new Error("Invalid Sui address");return r&&Mt(r)&&(r=(await this.core.mvr.resolveType({type:r})).type),await this.transport.request({method:"suix_getBalance",params:[e,r],signal:n})}async getAllBalances(e){if(!e.owner||!vr(xe(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllBalances",params:[e.owner],signal:e.signal})}async getCoinMetadata({coinType:e,signal:r}){return e&&Mt(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoinMetadata",params:[e],signal:r})}async getTotalSupply({coinType:e,signal:r}){return e&&Mt(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getTotalSupply",params:[e],signal:r})}async call(e,r,{signal:n}={}){return await this.transport.request({method:e,params:r,signal:n})}async getMoveFunctionArgTypes({package:e,module:r,function:n,signal:s}){return e&&zt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getMoveFunctionArgTypes",params:[e,r,n],signal:s})}async getNormalizedMoveModulesByPackage({package:e,signal:r}){return e&&zt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModulesByPackage",params:[e],signal:r})}async getNormalizedMoveModule({package:e,module:r,signal:n}){return e&&zt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModule",params:[e,r],signal:n})}async getNormalizedMoveFunction({package:e,module:r,function:n,signal:s}){return e&&zt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveFunction",params:[e,r,n],signal:s})}async getNormalizedMoveStruct({package:e,module:r,struct:n,signal:s}){return e&&zt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveStruct",params:[e,r,n],signal:s})}async getOwnedObjects(e){if(!e.owner||!vr(xe(e.owner)))throw new Error("Invalid Sui address");const r=e.filter?{...e.filter}:void 0;return r&&"MoveModule"in r&&zt(r.MoveModule.package)?r.MoveModule={module:r.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:r.MoveModule.package})).package}:r&&"StructType"in r&&Mt(r.StructType)&&(r.StructType=(await this.core.mvr.resolveType({type:r.StructType})).type),await this.transport.request({method:"suix_getOwnedObjects",params:[e.owner,{filter:r,options:e.options},e.cursor,e.limit],signal:e.signal})}async getObject(e){if(!e.id||!ec(vn(e.id)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"sui_getObject",params:[e.id,e.options],signal:e.signal})}async tryGetPastObject(e){return await this.transport.request({method:"sui_tryGetPastObject",params:[e.id,e.version,e.options],signal:e.signal})}async multiGetObjects(e){if(e.ids.forEach(n=>{if(!n||!ec(vn(n)))throw new Error(`Invalid Sui Object id ${n}`)}),e.ids.length!==new Set(e.ids).size)throw new Error(`Duplicate object ids in batch call ${e.ids}`);return await this.transport.request({method:"sui_multiGetObjects",params:[e.ids,e.options],signal:e.signal})}async queryTransactionBlocks({filter:e,options:r,cursor:n,limit:s,order:i,signal:o}){return e&&"MoveFunction"in e&&zt(e.MoveFunction.package)&&(e={...e,MoveFunction:{package:(await this.core.mvr.resolvePackage({package:e.MoveFunction.package})).package}}),await this.transport.request({method:"suix_queryTransactionBlocks",params:[{filter:e,options:r},n,s,(i||"descending")==="descending"],signal:o})}async getTransactionBlock(e){if(!Zy(e.digest))throw new Error("Invalid Transaction digest");return await this.transport.request({method:"sui_getTransactionBlock",params:[e.digest,e.options],signal:e.signal})}async multiGetTransactionBlocks(e){if(e.digests.forEach(n=>{if(!Zy(n))throw new Error(`Invalid Transaction digest ${n}`)}),e.digests.length!==new Set(e.digests).size)throw new Error(`Duplicate digests in batch call ${e.digests}`);return await this.transport.request({method:"sui_multiGetTransactionBlocks",params:[e.digests,e.options],signal:e.signal})}async executeTransactionBlock({transactionBlock:e,signature:r,options:n,requestType:s,signal:i}){const o=await this.transport.request({method:"sui_executeTransactionBlock",params:[typeof e=="string"?e:wt(e),Array.isArray(r)?r:[r],n],signal:i});if(s==="WaitForLocalExecution")try{await this.waitForTransaction({digest:o.digest})}catch{}return o}async signAndExecuteTransaction({transaction:e,signer:r,...n}){let s;e instanceof Uint8Array?s=e:(e.setSenderIfNotSet(r.toSuiAddress()),s=await e.build({client:this}));const{signature:i,bytes:o}=await r.signTransaction(s);return this.executeTransactionBlock({transactionBlock:o,signature:i,...n})}async getTotalTransactionBlocks({signal:e}={}){const r=await this.transport.request({method:"sui_getTotalTransactionBlocks",params:[],signal:e});return BigInt(r)}async getReferenceGasPrice({signal:e}={}){const r=await this.transport.request({method:"suix_getReferenceGasPrice",params:[],signal:e});return BigInt(r)}async getStakes(e){if(!e.owner||!vr(xe(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getStakes",params:[e.owner],signal:e.signal})}async getStakesByIds(e){return e.stakedSuiIds.forEach(r=>{if(!r||!ec(vn(r)))throw new Error(`Invalid Sui Stake id ${r}`)}),await this.transport.request({method:"suix_getStakesByIds",params:[e.stakedSuiIds],signal:e.signal})}async getLatestSuiSystemState({signal:e}={}){return await this.transport.request({method:"suix_getLatestSuiSystemState",params:[],signal:e})}async queryEvents({query:e,cursor:r,limit:n,order:s,signal:i}){return e&&"MoveEventType"in e&&Mt(e.MoveEventType)&&(e={...e,MoveEventType:(await this.core.mvr.resolveType({type:e.MoveEventType})).type}),e&&"MoveEventModule"in e&&zt(e.MoveEventModule.package)&&(e={...e,MoveEventModule:{module:e.MoveEventModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveEventModule.package})).package}}),"MoveModule"in e&&zt(e.MoveModule.package)&&(e={...e,MoveModule:{module:e.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveModule.package})).package}}),await this.transport.request({method:"suix_queryEvents",params:[e,r,n,(s||"descending")==="descending"],signal:i})}async subscribeEvent(e){return this.transport.subscribe({method:"suix_subscribeEvent",unsubscribe:"suix_unsubscribeEvent",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async subscribeTransaction(e){return this.transport.subscribe({method:"suix_subscribeTransaction",unsubscribe:"suix_unsubscribeTransaction",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async devInspectTransactionBlock(e){var n,s;let r;if(K2(e.transactionBlock))e.transactionBlock.setSenderIfNotSet(e.sender),r=wt(await e.transactionBlock.build({client:this,onlyTransactionKind:!0}));else if(typeof e.transactionBlock=="string")r=e.transactionBlock;else if(e.transactionBlock instanceof Uint8Array)r=wt(e.transactionBlock);else throw new Error("Unknown transaction block format.");return(n=e.signal)==null||n.throwIfAborted(),await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e.sender,r,(s=e.gasPrice)==null?void 0:s.toString(),e.epoch],signal:e.signal})}async dryRunTransactionBlock(e){return await this.transport.request({method:"sui_dryRunTransactionBlock",params:[typeof e.transactionBlock=="string"?e.transactionBlock:wt(e.transactionBlock)]})}async getDynamicFields(e){if(!e.parentId||!ec(vn(e.parentId)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"suix_getDynamicFields",params:[e.parentId,e.cursor,e.limit],signal:e.signal})}async getDynamicFieldObject(e){return await this.transport.request({method:"suix_getDynamicFieldObject",params:[e.parentId,e.name],signal:e.signal})}async getLatestCheckpointSequenceNumber({signal:e}={}){const r=await this.transport.request({method:"sui_getLatestCheckpointSequenceNumber",params:[],signal:e});return String(r)}async getCheckpoint(e){return await this.transport.request({method:"sui_getCheckpoint",params:[e.id],signal:e.signal})}async getCheckpoints(e){return await this.transport.request({method:"sui_getCheckpoints",params:[e.cursor,e==null?void 0:e.limit,e.descendingOrder],signal:e.signal})}async getCommitteeInfo(e){return await this.transport.request({method:"suix_getCommitteeInfo",params:[e==null?void 0:e.epoch],signal:e==null?void 0:e.signal})}async getNetworkMetrics({signal:e}={}){return await this.transport.request({method:"suix_getNetworkMetrics",params:[],signal:e})}async getAddressMetrics({signal:e}={}){return await this.transport.request({method:"suix_getLatestAddressMetrics",params:[],signal:e})}async getEpochMetrics(e){return await this.transport.request({method:"suix_getEpochMetrics",params:[e==null?void 0:e.cursor,e==null?void 0:e.limit,e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getAllEpochAddressMetrics(e){return await this.transport.request({method:"suix_getAllEpochAddressMetrics",params:[e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getEpochs(e){return await this.transport.request({method:"suix_getEpochs",params:[e==null?void 0:e.cursor,e==null?void 0:e.limit,e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getMoveCallMetrics({signal:e}={}){return await this.transport.request({method:"suix_getMoveCallMetrics",params:[],signal:e})}async getCurrentEpoch({signal:e}={}){return await this.transport.request({method:"suix_getCurrentEpoch",params:[],signal:e})}async getValidatorsApy({signal:e}={}){return await this.transport.request({method:"suix_getValidatorsApy",params:[],signal:e})}async getChainIdentifier({signal:e}={}){const r=await this.getCheckpoint({id:"0",signal:e}),n=na(r.digest);return ji(n.slice(0,4))}async resolveNameServiceAddress(e){return await this.transport.request({method:"suix_resolveNameServiceAddress",params:[e.name],signal:e.signal})}async resolveNameServiceNames({format:e="dot",...r}){const{nextCursor:n,hasNextPage:s,data:i}=await this.transport.request({method:"suix_resolveNameServiceNames",params:[r.address,r.cursor,r.limit],signal:r.signal});return{hasNextPage:s,nextCursor:n,data:i.map(o=>CI(o,e))}}async getProtocolConfig(e){return await this.transport.request({method:"sui_getProtocolConfig",params:[e==null?void 0:e.version],signal:e==null?void 0:e.signal})}async verifyZkLoginSignature(e){return await this.transport.request({method:"sui_verifyZkLoginSignature",params:[e.bytes,e.signature,e.intentScope,e.author],signal:e.signal})}async waitForTransaction({signal:e,timeout:r=60*1e3,pollInterval:n=2*1e3,...s}){const i=AbortSignal.timeout(r),o=new Promise((a,c)=>{i.addEventListener("abort",()=>c(i.reason))});for(o.catch(()=>{});!i.aborted;){e==null||e.throwIfAborted();try{return await this.getTransactionBlock(s)}catch{await Promise.race([new Promise(c=>setTimeout(c,n)),o])}}throw i.throwIfAborted(),new Error("Unexpected error while waiting for transaction block.")}experimental_asClientExtension(){return{name:"jsonRPC",register:()=>this}}}class K4{constructor(e,r,n){this.client=new fm({url:qy(n)}),this.url=e instanceof g.Url?e:new g.Url(e),this.account=r,this.network=n}get htlcActorAddress(){return"accounts"in this.account?this.account.accounts[0].address:this.account.toSuiAddress()}async initiate(e){var r,n,s;if(!e)return g.Err("Order is required");if(X.isSuiOrderResponse(e))return this.initiateWithCreateOrderResponse(e);try{const{source_swap:i}=e,o=BigInt(i.amount),a=i.asset,c=i.redeemer,u=i.secret_hash,f=await Ph(i.asset,this.url);if(!f.ok)return g.Err(f.error);const{tokenAddress:l}=f.val,p=new $d;p.setSender(this.htlcActorAddress);const[d]=p.splitCoins(p.gas,[o]);p.moveCall({target:`${cd[this.network].packageId}::${cd[this.network].moduleName}::initiate`,typeArguments:[l],arguments:[p.object(a),p.pure.address(this.htlcActorAddress),p.pure.address(c),p.pure.vector("u8",Buffer.from(u,"hex")),p.pure.u64(o),p.pure.u256(i.timelock),p.pure.vector("u8",Buffer.from("")),d,p.object(qO)]});const m=await p.build({client:this.client}),b=await this.client.dryRunTransactionBlock({transactionBlock:m});if(b.effects.status.status==="failure")return g.Err(`${b.effects.status.error}`);let E;if("features"in this.account?E=await((r=this.account.features[up.SuiSignAndExecuteTransaction])==null?void 0:r.signAndExecuteTransaction({transaction:p,account:this.account.accounts[0],chain:`sui:${this.network}`})):E=await this.client.signAndExecuteTransaction({signer:this.account,transaction:p,options:{showEffects:!0}}),!E)return g.Err("Failed to initiate");const A=await this.client.waitForTransaction({digest:E.digest,options:{showEffects:!0}});return((n=A.effects)==null?void 0:n.status.status)==="failure"?g.Err(`Failed to initiate: ${(s=A.effects)==null?void 0:s.status.error}`):g.Ok(A.digest)}catch(i){return g.Err(i)}}async initiateWithCreateOrderResponse(e){var a,c,u;const{ptb_bytes:r}=e,s=await new fm({url:qy("testnet")}).getReferenceGasPrice(),i=1e7,o=$d.fromKind(new Uint8Array(r));o.setSender(this.htlcActorAddress),o.setGasPrice(s),o.setGasBudget(i);try{let f;if("features"in this.account?f=await((a=this.account.features[up.SuiSignAndExecuteTransaction])==null?void 0:a.signAndExecuteTransaction({transaction:o,account:this.account.accounts[0],chain:`sui:${this.network}`})):f=await this.client.signAndExecuteTransaction({signer:this.account,transaction:o,options:{showEffects:!0}}),!f)return g.Err("Failed to initiate");const l=await this.client.waitForTransaction({digest:f.digest,options:{showEffects:!0}});return((c=l.effects)==null?void 0:c.status.status)==="failure"?g.Err(`Failed to initiate: ${(u=l.effects)==null?void 0:u.status.error}`):g.Ok(l.digest)}catch(f){return g.Err(String(f))}}async redeem(e,r){try{const n=await g.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:e.order_id,secret:r,perform_on:"Destination"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return n.error?g.Err(n.error):n.result?g.Ok(n.result):g.Err("Redeem: No result found")}catch(n){return g.Err(String(n))}}async refund(){return g.Err("Refund is taken care of by the relayer")}}const Z4=t=>{if(t)if(typeof t=="string"){const e=g.DigestKey.from(t);if(!e.ok)throw new Error(e.error);return e.val}else return t},lm=t=>typeof t=="string"?new g.ApiKey(t):t;class Y4{constructor(e={}){const r={stdTTL:e.ttl?e.ttl/1e3:3600,checkperiod:600};this.cache=new a6(r)}makeKey(e,r){return`${e}:${r}`}set(e,r,n,s){const i=this.makeKey(e,r);s?this.cache.set(i,n,s/1e3):this.cache.set(i,n)}get(e,r){const n=this.makeKey(e,r);return this.cache.get(n)}remove(e,r){const n=this.makeKey(e,r);this.cache.del(n)}clear(e){if(e){const r=this.cache.keys().filter(n=>n.startsWith(`${e}:`));this.cache.del(r)}else this.cache.flushAll()}setBitcoinRedeem(e,r,n){this.set("bitcoinRedeem",e,r,n)}getBitcoinRedeem(e){return this.get("bitcoinRedeem",e)}setOrderExecution(e,r,n,s,i){const o=this.makeOrderKey(e,r),a={txHash:n,timeStamp:Date.now(),btcRedeemUTXO:s};this.set("orderExecutor",o,a,i)}getOrderExecution(e,r){const n=this.makeOrderKey(e,r);return this.get("orderExecutor",n)}removeOrderExecution(e,r){const n=this.makeOrderKey(e,r);this.remove("orderExecutor",n)}makeOrderKey(e,r){return`${r}_${e.order_id??e.created_at}`}setSacpCache(e,r,n){this.set("refundSacp",e,r,n)}getSacpCache(e){return this.get("refundSacp",e)}has(e,r){const n=this.makeKey(e,r);return this.cache.has(n)}peek(e,r){return this.get(e,r)}getRemainingTTL(e,r){const n=this.makeKey(e,r),s=this.cache.getTtl(n);if(s===void 0)return-1;const i=Date.now();return Math.max(0,s-i)}}var ca,ua,fa,Xe,Ii,Jn;class X4{constructor(e,r,n,s,i,o){hs(this,ca);hs(this,ua);hs(this,fa);hs(this,Xe);hs(this,Ii);hs(this,Jn);this.isBackgroundServiceRunning=!1,this.stopBackgroundExecution=null,this.htlcs=r,this.events=o,ps(this,ca,e),ps(this,ua,n),ps(this,fa,Mi.fromDigestKey(e.digestKey)),ps(this,Xe,new Y4),ps(this,Ii,s),ps(this,Jn,i)}async getAddressesFromHTLCs(){var n,s,i,o,a;const e=new Set;return[(n=this.htlcs.evm)==null?void 0:n.htlcActorAddress,(s=this.htlcs.sui)==null?void 0:s.htlcActorAddress,(i=this.htlcs.solana)==null?void 0:i.htlcActorAddress,(o=this.htlcs.starknet)==null?void 0:o.htlcActorAddress,(a=this.htlcs.bitcoin)==null?void 0:a.htlcActorAddress].filter(c=>!!c&&c.length>0).forEach(c=>e.add(c.toLowerCase())),Array.from(e)}start(e=5e3,r){this.isBackgroundServiceRunning||this.stopBackgroundExecution||(this.isBackgroundServiceRunning=!0,(async()=>{try{if(r){this.stop();return}const n=await this.execute(e);n&&(this.stopBackgroundExecution=n)}catch(n){console.error("Error starting background executor:",n),this.isBackgroundServiceRunning=!1}})())}stop(){if(this.stopBackgroundExecution){try{this.stopBackgroundExecution()}catch{console.error("Error stopping background executor")}this.stopBackgroundExecution=null}this.isBackgroundServiceRunning=!1}async execute(e=5e3){const r=await this.getAddressesFromHTLCs();r.length===0&&r.push(Be(this,ca).userId.toLowerCase());let n=!1,s=null;const i=async()=>{if(!n){n=!0;try{const o=r.map(async c=>{try{const u=await Be(this,ua).getOrders({from_owner:c,status:X.OrderLifecycle.pending,per_page:500});return u.ok?u.val.data:(this.events.emit("error",{},`Failed to fetch orders for address ${c}: ${u.error}`),[])}catch(u){return this.events.emit("error",{},`Failed to fetch orders for address ${c}: ${u}`),[]}}),a=await Promise.all(o);this.events.emit("onPendingOrdersChanged",a.flat()),await this.processOrderActions(a.flat())}finally{n=!1}}};return await i(),s=setInterval(i,e),()=>{s&&clearInterval(s)}}async processOrderActions(e){const r=new Set([X.OrderStatus.InitiateDetected,X.OrderStatus.AwaitingRefund,X.OrderStatus.Initiated,X.OrderStatus.RefundDetected,X.OrderStatus.Refunded,X.OrderStatus.Expired]),n=e.map(async s=>{try{X.isBitcoin(s.source_swap.chain)&&r.has(s.status)&&!X.isCompleted(s)&&await this.postRefundSACP(s),X.parseAction(s)===X.OrderAction.Redeem&&await this.handleRedeemAction(s)}catch(i){this.events.emit("error",s,`Error processing order ${s.order_id}: ${i}`)}});await Promise.all(n)}async handleRedeemAction(e){const r=await Be(this,fa).generateSecret(e.nonce);if(!r.ok){this.events.emit("error",e,r.error);return}const n=g.trim0x(r.val.secretHash),s=g.trim0x(e.source_swap.secret_hash);if(n!==s){this.events.emit("log",e.order_id,"skipping redeem: secret hash mismatch");return}const i=r.val.secret,o=X.getBlockchainType(e.destination_swap.chain),c={[X.BlockchainType.evm]:()=>this.evmRedeem(e,i),[X.BlockchainType.bitcoin]:()=>this.btcRedeem(e,i),[X.BlockchainType.starknet]:()=>this.starknetRedeem(e,i),[X.BlockchainType.solana]:()=>this.solRedeem(e,i),[X.BlockchainType.sui]:()=>this.suiRedeem(e,i)}[o];c?await c():this.events.emit("error",e,`Unsupported chain: ${e.destination_swap.chain}`)}async evmRedeem(e,r){if(this.events.emit("log",e.order_id,"executing evm redeem"),Be(this,Xe).getOrderExecution(e,X.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.evm){this.events.emit("error",e,"EVM HTLC is required");return}const s=await this.htlcs.evm.redeem(e,r);if(!s.ok){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Be(this,Xe).setOrderExecution(e,X.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}Be(this,Xe).setOrderExecution(e,X.OrderAction.Redeem,s.val),this.events.emit("success",e,X.OrderAction.Redeem,s.val)}async starknetRedeem(e,r){if(this.events.emit("log",e.order_id,"executing starknet redeem"),Be(this,Xe).getOrderExecution(e,X.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.starknet){this.events.emit("error",e,"Starknet HTLC is required");return}const s=await this.htlcs.starknet.redeem(e,r);if(!s.ok){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Be(this,Xe).setOrderExecution(e,X.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Be(this,Xe).setOrderExecution(e,X.OrderAction.Redeem,s.val),this.events.emit("success",e,X.OrderAction.Redeem,s.val))}async solRedeem(e,r){if(this.events.emit("log",e.order_id,"executing sol redeem"),Be(this,Xe).getOrderExecution(e,X.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.solana){this.events.emit("error",e,"Solana HTLC is required");return}const s=await this.htlcs.solana.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Be(this,Xe).setOrderExecution(e,X.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Be(this,Xe).setOrderExecution(e,X.OrderAction.Redeem,s.val),this.events.emit("success",e,X.OrderAction.Redeem,s.val))}async suiRedeem(e,r){if(this.events.emit("log",e.order_id,"executing sui redeem"),Be(this,Xe).getOrderExecution(e,X.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.sui){this.events.emit("error",e,"Sui HTLC is required");return}const s=await this.htlcs.sui.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Be(this,Xe).setOrderExecution(e,X.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Be(this,Xe).setOrderExecution(e,X.OrderAction.Redeem,s.val),this.events.emit("success",e,X.OrderAction.Redeem,s.val))}async btcRedeem(e,r){var a,c;const n=(a=this.htlcs.bitcoin)==null?void 0:a.getProvider();if(!n){this.events.emit("error",e,"Bitcoin provider not found");return}const s=Be(this,Xe).getBitcoinRedeem(e.order_id),i=(c=e.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:c.split(":").at(0);if(!i){this.events.emit("error",e,"Failed to get initiate_tx_hash");return}let o=!1;if(s)if(s.redeemedFromUTXO&&s.redeemedFromUTXO!==i)o=!0,this.events.emit("log",e.order_id,"rbf btc redeem");else if(s.redeemedAt&&Date.now()-s.redeemedAt>1e3*60*15)this.events.emit("log",e.order_id,"redeem not confirmed in last 15 minutes"),o=!0;else{this.events.emit("log",e.order_id,"btcRedeem: already redeemed");return}else if(e.destination_swap.redeem_tx_hash&&!Number(e.destination_swap.redeem_block_number))try{const u=await(await n).getTransaction(e.destination_swap.redeem_tx_hash);let f=!1;for(const l of u.vin)if(l.txid===i){f=!0;break}if(f){this.events.emit("log",e.order_id,"already a valid redeem");let l=0;try{const[p]=await(await n).getTransactionTimes([e.destination_swap.redeem_tx_hash]);p!==0&&(l=p)}catch{l=Date.now()}Be(this,Xe).setBitcoinRedeem(e.order_id,{redeemedFromUTXO:i,redeemedAt:l,redeemTxHash:e.destination_swap.redeem_tx_hash});return}o=!0}catch(u){if(u.message.includes("Transaction not found"))o=!0;else{this.events.emit("error",e,"Failed to get redeem tx: "+u);return}}this.events.emit("log",e.order_id,"executing btc redeem");try{if(!this.htlcs.bitcoin){this.events.emit("error",e,"Bitcoin HTLC is required");return}const u=await this.htlcs.bitcoin.getRedeemHex(e,g.trim0x(r),o?[i]:[]);if(!u.ok){this.events.emit("error",e,"Failed to get redeem hex");return}const f=await this.broadcastRedeemTx(u.val,e.order_id);if(!f.ok){this.events.emit("error",e,f.error||"Failed to broadcast redeem tx");return}o?(this.events.emit("log",e.order_id,"rbf: btc redeem success"),this.events.emit("rbf",e,f.val)):this.events.emit("success",e,X.OrderAction.Redeem,f.val),Be(this,Xe).setBitcoinRedeem(e.order_id,{redeemedFromUTXO:i,redeemedAt:Date.now(),redeemTxHash:f.val})}catch(u){this.events.emit("error",e,"Failed btc redeem: "+u)}}async postRefundSACP(e){if(e.source_swap.delegate)try{if(!this.htlcs.bitcoin){this.events.emit("error",e,"Bitcoin HTLC is required");return}const n=await Be(this,Ii).getAuthHeaders();if(n.error){this.events.emit("error",e,"Failed to get auth headers: "+n.error);return}const s=await g.Fetcher.post(new g.Url(Be(this,Jn).baseurl).endpoint("relayer/bitcoin/instant-refund-hash"),{body:JSON.stringify({order_id:e.order_id}),headers:{"Content-Type":"application/json",...n.val}});if(s.error||!s.result){this.events.emit("error",e,"Failed to get hash while posting instant refund SACP: "+s.error);return}const i=await this.htlcs.bitcoin.generateInstantRefundSACPWithHash(s.result),o=new g.Url(Be(this,Jn).baseurl).endpoint("relayer/bitcoin/instant-refund");(await g.Fetcher.post(o,{headers:{"Content-Type":"application/json",...n.val},body:JSON.stringify({order_id:e.order_id,signatures:i.val})})).ok&&Be(this,Xe).setSacpCache(e.order_id,{initTxHash:e.source_swap.initiate_tx_hash})}catch(n){this.events.emit("error",e,"Failed to generate and post SACP: "+n);return}}async broadcastRedeemTx(e,r){try{if(!Be(this,Jn))return g.Err("API not found");const n=new g.Url(Be(this,Jn).relayer).endpoint("/bitcoin/redeem "),s=await Be(this,Ii).getAuthHeaders(),o=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...s.val},body:JSON.stringify({redeem_tx_bytes:e,order_id:r})})).json();return o.status==="Ok"&&o.result?g.Ok(o.result):g.Err(o.error)}catch(n){return g.Err("Failed to broadcast redeem tx: "+n)}}}ca=new WeakMap,ua=new WeakMap,fa=new WeakMap,Xe=new WeakMap,Ii=new WeakMap,Jn=new WeakMap;const lo={p2wpkh:"p2wpkh","p2wpkh-p2sh":"p2wpkh-p2sh"},mc={ALL:pe.Transaction.SIGHASH_ALL,NONE:pe.Transaction.SIGHASH_NONE,SINGLE:pe.Transaction.SIGHASH_SINGLE,ALL_ANYONECANPAY:pe.Transaction.SIGHASH_ALL|pe.Transaction.SIGHASH_ANYONECANPAY,NONE_ANYONECANPAY:pe.Transaction.SIGHASH_NONE|pe.Transaction.SIGHASH_ANYONECANPAY,SINGLE_ANYONECANPAY:pe.Transaction.SIGHASH_SINGLE|pe.Transaction.SIGHASH_ANYONECANPAY};class $s{constructor(e,r){this._scriptType=e,this._sigHashType=r}get scriptType(){return this._scriptType}get sigHashType(){return this._sigHashType}toString(){return`${this._scriptType} ${this._sigHashType}`}static async fromString(e){const[r,n]=e.split(" "),s=await fp.mixed().oneOf(["segwitV0","segwitV1","p2shSignature"]).required().validate(r),i=await fp.mixed().oneOf(Object.values(mc)).required().validate(parseInt(n));return new $s(s,i)}}const ws={INVALID_PK:"invalid private key",FEE_EXCEEDS_AMOUNT:(t,e)=>`fee exceeds amount: fee: ${t} > amount: ${e}`,SWAP_NOT_FOUND:"swap config not found, please set the swap config first",SCRIPT_NOT_FUNDED:"script not funded",SWAP_NOT_EXPIRED:t=>`swap not expired. Need ${t} more blocks`,MIN_AMOUNT:t=>`amount is too low. Minimum amount is ${t}`,INSUFFICIENT_FUNDS:(t,e)=>`insufficient funds, need ${e} but got ${t}`,AmtPlusFeeExceedsBalance:(t,e,r)=>`amount + fee exceeds balance. Need ${t+e} but got ${r}`},wo={INVALID_SECRET_HASH:"invalid secret hash",INVALID_PUBKEY_OR_SECRET:"invalid public key or secret",INVALID_PUBKEY:"invalid public key",ORDER_NOT_EXPIRED:"you cannot refund before your transaction expires"},J4=(t,e,r=!1)=>{const n=o=>{try{o=pe.address.fromBech32(o).data.toString("hex")}catch(a){if(ld(a))(a.message.includes("Mixed-case string")||a.message.includes("too short"))&&(o=pe.address.fromBase58Check(o).hash.toString("hex"));else throw new Error(String(a))}return o},s=pe.script.fromASM(`
|
|
88
|
+
${String(n)}`);Ad(e);for(let s=0;s<e.callbacks.length;s++){const i=n[s];i instanceof Error?e.callbacks[s].reject(i):e.callbacks[s].resolve(i)}}).catch(n=>{hl(t,e,n)})}function hl(t,e,r){Ad(e);for(let n=0;n<e.keys.length;n++)t.clear(e.keys[n]),e.callbacks[n].reject(r)}function Ad(t){if(t.cacheHits)for(let e=0;e<t.cacheHits.length;e++)t.cacheHits[e]()}function aI(t){if(!(!t||t.batch!==!1))return 1;const r=t&&t.maxBatchSize;if(r===void 0)return 1/0;if(typeof r!="number"||r<1)throw new TypeError(`maxBatchSize must be a positive number: ${r}`);return r}function cI(t){const e=t&&t.batchScheduleFn;if(e===void 0)return sI;if(typeof e!="function")throw new TypeError(`batchScheduleFn must be a function: ${e}`);return e}function uI(t){const e=t&&t.cacheKeyFn;if(e===void 0)return r=>r;if(typeof e!="function")throw new TypeError(`cacheKeyFn must be a function: ${e}`);return e}function fI(t){if(!(!t||t.cache!==!1))return null;const r=t&&t.cacheMap;if(r===void 0)return new Map;if(r!==null){const s=["get","set","delete","clear"].filter(i=>r&&typeof r[i]!="function");if(s.length!==0)throw new TypeError("Custom cacheMap missing methods: "+s.join(", "))}return r}function lI(t){return t&&t.name?t.name:null}function Kw(t){return typeof t=="object"&&t!==null&&"length"in t&&typeof t.length=="number"&&(t.length===0||t.length>0&&Object.prototype.hasOwnProperty.call(t,t.length-1))}function kc(t){const e=[];let r=0;if(t===0)return[0];for(;t>0;)e[r]=t&127,(t>>=7)&&(e[r]|=128),r+=1;return e}function dI(t){let e=0,r=0,n=0;for(;;){const s=t[n];if(n+=1,e|=(s&127)<<r,!(s&128))break;r+=7}return{value:e,length:n}}class hI{constructor(e){this.bytePosition=0,this.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)}shift(e){return this.bytePosition+=e,this}read8(){const e=this.dataView.getUint8(this.bytePosition);return this.shift(1),e}read16(){const e=this.dataView.getUint16(this.bytePosition,!0);return this.shift(2),e}read32(){const e=this.dataView.getUint32(this.bytePosition,!0);return this.shift(4),e}read64(){const e=this.read32(),n=this.read32().toString(16)+e.toString(16).padStart(8,"0");return BigInt("0x"+n).toString(10)}read128(){const e=BigInt(this.read64()),n=BigInt(this.read64()).toString(16)+e.toString(16).padStart(16,"0");return BigInt("0x"+n).toString(10)}read256(){const e=BigInt(this.read128()),n=BigInt(this.read128()).toString(16)+e.toString(16).padStart(32,"0");return BigInt("0x"+n).toString(10)}readBytes(e){const r=this.bytePosition+this.dataView.byteOffset,n=new Uint8Array(this.dataView.buffer,r,e);return this.shift(e),n}readULEB(){const e=this.bytePosition+this.dataView.byteOffset,r=new Uint8Array(this.dataView.buffer,e),{value:n,length:s}=dI(r);return this.shift(s),n}readVec(e){const r=this.readULEB(),n=[];for(let s=0;s<r;s++)n.push(e(this,s,r));return n}}function pI(t,e){switch(e){case"base58":return Su(t);case"base64":return wt(t);case"hex":return ji(t);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}function Zw(t,e=["<",">"]){const[r,n]=e,s=[];let i="",o=0;for(let a=0;a<t.length;a++){const c=t[a];if(c===r&&o++,c===n&&o--,o===0&&c===","){s.push(i.trim()),i="";continue}i+=c}return s.push(i.trim()),s}class yI{constructor({initialSize:e=1024,maxSize:r=1/0,allocateSize:n=1024}={}){this.bytePosition=0,this.size=e,this.maxSize=r,this.allocateSize=n,this.dataView=new DataView(new ArrayBuffer(e))}ensureSizeOrGrow(e){const r=this.bytePosition+e;if(r>this.size){const n=Math.min(this.maxSize,this.size+this.allocateSize);if(r>n)throw new Error(`Attempting to serialize to BCS, but buffer does not have enough size. Allocated size: ${this.size}, Max size: ${this.maxSize}, Required size: ${r}`);this.size=n;const s=new ArrayBuffer(this.size);new Uint8Array(s).set(new Uint8Array(this.dataView.buffer)),this.dataView=new DataView(s)}}shift(e){return this.bytePosition+=e,this}write8(e){return this.ensureSizeOrGrow(1),this.dataView.setUint8(this.bytePosition,Number(e)),this.shift(1)}write16(e){return this.ensureSizeOrGrow(2),this.dataView.setUint16(this.bytePosition,Number(e),!0),this.shift(2)}write32(e){return this.ensureSizeOrGrow(4),this.dataView.setUint32(this.bytePosition,Number(e),!0),this.shift(4)}write64(e){return pl(BigInt(e),8).forEach(r=>this.write8(r)),this}write128(e){return pl(BigInt(e),16).forEach(r=>this.write8(r)),this}write256(e){return pl(BigInt(e),32).forEach(r=>this.write8(r)),this}writeULEB(e){return kc(e).forEach(r=>this.write8(r)),this}writeVec(e,r){return this.writeULEB(e.length),Array.from(e).forEach((n,s)=>r(this,n,s,e.length)),this}*[Symbol.iterator](){for(let e=0;e<this.bytePosition;e++)yield this.dataView.getUint8(e);return this.toBytes()}toBytes(){return new Uint8Array(this.dataView.buffer.slice(0,this.bytePosition))}toString(e){return pI(this.toBytes(),e)}}function pl(t,e){const r=new Uint8Array(e);let n=0;for(;t>0;)r[n]=Number(t%BigInt(256)),t=t/BigInt(256),n+=1;return r}var Yw=t=>{throw TypeError(t)},Xw=(t,e,r)=>e.has(t)||Yw("Cannot "+r),wr=(t,e,r)=>(Xw(t,e,"read from private field"),r?r.call(t):e.get(t)),Tc=(t,e,r)=>e.has(t)?Yw("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),_c=(t,e,r,n)=>(Xw(t,e,"write to private field"),e.set(t,r),r),pi,go,lc,Wn;const mI=class Jw{constructor(e){Tc(this,pi),Tc(this,go),this.name=e.name,this.read=e.read,this.serializedSize=e.serializedSize??(()=>null),_c(this,pi,e.write),_c(this,go,e.serialize??((r,n)=>{const s=new yI({initialSize:this.serializedSize(r)??void 0,...n});return wr(this,pi).call(this,r,s),s.toBytes()})),this.validate=e.validate??(()=>{})}write(e,r){this.validate(e),wr(this,pi).call(this,e,r)}serialize(e,r){return this.validate(e),new bI(this,wr(this,go).call(this,e,r))}parse(e){const r=new hI(e);return this.read(r)}fromHex(e){return this.parse(Gw(e))}fromBase58(e){return this.parse(na(e))}fromBase64(e){return this.parse(Gt(e))}transform({name:e,input:r,output:n,validate:s}){return new Jw({name:e??this.name,read:i=>n?n(this.read(i)):this.read(i),write:(i,o)=>wr(this,pi).call(this,r?r(i):i,o),serializedSize:i=>this.serializedSize(r?r(i):i),serialize:(i,o)=>wr(this,go).call(this,r?r(i):i,o),validate:i=>{s==null||s(i),this.validate(r?r(i):i)}})}};pi=new WeakMap;go=new WeakMap;let en=mI;const Qw=Symbol.for("@mysten/serialized-bcs");function Kh(t){return!!t&&typeof t=="object"&&t[Qw]===!0}class bI{constructor(e,r){Tc(this,lc),Tc(this,Wn),_c(this,lc,e),_c(this,Wn,r)}get[Qw](){return!0}toBytes(){return wr(this,Wn)}toHex(){return ji(wr(this,Wn))}toBase64(){return wt(wr(this,Wn))}toBase58(){return Su(wr(this,Wn))}parse(){return wr(this,lc).parse(wr(this,Wn))}}lc=new WeakMap;Wn=new WeakMap;function Pc({size:t,...e}){return new en({...e,serializedSize:()=>t})}function yl({readMethod:t,writeMethod:e,...r}){return Pc({...r,read:n=>n[t](),write:(n,s)=>s[e](n),validate:n=>{var s;if(n<0||n>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${n}. Expected value in range 0-${r.maxValue}`);(s=r.validate)==null||s.call(r,n)}})}function ml({readMethod:t,writeMethod:e,...r}){return Pc({...r,read:n=>n[t](),write:(n,s)=>s[e](BigInt(n)),validate:n=>{var i;const s=BigInt(n);if(s<0||s>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${s}. Expected value in range 0-${r.maxValue}`);(i=r.validate)==null||i.call(r,s)}})}function gI({serialize:t,...e}){const r=new en({...e,serialize:t,write:(n,s)=>{for(const i of r.serialize(n).toBytes())s.write8(i)}});return r}function wI({toBytes:t,fromBytes:e,...r}){return new en({...r,read:n=>{const s=n.readULEB(),i=n.readBytes(s);return e(i)},write:(n,s)=>{const i=t(n);s.writeULEB(i.length);for(let o=0;o<i.length;o++)s.write8(i[o])},serialize:n=>{const s=t(n),i=kc(s.length),o=new Uint8Array(i.length+s.length);return o.set(i,0),o.set(s,i.length),o},validate:n=>{var s;if(typeof n!="string")throw new TypeError(`Invalid ${r.name} value: ${n}. Expected string`);(s=r.validate)==null||s.call(r,n)}})}function vI(t){let e=null;function r(){return e||(e=t()),e}return new en({name:"lazy",read:n=>r().read(n),serializedSize:n=>r().serializedSize(n),write:(n,s)=>r().write(n,s),serialize:(n,s)=>r().serialize(n,s).toBytes()})}class EI extends en{constructor({name:e,fields:r,...n}){const s=Object.entries(r);super({name:e,serializedSize:i=>{let o=0;for(const[a,c]of s){const u=c.serializedSize(i[a]);if(u==null)return null;o+=u}return o},read:i=>{const o={};for(const[a,c]of s)o[a]=c.read(i);return o},write:(i,o)=>{for(const[a,c]of s)c.write(i[a],o)},...n,validate:i=>{var o;if((o=n==null?void 0:n.validate)==null||o.call(n,i),typeof i!="object"||i==null)throw new TypeError(`Expected object, found ${typeof i}`)}})}}class SI extends en{constructor({fields:e,...r}){const n=Object.entries(e);super({read:s=>{const i=s.readULEB(),o=n[i];if(!o)throw new TypeError(`Unknown value ${i} for enum ${name}`);const[a,c]=o;return{[a]:(c==null?void 0:c.read(s))??!0,$kind:a}},write:(s,i)=>{const[o,a]=Object.entries(s).filter(([c])=>Object.hasOwn(e,c))[0];for(let c=0;c<n.length;c++){const[u,f]=n[c];if(u===o){i.writeULEB(c),f==null||f.write(a,i);return}}},...r,validate:s=>{var a;if((a=r==null?void 0:r.validate)==null||a.call(r,s),typeof s!="object"||s==null)throw new TypeError(`Expected object, found ${typeof s}`);const i=Object.keys(s).filter(c=>s[c]!==void 0&&Object.hasOwn(e,c));if(i.length!==1)throw new TypeError(`Expected object with one key, but found ${i.length} for type ${name}}`);const[o]=i;if(!Object.hasOwn(e,o))throw new TypeError(`Invalid enum variant ${o}`)}})}}class AI extends en{constructor({fields:e,name:r,...n}){super({name:r??`(${e.map(s=>s.name).join(", ")})`,serializedSize:s=>{let i=0;for(let o=0;o<e.length;o++){const a=e[o].serializedSize(s[o]);if(a==null)return null;i+=a}return i},read:s=>{const i=[];for(const o of e)i.push(o.read(s));return i},write:(s,i)=>{for(let o=0;o<e.length;o++)e[o].write(s[o],i)},...n,validate:s=>{var i;if((i=n==null?void 0:n.validate)==null||i.call(n,s),!Array.isArray(s))throw new TypeError(`Expected array, found ${typeof s}`);if(s.length!==e.length)throw new TypeError(`Expected array of length ${e.length}, found ${s.length}`)}})}}function xI(t,e,r){return new en({read:n=>{const s=new Array(t);for(let i=0;i<t;i++)s[i]=e.read(n);return s},write:(n,s)=>{for(const i of n)e.write(i,s)},...r,name:(r==null?void 0:r.name)??`${e.name}[${t}]`,validate:n=>{var s;if((s=r==null?void 0:r.validate)==null||s.call(r,n),!n||typeof n!="object"||!("length"in n))throw new TypeError(`Expected array, found ${typeof n}`);if(n.length!==t)throw new TypeError(`Expected array of length ${t}, found ${n.length}`)}})}function kI(t){return _.enum(`Option<${t.name}>`,{None:null,Some:t}).transform({input:e=>e==null?{None:!0}:{Some:e},output:e=>e.$kind==="Some"?e.Some:null})}function TI(t,e){return new en({read:r=>{const n=r.readULEB(),s=new Array(n);for(let i=0;i<n;i++)s[i]=t.read(r);return s},write:(r,n)=>{n.writeULEB(r.length);for(const s of r)t.write(s,n)},...e,name:(e==null?void 0:e.name)??`vector<${t.name}>`,validate:r=>{var n;if((n=e==null?void 0:e.validate)==null||n.call(e,r),!r||typeof r!="object"||!("length"in r))throw new TypeError(`Expected array, found ${typeof r}`)}})}function _I(t,e){return _.vector(_.tuple([t,e])).transform({name:`Map<${t.name}, ${e.name}>`,input:r=>[...r.entries()],output:r=>{const n=new Map;for(const[s,i]of r)n.set(s,i);return n}})}const _={u8(t){return yl({readMethod:"read8",writeMethod:"write8",size:1,maxValue:2**8-1,...t,name:(t==null?void 0:t.name)??"u8"})},u16(t){return yl({readMethod:"read16",writeMethod:"write16",size:2,maxValue:2**16-1,...t,name:(t==null?void 0:t.name)??"u16"})},u32(t){return yl({readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...t,name:(t==null?void 0:t.name)??"u32"})},u64(t){return ml({readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...t,name:(t==null?void 0:t.name)??"u64"})},u128(t){return ml({readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...t,name:(t==null?void 0:t.name)??"u128"})},u256(t){return ml({readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...t,name:(t==null?void 0:t.name)??"u256"})},bool(t){return Pc({size:1,read:e=>e.read8()===1,write:(e,r)=>r.write8(e?1:0),...t,name:(t==null?void 0:t.name)??"bool",validate:e=>{var r;if((r=t==null?void 0:t.validate)==null||r.call(t,e),typeof e!="boolean")throw new TypeError(`Expected boolean, found ${typeof e}`)}})},uleb128(t){return gI({read:e=>e.readULEB(),serialize:e=>Uint8Array.from(kc(e)),...t,name:(t==null?void 0:t.name)??"uleb128"})},bytes(t,e){return Pc({size:t,read:r=>r.readBytes(t),write:(r,n)=>{const s=new Uint8Array(r);for(let i=0;i<t;i++)n.write8(s[i]??0)},...e,name:(e==null?void 0:e.name)??`bytes[${t}]`,validate:r=>{var n;if((n=e==null?void 0:e.validate)==null||n.call(e,r),!r||typeof r!="object"||!("length"in r))throw new TypeError(`Expected array, found ${typeof r}`);if(r.length!==t)throw new TypeError(`Expected array of length ${t}, found ${r.length}`)}})},byteVector(t){return new en({read:e=>{const r=e.readULEB();return e.readBytes(r)},write:(e,r)=>{const n=new Uint8Array(e);r.writeULEB(n.length);for(let s=0;s<n.length;s++)r.write8(n[s]??0)},...t,name:(t==null?void 0:t.name)??"vector<u8>",serializedSize:e=>{const r="length"in e?e.length:null;return r==null?null:kc(r).length+r},validate:e=>{var r;if((r=t==null?void 0:t.validate)==null||r.call(t,e),!e||typeof e!="object"||!("length"in e))throw new TypeError(`Expected array, found ${typeof e}`)}})},string(t){return wI({toBytes:e=>new TextEncoder().encode(e),fromBytes:e=>new TextDecoder().decode(e),...t,name:(t==null?void 0:t.name)??"string"})},fixedArray:xI,option:kI,vector:TI,tuple(t,e){return new AI({fields:t,...e})},struct(t,e,r){return new EI({name:t,fields:e,...r})},enum(t,e,r){return new SI({name:t,fields:e,...r})},map:_I,lazy(t){return vI(t)}};var e2=t=>{throw TypeError(t)},t2=(t,e,r)=>e.has(t)||e2("Cannot "+r),bt=(t,e,r)=>(t2(t,e,"read from private field"),e.get(t)),Ky=(t,e,r)=>e.has(t)?e2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Zy=(t,e,r,n)=>(t2(t,e,"write to private field"),e.set(t,r),r),gs,_t;const PI=class r2{constructor({prefix:e,cache:r}={}){Ky(this,gs),Ky(this,_t),Zy(this,gs,e??[]),Zy(this,_t,r??new Map)}read(e,r){const n=[bt(this,gs),...e].join(":");if(bt(this,_t).has(n))return bt(this,_t).get(n);const s=r();return bt(this,_t).set(n,s),typeof s=="object"&&s!==null&&"then"in s?Promise.resolve(s).then(i=>(bt(this,_t).set(n,i),i)).catch(i=>{throw bt(this,_t).delete(n),i}):s}readSync(e,r){const n=[bt(this,gs),...e].join(":");if(bt(this,_t).has(n))return bt(this,_t).get(n);const s=r();return bt(this,_t).set(n,s),s}clear(e){const r=[...bt(this,gs),...e??[]].join(":");if(!r){bt(this,_t).clear();return}for(const n of bt(this,_t).keys())n.startsWith(r)&&bt(this,_t).delete(n)}scope(e){return new r2({prefix:[...bt(this,gs),...Array.isArray(e)?e:[e]],cache:bt(this,_t)})}};gs=new WeakMap;_t=new WeakMap;let II=PI;class n2{constructor({network:e,base:r,cache:n=(r==null?void 0:r.cache)??new II}){this.network=e,this.base=r??this,this.cache=n}$extend(...e){return Object.create(this,Object.fromEntries(e.map(r=>{if("experimental_asClientExtension"in r){const{name:n,register:s}=r.experimental_asClientExtension();return[n,{value:s(this)}]}return[r.name,{value:r.register(this)}]})))}}const s2=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,i2=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i,OI=235;function BI(t){return t.length>OI?!1:t.includes("@")?s2.test(t):i2.test(t)}function CI(t,e="at"){const r=t.toLowerCase();let n;if(r.includes("@")){if(!s2.test(r))throw new Error(`Invalid SuiNS name ${t}`);const[s,i]=r.split("@");n=[...s?s.split("."):[],i]}else{if(!i2.test(r))throw new Error(`Invalid SuiNS name ${t}`);n=r.split(".").slice(0,-1)}return e==="dot"?`${n.join(".")}.sui`:`${n.slice(0,-1).join(".")}@${n[n.length-1]}`}const $I=/^([a-z0-9]+(?:-[a-z0-9]+)*)$/,RI=/^\d+$/,NI=64,o2="/",zt=t=>{const e=t.split(o2);if(e.length<2||e.length>3)return!1;const[r,n,s]=e;return s!==void 0&&!RI.test(s)||!BI(r)?!1:$I.test(n)&&n.length<NI},UI=t=>{const e=t.split(/::|<|>|,/);for(const r of e)if(r.includes(o2)&&!zt(r))return!1;return!0},MI=32;function Yy(t){try{return na(t).length===MI}catch{return!1}}const xu=32;function vr(t){return jI(t)&&LI(t)===xu}function ec(t){return vr(t)}function FI(t){return t.includes("::")?Gs(t):t}function Gs(t){const[e,r]=t.split("::"),n=zt(e),s=t.slice(e.length+r.length+4),i=s.includes("<")?s.slice(0,s.indexOf("<")):s,o=s.includes("<")?Zw(s.slice(s.indexOf("<")+1,s.lastIndexOf(">"))).map(a=>FI(a.trim())):[];return{address:n?e:xe(e),module:r,name:i,typeParams:o}}function Ic(t){const{address:e,module:r,name:n,typeParams:s}=typeof t=="string"?Gs(t):t,i=(s==null?void 0:s.length)>0?`<${s.map(o=>typeof o=="string"?o:Ic(o)).join(",")}>`:"";return`${e}::${r}::${n}${i}`}function xe(t,e=!1){let r=t.toLowerCase();return!e&&r.startsWith("0x")&&(r=r.slice(2)),`0x${r.padStart(xu*2,"0")}`}function vn(t,e=!1){return xe(t,e)}function jI(t){return/^(0x|0X)?[a-fA-F0-9]+$/.test(t)&&t.length%2===0}function LI(t){return/^(0x|0X)/.test(t)?(t.length-2)/2:t.length/2}const DI=/^vector<(.+)>$/,HI=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class Sr{static parseFromStr(e,r=!1){if(e==="address")return{address:null};if(e==="bool")return{bool:null};if(e==="u8")return{u8:null};if(e==="u16")return{u16:null};if(e==="u32")return{u32:null};if(e==="u64")return{u64:null};if(e==="u128")return{u128:null};if(e==="u256")return{u256:null};if(e==="signer")return{signer:null};const n=e.match(DI);if(n)return{vector:Sr.parseFromStr(n[1],r)};const s=e.match(HI);if(s)return{struct:{address:r?xe(s[1]):s[1],module:s[2],name:s[3],typeParams:s[5]===void 0?[]:Sr.parseStructTypeArgs(s[5],r)}};throw new Error(`Encountered unexpected token when parsing type args for ${e}`)}static parseStructTypeArgs(e,r=!1){return Zw(e).map(n=>Sr.parseFromStr(n,r))}static tagToString(e){if("bool"in e)return"bool";if("u8"in e)return"u8";if("u16"in e)return"u16";if("u32"in e)return"u32";if("u64"in e)return"u64";if("u128"in e)return"u128";if("u256"in e)return"u256";if("address"in e)return"address";if("signer"in e)return"signer";if("vector"in e)return`vector<${Sr.tagToString(e.vector)}>`;if("struct"in e){const r=e.struct,n=r.typeParams.map(Sr.tagToString).join(", ");return`${r.address}::${r.module}::${r.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}function zI(t){return _.u64({name:"unsafe_u64",...t}).transform({input:e=>e,output:e=>Number(e)})}function VI(t){return _.enum("Option",{None:null,Some:t})}const Ne=_.bytes(xu).transform({validate:t=>{const e=typeof t=="string"?t:ji(t);if(!e||!vr(xe(e)))throw new Error(`Invalid Sui address ${e}`)},input:t=>typeof t=="string"?Gw(xe(t)):t,output:t=>xe(ji(t))}),xr=_.vector(_.u8()).transform({name:"ObjectDigest",input:t=>na(t),output:t=>Su(new Uint8Array(t)),validate:t=>{if(na(t).length!==32)throw new Error("ObjectDigest must be 32 bytes")}}),or=_.struct("SuiObjectRef",{objectId:Ne,version:_.u64(),digest:xr}),a2=_.struct("SharedObjectRef",{objectId:Ne,initialSharedVersion:_.u64(),mutable:_.bool()}),c2=_.enum("ObjectArg",{ImmOrOwnedObject:or,SharedObject:a2,Receiving:or}),xs=_.enum("Owner",{AddressOwner:Ne,ObjectOwner:Ne,Shared:_.struct("Shared",{initialSharedVersion:_.u64()}),Immutable:null,ConsensusAddressOwner:_.struct("ConsensusAddressOwner",{owner:Ne,startVersion:_.u64()})}),u2=_.enum("CallArg",{Pure:_.struct("Pure",{bytes:_.vector(_.u8()).transform({input:t=>typeof t=="string"?Gt(t):t,output:t=>wt(new Uint8Array(t))})}),Object:c2}),Zh=_.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:_.lazy(()=>Zh),struct:_.lazy(()=>y2),u16:null,u32:null,u256:null}),Yh=Zh.transform({input:t=>typeof t=="string"?Sr.parseFromStr(t,!0):t,output:t=>Sr.tagToString(t)}),Gr=_.enum("Argument",{GasCoin:null,Input:_.u16(),Result:_.u16(),NestedResult:_.tuple([_.u16(),_.u16()])}),f2=_.struct("ProgrammableMoveCall",{package:Ne,module:_.string(),function:_.string(),typeArguments:_.vector(Yh),arguments:_.vector(Gr)}),l2=_.enum("Command",{MoveCall:f2,TransferObjects:_.struct("TransferObjects",{objects:_.vector(Gr),address:Gr}),SplitCoins:_.struct("SplitCoins",{coin:Gr,amounts:_.vector(Gr)}),MergeCoins:_.struct("MergeCoins",{destination:Gr,sources:_.vector(Gr)}),Publish:_.struct("Publish",{modules:_.vector(_.vector(_.u8()).transform({input:t=>typeof t=="string"?Gt(t):t,output:t=>wt(new Uint8Array(t))})),dependencies:_.vector(Ne)}),MakeMoveVec:_.struct("MakeMoveVec",{type:VI(Yh).transform({input:t=>t===null?{None:!0}:{Some:t},output:t=>t.Some??null}),elements:_.vector(Gr)}),Upgrade:_.struct("Upgrade",{modules:_.vector(_.vector(_.u8()).transform({input:t=>typeof t=="string"?Gt(t):t,output:t=>wt(new Uint8Array(t))})),dependencies:_.vector(Ne),package:Ne,ticket:Gr})}),d2=_.struct("ProgrammableTransaction",{inputs:_.vector(u2),commands:_.vector(l2)}),h2=_.enum("TransactionKind",{ProgrammableTransaction:d2,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),p2=_.enum("TransactionExpiration",{None:null,Epoch:zI()}),y2=_.struct("StructTag",{address:Ne,module:_.string(),name:_.string(),typeParams:_.vector(Zh)}),m2=_.struct("GasData",{payment:_.vector(or),owner:Ne,price:_.u64(),budget:_.u64()}),b2=_.struct("TransactionDataV1",{kind:h2,sender:Ne,gasData:m2,expiration:p2}),g2=_.enum("TransactionData",{V1:b2}),w2=_.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),v2=_.enum("IntentVersion",{V0:null}),E2=_.enum("AppId",{Sui:null}),S2=_.struct("Intent",{scope:w2,version:v2,appId:E2});function A2(t){return _.struct(`IntentMessage<${t.name}>`,{intent:S2,value:t})}const x2=_.enum("CompressedSignature",{ED25519:_.fixedArray(64,_.u8()),Secp256k1:_.fixedArray(64,_.u8()),Secp256r1:_.fixedArray(64,_.u8()),ZkLogin:_.vector(_.u8()),Passkey:_.vector(_.u8())}),k2=_.enum("PublicKey",{ED25519:_.fixedArray(32,_.u8()),Secp256k1:_.fixedArray(33,_.u8()),Secp256r1:_.fixedArray(33,_.u8()),ZkLogin:_.vector(_.u8()),Passkey:_.fixedArray(33,_.u8())}),T2=_.struct("MultiSigPkMap",{pubKey:k2,weight:_.u8()}),_2=_.struct("MultiSigPublicKey",{pk_map:_.vector(T2),threshold:_.u16()}),qI=_.struct("MultiSig",{sigs:_.vector(x2),bitmap:_.u16(),multisig_pk:_2}),GI=_.vector(_.u8()).transform({input:t=>typeof t=="string"?Gt(t):t,output:t=>wt(new Uint8Array(t))}),P2=_.struct("SenderSignedTransaction",{intentMessage:A2(g2),txSignatures:_.vector(GI)}),WI=_.vector(P2,{name:"SenderSignedData"}),KI=_.struct("PasskeyAuthenticator",{authenticatorData:_.vector(_.u8()),clientDataJson:_.string(),userSignature:_.vector(_.u8())}),ZI=_.enum("PackageUpgradeError",{UnableToFetchPackage:_.struct("UnableToFetchPackage",{packageId:Ne}),NotAPackage:_.struct("NotAPackage",{objectId:Ne}),IncompatibleUpgrade:null,DigestDoesNotMatch:_.struct("DigestDoesNotMatch",{digest:_.vector(_.u8())}),UnknownUpgradePolicy:_.struct("UnknownUpgradePolicy",{policy:_.u8()}),PackageIDDoesNotMatch:_.struct("PackageIDDoesNotMatch",{packageId:Ne,ticketId:Ne})}),YI=_.struct("ModuleId",{address:Ne,name:_.string()}),Xy=_.struct("MoveLocation",{module:YI,function:_.u16(),instruction:_.u16(),functionName:_.option(_.string())}),XI=_.enum("CommandArgumentError",{TypeMismatch:null,InvalidBCSBytes:null,InvalidUsageOfPureArg:null,InvalidArgumentToPrivateEntryFunction:null,IndexOutOfBounds:_.struct("IndexOutOfBounds",{idx:_.u16()}),SecondaryIndexOutOfBounds:_.struct("SecondaryIndexOutOfBounds",{resultIdx:_.u16(),secondaryIdx:_.u16()}),InvalidResultArity:_.struct("InvalidResultArity",{resultIdx:_.u16()}),InvalidGasCoinUsage:null,InvalidValueUsage:null,InvalidObjectByValue:null,InvalidObjectByMutRef:null,SharedObjectOperationNotAllowed:null}),JI=_.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),QI=_.enum("ExecutionFailureStatus",{InsufficientGas:null,InvalidGasObject:null,InvariantViolation:null,FeatureNotYetSupported:null,MoveObjectTooBig:_.struct("MoveObjectTooBig",{objectSize:_.u64(),maxObjectSize:_.u64()}),MovePackageTooBig:_.struct("MovePackageTooBig",{objectSize:_.u64(),maxObjectSize:_.u64()}),CircularObjectOwnership:_.struct("CircularObjectOwnership",{object:Ne}),InsufficientCoinBalance:null,CoinBalanceOverflow:null,PublishErrorNonZeroAddress:null,SuiMoveVerificationError:null,MovePrimitiveRuntimeError:_.option(Xy),MoveAbort:_.tuple([Xy,_.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:_.struct("CommandArgumentError",{argIdx:_.u16(),kind:XI}),TypeArgumentError:_.struct("TypeArgumentError",{argumentIdx:_.u16(),kind:JI}),UnusedValueWithoutDrop:_.struct("UnusedValueWithoutDrop",{resultIdx:_.u16(),secondaryIdx:_.u16()}),InvalidPublicFunctionReturnType:_.struct("InvalidPublicFunctionReturnType",{idx:_.u16()}),InvalidTransferObject:null,EffectsTooLarge:_.struct("EffectsTooLarge",{currentSize:_.u64(),maxSize:_.u64()}),PublishUpgradeMissingDependency:null,PublishUpgradeDependencyDowngrade:null,PackageUpgradeError:_.struct("PackageUpgradeError",{upgradeError:ZI}),WrittenObjectsTooLarge:_.struct("WrittenObjectsTooLarge",{currentSize:_.u64(),maxSize:_.u64()}),CertificateDenied:null,SuiMoveVerificationTimedout:null,SharedObjectOperationNotAllowed:null,InputObjectDeleted:null,ExecutionCancelledDueToSharedObjectCongestion:_.struct("ExecutionCancelledDueToSharedObjectCongestion",{congestedObjects:_.vector(Ne)}),AddressDeniedForCoin:_.struct("AddressDeniedForCoin",{address:Ne,coinType:_.string()}),CoinTypeGlobalPause:_.struct("CoinTypeGlobalPause",{coinType:_.string()}),ExecutionCancelledDueToRandomnessUnavailable:null}),I2=_.enum("ExecutionStatus",{Success:null,Failed:_.struct("ExecutionFailed",{error:QI,command:_.option(_.u64())})}),O2=_.struct("GasCostSummary",{computationCost:_.u64(),storageCost:_.u64(),storageRebate:_.u64(),nonRefundableStorageFee:_.u64()}),eO=_.struct("TransactionEffectsV1",{status:I2,executedEpoch:_.u64(),gasUsed:O2,modifiedAtVersions:_.vector(_.tuple([Ne,_.u64()])),sharedObjects:_.vector(or),transactionDigest:xr,created:_.vector(_.tuple([or,xs])),mutated:_.vector(_.tuple([or,xs])),unwrapped:_.vector(_.tuple([or,xs])),deleted:_.vector(or),unwrappedThenDeleted:_.vector(or),wrapped:_.vector(or),gasObject:_.tuple([or,xs]),eventsDigest:_.option(xr),dependencies:_.vector(xr)}),Xh=_.tuple([_.u64(),xr]),tO=_.enum("ObjectIn",{NotExist:null,Exist:_.tuple([Xh,xs])}),rO=_.enum("ObjectOut",{NotExist:null,ObjectWrite:_.tuple([xr,xs]),PackageWrite:Xh}),nO=_.enum("IDOperation",{None:null,Created:null,Deleted:null}),sO=_.struct("EffectsObjectChange",{inputState:tO,outputState:rO,idOperation:nO}),iO=_.enum("UnchangedSharedKind",{ReadOnlyRoot:Xh,MutateDeleted:_.u64(),ReadDeleted:_.u64(),Cancelled:_.u64(),PerEpochConfig:null}),oO=_.struct("TransactionEffectsV2",{status:I2,executedEpoch:_.u64(),gasUsed:O2,transactionDigest:xr,gasObjectIndex:_.option(_.u32()),eventsDigest:_.option(xr),dependencies:_.vector(xr),lamportVersion:_.u64(),changedObjects:_.vector(_.tuple([Ne,sO])),unchangedSharedObjects:_.vector(_.tuple([Ne,iO])),auxDataDigest:_.option(xr)}),aO=_.enum("TransactionEffects",{V1:eO,V2:oO});function ko(t){switch(t){case"u8":return _.u8();case"u16":return _.u16();case"u32":return _.u32();case"u64":return _.u64();case"u128":return _.u128();case"u256":return _.u256();case"bool":return _.bool();case"string":return _.string();case"id":case"address":return Ne}const e=t.match(/^(vector|option)<(.+)>$/);if(e){const[r,n]=e.slice(1);return r==="vector"?_.vector(ko(n)):_.option(ko(n))}throw new Error(`Invalid Pure type name: ${t}`)}const he={..._,U8:_.u8(),U16:_.u16(),U32:_.u32(),U64:_.u64(),U128:_.u128(),U256:_.u256(),ULEB128:_.uleb128(),Bool:_.bool(),String:_.string(),Address:Ne,AppId:E2,Argument:Gr,CallArg:u2,Command:l2,CompressedSignature:x2,GasData:m2,Intent:S2,IntentMessage:A2,IntentScope:w2,IntentVersion:v2,MultiSig:qI,MultiSigPkMap:T2,MultiSigPublicKey:_2,ObjectArg:c2,ObjectDigest:xr,Owner:xs,PasskeyAuthenticator:KI,ProgrammableMoveCall:f2,ProgrammableTransaction:d2,PublicKey:k2,SenderSignedData:WI,SenderSignedTransaction:P2,SharedObjectRef:a2,StructTag:y2,SuiObjectRef:or,TransactionData:g2,TransactionDataV1:b2,TransactionEffects:aO,TransactionExpiration:p2,TransactionKind:h2,TypeTag:Yh};var un;function cO(t){return{lang:(t==null?void 0:t.lang)??(un==null?void 0:un.lang),message:t==null?void 0:t.message,abortEarly:(t==null?void 0:t.abortEarly)??(un==null?void 0:un.abortEarly),abortPipeEarly:(t==null?void 0:t.abortPipeEarly)??(un==null?void 0:un.abortPipeEarly)}}var bl;function uO(t){return bl==null?void 0:bl.get(t)}var gl;function fO(t){return gl==null?void 0:gl.get(t)}var wl;function lO(t,e){var r;return(r=wl==null?void 0:wl.get(t))==null?void 0:r.get(e)}function B2(t){var r,n;const e=typeof t;return e==="string"?`"${t}"`:e==="number"||e==="bigint"||e==="boolean"?`${t}`:e==="object"||e==="function"?(t&&((n=(r=Object.getPrototypeOf(t))==null?void 0:r.constructor)==null?void 0:n.name))??"null":e}function Xt(t,e,r,n,s){const i=s&&"input"in s?s.input:r.value,o=(s==null?void 0:s.expected)??t.expects??null,a=(s==null?void 0:s.received)??B2(i),c={kind:t.kind,type:t.type,input:i,expected:o,received:a,message:`Invalid ${e}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:t.requirement,path:s==null?void 0:s.path,issues:s==null?void 0:s.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},u=t.kind==="schema",f=(s==null?void 0:s.message)??t.message??lO(t.reference,c.lang)??(u?fO(c.lang):null)??n.message??uO(c.lang);f&&(c.message=typeof f=="function"?f(c):f),u&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function dO(t,e){return Object.hasOwn(t,e)&&e!=="__proto__"&&e!=="prototype"&&e!=="constructor"}var hO=class extends Error{constructor(e){super(e[0].message);cp(this,"issues");this.name="ValiError",this.issues=e}};function Ba(t,e){return{kind:"validation",type:"check",reference:Ba,async:!1,expects:null,requirement:t,message:e,_run(r,n){return r.typed&&!this.requirement(r.value)&&Xt(this,"input",r,n),r}}}function Ge(t){return{kind:"validation",type:"integer",reference:Ge,async:!1,expects:null,requirement:Number.isInteger,message:t,_run(e,r){return e.typed&&!this.requirement(e.value)&&Xt(this,"integer",e,r),e}}}function ku(t){return{kind:"transformation",type:"transform",reference:ku,async:!1,operation:t,_run(e){return e.value=this.operation(e.value),e}}}function Jh(t,e,r){return typeof t.default=="function"?t.default(e,r):t.default}function xd(t,e){return!t._run({typed:!1,value:e},{abortEarly:!0}).issues}function fe(t,e){return{kind:"schema",type:"array",reference:fe,expects:"Array",async:!1,item:t,message:e,_run(r,n){var i;const s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let o=0;o<s.length;o++){const a=s[o],c=this.item._run({typed:!1,value:a},n);if(c.issues){const u={type:"array",origin:"value",input:s,key:o,value:a};for(const f of c.issues)f.path?f.path.unshift(u):f.path=[u],(i=r.issues)==null||i.push(f);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else Xt(this,"type",r,n);return r}}}function Qh(t){return{kind:"schema",type:"bigint",reference:Qh,expects:"bigint",async:!1,message:t,_run(e,r){return typeof e.value=="bigint"?e.typed=!0:Xt(this,"type",e,r),e}}}function Xi(t){return{kind:"schema",type:"boolean",reference:Xi,expects:"boolean",async:!1,message:t,_run(e,r){return typeof e.value=="boolean"?e.typed=!0:Xt(this,"type",e,r),e}}}function sa(t){return{kind:"schema",type:"lazy",reference:sa,expects:"unknown",async:!1,getter:t,_run(e,r){return this.getter(e.value)._run(e,r)}}}function de(t,e){return{kind:"schema",type:"literal",reference:de,expects:B2(t),async:!1,literal:t,message:e,_run(r,n){return r.value===this.literal?r.typed=!0:Xt(this,"type",r,n),r}}}function Se(t,...e){const r={kind:"schema",type:"nullable",reference:Se,expects:`${t.expects} | null`,async:!1,wrapped:t,_run(n,s){return n.value===null&&("default"in this&&(n.value=Jh(this,n,s)),n.value===null)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in e&&(r.default=e[0]),r}function Li(t,...e){const r={kind:"schema",type:"nullish",reference:Li,expects:`${t.expects} | null | undefined`,async:!1,wrapped:t,_run(n,s){return(n.value===null||n.value===void 0)&&("default"in this&&(n.value=Jh(this,n,s)),n.value===null||n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in e&&(r.default=e[0]),r}function De(t){return{kind:"schema",type:"number",reference:De,expects:"number",async:!1,message:t,_run(e,r){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:Xt(this,"type",e,r),e}}}function ee(t,e){return{kind:"schema",type:"object",reference:ee,expects:"Object",async:!1,entries:t,message:e,_run(r,n){var i;const s=r.value;if(s&&typeof s=="object"){r.typed=!0,r.value={};for(const o in this.entries){const a=s[o],c=this.entries[o]._run({typed:!1,value:a},n);if(c.issues){const u={type:"object",origin:"value",input:s,key:o,value:a};for(const f of c.issues)f.path?f.path.unshift(u):f.path=[u],(i=r.issues)==null||i.push(f);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),(c.value!==void 0||o in s)&&(r.value[o]=c.value)}}else Xt(this,"type",r,n);return r}}}function ot(t,...e){const r={kind:"schema",type:"optional",reference:ot,expects:`${t.expects} | undefined`,async:!1,wrapped:t,_run(n,s){return n.value===void 0&&("default"in this&&(n.value=Jh(this,n,s)),n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in e&&(r.default=e[0]),r}function ia(t,e,r){return{kind:"schema",type:"record",reference:ia,expects:"Object",async:!1,key:t,value:e,message:r,_run(n,s){var o,a;const i=n.value;if(i&&typeof i=="object"){n.typed=!0,n.value={};for(const c in i)if(dO(i,c)){const u=i[c],f=this.key._run({typed:!1,value:c},s);if(f.issues){const p={type:"object",origin:"key",input:i,key:c,value:u};for(const d of f.issues)d.path=[p],(o=n.issues)==null||o.push(d);if(n.issues||(n.issues=f.issues),s.abortEarly){n.typed=!1;break}}const l=this.value._run({typed:!1,value:u},s);if(l.issues){const p={type:"object",origin:"value",input:i,key:c,value:u};for(const d of l.issues)d.path?d.path.unshift(p):d.path=[p],(a=n.issues)==null||a.push(d);if(n.issues||(n.issues=l.issues),s.abortEarly){n.typed=!1;break}}(!f.typed||!l.typed)&&(n.typed=!1),f.typed&&(n.value[f.value]=l.value)}}else Xt(this,"type",n,s);return n}}}function ye(t){return{kind:"schema",type:"string",reference:ye,expects:"string",async:!1,message:t,_run(e,r){return typeof e.value=="string"?e.typed=!0:Xt(this,"type",e,r),e}}}function ep(t,e){return{kind:"schema",type:"tuple",reference:ep,expects:"Array",async:!1,items:t,message:e,_run(r,n){var i;const s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let o=0;o<this.items.length;o++){const a=s[o],c=this.items[o]._run({typed:!1,value:a},n);if(c.issues){const u={type:"array",origin:"value",input:s,key:o,value:a};for(const f of c.issues)f.path?f.path.unshift(u):f.path=[u],(i=r.issues)==null||i.push(f);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else Xt(this,"type",r,n);return r}}}function Jy(t){let e;if(t)for(const r of t)e?e.push(...r.issues):e=r.issues;return e}function mt(t,e){return{kind:"schema",type:"union",reference:mt,expects:[...new Set(t.map(r=>r.expects))].join(" | ")||"never",async:!1,options:t,message:e,_run(r,n){let s,i,o;for(const a of this.options){const c=a._run({typed:!1,value:r.value},n);if(c.typed)if(c.issues)i?i.push(c):i=[c];else{s=c;break}else o?o.push(c):o=[c]}if(s)return s;if(i){if(i.length===1)return i[0];Xt(this,"type",r,n,{issues:Jy(i)}),r.typed=!0}else{if((o==null?void 0:o.length)===1)return o[0];Xt(this,"type",r,n,{issues:Jy(o)})}return r}}}function Ws(){return{kind:"schema",type:"unknown",reference:Ws,expects:"unknown",async:!1,_run(t){return t.typed=!0,t}}}function qe(t,e,r){const n=t._run({typed:!1,value:e},cO(r));if(n.issues)throw new hO(n.issues);return n.value}function Ie(...t){return{...t[0],pipe:t,_run(e,r){for(let n=0;n<t.length;n++){if(e.issues&&(t[n].kind==="schema"||t[n].kind==="transformation")){e.typed=!1;break}(!e.issues||!r.abortEarly&&!r.abortPipeEarly)&&(e=t[n]._run(e,r))}return e}}}function ri(t){const e=Object.entries(t).map(([r,n])=>ee({[r]:n}));return Ie(mt(e),ku(r=>({...r,$kind:Object.keys(r)[0]})))}const Ji=Ie(ye(),ku(t=>xe(t)),Ba(vr)),Wt=Ji,Ks=ye(),Lt=Ie(mt([ye(),Ie(De(),Ge())]),Ba(t=>{try{return BigInt(t),BigInt(t)>=0&&BigInt(t)<=18446744073709551615n}catch{return!1}},"Invalid u64")),us=ee({objectId:Ji,version:Lt,digest:ye()}),Fe=Ie(mt([ee({GasCoin:de(!0)}),ee({Input:Ie(De(),Ge()),type:ot(de("pure"))}),ee({Input:Ie(De(),Ge()),type:ot(de("object"))}),ee({Result:Ie(De(),Ge())}),ee({NestedResult:ep([Ie(De(),Ge()),Ie(De(),Ge())])})]),ku(t=>({...t,$kind:Object.keys(t)[0]}))),pO=ee({budget:Se(Lt),price:Se(Lt),owner:Se(Ji),payment:Se(fe(us))}),kd=mt([de("address"),de("bool"),de("u8"),de("u16"),de("u32"),de("u64"),de("u128"),de("u256"),ee({vector:sa(()=>kd)}),ee({datatype:ee({package:ye(),module:ye(),type:ye(),typeParameters:fe(sa(()=>kd))})}),ee({typeParameter:Ie(De(),Ge())})]),yO=ee({ref:Se(mt([de("&"),de("&mut")])),body:kd}),mO=ee({package:Wt,module:ye(),function:ye(),typeArguments:fe(ye()),arguments:fe(Fe),_argumentTypes:ot(Se(fe(yO)))}),bO=ee({name:ye(),inputs:ia(ye(),mt([Fe,fe(Fe)])),data:ia(ye(),Ws())}),gO=ri({MoveCall:mO,TransferObjects:ee({objects:fe(Fe),address:Fe}),SplitCoins:ee({coin:Fe,amounts:fe(Fe)}),MergeCoins:ee({destination:Fe,sources:fe(Fe)}),Publish:ee({modules:fe(Ks),dependencies:fe(Wt)}),MakeMoveVec:ee({type:Se(ye()),elements:fe(Fe)}),Upgrade:ee({modules:fe(Ks),dependencies:fe(Wt),package:Wt,ticket:Fe}),$Intent:bO}),C2=ri({ImmOrOwnedObject:us,SharedObject:ee({objectId:Wt,initialSharedVersion:Lt,mutable:Xi()}),Receiving:us}),wO=ri({Object:C2,Pure:ee({bytes:Ks}),UnresolvedPure:ee({value:Ws()}),UnresolvedObject:ee({objectId:Wt,version:ot(Se(Lt)),digest:ot(Se(ye())),initialSharedVersion:ot(Se(Lt)),mutable:ot(Se(Xi()))})}),Qy=ri({Object:C2,Pure:ee({bytes:Ks})}),$2=ri({None:de(!0),Epoch:Lt}),dc=ee({version:de(2),sender:Li(Ji),expiration:Li($2),gasData:pO,inputs:fe(wO),commands:fe(gO)}),bs={MoveCall(t){const[e,r="",n=""]="target"in t?t.target.split("::"):[t.package,t.module,t.function];return{$kind:"MoveCall",MoveCall:{package:e,module:r,function:n,typeArguments:t.typeArguments??[],arguments:t.arguments??[]}}},TransferObjects(t,e){return{$kind:"TransferObjects",TransferObjects:{objects:t.map(r=>qe(Fe,r)),address:qe(Fe,e)}}},SplitCoins(t,e){return{$kind:"SplitCoins",SplitCoins:{coin:qe(Fe,t),amounts:e.map(r=>qe(Fe,r))}}},MergeCoins(t,e){return{$kind:"MergeCoins",MergeCoins:{destination:qe(Fe,t),sources:e.map(r=>qe(Fe,r))}}},Publish({modules:t,dependencies:e}){return{$kind:"Publish",Publish:{modules:t.map(r=>typeof r=="string"?r:wt(new Uint8Array(r))),dependencies:e.map(r=>vn(r))}}},Upgrade({modules:t,dependencies:e,package:r,ticket:n}){return{$kind:"Upgrade",Upgrade:{modules:t.map(s=>typeof s=="string"?s:wt(new Uint8Array(s))),dependencies:e.map(s=>vn(s)),package:r,ticket:qe(Fe,n)}}},MakeMoveVec({type:t,elements:e}){return{$kind:"MakeMoveVec",MakeMoveVec:{type:t??null,elements:e.map(r=>qe(Fe,r))}}},Intent({name:t,inputs:e={},data:r={}}){return{$kind:"$Intent",$Intent:{name:t,inputs:Object.fromEntries(Object.entries(e).map(([n,s])=>[n,Array.isArray(s)?s.map(i=>qe(Fe,i)):qe(Fe,s)])),data:r}}}},Td=ee({digest:ye(),objectId:ye(),version:mt([Ie(De(),Ge()),ye(),Qh()])}),vO=ri({ImmOrOwned:Td,Shared:ee({objectId:Wt,initialSharedVersion:Lt,mutable:Xi()}),Receiving:Td}),em=ri({Object:vO,Pure:fe(Ie(De(),Ge()))}),R2=mt([ee({kind:de("Input"),index:Ie(De(),Ge()),value:Ws(),type:ot(de("object"))}),ee({kind:de("Input"),index:Ie(De(),Ge()),value:Ws(),type:de("pure")})]),EO=mt([ee({Epoch:Ie(De(),Ge())}),ee({None:Se(de(!0))})]),tm=Ie(mt([De(),ye(),Qh()]),Ba(t=>{if(!["string","number","bigint"].includes(typeof t))return!1;try{return BigInt(t),!0}catch{return!1}})),tp=mt([ee({bool:Se(de(!0))}),ee({u8:Se(de(!0))}),ee({u64:Se(de(!0))}),ee({u128:Se(de(!0))}),ee({address:Se(de(!0))}),ee({signer:Se(de(!0))}),ee({vector:sa(()=>tp)}),ee({struct:sa(()=>SO)}),ee({u16:Se(de(!0))}),ee({u32:Se(de(!0))}),ee({u256:Se(de(!0))})]),SO=ee({address:ye(),module:ye(),name:ye(),typeParams:fe(tp)}),AO=ee({budget:ot(tm),price:ot(tm),payment:ot(fe(Td)),owner:ot(ye())}),xO=[R2,ee({kind:de("GasCoin")}),ee({kind:de("Result"),index:Ie(De(),Ge())}),ee({kind:de("NestedResult"),index:Ie(De(),Ge()),resultIndex:Ie(De(),Ge())})],On=mt([...xO]),kO=ee({kind:de("MoveCall"),target:Ie(ye(),Ba(t=>t.split("::").length===3)),typeArguments:fe(ye()),arguments:fe(On)}),TO=ee({kind:de("TransferObjects"),objects:fe(On),address:On}),_O=ee({kind:de("SplitCoins"),coin:On,amounts:fe(On)}),PO=ee({kind:de("MergeCoins"),destination:On,sources:fe(On)}),IO=ee({kind:de("MakeMoveVec"),type:mt([ee({Some:tp}),ee({None:Se(de(!0))})]),objects:fe(On)}),OO=ee({kind:de("Publish"),modules:fe(fe(Ie(De(),Ge()))),dependencies:fe(ye())}),BO=ee({kind:de("Upgrade"),modules:fe(fe(Ie(De(),Ge()))),dependencies:fe(ye()),packageId:ye(),ticket:On}),CO=[kO,TO,_O,PO,OO,BO,IO],$O=mt([...CO]);ee({version:de(1),sender:ot(ye()),expiration:Li(EO),gasConfig:AO,inputs:fe(R2),transactions:fe($O)});function rm(t){var r;const e=t.inputs.map((n,s)=>{if(n.Object)return{kind:"Input",index:s,value:{Object:n.Object.ImmOrOwnedObject?{ImmOrOwned:n.Object.ImmOrOwnedObject}:n.Object.Receiving?{Receiving:{digest:n.Object.Receiving.digest,version:n.Object.Receiving.version,objectId:n.Object.Receiving.objectId}}:{Shared:{mutable:n.Object.SharedObject.mutable,initialSharedVersion:n.Object.SharedObject.initialSharedVersion,objectId:n.Object.SharedObject.objectId}}},type:"object"};if(n.Pure)return{kind:"Input",index:s,value:{Pure:Array.from(Gt(n.Pure.bytes))},type:"pure"};if(n.UnresolvedPure)return{kind:"Input",type:"pure",index:s,value:n.UnresolvedPure.value};if(n.UnresolvedObject)return{kind:"Input",type:"object",index:s,value:n.UnresolvedObject.objectId};throw new Error("Invalid input")});return{version:1,sender:t.sender??void 0,expiration:((r=t.expiration)==null?void 0:r.$kind)==="Epoch"?{Epoch:Number(t.expiration.Epoch)}:t.expiration?{None:!0}:null,gasConfig:{owner:t.gasData.owner??void 0,budget:t.gasData.budget??void 0,price:t.gasData.price??void 0,payment:t.gasData.payment??void 0},inputs:e,transactions:t.commands.map(n=>{if(n.MakeMoveVec)return{kind:"MakeMoveVec",type:n.MakeMoveVec.type===null?{None:!0}:{Some:Sr.parseFromStr(n.MakeMoveVec.type)},objects:n.MakeMoveVec.elements.map(s=>fn(s,e))};if(n.MergeCoins)return{kind:"MergeCoins",destination:fn(n.MergeCoins.destination,e),sources:n.MergeCoins.sources.map(s=>fn(s,e))};if(n.MoveCall)return{kind:"MoveCall",target:`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`,typeArguments:n.MoveCall.typeArguments,arguments:n.MoveCall.arguments.map(s=>fn(s,e))};if(n.Publish)return{kind:"Publish",modules:n.Publish.modules.map(s=>Array.from(Gt(s))),dependencies:n.Publish.dependencies};if(n.SplitCoins)return{kind:"SplitCoins",coin:fn(n.SplitCoins.coin,e),amounts:n.SplitCoins.amounts.map(s=>fn(s,e))};if(n.TransferObjects)return{kind:"TransferObjects",objects:n.TransferObjects.objects.map(s=>fn(s,e)),address:fn(n.TransferObjects.address,e)};if(n.Upgrade)return{kind:"Upgrade",modules:n.Upgrade.modules.map(s=>Array.from(Gt(s))),dependencies:n.Upgrade.dependencies,packageId:n.Upgrade.package,ticket:fn(n.Upgrade.ticket,e)};throw new Error(`Unknown transaction ${Object.keys(n)}`)})}}function fn(t,e){if(t.$kind==="GasCoin")return{kind:"GasCoin"};if(t.$kind==="Result")return{kind:"Result",index:t.Result};if(t.$kind==="NestedResult")return{kind:"NestedResult",index:t.NestedResult[0],resultIndex:t.NestedResult[1]};if(t.$kind==="Input")return e[t.Input];throw new Error(`Invalid argument ${Object.keys(t)}`)}function RO(t){var e,r,n;return qe(dc,{version:2,sender:t.sender??null,expiration:t.expiration?"Epoch"in t.expiration?{Epoch:t.expiration.Epoch}:{None:!0}:null,gasData:{owner:t.gasConfig.owner??null,budget:((e=t.gasConfig.budget)==null?void 0:e.toString())??null,price:((r=t.gasConfig.price)==null?void 0:r.toString())??null,payment:((n=t.gasConfig.payment)==null?void 0:n.map(s=>({digest:s.digest,objectId:s.objectId,version:s.version.toString()})))??null},inputs:t.inputs.map(s=>{if(s.kind==="Input"){if(xd(em,s.value)){const i=qe(em,s.value);if(i.Object){if(i.Object.ImmOrOwned)return{Object:{ImmOrOwnedObject:{objectId:i.Object.ImmOrOwned.objectId,version:String(i.Object.ImmOrOwned.version),digest:i.Object.ImmOrOwned.digest}}};if(i.Object.Shared)return{Object:{SharedObject:{mutable:i.Object.Shared.mutable??null,initialSharedVersion:i.Object.Shared.initialSharedVersion,objectId:i.Object.Shared.objectId}}};if(i.Object.Receiving)return{Object:{Receiving:{digest:i.Object.Receiving.digest,version:String(i.Object.Receiving.version),objectId:i.Object.Receiving.objectId}}};throw new Error("Invalid object input")}return{Pure:{bytes:wt(new Uint8Array(i.Pure))}}}return s.type==="object"?{UnresolvedObject:{objectId:s.value}}:{UnresolvedPure:{value:s.value}}}throw new Error("Invalid input")}),commands:t.transactions.map(s=>{switch(s.kind){case"MakeMoveVec":return{MakeMoveVec:{type:"Some"in s.type?Sr.tagToString(s.type.Some):null,elements:s.objects.map(i=>ln(i))}};case"MergeCoins":return{MergeCoins:{destination:ln(s.destination),sources:s.sources.map(i=>ln(i))}};case"MoveCall":{const[i,o,a]=s.target.split("::");return{MoveCall:{package:i,module:o,function:a,typeArguments:s.typeArguments,arguments:s.arguments.map(c=>ln(c))}}}case"Publish":return{Publish:{modules:s.modules.map(i=>wt(Uint8Array.from(i))),dependencies:s.dependencies}};case"SplitCoins":return{SplitCoins:{coin:ln(s.coin),amounts:s.amounts.map(i=>ln(i))}};case"TransferObjects":return{TransferObjects:{objects:s.objects.map(i=>ln(i)),address:ln(s.address)}};case"Upgrade":return{Upgrade:{modules:s.modules.map(i=>wt(Uint8Array.from(i))),dependencies:s.dependencies,package:s.packageId,ticket:ln(s.ticket)}}}throw new Error(`Unknown transaction ${Object.keys(s)}`)})})}function ln(t){switch(t.kind){case"GasCoin":return{GasCoin:!0};case"Result":return{Result:t.index};case"NestedResult":return{NestedResult:[t.index,t.resultIndex]};case"Input":return{Input:t.index}}}function Ca(t){return mt(Object.entries(t).map(([e,r])=>ee({[e]:r})))}const br=Ca({GasCoin:de(!0),Input:Ie(De(),Ge()),Result:Ie(De(),Ge()),NestedResult:ep([Ie(De(),Ge()),Ie(De(),Ge())])}),NO=ee({budget:Se(Lt),price:Se(Lt),owner:Se(Ji),payment:Se(fe(us))}),UO=ee({package:Wt,module:ye(),function:ye(),typeArguments:fe(ye()),arguments:fe(br)}),MO=ee({name:ye(),inputs:ia(ye(),mt([br,fe(br)])),data:ia(ye(),Ws())}),FO=Ca({MoveCall:UO,TransferObjects:ee({objects:fe(br),address:br}),SplitCoins:ee({coin:br,amounts:fe(br)}),MergeCoins:ee({destination:br,sources:fe(br)}),Publish:ee({modules:fe(Ks),dependencies:fe(Wt)}),MakeMoveVec:ee({type:Se(ye()),elements:fe(br)}),Upgrade:ee({modules:fe(Ks),dependencies:fe(Wt),package:Wt,ticket:br}),$Intent:MO}),jO=Ca({ImmOrOwnedObject:us,SharedObject:ee({objectId:Wt,initialSharedVersion:Lt,mutable:Xi()}),Receiving:us}),LO=Ca({Object:jO,Pure:ee({bytes:Ks}),UnresolvedPure:ee({value:Ws()}),UnresolvedObject:ee({objectId:Wt,version:ot(Se(Lt)),digest:ot(Se(ye())),initialSharedVersion:ot(Se(Lt)),mutable:ot(Se(Xi()))})}),DO=Ca({None:de(!0),Epoch:Lt}),HO=ee({version:de(2),sender:Li(Ji),expiration:Li(DO),gasData:NO,inputs:fe(LO),commands:fe(FO),digest:ot(Se(ye()))});function zO(t){return{$kind:"Pure",Pure:{bytes:t instanceof Uint8Array?wt(t):t.toBase64()}}}const kr={Pure:zO,ObjectRef({objectId:t,digest:e,version:r}){return{$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{digest:e,version:r,objectId:xe(t)}}}},SharedObjectRef({objectId:t,mutable:e,initialSharedVersion:r}){return{$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{mutable:e,initialSharedVersion:r,objectId:xe(t)}}}},ReceivingRef({objectId:t,digest:e,version:r}){return{$kind:"Object",Object:{$kind:"Receiving",Receiving:{digest:e,version:r,objectId:xe(t)}}}}};BigInt(1e9);const VO="0x1",N2="0x2",qO=vn("0x6"),GO=`${N2}::sui::SUI`;vn("0x5");const WO=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),nt=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),te=new Uint32Array(32);function zn(t,e,r,n,s,i){const o=s[i],a=s[i+1];let c=te[2*t],u=te[2*t+1],f=te[2*e],l=te[2*e+1],p=te[2*r],d=te[2*r+1],m=te[2*n],b=te[2*n+1],E=Vm(c,f,o);u=qm(E,u,l,a),c=E|0,{Dh:b,Dl:m}={Dh:b^u,Dl:m^c},{Dh:b,Dl:m}={Dh:kv(b,m),Dl:Tv(b)},{h:d,l:p}=zm(d,p,b,m),{Bh:l,Bl:f}={Bh:l^d,Bl:f^p},{Bh:l,Bl:f}={Bh:Dm(l,f,24),Bl:Hm(l,f,24)},te[2*t]=c,te[2*t+1]=u,te[2*e]=f,te[2*e+1]=l,te[2*r]=p,te[2*r+1]=d,te[2*n]=m,te[2*n+1]=b}function Vn(t,e,r,n,s,i){const o=s[i],a=s[i+1];let c=te[2*t],u=te[2*t+1],f=te[2*e],l=te[2*e+1],p=te[2*r],d=te[2*r+1],m=te[2*n],b=te[2*n+1],E=Vm(c,f,o);u=qm(E,u,l,a),c=E|0,{Dh:b,Dl:m}={Dh:b^u,Dl:m^c},{Dh:b,Dl:m}={Dh:Dm(b,m,16),Dl:Hm(b,m,16)},{h:d,l:p}=zm(d,p,b,m),{Bh:l,Bl:f}={Bh:l^d,Bl:f^p},{Bh:l,Bl:f}={Bh:Av(l,f,63),Bl:xv(l,f,63)},te[2*t]=c,te[2*t+1]=u,te[2*e]=f,te[2*e+1]=l,te[2*r]=p,te[2*r+1]=d,te[2*n]=m,te[2*n+1]=b}function KO(t,e={},r,n,s){if(ss(r),t<0||t>r)throw new Error("outputLen bigger than keyLen");const{key:i,salt:o,personalization:a}=e;if(i!==void 0&&(i.length<1||i.length>r))throw new Error("key length must be undefined or 1.."+r);if(o!==void 0&&o.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==s)throw new Error("personalization must be undefined or "+s)}class ZO extends Rc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,ss(e),ss(r),this.blockLen=e,this.outputLen=r,this.buffer=new Uint8Array(e),this.buffer32=Io(this.buffer)}update(e){os(this),e=En(e),is(e);const{blockLen:r,buffer:n,buffer32:s}=this,i=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<i;){this.pos===r&&(Kn(s),this.compress(s,0,!1),Kn(s),this.pos=0);const u=Math.min(r-this.pos,i-c),f=o+c;if(u===r&&!(f%4)&&c+u<i){const l=new Uint32Array(a,f,Math.floor((i-c)/4));Kn(l);for(let p=0;c+r<i;p+=s.length,c+=r)this.length+=r,this.compress(l,p,!1);Kn(l);continue}n.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){os(this),Nd(e,this);const{pos:r,buffer32:n}=this;this.finished=!0,Ir(this.buffer.subarray(r)),Kn(n),this.compress(n,0,!0),Kn(n);const s=Io(e);this.get().forEach((i,o)=>s[o]=dn(i))}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){const{buffer:r,length:n,finished:s,destroyed:i,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(r),e.destroyed=i,e.finished=s,e.length=n,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class YO extends ZO{constructor(e={}){const r=e.dkLen===void 0?64:e.dkLen;super(128,r),this.v0l=nt[0]|0,this.v0h=nt[1]|0,this.v1l=nt[2]|0,this.v1h=nt[3]|0,this.v2l=nt[4]|0,this.v2h=nt[5]|0,this.v3l=nt[6]|0,this.v3h=nt[7]|0,this.v4l=nt[8]|0,this.v4h=nt[9]|0,this.v5l=nt[10]|0,this.v5h=nt[11]|0,this.v6l=nt[12]|0,this.v6h=nt[13]|0,this.v7l=nt[14]|0,this.v7h=nt[15]|0,KO(r,e,64,16,16);let{key:n,personalization:s,salt:i}=e,o=0;if(n!==void 0&&(n=En(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=En(i);const a=Io(i);this.v4l^=dn(a[0]),this.v4h^=dn(a[1]),this.v5l^=dn(a[2]),this.v5h^=dn(a[3])}if(s!==void 0){s=En(s);const a=Io(s);this.v6l^=dn(a[0]),this.v6h^=dn(a[1]),this.v7l^=dn(a[2]),this.v7h^=dn(a[3])}if(n!==void 0){const a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:e,v0h:r,v1l:n,v1h:s,v2l:i,v2h:o,v3l:a,v3h:c,v4l:u,v4h:f,v5l:l,v5h:p,v6l:d,v6h:m,v7l:b,v7h:E}=this;return[e,r,n,s,i,o,a,c,u,f,l,p,d,m,b,E]}set(e,r,n,s,i,o,a,c,u,f,l,p,d,m,b,E){this.v0l=e|0,this.v0h=r|0,this.v1l=n|0,this.v1h=s|0,this.v2l=i|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=f|0,this.v5l=l|0,this.v5h=p|0,this.v6l=d|0,this.v6h=m|0,this.v7l=b|0,this.v7h=E|0}compress(e,r,n){this.get().forEach((c,u)=>te[u]=c),te.set(nt,16);let{h:s,l:i}=Lm(BigInt(this.length));te[24]=nt[8]^i,te[25]=nt[9]^s,n&&(te[28]=~te[28],te[29]=~te[29]);let o=0;const a=WO;for(let c=0;c<12;c++)zn(0,4,8,12,e,r+2*a[o++]),Vn(0,4,8,12,e,r+2*a[o++]),zn(1,5,9,13,e,r+2*a[o++]),Vn(1,5,9,13,e,r+2*a[o++]),zn(2,6,10,14,e,r+2*a[o++]),Vn(2,6,10,14,e,r+2*a[o++]),zn(3,7,11,15,e,r+2*a[o++]),Vn(3,7,11,15,e,r+2*a[o++]),zn(0,5,10,15,e,r+2*a[o++]),Vn(0,5,10,15,e,r+2*a[o++]),zn(1,6,11,12,e,r+2*a[o++]),Vn(1,6,11,12,e,r+2*a[o++]),zn(2,7,8,13,e,r+2*a[o++]),Vn(2,7,8,13,e,r+2*a[o++]),zn(3,4,9,14,e,r+2*a[o++]),Vn(3,4,9,14,e,r+2*a[o++]);this.v0l^=te[0]^te[16],this.v0h^=te[1]^te[17],this.v1l^=te[2]^te[18],this.v1h^=te[3]^te[19],this.v2l^=te[4]^te[20],this.v2h^=te[5]^te[21],this.v3l^=te[6]^te[22],this.v3h^=te[7]^te[23],this.v4l^=te[8]^te[24],this.v4h^=te[9]^te[25],this.v5l^=te[10]^te[26],this.v5h^=te[11]^te[27],this.v6l^=te[12]^te[28],this.v6h^=te[13]^te[29],this.v7l^=te[14]^te[30],this.v7h^=te[15]^te[31],Ir(te)}destroy(){this.destroyed=!0,Ir(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const XO=Uv(t=>new YO(t)),U2=XO;function JO(t,e,r){const n=he.Address.serialize(t).toBytes(),s=he.TypeTag.serialize(e).toBytes(),i=he.u64().serialize(r.length).toBytes(),o=U2.create({dkLen:32});return o.update(new Uint8Array([240])),o.update(n),o.update(i),o.update(r),o.update(s),`0x${ji(o.digest().slice(0,32))}`}const QO="object",e4="ID",t4="ascii",r4="String",n4="string",s4="String",i4="option",o4="Option";function a4(t){const e=typeof t.body=="object"&&"datatype"in t.body?t.body.datatype:null;return!!e&&xe(e.package)===xe("0x2")&&e.module==="tx_context"&&e.type==="TxContext"}function _d(t){if(typeof t=="string")switch(t){case"address":return he.Address;case"bool":return he.Bool;case"u8":return he.U8;case"u16":return he.U16;case"u32":return he.U32;case"u64":return he.U64;case"u128":return he.U128;case"u256":return he.U256;default:throw new Error(`Unknown type signature ${t}`)}if("vector"in t){if(t.vector==="u8")return he.vector(he.U8).transform({input:r=>typeof r=="string"?new TextEncoder().encode(r):r,output:r=>r});const e=_d(t.vector);return e?he.vector(e):null}if("datatype"in t){const e=xe(t.datatype.package);if(e===xe(VO)){if(t.datatype.module===t4&&t.datatype.type===r4||t.datatype.module===n4&&t.datatype.type===s4)return he.String;if(t.datatype.module===i4&&t.datatype.type===o4){const r=_d(t.datatype.typeParameters[0]);return r?he.vector(r):null}}if(e===xe(N2)&&t.datatype.module===QO&&t.datatype.type===e4)return he.Address}return null}function c4(t){return typeof t=="object"&&"Reference"in t?{ref:"&",body:To(t.Reference)}:typeof t=="object"&&"MutableReference"in t?{ref:"&mut",body:To(t.MutableReference)}:{ref:null,body:To(t)}}function To(t){if(typeof t=="string")switch(t){case"Address":return"address";case"Bool":return"bool";case"U8":return"u8";case"U16":return"u16";case"U32":return"u32";case"U64":return"u64";case"U128":return"u128";case"U256":return"u256";default:throw new Error(`Unexpected type ${t}`)}if("Vector"in t)return{vector:To(t.Vector)};if("Struct"in t)return{datatype:{package:t.Struct.address,module:t.Struct.module,type:t.Struct.name,typeParameters:t.Struct.typeArguments.map(To)}};if("TypeParameter"in t)return{typeParameter:t.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(t)}`)}const u4=50,f4=1000n,l4=5e10;function M2(t){return async function(r,n,s){return await m4(r,t),await y4(r,t),n.onlyTransactionKind||(await d4(r,t),await h4(r,t),await p4(r,t)),await s()}}async function d4(t,e){t.gasConfig.price||(t.gasConfig.price=String(await e.getReferenceGasPrice()))}async function h4(t,e){if(t.gasConfig.budget)return;const r=await e.dryRunTransactionBlock({transactionBlock:t.build({overrides:{gasData:{budget:String(l4),payment:[]}}})});if(r.effects.status.status!=="success")throw new Error(`Dry run failed, could not automatically determine a budget: ${r.effects.status.error}`,{cause:r});const n=f4*BigInt(t.gasConfig.price||1n),s=BigInt(r.effects.gasUsed.computationCost)+n,i=s+BigInt(r.effects.gasUsed.storageCost)-BigInt(r.effects.gasUsed.storageRebate);t.gasConfig.budget=String(i>s?i:s)}async function p4(t,e){if(!t.gasConfig.payment){const n=(await e.getCoins({owner:t.gasConfig.owner||t.sender,coinType:GO})).data.filter(s=>!t.inputs.find(o=>{var a;return(a=o.Object)!=null&&a.ImmOrOwnedObject?s.coinObjectId===o.Object.ImmOrOwnedObject.objectId:!1})).map(s=>({objectId:s.coinObjectId,digest:s.digest,version:s.version}));if(!n.length)throw new Error("No valid gas coins found for the transaction.");t.gasConfig.payment=n.map(s=>qe(us,s))}}async function y4(t,e){const r=t.inputs.filter(f=>{var l;return f.UnresolvedObject&&!(f.UnresolvedObject.version||(l=f.UnresolvedObject)!=null&&l.initialSharedVersion)}),n=[...new Set(r.map(f=>vn(f.UnresolvedObject.objectId)))],s=n.length?Au(n,u4):[],i=(await Promise.all(s.map(f=>e.multiGetObjects({ids:f,options:{showOwner:!0}})))).flat(),o=new Map(n.map((f,l)=>[f,i[l]])),a=Array.from(o).filter(([f,l])=>l.error).map(([f,l])=>JSON.stringify(l.error));if(a.length)throw new Error(`The following input objects are invalid: ${a.join(", ")}`);const c=i.map(f=>{if(f.error||!f.data)throw new Error(`Failed to fetch object: ${f.error}`);const l=f.data.owner,p=l&&typeof l=="object"?"Shared"in l?l.Shared.initial_shared_version:"ConsensusAddressOwner"in l?l.ConsensusAddressOwner.start_version:null:null;return{objectId:f.data.objectId,digest:f.data.digest,version:f.data.version,initialSharedVersion:p}}),u=new Map(n.map((f,l)=>[f,c[l]]));for(const[f,l]of t.inputs.entries()){if(!l.UnresolvedObject)continue;let p;const d=xe(l.UnresolvedObject.objectId),m=u.get(d);l.UnresolvedObject.initialSharedVersion??(m==null?void 0:m.initialSharedVersion)?p=kr.SharedObjectRef({objectId:d,initialSharedVersion:l.UnresolvedObject.initialSharedVersion||(m==null?void 0:m.initialSharedVersion),mutable:l.UnresolvedObject.mutable||b4(t,f)}):g4(t,f)&&(p=kr.ReceivingRef({objectId:d,digest:l.UnresolvedObject.digest??(m==null?void 0:m.digest),version:l.UnresolvedObject.version??(m==null?void 0:m.version)})),t.inputs[t.inputs.indexOf(l)]=p??kr.ObjectRef({objectId:d,digest:l.UnresolvedObject.digest??(m==null?void 0:m.digest),version:l.UnresolvedObject.version??(m==null?void 0:m.version)})}}async function m4(t,e){const{inputs:r,commands:n}=t,s=[],i=new Set;n.forEach(a=>{if(a.MoveCall){if(a.MoveCall._argumentTypes)return;if(a.MoveCall.arguments.map(f=>f.$kind==="Input"?t.inputs[f.Input]:null).some(f=>(f==null?void 0:f.UnresolvedPure)||(f==null?void 0:f.UnresolvedObject)&&typeof(f==null?void 0:f.UnresolvedObject.mutable)!="boolean")){const f=`${a.MoveCall.package}::${a.MoveCall.module}::${a.MoveCall.function}`;i.add(f),s.push(a.MoveCall)}}});const o=new Map;i.size>0&&await Promise.all([...i].map(async a=>{const[c,u,f]=a.split("::"),l=await e.getNormalizedMoveFunction({package:c,module:u,function:f});o.set(a,l.parameters.map(p=>c4(p)))})),s.length&&await Promise.all(s.map(async a=>{const c=o.get(`${a.package}::${a.module}::${a.function}`);if(!c)return;const f=c.length>0&&a4(c.at(-1))?c.slice(0,c.length-1):c;a._argumentTypes=f})),n.forEach(a=>{if(!a.MoveCall)return;const c=a.MoveCall,u=`${c.package}::${c.module}::${c.function}`,f=c._argumentTypes;if(f){if(f.length!==a.MoveCall.arguments.length)throw new Error(`Incorrect number of arguments for ${u}`);f.forEach((l,p)=>{var P,S;const d=c.arguments[p];if(d.$kind!=="Input")return;const m=r[d.Input];if(!m.UnresolvedPure&&!m.UnresolvedObject)return;const b=((P=m.UnresolvedPure)==null?void 0:P.value)??((S=m.UnresolvedObject)==null?void 0:S.objectId),E=_d(l.body);if(E){d.type="pure",r[r.indexOf(m)]=kr.Pure(E.serialize(b));return}if(typeof b!="string")throw new Error(`Expect the argument to be an object id string, got ${JSON.stringify(b,null,2)}`);d.type="object";const A=m.UnresolvedPure?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:b}}:m;r[d.Input]=A})}})}function b4(t,e){let r=!1;return t.getInputUses(e,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=s.MoveCall._argumentTypes[i].ref!=="&"||r}(s.$kind==="MakeMoveVec"||s.$kind==="MergeCoins"||s.$kind==="SplitCoins"||s.$kind==="TransferObjects")&&(r=!0)}),r}function g4(t,e){let r=!1;return t.getInputUses(e,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=w4(s.MoveCall._argumentTypes[i])||r}}),r}function w4(t){return typeof t.body!="object"||!("datatype"in t.body)?!1:t.body.datatype.package==="0x2"&&t.body.datatype.module==="transfer"&&t.body.datatype.type==="Receiving"}function F2(t,e){return!!(t.inputs.some(r=>r.UnresolvedObject||r.UnresolvedPure)||!e.onlyTransactionKind&&(!t.gasConfig.price||!t.gasConfig.budget||!t.gasConfig.payment))}async function v4(t,e,r){var i;if(S4(t),!F2(t,e))return await nm(t),r();const n=E4(e);return(((i=n.core)==null?void 0:i.resolveTransactionPlugin())??M2(n))(t,e,async()=>{await nm(t),await r()})}function nm(t){t.inputs.forEach((e,r)=>{if(e.$kind!=="Object"&&e.$kind!=="Pure")throw new Error(`Input at index ${r} has not been resolved. Expected a Pure or Object input, but found ${JSON.stringify(e)}`)})}function E4(t){if(!t.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return t.client}function S4(t){for(const e of t.commands)switch(e.$kind){case"SplitCoins":e.SplitCoins.amounts.forEach(r=>{sm(r,he.U64,t)});break;case"TransferObjects":sm(e.TransferObjects.address,he.Address,t);break}}function sm(t,e,r){if(t.$kind!=="Input")return;const n=r.inputs[t.Input];n.$kind==="UnresolvedPure"&&(r.inputs[t.Input]=kr.Pure(e.serialize(n.UnresolvedPure.value)))}function A4(t){function e(r){return t(r)}return e.system=r=>{const n=r==null?void 0:r.mutable;return e(n!==void 0?kr.SharedObjectRef({objectId:"0x5",initialSharedVersion:1,mutable:n}):{$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x5",initialSharedVersion:1}})},e.clock=()=>e(kr.SharedObjectRef({objectId:"0x6",initialSharedVersion:1,mutable:!1})),e.random=()=>e({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x8",mutable:!1}}),e.denyList=r=>e({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x403",mutable:r==null?void 0:r.mutable}}),e.option=({type:r,value:n})=>s=>s.moveCall({typeArguments:[r],target:`0x1::option::${n===null?"none":"some"}`,arguments:n===null?[]:[s.object(n)]}),e}function x4(t){function e(r,n){if(typeof r=="string")return t(ko(r).serialize(n));if(r instanceof Uint8Array||Kh(r))return t(r);throw new Error("tx.pure must be called either a bcs type name, or a serialized bcs value")}return e.u8=r=>t(he.U8.serialize(r)),e.u16=r=>t(he.U16.serialize(r)),e.u32=r=>t(he.U32.serialize(r)),e.u64=r=>t(he.U64.serialize(r)),e.u128=r=>t(he.U128.serialize(r)),e.u256=r=>t(he.U256.serialize(r)),e.bool=r=>t(he.Bool.serialize(r)),e.string=r=>t(he.String.serialize(r)),e.address=r=>t(he.Address.serialize(r)),e.id=e.address,e.vector=(r,n)=>t(he.vector(ko(r)).serialize(n)),e.option=(r,n)=>t(he.option(ko(r)).serialize(n)),e}function k4(t,e){const r=Array.from(`${t}::`).map(s=>s.charCodeAt(0)),n=new Uint8Array(r.length+e.length);return n.set(r),n.set(e,r.length),U2(n,{dkLen:32})}function im(t){return xe(t).replace("0x","")}class Ut{constructor(e){this.version=2,this.sender=(e==null?void 0:e.sender)??null,this.expiration=(e==null?void 0:e.expiration)??null,this.inputs=(e==null?void 0:e.inputs)??[],this.commands=(e==null?void 0:e.commands)??[],this.gasData=(e==null?void 0:e.gasData)??{budget:null,price:null,owner:null,payment:null}}static fromKindBytes(e){const n=he.TransactionKind.parse(e).ProgrammableTransaction;if(!n)throw new Error("Unable to deserialize from bytes.");return Ut.restore({version:2,sender:null,expiration:null,gasData:{budget:null,owner:null,payment:null,price:null},inputs:n.inputs,commands:n.commands})}static fromBytes(e){const r=he.TransactionData.parse(e),n=r==null?void 0:r.V1,s=n.kind.ProgrammableTransaction;if(!n||!s)throw new Error("Unable to deserialize from bytes.");return Ut.restore({version:2,sender:n.sender,expiration:n.expiration,gasData:n.gasData,inputs:s.inputs,commands:s.commands})}static restore(e){return e.version===2?new Ut(qe(dc,e)):new Ut(qe(dc,RO(e)))}static getDigestFromBytes(e){const r=k4("TransactionData",e);return Su(r)}get gasConfig(){return this.gasData}set gasConfig(e){this.gasData=e}build({maxSizeBytes:e=1/0,overrides:r,onlyTransactionKind:n}={}){const s=this.inputs,i=this.commands,o={ProgrammableTransaction:{inputs:s,commands:i}};if(n)return he.TransactionKind.serialize(o,{maxSize:e}).toBytes();const a=(r==null?void 0:r.expiration)??this.expiration,c=(r==null?void 0:r.sender)??this.sender,u={...this.gasData,...r==null?void 0:r.gasConfig,...r==null?void 0:r.gasData};if(!c)throw new Error("Missing transaction sender");if(!u.budget)throw new Error("Missing gas budget");if(!u.payment)throw new Error("Missing gas payment");if(!u.price)throw new Error("Missing gas price");const f={sender:im(c),expiration:a||{None:!0},gasData:{payment:u.payment,owner:im(this.gasData.owner??c),price:BigInt(u.price),budget:BigInt(u.budget)},kind:{ProgrammableTransaction:{inputs:s,commands:i}}};return he.TransactionData.serialize({V1:f},{maxSize:e}).toBytes()}addInput(e,r){const n=this.inputs.length;return this.inputs.push(r),{Input:n,type:e,$kind:"Input"}}getInputUses(e,r){this.mapArguments((n,s)=>(n.$kind==="Input"&&n.Input===e&&r(n,s),n))}mapCommandArguments(e,r){const n=this.commands[e];switch(n.$kind){case"MoveCall":n.MoveCall.arguments=n.MoveCall.arguments.map(i=>r(i,n,e));break;case"TransferObjects":n.TransferObjects.objects=n.TransferObjects.objects.map(i=>r(i,n,e)),n.TransferObjects.address=r(n.TransferObjects.address,n,e);break;case"SplitCoins":n.SplitCoins.coin=r(n.SplitCoins.coin,n,e),n.SplitCoins.amounts=n.SplitCoins.amounts.map(i=>r(i,n,e));break;case"MergeCoins":n.MergeCoins.destination=r(n.MergeCoins.destination,n,e),n.MergeCoins.sources=n.MergeCoins.sources.map(i=>r(i,n,e));break;case"MakeMoveVec":n.MakeMoveVec.elements=n.MakeMoveVec.elements.map(i=>r(i,n,e));break;case"Upgrade":n.Upgrade.ticket=r(n.Upgrade.ticket,n,e);break;case"$Intent":const s=n.$Intent.inputs;n.$Intent.inputs={};for(const[i,o]of Object.entries(s))n.$Intent.inputs[i]=Array.isArray(o)?o.map(a=>r(a,n,e)):r(o,n,e);break;case"Publish":break;default:throw new Error(`Unexpected transaction kind: ${n.$kind}`)}}mapArguments(e){for(const r of this.commands.keys())this.mapCommandArguments(r,e)}replaceCommand(e,r,n=e){if(!Array.isArray(r)){this.commands[e]=r;return}const s=r.length-1;this.commands.splice(e,1,...r),s!==0&&this.mapArguments((i,o,a)=>{if(a<e+r.length)return i;switch(i.$kind){case"Result":i.Result===e&&(i.Result=n),i.Result>e&&(i.Result+=s);break;case"NestedResult":i.NestedResult[0]===e&&(i.NestedResult[0]=n),i.NestedResult[0]>e&&(i.NestedResult[0]+=s);break}return i})}getDigest(){const e=this.build({onlyTransactionKind:!1});return Ut.getDigestFromBytes(e)}snapshot(){return qe(dc,this)}shallowClone(){return new Ut({version:this.version,sender:this.sender,expiration:this.expiration,gasData:{...this.gasData},inputs:[...this.inputs],commands:[...this.commands]})}}function om(t){if(typeof t=="string")return xe(t);if(t.Object)return t.Object.ImmOrOwnedObject?xe(t.Object.ImmOrOwnedObject.objectId):t.Object.Receiving?xe(t.Object.Receiving.objectId):xe(t.Object.SharedObject.objectId);if(t.UnresolvedObject)return xe(t.UnresolvedObject.objectId)}var j2=t=>{throw TypeError(t)},rp=(t,e,r)=>e.has(t)||j2("Cannot "+r),it=(t,e,r)=>(rp(t,e,"read from private field"),r?r.call(t):e.get(t)),uo=(t,e,r)=>e.has(t)?j2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),tc=(t,e,r,n)=>(rp(t,e,"write to private field"),e.set(t,r),r),Tu=(t,e,r)=>(rp(t,e,"access private method"),r),oa,Bn,aa,Zn,Kr,Pd,Id,L2,D2,np;const T4="/",_4={"Mvr-Source":`@mysten/sui@${$w}`};class P4{constructor({cache:e,url:r,pageSize:n=50,overrides:s}){uo(this,Kr),uo(this,oa),uo(this,Bn),uo(this,aa),uo(this,Zn),tc(this,oa,e),tc(this,Bn,r),tc(this,aa,n),tc(this,Zn,{packages:s==null?void 0:s.packages,types:s==null?void 0:s.types}),I4(it(this,Zn))}async resolvePackage({package:e}){return{package:await it(this,Kr,Pd).load(e)}}async resolveType({type:e}){const r=[...Od(e)],n=await it(this,Kr,Id).loadMany(r),s={};for(let i=0;i<r.length;i++){const o=n[i];if(o instanceof Error)throw o;s[r[i]]=o}return{type:Bd(e,s)}}async resolve({types:e=[],packages:r=[]}){var f,l,p;const n=new Set;for(const d of e??[])Od(d,n);const s=[...n],[i,o]=await Promise.all([s.length>0?it(this,Kr,Id).loadMany(s):[],r.length>0?it(this,Kr,Pd).loadMany(r):[]]),a={...(f=it(this,Zn))==null?void 0:f.types};for(const[d,m]of s.entries()){const b=i[d];if(b instanceof Error)throw b;a[m]=b}const c={};for(const d of e??[]){const m=Bd(d,a);c[d]={type:m}}const u={};for(const[d,m]of(r??[]).entries()){const b=((p=(l=it(this,Zn))==null?void 0:l.packages)==null?void 0:p[m])??o[d];if(b instanceof Error)throw b;u[m]={package:b}}return{types:c,packages:u}}}oa=new WeakMap;Bn=new WeakMap;aa=new WeakMap;Zn=new WeakMap;Kr=new WeakSet;Pd=function(){return it(this,oa).readSync(["#mvrPackageDataLoader",it(this,Bn)??""],()=>{var r;const t=new Ww(async n=>{if(!it(this,Bn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await Tu(this,Kr,L2).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve package: ${i}`))}),e=(r=it(this,Zn))==null?void 0:r.packages;if(e)for(const[n,s]of Object.entries(e))t.prime(n,s);return t})};Id=function(){return it(this,oa).readSync(["#mvrTypeDataLoader",it(this,Bn)??""],()=>{var r;const t=new Ww(async n=>{if(!it(this,Bn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await Tu(this,Kr,D2).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve type: ${i}`))}),e=(r=it(this,Zn))==null?void 0:r.types;if(e)for(const[n,s]of Object.entries(e))t.prime(n,s);return t})};L2=async function(t){if(t.length===0)return{};const e=Au(t,it(this,aa)),r={};return await Promise.all(e.map(async n=>{var i;const s=await Tu(this,Kr,np).call(this,"/v1/resolution/bulk",{names:n});if(s!=null&&s.resolution)for(const o of Object.keys(s==null?void 0:s.resolution)){const a=(i=s.resolution[o])==null?void 0:i.package_id;a&&(r[o]=a)}})),r};D2=async function(t){if(t.length===0)return{};const e=Au(t,it(this,aa)),r={};return await Promise.all(e.map(async n=>{var i;const s=await Tu(this,Kr,np).call(this,"/v1/struct-definition/bulk",{types:n});if(s!=null&&s.resolution)for(const o of Object.keys(s==null?void 0:s.resolution)){const a=(i=s.resolution[o])==null?void 0:i.type_tag;a&&(r[o]=a)}})),r};np=async function(t,e){if(!it(this,Bn))throw new Error("MVR Api URL is not set for the current client");const r=await fetch(`${it(this,Bn)}${t}`,{method:"POST",headers:{"Content-Type":"application/json",..._4},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(`Failed to resolve types: ${n==null?void 0:n.message}`)}return r.json()};function I4(t){if(t!=null&&t.packages)for(const[e,r]of Object.entries(t.packages)){if(!zt(e))throw new Error(`Invalid package name: ${e}`);if(!vr(xe(r)))throw new Error(`Invalid package ID: ${r}`)}if(t!=null&&t.types)for(const[e,r]of Object.entries(t.types)){if(Gs(e).typeParams.length>0)throw new Error("Type overrides must be first-level only. If you want to supply generic types, just pass each type individually.");const n=Gs(r);if(!vr(n.address))throw new Error(`Invalid type: ${r}`)}}function Od(t,e=new Set){if(typeof t=="string"&&!Mt(t))return e;const r=H2(t)?t:Gs(t);Mt(r.address)&&e.add(`${r.address}::${r.module}::${r.name}`);for(const n of r.typeParams)Od(n,e);return e}function Bd(t,e){const r=H2(t)?t:Gs(t),n=`${r.address}::${r.module}::${r.name}`,s=e[n];return Ic({...r,address:s?s.split("::")[0]:r.address,typeParams:r.typeParams.map(i=>Bd(i,e))})}function Mt(t){return t.includes(T4)||t.includes("@")||t.includes(".sui")}function H2(t){return typeof t=="object"&&"address"in t&&"module"in t&&"name"in t&&"typeParams"in t}function O4(t){const e=new Set,r=new Set;for(const n of t.commands)switch(n.$kind){case"MakeMoveVec":n.MakeMoveVec.type&&am([n.MakeMoveVec.type]).forEach(o=>{r.add(o)});break;case"MoveCall":const s=n.MoveCall,i=s.package.split("::")[0];if(Mt(i)){if(!zt(i))throw new Error(`Invalid package name: ${i}`);e.add(i)}am(s.typeArguments??[]).forEach(o=>{r.add(o)});break}return{packages:[...e],types:[...r]}}function B4(t,e){var r;for(const n of t.commands){if((r=n.MakeMoveVec)!=null&&r.type){if(!Mt(n.MakeMoveVec.type))continue;if(!e.types[n.MakeMoveVec.type])throw new Error(`No resolution found for type: ${n.MakeMoveVec.type}`);n.MakeMoveVec.type=e.types[n.MakeMoveVec.type].type}const s=n.MoveCall;if(!s)continue;const i=s.package.split("::"),o=i[0];if(Mt(o)&&!e.packages[o])throw new Error(`No address found for package: ${o}`);Mt(o)&&(i[0]=e.packages[o].package,s.package=i.join("::"));const a=s.typeArguments;if(a){for(let c=0;c<a.length;c++)if(Mt(a[c])){if(!e.types[a[c]])throw new Error(`No resolution found for type: ${a[c]}`);a[c]=e.types[a[c]].type}s.typeArguments=a}}}function am(t){const e=new Set;for(const r of t)if(Mt(r)){if(!UI(r))throw new Error(`Invalid type with names: ${r}`);e.add(r)}return e}const C4=t=>async(e,r,n)=>{const s=O4(e);if(s.types.length===0&&s.packages.length===0)return n();const i=await $4(r).core.mvr.resolve({types:s.types,packages:s.packages});B4(e,i),await n()};function $4(t){if(!t.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return t.client}var z2=t=>{throw TypeError(t)},sp=(t,e,r)=>e.has(t)||z2("Cannot "+r),X=(t,e,r)=>(sp(t,e,"read from private field"),r?r.call(t):e.get(t)),zr=(t,e,r)=>e.has(t)?z2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),$e=(t,e,r,n)=>(sp(t,e,"write to private field"),e.set(t,r),r),st=(t,e,r)=>(sp(t,e,"access private method"),r),ks,Cs,mn,Xr,cr,ur,Ar,Yn,ce,Ke,V2,hc,pc,yc,Oc,Cd,ip,q2,G2;function vl(t,e=1/0){const r={$kind:"Result",get Result(){return typeof t=="function"?t():t}},n=[],s=i=>n[i]??(n[i]={$kind:"NestedResult",get NestedResult(){return[typeof t=="function"?t():t,i]}});return new Proxy(r,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(i,o){if(o in i)return Reflect.get(i,o);if(o===Symbol.iterator)return function*(){let c=0;for(;c<e;)yield s(c),c++};if(typeof o=="symbol")return;const a=parseInt(o,10);if(!(Number.isNaN(a)||a<0))return s(a)}})}const W2=Symbol.for("@mysten/transaction");function K2(t){return!!t&&typeof t=="object"&&t[W2]===!0}const cm={buildPlugins:new Map,serializationPlugins:new Map},El=Symbol.for("@mysten/transaction/registry");function fo(){try{const t=globalThis;return t[El]||(t[El]=cm),t[El]}catch{return cm}}const Z2=class $d{constructor(){zr(this,Ke),zr(this,ks),zr(this,Cs),zr(this,mn,new Map),zr(this,Xr,[]),zr(this,cr,[]),zr(this,ur,new Set),zr(this,Ar,new Set),zr(this,Yn,new Map),zr(this,ce),this.object=A4(r=>{var i,o;if(typeof r=="function")return this.object(this.add(r));if(typeof r=="object"&&xd(Fe,r))return r;const n=om(r),s=X(this,ce).inputs.find(a=>n===om(a));return(i=s==null?void 0:s.Object)!=null&&i.SharedObject&&typeof r=="object"&&((o=r.Object)!=null&&o.SharedObject)&&(s.Object.SharedObject.mutable=s.Object.SharedObject.mutable||r.Object.SharedObject.mutable),s?{$kind:"Input",Input:X(this,ce).inputs.indexOf(s),type:"object"}:st(this,Ke,pc).call(this,"object",typeof r=="string"?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:xe(r)}}:r)});const e=fo();$e(this,ce,new Ut),$e(this,Cs,[...e.buildPlugins.values()]),$e(this,ks,[...e.serializationPlugins.values()])}static fromKind(e){const r=new $d;return $e(r,ce,Ut.fromKindBytes(typeof e=="string"?Gt(e):e)),$e(r,Xr,X(r,ce).inputs.slice()),$e(r,cr,X(r,ce).commands.slice()),$e(r,ur,new Set(X(r,cr).map((n,s)=>s))),r}static from(e){const r=new $d;return K2(e)?$e(r,ce,new Ut(e.getData())):typeof e!="string"||!e.startsWith("{")?$e(r,ce,Ut.fromBytes(typeof e=="string"?Gt(e):e)):$e(r,ce,Ut.restore(JSON.parse(e))),$e(r,Xr,X(r,ce).inputs.slice()),$e(r,cr,X(r,ce).commands.slice()),$e(r,ur,new Set(X(r,cr).map((n,s)=>s))),r}static registerGlobalSerializationPlugin(e,r){fo().serializationPlugins.set(e,r??e)}static unregisterGlobalSerializationPlugin(e){fo().serializationPlugins.delete(e)}static registerGlobalBuildPlugin(e,r){fo().buildPlugins.set(e,r??e)}static unregisterGlobalBuildPlugin(e){fo().buildPlugins.delete(e)}addSerializationPlugin(e){X(this,ks).push(e)}addBuildPlugin(e){X(this,Cs).push(e)}addIntentResolver(e,r){if(X(this,mn).has(e)&&X(this,mn).get(e)!==r)throw new Error(`Intent resolver for ${e} already exists`);X(this,mn).set(e,r)}setSender(e){X(this,ce).sender=e}setSenderIfNotSet(e){X(this,ce).sender||(X(this,ce).sender=e)}setExpiration(e){X(this,ce).expiration=e?qe($2,e):null}setGasPrice(e){X(this,ce).gasConfig.price=String(e)}setGasBudget(e){X(this,ce).gasConfig.budget=String(e)}setGasBudgetIfNotSet(e){X(this,ce).gasData.budget==null&&(X(this,ce).gasConfig.budget=String(e))}setGasOwner(e){X(this,ce).gasConfig.owner=e}setGasPayment(e){X(this,ce).gasConfig.payment=e.map(r=>qe(us,r))}get blockData(){return rm(X(this,ce).snapshot())}getData(){return X(this,ce).snapshot()}get[W2](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:x4(e=>Kh(e)?st(this,Ke,pc).call(this,"pure",{$kind:"Pure",Pure:{bytes:e.toBase64()}}):st(this,Ke,pc).call(this,"pure",xd(Qy,e)?qe(Qy,e):e instanceof Uint8Array?kr.Pure(e):{$kind:"UnresolvedPure",UnresolvedPure:{value:e}}))}),this.pure}get gas(){return{$kind:"GasCoin",GasCoin:!0}}objectRef(...e){return this.object(kr.ObjectRef(...e))}receivingRef(...e){return this.object(kr.ReceivingRef(...e))}sharedObjectRef(...e){return this.object(kr.SharedObjectRef(...e))}add(e){if(typeof e=="function"){if(X(this,Yn).has(e))return X(this,Yn).get(e);const r=st(this,Ke,V2).call(this),n=e(r);if(!(n&&typeof n=="object"&&"then"in n))return $e(this,ur,X(r,ur)),X(this,Yn).set(e,n),n;const s=st(this,Ke,hc).call(this,{$kind:"$Intent",$Intent:{name:"AsyncTransactionThunk",inputs:{},data:{resultIndex:X(this,ce).commands.length,result:null}}});X(this,Ar).add(Promise.resolve(n).then(o=>{s.$Intent.data.result=o}));const i=vl(()=>s.$Intent.data.resultIndex);return X(this,Yn).set(e,i),i}else st(this,Ke,hc).call(this,e);return vl(X(this,ce).commands.length-1)}splitCoins(e,r){const n=bs.SplitCoins(typeof e=="string"?this.object(e):st(this,Ke,Oc).call(this,e),r.map(s=>typeof s=="number"||typeof s=="bigint"||typeof s=="string"?this.pure.u64(s):st(this,Ke,yc).call(this,s)));return st(this,Ke,hc).call(this,n),vl(X(this,ce).commands.length-1,r.length)}mergeCoins(e,r){return this.add(bs.MergeCoins(this.object(e),r.map(n=>this.object(n))))}publish({modules:e,dependencies:r}){return this.add(bs.Publish({modules:e,dependencies:r}))}upgrade({modules:e,dependencies:r,package:n,ticket:s}){return this.add(bs.Upgrade({modules:e,dependencies:r,package:n,ticket:this.object(s)}))}moveCall({arguments:e,...r}){return this.add(bs.MoveCall({...r,arguments:e==null?void 0:e.map(n=>st(this,Ke,yc).call(this,n))}))}transferObjects(e,r){return this.add(bs.TransferObjects(e.map(n=>this.object(n)),typeof r=="string"?this.pure.address(r):st(this,Ke,yc).call(this,r)))}makeMoveVec({type:e,elements:r}){return this.add(bs.MakeMoveVec({type:e,elements:r.map(n=>this.object(n))}))}serialize(){return JSON.stringify(rm(X(this,ce).snapshot()))}async toJSON(e={}){await this.prepareForSerialization(e);const r=this.isFullyResolved();return JSON.stringify(qe(HO,r?{...X(this,ce).snapshot(),digest:X(this,ce).getDigest()}:X(this,ce).snapshot()),(n,s)=>typeof s=="bigint"?s.toString():s,2)}async sign(e){const{signer:r,...n}=e,s=await this.build(n);return r.signTransaction(s)}isFullyResolved(){return!(!X(this,ce).sender||X(this,Ar).size>0||X(this,ce).commands.some(e=>e.$Intent)||F2(X(this,ce),{}))}async build(e={}){return await this.prepareForSerialization(e),await st(this,Ke,Cd).call(this,e),X(this,ce).build({onlyTransactionKind:e.onlyTransactionKind})}async getDigest(e={}){return await this.prepareForSerialization(e),await st(this,Ke,Cd).call(this,e),X(this,ce).getDigest()}async prepareForSerialization(e){var s;await st(this,Ke,q2).call(this),st(this,Ke,G2).call(this);const r=new Set;for(const i of X(this,ce).commands)i.$Intent&&r.add(i.$Intent.name);const n=[...X(this,ks)];for(const i of r)if(!((s=e.supportedIntents)!=null&&s.includes(i))){if(!X(this,mn).has(i))throw new Error(`Missing intent resolver for ${i}`);n.push(X(this,mn).get(i))}n.push(C4()),await st(this,Ke,ip).call(this,n,e)}};ks=new WeakMap;Cs=new WeakMap;mn=new WeakMap;Xr=new WeakMap;cr=new WeakMap;ur=new WeakMap;Ar=new WeakMap;Yn=new WeakMap;ce=new WeakMap;Ke=new WeakSet;V2=function(){const t=new Z2;return $e(t,ce,X(this,ce)),$e(t,ks,X(this,ks)),$e(t,Cs,X(this,Cs)),$e(t,mn,X(this,mn)),$e(t,Ar,X(this,Ar)),$e(t,ur,new Set(X(this,ur))),$e(t,Yn,X(this,Yn)),X(this,Xr).push(X(t,Xr)),X(this,cr).push(X(t,cr)),t};hc=function(t){const e=X(this,ce).commands.length;return X(this,cr).push(t),X(this,ur).add(e),X(this,ce).commands.push(t),X(this,ce).mapCommandArguments(e,r=>{if(r.$kind==="Result"&&!X(this,ur).has(r.Result))throw new Error(`Result { Result: ${r.Result} } is not available to use the current transaction`);if(r.$kind==="NestedResult"&&!X(this,ur).has(r.NestedResult[0]))throw new Error(`Result { NestedResult: [${r.NestedResult[0]}, ${r.NestedResult[1]}] } is not available to use the current transaction`);if(r.$kind==="Input"&&r.Input>=X(this,ce).inputs.length)throw new Error(`Input { Input: ${r.Input} } references an input that does not exist in the current transaction`);return r}),t};pc=function(t,e){return X(this,Xr).push(e),X(this,ce).addInput(t,e)};yc=function(t){return Kh(t)?this.pure(t):st(this,Ke,Oc).call(this,t)};Oc=function(t){if(typeof t=="function"){const e=this.add(t);return typeof e=="function"?st(this,Ke,Oc).call(this,e):qe(Fe,e)}return qe(Fe,t)};Cd=async function(t){if(!t.onlyTransactionKind&&!X(this,ce).sender)throw new Error("Missing transaction sender");await st(this,Ke,ip).call(this,[...X(this,Cs),v4],t)};ip=async function(t,e){try{const r=n=>{if(n>=t.length)return()=>{};const s=t[n];return async()=>{const i=r(n+1);let o=!1,a=!1;if(await s(X(this,ce),e,async()=>{if(o)throw new Error(`next() was call multiple times in TransactionPlugin ${n}`);o=!0,await i(),a=!0}),!o)throw new Error(`next() was not called in TransactionPlugin ${n}`);if(!a)throw new Error(`next() was not awaited in TransactionPlugin ${n}`)}};await r(0)()}finally{$e(this,Xr,X(this,ce).inputs.slice()),$e(this,cr,X(this,ce).commands.slice())}};q2=async function(){for(;X(this,Ar).size>0;){const t=Promise.all(X(this,Ar));X(this,Ar).clear(),X(this,Ar).add(t),await t,X(this,Ar).delete(t)}};G2=function(){var o;const t=X(this,ce).commands,e=X(this,ce).inputs,r=X(this,cr).flat(1/0),n=X(this,Xr).flat(1/0);if(r.length!==t.length)throw new Error("Unexpected number of commands found in transaction data");if(n.length!==e.length)throw new Error("Unexpected number of inputs found in transaction data");const s=r.filter(a=>{var c;return((c=a.$Intent)==null?void 0:c.name)!=="AsyncTransactionThunk"});X(this,ce).commands=s,X(this,ce).inputs=n,$e(this,cr,s),$e(this,Xr,n),$e(this,ur,new Set(s.map((a,c)=>c)));function i(a){var f;const c=t[a];if(((f=c.$Intent)==null?void 0:f.name)==="AsyncTransactionThunk"){const l=c.$Intent.data.result;if(l==null)throw new Error("AsyncTransactionThunk has not been resolved");return i(l.Result)}const u=s.indexOf(c);if(u===-1)throw new Error("Unable to find original index for command");return u}X(this,ce).mapArguments(a=>{if(a.$kind==="Input"){const c=n.indexOf(e[a.Input]);if(c===-1)throw new Error("Input has not been resolved");return{...a,Input:c}}else if(a.$kind==="Result"){const c=i(a.Result);return{...a,Result:c}}else if(a.$kind==="NestedResult"){const c=i(a.NestedResult[0]);return{...a,NestedResult:[c,a.NestedResult[1]]}}return a});for(const[a,c]of t.entries())if(((o=c.$Intent)==null?void 0:o.name)==="AsyncTransactionThunk")try{c.$Intent.data.resultIndex=i(a)}catch{}};let Rd=Z2;const R4={mainnet:"https://mainnet.mvr.mystenlabs.com",testnet:"https://testnet.mvr.mystenlabs.com"};class N4 extends n2{constructor(e){var r,n,s;super(e),this.core=this,this.mvr=new P4({cache:this.cache.scope("core.mvr"),url:((r=e.mvr)==null?void 0:r.url)??R4[this.network],pageSize:(n=e.mvr)==null?void 0:n.pageSize,overrides:(s=e.mvr)==null?void 0:s.overrides})}async getObject(e){const{objectId:r}=e,{objects:[n]}=await this.getObjects({objectIds:[r],signal:e.signal});if(n instanceof Error)throw n;return{object:n}}async getDynamicField(e){const r=JO(e.parentId,Sr.parseFromStr(e.name.type),e.name.bcs),{objects:[n]}=await this.getObjects({objectIds:[r],signal:e.signal});if(n instanceof Error)throw n;const s=Gs(n.type),i=await n.content;return{dynamicField:{id:n.id,digest:n.digest,version:n.version,type:n.type,name:{type:typeof s.typeParams[0]=="string"?s.typeParams[0]:Ic(s.typeParams[0]),bcs:e.name.bcs},value:{type:typeof s.typeParams[1]=="string"?s.typeParams[1]:Ic(s.typeParams[1]),bcs:i.slice(xu+e.name.bcs.length)}}}}async waitForTransaction({signal:e,timeout:r=60*1e3,...n}){const s=e?AbortSignal.any([AbortSignal.timeout(r),e]):AbortSignal.timeout(r),i=new Promise((o,a)=>{s.addEventListener("abort",()=>a(s.reason))});for(i.catch(()=>{});;){s.throwIfAborted();try{return await this.getTransaction({...n,signal:s})}catch{await Promise.race([new Promise(a=>setTimeout(a,2e3)),i])}}}}class U4 extends Error{}class Xn extends U4{constructor(e,r){super(r),this.code=e}static fromResponse(e,r){switch(e.code){case"notExists":return new Xn(e.code,`Object ${e.object_id} does not exist`);case"dynamicFieldNotFound":return new Xn(e.code,`Dynamic field not found for object ${e.parent_object_id}`);case"deleted":return new Xn(e.code,`Object ${e.object_id} has been deleted`);case"displayError":return new Xn(e.code,`Display error: ${e.error}`);case"unknown":default:return new Xn(e.code,`Unknown error while loading object${r?` ${r}`:""}`)}}}function M4(t){return{...Ut.fromBytes(t).snapshot(),bcs:t}}function F4(t){const e=he.TransactionEffects.parse(t);switch(e.$kind){case"V1":return j4({effects:e.V1});case"V2":return L4({bytes:t,effects:e.V2});default:throw new Error(`Unknown transaction effects version: ${e.$kind}`)}}function j4(t){throw new Error("V1 effects are not supported yet")}function L4({bytes:t,effects:e}){const r=e.changedObjects.map(([n,s])=>{var i,o,a,c,u,f;return{id:n,inputState:s.inputState.$kind==="Exist"?"Exists":"DoesNotExist",inputVersion:((i=s.inputState.Exist)==null?void 0:i[0][0])??null,inputDigest:((o=s.inputState.Exist)==null?void 0:o[0][1])??null,inputOwner:((a=s.inputState.Exist)==null?void 0:a[1])??null,outputState:s.outputState.$kind==="NotExist"?"DoesNotExist":s.outputState.$kind,outputVersion:s.outputState.$kind==="PackageWrite"?(c=s.outputState.PackageWrite)==null?void 0:c[0]:s.outputState.ObjectWrite?e.lamportVersion:null,outputDigest:s.outputState.$kind==="PackageWrite"?(u=s.outputState.PackageWrite)==null?void 0:u[1]:((f=s.outputState.ObjectWrite)==null?void 0:f[0])??null,outputOwner:s.outputState.ObjectWrite?s.outputState.ObjectWrite[1]:null,idOperation:s.idOperation.$kind}});return{bcs:t,digest:e.transactionDigest,version:2,status:e.status.$kind==="Success"?{success:!0,error:null}:{success:!1,error:e.status.Failed.error.$kind},gasUsed:e.gasUsed,transactionDigest:e.transactionDigest,gasObject:e.gasObjectIndex===null?null:r[e.gasObjectIndex]??null,eventsDigest:e.eventsDigest,dependencies:e.dependencies,lamportVersion:e.lamportVersion,changedObjects:r,unchangedSharedObjects:e.unchangedSharedObjects.map(([n,s])=>({kind:s.$kind==="MutateDeleted"?"MutateConsensusStreamEnded":s.$kind==="ReadDeleted"?"ReadConsensusStreamEnded":s.$kind,objectId:n,version:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[0]:s[s.$kind],digest:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[1]:null})),auxiliaryDataDigest:e.auxDataDigest}}var Y2=t=>{throw TypeError(t)},X2=(t,e,r)=>e.has(t)||Y2("Cannot "+r),Ht=(t,e,r)=>(X2(t,e,"read from private field"),r?r.call(t):e.get(t)),D4=(t,e,r)=>e.has(t)?Y2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),H4=(t,e,r,n)=>(X2(t,e,"write to private field"),e.set(t,r),r),gt;class z4 extends N4{constructor({jsonRpcClient:e,mvr:r}){super({network:e.network,base:e,mvr:r}),D4(this,gt),H4(this,gt,e)}async getObjects(e){const r=Au(e.objectIds,50),n=[];for(const s of r){const i=await Ht(this,gt).multiGetObjects({ids:s,options:{showOwner:!0,showType:!0,showBcs:!0},signal:e.signal});for(const[o,a]of i.entries())a.error?n.push(Xn.fromResponse(a.error,s[o])):n.push(um(a.data))}return{objects:n}}async getOwnedObjects(e){const r=await Ht(this,gt).getOwnedObjects({owner:e.address,limit:e.limit,cursor:e.cursor,options:{showOwner:!0,showType:!0,showBcs:!0},filter:e.type?{StructType:e.type}:null,signal:e.signal});return{objects:r.data.map(n=>{if(n.error)throw Xn.fromResponse(n.error);return um(n.data)}),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getCoins(e){const r=await Ht(this,gt).getCoins({owner:e.address,coinType:e.coinType,limit:e.limit,cursor:e.cursor,signal:e.signal});return{objects:r.data.map(n=>({id:n.coinObjectId,version:n.version,digest:n.digest,balance:n.balance,type:`0x2::coin::Coin<${n.coinType}>`,content:Promise.resolve(G4.serialize({id:n.coinObjectId,balance:{value:n.balance}}).toBytes()),owner:{$kind:"ObjectOwner",ObjectOwner:e.address}})),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getBalance(e){const r=await Ht(this,gt).getBalance({owner:e.address,coinType:e.coinType,signal:e.signal});return{balance:{coinType:r.coinType,balance:r.totalBalance}}}async getAllBalances(e){return{balances:(await Ht(this,gt).getAllBalances({owner:e.address,signal:e.signal})).map(n=>({coinType:n.coinType,balance:n.totalBalance})),hasNextPage:!1,cursor:null}}async getTransaction(e){const r=await Ht(this,gt).getTransactionBlock({digest:e.digest,options:{showRawInput:!0,showObjectChanges:!0,showRawEffects:!0,showEvents:!0,showEffects:!0},signal:e.signal});return{transaction:fm(r)}}async executeTransaction(e){const r=await Ht(this,gt).executeTransactionBlock({transactionBlock:e.transaction,signature:e.signatures,options:{showRawEffects:!0,showEvents:!0,showObjectChanges:!0,showRawInput:!0,showEffects:!0},signal:e.signal});return{transaction:fm(r)}}async dryRunTransaction(e){const r=Rd.from(e.transaction),n=await Ht(this,gt).dryRunTransactionBlock({transactionBlock:e.transaction,signal:e.signal}),{effects:s,objectTypes:i}=V4({effects:n.effects,objectChanges:n.objectChanges});return{transaction:{digest:await r.getDigest(),epoch:null,effects:s,objectTypes:Promise.resolve(i),signatures:[],transaction:M4(e.transaction)}}}async getReferenceGasPrice(e){const r=await Ht(this,gt).getReferenceGasPrice({signal:e==null?void 0:e.signal});return{referenceGasPrice:String(r)}}async getDynamicFields(e){const r=await Ht(this,gt).getDynamicFields({parentId:e.parentId,limit:e.limit,cursor:e.cursor});return{dynamicFields:r.data.map(n=>({id:n.objectId,type:n.objectType,name:{type:n.name.type,bcs:Gt(n.bcsName)}})),hasNextPage:r.hasNextPage,cursor:r.nextCursor}}async verifyZkLoginSignature(e){const r=await Ht(this,gt).verifyZkLoginSignature({bytes:e.bytes,signature:e.signature,intentScope:e.intentScope,author:e.author});return{success:r.success,errors:r.errors}}resolveNameServiceNames(e){return Ht(this,gt).resolveNameServiceNames(e)}resolveTransactionPlugin(){return M2(Ht(this,gt))}}gt=new WeakMap;function um(t){var e;return{id:t.objectId,version:t.version,digest:t.digest,type:t.type,content:Promise.resolve(((e=t.bcs)==null?void 0:e.dataType)==="moveObject"?Gt(t.bcs.bcsBytes):new Uint8Array),owner:yi(t.owner)}}function yi(t){if(t==="Immutable")return{$kind:"Immutable",Immutable:!0};if("ConsensusAddressOwner"in t)return{$kind:"ConsensusAddressOwner",ConsensusAddressOwner:{owner:t.ConsensusAddressOwner.owner,startVersion:t.ConsensusAddressOwner.start_version}};if("AddressOwner"in t)return{$kind:"AddressOwner",AddressOwner:t.AddressOwner};if("ObjectOwner"in t)return{$kind:"ObjectOwner",ObjectOwner:t.ObjectOwner};if("Shared"in t)return{$kind:"Shared",Shared:{initialSharedVersion:t.Shared.initial_shared_version}};throw new Error(`Unknown owner type: ${JSON.stringify(t)}`)}function fm(t){var i,o;const e=he.SenderSignedData.parse(Gt(t.rawTransaction))[0],r={};(i=t.objectChanges)==null||i.forEach(a=>{a.type!=="published"&&(r[a.objectId]=a.objectType)});const n=he.TransactionData.serialize(e.intentMessage.value).toBytes(),s=Ut.restore({version:2,sender:e.intentMessage.value.V1.sender,expiration:e.intentMessage.value.V1.expiration,gasData:e.intentMessage.value.V1.gasData,inputs:e.intentMessage.value.V1.kind.ProgrammableTransaction.inputs,commands:e.intentMessage.value.V1.kind.ProgrammableTransaction.commands});return{digest:t.digest,epoch:((o=t.effects)==null?void 0:o.executedEpoch)??null,effects:F4(new Uint8Array(t.rawEffects)),objectTypes:Promise.resolve(r),transaction:{...s,bcs:n},signatures:e.txSignatures}}function V4({bytes:t,effects:e,objectChanges:r}){var o;const n=[],s=[],i={};return r==null||r.forEach(a=>{var c,u,f,l;switch(a.type){case"published":n.push({id:a.packageId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"PackageWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:null,idOperation:"Created"});break;case"transferred":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:a.digest,inputOwner:{$kind:"AddressOwner",AddressOwner:a.sender},outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:yi(a.recipient),idOperation:"None"}),i[a.objectId]=a.objectType;break;case"mutated":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.previousVersion,inputDigest:null,inputOwner:yi(a.owner),outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:yi(a.owner),idOperation:"None"}),i[a.objectId]=a.objectType;break;case"deleted":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:((u=(c=e.deleted)==null?void 0:c.find(p=>p.objectId===a.objectId))==null?void 0:u.digest)??null,inputOwner:null,outputState:"DoesNotExist",outputVersion:null,outputDigest:null,outputOwner:null,idOperation:"Deleted"}),i[a.objectId]=a.objectType;break;case"wrapped":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:null,inputOwner:{$kind:"AddressOwner",AddressOwner:a.sender},outputState:"ObjectWrite",outputVersion:a.version,outputDigest:((l=(f=e.wrapped)==null?void 0:f.find(p=>p.objectId===a.objectId))==null?void 0:l.digest)??null,outputOwner:{$kind:"ObjectOwner",ObjectOwner:a.sender},idOperation:"None"}),i[a.objectId]=a.objectType;break;case"created":n.push({id:a.objectId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:yi(a.owner),idOperation:"Created"}),i[a.objectId]=a.objectType;break}}),{objectTypes:i,effects:{bcs:t??null,digest:e.transactionDigest,version:2,status:e.status.status==="success"?{success:!0,error:null}:{success:!1,error:e.status.error},gasUsed:e.gasUsed,transactionDigest:e.transactionDigest,gasObject:{id:(o=e.gasObject)==null?void 0:o.reference.objectId,inputState:"Exists",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:e.gasObject.reference.version,outputDigest:e.gasObject.reference.digest,outputOwner:yi(e.gasObject.owner),idOperation:"None"},eventsDigest:e.eventsDigest??null,dependencies:e.dependencies??[],lamportVersion:e.gasObject.reference.version,changedObjects:n,unchangedSharedObjects:s,auxiliaryDataDigest:null}}}const q4=he.struct("Balance",{value:he.u64()}),G4=he.struct("Coin",{id:he.Address,balance:q4}),W4=Symbol.for("@mysten/SuiClient");class lm extends n2{constructor(e){super({network:e.network??"unknown"}),this.jsonRpc=this,this.transport=e.transport??new YP({url:e.url}),this.core=new z4({jsonRpcClient:this,mvr:e.mvr})}get[W4](){return!0}async getRpcApiVersion({signal:e}={}){return(await this.transport.request({method:"rpc.discover",params:[],signal:e})).info.version}async getCoins({coinType:e,owner:r,cursor:n,limit:s,signal:i}){if(!r||!vr(xe(r)))throw new Error("Invalid Sui address");return e&&Mt(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoins",params:[r,e,n,s],signal:i})}async getAllCoins(e){if(!e.owner||!vr(xe(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllCoins",params:[e.owner,e.cursor,e.limit],signal:e.signal})}async getBalance({owner:e,coinType:r,signal:n}){if(!e||!vr(xe(e)))throw new Error("Invalid Sui address");return r&&Mt(r)&&(r=(await this.core.mvr.resolveType({type:r})).type),await this.transport.request({method:"suix_getBalance",params:[e,r],signal:n})}async getAllBalances(e){if(!e.owner||!vr(xe(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllBalances",params:[e.owner],signal:e.signal})}async getCoinMetadata({coinType:e,signal:r}){return e&&Mt(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoinMetadata",params:[e],signal:r})}async getTotalSupply({coinType:e,signal:r}){return e&&Mt(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getTotalSupply",params:[e],signal:r})}async call(e,r,{signal:n}={}){return await this.transport.request({method:e,params:r,signal:n})}async getMoveFunctionArgTypes({package:e,module:r,function:n,signal:s}){return e&&zt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getMoveFunctionArgTypes",params:[e,r,n],signal:s})}async getNormalizedMoveModulesByPackage({package:e,signal:r}){return e&&zt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModulesByPackage",params:[e],signal:r})}async getNormalizedMoveModule({package:e,module:r,signal:n}){return e&&zt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModule",params:[e,r],signal:n})}async getNormalizedMoveFunction({package:e,module:r,function:n,signal:s}){return e&&zt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveFunction",params:[e,r,n],signal:s})}async getNormalizedMoveStruct({package:e,module:r,struct:n,signal:s}){return e&&zt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveStruct",params:[e,r,n],signal:s})}async getOwnedObjects(e){if(!e.owner||!vr(xe(e.owner)))throw new Error("Invalid Sui address");const r=e.filter?{...e.filter}:void 0;return r&&"MoveModule"in r&&zt(r.MoveModule.package)?r.MoveModule={module:r.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:r.MoveModule.package})).package}:r&&"StructType"in r&&Mt(r.StructType)&&(r.StructType=(await this.core.mvr.resolveType({type:r.StructType})).type),await this.transport.request({method:"suix_getOwnedObjects",params:[e.owner,{filter:r,options:e.options},e.cursor,e.limit],signal:e.signal})}async getObject(e){if(!e.id||!ec(vn(e.id)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"sui_getObject",params:[e.id,e.options],signal:e.signal})}async tryGetPastObject(e){return await this.transport.request({method:"sui_tryGetPastObject",params:[e.id,e.version,e.options],signal:e.signal})}async multiGetObjects(e){if(e.ids.forEach(n=>{if(!n||!ec(vn(n)))throw new Error(`Invalid Sui Object id ${n}`)}),e.ids.length!==new Set(e.ids).size)throw new Error(`Duplicate object ids in batch call ${e.ids}`);return await this.transport.request({method:"sui_multiGetObjects",params:[e.ids,e.options],signal:e.signal})}async queryTransactionBlocks({filter:e,options:r,cursor:n,limit:s,order:i,signal:o}){return e&&"MoveFunction"in e&&zt(e.MoveFunction.package)&&(e={...e,MoveFunction:{package:(await this.core.mvr.resolvePackage({package:e.MoveFunction.package})).package}}),await this.transport.request({method:"suix_queryTransactionBlocks",params:[{filter:e,options:r},n,s,(i||"descending")==="descending"],signal:o})}async getTransactionBlock(e){if(!Yy(e.digest))throw new Error("Invalid Transaction digest");return await this.transport.request({method:"sui_getTransactionBlock",params:[e.digest,e.options],signal:e.signal})}async multiGetTransactionBlocks(e){if(e.digests.forEach(n=>{if(!Yy(n))throw new Error(`Invalid Transaction digest ${n}`)}),e.digests.length!==new Set(e.digests).size)throw new Error(`Duplicate digests in batch call ${e.digests}`);return await this.transport.request({method:"sui_multiGetTransactionBlocks",params:[e.digests,e.options],signal:e.signal})}async executeTransactionBlock({transactionBlock:e,signature:r,options:n,requestType:s,signal:i}){const o=await this.transport.request({method:"sui_executeTransactionBlock",params:[typeof e=="string"?e:wt(e),Array.isArray(r)?r:[r],n],signal:i});if(s==="WaitForLocalExecution")try{await this.waitForTransaction({digest:o.digest})}catch{}return o}async signAndExecuteTransaction({transaction:e,signer:r,...n}){let s;e instanceof Uint8Array?s=e:(e.setSenderIfNotSet(r.toSuiAddress()),s=await e.build({client:this}));const{signature:i,bytes:o}=await r.signTransaction(s);return this.executeTransactionBlock({transactionBlock:o,signature:i,...n})}async getTotalTransactionBlocks({signal:e}={}){const r=await this.transport.request({method:"sui_getTotalTransactionBlocks",params:[],signal:e});return BigInt(r)}async getReferenceGasPrice({signal:e}={}){const r=await this.transport.request({method:"suix_getReferenceGasPrice",params:[],signal:e});return BigInt(r)}async getStakes(e){if(!e.owner||!vr(xe(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getStakes",params:[e.owner],signal:e.signal})}async getStakesByIds(e){return e.stakedSuiIds.forEach(r=>{if(!r||!ec(vn(r)))throw new Error(`Invalid Sui Stake id ${r}`)}),await this.transport.request({method:"suix_getStakesByIds",params:[e.stakedSuiIds],signal:e.signal})}async getLatestSuiSystemState({signal:e}={}){return await this.transport.request({method:"suix_getLatestSuiSystemState",params:[],signal:e})}async queryEvents({query:e,cursor:r,limit:n,order:s,signal:i}){return e&&"MoveEventType"in e&&Mt(e.MoveEventType)&&(e={...e,MoveEventType:(await this.core.mvr.resolveType({type:e.MoveEventType})).type}),e&&"MoveEventModule"in e&&zt(e.MoveEventModule.package)&&(e={...e,MoveEventModule:{module:e.MoveEventModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveEventModule.package})).package}}),"MoveModule"in e&&zt(e.MoveModule.package)&&(e={...e,MoveModule:{module:e.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveModule.package})).package}}),await this.transport.request({method:"suix_queryEvents",params:[e,r,n,(s||"descending")==="descending"],signal:i})}async subscribeEvent(e){return this.transport.subscribe({method:"suix_subscribeEvent",unsubscribe:"suix_unsubscribeEvent",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async subscribeTransaction(e){return this.transport.subscribe({method:"suix_subscribeTransaction",unsubscribe:"suix_unsubscribeTransaction",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async devInspectTransactionBlock(e){var n,s;let r;if(K2(e.transactionBlock))e.transactionBlock.setSenderIfNotSet(e.sender),r=wt(await e.transactionBlock.build({client:this,onlyTransactionKind:!0}));else if(typeof e.transactionBlock=="string")r=e.transactionBlock;else if(e.transactionBlock instanceof Uint8Array)r=wt(e.transactionBlock);else throw new Error("Unknown transaction block format.");return(n=e.signal)==null||n.throwIfAborted(),await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e.sender,r,(s=e.gasPrice)==null?void 0:s.toString(),e.epoch],signal:e.signal})}async dryRunTransactionBlock(e){return await this.transport.request({method:"sui_dryRunTransactionBlock",params:[typeof e.transactionBlock=="string"?e.transactionBlock:wt(e.transactionBlock)]})}async getDynamicFields(e){if(!e.parentId||!ec(vn(e.parentId)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"suix_getDynamicFields",params:[e.parentId,e.cursor,e.limit],signal:e.signal})}async getDynamicFieldObject(e){return await this.transport.request({method:"suix_getDynamicFieldObject",params:[e.parentId,e.name],signal:e.signal})}async getLatestCheckpointSequenceNumber({signal:e}={}){const r=await this.transport.request({method:"sui_getLatestCheckpointSequenceNumber",params:[],signal:e});return String(r)}async getCheckpoint(e){return await this.transport.request({method:"sui_getCheckpoint",params:[e.id],signal:e.signal})}async getCheckpoints(e){return await this.transport.request({method:"sui_getCheckpoints",params:[e.cursor,e==null?void 0:e.limit,e.descendingOrder],signal:e.signal})}async getCommitteeInfo(e){return await this.transport.request({method:"suix_getCommitteeInfo",params:[e==null?void 0:e.epoch],signal:e==null?void 0:e.signal})}async getNetworkMetrics({signal:e}={}){return await this.transport.request({method:"suix_getNetworkMetrics",params:[],signal:e})}async getAddressMetrics({signal:e}={}){return await this.transport.request({method:"suix_getLatestAddressMetrics",params:[],signal:e})}async getEpochMetrics(e){return await this.transport.request({method:"suix_getEpochMetrics",params:[e==null?void 0:e.cursor,e==null?void 0:e.limit,e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getAllEpochAddressMetrics(e){return await this.transport.request({method:"suix_getAllEpochAddressMetrics",params:[e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getEpochs(e){return await this.transport.request({method:"suix_getEpochs",params:[e==null?void 0:e.cursor,e==null?void 0:e.limit,e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getMoveCallMetrics({signal:e}={}){return await this.transport.request({method:"suix_getMoveCallMetrics",params:[],signal:e})}async getCurrentEpoch({signal:e}={}){return await this.transport.request({method:"suix_getCurrentEpoch",params:[],signal:e})}async getValidatorsApy({signal:e}={}){return await this.transport.request({method:"suix_getValidatorsApy",params:[],signal:e})}async getChainIdentifier({signal:e}={}){const r=await this.getCheckpoint({id:"0",signal:e}),n=na(r.digest);return ji(n.slice(0,4))}async resolveNameServiceAddress(e){return await this.transport.request({method:"suix_resolveNameServiceAddress",params:[e.name],signal:e.signal})}async resolveNameServiceNames({format:e="dot",...r}){const{nextCursor:n,hasNextPage:s,data:i}=await this.transport.request({method:"suix_resolveNameServiceNames",params:[r.address,r.cursor,r.limit],signal:r.signal});return{hasNextPage:s,nextCursor:n,data:i.map(o=>CI(o,e))}}async getProtocolConfig(e){return await this.transport.request({method:"sui_getProtocolConfig",params:[e==null?void 0:e.version],signal:e==null?void 0:e.signal})}async verifyZkLoginSignature(e){return await this.transport.request({method:"sui_verifyZkLoginSignature",params:[e.bytes,e.signature,e.intentScope,e.author],signal:e.signal})}async waitForTransaction({signal:e,timeout:r=60*1e3,pollInterval:n=2*1e3,...s}){const i=AbortSignal.timeout(r),o=new Promise((a,c)=>{i.addEventListener("abort",()=>c(i.reason))});for(o.catch(()=>{});!i.aborted;){e==null||e.throwIfAborted();try{return await this.getTransactionBlock(s)}catch{await Promise.race([new Promise(c=>setTimeout(c,n)),o])}}throw i.throwIfAborted(),new Error("Unexpected error while waiting for transaction block.")}experimental_asClientExtension(){return{name:"jsonRPC",register:()=>this}}}class K4{constructor(e,r,n){this.client=new lm({url:Gy(n)}),this.url=e instanceof g.Url?e:new g.Url(e),this.account=r,this.network=n}get htlcActorAddress(){return"accounts"in this.account?this.account.accounts[0].address:this.account.toSuiAddress()}async initiate(e){var r,n,s;if(!e)return g.Err("Order is required");if(Y.isSuiOrderResponse(e))return this.initiateWithCreateOrderResponse(e);try{const{source_swap:i}=e,o=BigInt(i.amount),a=i.asset,c=i.redeemer,u=i.secret_hash,f=await Ih(i.asset,this.url);if(!f.ok)return g.Err(f.error);const{tokenAddress:l}=f.val,p=new Rd;p.setSender(this.htlcActorAddress);const[d]=p.splitCoins(p.gas,[o]);p.moveCall({target:`${ud[this.network].packageId}::${ud[this.network].moduleName}::initiate`,typeArguments:[l],arguments:[p.object(a),p.pure.address(this.htlcActorAddress),p.pure.address(c),p.pure.vector("u8",Buffer.from(u,"hex")),p.pure.u64(o),p.pure.u256(i.timelock),p.pure.vector("u8",Buffer.from("")),d,p.object(qO)]});const m=await p.build({client:this.client}),b=await this.client.dryRunTransactionBlock({transactionBlock:m});if(b.effects.status.status==="failure")return g.Err(`${b.effects.status.error}`);let E;if("features"in this.account?E=await((r=this.account.features[fp.SuiSignAndExecuteTransaction])==null?void 0:r.signAndExecuteTransaction({transaction:p,account:this.account.accounts[0],chain:`sui:${this.network}`})):E=await this.client.signAndExecuteTransaction({signer:this.account,transaction:p,options:{showEffects:!0}}),!E)return g.Err("Failed to initiate");const A=await this.client.waitForTransaction({digest:E.digest,options:{showEffects:!0}});return((n=A.effects)==null?void 0:n.status.status)==="failure"?g.Err(`Failed to initiate: ${(s=A.effects)==null?void 0:s.status.error}`):g.Ok(A.digest)}catch(i){return g.Err(i)}}async initiateWithCreateOrderResponse(e){var a,c,u;const{ptb_bytes:r}=e,s=await new lm({url:Gy("testnet")}).getReferenceGasPrice(),i=1e7,o=Rd.fromKind(new Uint8Array(r));o.setSender(this.htlcActorAddress),o.setGasPrice(s),o.setGasBudget(i);try{let f;if("features"in this.account?f=await((a=this.account.features[fp.SuiSignAndExecuteTransaction])==null?void 0:a.signAndExecuteTransaction({transaction:o,account:this.account.accounts[0],chain:`sui:${this.network}`})):f=await this.client.signAndExecuteTransaction({signer:this.account,transaction:o,options:{showEffects:!0}}),!f)return g.Err("Failed to initiate");const l=await this.client.waitForTransaction({digest:f.digest,options:{showEffects:!0}});return((c=l.effects)==null?void 0:c.status.status)==="failure"?g.Err(`Failed to initiate: ${(u=l.effects)==null?void 0:u.status.error}`):g.Ok(l.digest)}catch(f){return g.Err(String(f))}}async redeem(e,r){try{const n=await g.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:e.order_id,secret:r,perform_on:"Destination"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return n.error?g.Err(n.error):n.result?g.Ok(n.result):g.Err("Redeem: No result found")}catch(n){return g.Err(String(n))}}async refund(){return g.Err("Refund is taken care of by the relayer")}}const Z4=t=>{if(t)if(typeof t=="string"){const e=g.DigestKey.from(t);if(!e.ok)throw new Error(e.error);return e.val}else return t},dm=t=>typeof t=="string"?new g.ApiKey(t):t;class Y4{constructor(e={}){const r={stdTTL:e.ttl?e.ttl/1e3:3600,checkperiod:600};this.cache=new a6(r)}makeKey(e,r){return`${e}:${r}`}set(e,r,n,s){const i=this.makeKey(e,r);s?this.cache.set(i,n,s/1e3):this.cache.set(i,n)}get(e,r){const n=this.makeKey(e,r);return this.cache.get(n)}remove(e,r){const n=this.makeKey(e,r);this.cache.del(n)}clear(e){if(e){const r=this.cache.keys().filter(n=>n.startsWith(`${e}:`));this.cache.del(r)}else this.cache.flushAll()}setBitcoinRedeem(e,r,n){this.set("bitcoinRedeem",e,r,n)}getBitcoinRedeem(e){return this.get("bitcoinRedeem",e)}setOrderExecution(e,r,n,s,i){const o=this.makeOrderKey(e,r),a={txHash:n,timeStamp:Date.now(),btcRedeemUTXO:s};this.set("orderExecutor",o,a,i)}getOrderExecution(e,r){const n=this.makeOrderKey(e,r);return this.get("orderExecutor",n)}removeOrderExecution(e,r){const n=this.makeOrderKey(e,r);this.remove("orderExecutor",n)}makeOrderKey(e,r){return`${r}_${e.order_id??e.created_at}`}setSacpCache(e,r,n){this.set("refundSacp",e,r,n)}getSacpCache(e){return this.get("refundSacp",e)}has(e,r){const n=this.makeKey(e,r);return this.cache.has(n)}peek(e,r){return this.get(e,r)}getRemainingTTL(e,r){const n=this.makeKey(e,r),s=this.cache.getTtl(n);if(s===void 0)return-1;const i=Date.now();return Math.max(0,s-i)}}var ca,ua,fa,Xe,Ii,Jn;class X4{constructor(e,r,n,s,i,o){hs(this,ca);hs(this,ua);hs(this,fa);hs(this,Xe);hs(this,Ii);hs(this,Jn);this.isBackgroundServiceRunning=!1,this.stopBackgroundExecution=null,this.htlcs=r,this.events=o,ps(this,ca,e),ps(this,ua,n),ps(this,fa,Mi.fromDigestKey(e.digestKey)),ps(this,Xe,new Y4),ps(this,Ii,s),ps(this,Jn,i)}async getAddressesFromHTLCs(){var n,s,i,o,a;const e=new Set;return[(n=this.htlcs.evm)==null?void 0:n.htlcActorAddress,(s=this.htlcs.sui)==null?void 0:s.htlcActorAddress,(i=this.htlcs.solana)==null?void 0:i.htlcActorAddress,(o=this.htlcs.starknet)==null?void 0:o.htlcActorAddress,(a=this.htlcs.bitcoin)==null?void 0:a.htlcActorAddress].filter(c=>!!c&&c.length>0).forEach(c=>e.add(c.toLowerCase())),Array.from(e)}start(e=5e3,r){this.isBackgroundServiceRunning||this.stopBackgroundExecution||(this.isBackgroundServiceRunning=!0,(async()=>{try{if(r){this.stop();return}const n=await this.execute(e);n&&(this.stopBackgroundExecution=n)}catch(n){console.error("Error starting background executor:",n),this.isBackgroundServiceRunning=!1}})())}stop(){if(this.stopBackgroundExecution){try{this.stopBackgroundExecution()}catch{console.error("Error stopping background executor")}this.stopBackgroundExecution=null}this.isBackgroundServiceRunning=!1}async execute(e=5e3){const r=await this.getAddressesFromHTLCs();r.length===0&&r.push(Be(this,ca).userId.toLowerCase());let n=!1,s=null;const i=async()=>{if(!n){n=!0;try{const o=r.map(async c=>{try{const u=await Be(this,ua).getOrders({from_owner:c,status:Y.OrderLifecycle.pending,per_page:500});return u.ok?u.val.data:(this.events.emit("error",{},`Failed to fetch orders for address ${c}: ${u.error}`),[])}catch(u){return this.events.emit("error",{},`Failed to fetch orders for address ${c}: ${u}`),[]}}),a=await Promise.all(o);this.events.emit("onPendingOrdersChanged",a.flat()),await this.processOrderActions(a.flat())}finally{n=!1}}};return await i(),s=setInterval(i,e),()=>{s&&clearInterval(s)}}async processOrderActions(e){const r=new Set([Y.OrderStatus.InitiateDetected,Y.OrderStatus.AwaitingRefund,Y.OrderStatus.Initiated,Y.OrderStatus.RefundDetected,Y.OrderStatus.Refunded,Y.OrderStatus.Expired]),n=e.map(async s=>{try{Y.isBitcoin(s.source_swap.chain)&&r.has(s.status)&&!Y.isCompleted(s)&&await this.postRefundSACP(s),Y.parseAction(s)===Y.OrderAction.Redeem&&await this.handleRedeemAction(s)}catch(i){this.events.emit("error",s,`Error processing order ${s.order_id}: ${i}`)}});await Promise.all(n)}async handleRedeemAction(e){const r=await Be(this,fa).generateSecret(e.nonce);if(!r.ok){this.events.emit("error",e,r.error);return}const n=g.trim0x(r.val.secretHash),s=g.trim0x(e.source_swap.secret_hash);if(n!==s){this.events.emit("log",e.order_id,"skipping redeem: secret hash mismatch");return}const i=r.val.secret,o=Y.getBlockchainType(e.destination_swap.chain),c={[Y.BlockchainType.evm]:()=>this.evmRedeem(e,i),[Y.BlockchainType.bitcoin]:()=>this.btcRedeem(e,i),[Y.BlockchainType.starknet]:()=>this.starknetRedeem(e,i),[Y.BlockchainType.solana]:()=>this.solRedeem(e,i),[Y.BlockchainType.sui]:()=>this.suiRedeem(e,i)}[o];c?await c():this.events.emit("error",e,`Unsupported chain: ${e.destination_swap.chain}`)}async evmRedeem(e,r){if(this.events.emit("log",e.order_id,"executing evm redeem"),Be(this,Xe).getOrderExecution(e,Y.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.evm){this.events.emit("error",e,"EVM HTLC is required");return}const s=await this.htlcs.evm.redeem(e,r);if(!s.ok){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Be(this,Xe).setOrderExecution(e,Y.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}Be(this,Xe).setOrderExecution(e,Y.OrderAction.Redeem,s.val),this.events.emit("success",e,Y.OrderAction.Redeem,s.val)}async starknetRedeem(e,r){if(this.events.emit("log",e.order_id,"executing starknet redeem"),Be(this,Xe).getOrderExecution(e,Y.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.starknet){this.events.emit("error",e,"Starknet HTLC is required");return}const s=await this.htlcs.starknet.redeem(e,r);if(!s.ok){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Be(this,Xe).setOrderExecution(e,Y.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Be(this,Xe).setOrderExecution(e,Y.OrderAction.Redeem,s.val),this.events.emit("success",e,Y.OrderAction.Redeem,s.val))}async solRedeem(e,r){if(this.events.emit("log",e.order_id,"executing sol redeem"),Be(this,Xe).getOrderExecution(e,Y.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.solana){this.events.emit("error",e,"Solana HTLC is required");return}const s=await this.htlcs.solana.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Be(this,Xe).setOrderExecution(e,Y.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Be(this,Xe).setOrderExecution(e,Y.OrderAction.Redeem,s.val),this.events.emit("success",e,Y.OrderAction.Redeem,s.val))}async suiRedeem(e,r){if(this.events.emit("log",e.order_id,"executing sui redeem"),Be(this,Xe).getOrderExecution(e,Y.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.sui){this.events.emit("error",e,"Sui HTLC is required");return}const s=await this.htlcs.sui.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Be(this,Xe).setOrderExecution(e,Y.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Be(this,Xe).setOrderExecution(e,Y.OrderAction.Redeem,s.val),this.events.emit("success",e,Y.OrderAction.Redeem,s.val))}async btcRedeem(e,r){var a,c;const n=(a=this.htlcs.bitcoin)==null?void 0:a.getProvider();if(!n){this.events.emit("error",e,"Bitcoin provider not found");return}const s=Be(this,Xe).getBitcoinRedeem(e.order_id),i=(c=e.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:c.split(":").at(0);if(!i){this.events.emit("error",e,"Failed to get initiate_tx_hash");return}let o=!1;if(s)if(s.redeemedFromUTXO&&s.redeemedFromUTXO!==i)o=!0,this.events.emit("log",e.order_id,"rbf btc redeem");else if(s.redeemedAt&&Date.now()-s.redeemedAt>1e3*60*15)this.events.emit("log",e.order_id,"redeem not confirmed in last 15 minutes"),o=!0;else{this.events.emit("log",e.order_id,"btcRedeem: already redeemed");return}else if(e.destination_swap.redeem_tx_hash&&!Number(e.destination_swap.redeem_block_number))try{const u=await(await n).getTransaction(e.destination_swap.redeem_tx_hash);let f=!1;for(const l of u.vin)if(l.txid===i){f=!0;break}if(f){this.events.emit("log",e.order_id,"already a valid redeem");let l=0;try{const[p]=await(await n).getTransactionTimes([e.destination_swap.redeem_tx_hash]);p!==0&&(l=p)}catch{l=Date.now()}Be(this,Xe).setBitcoinRedeem(e.order_id,{redeemedFromUTXO:i,redeemedAt:l,redeemTxHash:e.destination_swap.redeem_tx_hash});return}o=!0}catch(u){if(u.message.includes("Transaction not found"))o=!0;else{this.events.emit("error",e,"Failed to get redeem tx: "+u);return}}this.events.emit("log",e.order_id,"executing btc redeem");try{if(!this.htlcs.bitcoin){this.events.emit("error",e,"Bitcoin HTLC is required");return}const u=await this.htlcs.bitcoin.getRedeemHex(e,g.trim0x(r),o?[i]:[]);if(!u.ok){this.events.emit("error",e,"Failed to get redeem hex");return}const f=await this.broadcastRedeemTx(u.val,e.order_id);if(!f.ok){this.events.emit("error",e,f.error||"Failed to broadcast redeem tx");return}o?(this.events.emit("log",e.order_id,"rbf: btc redeem success"),this.events.emit("rbf",e,f.val)):this.events.emit("success",e,Y.OrderAction.Redeem,f.val),Be(this,Xe).setBitcoinRedeem(e.order_id,{redeemedFromUTXO:i,redeemedAt:Date.now(),redeemTxHash:f.val})}catch(u){this.events.emit("error",e,"Failed btc redeem: "+u)}}async postRefundSACP(e){if(e.source_swap.delegate)try{if(!this.htlcs.bitcoin){this.events.emit("error",e,"Bitcoin HTLC is required");return}const n=await Be(this,Ii).getAuthHeaders();if(n.error){this.events.emit("error",e,"Failed to get auth headers: "+n.error);return}const s=await g.Fetcher.post(new g.Url(Be(this,Jn).baseurl).endpoint("relayer/bitcoin/instant-refund-hash"),{body:JSON.stringify({order_id:e.order_id}),headers:{"Content-Type":"application/json",...n.val}});if(s.error||!s.result){this.events.emit("error",e,"Failed to get hash while posting instant refund SACP: "+s.error);return}const i=await this.htlcs.bitcoin.generateInstantRefundSACPWithHash(s.result),o=new g.Url(Be(this,Jn).baseurl).endpoint("relayer/bitcoin/instant-refund");(await g.Fetcher.post(o,{headers:{"Content-Type":"application/json",...n.val},body:JSON.stringify({order_id:e.order_id,signatures:i.val})})).ok&&Be(this,Xe).setSacpCache(e.order_id,{initTxHash:e.source_swap.initiate_tx_hash})}catch(n){this.events.emit("error",e,"Failed to generate and post SACP: "+n);return}}async broadcastRedeemTx(e,r){try{if(!Be(this,Jn))return g.Err("API not found");const n=new g.Url(Be(this,Jn).relayer).endpoint("/bitcoin/redeem "),s=await Be(this,Ii).getAuthHeaders(),o=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...s.val},body:JSON.stringify({redeem_tx_bytes:e,order_id:r})})).json();return o.status==="Ok"&&o.result?g.Ok(o.result):g.Err(o.error)}catch(n){return g.Err("Failed to broadcast redeem tx: "+n)}}}ca=new WeakMap,ua=new WeakMap,fa=new WeakMap,Xe=new WeakMap,Ii=new WeakMap,Jn=new WeakMap;const lo={p2wpkh:"p2wpkh","p2wpkh-p2sh":"p2wpkh-p2sh"},mc={ALL:pe.Transaction.SIGHASH_ALL,NONE:pe.Transaction.SIGHASH_NONE,SINGLE:pe.Transaction.SIGHASH_SINGLE,ALL_ANYONECANPAY:pe.Transaction.SIGHASH_ALL|pe.Transaction.SIGHASH_ANYONECANPAY,NONE_ANYONECANPAY:pe.Transaction.SIGHASH_NONE|pe.Transaction.SIGHASH_ANYONECANPAY,SINGLE_ANYONECANPAY:pe.Transaction.SIGHASH_SINGLE|pe.Transaction.SIGHASH_ANYONECANPAY};class $s{constructor(e,r){this._scriptType=e,this._sigHashType=r}get scriptType(){return this._scriptType}get sigHashType(){return this._sigHashType}toString(){return`${this._scriptType} ${this._sigHashType}`}static async fromString(e){const[r,n]=e.split(" "),s=await lp.mixed().oneOf(["segwitV0","segwitV1","p2shSignature"]).required().validate(r),i=await lp.mixed().oneOf(Object.values(mc)).required().validate(parseInt(n));return new $s(s,i)}}const ws={INVALID_PK:"invalid private key",FEE_EXCEEDS_AMOUNT:(t,e)=>`fee exceeds amount: fee: ${t} > amount: ${e}`,SWAP_NOT_FOUND:"swap config not found, please set the swap config first",SCRIPT_NOT_FUNDED:"script not funded",SWAP_NOT_EXPIRED:t=>`swap not expired. Need ${t} more blocks`,MIN_AMOUNT:t=>`amount is too low. Minimum amount is ${t}`,INSUFFICIENT_FUNDS:(t,e)=>`insufficient funds, need ${e} but got ${t}`,AmtPlusFeeExceedsBalance:(t,e,r)=>`amount + fee exceeds balance. Need ${t+e} but got ${r}`},wo={INVALID_SECRET_HASH:"invalid secret hash",INVALID_PUBKEY_OR_SECRET:"invalid public key or secret",INVALID_PUBKEY:"invalid public key",ORDER_NOT_EXPIRED:"you cannot refund before your transaction expires"},J4=(t,e,r=!1)=>{const n=o=>{try{o=pe.address.fromBech32(o).data.toString("hex")}catch(a){if(dd(a))(a.message.includes("Mixed-case string")||a.message.includes("too short"))&&(o=pe.address.fromBase58Check(o).hash.toString("hex"));else throw new Error(String(a))}return o},s=pe.script.fromASM(`
|
|
89
89
|
OP_IF
|
|
90
90
|
OP_SHA256
|
|
91
91
|
${t.secretHash}
|
|
@@ -103,4 +103,4 @@ ${String(n)}`);Sd(e);for(let s=0;s<e.callbacks.length;s++){const i=n[s];i instan
|
|
|
103
103
|
OP_ENDIF
|
|
104
104
|
OP_EQUALVERIFY
|
|
105
105
|
OP_CHECKSIG
|
|
106
|
-
`.trim().replace(/\s+/g," ")),i=pe.payments[r?"p2sh":"p2wsh"]({redeem:{output:s},network:e});if(!i.address)throw new Error("Could not build address");return{script:s,address:i.address}},_o={P2SH:"p2sh",P2WSH:"p2wsh",P2TR:"p2tr"};var J2=(t=>(t[t.Bitcoin=0]="Bitcoin",t[t.EVM=1]="EVM",t))(J2||{});class Q4{addSignatureSegwitV0(e=mc.ALL){return new $s("segwitV0",e)}addSignatureP2sh(e=mc.ALL){return new $s("p2shSignature",e)}addSignatureSegwitV1(e=mc.ALL){return new $s("segwitV1",e)}chain(){return J2.Bitcoin}async addAllInputs(e,r,n,s){const i=(s==null?void 0:s.utxos)||await n.getUTXOs(r);for(const o of i){const a=await n.getTxIndex(o.txid,r);e.addInput(fd(o.txid),a,s==null?void 0:s.nSequence)}return e}async suggestFee(e,r){const n=await this.getAddress();return(await this.getProvider()).suggestFee(n,e,r)}async toOutputScript(e){return pe.address.toOutputScript(e,await this.getNetwork())}totalValueFromUTXOs(e){return e.reduce((r,n)=>r+n.value,0)}async scriptToAddress(e){const r=pe.payments.p2wsh({redeem:{output:e},network:await this.getNetwork()});if(!r.address)throw new Error("Could not generate p2wsh address");return r.address}async newSwap(e){if(e.secretHash=g.trim0x(e.secretHash),e.secretHash.length!==64)throw new Error(wo.INVALID_SECRET_HASH);const{script:r,address:n}=J4(e,await this.getNetwork());return new eB(this,{...e,redeemScript:r,scriptAddress:n})}getScriptType(e,r){try{if(pe.address.fromBase58Check(e).version===r.scriptHash)return _o.P2SH}catch{const s=pe.address.fromBech32(e);if(s.prefix!==r.bech32)throw new Error("Invalid address");if(s.version===0){if(s.data.length===32)return _o.P2WSH}else if(s.version===1&&s.data.length===32)return _o.P2TR}throw new Error("Unsupported script type")}}class eB{constructor(e,r){if(r.secretHash=g.trim0x(r.secretHash),r.secretHash.length!==64)throw new Error(wo.INVALID_SECRET_HASH);this.wallet=e,this.swap=r}id(){return this.swap.scriptAddress}async init(){return this.wallet.send(this.swap.scriptAddress,+this.swap.amount.toString())}async redeem(e,r){e=g.trim0x(e);const n=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),Buffer.from(e,"hex"),pe.script.number.encode(1),this.swap.redeemScript],s=pe.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!s)throw new Error("Could not generate p2wsh address for redeem script");try{return await this.wallet.spend(this.swap.redeemScript,s,{witness:n,toAddress:r})}catch(i){throw ld(i)?i.message.includes("OP_EQUALVERIFY")?new Error(wo.INVALID_PUBKEY_OR_SECRET):new Error(i.message):new Error(String(i))}}async refund(e){const r=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),pe.script.number.encode(0),this.swap.redeemScript];try{const n=pe.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!n)throw new Error("Could not generate p2wsh address for refund script");return await this.wallet.spend(this.swap.redeemScript,n,{toAddress:e,witness:r,nSequence:this.swap.expiryBlocks})}catch(n){throw ld(n)?n.message.includes("OP_EQUALVERIFY")?new Error(wo.INVALID_PUBKEY):n.message.includes("BIP")?new Error(wo.ORDER_NOT_EXPIRED):new Error(n.message):new Error(String(n))}}}const vl=(t,e,r,n)=>`m/${t}'/${e===Tr.Mainnet?0:1}'/${r}'/0/${n??0}`,Q2={bip44:(t,e,r)=>vl("44",t,r??0,e),bip49:(t,e,r)=>vl("49",t,r??0,e),bip84:(t,e,r)=>vl("84",t,r??0,e)};function El(t){if(t===Tr.Mainnet)return pe.networks.bitcoin;if(t===Tr.Testnet)return pe.networks.testnet;if(t===Tr.Regtest)return pe.networks.regtest;throw new Error("Invalid network")}function tB(t,e,r){if(!lp.validateMnemonic(t))throw new Error("Invalid mnemonic");const n=(r==null?void 0:r.path)??Q2.bip44(e,(r==null?void 0:r.index)??0),s=c6.BIP32Factory(fr).fromSeed(lp.mnemonicToSeedSync(t));return rB(s,n)}const rB=(t,e)=>{const r=t.derivePath(e).privateKey;if(!r)throw new Error("Unable to derive private key from mnemonic");return r.toString("hex")};pe.initEccLib(fr);class Ts extends Q4{constructor({privateKey:e,provider:r,pkPath:n,pkType:s}){const i=rc.ECPairFactory(fr),o=El(r.getNetwork()),a=Buffer.from(e,"hex");if(a.length===0)throw new Error("invalid private key");super(),this.minAmt=1e3,this.path=n||"",this.pkType=s,this.signer=i.fromPrivateKey(a,{network:o}),this.provider=r,this.network=o}static fromMnemonic(e,r,n){const s=Q2.bip84(r.getNetwork(),n==null?void 0:n.index),i=tB(e,r.getNetwork(),{path:s});return new Ts({privateKey:i,provider:r,pkType:lo.p2wpkh,pkPath:s})}static fromPrivateKey(e,r,n){return new Ts({privateKey:e,provider:r,pkType:(n==null?void 0:n.pkType)??lo.p2wpkh,pkPath:(n==null?void 0:n.pkPath)??"unknown"})}static createRandom(e){const r=rc.ECPairFactory(fr),n=El(e.getNetwork()),s=r.makeRandom({network:n});if(!s.privateKey)throw new Error("Failed to create random key");return new Ts({privateKey:s.privateKey.toString("hex"),provider:e,pkType:lo.p2wpkh,pkPath:"unknown"})}static fromWIF(e,r,n){const s=rc.ECPairFactory(fr),i=El(r.getNetwork()),o=s.fromWIF(e,i);if(!o.privateKey)throw new Error("Invalid WIF");return Ts.fromPrivateKey(o.privateKey.toString("hex"),r,n)}walletConfig(){return{network:this.provider.getNetwork(),path:this.path,addressType:this.pkType}}async spend(e,r,{toAddress:n,fee:s,nSequence:i,unlockScript:o,witness:a}){var p;const c=this.getScriptType(r,this.network),u=await this.provider.getBalance(r);if(u===0)throw new Error(ws.SCRIPT_NOT_FUNDED);let f=new pe.Transaction;if(f.version=2,s??(s=await this.provider.suggestFee(r,u,xi.FAST)),s>u)throw new Error(ws.FEE_EXCEEDS_AMOUNT(s,u));const l=await this.provider.getUTXOs(r);f=await this.addAllInputs(f,r,this.provider,{nSequence:i,utxos:l}),f.addOutput(await this.toOutputScript(n??await this.getAddress()),u-s);for(let d=0;d<f.ins.length;d++)if(c===_o.P2SH){if(!o)throw new Error("Unlock script is required for p2sh");const m=[];for(const E of o)if(E instanceof $s){const A=E.sigHashType,P=f.hashForSignature(d,e,A);m.push(pe.script.signature.encode(Buffer.from(await this.sign(P.toString("hex")),"hex"),A))}else m.push(E);const b=(p=pe.payments.p2sh({redeem:{input:pe.script.compile(m),output:e},network:this.network}).redeem)==null?void 0:p.input;f.setInputScript(d,b)}else if(c===_o.P2WSH){if(!a)throw new Error("Witness is required for p2wsh");const m=[];for(const b of a)if(b instanceof $s){const E=b.sigHashType,A=f.hashForWitnessV0(d,e,l[d].value,E);m.push(pe.script.signature.encode(Buffer.from(await this.sign(A.toString("hex")),"hex"),E))}else m.push(b);f.setWitness(d,m)}else throw new Error("Invalid script type "+c);return this.provider.broadcast(f.toHex())}async getAddress(){if(this.pkType===lo["p2wpkh-p2sh"]){const{address:r}=pe.payments.p2sh({redeem:pe.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network});if(!r)throw new Error("failed to get the p2wpkh-p2sh address");return r}const{address:e}=pe.payments[this.pkType]({pubkey:this.signer.publicKey,network:this.network});if(!e)throw new Error("failed to get the p2wpkh address");return e}getProvider(){return Promise.resolve(this.provider)}async getBalance(){return this.provider.getBalance(await this.getAddress())}getPublicKey(){return this.signer.publicKey.toString("hex")}getNetwork(){return Promise.resolve(this.network)}static async generateUnsignedPSBT(e,r,n,s,i,o){if(o||(o=await e.suggestFee(n,i,xi.FAST)),o>i)throw new Error(ws.FEE_EXCEEDS_AMOUNT(o,i));const a=await e.getUTXOs(n,i+o),c=a.reduce((l,p)=>l+p.value,0);if(c<i+o)throw new Error(ws.INSUFFICIENT_FUNDS(c,i+o));const u=new pe.Psbt({network:r});for(const l of a){const p=await e.getTransactionHex(l.txid);u.addInput({hash:fd(l.txid),index:l.vout,nonWitnessUtxo:Buffer.from(p,"hex")})}const f=c-i-o;return u.addOutput({address:s,value:i}),f>546&&u.addOutput({address:n,value:f}),{txHex:u.toHex(),utxoCount:a.length}}async _send(e,r,n){var u;if(n||(n=await this.provider.suggestFee(await this.getAddress(),r,xi.FAST)),n>r)throw new Error(ws.FEE_EXCEEDS_AMOUNT(n,r));if(r<this.minAmt)throw new Error(ws.MIN_AMOUNT(this.minAmt));const s=await this.getAddress(),i=await this.provider.getUTXOs(s,r+n),o=i.reduce((f,l)=>f+l.value,0),a=new pe.Psbt({network:this.network});for(const f of i){const l=await this.provider.getTransactionHex(f.txid),p=await this.provider.getTransaction(f.txid);let d;this.pkType===lo["p2wpkh-p2sh"]&&(d={witnessUtxo:{script:Buffer.from(p.vout[f.vout].scriptpubkey,"hex"),value:f.value},redeemScript:(u=pe.payments.p2sh({redeem:pe.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network}).redeem)==null?void 0:u.output}),a.addInput({hash:fd(f.txid),index:f.vout,nonWitnessUtxo:Buffer.from(l,"hex"),...d})}const c=o-r-n;return a.addOutput({address:e,value:r}),c>0&&a.addOutput({address:s,value:c}),a.signAllInputs(this.signer).finalizeAllInputs(),a.extractTransaction().toHex()}async send(e,r,n){const s=await this._send(e,r,n);return this.provider.broadcast(s)}async sign(e){return e=e.startsWith("0x")?e.slice(2):e,this.signer.sign(Buffer.from(e,"hex")).toString("hex")}async signSchnorr(e){return this.signer.signSchnorr(e)}}const nB=t=>t.map(e=>e),sB=t=>{if(t===g.Network.TESTNET)return iB;if(t===g.Network.MAINNET)return oB;throw new Error("Invalid network")},iB=["https://mempool.space/testnet4/api"],oB=["https://mempool.space/api","https://blockstream.info/api"],dm=t=>t.sort((e,r)=>e.status.confirmed!=r.status.confirmed?e.status.confirmed?-1:1:r.value-e.value);class e6{constructor(e,r){this.cacheTimeout=2e3,this.utxosCache=new Map,this.APIs=r?nB([r]):sB(e),this.network=V3(e)}async getTxIndex(e,r){const n=this.APIs.map(i=>`${i}/tx/${e}`),{vout:s}=await g.Fetcher.getWithFallback(n);for(let i=0;i<s.length;i++)if(s[i].scriptpubkey_address===r)return i;throw new Error("failed to get tx index")}async broadcast(e){if(!/^[0-9a-fA-F]+$/.test(e))throw new Error("invalid tx hex");for(let r=0;r<5;r++)try{return g.Fetcher.postWithFallback(this.APIs.map(n=>`${n}/tx`),{body:e})}catch(n){if(r===4)throw n;await new Promise(s=>setTimeout(s,500))}throw new Error("failed to broadcast tx")}async getBalance(e){return(await this.getUTXOs(e)).reduce((r,n)=>r+n.value,0)}setTimeoutForCache(e){this.cacheTimeout=e}async getUTXOs(e,r){const n=this.utxosCache.get(e);if(n&&Date.now()-n.timestamp<this.cacheTimeout)return hm(n.utxos,r);const s=await g.Fetcher.getWithFallback(this.APIs.map(i=>`${i}/address/${e}/utxo`),{signal:AbortSignal.timeout(5e3)});return this.utxosCache.set(e,{timestamp:Date.now(),utxos:s}),hm(s,r)}async getTransactionHex(e){return g.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${e}/hex`))}async getTransaction(e){return g.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${e}`))}async getConfirmations(e){const r=await this.getTransaction(e);return!r.status.confirmed||!r.status.block_height?0:await this.getLatestTip()-r.status.block_height+1}async getFeeRates(){if(this.network===Tr.Regtest)return{fastestFee:8,halfHourFee:7,hourFee:6,economyFee:4,minimumFee:2};let e="";this.network===Tr.Testnet&&(e="testnet4/");const r=`https://mempool.space/${e}api/v1/fees/recommended`,n=`https://blockstream.info/${e}api/fee-estimates`,s=await g.Fetcher.getWithFallback([r,n],{signal:AbortSignal.timeout(5e3)});return"fastestFee"in s?s.fastestFee===1?{fastestFee:2,halfHourFee:2,hourFee:2,economyFee:2,minimumFee:2}:s:{fastestFee:s[1],halfHourFee:s[5],hourFee:s[10],economyFee:s[20],minimumFee:s[25]}}async getTransactions(e,r){const n=await g.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/address/${e}/txs`));if(r===oc.ALL)return n;if(r===oc.IN)return n.filter(s=>s.vout.find(i=>i.scriptpubkey_address===e));if(r===oc.OUT)return n.filter(s=>s.vin.find(i=>i.prevout.scriptpubkey_address===e));throw new Error("failed to get transactions: invalid bitcoin tx type")}getNetwork(){return this.network}async getLatestTip(){return g.Fetcher.getWithFallback(this.APIs.map(e=>`${e}/blocks/tip/height`))}async suggestFee(e,r,n){const i=(await this.getUTXOs(e,r)).length,o=2,a=await this.getFeeRates();return Math.floor(a[M3[n]]*1.05)*(i*70+o*31+10)}async getTransactionTimes(e){const r=e.map(s=>`txId[]=${s}`).join("&");return(await g.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/v1/transaction-times?${r}`))).map(s=>s*1e3)}}const hm=(t,e)=>{if(Array.isArray(t)){if(e){const r=t.reduce((i,o)=>i+o.value,0);if(r<e)throw new Error(ws.INSUFFICIENT_FUNDS(r,e));let n=BigInt(0);t.sort((i,o)=>o.value-i.value);const s=[];for(const i of t)if(n+=BigInt(i.value),s.push(i),n>=e)break;return dm(s)}return dm(t)}return[]};class aB extends g.EventBroker{emit(e,...r){super.emit(e,...r)}}class ip extends X.Orderbook{constructor(e){const{api:r,network:n}=ud(e.environment);super(new g.Url(r.baseurl)),this._redeemServiceEnabled=!0,this.executeInterval=5e3,this.network=n,this._api=r,this._digestKey=Z4(e.digestKey),this._auth=lm(e.apiKey),this._quote=e.quote??new iw(this._api.baseurl),this._htlcs=e.htlc??{},this._events=new aB,this._executor=this._digestKey?new X4(this._digestKey,this.htlcs,this,this._auth,this._api,this._events):void 0}setRedeemServiceEnabled(e){var r,n;if(this._redeemServiceEnabled=e,e)(r=this._executor)==null||r.stop();else{if(!this._digestKey)throw new Error("Digest key is required for manual secret management");if(this._secretManager=Mi.fromDigestKey(this._digestKey.digestKey),!this._htlcs.bitcoin){const s=new e6(this.network);this._htlcs.bitcoin=new D0(Ts.fromPrivateKey(this._digestKey.digestKey,s),this.network)}(n=this._executor)==null||n.start(this.executeInterval,this._redeemServiceEnabled)}return this}static fromWallets(e){const r=lm(e.apiKey),{api:n,network:s}=ud(e.environment);if(!n)throw new Error("API not found, invalid environment "+e.environment);const i=e.wallets?{evm:e.wallets.evm?new dw(n.baseurl,e.wallets.evm,r):void 0,starknet:e.wallets.starknet?new bw(n.baseurl,e.wallets.starknet,s,r):void 0,solana:e.wallets.solana?new Cw(e.wallets.solana,new g.Url(n.baseurl),s,r,{programAddress:e.solanaProgramAddress}):void 0,sui:e.wallets.sui?new K4(n.baseurl,e.wallets.sui,s):void 0,bitcoin:e.wallets.bitcoin?new D0(e.wallets.bitcoin,s):void 0}:{};return new ip({htlc:i,...e})}get htlcs(){return{evm:this._htlcs.evm,starknet:this._htlcs.starknet,solana:this._htlcs.solana,sui:this._htlcs.sui,bitcoin:this._htlcs.bitcoin}}get quote(){return this._quote}get secretManager(){if(this._redeemServiceEnabled||!this._secretManager)throw new Error("Secret manager is not available");return this._secretManager}get auth(){return this._auth}get digestKey(){return this._digestKey}get executor(){return this._executor}get redeemServiceEnabled(){return this._redeemServiceEnabled}async createSwap(e){const r=X.ChainAsset.from(e.fromAsset).blockchainType,n=await K3(r,this._htlcs);if(!n.ok)return g.Err(n.error);const s=await this.createOrder(e);if(!s.ok)return g.Err(s.error);const i=s.val;switch(r){case X.BlockchainType.evm:if(!this._htlcs.evm||!X.isEvmOrderResponse(i))return g.Err("Order type does not match EVM blockchain type");{const o=await this._htlcs.evm.initiate(i);if(!o.ok)return g.Err(`EVM HTLC initiation failed: ${o.error}`)}break;case X.BlockchainType.solana:if(!this._htlcs.solana||!X.isSolanaOrderResponse(i))return g.Err("Order type does not match Solana blockchain type");{const o=await this._htlcs.solana.initiate(i);if(!o.ok)return g.Err(`Solana HTLC initiation failed: ${o.error}`)}break;case X.BlockchainType.starknet:if(!this._htlcs.starknet||!X.isStarknetOrderResponse(i))return g.Err("Order type does not match Starknet blockchain type");{const o=await this._htlcs.starknet.initiate(i);if(!o.ok)return g.Err(`Starknet HTLC initiation failed: ${o.error}`)}break;case X.BlockchainType.sui:if(!this._htlcs.sui||!X.isSuiOrderResponse(i))return g.Err("Order type does not match Sui blockchain type");{const o=await this._htlcs.sui.initiate(i);if(!o.ok)return g.Err(`Sui HTLC initiation failed: ${o.error}`)}break;default:return g.Err("Unsupported blockchain type for swap initiation")}return g.Ok(i.order_id)}async createOrder(e){var A;if(g.hasKeys(e,["source","destination","nonce"]))return super.createOrder(e,this._auth);const r=e,n=await this.validateAndFillParams(r);if(!n.ok)return g.Err(n.error);const{sendAddress:s,receiveAddress:i,fromAsset:o,toAsset:a}=n.val,c=Date.now().toString();let u;if(!this.redeemServiceEnabled){const P=await this.secretManager.generateSecret(c);if(!P.ok)return g.Err(P.error);u=P.val.secretHash}const f=(A=r.addresses)==null?void 0:A.bitcoin,l=X.isBitcoin(X.ChainAsset.from(r.fromAsset).chain),p=X.isBitcoin(X.ChainAsset.from(r.toAsset).chain),d=!l&&!p||!!u,m={source:{asset:o.toString(),owner:l?f??s:s,delegate:d&&l?s:null,amount:r.sendAmount},destination:{asset:a.toString(),owner:p?f??i:i,delegate:d&&p?i:null,amount:r.receiveAmount},nonce:Number(c),...!this.redeemServiceEnabled&&u?{secret_hash:g.trim0x(u)}:{},affiliate_fees:W3(r.affiliateFee),slippage:50},b=await super.createOrder(m,this._auth);if(!b.ok)return g.Err(b.error);const E=X.ChainAsset.from(r.fromAsset).blockchainType;return b.val.type!==E?g.Err("Order response type does not match source blockchain type"):g.Ok(b.val)}async validateAndFillParams(e){var c;if(!e.fromAsset||!e.toAsset)return g.Err("Source and destination assets are required for swap");const r=X.ChainAsset.from(e.fromAsset),n=X.ChainAsset.from(e.toAsset);if(r.network!==n.network)return g.Err("Both assets should be on the same network (either mainnet or testnet)");const s=p0(e.sendAmount);if(!s.ok)return g.Err(s.error);const i=p0(e.receiveAmount);if(!i.ok)return g.Err(i.error);if(s<i)return g.Err("Send amount should be greater than receive amount");if((X.isBitcoin(X.ChainAsset.from(e.fromAsset).chain)||X.isBitcoin(X.ChainAsset.from(e.toAsset).chain))&&!((c=e.addresses)!=null&&c.bitcoin))return g.Err("Bitcoin address in addresses is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const o=await y0(r.blockchainType,this._htlcs,e.addresses);if(!o.ok)return g.Err(o.error);const a=await y0(n.blockchainType,this._htlcs,e.addresses);return a.ok?g.Ok({sendAddress:o.val,receiveAddress:a.val,fromAsset:r,toAsset:n}):g.Err(a.error)}on(e,r){return this._events.on(e,r),this}off(e,r){return this._events.off(e,r),this}}class cB{constructor(e,r,n){this.callData=new Je.CallData(hw),this.account=e,this.starknetProvider=new Je.RpcProvider({nodeUrl:r||(n?Qo[n].nodeUrl:Qo.mainnet.nodeUrl)})}get htlcActorAddress(){return this.account.address}async getHTLCContract(e,r=!1){const n=r?e.destination_swap.asset:e.source_swap.asset;return new Je.Contract(mw,n,this.account)}async initiate(e){try{const n=await(await this.getHTLCContract(e)).token();if(!n)throw new Error("Token address retrieval failed");const s=Je.num.toHex(n),i=Je.cairo.uint256(BigInt(e.source_swap.amount));try{const c=await pw(this.account,s,e.source_swap.asset,BigInt(e.source_swap.amount),this.starknetProvider);if(c.error)return g.Err(c.error)}catch(c){return g.Err(`Allowance check failed: ${c}`)}const o=e.source_swap.secret_hash;if(!o)return g.Err("Invalid order: secret_hash is undefined");const a=await this.account.execute({contractAddress:e.source_swap.asset,entrypoint:"initiate",calldata:[e.source_swap.redeemer,BigInt(e.source_swap.timelock),i.low,i.high,...g.hexToU32Array(o)]});if(!a.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return g.Ok(a.transaction_hash)}catch(r){return g.Err(`HTLC Initiation Error: ${r}`)}}async redeem(e,r){try{const n=await this.getHTLCContract(e,!0),s=e.source_swap.chain.includes("starknet")?e.source_swap.swap_id:e.destination_swap.swap_id,i=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:Je.CallData.compile({swap_id:s,secret:g.hexToU32Array(r)})});return i.transaction_hash?g.Ok(i.transaction_hash):g.Err("Failed to redeem HTLC transaction")}catch{return g.Err("HTLC Redeem Error")}}async refund(e){try{const r=e.source_swap.chain.includes("starknet")?e.source_swap.swap_id:e.destination_swap.swap_id,n=await this.getHTLCContract(e),s=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return s.transaction_hash?g.Ok(s.transaction_hash):g.Err("Failed to refund HTLC transaction")}catch{return g.Err("HTLC Refund Error")}}}class uB{constructor(e){if(this.provider=e,!e)throw new Error("Provider is required");this.provider=e,this.program=new Vt.Program(md,e)}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async initiate(e){if(!e)return g.Err("Order is required");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=es.from(e),o=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Vt.web3.PublicKey.findProgramAddressSync(o,this.program.programId)[0];const a=await this.program.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction(),c=await this.provider.sendAndConfirm(a);return c?g.Ok(c):g.Err("Failed to initiate HTLC transaction")}catch(r){return g.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(e,r){if(!e)return g.Err("Order is required");if(!r)return g.Err("Secret is required");const{secretHash:n}=es.from(e),s=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Vt.web3.PublicKey.findProgramAddressSync(s,this.program.programId)[0];try{const{redeemer:i}=es.from(e);if(!this.swapAccount)return g.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const o=await this.program.methods.redeem(Bw(r)).accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey,redeemer:i}).transaction(),a=await this.provider.sendAndConfirm(o);return a?g.Ok(a):g.Err("Failed to redeem HTLC transaction")}catch(i){return g.Err(`Error redeeming swap: ${i instanceof Error?i.message:String(i)}`)}}async refund(e){if(!e)return g.Err("Order is required");const{secretHash:r}=es.from(e),n=[Buffer.from("swap_account"),Buffer.from(r)];this.swapAccount=Vt.web3.PublicKey.findProgramAddressSync(n,this.program.programId)[0];try{if(console.log("Initiating refund for ::",e.source_swap.swap_id),!this.swapAccount)return g.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const s=await this.program.methods.refund().accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey}).transaction(),i=await this.provider.sendAndConfirm(s);return i?g.Ok(i):g.Err("Failed to refund HTLC transaction")}catch(s){return g.Err(`Error refunding swap: ${s instanceof Error?s.message:String(s)}`)}}}class fB{constructor(e,r){this.apiBaseUrl=e,this.apiKey=r,this.policy=null}async loadPolicy(){try{const r=await(await fetch(`${this.apiBaseUrl}/policy`,{headers:{"garden-app-id":this.apiKey,accept:"application/json"}})).json();if(r.status==="Ok")this.policy=r.result;else throw new Error(`API Error: ${r.error}`)}catch(e){throw new Error(`Failed to load policy: ${e}`)}}isValidRoute(e,r){if(!this.policy)throw new Error("Policy not loaded. Call loadPolicy() first.");return e===r?!1:this.isInIsolationGroup(e,r)?this.isValidIsolationGroup(e,r):this.isWhitelistOverride(e,r)?!0:this.isBlacklisted(e,r)?!1:this.policy.default==="open"}getValidDestinations(e,r){return r.filter(n=>this.isValidRoute(e,n))}getAllValidRoutes(e){const r=[];for(const n of e)for(const s of e)this.isValidRoute(n,s)&&r.push({from:n,to:s});return r}isInIsolationGroup(e,r){return this.policy.isolation_groups.some(n=>{const s=this.parseIsolationGroup(n);return s.includes(e)||s.includes(r)})}isValidIsolationGroup(e,r){return this.policy.isolation_groups.some(n=>{const s=this.parseIsolationGroup(n);return s.includes(e)&&s.includes(r)})}isWhitelistOverride(e,r){return this.policy.whitelist_overrides.some(n=>this.matchesPattern(e,r,n))}isBlacklisted(e,r){return this.policy.blacklist_pairs.some(n=>this.matchesPattern(e,r,n))}parseIsolationGroup(e){return e.split("<->").map(n=>X.ChainAsset.from(n))}matchesPattern(e,r,n){const[s,i]=n.split("->").map(o=>o.trim());return this.matchesAssetPattern(e,s)&&this.matchesAssetPattern(r,i)}matchesAssetPattern(e,r){if(r==="*")return!0;if(r.includes("*")){if(r.endsWith(":*")){const n=r.slice(0,-2);return e.toString().startsWith(n+":")}if(r.startsWith("*:")){const n=r.slice(2);return e.toString().endsWith(":"+n)}}return e.toString()===r}}function lB(t,e){const r={};for(const n of t)r[n.toString()]=e.getValidDestinations(n,t);return r}exports.API=ic;exports.BaseError=L;exports.BitcoinNetwork=Tr;exports.BitcoinProvider=e6;exports.BitcoinWallet=Ts;exports.DEFAULT_AFFILIATE_ASSET=_1;exports.EvmRelay=dw;exports.Garden=ip;exports.HttpRequestError=vi;exports.Quote=iw;exports.RouteValidator=fB;exports.STARKNET_CONFIG=Qo;exports.SUI_CONFIG=cd;exports.SecretManager=Mi;exports.SolanaHTLC=uB;exports.SolanaRelay=Cw;exports.SolanaRelayerAddress=T1;exports.StarknetHTLC=cB;exports.StarknetRelay=bw;exports.botanixMainnet=cw;exports.buildRouteMatrix=lB;exports.call=Ea;exports.checkAllowance=So;exports.checkAllowanceAndApprove=pw;exports.concat=Kt;exports.constructOrderPair=P1;exports.decodeErrorResult=ob;exports.encodeAbiParameters=fs;exports.evmToViemChainMap=du;exports.getChainNameFromChainId=lw;exports.getUrl=Fc;exports.hyperliquid=fw;exports.hyperliquidTestnet=uw;exports.isAddressEqual=Gi;exports.isAllowanceSufficient=yw;exports.isHex=Pr;exports.localBatchGatewayRequest=yg;exports.localBatchGatewayUrl=Aa;exports.resolveApiConfig=ud;exports.solanaProgramAddress=ad;exports.stringify=Qe;exports.switchOrAddNetwork=yd;exports.toXOnly=je;exports.validateBTCAddress=z3;
|
|
106
|
+
`.trim().replace(/\s+/g," ")),i=pe.payments[r?"p2sh":"p2wsh"]({redeem:{output:s},network:e});if(!i.address)throw new Error("Could not build address");return{script:s,address:i.address}},_o={P2SH:"p2sh",P2WSH:"p2wsh",P2TR:"p2tr"};var J2=(t=>(t[t.Bitcoin=0]="Bitcoin",t[t.EVM=1]="EVM",t))(J2||{});class Q4{addSignatureSegwitV0(e=mc.ALL){return new $s("segwitV0",e)}addSignatureP2sh(e=mc.ALL){return new $s("p2shSignature",e)}addSignatureSegwitV1(e=mc.ALL){return new $s("segwitV1",e)}chain(){return J2.Bitcoin}async addAllInputs(e,r,n,s){const i=(s==null?void 0:s.utxos)||await n.getUTXOs(r);for(const o of i){const a=await n.getTxIndex(o.txid,r);e.addInput(ld(o.txid),a,s==null?void 0:s.nSequence)}return e}async suggestFee(e,r){const n=await this.getAddress();return(await this.getProvider()).suggestFee(n,e,r)}async toOutputScript(e){return pe.address.toOutputScript(e,await this.getNetwork())}totalValueFromUTXOs(e){return e.reduce((r,n)=>r+n.value,0)}async scriptToAddress(e){const r=pe.payments.p2wsh({redeem:{output:e},network:await this.getNetwork()});if(!r.address)throw new Error("Could not generate p2wsh address");return r.address}async newSwap(e){if(e.secretHash=g.trim0x(e.secretHash),e.secretHash.length!==64)throw new Error(wo.INVALID_SECRET_HASH);const{script:r,address:n}=J4(e,await this.getNetwork());return new eB(this,{...e,redeemScript:r,scriptAddress:n})}getScriptType(e,r){try{if(pe.address.fromBase58Check(e).version===r.scriptHash)return _o.P2SH}catch{const s=pe.address.fromBech32(e);if(s.prefix!==r.bech32)throw new Error("Invalid address");if(s.version===0){if(s.data.length===32)return _o.P2WSH}else if(s.version===1&&s.data.length===32)return _o.P2TR}throw new Error("Unsupported script type")}}class eB{constructor(e,r){if(r.secretHash=g.trim0x(r.secretHash),r.secretHash.length!==64)throw new Error(wo.INVALID_SECRET_HASH);this.wallet=e,this.swap=r}id(){return this.swap.scriptAddress}async init(){return this.wallet.send(this.swap.scriptAddress,+this.swap.amount.toString())}async redeem(e,r){e=g.trim0x(e);const n=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),Buffer.from(e,"hex"),pe.script.number.encode(1),this.swap.redeemScript],s=pe.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!s)throw new Error("Could not generate p2wsh address for redeem script");try{return await this.wallet.spend(this.swap.redeemScript,s,{witness:n,toAddress:r})}catch(i){throw dd(i)?i.message.includes("OP_EQUALVERIFY")?new Error(wo.INVALID_PUBKEY_OR_SECRET):new Error(i.message):new Error(String(i))}}async refund(e){const r=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),pe.script.number.encode(0),this.swap.redeemScript];try{const n=pe.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!n)throw new Error("Could not generate p2wsh address for refund script");return await this.wallet.spend(this.swap.redeemScript,n,{toAddress:e,witness:r,nSequence:this.swap.expiryBlocks})}catch(n){throw dd(n)?n.message.includes("OP_EQUALVERIFY")?new Error(wo.INVALID_PUBKEY):n.message.includes("BIP")?new Error(wo.ORDER_NOT_EXPIRED):new Error(n.message):new Error(String(n))}}}const Sl=(t,e,r,n)=>`m/${t}'/${e===Tr.Mainnet?0:1}'/${r}'/0/${n??0}`,Q2={bip44:(t,e,r)=>Sl("44",t,r??0,e),bip49:(t,e,r)=>Sl("49",t,r??0,e),bip84:(t,e,r)=>Sl("84",t,r??0,e)};function Al(t){if(t===Tr.Mainnet)return pe.networks.bitcoin;if(t===Tr.Testnet)return pe.networks.testnet;if(t===Tr.Regtest)return pe.networks.regtest;throw new Error("Invalid network")}function tB(t,e,r){if(!dp.validateMnemonic(t))throw new Error("Invalid mnemonic");const n=(r==null?void 0:r.path)??Q2.bip44(e,(r==null?void 0:r.index)??0),s=c6.BIP32Factory(fr).fromSeed(dp.mnemonicToSeedSync(t));return rB(s,n)}const rB=(t,e)=>{const r=t.derivePath(e).privateKey;if(!r)throw new Error("Unable to derive private key from mnemonic");return r.toString("hex")};pe.initEccLib(fr);class Ts extends Q4{constructor({privateKey:e,provider:r,pkPath:n,pkType:s}){const i=rc.ECPairFactory(fr),o=Al(r.getNetwork()),a=Buffer.from(e,"hex");if(a.length===0)throw new Error("invalid private key");super(),this.minAmt=1e3,this.path=n||"",this.pkType=s,this.signer=i.fromPrivateKey(a,{network:o}),this.provider=r,this.network=o}static fromMnemonic(e,r,n){const s=Q2.bip84(r.getNetwork(),n==null?void 0:n.index),i=tB(e,r.getNetwork(),{path:s});return new Ts({privateKey:i,provider:r,pkType:lo.p2wpkh,pkPath:s})}static fromPrivateKey(e,r,n){return new Ts({privateKey:e,provider:r,pkType:(n==null?void 0:n.pkType)??lo.p2wpkh,pkPath:(n==null?void 0:n.pkPath)??"unknown"})}static createRandom(e){const r=rc.ECPairFactory(fr),n=Al(e.getNetwork()),s=r.makeRandom({network:n});if(!s.privateKey)throw new Error("Failed to create random key");return new Ts({privateKey:s.privateKey.toString("hex"),provider:e,pkType:lo.p2wpkh,pkPath:"unknown"})}static fromWIF(e,r,n){const s=rc.ECPairFactory(fr),i=Al(r.getNetwork()),o=s.fromWIF(e,i);if(!o.privateKey)throw new Error("Invalid WIF");return Ts.fromPrivateKey(o.privateKey.toString("hex"),r,n)}walletConfig(){return{network:this.provider.getNetwork(),path:this.path,addressType:this.pkType}}async spend(e,r,{toAddress:n,fee:s,nSequence:i,unlockScript:o,witness:a}){var p;const c=this.getScriptType(r,this.network),u=await this.provider.getBalance(r);if(u===0)throw new Error(ws.SCRIPT_NOT_FUNDED);let f=new pe.Transaction;if(f.version=2,s??(s=await this.provider.suggestFee(r,u,xi.FAST)),s>u)throw new Error(ws.FEE_EXCEEDS_AMOUNT(s,u));const l=await this.provider.getUTXOs(r);f=await this.addAllInputs(f,r,this.provider,{nSequence:i,utxos:l}),f.addOutput(await this.toOutputScript(n??await this.getAddress()),u-s);for(let d=0;d<f.ins.length;d++)if(c===_o.P2SH){if(!o)throw new Error("Unlock script is required for p2sh");const m=[];for(const E of o)if(E instanceof $s){const A=E.sigHashType,P=f.hashForSignature(d,e,A);m.push(pe.script.signature.encode(Buffer.from(await this.sign(P.toString("hex")),"hex"),A))}else m.push(E);const b=(p=pe.payments.p2sh({redeem:{input:pe.script.compile(m),output:e},network:this.network}).redeem)==null?void 0:p.input;f.setInputScript(d,b)}else if(c===_o.P2WSH){if(!a)throw new Error("Witness is required for p2wsh");const m=[];for(const b of a)if(b instanceof $s){const E=b.sigHashType,A=f.hashForWitnessV0(d,e,l[d].value,E);m.push(pe.script.signature.encode(Buffer.from(await this.sign(A.toString("hex")),"hex"),E))}else m.push(b);f.setWitness(d,m)}else throw new Error("Invalid script type "+c);return this.provider.broadcast(f.toHex())}async getAddress(){if(this.pkType===lo["p2wpkh-p2sh"]){const{address:r}=pe.payments.p2sh({redeem:pe.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network});if(!r)throw new Error("failed to get the p2wpkh-p2sh address");return r}const{address:e}=pe.payments[this.pkType]({pubkey:this.signer.publicKey,network:this.network});if(!e)throw new Error("failed to get the p2wpkh address");return e}getProvider(){return Promise.resolve(this.provider)}async getBalance(){return this.provider.getBalance(await this.getAddress())}getPublicKey(){return this.signer.publicKey.toString("hex")}getNetwork(){return Promise.resolve(this.network)}static async generateUnsignedPSBT(e,r,n,s,i,o){if(o||(o=await e.suggestFee(n,i,xi.FAST)),o>i)throw new Error(ws.FEE_EXCEEDS_AMOUNT(o,i));const a=await e.getUTXOs(n,i+o),c=a.reduce((l,p)=>l+p.value,0);if(c<i+o)throw new Error(ws.INSUFFICIENT_FUNDS(c,i+o));const u=new pe.Psbt({network:r});for(const l of a){const p=await e.getTransactionHex(l.txid);u.addInput({hash:ld(l.txid),index:l.vout,nonWitnessUtxo:Buffer.from(p,"hex")})}const f=c-i-o;return u.addOutput({address:s,value:i}),f>546&&u.addOutput({address:n,value:f}),{txHex:u.toHex(),utxoCount:a.length}}async _send(e,r,n){var u;if(n||(n=await this.provider.suggestFee(await this.getAddress(),r,xi.FAST)),n>r)throw new Error(ws.FEE_EXCEEDS_AMOUNT(n,r));if(r<this.minAmt)throw new Error(ws.MIN_AMOUNT(this.minAmt));const s=await this.getAddress(),i=await this.provider.getUTXOs(s,r+n),o=i.reduce((f,l)=>f+l.value,0),a=new pe.Psbt({network:this.network});for(const f of i){const l=await this.provider.getTransactionHex(f.txid),p=await this.provider.getTransaction(f.txid);let d;this.pkType===lo["p2wpkh-p2sh"]&&(d={witnessUtxo:{script:Buffer.from(p.vout[f.vout].scriptpubkey,"hex"),value:f.value},redeemScript:(u=pe.payments.p2sh({redeem:pe.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network}).redeem)==null?void 0:u.output}),a.addInput({hash:ld(f.txid),index:f.vout,nonWitnessUtxo:Buffer.from(l,"hex"),...d})}const c=o-r-n;return a.addOutput({address:e,value:r}),c>0&&a.addOutput({address:s,value:c}),a.signAllInputs(this.signer).finalizeAllInputs(),a.extractTransaction().toHex()}async send(e,r,n){const s=await this._send(e,r,n);return this.provider.broadcast(s)}async sign(e){return e=e.startsWith("0x")?e.slice(2):e,this.signer.sign(Buffer.from(e,"hex")).toString("hex")}async signSchnorr(e){return this.signer.signSchnorr(e)}}const nB=t=>t.map(e=>e),sB=t=>{if(t===g.Network.TESTNET)return iB;if(t===g.Network.MAINNET)return oB;throw new Error("Invalid network")},iB=["https://mempool.space/testnet4/api"],oB=["https://mempool.space/api","https://blockstream.info/api"],hm=t=>t.sort((e,r)=>e.status.confirmed!=r.status.confirmed?e.status.confirmed?-1:1:r.value-e.value);class e6{constructor(e,r){this.cacheTimeout=2e3,this.utxosCache=new Map,this.APIs=r?nB([r]):sB(e),this.network=V3(e)}async getTxIndex(e,r){const n=this.APIs.map(i=>`${i}/tx/${e}`),{vout:s}=await g.Fetcher.getWithFallback(n);for(let i=0;i<s.length;i++)if(s[i].scriptpubkey_address===r)return i;throw new Error("failed to get tx index")}async broadcast(e){if(!/^[0-9a-fA-F]+$/.test(e))throw new Error("invalid tx hex");for(let r=0;r<5;r++)try{return g.Fetcher.postWithFallback(this.APIs.map(n=>`${n}/tx`),{body:e})}catch(n){if(r===4)throw n;await new Promise(s=>setTimeout(s,500))}throw new Error("failed to broadcast tx")}async getBalance(e){return(await this.getUTXOs(e)).reduce((r,n)=>r+n.value,0)}setTimeoutForCache(e){this.cacheTimeout=e}async getUTXOs(e,r){const n=this.utxosCache.get(e);if(n&&Date.now()-n.timestamp<this.cacheTimeout)return pm(n.utxos,r);const s=await g.Fetcher.getWithFallback(this.APIs.map(i=>`${i}/address/${e}/utxo`),{signal:AbortSignal.timeout(5e3)});return this.utxosCache.set(e,{timestamp:Date.now(),utxos:s}),pm(s,r)}async getTransactionHex(e){return g.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${e}/hex`))}async getTransaction(e){return g.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${e}`))}async getConfirmations(e){const r=await this.getTransaction(e);return!r.status.confirmed||!r.status.block_height?0:await this.getLatestTip()-r.status.block_height+1}async getFeeRates(){if(this.network===Tr.Regtest)return{fastestFee:8,halfHourFee:7,hourFee:6,economyFee:4,minimumFee:2};let e="";this.network===Tr.Testnet&&(e="testnet4/");const r=`https://mempool.space/${e}api/v1/fees/recommended`,n=`https://blockstream.info/${e}api/fee-estimates`,s=await g.Fetcher.getWithFallback([r,n],{signal:AbortSignal.timeout(5e3)});return"fastestFee"in s?s.fastestFee===1?{fastestFee:2,halfHourFee:2,hourFee:2,economyFee:2,minimumFee:2}:s:{fastestFee:s[1],halfHourFee:s[5],hourFee:s[10],economyFee:s[20],minimumFee:s[25]}}async getTransactions(e,r){const n=await g.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/address/${e}/txs`));if(r===oc.ALL)return n;if(r===oc.IN)return n.filter(s=>s.vout.find(i=>i.scriptpubkey_address===e));if(r===oc.OUT)return n.filter(s=>s.vin.find(i=>i.prevout.scriptpubkey_address===e));throw new Error("failed to get transactions: invalid bitcoin tx type")}getNetwork(){return this.network}async getLatestTip(){return g.Fetcher.getWithFallback(this.APIs.map(e=>`${e}/blocks/tip/height`))}async suggestFee(e,r,n){const i=(await this.getUTXOs(e,r)).length,o=2,a=await this.getFeeRates();return Math.floor(a[M3[n]]*1.05)*(i*70+o*31+10)}async getTransactionTimes(e){const r=e.map(s=>`txId[]=${s}`).join("&");return(await g.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/v1/transaction-times?${r}`))).map(s=>s*1e3)}}const pm=(t,e)=>{if(Array.isArray(t)){if(e){const r=t.reduce((i,o)=>i+o.value,0);if(r<e)throw new Error(ws.INSUFFICIENT_FUNDS(r,e));let n=BigInt(0);t.sort((i,o)=>o.value-i.value);const s=[];for(const i of t)if(n+=BigInt(i.value),s.push(i),n>=e)break;return hm(s)}return hm(t)}return[]};class aB extends g.EventBroker{emit(e,...r){super.emit(e,...r)}}class op extends Y.Orderbook{constructor(e){const{api:r,network:n}=fd(e.environment);if(!r)throw new Error("API Key not found");super(new g.Url(r.baseurl)),this._redeemServiceEnabled=!0,this.executeInterval=5e3,this.network=n,this._api=r,this._digestKey=Z4(e.digestKey),this._auth=dm(e.apiKey),this._quote=e.quote??new iw(this._api.baseurl),this._htlcs=e.htlc??{},this._events=new aB,this._executor=this._digestKey?new X4(this._digestKey,this.htlcs,this,this._auth,this._api,this._events):void 0}setRedeemServiceEnabled(e){var r,n;if(this._redeemServiceEnabled=e,e)(r=this._executor)==null||r.stop();else{if(!this._digestKey)throw new Error("Digest key is required for manual secret management");if(this._secretManager=Mi.fromDigestKey(this._digestKey.digestKey),!this._htlcs.bitcoin){const s=new e6(this.network);this._htlcs.bitcoin=new H0(Ts.fromPrivateKey(this._digestKey.digestKey,s),this.network)}(n=this._executor)==null||n.start(this.executeInterval,this._redeemServiceEnabled)}return this}static fromWallets(e){const r=dm(e.apiKey),{api:n,network:s}=fd(e.environment);if(!n)throw new Error("API not found, invalid environment "+e.environment);const i=e.wallets?{evm:e.wallets.evm?new dw(n.baseurl,e.wallets.evm,r):void 0,starknet:e.wallets.starknet?new bw(n.baseurl,e.wallets.starknet,s,r):void 0,solana:e.wallets.solana?new Cw(e.wallets.solana,new g.Url(n.baseurl),s,r,{programAddress:e.solanaProgramAddress}):void 0,sui:e.wallets.sui?new K4(n.baseurl,e.wallets.sui,s):void 0,bitcoin:e.wallets.bitcoin?new H0(e.wallets.bitcoin,s):void 0}:{};return new op({htlc:i,...e})}get htlcs(){return{evm:this._htlcs.evm,starknet:this._htlcs.starknet,solana:this._htlcs.solana,sui:this._htlcs.sui,bitcoin:this._htlcs.bitcoin}}get quote(){return this._quote}get secretManager(){if(this._redeemServiceEnabled||!this._secretManager)throw new Error("Secret manager is not available");return this._secretManager}get auth(){return this._auth}get digestKey(){return this._digestKey}get executor(){return this._executor}get redeemServiceEnabled(){return this._redeemServiceEnabled}async createSwap(e){const r=Y.ChainAsset.from(e.fromAsset).blockchainType,n=await K3(r,this._htlcs);if(!n.ok)return g.Err(n.error);const s=await this.createOrder(e);if(!s.ok)return g.Err(s.error);const i=s.val;switch(r){case Y.BlockchainType.evm:if(!this._htlcs.evm||!Y.isEvmOrderResponse(i))return g.Err("Order type does not match EVM blockchain type");{const o=await this._htlcs.evm.initiate(i);if(!o.ok)return g.Err(`EVM HTLC initiation failed: ${o.error}`)}break;case Y.BlockchainType.solana:if(!this._htlcs.solana||!Y.isSolanaOrderResponse(i))return g.Err("Order type does not match Solana blockchain type");{const o=await this._htlcs.solana.initiate(i);if(!o.ok)return g.Err(`Solana HTLC initiation failed: ${o.error}`)}break;case Y.BlockchainType.starknet:if(!this._htlcs.starknet||!Y.isStarknetOrderResponse(i))return g.Err("Order type does not match Starknet blockchain type");{const o=await this._htlcs.starknet.initiate(i);if(!o.ok)return g.Err(`Starknet HTLC initiation failed: ${o.error}`)}break;case Y.BlockchainType.sui:if(!this._htlcs.sui||!Y.isSuiOrderResponse(i))return g.Err("Order type does not match Sui blockchain type");{const o=await this._htlcs.sui.initiate(i);if(!o.ok)return g.Err(`Sui HTLC initiation failed: ${o.error}`)}break;case Y.BlockchainType.bitcoin:return g.Ok(i);default:return g.Err("Unsupported blockchain type for swap initiation")}return g.Ok(i.order_id)}async createOrder(e){var A;if(g.hasKeys(e,["source","destination","nonce"]))return super.createOrder(e,this._auth);const r=e,n=await this.validateAndFillParams(r);if(!n.ok)return g.Err(n.error);const{sendAddress:s,receiveAddress:i,fromAsset:o,toAsset:a}=n.val,c=Date.now().toString();let u;if(!this.redeemServiceEnabled){const P=await this.secretManager.generateSecret(c);if(!P.ok)return g.Err(P.error);u=P.val.secretHash}const f=(A=r.addresses)==null?void 0:A.bitcoin,l=Y.isBitcoin(Y.ChainAsset.from(r.fromAsset).chain),p=Y.isBitcoin(Y.ChainAsset.from(r.toAsset).chain),d=!l&&!p||!!u,m={source:{asset:o.toString(),owner:l?f??s:s,delegate:d&&l?s:null,amount:r.sendAmount},destination:{asset:a.toString(),owner:p?f??i:i,delegate:d&&p?i:null,amount:r.receiveAmount},nonce:Number(c),...!this.redeemServiceEnabled&&u?{secret_hash:g.trim0x(u)}:{},affiliate_fees:W3(r.affiliateFee),slippage:50},b=await super.createOrder(m,this._auth);if(!b.ok)return g.Err(b.error);const E=Y.ChainAsset.from(r.fromAsset).blockchainType;return b.val.type!==E?g.Err("Order response type does not match source blockchain type"):g.Ok(b.val)}async validateAndFillParams(e){var c;if(!e.fromAsset||!e.toAsset)return g.Err("Source and destination assets are required for swap");const r=Y.ChainAsset.from(e.fromAsset),n=Y.ChainAsset.from(e.toAsset);if(r.network!==n.network)return g.Err("Both assets should be on the same network (either mainnet or testnet)");const s=m0(e.sendAmount);if(!s.ok)return g.Err(s.error);const i=m0(e.receiveAmount);if(!i.ok)return g.Err(i.error);if(s<i)return g.Err("Send amount should be greater than receive amount");if((Y.isBitcoin(Y.ChainAsset.from(e.fromAsset).chain)||Y.isBitcoin(Y.ChainAsset.from(e.toAsset).chain))&&!((c=e.addresses)!=null&&c.bitcoin))return g.Err("Bitcoin address in addresses is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const o=await this._getAddresses(r.blockchainType,e.addresses);if(!o.ok)return g.Err(o.error);const a=await this._getAddresses(n.blockchainType,e.addresses);return a.ok?g.Ok({sendAddress:o.val,receiveAddress:a.val,fromAsset:r,toAsset:n}):g.Err(a.error)}async _getAddresses(e,r){var n;if(this._redeemServiceEnabled&&r&&r[e])return g.Ok(r[e]);switch(e){case Y.BlockchainType.evm:return this._htlcs.evm?g.Ok(this._htlcs.evm.htlcActorAddress):g.Err("Please provide evmHTLC when initializing garden or pass EVM address in SwapParams");case Y.BlockchainType.bitcoin:{const s=(n=this._htlcs.bitcoin)==null?void 0:n.getPublicKey;return!s||!H3(s)?g.Err("Invalid btc public key or pass Bitcoin address in SwapParams"):g.Ok(je(s))}case Y.BlockchainType.solana:return this._htlcs.solana?g.Ok(this._htlcs.solana.htlcActorAddress):g.Err("Please provide solanaHTLC when initializing garden or pass Solana address in SwapParams");case Y.BlockchainType.starknet:return this._htlcs.starknet?g.Ok(this._htlcs.starknet.htlcActorAddress):g.Err("Please provide starknetHTLC when initializing garden or pass Starknet address in SwapParams");case Y.BlockchainType.sui:return this._htlcs.sui?g.Ok(this._htlcs.sui.htlcActorAddress):g.Err("Please provide suiHTLC when initializing garden or pass Sui address in SwapParams");default:return g.Err("Unsupported chain")}}on(e,r){return this._events.on(e,r),this}off(e,r){return this._events.off(e,r),this}}class cB{constructor(e,r,n){this.callData=new Je.CallData(hw),this.account=e,this.starknetProvider=new Je.RpcProvider({nodeUrl:r||(n?Qo[n].nodeUrl:Qo.mainnet.nodeUrl)})}get htlcActorAddress(){return this.account.address}async getHTLCContract(e,r=!1){const n=r?e.destination_swap.asset:e.source_swap.asset;return new Je.Contract(mw,n,this.account)}async initiate(e){try{const n=await(await this.getHTLCContract(e)).token();if(!n)throw new Error("Token address retrieval failed");const s=Je.num.toHex(n),i=Je.cairo.uint256(BigInt(e.source_swap.amount));try{const c=await pw(this.account,s,e.source_swap.asset,BigInt(e.source_swap.amount),this.starknetProvider);if(c.error)return g.Err(c.error)}catch(c){return g.Err(`Allowance check failed: ${c}`)}const o=e.source_swap.secret_hash;if(!o)return g.Err("Invalid order: secret_hash is undefined");const a=await this.account.execute({contractAddress:e.source_swap.asset,entrypoint:"initiate",calldata:[e.source_swap.redeemer,BigInt(e.source_swap.timelock),i.low,i.high,...g.hexToU32Array(o)]});if(!a.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return g.Ok(a.transaction_hash)}catch(r){return g.Err(`HTLC Initiation Error: ${r}`)}}async redeem(e,r){try{const n=await this.getHTLCContract(e,!0),s=e.source_swap.chain.includes("starknet")?e.source_swap.swap_id:e.destination_swap.swap_id,i=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:Je.CallData.compile({swap_id:s,secret:g.hexToU32Array(r)})});return i.transaction_hash?g.Ok(i.transaction_hash):g.Err("Failed to redeem HTLC transaction")}catch{return g.Err("HTLC Redeem Error")}}async refund(e){try{const r=e.source_swap.chain.includes("starknet")?e.source_swap.swap_id:e.destination_swap.swap_id,n=await this.getHTLCContract(e),s=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return s.transaction_hash?g.Ok(s.transaction_hash):g.Err("Failed to refund HTLC transaction")}catch{return g.Err("HTLC Refund Error")}}}class uB{constructor(e){if(this.provider=e,!e)throw new Error("Provider is required");this.provider=e,this.program=new Vt.Program(bd,e)}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async initiate(e){if(!e)return g.Err("Order is required");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=es.from(e),o=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Vt.web3.PublicKey.findProgramAddressSync(o,this.program.programId)[0];const a=await this.program.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction(),c=await this.provider.sendAndConfirm(a);return c?g.Ok(c):g.Err("Failed to initiate HTLC transaction")}catch(r){return g.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(e,r){if(!e)return g.Err("Order is required");if(!r)return g.Err("Secret is required");const{secretHash:n}=es.from(e),s=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Vt.web3.PublicKey.findProgramAddressSync(s,this.program.programId)[0];try{const{redeemer:i}=es.from(e);if(!this.swapAccount)return g.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const o=await this.program.methods.redeem(Bw(r)).accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey,redeemer:i}).transaction(),a=await this.provider.sendAndConfirm(o);return a?g.Ok(a):g.Err("Failed to redeem HTLC transaction")}catch(i){return g.Err(`Error redeeming swap: ${i instanceof Error?i.message:String(i)}`)}}async refund(e){if(!e)return g.Err("Order is required");const{secretHash:r}=es.from(e),n=[Buffer.from("swap_account"),Buffer.from(r)];this.swapAccount=Vt.web3.PublicKey.findProgramAddressSync(n,this.program.programId)[0];try{if(console.log("Initiating refund for ::",e.source_swap.swap_id),!this.swapAccount)return g.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const s=await this.program.methods.refund().accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey}).transaction(),i=await this.provider.sendAndConfirm(s);return i?g.Ok(i):g.Err("Failed to refund HTLC transaction")}catch(s){return g.Err(`Error refunding swap: ${s instanceof Error?s.message:String(s)}`)}}}class fB{constructor(e,r){this.apiBaseUrl=e,this.apiKey=r,this.policy=null}async loadPolicy(){try{const r=await(await fetch(`${this.apiBaseUrl}/policy`,{headers:{"garden-app-id":this.apiKey,accept:"application/json"}})).json();if(r.status==="Ok")this.policy=r.result;else throw new Error(`API Error: ${r.error}`)}catch(e){throw new Error(`Failed to load policy: ${e}`)}}isValidRoute(e,r){if(!this.policy)throw new Error("Policy not loaded. Call loadPolicy() first.");return e===r?!1:this.isInIsolationGroup(e,r)?this.isValidIsolationGroup(e,r):this.isWhitelistOverride(e,r)?!0:this.isBlacklisted(e,r)?!1:this.policy.default==="open"}getValidDestinations(e,r){return r.filter(n=>this.isValidRoute(e,n))}getAllValidRoutes(e){const r=[];for(const n of e)for(const s of e)this.isValidRoute(n,s)&&r.push({from:n,to:s});return r}isInIsolationGroup(e,r){return this.policy.isolation_groups.some(n=>{const s=this.parseIsolationGroup(n);return s.includes(e)||s.includes(r)})}isValidIsolationGroup(e,r){return this.policy.isolation_groups.some(n=>{const s=this.parseIsolationGroup(n);return s.includes(e)&&s.includes(r)})}isWhitelistOverride(e,r){return this.policy.whitelist_overrides.some(n=>this.matchesPattern(e,r,n))}isBlacklisted(e,r){return this.policy.blacklist_pairs.some(n=>this.matchesPattern(e,r,n))}parseIsolationGroup(e){return e.split("<->").map(n=>Y.ChainAsset.from(n))}matchesPattern(e,r,n){const[s,i]=n.split("->").map(o=>o.trim());return this.matchesAssetPattern(e,s)&&this.matchesAssetPattern(r,i)}matchesAssetPattern(e,r){if(r==="*")return!0;if(r.includes("*")){if(r.endsWith(":*")){const n=r.slice(0,-2);return e.toString().startsWith(n+":")}if(r.startsWith("*:")){const n=r.slice(2);return e.toString().endsWith(":"+n)}}return e.toString()===r}}function lB(t,e){const r={};for(const n of t)r[n.toString()]=e.getValidDestinations(n,t);return r}exports.API=ic;exports.BaseError=L;exports.BitcoinNetwork=Tr;exports.BitcoinProvider=e6;exports.BitcoinWallet=Ts;exports.DEFAULT_AFFILIATE_ASSET=_1;exports.EvmRelay=dw;exports.Garden=op;exports.HttpRequestError=vi;exports.Quote=iw;exports.RouteValidator=fB;exports.STARKNET_CONFIG=Qo;exports.SUI_CONFIG=ud;exports.SecretManager=Mi;exports.SolanaHTLC=uB;exports.SolanaRelay=Cw;exports.SolanaRelayerAddress=T1;exports.StarknetHTLC=cB;exports.StarknetRelay=bw;exports.botanixMainnet=cw;exports.buildRouteMatrix=lB;exports.call=wa;exports.checkAllowance=So;exports.checkAllowanceAndApprove=pw;exports.concat=Kt;exports.constructOrderPair=P1;exports.decodeErrorResult=ab;exports.encodeAbiParameters=fs;exports.evmToViemChainMap=pu;exports.getChainNameFromChainId=lw;exports.getUrl=jc;exports.hyperliquid=fw;exports.hyperliquidTestnet=uw;exports.isAddressEqual=Gi;exports.isAllowanceSufficient=yw;exports.isHex=Pr;exports.localBatchGatewayRequest=lg;exports.localBatchGatewayUrl=Ea;exports.resolveApiConfig=fd;exports.solanaProgramAddress=cd;exports.stringify=Qe;exports.switchOrAddNetwork=md;exports.toXOnly=je;exports.validateBTCAddress=z3;
|