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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/{ccip-Cmo2J8uO.js → ccip-BE4ehdw2.js} +1 -1
  2. package/dist/{ccip-BixEUfCX.cjs → ccip-CWyEeg1d.cjs} +1 -1
  3. package/dist/{index-BsnXI660.js → index-3Y2kQfE0.js} +11944 -11296
  4. package/dist/index-Cnz5kiIK.cjs +106 -0
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.js +30 -38
  7. package/dist/src/index.d.ts +0 -6
  8. package/dist/src/lib/bitcoin/API.d.ts +3 -1
  9. package/dist/src/lib/bitcoin/bitcoinHtlc.d.ts +5 -14
  10. package/dist/src/lib/bitcoin/bitcoinhtlc.types.d.ts +4 -4
  11. package/dist/src/lib/bitcoin/provider/provider.d.ts +2 -1
  12. package/dist/src/lib/bitcoin/wallet/abstractWallet.d.ts +1 -1
  13. package/dist/src/lib/bitcoin/wallet/wallet.d.ts +1 -1
  14. package/dist/src/lib/bitcoin/wallet/wallet.interface.d.ts +1 -1
  15. package/dist/src/lib/evm/htlc/evmHTLC.d.ts +42 -42
  16. package/dist/src/lib/evm/relay/evmRelay.d.ts +1 -1
  17. package/dist/src/lib/garden/cache/GardenCache.d.ts +1 -2
  18. package/dist/src/lib/garden/executor/executor.d.ts +3 -3
  19. package/dist/src/lib/garden/garden.d.ts +4 -7
  20. package/dist/src/lib/garden/garden.types.d.ts +15 -9
  21. package/dist/src/lib/quote/quote.d.ts +2 -2
  22. package/dist/src/lib/quote/quote.types.d.ts +2 -2
  23. package/dist/src/lib/solana/relayer/solanaRelay.d.ts +23 -19
  24. package/dist/src/lib/sui/relay/suiRelay.d.ts +1 -1
  25. package/dist/src/lib/switchOrAddNetwork.d.ts +4 -4
  26. package/dist/src/lib/utils.d.ts +3 -1
  27. package/package.json +4 -4
  28. package/dist/index-Bx--llHe.cjs +0 -106
  29. package/dist/src/lib/blockNumberFetcher/blockNumber.d.ts +0 -15
  30. package/dist/src/lib/evm/relay/evmRelay.types.d.ts +0 -26
  31. package/dist/src/lib/orderStatus/orderStatus.d.ts +0 -25
  32. package/dist/src/lib/orderStatus/status.d.ts +0 -130
@@ -1,106 +0,0 @@
1
- "use strict";var zv=Object.defineProperty;var Wh=t=>{throw TypeError(t)};var Vv=(t,e,r)=>e in t?zv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Kh=(t,e,r)=>Vv(t,typeof e!="symbol"?e+"":e,r),Zh=(t,e,r)=>e.has(t)||Wh("Cannot "+r);var Ie=(t,e,r)=>(Zh(t,e,"read from private field"),r?r.call(t):e.get(t)),ls=(t,e,r)=>e.has(t)?Wh("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),fs=(t,e,r,n)=>(Zh(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r);const oe=require("@gardenfi/orderbook"),b=require("@gardenfi/utils"),pe=require("bitcoinjs-lib"),qv=require("tiny-secp256k1"),Jm=require("varuint-bitcoin"),Gv=require("bignumber.js"),Ja=require("ecpair"),st=require("starknet"),ir=require("@coral-xyz/anchor"),Wv=require("@solana/spl-token"),Xh=require("@mysten/wallet-standard"),Kv=require("node-cache"),Yh=require("bip39"),Zv=require("bip32"),Jh=require("yup");function Tc(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=Tc(pe),cr=Tc(qv),Qh=Tc(Jm),Xv=Tc(Wv),Yv="1.0.8";let dr=class mf extends Error{constructor(e,r={}){var o;const n=r.cause instanceof mf?r.cause.details:(o=r.cause)!=null&&o.message?r.cause.message:r.details,s=r.cause instanceof mf&&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@${Yv}`].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 Pn(t,e){const r=t.exec(e);return r==null?void 0:r.groups}const Qm=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,e0=/^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)?$/,t0=/^\(.+?\).*?$/,ep=/^tuple(?<array>(\[(\d*)\])*)$/;function gf(t){let e=t.type;if(ep.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+=gf(i),s<r-1&&(e+=", ")}const n=Pn(ep,t.type);return e+=`)${(n==null?void 0:n.array)??""}`,gf({...t,type:e})}return"indexed"in t&&t.indexed&&(e=`${e} indexed`),t.name?`${e} ${t.name}`:e}function Xi(t){let e="";const r=t.length;for(let n=0;n<r;n++){const s=t[n];e+=gf(s),n!==r-1&&(e+=", ")}return e}function Jv(t){var e;return t.type==="function"?`function ${t.name}(${Xi(t.inputs)})${t.stateMutability&&t.stateMutability!=="nonpayable"?` ${t.stateMutability}`:""}${(e=t.outputs)!=null&&e.length?` returns (${Xi(t.outputs)})`:""}`:t.type==="event"?`event ${t.name}(${Xi(t.inputs)})`:t.type==="error"?`error ${t.name}(${Xi(t.inputs)})`:t.type==="constructor"?`constructor(${Xi(t.inputs)})${t.stateMutability==="payable"?" payable":""}`:t.type==="fallback"?`fallback() external${t.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const r0=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function Qv(t){return r0.test(t)}function e2(t){return Pn(r0,t)}const n0=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function t2(t){return n0.test(t)}function r2(t){return Pn(n0,t)}const s0=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function n2(t){return s0.test(t)}function s2(t){return Pn(s0,t)}const i0=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function o0(t){return i0.test(t)}function i2(t){return Pn(i0,t)}const a0=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function o2(t){return a0.test(t)}function a2(t){return Pn(a0,t)}const c0=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function c2(t){return c0.test(t)}function u2(t){return Pn(c0,t)}const l2=/^receive\(\) external payable$/;function f2(t){return l2.test(t)}const d2=new Set(["indexed"]),bf=new Set(["calldata","memory","storage"]);let h2=class extends dr{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"})}},p2=class extends dr{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"})}},y2=class extends dr{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}},m2=class extends dr{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"})}},g2=class extends dr{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"})}},b2=class extends dr{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"})}},w2=class extends dr{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"})}},Li=class extends dr{constructor({signature:e,type:r}){super(`Invalid ${r} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}},v2=class extends dr{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}},E2=class extends dr{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"})}},S2=class extends dr{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"})}},A2=class extends dr{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 x2(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 Eu=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 k2(t,e={}){if(n2(t))return _2(t,e);if(t2(t))return T2(t,e);if(Qv(t))return I2(t,e);if(o2(t))return P2(t,e);if(c2(t))return O2(t);if(f2(t))return{type:"receive",stateMutability:"payable"};throw new v2({signature:t})}function _2(t,e={}){const r=s2(t);if(!r)throw new Li({signature:t,type:"function"});const n=Er(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push($s(n[a],{modifiers:bf,structs:e,type:"function"}));const o=[];if(r.returns){const a=Er(r.returns),c=a.length;for(let l=0;l<c;l++)o.push($s(a[l],{modifiers:bf,structs:e,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:s,outputs:o}}function T2(t,e={}){const r=r2(t);if(!r)throw new Li({signature:t,type:"event"});const n=Er(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push($s(n[o],{modifiers:d2,structs:e,type:"event"}));return{name:r.name,type:"event",inputs:s}}function I2(t,e={}){const r=e2(t);if(!r)throw new Li({signature:t,type:"error"});const n=Er(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push($s(n[o],{structs:e,type:"error"}));return{name:r.name,type:"error",inputs:s}}function P2(t,e={}){const r=a2(t);if(!r)throw new Li({signature:t,type:"constructor"});const n=Er(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push($s(n[o],{structs:e,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:s}}function O2(t){const e=u2(t);if(!e)throw new Li({signature:t,type:"fallback"});return{type:"fallback",stateMutability:e.stateMutability??"nonpayable"}}const B2=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,C2=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,$2=/^u?int$/;function $s(t,e){var f,h;const r=x2(t,e==null?void 0:e.type,e==null?void 0:e.structs);if(Eu.has(r))return Eu.get(r);const n=t0.test(t),s=Pn(n?C2:B2,t);if(!s)throw new y2({param:t});if(s.name&&N2(s.name))throw new m2({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,l={};if(n){c="tuple";const d=Er(s.type),m=[],g=d.length;for(let v=0;v<g;v++)m.push($s(d[v],{structs:a}));l={components:m}}else if(s.type in a)c="tuple",l={components:a[s.type]};else if($2.test(s.type))c=`${s.type}256`;else if(c=s.type,(e==null?void 0:e.type)!=="struct"&&!u0(c))throw new p2({type:c});if(s.modifier){if(!((h=(f=e==null?void 0:e.modifiers)==null?void 0:f.has)!=null&&h.call(f,s.modifier)))throw new g2({param:t,type:e==null?void 0:e.type,modifier:s.modifier});if(bf.has(s.modifier)&&!U2(c,!!s.array))throw new b2({param:t,type:e==null?void 0:e.type,modifier:s.modifier})}const u={type:`${c}${s.array??""}`,...i,...o,...l};return Eu.set(r,u),u}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 A2({current:r,depth:n});return e.push(r.trim()),e}function u0(t){return t==="address"||t==="bool"||t==="function"||t==="string"||Qm.test(t)||e0.test(t)}const R2=/^(?: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 N2(t){return t==="address"||t==="bool"||t==="function"||t==="string"||t==="tuple"||Qm.test(t)||e0.test(t)||R2.test(t)}function U2(t,e){return e||t==="bytes"||t==="string"||t==="tuple"}function M2(t){const e={},r=t.length;for(let o=0;o<r;o++){const a=t[o];if(!o0(a))continue;const c=i2(a);if(!c)throw new Li({signature:a,type:"struct"});const l=c.properties.split(";"),u=[],f=l.length;for(let h=0;h<f;h++){const m=l[h].trim();if(!m)continue;const g=$s(m,{type:"struct"});u.push(g)}if(!u.length)throw new E2({signature:a});e[c.name]=u}const n={},s=Object.entries(e),i=s.length;for(let o=0;o<i;o++){const[a,c]=s[o];n[a]=l0(c,e)}return n}const F2=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function l0(t,e,r=new Set){const n=[],s=t.length;for(let i=0;i<s;i++){const o=t[i];if(t0.test(o.type))n.push(o);else{const c=Pn(F2,o.type);if(!(c!=null&&c.type))throw new w2({abiParameter:o});const{array:l,type:u}=c;if(u in e){if(r.has(u))throw new S2({type:u});n.push({...o,type:`tuple${l??""}`,components:l0(e[u]??[],e,new Set([...r,u]))})}else if(u0(u))n.push(o);else throw new h2({type:u})}}return n}function f0(t){const e=M2(t),r=[],n=t.length;for(let s=0;s<n;s++){const i=t[s];o0(i)||r.push(k2(i,e))}return r}function ae(t,e,r){const n=t[e.name];if(typeof n=="function")return n;const s=t[r];return typeof s=="function"?s:i=>e(t,i)}function _r(t,{includeName:e=!1}={}){if(t.type!=="function"&&t.type!=="event"&&t.type!=="error")throw new Y2(t.type);return`${t.name}(${Ic(t.inputs,{includeName:e})})`}function Ic(t,{includeName:e=!1}={}){return t?t.map(r=>j2(r,{includeName:e})).join(e?", ":","):""}function j2(t,{includeName:e}){return t.type.startsWith("tuple")?`(${Ic(t.components,{includeName:e})})${t.type.slice(5)}`:t.type+(e&&t.name?` ${t.name}`:"")}function Tr(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function Le(t){return Tr(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const d0="2.35.1";let Yi={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:r})=>e?`${t??"https://viem.sh"}${e}${r?`#${r}`:""}`:void 0,version:`viem@${d0}`},H=class wf extends Error{constructor(e,r={}){var a;const n=(()=>{var c;return r.cause instanceof wf?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),s=r.cause instanceof wf&&r.cause.docsPath||r.docsPath,i=(a=Yi.getDocsUrl)==null?void 0:a.call(Yi,{...r,docsPath:s}),o=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...Yi.version?[`Version: ${Yi.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=d0}walk(e){return h0(this,e)}};function h0(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?h0(t.cause,e):e?null:t}class L2 extends H{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 tp extends H{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 p0 extends H{constructor({data:e,params:r,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join(`
6
- `),{metaMessages:[`Params: (${Ic(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 aa extends H{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError"})}}class D2 extends H{constructor({expectedLength:e,givenLength:r,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${e}`,`Given length: ${r}`].join(`
7
- `),{name:"AbiEncodingArrayLengthMismatchError"})}}class H2 extends H{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${Le(r)}) does not match expected size (bytes${e}).`,{name:"AbiEncodingBytesSizeMismatchError"})}}class z2 extends H{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${e}`,`Given length (values): ${r}`].join(`
8
- `),{name:"AbiEncodingLengthMismatchError"})}}class V2 extends H{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 rp extends H{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 y0 extends H{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 q2 extends H{constructor({docsPath:e}){super("Cannot extract event signature from empty topics.",{docsPath:e,name:"AbiEventSignatureEmptyTopicsError"})}}class m0 extends H{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 np extends H{constructor(e,{docsPath:r}={}){super([`Event ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it."].join(`
13
- `),{docsPath:r,name:"AbiEventNotFoundError"})}}class Ii extends H{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 g0 extends H{constructor(e,{docsPath:r}){super([`Function "${e}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join(`
15
- `),{docsPath:r,name:"AbiFunctionOutputsNotFoundError"})}}class G2 extends H{constructor(e,{docsPath:r}){super([`Encoded function signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
16
- `),{docsPath:r,name:"AbiFunctionSignatureNotFoundError"})}}class W2 extends H{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 K2=class extends H{constructor({expectedSize:e,givenSize:r}){super(`Expected bytes${e}, got bytes${r}.`,{name:"BytesSizeMismatchError"})}};class To extends H{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: (${Ic(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 Pc extends H{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
- `),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e}}class Z2 extends H{constructor(e,{docsPath:r}){super([`Type "${e}" is not a valid encoding type.`,"Please provide a valid ABI type."].join(`
19
- `),{docsPath:r,name:"InvalidAbiEncodingType"})}}class X2 extends H{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 b0=class extends H{constructor(e){super([`Value "${e}" is not a valid array.`].join(`
21
- `),{name:"InvalidArrayError"})}};class Y2 extends H{constructor(e){super([`"${e}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(`
22
- `),{name:"InvalidDefinitionTypeError"})}}class J2 extends H{constructor(e){super(`Filter type "${e}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}let w0=class extends H{constructor({offset:e,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},v0=class extends H{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 sp extends H{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 Di(t,{dir:e,size:r=32}={}){return typeof t=="string"?es(t,{dir:e,size:r}):Q2(t,{dir:e,size:r})}function es(t,{dir:e,size:r=32}={}){if(r===null)return t;const n=t.replace("0x","");if(n.length>r*2)throw new v0({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function Q2(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new v0({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 E0=class extends H{constructor({max:e,min:r,signed:n,size:s,value:i}){super(`Number "${i}" is not in safe ${s?`${s*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}};class eE extends H{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 tE extends H{constructor(e){super(`Hex value "${e}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}let rE=class extends H{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function ur(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 Or(t,{size:e}){if(Le(t)>e)throw new rE({givenSize:Le(t),maxSize:e})}function at(t,e={}){const{signed:r}=e;e.size&&Or(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 nE(t,e={}){let r=t;if(e.size&&(Or(r,{size:e.size}),r=ur(r)),ur(r)==="0x00")return!1;if(ur(r)==="0x01")return!0;throw new tE(r)}function lr(t,e={}){return Number(at(t,e))}const sE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ot(t,e={}){return typeof t=="number"||typeof t=="bigint"?X(t,e):typeof t=="string"?Pi(t,e):typeof t=="boolean"?S0(t,e):Qe(t,e)}function S0(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(Or(r,{size:e.size}),Di(r,{size:e.size})):r}function Qe(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=sE[t[s]];const n=`0x${r}`;return typeof e.size=="number"?(Or(n,{size:e.size}),Di(n,{dir:"right",size:e.size})):n}function X(t,e={}){const{signed:r,size:n}=e,s=BigInt(t);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<o){const c=typeof t=="bigint"?"n":"";throw new E0({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?Di(a,{size:n}):a}const iE=new TextEncoder;function Pi(t,e={}){const r=iE.encode(t);return Qe(r,e)}const oE=new TextEncoder;function Hi(t,e={}){return typeof t=="number"||typeof t=="bigint"?cE(t,e):typeof t=="boolean"?aE(t,e):Tr(t)?Ir(t,e):Ts(t,e)}function aE(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?(Or(r,{size:e.size}),Di(r,{size:e.size})):r}const en={zero:48,nine:57,A:65,F:70,a:97,f:102};function ip(t){if(t>=en.zero&&t<=en.nine)return t-en.zero;if(t>=en.A&&t<=en.F)return t-(en.A-10);if(t>=en.a&&t<=en.f)return t-(en.a-10)}function Ir(t,e={}){let r=t;e.size&&(Or(r,{size:e.size}),r=Di(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=ip(n.charCodeAt(a++)),l=ip(n.charCodeAt(a++));if(c===void 0||l===void 0)throw new H(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);i[o]=c*16+l}return i}function cE(t,e){const r=X(t,e);return Ir(r)}function Ts(t,e={}){const r=oE.encode(t);return typeof e.size=="number"?(Or(r,{size:e.size}),Di(r,{dir:"right",size:e.size})):r}const Pa=BigInt(2**32-1),op=BigInt(32);function A0(t,e=!1){return e?{h:Number(t&Pa),l:Number(t>>op&Pa)}:{h:Number(t>>op&Pa)|0,l:Number(t&Pa)|0}}function uE(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}=A0(t[i],e);[n[i],s[i]]=[o,a]}return[n,s]}const x0=(t,e,r)=>t>>>r|e<<32-r,k0=(t,e,r)=>t<<32-r|e>>>r,lE=(t,e,r)=>t<<64-r|e>>>r-32,fE=(t,e,r)=>t>>>r-32|e<<64-r,dE=(t,e)=>e,hE=(t,e)=>t,pE=(t,e,r)=>t<<r|e>>>32-r,yE=(t,e,r)=>e<<r|t>>>32-r,mE=(t,e,r)=>e<<r-32|t>>>64-r,gE=(t,e,r)=>t<<r-32|e>>>64-r;function _0(t,e,r,n){const s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const T0=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),I0=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,ni=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Oc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ns(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Zr(t,...e){if(!Oc(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 P0(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ns(t.outputLen),ns(t.blockLen)}function ss(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 kd(t,e){Zr(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 Pr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Su(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Nr(t,e){return t<<32-e|t>>>e}function Oa(t,e){return t<<e|t>>>32-e>>>0}const O0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function B0(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const fn=O0?t=>t:t=>B0(t);function bE(t){for(let e=0;e<t.length;e++)t[e]=B0(t[e]);return t}const Gn=O0?t=>t:bE,C0=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",wE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function gi(t){if(Zr(t),C0)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=wE[t[r]];return e}const tn={_0:48,_9:57,A:65,F:70,a:97,f:102};function ap(t){if(t>=tn._0&&t<=tn._9)return t-tn._0;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 hc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(C0)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=ap(t.charCodeAt(i)),a=ap(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 vE(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function vn(t){return typeof t=="string"&&(t=vE(t)),Zr(t),t}function Wn(...t){let e=0;for(let n=0;n<t.length;n++){const s=t[n];Zr(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 Bc{}function Cc(t){const e=n=>t().update(vn(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function EE(t){const e=(n,s)=>t(s).update(vn(n)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}function $0(t=32){if(ni&&typeof ni.getRandomValues=="function")return ni.getRandomValues(new Uint8Array(t));if(ni&&typeof ni.randomBytes=="function")return Uint8Array.from(ni.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const SE=BigInt(0),Ji=BigInt(1),AE=BigInt(2),xE=BigInt(7),kE=BigInt(256),_E=BigInt(113),R0=[],N0=[],U0=[];for(let t=0,e=Ji,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],R0.push(2*(5*n+r)),N0.push((t+1)*(t+2)/2%64);let s=SE;for(let i=0;i<7;i++)e=(e<<Ji^(e>>xE)*_E)%kE,e&AE&&(s^=Ji<<(Ji<<BigInt(i))-Ji);U0.push(s)}const M0=uE(U0,!0),TE=M0[0],IE=M0[1],cp=(t,e,r)=>r>32?mE(t,e,r):pE(t,e,r),up=(t,e,r)=>r>32?gE(t,e,r):yE(t,e,r);function PE(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,l=r[c],u=r[c+1],f=cp(l,u,1)^r[a],h=up(l,u,1)^r[a+1];for(let d=0;d<50;d+=10)t[o+d]^=f,t[o+d+1]^=h}let s=t[2],i=t[3];for(let o=0;o<24;o++){const a=N0[o],c=cp(s,i,a),l=up(s,i,a),u=R0[o];s=t[u],i=t[u+1],t[u]=c,t[u+1]=l}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]^=TE[n],t[1]^=IE[n]}Pr(r)}class _d extends Bc{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,ns(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(){Gn(this.state32),PE(this.state32,this.rounds),Gn(this.state32),this.posOut=0,this.pos=0}update(e){ss(this),e=vn(e),Zr(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){ss(this,!1),Zr(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 ns(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(kd(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,Pr(this.state)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:s,rounds:i,enableXOF:o}=this;return e||(e=new _d(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 OE=(t,e,r)=>Cc(()=>new _d(e,t,r)),F0=OE(1,136,256/8);function ft(t,e){const r=e||"hex",n=F0(Tr(t,{strict:!1})?Hi(t):t);return r==="bytes"?n:Ot(n)}const BE=t=>ft(Hi(t));function CE(t){return BE(t)}function $E(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 H("Unable to normalize signature.");return s}const RE=t=>{const e=typeof t=="string"?t:Jv(t);return $E(e)};function j0(t){return CE(RE(t))}const $c=j0;let Ct=class extends H{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"})}},Rc=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 Au=new Rc(8192);function ca(t,e){if(Au.has(`${t}.${e}`))return Au.get(`${t}.${e}`);const r=t.substring(2).toLowerCase(),n=ft(Ts(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 Au.set(`${t}.${e}`,i),i}function L0(t,e){if(!ot(t,{strict:!1}))throw new Ct({address:t});return ca(t,e)}const NE=/^0x[a-fA-F0-9]{40}$/,xu=new Rc(8192);function ot(t,e){const{strict:r=!0}=e??{},n=`${t}.${r}`;if(xu.has(n))return xu.get(n);const s=NE.test(t)?t.toLowerCase()===t?!0:r?ca(t)===t:!0:!1;return xu.set(n,s),s}function Kt(t){return typeof t[0]=="string"?Br(t):UE(t)}function UE(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 Br(t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function Rs(t,e,r,{strict:n}={}){return Tr(t,{strict:!1})?pc(t,e,r,{strict:n}):z0(t,e,r,{strict:n})}function D0(t,e){if(typeof e=="number"&&e>0&&e>Le(t)-1)throw new w0({offset:e,position:"start",size:Le(t)})}function H0(t,e,r){if(typeof e=="number"&&typeof r=="number"&&Le(t)!==r-e)throw new w0({offset:r,position:"end",size:Le(t)})}function z0(t,e,r,{strict:n}={}){D0(t,e);const s=t.slice(e,r);return n&&H0(s,e,r),s}function pc(t,e,r,{strict:n}={}){D0(t,e);const s=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return n&&H0(s,e,r),s}const ME=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,V0=/^(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 On(t,e){if(t.length!==e.length)throw new z2({expectedLength:t.length,givenLength:e.length});const r=FE({params:t,values:e}),n=Id(r);return n.length===0?"0x":n}function FE({params:t,values:e}){const r=[];for(let n=0;n<t.length;n++)r.push(Td({param:t[n],value:e[n]}));return r}function Td({param:t,value:e}){const r=Pd(t.type);if(r){const[n,s]=r;return LE(e,{length:n,param:{...t,type:s}})}if(t.type==="tuple")return qE(e,{param:t});if(t.type==="address")return jE(e);if(t.type==="bool")return HE(e);if(t.type.startsWith("uint")||t.type.startsWith("int")){const n=t.type.startsWith("int"),[,,s="256"]=V0.exec(t.type)??[];return zE(e,{signed:n,size:Number(s)})}if(t.type.startsWith("bytes"))return DE(e,{param:t});if(t.type==="string")return VE(e);throw new Z2(t.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function Id(t){let e=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?e+=32:e+=Le(a)}const r=[],n=[];let s=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?(r.push(X(e+s,{size:32})),n.push(a),s+=Le(a)):r.push(a)}return Kt([...r,...n])}function jE(t){if(!ot(t))throw new Ct({address:t});return{dynamic:!1,encoded:es(t.toLowerCase())}}function LE(t,{length:e,param:r}){const n=e===null;if(!Array.isArray(t))throw new b0(t);if(!n&&t.length!==e)throw new D2({expectedLength:e,givenLength:t.length,type:`${r.type}[${e}]`});let s=!1;const i=[];for(let o=0;o<t.length;o++){const a=Td({param:r,value:t[o]});a.dynamic&&(s=!0),i.push(a)}if(n||s){const o=Id(i);if(n){const a=X(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 DE(t,{param:e}){const[,r]=e.type.split("bytes"),n=Le(t);if(!r){let s=t;return n%32!==0&&(s=es(s,{dir:"right",size:Math.ceil((t.length-2)/2/32)*32})),{dynamic:!0,encoded:Kt([es(X(n,{size:32})),s])}}if(n!==Number.parseInt(r))throw new H2({expectedSize:Number.parseInt(r),value:t});return{dynamic:!1,encoded:es(t,{dir:"right"})}}function HE(t){if(typeof t!="boolean")throw new H(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:es(S0(t))}}function zE(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 E0({max:n.toString(),min:s.toString(),signed:e,size:r/8,value:t.toString()})}return{dynamic:!1,encoded:X(t,{size:32,signed:e})}}function VE(t){const e=Pi(t),r=Math.ceil(Le(e)/32),n=[];for(let s=0;s<r;s++)n.push(es(Rs(e,s*32,(s+1)*32),{dir:"right"}));return{dynamic:!0,encoded:Kt([es(X(Le(e),{size:32})),...n])}}function qE(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=Td({param:i,value:t[o]});n.push(a),a.dynamic&&(r=!0)}return{dynamic:r,encoded:r?Id(n):Kt(n.map(({encoded:s})=>s))}}function Pd(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}const ua=t=>Rs(j0(t),0,4);function Ks(t){const{abi:e,args:r=[],name:n}=t,s=Tr(n,{strict:!1}),i=e.filter(a=>s?a.type==="function"?ua(a)===n:a.type==="event"?$c(a)===n:!1:"name"in a&&a.name===n);if(i.length===0)return;if(i.length===1)return i[0];let o;for(const a of i){if(!("inputs"in a))continue;if(!r||r.length===0){if(!a.inputs||a.inputs.length===0)return a;continue}if(!a.inputs||a.inputs.length===0||a.inputs.length!==r.length)continue;if(r.every((l,u)=>{const f="inputs"in a&&a.inputs[u];return f?vf(l,f):!1})){if(o&&"inputs"in o&&o.inputs){const l=q0(a.inputs,o.inputs,r);if(l)throw new W2({abiItem:a,type:l[0]},{abiItem:o,type:l[1]})}o=a}}return o||i[0]}function vf(t,e){const r=typeof t,n=e.type;switch(n){case"address":return ot(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)=>vf(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=>vf(s,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function q0(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 q0(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")?ot(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?ot(r[n],{strict:!1}):!1)return o}}const lp="/docs/contract/encodeEventTopics";function la(t){var c;const{abi:e,eventName:r,args:n}=t;let s=e[0];if(r){const l=Ks({abi:e,name:r});if(!l)throw new np(r,{docsPath:lp});s=l}if(s.type!=="event")throw new np(void 0,{docsPath:lp});const i=_r(s),o=$c(i);let a=[];if(n&&"inputs"in s){const l=(c=s.inputs)==null?void 0:c.filter(f=>"indexed"in f&&f.indexed),u=Array.isArray(n)?n:Object.values(n).length>0?(l==null?void 0:l.map(f=>n[f.name]))??[]:[];u.length>0&&(a=(l==null?void 0:l.map((f,h)=>Array.isArray(u[h])?u[h].map((d,m)=>fp({param:f,value:u[h][m]})):typeof u[h]<"u"&&u[h]!==null?fp({param:f,value:u[h]}):null))??[])}return[o,...a]}function fp({param:t,value:e}){if(t.type==="string"||t.type==="bytes")return ft(Hi(e));if(t.type==="tuple"||t.type.match(/^(.*)\[(\d+)?\]$/))throw new J2(t.type);return On([t],[e])}function Nc(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 Od(t,e){const{address:r,abi:n,args:s,eventName:i,fromBlock:o,strict:a,toBlock:c}=e,l=Nc(t,{method:"eth_newFilter"}),u=i?la({abi:n,args:s,eventName:i}):void 0,f=await t.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof o=="bigint"?X(o):o,toBlock:typeof c=="bigint"?X(c):c,topics:u}]});return{abi:n,args:s,eventName:i,id:f,request:l(f),strict:!!a,type:"event"}}function We(t){return typeof t=="string"?{address:t,type:"json-rpc"}:t}const dp="/docs/contract/encodeFunctionData";function GE(t){const{abi:e,args:r,functionName:n}=t;let s=e[0];if(n){const i=Ks({abi:e,args:r,name:n});if(!i)throw new Ii(n,{docsPath:dp});s=i}if(s.type!=="function")throw new Ii(void 0,{docsPath:dp});return{abi:[s],functionName:ua(_r(s))}}function hr(t){const{args:e}=t,{abi:r,functionName:n}=(()=>{var a;return t.abi.length===1&&((a=t.functionName)!=null&&a.startsWith("0x"))?t:GE(t)})(),s=r[0],i=n,o="inputs"in s&&s.inputs?On(s.inputs,e??[]):void 0;return Br([i,o??"0x"])}const WE={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."},G0={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},KE={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};class hp extends H{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class W0 extends H{constructor({length:e,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${e}\`).`,{name:"PositionOutOfBoundsError"})}}class ZE extends H{constructor({count:e,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${e}\`).`,{name:"RecursiveReadLimitExceededError"})}}const XE={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 ZE({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(t){if(t<0||t>this.bytes.length-1)throw new W0({length:this.bytes.length,position:t})},decrementPosition(t){if(t<0)throw new hp({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 hp({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 Bd(t,{recursiveReadLimit:e=8192}={}){const r=Object.create(XE);return r.bytes=t,r.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=e,r}function YE(t,e={}){typeof e.size<"u"&&Or(t,{size:e.size});const r=Qe(t,e);return at(r,e)}function JE(t,e={}){let r=t;if(typeof e.size<"u"&&(Or(r,{size:e.size}),r=ur(r)),r.length>1||r[0]>1)throw new eE(r);return!!r[0]}function En(t,e={}){typeof e.size<"u"&&Or(t,{size:e.size});const r=Qe(t,e);return lr(r,e)}function QE(t,e={}){let r=t;return typeof e.size<"u"&&(Or(r,{size:e.size}),r=ur(r,{dir:"right"})),new TextDecoder().decode(r)}function fa(t,e){const r=typeof e=="string"?Ir(e):e,n=Bd(r);if(Le(r)===0&&t.length>0)throw new aa;if(Le(e)&&Le(e)<32)throw new p0({data:typeof e=="string"?e:Qe(e),params:t,size:Le(e)});let s=0;const i=[];for(let o=0;o<t.length;++o){const a=t[o];n.setPosition(s);const[c,l]=bi(n,a,{staticPosition:0});s+=l,i.push(c)}return i}function bi(t,e,{staticPosition:r}){const n=Pd(e.type);if(n){const[s,i]=n;return tS(t,{...e,type:i},{length:s,staticPosition:r})}if(e.type==="tuple")return iS(t,e,{staticPosition:r});if(e.type==="address")return eS(t);if(e.type==="bool")return rS(t);if(e.type.startsWith("bytes"))return nS(t,e,{staticPosition:r});if(e.type.startsWith("uint")||e.type.startsWith("int"))return sS(t,e);if(e.type==="string")return oS(t,{staticPosition:r});throw new X2(e.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const pp=32,Ef=32;function eS(t){const e=t.readBytes(32);return[ca(Qe(z0(e,-20))),32]}function tS(t,e,{length:r,staticPosition:n}){if(!r){const o=En(t.readBytes(Ef)),a=n+o,c=a+pp;t.setPosition(a);const l=En(t.readBytes(pp)),u=Po(e);let f=0;const h=[];for(let d=0;d<l;++d){t.setPosition(c+(u?d*32:f));const[m,g]=bi(t,e,{staticPosition:c});f+=g,h.push(m)}return t.setPosition(n+32),[h,32]}if(Po(e)){const o=En(t.readBytes(Ef)),a=n+o,c=[];for(let l=0;l<r;++l){t.setPosition(a+l*32);const[u]=bi(t,e,{staticPosition:a});c.push(u)}return t.setPosition(n+32),[c,32]}let s=0;const i=[];for(let o=0;o<r;++o){const[a,c]=bi(t,e,{staticPosition:n+s});s+=c,i.push(a)}return[i,s]}function rS(t){return[JE(t.readBytes(32),{size:32}),32]}function nS(t,e,{staticPosition:r}){const[n,s]=e.type.split("bytes");if(!s){const o=En(t.readBytes(32));t.setPosition(r+o);const a=En(t.readBytes(32));if(a===0)return t.setPosition(r+32),["0x",32];const c=t.readBytes(a);return t.setPosition(r+32),[Qe(c),32]}return[Qe(t.readBytes(Number.parseInt(s),32)),32]}function sS(t,e){const r=e.type.startsWith("int"),n=Number.parseInt(e.type.split("int")[1]||"256"),s=t.readBytes(32);return[n>48?YE(s,{signed:r}):En(s,{signed:r}),32]}function iS(t,e,{staticPosition:r}){const n=e.components.length===0||e.components.some(({name:o})=>!o),s=n?[]:{};let i=0;if(Po(e)){const o=En(t.readBytes(Ef)),a=r+o;for(let c=0;c<e.components.length;++c){const l=e.components[c];t.setPosition(a+i);const[u,f]=bi(t,l,{staticPosition:a});i+=f,s[n?c:l==null?void 0:l.name]=u}return t.setPosition(r+32),[s,32]}for(let o=0;o<e.components.length;++o){const a=e.components[o],[c,l]=bi(t,a,{staticPosition:r});s[n?o:a==null?void 0:a.name]=c,i+=l}return[s,i]}function oS(t,{staticPosition:e}){const r=En(t.readBytes(32)),n=e+r;t.setPosition(n);const s=En(t.readBytes(32));if(s===0)return t.setPosition(e+32),["",32];const i=t.readBytes(s,32),o=QE(ur(i));return t.setPosition(e+32),[o,32]}function Po(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(Po);const r=Pd(t.type);return!!(r&&Po({...t,type:r[1]}))}function K0(t){const{abi:e,data:r}=t,n=Rs(r,0,4);if(n==="0x")throw new aa;const i=[...e||[],G0,KE].find(o=>o.type==="error"&&n===ua(_r(o)));if(!i)throw new y0(n,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:i,args:"inputs"in i&&i.inputs&&i.inputs.length>0?fa(i.inputs,Rs(r,4)):void 0,errorName:i.name}}const Je=(t,e,r)=>JSON.stringify(t,(n,s)=>typeof s=="bigint"?s.toString():s,r);function Z0({abiItem:t,args:e,includeFunctionName:r=!0,includeName:n=!1}){if("name"in t&&"inputs"in t&&t.inputs)return`${r?t.name:""}(${t.inputs.map((s,i)=>`${n&&s.name?`${s.name}: `:""}${typeof e[i]=="object"?Je(e[i]):e[i]}`).join(", ")})`}const aS={gwei:9,wei:18},cS={ether:-9,wei:9};function X0(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 Cd(t,e="wei"){return X0(t,aS[e])}function Ft(t,e="wei"){return X0(t,cS[e])}class uS extends H{constructor({address:e}){super(`State for account "${e}" is set multiple times.`,{name:"AccountStateConflictError"})}}class lS extends H{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function yp(t){return t.reduce((e,{slot:r,value:n})=>`${e} ${r}: ${n}
23
- `,"")}function fS(t){return t.reduce((e,{address:r,...n})=>{let s=`${e} ${r}:
24
- `;return n.nonce&&(s+=` nonce: ${n.nonce}
25
- `),n.balance&&(s+=` balance: ${n.balance}
26
- `),n.code&&(s+=` code: ${n.code}
27
- `),n.state&&(s+=` state:
28
- `,s+=yp(n.state)),n.stateDiff&&(s+=` stateDiff:
29
- `,s+=yp(n.stateDiff)),s},` State Override:
30
- `).slice(0,-1)}function da(t){const e=Object.entries(t).map(([n,s])=>s===void 0||s===!1?null:[n,s]).filter(Boolean),r=e.reduce((n,[s])=>Math.max(n,s.length),0);return e.map(([n,s])=>` ${`${n}:`.padEnd(r+1)} ${s}`).join(`
31
- `)}class dS extends H{constructor(){super(["Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.","Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others."].join(`
32
- `),{name:"FeeConflictError"})}}class hS extends H{constructor({v:e}){super(`Invalid \`v\` value "${e}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class pS extends H{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",da(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 yS extends H{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 mS extends H{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:l,nonce:u,to:f,value:h}){var m;const d=da({chain:s&&`${s==null?void 0:s.name} (id: ${s==null?void 0:s.id})`,from:r==null?void 0:r.address,to:f,value:typeof h<"u"&&`${Cd(h)} ${((m=s==null?void 0:s.nativeCurrency)==null?void 0:m.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${Ft(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Ft(c)} gwei`,maxPriorityFeePerGas:typeof l<"u"&&`${Ft(l)} gwei`,nonce:u});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 Y0 extends H{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 J0 extends H{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 gS extends H{constructor({hash:e}){super(`Timed out while waiting for transaction with hash "${e}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}const bS=t=>t,Uc=t=>t;class Q0 extends H{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:l,nonce:u,to:f,value:h,stateOverride:d}){var v;const m=r?We(r):void 0;let g=da({from:m==null?void 0:m.address,to:f,value:typeof h<"u"&&`${Cd(h)} ${((v=s==null?void 0:s.nativeCurrency)==null?void 0:v.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${Ft(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Ft(c)} gwei`,maxPriorityFeePerGas:typeof l<"u"&&`${Ft(l)} gwei`,nonce:u});d&&(g+=`
33
- ${fS(d)}`),super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Raw Call Arguments:",g].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class wS extends H{constructor(e,{abi:r,args:n,contractAddress:s,docsPath:i,functionName:o,sender:a}){const c=Ks({abi:r,args:n,name:o}),l=c?Z0({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,u=c?_r(c,{includeName:!0}):void 0,f=da({address:s&&bS(s),function:u,args:l&&l!=="()"&&`${[...Array((o==null?void 0:o.length)??0).keys()].map(()=>" ").join("")}${l}`,sender:a});super(e.shortMessage||`An unknown error occurred while executing the contract function "${o}".`,{cause:e,docsPath:i,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],f&&"Contract Call:",f].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=r,this.args=n,this.cause=e,this.contractAddress=s,this.functionName=o,this.sender=a}}class Sf extends H{constructor({abi:e,data:r,functionName:n,message:s}){let i,o,a,c;if(r&&r!=="0x")try{o=K0({abi:e,data:r});const{abiItem:u,errorName:f,args:h}=o;if(f==="Error")c=h[0];else if(f==="Panic"){const[d]=h;c=WE[d]}else{const d=u?_r(u,{includeName:!0}):void 0,m=u&&h?Z0({abiItem:u,args:h,includeFunctionName:!1,includeName:!1}):void 0;a=[d?`Error: ${d}`:"",m&&m!=="()"?` ${[...Array((f==null?void 0:f.length)??0).keys()].map(()=>" ").join("")}${m}`:""]}}catch(u){i=u}else s&&(c=s);let l;i instanceof y0&&(l=i.signature,a=[`Unable to decode signature "${l}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${l}.`]),super(c&&c!=="execution reverted"||l?[`The contract function "${n}" reverted with the following ${l?"signature":"reason"}:`,c||l].join(`
34
- `):`The contract function "${n}" reverted.`,{cause:i,metaMessages:a,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=o,this.raw=r,this.reason=c,this.signature=l}}class vS extends H{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 ES extends H{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 Mc extends H{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 wi extends H{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: ${Uc(o)}`,e&&`Request body: ${Je(e)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=e,this.headers=s,this.status=i,this.url=o}}class $d extends H{constructor({body:e,error:r,url:n}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[`URL: ${Uc(n)}`,`Request body: ${Je(e)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=r.code,this.data=r.data}}class mp extends H{constructor({body:e,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${Uc(r)}`,`Request body: ${Je(e)}`],name:"TimeoutError"})}}const SS=-1;class Lt extends H{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 $d?e.code:r??SS}}class Yt extends Lt{constructor(e,r){super(e,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}}class Oo extends Lt{constructor(e){super(e,{code:Oo.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(Oo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class Bo extends Lt{constructor(e){super(e,{code:Bo.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(Bo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class Co extends Lt{constructor(e,{method:r}={}){super(e,{code:Co.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}}Object.defineProperty(Co,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class $o extends Lt{constructor(e){super(e,{code:$o.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
35
- `)})}}Object.defineProperty($o,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class Ns extends Lt{constructor(e){super(e,{code:Ns.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(Ns,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class Us extends Lt{constructor(e){super(e,{code:Us.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
36
- `)})}}Object.defineProperty(Us,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class Ro extends Lt{constructor(e){super(e,{code:Ro.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(Ro,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class No extends Lt{constructor(e){super(e,{code:No.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(No,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class Uo extends Lt{constructor(e){super(e,{code:Uo.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(Uo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class bs extends Lt{constructor(e,{method:r}={}){super(e,{code:bs.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}}Object.defineProperty(bs,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class Oi extends Lt{constructor(e){super(e,{code:Oi.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(Oi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class Mo extends Lt{constructor(e){super(e,{code:Mo.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(Mo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class vi extends Yt{constructor(e){super(e,{code:vi.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(vi,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class Fo extends Yt{constructor(e){super(e,{code:Fo.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(Fo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class jo extends Yt{constructor(e,{method:r}={}){super(e,{code:jo.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}}Object.defineProperty(jo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Lo extends Yt{constructor(e){super(e,{code:Lo.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Lo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class Do extends Yt{constructor(e){super(e,{code:Do.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Do,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class Ho extends Yt{constructor(e){super(e,{code:Ho.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(Ho,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class Bi extends Yt{constructor(e){super(e,{code:Bi.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(Bi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class zo extends Yt{constructor(e){super(e,{code:zo.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(zo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class Vo extends Yt{constructor(e){super(e,{code:Vo.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(Vo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class qo extends Yt{constructor(e){super(e,{code:qo.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(qo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class Go extends Yt{constructor(e){super(e,{code:Go.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(Go,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class Wo extends Yt{constructor(e){super(e,{code:Wo.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(Wo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class Ci extends Yt{constructor(e){super(e,{code:Ci.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(Ci,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class AS extends Lt{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const xS=3;function Ms(t,{abi:e,address:r,args:n,docsPath:s,functionName:i,sender:o}){const a=t instanceof Mc?t:t instanceof H?t.walk(m=>"data"in m)||t.walk():{},{code:c,data:l,details:u,message:f,shortMessage:h}=a,d=t instanceof aa?new vS({functionName:i}):[xS,Ns.code].includes(c)&&(l||u||f||h)?new Sf({abi:e,data:typeof l=="object"?l.data:l,functionName:i,message:a instanceof $d?u:h??f}):t;return new wS(d,{abi:e,args:n,contractAddress:r,docsPath:s,functionName:i,sender:o})}function kS(t){const e=ft(`0x${t.substring(4)}`).substring(26);return ca(`0x${e}`)}async function _S({hash:t,signature:e}){const r=Tr(t)?t:Ot(t),{secp256k1:n}=await Promise.resolve().then(()=>d_);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:u,v:f,yParity:h}=e,d=Number(h??f),m=gp(d);return new n.Signature(at(l),at(u)).addRecoveryBit(m)}const o=Tr(e)?e:Ot(e);if(Le(o)!==65)throw new Error("invalid signature length");const a=lr(`0x${o.slice(130)}`),c=gp(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function gp(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 eg({hash:t,signature:e}){return kS(await _S({hash:t,signature:e}))}function is(t,e="hex"){const r=tg(t),n=Bd(new Uint8Array(r.length));return r.encode(n),e==="hex"?Qe(n.bytes):n.bytes}function tg(t){return Array.isArray(t)?TS(t.map(e=>tg(e))):IS(t)}function TS(t){const e=t.reduce((s,i)=>s+i.length,0),r=rg(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 IS(t){const e=typeof t=="string"?Ir(t):t,r=rg(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 rg(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 H("Length is too large.")}function PS(t){const{chainId:e,nonce:r,to:n}=t,s=t.contractAddress??t.address,i=ft(Br(["0x05",is([e?X(e):"0x",s,r?X(r):"0x"])]));return n==="bytes"?Ir(i):i}async function ng(t){const{authorization:e,signature:r}=t;return eg({hash:PS(e),signature:r??e})}class OS extends H{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:l,nonce:u,to:f,value:h}){var m;const d=da({from:r==null?void 0:r.address,to:f,value:typeof h<"u"&&`${Cd(h)} ${((m=s==null?void 0:s.nativeCurrency)==null?void 0:m.symbol)||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${Ft(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Ft(c)} gwei`,maxPriorityFeePerGas:typeof l<"u"&&`${Ft(l)} gwei`,nonce:u});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 pi extends H{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(pi,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(pi,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});class Fs extends H{constructor({cause:e,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Ft(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(Fs,"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 Af extends H{constructor({cause:e,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Ft(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}}Object.defineProperty(Af,"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 xf extends H{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(xf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class kf extends H{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(kf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class _f extends H{constructor({cause:e,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:e,name:"NonceMaxValueError"})}}Object.defineProperty(_f,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class Tf extends H{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(Tf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class If extends H{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(If,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class Pf extends H{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(Pf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class Of extends H{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(Of,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class Ko extends H{constructor({cause:e,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${Ft(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${Ft(n)} gwei`:""}).`].join(`
39
- `),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(Ko,"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 ha extends H{constructor({cause:e}){super(`An error occurred while executing: ${e==null?void 0:e.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}function Fc(t,e){const r=(t.details||"").toLowerCase(),n=t instanceof H?t.walk(s=>(s==null?void 0:s.code)===pi.code):t;return n instanceof H?new pi({cause:t,message:n.details}):pi.nodeMessage.test(r)?new pi({cause:t,message:t.details}):Fs.nodeMessage.test(r)?new Fs({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas}):Af.nodeMessage.test(r)?new Af({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas}):xf.nodeMessage.test(r)?new xf({cause:t,nonce:e==null?void 0:e.nonce}):kf.nodeMessage.test(r)?new kf({cause:t,nonce:e==null?void 0:e.nonce}):_f.nodeMessage.test(r)?new _f({cause:t,nonce:e==null?void 0:e.nonce}):Tf.nodeMessage.test(r)?new Tf({cause:t}):If.nodeMessage.test(r)?new If({cause:t,gas:e==null?void 0:e.gas}):Pf.nodeMessage.test(r)?new Pf({cause:t,gas:e==null?void 0:e.gas}):Of.nodeMessage.test(r)?new Of({cause:t}):Ko.nodeMessage.test(r)?new Ko({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas,maxPriorityFeePerGas:e==null?void 0:e.maxPriorityFeePerGas}):new ha({cause:t})}function BS(t,{docsPath:e,...r}){const n=(()=>{const s=Fc(t,r);return s instanceof ha?t:s})();return new OS(n,{docsPath:e,...r})}function jc(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 Rd(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 CS={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function zi(t){const e={};return typeof t.authorizationList<"u"&&(e.authorizationList=$S(t.authorizationList)),typeof t.accessList<"u"&&(e.accessList=t.accessList),typeof t.blobVersionedHashes<"u"&&(e.blobVersionedHashes=t.blobVersionedHashes),typeof t.blobs<"u"&&(typeof t.blobs[0]!="string"?e.blobs=t.blobs.map(r=>Qe(r)):e.blobs=t.blobs),typeof t.data<"u"&&(e.data=t.data),typeof t.from<"u"&&(e.from=t.from),typeof t.gas<"u"&&(e.gas=X(t.gas)),typeof t.gasPrice<"u"&&(e.gasPrice=X(t.gasPrice)),typeof t.maxFeePerBlobGas<"u"&&(e.maxFeePerBlobGas=X(t.maxFeePerBlobGas)),typeof t.maxFeePerGas<"u"&&(e.maxFeePerGas=X(t.maxFeePerGas)),typeof t.maxPriorityFeePerGas<"u"&&(e.maxPriorityFeePerGas=X(t.maxPriorityFeePerGas)),typeof t.nonce<"u"&&(e.nonce=X(t.nonce)),typeof t.to<"u"&&(e.to=t.to),typeof t.type<"u"&&(e.type=CS[t.type]),typeof t.value<"u"&&(e.value=X(t.value)),e}function $S(t){return t.map(e=>({address:e.address,r:e.r?X(BigInt(e.r)):e.r,s:e.s?X(BigInt(e.s)):e.s,chainId:X(e.chainId),nonce:X(e.nonce),...typeof e.yParity<"u"?{yParity:X(e.yParity)}:{},...typeof e.v<"u"&&typeof e.yParity>"u"?{v:X(e.v)}:{}}))}function bp(t){if(!(!t||t.length===0))return t.reduce((e,{slot:r,value:n})=>{if(r.length!==66)throw new sp({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new sp({size:n.length,targetSize:66,type:"hex"});return e[r]=n,e},{})}function RS(t){const{balance:e,nonce:r,state:n,stateDiff:s,code:i}=t,o={};if(i!==void 0&&(o.code=i),e!==void 0&&(o.balance=X(e)),r!==void 0&&(o.nonce=X(r)),n!==void 0&&(o.state=bp(n)),s!==void 0){if(o.state)throw new lS;o.stateDiff=bp(s)}return o}function Nd(t){if(!t)return;const e={};for(const{address:r,...n}of t){if(!ot(r,{strict:!1}))throw new Ct({address:r});if(e[r])throw new uS({address:r});e[r]=RS(n)}return e}const Lc=2n**256n-1n;function Zs(t){const{account:e,gasPrice:r,maxFeePerGas:n,maxPriorityFeePerGas:s,to:i}=t,o=e?We(e):void 0;if(o&&!ot(o.address))throw new Ct({address:o.address});if(i&&!ot(i))throw new Ct({address:i});if(typeof r<"u"&&(typeof n<"u"||typeof s<"u"))throw new dS;if(n&&n>Lc)throw new Fs({maxFeePerGas:n});if(s&&n&&s>n)throw new Ko({maxFeePerGas:n,maxPriorityFeePerGas:s})}class NS extends H{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class Ud extends H{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class US extends H{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${Ft(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class sg extends H{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 ig={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Dc(t){const e={...t,blockHash:t.blockHash?t.blockHash:null,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,chainId:t.chainId?lr(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?lr(t.nonce):void 0,to:t.to?t.to:null,transactionIndex:t.transactionIndex?Number(t.transactionIndex):null,type:t.type?ig[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=FS(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 MS=Rd("transaction",Dc);function FS(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 Md(t){const e=(t.transactions??[]).map(r=>typeof r=="string"?r:Dc(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 jS=Rd("block",Md);async function Wr(t,{blockHash:e,blockNumber:r,blockTag:n=t.experimental_blockTag??"latest",includeTransactions:s}={}){var l,u,f;const i=s??!1,o=r!==void 0?X(r):void 0;let a=null;if(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 sg({blockHash:e,blockNumber:r});return(((f=(u=(l=t.chain)==null?void 0:l.formatters)==null?void 0:u.block)==null?void 0:f.format)||Md)(a)}async function Fd(t){const e=await t.request({method:"eth_gasPrice"});return BigInt(e)}async function LS(t,e){return og(t,e)}async function og(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 l=r||await ae(t,Wr,"getBlock")({}),u=await a({block:l,client:t,request:s});if(u===null)throw new Error;return u}if(typeof a<"u")return a;const c=await t.request({method:"eth_maxPriorityFeePerGas"});return at(c)}catch{const[a,c]=await Promise.all([r?Promise.resolve(r):ae(t,Wr,"getBlock")({}),ae(t,Fd,"getGasPrice")({})]);if(typeof a.baseFeePerGas!="bigint")throw new Ud;const l=c-a.baseFeePerGas;return l<0n?0n:l}}async function DS(t,e){return Bf(t,e)}async function Bf(t,e){var h,d;const{block:r,chain:n=t.chain,request:s,type:i="eip1559"}=e||{},o=await(async()=>{var m,g;return typeof((m=n==null?void 0:n.fees)==null?void 0:m.baseFeeMultiplier)=="function"?n.fees.baseFeeMultiplier({block:r,client:t,request:s}):((g=n==null?void 0:n.fees)==null?void 0:g.baseFeeMultiplier)??1.2})();if(o<1)throw new NS;const c=10**(((h=o.toString().split(".")[1])==null?void 0:h.length)??0),l=m=>m*BigInt(Math.ceil(o*c))/BigInt(c),u=r||await ae(t,Wr,"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:l,request:s,type:i});if(m!==null)return m}if(i==="eip1559"){if(typeof u.baseFeePerGas!="bigint")throw new Ud;const m=typeof(s==null?void 0:s.maxPriorityFeePerGas)=="bigint"?s.maxPriorityFeePerGas:await og(t,{block:u,chain:n,request:s}),g=l(u.baseFeePerGas);return{maxFeePerGas:(s==null?void 0:s.maxFeePerGas)??g+m,maxPriorityFeePerGas:m}}return{gasPrice:(s==null?void 0:s.gasPrice)??l(await ae(t,Fd,"getGasPrice")({}))}}async function jd(t,{address:e,blockTag:r="latest",blockNumber:n}){const s=await t.request({method:"eth_getTransactionCount",params:[e,typeof n=="bigint"?X(n):r]},{dedupe:!!n});return lr(s)}function Ld(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=>Ir(i)):t.blobs,s=[];for(const i of n)s.push(Uint8Array.from(e.blobToKzgCommitment(i)));return r==="bytes"?s:s.map(i=>Qe(i))}function Dd(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=>Ir(o)):t.blobs,s=typeof t.commitments[0]=="string"?t.commitments.map(o=>Ir(o)):t.commitments,i=[];for(let o=0;o<n.length;o++){const a=n[o],c=s[o];i.push(Uint8Array.from(e.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map(o=>Qe(o))}function HS(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,l=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+l,a,n)}function zS(t,e,r){return t&e^~t&r}function VS(t,e,r){return t&e^t&r^e&r}let ag=class extends Bc{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=Su(this.buffer)}update(e){ss(this),e=vn(e),Zr(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=Su(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){ss(this),kd(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:o}=this;r[o++]=128,Pr(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let f=o;f<s;f++)r[f]=0;HS(n,s-8,BigInt(this.length*8),i),this.process(n,0);const a=Su(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],i)}digest(){const{buffer: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 Rn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Nn=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),qS=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]),Un=new Uint32Array(64);let Hd=class extends ag{constructor(e=32){super(64,e,8,!1),this.A=Rn[0]|0,this.B=Rn[1]|0,this.C=Rn[2]|0,this.D=Rn[3]|0,this.E=Rn[4]|0,this.F=Rn[5]|0,this.G=Rn[6]|0,this.H=Rn[7]|0}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 f=0;f<16;f++,r+=4)Un[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){const h=Un[f-15],d=Un[f-2],m=Nr(h,7)^Nr(h,18)^h>>>3,g=Nr(d,17)^Nr(d,19)^d>>>10;Un[f]=g+Un[f-7]+m+Un[f-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){const h=Nr(a,6)^Nr(a,11)^Nr(a,25),d=u+h+zS(a,c,l)+qS[f]+Un[f]|0,g=(Nr(n,2)^Nr(n,13)^Nr(n,22))+VS(n,s,i)|0;u=l,l=c,c=a,a=o+d|0,o=i,i=s,s=n,n=d+g|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,i,o,a,c,l,u)}roundClean(){Pr(Un)}destroy(){this.set(0,0,0,0,0,0,0,0),Pr(this.buffer)}},cg=class extends Hd{constructor(){super(28),this.A=Nn[0]|0,this.B=Nn[1]|0,this.C=Nn[2]|0,this.D=Nn[3]|0,this.E=Nn[4]|0,this.F=Nn[5]|0,this.G=Nn[6]|0,this.H=Nn[7]|0}};const ug=Cc(()=>new Hd),GS=Cc(()=>new cg),WS=Hd,lg=ug,KS=cg,ZS=GS,XS=Object.freeze(Object.defineProperty({__proto__:null,SHA224:KS,SHA256:WS,sha224:ZS,sha256:lg},Symbol.toStringTag,{value:"Module"}));function lo(t,e){const r=e||"hex",n=lg(Tr(t,{strict:!1})?Hi(t):t);return r==="bytes"?n:Ot(n)}function YS(t){const{commitment:e,version:r=1}=t,n=t.to??(typeof e=="string"?"hex":"bytes"),s=lo(e,"bytes");return s.set([r],0),n==="bytes"?s:Qe(s)}function fg(t){const{commitments:e,version:r}=t,n=t.to??(typeof e[0]=="string"?"hex":"bytes"),s=[];for(const i of e)s.push(YS({commitment:i,to:n,version:r}));return s}const wp=6,dg=32,zd=4096,hg=dg*zd,vp=hg*wp-1-1*zd*wp,pg=1;class JS extends H{constructor({maxSize:e,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class yg extends H{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class QS extends H{constructor({hash:e,size:r}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class eA extends H{constructor({hash:e,version:r}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:[`Expected: ${pg}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function tA(t){const e=t.to??(typeof t.data=="string"?"hex":"bytes"),r=typeof t.data=="string"?Ir(t.data):t.data,n=Le(r);if(!n)throw new yg;if(n>vp)throw new JS({maxSize:vp,size:n});const s=[];let i=!0,o=0;for(;i;){const a=Bd(new Uint8Array(hg));let c=0;for(;c<zd;){const l=r.slice(o,o+(dg-1));if(a.pushByte(0),a.pushBytes(l),l.length<31){a.pushByte(128),i=!1;break}c++,o+=31}s.push(a)}return e==="bytes"?s.map(a=>a.bytes):s.map(a=>Qe(a.bytes))}function mg(t){const{data:e,kzg:r,to:n}=t,s=t.blobs??tA({data:e,to:n}),i=t.commitments??Ld({blobs:s,kzg:r,to:n}),o=t.proofs??Dd({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 gg(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 pS({transaction:t})}async function Vi(t){const e=await t.request({method:"eth_chainId"},{dedupe:!0});return lr(e)}const bg=["blobVersionedHashes","chainId","fees","gas","nonce","type"],Ep=new Map;async function Hc(t,e){const{account:r=t.account,blobs:n,chain:s,gas:i,kzg:o,nonce:a,nonceManager:c,parameters:l=bg,type:u}=e,f=r&&We(r),h={...e,...f?{from:f==null?void 0:f.address}:{}};let d;async function m(){return d||(d=await ae(t,Wr,"getBlock")({blockTag:"latest"}),d)}let g;async function v(){return g||(s?s.id:typeof e.chainId<"u"?e.chainId:(g=await ae(t,Vi,"getChainId")({}),g))}if(l.includes("nonce")&&typeof a>"u"&&f)if(c){const S=await v();h.nonce=await c.consume({address:f.address,chainId:S,client:t})}else h.nonce=await ae(t,jd,"getTransactionCount")({address:f.address,blockTag:"pending"});if((l.includes("blobVersionedHashes")||l.includes("sidecars"))&&n&&o){const S=Ld({blobs:n,kzg:o});if(l.includes("blobVersionedHashes")){const _=fg({commitments:S,to:"hex"});h.blobVersionedHashes=_}if(l.includes("sidecars")){const _=Dd({blobs:n,commitments:S,kzg:o}),E=mg({blobs:n,commitments:S,proofs:_,to:"hex"});h.sidecars=E}}if(l.includes("chainId")&&(h.chainId=await v()),(l.includes("fees")||l.includes("type"))&&typeof u>"u")try{h.type=gg(h)}catch{let S=Ep.get(t.uid);if(typeof S>"u"){const _=await m();S=typeof(_==null?void 0:_.baseFeePerGas)=="bigint",Ep.set(t.uid,S)}h.type=S?"eip1559":"legacy"}if(l.includes("fees"))if(h.type!=="legacy"&&h.type!=="eip2930"){if(typeof h.maxFeePerGas>"u"||typeof h.maxPriorityFeePerGas>"u"){const S=await m(),{maxFeePerGas:_,maxPriorityFeePerGas:E}=await Bf(t,{block:S,chain:s,request:h});if(typeof e.maxPriorityFeePerGas>"u"&&e.maxFeePerGas&&e.maxFeePerGas<E)throw new US({maxPriorityFeePerGas:E});h.maxPriorityFeePerGas=E,h.maxFeePerGas=_}}else{if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")throw new Ud;if(typeof e.gasPrice>"u"){const S=await m(),{gasPrice:_}=await Bf(t,{block:S,chain:s,request:h,type:"legacy"});h.gasPrice=_}}return l.includes("gas")&&typeof i>"u"&&(h.gas=await ae(t,Vd,"estimateGas")({...h,account:f&&{address:f.address,type:"json-rpc"}})),Zs(h),delete h.parameters,h}async function wg(t,{address:e,blockNumber:r,blockTag:n=t.experimental_blockTag??"latest"}){const s=typeof r=="bigint"?X(r):void 0,i=await t.request({method:"eth_getBalance",params:[e,s||n]});return BigInt(i)}async function Vd(t,e){var s,i,o;const{account:r=t.account}=e,n=r?We(r):void 0;try{let N=function(Z){const{block:ee,request:D,rpcStateOverride:T}=Z;return t.request({method:"eth_estimateGas",params:T?[D,ee??t.experimental_blockTag??"latest",T]:ee?[D,ee]:[D]})};const{accessList:a,authorizationList:c,blobs:l,blobVersionedHashes:u,blockNumber:f,blockTag:h,data:d,gas:m,gasPrice:g,maxFeePerBlobGas:v,maxFeePerGas:S,maxPriorityFeePerGas:_,nonce:E,value:x,stateOverride:O,...P}=await Hc(t,{...e,parameters:(n==null?void 0:n.type)==="local"?void 0:["blobVersionedHashes"]}),z=(typeof f=="bigint"?X(f):void 0)||h,C=Nd(O),Y=await(async()=>{if(P.to)return P.to;if(c&&c.length>0)return await ng({authorization:c[0]}).catch(()=>{throw new H("`to` is required. Could not infer from `authorizationList`")})})();Zs(e);const W=(o=(i=(s=t.chain)==null?void 0:s.formatters)==null?void 0:i.transactionRequest)==null?void 0:o.format,U=(W||zi)({...jc(P,{format:W}),from:n==null?void 0:n.address,accessList:a,authorizationList:c,blobs:l,blobVersionedHashes:u,data:d,gas:m,gasPrice:g,maxFeePerBlobGas:v,maxFeePerGas:S,maxPriorityFeePerGas:_,nonce:E,to:Y,value:x});let F=BigInt(await N({block:z,request:U,rpcStateOverride:C}));if(c){const Z=await wg(t,{address:U.from}),ee=await Promise.all(c.map(async D=>{const{address:T}=D,L=await N({block:z,request:{authorizationList:void 0,data:d,from:n==null?void 0:n.address,to:T,value:X(Z)},rpcStateOverride:C}).catch(()=>100000n);return 2n*BigInt(L)}));F+=ee.reduce((D,T)=>D+T,0n)}return F}catch(a){throw BS(a,{...e,account:n,chain:t.chain})}}async function vg(t,e){const{abi:r,address:n,args:s,functionName:i,dataSuffix:o,...a}=e,c=hr({abi:r,args:s,functionName:i});try{return await ae(t,Vd,"estimateGas")({data:`${c}${o?o.replace("0x",""):""}`,to:n,...a})}catch(l){const u=a.account?We(a.account):void 0;throw Ms(l,{abi:r,address:n,args:s,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:u==null?void 0:u.address})}}function pa(t,e){if(!ot(t,{strict:!1}))throw new Ct({address:t});if(!ot(e,{strict:!1}))throw new Ct({address:e});return t.toLowerCase()===e.toLowerCase()}const Sp="/docs/contract/decodeEventLog";function qd(t){const{abi:e,data:r,strict:n,topics:s}=t,i=n??!0,[o,...a]=s;if(!o)throw new q2({docsPath:Sp});const c=e.find(g=>g.type==="event"&&o===$c(_r(g)));if(!(c&&"name"in c)||c.type!=="event")throw new m0(o,{docsPath:Sp});const{name:l,inputs:u}=c,f=u==null?void 0:u.some(g=>!("name"in g&&g.name)),h=f?[]:{},d=u.map((g,v)=>[g,v]).filter(([g])=>"indexed"in g&&g.indexed);for(let g=0;g<d.length;g++){const[v,S]=d[g],_=a[g];if(!_)throw new Pc({abiItem:c,param:v});h[f?S:v.name||S]=rA({param:v,value:_})}const m=u.filter(g=>!("indexed"in g&&g.indexed));if(m.length>0){if(r&&r!=="0x")try{const g=fa(m,r);if(g)if(f)for(let v=0;v<u.length;v++)h[v]=h[v]??g.shift();else for(let v=0;v<m.length;v++)h[m[v].name]=g[v]}catch(g){if(i)throw g instanceof p0||g instanceof W0?new To({abiItem:c,data:r,params:m,size:Le(r)}):g}else if(i)throw new To({abiItem:c,data:"0x",params:m,size:0})}return{eventName:l,args:Object.values(h).length>0?h:void 0}}function rA({param:t,value:e}){return t.type==="string"||t.type==="bytes"||t.type==="tuple"||t.type.match(/^(.*)\[(\d+)?\]$/)?e:(fa([t],e)||[])[0]}function Gd(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(u=>u.type==="event"&&o.topics[0]===$c(u));if(!c)return null;const l=qd({...o,abi:[c],strict:s});return i&&!i.includes(l.eventName)||!nA({args:l.args,inputs:c.inputs,matchArgs:r})?null:{...l,...o}}catch(c){let l,u;if(c instanceof m0)return null;if(c instanceof To||c instanceof Pc){if(s)return null;l=c.abiItem.name,u=(a=c.abiItem.inputs)==null?void 0:a.some(f=>!("name"in f&&f.name))}return{...o,args:u?[]:{},eventName:l}}}).filter(Boolean)}function nA(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"?pa(o,a):i.type==="string"||i.type==="bytes"?ft(Hi(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(l=>s(a,l,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(l=>l.name===i);return a?(Array.isArray(o)?o:[o]).some(l=>s(a,l,e[i])):!1}):!1}function An(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 Wd(t,{address:e,blockHash:r,fromBlock:n,toBlock:s,event:i,events:o,args:a,strict:c}={}){const l=c??!1,u=o??(i?[i]:void 0);let f=[];u&&(f=[u.flatMap(g=>la({abi:[g],eventName:g.name,args:o?void 0:a}))],i&&(f=f[0]));let h;r?h=await t.request({method:"eth_getLogs",params:[{address:e,topics:f,blockHash:r}]}):h=await t.request({method:"eth_getLogs",params:[{address:e,topics:f,fromBlock:typeof n=="bigint"?X(n):n,toBlock:typeof s=="bigint"?X(s):s}]});const d=h.map(m=>An(m));return u?Gd({abi:u,args:a,logs:d,strict:l}):d}async function Kd(t,e){const{abi:r,address:n,args:s,blockHash:i,eventName:o,fromBlock:a,toBlock:c,strict:l}=e,u=o?Ks({abi:r,name:o}):void 0,f=u?void 0:r.filter(h=>h.type==="event");return ae(t,Wd,"getLogs")({address:n,args:s,blockHash:i,event:u,events:f,fromBlock:a,toBlock:c,strict:l})}const ku="/docs/contract/decodeFunctionResult";function Xs(t){const{abi:e,args:r,functionName:n,data:s}=t;let i=e[0];if(n){const a=Ks({abi:e,args:r,name:n});if(!a)throw new Ii(n,{docsPath:ku});i=a}if(i.type!=="function")throw new Ii(void 0,{docsPath:ku});if(!i.outputs)throw new g0(i.name,{docsPath:ku});const o=fa(i.outputs,s);if(o&&o.length>1)return o;if(o&&o.length===1)return o[0]}const sA="0.1.1";function iA(){return sA}let Ke=class Cf extends Error{constructor(e,r={}){const n=(()=>{var c;if(r.cause instanceof Cf){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 Cf&&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@${iA()}`}),this.cause=r.cause,this.details=n,this.docs=o,this.docsPath=s,this.shortMessage=e}walk(e){return Eg(this,e)}};function Eg(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Eg(t.cause,e):e?null:t}const oA="#__bigint";function aA(t,e,r){return JSON.stringify(t,(n,s)=>typeof s=="bigint"?s.toString()+oA:s,r)}function cA(t,e){if(xp(t)>e)throw new bA({givenSize:xp(t),maxSize:e})}const rn={zero:48,nine:57,A:65,F:70,a:97,f:102};function Ap(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 uA(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;if(t.length>n)throw new wA({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 Zd(t,e){if(fr(t)>e)throw new xA({givenSize:fr(t),maxSize:e})}function lA(t,e){if(typeof e=="number"&&e>0&&e>fr(t)-1)throw new _g({offset:e,position:"start",size:fr(t)})}function fA(t,e,r){if(typeof e=="number"&&typeof r=="number"&&fr(t)!==r-e)throw new _g({offset:r,position:"end",size:fr(t)})}function Sg(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 kA({size:Math.ceil(s.length/2),targetSize:n,type:"Hex"});return`0x${s[r==="right"?"padEnd":"padStart"](n*2,"0")}`}const dA=new TextEncoder;function hA(t){return t instanceof Uint8Array?t:typeof t=="string"?yA(t):pA(t)}function pA(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function yA(t,e={}){const{size:r}=e;let n=t;r&&(Zd(t,r),n=Ls(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 l=Ap(s.charCodeAt(c++)),u=Ap(s.charCodeAt(c++));if(l===void 0||u===void 0)throw new Ke(`Invalid byte sequence ("${s[c-2]}${s[c-1]}" in "${s}").`);o[a]=l*16+u}return o}function mA(t,e={}){const{size:r}=e,n=dA.encode(t);return typeof r=="number"?(cA(n,r),gA(n,r)):n}function gA(t,e){return uA(t,{dir:"right",size:e})}function xp(t){return t.length}let bA=class extends Ke{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},wA=class extends Ke{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}};const vA=new TextEncoder,EA=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function SA(t,e={}){const{strict:r=!1}=e;if(!t)throw new kp(t);if(typeof t!="string")throw new kp(t);if(r&&!/^0x[0-9a-fA-F]*$/.test(t))throw new _p(t);if(!t.startsWith("0x"))throw new _p(t)}function Xr(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function Ag(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(Zd(r,e.size),js(r,e.size)):r}function xg(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=EA[t[s]];const n=`0x${r}`;return typeof e.size=="number"?(Zd(n,e.size),Ls(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 l=typeof t=="bigint"?"n":"";throw new kg({max:i?`${i}${l}`:void 0,min:`${o}${l}`,signed:r,size:n,value:`${t}${l}`})}const c=`0x${(r&&s<0?(1n<<BigInt(n*8))+BigInt(s):s).toString(16)}`;return n?js(c,n):c}function Xd(t,e={}){return xg(vA.encode(t),e)}function js(t,e){return Sg(t,{dir:"left",size:e})}function Ls(t,e){return Sg(t,{dir:"right",size:e})}function Yd(t,e,r,n={}){const{strict:s}=n;lA(t,e);const i=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return s&&fA(i,e,r),i}function fr(t){return Math.ceil((t.length-2)/2)}function AA(t,e={}){const{strict:r=!1}=e;try{return SA(t,{strict:r}),!0}catch{return!1}}class kg extends Ke{constructor({max:e,min:r,signed:n,size:s,value:i}){super(`Number \`${i}\` is not in safe${s?` ${s*8}-bit`:""}${n?" signed":" unsigned"} integer range ${e?`(\`${r}\` to \`${e}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class kp extends Ke{constructor(e){super(`Value \`${typeof e=="object"?aA(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 _p extends Ke{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class xA extends Ke{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class _g extends Ke{constructor({offset:e,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class kA extends Ke{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}function _A(t){return{address:t.address,amount:It(t.amount),index:It(t.index),validatorIndex:It(t.validatorIndex)}}function Tg(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(_A)}}}const $f=[{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"}],Rf=[{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"}]}],Ig=[{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"}],Pg=[...Ig,{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"}]}],TA=[...Ig,{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"}]}],Tp=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],Ip=[{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"}]}],Pp=[{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"}],IA="0x82ad56cb",Og="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",PA="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",OA="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572";class Nf extends H{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 BA extends H{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 CA extends H{constructor(){super(["No chain was provided to the request.","Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."].join(`
41
- `),{name:"ChainNotFoundError"})}}class Bg extends H{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class zc extends H{constructor({chainId:e}){super(typeof e=="number"?`Chain ID "${e}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const _u="/docs/contract/encodeDeployData";function Vc(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 L2({docsPath:_u});if(!("inputs"in s))throw new tp({docsPath:_u});if(!s.inputs||s.inputs.length===0)throw new tp({docsPath:_u});const i=On(s.inputs,r);return Br([n,i])}function qi({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 Nf({chain:e,contract:{name:r}});if(t&&n.blockCreated&&n.blockCreated>t)throw new Nf({blockNumber:t,chain:e,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function Cg(t,{docsPath:e,...r}){const n=(()=>{const s=Fc(t,r);return s instanceof ha?t:s})();return new Q0(n,{docsPath:e,...r})}function Jd(){let t=()=>{},e=()=>{};return{promise:new Promise((n,s)=>{t=n,e=s}),resolve:t,reject:e}}const Tu=new Map;function $g({fn:t,id:e,shouldSplitBatch:r,wait:n=0,sort:s}){const i=async()=>{const u=c();o();const f=u.map(({args:h})=>h);f.length!==0&&t(f).then(h=>{s&&Array.isArray(h)&&h.sort(s);for(let d=0;d<u.length;d++){const{resolve:m}=u[d];m==null||m([h[d],h])}}).catch(h=>{for(let d=0;d<u.length;d++){const{reject:m}=u[d];m==null||m(h)}})},o=()=>Tu.delete(e),a=()=>c().map(({args:u})=>u),c=()=>Tu.get(e)||[],l=u=>Tu.set(e,[...c(),u]);return{flush:o,async schedule(u){const{promise:f,resolve:h,reject:d}=Jd();return(r==null?void 0:r([...a(),u]))&&i(),c().length>0?(l({args:u,resolve:h,reject:d}),f):(l({args:u,resolve:h,reject:d}),setTimeout(i,n),f)}}}async function ya(t,e){var U,N,F,Z;const{account:r=t.account,authorizationList:n,batch:s=!!((U=t.batch)!=null&&U.multicall),blockNumber:i,blockTag:o=t.experimental_blockTag??"latest",accessList:a,blobs:c,blockOverrides:l,code:u,data:f,factory:h,factoryData:d,gas:m,gasPrice:g,maxFeePerBlobGas:v,maxFeePerGas:S,maxPriorityFeePerGas:_,nonce:E,to:x,value:O,stateOverride:P,...$}=e,z=r?We(r):void 0;if(u&&(h||d))throw new H("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(u&&x)throw new H("Cannot provide both `code` & `to` as parameters.");const C=u&&f,Y=h&&d&&x&&f,W=C||Y,K=C?NA({code:u,data:f}):Y?UA({data:f,factory:h,factoryData:d,to:x}):f;try{Zs(e);const D=(typeof i=="bigint"?X(i):void 0)||o,T=l?Tg(l):void 0,L=Nd(P),G=(Z=(F=(N=t.chain)==null?void 0:N.formatters)==null?void 0:F.transactionRequest)==null?void 0:Z.format,R=(G||zi)({...jc($,{format:G}),from:z==null?void 0:z.address,accessList:a,authorizationList:n,blobs:c,data:K,gas:m,gasPrice:g,maxFeePerBlobGas:v,maxFeePerGas:S,maxPriorityFeePerGas:_,nonce:E,to:W?void 0:x,value:O});if(s&&$A({request:R})&&!L&&!T)try{return await RA(t,{...R,blockNumber:i,blockTag:o})}catch(ne){if(!(ne instanceof Bg)&&!(ne instanceof Nf))throw ne}const j=(()=>{const ne=[R,D];return L&&T?[...ne,L,T]:L?[...ne,L]:T?[...ne,{},T]:ne})(),J=await t.request({method:"eth_call",params:j});return J==="0x"?{data:void 0}:{data:J}}catch(ee){const D=MA(ee),{offchainLookup:T,offchainLookupSignature:L}=await Promise.resolve().then(()=>require("./ccip-BixEUfCX.cjs"));if(t.ccipRead!==!1&&(D==null?void 0:D.slice(0,10))===L&&x)return{data:await T(t,{data:D,to:x})};throw W&&(D==null?void 0:D.slice(0,10))==="0x101bb98d"?new ES({factory:h}):Cg(ee,{...e,account:z,chain:t.chain})}}function $A({request:t}){const{data:e,to:r,...n}=t;return!(!e||e.startsWith(IA)||!r||Object.values(n).filter(s=>typeof s<"u").length>0)}async function RA(t,e){var g;const{batchSize:r=1024,wait:n=0}=typeof((g=t.batch)==null?void 0:g.multicall)=="object"?t.batch.multicall:{},{blockNumber:s,blockTag:i=t.experimental_blockTag??"latest",data:o,multicallAddress:a,to:c}=e;let l=a;if(!l){if(!t.chain)throw new Bg;l=qi({blockNumber:s,chain:t.chain,contract:"multicall3"})}const f=(typeof s=="bigint"?X(s):void 0)||i,{schedule:h}=$g({id:`${t.uid}.${f}`,wait:n,shouldSplitBatch(v){return v.reduce((_,{data:E})=>_+(E.length-2),0)>r*2},fn:async v=>{const S=v.map(x=>({allowFailure:!0,callData:x.data,target:x.to})),_=hr({abi:$f,args:[S],functionName:"aggregate3"}),E=await t.request({method:"eth_call",params:[{data:_,to:l},f]});return Xs({abi:$f,args:[S],functionName:"aggregate3",data:E||"0x"})}}),[{returnData:d,success:m}]=await h({data:o,to:c});if(!m)throw new Mc({data:d});return d==="0x"?{data:void 0}:{data:d}}function NA(t){const{code:e,data:r}=t;return Vc({abi:f0(["constructor(bytes, bytes)"]),bytecode:Og,args:[e,r]})}function UA(t){const{data:e,factory:r,factoryData:n,to:s}=t;return Vc({abi:f0(["constructor(address, bytes, address, bytes)"]),bytecode:PA,args:[s,e,r,n]})}function MA(t){var r;if(!(t instanceof H))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 Yr(t,e){const{abi:r,address:n,args:s,functionName:i,...o}=e,a=hr({abi:r,args:s,functionName:i});try{const{data:c}=await ae(t,ya,"call")({...o,data:a,to:n});return Xs({abi:r,args:s,functionName:i,data:c||"0x"})}catch(c){throw Ms(c,{abi:r,address:n,args:s,docsPath:"/docs/contract/readContract",functionName:i})}}async function Rg(t,e){const{abi:r,address:n,args:s,dataSuffix:i,functionName:o,...a}=e,c=a.account?We(a.account):t.account,l=hr({abi:r,args:s,functionName:o});try{const{data:u}=await ae(t,ya,"call")({batch:!1,data:`${l}${i?i.replace("0x",""):""}`,to:n,...a,account:c}),f=Xs({abi:r,args:s,functionName:o,data:u||"0x"}),h=r.filter(d=>"name"in d&&d.name===e.functionName);return{result:f,request:{abi:h,address:n,args:s,dataSuffix:i,functionName:o,...a,account:c}}}catch(u){throw Ms(u,{abi:r,address:n,args:s,docsPath:"/docs/contract/simulateContract",functionName:o,sender:c==null?void 0:c.address})}}const Iu=new Map,Op=new Map;let FA=0;function xn(t,e,r){const n=++FA,s=()=>Iu.get(t)||[],i=()=>{const u=s();Iu.set(t,u.filter(f=>f.id!==n))},o=()=>{const u=s();if(!u.some(h=>h.id===n))return;const f=Op.get(t);if(u.length===1&&f){const h=f();h instanceof Promise&&h.catch(()=>{})}i()},a=s();if(Iu.set(t,[...a,{id:n,fns:e}]),a&&a.length>0)return o;const c={};for(const u in e)c[u]=(...f)=>{var d,m;const h=s();if(h.length!==0)for(const g of h)(m=(d=g.fns)[u])==null||m.call(d,...f)};const l=r(c);return typeof l=="function"&&Op.set(t,l),o}async function Uf(t){return new Promise(e=>setTimeout(e,t))}function Gi(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 Uf(c);const l=async()=>{s&&(await t({unpoll:i}),await Uf(n),l())};l()})(),i}const jA=new Map,LA=new Map;function DA(t){const e=(s,i)=>({clear:()=>i.delete(s),get:()=>i.get(s),set:o=>i.set(s,o)}),r=e(t,jA),n=e(t,LA);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function HA(t,{cacheKey:e,cacheTime:r=Number.POSITIVE_INFINITY}){const n=DA(e),s=n.response.get();if(s&&r>0&&new Date().getTime()-s.created.getTime()<r)return s.data;let i=n.promise.get();i||(i=t(),n.promise.set(i));try{const o=await i;return n.response.set({created:new Date,data:o}),o}finally{n.promise.clear()}}const zA=t=>`blockNumber.${t}`;async function ma(t,{cacheTime:e=t.cacheTime}={}){const r=await HA(()=>t.request({method:"eth_blockNumber"}),{cacheKey:zA(t.uid),cacheTime:e});return BigInt(r)}async function qc(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=>An(i));return!("abi"in e)||!e.abi?s:Gd({abi:e.abi,logs:s,strict:r})}async function Gc(t,{filter:e}){return e.request({method:"eth_uninstallFilter",params:[e.id]})}function Ng(t,e){const{abi:r,address:n,args:s,batch:i=!0,eventName:o,fromBlock:a,onError:c,onLogs:l,poll:u,pollingInterval:f=t.pollingInterval,strict:h}=e;return(typeof u<"u"?u:typeof a=="bigint"?!0:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")))?(()=>{const v=h??!1,S=Je(["watchContractEvent",n,s,i,t.uid,o,f,v,a]);return xn(S,{onLogs:l,onError:c},_=>{let E;a!==void 0&&(E=a-1n);let x,O=!1;const P=Gi(async()=>{var $;if(!O){try{x=await ae(t,Od,"createContractEventFilter")({abi:r,address:n,args:s,eventName:o,strict:v,fromBlock:a})}catch{}O=!0;return}try{let z;if(x)z=await ae(t,qc,"getFilterChanges")({filter:x});else{const C=await ae(t,ma,"getBlockNumber")({});E&&E<C?z=await ae(t,Kd,"getContractEvents")({abi:r,address:n,args:s,eventName:o,fromBlock:E+1n,toBlock:C,strict:v}):z=[],E=C}if(z.length===0)return;if(i)_.onLogs(z);else for(const C of z)_.onLogs([C])}catch(z){x&&z instanceof Us&&(O=!1),($=_.onError)==null||$.call(_,z)}},{emitOnBegin:!0,interval:f});return async()=>{x&&await ae(t,Gc,"uninstallFilter")({filter:x}),P()}})})():(()=>{const v=h??!1,S=Je(["watchContractEvent",n,s,i,t.uid,o,f,v]);let _=!0,E=()=>_=!1;return xn(S,{onLogs:l,onError:c},x=>((async()=>{try{const O=(()=>{if(t.transport.type==="fallback"){const z=t.transport.transports.find(C=>C.config.type==="webSocket"||C.config.type==="ipc");return z?z.value:t.transport}return t.transport})(),P=o?la({abi:r,eventName:o,args:s}):[],{unsubscribe:$}=await O.subscribe({params:["logs",{address:n,topics:P}],onData(z){var Y;if(!_)return;const C=z.result;try{const{eventName:W,args:K}=qd({abi:r,data:C.data,topics:C.topics,strict:h}),U=An(C,{args:K,eventName:W});x.onLogs([U])}catch(W){let K,U;if(W instanceof To||W instanceof Pc){if(h)return;K=W.abiItem.name,U=(Y=W.abiItem.inputs)==null?void 0:Y.some(F=>!("name"in F&&F.name))}const N=An(C,{args:U?[]:{},eventName:K});x.onLogs([N])}},onError(z){var C;(C=x.onError)==null||C.call(x,z)}});E=$,_||E()}catch(O){c==null||c(O)}})(),()=>E()))})()}class Ys extends H{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 Qa extends H{constructor({docsPath:e,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:e,metaMessages:r,name:"AccountTypeNotSupportedError"})}}function Ug({chain:t,currentChainId:e}){if(!t)throw new CA;if(e!==t.id)throw new BA({chain:t,currentChainId:e})}function Mg(t,{docsPath:e,...r}){const n=(()=>{const s=Fc(t,r);return s instanceof ha?t:s})();return new mS(n,{docsPath:e,...r})}async function Qd(t,{serializedTransaction:e}){return t.request({method:"eth_sendRawTransaction",params:[e]},{retryCount:0})}const Pu=new Rc(128);async function Wc(t,e){var _,E,x,O;const{account:r=t.account,chain:n=t.chain,accessList:s,authorizationList:i,blobs:o,data:a,gas:c,gasPrice:l,maxFeePerBlobGas:u,maxFeePerGas:f,maxPriorityFeePerGas:h,nonce:d,type:m,value:g,...v}=e;if(typeof r>"u")throw new Ys({docsPath:"/docs/actions/wallet/sendTransaction"});const S=r?We(r):null;try{Zs(e);const P=await(async()=>{if(e.to)return e.to;if(e.to!==null&&i&&i.length>0)return await ng({authorization:i[0]}).catch(()=>{throw new H("`to` is required. Could not infer from `authorizationList`.")})})();if((S==null?void 0:S.type)==="json-rpc"||S===null){let $;n!==null&&($=await ae(t,Vi,"getChainId")({}),Ug({currentChainId:$,chain:n}));const z=(x=(E=(_=t.chain)==null?void 0:_.formatters)==null?void 0:E.transactionRequest)==null?void 0:x.format,Y=(z||zi)({...jc(v,{format:z}),accessList:s,authorizationList:i,blobs:o,chainId:$,data:a,from:S==null?void 0:S.address,gas:c,gasPrice:l,maxFeePerBlobGas:u,maxFeePerGas:f,maxPriorityFeePerGas:h,nonce:d,to:P,type:m,value:g}),W=Pu.get(t.uid),K=W?"wallet_sendTransaction":"eth_sendTransaction";try{return await t.request({method:K,params:[Y]},{retryCount:0})}catch(U){if(W===!1)throw U;const N=U;if(N.name==="InvalidInputRpcError"||N.name==="InvalidParamsRpcError"||N.name==="MethodNotFoundRpcError"||N.name==="MethodNotSupportedRpcError")return await t.request({method:"wallet_sendTransaction",params:[Y]},{retryCount:0}).then(F=>(Pu.set(t.uid,!0),F)).catch(F=>{const Z=F;throw Z.name==="MethodNotFoundRpcError"||Z.name==="MethodNotSupportedRpcError"?(Pu.set(t.uid,!1),N):Z});throw N}}if((S==null?void 0:S.type)==="local"){const $=await ae(t,Hc,"prepareTransactionRequest")({account:S,accessList:s,authorizationList:i,blobs:o,chain:n,data:a,gas:c,gasPrice:l,maxFeePerBlobGas:u,maxFeePerGas:f,maxPriorityFeePerGas:h,nonce:d,nonceManager:S.nonceManager,parameters:[...bg,"sidecars"],type:m,value:g,...v,to:P}),z=(O=n==null?void 0:n.serializers)==null?void 0:O.transaction,C=await S.signTransaction($,{serializer:z});return await ae(t,Qd,"sendRawTransaction")({serializedTransaction:C})}throw(S==null?void 0:S.type)==="smart"?new Qa({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new Qa({docsPath:"/docs/actions/wallet/sendTransaction",type:S==null?void 0:S.type})}catch(P){throw P instanceof Qa?P:Mg(P,{...e,account:S,chain:e.chain||void 0})}}async function Fg(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 Ys({docsPath:"/docs/contract/writeContract"});const l=n?We(n):null,u=hr({abi:r,args:i,functionName:a});try{return await ae(t,Wc,"sendTransaction")({data:`${u}${o?o.replace("0x",""):""}`,to:s,account:l,...c})}catch(f){throw Ms(f,{abi:r,address:s,args:i,docsPath:"/docs/contract/writeContract",functionName:a,sender:l==null?void 0:l.address})}}function Bp({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 l=!1,u=!1,f=!1;for(const h of t)if(h.type==="function"?h.stateMutability==="view"||h.stateMutability==="pure"?l=!0:u=!0:h.type==="event"&&(f=!0),l&&u&&f)break;return o&&(l&&(c.read=new Proxy({},{get(h,d){return(...m)=>{const{args:g,options:v}=Ba(m);return ae(s,Yr,"readContract")({abi:t,address:e,functionName:d,args:g,...v})}}})),u&&(c.simulate=new Proxy({},{get(h,d){return(...m)=>{const{args:g,options:v}=Ba(m);return ae(s,Rg,"simulateContract")({abi:t,address:e,functionName:d,args:g,...v})}}})),f&&(c.createEventFilter=new Proxy({},{get(h,d){return(...m)=>{const g=t.find(_=>_.type==="event"&&_.name===d),{args:v,options:S}=Ou(m,g);return ae(s,Od,"createContractEventFilter")({abi:t,address:e,eventName:d,args:v,...S})}}}),c.getEvents=new Proxy({},{get(h,d){return(...m)=>{const g=t.find(_=>_.type==="event"&&_.name===d),{args:v,options:S}=Ou(m,g);return ae(s,Kd,"getContractEvents")({abi:t,address:e,eventName:d,args:v,...S})}}}),c.watchEvent=new Proxy({},{get(h,d){return(...m)=>{const g=t.find(_=>_.type==="event"&&_.name===d),{args:v,options:S}=Ou(m,g);return ae(s,Ng,"watchContractEvent")({abi:t,address:e,eventName:d,args:v,...S})}}}))),a&&u&&(c.write=new Proxy({},{get(h,d){return(...m)=>{const{args:g,options:v}=Ba(m);return ae(i,Fg,"writeContract")({abi:t,address:e,functionName:d,args:g,...v})}}})),(o||a)&&u&&(c.estimateGas=new Proxy({},{get(h,d){return(...m)=>{const{args:g,options:v}=Ba(m);return ae(s??i,vg,"estimateContractGas")({abi:t,address:e,functionName:d,args:g,...v,account:v.account??i.account})}}})),c.address=e,c.abi=t,c}function Ba(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 Ou(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 VA extends H{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 yc(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:l})=>{const u=typeof e=="function"?e({count:a,error:l}):e;u&&await Uf(u),o({count:a+1})};try{const l=await t();s(l)}catch(l){if(a<r&&await n({count:a,error:l}))return c({error:l});i(l)}};o()})}const jg={"0x0":"reverted","0x1":"success"};function Lg(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=>An(r)):null,to:t.to?t.to:null,transactionIndex:t.transactionIndex?lr(t.transactionIndex):null,status:t.status?jg[t.status]:null,type:t.type?ig[t.type]||t.type:null};return t.blobGasPrice&&(e.blobGasPrice=BigInt(t.blobGasPrice)),t.blobGasUsed&&(e.blobGasUsed=BigInt(t.blobGasUsed)),e}const qA=Rd("transactionReceipt",Lg),Dg="0x5792579257925792579257925792579257925792579257925792579257925792",Hg=X(0,{size:32});async function GA(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:l="2.0.0"}=e,u=r?We(r):null,f=e.calls.map(h=>{const d=h,m=d.abi?hr({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?X(d.value):void 0}});try{const h=await t.request({method:"wallet_sendCalls",params:[{atomicRequired:a,calls:f,capabilities:n,chainId:X(s.id),from:u==null?void 0:u.address,id:c,version:l}]},{retryCount:0});return typeof h=="string"?{id:h}:h}catch(h){const d=h;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(_=>!_.optional)){const _="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new Bi(new H(_,{details:_}))}if(a&&f.length>1){const S="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new Ci(new H(S,{details:S}))}const m=[];for(const S of f){const _=Wc(t,{account:u,chain:s,data:S.data,to:S.to,value:S.value?at(S.value):void 0});m.push(_),o>0&&await new Promise(E=>setTimeout(E,o))}const g=await Promise.allSettled(m);if(g.every(S=>S.status==="rejected"))throw g[0].reason;const v=g.map(S=>S.status==="fulfilled"?S.value:Hg);return{id:Kt([...v,X(s.id,{size:32}),Dg])}}throw Mg(h,{...e,account:u,chain:e.chain})}}async function zg(t,e){async function r(u){if(u.endsWith(Dg.slice(2))){const h=ur(pc(u,-64,-32)),d=pc(u,0,-64).slice(2).match(/.{1,64}/g),m=await Promise.all(d.map(v=>Hg.slice(2)!==v?t.request({method:"eth_getTransactionReceipt",params:[`0x${v}`]},{dedupe:!0}):void 0)),g=m.some(v=>v===null)?100:m.every(v=>(v==null?void 0:v.status)==="0x1")?200:m.every(v=>(v==null?void 0:v.status)==="0x0")?500:600;return{atomic:!1,chainId:lr(h),receipts:m.filter(Boolean),status:g,version:"2.0.0"}}return t.request({method:"wallet_getCallsStatus",params:[u]})}const{atomic:n=!1,chainId:s,receipts:i,version:o="2.0.0",...a}=await r(e.id),[c,l]=(()=>{const u=a.status;return u>=100&&u<200?["pending",u]:u>=200&&u<300?["success",u]:u>=300&&u<700?["failure",u]:u==="CONFIRMED"?["success",200]:u==="PENDING"?["pending",100]:[void 0,u]})();return{...a,atomic:n,chainId:s?lr(s):void 0,receipts:(i==null?void 0:i.map(u=>({...u,blockNumber:at(u.blockNumber),gasUsed:at(u.gasUsed),status:jg[u.status]})))??[],statusCode:l,status:c,version:o}}async function WA(t,e){const{id:r,pollingInterval:n=t.pollingInterval,status:s=({statusCode:g})=>g===200||g>=300,retryCount:i=4,retryDelay:o=({count:g})=>~~(1<<g)*200,timeout:a=6e4,throwOnFailure:c=!1}=e,l=Je(["waitForCallsStatus",t.uid,r]),{promise:u,resolve:f,reject:h}=Jd();let d;const m=xn(l,{resolve:f,reject:h},g=>{const v=Gi(async()=>{const S=_=>{clearTimeout(d),v(),_(),m()};try{const _=await yc(async()=>{const E=await zg(t,{id:r});if(c&&E.status==="failure")throw new VA(E);return E},{retryCount:i,delay:o});if(!s(_))return;S(()=>g.resolve(_))}catch(_){S(()=>g.reject(_))}},{interval:n,emitOnBegin:!0});return v});return d=a?setTimeout(()=>{m(),clearTimeout(d),h(new KA({id:r}))},a):void 0,await u}class KA extends H{constructor({id:e}){super(`Timed out while waiting for call bundle with id "${e}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}const Mf=256;let Ca=Mf,$a;function Vg(t=11){if(!$a||Ca+t>Mf*2){$a="",Ca=0;for(let e=0;e<Mf;e++)$a+=(256+Math.random()*256|0).toString(16).substring(1)}return $a.substring(Ca,Ca+++t)}function qg(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,l=Math.min(Math.max(Math.floor(c/2),500),4e3),u=t.pollingInterval??l,f=t.cacheTime??u,h=t.account?We(t.account):void 0,{config:d,request:m,value:g}=t.transport({chain:r,pollingInterval:u}),v={...d,...g},S={account:h,batch:e,cacheTime:f,ccipRead:n,chain:r,key:s,name:i,pollingInterval:u,request:m,transport:v,type:o,uid:Vg(),...a?{experimental_blockTag:a}:{}};function _(E){return x=>{const O=x(E);for(const $ in S)delete O[$];const P={...E,...O};return Object.assign(P,{extend:_(P)})}}return Object.assign(S,{extend:_(S)})}const Ra=new Rc(8192);function ZA(t,{enabled:e=!0,id:r}){if(!e||!r)return t();if(Ra.get(r))return Ra.get(r);const n=t().finally(()=>Ra.delete(r));return Ra.set(r,n),n}function XA(t,e={}){return async(r,n={})=>{var f;const{dedupe:s=!1,methods:i,retryDelay:o=150,retryCount:a=3,uid:c}={...e,...n},{method:l}=r;if((f=i==null?void 0:i.exclude)!=null&&f.includes(l))throw new bs(new Error("method not supported"),{method:l});if(i!=null&&i.include&&!i.include.includes(l))throw new bs(new Error("method not supported"),{method:l});const u=s?Pi(`${c}.${Je(r)}`):void 0;return ZA(()=>yc(async()=>{try{return await t(r)}catch(h){const d=h;switch(d.code){case Oo.code:throw new Oo(d);case Bo.code:throw new Bo(d);case Co.code:throw new Co(d,{method:r.method});case $o.code:throw new $o(d);case Ns.code:throw new Ns(d);case Us.code:throw new Us(d);case Ro.code:throw new Ro(d);case No.code:throw new No(d);case Uo.code:throw new Uo(d);case bs.code:throw new bs(d,{method:r.method});case Oi.code:throw new Oi(d);case Mo.code:throw new Mo(d);case vi.code:throw new vi(d);case Fo.code:throw new Fo(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 Bi.code:throw new Bi(d);case zo.code:throw new zo(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 Ci.code:throw new Ci(d);case 5e3:throw new vi(d);default:throw h instanceof H?h:new AS(d)}}},{delay:({count:h,error:d})=>{var m;if(d&&d instanceof wi){const g=(m=d==null?void 0:d.headers)==null?void 0:m.get("Retry-After");if(g!=null&&g.match(/\d/))return Number.parseInt(g)*1e3}return~~(1<<h)*o},retryCount:a,shouldRetry:({error:h})=>YA(h)}),{enabled:s,id:u})}}function YA(t){return"code"in t&&typeof t.code=="number"?t.code===-1||t.code===Oi.code||t.code===Ns.code:t instanceof wi&&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 Gg({key:t,methods:e,name:r,request:n,retryCount:s=3,retryDelay:i=150,timeout:o,type:a},c){const l=Vg();return{config:{key:t,methods:e,name:r,request:n,retryCount:s,retryDelay:i,timeout:o,type:a},request:XA(n,{methods:e,retryCount:s,retryDelay:i,uid:l}),value:c}}function Cp(t,e={}){const{key:r="custom",methods:n,name:s="Custom Provider",retryDelay:i}=e;return({retryCount:o})=>Gg({key:r,methods:n,name:s,request:t.request.bind(t),retryCount:e.retryCount??o,retryDelay:i,type:"custom"})}class JA extends H{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}function QA(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 ex(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const $p=ex();function tx(t,e={}){return{async request(r){var f;const{body:n,onRequest:s=e.onRequest,onResponse:i=e.onResponse,timeout:o=e.timeout??1e4}=r,a={...e.fetchOptions??{},...r.fetchOptions??{}},{headers:c,method:l,signal:u}=a;try{const h=await QA(async({signal:m})=>{const g={...a,body:Array.isArray(n)?Je(n.map(E=>({jsonrpc:"2.0",id:E.id??$p.take(),...E}))):Je({jsonrpc:"2.0",id:n.id??$p.take(),...n}),headers:{"Content-Type":"application/json",...c},method:l||"POST",signal:u||(o>0?m:null)},v=new Request(t,g),S=await(s==null?void 0:s(v,g))??{...g,url:t};return await fetch(S.url??t,S)},{errorInstance:new mp({body:n,url:t}),timeout:o,signal:!0});i&&await i(h);let d;if((f=h.headers.get("Content-Type"))!=null&&f.startsWith("application/json"))d=await h.json();else{d=await h.text();try{d=JSON.parse(d||"{}")}catch(m){if(h.ok)throw m;d={error:d}}}if(!h.ok)throw new wi({body:n,details:Je(d.error)||h.statusText,headers:h.headers,status:h.status,url:t});return d}catch(h){throw h instanceof wi||h instanceof mp?h:new wi({body:n,cause:h,url:t})}}}}function Wg(t,e={}){const{batch:r,fetchOptions:n,key:s="http",methods:i,name:o="HTTP JSON-RPC",onFetchRequest:a,onFetchResponse:c,retryDelay:l,raw:u}=e;return({chain:f,retryCount:h,timeout:d})=>{const{batchSize:m=1e3,wait:g=0}=typeof r=="object"?r:{},v=e.retryCount??h,S=d??e.timeout??1e4,_=f==null?void 0:f.rpcUrls.default.http[0];if(!_)throw new JA;const E=tx(_,{fetchOptions:n,onRequest:a,onResponse:c,timeout:S});return Gg({key:s,methods:i,name:o,async request({method:x,params:O}){const P={method:x,params:O},{schedule:$}=$g({id:_,wait:g,shouldSplitBatch(W){return W.length>m},fn:W=>E.request({body:W}),sort:(W,K)=>W.id-K.id}),z=async W=>r?$(W):[await E.request({body:W})],[{error:C,result:Y}]=await z(P);if(u)return{error:C,result:Y};if(C)throw new $d({body:P,error:C,url:_});return Y},retryCount:v,retryDelay:l,timeout:S,type:"http"},{fetchOptions:n,url:_})}}function eh(t){var r,n,s,i,o,a;if(!(t instanceof H))return!1;const e=t.walk(c=>c instanceof Sf);return e instanceof Sf?((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 rx(t){const{abi:e,data:r}=t,n=Rs(r,0,4),s=e.find(i=>i.type==="function"&&n===ua(_r(i)));if(!s)throw new G2(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:s.name,args:"inputs"in s&&s.inputs&&s.inputs.length>0?fa(s.inputs,Rs(r,4)):void 0}}const Bu="/docs/contract/encodeErrorResult";function Rp(t){const{abi:e,errorName:r,args:n}=t;let s=e[0];if(r){const c=Ks({abi:e,args:n,name:r});if(!c)throw new rp(r,{docsPath:Bu});s=c}if(s.type!=="error")throw new rp(void 0,{docsPath:Bu});const i=_r(s),o=ua(i);let a="0x";if(n&&n.length>0){if(!s.inputs)throw new V2(s.name,{docsPath:Bu});a=On(s.inputs,n)}return Br([o,a])}const Cu="/docs/contract/encodeFunctionResult";function nx(t){const{abi:e,functionName:r,result:n}=t;let s=e[0];if(r){const o=Ks({abi:e,name:r});if(!o)throw new Ii(r,{docsPath:Cu});s=o}if(s.type!=="function")throw new Ii(void 0,{docsPath:Cu});if(!s.outputs)throw new g0(s.name,{docsPath:Cu});const i=(()=>{if(s.outputs.length===0)return[];if(s.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new b0(n)})();return On(s.outputs,i)}const ga="x-batch-gateway:true";async function Kg(t){const{data:e,ccipRequest:r}=t,{args:[n]}=rx({abi:Rf,data:e}),s=[],i=[];return await Promise.all(n.map(async(o,a)=>{try{i[a]=o.urls.includes(ga)?await Kg({data:o.data,ccipRequest:r}):await r(o),s[a]=!1}catch(c){s[a]=!0,i[a]=sx(c)}})),nx({abi:Rf,functionName:"query",result:[s,i]})}function sx(t){return t.name==="HttpRequestError"&&t.status?Rp({abi:Rf,errorName:"HttpError",args:[t.status,t.shortMessage]}):Rp({abi:[G0],errorName:"Error",args:["shortMessage"in t?t.shortMessage:t.message]})}function Zg(t){if(t.length!==66||t.indexOf("[")!==0||t.indexOf("]")!==65)return null;const e=`0x${t.slice(1,65)}`;return Tr(e)?e:null}function Ff(t){let e=new Uint8Array(32).fill(0);if(!t)return Qe(e);const r=t.split(".");for(let n=r.length-1;n>=0;n-=1){const s=Zg(r[n]),i=s?Hi(s):ft(Ts(r[n]),"bytes");e=ft(Kt([e,i]),"bytes")}return Qe(e)}function ix(t){return`[${t.slice(2)}]`}function ox(t){const e=new Uint8Array(32).fill(0);return t?Zg(t)||ft(Ts(t)):Qe(e)}function th(t){const e=t.replace(/^\.|\.$/gm,"");if(e.length===0)return new Uint8Array(1);const r=new Uint8Array(Ts(e).byteLength+2);let n=0;const s=e.split(".");for(let i=0;i<s.length;i++){let o=Ts(s[i]);o.byteLength>255&&(o=Ts(ix(ox(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 ax(t,e){const{blockNumber:r,blockTag:n,coinType:s,name:i,gatewayUrls:o,strict:a}=e,{chain:c}=t,l=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return qi({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),u=c==null?void 0:c.ensTlds;if(u&&!u.some(h=>i.endsWith(h)))return null;const f=s!=null?[Ff(i),BigInt(s)]:[Ff(i)];try{const h=hr({abi:Ip,functionName:"addr",args:f}),d={address:l,abi:Pg,functionName:"resolveWithGateways",args:[Ot(th(i)),h,o??[ga]],blockNumber:r,blockTag:n},g=await ae(t,Yr,"readContract")(d);if(g[0]==="0x")return null;const v=Xs({abi:Ip,args:f,functionName:"addr",data:g[0]});return v==="0x"||ur(v)==="0x00"?null:v}catch(h){if(a)throw h;if(eh(h))return null;throw h}}class cx extends H{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 Qi extends H{constructor({reason:e}){super(`ENS NFT avatar URI is invalid. ${e}`,{name:"EnsAvatarInvalidNftUriError"})}}class rh extends H{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 ux extends H{constructor({namespace:e}){super(`ENS NFT avatar namespace "${e}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const lx=/(?<protocol>https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,fx=/^(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>\/.*)?$/,dx=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,hx=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function px(t){try{const e=await fetch(t,{method:"HEAD"});if(e.status===200){const r=e.headers.get("content-type");return r==null?void 0:r.startsWith("image/")}return!1}catch(e){return typeof e=="object"&&typeof e.response<"u"||!globalThis.hasOwnProperty("Image")?!1:new Promise(r=>{const n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=t})}}function Np(t,e){return t?t.endsWith("/")?t.slice(0,-1):t:e}function Xg({uri:t,gatewayUrls:e}){const r=dx.test(t);if(r)return{uri:t,isOnChain:!0,isEncoded:r};const n=Np(e==null?void 0:e.ipfs,"https://ipfs.io"),s=Np(e==null?void 0:e.arweave,"https://arweave.net"),i=t.match(lx),{protocol:o,subpath:a,target:c,subtarget:l=""}=(i==null?void 0:i.groups)||{},u=o==="ipns:/"||a==="ipns/",f=o==="ipfs:/"||a==="ipfs/"||fx.test(t);if(t.startsWith("http")&&!u&&!f){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((u||f)&&c)return{uri:`${n}/${u?"ipns":"ipfs"}/${c}${l}`,isOnChain:!1,isEncoded:!1};if(o==="ar:/"&&c)return{uri:`${s}/${c}${l||""}`,isOnChain:!1,isEncoded:!1};let h=t.replace(hx,"");if(h.startsWith("<svg")&&(h=`data:image/svg+xml;base64,${btoa(h)}`),h.startsWith("data:")||h.startsWith("{"))return{uri:h,isOnChain:!0,isEncoded:!1};throw new rh({uri:t})}function Yg(t){if(typeof t!="object"||!("image"in t)&&!("image_url"in t)&&!("image_data"in t))throw new cx({data:t});return t.image||t.image_url||t.image_data}async function yx({gatewayUrls:t,uri:e}){try{const r=await fetch(e).then(s=>s.json());return await nh({gatewayUrls:t,uri:Yg(r)})}catch{throw new rh({uri:e})}}async function nh({gatewayUrls:t,uri:e}){const{uri:r,isOnChain:n}=Xg({uri:e,gatewayUrls:t});if(n||await px(r))return r;throw new rh({uri:e})}function mx(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 Qi({reason:"Only EIP-155 supported"});if(!o)throw new Qi({reason:"Chain ID not found"});if(!c)throw new Qi({reason:"Contract address not found"});if(!s)throw new Qi({reason:"Token ID not found"});if(!a)throw new Qi({reason:"ERC namespace not found"});return{chainID:Number.parseInt(o),namespace:a.toLowerCase(),contractAddress:c,tokenID:s}}async function gx(t,{nft:e}){if(e.namespace==="erc721")return Yr(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 Yr(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 ux({namespace:e.namespace})}async function bx(t,{gatewayUrls:e,record:r}){return/eip155:/i.test(r)?wx(t,{gatewayUrls:e,record:r}):nh({uri:r,gatewayUrls:e})}async function wx(t,{gatewayUrls:e,record:r}){const n=mx(r),s=await gx(t,{nft:n}),{uri:i,isOnChain:o,isEncoded:a}=Xg({uri:s,gatewayUrls:e});if(o&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){const l=a?atob(i.replace("data:application/json;base64,","")):i,u=JSON.parse(l);return nh({uri:Yg(u),gatewayUrls:e})}let c=n.tokenID;return n.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),yx({gatewayUrls:e,uri:i.replace(/(?:0x)?{id}/,c)})}async function Jg(t,e){const{blockNumber:r,blockTag:n,key:s,name:i,gatewayUrls:o,strict:a}=e,{chain:c}=t,l=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return qi({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),u=c==null?void 0:c.ensTlds;if(u&&!u.some(f=>i.endsWith(f)))return null;try{const f={address:l,abi:Pg,args:[Ot(th(i)),hr({abi:Tp,functionName:"text",args:[Ff(i),s]}),o??[ga]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},d=await ae(t,Yr,"readContract")(f);if(d[0]==="0x")return null;const m=Xs({abi:Tp,functionName:"text",data:d[0]});return m===""?null:m}catch(f){if(a)throw f;if(eh(f))return null;throw f}}async function vx(t,{blockNumber:e,blockTag:r,assetGatewayUrls:n,name:s,gatewayUrls:i,strict:o,universalResolverAddress:a}){const c=await ae(t,Jg,"getEnsText")({blockNumber:e,blockTag:r,key:"avatar",name:s,universalResolverAddress:a,gatewayUrls:i,strict:o});if(!c)return null;try{return await bx(t,{record:c,gatewayUrls:n})}catch{return null}}async function Ex(t,e){const{address:r,blockNumber:n,blockTag:s,coinType:i=60n,gatewayUrls:o,strict:a}=e,{chain:c}=t,l=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return qi({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{const u={address:l,abi:TA,args:[r,i,o??[ga]],functionName:"reverseWithGateways",blockNumber:n,blockTag:s},f=ae(t,Yr,"readContract"),[h]=await f(u);return h||null}catch(u){if(a)throw u;if(eh(u))return null;throw u}}async function Sx(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 qi({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),a=i==null?void 0:i.ensTlds;if(a&&!a.some(l=>s.endsWith(l)))throw new Error(`${s} is not a valid ENS TLD (${a==null?void 0:a.join(", ")}) for chain "${i.name}" (id: ${i.id}).`);const[c]=await ae(t,Yr,"readContract")({address:o,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[Ot(th(s))],blockNumber:r,blockTag:n});return c}async function Qg(t,e){var v,S,_;const{account:r=t.account,blockNumber:n,blockTag:s="latest",blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:l,maxFeePerGas:u,maxPriorityFeePerGas:f,to:h,value:d,...m}=e,g=r?We(r):void 0;try{Zs(e);const x=(typeof n=="bigint"?X(n):void 0)||s,O=(_=(S=(v=t.chain)==null?void 0:v.formatters)==null?void 0:S.transactionRequest)==null?void 0:_.format,$=(O||zi)({...jc(m,{format:O}),from:g==null?void 0:g.address,blobs:i,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:l,maxFeePerGas:u,maxPriorityFeePerGas:f,to:h,value:d}),z=await t.request({method:"eth_createAccessList",params:[$,x]});return{accessList:z.accessList,gasUsed:BigInt(z.gasUsed)}}catch(E){throw Cg(E,{...e,account:g,chain:t.chain})}}async function Ax(t){const e=Nc(t,{method:"eth_newBlockFilter"}),r=await t.request({method:"eth_newBlockFilter"});return{id:r,request:e(r),type:"block"}}async function eb(t,{address:e,args:r,event:n,events:s,fromBlock:i,strict:o,toBlock:a}={}){const c=s??(n?[n]:void 0),l=Nc(t,{method:"eth_newFilter"});let u=[];c&&(u=[c.flatMap(d=>la({abi:[d],eventName:d.name,args:r}))],n&&(u=u[0]));const f=await t.request({method:"eth_newFilter",params:[{address:e,fromBlock:typeof i=="bigint"?X(i):i,toBlock:typeof a=="bigint"?X(a):a,...u.length?{topics:u}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:i,id:f,request:l(f),strict:!!o,toBlock:a,type:"event"}}async function tb(t){const e=Nc(t,{method:"eth_newPendingTransactionFilter"}),r=await t.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:e(r),type:"transaction"}}async function xx(t){const e=await t.request({method:"eth_blobBaseFee"});return BigInt(e)}async function kx(t,{blockHash:e,blockNumber:r,blockTag:n="latest"}={}){const s=r!==void 0?X(r):void 0;let i;return e?i=await t.request({method:"eth_getBlockTransactionCountByHash",params:[e]},{dedupe:!0}):i=await t.request({method:"eth_getBlockTransactionCountByNumber",params:[s||n]},{dedupe:!!s}),lr(i)}async function Up(t,{address:e,blockNumber:r,blockTag:n="latest"}){const s=r!==void 0?X(r):void 0,i=await t.request({method:"eth_getCode",params:[e,s||n]},{dedupe:!!s});if(i!=="0x")return i}class _x extends H{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 Tx(t,e){const{address:r,factory:n,factoryData:s}=e;try{const[i,o,a,c,l,u,f]=await ae(t,Yr,"readContract")({abi:Ix,address:r,functionName:"eip712Domain",factory:n,factoryData:s});return{domain:{name:o,version:a,chainId:Number(c),verifyingContract:l,salt:u},extensions:f,fields:i}}catch(i){const o=i;throw o.name==="ContractFunctionExecutionError"&&o.cause.name==="ContractFunctionZeroDataError"?new _x({address:r}):o}}const Ix=[{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 Px(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 Ox(t,{blockCount:e,blockNumber:r,blockTag:n="latest",rewardPercentiles:s}){const i=typeof r=="bigint"?X(r):void 0,o=await t.request({method:"eth_feeHistory",params:[X(e),i||n,s]},{dedupe:!!i});return Px(o)}async function Bx(t,{filter:e}){const r=e.strict??!1,s=(await e.request({method:"eth_getFilterLogs",params:[e.id]})).map(i=>An(i));return e.abi?Gd({abi:e.abi,logs:s,strict:r}):s}function ht(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}class Cx extends H{constructor({domain:e}){super(`Invalid domain "${Je(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class $x extends H{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 Rx extends H{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function Nx(t){const{domain:e={},message:r,primaryType:n}=t,s={EIP712Domain:ab({domain:e}),...t.types};ob({domain:e,message:r,primaryType:n,types:s});const i=["0x1901"];return e&&i.push(Ux({domain:e,types:s})),n!=="EIP712Domain"&&i.push(rb({data:r,primaryType:n,types:s})),ft(Kt(i))}function Ux({domain:t,types:e}){return rb({data:t,primaryType:"EIP712Domain",types:e})}function rb({data:t,primaryType:e,types:r}){const n=nb({data:t,primaryType:e,types:r});return ft(n)}function nb({data:t,primaryType:e,types:r}){const n=[{type:"bytes32"}],s=[Mx({primaryType:e,types:r})];for(const i of r[e]){const[o,a]=ib({types:r,name:i.name,type:i.type,value:t[i.name]});n.push(o),s.push(a)}return On(n,s)}function Mx({primaryType:t,types:e}){const r=Ot(Fx({primaryType:t,types:e}));return ft(r)}function Fx({primaryType:t,types:e}){let r="";const n=sb({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 sb({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])sb({primaryType:i.type,types:e},r);return r}function ib({types:t,name:e,type:r,value:n}){if(t[r]!==void 0)return[{type:"bytes32"},ft(nb({data:n,primaryType:r,types:t}))];if(r==="bytes")return n=`0x${(n.length%2?"0":"")+n.slice(2)}`,[{type:"bytes32"},ft(n)];if(r==="string")return[{type:"bytes32"},ft(Ot(n))];if(r.lastIndexOf("]")===r.length-1){const s=r.slice(0,r.lastIndexOf("[")),i=n.map(o=>ib({name:e,type:s,types:t,value:o}));return[{type:"bytes32"},ft(On(i.map(([o])=>o),i.map(([,o])=>o)))]}return[{type:r},n]}function jx(t){const{domain:e,message:r,primaryType:n,types:s}=t,i=(c,l)=>{const u={...l};for(const f of c){const{name:h,type:d}=f;d==="address"&&(u[h]=u[h].toLowerCase())}return u},o=s.EIP712Domain?e?i(s.EIP712Domain,e):{}:{},a=(()=>{if(n!=="EIP712Domain")return i(s[n],r)})();return Je({domain:o,message:a,primaryType:n,types:s})}function ob(t){const{domain:e,message:r,primaryType:n,types:s}=t,i=(o,a)=>{for(const c of o){const{name:l,type:u}=c,f=a[l],h=u.match(V0);if(h&&(typeof f=="number"||typeof f=="bigint")){const[g,v,S]=h;X(f,{signed:v==="int",size:Number.parseInt(S)/8})}if(u==="address"&&typeof f=="string"&&!ot(f))throw new Ct({address:f});const d=u.match(ME);if(d){const[g,v]=d;if(v&&Le(f)!==Number.parseInt(v))throw new K2({expectedSize:Number.parseInt(v),givenSize:Le(f)})}const m=s[u];m&&(Lx(u),i(m,f))}};if(s.EIP712Domain&&e){if(typeof e!="object")throw new Cx({domain:e});i(s.EIP712Domain,e)}if(n!=="EIP712Domain")if(s[n])i(s[n],r);else throw new $x({primaryType:n,types:s})}function ab({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 Lx(t){if(t==="address"||t==="bool"||t==="string"||t.startsWith("bytes")||t.startsWith("uint")||t.startsWith("int"))throw new Rx({type:t})}function Dx(t){const{authorizationList:e}=t;if(e)for(const r of e){const{chainId:n}=r,s=r.address;if(!ot(s))throw new Ct({address:s});if(n<0)throw new zc({chainId:n})}sh(t)}function Hx(t){const{blobVersionedHashes:e}=t;if(e){if(e.length===0)throw new yg;for(const r of e){const n=Le(r),s=lr(Rs(r,0,1));if(n!==32)throw new QS({hash:r,size:n});if(s!==pg)throw new eA({hash:r,version:s})}}sh(t)}function sh(t){const{chainId:e,maxPriorityFeePerGas:r,maxFeePerGas:n,to:s}=t;if(e<=0)throw new zc({chainId:e});if(s&&!ot(s))throw new Ct({address:s});if(n&&n>Lc)throw new Fs({maxFeePerGas:n});if(r&&n&&r>n)throw new Ko({maxFeePerGas:n,maxPriorityFeePerGas:r})}function zx(t){const{chainId:e,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=t;if(e<=0)throw new zc({chainId:e});if(i&&!ot(i))throw new Ct({address:i});if(r||s)throw new H("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Lc)throw new Fs({maxFeePerGas:n})}function Vx(t){const{chainId:e,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=t;if(i&&!ot(i))throw new Ct({address:i});if(typeof e<"u"&&e<=0)throw new zc({chainId:e});if(r||s)throw new H("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Lc)throw new Fs({maxFeePerGas:n})}function Kc(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 yS({storageKey:s[i]});if(!ot(n,{strict:!1}))throw new Ct({address:n});e.push([n,s])}return e}function qx(t,e){const r=gg(t);return r==="eip1559"?Kx(t,e):r==="eip2930"?Zx(t,e):r==="eip4844"?Wx(t,e):r==="eip7702"?Gx(t,e):Xx(t,e)}function Gx(t,e){const{authorizationList:r,chainId:n,gas:s,nonce:i,to:o,value:a,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:u,data:f}=t;Dx(t);const h=Kc(u),d=Yx(r);return Br(["0x04",is([X(n),i?X(i):"0x",l?X(l):"0x",c?X(c):"0x",s?X(s):"0x",o??"0x",a?X(a):"0x",f??"0x",h,d,...ba(t,e)])])}function Wx(t,e){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:u,data:f}=t;Hx(t);let h=t.blobVersionedHashes,d=t.sidecars;if(t.blobs&&(typeof h>"u"||typeof d>"u")){const E=typeof t.blobs[0]=="string"?t.blobs:t.blobs.map(P=>Qe(P)),x=t.kzg,O=Ld({blobs:E,kzg:x});if(typeof h>"u"&&(h=fg({commitments:O})),typeof d>"u"){const P=Dd({blobs:E,commitments:O,kzg:x});d=mg({blobs:E,commitments:O,proofs:P})}}const m=Kc(u),g=[X(r),s?X(s):"0x",l?X(l):"0x",c?X(c):"0x",n?X(n):"0x",i??"0x",o?X(o):"0x",f??"0x",m,a?X(a):"0x",h??[],...ba(t,e)],v=[],S=[],_=[];if(d)for(let E=0;E<d.length;E++){const{blob:x,commitment:O,proof:P}=d[E];v.push(x),S.push(O),_.push(P)}return Br(["0x03",is(d?[g,v,S,_]:g)])}function Kx(t,e){const{chainId:r,gas:n,nonce:s,to:i,value:o,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:l,data:u}=t;sh(t);const f=Kc(l),h=[X(r),s?X(s):"0x",c?X(c):"0x",a?X(a):"0x",n?X(n):"0x",i??"0x",o?X(o):"0x",u??"0x",f,...ba(t,e)];return Br(["0x02",is(h)])}function Zx(t,e){const{chainId:r,gas:n,data:s,nonce:i,to:o,value:a,accessList:c,gasPrice:l}=t;zx(t);const u=Kc(c),f=[X(r),i?X(i):"0x",l?X(l):"0x",n?X(n):"0x",o??"0x",a?X(a):"0x",s??"0x",u,...ba(t,e)];return Br(["0x01",is(f)])}function Xx(t,e){const{chainId:r=0,gas:n,data:s,nonce:i,to:o,value:a,gasPrice:c}=t;Vx(t);let l=[i?X(i):"0x",c?X(c):"0x",n?X(n):"0x",o??"0x",a?X(a):"0x",s??"0x"];if(e){const u=(()=>{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 hS({v:e.v});return d})(),f=ur(e.r),h=ur(e.s);l=[...l,X(u),f==="0x00"?"0x":f,h==="0x00"?"0x":h]}else r>0&&(l=[...l,X(r),"0x","0x"]);return is(l)}function ba(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=ur(r.r),o=ur(r.s);return[typeof s=="number"?s?X(1):"0x":n===0n?"0x":n===1n?X(1):n===27n?"0x":X(1),i==="0x00"?"0x":i,o==="0x00"?"0x":o]}function Yx(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?Ot(n):"0x",o,s?Ot(s):"0x",...ba({},i)])}return e}const Jx=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),cb=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),Qx=cb.map(t=>(9*t+5)%16),ub=(()=>{const r=[[cb],[Qx]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>Jx[i]));return r})(),lb=ub[0],fb=ub[1],db=[[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)),e6=lb.map((t,e)=>t.map(r=>db[e][r])),t6=fb.map((t,e)=>t.map(r=>db[e][r])),r6=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),n6=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Mp(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 Na=new Uint32Array(16);let hb=class extends ag{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)Na[d]=e.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,o=i,a=this.h2|0,c=a,l=this.h3|0,u=l,f=this.h4|0,h=f;for(let d=0;d<5;d++){const m=4-d,g=r6[d],v=n6[d],S=lb[d],_=fb[d],E=e6[d],x=t6[d];for(let O=0;O<16;O++){const P=Oa(n+Mp(d,i,a,l)+Na[S[O]]+g,E[O])+f|0;n=f,f=l,l=Oa(a,10)|0,a=i,i=P}for(let O=0;O<16;O++){const P=Oa(s+Mp(m,o,c,u)+Na[_[O]]+v,x[O])+h|0;s=h,h=u,u=Oa(c,10)|0,c=o,o=P}}this.set(this.h1+a+u|0,this.h2+l+h|0,this.h3+f+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){Pr(Na)}destroy(){this.destroyed=!0,Pr(this.buffer),this.set(0,0,0,0,0)}};const s6=Cc(()=>new hb),i6=hb,o6=s6,a6=Object.freeze(Object.defineProperty({__proto__:null,RIPEMD160:i6,ripemd160:o6},Symbol.toStringTag,{value:"Module"})),c6=`Ethereum Signed Message:
43
- `;function u6(t){const e=typeof t=="string"?Pi(t):typeof t.raw=="string"?t.raw:Qe(t.raw),r=Pi(`${c6}${Le(e)}`);return Kt([r,e])}function pb(t,e){return ft(u6(t),e)}const yb="0x6492649264926492649264926492649264926492649264926492649264926492";function l6(t){return pc(t,-32)===yb}function f6(t){const{address:e,data:r,signature:n,to:s="hex"}=t,i=Br([On([{type:"address"},{type:"bytes"},{type:"bytes"}],[e,r,n]),yb]);return s==="hex"?i:Ir(i)}function d6(t){return t.map(e=>({...e,value:BigInt(e.value)}))}function h6(t){return{...t,balance:t.balance?BigInt(t.balance):void 0,nonce:t.nonce?lr(t.nonce):void 0,storageProof:t.storageProof?d6(t.storageProof):void 0}}async function p6(t,{address:e,blockNumber:r,blockTag:n,storageKeys:s}){const i=n??"latest",o=r!==void 0?X(r):void 0,a=await t.request({method:"eth_getProof",params:[e,s,o||i]});return h6(a)}async function y6(t,{address:e,blockNumber:r,blockTag:n="latest",slot:s}){const i=r!==void 0?X(r):void 0;return await t.request({method:"eth_getStorageAt",params:[e,s,i||n]})}async function ih(t,{blockHash:e,blockNumber:r,blockTag:n,hash:s,index:i}){var u,f,h;const o=n||"latest",a=r!==void 0?X(r):void 0;let c=null;if(s?c=await t.request({method:"eth_getTransactionByHash",params:[s]},{dedupe:!0}):e?c=await t.request({method:"eth_getTransactionByBlockHashAndIndex",params:[e,X(i)]},{dedupe:!0}):c=await t.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[a||o,X(i)]},{dedupe:!!a}),!c)throw new Y0({blockHash:e,blockNumber:r,blockTag:o,hash:s,index:i});return(((h=(f=(u=t.chain)==null?void 0:u.formatters)==null?void 0:f.transaction)==null?void 0:h.format)||Dc)(c)}async function m6(t,{hash:e,transactionReceipt:r}){const[n,s]=await Promise.all([ae(t,ma,"getBlockNumber")({}),e?ae(t,ih,"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 ec(t,{hash:e}){var s,i,o;const r=await t.request({method:"eth_getTransactionReceipt",params:[e]},{dedupe:!0});if(!r)throw new J0({hash:e});return(((o=(i=(s=t.chain)==null?void 0:s.formatters)==null?void 0:i.transactionReceipt)==null?void 0:o.format)||Lg)(r)}async function g6(t,e){var _;const{account:r,authorizationList:n,allowFailure:s=!0,batchSize:i,blockNumber:o,blockTag:a,multicallAddress:c,stateOverride:l}=e,u=e.contracts,f=i??(typeof((_=t.batch)==null?void 0:_.multicall)=="object"&&t.batch.multicall.batchSize||1024);let h=c;if(!h){if(!t.chain)throw new Error("client chain not configured. multicallAddress is required.");h=qi({blockNumber:o,chain:t.chain,contract:"multicall3"})}const d=[[]];let m=0,g=0;for(let E=0;E<u.length;E++){const{abi:x,address:O,args:P,functionName:$}=u[E];try{const z=hr({abi:x,args:P,functionName:$});g+=(z.length-2)/2,f>0&&g>f&&d[m].length>0&&(m++,g=(z.length-2)/2,d[m]=[]),d[m]=[...d[m],{allowFailure:!0,callData:z,target:O}]}catch(z){const C=Ms(z,{abi:x,address:O,args:P,docsPath:"/docs/contract/multicall",functionName:$,sender:r});if(!s)throw C;d[m]=[...d[m],{allowFailure:!0,callData:"0x",target:O}]}}const v=await Promise.allSettled(d.map(E=>ae(t,Yr,"readContract")({abi:$f,account:r,address:h,args:[E],authorizationList:n,blockNumber:o,blockTag:a,functionName:"aggregate3",stateOverride:l}))),S=[];for(let E=0;E<v.length;E++){const x=v[E];if(x.status==="rejected"){if(!s)throw x.reason;for(let P=0;P<d[E].length;P++)S.push({status:"failure",error:x.reason,result:void 0});continue}const O=x.value;for(let P=0;P<O.length;P++){const{returnData:$,success:z}=O[P],{callData:C}=d[E][P],{abi:Y,address:W,functionName:K,args:U}=u[S.length];try{if(C==="0x")throw new aa;if(!z)throw new Mc({data:$});const N=Xs({abi:Y,args:U,data:$,functionName:K});S.push(s?{result:N,status:"success"}:N)}catch(N){const F=Ms(N,{abi:Y,address:W,args:U,docsPath:"/docs/contract/multicall",functionName:K});if(!s)throw F;S.push({error:F,result:void 0,status:"failure"})}}}if(S.length!==u.length)throw new H("multicall results mismatch");return S}async function jf(t,e){const{blockNumber:r,blockTag:n=t.experimental_blockTag??"latest",blocks:s,returnFullTransactions:i,traceTransfers:o,validation:a}=e;try{const c=[];for(const h of s){const d=h.blockOverrides?Tg(h.blockOverrides):void 0,m=h.calls.map(v=>{const S=v,_=S.account?We(S.account):void 0,E=S.abi?hr(S):S.data,x={...S,data:S.dataSuffix?Kt([E||"0x",S.dataSuffix]):E,from:S.from??(_==null?void 0:_.address)};return Zs(x),zi(x)}),g=h.stateOverrides?Nd(h.stateOverrides):void 0;c.push({blockOverrides:d,calls:m,stateOverrides:g})}const u=(typeof r=="bigint"?X(r):void 0)||n;return(await t.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:i,traceTransfers:o,validation:a},u]})).map((h,d)=>({...Md(h),calls:h.calls.map((m,g)=>{var Y,W;const{abi:v,args:S,functionName:_,to:E}=s[d].calls[g],x=((Y=m.error)==null?void 0:Y.data)??m.returnData,O=BigInt(m.gasUsed),P=(W=m.logs)==null?void 0:W.map(K=>An(K)),$=m.status==="0x1"?"success":"failure",z=v&&$==="success"&&x!=="0x"?Xs({abi:v,data:x,functionName:_}):null,C=(()=>{var U;if($==="success")return;let K;if(((U=m.error)==null?void 0:U.data)==="0x"?K=new aa:m.error&&(K=new Mc(m.error)),!!K)return Ms(K,{abi:v??[],address:E??"0x",args:S,functionName:_??"<unknown>"})})();return{data:x,gasUsed:O,logs:P,status:$,...$==="success"?{result:z}:{error:C}}})}))}catch(c){const l=c,u=Fc(l,{});throw u instanceof ha?l:u}}const b6="1.0.9";class wt extends Error{constructor(e,r={}){var o;const n=r.cause instanceof wt?r.cause.details:(o=r.cause)!=null&&o.message?r.cause.message:r.details,s=r.cause instanceof wt&&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@${b6}`].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 Bn(t,e){const r=t.exec(e);return r==null?void 0:r.groups}const mb=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,gb=/^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)?$/,bb=/^\(.+?\).*?$/,Fp=/^tuple(?<array>(\[(\d*)\])*)$/;function Lf(t){let e=t.type;if(Fp.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+=Lf(i),s<r-1&&(e+=", ")}const n=Bn(Fp,t.type);return e+=`)${(n==null?void 0:n.array)??""}`,Lf({...t,type:e})}return"indexed"in t&&t.indexed&&(e=`${e} indexed`),t.name?`${e} ${t.name}`:e}function eo(t){let e="";const r=t.length;for(let n=0;n<r;n++){const s=t[n];e+=Lf(s),n!==r-1&&(e+=", ")}return e}function Df(t){var e;return t.type==="function"?`function ${t.name}(${eo(t.inputs)})${t.stateMutability&&t.stateMutability!=="nonpayable"?` ${t.stateMutability}`:""}${(e=t.outputs)!=null&&e.length?` returns (${eo(t.outputs)})`:""}`:t.type==="event"?`event ${t.name}(${eo(t.inputs)})`:t.type==="error"?`error ${t.name}(${eo(t.inputs)})`:t.type==="constructor"?`constructor(${eo(t.inputs)})${t.stateMutability==="payable"?" payable":""}`:t.type==="fallback"?`fallback() external${t.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const wb=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function w6(t){return wb.test(t)}function v6(t){return Bn(wb,t)}const vb=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function E6(t){return vb.test(t)}function S6(t){return Bn(vb,t)}const Eb=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function A6(t){return Eb.test(t)}function x6(t){return Bn(Eb,t)}const Sb=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function Ab(t){return Sb.test(t)}function k6(t){return Bn(Sb,t)}const xb=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function _6(t){return xb.test(t)}function T6(t){return Bn(xb,t)}const kb=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function I6(t){return kb.test(t)}function P6(t){return Bn(kb,t)}const O6=/^receive\(\) external payable$/;function B6(t){return O6.test(t)}const C6=new Set(["indexed"]),Hf=new Set(["calldata","memory","storage"]);class $6 extends wt{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 R6 extends wt{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 N6 extends wt{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 U6 extends wt{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}}class M6 extends wt{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 F6 extends wt{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 j6 extends wt{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 L6 extends wt{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 Wi extends wt{constructor({signature:e,type:r}){super(`Invalid ${r} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}}class D6 extends wt{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}}class H6 extends wt{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 z6 extends wt{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 V6 extends wt{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 q6(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 jp(t,e={}){if(A6(t))return G6(t,e);if(E6(t))return W6(t,e);if(w6(t))return K6(t,e);if(_6(t))return Z6(t,e);if(I6(t))return X6(t);if(B6(t))return{type:"receive",stateMutability:"payable"};throw new D6({signature:t})}function G6(t,e={}){const r=x6(t);if(!r)throw new Wi({signature:t,type:"function"});const n=Sr(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push(Ds(n[a],{modifiers:Hf,structs:e,type:"function"}));const o=[];if(r.returns){const a=Sr(r.returns),c=a.length;for(let l=0;l<c;l++)o.push(Ds(a[l],{modifiers:Hf,structs:e,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:s,outputs:o}}function W6(t,e={}){const r=S6(t);if(!r)throw new Wi({signature:t,type:"event"});const n=Sr(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Ds(n[o],{modifiers:C6,structs:e,type:"event"}));return{name:r.name,type:"event",inputs:s}}function K6(t,e={}){const r=v6(t);if(!r)throw new Wi({signature:t,type:"error"});const n=Sr(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Ds(n[o],{structs:e,type:"error"}));return{name:r.name,type:"error",inputs:s}}function Z6(t,e={}){const r=T6(t);if(!r)throw new Wi({signature:t,type:"constructor"});const n=Sr(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Ds(n[o],{structs:e,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:s}}function X6(t){const e=P6(t);if(!e)throw new Wi({signature:t,type:"fallback"});return{type:"fallback",stateMutability:e.stateMutability??"nonpayable"}}const Y6=/^(?<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$_]*))?$/,J6=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,Q6=/^u?int$/;function Ds(t,e){var f,h;const r=q6(t,e==null?void 0:e.type,e==null?void 0:e.structs);if($u.has(r))return $u.get(r);const n=bb.test(t),s=Bn(n?J6:Y6,t);if(!s)throw new U6({param:t});if(s.name&&tk(s.name))throw new M6({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,l={};if(n){c="tuple";const d=Sr(s.type),m=[],g=d.length;for(let v=0;v<g;v++)m.push(Ds(d[v],{structs:a}));l={components:m}}else if(s.type in a)c="tuple",l={components:a[s.type]};else if(Q6.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"&&!_b(c))throw new N6({type:c});if(s.modifier){if(!((h=(f=e==null?void 0:e.modifiers)==null?void 0:f.has)!=null&&h.call(f,s.modifier)))throw new F6({param:t,type:e==null?void 0:e.type,modifier:s.modifier});if(Hf.has(s.modifier)&&!rk(c,!!s.array))throw new j6({param:t,type:e==null?void 0:e.type,modifier:s.modifier})}const u={type:`${c}${s.array??""}`,...i,...o,...l};return $u.set(r,u),u}function Sr(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?Sr(a,[...e,r.trim()]):Sr(a,e,`${r}${o}`,n);case"(":return Sr(a,e,`${r}${o}`,n+1);case")":return Sr(a,e,`${r}${o}`,n-1);default:return Sr(a,e,`${r}${o}`,n)}}if(r==="")return e;if(n!==0)throw new V6({current:r,depth:n});return e.push(r.trim()),e}function _b(t){return t==="address"||t==="bool"||t==="function"||t==="string"||mb.test(t)||gb.test(t)}const ek=/^(?: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 tk(t){return t==="address"||t==="bool"||t==="function"||t==="string"||t==="tuple"||mb.test(t)||gb.test(t)||ek.test(t)}function rk(t,e){return e||t==="bytes"||t==="string"||t==="tuple"}function nk(t){const e={},r=t.length;for(let o=0;o<r;o++){const a=t[o];if(!Ab(a))continue;const c=k6(a);if(!c)throw new Wi({signature:a,type:"struct"});const l=c.properties.split(";"),u=[],f=l.length;for(let h=0;h<f;h++){const m=l[h].trim();if(!m)continue;const g=Ds(m,{type:"struct"});u.push(g)}if(!u.length)throw new H6({signature:a});e[c.name]=u}const n={},s=Object.entries(e),i=s.length;for(let o=0;o<i;o++){const[a,c]=s[o];n[a]=Tb(c,e)}return n}const sk=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function Tb(t,e,r=new Set){const n=[],s=t.length;for(let i=0;i<s;i++){const o=t[i];if(bb.test(o.type))n.push(o);else{const c=Bn(sk,o.type);if(!(c!=null&&c.type))throw new L6({abiParameter:o});const{array:l,type:u}=c;if(u in e){if(r.has(u))throw new z6({type:u});n.push({...o,type:`tuple${l??""}`,components:Tb(e[u]??[],e,new Set([...r,u]))})}else if(_b(u))n.push(o);else throw new R6({type:u})}}return n}function Lp(t){let e;if(typeof t=="string")e=jp(t);else{const r=nk(t),n=t.length;for(let s=0;s<n;s++){const i=t[s];if(!Ab(i)){e=jp(i,r);break}}}if(!e)throw new $6({signature:t});return e}function Ib(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,n=F0(hA(t));return r==="Bytes"?n:xg(n)}class ik 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 ok={checksum:new ik(8192)},Ru=ok.checksum,ak=/^0x[a-fA-F0-9]{40}$/;function Zc(t,e={}){const{strict:r=!0}=e;if(!ak.test(t))throw new Dp({address:t,cause:new uk});if(r){if(t.toLowerCase()===t)return;if(ck(t)!==t)throw new Dp({address:t,cause:new lk})}}function ck(t){if(Ru.has(t))return Ru.get(t);Zc(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=Ib(mA(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 Ru.set(t,s),s}function zf(t,e={}){const{strict:r=!0}=e??{};try{return Zc(t,{strict:r}),!0}catch{return!1}}class Dp extends Ke{constructor({address:e,cause:r}){super(`Address "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class uk extends Ke{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class lk extends Ke{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}function Vf(t){let e=!0,r="",n=0,s="",i=!1;for(let o=0;o<t.length;o++){const a=t[o];if(["(",")",","].includes(a)&&(e=!0),a==="("&&n++,a===")"&&n--,!!e){if(n===0){if(a===" "&&["event","function","error",""].includes(s))s="";else if(s+=a,a===")"){i=!0;break}continue}if(a===" "){t[o-1]!==","&&r!==","&&r!==",("&&(r="",e=!1);continue}s+=a,r+=a}}if(!i)throw new Ke("Unable to normalize signature.");return s}function qf(t,e){const r=typeof t,n=e.type;switch(n){case"address":return zf(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)=>qf(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=>qf(s,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function Pb(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 Pb(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")?zf(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?zf(r[n],{strict:!1}):!1)return o}}function Ob(t,e={}){const{prepare:r=!0}=e,n=Array.isArray(t)||typeof t=="string"?Lp(t):t;return{...n,...r?{hash:yi(n)}:{}}}function fk(t,e,r){const{args:n=[],prepare:s=!0}=r??{},i=AA(e,{strict:!1}),o=t.filter(l=>i?l.type==="function"||l.type==="error"?Bb(l)===Yd(e,0,4):l.type==="event"?yi(l)===e:!1:"name"in l&&l.name===e);if(o.length===0)throw new Gf({name:e});if(o.length===1)return{...o[0],...s?{hash:yi(o[0])}:{}};let a;for(const l of o){if(!("inputs"in l))continue;if(!n||n.length===0){if(!l.inputs||l.inputs.length===0)return{...l,...s?{hash:yi(l)}:{}};continue}if(!l.inputs||l.inputs.length===0||l.inputs.length!==n.length)continue;if(n.every((f,h)=>{const d="inputs"in l&&l.inputs[h];return d?qf(f,d):!1})){if(a&&"inputs"in a&&a.inputs){const f=Pb(l.inputs,a.inputs,n);if(f)throw new hk({abiItem:l,type:f[0]},{abiItem:a,type:f[1]})}a=l}}const c=(()=>{if(a)return a;const[l,...u]=o;return{...l,overloads:u}})();if(!c)throw new Gf({name:e});return{...c,...s?{hash:yi(c)}:{}}}function Bb(t){return Yd(yi(t),0,4)}function dk(t){const e=typeof t=="string"?t:Df(t);return Vf(e)}function yi(t){return typeof t!="string"&&"hash"in t&&t.hash?t.hash:Ib(Xd(dk(t)))}class hk extends Ke{constructor(e,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${e.type}\` in \`${Vf(Df(e.abiItem))}\`, and`,`\`${r.type}\` in \`${Vf(Df(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 Gf extends Ke{constructor({name:e,data:r,type:n="item"}){const s=e?` with name "${e}"`:r?` with data "${r}"`:"";super(`ABI ${n}${s} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}const pk=/^(.*)\[([0-9]*)\]$/,yk=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Cb=/^(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 mk({checksumAddress:t,parameters:e,values:r}){const n=[];for(let s=0;s<e.length;s++)n.push(oh({checksumAddress:t,parameter:e[s],value:r[s]}));return n}function oh({checksumAddress:t=!1,parameter:e,value:r}){const n=e,s=xk(n.type);if(s){const[i,o]=s;return bk(r,{checksumAddress:t,length:i,parameter:{...n,type:o}})}if(n.type==="tuple")return Ak(r,{checksumAddress:t,parameter:n});if(n.type==="address")return gk(r,{checksum:t});if(n.type==="bool")return vk(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){const i=n.type.startsWith("int"),[,,o="256"]=Cb.exec(n.type)??[];return Ek(r,{signed:i,size:Number(o)})}if(n.type.startsWith("bytes"))return wk(r,{type:n.type});if(n.type==="string")return Sk(r);throw new Ub(n.type)}function ah(t){let e=0;for(let i=0;i<t.length;i++){const{dynamic:o,encoded:a}=t[i];o?e+=32:e+=fr(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+=fr(a)):r.push(a)}return Xr(...r,...n)}function gk(t,e){const{checksum:r=!1}=e;return Zc(t,{strict:r}),{dynamic:!1,encoded:js(t.toLowerCase())}}function bk(t,e){const{checksumAddress:r,length:n,parameter:s}=e,i=n===null;if(!Array.isArray(t))throw new _k(t);if(!i&&t.length!==n)throw new kk({expectedLength:n,givenLength:t.length,type:`${s.type}[${n}]`});let o=!1;const a=[];for(let c=0;c<t.length;c++){const l=oh({checksumAddress:r,parameter:s,value:t[c]});l.dynamic&&(o=!0),a.push(l)}if(i||o){const c=ah(a);if(i){const l=It(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?Xr(l,c):l}}if(o)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Xr(...a.map(({encoded:c})=>c))}}function wk(t,{type:e}){const[,r]=e.split("bytes"),n=fr(t);if(!r){let s=t;return n%32!==0&&(s=Ls(s,Math.ceil((t.length-2)/2/32)*32)),{dynamic:!0,encoded:Xr(js(It(n,{size:32})),s)}}if(n!==Number.parseInt(r))throw new Rb({expectedSize:Number.parseInt(r),value:t});return{dynamic:!1,encoded:Ls(t)}}function vk(t){if(typeof t!="boolean")throw new Ke(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:js(Ag(t))}}function Ek(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 kg({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 Sk(t){const e=Xd(t),r=Math.ceil(fr(e)/32),n=[];for(let s=0;s<r;s++)n.push(Ls(Yd(e,s*32,(s+1)*32)));return{dynamic:!0,encoded:Xr(Ls(It(fr(e),{size:32})),...n)}}function Ak(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,l=oh({checksumAddress:r,parameter:a,value:t[c]});i.push(l),l.dynamic&&(s=!0)}return{dynamic:s,encoded:s?ah(i):Xr(...i.map(({encoded:o})=>o))}}function xk(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function $b(t,e,r){const{checksumAddress:n=!1}={};if(t.length!==e.length)throw new Nb({expectedLength:t.length,givenLength:e.length});const s=mk({checksumAddress:n,parameters:t,values:e}),i=ah(s);return i.length===0?"0x":i}function Wf(t,e){if(t.length!==e.length)throw new Nb({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(Wf.encode(s,i))}return Xr(...r)}(function(t){function e(r,n,s=!1){if(r==="address"){const c=n;return Zc(c),js(c.toLowerCase(),s?32:0)}if(r==="string")return Xd(n);if(r==="bytes")return n;if(r==="bool")return js(Ag(n),s?32:1);const i=r.match(Cb);if(i){const[c,l,u="256"]=i,f=Number.parseInt(u)/8;return It(n,{size:s?32:f,signed:l==="int"})}const o=r.match(yk);if(o){const[c,l]=o;if(Number.parseInt(l)!==(n.length-2)/2)throw new Rb({expectedSize:Number.parseInt(l),value:n});return Ls(n,s?32:0)}const a=r.match(pk);if(a&&Array.isArray(n)){const[c,l]=a,u=[];for(let f=0;f<n.length;f++)u.push(e(l,n[f],!0));return u.length===0?"0x":Xr(...u)}throw new Ub(r)}t.encode=e})(Wf||(Wf={}));class kk extends Ke{constructor({expectedLength:e,givenLength:r,type:n}){super(`Array length mismatch for type \`${n}\`. Expected: \`${e}\`. Given: \`${r}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class Rb extends Ke{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${fr(r)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class Nb extends Ke{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${r}`].join(`
45
- `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class _k extends Ke{constructor(e){super(`Value \`${e}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class Ub extends Ke{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}function Tk(t,e){var s;const{bytecode:r,args:n}=e;return Xr(r,(s=t.inputs)!=null&&s.length&&(n!=null&&n.length)?$b(t.inputs,n):"0x")}function Ik(t){return Ob(t)}function Pk(t,...e){const{overloads:r}=t,n=r?Ok([t,...r],t.name,{args:e[0]}):t,s=Bk(n),i=e.length>0?$b(n.inputs,e[0]):void 0;return i?Xr(s,i):s}function si(t,e={}){return Ob(t,e)}function Ok(t,e,r){const n=fk(t,e,r);if(n.type!=="function")throw new Gf({name:e,type:"function"});return n}function Bk(t){return Bb(t)}const Ck="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Ur="0x0000000000000000000000000000000000000000",$k="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function Rk(t,e){const{blockNumber:r,blockTag:n,calls:s,stateOverrides:i,traceAssetChanges:o,traceTransfers:a,validation:c}=e,l=e.account?We(e.account):void 0;if(o&&!l)throw new H("`account` is required when `traceAssetChanges` is true");const u=l?Tk(Ik("constructor(bytes, bytes)"),{bytecode:Og,args:[$k,Pk(si("function getBalance(address)"),[l.address])]}):void 0,f=o?await Promise.all(e.calls.map(async D=>{if(!D.data&&!D.abi)return;const{accessList:T}=await Qg(t,{account:l.address,...D,data:D.abi?hr(D):D.data});return T.map(({address:L,storageKeys:G})=>G.length>0?L:null)})).then(D=>D.flat().filter(Boolean)):[],h=await jf(t,{blockNumber:r,blockTag:n,blocks:[...o?[{calls:[{data:u}],stateOverrides:i},{calls:f.map((D,T)=>({abi:[si("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[l.address],to:D,from:Ur,nonce:T})),stateOverrides:[{address:Ur,nonce:0}]}]:[],{calls:[...s,{}].map(D=>({...D,from:l==null?void 0:l.address})),stateOverrides:i},...o?[{calls:[{data:u}]},{calls:f.map((D,T)=>({abi:[si("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[l.address],to:D,from:Ur,nonce:T})),stateOverrides:[{address:Ur,nonce:0}]},{calls:f.map((D,T)=>({to:D,abi:[si("function decimals() returns (uint256)")],functionName:"decimals",from:Ur,nonce:T})),stateOverrides:[{address:Ur,nonce:0}]},{calls:f.map((D,T)=>({to:D,abi:[si("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:Ur,nonce:T})),stateOverrides:[{address:Ur,nonce:0}]},{calls:f.map((D,T)=>({to:D,abi:[si("function symbol() returns (string)")],functionName:"symbol",from:Ur,nonce:T})),stateOverrides:[{address:Ur,nonce:0}]}]:[]],traceTransfers:a,validation:c}),d=o?h[2]:h[0],[m,g,,v,S,_,E,x]=o?h:[],{calls:O,...P}=d,$=O.slice(0,-1)??[],z=(m==null?void 0:m.calls)??[],C=(g==null?void 0:g.calls)??[],Y=[...z,...C].map(D=>D.status==="success"?at(D.data):null),W=(v==null?void 0:v.calls)??[],K=(S==null?void 0:S.calls)??[],U=[...W,...K].map(D=>D.status==="success"?at(D.data):null),N=((_==null?void 0:_.calls)??[]).map(D=>D.status==="success"?D.result:null),F=((x==null?void 0:x.calls)??[]).map(D=>D.status==="success"?D.result:null),Z=((E==null?void 0:E.calls)??[]).map(D=>D.status==="success"?D.result:null),ee=[];for(const[D,T]of U.entries()){const L=Y[D];if(typeof T!="bigint"||typeof L!="bigint")continue;const G=N[D-1],I=F[D-1],R=Z[D-1],j=D===0?{address:Ck,decimals:18,symbol:"ETH"}:{address:f[D-1],decimals:R||G?Number(G??1):void 0,symbol:I??void 0};ee.some(J=>J.token.address===j.address)||ee.push({token:j,value:{pre:L,post:T,diff:T-L}})}return{assetChanges:ee,block:P,results:$}}class Mb extends Bc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,P0(e);const n=vn(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),Pr(i)}update(e){return ss(this),this.iHash.update(e),this}digestInto(e){ss(this),Zr(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 Fb=(t,e,r)=>new Mb(t,e).update(r).digest();Fb.create=(t,e)=>new Mb(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ch=BigInt(0),Kf=BigInt(1);function mc(t,e=""){if(typeof t!="boolean"){const r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function ws(t,e,r=""){const n=Oc(t),s=t==null?void 0:t.length,i=e!==void 0;if(!n||i&&s!==e){const o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function Ua(t){const e=t.toString(16);return e.length&1?"0"+e:e}function jb(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?ch:BigInt("0x"+t)}function Xc(t){return jb(gi(t))}function Lb(t){return Zr(t),jb(gi(Uint8Array.from(t).reverse()))}function uh(t,e){return hc(t.toString(16).padStart(e*2,"0"))}function Db(t,e){return uh(t,e).reverse()}function $t(t,e,r){let n;if(typeof e=="string")try{n=hc(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Oc(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");return n.length,n}const Nu=t=>typeof t=="bigint"&&ch<=t;function Nk(t,e,r){return Nu(t)&&Nu(e)&&Nu(r)&&e<=t&&t<r}function Uk(t,e,r,n){if(!Nk(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Hb(t){let e;for(e=0;t>ch;t>>=Kf,e+=1);return e}const wa=t=>(Kf<<BigInt(t))-Kf;function Mk(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");const n=d=>new Uint8Array(d),s=d=>Uint8Array.of(d);let i=n(t),o=n(t),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...d)=>r(o,i,...d),u=(d=n(0))=>{o=l(s(0),d),i=l(),d.length!==0&&(o=l(s(1),d),i=l())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0;const m=[];for(;d<e;){i=l();const g=i.slice();m.push(g),d+=i.length}return Wn(...m)};return(d,m)=>{c(),u(d);let g;for(;!(g=m(f()));)u();return c(),g}}function lh(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(s,i,o){const a=t[s];if(o&&a===void 0)return;const c=typeof a;if(c!==i||a===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([s,i])=>n(s,i,!1)),Object.entries(r).forEach(([s,i])=>n(s,i,!0))}function Hp(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 Mt=BigInt(0),Bt=BigInt(1),vs=BigInt(2),zb=BigInt(3),Vb=BigInt(4),qb=BigInt(5),Fk=BigInt(7),Gb=BigInt(8),jk=BigInt(9),Wb=BigInt(16);function mr(t,e){const r=t%e;return r>=Mt?r:e+r}function Qt(t,e,r){let n=t;for(;e-- >Mt;)n*=n,n%=r;return n}function zp(t,e){if(t===Mt)throw new Error("invert: expected non-zero number");if(e<=Mt)throw new Error("invert: expected positive modulus, got "+e);let r=mr(t,e),n=e,s=Mt,i=Bt;for(;r!==Mt;){const a=n/r,c=n%r,l=s-i*a;n=r,r=c,s=i,i=l}if(n!==Bt)throw new Error("invert: does not exist");return mr(s,e)}function fh(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function Kb(t,e){const r=(t.ORDER+Bt)/Vb,n=t.pow(e,r);return fh(t,n,e),n}function Lk(t,e){const r=(t.ORDER-qb)/Gb,n=t.mul(e,vs),s=t.pow(n,r),i=t.mul(e,s),o=t.mul(t.mul(i,vs),s),a=t.mul(i,t.sub(o,t.ONE));return fh(t,a,e),a}function Dk(t){const e=va(t),r=Zb(t),n=r(e,e.neg(e.ONE)),s=r(e,n),i=r(e,e.neg(n)),o=(t+Fk)/Wb;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,n);const f=a.mul(l,s),h=a.mul(l,i),d=a.eql(a.sqr(u),c),m=a.eql(a.sqr(f),c);l=a.cmov(l,u,d),u=a.cmov(h,f,m);const g=a.eql(a.sqr(u),c),v=a.cmov(l,u,g);return fh(a,v,c),v}}function Zb(t){if(t<zb)throw new Error("sqrt is not defined for small field");let e=t-Bt,r=0;for(;e%vs===Mt;)e/=vs,r++;let n=vs;const s=va(t);for(;Vp(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Kb;let i=s.pow(n,e);const o=(e+Bt)/vs;return function(c,l){if(c.is0(l))return l;if(Vp(c,l)!==1)throw new Error("Cannot find square root");let u=r,f=c.mul(c.ONE,i),h=c.pow(l,e),d=c.pow(l,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let m=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(m++,g=c.sqr(g),m===u)throw new Error("Cannot find square root");const v=Bt<<BigInt(u-m-1),S=c.pow(f,v);u=m,f=c.sqr(S),h=c.mul(h,f),d=c.mul(d,S)}return d}}function Hk(t){return t%Vb===zb?Kb:t%Gb===qb?Lk:t%Wb===jk?Dk(t):Zb(t)}const zk=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Vk(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=zk.reduce((n,s)=>(n[s]="function",n),e);return lh(t,r),t}function qk(t,e,r){if(r<Mt)throw new Error("invalid exponent, negatives unsupported");if(r===Mt)return t.ONE;if(r===Bt)return e;let n=t.ONE,s=e;for(;r>Mt;)r&Bt&&(n=t.mul(n,s)),s=t.sqr(s),r>>=Bt;return n}function Xb(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 Vp(t,e){const r=(t.ORDER-Bt)/vs,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 Yb(t,e){e!==void 0&&ns(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function va(t,e,r=!1,n={}){if(t<=Mt)throw new Error("invalid field: expected ORDER > 0, got "+t);let s,i,o=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const h=e;h.BITS&&(s=h.BITS),h.sqrt&&(i=h.sqrt),typeof h.isLE=="boolean"&&(r=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(s=e),n.sqrt&&(i=n.sqrt);const{nBitLength:c,nByteLength:l}=Yb(t,s);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const f=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:l,MASK:wa(c),ZERO:Mt,ONE:Bt,allowedLengths:a,create:h=>mr(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return Mt<=h&&h<t},is0:h=>h===Mt,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&Bt)===Bt,neg:h=>mr(-h,t),eql:(h,d)=>h===d,sqr:h=>mr(h*h,t),add:(h,d)=>mr(h+d,t),sub:(h,d)=>mr(h-d,t),mul:(h,d)=>mr(h*d,t),pow:(h,d)=>qk(f,h,d),div:(h,d)=>mr(h*zp(d,t),t),sqrN:h=>h*h,addN:(h,d)=>h+d,subN:(h,d)=>h-d,mulN:(h,d)=>h*d,inv:h=>zp(h,t),sqrt:i||(h=>(u||(u=Hk(t)),u(f,h))),toBytes:h=>r?Db(h,l):uh(h,l),fromBytes:(h,d=!0)=>{if(a){if(!a.includes(h.length)||h.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const g=new Uint8Array(l);g.set(h,r?0:g.length-h.length),h=g}if(h.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+h.length);let m=r?Lb(h):Xc(h);if(o&&(m=mr(m,t)),!d&&!f.isValid(m))throw new Error("invalid field element: outside of range 0..ORDER");return m},invertBatch:h=>Xb(f,h),cmov:(h,d,m)=>m?d:h});return Object.freeze(f)}function Jb(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 Qb(t){const e=Jb(t);return e+Math.ceil(e/2)}function Gk(t,e,r=!1){const n=t.length,s=Jb(e),i=Qb(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=r?Lb(t):Xc(t),a=mr(o,e-Bt)+Bt;return r?Db(a,s):uh(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const $i=BigInt(0),Es=BigInt(1);function gc(t,e){const r=e.negate();return t?r:e}function Uu(t,e){const r=Xb(t.Fp,e.map(n=>n.Z));return e.map((n,s)=>t.fromAffine(n.toAffine(r[s])))}function ew(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Mu(t,e){ew(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),s=2**t,i=wa(t),o=BigInt(t);return{windows:r,windowSize:n,mask:i,maxNumber:s,shiftBy:o}}function qp(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+=Es);const l=e*n,u=l+Math.abs(a)-1,f=a===0,h=a<0,d=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:h,isNegF:d,offsetF:l}}function Wk(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 Kk(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 Fu=new WeakMap,tw=new WeakMap;function ju(t){return tw.get(t)||1}function Gp(t){if(t!==$i)throw new Error("invalid wNAF")}class Zk{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let s=e;for(;r>$i;)r&Es&&(n=n.add(s)),s=s.double(),r>>=Es;return n}precomputeWindow(e,r){const{windows:n,windowSize:s}=Mu(r,this.bits),i=[];let o=e,a=o;for(let c=0;c<n;c++){a=o,i.push(a);for(let l=1;l<s;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,i=this.BASE;const o=Mu(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:h,offsetF:d}=qp(n,a,o);n=c,u?i=i.add(gc(h,r[d])):s=s.add(gc(f,r[l]))}return Gp(n),{p:s,f:i}}wNAFUnsafe(e,r,n,s=this.ZERO){const i=Mu(e,this.bits);for(let o=0;o<i.windows&&n!==$i;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=qp(n,o,i);if(n=a,!l){const f=r[c];s=s.add(u?f.negate():f)}}return Gp(n),s}getPrecomputes(e,r,n){let s=Fu.get(r);return s||(s=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(s=n(s)),Fu.set(r,s))),s}cached(e,r,n){const s=ju(e);return this.wNAF(s,this.getPrecomputes(s,e,n),r)}unsafe(e,r,n,s){const i=ju(e);return i===1?this._unsafeLadder(e,r,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),r,s)}createCache(e,r){ew(r,this.bits),tw.set(e,r),Fu.delete(e)}hasCache(e){return ju(e)!==1}}function Xk(t,e,r,n){let s=e,i=t.ZERO,o=t.ZERO;for(;r>$i||n>$i;)r&Es&&(i=i.add(s)),n&Es&&(o=o.add(s)),s=s.double(),r>>=Es,n>>=Es;return{p1:i,p2:o}}function Yk(t,e,r,n){Wk(r,t),Kk(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=Hb(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=wa(c),u=new Array(Number(l)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let h=o;for(let d=f;d>=0;d-=c){u.fill(o);for(let g=0;g<i;g++){const v=n[g],S=Number(v>>BigInt(d)&l);u[S]=u[S].add(r[g])}let m=o;for(let g=u.length-1,v=o;g>0;g--)v=v.add(u[g]),m=m.add(v);if(h=h.add(m),d!==0)for(let g=0;g<c;g++)h=h.double()}return h}function Wp(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Vk(e),e}else return va(t,{isLE:r})}function Jk(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>$i))throw new Error(`CURVE.${c} must be positive bigint`)}const s=Wp(e.p,r.Fp,n),i=Wp(e.n,r.Fn,n),a=["Gx","Gy","a","b"];for(const c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Kp=(t,e)=>(t+(t>=0?e:-e)/rw)/e;function Qk(t,e,r){const[[n,s],[i,o]]=e,a=Kp(o*t,r),c=Kp(-s*t,r);let l=t-a*n-c*i,u=-a*s-c*o;const f=l<gn,h=u<gn;f&&(l=-l),h&&(u=-u);const d=wa(Math.ceil(Hb(r)/2))+Ei;if(l<gn||l>=d||u<gn||u>=d)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:l,k2neg:h,k2:u}}function Zf(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Lu(t,e){const r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return mc(r.lowS,"lowS"),mc(r.prehash,"prehash"),r.format!==void 0&&Zf(r.format),r}class e_ extends Error{constructor(e=""){super(e)}}const hn={Err:e_,_tlv:{encode:(t,e)=>{const{Err:r}=hn;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=Ua(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const i=n>127?Ua(s.length/2|128):"";return Ua(t)+i+s+e},decode(t,e){const{Err:r}=hn;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 l=e.subarray(n,n+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=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}=hn;if(t<gn)throw new e("integer: negative integers are not allowed");let r=Ua(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}=hn;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 Xc(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=hn,s=$t("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:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(t){const{_tlv:e,_int:r}=hn,n=e.encode(2,r.encode(t.r)),s=e.encode(2,r.encode(t.s)),i=n+s;return e.encode(48,i)}},gn=BigInt(0),Ei=BigInt(1),rw=BigInt(2),Ma=BigInt(3),t_=BigInt(4);function mi(t,e){const{BYTES:r}=t;let n;if(typeof e=="bigint")n=e;else{let s=$t("private key",e);try{n=t.fromBytes(s)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function r_(t,e={}){const r=Jk("weierstrass",t,e),{Fp:n,Fn:s}=r;let i=r.CURVE;const{h:o,n:a}=i;lh(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=sw(n,s);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(K,U,N){const{x:F,y:Z}=U.toAffine(),ee=n.toBytes(F);if(mc(N,"isCompressed"),N){u();const D=!n.isOdd(Z);return Wn(nw(D),ee)}else return Wn(Uint8Array.of(4),ee,n.toBytes(Z))}function h(K){ws(K,void 0,"Point");const{publicKey:U,publicKeyUncompressed:N}=l,F=K.length,Z=K[0],ee=K.subarray(1);if(F===U&&(Z===2||Z===3)){const D=n.fromBytes(ee);if(!n.isValid(D))throw new Error("bad point: is not on curve, wrong x");const T=g(D);let L;try{L=n.sqrt(T)}catch(R){const j=R instanceof Error?": "+R.message:"";throw new Error("bad point: is not on curve, sqrt error"+j)}u();const G=n.isOdd(L);return(Z&1)===1!==G&&(L=n.neg(L)),{x:D,y:L}}else if(F===N&&Z===4){const D=n.BYTES,T=n.fromBytes(ee.subarray(0,D)),L=n.fromBytes(ee.subarray(D,D*2));if(!v(T,L))throw new Error("bad point: is not on curve");return{x:T,y:L}}else throw new Error(`bad point: got length ${F}, expected compressed=${U} or uncompressed=${N}`)}const d=e.toBytes||f,m=e.fromBytes||h;function g(K){const U=n.sqr(K),N=n.mul(U,K);return n.add(n.add(N,n.mul(K,i.a)),i.b)}function v(K,U){const N=n.sqr(U),F=g(K);return n.eql(N,F)}if(!v(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const S=n.mul(n.pow(i.a,Ma),t_),_=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(S,_)))throw new Error("bad curve params: a or b");function E(K,U,N=!1){if(!n.isValid(U)||N&&n.is0(U))throw new Error(`bad point coordinate ${K}`);return U}function x(K){if(!(K instanceof C))throw new Error("ProjectivePoint expected")}function O(K){if(!c||!c.basises)throw new Error("no endo");return Qk(K,c.basises,s.ORDER)}const P=Hp((K,U)=>{const{X:N,Y:F,Z}=K;if(n.eql(Z,n.ONE))return{x:N,y:F};const ee=K.is0();U==null&&(U=ee?n.ONE:n.inv(Z));const D=n.mul(N,U),T=n.mul(F,U),L=n.mul(Z,U);if(ee)return{x:n.ZERO,y:n.ZERO};if(!n.eql(L,n.ONE))throw new Error("invZ was invalid");return{x:D,y:T}}),$=Hp(K=>{if(K.is0()){if(e.allowInfinityPoint&&!n.is0(K.Y))return;throw new Error("bad point: ZERO")}const{x:U,y:N}=K.toAffine();if(!n.isValid(U)||!n.isValid(N))throw new Error("bad point: x or y not field elements");if(!v(U,N))throw new Error("bad point: equation left != right");if(!K.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function z(K,U,N,F,Z){return N=new C(n.mul(N.X,K),N.Y,N.Z),U=gc(F,U),N=gc(Z,N),U.add(N)}class C{constructor(U,N,F){this.X=E("x",U),this.Y=E("y",N,!0),this.Z=E("z",F),Object.freeze(this)}static CURVE(){return i}static fromAffine(U){const{x:N,y:F}=U||{};if(!U||!n.isValid(N)||!n.isValid(F))throw new Error("invalid affine point");if(U instanceof C)throw new Error("projective point not allowed");return n.is0(N)&&n.is0(F)?C.ZERO:new C(N,F,n.ONE)}static fromBytes(U){const N=C.fromAffine(m(ws(U,void 0,"point")));return N.assertValidity(),N}static fromHex(U){return C.fromBytes($t("pointHex",U))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(U=8,N=!0){return W.createCache(this,U),N||this.multiply(Ma),this}assertValidity(){$(this)}hasEvenY(){const{y:U}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(U)}equals(U){x(U);const{X:N,Y:F,Z}=this,{X:ee,Y:D,Z:T}=U,L=n.eql(n.mul(N,T),n.mul(ee,Z)),G=n.eql(n.mul(F,T),n.mul(D,Z));return L&&G}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){const{a:U,b:N}=i,F=n.mul(N,Ma),{X:Z,Y:ee,Z:D}=this;let T=n.ZERO,L=n.ZERO,G=n.ZERO,I=n.mul(Z,Z),R=n.mul(ee,ee),j=n.mul(D,D),J=n.mul(Z,ee);return J=n.add(J,J),G=n.mul(Z,D),G=n.add(G,G),T=n.mul(U,G),L=n.mul(F,j),L=n.add(T,L),T=n.sub(R,L),L=n.add(R,L),L=n.mul(T,L),T=n.mul(J,T),G=n.mul(F,G),j=n.mul(U,j),J=n.sub(I,j),J=n.mul(U,J),J=n.add(J,G),G=n.add(I,I),I=n.add(G,I),I=n.add(I,j),I=n.mul(I,J),L=n.add(L,I),j=n.mul(ee,D),j=n.add(j,j),I=n.mul(j,J),T=n.sub(T,I),G=n.mul(j,R),G=n.add(G,G),G=n.add(G,G),new C(T,L,G)}add(U){x(U);const{X:N,Y:F,Z}=this,{X:ee,Y:D,Z:T}=U;let L=n.ZERO,G=n.ZERO,I=n.ZERO;const R=i.a,j=n.mul(i.b,Ma);let J=n.mul(N,ee),ne=n.mul(F,D),ue=n.mul(Z,T),ce=n.add(N,F),se=n.add(ee,D);ce=n.mul(ce,se),se=n.add(J,ne),ce=n.sub(ce,se),se=n.add(N,Z);let ie=n.add(ee,T);return se=n.mul(se,ie),ie=n.add(J,ue),se=n.sub(se,ie),ie=n.add(F,Z),L=n.add(D,T),ie=n.mul(ie,L),L=n.add(ne,ue),ie=n.sub(ie,L),I=n.mul(R,se),L=n.mul(j,ue),I=n.add(L,I),L=n.sub(ne,I),I=n.add(ne,I),G=n.mul(L,I),ne=n.add(J,J),ne=n.add(ne,J),ue=n.mul(R,ue),se=n.mul(j,se),ne=n.add(ne,ue),ue=n.sub(J,ue),ue=n.mul(R,ue),se=n.add(se,ue),J=n.mul(ne,se),G=n.add(G,J),J=n.mul(ie,se),L=n.mul(ce,L),L=n.sub(L,J),J=n.mul(ce,ne),I=n.mul(ie,I),I=n.add(I,J),new C(L,G,I)}subtract(U){return this.add(U.negate())}is0(){return this.equals(C.ZERO)}multiply(U){const{endo:N}=e;if(!s.isValidNot0(U))throw new Error("invalid scalar: out of range");let F,Z;const ee=D=>W.cached(this,D,T=>Uu(C,T));if(N){const{k1neg:D,k1:T,k2neg:L,k2:G}=O(U),{p:I,f:R}=ee(T),{p:j,f:J}=ee(G);Z=R.add(J),F=z(N.beta,I,j,D,L)}else{const{p:D,f:T}=ee(U);F=D,Z=T}return Uu(C,[F,Z])[0]}multiplyUnsafe(U){const{endo:N}=e,F=this;if(!s.isValid(U))throw new Error("invalid scalar: out of range");if(U===gn||F.is0())return C.ZERO;if(U===Ei)return F;if(W.hasCache(this))return this.multiply(U);if(N){const{k1neg:Z,k1:ee,k2neg:D,k2:T}=O(U),{p1:L,p2:G}=Xk(C,F,ee,T);return z(N.beta,L,G,Z,D)}else return W.unsafe(F,U)}multiplyAndAddUnsafe(U,N,F){const Z=this.multiplyUnsafe(N).add(U.multiplyUnsafe(F));return Z.is0()?void 0:Z}toAffine(U){return P(this,U)}isTorsionFree(){const{isTorsionFree:U}=e;return o===Ei?!0:U?U(C,this):W.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:U}=e;return o===Ei?this:U?U(C,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(U=!0){return mc(U,"isCompressed"),this.assertValidity(),d(C,this,U)}toHex(U=!0){return gi(this.toBytes(U))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(U=!0){return this.toBytes(U)}_setWindowSize(U){this.precompute(U)}static normalizeZ(U){return Uu(C,U)}static msm(U,N){return Yk(C,s,U,N)}static fromPrivateKey(U){return C.BASE.multiply(mi(s,U))}}C.BASE=new C(i.Gx,i.Gy,n.ONE),C.ZERO=new C(n.ZERO,n.ONE,n.ZERO),C.Fp=n,C.Fn=s;const Y=s.BITS,W=new Zk(C,e.endo?Math.ceil(Y/2):Y);return C.BASE.precompute(8),C}function nw(t){return Uint8Array.of(t?2:3)}function sw(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function n_(t,e={}){const{Fn:r}=t,n=e.randomBytes||$0,s=Object.assign(sw(t.Fp,r),{seed:Qb(r.ORDER)});function i(d){try{return!!mi(r,d)}catch{return!1}}function o(d,m){const{publicKey:g,publicKeyUncompressed:v}=s;try{const S=d.length;return m===!0&&S!==g||m===!1&&S!==v?!1:!!t.fromBytes(d)}catch{return!1}}function a(d=n(s.seed)){return Gk(ws(d,s.seed,"seed"),r.ORDER)}function c(d,m=!0){return t.BASE.multiply(mi(r,d)).toBytes(m)}function l(d){const m=a(d);return{secretKey:m,publicKey:c(m)}}function u(d){if(typeof d=="bigint")return!1;if(d instanceof t)return!0;const{secretKey:m,publicKey:g,publicKeyUncompressed:v}=s;if(r.allowedLengths||m===g)return;const S=$t("key",d).length;return S===g||S===v}function f(d,m,g=!0){if(u(d)===!0)throw new Error("first arg must be private key");if(u(m)===!1)throw new Error("second arg must be public key");const v=mi(r,d);return t.fromHex(m).multiply(v).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:l,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:d=>mi(r,d),precompute(d=8,m=t.BASE){return m.precompute(d,!1)}},lengths:s})}function s_(t,e,r={}){P0(e),lh(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||$0,s=r.hmac||((N,...F)=>Fb(e,N,Wn(...F))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:h,lengths:d}=n_(t,r),m={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function v(N){const F=a>>Ei;return N>F}function S(N,F){if(!o.isValidNot0(F))throw new Error(`invalid signature ${N}: out of range 1..Point.Fn.ORDER`);return F}function _(N,F){Zf(F);const Z=d.signature,ee=F==="compact"?Z:F==="recovered"?Z+1:void 0;return ws(N,ee,`${F} signature`)}class E{constructor(F,Z,ee){this.r=S("r",F),this.s=S("s",Z),ee!=null&&(this.recovery=ee),Object.freeze(this)}static fromBytes(F,Z=g){_(F,Z);let ee;if(Z==="der"){const{r:G,s:I}=hn.toSig(ws(F));return new E(G,I)}Z==="recovered"&&(ee=F[0],Z="compact",F=F.subarray(1));const D=o.BYTES,T=F.subarray(0,D),L=F.subarray(D,D*2);return new E(o.fromBytes(T),o.fromBytes(L),ee)}static fromHex(F,Z){return this.fromBytes(hc(F),Z)}addRecoveryBit(F){return new E(this.r,this.s,F)}recoverPublicKey(F){const Z=i.ORDER,{r:ee,s:D,recovery:T}=this;if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");if(a*rw<Z&&T>1)throw new Error("recovery id is ambiguous for h>1 curve");const G=T===2||T===3?ee+a:ee;if(!i.isValid(G))throw new Error("recovery id 2 or 3 invalid");const I=i.toBytes(G),R=t.fromBytes(Wn(nw((T&1)===0),I)),j=o.inv(G),J=O($t("msgHash",F)),ne=o.create(-J*j),ue=o.create(D*j),ce=t.BASE.multiplyUnsafe(ne).add(R.multiplyUnsafe(ue));if(ce.is0())throw new Error("point at infinify");return ce.assertValidity(),ce}hasHighS(){return v(this.s)}toBytes(F=g){if(Zf(F),F==="der")return hc(hn.hexFromSig(this));const Z=o.toBytes(this.r),ee=o.toBytes(this.s);if(F==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Wn(Uint8Array.of(this.recovery),Z,ee)}return Wn(Z,ee)}toHex(F){return gi(this.toBytes(F))}assertValidity(){}static fromCompact(F){return E.fromBytes($t("sig",F),"compact")}static fromDER(F){return E.fromBytes($t("sig",F),"der")}normalizeS(){return this.hasHighS()?new E(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return gi(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return gi(this.toBytes("compact"))}}const x=r.bits2int||function(F){if(F.length>8192)throw new Error("input is too large");const Z=Xc(F),ee=F.length*8-c;return ee>0?Z>>BigInt(ee):Z},O=r.bits2int_modN||function(F){return o.create(x(F))},P=wa(c);function $(N){return Uk("num < 2^"+c,N,gn,P),o.toBytes(N)}function z(N,F){return ws(N,void 0,"message"),F?ws(e(N),void 0,"prehashed message"):N}function C(N,F,Z){if(["recovered","canonical"].some(ne=>ne in Z))throw new Error("sign() legacy options not supported");const{lowS:ee,prehash:D,extraEntropy:T}=Lu(Z,m);N=z(N,D);const L=O(N),G=mi(o,F),I=[$(G),$(L)];if(T!=null&&T!==!1){const ne=T===!0?n(d.secretKey):T;I.push($t("extraEntropy",ne))}const R=Wn(...I),j=L;function J(ne){const ue=x(ne);if(!o.isValidNot0(ue))return;const ce=o.inv(ue),se=t.BASE.multiply(ue).toAffine(),ie=o.create(se.x);if(ie===gn)return;const me=o.create(ce*o.create(j+ie*G));if(me===gn)return;let be=(se.x===ie?0:2)|Number(se.y&Ei),Ee=me;return ee&&v(me)&&(Ee=o.neg(me),be^=1),new E(ie,Ee,be)}return{seed:R,k2sig:J}}function Y(N,F,Z={}){N=$t("message",N);const{seed:ee,k2sig:D}=C(N,F,Z);return Mk(e.outputLen,o.BYTES,s)(ee,D)}function W(N){let F;const Z=typeof N=="string"||Oc(N),ee=!Z&&N!==null&&typeof N=="object"&&typeof N.r=="bigint"&&typeof N.s=="bigint";if(!Z&&!ee)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(ee)F=new E(N.r,N.s);else if(Z){try{F=E.fromBytes($t("sig",N),"der")}catch(D){if(!(D instanceof hn.Err))throw D}if(!F)try{F=E.fromBytes($t("sig",N),"compact")}catch{return!1}}return F||!1}function K(N,F,Z,ee={}){const{lowS:D,prehash:T,format:L}=Lu(ee,m);if(Z=$t("publicKey",Z),F=z($t("message",F),T),"strict"in ee)throw new Error("options.strict was renamed to lowS");const G=L===void 0?W(N):E.fromBytes($t("sig",N),L);if(G===!1)return!1;try{const I=t.fromBytes(Z);if(D&&G.hasHighS())return!1;const{r:R,s:j}=G,J=O(F),ne=o.inv(j),ue=o.create(J*ne),ce=o.create(R*ne),se=t.BASE.multiplyUnsafe(ue).add(I.multiplyUnsafe(ce));return se.is0()?!1:o.create(se.x)===R}catch{return!1}}function U(N,F,Z={}){const{prehash:ee}=Lu(Z,m);return F=z(F,ee),E.fromBytes(N,"recovered").recoverPublicKey(F).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:h,lengths:d,Point:t,sign:Y,verify:K,recoverPublicKey:U,Signature:E,hash:e})}function i_(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const s=va(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),i={Fp:r,Fn:s,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function o_(t){const{CURVE:e,curveOpts:r}=i_(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function a_(t,e){const r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,Yb(r.Fn.ORDER,r.Fn.BITS))})}function c_(t){const{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:s}=o_(t),i=r_(e,r),o=s_(i,n,s);return a_(t,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function u_(t,e){const r=n=>c_({...t,hash:n});return{...r(e),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const dh={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},l_={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Zp=BigInt(2);function f_(t){const e=dh.p,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,u=l*l*t%e,f=Qt(u,r,e)*u%e,h=Qt(f,r,e)*u%e,d=Qt(h,Zp,e)*l%e,m=Qt(d,s,e)*d%e,g=Qt(m,i,e)*m%e,v=Qt(g,a,e)*g%e,S=Qt(v,c,e)*v%e,_=Qt(S,a,e)*g%e,E=Qt(_,r,e)*u%e,x=Qt(E,o,e)*m%e,O=Qt(x,n,e)*l%e,P=Qt(O,Zp,e);if(!Xf.eql(Xf.sqr(P),t))throw new Error("Cannot find square root");return P}const Xf=va(dh.p,{sqrt:f_}),iw=u_({...dh,Fp:Xf,lowS:!0,endo:l_},ug),d_=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:iw},Symbol.toStringTag,{value:"Module"}));function h_({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 iw.Signature(at(t),at(e)).toCompactHex()}${i===0?"1b":"1c"}`;return r==="hex"?o:Ir(o)}async function hh(t,e){var f,h,d;const{address:r,factory:n,factoryData:s,hash:i,signature:o,universalSignatureVerifierAddress:a=(d=(h=(f=t.chain)==null?void 0:f.contracts)==null?void 0:h.universalSignatureVerifier)==null?void 0:d.address,...c}=e,l=Tr(o)?o:typeof o=="object"&&"r"in o&&"s"in o?h_(o):Qe(o),u=await(async()=>!n&&!s||l6(l)?l:f6({address:n,data:s,signature:l}))();try{const m=a?{to:a,data:hr({abi:Pp,functionName:"isValidSig",args:[r,i,u]}),...c}:{data:Vc({abi:Pp,args:[r,i,u],bytecode:OA}),...c},{data:g}=await ae(t,ya,"call")(m);return nE(g??"0x0")}catch(m){try{if(pa(L0(r),await eg({hash:i,signature:o})))return!0}catch{}if(m instanceof Q0)return!1;throw m}}async function p_(t,{address:e,message:r,factory:n,factoryData:s,signature:i,...o}){const a=pb(r);return hh(t,{address:e,factory:n,factoryData:s,hash:a,signature:i,...o})}async function y_(t,e){const{address:r,factory:n,factoryData:s,signature:i,message:o,primaryType:a,types:c,domain:l,...u}=e,f=Nx({message:o,primaryType:a,types:c,domain:l});return hh(t,{address:r,factory:n,factoryData:s,hash:f,signature:i,...u})}function ow(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 f=Je(["watchBlockNumber",t.uid,e,r,o]);return xn(f,{onBlockNumber:n,onError:s},h=>Gi(async()=>{var d;try{const m=await ae(t,ma,"getBlockNumber")({cacheTime:0});if(c){if(m===c)return;if(m-c>1&&r)for(let g=c+1n;g<m;g++)h.onBlockNumber(g,c),c=g}(!c||m>c)&&(h.onBlockNumber(m,c),c=m)}catch(m){(d=h.onError)==null||d.call(h,m)}},{emitOnBegin:e,interval:o}))})():(()=>{const f=Je(["watchBlockNumber",t.uid,e,r]);return xn(f,{onBlockNumber:n,onError:s},h=>{let d=!0,m=()=>d=!1;return(async()=>{try{const g=(()=>{if(t.transport.type==="fallback"){const S=t.transport.transports.find(_=>_.config.type==="webSocket"||_.config.type==="ipc");return S?S.value:t.transport}return t.transport})(),{unsubscribe:v}=await g.subscribe({params:["newHeads"],onData(S){var E;if(!d)return;const _=at((E=S.result)==null?void 0:E.number);h.onBlockNumber(_,c),c=_},onError(S){var _;(_=h.onError)==null||_.call(h,S)}});m=v,d||m()}catch(g){s==null||s(g)}})(),()=>m()})})()}async function m_(t,e){const{checkReplacement:r=!0,confirmations:n=1,hash:s,onReplaced:i,retryCount:o=6,retryDelay:a=({count:O})=>~~(1<<O)*200,timeout:c=18e4}=e,l=Je(["waitForTransactionReceipt",t.uid,s]),u=(()=>{var O;return e.pollingInterval?e.pollingInterval:(O=t.chain)!=null&&O.experimental_preconfirmationTime?t.chain.experimental_preconfirmationTime:t.pollingInterval})();let f,h,d,m=!1,g,v;const{promise:S,resolve:_,reject:E}=Jd(),x=c?setTimeout(()=>{v==null||v(),g==null||g(),E(new gS({hash:s}))},c):void 0;return g=xn(l,{onReplaced:i,resolve:_,reject:E},async O=>{if(d=await ae(t,ec,"getTransactionReceipt")({hash:s}).catch(()=>{}),d&&n<=1){clearTimeout(x),O.resolve(d),g==null||g();return}v=ae(t,ow,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:u,async onBlockNumber(P){const $=C=>{clearTimeout(x),v==null||v(),C(),g==null||g()};let z=P;if(!m)try{if(d){if(n>1&&(!d.blockNumber||z-d.blockNumber+1n<n))return;$(()=>O.resolve(d));return}if(r&&!f&&(m=!0,await yc(async()=>{f=await ae(t,ih,"getTransaction")({hash:s}),f.blockNumber&&(z=f.blockNumber)},{delay:a,retryCount:o}),m=!1),d=await ae(t,ec,"getTransactionReceipt")({hash:s}),n>1&&(!d.blockNumber||z-d.blockNumber+1n<n))return;$(()=>O.resolve(d))}catch(C){if(C instanceof Y0||C instanceof J0){if(!f){m=!1;return}try{h=f,m=!0;const Y=await yc(()=>ae(t,Wr,"getBlock")({blockNumber:z,includeTransactions:!0}),{delay:a,retryCount:o,shouldRetry:({error:U})=>U instanceof sg});m=!1;const W=Y.transactions.find(({from:U,nonce:N})=>U===h.from&&N===h.nonce);if(!W||(d=await ae(t,ec,"getTransactionReceipt")({hash:W.hash}),n>1&&(!d.blockNumber||z-d.blockNumber+1n<n)))return;let K="replaced";W.to===h.to&&W.value===h.value&&W.input===h.input?K="repriced":W.from===W.to&&W.value===0n&&(K="cancelled"),$(()=>{var U;(U=O.onReplaced)==null||U.call(O,{reason:K,replacedTransaction:h,transaction:W,transactionReceipt:d}),O.resolve(d)})}catch(Y){$(()=>O.reject(Y))}}else $(()=>O.reject(C))}}})}),S}function g_(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 l=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")),u=o??!1;let f;return l?(()=>{const m=Je(["watchBlocks",t.uid,e,r,n,u,c]);return xn(m,{onBlock:s,onError:i},g=>Gi(async()=>{var v;try{const S=await ae(t,Wr,"getBlock")({blockTag:e,includeTransactions:u});if(S.number!==null&&(f==null?void 0:f.number)!=null){if(S.number===f.number)return;if(S.number-f.number>1&&r)for(let _=(f==null?void 0:f.number)+1n;_<S.number;_++){const E=await ae(t,Wr,"getBlock")({blockNumber:_,includeTransactions:u});g.onBlock(E,f),f=E}}((f==null?void 0:f.number)==null||e==="pending"&&(S==null?void 0:S.number)==null||S.number!==null&&S.number>f.number)&&(g.onBlock(S,f),f=S)}catch(S){(v=g.onError)==null||v.call(g,S)}},{emitOnBegin:n,interval:c}))})():(()=>{let m=!0,g=!0,v=()=>m=!1;return(async()=>{try{n&&ae(t,Wr,"getBlock")({blockTag:e,includeTransactions:u}).then(E=>{m&&g&&(s(E,void 0),g=!1)}).catch(i);const S=(()=>{if(t.transport.type==="fallback"){const E=t.transport.transports.find(x=>x.config.type==="webSocket"||x.config.type==="ipc");return E?E.value:t.transport}return t.transport})(),{unsubscribe:_}=await S.subscribe({params:["newHeads"],async onData(E){var O;if(!m)return;const x=await ae(t,Wr,"getBlock")({blockNumber:(O=E.result)==null?void 0:O.number,includeTransactions:u}).catch(()=>{});m&&(s(x,f),g=!1,f=x)},onError(E){i==null||i(E)}});v=_,m||v()}catch(S){i==null||i(S)}})(),()=>v()})()}function b_(t,{address:e,args:r,batch:n=!0,event:s,events:i,fromBlock:o,onError:a,onLogs:c,poll:l,pollingInterval:u=t.pollingInterval,strict:f}){const h=typeof l<"u"?l: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=f??!1;return h?(()=>{const v=Je(["watchEvent",e,r,n,t.uid,s,u,o]);return xn(v,{onLogs:c,onError:a},S=>{let _;o!==void 0&&(_=o-1n);let E,x=!1;const O=Gi(async()=>{var P;if(!x){try{E=await ae(t,eb,"createEventFilter")({address:e,args:r,event:s,events:i,strict:d,fromBlock:o})}catch{}x=!0;return}try{let $;if(E)$=await ae(t,qc,"getFilterChanges")({filter:E});else{const z=await ae(t,ma,"getBlockNumber")({});_&&_!==z?$=await ae(t,Wd,"getLogs")({address:e,args:r,event:s,events:i,fromBlock:_+1n,toBlock:z}):$=[],_=z}if($.length===0)return;if(n)S.onLogs($);else for(const z of $)S.onLogs([z])}catch($){E&&$ instanceof Us&&(x=!1),(P=S.onError)==null||P.call(S,$)}},{emitOnBegin:!0,interval:u});return async()=>{E&&await ae(t,Gc,"uninstallFilter")({filter:E}),O()}})})():(()=>{let v=!0,S=()=>v=!1;return(async()=>{try{const _=(()=>{if(t.transport.type==="fallback"){const P=t.transport.transports.find($=>$.config.type==="webSocket"||$.config.type==="ipc");return P?P.value:t.transport}return t.transport})(),E=i??(s?[s]:void 0);let x=[];E&&(x=[E.flatMap($=>la({abi:[$],eventName:$.name,args:r}))],s&&(x=x[0]));const{unsubscribe:O}=await _.subscribe({params:["logs",{address:e,topics:x}],onData(P){var z;if(!v)return;const $=P.result;try{const{eventName:C,args:Y}=qd({abi:E??[],data:$.data,topics:$.topics,strict:d}),W=An($,{args:Y,eventName:C});c([W])}catch(C){let Y,W;if(C instanceof To||C instanceof Pc){if(f)return;Y=C.abiItem.name,W=(z=C.abiItem.inputs)==null?void 0:z.some(U=>!("name"in U&&U.name))}const K=An($,{args:W?[]:{},eventName:Y});c([K])}},onError(P){a==null||a(P)}});S=O,v||S()}catch(_){a==null||a(_)}})(),()=>S()})()}function w_(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 l=Je(["watchPendingTransactions",t.uid,e,i]);return xn(l,{onTransactions:n,onError:r},u=>{let f;const h=Gi(async()=>{var d;try{if(!f)try{f=await ae(t,tb,"createPendingTransactionFilter")({});return}catch(g){throw h(),g}const m=await ae(t,qc,"getFilterChanges")({filter:f});if(m.length===0)return;if(e)u.onTransactions(m);else for(const g of m)u.onTransactions([g])}catch(m){(d=u.onError)==null||d.call(u,m)}},{emitOnBegin:!0,interval:i});return async()=>{f&&await ae(t,Gc,"uninstallFilter")({filter:f}),h()}})})():(()=>{let l=!0,u=()=>l=!1;return(async()=>{try{const{unsubscribe:f}=await t.transport.subscribe({params:["newPendingTransactions"],onData(h){if(!l)return;const d=h.result;n([d])},onError(h){r==null||r(h)}});u=f,l||u()}catch(f){r==null||r(f)}})(),()=>u()})()}function v_(t){var f,h,d;const{scheme:e,statement:r,...n}=((f=t.match(E_))==null?void 0:f.groups)??{},{chainId:s,expirationTime:i,issuedAt:o,notBefore:a,requestId:c,...l}=((h=t.match(S_))==null?void 0:h.groups)??{},u=(d=t.split("Resources:")[1])==null?void 0:d.split(`
46
- - `).slice(1);return{...n,...l,...s?{chainId:Number(s)}:{},...i?{expirationTime:new Date(i)}:{},...o?{issuedAt:new Date(o)}:{},...a?{notBefore:new Date(a)}:{},...c?{requestId:c}:{},...u?{resources:u}:{},...e?{scheme:e}:{},...r?{statement:r}:{}}}const E_=/^(?:(?<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)?/,S_=/(?: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 A_(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||!ot(n.address,{strict:!1})||e&&!pa(n.address,e))return!1}catch{return!1}return!0}async function x_(t,e){const{address:r,domain:n,message:s,nonce:i,scheme:o,signature:a,time:c=new Date,...l}=e,u=v_(s);if(!u.address||!A_({address:r,domain:n,message:u,nonce:i,scheme:o,time:c}))return!1;const h=pb(s);return hh(t,{address:u.address,hash:h,signature:a,...l})}function k_(t){return{call:e=>ya(t,e),createAccessList:e=>Qg(t,e),createBlockFilter:()=>Ax(t),createContractEventFilter:e=>Od(t,e),createEventFilter:e=>eb(t,e),createPendingTransactionFilter:()=>tb(t),estimateContractGas:e=>vg(t,e),estimateGas:e=>Vd(t,e),getBalance:e=>wg(t,e),getBlobBaseFee:()=>xx(t),getBlock:e=>Wr(t,e),getBlockNumber:e=>ma(t,e),getBlockTransactionCount:e=>kx(t,e),getBytecode:e=>Up(t,e),getChainId:()=>Vi(t),getCode:e=>Up(t,e),getContractEvents:e=>Kd(t,e),getEip712Domain:e=>Tx(t,e),getEnsAddress:e=>ax(t,e),getEnsAvatar:e=>vx(t,e),getEnsName:e=>Ex(t,e),getEnsResolver:e=>Sx(t,e),getEnsText:e=>Jg(t,e),getFeeHistory:e=>Ox(t,e),estimateFeesPerGas:e=>DS(t,e),getFilterChanges:e=>qc(t,e),getFilterLogs:e=>Bx(t,e),getGasPrice:()=>Fd(t),getLogs:e=>Wd(t,e),getProof:e=>p6(t,e),estimateMaxPriorityFeePerGas:e=>LS(t,e),getStorageAt:e=>y6(t,e),getTransaction:e=>ih(t,e),getTransactionConfirmations:e=>m6(t,e),getTransactionCount:e=>jd(t,e),getTransactionReceipt:e=>ec(t,e),multicall:e=>g6(t,e),prepareTransactionRequest:e=>Hc(t,e),readContract:e=>Yr(t,e),sendRawTransaction:e=>Qd(t,e),simulate:e=>jf(t,e),simulateBlocks:e=>jf(t,e),simulateCalls:e=>Rk(t,e),simulateContract:e=>Rg(t,e),verifyMessage:e=>p_(t,e),verifySiweMessage:e=>x_(t,e),verifyTypedData:e=>y_(t,e),uninstallFilter:e=>Gc(t,e),waitForTransactionReceipt:e=>m_(t,e),watchBlocks:e=>g_(t,e),watchBlockNumber:e=>ow(t,e),watchContractEvent:e=>Ng(t,e),watchEvent:e=>b_(t,e),watchPendingTransactions:e=>w_(t,e)}}function __(t){const{key:e="public",name:r="Public Client"}=t;return qg({...t,key:e,name:r,type:"publicClient"}).extend(k_)}async function T_(t,{chain:e}){const{id:r,name:n,nativeCurrency:s,rpcUrls:i,blockExplorers:o}=e;await t.request({method:"wallet_addEthereumChain",params:[{chainId:X(r),chainName:n,nativeCurrency:s,rpcUrls:i.default.http,blockExplorerUrls:o?Object.values(o).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}function I_(t,e){const{abi:r,args:n,bytecode:s,...i}=e,o=Vc({abi:r,args:n,bytecode:s});return Wc(t,{...i,...i.authorizationList?{to:null}:{},data:o})}async function P_(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=>ca(n))}async function O_(t,e={}){const{account:r=t.account,chainId:n}=e,s=r?We(r):void 0,i=n?[s==null?void 0:s.address,[X(n)]]:[s==null?void 0:s.address],o=await t.request({method:"wallet_getCapabilities",params:i}),a={};for(const[c,l]of Object.entries(o)){a[Number(c)]={};for(let[u,f]of Object.entries(l))u==="addSubAccount"&&(u="unstable_addSubAccount"),a[Number(c)][u]=f}return typeof n=="number"?a[n]:a}async function B_(t){return await t.request({method:"wallet_getPermissions"},{dedupe:!0})}async function aw(t,e){var c;const{account:r=t.account,chainId:n,nonce:s}=e;if(!r)throw new Ys({docsPath:"/docs/eip7702/prepareAuthorization"});const i=We(r),o=(()=>{if(e.executor)return e.executor==="self"?e.executor:We(e.executor)})(),a={address:e.contractAddress??e.address,chainId:n,nonce:s};return typeof a.chainId>"u"&&(a.chainId=((c=t.chain)==null?void 0:c.id)??await ae(t,Vi,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await ae(t,jd,"getTransactionCount")({address:i.address,blockTag:"pending"}),(o==="self"||o!=null&&o.address&&pa(o.address,i.address))&&(a.nonce+=1)),a}async function C_(t){return(await t.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>L0(r))}async function $_(t,e){return t.request({method:"wallet_requestPermissions",params:[e]},{retryCount:0})}async function R_(t,e){const{id:r}=e;await t.request({method:"wallet_showCallsStatus",params:[r]})}async function N_(t,e){const{account:r=t.account}=e;if(!r)throw new Ys({docsPath:"/docs/eip7702/signAuthorization"});const n=We(r);if(!n.signAuthorization)throw new Qa({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});const s=await aw(t,e);return n.signAuthorization(s)}async function U_(t,{account:e=t.account,message:r}){if(!e)throw new Ys({docsPath:"/docs/actions/wallet/signMessage"});const n=We(e);if(n.signMessage)return n.signMessage({message:r});const s=typeof r=="string"?Pi(r):r.raw instanceof Uint8Array?Ot(r.raw):r.raw;return t.request({method:"personal_sign",params:[s,n.address]},{retryCount:0})}async function M_(t,e){var l,u,f,h;const{account:r=t.account,chain:n=t.chain,...s}=e;if(!r)throw new Ys({docsPath:"/docs/actions/wallet/signTransaction"});const i=We(r);Zs({account:i,...e});const o=await ae(t,Vi,"getChainId")({});n!==null&&Ug({currentChainId:o,chain:n});const a=(n==null?void 0:n.formatters)||((l=t.chain)==null?void 0:l.formatters),c=((u=a==null?void 0:a.transactionRequest)==null?void 0:u.format)||zi;return i.signTransaction?i.signTransaction({...s,chainId:o},{serializer:(h=(f=t.chain)==null?void 0:f.serializers)==null?void 0:h.transaction}):await t.request({method:"eth_signTransaction",params:[{...c(s),chainId:X(o),from:i.address}]},{retryCount:0})}async function F_(t,e){const{account:r=t.account,domain:n,message:s,primaryType:i}=e;if(!r)throw new Ys({docsPath:"/docs/actions/wallet/signTypedData"});const o=We(r),a={EIP712Domain:ab({domain:n}),...e.types};if(ob({domain:n,message:s,primaryType:i,types:a}),o.signTypedData)return o.signTypedData({domain:n,message:s,primaryType:i,types:a});const c=jx({domain:n,message:s,primaryType:i,types:a});return t.request({method:"eth_signTypedData_v4",params:[o.address,c]},{retryCount:0})}async function j_(t,{id:e}){await t.request({method:"wallet_switchEthereumChain",params:[{chainId:X(e)}]},{retryCount:0})}async function L_(t,e){return await t.request({method:"wallet_watchAsset",params:e},{retryCount:0})}function D_(t){return{addChain:e=>T_(t,e),deployContract:e=>I_(t,e),getAddresses:()=>P_(t),getCallsStatus:e=>zg(t,e),getCapabilities:e=>O_(t,e),getChainId:()=>Vi(t),getPermissions:()=>B_(t),prepareAuthorization:e=>aw(t,e),prepareTransactionRequest:e=>Hc(t,e),requestAddresses:()=>C_(t),requestPermissions:e=>$_(t,e),sendCalls:e=>GA(t,e),sendRawTransaction:e=>Qd(t,e),sendTransaction:e=>Wc(t,e),showCallsStatus:e=>R_(t,e),signAuthorization:e=>N_(t,e),signMessage:e=>U_(t,e),signTransaction:e=>M_(t,e),signTypedData:e=>F_(t,e),switchChain:e=>j_(t,e),waitForCallsStatus:e=>WA(t,e),watchAsset:e=>L_(t,e),writeContract:e=>Fg(t,e)}}function Du(t){const{key:e="wallet",name:r="Wallet Client",transport:n}=t;return qg({...t,key:e,name:r,transport:n,type:"walletClient"}).extend(D_)}const tc={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:""}},Zo={[b.Network.MAINNET]:{chainId:"0x534e5f4d41494e",nodeUrl:"https://starknet-mainnet.public.blastapi.io/rpc/v0_8"},[b.Network.TESTNET]:{chainId:"0x534e5f5345504f4c4941",nodeUrl:"https://starknet-sepolia.public.blastapi.io/rpc/v0_8"},[b.Network.LOCALNET]:{chainId:"",nodeUrl:""}},Yf={[b.Network.MAINNET]:"9cBuPNiHXiMNg3Fin8xLCGJQBTXjYQTFtyaFQv2uiM1H",[b.Network.TESTNET]:"ANUVKxeqaec3bf4DVPqLTnG1PT3Fng56wPcE7LXAb46Q",[b.Network.LOCALNET]:"AKnL4NNf3DGWZJS6cPknBuEGnVsV4A4m5tgebLHaRSZ9"},Jf={mainnet:{native:"2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",spl:"gdnvdMCHJgnidtU7SL8RkRshHPvDJU1pdfZEpoLvqdU"},staging:{native:"6eksgdCnSjUaGQWZ6iYvauv1qzvYPF33RTGTM1ZuyENx",spl:"2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC"}},Qf={[b.Network.TESTNET]:{packageId:"0x99865b03dd1bc03d0a6a805c454ea257c464f7abcccae9cd4b621b91e7ca04de",moduleName:"AtomicSwap"},[b.Network.MAINNET]:{packageId:"0xbfb5728aab0dd117747ef4574af6d3540ea6093109c22856e3ae201dfd58c0fc",moduleName:"AtomicSwap"},[b.Network.LOCALNET]:{packageId:"",moduleName:""}},cw={asset:oe.ChainAsset.from(oe.SupportedAssets.mainnet.base.cBBTC)};var Si=(t=>(t.SLOW="SLOW",t.MEDIUM="MEDIUM",t.FAST="FAST",t))(Si||{}),qt=(t=>(t.Mainnet="Mainnet",t.Testnet="Testnet",t.Regtest="Regtest",t))(qt||{}),rc=(t=>(t.ALL="ALL",t.IN="IN",t.OUT="OUT",t))(rc||{});const H_={SLOW:"economyFee",MEDIUM:"hourFee",FAST:"fastestFee"};function ed(t){const e=typeof t=="string"?t:t.network,r=e===b.Network.MAINNET?tc.mainnet:b.Network.TESTNET?tc.testnet:tc.localnet;return{api:typeof t=="string"?r:{...r,...t},network:e}}function z_(t){return typeof t=="string"&&(t=Buffer.from(t,"hex")),t.length===32?t:t.subarray(1,33)}function Xp(t,e){if(!t)throw new Error(e)}function V_(t){return Buffer.concat([Uint8Array.from([192]),q_(t)])}function q_(t){const e=Qh.encodingLength(t.length),r=Buffer.allocUnsafe(e);return Qh.encode(t.length,r),Buffer.concat([r,t])}function G_(t,e){if(t.compare(e)>0){const r=t;t=e,e=r}return[t,e]}const Me=t=>t.length===64?t:t.slice(2),W_=t=>{if(!t)return!1;try{const e=Buffer.from(t,"hex");return cr.isPoint(e)}catch{return!1}},uw=(t,e,r,n)=>t+":"+e.toLowerCase()+"::"+r+":"+n.toLowerCase();function K_(t,e){if(!t)return!1;const r=e===b.Environment.MAINNET?Ae.networks.bitcoin:e===b.Environment.TESTNET?Ae.networks.testnet:Ae.networks.regtest;if(!r)return!1;Ae.initEccLib(cr);try{return Ae.address.toOutputScript(t,r),!0}catch{return!1}}function to(t,e){const r=[];for(let n=0;n<e;n++)r.push(t);return r}const Hu=t=>{switch(t){case b.Network.MAINNET:return qt.Mainnet;case b.Network.TESTNET:return qt.Testnet;case b.Network.LOCALNET:return qt.Regtest;default:throw new Error(`Invalid bitcoin network ${t}`)}},Z_=t=>{const e=t.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(e)},Yp=t=>{if(typeof t=="object"&&"r"in t&&"s"in t)return b.Ok([t.r.toString(),t.s.toString()]);if(Array.isArray(t)){const e=t.map(r=>typeof r=="string"&&r.startsWith("0x")&&Z_(r)?BigInt(r).toString():r);return b.Ok(e)}return b.Err("Invalid signature format")};function td(t){return Buffer.from(t,"hex").reverse()}function rd(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"}const zu=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 b.Fetcher.get(e+"/v2/assets");if(r.error)return b.Err("Failed to fetch asset info: "+r.error);const s=(r.result||[]).find(l=>l.id===t);if(!s)return b.Err(`Asset info not found for asset id: ${t}`);const i=((a=s.htlc)==null?void 0:a.address)||"",o=((c=s.token)==null?void 0:c.address)||"";return b.Ok({htlcAddress:i,tokenAddress:o})},Jp=t=>{if(t==null||t.includes("."))return b.Err("Invalid amount ",t);const e=new Gv.BigNumber(t);return!e.isInteger()||e.isNaN()||e.lt(0)||e.isLessThanOrEqualTo(0)?b.Err("Invalid amount ",t):b.Ok(e)},X_=t=>(t??[]).map(e=>({fee:e.fee,address:e.address,asset:e.asset??cw.asset})),Qp=async(t,e,r)=>{var n;if(r&&r[t])return b.Ok(r[t]);switch(t){case oe.BlockchainType.evm:return e.evm?b.Ok(e.evm.htlcActorAddress):b.Err("Please provide evmHTLC when initializing garden or pass EVM address in SwapParams");case oe.BlockchainType.bitcoin:{const s=await((n=e.bitcoin)==null?void 0:n.getPublicKey());return!s||!W_(s)?b.Err("Invalid btc public key or pass Bitcoin address in SwapParams"):b.Ok(Me(s))}case oe.BlockchainType.solana:return e.solana?b.Ok(e.solana.htlcActorAddress):b.Err("Please provide solanaHTLC when initializing garden or pass Solana address in SwapParams");case oe.BlockchainType.starknet:return e.starknet?b.Ok(e.starknet.htlcActorAddress):b.Err("Please provide starknetHTLC when initializing garden or pass Starknet address in SwapParams");case oe.BlockchainType.sui:return e.sui?b.Ok(e.sui.htlcActorAddress):b.Err("Please provide suiHTLC when initializing garden or pass Sui address in SwapParams");default:return b.Err("Unsupported chain")}},Y_=async(t,e)=>{const n={[oe.BlockchainType.evm]:{htlc:e.evm,name:"EVM"},[oe.BlockchainType.solana]:{htlc:e.solana,name:"Solana"},[oe.BlockchainType.starknet]:{htlc:e.starknet,name:"Starknet"},[oe.BlockchainType.sui]:{htlc:e.sui,name:"Sui"},[oe.BlockchainType.bitcoin]:{htlc:e.bitcoin,name:"Bitcoin"}}[t];return n?n.htlc?b.Ok(void 0):b.Err(`${n.name} HTLC is required for swap initiation. Please provide ${n.name.toLowerCase()}HTLC when initializing garden.`):b.Err(`Unsupported blockchain type for swap initiation: ${t}`)},J_=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),Q_=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),eT=Buffer.concat([J_,Q_]),tT=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),ey={failedToCreateInternalPubkey:"failed to create internal pubkey"};function ty(){const t=pe.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),e=cr.pointMultiply(Buffer.concat([Buffer.from("04","hex"),eT]),t);if(!e)throw new Error(ey.failedToCreateInternalPubkey);const r=cr.pointAdd(tT,e);if(!r)throw new Error(ey.failedToCreateInternalPubkey);return z_(Buffer.from(r))}var Jr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function lw(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}),r}var Fe={},vt={},Js={},Yc={};Yc.byteLength=sT;Yc.toByteArray=oT;Yc.fromByteArray=uT;var qr=[],rr=[],rT=typeof Uint8Array<"u"?Uint8Array:Array,Vu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var ii=0,nT=Vu.length;ii<nT;++ii)qr[ii]=Vu[ii],rr[Vu.charCodeAt(ii)]=ii;rr[45]=62;rr[95]=63;function fw(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 sT(t){var e=fw(t),r=e[0],n=e[1];return(r+n)*3/4-n}function iT(t,e,r){return(e+r)*3/4-r}function oT(t){var e,r=fw(t),n=r[0],s=r[1],i=new rT(iT(t,n,s)),o=0,a=s>0?n-4:n,c;for(c=0;c<a;c+=4)e=rr[t.charCodeAt(c)]<<18|rr[t.charCodeAt(c+1)]<<12|rr[t.charCodeAt(c+2)]<<6|rr[t.charCodeAt(c+3)],i[o++]=e>>16&255,i[o++]=e>>8&255,i[o++]=e&255;return s===2&&(e=rr[t.charCodeAt(c)]<<2|rr[t.charCodeAt(c+1)]>>4,i[o++]=e&255),s===1&&(e=rr[t.charCodeAt(c)]<<10|rr[t.charCodeAt(c+1)]<<4|rr[t.charCodeAt(c+2)]>>2,i[o++]=e>>8&255,i[o++]=e&255),i}function aT(t){return qr[t>>18&63]+qr[t>>12&63]+qr[t>>6&63]+qr[t&63]}function cT(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(aT(n));return s.join("")}function uT(t){for(var e,r=t.length,n=r%3,s=[],i=16383,o=0,a=r-n;o<a;o+=i)s.push(cT(t,o,o+i>a?a:o+i));return n===1?(e=t[r-1],s.push(qr[e>>2]+qr[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],s.push(qr[e>>10]+qr[e>>4&63]+qr[e<<2&63]+"=")),s.join("")}var yh={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */yh.read=function(t,e,r,n,s){var i,o,a=s*8-n-1,c=(1<<a)-1,l=c>>1,u=-7,f=r?s-1:0,h=r?-1:1,d=t[e+f];for(f+=h,i=d&(1<<-u)-1,d>>=-u,u+=a;u>0;i=i*256+t[e+f],f+=h,u-=8);for(o=i&(1<<-u)-1,i>>=-u,u+=n;u>0;o=o*256+t[e+f],f+=h,u-=8);if(i===0)i=1-l;else{if(i===c)return o?NaN:(d?-1:1)*(1/0);o=o+Math.pow(2,n),i=i-l}return(d?-1:1)*o*Math.pow(2,i-n)};yh.write=function(t,e,r,n,s,i){var o,a,c,l=i*8-s-1,u=(1<<l)-1,f=u>>1,h=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,m=n?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+f>=1?e+=h/c:e+=h*Math.pow(2,1-f),e*c>=2&&(o++,c/=2),o+f>=u?(a=0,o=u):o+f>=1?(a=(e*c-1)*Math.pow(2,s),o=o+f):(a=e*Math.pow(2,f-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,l+=s;l>0;t[r+d]=o&255,d+=m,o/=256,l-=8);t[r+d-m]|=g*128};/*!
47
- * The buffer module from node.js, for the browser.
48
- *
49
- * @author Feross Aboukhadijeh <https://feross.org>
50
- * @license MIT
51
- */(function(t){const e=Yc,r=yh,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=a,t.SlowBuffer=_,t.INSPECT_MAX_BYTES=50;const s=2147483647;t.kMaxLength=s,a.TYPED_ARRAY_SUPPORT=i(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function i(){try{const w=new Uint8Array(1),p={foo:function(){return 42}};return Object.setPrototypeOf(p,Uint8Array.prototype),Object.setPrototypeOf(w,p),w.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(w){if(w>s)throw new RangeError('The value "'+w+'" is invalid for option "size"');const p=new Uint8Array(w);return Object.setPrototypeOf(p,a.prototype),p}function a(w,p,y){if(typeof w=="number"){if(typeof p=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return f(w)}return c(w,p,y)}a.poolSize=8192;function c(w,p,y){if(typeof w=="string")return h(w,p);if(ArrayBuffer.isView(w))return m(w);if(w==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof w);if(St(w,ArrayBuffer)||w&&St(w.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(St(w,SharedArrayBuffer)||w&&St(w.buffer,SharedArrayBuffer)))return g(w,p,y);if(typeof w=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const A=w.valueOf&&w.valueOf();if(A!=null&&A!==w)return a.from(A,p,y);const B=v(w);if(B)return B;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof w[Symbol.toPrimitive]=="function")return a.from(w[Symbol.toPrimitive]("string"),p,y);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof w)}a.from=function(w,p,y){return c(w,p,y)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function l(w){if(typeof w!="number")throw new TypeError('"size" argument must be of type number');if(w<0)throw new RangeError('The value "'+w+'" is invalid for option "size"')}function u(w,p,y){return l(w),w<=0?o(w):p!==void 0?typeof y=="string"?o(w).fill(p,y):o(w).fill(p):o(w)}a.alloc=function(w,p,y){return u(w,p,y)};function f(w){return l(w),o(w<0?0:S(w)|0)}a.allocUnsafe=function(w){return f(w)},a.allocUnsafeSlow=function(w){return f(w)};function h(w,p){if((typeof p!="string"||p==="")&&(p="utf8"),!a.isEncoding(p))throw new TypeError("Unknown encoding: "+p);const y=E(w,p)|0;let A=o(y);const B=A.write(w,p);return B!==y&&(A=A.slice(0,B)),A}function d(w){const p=w.length<0?0:S(w.length)|0,y=o(p);for(let A=0;A<p;A+=1)y[A]=w[A]&255;return y}function m(w){if(St(w,Uint8Array)){const p=new Uint8Array(w);return g(p.buffer,p.byteOffset,p.byteLength)}return d(w)}function g(w,p,y){if(p<0||w.byteLength<p)throw new RangeError('"offset" is outside of buffer bounds');if(w.byteLength<p+(y||0))throw new RangeError('"length" is outside of buffer bounds');let A;return p===void 0&&y===void 0?A=new Uint8Array(w):y===void 0?A=new Uint8Array(w,p):A=new Uint8Array(w,p,y),Object.setPrototypeOf(A,a.prototype),A}function v(w){if(a.isBuffer(w)){const p=S(w.length)|0,y=o(p);return y.length===0||w.copy(y,0,0,p),y}if(w.length!==void 0)return typeof w.length!="number"||Cn(w.length)?o(0):d(w);if(w.type==="Buffer"&&Array.isArray(w.data))return d(w.data)}function S(w){if(w>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return w|0}function _(w){return+w!=w&&(w=0),a.alloc(+w)}a.isBuffer=function(p){return p!=null&&p._isBuffer===!0&&p!==a.prototype},a.compare=function(p,y){if(St(p,Uint8Array)&&(p=a.from(p,p.offset,p.byteLength)),St(y,Uint8Array)&&(y=a.from(y,y.offset,y.byteLength)),!a.isBuffer(p)||!a.isBuffer(y))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(p===y)return 0;let A=p.length,B=y.length;for(let M=0,V=Math.min(A,B);M<V;++M)if(p[M]!==y[M]){A=p[M],B=y[M];break}return A<B?-1:B<A?1:0},a.isEncoding=function(p){switch(String(p).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(p,y){if(!Array.isArray(p))throw new TypeError('"list" argument must be an Array of Buffers');if(p.length===0)return a.alloc(0);let A;if(y===void 0)for(y=0,A=0;A<p.length;++A)y+=p[A].length;const B=a.allocUnsafe(y);let M=0;for(A=0;A<p.length;++A){let V=p[A];if(St(V,Uint8Array))M+V.length>B.length?(a.isBuffer(V)||(V=a.from(V)),V.copy(B,M)):Uint8Array.prototype.set.call(B,V,M);else if(a.isBuffer(V))V.copy(B,M);else throw new TypeError('"list" argument must be an Array of Buffers');M+=V.length}return B};function E(w,p){if(a.isBuffer(w))return w.length;if(ArrayBuffer.isView(w)||St(w,ArrayBuffer))return w.byteLength;if(typeof w!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof w);const y=w.length,A=arguments.length>2&&arguments[2]===!0;if(!A&&y===0)return 0;let B=!1;for(;;)switch(p){case"ascii":case"latin1":case"binary":return y;case"utf8":case"utf-8":return $r(w).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return y*2;case"hex":return y>>>1;case"base64":return Rr(w).length;default:if(B)return A?-1:$r(w).length;p=(""+p).toLowerCase(),B=!0}}a.byteLength=E;function x(w,p,y){let A=!1;if((p===void 0||p<0)&&(p=0),p>this.length||((y===void 0||y>this.length)&&(y=this.length),y<=0)||(y>>>=0,p>>>=0,y<=p))return"";for(w||(w="utf8");;)switch(w){case"hex":return T(this,p,y);case"utf8":case"utf-8":return N(this,p,y);case"ascii":return ee(this,p,y);case"latin1":case"binary":return D(this,p,y);case"base64":return U(this,p,y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,p,y);default:if(A)throw new TypeError("Unknown encoding: "+w);w=(w+"").toLowerCase(),A=!0}}a.prototype._isBuffer=!0;function O(w,p,y){const A=w[p];w[p]=w[y],w[y]=A}a.prototype.swap16=function(){const p=this.length;if(p%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let y=0;y<p;y+=2)O(this,y,y+1);return this},a.prototype.swap32=function(){const p=this.length;if(p%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let y=0;y<p;y+=4)O(this,y,y+3),O(this,y+1,y+2);return this},a.prototype.swap64=function(){const p=this.length;if(p%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let y=0;y<p;y+=8)O(this,y,y+7),O(this,y+1,y+6),O(this,y+2,y+5),O(this,y+3,y+4);return this},a.prototype.toString=function(){const p=this.length;return p===0?"":arguments.length===0?N(this,0,p):x.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(p){if(!a.isBuffer(p))throw new TypeError("Argument must be a Buffer");return this===p?!0:a.compare(this,p)===0},a.prototype.inspect=function(){let p="";const y=t.INSPECT_MAX_BYTES;return p=this.toString("hex",0,y).replace(/(.{2})/g,"$1 ").trim(),this.length>y&&(p+=" ... "),"<Buffer "+p+">"},n&&(a.prototype[n]=a.prototype.inspect),a.prototype.compare=function(p,y,A,B,M){if(St(p,Uint8Array)&&(p=a.from(p,p.offset,p.byteLength)),!a.isBuffer(p))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof p);if(y===void 0&&(y=0),A===void 0&&(A=p?p.length:0),B===void 0&&(B=0),M===void 0&&(M=this.length),y<0||A>p.length||B<0||M>this.length)throw new RangeError("out of range index");if(B>=M&&y>=A)return 0;if(B>=M)return-1;if(y>=A)return 1;if(y>>>=0,A>>>=0,B>>>=0,M>>>=0,this===p)return 0;let V=M-B,ge=A-y;const De=Math.min(V,ge),$e=this.slice(B,M),He=p.slice(y,A);for(let xe=0;xe<De;++xe)if($e[xe]!==He[xe]){V=$e[xe],ge=He[xe];break}return V<ge?-1:ge<V?1:0};function P(w,p,y,A,B){if(w.length===0)return-1;if(typeof y=="string"?(A=y,y=0):y>2147483647?y=2147483647:y<-2147483648&&(y=-2147483648),y=+y,Cn(y)&&(y=B?0:w.length-1),y<0&&(y=w.length+y),y>=w.length){if(B)return-1;y=w.length-1}else if(y<0)if(B)y=0;else return-1;if(typeof p=="string"&&(p=a.from(p,A)),a.isBuffer(p))return p.length===0?-1:$(w,p,y,A,B);if(typeof p=="number")return p=p&255,typeof Uint8Array.prototype.indexOf=="function"?B?Uint8Array.prototype.indexOf.call(w,p,y):Uint8Array.prototype.lastIndexOf.call(w,p,y):$(w,[p],y,A,B);throw new TypeError("val must be string, number or Buffer")}function $(w,p,y,A,B){let M=1,V=w.length,ge=p.length;if(A!==void 0&&(A=String(A).toLowerCase(),A==="ucs2"||A==="ucs-2"||A==="utf16le"||A==="utf-16le")){if(w.length<2||p.length<2)return-1;M=2,V/=2,ge/=2,y/=2}function De(He,xe){return M===1?He[xe]:He.readUInt16BE(xe*M)}let $e;if(B){let He=-1;for($e=y;$e<V;$e++)if(De(w,$e)===De(p,He===-1?0:$e-He)){if(He===-1&&(He=$e),$e-He+1===ge)return He*M}else He!==-1&&($e-=$e-He),He=-1}else for(y+ge>V&&(y=V-ge),$e=y;$e>=0;$e--){let He=!0;for(let xe=0;xe<ge;xe++)if(De(w,$e+xe)!==De(p,xe)){He=!1;break}if(He)return $e}return-1}a.prototype.includes=function(p,y,A){return this.indexOf(p,y,A)!==-1},a.prototype.indexOf=function(p,y,A){return P(this,p,y,A,!0)},a.prototype.lastIndexOf=function(p,y,A){return P(this,p,y,A,!1)};function z(w,p,y,A){y=Number(y)||0;const B=w.length-y;A?(A=Number(A),A>B&&(A=B)):A=B;const M=p.length;A>M/2&&(A=M/2);let V;for(V=0;V<A;++V){const ge=parseInt(p.substr(V*2,2),16);if(Cn(ge))return V;w[y+V]=ge}return V}function C(w,p,y,A){return Et($r(p,w.length-y),w,y,A)}function Y(w,p,y,A){return Et(us(p),w,y,A)}function W(w,p,y,A){return Et(Rr(p),w,y,A)}function K(w,p,y,A){return Et(q(p,w.length-y),w,y,A)}a.prototype.write=function(p,y,A,B){if(y===void 0)B="utf8",A=this.length,y=0;else if(A===void 0&&typeof y=="string")B=y,A=this.length,y=0;else if(isFinite(y))y=y>>>0,isFinite(A)?(A=A>>>0,B===void 0&&(B="utf8")):(B=A,A=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const M=this.length-y;if((A===void 0||A>M)&&(A=M),p.length>0&&(A<0||y<0)||y>this.length)throw new RangeError("Attempt to write outside buffer bounds");B||(B="utf8");let V=!1;for(;;)switch(B){case"hex":return z(this,p,y,A);case"utf8":case"utf-8":return C(this,p,y,A);case"ascii":case"latin1":case"binary":return Y(this,p,y,A);case"base64":return W(this,p,y,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return K(this,p,y,A);default:if(V)throw new TypeError("Unknown encoding: "+B);B=(""+B).toLowerCase(),V=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function U(w,p,y){return p===0&&y===w.length?e.fromByteArray(w):e.fromByteArray(w.slice(p,y))}function N(w,p,y){y=Math.min(w.length,y);const A=[];let B=p;for(;B<y;){const M=w[B];let V=null,ge=M>239?4:M>223?3:M>191?2:1;if(B+ge<=y){let De,$e,He,xe;switch(ge){case 1:M<128&&(V=M);break;case 2:De=w[B+1],(De&192)===128&&(xe=(M&31)<<6|De&63,xe>127&&(V=xe));break;case 3:De=w[B+1],$e=w[B+2],(De&192)===128&&($e&192)===128&&(xe=(M&15)<<12|(De&63)<<6|$e&63,xe>2047&&(xe<55296||xe>57343)&&(V=xe));break;case 4:De=w[B+1],$e=w[B+2],He=w[B+3],(De&192)===128&&($e&192)===128&&(He&192)===128&&(xe=(M&15)<<18|(De&63)<<12|($e&63)<<6|He&63,xe>65535&&xe<1114112&&(V=xe))}}V===null?(V=65533,ge=1):V>65535&&(V-=65536,A.push(V>>>10&1023|55296),V=56320|V&1023),A.push(V),B+=ge}return Z(A)}const F=4096;function Z(w){const p=w.length;if(p<=F)return String.fromCharCode.apply(String,w);let y="",A=0;for(;A<p;)y+=String.fromCharCode.apply(String,w.slice(A,A+=F));return y}function ee(w,p,y){let A="";y=Math.min(w.length,y);for(let B=p;B<y;++B)A+=String.fromCharCode(w[B]&127);return A}function D(w,p,y){let A="";y=Math.min(w.length,y);for(let B=p;B<y;++B)A+=String.fromCharCode(w[B]);return A}function T(w,p,y){const A=w.length;(!p||p<0)&&(p=0),(!y||y<0||y>A)&&(y=A);let B="";for(let M=p;M<y;++M)B+=ri[w[M]];return B}function L(w,p,y){const A=w.slice(p,y);let B="";for(let M=0;M<A.length-1;M+=2)B+=String.fromCharCode(A[M]+A[M+1]*256);return B}a.prototype.slice=function(p,y){const A=this.length;p=~~p,y=y===void 0?A:~~y,p<0?(p+=A,p<0&&(p=0)):p>A&&(p=A),y<0?(y+=A,y<0&&(y=0)):y>A&&(y=A),y<p&&(y=p);const B=this.subarray(p,y);return Object.setPrototypeOf(B,a.prototype),B};function G(w,p,y){if(w%1!==0||w<0)throw new RangeError("offset is not uint");if(w+p>y)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(p,y,A){p=p>>>0,y=y>>>0,A||G(p,y,this.length);let B=this[p],M=1,V=0;for(;++V<y&&(M*=256);)B+=this[p+V]*M;return B},a.prototype.readUintBE=a.prototype.readUIntBE=function(p,y,A){p=p>>>0,y=y>>>0,A||G(p,y,this.length);let B=this[p+--y],M=1;for(;y>0&&(M*=256);)B+=this[p+--y]*M;return B},a.prototype.readUint8=a.prototype.readUInt8=function(p,y){return p=p>>>0,y||G(p,1,this.length),this[p]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(p,y){return p=p>>>0,y||G(p,2,this.length),this[p]|this[p+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(p,y){return p=p>>>0,y||G(p,2,this.length),this[p]<<8|this[p+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(p,y){return p=p>>>0,y||G(p,4,this.length),(this[p]|this[p+1]<<8|this[p+2]<<16)+this[p+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(p,y){return p=p>>>0,y||G(p,4,this.length),this[p]*16777216+(this[p+1]<<16|this[p+2]<<8|this[p+3])},a.prototype.readBigUInt64LE=$n(function(p){p=p>>>0,Ee(p,"offset");const y=this[p],A=this[p+7];(y===void 0||A===void 0)&&Ue(p,this.length-8);const B=y+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24,M=this[++p]+this[++p]*2**8+this[++p]*2**16+A*2**24;return BigInt(B)+(BigInt(M)<<BigInt(32))}),a.prototype.readBigUInt64BE=$n(function(p){p=p>>>0,Ee(p,"offset");const y=this[p],A=this[p+7];(y===void 0||A===void 0)&&Ue(p,this.length-8);const B=y*2**24+this[++p]*2**16+this[++p]*2**8+this[++p],M=this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+A;return(BigInt(B)<<BigInt(32))+BigInt(M)}),a.prototype.readIntLE=function(p,y,A){p=p>>>0,y=y>>>0,A||G(p,y,this.length);let B=this[p],M=1,V=0;for(;++V<y&&(M*=256);)B+=this[p+V]*M;return M*=128,B>=M&&(B-=Math.pow(2,8*y)),B},a.prototype.readIntBE=function(p,y,A){p=p>>>0,y=y>>>0,A||G(p,y,this.length);let B=y,M=1,V=this[p+--B];for(;B>0&&(M*=256);)V+=this[p+--B]*M;return M*=128,V>=M&&(V-=Math.pow(2,8*y)),V},a.prototype.readInt8=function(p,y){return p=p>>>0,y||G(p,1,this.length),this[p]&128?(255-this[p]+1)*-1:this[p]},a.prototype.readInt16LE=function(p,y){p=p>>>0,y||G(p,2,this.length);const A=this[p]|this[p+1]<<8;return A&32768?A|4294901760:A},a.prototype.readInt16BE=function(p,y){p=p>>>0,y||G(p,2,this.length);const A=this[p+1]|this[p]<<8;return A&32768?A|4294901760:A},a.prototype.readInt32LE=function(p,y){return p=p>>>0,y||G(p,4,this.length),this[p]|this[p+1]<<8|this[p+2]<<16|this[p+3]<<24},a.prototype.readInt32BE=function(p,y){return p=p>>>0,y||G(p,4,this.length),this[p]<<24|this[p+1]<<16|this[p+2]<<8|this[p+3]},a.prototype.readBigInt64LE=$n(function(p){p=p>>>0,Ee(p,"offset");const y=this[p],A=this[p+7];(y===void 0||A===void 0)&&Ue(p,this.length-8);const B=this[p+4]+this[p+5]*2**8+this[p+6]*2**16+(A<<24);return(BigInt(B)<<BigInt(32))+BigInt(y+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24)}),a.prototype.readBigInt64BE=$n(function(p){p=p>>>0,Ee(p,"offset");const y=this[p],A=this[p+7];(y===void 0||A===void 0)&&Ue(p,this.length-8);const B=(y<<24)+this[++p]*2**16+this[++p]*2**8+this[++p];return(BigInt(B)<<BigInt(32))+BigInt(this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+A)}),a.prototype.readFloatLE=function(p,y){return p=p>>>0,y||G(p,4,this.length),r.read(this,p,!0,23,4)},a.prototype.readFloatBE=function(p,y){return p=p>>>0,y||G(p,4,this.length),r.read(this,p,!1,23,4)},a.prototype.readDoubleLE=function(p,y){return p=p>>>0,y||G(p,8,this.length),r.read(this,p,!0,52,8)},a.prototype.readDoubleBE=function(p,y){return p=p>>>0,y||G(p,8,this.length),r.read(this,p,!1,52,8)};function I(w,p,y,A,B,M){if(!a.isBuffer(w))throw new TypeError('"buffer" argument must be a Buffer instance');if(p>B||p<M)throw new RangeError('"value" argument is out of bounds');if(y+A>w.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(p,y,A,B){if(p=+p,y=y>>>0,A=A>>>0,!B){const ge=Math.pow(2,8*A)-1;I(this,p,y,A,ge,0)}let M=1,V=0;for(this[y]=p&255;++V<A&&(M*=256);)this[y+V]=p/M&255;return y+A},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(p,y,A,B){if(p=+p,y=y>>>0,A=A>>>0,!B){const ge=Math.pow(2,8*A)-1;I(this,p,y,A,ge,0)}let M=A-1,V=1;for(this[y+M]=p&255;--M>=0&&(V*=256);)this[y+M]=p/V&255;return y+A},a.prototype.writeUint8=a.prototype.writeUInt8=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,1,255,0),this[y]=p&255,y+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,2,65535,0),this[y]=p&255,this[y+1]=p>>>8,y+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,2,65535,0),this[y]=p>>>8,this[y+1]=p&255,y+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,4,4294967295,0),this[y+3]=p>>>24,this[y+2]=p>>>16,this[y+1]=p>>>8,this[y]=p&255,y+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,4,4294967295,0),this[y]=p>>>24,this[y+1]=p>>>16,this[y+2]=p>>>8,this[y+3]=p&255,y+4};function R(w,p,y,A,B){be(p,A,B,w,y,7);let M=Number(p&BigInt(4294967295));w[y++]=M,M=M>>8,w[y++]=M,M=M>>8,w[y++]=M,M=M>>8,w[y++]=M;let V=Number(p>>BigInt(32)&BigInt(4294967295));return w[y++]=V,V=V>>8,w[y++]=V,V=V>>8,w[y++]=V,V=V>>8,w[y++]=V,y}function j(w,p,y,A,B){be(p,A,B,w,y,7);let M=Number(p&BigInt(4294967295));w[y+7]=M,M=M>>8,w[y+6]=M,M=M>>8,w[y+5]=M,M=M>>8,w[y+4]=M;let V=Number(p>>BigInt(32)&BigInt(4294967295));return w[y+3]=V,V=V>>8,w[y+2]=V,V=V>>8,w[y+1]=V,V=V>>8,w[y]=V,y+8}a.prototype.writeBigUInt64LE=$n(function(p,y=0){return R(this,p,y,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=$n(function(p,y=0){return j(this,p,y,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(p,y,A,B){if(p=+p,y=y>>>0,!B){const De=Math.pow(2,8*A-1);I(this,p,y,A,De-1,-De)}let M=0,V=1,ge=0;for(this[y]=p&255;++M<A&&(V*=256);)p<0&&ge===0&&this[y+M-1]!==0&&(ge=1),this[y+M]=(p/V>>0)-ge&255;return y+A},a.prototype.writeIntBE=function(p,y,A,B){if(p=+p,y=y>>>0,!B){const De=Math.pow(2,8*A-1);I(this,p,y,A,De-1,-De)}let M=A-1,V=1,ge=0;for(this[y+M]=p&255;--M>=0&&(V*=256);)p<0&&ge===0&&this[y+M+1]!==0&&(ge=1),this[y+M]=(p/V>>0)-ge&255;return y+A},a.prototype.writeInt8=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,1,127,-128),p<0&&(p=255+p+1),this[y]=p&255,y+1},a.prototype.writeInt16LE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,2,32767,-32768),this[y]=p&255,this[y+1]=p>>>8,y+2},a.prototype.writeInt16BE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,2,32767,-32768),this[y]=p>>>8,this[y+1]=p&255,y+2},a.prototype.writeInt32LE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,4,2147483647,-2147483648),this[y]=p&255,this[y+1]=p>>>8,this[y+2]=p>>>16,this[y+3]=p>>>24,y+4},a.prototype.writeInt32BE=function(p,y,A){return p=+p,y=y>>>0,A||I(this,p,y,4,2147483647,-2147483648),p<0&&(p=4294967295+p+1),this[y]=p>>>24,this[y+1]=p>>>16,this[y+2]=p>>>8,this[y+3]=p&255,y+4},a.prototype.writeBigInt64LE=$n(function(p,y=0){return R(this,p,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=$n(function(p,y=0){return j(this,p,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function J(w,p,y,A,B,M){if(y+A>w.length)throw new RangeError("Index out of range");if(y<0)throw new RangeError("Index out of range")}function ne(w,p,y,A,B){return p=+p,y=y>>>0,B||J(w,p,y,4),r.write(w,p,y,A,23,4),y+4}a.prototype.writeFloatLE=function(p,y,A){return ne(this,p,y,!0,A)},a.prototype.writeFloatBE=function(p,y,A){return ne(this,p,y,!1,A)};function ue(w,p,y,A,B){return p=+p,y=y>>>0,B||J(w,p,y,8),r.write(w,p,y,A,52,8),y+8}a.prototype.writeDoubleLE=function(p,y,A){return ue(this,p,y,!0,A)},a.prototype.writeDoubleBE=function(p,y,A){return ue(this,p,y,!1,A)},a.prototype.copy=function(p,y,A,B){if(!a.isBuffer(p))throw new TypeError("argument should be a Buffer");if(A||(A=0),!B&&B!==0&&(B=this.length),y>=p.length&&(y=p.length),y||(y=0),B>0&&B<A&&(B=A),B===A||p.length===0||this.length===0)return 0;if(y<0)throw new RangeError("targetStart out of bounds");if(A<0||A>=this.length)throw new RangeError("Index out of range");if(B<0)throw new RangeError("sourceEnd out of bounds");B>this.length&&(B=this.length),p.length-y<B-A&&(B=p.length-y+A);const M=B-A;return this===p&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(y,A,B):Uint8Array.prototype.set.call(p,this.subarray(A,B),y),M},a.prototype.fill=function(p,y,A,B){if(typeof p=="string"){if(typeof y=="string"?(B=y,y=0,A=this.length):typeof A=="string"&&(B=A,A=this.length),B!==void 0&&typeof B!="string")throw new TypeError("encoding must be a string");if(typeof B=="string"&&!a.isEncoding(B))throw new TypeError("Unknown encoding: "+B);if(p.length===1){const V=p.charCodeAt(0);(B==="utf8"&&V<128||B==="latin1")&&(p=V)}}else typeof p=="number"?p=p&255:typeof p=="boolean"&&(p=Number(p));if(y<0||this.length<y||this.length<A)throw new RangeError("Out of range index");if(A<=y)return this;y=y>>>0,A=A===void 0?this.length:A>>>0,p||(p=0);let M;if(typeof p=="number")for(M=y;M<A;++M)this[M]=p;else{const V=a.isBuffer(p)?p:a.from(p,B),ge=V.length;if(ge===0)throw new TypeError('The value "'+p+'" is invalid for argument "value"');for(M=0;M<A-y;++M)this[M+y]=V[M%ge]}return this};const ce={};function se(w,p,y){ce[w]=class extends y{constructor(){super(),Object.defineProperty(this,"message",{value:p.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${w}]`,this.stack,delete this.name}get code(){return w}set code(B){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:B,writable:!0})}toString(){return`${this.name} [${w}]: ${this.message}`}}}se("ERR_BUFFER_OUT_OF_BOUNDS",function(w){return w?`${w} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),se("ERR_INVALID_ARG_TYPE",function(w,p){return`The "${w}" argument must be of type number. Received type ${typeof p}`},TypeError),se("ERR_OUT_OF_RANGE",function(w,p,y){let A=`The value of "${w}" is out of range.`,B=y;return Number.isInteger(y)&&Math.abs(y)>2**32?B=ie(String(y)):typeof y=="bigint"&&(B=String(y),(y>BigInt(2)**BigInt(32)||y<-(BigInt(2)**BigInt(32)))&&(B=ie(B)),B+="n"),A+=` It must be ${p}. Received ${B}`,A},RangeError);function ie(w){let p="",y=w.length;const A=w[0]==="-"?1:0;for(;y>=A+4;y-=3)p=`_${w.slice(y-3,y)}${p}`;return`${w.slice(0,y)}${p}`}function me(w,p,y){Ee(p,"offset"),(w[p]===void 0||w[p+y]===void 0)&&Ue(p,w.length-(y+1))}function be(w,p,y,A,B,M){if(w>y||w<p){const V=typeof p=="bigint"?"n":"";let ge;throw p===0||p===BigInt(0)?ge=`>= 0${V} and < 2${V} ** ${(M+1)*8}${V}`:ge=`>= -(2${V} ** ${(M+1)*8-1}${V}) and < 2 ** ${(M+1)*8-1}${V}`,new ce.ERR_OUT_OF_RANGE("value",ge,w)}me(A,B,M)}function Ee(w,p){if(typeof w!="number")throw new ce.ERR_INVALID_ARG_TYPE(p,"number",w)}function Ue(w,p,y){throw Math.floor(w)!==w?(Ee(w,y),new ce.ERR_OUT_OF_RANGE("offset","an integer",w)):p<0?new ce.ERR_BUFFER_OUT_OF_BOUNDS:new ce.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${p}`,w)}const Dt=/[^+/0-9A-Za-z-_]/g;function et(w){if(w=w.split("=")[0],w=w.trim().replace(Dt,""),w.length<2)return"";for(;w.length%4!==0;)w=w+"=";return w}function $r(w,p){p=p||1/0;let y;const A=w.length;let B=null;const M=[];for(let V=0;V<A;++V){if(y=w.charCodeAt(V),y>55295&&y<57344){if(!B){if(y>56319){(p-=3)>-1&&M.push(239,191,189);continue}else if(V+1===A){(p-=3)>-1&&M.push(239,191,189);continue}B=y;continue}if(y<56320){(p-=3)>-1&&M.push(239,191,189),B=y;continue}y=(B-55296<<10|y-56320)+65536}else B&&(p-=3)>-1&&M.push(239,191,189);if(B=null,y<128){if((p-=1)<0)break;M.push(y)}else if(y<2048){if((p-=2)<0)break;M.push(y>>6|192,y&63|128)}else if(y<65536){if((p-=3)<0)break;M.push(y>>12|224,y>>6&63|128,y&63|128)}else if(y<1114112){if((p-=4)<0)break;M.push(y>>18|240,y>>12&63|128,y>>6&63|128,y&63|128)}else throw new Error("Invalid code point")}return M}function us(w){const p=[];for(let y=0;y<w.length;++y)p.push(w.charCodeAt(y)&255);return p}function q(w,p){let y,A,B;const M=[];for(let V=0;V<w.length&&!((p-=2)<0);++V)y=w.charCodeAt(V),A=y>>8,B=y%256,M.push(B),M.push(A);return M}function Rr(w){return e.toByteArray(et(w))}function Et(w,p,y,A){let B;for(B=0;B<A&&!(B+y>=p.length||B>=w.length);++B)p[B+y]=w[B];return B}function St(w,p){return w instanceof p||w!=null&&w.constructor!=null&&w.constructor.name!=null&&w.constructor.name===p.name}function Cn(w){return w!==w}const ri=function(){const w="0123456789abcdef",p=new Array(256);for(let y=0;y<16;++y){const A=y*16;for(let B=0;B<16;++B)p[A+B]=w[y]+w[B]}return p}();function $n(w){return typeof BigInt>"u"?Hv:w}function Hv(){throw new Error("BigInt not supported")}})(Js);var Xo={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}};Xo.Null=Xo.Nil;for(var ry in Xo)Xo[ry].toJSON=(function(t){return t}).bind(null,ry);var mh=Xo,Is=mh;function dw(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function gh(t){return Is.Nil(t)?"":dw(t.constructor)}function lT(t){return Is.Function(t)?"":Is.String(t)?JSON.stringify(t):t&&Is.Object(t)?"":t}function bh(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function bc(t){return Is.Function(t)?t.toJSON?t.toJSON():dw(t):Is.Array(t)?"Array":t&&Is.Object(t)?"Object":t!==void 0?t:""}function hw(t,e,r){var n=lT(e);return"Expected "+bc(t)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function kn(t,e,r){r=r||gh(e),this.message=hw(t,e,r),bh(this,kn),this.__type=t,this.__value=e,this.__valueTypeName=r}kn.prototype=Object.create(Error.prototype);kn.prototype.constructor=kn;function fT(t,e,r,n,s){var i='" of type ';return e==="key"&&(i='" with key type '),hw('property "'+bc(r)+i+bc(t),n,s)}function Ai(t,e,r,n,s){t?(s=s||gh(n),this.message=fT(t,r,e,n,s)):this.message='Unexpected property "'+e+'"',bh(this,kn),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=s}Ai.prototype=Object.create(Error.prototype);Ai.prototype.constructor=kn;function dT(t,e){return new kn(t,{},e)}function hT(t,e,r){return t instanceof Ai?(e=e+"."+t.__property,t=new Ai(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof kn&&(t=new Ai(t.__type,e,r,t.__value,t.__valueTypeName)),bh(t),t}var pw={TfTypeError:kn,TfPropertyTypeError:Ai,tfCustomError:dT,tfSubError:hT,tfJSON:bc,getValueTypeName:gh},qu,ny;function pT(){if(ny)return qu;ny=1;var t=mh,e=pw;function r(P){return Buffer.isBuffer(P)}function n(P){return typeof P=="string"&&/^([0-9a-f]{2})+$/i.test(P)}function s(P,$){var z=P.toJSON();function C(Y){if(!P(Y))return!1;if(Y.length===$)return!0;throw e.tfCustomError(z+"(Length: "+$+")",z+"(Length: "+Y.length+")")}return C.toJSON=function(){return z},C}var i=s.bind(null,t.Array),o=s.bind(null,r),a=s.bind(null,n),c=s.bind(null,t.String);function l(P,$,z){z=z||t.Number;function C(Y,W){return z(Y,W)&&Y>P&&Y<$}return C.toJSON=function(){return`${z.toJSON()} between [${P}, ${$}]`},C}var u=Math.pow(2,53)-1;function f(P){return typeof P=="number"&&isFinite(P)}function h(P){return P<<24>>24===P}function d(P){return P<<16>>16===P}function m(P){return(P|0)===P}function g(P){return typeof P=="number"&&P>=-u&&P<=u&&Math.floor(P)===P}function v(P){return(P&255)===P}function S(P){return(P&65535)===P}function _(P){return P>>>0===P}function E(P){return typeof P=="number"&&P>=0&&P<=u&&Math.floor(P)===P}var x={ArrayN:i,Buffer:r,BufferN:o,Finite:f,Hex:n,HexN:a,Int8:h,Int16:d,Int32:m,Int53:g,Range:l,StringN:c,UInt8:v,UInt16:S,UInt32:_,UInt53:E};for(var O in x)x[O].toJSON=(function(P){return P}).bind(null,O);return qu=x,qu}var Ea=pw,ct=mh,nn=Ea.tfJSON,yw=Ea.TfTypeError,mw=Ea.TfPropertyTypeError,ro=Ea.tfSubError,yT=Ea.getValueTypeName,mn={arrayOf:function(e,r){e=zr(e),r=r||{};function n(s,i){return!ct.Array(s)||ct.Nil(s)||r.minLength!==void 0&&s.length<r.minLength||r.maxLength!==void 0&&s.length>r.maxLength||r.length!==void 0&&s.length!==r.length?!1:s.every(function(o,a){try{return Tt(e,o,i)}catch(c){throw ro(c,a)}})}return n.toJSON=function(){var s="["+nn(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=zr(e);function r(n,s){return ct.Nil(n)||e(n,s,t)}return r.toJSON=function(){return"?"+nn(e)},r},map:function(e,r){e=zr(e),r&&(r=zr(r));function n(s,i){if(!ct.Object(s)||ct.Nil(s))return!1;for(var o in s){try{r&&Tt(r,o,i)}catch(c){throw ro(c,o,"key")}try{var a=s[o];Tt(e,a,i)}catch(c){throw ro(c,o)}}return!0}return r?n.toJSON=function(){return"{"+nn(r)+": "+nn(e)+"}"}:n.toJSON=function(){return"{"+nn(e)+"}"},n},object:function(e){var r={};for(var n in e)r[n]=zr(e[n]);function s(i,o){if(!ct.Object(i)||ct.Nil(i))return!1;var a;try{for(a in r){var c=r[a],l=i[a];Tt(c,l,o)}}catch(u){throw ro(u,a)}if(o){for(a in i)if(!r[a])throw new mw(void 0,a)}return!0}return s.toJSON=function(){return nn(r)},s},anyOf:function(){var e=[].slice.call(arguments).map(zr);function r(n,s){return e.some(function(i){try{return Tt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return e.map(nn).join("|")},r},allOf:function(){var e=[].slice.call(arguments).map(zr);function r(n,s){return e.every(function(i){try{return Tt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return e.map(nn).join(" & ")},r},quacksLike:function(e){function r(n){return e===yT(n)}return r.toJSON=function(){return e},r},tuple:function(){var e=[].slice.call(arguments).map(zr);function r(n,s){return ct.Nil(n)||ct.Nil(n.length)||s&&n.length!==e.length?!1:e.every(function(i,o){try{return Tt(i,n[o],s)}catch(a){throw ro(a,o)}})}return r.toJSON=function(){return"("+e.map(nn).join(", ")+")"},r},value:function(e){function r(n){return n===e}return r.toJSON=function(){return e},r}};mn.oneOf=mn.anyOf;function zr(t){if(ct.String(t))return t[0]==="?"?mn.maybe(t.slice(1)):ct[t]||mn.quacksLike(t);if(t&&ct.Object(t)){if(ct.Array(t)){if(t.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return mn.arrayOf(t[0])}return mn.object(t)}else if(ct.Function(t))return t;return mn.value(t)}function Tt(t,e,r,n){if(ct.Function(t)){if(t(e,r))return!0;throw new yw(n||t,e)}return Tt(zr(t),e,r)}for(var ts in ct)Tt[ts]=ct[ts];for(ts in mn)Tt[ts]=mn[ts];var sy=pT();for(ts in sy)Tt[ts]=sy[ts];Tt.compile=zr;Tt.TfTypeError=yw;Tt.TfPropertyTypeError=mw;var mT=Tt;(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=Js;t.typeforce=mT;const r=e.Buffer.alloc(32,0),n=e.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function s(u,f){return u.length!==f.length?!1:u.every((h,d)=>h.equals(f[d]))}t.stacksEqual=s;function i(u){if(!e.Buffer.isBuffer(u)||u.length<33)return!1;const f=u[0],h=u.slice(1,33);if(h.compare(r)===0||h.compare(n)>=0)return!1;if((f===2||f===3)&&u.length===33)return!0;const d=u.slice(33);return d.compare(r)===0||d.compare(n)>=0?!1:f===4&&u.length===65}t.isPoint=i;const o=21*1e14;function a(u){return t.typeforce.UInt53(u)&&u<=o}t.Satoshi=a,t.TAPLEAF_VERSION_MASK=254;function c(u){return!u||!("output"in u)||!e.Buffer.isBuffer(u.output)?!1:u.version!==void 0?(u.version&t.TAPLEAF_VERSION_MASK)===u.version:!0}t.isTapleaf=c;function l(u){return(0,t.Array)(u)?u.length!==2?!1:u.every(f=>l(f)):c(u)}t.isTaptree=l,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})(vt);var Sa={},ut={};Object.defineProperty(ut,"__esModule",{value:!0});ut.BufferReader=ut.BufferWriter=ut.cloneBuffer=ut.reverseBuffer=ut.writeUInt64LE=ut.readUInt64LE=ut.varuint=void 0;const Ps=vt,{typeforce:gw}=Ps,Yo=Jm;ut.varuint=Yo;function bw(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 ww(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,bw(n+r,9007199254740991),n+r}ut.readUInt64LE=ww;function vw(t,e,r){return bw(e,9007199254740991),t.writeInt32LE(e&-1,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}ut.writeUInt64LE=vw;function gT(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}ut.reverseBuffer=gT;function bT(t){const e=Buffer.allocUnsafe(t.length);return t.copy(e),e}ut.cloneBuffer=bT;class wh{static withCapacity(e){return new wh(Buffer.alloc(e))}constructor(e,r=0){this.buffer=e,this.offset=r,gw(Ps.tuple(Ps.Buffer,Ps.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=vw(this.buffer,e,this.offset)}writeVarInt(e){Yo.encode(e,this.buffer,this.offset),this.offset+=Yo.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}`)}}ut.BufferWriter=wh;class wT{constructor(e,r=0){this.buffer=e,this.offset=r,gw(Ps.tuple(Ps.Buffer,Ps.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=ww(this.buffer,this.offset);return this.offset+=8,e}readVarInt(){const e=Yo.decode(this.buffer,this.offset);return this.offset+=Yo.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}}ut.BufferReader=wT;var cs={};const vT=lw(a6);var Ri={},Rt={},Pt={},vh={},Jc={};Object.defineProperty(Jc,"__esModule",{value:!0});Jc.crypto=void 0;Jc.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=l,t.clean=u,t.createView=f,t.rotr=h,t.rotl=d,t.byteSwap=m,t.byteSwap32=g,t.bytesToHex=_,t.hexToBytes=O,t.asyncLoop=$,t.utf8ToBytes=z,t.bytesToUtf8=C,t.toBytes=Y,t.kdfInputToBytes=W,t.concatBytes=K,t.checkOpts=U,t.createHasher=F,t.createOptHasher=Z,t.createXOFer=ee,t.randomBytes=D;const e=Jc;function r(T){return T instanceof Uint8Array||ArrayBuffer.isView(T)&&T.constructor.name==="Uint8Array"}function n(T){if(!Number.isSafeInteger(T)||T<0)throw new Error("positive integer expected, got "+T)}function s(T,...L){if(!r(T))throw new Error("Uint8Array expected");if(L.length>0&&!L.includes(T.length))throw new Error("Uint8Array expected of length "+L+", got length="+T.length)}function i(T){if(typeof T!="function"||typeof T.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");n(T.outputLen),n(T.blockLen)}function o(T,L=!0){if(T.destroyed)throw new Error("Hash instance has been destroyed");if(L&&T.finished)throw new Error("Hash#digest() has already been called")}function a(T,L){s(T);const G=L.outputLen;if(T.length<G)throw new Error("digestInto() expects output buffer of length at least "+G)}function c(T){return new Uint8Array(T.buffer,T.byteOffset,T.byteLength)}function l(T){return new Uint32Array(T.buffer,T.byteOffset,Math.floor(T.byteLength/4))}function u(...T){for(let L=0;L<T.length;L++)T[L].fill(0)}function f(T){return new DataView(T.buffer,T.byteOffset,T.byteLength)}function h(T,L){return T<<32-L|T>>>L}function d(T,L){return T<<L|T>>>32-L>>>0}t.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function m(T){return T<<24&4278190080|T<<8&16711680|T>>>8&65280|T>>>24&255}t.swap8IfBE=t.isLE?T=>T:T=>m(T),t.byteSwapIfBE=t.swap8IfBE;function g(T){for(let L=0;L<T.length;L++)T[L]=m(T[L]);return T}t.swap32IfBE=t.isLE?T=>T:g;const v=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",S=Array.from({length:256},(T,L)=>L.toString(16).padStart(2,"0"));function _(T){if(s(T),v)return T.toHex();let L="";for(let G=0;G<T.length;G++)L+=S[T[G]];return L}const E={_0:48,_9:57,A:65,F:70,a:97,f:102};function x(T){if(T>=E._0&&T<=E._9)return T-E._0;if(T>=E.A&&T<=E.F)return T-(E.A-10);if(T>=E.a&&T<=E.f)return T-(E.a-10)}function O(T){if(typeof T!="string")throw new Error("hex string expected, got "+typeof T);if(v)return Uint8Array.fromHex(T);const L=T.length,G=L/2;if(L%2)throw new Error("hex string expected, got unpadded hex of length "+L);const I=new Uint8Array(G);for(let R=0,j=0;R<G;R++,j+=2){const J=x(T.charCodeAt(j)),ne=x(T.charCodeAt(j+1));if(J===void 0||ne===void 0){const ue=T[j]+T[j+1];throw new Error('hex string expected, got non-hex character "'+ue+'" at index '+j)}I[R]=J*16+ne}return I}const P=async()=>{};t.nextTick=P;async function $(T,L,G){let I=Date.now();for(let R=0;R<T;R++){G(R);const j=Date.now()-I;j>=0&&j<L||(await(0,t.nextTick)(),I+=j)}}function z(T){if(typeof T!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(T))}function C(T){return new TextDecoder().decode(T)}function Y(T){return typeof T=="string"&&(T=z(T)),s(T),T}function W(T){return typeof T=="string"&&(T=z(T)),s(T),T}function K(...T){let L=0;for(let I=0;I<T.length;I++){const R=T[I];s(R),L+=R.length}const G=new Uint8Array(L);for(let I=0,R=0;I<T.length;I++){const j=T[I];G.set(j,R),R+=j.length}return G}function U(T,L){if(L!==void 0&&{}.toString.call(L)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(T,L)}class N{}t.Hash=N;function F(T){const L=I=>T().update(Y(I)).digest(),G=T();return L.outputLen=G.outputLen,L.blockLen=G.blockLen,L.create=()=>T(),L}function Z(T){const L=(I,R)=>T(R).update(Y(I)).digest(),G=T({});return L.outputLen=G.outputLen,L.blockLen=G.blockLen,L.create=I=>T(I),L}function ee(T){const L=(I,R)=>T(R).update(Y(I)).digest(),G=T({});return L.outputLen=G.outputLen,L.blockLen=G.blockLen,L.create=I=>T(I),L}t.wrapConstructor=F,t.wrapConstructorWithOpts=Z,t.wrapXOFConstructorWithOpts=ee;function D(T=32){if(e.crypto&&typeof e.crypto.getRandomValues=="function")return e.crypto.getRandomValues(new Uint8Array(T));if(e.crypto&&typeof e.crypto.randomBytes=="function")return Uint8Array.from(e.crypto.randomBytes(T));throw new Error("crypto.getRandomValues must be defined")}})(vh);Object.defineProperty(Pt,"__esModule",{value:!0});Pt.SHA512_IV=Pt.SHA384_IV=Pt.SHA224_IV=Pt.SHA256_IV=Pt.HashMD=void 0;Pt.setBigUint64=Ew;Pt.Chi=ET;Pt.Maj=ST;const Mr=vh;function Ew(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,l=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+l,a,n)}function ET(t,e,r){return t&e^~t&r}function ST(t,e,r){return t&e^t&r^e&r}class AT extends Mr.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,Mr.createView)(this.buffer)}update(e){(0,Mr.aexists)(this),e=(0,Mr.toBytes)(e),(0,Mr.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,Mr.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,Mr.aexists)(this),(0,Mr.aoutput)(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:o}=this;r[o++]=128,(0,Mr.clean)(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let f=o;f<s;f++)r[f]=0;Ew(n,s-8,BigInt(this.length*8),i),this.process(n,0);const a=(0,Mr.createView)(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],i)}digest(){const{buffer: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()}}Pt.HashMD=AT;Pt.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);Pt.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);Pt.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);Pt.SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);Object.defineProperty(Rt,"__esModule",{value:!0});Rt.ripemd160=Rt.RIPEMD160=Rt.md5=Rt.MD5=Rt.sha1=Rt.SHA1=void 0;const Os=Pt,lt=vh,ai=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Mn=new Uint32Array(80);class Sw extends Os.HashMD{constructor(){super(64,20,8,!1),this.A=ai[0]|0,this.B=ai[1]|0,this.C=ai[2]|0,this.D=ai[3]|0,this.E=ai[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)Mn[c]=e.getUint32(r,!1);for(let c=16;c<80;c++)Mn[c]=(0,lt.rotl)(Mn[c-3]^Mn[c-8]^Mn[c-14]^Mn[c-16],1);let{A:n,B:s,C:i,D:o,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=(0,Os.Chi)(s,i,o),u=1518500249):c<40?(l=s^i^o,u=1859775393):c<60?(l=(0,Os.Maj)(s,i,o),u=2400959708):(l=s^i^o,u=3395469782);const f=(0,lt.rotl)(n,5)+l+a+u+Mn[c]|0;a=o,o=i,i=(0,lt.rotl)(s,30),s=n,n=f}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,this.set(n,s,i,o,a)}roundClean(){(0,lt.clean)(Mn)}destroy(){this.set(0,0,0,0,0),(0,lt.clean)(this.buffer)}}Rt.SHA1=Sw;Rt.sha1=(0,lt.createHasher)(()=>new Sw);const xT=Math.pow(2,32),kT=Array.from({length:64},(t,e)=>Math.floor(xT*Math.abs(Math.sin(e+1)))),Fa=ai.slice(0,4),Gu=new Uint32Array(16);class Aw extends Os.HashMD{constructor(){super(64,16,8,!0),this.A=Fa[0]|0,this.B=Fa[1]|0,this.C=Fa[2]|0,this.D=Fa[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)Gu[a]=e.getUint32(r,!0);let{A:n,B:s,C:i,D:o}=this;for(let a=0;a<64;a++){let c,l,u;a<16?(c=(0,Os.Chi)(s,i,o),l=a,u=[7,12,17,22]):a<32?(c=(0,Os.Chi)(o,s,i),l=(5*a+1)%16,u=[5,9,14,20]):a<48?(c=s^i^o,l=(3*a+5)%16,u=[4,11,16,23]):(c=i^(s|~o),l=7*a%16,u=[6,10,15,21]),c=c+n+kT[a]+Gu[l],n=o,o=i,i=s,s=s+(0,lt.rotl)(c,u[a%4])}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,this.set(n,s,i,o)}roundClean(){(0,lt.clean)(Gu)}destroy(){this.set(0,0,0,0),(0,lt.clean)(this.buffer)}}Rt.MD5=Aw;Rt.md5=(0,lt.createHasher)(()=>new Aw);const _T=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),xw=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),TT=xw.map(t=>(9*t+5)%16),kw=(()=>{const r=[[xw],[TT]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>_T[i]));return r})(),_w=kw[0],Tw=kw[1],Iw=[[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)),IT=_w.map((t,e)=>t.map(r=>Iw[e][r])),PT=Tw.map((t,e)=>t.map(r=>Iw[e][r])),OT=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),BT=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function iy(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);class Pw extends Os.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)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,l=this.h3|0,u=l,f=this.h4|0,h=f;for(let d=0;d<5;d++){const m=4-d,g=OT[d],v=BT[d],S=_w[d],_=Tw[d],E=IT[d],x=PT[d];for(let O=0;O<16;O++){const P=(0,lt.rotl)(n+iy(d,i,a,l)+ja[S[O]]+g,E[O])+f|0;n=f,f=l,l=(0,lt.rotl)(a,10)|0,a=i,i=P}for(let O=0;O<16;O++){const P=(0,lt.rotl)(s+iy(m,o,c,u)+ja[_[O]]+v,x[O])+h|0;s=h,h=u,u=(0,lt.rotl)(c,10)|0,c=o,o=P}}this.set(this.h1+a+u|0,this.h2+l+h|0,this.h3+f+s|0,this.h4+n+o|0,this.h0+i+c|0)}roundClean(){(0,lt.clean)(ja)}destroy(){this.destroyed=!0,(0,lt.clean)(this.buffer),this.set(0,0,0,0,0)}}Rt.RIPEMD160=Pw;Rt.ripemd160=(0,lt.createHasher)(()=>new Pw);Object.defineProperty(Ri,"__esModule",{value:!0});Ri.sha1=Ri.SHA1=void 0;const Ow=Rt;Ri.SHA1=Ow.SHA1;Ri.sha1=Ow.sha1;const Bw=lw(XS);(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=vT,r=Ri,n=Bw;function s(u){return Buffer.from((0,e.ripemd160)(Uint8Array.from(u)))}t.ripemd160=s;function i(u){return Buffer.from((0,r.sha1)(Uint8Array.from(u)))}t.sha1=i;function o(u){return Buffer.from((0,n.sha256)(Uint8Array.from(u)))}t.sha256=o;function a(u){return Buffer.from((0,e.ripemd160)((0,n.sha256)(Uint8Array.from(u))))}t.hash160=a;function c(u){return Buffer.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(u))))}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 l(u,f){return o(Buffer.concat([t.TAGGED_HASH_PREFIXES[u],f]))}t.taggedHash=l})(cs);var Wu={},Sn={};Object.defineProperty(Sn,"__esModule",{value:!0});Sn.encode=Sn.decode=Sn.check=void 0;function CT(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))}Sn.check=CT;function $T(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)}}Sn.decode=$T;function RT(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}Sn.encode=RT;var Hs={};Object.defineProperty(Hs,"__esModule",{value:!0});Hs.REVERSE_OPS=Hs.OPS=void 0;const nd={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};Hs.OPS=nd;const Cw={};Hs.REVERSE_OPS=Cw;for(const t of Object.keys(nd)){const e=nd[t];Cw[e]=t}var rs={};Object.defineProperty(rs,"__esModule",{value:!0});rs.decode=rs.encode=rs.encodingLength=void 0;const Jn=Hs;function $w(t){return t<Jn.OPS.OP_PUSHDATA1?1:t<=255?2:t<=65535?3:5}rs.encodingLength=$w;function NT(t,e,r){const n=$w(e);return n===1?t.writeUInt8(e,r):n===2?(t.writeUInt8(Jn.OPS.OP_PUSHDATA1,r),t.writeUInt8(e,r+1)):n===3?(t.writeUInt8(Jn.OPS.OP_PUSHDATA2,r),t.writeUInt16LE(e,r+1)):(t.writeUInt8(Jn.OPS.OP_PUSHDATA4,r),t.writeUInt32LE(e,r+1)),n}rs.encode=NT;function UT(t,e){const r=t.readUInt8(e);let n,s;if(r<Jn.OPS.OP_PUSHDATA1)n=r,s=1;else if(r===Jn.OPS.OP_PUSHDATA1){if(e+2>t.length)return null;n=t.readUInt8(e+1),s=2}else if(r===Jn.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!==Jn.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=t.readUInt32LE(e+1),s=5}return{opcode:r,number:n,size:s}}rs.decode=UT;var Ni={};Object.defineProperty(Ni,"__esModule",{value:!0});Ni.encode=Ni.decode=void 0;function MT(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}Ni.decode=MT;function FT(t){return t>2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}function jT(t){let e=Math.abs(t);const r=FT(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}Ni.encode=jT;var ds={},oy;function LT(){if(oy)return ds;oy=1,Object.defineProperty(ds,"__esModule",{value:!0}),ds.encode=ds.decode=void 0;const t=Sn,e=Jt(),r=vt,{typeforce:n}=r,s=Buffer.alloc(1,0);function i(l){let u=0;for(;l[u]===0;)++u;return u===l.length?s:(l=l.slice(u),l[0]&128?Buffer.concat([s,l],1+l.length):l)}function o(l){l[0]===0&&(l=l.slice(1));const u=Buffer.alloc(32,0),f=Math.max(0,32-l.length);return l.copy(u,f),u}function a(l){const u=l.readUInt8(l.length-1);if(!(0,e.isDefinedHashType)(u))throw new Error("Invalid hashType "+u);const f=t.decode(l.slice(0,-1)),h=o(f.r),d=o(f.s);return{signature:Buffer.concat([h,d],64),hashType:u}}ds.decode=a;function c(l,u){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:l,hashType:u}),!(0,e.isDefinedHashType)(u))throw new Error("Invalid hashType "+u);const f=Buffer.allocUnsafe(1);f.writeUInt8(u,0);const h=i(l.slice(0,32)),d=i(l.slice(32,64));return Buffer.concat([t.encode(h,d),f])}return ds.encode=c,ds}var ay;function Jt(){return ay||(ay=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=Sn,r=Hs;Object.defineProperty(t,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=rs,s=Ni,i=LT(),o=vt,{typeforce:a}=o,c=r.OPS.OP_RESERVED;function l(C){return o.Number(C)&&(C===r.OPS.OP_0||C>=r.OPS.OP_1&&C<=r.OPS.OP_16||C===r.OPS.OP_1NEGATE)}function u(C){return o.Buffer(C)||l(C)}function f(C){return o.Array(C)&&C.every(u)}t.isPushOnly=f;function h(C){return C.length-C.filter(u).length}t.countNonPushOnlyOPs=h;function d(C){if(C.length===0)return r.OPS.OP_0;if(C.length===1){if(C[0]>=1&&C[0]<=16)return c+C[0];if(C[0]===129)return r.OPS.OP_1NEGATE}}function m(C){return Buffer.isBuffer(C)}function g(C){return o.Array(C)}function v(C){return Buffer.isBuffer(C)}function S(C){if(m(C))return C;a(o.Array,C);const Y=C.reduce((U,N)=>v(N)?N.length===1&&d(N)!==void 0?U+1:U+n.encodingLength(N.length)+N.length:U+1,0),W=Buffer.allocUnsafe(Y);let K=0;if(C.forEach(U=>{if(v(U)){const N=d(U);if(N!==void 0){W.writeUInt8(N,K),K+=1;return}K+=n.encode(W,U.length,K),U.copy(W,K),K+=U.length}else W.writeUInt8(U,K),K+=1}),K!==W.length)throw new Error("Could not decode chunks");return W}t.compile=S;function _(C){if(g(C))return C;a(o.Buffer,C);const Y=[];let W=0;for(;W<C.length;){const K=C[W];if(K>r.OPS.OP_0&&K<=r.OPS.OP_PUSHDATA4){const U=n.decode(C,W);if(U===null||(W+=U.size,W+U.number>C.length))return null;const N=C.slice(W,W+U.number);W+=U.number;const F=d(N);F!==void 0?Y.push(F):Y.push(N)}else Y.push(K),W+=1}return Y}t.decompile=_;function E(C){if(m(C)&&(C=_(C)),!C)throw new Error("Could not convert invalid chunks to ASM");return C.map(Y=>{if(v(Y)){const W=d(Y);if(W===void 0)return Y.toString("hex");Y=W}return r.REVERSE_OPS[Y]}).join(" ")}t.toASM=E;function x(C){return a(o.String,C),S(C.split(" ").map(Y=>r.OPS[Y]!==void 0?r.OPS[Y]:(a(o.Hex,Y),Buffer.from(Y,"hex"))))}t.fromASM=x;function O(C){return C=_(C),a(f,C),C.map(Y=>v(Y)?Y:Y===r.OPS.OP_0?Buffer.allocUnsafe(0):s.encode(Y-c))}t.toStack=O;function P(C){return o.isPoint(C)}t.isCanonicalPubKey=P;function $(C){const Y=C&-129;return Y>0&&Y<4}t.isDefinedHashType=$;function z(C){return!Buffer.isBuffer(C)||!$(C[C.length-1])?!1:e.check(C.slice(0,-1))}t.isCanonicalScriptSignature=z,t.number=s,t.signature=i}(Wu)),Wu}Object.defineProperty(Sa,"__esModule",{value:!0});Sa.Transaction=void 0;const Ze=ut,At=cs,cy=Jt(),DT=Jt(),we=vt,{typeforce:Fr}=we;function yr(t){const e=t.length;return Ze.varuint.encodingLength(e)+e}function HT(t){const e=t.length;return Ze.varuint.encodingLength(e)+t.reduce((r,n)=>r+yr(n),0)}const zn=Buffer.allocUnsafe(0),Ku=[],Zu=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),uy=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),zT=Buffer.from("ffffffffffffffff","hex"),VT={script:zn,valueBuffer:zT};function qT(t){return t.value!==void 0}let Cr=class ke{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(e,r){const n=new Ze.BufferReader(e),s=new ke;s.version=n.readInt32();const i=n.readUInt8(),o=n.readUInt8();let a=!1;i===ke.ADVANCED_TRANSACTION_MARKER&&o===ke.ADVANCED_TRANSACTION_FLAG?a=!0:n.offset-=2;const c=n.readVarInt();for(let u=0;u<c;++u)s.ins.push({hash:n.readSlice(32),index:n.readUInt32(),script:n.readVarSlice(),sequence:n.readUInt32(),witness:Ku});const l=n.readVarInt();for(let u=0;u<l;++u)s.outs.push({value:n.readUInt64(),script:n.readVarSlice()});if(a){for(let u=0;u<c;++u)s.ins[u].witness=n.readVector();if(!s.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(s.locktime=n.readUInt32(),r)return s;if(n.offset!==e.length)throw new Error("Transaction has unexpected data");return s}static fromHex(e){return ke.fromBuffer(Buffer.from(e,"hex"),!1)}static isCoinbaseHash(e){Fr(we.Hash256bit,e);for(let r=0;r<32;++r)if(e[r]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&ke.isCoinbaseHash(this.ins[0].hash)}addInput(e,r,n,s){return Fr(we.tuple(we.Hash256bit,we.UInt32,we.maybe(we.UInt32),we.maybe(we.Buffer)),arguments),we.Null(n)&&(n=ke.DEFAULT_SEQUENCE),this.ins.push({hash:e,index:r,script:s||zn,sequence:n,witness:Ku})-1}addOutput(e,r){return Fr(we.tuple(we.Buffer,we.Satoshi),arguments),this.outs.push({script:e,value:r})-1}hasWitnesses(){return this.ins.some(e=>e.witness.length!==0)}stripWitnesses(){this.ins.forEach(e=>{e.witness=Ku})}weight(){const e=this.byteLength(!1),r=this.byteLength(!0);return e*3+r}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(e=!0){const r=e&&this.hasWitnesses();return(r?10:8)+Ze.varuint.encodingLength(this.ins.length)+Ze.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,s)=>n+40+yr(s.script),0)+this.outs.reduce((n,s)=>n+8+yr(s.script),0)+(r?this.ins.reduce((n,s)=>n+HT(s.witness),0):0)}clone(){const e=new ke;return e.version=this.version,e.locktime=this.locktime,e.ins=this.ins.map(r=>({hash:r.hash,index:r.index,script:r.script,sequence:r.sequence,witness:r.witness})),e.outs=this.outs.map(r=>({script:r.script,value:r.value})),e}hashForSignature(e,r,n){if(Fr(we.tuple(we.UInt32,we.Buffer,we.Number),arguments),e>=this.ins.length)return uy;const s=cy.compile(cy.decompile(r).filter(a=>a!==DT.OPS.OP_CODESEPARATOR)),i=this.clone();if((n&31)===ke.SIGHASH_NONE)i.outs=[],i.ins.forEach((a,c)=>{c!==e&&(a.sequence=0)});else if((n&31)===ke.SIGHASH_SINGLE){if(e>=this.outs.length)return uy;i.outs.length=e+1;for(let a=0;a<e;a++)i.outs[a]=VT;i.ins.forEach((a,c)=>{c!==e&&(a.sequence=0)})}n&ke.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[e]],i.ins[0].script=s):(i.ins.forEach(a=>{a.script=zn}),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),At.hash256(o)}hashForWitnessV1(e,r,n,s,i,o){if(console.log("hashForWitnessV1 :"),Fr(we.tuple(we.UInt32,Fr.arrayOf(we.Buffer),Fr.arrayOf(we.Satoshi),we.UInt32),arguments),n.length!==this.ins.length||r.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const a=s===ke.SIGHASH_DEFAULT?ke.SIGHASH_ALL:s&ke.SIGHASH_OUTPUT_MASK,l=(s&ke.SIGHASH_INPUT_MASK)===ke.SIGHASH_ANYONECANPAY,u=a===ke.SIGHASH_NONE,f=a===ke.SIGHASH_SINGLE;let h=zn,d=zn,m=zn,g=zn,v=zn;if(!l){let x=Ze.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(O=>{x.writeSlice(O.hash),x.writeUInt32(O.index)}),h=At.sha256(x.end()),x=Ze.BufferWriter.withCapacity(8*this.ins.length),n.forEach(O=>x.writeUInt64(O)),d=At.sha256(x.end()),console.log("prevOutScripts.map(varSliceSize).reduce((a, b) => a + b), :",r.map(yr).reduce((O,P)=>O+P)),x=Ze.BufferWriter.withCapacity(r.map(yr).reduce((O,P)=>O+P)),r.forEach(O=>x.writeVarSlice(O)),m=At.sha256(x.end()),x=Ze.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(O=>x.writeUInt32(O.sequence)),g=At.sha256(x.end())}if(u||f){if(f&&e<this.outs.length){const x=this.outs[e],O=Ze.BufferWriter.withCapacity(8+yr(x.script));O.writeUInt64(x.value),O.writeVarSlice(x.script),v=At.sha256(O.end())}}else{const x=this.outs.map(P=>8+yr(P.script)).reduce((P,$)=>P+$),O=Ze.BufferWriter.withCapacity(x);this.outs.forEach(P=>{O.writeUInt64(P.value),O.writeVarSlice(P.script)}),v=At.sha256(O.end())}const S=(i?2:0)+(o?1:0),_=174-(l?49:0)-(u?32:0)+(o?32:0)+(i?37:0),E=Ze.BufferWriter.withCapacity(_);if(E.writeUInt8(s),E.writeInt32(this.version),E.writeUInt32(this.locktime),E.writeSlice(h),E.writeSlice(d),E.writeSlice(m),E.writeSlice(g),u||f||E.writeSlice(v),E.writeUInt8(S),l){const x=this.ins[e];E.writeSlice(x.hash),E.writeUInt32(x.index),E.writeUInt64(n[e]),E.writeVarSlice(r[e]),E.writeUInt32(x.sequence)}else E.writeUInt32(e);if(o){const x=Ze.BufferWriter.withCapacity(yr(o));x.writeVarSlice(o),E.writeSlice(At.sha256(x.end()))}return f&&E.writeSlice(v),i&&(E.writeSlice(i),E.writeUInt8(0),E.writeUInt32(4294967295)),At.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),E.end()]))}hashForWitnessV0(e,r,n,s){Fr(we.tuple(we.UInt32,we.Buffer,we.Satoshi,we.UInt32),arguments);let i=Buffer.from([]),o,a=Zu,c=Zu,l=Zu;if(s&ke.SIGHASH_ANYONECANPAY||(i=Buffer.allocUnsafe(36*this.ins.length),o=new Ze.BufferWriter(i,0),this.ins.forEach(f=>{o.writeSlice(f.hash),o.writeUInt32(f.index)}),c=At.hash256(i)),!(s&ke.SIGHASH_ANYONECANPAY)&&(s&31)!==ke.SIGHASH_SINGLE&&(s&31)!==ke.SIGHASH_NONE&&(i=Buffer.allocUnsafe(4*this.ins.length),o=new Ze.BufferWriter(i,0),this.ins.forEach(f=>{o.writeUInt32(f.sequence)}),l=At.hash256(i)),(s&31)!==ke.SIGHASH_SINGLE&&(s&31)!==ke.SIGHASH_NONE){const f=this.outs.reduce((h,d)=>h+8+yr(d.script),0);i=Buffer.allocUnsafe(f),o=new Ze.BufferWriter(i,0),this.outs.forEach(h=>{o.writeUInt64(h.value),o.writeVarSlice(h.script)}),a=At.hash256(i)}else if((s&31)===ke.SIGHASH_SINGLE&&e<this.outs.length){const f=this.outs[e];i=Buffer.allocUnsafe(8+yr(f.script)),o=new Ze.BufferWriter(i,0),o.writeUInt64(f.value),o.writeVarSlice(f.script),a=At.hash256(i)}i=Buffer.allocUnsafe(156+yr(r)),o=new Ze.BufferWriter(i,0);const u=this.ins[e];return o.writeInt32(this.version),o.writeSlice(c),o.writeSlice(l),o.writeSlice(u.hash),o.writeUInt32(u.index),o.writeVarSlice(r),o.writeUInt64(n),o.writeUInt32(u.sequence),o.writeSlice(a),o.writeUInt32(this.locktime),o.writeUInt32(s),At.hash256(i)}getHash(e){return e&&this.isCoinbase()?Buffer.alloc(32,0):At.hash256(this.__toBuffer(void 0,void 0,e))}getId(){return(0,Ze.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(e,r){return this.__toBuffer(e,r,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(e,r){Fr(we.tuple(we.Number,we.Buffer),arguments),this.ins[e].script=r}setWitness(e,r){Fr(we.tuple(we.Number,[we.Buffer]),arguments),this.ins[e].witness=r}__toBuffer(e,r,n=!1){e||(e=Buffer.allocUnsafe(this.byteLength(n)));const s=new Ze.BufferWriter(e,r||0);s.writeInt32(this.version);const i=n&&this.hasWitnesses();return i&&(s.writeUInt8(ke.ADVANCED_TRANSACTION_MARKER),s.writeUInt8(ke.ADVANCED_TRANSACTION_FLAG)),s.writeVarInt(this.ins.length),this.ins.forEach(o=>{s.writeSlice(o.hash),s.writeUInt32(o.index),s.writeVarSlice(o.script),s.writeUInt32(o.sequence)}),s.writeVarInt(this.outs.length),this.outs.forEach(o=>{qT(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}};Sa.Transaction=Cr;Cr.DEFAULT_SEQUENCE=4294967295;Cr.SIGHASH_DEFAULT=0;Cr.SIGHASH_ALL=1;Cr.SIGHASH_NONE=2;Cr.SIGHASH_SINGLE=3;Cr.SIGHASH_ANYONECANPAY=128;Cr.SIGHASH_OUTPUT_MASK=3;Cr.SIGHASH_INPUT_MASK=128;Cr.ADVANCED_TRANSACTION_MARKER=0;Cr.ADVANCED_TRANSACTION_FLAG=1;var _e={},Aa={};Object.defineProperty(Aa,"__esModule",{value:!0});const GT=9007199254740991;function Eh(t){if(t<0||t>GT||t%1!==0)throw new RangeError("value out of range")}function fo(t,e,r){if(Eh(t),e||(e=Buffer.allocUnsafe(Rw(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(fo,{bytes:1})):t<=65535?(e.writeUInt8(253,r),e.writeUInt16LE(t,r+1),Object.assign(fo,{bytes:3})):t<=4294967295?(e.writeUInt8(254,r),e.writeUInt32LE(t,r+1),Object.assign(fo,{bytes:5})):(e.writeUInt8(255,r),e.writeUInt32LE(t>>>0,r+1),e.writeUInt32LE(t/4294967296|0,r+5),Object.assign(fo,{bytes:9})),e}Aa.encode=fo;function ho(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(ho,{bytes:1}),r;if(r===253)return Object.assign(ho,{bytes:3}),t.readUInt16LE(e+1);if(r===254)return Object.assign(ho,{bytes:5}),t.readUInt32LE(e+1);{Object.assign(ho,{bytes:9});const n=t.readUInt32LE(e+1),i=t.readUInt32LE(e+5)*4294967296+n;return Eh(i),i}}Aa.decode=ho;function Rw(t){return Eh(t),t<253?1:t<=65535?3:t<=4294967295?5:9}Aa.encodingLength=Rw;var Xu={},Qc={},bt={};Object.defineProperty(bt,"__esModule",{value:!0});bt.testnet=bt.regtest=bt.bitcoin=void 0;bt.bitcoin={messagePrefix:`Bitcoin Signed Message:
52
- `,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};bt.regtest={messagePrefix:`Bitcoin Signed Message:
53
- `,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};bt.testnet={messagePrefix:`Bitcoin Signed Message:
54
- `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var Zt={};Object.defineProperty(Zt,"__esModule",{value:!0});Zt.value=Zt.prop=void 0;function WT(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})}})}Zt.prop=WT;function KT(t){let e;return()=>(e!==void 0||(e=t()),e)}Zt.value=KT;Object.defineProperty(Qc,"__esModule",{value:!0});Qc.p2data=void 0;const ZT=bt,nc=Jt(),jr=vt,ly=Zt,fy=nc.OPS;function XT(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,jr.typeforce)({network:jr.typeforce.maybe(jr.typeforce.Object),output:jr.typeforce.maybe(jr.typeforce.Buffer),data:jr.typeforce.maybe(jr.typeforce.arrayOf(jr.typeforce.Buffer))},t);const n={name:"embed",network:t.network||ZT.bitcoin};if(ly.prop(n,"output",()=>{if(t.data)return nc.compile([fy.OP_RETURN].concat(t.data))}),ly.prop(n,"data",()=>{if(t.output)return nc.decompile(t.output).slice(1)}),e.validate&&t.output){const s=nc.decompile(t.output);if(s[0]!==fy.OP_RETURN)throw new TypeError("Output is invalid");if(!s.slice(1).every(jr.typeforce.Buffer))throw new TypeError("Output is invalid");if(t.data&&!(0,jr.stacksEqual)(t.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,t)}Qc.p2data=XT;var eu={};Object.defineProperty(eu,"__esModule",{value:!0});eu.p2ms=void 0;const YT=bt,ci=Jt(),qe=vt,Fn=Zt,ui=ci.OPS,La=ui.OP_RESERVED;function JT(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 ci.isCanonicalScriptSignature(c)||(e.allowIncomplete&&c===ui.OP_0)!==void 0}(0,qe.typeforce)({network:qe.typeforce.maybe(qe.typeforce.Object),m:qe.typeforce.maybe(qe.typeforce.Number),n:qe.typeforce.maybe(qe.typeforce.Number),output:qe.typeforce.maybe(qe.typeforce.Buffer),pubkeys:qe.typeforce.maybe(qe.typeforce.arrayOf(qe.isPoint)),signatures:qe.typeforce.maybe(qe.typeforce.arrayOf(r)),input:qe.typeforce.maybe(qe.typeforce.Buffer)},t);const s={network:t.network||YT.bitcoin};let i=[],o=!1;function a(c){o||(o=!0,i=ci.decompile(c),s.m=i[0]-La,s.n=i[i.length-2]-La,s.pubkeys=i.slice(1,-2))}if(Fn.prop(s,"output",()=>{if(t.m&&s.n&&t.pubkeys)return ci.compile([].concat(La+t.m,t.pubkeys,La+s.n,ui.OP_CHECKMULTISIG))}),Fn.prop(s,"m",()=>{if(s.output)return a(s.output),s.m}),Fn.prop(s,"n",()=>{if(s.pubkeys)return s.pubkeys.length}),Fn.prop(s,"pubkeys",()=>{if(t.output)return a(t.output),s.pubkeys}),Fn.prop(s,"signatures",()=>{if(t.input)return ci.decompile(t.input).slice(1)}),Fn.prop(s,"input",()=>{if(t.signatures)return ci.compile([ui.OP_0].concat(t.signatures))}),Fn.prop(s,"witness",()=>{if(s.input)return[]}),Fn.prop(s,"name",()=>{if(!(!s.m||!s.n))return`p2ms(${s.m} of ${s.n})`}),e.validate){if(t.output){if(a(t.output),!qe.typeforce.Number(i[0]))throw new TypeError("Output is invalid");if(!qe.typeforce.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==ui.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(s.m<=0||s.n>16||s.m>s.n||s.n!==i.length-3)throw new TypeError("Output is invalid");if(!s.pubkeys.every(c=>(0,qe.isPoint)(c)))throw new TypeError("Output is invalid");if(t.m!==void 0&&t.m!==s.m)throw new TypeError("m mismatch");if(t.n!==void 0&&t.n!==s.n)throw new TypeError("n mismatch");if(t.pubkeys&&!(0,qe.stacksEqual)(t.pubkeys,s.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(t.n!==void 0&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(s.n=t.pubkeys.length,s.n<s.m)throw new TypeError("Pubkey count cannot be less than m")}if(t.signatures){if(t.signatures.length<s.m)throw new TypeError("Not enough signatures provided");if(t.signatures.length>s.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==ui.OP_0)throw new TypeError("Input is invalid");if(s.signatures.length===0||!s.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!(0,qe.stacksEqual)(t.signatures,s.signatures))throw new TypeError("Signature mismatch");if(t.m!==void 0&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(s,t)}eu.p2ms=JT;var tu={};Object.defineProperty(tu,"__esModule",{value:!0});tu.p2pk=void 0;const QT=bt,li=Jt(),pr=vt,oi=Zt,dy=li.OPS;function eI(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,pr.typeforce)({network:pr.typeforce.maybe(pr.typeforce.Object),output:pr.typeforce.maybe(pr.typeforce.Buffer),pubkey:pr.typeforce.maybe(pr.isPoint),signature:pr.typeforce.maybe(li.isCanonicalScriptSignature),input:pr.typeforce.maybe(pr.typeforce.Buffer)},t);const r=oi.value(()=>li.decompile(t.input)),s={name:"p2pk",network:t.network||QT.bitcoin};if(oi.prop(s,"output",()=>{if(t.pubkey)return li.compile([t.pubkey,dy.OP_CHECKSIG])}),oi.prop(s,"pubkey",()=>{if(t.output)return t.output.slice(1,-1)}),oi.prop(s,"signature",()=>{if(t.input)return r()[0]}),oi.prop(s,"input",()=>{if(t.signature)return li.compile([t.signature])}),oi.prop(s,"witness",()=>{if(s.input)return[]}),e.validate){if(t.output){if(t.output[t.output.length-1]!==dy.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,pr.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(!li.isCanonicalScriptSignature(s.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(s,t)}tu.p2pk=eI;var ru={};function tI(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),l=Math.log(256)/Math.log(o);function u(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,g=0,v=0,S=d.length;v!==S&&d[v]===0;)v++,m++;for(var _=(S-v)*l+1>>>0,E=new Uint8Array(_);v!==S;){for(var x=d[v],O=0,P=_-1;(x!==0||O<g)&&P!==-1;P--,O++)x+=256*E[P]>>>0,E[P]=x%o>>>0,x=x/o>>>0;if(x!==0)throw new Error("Non-zero carry");g=O,v++}for(var $=_-g;$!==_&&E[$]===0;)$++;for(var z=a.repeat(m);$<_;++$)z+=t.charAt(E[$]);return z}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;for(var m=0,g=0,v=0;d[m]===a;)g++,m++;for(var S=(d.length-m)*c+1>>>0,_=new Uint8Array(S);d[m];){var E=d.charCodeAt(m);if(E>255)return;var x=e[E];if(x===255)return;for(var O=0,P=S-1;(x!==0||O<v)&&P!==-1;P--,O++)x+=o*_[P]>>>0,_[P]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");v=O,m++}for(var $=S-v;$!==S&&_[$]===0;)$++;for(var z=new Uint8Array(g+(S-$)),C=g;$!==S;)z[C++]=_[$++];return z}function h(d){var m=f(d);if(m)return m;throw new Error("Non-base"+o+" character")}return{encode:u,decodeUnsafe:f,decode:h}}var rI=tI;const nI=rI,sI="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var iI=nI(sI),Yu=iI,oI=function(t){function e(i){var o=Uint8Array.from(i),a=t(o),c=o.length+4,l=new Uint8Array(c);return l.set(o,0),l.set(a.subarray(0,4),o.length),Yu.encode(l,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=Yu.decodeUnsafe(i);if(o)return r(o)}function s(i){var o=Yu.decode(i),a=r(o);if(!a)throw new Error("Invalid checksum");return a}return{encode:e,decode:s,decodeUnsafe:n}},{sha256:hy}=Bw,aI=oI;function cI(t){return hy(hy(t))}var Sh=aI(cI);Object.defineProperty(ru,"__esModule",{value:!0});ru.p2pkh=void 0;const Ju=cs,uI=bt,fi=Jt(),xt=vt,sn=Zt,py=Sh,jn=fi.OPS;function lI(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,xt.typeforce)({network:xt.typeforce.maybe(xt.typeforce.Object),address:xt.typeforce.maybe(xt.typeforce.String),hash:xt.typeforce.maybe(xt.typeforce.BufferN(20)),output:xt.typeforce.maybe(xt.typeforce.BufferN(25)),pubkey:xt.typeforce.maybe(xt.isPoint),signature:xt.typeforce.maybe(fi.isCanonicalScriptSignature),input:xt.typeforce.maybe(xt.typeforce.Buffer)},t);const r=sn.value(()=>{const o=Buffer.from(py.decode(t.address)),a=o.readUInt8(0),c=o.slice(1);return{version:a,hash:c}}),n=sn.value(()=>fi.decompile(t.input)),s=t.network||uI.bitcoin,i={name:"p2pkh",network:s};if(sn.prop(i,"address",()=>{if(!i.hash)return;const o=Buffer.allocUnsafe(21);return o.writeUInt8(s.pubKeyHash,0),i.hash.copy(o,1),py.encode(o)}),sn.prop(i,"hash",()=>{if(t.output)return t.output.slice(3,23);if(t.address)return r().hash;if(t.pubkey||i.pubkey)return Ju.hash160(t.pubkey||i.pubkey)}),sn.prop(i,"output",()=>{if(i.hash)return fi.compile([jn.OP_DUP,jn.OP_HASH160,i.hash,jn.OP_EQUALVERIFY,jn.OP_CHECKSIG])}),sn.prop(i,"pubkey",()=>{if(t.input)return n()[1]}),sn.prop(i,"signature",()=>{if(t.input)return n()[0]}),sn.prop(i,"input",()=>{if(t.pubkey&&t.signature)return fi.compile([t.signature,t.pubkey])}),sn.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]!==jn.OP_DUP||t.output[1]!==jn.OP_HASH160||t.output[2]!==20||t.output[23]!==jn.OP_EQUALVERIFY||t.output[24]!==jn.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=Ju.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(!fi.isCanonicalScriptSignature(a[0]))throw new TypeError("Input has invalid signature");if(!(0,xt.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=Ju.hash160(a[1]);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)}ru.p2pkh=lI;var nu={};Object.defineProperty(nu,"__esModule",{value:!0});nu.p2sh=void 0;const yy=cs,fI=bt,Hr=Jt(),Be=vt,Lr=Zt,my=Sh,no=Hr.OPS;function dI(t,e){if(!t.address&&!t.hash&&!t.output&&!t.redeem&&!t.input)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Be.typeforce)({network:Be.typeforce.maybe(Be.typeforce.Object),address:Be.typeforce.maybe(Be.typeforce.String),hash:Be.typeforce.maybe(Be.typeforce.BufferN(20)),output:Be.typeforce.maybe(Be.typeforce.BufferN(23)),redeem:Be.typeforce.maybe({network:Be.typeforce.maybe(Be.typeforce.Object),output:Be.typeforce.maybe(Be.typeforce.Buffer),input:Be.typeforce.maybe(Be.typeforce.Buffer),witness:Be.typeforce.maybe(Be.typeforce.arrayOf(Be.typeforce.Buffer))}),input:Be.typeforce.maybe(Be.typeforce.Buffer),witness:Be.typeforce.maybe(Be.typeforce.arrayOf(Be.typeforce.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||fI.bitcoin);const n={network:r},s=Lr.value(()=>{const a=Buffer.from(my.decode(t.address)),c=a.readUInt8(0),l=a.slice(1);return{version:c,hash:l}}),i=Lr.value(()=>Hr.decompile(t.input)),o=Lr.value(()=>{const a=i(),c=a[a.length-1];return{network:r,output:c===no.OP_FALSE?Buffer.from([]):c,input:Hr.compile(a.slice(0,-1)),witness:t.witness||[]}});if(Lr.prop(n,"address",()=>{if(!n.hash)return;const a=Buffer.allocUnsafe(21);return a.writeUInt8(n.network.scriptHash,0),n.hash.copy(a,1),my.encode(a)}),Lr.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 yy.hash160(n.redeem.output)}),Lr.prop(n,"output",()=>{if(n.hash)return Hr.compile([no.OP_HASH160,n.hash,no.OP_EQUAL])}),Lr.prop(n,"redeem",()=>{if(t.input)return o()}),Lr.prop(n,"input",()=>{if(!(!t.redeem||!t.redeem.input||!t.redeem.output))return Hr.compile([].concat(Hr.decompile(t.redeem.input),t.redeem.output))}),Lr.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),Lr.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]!==no.OP_HASH160||t.output[1]!==20||t.output[22]!==no.OP_EQUAL)throw new TypeError("Output is invalid");const l=t.output.slice(2,22);if(a.length>0&&!a.equals(l))throw new TypeError("Hash mismatch");a=l}const c=l=>{if(l.output){const u=Hr.decompile(l.output);if(!u||u.length<1)throw new TypeError("Redeem.output too short");if(l.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(Hr.countNonPushOnlyOPs(u)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const f=yy.hash160(l.output);if(a.length>0&&!a.equals(f))throw new TypeError("Hash mismatch");a=f}if(l.input){const u=l.input.length>0,f=l.witness&&l.witness.length>0;if(!u&&!f)throw new TypeError("Empty input");if(u&&f)throw new TypeError("Input and witness provided");if(u){const h=Hr.decompile(l.input);if(!Hr.isPushOnly(h))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const l=i();if(!l||l.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(o().output))throw new TypeError("Input is invalid");c(o())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const l=o();if(t.redeem.output&&!t.redeem.output.equals(l.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(l.input))throw new TypeError("Redeem.input mismatch")}c(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!(0,Be.stacksEqual)(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)}nu.p2sh=dI;var su={},_n={};Object.defineProperty(_n,"__esModule",{value:!0});_n.bech32m=_n.bech32=void 0;const wc="qpzry9x8gf2tvdw0s3jn54khce6mua7l",Nw={};for(let t=0;t<wc.length;t++){const e=wc.charAt(t);Nw[e]=t}function xi(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 gy(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=xi(e)^n>>5}e=xi(e);for(let r=0;r<t.length;++r){const n=t.charCodeAt(r);e=xi(e)^n&31}return e}function Ah(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 hI(t){return Ah(t,8,5,!0)}function pI(t){const e=Ah(t,5,8,!1);if(Array.isArray(e))return e}function yI(t){const e=Ah(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}function Uw(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 l=gy(o);if(typeof l=="string")throw new Error(l);let u=o+"1";for(let f=0;f<a.length;++f){const h=a[f];if(h>>5)throw new Error("Non 5-bit word");l=xi(l)^h,u+=wc.charAt(h)}for(let f=0;f<6;++f)l=xi(l);l^=e;for(let f=0;f<6;++f){const h=l>>(5-f)*5&31;u+=wc.charAt(h)}return u}function n(o,a){if(a=a||90,o.length<8)return o+" too short";if(o.length>a)return"Exceeds length limit";const c=o.toLowerCase(),l=o.toUpperCase();if(o!==c&&o!==l)return"Mixed-case string "+o;o=c;const u=o.lastIndexOf("1");if(u===-1)return"No separator character for "+o;if(u===0)return"Missing prefix for "+o;const f=o.slice(0,u),h=o.slice(u+1);if(h.length<6)return"Data too short";let d=gy(f);if(typeof d=="string")return d;const m=[];for(let g=0;g<h.length;++g){const v=h.charAt(g),S=Nw[v];if(S===void 0)return"Unknown character "+v;d=xi(d)^S,!(g+6>=h.length)&&m.push(S)}return d!==e?"Invalid checksum for "+o:{prefix:f,words:m}}function s(o,a){const c=n(o,a);if(typeof c=="object")return c}function i(o,a){const c=n(o,a);if(typeof c=="object")return c;throw new Error(c)}return{decodeUnsafe:s,decode:i,encode:r,toWords:hI,fromWordsUnsafe:pI,fromWords:yI}}_n.bech32=Uw("bech32");_n.bech32m=Uw("bech32m");Object.defineProperty(su,"__esModule",{value:!0});su.p2wpkh=void 0;const Qu=cs,mI=bt,sc=Jt(),tt=vt,Ln=Zt,Da=_n,by=sc.OPS,gI=Buffer.alloc(0);function bI(t,e){if(!t.address&&!t.hash&&!t.output&&!t.pubkey&&!t.witness)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,tt.typeforce)({address:tt.typeforce.maybe(tt.typeforce.String),hash:tt.typeforce.maybe(tt.typeforce.BufferN(20)),input:tt.typeforce.maybe(tt.typeforce.BufferN(0)),network:tt.typeforce.maybe(tt.typeforce.Object),output:tt.typeforce.maybe(tt.typeforce.BufferN(22)),pubkey:tt.typeforce.maybe(tt.isPoint),signature:tt.typeforce.maybe(sc.isCanonicalScriptSignature),witness:tt.typeforce.maybe(tt.typeforce.arrayOf(tt.typeforce.Buffer))},t);const r=Ln.value(()=>{const i=Da.bech32.decode(t.address),o=i.words.shift(),a=Da.bech32.fromWords(i.words);return{version:o,prefix:i.prefix,data:Buffer.from(a)}}),n=t.network||mI.bitcoin,s={name:"p2wpkh",network:n};if(Ln.prop(s,"address",()=>{if(!s.hash)return;const i=Da.bech32.toWords(s.hash);return i.unshift(0),Da.bech32.encode(n.bech32,i)}),Ln.prop(s,"hash",()=>{if(t.output)return t.output.slice(2,22);if(t.address)return r().data;if(t.pubkey||s.pubkey)return Qu.hash160(t.pubkey||s.pubkey)}),Ln.prop(s,"output",()=>{if(s.hash)return sc.compile([by.OP_0,s.hash])}),Ln.prop(s,"pubkey",()=>{if(t.pubkey)return t.pubkey;if(t.witness)return t.witness[1]}),Ln.prop(s,"signature",()=>{if(t.witness)return t.witness[0]}),Ln.prop(s,"input",()=>{if(s.witness)return gI}),Ln.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]!==by.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=Qu.hash160(t.pubkey);if(i.length>0&&!i.equals(o))throw new TypeError("Hash mismatch");if(i=o,!(0,tt.isPoint)(t.pubkey)||t.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(t.witness.length!==2)throw new TypeError("Witness is invalid");if(!sc.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,tt.isPoint)(t.witness[1])||t.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const o=Qu.hash160(t.witness[1]);if(i.length>0&&!i.equals(o))throw new TypeError("Hash mismatch")}}return Object.assign(s,t)}su.p2wpkh=bI;var iu={};Object.defineProperty(iu,"__esModule",{value:!0});iu.p2wsh=void 0;const wy=cs,wI=bt,dn=Jt(),Pe=vt,on=Zt,Ha=_n,vy=dn.OPS,el=Buffer.alloc(0);function za(t){return!!(Buffer.isBuffer(t)&&t.length===65&&t[0]===4&&(0,Pe.isPoint)(t))}function vI(t,e){if(!t.address&&!t.hash&&!t.output&&!t.redeem&&!t.witness)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Pe.typeforce)({network:Pe.typeforce.maybe(Pe.typeforce.Object),address:Pe.typeforce.maybe(Pe.typeforce.String),hash:Pe.typeforce.maybe(Pe.typeforce.BufferN(32)),output:Pe.typeforce.maybe(Pe.typeforce.BufferN(34)),redeem:Pe.typeforce.maybe({input:Pe.typeforce.maybe(Pe.typeforce.Buffer),network:Pe.typeforce.maybe(Pe.typeforce.Object),output:Pe.typeforce.maybe(Pe.typeforce.Buffer),witness:Pe.typeforce.maybe(Pe.typeforce.arrayOf(Pe.typeforce.Buffer))}),input:Pe.typeforce.maybe(Pe.typeforce.BufferN(0)),witness:Pe.typeforce.maybe(Pe.typeforce.arrayOf(Pe.typeforce.Buffer))},t);const r=on.value(()=>{const o=Ha.bech32.decode(t.address),a=o.words.shift(),c=Ha.bech32.fromWords(o.words);return{version:a,prefix:o.prefix,data:Buffer.from(c)}}),n=on.value(()=>dn.decompile(t.redeem.input));let s=t.network;s||(s=t.redeem&&t.redeem.network||wI.bitcoin);const i={network:s};if(on.prop(i,"address",()=>{if(!i.hash)return;const o=Ha.bech32.toWords(i.hash);return o.unshift(0),Ha.bech32.encode(s.bech32,o)}),on.prop(i,"hash",()=>{if(t.output)return t.output.slice(2);if(t.address)return r().data;if(i.redeem&&i.redeem.output)return wy.sha256(i.redeem.output)}),on.prop(i,"output",()=>{if(i.hash)return dn.compile([vy.OP_0,i.hash])}),on.prop(i,"redeem",()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:el,witness:t.witness.slice(0,-1)}}),on.prop(i,"input",()=>{if(i.witness)return el}),on.prop(i,"witness",()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const o=dn.toStack(n());return i.redeem=Object.assign({witness:o},t.redeem),i.redeem.input=el,[].concat(o,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)}),on.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]!==vy.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=dn.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(dn.countNonPushOnlyOPs(a)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const c=wy.sha256(t.redeem.output);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch");o=c}if(t.redeem.input&&!dn.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!(0,Pe.stacksEqual)(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(za)||t.redeem.output&&(dn.decompile(t.redeem.output)||[]).some(za))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(za)||(dn.decompile(a)||[]).some(za))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(i,t)}iu.p2wsh=vI;var so={},zs={};Object.defineProperty(zs,"__esModule",{value:!0});zs.getEccLib=zs.initEccLib=void 0;const bo={};function EI(t,e){t?t!==bo.eccLib&&(e!=null&&e.DANGER_DO_NOT_VERIFY_ECCLIB||AI(t),bo.eccLib=t):bo.eccLib=t}zs.initEccLib=EI;function SI(){if(!bo.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return bo.eccLib}zs.getEccLib=SI;const an=t=>Buffer.from(t,"hex");function AI(t){er(typeof t.isXOnlyPoint=="function"),er(t.isXOnlyPoint(an("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),er(t.isXOnlyPoint(an("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),er(t.isXOnlyPoint(an("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),er(t.isXOnlyPoint(an("0000000000000000000000000000000000000000000000000000000000000001"))),er(!t.isXOnlyPoint(an("0000000000000000000000000000000000000000000000000000000000000000"))),er(!t.isXOnlyPoint(an("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),er(typeof t.xOnlyPointAddTweak=="function"),xI.forEach(e=>{const r=t.xOnlyPointAddTweak(an(e.pubkey),an(e.tweak));e.result===null?er(r===null):(er(r!==null),er(r.parity===e.parity),er(Buffer.from(r.xOnlyPubkey).equals(an(e.result))))})}function er(t){if(!t)throw new Error("ecc library invalid")}const xI=[{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 xh={};(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=Js,r=zs,n=cs,s=ut,i=vt;t.LEAF_VERSION_TAPSCRIPT=192,t.MAX_TAPTREE_DEPTH=128;const o=g=>"left"in g&&"right"in g;function a(g,v){if(g.length<33)throw new TypeError(`The control-block length is too small. Got ${g.length}, expected min 33.`);const S=(g.length-33)/32;let _=v;for(let E=0;E<S;E++){const x=g.slice(33+32*E,65+32*E);_.compare(x)<0?_=d(_,x):_=d(x,_)}return _}t.rootHashFromPath=a;function c(g){if((0,i.isTapleaf)(g))return{hash:u(g)};const v=[c(g[0]),c(g[1])];v.sort((E,x)=>E.hash.compare(x.hash));const[S,_]=v;return{hash:d(S.hash,_.hash),left:S,right:_}}t.toHashTree=c;function l(g,v){if(o(g)){const S=l(g.left,v);if(S!==void 0)return[...S,g.right.hash];const _=l(g.right,v);if(_!==void 0)return[..._,g.left.hash]}else if(g.hash.equals(v))return[]}t.findScriptPath=l;function u(g){const v=g.version||t.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",e.Buffer.concat([e.Buffer.from([v]),m(g.output)]))}t.tapleafHash=u;function f(g,v){return n.taggedHash("TapTweak",e.Buffer.concat(v?[g,v]:[g]))}t.tapTweakHash=f;function h(g,v){if(!e.Buffer.isBuffer(g)||g.length!==32||v&&v.length!==32)return null;const S=f(g,v),_=(0,r.getEccLib)().xOnlyPointAddTweak(g,S);return!_||_.xOnlyPubkey===null?null:{parity:_.parity,x:e.Buffer.from(_.xOnlyPubkey)}}t.tweakKey=h;function d(g,v){return n.taggedHash("TapBranch",e.Buffer.concat([g,v]))}function m(g){const v=s.varuint.encodingLength(g.length),S=e.Buffer.allocUnsafe(v);return s.varuint.encode(g.length,S),e.Buffer.concat([S,g])}})(xh);var kt={},Ey;function kI(){if(Ey)return kt;Ey=1,Object.defineProperty(kt,"__esModule",{value:!0}),kt.toOutputScript=kt.fromOutputScript=kt.toBech32=kt.toBase58Check=kt.fromBech32=kt.fromBase58Check=void 0;const t=bt,e=kh(),r=Jt(),n=vt,s=_n,i=Sh,o=40,a=2,c=16,l=2,u=80,f="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function h(E,x){const O=E.slice(2);if(O.length<a||O.length>o)throw new TypeError("Invalid program length for segwit address");const P=E[0]-u;if(P<l||P>c)throw new TypeError("Invalid version for segwit address");if(E[1]!==O.length)throw new TypeError("Invalid script for segwit address");return console.warn(f),v(O,P,x.bech32)}function d(E){const x=Buffer.from(i.decode(E));if(x.length<21)throw new TypeError(E+" is too short");if(x.length>21)throw new TypeError(E+" is too long");const O=x.readUInt8(0),P=x.slice(1);return{version:O,hash:P}}kt.fromBase58Check=d;function m(E){let x,O;try{x=s.bech32.decode(E)}catch{}if(x){if(O=x.words[0],O!==0)throw new TypeError(E+" uses wrong encoding")}else if(x=s.bech32m.decode(E),O=x.words[0],O===0)throw new TypeError(E+" uses wrong encoding");const P=s.bech32.fromWords(x.words.slice(1));return{version:O,prefix:x.prefix,data:Buffer.from(P)}}kt.fromBech32=m;function g(E,x){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const O=Buffer.allocUnsafe(21);return O.writeUInt8(x,0),E.copy(O,1),i.encode(O)}kt.toBase58Check=g;function v(E,x,O){const P=s.bech32.toWords(E);return P.unshift(x),x===0?s.bech32.encode(O,P):s.bech32m.encode(O,P)}kt.toBech32=v;function S(E,x){x=x||t.bitcoin;try{return e.p2pkh({output:E,network:x}).address}catch{}try{return e.p2sh({output:E,network:x}).address}catch{}try{return e.p2wpkh({output:E,network:x}).address}catch{}try{return e.p2wsh({output:E,network:x}).address}catch{}try{return e.p2tr({output:E,network:x}).address}catch{}try{return h(E,x)}catch{}throw new Error(r.toASM(E)+" has no matching Address")}kt.fromOutputScript=S;function _(E,x){x=x||t.bitcoin;let O,P;try{O=d(E)}catch{}if(O){if(O.version===x.pubKeyHash)return e.p2pkh({hash:O.hash}).output;if(O.version===x.scriptHash)return e.p2sh({hash:O.hash}).output}else{try{P=m(E)}catch{}if(P){if(P.prefix!==x.bech32)throw new Error(E+" has an invalid prefix");if(P.version===0){if(P.data.length===20)return e.p2wpkh({hash:P.data}).output;if(P.data.length===32)return e.p2wsh({hash:P.data}).output}else if(P.version===1){if(P.data.length===32)return e.p2tr({pubkey:P.data}).output}else if(P.version>=l&&P.version<=c&&P.data.length>=a&&P.data.length<=o)return console.warn(f),r.compile([P.version+u,P.data])}}throw new Error(E+" has no matching Script")}return kt.toOutputScript=_,kt}var Sy;function _I(){if(Sy)return so;Sy=1,Object.defineProperty(so,"__esModule",{value:!0}),so.p2tr=void 0;const t=Js,e=bt,r=Jt(),n=vt,s=zs,i=xh,o=Zt,a=_n,c=kI(),l=r.OPS,u=1,f=80;function h(d,m){if(!d.address&&!d.output&&!d.pubkey&&!d.internalPubkey&&!(d.witness&&d.witness.length>1))throw new TypeError("Not enough data");m=Object.assign({validate:!0},m||{}),(0,n.typeforce)({address:n.typeforce.maybe(n.typeforce.String),input:n.typeforce.maybe(n.typeforce.BufferN(0)),network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.BufferN(34)),internalPubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),hash:n.typeforce.maybe(n.typeforce.BufferN(32)),pubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),signature:n.typeforce.maybe(n.typeforce.anyOf(n.typeforce.BufferN(64),n.typeforce.BufferN(65))),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer)),scriptTree:n.typeforce.maybe(n.isTaptree),redeem:n.typeforce.maybe({output:n.typeforce.maybe(n.typeforce.Buffer),redeemVersion:n.typeforce.maybe(n.typeforce.Number),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer))}),redeemVersion:n.typeforce.maybe(n.typeforce.Number)},d);const g=o.value(()=>(0,c.fromBech32)(d.address)),v=o.value(()=>{if(!(!d.witness||!d.witness.length))return d.witness.length>=2&&d.witness[d.witness.length-1][0]===f?d.witness.slice(0,-1):d.witness.slice()}),S=o.value(()=>{if(d.scriptTree)return(0,i.toHashTree)(d.scriptTree);if(d.hash)return{hash:d.hash}}),_=d.network||e.bitcoin,E={name:"p2tr",network:_};if(o.prop(E,"address",()=>{if(!E.pubkey)return;const x=a.bech32m.toWords(E.pubkey);return x.unshift(u),a.bech32m.encode(_.bech32,x)}),o.prop(E,"hash",()=>{const x=S();if(x)return x.hash;const O=v();if(O&&O.length>1){const P=O[O.length-1],$=P[0]&n.TAPLEAF_VERSION_MASK,z=O[O.length-2],C=(0,i.tapleafHash)({output:z,version:$});return(0,i.rootHashFromPath)(P,C)}return null}),o.prop(E,"output",()=>{if(E.pubkey)return r.compile([l.OP_1,E.pubkey])}),o.prop(E,"redeemVersion",()=>d.redeemVersion?d.redeemVersion:d.redeem&&d.redeem.redeemVersion!==void 0&&d.redeem.redeemVersion!==null?d.redeem.redeemVersion:i.LEAF_VERSION_TAPSCRIPT),o.prop(E,"redeem",()=>{const x=v();if(!(!x||x.length<2))return{output:x[x.length-2],witness:x.slice(0,-2),redeemVersion:x[x.length-1][0]&n.TAPLEAF_VERSION_MASK}}),o.prop(E,"pubkey",()=>{if(d.pubkey)return d.pubkey;if(d.output)return d.output.slice(2);if(d.address)return g().data;if(E.internalPubkey){const x=(0,i.tweakKey)(E.internalPubkey,E.hash);if(x)return x.x}}),o.prop(E,"internalPubkey",()=>{if(d.internalPubkey)return d.internalPubkey;const x=v();if(x&&x.length>1)return x[x.length-1].slice(1,33)}),o.prop(E,"signature",()=>{if(d.signature)return d.signature;const x=v();if(!(!x||x.length!==1))return x[0]}),o.prop(E,"witness",()=>{if(d.witness)return d.witness;const x=S();if(x&&d.redeem&&d.redeem.output&&d.internalPubkey){const O=(0,i.tapleafHash)({output:d.redeem.output,version:E.redeemVersion}),P=(0,i.findScriptPath)(x,O);if(!P)return;const $=(0,i.tweakKey)(d.internalPubkey,x.hash);if(!$)return;const z=t.Buffer.concat([t.Buffer.from([E.redeemVersion|$.parity]),d.internalPubkey].concat(P));return[d.redeem.output,z]}if(d.signature)return[d.signature]}),m.validate){let x=t.Buffer.from([]);if(d.address){if(_&&_.bech32!==g().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(g().version!==u)throw new TypeError("Invalid address version");if(g().data.length!==32)throw new TypeError("Invalid address data");x=g().data}if(d.pubkey){if(x.length>0&&!x.equals(d.pubkey))throw new TypeError("Pubkey mismatch");x=d.pubkey}if(d.output){if(d.output.length!==34||d.output[0]!==l.OP_1||d.output[1]!==32)throw new TypeError("Output is invalid");if(x.length>0&&!x.equals(d.output.slice(2)))throw new TypeError("Pubkey mismatch");x=d.output.slice(2)}if(d.internalPubkey){const $=(0,i.tweakKey)(d.internalPubkey,E.hash);if(x.length>0&&!x.equals($.x))throw new TypeError("Pubkey mismatch");x=$.x}if(x&&x.length&&!(0,s.getEccLib)().isXOnlyPoint(x))throw new TypeError("Invalid pubkey for p2tr");const O=S();if(d.hash&&O&&!d.hash.equals(O.hash))throw new TypeError("Hash mismatch");if(d.redeem&&d.redeem.output&&O){const $=(0,i.tapleafHash)({output:d.redeem.output,version:E.redeemVersion});if(!(0,i.findScriptPath)(O,$))throw new TypeError("Redeem script not in tree")}const P=v();if(d.redeem&&E.redeem){if(d.redeem.redeemVersion&&d.redeem.redeemVersion!==E.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(d.redeem.output){if(r.decompile(d.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(E.redeem.output&&!d.redeem.output.equals(E.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(d.redeem.witness&&E.redeem.witness&&!(0,n.stacksEqual)(d.redeem.witness,E.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(P&&P.length)if(P.length===1){if(d.signature&&!d.signature.equals(P[0]))throw new TypeError("Signature mismatch")}else{const $=P[P.length-1];if($.length<33)throw new TypeError(`The control-block length is too small. Got ${$.length}, expected min 33.`);if(($.length-33)%32!==0)throw new TypeError(`The control-block length of ${$.length} is incorrect!`);const z=($.length-33)/32;if(z>128)throw new TypeError(`The script path is too long. Got ${z}, expected max 128.`);const C=$.slice(1,33);if(d.internalPubkey&&!d.internalPubkey.equals(C))throw new TypeError("Internal pubkey mismatch");if(!(0,s.getEccLib)().isXOnlyPoint(C))throw new TypeError("Invalid internalPubkey for p2tr witness");const Y=$[0]&n.TAPLEAF_VERSION_MASK,W=P[P.length-2],K=(0,i.tapleafHash)({output:W,version:Y}),U=(0,i.rootHashFromPath)($,K),N=(0,i.tweakKey)(C,U);if(!N)throw new TypeError("Invalid outputKey for p2tr witness");if(x.length&&!x.equals(N.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(N.parity!==($[0]&1))throw new Error("Incorrect parity")}}return Object.assign(E,d)}return so.p2tr=h,so}var Ay;function kh(){return Ay||(Ay=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=Qc;Object.defineProperty(t,"embed",{enumerable:!0,get:function(){return e.p2data}});const r=eu;Object.defineProperty(t,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=tu;Object.defineProperty(t,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const s=ru;Object.defineProperty(t,"p2pkh",{enumerable:!0,get:function(){return s.p2pkh}});const i=nu;Object.defineProperty(t,"p2sh",{enumerable:!0,get:function(){return i.p2sh}});const o=su;Object.defineProperty(t,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const a=iu;Object.defineProperty(t,"p2wsh",{enumerable:!0,get:function(){return a.p2wsh}});const c=_I();Object.defineProperty(t,"p2tr",{enumerable:!0,get:function(){return c.p2tr}})}(Xu)),Xu}Object.defineProperty(_e,"__esModule",{value:!0});_e.signatureBlocksAction=_e.checkInputForSig=_e.pubkeyInScript=_e.pubkeyPositionInScript=_e.witnessStackToScriptWitness=_e.isP2TR=_e.isP2SHScript=_e.isP2WSHScript=_e.isP2WPKH=_e.isP2PKH=_e.isP2PK=_e.isP2MS=void 0;const xy=Aa,wo=Jt(),Va=Sa,TI=cs,Qs=kh();function ei(t){return e=>{try{return t({output:e}),!0}catch{return!1}}}_e.isP2MS=ei(Qs.p2ms);_e.isP2PK=ei(Qs.p2pk);_e.isP2PKH=ei(Qs.p2pkh);_e.isP2WPKH=ei(Qs.p2wpkh);_e.isP2WSHScript=ei(Qs.p2wsh);_e.isP2SHScript=ei(Qs.p2sh);_e.isP2TR=ei(Qs.p2tr);function II(t){let e=Buffer.allocUnsafe(0);function r(o){e=Buffer.concat([e,Buffer.from(o)])}function n(o){const a=e.length,c=xy.encodingLength(o);e=Buffer.concat([e,Buffer.allocUnsafe(c)]),xy.encode(o,e,a)}function s(o){n(o.length),r(o)}function i(o){n(o.length),o.forEach(s)}return i(t),e}_e.witnessStackToScriptWitness=II;function Mw(t,e){const r=(0,TI.hash160)(t),n=t.slice(1,33),s=wo.decompile(e);if(s===null)throw new Error("Unknown script error");return s.findIndex(i=>typeof i=="number"?!1:i.equals(t)||i.equals(r)||i.equals(n))}_e.pubkeyPositionInScript=Mw;function PI(t,e){return Mw(t,e)!==-1}_e.pubkeyInScript=PI;function OI(t,e){return BI(t).some(n=>Fw(n,wo.signature.decode,e))}_e.checkInputForSig=OI;function Fw(t,e,r){const{hashType:n}=e(t),s=[];switch(n&Va.Transaction.SIGHASH_ANYONECANPAY&&s.push("addInput"),n&31){case Va.Transaction.SIGHASH_ALL:break;case Va.Transaction.SIGHASH_SINGLE:case Va.Transaction.SIGHASH_NONE:s.push("addOutput"),s.push("setInputSequence");break}return s.indexOf(r)===-1}_e.signatureBlocksAction=Fw;function BI(t){let e=[];if((t.partialSig||[]).length===0){if(!t.finalScriptSig&&!t.finalScriptWitness)return[];e=CI(t)}else e=t.partialSig;return e.map(r=>r.signature)}function CI(t){const e=t.finalScriptSig?wo.decompile(t.finalScriptSig)||[]:[],r=t.finalScriptWitness?wo.decompile(t.finalScriptWitness)||[]:[];return e.concat(r).filter(n=>Buffer.isBuffer(n)&&wo.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(Fe,"__esModule",{value:!0});Fe.checkTaprootInputForSigs=Fe.tapTreeFromList=Fe.tapTreeToList=Fe.tweakInternalPubKey=Fe.checkTaprootOutputFields=Fe.checkTaprootInputFields=Fe.isTaprootOutput=Fe.isTaprootInput=po=Fe.serializeTaprootSignature=Fe.tapScriptFinalizer=Fe.toXOnly=void 0;const _h=vt,$I=Sa,ou=_e,os=xh,RI=kh(),NI=_e,UI=t=>t.length===32?t:t.slice(1,33);Fe.toXOnly=UI;function MI(t,e,r){const n=tP(e,t,r);try{const i=QI(e,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,ou.witnessStackToScriptWitness)(i)}}catch(s){throw new Error(`Can not finalize taproot input #${t}: ${s}`)}}Fe.tapScriptFinalizer=MI;function FI(t,e){const r=e?Buffer.from([e]):Buffer.from([]);return Buffer.concat([t,r])}var po=Fe.serializeTaprootSignature=FI;function ic(t){return t&&!!(t.tapInternalKey||t.tapMerkleRoot||t.tapLeafScript&&t.tapLeafScript.length||t.tapBip32Derivation&&t.tapBip32Derivation.length||t.witnessUtxo&&(0,ou.isP2TR)(t.witnessUtxo.script))}Fe.isTaprootInput=ic;function oc(t,e){return t&&!!(t.tapInternalKey||t.tapTree||t.tapBip32Derivation&&t.tapBip32Derivation.length||e&&(0,ou.isP2TR)(e))}Fe.isTaprootOutput=oc;function jI(t,e,r){XI(t,e,r),JI(t,e,r)}Fe.checkTaprootInputFields=jI;function LI(t,e,r){YI(t,e,r),DI(t,e)}Fe.checkTaprootOutputFields=LI;function DI(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=HI(r,n);if(s&&!s.equals(i))throw new Error("Error adding output. Script or address missmatch.")}}function HI(t,e){const r=e&&jw(e.leaves),{output:n}=(0,RI.p2tr)({internalPubkey:t,scriptTree:r});return n}function zI(t,e){const r=e.tapInternalKey,n=r&&(0,os.tweakKey)(r,e.tapMerkleRoot);if(!n)throw new Error(`Cannot tweak tap internal key for input #${t}. Public key: ${r&&r.toString("hex")}`);return n.x}Fe.tweakInternalPubKey=zI;function VI(t){if(!(0,_h.isTaptree)(t))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return sd(t)}Fe.tapTreeToList=VI;function jw(t=[]){return t.length===1&&t[0].depth===0?{output:t[0].script,version:t[0].leafVersion}:ZI(t)}Fe.tapTreeFromList=jw;function qI(t,e){return WI(t).some(n=>(0,NI.signatureBlocksAction)(n,GI,e))}Fe.checkTaprootInputForSigs=qI;function GI(t){return{signature:t.slice(0,64),hashType:t.slice(64)[0]||$I.Transaction.SIGHASH_DEFAULT}}function WI(t){const e=[];if(t.tapKeySig&&e.push(t.tapKeySig),t.tapScriptSig&&e.push(...t.tapScriptSig.map(r=>r.signature)),!e.length){const r=KI(t.finalScriptWitness);r&&e.push(r)}return e}function KI(t){if(!t)return;const e=t.slice(2);if(e.length===64||e.length===65)return e}function sd(t,e=[],r=0){if(r>os.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return t?(0,_h.isTapleaf)(t)?(e.push({depth:r,leafVersion:t.version||os.LEAF_VERSION_TAPSCRIPT,script:t.output}),e):(t[0]&&sd(t[0],e,r+1),t[1]&&sd(t[1],e,r+1),e):[]}function ZI(t){let e;for(const r of t)if(e=id(r,e),!e)throw new Error("No room left to insert tapleaf in tree");return e}function id(t,e,r=0){if(r>os.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,_h.isTapleaf)(e))return;const n=id(t,e&&e[0],r+1);if(n)return[n,e&&e[1]];const s=id(t,e&&e[1],r+1);if(s)return[e&&e[0],s]}function XI(t,e,r){const n=ic(t)&&ki(e),s=ki(t)&&ic(e),i=t===e&&ic(e)&&ki(e);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function YI(t,e,r){const n=oc(t)&&ki(e),s=ki(t)&&oc(e),i=t===e&&oc(e)&&ki(e);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function JI(t,e,r){if(e.tapMerkleRoot){const n=(e.tapLeafScript||[]).every(i=>tl(i,e.tapMerkleRoot)),s=(t.tapLeafScript||[]).every(i=>tl(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=>tl(s,t.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function tl(t,e){if(!e)return!0;const r=(0,os.tapleafHash)({output:t.script,version:t.leafVersion});return(0,os.rootHashFromPath)(t.controlBlock,r).equals(e)}function QI(t,e){const r=(0,os.tapleafHash)({output:e.script,version:e.leafVersion});return(t.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>eP(e.script,n)).sort((n,s)=>s.positionInScript-n.positionInScript).map(n=>n.signature)}function eP(t,e){return Object.assign({positionInScript:(0,ou.pubkeyPositionInScript)(e.pubkey,t)},e)}function tP(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=>rP(s,t.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${e}. Signature for tapleaf script not found.`);return n}function rP(t,e,r){const n=(0,os.tapleafHash)({output:t.script,version:t.leafVersion});return(!r||r.equals(n))&&e.find(i=>i.leafHash.equals(n))!==void 0}function ki(t){return t&&!!(t.redeemScript||t.witnessScript||t.bip32Derivation&&t.bip32Derivation.length)}const tr={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"},qa=192;Ae.initEccLib(cr);let ky=class Lw{constructor(e,r){this.signer=e,this.internalPubkey=ty(),this.network=r}static async from(e){const r=await e.getNetwork();return new Lw(e,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(tr.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 l=[];if(i&&i.length>0)for(const h of i){const d=await c.getTransaction(h);for(let m=0;m<d.vout.length;m++){const g=d.vout[m];g.scriptpubkey_address===a&&l.push({txid:d.txid,vout:m,value:g.value,status:{confirmed:!1}})}}else l=await c.getUTXOs(a);const u=l.reduce((h,d)=>h+d.value,0);if(u===0)throw new Error(`${a} ${tr.notFunded}`);for(let h=0;h<l.length;h++)o.addInput(Buffer.from(l[h].txid,"hex").reverse(),l[h].vout);if(s!=null&&s.vSize){const h=await c.getFeeRates(),d=Math.ceil(h.hourFee*s.vSize),m=u-d;return o.addOutput(Ae.address.toOutputScript(r,this.network),m),{tx:o,usedUtxos:l}}const f=(s==null?void 0:s.fee)??await c.suggestFee(a,u,Si.MEDIUM);return o.addOutput(Ae.address.toOutputScript(r,this.network),u-f),{tx:o,usedUtxos:l,fee:f,balance:u}}async 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;oe.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,Si.MEDIUM));const a=await this.signer.send(i,o,r);return b.Ok(a)}async generateRedeemSACP(e,r,n){const{tx:s,usedUtxos:i}=await this._buildRawTx(e,e.destination_swap.delegate,"redeem",{fee:n}),o=await this.getOutputScript(e,"redeem"),a=Ae.Transaction.SIGHASH_SINGLE|Ae.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(1,e),l=i.map(f=>f.value),u=to(o,i.length);for(let f=0;f<s.ins.length;f++){const h=s.hashForWitnessV1(f,u,l,a,c),d=await this.signer.signSchnorr(h);s.setWitness(f,[po(d,a),Buffer.from(r,"hex"),this.redeemLeaf(b.trim0x(e.destination_swap.secret_hash),Me(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}return s.toHex()}async generateInstantRefundSACP(e){const r=await 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(f=>f.value));s.forEach(({value:f})=>{n.addOutput(r,f-(f===o?i??0:0))});const a=Ae.Transaction.SIGHASH_SINGLE|Ae.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(2,e),l=s.map(f=>f.value),u=to(r,s.length);for(let f=0;f<n.ins.length;f++){const h=n.hashForWitnessV1(f,u,l,a,c),d=await this.signer.signSchnorr(h);n.setWitness(f,[po(d,a),po(d,a),this.instantRefundLeaf(Me(e.source_swap.initiator),Me(e.destination_swap.delegate)),await this.generateControlBlockFor(2,e)])}return n.toHex()}async generateInstantRefundSACPWithHash(e){const r=[],n=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(po(o,n).toString("hex"))}return b.Ok(r)}async instantRefund(e,r,n){Xp(r.length>0,tr.noCounterpartySigs);const{tx:s,usedUtxos:i}=await this._buildRawTx(e,await this.signer.getAddress(),"instantRefund",{fee:n});for(const h of i)if(!r.find(d=>d.utxo===h.txid))throw new Error(tr.counterPartySigNotFound(h.txid));const o=await this.getOutputScript(e,"instantRefund"),a=Ae.Transaction.SIGHASH_DEFAULT,c=this.leafHash(2,e),l=i.map(h=>h.value),u=to(o,i.length);for(let h=0;h<s.ins.length;h++){const d=s.hashForWitnessV1(h,u,l,a,c);if(!cr.verifySchnorr(d,Buffer.from(Me(e.destination_swap.delegate),"hex"),Buffer.from(r[h].sig,"hex")))throw new Error(tr.invalidCounterpartySigForUTXO(r[h].utxo));const m=await this.signer.signSchnorr(d),g=Buffer.from(s.ins[h].hash).reverse().toString("hex"),v=r.find(S=>S.utxo===g);if(!v)throw new Error(tr.counterPartySigNotFound(g));s.setWitness(h,[Buffer.from(v.sig,"hex"),m,this.instantRefundLeaf(Me(e.source_swap.initiator),Me(e.destination_swap.delegate)),await this.generateControlBlockFor(2,e)])}return await(await this.getProvider()).broadcast(s.toHex())}async redeem(e,r,n){const s=await this.getRedeemHex(e,r,n);if(!s.ok)return b.Err(s.error);const o=await(await this.getProvider()).broadcast(s.val);return b.Ok(o)}async getRedeemHex(e,r,n){Xp(Ae.crypto.sha256(Buffer.from(r,"hex")).toString("hex")===b.trim0x(e.destination_swap.secret_hash),tr.secretMismatch);const o=(oe.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),l=this.leafHash(1,e),u=c.map(m=>m.value),f=to(await this.getOutputScript(e,"redeem"),c.length),h=Ae.Transaction.SIGHASH_DEFAULT;for(let m=0;m<a.ins.length;m++){const g=a.hashForWitnessV1(m,f,u,h,l),v=await this.signer.signSchnorr(g);a.setWitness(m,[v,Buffer.from(r,"hex"),this.redeemLeaf(b.trim0x(e.destination_swap.secret_hash),Me(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}const{tx:d}=await this._buildRawTx(e,o,"redeem",{vSize:a.virtualSize()},n);for(let m=0;m<d.ins.length;m++){const g=d.hashForWitnessV1(m,f,u,h,l),v=await this.signer.signSchnorr(g);d.setWitness(m,[v,Buffer.from(r,"hex"),this.redeemLeaf(b.trim0x(e.destination_swap.secret_hash),Me(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}return b.Ok(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(tr.htlcNotExpired(o));const a=this.leafHash(0,e),c=s.map(d=>d.value),l=to(await this.getOutputScript(e,"refund"),s.length),u=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,l,c,u,a),g=await this.signer.signSchnorr(m);n.setWitness(d,[g,this.refundLeaf(e.source_swap.timelock,Me(e.source_swap.initiator)),await this.generateControlBlockFor(0,e)])}const h=await(await this.getProvider()).broadcast(n.toHex());return b.Ok(h)}async canRefund(e,r){const s=await(await this.getProvider()).getLatestTip();for(const i of r){let o=0;if(i.status.confirmed&&i.status.block_height+e.source_swap.timelock>s?o=i.status.block_height+e.source_swap.timelock-s+1:i.status.confirmed||(o=e.source_swap.timelock+1),o>0)return[!1,o]}return[!0,0]}async generateControlBlockFor(e,r){let n,s;switch(e){case 1:n=this.redeemLeaf(b.trim0x(r.destination_swap.secret_hash),Me(r.destination_swap.delegate)),s=this.generateLeaves(r,"redeem");break;case 0:n=this.refundLeaf(r.source_swap.timelock,Me(r.source_swap.initiator)),s=this.generateLeaves(r,"refund");break;case 2:n=this.instantRefundLeaf(Me(r.source_swap.initiator),Me(r.destination_swap.delegate)),s=this.generateLeaves(r,"instantRefund");break;default:throw new Error(tr.controlBlockGenerationFailed)}const i=await this.signer.getNetwork(),o=Ae.payments.p2tr({internalPubkey:ty(),network:i,scriptTree:s,redeem:{output:n,redeemVersion:qa}});if(!o.witness)throw new Error(tr.controlBlockGenerationFailed);return o.witness[o.witness.length-1]}leafHash(e,r){let n;switch(e){case 1:n=this.redeemLeaf(b.trim0x(r.destination_swap.secret_hash),Me(r.destination_swap.delegate));break;case 0:n=this.refundLeaf(r.source_swap.timelock,Me(r.source_swap.initiator));break;case 2:n=this.instantRefundLeaf(Me(r.source_swap.initiator),Me(r.destination_swap.redeemer));break;default:throw new Error(tr.invalidLeaf)}return Ae.crypto.taggedHash("TapLeaf",V_(n))}refundLeaf(e,r){return Ae.script.fromASM(`
55
- ${Ae.script.number.encode(e).toString("hex")}
56
- OP_CHECKSEQUENCEVERIFY
57
- OP_DROP
58
- ${r}
59
- OP_CHECKSIG
60
- `.trim().replace(/\s+/g," "))}redeemLeaf(e,r){return Ae.script.fromASM(`
61
- OP_SHA256
62
- ${e}
63
- OP_EQUALVERIFY
64
- ${r}
65
- OP_CHECKSIG
66
- `.trim().replace(/\s+/g," "))}instantRefundLeaf(e,r){return Ae.script.fromASM(`
67
- ${e}
68
- OP_CHECKSIG
69
- ${r}
70
- OP_CHECKSIGADD
71
- OP_2
72
- OP_NUMEQUAL
73
- `.trim().replace(/\s+/g," "))}generateLeaves(e,r){let n,s,i;switch(r){case"redeem":n=e.destination_swap,s=n.delegate,i=n.delegate;break;case"refund":n=e.source_swap,s=n.delegate,i=n.delegate;break;case"instantRefund":n=e.source_swap,s=n.redeemer,i=n.redeemer;break;default:throw new Error("Invalid leaf generation type")}return[{version:qa,output:this.redeemLeaf(n.secret_hash,Me(s))},[{version:qa,output:this.refundLeaf(n.timelock,Me(n.initiator))},{version:qa,output:this.instantRefundLeaf(Me(n.initiator),Me(i))}]]}generateMerkleProofFor(e,r){const n=this.leafHash(1,r),s=this.leafHash(2,r),i=this.leafHash(0,r);switch(e){case 1:{const o=G_(i,s);return[Ae.crypto.taggedHash("TapBranch",Buffer.concat(o))]}case 0:return[s,n];case 2:return[i,n];default:throw new Error(tr.invalidLeaf)}}getProvider(){return this.signer.getProvider()}getPublicKey(){return this.signer.getPublicKey()}htlcActorAddress(){return this.signer.getAddress()}};class Dw{constructor(e){this.quoteUrl=new b.Url(e)}async getQuoteFromAssets({fromAsset:e,toAsset:r,amount:n,isExactOut:s=!1,options:i}){const o=oe.ChainAsset.fromAsset(e),a=oe.ChainAsset.fromAsset(r);return this.getQuote(o,a,n,s,i)}async getQuote(e,r,n,s=!1,i){try{const o={from:e.toString(),to:r.toString(),...s?{to_amount:n.toString()}:{from_amount:n.toString()},...(i==null?void 0:i.affiliateFee)!==void 0&&{affiliate_fee:i.affiliateFee.toString()}},a=this.quoteUrl.endpoint("/v2/quote").addSearchParams(o),c=await b.Fetcher.get(a,{retryCount:0,...i==null?void 0:i.request});return c.error?b.Err(c.error):c.result?b.Ok(c.result):b.Err("GetQuote: Unexpected error, result is undefined")}catch(o){return b.Err("GetQuote:",String(o))}}async getStrategies(){try{const e=await b.Fetcher.get(this.quoteUrl.endpoint("/strategies"));if(e.error)return b.Err(e.error);if(!e.result)return b.Err("GetStrategies: Unexpected error, result is undefined");const r={};for(const n of Object.values(e.result)){const s=uw(n.source_chain,n.source_asset.asset,n.dest_chain,n.dest_asset.asset);r[s]={id:n.id,minAmount:n.min_amount,maxAmount:n.max_amount,fee:n.fee,fixed_fee:Number(n.fixed_fee)}}return b.Ok(r)}catch(e){return b.Err("GetStrategies:",String(e))}}}class Ui extends b.EventBroker{get isInitialized(){return!!this.digestKey}constructor(e,r){super(),this.digestKey=e,this.walletClient=r}static fromDigestKey(e){return new Ui(b.trim0x(e))}static fromWalletClient(e){return new Ui(void 0,e)}async initialize(){if(this.digestKey)return b.Ok("Already initialized");const e=await this.deriveDigestKeyFromWalletClient();return e.error?b.Err(e.error):(this.emit("initialized",!0),b.Ok("Initialized"))}async deriveDigestKeyFromWalletClient(){if(!this.walletClient)return b.Err("No walletClient found");if(!this.walletClient.account)return b.Err("No account found");try{const e=await this.walletClient.signTypedData({account:this.walletClient.account,types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"}],Data:[{name:"Message",type:"string"},{name:"Version",type:"string"},{name:"Nonce",type:"uint256"}]},domain:{name:"GARDEN FINANCE",version:"1"},primaryType:"Data",message:{Message:"Initialize your account",Version:"1.0.2",Nonce:1n}});return this.digestKey=b.trim0x(lo(e)),this.emit("initialized",!0),b.Ok(this.digestKey)}catch(e){return b.Err("Failed to initialize: "+e)}}async getDigestKey(){if(!this.digestKey&&!this.walletClient)return b.Err("No private key or wallet client found");if(!this.digestKey&&this.walletClient){const e=await this.deriveDigestKeyFromWalletClient();if(e.error)return b.Err(e.error)}return this.digestKey?b.Ok(this.digestKey):b.Err("No private key found")}async generateSecret(e){const r=await this.signMessage(e);if(!r.ok)return b.Err(r.error);const n=lo(b.with0x(r.val)),s=lo(n);return b.Ok({secret:n,secretHash:s})}async signMessage(e){if(!this.digestKey){const l=await this.getDigestKey();if(!l.ok)return b.Err(l.error);this.digestKey=l.val}const r=Ja.ECPairFactory(cr),n="Garden.fi"+e.toString(),s=Buffer.from(n,"utf8"),i=lo(s),o=Buffer.from(b.trim0x(this.digestKey),"hex");if(o.length!==32)return b.Err("Invalid private key length. Expected 32 bytes.");const c=r.fromPrivateKey(o).sign(Buffer.from(b.trim0x(i),"hex"));return b.Ok(c.toString("hex"))}}const nP=[{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"}],sP={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},iP={block:jS({format(t){var r;return{transactions:(r=t.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const s=Dc(n);return s.typeHex==="0x7e"&&(s.isSystemTx=n.isSystemTx,s.mint=n.mint?at(n.mint):void 0,s.sourceHash=n.sourceHash,s.type="deposit"),s}),stateRoot:t.stateRoot}}}),transaction:MS({format(t){const e={};return t.type==="0x7e"&&(e.isSystemTx=t.isSystemTx,e.mint=t.mint?at(t.mint):void 0,e.sourceHash=t.sourceHash,e.type="deposit"),e}}),transactionReceipt:qA({format(t){return{l1GasPrice:t.l1GasPrice?at(t.l1GasPrice):null,l1GasUsed:t.l1GasUsed?at(t.l1GasUsed):null,l1Fee:t.l1Fee?at(t.l1Fee):null,l1FeeScalar:t.l1FeeScalar?Number(t.l1FeeScalar):null}}})};function oP(t,e){return uP(t)?cP(t):qx(t,e)}const aP={transaction:oP};function cP(t){lP(t);const{sourceHash:e,data:r,from:n,gas:s,isSystemTx:i,mint:o,to:a,value:c}=t,l=[e,n,a??"0x",o?Ot(o):"0x",c?Ot(c):"0x",s?Ot(s):"0x",i?"0x1":"0x",r??"0x"];return Br(["0x7e",is(l)])}function uP(t){return t.type==="deposit"||typeof t.sourceHash<"u"}function lP(t){const{from:e,to:r}=t;if(e&&!ot(e))throw new Ct({address:e});if(r&&!ot(r))throw new Ct({address:r})}const Mi={blockTime:2e3,contracts:sP,formatters:iP,serializers:aP},fP=ht({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}}}),dP=ht({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}),io=1,Hw=ht({...Mi,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:{...Mi.contracts,disputeGameFactory:{[io]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[io]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[io]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[io]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:io});({...Hw});const oo=11155111,zw=ht({...Mi,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:{...Mi.contracts,disputeGameFactory:{[oo]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[oo]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[oo]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[oo]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:oo});({...zw});const hP=ht({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}),pP=ht({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}),yP=ht({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}}}),mP=ht({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}),gP=ht({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}),bP=ht({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}),wP=1,vP=ht({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:wP}),EP=ht({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}}}),SP=ht({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}),AP=ht({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}),Ga=1,xP=ht({...Mi,id:130,name:"Unichain",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.unichain.org/"]}},blockExplorers:{default:{name:"Uniscan",url:"https://uniscan.xyz",apiUrl:"https://api.uniscan.xyz/api"}},contracts:{...Mi.contracts,multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:0},disputeGameFactory:{[Ga]:{address:"0x2F12d621a16e2d3285929C9996f478508951dFe4"}},portal:{[Ga]:{address:"0x0bd48f6B86a26D3a217d0Fa6FfE2B491B956A7a2"}},l1StandardBridge:{[Ga]:{address:"0x81014F44b0a345033bB2b3B21C7a1A308B35fEeA"}}},sourceId:Ga}),kP={...AP,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},Vw={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/"]}}},qw={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"]}}},Gw={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"]}}},au={ethereum:EP,arbitrum:fP,ethereum_sepolia:kP,arbitrum_sepolia:dP,ethereum_localnet:oe.EthereumLocalnet,arbitrum_localnet:oe.ArbitrumLocalnet,base_sepolia:zw,base:Hw,bera_testnet:pP,citrea_testnet:gP,core:bP,bera:hP,monad_testnet:SP,hyperliquid_testnet:qw,hyperliquid:Gw,unichain:xP,corn:vP,botanix:Vw,bnbchain:yP,bnbchain_testnet:mP},Ww=t=>{for(const[e,r]of Object.entries(au))if(r.id===t)return e;return null},od=async(t,e)=>{var s,i,o;const r=au[t],n=await e.getChainId();if(r)try{if(r.id===n)return b.Ok({message:"Already on the network",walletClient:e});await e.switchChain({id:r.id});const a=Du({account:e.account,chain:r,transport:Cp(e.transport)});return b.Ok({message:"Switched chain",walletClient:a})}catch(a){if(_P(a))if(a.code===4902||a.code===-32603)try{await e.addChain({chain:r});const c=Du({account:e.account,chain:r,transport:Cp(e.transport)});return b.Ok({message:"Added network",walletClient:c})}catch{return b.Err("Failed to add network")}else if((i=(s=a.body)==null?void 0:s.method)!=null&&i.includes("wallet_switchEthereumChain")||(o=a.message)!=null&&o.includes("wallet_switchEthereumChain")){const c=Du({account:e.account,chain:r,transport:Wg()});return b.Ok({message:"Added network",walletClient:c})}else return b.Err("Failed to switch network");else return b.Err("Failed to switch network")}else return b.Err("Chain not supported")},_P=t=>typeof t=="object"&&t!=null&&("code"in t||"message"in t||"body"in t),TP=[{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 Kw{constructor(e,r,n){this.url=new b.Url(e.toString()),this.auth=n,this.wallet=r}get htlcActorAddress(){if(!this.wallet.account)throw new Error("No account found");return this.wallet.account.address}async initiate(e){if(oe.isEvmOrderResponse(e))return this.initiateWithCreateOrderResponse(e);if(!this.wallet.account)return b.Err("No account found");if(this.wallet.account.address.toLowerCase()!==e.source_swap.initiator.toLowerCase())return b.Err("Account address and order initiator mismatch");if(!oe.isEVM(e.source_swap.chain))return b.Err("Source chain is not an EVM chain");const r=e.source_swap.chain,n=await od(r,this.wallet);if(!n.ok)return b.Err(n.error);if(this.wallet=n.val.walletClient,!this.wallet.account)return b.Err("No account found");const{source_swap:s}=e;if(!s.amount||!s.redeemer||!s.timelock||!s.secret_hash)return b.Err("Invalid order");const i=b.with0x(s.secret_hash),o=BigInt(s.timelock),a=b.with0x(s.redeemer),c=BigInt(s.amount),l=await ph(e.source_swap.asset,this.url);if(!l.ok)return b.Err(l.error);const{htlcAddress:u,tokenAddress:f}=l.val,h=oe.ChainAsset.fromString(e.source_swap.asset);return oe.isEvmNativeToken(h.getChain(),h.getSymbol())?this._initiateOnNativeHTLC(i,o,c,a,u):this._initiateOnErc20HTLC(i,o,c,a,u,f,e.order_id)}async _initiateOnNativeHTLC(e,r,n,s,i){if(!this.wallet.account)return b.Err("No account found");try{const a=await Bp({address:b.with0x(i),abi:TP,client:this.wallet}).write.initiate([s,r,n,e],{account:this.wallet.account,chain:this.wallet.chain,value:n});return b.Ok(a)}catch(o){return b.Err("Failed to initiate on native HTLC",String(o))}}async _initiateOnErc20HTLC(e,r,n,s,i,o,a){if(!this.wallet.account)return b.Err("No account found");try{const c=await this.auth.getAuthHeaders();if(!c.ok)return b.Err(c.error);const l=Bp({address:b.with0x(i),abi:nP,client:this.wallet}),u=await b.checkAllowanceAndApprove(Number(n),o,i,this.wallet);if(!u.ok)return b.Err(u.error);const f=await l.read.eip712Domain(),h=await this.wallet.signTypedData({account:this.wallet.account,domain:{name:f[1],version:f[2],chainId:Number(f[3]),verifyingContract:f[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:s,timelock:r,amount:n,secretHash:e}}),d={...c.val,"Content-Type":"application/json"},m=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(a).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:h}),headers:d});if(m.error)return b.Err(m.error);const g=await b.waitForTransactionReceipt(this.wallet,m.result);return g.val&&g.val.status==="success"?b.Ok(m.result?m.result:"Initiate hash not found"):b.Err("Init failed: Transaction receipt not successful")}catch(c){return console.log("init error :",c),b.Err(String(c))}}async executeApprovalTransaction(e){var r;if(!this.wallet.account)return b.Err("No account found");if(!e.approval_transaction)return b.Ok("No approval transaction required");try{const n=e.approval_transaction,s=await this.wallet.sendTransaction({account:this.wallet.account,to:b.with0x(n.to),value:BigInt(n.value),data:b.with0x(n.data),gas:BigInt(n.gas_limit),chain:this.wallet.chain});return((r=(await b.waitForTransactionReceipt(this.wallet,s)).val)==null?void 0:r.status)!=="success"?b.Err("Approval transaction failed"):b.Ok(s)}catch(n){return console.error("executeApprovalTransaction error:",n),b.Err("Failed to execute approval: "+((n==null?void 0:n.message)||String(n)))}}async initiateWithCreateOrderResponse(e){const r=e.initiate_transaction.chain_id,n=Ww(r);if(!n)return b.Err(`Unsupported chain ID: ${r}`);const s=await od(n,this.wallet);if(!s.ok)return b.Err(s.error);if(this.wallet=s.val.walletClient,!this.wallet.account)return b.Err("No account found");try{if(e.approval_transaction){const l=await this.executeApprovalTransaction(e);if(l.error)return b.Err(`Approval failed: ${l.error}`);console.log("Approval transaction completed:",l.val)}const{typed_data:i}=e,o=await this.wallet.signTypedData({account:this.wallet.account,domain:i.domain,types:i.types,primaryType:i.primaryType,message:i.message}),a={...(await this.auth.getAuthHeaders()).val,"Content-Type":"application/json"},c=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:o}),headers:a});return c.error?b.Err(c.error):c.result?b.Ok(c.result):b.Err("Initiate failed: Result is undefined")}catch(i){return console.error("initiateWithCreateOrderResponse error:",i),b.Err("Failed to initiate: "+String(i))}}async redeem(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return b.Err(n.error);const s=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:b.trim0x(r)}),headers:{...n.val,"Content-Type":"application/json"}});if(s.error)return b.Err(s.error);const i=au[e.destination_swap.chain],a=await __({chain:i,transport:Wg()}).waitForTransactionReceipt({hash:s.result,confirmations:1,timeout:3e5});return a&&a.status==="success"?b.Ok(s.result?s.result:"Redeem hash not found"):b.Err("Redeem failed: Transaction receipt not successful")}catch(n){return b.Err(String(n))}}async refund(){return b.Err("Refund not supported")}}const Zw=[{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"}]}],Xw=async(t,e,r,n,s)=>{try{const i=await vo(t.address,e,r,s);if(!i.ok)return b.Err(i.error);if(i.val>=n)return b.Ok("Allowance already approved");const a=st.cairo.uint256(BigInt(n)),c=await t.execute([{contractAddress:b.with0x(e),entrypoint:"approve",calldata:[b.with0x(r),a.low,a.high]}]);await s.waitForTransaction(c.transaction_hash,{retryInterval:3e3,successStates:[st.TransactionExecutionStatus.SUCCEEDED]}),await b.sleep(2e3);for(let l=0;l<20;l++){const u=await vo(t.address,e,r,s);if(!u.ok)return b.Err(u.error);if(u.val>=n)return b.Ok(c.transaction_hash);await b.sleep(2e3);let f=0n;for(let h=0;h<20;h++){const d=await vo(t.address,e,r,s);if(!d.ok)return b.Err(d.error);if(f=d.val,f>=n)break;await b.sleep(2e3)}return f<n?b.Err("Allowance not approved"):b.Ok(c.transaction_hash)}return b.Err("Allowance not approved after transaction.")}catch(i){return b.Err(`Failed to check or approve allowance: ${i instanceof Error?i.message:String(i)}`)}},vo=async(t,e,r,n)=>{try{const i=await new st.Contract(Zw,b.with0x(e),n).call("allowance",[b.with0x(t),b.with0x(r)]);return b.Ok(BigInt((i==null?void 0:i.toString())||"0"))}catch(s){return b.Err(`Failed to check allowance: ${s instanceof Error?s.message:String(s)}`)}},Yw=async(t,e,r,n,s)=>{const i=await vo(t,e,r,n);return i.ok?b.Ok(i.val>=s):b.Err(i.error)},Jw=[{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"}]}],IP={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 Qw{constructor(e,r,n,s,i){this.url=e instanceof b.Url?e:new b.Url(e),this.account=r,this.starknetProvider=new st.RpcProvider({nodeUrl:i||Zo[n].nodeUrl}),this.chainId=Zo[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(oe.isStarknetOrderResponse(e))return this.initiateWithCreateOrderResponse(e);if(!this.account.address)return b.Err("No account address");const{source_swap:r}=e,{redeemer:n,amount:s}=r;if(!s||!n||!r.secret_hash||!r.timelock)return b.Err("Invalid order");try{const i=new st.Contract(Jw,e.source_swap.asset,this.account),o=await(i==null?void 0:i.token()),a=st.num.toHex(o),c=await Yw(this.account.address,a,r.asset,this.starknetProvider,BigInt(r.amount));return c.error?b.Err(c.error):c.val?this.initiateRelay(e):this.approveAndInitiate(a,e)}catch(i){return b.Err(String(i))}}async approveAndInitiate(e,r){const{source_swap:n}=r,{redeemer:s,amount:i}=n,{secret_hash:o,timelock:a}=n,c=n.asset;try{const l=st.cairo.uint256(BigInt(i)),u={contractAddress:b.with0x(e),entrypoint:"approve",calldata:[c,l.low,l.high]},f=st.cairo.uint256(i),h={contractAddress:b.with0x(c),entrypoint:"initiate",calldata:[s,a.toString(),f.low.toString(),f.high.toString(),...b.hexToU32Array(o)]},d=await this.account.execute([u,h]);return await this.starknetProvider.waitForTransaction(d.transaction_hash,{retryInterval:2e3,successStates:[st.TransactionExecutionStatus.SUCCEEDED]}),b.Ok(d.transaction_hash)}catch(l){return b.Err(`Failed to approve and initiate: ${String(l)}`)}}async initiateRelay(e){const{source_swap:r}=e,{redeemer:n,amount:s}=r;if(!r.secret_hash)return b.Err("Invalid order: secret_hash is undefined");const i=b.with0x(r.secret_hash),a={domain:{name:"HTLC",version:st.shortString.encodeShortString("1"),chainId:this.chainId,revision:st.TypedDataRevision.ACTIVE},primaryType:"Initiate",types:IP,message:{redeemer:n,amount:st.cairo.uint256(s),timelock:e.source_swap.timelock,secretHash:b.hexToU32Array(i)}};try{const c=await this.account.signMessage(a),l=Yp(c);if(l.error)return b.Err(l.error);const u=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:l.val}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return u.error?b.Err(u.error):u.result?b.Ok(u.result):b.Err("Init: No result found")}catch(c){return b.Err(`Failed to initiate relayer: ${String(c)}`)}}async redeem(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return b.Err(n.error);const s=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:b.trim0x(r)}),headers:{...n.val,"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return s.error?b.Err(s.error):s.result?b.Ok(s.result):b.Err("Redeem: No result found")}catch(n){return b.Err(String(n))}}async executeApprovalTransaction(e){if(!this.account.address)return b.Err("No account address");if(!e.approval_transaction)return b.Ok("No approval transaction required");try{const r=e.approval_transaction,n=await this.account.execute([{contractAddress:b.with0x(r.to),entrypoint:b.with0x(r.selector),calldata:r.calldata}]);return await this.starknetProvider.waitForTransaction(n.transaction_hash,{retryInterval:2e3,successStates:[st.TransactionExecutionStatus.SUCCEEDED]}),b.Ok(n.transaction_hash)}catch(r){return console.error("executeApprovalTransaction error:",r),b.Err("Failed to execute approval: "+((r==null?void 0:r.message)||String(r)))}}async initiateWithCreateOrderResponse(e){const r=await this.auth.getAuthHeaders();if(!r.ok)return b.Err(r.error);if(!this.account.address)return b.Err("No account address");const n=await this.executeApprovalTransaction(e);if(n.error)return b.Err(n.error);const{typed_data:s}=e,i=await this.account.signMessage(s),o=Yp(i);if(o.error)return b.Err(o.error);const a=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:Array.isArray(o.val)?o.val.join(","):o.val}),headers:{...r.val,"Content-Type":"application/json"}});return a.error?b.Err(a.error):b.Ok(a.result)}async refund(){return b.Err("Refund is taken care of by the relayer")}}const PP="2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC",OP={name:"solana_spl_swaps",version:"0.4.0",spec:"0.1.0",description:"Created with Anchor"},BP=[{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:[]}],CP=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],$P=[{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]}],RP=[{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"}],NP=[{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"}]}}],_y={address:PP,metadata:OP,instructions:BP,accounts:CP,events:$P,errors:RP,types:NP},UP="2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",MP={name:"solana_native_swaps",version:"0.3.0",spec:"0.1.0",description:"Created with Anchor"},FP=[{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:[]}],jP=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],LP=[{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]}],DP=[{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"}],HP=[{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]}}]}}],ad={address:UP,metadata:MP,instructions:FP,accounts:jP,events:LP,errors:DP,types:HP};var bn={},cu={};Object.defineProperty(cu,"__esModule",{value:!0});cu.encode=zP;cu.decode=VP;const Ty=Js;function zP(t){return t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),"0x")}function VP(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?Ty.Buffer.from([]):Ty.Buffer.from(e.map(r=>parseInt(r,16)))}var uu={},Vs={},rl;Object.defineProperty(Vs,"__esModule",{value:!0});Vs.isVersionedTransaction=Vs.isBrowser=void 0;Vs.chunks=qP;Vs.isBrowser=process.env.ANCHOR_BROWSER||typeof window<"u"&&!(!((rl=window.process)===null||rl===void 0)&&rl.hasOwnProperty("type"));function qP(t,e){return Array.apply(0,new Array(Math.ceil(t.length/e))).map((r,n)=>t.slice(n*e,(n+1)*e))}const GP=t=>"version"in t;Vs.isVersionedTransaction=GP;var nl={},sl={},il,Iy;function e1(){return Iy||(Iy=1,il=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}),il}var ol,Py;function lu(){if(Py)return ol;Py=1;var t=e1();return ol=function(){return t()&&!!Symbol.toStringTag},ol}var al,Oy;function t1(){return Oy||(Oy=1,al=Object),al}var cl,By;function WP(){return By||(By=1,cl=Error),cl}var ul,Cy;function KP(){return Cy||(Cy=1,ul=EvalError),ul}var ll,$y;function ZP(){return $y||($y=1,ll=RangeError),ll}var fl,Ry;function XP(){return Ry||(Ry=1,fl=ReferenceError),fl}var dl,Ny;function r1(){return Ny||(Ny=1,dl=SyntaxError),dl}var hl,Uy;function xa(){return Uy||(Uy=1,hl=TypeError),hl}var pl,My;function YP(){return My||(My=1,pl=URIError),pl}var yl,Fy;function JP(){return Fy||(Fy=1,yl=Math.abs),yl}var ml,jy;function QP(){return jy||(jy=1,ml=Math.floor),ml}var gl,Ly;function e5(){return Ly||(Ly=1,gl=Math.max),gl}var bl,Dy;function t5(){return Dy||(Dy=1,bl=Math.min),bl}var wl,Hy;function r5(){return Hy||(Hy=1,wl=Math.pow),wl}var vl,zy;function n5(){return zy||(zy=1,vl=Math.round),vl}var El,Vy;function s5(){return Vy||(Vy=1,El=Number.isNaN||function(e){return e!==e}),El}var Sl,qy;function i5(){if(qy)return Sl;qy=1;var t=s5();return Sl=function(r){return t(r)||r===0?r:r<0?-1:1},Sl}var Al,Gy;function o5(){return Gy||(Gy=1,Al=Object.getOwnPropertyDescriptor),Al}var xl,Wy;function Ki(){if(Wy)return xl;Wy=1;var t=o5();if(t)try{t([],"length")}catch{t=null}return xl=t,xl}var kl,Ky;function fu(){if(Ky)return kl;Ky=1;var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch{t=!1}return kl=t,kl}var _l,Zy;function a5(){if(Zy)return _l;Zy=1;var t=typeof Symbol<"u"&&Symbol,e=e1();return _l=function(){return typeof t!="function"||typeof Symbol!="function"||typeof t("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},_l}var Tl,Xy;function n1(){return Xy||(Xy=1,Tl=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),Tl}var Il,Yy;function s1(){if(Yy)return Il;Yy=1;var t=t1();return Il=t.getPrototypeOf||null,Il}var Pl,Jy;function c5(){if(Jy)return Pl;Jy=1;var t="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,r=Math.max,n="[object Function]",s=function(c,l){for(var u=[],f=0;f<c.length;f+=1)u[f]=c[f];for(var h=0;h<l.length;h+=1)u[h+c.length]=l[h];return u},i=function(c,l){for(var u=[],f=l,h=0;f<c.length;f+=1,h+=1)u[h]=c[f];return u},o=function(a,c){for(var l="",u=0;u<a.length;u+=1)l+=a[u],u+1<a.length&&(l+=c);return l};return Pl=function(c){var l=this;if(typeof l!="function"||e.apply(l)!==n)throw new TypeError(t+l);for(var u=i(arguments,1),f,h=function(){if(this instanceof f){var S=l.apply(this,s(u,arguments));return Object(S)===S?S:this}return l.apply(c,s(u,arguments))},d=r(0,l.length-u.length),m=[],g=0;g<d;g++)m[g]="$"+g;if(f=Function("binder","return function ("+o(m,",")+"){ return binder.apply(this,arguments); }")(h),l.prototype){var v=function(){};v.prototype=l.prototype,f.prototype=new v,v.prototype=null}return f},Pl}var Ol,Qy;function ka(){if(Qy)return Ol;Qy=1;var t=c5();return Ol=Function.prototype.bind||t,Ol}var Bl,em;function Th(){return em||(em=1,Bl=Function.prototype.call),Bl}var Cl,tm;function Ih(){return tm||(tm=1,Cl=Function.prototype.apply),Cl}var $l,rm;function u5(){return rm||(rm=1,$l=typeof Reflect<"u"&&Reflect&&Reflect.apply),$l}var Rl,nm;function i1(){if(nm)return Rl;nm=1;var t=ka(),e=Ih(),r=Th(),n=u5();return Rl=n||t.call(r,e),Rl}var Nl,sm;function Ph(){if(sm)return Nl;sm=1;var t=ka(),e=xa(),r=Th(),n=i1();return Nl=function(i){if(i.length<1||typeof i[0]!="function")throw new e("a function is required");return n(t,r,i)},Nl}var Ul,im;function l5(){if(im)return Ul;im=1;var t=Ph(),e=Ki(),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 Ul=n&&typeof n.get=="function"?t([n.get]):typeof i=="function"?function(a){return i(a==null?a:s(a))}:!1,Ul}var Ml,om;function Oh(){if(om)return Ml;om=1;var t=n1(),e=s1(),r=l5();return Ml=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,Ml}var Fl,am;function o1(){if(am)return Fl;am=1;var t=Function.prototype.call,e=Object.prototype.hasOwnProperty,r=ka();return Fl=r.call(t,e),Fl}var jl,cm;function a1(){if(cm)return jl;cm=1;var t,e=t1(),r=WP(),n=KP(),s=ZP(),i=XP(),o=r1(),a=xa(),c=YP(),l=JP(),u=QP(),f=e5(),h=t5(),d=r5(),m=n5(),g=i5(),v=Function,S=function(se){try{return v('"use strict"; return ('+se+").constructor;")()}catch{}},_=Ki(),E=fu(),x=function(){throw new a},O=_?function(){try{return arguments.callee,x}catch{try{return _(arguments,"callee").get}catch{return x}}}():x,P=a5()(),$=Oh(),z=s1(),C=n1(),Y=Ih(),W=Th(),K={},U=typeof Uint8Array>"u"||!$?t:$(Uint8Array),N={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?t:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?t:ArrayBuffer,"%ArrayIteratorPrototype%":P&&$?$([][Symbol.iterator]()):t,"%AsyncFromSyncIteratorPrototype%":t,"%AsyncFunction%":K,"%AsyncGenerator%":K,"%AsyncGeneratorFunction%":K,"%AsyncIteratorPrototype%":K,"%Atomics%":typeof Atomics>"u"?t:Atomics,"%BigInt%":typeof BigInt>"u"?t:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?t:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?t:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?t:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":typeof Float16Array>"u"?t:Float16Array,"%Float32Array%":typeof Float32Array>"u"?t:Float32Array,"%Float64Array%":typeof Float64Array>"u"?t:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?t:FinalizationRegistry,"%Function%":v,"%GeneratorFunction%":K,"%Int8Array%":typeof Int8Array>"u"?t:Int8Array,"%Int16Array%":typeof Int16Array>"u"?t:Int16Array,"%Int32Array%":typeof Int32Array>"u"?t:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":P&&$?$($([][Symbol.iterator]())):t,"%JSON%":typeof JSON=="object"?JSON:t,"%Map%":typeof Map>"u"?t:Map,"%MapIteratorPrototype%":typeof Map>"u"||!P||!$?t:$(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":e,"%Object.getOwnPropertyDescriptor%":_,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?t:Promise,"%Proxy%":typeof Proxy>"u"?t:Proxy,"%RangeError%":s,"%ReferenceError%":i,"%Reflect%":typeof Reflect>"u"?t:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?t:Set,"%SetIteratorPrototype%":typeof Set>"u"||!P||!$?t:$(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?t:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":P&&$?$(""[Symbol.iterator]()):t,"%Symbol%":P?Symbol:t,"%SyntaxError%":o,"%ThrowTypeError%":O,"%TypedArray%":U,"%TypeError%":a,"%Uint8Array%":typeof Uint8Array>"u"?t:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?t:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?t:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?t:Uint32Array,"%URIError%":c,"%WeakMap%":typeof WeakMap>"u"?t:WeakMap,"%WeakRef%":typeof WeakRef>"u"?t:WeakRef,"%WeakSet%":typeof WeakSet>"u"?t:WeakSet,"%Function.prototype.call%":W,"%Function.prototype.apply%":Y,"%Object.defineProperty%":E,"%Object.getPrototypeOf%":z,"%Math.abs%":l,"%Math.floor%":u,"%Math.max%":f,"%Math.min%":h,"%Math.pow%":d,"%Math.round%":m,"%Math.sign%":g,"%Reflect.getPrototypeOf%":C};if($)try{null.error}catch(se){var F=$($(se));N["%Error.prototype%"]=F}var Z=function se(ie){var me;if(ie==="%AsyncFunction%")me=S("async function () {}");else if(ie==="%GeneratorFunction%")me=S("function* () {}");else if(ie==="%AsyncGeneratorFunction%")me=S("async function* () {}");else if(ie==="%AsyncGenerator%"){var be=se("%AsyncGeneratorFunction%");be&&(me=be.prototype)}else if(ie==="%AsyncIteratorPrototype%"){var Ee=se("%AsyncGenerator%");Ee&&$&&(me=$(Ee.prototype))}return N[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"]},D=ka(),T=o1(),L=D.call(W,Array.prototype.concat),G=D.call(Y,Array.prototype.splice),I=D.call(W,String.prototype.replace),R=D.call(W,String.prototype.slice),j=D.call(W,RegExp.prototype.exec),J=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,ne=/\\(\\)?/g,ue=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 Ee=[];return I(ie,J,function(Ue,Dt,et,$r){Ee[Ee.length]=et?I($r,ne,"$1"):Dt||Ue}),Ee},ce=function(ie,me){var be=ie,Ee;if(T(ee,be)&&(Ee=ee[be],be="%"+Ee[0]+"%"),T(N,be)){var Ue=N[be];if(Ue===K&&(Ue=Z(be)),typeof Ue>"u"&&!me)throw new a("intrinsic "+ie+" exists, but is not available. Please file an issue!");return{alias:Ee,name:be,value:Ue}}throw new o("intrinsic "+ie+" does not exist!")};return jl=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(j(/^%?[^%]*%?$/,ie)===null)throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var be=ue(ie),Ee=be.length>0?be[0]:"",Ue=ce("%"+Ee+"%",me),Dt=Ue.name,et=Ue.value,$r=!1,us=Ue.alias;us&&(Ee=us[0],G(be,L([0,1],us)));for(var q=1,Rr=!0;q<be.length;q+=1){var Et=be[q],St=R(Et,0,1),Cn=R(Et,-1);if((St==='"'||St==="'"||St==="`"||Cn==='"'||Cn==="'"||Cn==="`")&&St!==Cn)throw new o("property names with quotes must have matching quotes");if((Et==="constructor"||!Rr)&&($r=!0),Ee+="."+Et,Dt="%"+Ee+"%",T(N,Dt))et=N[Dt];else if(et!=null){if(!(Et in et)){if(!me)throw new a("base intrinsic for "+ie+" exists, but the property is not available.");return}if(_&&q+1>=be.length){var ri=_(et,Et);Rr=!!ri,Rr&&"get"in ri&&!("originalValue"in ri.get)?et=ri.get:et=et[Et]}else Rr=T(et,Et),et=et[Et];Rr&&!$r&&(N[Dt]=et)}}return et},jl}var Ll,um;function _a(){if(um)return Ll;um=1;var t=a1(),e=Ph(),r=e([t("%String.prototype.indexOf%")]);return Ll=function(s,i){var o=t(s,!!i);return typeof o=="function"&&r(s,".prototype.")>-1?e([o]):o},Ll}var Dl,lm;function f5(){if(lm)return Dl;lm=1;var t=lu()(),e=_a(),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,Dl=i?n:s,Dl}var Hl,fm;function d5(){if(fm)return Hl;fm=1;var t=_a(),e=lu()(),r=o1(),n=Ki(),s;if(e){var i=t("RegExp.prototype.exec"),o={},a=function(){throw o},c={toString:a,valueOf:a};typeof Symbol.toPrimitive=="symbol"&&(c[Symbol.toPrimitive]=a),s=function(h){if(!h||typeof h!="object")return!1;var d=n(h,"lastIndex"),m=d&&r(d,"value");if(!m)return!1;try{i(h,c)}catch(g){return g===o}}}else{var l=t("Object.prototype.toString"),u="[object RegExp]";s=function(h){return!h||typeof h!="object"&&typeof h!="function"?!1:l(h)===u}}return Hl=s,Hl}var zl,dm;function h5(){if(dm)return zl;dm=1;var t=_a(),e=d5(),r=t("RegExp.prototype.exec"),n=xa();return zl=function(i){if(!e(i))throw new n("`regex` must be a RegExp");return function(a){return r(i,a)!==null}},zl}var Vl,hm;function p5(){if(hm)return Vl;hm=1;var t=_a(),e=h5(),r=e(/^\s*(?:function)?\*/),n=lu()(),s=Oh(),i=t("Object.prototype.toString"),o=t("Function.prototype.toString"),a=function(){if(!n)return!1;try{return Function("return function*() {}")()}catch{}},c;return Vl=function(u){if(typeof u!="function")return!1;if(r(o(u)))return!0;if(!n){var f=i(u);return f==="[object GeneratorFunction]"}if(!s)return!1;if(typeof c>"u"){var h=a();c=h?s(h):!1}return s(u)===c},Vl}var ql,pm;function y5(){if(pm)return ql;pm=1;var t=Function.prototype.toString,e=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,r,n;if(typeof e=="function"&&typeof Object.defineProperty=="function")try{r=Object.defineProperty({},"length",{get:function(){throw n}}),n={},e(function(){throw 42},null,r)}catch(_){_!==n&&(e=null)}else e=null;var s=/^\s*class\b/,i=function(E){try{var x=t.call(E);return s.test(x)}catch{return!1}},o=function(E){try{return i(E)?!1:(t.call(E),!0)}catch{return!1}},a=Object.prototype.toString,c="[object Object]",l="[object Function]",u="[object GeneratorFunction]",f="[object HTMLAllCollection]",h="[object HTML document.all class]",d="[object HTMLCollection]",m=typeof Symbol=="function"&&!!Symbol.toStringTag,g=!(0 in[,]),v=function(){return!1};if(typeof document=="object"){var S=document.all;a.call(S)===a.call(document.all)&&(v=function(E){if((g||!E)&&(typeof E>"u"||typeof E=="object"))try{var x=a.call(E);return(x===f||x===h||x===d||x===c)&&E("")==null}catch{}return!1})}return ql=e?function(E){if(v(E))return!0;if(!E||typeof E!="function"&&typeof E!="object")return!1;try{e(E,null,r)}catch(x){if(x!==n)return!1}return!i(E)&&o(E)}:function(E){if(v(E))return!0;if(!E||typeof E!="function"&&typeof E!="object")return!1;if(m)return o(E);if(i(E))return!1;var x=a.call(E);return x!==l&&x!==u&&!/^\[object HTML/.test(x)?!1:o(E)},ql}var Gl,ym;function m5(){if(ym)return Gl;ym=1;var t=y5(),e=Object.prototype.toString,r=Object.prototype.hasOwnProperty,n=function(c,l,u){for(var f=0,h=c.length;f<h;f++)r.call(c,f)&&(u==null?l(c[f],f,c):l.call(u,c[f],f,c))},s=function(c,l,u){for(var f=0,h=c.length;f<h;f++)u==null?l(c.charAt(f),f,c):l.call(u,c.charAt(f),f,c)},i=function(c,l,u){for(var f in c)r.call(c,f)&&(u==null?l(c[f],f,c):l.call(u,c[f],f,c))};function o(a){return e.call(a)==="[object Array]"}return Gl=function(c,l,u){if(!t(l))throw new TypeError("iterator must be a function");var f;arguments.length>=3&&(f=u),o(c)?n(c,l,f):typeof c=="string"?s(c,l,f):i(c,l,f)},Gl}var Wl,mm;function g5(){return mm||(mm=1,Wl=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),Wl}var Kl,gm;function b5(){if(gm)return Kl;gm=1;var t=g5(),e=typeof globalThis>"u"?Jr:globalThis;return Kl=function(){for(var n=[],s=0;s<t.length;s++)typeof e[t[s]]=="function"&&(n[n.length]=t[s]);return n},Kl}var Zl={exports:{}},Xl,bm;function w5(){if(bm)return Xl;bm=1;var t=fu(),e=r1(),r=xa(),n=Ki();return Xl=function(i,o,a){if(!i||typeof i!="object"&&typeof i!="function")throw new r("`obj` must be an object or a function`");if(typeof o!="string"&&typeof o!="symbol")throw new r("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new r("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new r("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new r("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new r("`loose`, if provided, must be a boolean");var c=arguments.length>3?arguments[3]:null,l=arguments.length>4?arguments[4]:null,u=arguments.length>5?arguments[5]:null,f=arguments.length>6?arguments[6]:!1,h=!!n&&n(i,o);if(t)t(i,o,{configurable:u===null&&h?h.configurable:!u,enumerable:c===null&&h?h.enumerable:!c,value:a,writable:l===null&&h?h.writable:!l});else if(f||!c&&!l&&!u)i[o]=a;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Xl}var Yl,wm;function v5(){if(wm)return Yl;wm=1;var t=fu(),e=function(){return!!t};return e.hasArrayLengthDefineBug=function(){if(!t)return null;try{return t([],"length",{value:1}).length!==1}catch{return!0}},Yl=e,Yl}var Jl,vm;function E5(){if(vm)return Jl;vm=1;var t=a1(),e=w5(),r=v5()(),n=Ki(),s=xa(),i=t("%Math.floor%");return Jl=function(a,c){if(typeof a!="function")throw new s("`fn` is not a function");if(typeof c!="number"||c<0||c>4294967295||i(c)!==c)throw new s("`length` must be a positive 32-bit integer");var l=arguments.length>2&&!!arguments[2],u=!0,f=!0;if("length"in a&&n){var h=n(a,"length");h&&!h.configurable&&(u=!1),h&&!h.writable&&(f=!1)}return(u||f||!l)&&(r?e(a,"length",c,!0,!0):e(a,"length",c)),a},Jl}var Ql,Em;function S5(){if(Em)return Ql;Em=1;var t=ka(),e=Ih(),r=i1();return Ql=function(){return r(t,e,arguments)},Ql}var Sm;function A5(){return Sm||(Sm=1,function(t){var e=E5(),r=fu(),n=Ph(),s=S5();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}(Zl)),Zl.exports}var ef,Am;function c1(){if(Am)return ef;Am=1;var t=m5(),e=b5(),r=A5(),n=_a(),s=Ki(),i=Oh(),o=n("Object.prototype.toString"),a=lu()(),c=typeof globalThis>"u"?Jr:globalThis,l=e(),u=n("String.prototype.slice"),f=n("Array.prototype.indexOf",!0)||function(v,S){for(var _=0;_<v.length;_+=1)if(v[_]===S)return _;return-1},h={__proto__:null};a&&s&&i?t(l,function(g){var v=new c[g];if(Symbol.toStringTag in v&&i){var S=i(v),_=s(S,Symbol.toStringTag);if(!_&&S){var E=i(S);_=s(E,Symbol.toStringTag)}h["$"+g]=r(_.get)}}):t(l,function(g){var v=new c[g],S=v.slice||v.set;S&&(h["$"+g]=r(S))});var d=function(v){var S=!1;return t(h,function(_,E){if(!S)try{"$"+_(v)===E&&(S=u(E,1))}catch{}}),S},m=function(v){var S=!1;return t(h,function(_,E){if(!S)try{_(v),S=u(E,1)}catch{}}),S};return ef=function(v){if(!v||typeof v!="object")return!1;if(!a){var S=u(o(v),8,-1);return f(l,S)>-1?S:S!=="Object"?!1:m(v)}return s?d(v):null},ef}var tf,xm;function x5(){if(xm)return tf;xm=1;var t=c1();return tf=function(r){return!!t(r)},tf}var km;function k5(){return km||(km=1,function(t){var e=f5(),r=p5(),n=c1(),s=x5();function i(q){return q.call.bind(q)}var o=typeof BigInt<"u",a=typeof Symbol<"u",c=i(Object.prototype.toString),l=i(Number.prototype.valueOf),u=i(String.prototype.valueOf),f=i(Boolean.prototype.valueOf);if(o)var h=i(BigInt.prototype.valueOf);if(a)var d=i(Symbol.prototype.valueOf);function m(q,Rr){if(typeof q!="object")return!1;try{return Rr(q),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=r,t.isTypedArray=s;function g(q){return typeof Promise<"u"&&q instanceof Promise||q!==null&&typeof q=="object"&&typeof q.then=="function"&&typeof q.catch=="function"}t.isPromise=g;function v(q){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(q):s(q)||R(q)}t.isArrayBufferView=v;function S(q){return n(q)==="Uint8Array"}t.isUint8Array=S;function _(q){return n(q)==="Uint8ClampedArray"}t.isUint8ClampedArray=_;function E(q){return n(q)==="Uint16Array"}t.isUint16Array=E;function x(q){return n(q)==="Uint32Array"}t.isUint32Array=x;function O(q){return n(q)==="Int8Array"}t.isInt8Array=O;function P(q){return n(q)==="Int16Array"}t.isInt16Array=P;function $(q){return n(q)==="Int32Array"}t.isInt32Array=$;function z(q){return n(q)==="Float32Array"}t.isFloat32Array=z;function C(q){return n(q)==="Float64Array"}t.isFloat64Array=C;function Y(q){return n(q)==="BigInt64Array"}t.isBigInt64Array=Y;function W(q){return n(q)==="BigUint64Array"}t.isBigUint64Array=W;function K(q){return c(q)==="[object Map]"}K.working=typeof Map<"u"&&K(new Map);function U(q){return typeof Map>"u"?!1:K.working?K(q):q instanceof Map}t.isMap=U;function N(q){return c(q)==="[object Set]"}N.working=typeof Set<"u"&&N(new Set);function F(q){return typeof Set>"u"?!1:N.working?N(q):q instanceof Set}t.isSet=F;function Z(q){return c(q)==="[object WeakMap]"}Z.working=typeof WeakMap<"u"&&Z(new WeakMap);function ee(q){return typeof WeakMap>"u"?!1:Z.working?Z(q):q instanceof WeakMap}t.isWeakMap=ee;function D(q){return c(q)==="[object WeakSet]"}D.working=typeof WeakSet<"u"&&D(new WeakSet);function T(q){return D(q)}t.isWeakSet=T;function L(q){return c(q)==="[object ArrayBuffer]"}L.working=typeof ArrayBuffer<"u"&&L(new ArrayBuffer);function G(q){return typeof ArrayBuffer>"u"?!1:L.working?L(q):q instanceof ArrayBuffer}t.isArrayBuffer=G;function I(q){return c(q)==="[object DataView]"}I.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&I(new DataView(new ArrayBuffer(1),0,1));function R(q){return typeof DataView>"u"?!1:I.working?I(q):q instanceof DataView}t.isDataView=R;var j=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function J(q){return c(q)==="[object SharedArrayBuffer]"}function ne(q){return typeof j>"u"?!1:(typeof J.working>"u"&&(J.working=J(new j)),J.working?J(q):q instanceof j)}t.isSharedArrayBuffer=ne;function ue(q){return c(q)==="[object AsyncFunction]"}t.isAsyncFunction=ue;function ce(q){return c(q)==="[object Map Iterator]"}t.isMapIterator=ce;function se(q){return c(q)==="[object Set Iterator]"}t.isSetIterator=se;function ie(q){return c(q)==="[object Generator]"}t.isGeneratorObject=ie;function me(q){return c(q)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=me;function be(q){return m(q,l)}t.isNumberObject=be;function Ee(q){return m(q,u)}t.isStringObject=Ee;function Ue(q){return m(q,f)}t.isBooleanObject=Ue;function Dt(q){return o&&m(q,h)}t.isBigIntObject=Dt;function et(q){return a&&m(q,d)}t.isSymbolObject=et;function $r(q){return be(q)||Ee(q)||Ue(q)||Dt(q)||et(q)}t.isBoxedPrimitive=$r;function us(q){return typeof Uint8Array<"u"&&(G(q)||ne(q))}t.isAnyArrayBuffer=us,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(q){Object.defineProperty(t,q,{enumerable:!1,value:function(){throw new Error(q+" is not supported in userland")}})})}(sl)),sl}var rf,_m;function _5(){return _m||(_m=1,rf=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"}),rf}var Wa={exports:{}},Tm;function T5(){return Tm||(Tm=1,typeof Object.create=="function"?Wa.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Wa.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}),Wa.exports}var Im;function u1(){return Im||(Im=1,function(t){var e=Object.getOwnPropertyDescriptors||function(R){for(var j=Object.keys(R),J={},ne=0;ne<j.length;ne++)J[j[ne]]=Object.getOwnPropertyDescriptor(R,j[ne]);return J},r=/%[sdj%]/g;t.format=function(I){if(!O(I)){for(var R=[],j=0;j<arguments.length;j++)R.push(o(arguments[j]));return R.join(" ")}for(var j=1,J=arguments,ne=J.length,ue=String(I).replace(r,function(se){if(se==="%%")return"%";if(j>=ne)return se;switch(se){case"%s":return String(J[j++]);case"%d":return Number(J[j++]);case"%j":try{return JSON.stringify(J[j++])}catch{return"[Circular]"}default:return se}}),ce=J[j];j<ne;ce=J[++j])_(ce)||!C(ce)?ue+=" "+ce:ue+=" "+o(ce);return ue},t.deprecate=function(I,R){if(typeof process<"u"&&process.noDeprecation===!0)return I;if(typeof process>"u")return function(){return t.deprecate(I,R).apply(this,arguments)};var j=!1;function J(){if(!j){if(process.throwDeprecation)throw new Error(R);process.traceDeprecation?console.trace(R):console.error(R),j=!0}return I.apply(this,arguments)}return J};var n={},s=/^$/;if(process.env.NODE_DEBUG){var i=process.env.NODE_DEBUG;i=i.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),s=new RegExp("^"+i+"$","i")}t.debuglog=function(I){if(I=I.toUpperCase(),!n[I])if(s.test(I)){var R=process.pid;n[I]=function(){var j=t.format.apply(t,arguments);console.error("%s %d: %s",I,R,j)}}else n[I]=function(){};return n[I]};function o(I,R){var j={seen:[],stylize:c};return arguments.length>=3&&(j.depth=arguments[2]),arguments.length>=4&&(j.colors=arguments[3]),S(R)?j.showHidden=R:R&&t._extend(j,R),$(j.showHidden)&&(j.showHidden=!1),$(j.depth)&&(j.depth=2),$(j.colors)&&(j.colors=!1),$(j.customInspect)&&(j.customInspect=!0),j.colors&&(j.stylize=a),u(j,I,j.depth)}t.inspect=o,o.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},o.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function a(I,R){var j=o.styles[R];return j?"\x1B["+o.colors[j][0]+"m"+I+"\x1B["+o.colors[j][1]+"m":I}function c(I,R){return I}function l(I){var R={};return I.forEach(function(j,J){R[j]=!0}),R}function u(I,R,j){if(I.customInspect&&R&&K(R.inspect)&&R.inspect!==t.inspect&&!(R.constructor&&R.constructor.prototype===R)){var J=R.inspect(j,I);return O(J)||(J=u(I,J,j)),J}var ne=f(I,R);if(ne)return ne;var ue=Object.keys(R),ce=l(ue);if(I.showHidden&&(ue=Object.getOwnPropertyNames(R)),W(R)&&(ue.indexOf("message")>=0||ue.indexOf("description")>=0))return h(R);if(ue.length===0){if(K(R)){var se=R.name?": "+R.name:"";return I.stylize("[Function"+se+"]","special")}if(z(R))return I.stylize(RegExp.prototype.toString.call(R),"regexp");if(Y(R))return I.stylize(Date.prototype.toString.call(R),"date");if(W(R))return h(R)}var ie="",me=!1,be=["{","}"];if(v(R)&&(me=!0,be=["[","]"]),K(R)){var Ee=R.name?": "+R.name:"";ie=" [Function"+Ee+"]"}if(z(R)&&(ie=" "+RegExp.prototype.toString.call(R)),Y(R)&&(ie=" "+Date.prototype.toUTCString.call(R)),W(R)&&(ie=" "+h(R)),ue.length===0&&(!me||R.length==0))return be[0]+ie+be[1];if(j<0)return z(R)?I.stylize(RegExp.prototype.toString.call(R),"regexp"):I.stylize("[Object]","special");I.seen.push(R);var Ue;return me?Ue=d(I,R,j,ce,ue):Ue=ue.map(function(Dt){return m(I,R,j,ce,Dt,me)}),I.seen.pop(),g(Ue,ie,be)}function f(I,R){if($(R))return I.stylize("undefined","undefined");if(O(R)){var j="'"+JSON.stringify(R).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return I.stylize(j,"string")}if(x(R))return I.stylize(""+R,"number");if(S(R))return I.stylize(""+R,"boolean");if(_(R))return I.stylize("null","null")}function h(I){return"["+Error.prototype.toString.call(I)+"]"}function d(I,R,j,J,ne){for(var ue=[],ce=0,se=R.length;ce<se;++ce)D(R,String(ce))?ue.push(m(I,R,j,J,String(ce),!0)):ue.push("");return ne.forEach(function(ie){ie.match(/^\d+$/)||ue.push(m(I,R,j,J,ie,!0))}),ue}function m(I,R,j,J,ne,ue){var ce,se,ie;if(ie=Object.getOwnPropertyDescriptor(R,ne)||{value:R[ne]},ie.get?ie.set?se=I.stylize("[Getter/Setter]","special"):se=I.stylize("[Getter]","special"):ie.set&&(se=I.stylize("[Setter]","special")),D(J,ne)||(ce="["+ne+"]"),se||(I.seen.indexOf(ie.value)<0?(_(j)?se=u(I,ie.value,null):se=u(I,ie.value,j-1),se.indexOf(`
74
- `)>-1&&(ue?se=se.split(`
75
- `).map(function(me){return" "+me}).join(`
76
- `).slice(2):se=`
77
- `+se.split(`
78
- `).map(function(me){return" "+me}).join(`
79
- `))):se=I.stylize("[Circular]","special")),$(ce)){if(ue&&ne.match(/^\d+$/))return se;ce=JSON.stringify(""+ne),ce.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(ce=ce.slice(1,-1),ce=I.stylize(ce,"name")):(ce=ce.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),ce=I.stylize(ce,"string"))}return ce+": "+se}function g(I,R,j){var J=I.reduce(function(ne,ue){return ue.indexOf(`
80
- `)>=0,ne+ue.replace(/\u001b\[\d\d?m/g,"").length+1},0);return J>60?j[0]+(R===""?"":R+`
81
- `)+" "+I.join(`,
82
- `)+" "+j[1]:j[0]+R+" "+I.join(", ")+" "+j[1]}t.types=k5();function v(I){return Array.isArray(I)}t.isArray=v;function S(I){return typeof I=="boolean"}t.isBoolean=S;function _(I){return I===null}t.isNull=_;function E(I){return I==null}t.isNullOrUndefined=E;function x(I){return typeof I=="number"}t.isNumber=x;function O(I){return typeof I=="string"}t.isString=O;function P(I){return typeof I=="symbol"}t.isSymbol=P;function $(I){return I===void 0}t.isUndefined=$;function z(I){return C(I)&&N(I)==="[object RegExp]"}t.isRegExp=z,t.types.isRegExp=z;function C(I){return typeof I=="object"&&I!==null}t.isObject=C;function Y(I){return C(I)&&N(I)==="[object Date]"}t.isDate=Y,t.types.isDate=Y;function W(I){return C(I)&&(N(I)==="[object Error]"||I instanceof Error)}t.isError=W,t.types.isNativeError=W;function K(I){return typeof I=="function"}t.isFunction=K;function U(I){return I===null||typeof I=="boolean"||typeof I=="number"||typeof I=="string"||typeof I=="symbol"||typeof I>"u"}t.isPrimitive=U,t.isBuffer=_5();function N(I){return Object.prototype.toString.call(I)}function F(I){return I<10?"0"+I.toString(10):I.toString(10)}var Z=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ee(){var I=new Date,R=[F(I.getHours()),F(I.getMinutes()),F(I.getSeconds())].join(":");return[I.getDate(),Z[I.getMonth()],R].join(" ")}t.log=function(){console.log("%s - %s",ee(),t.format.apply(t,arguments))},t.inherits=T5(),t._extend=function(I,R){if(!R||!C(R))return I;for(var j=Object.keys(R),J=j.length;J--;)I[j[J]]=R[j[J]];return I};function D(I,R){return Object.prototype.hasOwnProperty.call(I,R)}var T=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;t.promisify=function(R){if(typeof R!="function")throw new TypeError('The "original" argument must be of type Function');if(T&&R[T]){var j=R[T];if(typeof j!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(j,T,{value:j,enumerable:!1,writable:!1,configurable:!0}),j}function j(){for(var J,ne,ue=new Promise(function(ie,me){J=ie,ne=me}),ce=[],se=0;se<arguments.length;se++)ce.push(arguments[se]);ce.push(function(ie,me){ie?ne(ie):J(me)});try{R.apply(this,ce)}catch(ie){ne(ie)}return ue}return Object.setPrototypeOf(j,Object.getPrototypeOf(R)),T&&Object.defineProperty(j,T,{value:j,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(j,e(R))},t.promisify.custom=T;function L(I,R){if(!I){var j=new Error("Promise was rejected with a falsy value");j.reason=I,I=j}return R(I)}function G(I){if(typeof I!="function")throw new TypeError('The "original" argument must be of type Function');function R(){for(var j=[],J=0;J<arguments.length;J++)j.push(arguments[J]);var ne=j.pop();if(typeof ne!="function")throw new TypeError("The last argument must be of type Function");var ue=this,ce=function(){return ne.apply(ue,arguments)};I.apply(this,j).then(function(se){process.nextTick(ce.bind(null,null,se))},function(se){process.nextTick(L.bind(null,se,ce))})}return Object.setPrototypeOf(R,Object.getPrototypeOf(I)),Object.defineProperties(R,e(I)),R}t.callbackify=G}(nl)),nl}Object.defineProperty(uu,"__esModule",{value:!0});uu.decode=I5;uu.encode=P5;const l1=Vs;function I5(t){return(l1.isBrowser?new TextDecoder("utf-8"):new(u1()).TextDecoder("utf-8")).decode(t)}function P5(t){return(l1.isBrowser?new TextEncoder:new(u1()).TextEncoder("utf-8")).encode(t)}var du={},cd={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(t,e){var r=Js,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 l=n(o);return a!==void 0?typeof c=="string"?l.fill(a,c):l.fill(a):l.fill(0),l},i.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return n(o)},i.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(o)}})(cd,cd.exports);var O5=cd.exports,Ka=O5.Buffer;function B5(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),l=Math.log(256)/Math.log(o);function u(d){if((Array.isArray(d)||d instanceof Uint8Array)&&(d=Ka.from(d)),!Ka.isBuffer(d))throw new TypeError("Expected Buffer");if(d.length===0)return"";for(var m=0,g=0,v=0,S=d.length;v!==S&&d[v]===0;)v++,m++;for(var _=(S-v)*l+1>>>0,E=new Uint8Array(_);v!==S;){for(var x=d[v],O=0,P=_-1;(x!==0||O<g)&&P!==-1;P--,O++)x+=256*E[P]>>>0,E[P]=x%o>>>0,x=x/o>>>0;if(x!==0)throw new Error("Non-zero carry");g=O,v++}for(var $=_-g;$!==_&&E[$]===0;)$++;for(var z=a.repeat(m);$<_;++$)z+=t.charAt(E[$]);return z}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return Ka.alloc(0);for(var m=0,g=0,v=0;d[m]===a;)g++,m++;for(var S=(d.length-m)*c+1>>>0,_=new Uint8Array(S);m<d.length;){var E=d.charCodeAt(m);if(E>255)return;var x=e[E];if(x===255)return;for(var O=0,P=S-1;(x!==0||O<v)&&P!==-1;P--,O++)x+=o*_[P]>>>0,_[P]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");v=O,m++}for(var $=S-v;$!==S&&_[$]===0;)$++;var z=Ka.allocUnsafe(g+(S-$));z.fill(0,0,g);for(var C=g;$!==S;)z[C++]=_[$++];return z}function h(d){var m=f(d);if(m)return m;throw new Error("Non-base"+o+" character")}return{encode:u,decodeUnsafe:f,decode:h}}var C5=B5,$5=C5,R5="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",N5=$5(R5),U5=Jr&&Jr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(du,"__esModule",{value:!0});du.encode=M5;du.decode=F5;const f1=U5(N5);function M5(t){return f1.default.encode(t)}function F5(t){return f1.default.decode(t)}var hu={};Object.defineProperty(hu,"__esModule",{value:!0});hu.encode=L5;hu.decode=D5;const j5=Js;function L5(t){return t.toString("base64")}function D5(t){return j5.Buffer.from(t,"base64")}var H5=Jr&&Jr.__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]}),z5=Jr&&Jr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),pu=Jr&&Jr.__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)&&H5(e,t,r);return z5(e,t),e};Object.defineProperty(bn,"__esModule",{value:!0});bn.base64=bn.bs58=bn.utf8=d1=bn.hex=void 0;var d1=bn.hex=pu(cu);bn.utf8=pu(uu);bn.bs58=pu(du);bn.base64=pu(hu);class Qn{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 ir.web3.PublicKey(r)}catch(o){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:o})}try{this.amount=new ir.BN(s.toString(10),10),this.expiresIn=new ir.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 Qn(n,s,i,a,o)}}function h1(t){let e;try{e=[...d1.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 p1{constructor(e,r,n,s,i){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)throw new Error("Relayer address is required");try{this.relayer=new ir.web3.PublicKey(n),this.orderbook=new oe.Orderbook(r),this.auth=i}catch(c){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:c})}const o=s.spl?{..._y,metadata:{..._y.metadata??{}},address:s.spl}:void 0,a=s.native?{...ad,metadata:{...ad.metadata??{}},address:s.native}:void 0;try{this.splProgram=o?new ir.Program(o,this.provider):void 0,this.nativeProgram=a?new ir.Program(a,this.provider):void 0}catch(c){throw new Error("Error creating Program instances. Ensure the IDLs and provider are correct.",{cause:c})}}get htlcActorAddress(){if(!this.provider.publicKey)throw new Error("No provider public key found");return this.provider.publicKey.toBase58()}async sendSplViaRelayer(e,r){try{e.recentBlockhash=(await this.provider.connection.getLatestBlockhash()).blockhash,e.feePayer=this.relayer;const s=(await this.provider.wallet.signTransaction(e)).serialize({requireAllSignatures:!1}).toString("base64"),i=await b.Fetcher.post(this.url.endpoint("/initiate"),{body:JSON.stringify({order_id:r,serialized_tx:s}),headers:{"Content-Type":"application/json"}});return i.error||!i.result?b.Err(`Error from Relayer: ${i.error}`):await zu(this.provider.connection,i.result)?b.Ok(i.result):b.Err("Relayer: Failed to Initiate swap, confirmation timed out")}catch(n){return b.Err(`Failed to send SPL transaction: ${n instanceof Error?n.message:String(n)}`)}}async initiateViaHTLC(e,r){if(!r)return b.Err("Order is required");try{const n=await this.provider.sendAndConfirm(e);return n?await zu(this.provider.connection,n)?b.Ok(n):b.Err("HTLC: Failed to Initiate swap, confirmation timed out"):b.Err("Failed to initiate HTLC transaction")}catch(n){return b.Err(`Error initiating swap: ${n instanceof Error?n.message:String(n)}`)}}async initiateSplSwap(e){if(!this.splProgram)return b.Err("SPL program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=Qn.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 b.Err(a.error);const{tokenAddress:c}=a.val,l=new ir.web3.PublicKey(c),u={initiator:this.provider.publicKey,mint:l,initiatorTokenAccount:Xv.getAssociatedTokenAddressSync(l,this.provider.publicKey),sponsor:this.relayer},f=await o.accounts(u).transaction();return this.sendSplViaRelayer(f,e.order_id)}catch(r){return b.Err(`Error initiating SPL swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateNativeSwap(e){if(!this.nativeProgram)return b.Err("Native program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=Qn.from(e),o=await this.nativeProgram.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction();return this.initiateViaHTLC(o,e)}catch(r){return b.Err(`Error initiating native swap: ${r instanceof Error?r.message:String(r)}`)}}async initiate(e){if(!e)return b.Err("Order is required");if(oe.isSolanaOrderResponse(e))return this.initiateWithCreateOrderResponse(e);try{const r=oe.ChainAsset.fromString(e.source_swap.asset);return oe.isSolanaNativeToken(r.getChain(),r.getSymbol())?this.nativeProgram?await this.initiateNativeSwap(e):b.Err("Native program is not initialized"):this.splProgram?await this.initiateSplSwap(e):b.Err("SPL program is not initialized")}catch(r){return b.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return b.Err(n.error);const s=h1(r),i=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:Buffer.from(s).toString("hex")}),headers:{...n.val,"Content-Type":"application/json"}});if(i.error||!i.result)return b.Err(`Redeem: Error from relayer: ${i.error}`);const o=i.result;return await zu(this.provider.connection,o)?b.Ok(o):b.Err("Redeem: Timed out waiting for confirmation")}catch(n){return console.error("Redeem: Caught exception:",n),b.Err(`Error redeeming: ${n}`)}}async initiateWithCreateOrderResponse(e){if(!this.relayer)return b.Err("No relayer address");const{versioned_tx:r,order_id:n}=e,s=await this.auth.getAuthHeaders();if(!s.ok)return b.Err(s.error);try{const i=await this.orderbook.getOrder(n);if(i.error||!i.val)return b.Err(`Failed to fetch order by id: ${i.error}`);const o=oe.ChainAsset.fromString(i.val.source_swap.asset);if(oe.isSolanaNativeToken(o.getChain(),o.getSymbol()))return await this.initiateNativeSwap(i.val);const a=ir.web3.VersionedTransaction.deserialize(Buffer.from(r,"base64")),c=await this.provider.wallet.signTransaction(a);if(!c.signatures[0])return b.Err("No signature found after signing transaction");const u=Buffer.from(c.serialize()).toString("base64"),f=await b.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({serialized_tx:u}),headers:{...s.val,"Content-Type":"application/json"}});return f.error?b.Err(`Initiate: Error from relayer: ${f.error}`):f.result?b.Ok(f.result):b.Err("Initiate: No transaction hash returned from relayer")}catch(i){return b.Err(`Error initiating with create order response: ${i}`)}}async refund(){return b.Err("Refund is automatically handled by the relayer.")}}const y1="1.37.4",V5="1.55.0",q5={"-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 m1 extends Error{}class g1 extends m1{constructor(e,r){super(e),this.code=r,this.type=q5[r]??"ServerError"}}class G5 extends m1{constructor(e,r,n){super(e),this.status=r,this.statusText=n}}var b1=t=>{throw TypeError(t)},Bh=(t,e,r)=>e.has(t)||b1("Cannot "+r),Re=(t,e,r)=>(Bh(t,e,"read from private field"),r?r.call(t):e.get(t)),hs=(t,e,r)=>e.has(t)?b1("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),_i=(t,e,r,n)=>(Bh(t,e,"write to private field"),e.set(t,r),r),w1=(t,e,r)=>(Bh(t,e,"access private method"),r),W5=(t,e,r,n)=>({set _(s){_i(t,e,s)},get _(){return Re(t,e,n)}}),Vn,Eo,pn,Ss,Jo,As,vc,v1,E1;function K5(t){const e=new URL(t);return e.protocol=e.protocol.replace("http","ws"),e.toString()}const Z5={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5};class X5{constructor(e,r={}){if(hs(this,vc),hs(this,Vn,0),hs(this,Eo,0),hs(this,pn,null),hs(this,Ss,null),hs(this,Jo,new Set),hs(this,As,new Map),this.endpoint=e,this.options={...Z5,...r},!this.options.WebSocketConstructor)throw new Error("Missing WebSocket constructor");this.endpoint.startsWith("http")&&(this.endpoint=K5(this.endpoint))}async makeRequest(e,r,n){const s=await w1(this,vc,v1).call(this);return new Promise((i,o)=>{_i(this,Vn,Re(this,Vn)+1),Re(this,As).set(Re(this,Vn),{resolve:i,reject:o,timeout:setTimeout(()=>{Re(this,As).delete(Re(this,Vn)),o(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n==null||n.addEventListener("abort",()=>{Re(this,As).delete(Re(this,Vn)),o(n.reason)}),s.send(JSON.stringify({jsonrpc:"2.0",id:Re(this,Vn),method:e,params:r}))}).then(({error:i,result:o})=>{if(i)throw new g1(i.message,i.code);return o})}async subscribe(e){const r=new Y5(e);return Re(this,Jo).add(r),await r.subscribe(this),()=>r.unsubscribe(this)}}Vn=new WeakMap;Eo=new WeakMap;pn=new WeakMap;Ss=new WeakMap;Jo=new WeakMap;As=new WeakMap;vc=new WeakSet;v1=function(){return Re(this,Ss)?Re(this,Ss):(_i(this,Ss,new Promise(t=>{var e;(e=Re(this,pn))==null||e.close(),_i(this,pn,new this.options.WebSocketConstructor(this.endpoint)),Re(this,pn).addEventListener("open",()=>{_i(this,Eo,0),t(Re(this,pn))}),Re(this,pn).addEventListener("close",()=>{W5(this,Eo)._++,Re(this,Eo)<=this.options.maxReconnects&&setTimeout(()=>{w1(this,vc,E1).call(this)},this.options.reconnectTimeout)}),Re(this,pn).addEventListener("message",({data:r})=>{let n;try{n=JSON.parse(r)}catch(s){console.error(new Error(`Failed to parse RPC message: ${r}`,{cause:s}));return}if("id"in n&&n.id!=null&&Re(this,As).has(n.id)){const{resolve:s,timeout:i}=Re(this,As).get(n.id);clearTimeout(i),s(n)}else if("params"in n){const{params:s}=n;Re(this,Jo).forEach(i=>{i.subscriptionId===s.subscription&&s.subscription===i.subscriptionId&&i.onMessage(s.result)})}})})),Re(this,Ss))};E1=async function(){var t;return(t=Re(this,pn))==null||t.close(),_i(this,Ss,null),Promise.allSettled([...Re(this,Jo)].map(e=>e.subscribe(this)))};class Y5{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 S1=t=>{throw TypeError(t)},Ch=(t,e,r)=>e.has(t)||S1("Cannot "+r),sr=(t,e,r)=>(Ch(t,e,"read from private field"),r?r.call(t):e.get(t)),Za=(t,e,r)=>e.has(t)?S1("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),ud=(t,e,r,n)=>(Ch(t,e,"write to private field"),e.set(t,r),r),J5=(t,e,r)=>(Ch(t,e,"access private method"),r),yo,br,So,ld,A1;class Q5{constructor(e){Za(this,ld),Za(this,yo,0),Za(this,br),Za(this,So),ud(this,br,e)}fetch(e,r){const n=sr(this,br).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;ud(this,yo,sr(this,yo)+1);const r=await this.fetch(((s=sr(this,br).rpc)==null?void 0:s.url)??sr(this,br).url,{method:"POST",signal:e.signal,headers:{"Content-Type":"application/json","Client-Sdk-Type":"typescript","Client-Sdk-Version":y1,"Client-Target-Api-Version":V5,"Client-Request-Method":e.method,...(i=sr(this,br).rpc)==null?void 0:i.headers},body:JSON.stringify({jsonrpc:"2.0",id:sr(this,yo),method:e.method,params:e.params})});if(!r.ok)throw new G5(`Unexpected status code: ${r.status}`,r.status,r.statusText);const n=await r.json();if("error"in n&&n.error!=null)throw new g1(n.error.message,n.error.code);return n.result}async subscribe(e){const r=await J5(this,ld,A1).call(this).subscribe(e);return e.signal&&(e.signal.throwIfAborted(),e.signal.addEventListener("abort",()=>{r()})),async()=>!!await r()}}yo=new WeakMap;br=new WeakMap;So=new WeakMap;ld=new WeakSet;A1=function(){var t;if(!sr(this,So)){const e=sr(this,br).WebSocketConstructor??WebSocket;if(!e)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");ud(this,So,new X5(((t=sr(this,br).websocket)==null?void 0:t.url)??sr(this,br).url,{WebSocketConstructor:e,...sr(this,br).websocket}))}return sr(this,So)};function Pm(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 eO(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function x1(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 fd(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function k1(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function dd(t){if(!Array.isArray(t))throw new Error("array expected")}function _1(t,e){if(!x1(!0,e))throw new Error(`${t}: array of strings expected`)}function tO(t,e){if(!x1(!1,e))throw new Error(`${t}: array of numbers expected`)}function rO(...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 nO(t){const e=typeof t=="string"?t.split(""):t,r=e.length;_1("alphabet",e);const n=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(dd(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=>(dd(s),s.map(i=>{fd("alphabet.decode",i);const o=n.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${t}`);return o}))}}function sO(t=""){return fd("join",t),{encode:e=>(_1("join.decode",e),e.join(t)),decode:e=>(fd("join.decode",e),e.split(t))}}function Om(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(dd(t),!t.length)return[];let n=0;const s=[],i=Array.from(t,a=>{if(k1(a),a<0||a>=e)throw new Error(`invalid integer: ${a}`);return a}),o=i.length;for(;;){let a=0,c=!0;for(let l=n;l<o;l++){const u=i[l],f=e*a,h=f+u;if(!Number.isSafeInteger(h)||f/e!==a||h-u!==f)throw new Error("convertRadix: carry overflow");const d=h/r;a=h%r;const m=Math.floor(d);if(i[l]=m,!Number.isSafeInteger(m)||m*r+a!==h)throw new Error("convertRadix: carry overflow");if(c)m?c=!1:n=l;else continue}if(s.push(a),c)break}for(let a=0;a<t.length-1&&t[a]===0;a++)s.push(0);return s.reverse()}function iO(t){k1(t);const e=2**8;return{encode:r=>{if(!eO(r))throw new Error("radix.encode input should be Uint8Array");return Om(Array.from(r),e,t)},decode:r=>(tO("radix.decode",r),Uint8Array.from(Om(r,t,e)))}}const oO=t=>rO(iO(58),nO(t),sO("")),T1=oO("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),yu=t=>T1.encode(t),Qo=t=>T1.decode(t);function Gt(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}const nf=8192;function gt(t){if(t.length<nf)return btoa(String.fromCharCode(...t));let e="";for(var r=0;r<t.length;r+=nf){const n=t.slice(r,r+nf);e+=String.fromCharCode(...n)}return btoa(e)}function I1(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 Fi(t){return t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),"")}function mu(t,e){return Array.from({length:Math.ceil(t.length/e)},(r,n)=>t.slice(n*e,(n+1)*e))}class P1{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=lO(r),this._batchScheduleFn=fO(r),this._cacheKeyFn=dO(r),this._cacheMap=hO(r),this._batch=null,this.name=pO(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=cO(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(!O1(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 aO=typeof process=="object"&&typeof process.nextTick=="function"?function(t){sf||(sf=Promise.resolve()),sf.then(()=>{process.nextTick(t)})}:typeof setImmediate=="function"?function(t){setImmediate(t)}:function(t){setTimeout(t)};let sf;function cO(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(()=>{uO(t,r)}),r}function uO(t,e){if(e.hasDispatched=!0,e.keys.length===0){hd(e);return}let r;try{r=t._batchLoadFn(e.keys)}catch(n){return of(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 of(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(!O1(n))throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array: ${String(n)}.`);if(n.length!==e.keys.length)throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys.
83
-
84
- Keys:
85
- ${String(e.keys)}
86
-
87
- Values:
88
- ${String(n)}`);hd(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=>{of(t,e,n)})}function of(t,e,r){hd(e);for(let n=0;n<e.keys.length;n++)t.clear(e.keys[n]),e.callbacks[n].reject(r)}function hd(t){if(t.cacheHits)for(let e=0;e<t.cacheHits.length;e++)t.cacheHits[e]()}function lO(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 fO(t){const e=t&&t.batchScheduleFn;if(e===void 0)return aO;if(typeof e!="function")throw new TypeError(`batchScheduleFn must be a function: ${e}`);return e}function dO(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 hO(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 pO(t){return t&&t.name?t.name:null}function O1(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 Ec(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 yO(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 mO{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}=yO(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 gO(t,e){switch(e){case"base58":return yu(t);case"base64":return gt(t);case"hex":return Fi(t);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}function B1(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 bO{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 af(BigInt(e),8).forEach(r=>this.write8(r)),this}write128(e){return af(BigInt(e),16).forEach(r=>this.write8(r)),this}write256(e){return af(BigInt(e),32).forEach(r=>this.write8(r)),this}writeULEB(e){return Ec(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 gO(this.toBytes(),e)}}function af(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 C1=t=>{throw TypeError(t)},$1=(t,e,r)=>e.has(t)||C1("Cannot "+r),wr=(t,e,r)=>($1(t,e,"read from private field"),r?r.call(t):e.get(t)),Sc=(t,e,r)=>e.has(t)?C1("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Ac=(t,e,r,n)=>($1(t,e,"write to private field"),e.set(t,r),r),di,mo,ac,qn;const wO=class R1{constructor(e){Sc(this,di),Sc(this,mo),this.name=e.name,this.read=e.read,this.serializedSize=e.serializedSize??(()=>null),Ac(this,di,e.write),Ac(this,mo,e.serialize??((r,n)=>{const s=new bO({initialSize:this.serializedSize(r)??void 0,...n});return wr(this,di).call(this,r,s),s.toBytes()})),this.validate=e.validate??(()=>{})}write(e,r){this.validate(e),wr(this,di).call(this,e,r)}serialize(e,r){return this.validate(e),new vO(this,wr(this,mo).call(this,e,r))}parse(e){const r=new mO(e);return this.read(r)}fromHex(e){return this.parse(I1(e))}fromBase58(e){return this.parse(Qo(e))}fromBase64(e){return this.parse(Gt(e))}transform({name:e,input:r,output:n,validate:s}){return new R1({name:e??this.name,read:i=>n?n(this.read(i)):this.read(i),write:(i,o)=>wr(this,di).call(this,r?r(i):i,o),serializedSize:i=>this.serializedSize(r?r(i):i),serialize:(i,o)=>wr(this,mo).call(this,r?r(i):i,o),validate:i=>{s==null||s(i),this.validate(r?r(i):i)}})}};di=new WeakMap;mo=new WeakMap;let Qr=wO;const N1=Symbol.for("@mysten/serialized-bcs");function $h(t){return!!t&&typeof t=="object"&&t[N1]===!0}class vO{constructor(e,r){Sc(this,ac),Sc(this,qn),Ac(this,ac,e),Ac(this,qn,r)}get[N1](){return!0}toBytes(){return wr(this,qn)}toHex(){return Fi(wr(this,qn))}toBase64(){return gt(wr(this,qn))}toBase58(){return yu(wr(this,qn))}parse(){return wr(this,ac).parse(wr(this,qn))}}ac=new WeakMap;qn=new WeakMap;function xc({size:t,...e}){return new Qr({...e,serializedSize:()=>t})}function cf({readMethod:t,writeMethod:e,...r}){return xc({...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 uf({readMethod:t,writeMethod:e,...r}){return xc({...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 EO({serialize:t,...e}){const r=new Qr({...e,serialize:t,write:(n,s)=>{for(const i of r.serialize(n).toBytes())s.write8(i)}});return r}function SO({toBytes:t,fromBytes:e,...r}){return new Qr({...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=Ec(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 AO(t){let e=null;function r(){return e||(e=t()),e}return new Qr({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 xO extends Qr{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 l=c.serializedSize(i[a]);if(l==null)return null;o+=l}return o},read:i=>{const o={};for(const[a,c]of s)o[a]=c.read(i);return o},write:(i,o)=>{for(const[a,c]of s)c.write(i[a],o)},...n,validate:i=>{var o;if((o=n==null?void 0:n.validate)==null||o.call(n,i),typeof i!="object"||i==null)throw new TypeError(`Expected object, found ${typeof i}`)}})}}class kO extends Qr{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[l,u]=n[c];if(l===o){i.writeULEB(c),u==null||u.write(a,i);return}}},...r,validate:s=>{var a;if((a=r==null?void 0:r.validate)==null||a.call(r,s),typeof s!="object"||s==null)throw new TypeError(`Expected object, found ${typeof s}`);const i=Object.keys(s).filter(c=>s[c]!==void 0&&Object.hasOwn(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 _O extends Qr{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 TO(t,e,r){return new Qr({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 IO(t){return k.enum(`Option<${t.name}>`,{None:null,Some:t}).transform({input:e=>e==null?{None:!0}:{Some:e},output:e=>e.$kind==="Some"?e.Some:null})}function PO(t,e){return new Qr({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 OO(t,e){return k.vector(k.tuple([t,e])).transform({name:`Map<${t.name}, ${e.name}>`,input:r=>[...r.entries()],output:r=>{const n=new Map;for(const[s,i]of r)n.set(s,i);return n}})}const k={u8(t){return cf({readMethod:"read8",writeMethod:"write8",size:1,maxValue:2**8-1,...t,name:(t==null?void 0:t.name)??"u8"})},u16(t){return cf({readMethod:"read16",writeMethod:"write16",size:2,maxValue:2**16-1,...t,name:(t==null?void 0:t.name)??"u16"})},u32(t){return cf({readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...t,name:(t==null?void 0:t.name)??"u32"})},u64(t){return uf({readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...t,name:(t==null?void 0:t.name)??"u64"})},u128(t){return uf({readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...t,name:(t==null?void 0:t.name)??"u128"})},u256(t){return uf({readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...t,name:(t==null?void 0:t.name)??"u256"})},bool(t){return xc({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 EO({read:e=>e.readULEB(),serialize:e=>Uint8Array.from(Ec(e)),...t,name:(t==null?void 0:t.name)??"uleb128"})},bytes(t,e){return xc({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 Qr({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:Ec(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 SO({toBytes:e=>new TextEncoder().encode(e),fromBytes:e=>new TextDecoder().decode(e),...t,name:(t==null?void 0:t.name)??"string"})},fixedArray:TO,option:IO,vector:PO,tuple(t,e){return new _O({fields:t,...e})},struct(t,e,r){return new xO({name:t,fields:e,...r})},enum(t,e,r){return new kO({name:t,fields:e,...r})},map:OO,lazy(t){return AO(t)}};var U1=t=>{throw TypeError(t)},M1=(t,e,r)=>e.has(t)||U1("Cannot "+r),yt=(t,e,r)=>(M1(t,e,"read from private field"),e.get(t)),Bm=(t,e,r)=>e.has(t)?U1("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Cm=(t,e,r,n)=>(M1(t,e,"write to private field"),e.set(t,r),r),ys,_t;const BO=class F1{constructor({prefix:e,cache:r}={}){Bm(this,ys),Bm(this,_t),Cm(this,ys,e??[]),Cm(this,_t,r??new Map)}read(e,r){const n=[yt(this,ys),...e].join(":");if(yt(this,_t).has(n))return yt(this,_t).get(n);const s=r();return yt(this,_t).set(n,s),typeof s=="object"&&s!==null&&"then"in s?Promise.resolve(s).then(i=>(yt(this,_t).set(n,i),i)).catch(i=>{throw yt(this,_t).delete(n),i}):s}readSync(e,r){const n=[yt(this,ys),...e].join(":");if(yt(this,_t).has(n))return yt(this,_t).get(n);const s=r();return yt(this,_t).set(n,s),s}clear(e){const r=[...yt(this,ys),...e??[]].join(":");if(!r){yt(this,_t).clear();return}for(const n of yt(this,_t).keys())n.startsWith(r)&&yt(this,_t).delete(n)}scope(e){return new F1({prefix:[...yt(this,ys),...Array.isArray(e)?e:[e]],cache:yt(this,_t)})}};ys=new WeakMap;_t=new WeakMap;let CO=BO;class j1{constructor({network:e,base:r,cache:n=(r==null?void 0:r.cache)??new CO}){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 L1=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,D1=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i,$O=235;function RO(t){return t.length>$O?!1:t.includes("@")?L1.test(t):D1.test(t)}function NO(t,e="at"){const r=t.toLowerCase();let n;if(r.includes("@")){if(!L1.test(r))throw new Error(`Invalid SuiNS name ${t}`);const[s,i]=r.split("@");n=[...s?s.split("."):[],i]}else{if(!D1.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 UO=/^([a-z0-9]+(?:-[a-z0-9]+)*)$/,MO=/^\d+$/,FO=64,H1="/",zt=t=>{const e=t.split(H1);if(e.length<2||e.length>3)return!1;const[r,n,s]=e;return s!==void 0&&!MO.test(s)||!RO(r)?!1:UO.test(n)&&n.length<FO},jO=t=>{const e=t.split(/::|<|>|,/);for(const r of e)if(r.includes(H1)&&!zt(r))return!1;return!0},LO=32;function $m(t){try{return Qo(t).length===LO}catch{return!1}}const gu=32;function vr(t){return HO(t)&&zO(t)===gu}function Xa(t){return vr(t)}function DO(t){return t.includes("::")?qs(t):t}function qs(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("<")?B1(s.slice(s.indexOf("<")+1,s.lastIndexOf(">"))).map(a=>DO(a.trim())):[];return{address:n?e:Se(e),module:r,name:i,typeParams:o}}function kc(t){const{address:e,module:r,name:n,typeParams:s}=typeof t=="string"?qs(t):t,i=(s==null?void 0:s.length)>0?`<${s.map(o=>typeof o=="string"?o:kc(o)).join(",")}>`:"";return`${e}::${r}::${n}${i}`}function Se(t,e=!1){let r=t.toLowerCase();return!e&&r.startsWith("0x")&&(r=r.slice(2)),`0x${r.padStart(gu*2,"0")}`}function wn(t,e=!1){return Se(t,e)}function HO(t){return/^(0x|0X)?[a-fA-F0-9]+$/.test(t)&&t.length%2===0}function zO(t){return/^(0x|0X)/.test(t)?(t.length-2)/2:t.length/2}const VO=/^vector<(.+)>$/,qO=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class Ar{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(VO);if(n)return{vector:Ar.parseFromStr(n[1],r)};const s=e.match(qO);if(s)return{struct:{address:r?Se(s[1]):s[1],module:s[2],name:s[3],typeParams:s[5]===void 0?[]:Ar.parseStructTypeArgs(s[5],r)}};throw new Error(`Encountered unexpected token when parsing type args for ${e}`)}static parseStructTypeArgs(e,r=!1){return B1(e).map(n=>Ar.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<${Ar.tagToString(e.vector)}>`;if("struct"in e){const r=e.struct,n=r.typeParams.map(Ar.tagToString).join(", ");return`${r.address}::${r.module}::${r.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}function GO(t){return k.u64({name:"unsafe_u64",...t}).transform({input:e=>e,output:e=>Number(e)})}function WO(t){return k.enum("Option",{None:null,Some:t})}const Ce=k.bytes(gu).transform({validate:t=>{const e=typeof t=="string"?t:Fi(t);if(!e||!vr(Se(e)))throw new Error(`Invalid Sui address ${e}`)},input:t=>typeof t=="string"?I1(Se(t)):t,output:t=>Se(Fi(t))}),kr=k.vector(k.u8()).transform({name:"ObjectDigest",input:t=>Qo(t),output:t=>yu(new Uint8Array(t)),validate:t=>{if(Qo(t).length!==32)throw new Error("ObjectDigest must be 32 bytes")}}),nr=k.struct("SuiObjectRef",{objectId:Ce,version:k.u64(),digest:kr}),z1=k.struct("SharedObjectRef",{objectId:Ce,initialSharedVersion:k.u64(),mutable:k.bool()}),V1=k.enum("ObjectArg",{ImmOrOwnedObject:nr,SharedObject:z1,Receiving:nr}),xs=k.enum("Owner",{AddressOwner:Ce,ObjectOwner:Ce,Shared:k.struct("Shared",{initialSharedVersion:k.u64()}),Immutable:null,ConsensusAddressOwner:k.struct("ConsensusAddressOwner",{owner:Ce,startVersion:k.u64()})}),q1=k.enum("CallArg",{Pure:k.struct("Pure",{bytes:k.vector(k.u8()).transform({input:t=>typeof t=="string"?Gt(t):t,output:t=>gt(new Uint8Array(t))})}),Object:V1}),Rh=k.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:k.lazy(()=>Rh),struct:k.lazy(()=>Y1),u16:null,u32:null,u256:null}),Nh=Rh.transform({input:t=>typeof t=="string"?Ar.parseFromStr(t,!0):t,output:t=>Ar.tagToString(t)}),Vr=k.enum("Argument",{GasCoin:null,Input:k.u16(),Result:k.u16(),NestedResult:k.tuple([k.u16(),k.u16()])}),G1=k.struct("ProgrammableMoveCall",{package:Ce,module:k.string(),function:k.string(),typeArguments:k.vector(Nh),arguments:k.vector(Vr)}),W1=k.enum("Command",{MoveCall:G1,TransferObjects:k.struct("TransferObjects",{objects:k.vector(Vr),address:Vr}),SplitCoins:k.struct("SplitCoins",{coin:Vr,amounts:k.vector(Vr)}),MergeCoins:k.struct("MergeCoins",{destination:Vr,sources:k.vector(Vr)}),Publish:k.struct("Publish",{modules:k.vector(k.vector(k.u8()).transform({input:t=>typeof t=="string"?Gt(t):t,output:t=>gt(new Uint8Array(t))})),dependencies:k.vector(Ce)}),MakeMoveVec:k.struct("MakeMoveVec",{type:WO(Nh).transform({input:t=>t===null?{None:!0}:{Some:t},output:t=>t.Some??null}),elements:k.vector(Vr)}),Upgrade:k.struct("Upgrade",{modules:k.vector(k.vector(k.u8()).transform({input:t=>typeof t=="string"?Gt(t):t,output:t=>gt(new Uint8Array(t))})),dependencies:k.vector(Ce),package:Ce,ticket:Vr})}),K1=k.struct("ProgrammableTransaction",{inputs:k.vector(q1),commands:k.vector(W1)}),Z1=k.enum("TransactionKind",{ProgrammableTransaction:K1,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),X1=k.enum("TransactionExpiration",{None:null,Epoch:GO()}),Y1=k.struct("StructTag",{address:Ce,module:k.string(),name:k.string(),typeParams:k.vector(Rh)}),J1=k.struct("GasData",{payment:k.vector(nr),owner:Ce,price:k.u64(),budget:k.u64()}),Q1=k.struct("TransactionDataV1",{kind:Z1,sender:Ce,gasData:J1,expiration:X1}),ev=k.enum("TransactionData",{V1:Q1}),tv=k.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),rv=k.enum("IntentVersion",{V0:null}),nv=k.enum("AppId",{Sui:null}),sv=k.struct("Intent",{scope:tv,version:rv,appId:nv});function iv(t){return k.struct(`IntentMessage<${t.name}>`,{intent:sv,value:t})}const ov=k.enum("CompressedSignature",{ED25519:k.fixedArray(64,k.u8()),Secp256k1:k.fixedArray(64,k.u8()),Secp256r1:k.fixedArray(64,k.u8()),ZkLogin:k.vector(k.u8()),Passkey:k.vector(k.u8())}),av=k.enum("PublicKey",{ED25519:k.fixedArray(32,k.u8()),Secp256k1:k.fixedArray(33,k.u8()),Secp256r1:k.fixedArray(33,k.u8()),ZkLogin:k.vector(k.u8()),Passkey:k.fixedArray(33,k.u8())}),cv=k.struct("MultiSigPkMap",{pubKey:av,weight:k.u8()}),uv=k.struct("MultiSigPublicKey",{pk_map:k.vector(cv),threshold:k.u16()}),KO=k.struct("MultiSig",{sigs:k.vector(ov),bitmap:k.u16(),multisig_pk:uv}),ZO=k.vector(k.u8()).transform({input:t=>typeof t=="string"?Gt(t):t,output:t=>gt(new Uint8Array(t))}),lv=k.struct("SenderSignedTransaction",{intentMessage:iv(ev),txSignatures:k.vector(ZO)}),XO=k.vector(lv,{name:"SenderSignedData"}),YO=k.struct("PasskeyAuthenticator",{authenticatorData:k.vector(k.u8()),clientDataJson:k.string(),userSignature:k.vector(k.u8())}),JO=k.enum("PackageUpgradeError",{UnableToFetchPackage:k.struct("UnableToFetchPackage",{packageId:Ce}),NotAPackage:k.struct("NotAPackage",{objectId:Ce}),IncompatibleUpgrade:null,DigestDoesNotMatch:k.struct("DigestDoesNotMatch",{digest:k.vector(k.u8())}),UnknownUpgradePolicy:k.struct("UnknownUpgradePolicy",{policy:k.u8()}),PackageIDDoesNotMatch:k.struct("PackageIDDoesNotMatch",{packageId:Ce,ticketId:Ce})}),QO=k.struct("ModuleId",{address:Ce,name:k.string()}),Rm=k.struct("MoveLocation",{module:QO,function:k.u16(),instruction:k.u16(),functionName:k.option(k.string())}),e3=k.enum("CommandArgumentError",{TypeMismatch:null,InvalidBCSBytes:null,InvalidUsageOfPureArg:null,InvalidArgumentToPrivateEntryFunction:null,IndexOutOfBounds:k.struct("IndexOutOfBounds",{idx:k.u16()}),SecondaryIndexOutOfBounds:k.struct("SecondaryIndexOutOfBounds",{resultIdx:k.u16(),secondaryIdx:k.u16()}),InvalidResultArity:k.struct("InvalidResultArity",{resultIdx:k.u16()}),InvalidGasCoinUsage:null,InvalidValueUsage:null,InvalidObjectByValue:null,InvalidObjectByMutRef:null,SharedObjectOperationNotAllowed:null}),t3=k.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),r3=k.enum("ExecutionFailureStatus",{InsufficientGas:null,InvalidGasObject:null,InvariantViolation:null,FeatureNotYetSupported:null,MoveObjectTooBig:k.struct("MoveObjectTooBig",{objectSize:k.u64(),maxObjectSize:k.u64()}),MovePackageTooBig:k.struct("MovePackageTooBig",{objectSize:k.u64(),maxObjectSize:k.u64()}),CircularObjectOwnership:k.struct("CircularObjectOwnership",{object:Ce}),InsufficientCoinBalance:null,CoinBalanceOverflow:null,PublishErrorNonZeroAddress:null,SuiMoveVerificationError:null,MovePrimitiveRuntimeError:k.option(Rm),MoveAbort:k.tuple([Rm,k.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:k.struct("CommandArgumentError",{argIdx:k.u16(),kind:e3}),TypeArgumentError:k.struct("TypeArgumentError",{argumentIdx:k.u16(),kind:t3}),UnusedValueWithoutDrop:k.struct("UnusedValueWithoutDrop",{resultIdx:k.u16(),secondaryIdx:k.u16()}),InvalidPublicFunctionReturnType:k.struct("InvalidPublicFunctionReturnType",{idx:k.u16()}),InvalidTransferObject:null,EffectsTooLarge:k.struct("EffectsTooLarge",{currentSize:k.u64(),maxSize:k.u64()}),PublishUpgradeMissingDependency:null,PublishUpgradeDependencyDowngrade:null,PackageUpgradeError:k.struct("PackageUpgradeError",{upgradeError:JO}),WrittenObjectsTooLarge:k.struct("WrittenObjectsTooLarge",{currentSize:k.u64(),maxSize:k.u64()}),CertificateDenied:null,SuiMoveVerificationTimedout:null,SharedObjectOperationNotAllowed:null,InputObjectDeleted:null,ExecutionCancelledDueToSharedObjectCongestion:k.struct("ExecutionCancelledDueToSharedObjectCongestion",{congestedObjects:k.vector(Ce)}),AddressDeniedForCoin:k.struct("AddressDeniedForCoin",{address:Ce,coinType:k.string()}),CoinTypeGlobalPause:k.struct("CoinTypeGlobalPause",{coinType:k.string()}),ExecutionCancelledDueToRandomnessUnavailable:null}),fv=k.enum("ExecutionStatus",{Success:null,Failed:k.struct("ExecutionFailed",{error:r3,command:k.option(k.u64())})}),dv=k.struct("GasCostSummary",{computationCost:k.u64(),storageCost:k.u64(),storageRebate:k.u64(),nonRefundableStorageFee:k.u64()}),n3=k.struct("TransactionEffectsV1",{status:fv,executedEpoch:k.u64(),gasUsed:dv,modifiedAtVersions:k.vector(k.tuple([Ce,k.u64()])),sharedObjects:k.vector(nr),transactionDigest:kr,created:k.vector(k.tuple([nr,xs])),mutated:k.vector(k.tuple([nr,xs])),unwrapped:k.vector(k.tuple([nr,xs])),deleted:k.vector(nr),unwrappedThenDeleted:k.vector(nr),wrapped:k.vector(nr),gasObject:k.tuple([nr,xs]),eventsDigest:k.option(kr),dependencies:k.vector(kr)}),Uh=k.tuple([k.u64(),kr]),s3=k.enum("ObjectIn",{NotExist:null,Exist:k.tuple([Uh,xs])}),i3=k.enum("ObjectOut",{NotExist:null,ObjectWrite:k.tuple([kr,xs]),PackageWrite:Uh}),o3=k.enum("IDOperation",{None:null,Created:null,Deleted:null}),a3=k.struct("EffectsObjectChange",{inputState:s3,outputState:i3,idOperation:o3}),c3=k.enum("UnchangedSharedKind",{ReadOnlyRoot:Uh,MutateDeleted:k.u64(),ReadDeleted:k.u64(),Cancelled:k.u64(),PerEpochConfig:null}),u3=k.struct("TransactionEffectsV2",{status:fv,executedEpoch:k.u64(),gasUsed:dv,transactionDigest:kr,gasObjectIndex:k.option(k.u32()),eventsDigest:k.option(kr),dependencies:k.vector(kr),lamportVersion:k.u64(),changedObjects:k.vector(k.tuple([Ce,a3])),unchangedSharedObjects:k.vector(k.tuple([Ce,c3])),auxDataDigest:k.option(kr)}),l3=k.enum("TransactionEffects",{V1:n3,V2:u3});function Ao(t){switch(t){case"u8":return k.u8();case"u16":return k.u16();case"u32":return k.u32();case"u64":return k.u64();case"u128":return k.u128();case"u256":return k.u256();case"bool":return k.bool();case"string":return k.string();case"id":case"address":return Ce}const e=t.match(/^(vector|option)<(.+)>$/);if(e){const[r,n]=e.slice(1);return r==="vector"?k.vector(Ao(n)):k.option(Ao(n))}throw new Error(`Invalid Pure type name: ${t}`)}const he={...k,U8:k.u8(),U16:k.u16(),U32:k.u32(),U64:k.u64(),U128:k.u128(),U256:k.u256(),ULEB128:k.uleb128(),Bool:k.bool(),String:k.string(),Address:Ce,AppId:nv,Argument:Vr,CallArg:q1,Command:W1,CompressedSignature:ov,GasData:J1,Intent:sv,IntentMessage:iv,IntentScope:tv,IntentVersion:rv,MultiSig:KO,MultiSigPkMap:cv,MultiSigPublicKey:uv,ObjectArg:V1,ObjectDigest:kr,Owner:xs,PasskeyAuthenticator:YO,ProgrammableMoveCall:G1,ProgrammableTransaction:K1,PublicKey:av,SenderSignedData:XO,SenderSignedTransaction:lv,SharedObjectRef:z1,StructTag:Y1,SuiObjectRef:nr,TransactionData:ev,TransactionDataV1:Q1,TransactionEffects:l3,TransactionExpiration:X1,TransactionKind:Z1,TypeTag:Nh};var cn;function f3(t){return{lang:(t==null?void 0:t.lang)??(cn==null?void 0:cn.lang),message:t==null?void 0:t.message,abortEarly:(t==null?void 0:t.abortEarly)??(cn==null?void 0:cn.abortEarly),abortPipeEarly:(t==null?void 0:t.abortPipeEarly)??(cn==null?void 0:cn.abortPipeEarly)}}var lf;function d3(t){return lf==null?void 0:lf.get(t)}var ff;function h3(t){return ff==null?void 0:ff.get(t)}var df;function p3(t,e){var r;return(r=df==null?void 0:df.get(t))==null?void 0:r.get(e)}function hv(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)??hv(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},l=t.kind==="schema",u=(s==null?void 0:s.message)??t.message??p3(t.reference,c.lang)??(l?h3(c.lang):null)??n.message??d3(c.lang);u&&(c.message=typeof u=="function"?u(c):u),l&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function y3(t,e){return Object.hasOwn(t,e)&&e!=="__proto__"&&e!=="prototype"&&e!=="constructor"}var m3=class extends Error{constructor(e){super(e[0].message);Kh(this,"issues");this.name="ValiError",this.issues=e}};function Ta(t,e){return{kind:"validation",type:"check",reference:Ta,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 Ve(t){return{kind:"validation",type:"integer",reference:Ve,async:!1,expects:null,requirement:Number.isInteger,message:t,_run(e,r){return e.typed&&!this.requirement(e.value)&&Xt(this,"integer",e,r),e}}}function bu(t){return{kind:"transformation",type:"transform",reference:bu,async:!1,operation:t,_run(e){return e.value=this.operation(e.value),e}}}function Mh(t,e,r){return typeof t.default=="function"?t.default(e,r):t.default}function pd(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 l={type:"array",origin:"value",input:s,key:o,value:a};for(const u of c.issues)u.path?u.path.unshift(l):u.path=[l],(i=r.issues)==null||i.push(u);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else Xt(this,"type",r,n);return r}}}function Fh(t){return{kind:"schema",type:"bigint",reference:Fh,expects:"bigint",async:!1,message:t,_run(e,r){return typeof e.value=="bigint"?e.typed=!0:Xt(this,"type",e,r),e}}}function wu(t){return{kind:"schema",type:"boolean",reference:wu,expects:"boolean",async:!1,message:t,_run(e,r){return typeof e.value=="boolean"?e.typed=!0:Xt(this,"type",e,r),e}}}function ea(t){return{kind:"schema",type:"lazy",reference:ea,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:hv(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 ve(t,...e){const r={kind:"schema",type:"nullable",reference:ve,expects:`${t.expects} | null`,async:!1,wrapped:t,_run(n,s){return n.value===null&&("default"in this&&(n.value=Mh(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 ji(t,...e){const r={kind:"schema",type:"nullish",reference:ji,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=Mh(this,n,s)),n.value===null||n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in e&&(r.default=e[0]),r}function je(t){return{kind:"schema",type:"number",reference:je,expects:"number",async:!1,message:t,_run(e,r){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0: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 l={type:"object",origin:"value",input:s,key:o,value:a};for(const u of c.issues)u.path?u.path.unshift(l):u.path=[l],(i=r.issues)==null||i.push(u);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),(c.value!==void 0||o in s)&&(r.value[o]=c.value)}}else Xt(this,"type",r,n);return r}}}function dt(t,...e){const r={kind:"schema",type:"optional",reference:dt,expects:`${t.expects} | undefined`,async:!1,wrapped:t,_run(n,s){return n.value===void 0&&("default"in this&&(n.value=Mh(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 ta(t,e,r){return{kind:"schema",type:"record",reference:ta,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(y3(i,c)){const l=i[c],u=this.key._run({typed:!1,value:c},s);if(u.issues){const h={type:"object",origin:"key",input:i,key:c,value:l};for(const d of u.issues)d.path=[h],(o=n.issues)==null||o.push(d);if(n.issues||(n.issues=u.issues),s.abortEarly){n.typed=!1;break}}const f=this.value._run({typed:!1,value:l},s);if(f.issues){const h={type:"object",origin:"value",input:i,key:c,value:l};for(const d of f.issues)d.path?d.path.unshift(h):d.path=[h],(a=n.issues)==null||a.push(d);if(n.issues||(n.issues=f.issues),s.abortEarly){n.typed=!1;break}}(!u.typed||!f.typed)&&(n.typed=!1),u.typed&&(n.value[u.value]=f.value)}}else 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 jh(t,e){return{kind:"schema",type:"tuple",reference:jh,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 l={type:"array",origin:"value",input:s,key:o,value:a};for(const u of c.issues)u.path?u.path.unshift(l):u.path=[l],(i=r.issues)==null||i.push(u);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else Xt(this,"type",r,n);return r}}}function Nm(t){let e;if(t)for(const r of t)e?e.push(...r.issues):e=r.issues;return e}function pt(t,e){return{kind:"schema",type:"union",reference:pt,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:Nm(i)}),r.typed=!0}else{if((o==null?void 0:o.length)===1)return o[0];Xt(this,"type",r,n,{issues:Nm(o)})}return r}}}function Gs(){return{kind:"schema",type:"unknown",reference:Gs,expects:"unknown",async:!1,_run(t){return t.typed=!0,t}}}function ze(t,e,r){const n=t._run({typed:!1,value:e},f3(r));if(n.issues)throw new m3(n.issues);return n.value}function Te(...t){return{...t[0],pipe:t,_run(e,r){for(let n=0;n<t.length;n++){if(e.issues&&(t[n].kind==="schema"||t[n].kind==="transformation")){e.typed=!1;break}(!e.issues||!r.abortEarly&&!r.abortPipeEarly)&&(e=t[n]._run(e,r))}return e}}}function ti(t){const e=Object.entries(t).map(([r,n])=>te({[r]:n}));return Te(pt(e),bu(r=>({...r,$kind:Object.keys(r)[0]})))}const Zi=Te(ye(),bu(t=>Se(t)),Ta(vr)),Wt=Zi,Ws=ye(),jt=Te(pt([ye(),Te(je(),Ve())]),Ta(t=>{try{return BigInt(t),BigInt(t)>=0&&BigInt(t)<=18446744073709551615n}catch{return!1}},"Invalid u64")),as=te({objectId:Zi,version:jt,digest:ye()}),Ne=Te(pt([te({GasCoin:de(!0)}),te({Input:Te(je(),Ve()),type:dt(de("pure"))}),te({Input:Te(je(),Ve()),type:dt(de("object"))}),te({Result:Te(je(),Ve())}),te({NestedResult:jh([Te(je(),Ve()),Te(je(),Ve())])})]),bu(t=>({...t,$kind:Object.keys(t)[0]}))),g3=te({budget:ve(jt),price:ve(jt),owner:ve(Zi),payment:ve(fe(as))}),yd=pt([de("address"),de("bool"),de("u8"),de("u16"),de("u32"),de("u64"),de("u128"),de("u256"),te({vector:ea(()=>yd)}),te({datatype:te({package:ye(),module:ye(),type:ye(),typeParameters:fe(ea(()=>yd))})}),te({typeParameter:Te(je(),Ve())})]),b3=te({ref:ve(pt([de("&"),de("&mut")])),body:yd}),w3=te({package:Wt,module:ye(),function:ye(),typeArguments:fe(ye()),arguments:fe(Ne),_argumentTypes:dt(ve(fe(b3)))}),v3=te({name:ye(),inputs:ta(ye(),pt([Ne,fe(Ne)])),data:ta(ye(),Gs())}),E3=ti({MoveCall:w3,TransferObjects:te({objects:fe(Ne),address:Ne}),SplitCoins:te({coin:Ne,amounts:fe(Ne)}),MergeCoins:te({destination:Ne,sources:fe(Ne)}),Publish:te({modules:fe(Ws),dependencies:fe(Wt)}),MakeMoveVec:te({type:ve(ye()),elements:fe(Ne)}),Upgrade:te({modules:fe(Ws),dependencies:fe(Wt),package:Wt,ticket:Ne}),$Intent:v3}),pv=ti({ImmOrOwnedObject:as,SharedObject:te({objectId:Wt,initialSharedVersion:jt,mutable:wu()}),Receiving:as}),S3=ti({Object:pv,Pure:te({bytes:Ws}),UnresolvedPure:te({value:Gs()}),UnresolvedObject:te({objectId:Wt,version:dt(ve(jt)),digest:dt(ve(ye())),initialSharedVersion:dt(ve(jt))})}),Um=ti({Object:pv,Pure:te({bytes:Ws})}),yv=ti({None:de(!0),Epoch:jt}),cc=te({version:de(2),sender:ji(Zi),expiration:ji(yv),gasData:g3,inputs:fe(S3),commands:fe(E3)}),ps={MoveCall(t){const[e,r="",n=""]="target"in t?t.target.split("::"):[t.package,t.module,t.function];return{$kind:"MoveCall",MoveCall:{package:e,module:r,function:n,typeArguments:t.typeArguments??[],arguments:t.arguments??[]}}},TransferObjects(t,e){return{$kind:"TransferObjects",TransferObjects:{objects:t.map(r=>ze(Ne,r)),address:ze(Ne,e)}}},SplitCoins(t,e){return{$kind:"SplitCoins",SplitCoins:{coin:ze(Ne,t),amounts:e.map(r=>ze(Ne,r))}}},MergeCoins(t,e){return{$kind:"MergeCoins",MergeCoins:{destination:ze(Ne,t),sources:e.map(r=>ze(Ne,r))}}},Publish({modules:t,dependencies:e}){return{$kind:"Publish",Publish:{modules:t.map(r=>typeof r=="string"?r:gt(new Uint8Array(r))),dependencies:e.map(r=>wn(r))}}},Upgrade({modules:t,dependencies:e,package:r,ticket:n}){return{$kind:"Upgrade",Upgrade:{modules:t.map(s=>typeof s=="string"?s:gt(new Uint8Array(s))),dependencies:e.map(s=>wn(s)),package:r,ticket:ze(Ne,n)}}},MakeMoveVec({type:t,elements:e}){return{$kind:"MakeMoveVec",MakeMoveVec:{type:t??null,elements:e.map(r=>ze(Ne,r))}}},Intent({name:t,inputs:e={},data:r={}}){return{$kind:"$Intent",$Intent:{name:t,inputs:Object.fromEntries(Object.entries(e).map(([n,s])=>[n,Array.isArray(s)?s.map(i=>ze(Ne,i)):ze(Ne,s)])),data:r}}}},md=te({digest:ye(),objectId:ye(),version:pt([Te(je(),Ve()),ye(),Fh()])}),A3=ti({ImmOrOwned:md,Shared:te({objectId:Wt,initialSharedVersion:jt,mutable:wu()}),Receiving:md}),Mm=ti({Object:A3,Pure:fe(Te(je(),Ve()))}),mv=pt([te({kind:de("Input"),index:Te(je(),Ve()),value:Gs(),type:dt(de("object"))}),te({kind:de("Input"),index:Te(je(),Ve()),value:Gs(),type:de("pure")})]),x3=pt([te({Epoch:Te(je(),Ve())}),te({None:ve(de(!0))})]),Fm=Te(pt([je(),ye(),Fh()]),Ta(t=>{if(!["string","number","bigint"].includes(typeof t))return!1;try{return BigInt(t),!0}catch{return!1}})),Lh=pt([te({bool:ve(de(!0))}),te({u8:ve(de(!0))}),te({u64:ve(de(!0))}),te({u128:ve(de(!0))}),te({address:ve(de(!0))}),te({signer:ve(de(!0))}),te({vector:ea(()=>Lh)}),te({struct:ea(()=>k3)}),te({u16:ve(de(!0))}),te({u32:ve(de(!0))}),te({u256:ve(de(!0))})]),k3=te({address:ye(),module:ye(),name:ye(),typeParams:fe(Lh)}),_3=te({budget:dt(Fm),price:dt(Fm),payment:dt(fe(md)),owner:dt(ye())}),T3=[mv,te({kind:de("GasCoin")}),te({kind:de("Result"),index:Te(je(),Ve())}),te({kind:de("NestedResult"),index:Te(je(),Ve()),resultIndex:Te(je(),Ve())})],Tn=pt([...T3]),I3=te({kind:de("MoveCall"),target:Te(ye(),Ta(t=>t.split("::").length===3)),typeArguments:fe(ye()),arguments:fe(Tn)}),P3=te({kind:de("TransferObjects"),objects:fe(Tn),address:Tn}),O3=te({kind:de("SplitCoins"),coin:Tn,amounts:fe(Tn)}),B3=te({kind:de("MergeCoins"),destination:Tn,sources:fe(Tn)}),C3=te({kind:de("MakeMoveVec"),type:pt([te({Some:Lh}),te({None:ve(de(!0))})]),objects:fe(Tn)}),$3=te({kind:de("Publish"),modules:fe(fe(Te(je(),Ve()))),dependencies:fe(ye())}),R3=te({kind:de("Upgrade"),modules:fe(fe(Te(je(),Ve()))),dependencies:fe(ye()),packageId:ye(),ticket:Tn}),N3=[I3,P3,O3,B3,$3,R3,C3],U3=pt([...N3]);te({version:de(1),sender:dt(ye()),expiration:ji(x3),gasConfig:_3,inputs:fe(mv),transactions:fe(U3)});function jm(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:Ar.parseFromStr(n.MakeMoveVec.type)},objects:n.MakeMoveVec.elements.map(s=>un(s,e))};if(n.MergeCoins)return{kind:"MergeCoins",destination:un(n.MergeCoins.destination,e),sources:n.MergeCoins.sources.map(s=>un(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=>un(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:un(n.SplitCoins.coin,e),amounts:n.SplitCoins.amounts.map(s=>un(s,e))};if(n.TransferObjects)return{kind:"TransferObjects",objects:n.TransferObjects.objects.map(s=>un(s,e)),address:un(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:un(n.Upgrade.ticket,e)};throw new Error(`Unknown transaction ${Object.keys(n)}`)})}}function un(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 M3(t){var e,r,n;return ze(cc,{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(pd(Mm,s.value)){const i=ze(Mm,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:gt(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?Ar.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=>gt(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=>gt(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 Ia(t){return pt(Object.entries(t).map(([e,r])=>te({[e]:r})))}const gr=Ia({GasCoin:de(!0),Input:Te(je(),Ve()),Result:Te(je(),Ve()),NestedResult:jh([Te(je(),Ve()),Te(je(),Ve())])}),F3=te({budget:ve(jt),price:ve(jt),owner:ve(Zi),payment:ve(fe(as))}),j3=te({package:Wt,module:ye(),function:ye(),typeArguments:fe(ye()),arguments:fe(gr)}),L3=te({name:ye(),inputs:ta(ye(),pt([gr,fe(gr)])),data:ta(ye(),Gs())}),D3=Ia({MoveCall:j3,TransferObjects:te({objects:fe(gr),address:gr}),SplitCoins:te({coin:gr,amounts:fe(gr)}),MergeCoins:te({destination:gr,sources:fe(gr)}),Publish:te({modules:fe(Ws),dependencies:fe(Wt)}),MakeMoveVec:te({type:ve(ye()),elements:fe(gr)}),Upgrade:te({modules:fe(Ws),dependencies:fe(Wt),package:Wt,ticket:gr}),$Intent:L3}),H3=Ia({ImmOrOwnedObject:as,SharedObject:te({objectId:Wt,initialSharedVersion:jt,mutable:wu()}),Receiving:as}),z3=Ia({Object:H3,Pure:te({bytes:Ws}),UnresolvedPure:te({value:Gs()}),UnresolvedObject:te({objectId:Wt,version:dt(ve(jt)),digest:dt(ve(ye())),initialSharedVersion:dt(ve(jt))})}),V3=Ia({None:de(!0),Epoch:jt}),q3=te({version:de(2),sender:ji(Zi),expiration:ji(V3),gasData:F3,inputs:fe(z3),commands:fe(D3),digest:dt(ve(ye()))});function G3(t){return{$kind:"Pure",Pure:{bytes:t instanceof Uint8Array?gt(t):t.toBase64()}}}const Vt={Pure:G3,ObjectRef({objectId:t,digest:e,version:r}){return{$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{digest:e,version:r,objectId:Se(t)}}}},SharedObjectRef({objectId:t,mutable:e,initialSharedVersion:r}){return{$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{mutable:e,initialSharedVersion:r,objectId:Se(t)}}}},ReceivingRef({objectId:t,digest:e,version:r}){return{$kind:"Object",Object:{$kind:"Receiving",Receiving:{digest:e,version:r,objectId:Se(t)}}}}};BigInt(1e9);const W3="0x1",gv="0x2",K3=wn("0x6"),Z3=`${gv}::sui::SUI`;wn("0x5");const X3=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),rt=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),re=new Uint32Array(32);function Dn(t,e,r,n,s,i){const o=s[i],a=s[i+1];let c=re[2*t],l=re[2*t+1],u=re[2*e],f=re[2*e+1],h=re[2*r],d=re[2*r+1],m=re[2*n],g=re[2*n+1],v=T0(c,u,o);l=I0(v,l,f,a),c=v|0,{Dh:g,Dl:m}={Dh:g^l,Dl:m^c},{Dh:g,Dl:m}={Dh:dE(g,m),Dl:hE(g)},{h:d,l:h}=_0(d,h,g,m),{Bh:f,Bl:u}={Bh:f^d,Bl:u^h},{Bh:f,Bl:u}={Bh:x0(f,u,24),Bl:k0(f,u,24)},re[2*t]=c,re[2*t+1]=l,re[2*e]=u,re[2*e+1]=f,re[2*r]=h,re[2*r+1]=d,re[2*n]=m,re[2*n+1]=g}function Hn(t,e,r,n,s,i){const o=s[i],a=s[i+1];let c=re[2*t],l=re[2*t+1],u=re[2*e],f=re[2*e+1],h=re[2*r],d=re[2*r+1],m=re[2*n],g=re[2*n+1],v=T0(c,u,o);l=I0(v,l,f,a),c=v|0,{Dh:g,Dl:m}={Dh:g^l,Dl:m^c},{Dh:g,Dl:m}={Dh:x0(g,m,16),Dl:k0(g,m,16)},{h:d,l:h}=_0(d,h,g,m),{Bh:f,Bl:u}={Bh:f^d,Bl:u^h},{Bh:f,Bl:u}={Bh:lE(f,u,63),Bl:fE(f,u,63)},re[2*t]=c,re[2*t+1]=l,re[2*e]=u,re[2*e+1]=f,re[2*r]=h,re[2*r+1]=d,re[2*n]=m,re[2*n+1]=g}function Y3(t,e={},r,n,s){if(ns(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 J3 extends Bc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,ns(e),ns(r),this.blockLen=e,this.outputLen=r,this.buffer=new Uint8Array(e),this.buffer32=Io(this.buffer)}update(e){ss(this),e=vn(e),Zr(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&&(Gn(s),this.compress(s,0,!1),Gn(s),this.pos=0);const l=Math.min(r-this.pos,i-c),u=o+c;if(l===r&&!(u%4)&&c+l<i){const f=new Uint32Array(a,u,Math.floor((i-c)/4));Gn(f);for(let h=0;c+r<i;h+=s.length,c+=r)this.length+=r,this.compress(f,h,!1);Gn(f);continue}n.set(e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){ss(this),kd(e,this);const{pos:r,buffer32:n}=this;this.finished=!0,Pr(this.buffer.subarray(r)),Gn(n),this.compress(n,0,!0),Gn(n);const s=Io(e);this.get().forEach((i,o)=>s[o]=fn(i))}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){const{buffer:r,length:n,finished:s,destroyed:i,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(r),e.destroyed=i,e.finished=s,e.length=n,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class Q3 extends J3{constructor(e={}){const r=e.dkLen===void 0?64:e.dkLen;super(128,r),this.v0l=rt[0]|0,this.v0h=rt[1]|0,this.v1l=rt[2]|0,this.v1h=rt[3]|0,this.v2l=rt[4]|0,this.v2h=rt[5]|0,this.v3l=rt[6]|0,this.v3h=rt[7]|0,this.v4l=rt[8]|0,this.v4h=rt[9]|0,this.v5l=rt[10]|0,this.v5h=rt[11]|0,this.v6l=rt[12]|0,this.v6h=rt[13]|0,this.v7l=rt[14]|0,this.v7h=rt[15]|0,Y3(r,e,64,16,16);let{key:n,personalization:s,salt:i}=e,o=0;if(n!==void 0&&(n=vn(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=vn(i);const a=Io(i);this.v4l^=fn(a[0]),this.v4h^=fn(a[1]),this.v5l^=fn(a[2]),this.v5h^=fn(a[3])}if(s!==void 0){s=vn(s);const a=Io(s);this.v6l^=fn(a[0]),this.v6h^=fn(a[1]),this.v7l^=fn(a[2]),this.v7h^=fn(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:l,v4h:u,v5l:f,v5h:h,v6l:d,v6h:m,v7l:g,v7h:v}=this;return[e,r,n,s,i,o,a,c,l,u,f,h,d,m,g,v]}set(e,r,n,s,i,o,a,c,l,u,f,h,d,m,g,v){this.v0l=e|0,this.v0h=r|0,this.v1l=n|0,this.v1h=s|0,this.v2l=i|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=u|0,this.v5l=f|0,this.v5h=h|0,this.v6l=d|0,this.v6h=m|0,this.v7l=g|0,this.v7h=v|0}compress(e,r,n){this.get().forEach((c,l)=>re[l]=c),re.set(rt,16);let{h:s,l:i}=A0(BigInt(this.length));re[24]=rt[8]^i,re[25]=rt[9]^s,n&&(re[28]=~re[28],re[29]=~re[29]);let o=0;const a=X3;for(let c=0;c<12;c++)Dn(0,4,8,12,e,r+2*a[o++]),Hn(0,4,8,12,e,r+2*a[o++]),Dn(1,5,9,13,e,r+2*a[o++]),Hn(1,5,9,13,e,r+2*a[o++]),Dn(2,6,10,14,e,r+2*a[o++]),Hn(2,6,10,14,e,r+2*a[o++]),Dn(3,7,11,15,e,r+2*a[o++]),Hn(3,7,11,15,e,r+2*a[o++]),Dn(0,5,10,15,e,r+2*a[o++]),Hn(0,5,10,15,e,r+2*a[o++]),Dn(1,6,11,12,e,r+2*a[o++]),Hn(1,6,11,12,e,r+2*a[o++]),Dn(2,7,8,13,e,r+2*a[o++]),Hn(2,7,8,13,e,r+2*a[o++]),Dn(3,4,9,14,e,r+2*a[o++]),Hn(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],Pr(re)}destroy(){this.destroyed=!0,Pr(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const eB=EE(t=>new Q3(t)),bv=eB;function tB(t,e,r){const n=he.Address.serialize(t).toBytes(),s=he.TypeTag.serialize(e).toBytes(),i=he.u64().serialize(r.length).toBytes(),o=bv.create({dkLen:32});return o.update(new Uint8Array([240])),o.update(n),o.update(i),o.update(r),o.update(s),`0x${Fi(o.digest().slice(0,32))}`}const rB="object",nB="ID",sB="ascii",iB="String",oB="string",aB="String",cB="option",uB="Option";function lB(t){const e=typeof t.body=="object"&&"datatype"in t.body?t.body.datatype:null;return!!e&&Se(e.package)===Se("0x2")&&e.module==="tx_context"&&e.type==="TxContext"}function gd(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=gd(t.vector);return e?he.vector(e):null}if("datatype"in t){const e=Se(t.datatype.package);if(e===Se(W3)){if(t.datatype.module===sB&&t.datatype.type===iB||t.datatype.module===oB&&t.datatype.type===aB)return he.String;if(t.datatype.module===cB&&t.datatype.type===uB){const r=gd(t.datatype.typeParameters[0]);return r?he.vector(r):null}}if(e===Se(gv)&&t.datatype.module===rB&&t.datatype.type===nB)return he.Address}return null}function fB(t){return typeof t=="object"&&"Reference"in t?{ref:"&",body:xo(t.Reference)}:typeof t=="object"&&"MutableReference"in t?{ref:"&mut",body:xo(t.MutableReference)}:{ref:null,body:xo(t)}}function xo(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:xo(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(xo)}};if("TypeParameter"in t)return{typeParameter:t.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(t)}`)}const dB=50,hB=1000n,pB=5e10;function wv(t){return async function(r,n,s){return await wB(r,t),await bB(r,t),n.onlyTransactionKind||(await yB(r,t),await mB(r,t),await gB(r,t)),await s()}}async function yB(t,e){t.gasConfig.price||(t.gasConfig.price=String(await e.getReferenceGasPrice()))}async function mB(t,e){if(t.gasConfig.budget)return;const r=await e.dryRunTransactionBlock({transactionBlock:t.build({overrides:{gasData:{budget:String(pB),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=hB*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 gB(t,e){if(!t.gasConfig.payment){const n=(await e.getCoins({owner:t.gasConfig.owner||t.sender,coinType:Z3})).data.filter(s=>!t.inputs.find(o=>{var a;return(a=o.Object)!=null&&a.ImmOrOwnedObject?s.coinObjectId===o.Object.ImmOrOwnedObject.objectId:!1})).map(s=>({objectId:s.coinObjectId,digest:s.digest,version:s.version}));if(!n.length)throw new Error("No valid gas coins found for the transaction.");t.gasConfig.payment=n.map(s=>ze(as,s))}}async function bB(t,e){const r=t.inputs.filter(u=>{var f;return u.UnresolvedObject&&!(u.UnresolvedObject.version||(f=u.UnresolvedObject)!=null&&f.initialSharedVersion)}),n=[...new Set(r.map(u=>wn(u.UnresolvedObject.objectId)))],s=n.length?mu(n,dB):[],i=(await Promise.all(s.map(u=>e.multiGetObjects({ids:u,options:{showOwner:!0}})))).flat(),o=new Map(n.map((u,f)=>[u,i[f]])),a=Array.from(o).filter(([u,f])=>f.error).map(([u,f])=>JSON.stringify(f.error));if(a.length)throw new Error(`The following input objects are invalid: ${a.join(", ")}`);const c=i.map(u=>{if(u.error||!u.data)throw new Error(`Failed to fetch object: ${u.error}`);const f=u.data.owner,h=f&&typeof f=="object"?"Shared"in f?f.Shared.initial_shared_version:"ConsensusAddressOwner"in f?f.ConsensusAddressOwner.start_version:null:null;return{objectId:u.data.objectId,digest:u.data.digest,version:u.data.version,initialSharedVersion:h}}),l=new Map(n.map((u,f)=>[u,c[f]]));for(const[u,f]of t.inputs.entries()){if(!f.UnresolvedObject)continue;let h;const d=Se(f.UnresolvedObject.objectId),m=l.get(d);f.UnresolvedObject.initialSharedVersion??(m==null?void 0:m.initialSharedVersion)?h=Vt.SharedObjectRef({objectId:d,initialSharedVersion:f.UnresolvedObject.initialSharedVersion||(m==null?void 0:m.initialSharedVersion),mutable:vB(t,u)}):EB(t,u)&&(h=Vt.ReceivingRef({objectId:d,digest:f.UnresolvedObject.digest??(m==null?void 0:m.digest),version:f.UnresolvedObject.version??(m==null?void 0:m.version)})),t.inputs[t.inputs.indexOf(f)]=h??Vt.ObjectRef({objectId:d,digest:f.UnresolvedObject.digest??(m==null?void 0:m.digest),version:f.UnresolvedObject.version??(m==null?void 0:m.version)})}}async function wB(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(u=>u.$kind==="Input"?t.inputs[u.Input]:null).some(u=>(u==null?void 0:u.UnresolvedPure)||(u==null?void 0:u.UnresolvedObject))){const u=`${a.MoveCall.package}::${a.MoveCall.module}::${a.MoveCall.function}`;i.add(u),s.push(a.MoveCall)}}});const o=new Map;i.size>0&&await Promise.all([...i].map(async a=>{const[c,l,u]=a.split("::"),f=await e.getNormalizedMoveFunction({package:c,module:l,function:u});o.set(a,f.parameters.map(h=>fB(h)))})),s.length&&await Promise.all(s.map(async a=>{const c=o.get(`${a.package}::${a.module}::${a.function}`);if(!c)return;const u=c.length>0&&lB(c.at(-1))?c.slice(0,c.length-1):c;a._argumentTypes=u})),n.forEach(a=>{if(!a.MoveCall)return;const c=a.MoveCall,l=`${c.package}::${c.module}::${c.function}`,u=c._argumentTypes;if(u){if(u.length!==a.MoveCall.arguments.length)throw new Error(`Incorrect number of arguments for ${l}`);u.forEach((f,h)=>{var _,E;const d=c.arguments[h];if(d.$kind!=="Input")return;const m=r[d.Input];if(!m.UnresolvedPure&&!m.UnresolvedObject)return;const g=((_=m.UnresolvedPure)==null?void 0:_.value)??((E=m.UnresolvedObject)==null?void 0:E.objectId),v=gd(f.body);if(v){d.type="pure",r[r.indexOf(m)]=Vt.Pure(v.serialize(g));return}if(typeof g!="string")throw new Error(`Expect the argument to be an object id string, got ${JSON.stringify(g,null,2)}`);d.type="object";const S=m.UnresolvedPure?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:g}}:m;r[d.Input]=S})}})}function vB(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 EB(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=SB(s.MoveCall._argumentTypes[i])||r}}),r}function SB(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 vv(t,e){return!!(t.inputs.some(r=>r.UnresolvedObject||r.UnresolvedPure)||!e.onlyTransactionKind&&(!t.gasConfig.price||!t.gasConfig.budget||!t.gasConfig.payment))}async function AB(t,e,r){var i;if(kB(t),!vv(t,e))return await Lm(t),r();const n=xB(e);return(((i=n.core)==null?void 0:i.resolveTransactionPlugin())??wv(n))(t,e,async()=>{await Lm(t),await r()})}function Lm(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 xB(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 kB(t){for(const e of t.commands)switch(e.$kind){case"SplitCoins":e.SplitCoins.amounts.forEach(r=>{Dm(r,he.U64,t)});break;case"TransferObjects":Dm(e.TransferObjects.address,he.Address,t);break}}function Dm(t,e,r){if(t.$kind!=="Input")return;const n=r.inputs[t.Input];n.$kind==="UnresolvedPure"&&(r.inputs[t.Input]=Vt.Pure(e.serialize(n.UnresolvedPure.value)))}function _B(t){function e(r){return t(r)}return e.system=r=>{const n=r==null?void 0:r.mutable;return e(n!==void 0?Vt.SharedObjectRef({objectId:"0x5",initialSharedVersion:1,mutable:n}):{$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x5",initialSharedVersion:1}})},e.clock=()=>e(Vt.SharedObjectRef({objectId:"0x6",initialSharedVersion:1,mutable:!1})),e.random=()=>e(Vt.SharedObjectRef({objectId:"0x8",initialSharedVersion:1,mutable:!1})),e.denyList=r=>{const n=r==null?void 0:r.mutable;return e(n!==void 0?Vt.SharedObjectRef({objectId:"0x403",initialSharedVersion:1,mutable:n}):{$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x403",initialSharedVersion:1}})},e.option=({type:r,value:n})=>s=>s.moveCall({typeArguments:[r],target:`0x1::option::${n===null?"none":"some"}`,arguments:n===null?[]:[s.object(n)]}),e}function TB(t){function e(r,n){if(typeof r=="string")return t(Ao(r).serialize(n));if(r instanceof Uint8Array||$h(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(Ao(r)).serialize(n)),e.option=(r,n)=>t(he.option(Ao(r)).serialize(n)),e}function IB(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),bv(n,{dkLen:32})}function Hm(t){return Se(t).replace("0x","")}class Nt{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 Nt.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 Nt.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 Nt(ze(cc,e)):new Nt(ze(cc,M3(e)))}static getDigestFromBytes(e){const r=IB("TransactionData",e);return yu(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,l={...this.gasData,...r==null?void 0:r.gasConfig,...r==null?void 0:r.gasData};if(!c)throw new Error("Missing transaction sender");if(!l.budget)throw new Error("Missing gas budget");if(!l.payment)throw new Error("Missing gas payment");if(!l.price)throw new Error("Missing gas price");const u={sender:Hm(c),expiration:a||{None:!0},gasData:{payment:l.payment,owner:Hm(this.gasData.owner??c),price:BigInt(l.price),budget:BigInt(l.budget)},kind:{ProgrammableTransaction:{inputs:s,commands:i}}};return he.TransactionData.serialize({V1:u},{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 Nt.getDigestFromBytes(e)}snapshot(){return ze(cc,this)}shallowClone(){return new Nt({version:this.version,sender:this.sender,expiration:this.expiration,gasData:{...this.gasData},inputs:[...this.inputs],commands:[...this.commands]})}}function zm(t){if(typeof t=="string")return Se(t);if(t.Object)return t.Object.ImmOrOwnedObject?Se(t.Object.ImmOrOwnedObject.objectId):t.Object.Receiving?Se(t.Object.Receiving.objectId):Se(t.Object.SharedObject.objectId);if(t.UnresolvedObject)return Se(t.UnresolvedObject.objectId)}var Ev=t=>{throw TypeError(t)},Dh=(t,e,r)=>e.has(t)||Ev("Cannot "+r),it=(t,e,r)=>(Dh(t,e,"read from private field"),r?r.call(t):e.get(t)),ao=(t,e,r)=>e.has(t)?Ev("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Ya=(t,e,r,n)=>(Dh(t,e,"write to private field"),e.set(t,r),r),vu=(t,e,r)=>(Dh(t,e,"access private method"),r),ra,In,na,Kn,Gr,bd,wd,Sv,Av,Hh;const PB="/",OB={"Mvr-Source":`@mysten/sui@${y1}`};class BB{constructor({cache:e,url:r,pageSize:n=50,overrides:s}){ao(this,Gr),ao(this,ra),ao(this,In),ao(this,na),ao(this,Kn),Ya(this,ra,e),Ya(this,In,r),Ya(this,na,n),Ya(this,Kn,{packages:s==null?void 0:s.packages,types:s==null?void 0:s.types}),CB(it(this,Kn))}async resolvePackage({package:e}){return{package:await it(this,Gr,bd).load(e)}}async resolveType({type:e}){const r=[...vd(e)],n=await it(this,Gr,wd).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:Ed(e,s)}}async resolve({types:e=[],packages:r=[]}){var u,f,h;const n=new Set;for(const d of e??[])vd(d,n);const s=[...n],[i,o]=await Promise.all([s.length>0?it(this,Gr,wd).loadMany(s):[],r.length>0?it(this,Gr,bd).loadMany(r):[]]),a={...(u=it(this,Kn))==null?void 0:u.types};for(const[d,m]of s.entries()){const g=i[d];if(g instanceof Error)throw g;a[m]=g}const c={};for(const d of e??[]){const m=Ed(d,a);c[d]={type:m}}const l={};for(const[d,m]of(r??[]).entries()){const g=((h=(f=it(this,Kn))==null?void 0:f.packages)==null?void 0:h[m])??o[d];if(g instanceof Error)throw g;l[m]={package:g}}return{types:c,packages:l}}}ra=new WeakMap;In=new WeakMap;na=new WeakMap;Kn=new WeakMap;Gr=new WeakSet;bd=function(){return it(this,ra).readSync(["#mvrPackageDataLoader",it(this,In)??""],()=>{var r;const t=new P1(async n=>{if(!it(this,In))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await vu(this,Gr,Sv).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve package: ${i}`))}),e=(r=it(this,Kn))==null?void 0:r.packages;if(e)for(const[n,s]of Object.entries(e))t.prime(n,s);return t})};wd=function(){return it(this,ra).readSync(["#mvrTypeDataLoader",it(this,In)??""],()=>{var r;const t=new P1(async n=>{if(!it(this,In))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await vu(this,Gr,Av).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve type: ${i}`))}),e=(r=it(this,Kn))==null?void 0:r.types;if(e)for(const[n,s]of Object.entries(e))t.prime(n,s);return t})};Sv=async function(t){if(t.length===0)return{};const e=mu(t,it(this,na)),r={};return await Promise.all(e.map(async n=>{var i;const s=await vu(this,Gr,Hh).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};Av=async function(t){if(t.length===0)return{};const e=mu(t,it(this,na)),r={};return await Promise.all(e.map(async n=>{var i;const s=await vu(this,Gr,Hh).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};Hh=async function(t,e){if(!it(this,In))throw new Error("MVR Api URL is not set for the current client");const r=await fetch(`${it(this,In)}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...OB},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 CB(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(Se(r)))throw new Error(`Invalid package ID: ${r}`)}if(t!=null&&t.types)for(const[e,r]of Object.entries(t.types)){if(qs(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=qs(r);if(!vr(n.address))throw new Error(`Invalid type: ${r}`)}}function vd(t,e=new Set){if(typeof t=="string"&&!Ut(t))return e;const r=xv(t)?t:qs(t);Ut(r.address)&&e.add(`${r.address}::${r.module}::${r.name}`);for(const n of r.typeParams)vd(n,e);return e}function Ed(t,e){const r=xv(t)?t:qs(t),n=`${r.address}::${r.module}::${r.name}`,s=e[n];return kc({...r,address:s?s.split("::")[0]:r.address,typeParams:r.typeParams.map(i=>Ed(i,e))})}function Ut(t){return t.includes(PB)||t.includes("@")||t.includes(".sui")}function xv(t){return typeof t=="object"&&"address"in t&&"module"in t&&"name"in t&&"typeParams"in t}function $B(t){const e=new Set,r=new Set;for(const n of t.commands)switch(n.$kind){case"MakeMoveVec":n.MakeMoveVec.type&&Vm([n.MakeMoveVec.type]).forEach(o=>{r.add(o)});break;case"MoveCall":const s=n.MoveCall,i=s.package.split("::")[0];if(Ut(i)){if(!zt(i))throw new Error(`Invalid package name: ${i}`);e.add(i)}Vm(s.typeArguments??[]).forEach(o=>{r.add(o)});break}return{packages:[...e],types:[...r]}}function RB(t,e){var r;for(const n of t.commands){if((r=n.MakeMoveVec)!=null&&r.type){if(!Ut(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(Ut(o)&&!e.packages[o])throw new Error(`No address found for package: ${o}`);Ut(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(Ut(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 Vm(t){const e=new Set;for(const r of t)if(Ut(r)){if(!jO(r))throw new Error(`Invalid type with names: ${r}`);e.add(r)}return e}const NB=t=>async(e,r,n)=>{const s=$B(e);if(s.types.length===0&&s.packages.length===0)return n();const i=await UB(r).core.mvr.resolve({types:s.types,packages:s.packages});RB(e,i),await n()};function UB(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 kv=t=>{throw TypeError(t)},zh=(t,e,r)=>e.has(t)||kv("Cannot "+r),Q=(t,e,r)=>(zh(t,e,"read from private field"),r?r.call(t):e.get(t)),Dr=(t,e,r)=>e.has(t)?kv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Oe=(t,e,r,n)=>(zh(t,e,"write to private field"),e.set(t,r),r),nt=(t,e,r)=>(zh(t,e,"access private method"),r),ks,Bs,yn,Kr,or,ar,xr,Zn,le,Ge,_v,uc,lc,fc,_c,Sd,Vh,Tv,Iv;function hf(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 Pv=Symbol.for("@mysten/transaction");function Ov(t){return!!t&&typeof t=="object"&&t[Pv]===!0}const qm={buildPlugins:new Map,serializationPlugins:new Map},pf=Symbol.for("@mysten/transaction/registry");function co(){try{const t=globalThis;return t[pf]||(t[pf]=qm),t[pf]}catch{return qm}}const Bv=class Ad{constructor(){Dr(this,Ge),Dr(this,ks),Dr(this,Bs),Dr(this,yn,new Map),Dr(this,Kr,[]),Dr(this,or,[]),Dr(this,ar,new Set),Dr(this,xr,new Set),Dr(this,Zn,new Map),Dr(this,le),this.object=_B(r=>{var i,o;if(typeof r=="function")return this.object(this.add(r));if(typeof r=="object"&&pd(Ne,r))return r;const n=zm(r),s=Q(this,le).inputs.find(a=>n===zm(a));return(i=s==null?void 0:s.Object)!=null&&i.SharedObject&&typeof r=="object"&&((o=r.Object)!=null&&o.SharedObject)&&(s.Object.SharedObject.mutable=s.Object.SharedObject.mutable||r.Object.SharedObject.mutable),s?{$kind:"Input",Input:Q(this,le).inputs.indexOf(s),type:"object"}:nt(this,Ge,lc).call(this,"object",typeof r=="string"?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:Se(r)}}:r)});const e=co();Oe(this,le,new Nt),Oe(this,Bs,[...e.buildPlugins.values()]),Oe(this,ks,[...e.serializationPlugins.values()])}static fromKind(e){const r=new Ad;return Oe(r,le,Nt.fromKindBytes(typeof e=="string"?Gt(e):e)),Oe(r,Kr,Q(r,le).inputs.slice()),Oe(r,or,Q(r,le).commands.slice()),Oe(r,ar,new Set(Q(r,or).map((n,s)=>s))),r}static from(e){const r=new Ad;return Ov(e)?Oe(r,le,new Nt(e.getData())):typeof e!="string"||!e.startsWith("{")?Oe(r,le,Nt.fromBytes(typeof e=="string"?Gt(e):e)):Oe(r,le,Nt.restore(JSON.parse(e))),Oe(r,Kr,Q(r,le).inputs.slice()),Oe(r,or,Q(r,le).commands.slice()),Oe(r,ar,new Set(Q(r,or).map((n,s)=>s))),r}static registerGlobalSerializationPlugin(e,r){co().serializationPlugins.set(e,r??e)}static unregisterGlobalSerializationPlugin(e){co().serializationPlugins.delete(e)}static registerGlobalBuildPlugin(e,r){co().buildPlugins.set(e,r??e)}static unregisterGlobalBuildPlugin(e){co().buildPlugins.delete(e)}addSerializationPlugin(e){Q(this,ks).push(e)}addBuildPlugin(e){Q(this,Bs).push(e)}addIntentResolver(e,r){if(Q(this,yn).has(e)&&Q(this,yn).get(e)!==r)throw new Error(`Intent resolver for ${e} already exists`);Q(this,yn).set(e,r)}setSender(e){Q(this,le).sender=e}setSenderIfNotSet(e){Q(this,le).sender||(Q(this,le).sender=e)}setExpiration(e){Q(this,le).expiration=e?ze(yv,e):null}setGasPrice(e){Q(this,le).gasConfig.price=String(e)}setGasBudget(e){Q(this,le).gasConfig.budget=String(e)}setGasBudgetIfNotSet(e){Q(this,le).gasData.budget==null&&(Q(this,le).gasConfig.budget=String(e))}setGasOwner(e){Q(this,le).gasConfig.owner=e}setGasPayment(e){Q(this,le).gasConfig.payment=e.map(r=>ze(as,r))}get blockData(){return jm(Q(this,le).snapshot())}getData(){return Q(this,le).snapshot()}get[Pv](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:TB(e=>$h(e)?nt(this,Ge,lc).call(this,"pure",{$kind:"Pure",Pure:{bytes:e.toBase64()}}):nt(this,Ge,lc).call(this,"pure",pd(Um,e)?ze(Um,e):e instanceof Uint8Array?Vt.Pure(e):{$kind:"UnresolvedPure",UnresolvedPure:{value:e}}))}),this.pure}get gas(){return{$kind:"GasCoin",GasCoin:!0}}objectRef(...e){return this.object(Vt.ObjectRef(...e))}receivingRef(...e){return this.object(Vt.ReceivingRef(...e))}sharedObjectRef(...e){return this.object(Vt.SharedObjectRef(...e))}add(e){if(typeof e=="function"){if(Q(this,Zn).has(e))return Q(this,Zn).get(e);const r=nt(this,Ge,_v).call(this),n=e(r);if(!(n&&typeof n=="object"&&"then"in n))return Oe(this,ar,Q(r,ar)),Q(this,Zn).set(e,n),n;const s=nt(this,Ge,uc).call(this,{$kind:"$Intent",$Intent:{name:"AsyncTransactionThunk",inputs:{},data:{resultIndex:Q(this,le).commands.length,result:null}}});Q(this,xr).add(Promise.resolve(n).then(o=>{s.$Intent.data.result=o}));const i=hf(()=>s.$Intent.data.resultIndex);return Q(this,Zn).set(e,i),i}else nt(this,Ge,uc).call(this,e);return hf(Q(this,le).commands.length-1)}splitCoins(e,r){const n=ps.SplitCoins(typeof e=="string"?this.object(e):nt(this,Ge,_c).call(this,e),r.map(s=>typeof s=="number"||typeof s=="bigint"||typeof s=="string"?this.pure.u64(s):nt(this,Ge,fc).call(this,s)));return nt(this,Ge,uc).call(this,n),hf(Q(this,le).commands.length-1,r.length)}mergeCoins(e,r){return this.add(ps.MergeCoins(this.object(e),r.map(n=>this.object(n))))}publish({modules:e,dependencies:r}){return this.add(ps.Publish({modules:e,dependencies:r}))}upgrade({modules:e,dependencies:r,package:n,ticket:s}){return this.add(ps.Upgrade({modules:e,dependencies:r,package:n,ticket:this.object(s)}))}moveCall({arguments:e,...r}){return this.add(ps.MoveCall({...r,arguments:e==null?void 0:e.map(n=>nt(this,Ge,fc).call(this,n))}))}transferObjects(e,r){return this.add(ps.TransferObjects(e.map(n=>this.object(n)),typeof r=="string"?this.pure.address(r):nt(this,Ge,fc).call(this,r)))}makeMoveVec({type:e,elements:r}){return this.add(ps.MakeMoveVec({type:e,elements:r.map(n=>this.object(n))}))}serialize(){return JSON.stringify(jm(Q(this,le).snapshot()))}async toJSON(e={}){await this.prepareForSerialization(e);const r=this.isFullyResolved();return JSON.stringify(ze(q3,r?{...Q(this,le).snapshot(),digest:Q(this,le).getDigest()}:Q(this,le).snapshot()),(n,s)=>typeof s=="bigint"?s.toString():s,2)}async sign(e){const{signer:r,...n}=e,s=await this.build(n);return r.signTransaction(s)}isFullyResolved(){return!(!Q(this,le).sender||Q(this,xr).size>0||Q(this,le).commands.some(e=>e.$Intent)||vv(Q(this,le),{}))}async build(e={}){return await this.prepareForSerialization(e),await nt(this,Ge,Sd).call(this,e),Q(this,le).build({onlyTransactionKind:e.onlyTransactionKind})}async getDigest(e={}){return await this.prepareForSerialization(e),await nt(this,Ge,Sd).call(this,e),Q(this,le).getDigest()}async prepareForSerialization(e){var s;await nt(this,Ge,Tv).call(this),nt(this,Ge,Iv).call(this);const r=new Set;for(const i of Q(this,le).commands)i.$Intent&&r.add(i.$Intent.name);const n=[...Q(this,ks)];for(const i of r)if(!((s=e.supportedIntents)!=null&&s.includes(i))){if(!Q(this,yn).has(i))throw new Error(`Missing intent resolver for ${i}`);n.push(Q(this,yn).get(i))}n.push(NB()),await nt(this,Ge,Vh).call(this,n,e)}};ks=new WeakMap;Bs=new WeakMap;yn=new WeakMap;Kr=new WeakMap;or=new WeakMap;ar=new WeakMap;xr=new WeakMap;Zn=new WeakMap;le=new WeakMap;Ge=new WeakSet;_v=function(){const t=new Bv;return Oe(t,le,Q(this,le)),Oe(t,ks,Q(this,ks)),Oe(t,Bs,Q(this,Bs)),Oe(t,yn,Q(this,yn)),Oe(t,xr,Q(this,xr)),Oe(t,ar,new Set(Q(this,ar))),Oe(t,Zn,Q(this,Zn)),Q(this,Kr).push(Q(t,Kr)),Q(this,or).push(Q(t,or)),t};uc=function(t){const e=Q(this,le).commands.length;return Q(this,or).push(t),Q(this,ar).add(e),Q(this,le).commands.push(t),Q(this,le).mapCommandArguments(e,r=>{if(r.$kind==="Result"&&!Q(this,ar).has(r.Result))throw new Error(`Result { Result: ${r.Result} } is not available to use the current transaction`);if(r.$kind==="NestedResult"&&!Q(this,ar).has(r.NestedResult[0]))throw new Error(`Result { NestedResult: [${r.NestedResult[0]}, ${r.NestedResult[1]}] } is not available to use the current transaction`);if(r.$kind==="Input"&&r.Input>=Q(this,le).inputs.length)throw new Error(`Input { Input: ${r.Input} } references an input that does not exist in the current transaction`);return r}),t};lc=function(t,e){return Q(this,Kr).push(e),Q(this,le).addInput(t,e)};fc=function(t){return $h(t)?this.pure(t):nt(this,Ge,_c).call(this,t)};_c=function(t){if(typeof t=="function"){const e=this.add(t);return typeof e=="function"?nt(this,Ge,_c).call(this,e):ze(Ne,e)}return ze(Ne,t)};Sd=async function(t){if(!t.onlyTransactionKind&&!Q(this,le).sender)throw new Error("Missing transaction sender");await nt(this,Ge,Vh).call(this,[...Q(this,Bs),AB],t)};Vh=async function(t,e){const r=n=>{if(n>=t.length)return()=>{};const s=t[n];return async()=>{const i=r(n+1);let o=!1,a=!1;if(await s(Q(this,le),e,async()=>{if(o)throw new Error(`next() was call multiple times in TransactionPlugin ${n}`);o=!0,await i(),a=!0}),!o)throw new Error(`next() was not called in TransactionPlugin ${n}`);if(!a)throw new Error(`next() was not awaited in TransactionPlugin ${n}`)}};await r(0)(),Oe(this,Kr,Q(this,le).inputs.slice()),Oe(this,or,Q(this,le).commands.slice())};Tv=async function(){for(;Q(this,xr).size>0;){const t=Promise.all(Q(this,xr));Q(this,xr).clear(),Q(this,xr).add(t),await t,Q(this,xr).delete(t)}};Iv=function(){var o;const t=Q(this,le).commands,e=Q(this,le).inputs,r=Q(this,or).flat(1/0),n=Q(this,Kr).flat(1/0);if(r.length!==t.length)throw new Error("Unexpected number of commands found in transaction data");if(n.length!==e.length)throw new Error("Unexpected number of inputs found in transaction data");const s=r.filter(a=>{var c;return((c=a.$Intent)==null?void 0:c.name)!=="AsyncTransactionThunk"});Q(this,le).commands=s,Q(this,le).inputs=n,Oe(this,or,s),Oe(this,Kr,n),Oe(this,ar,new Set(s.map((a,c)=>c)));function i(a){var u;const c=t[a];if(((u=c.$Intent)==null?void 0:u.name)==="AsyncTransactionThunk"){const f=c.$Intent.data.result;if(f==null)throw new Error("AsyncTransactionThunk has not been resolved");return i(f.Result)}const l=s.indexOf(c);if(l===-1)throw new Error("Unable to find original index for command");return l}Q(this,le).mapArguments(a=>{if(a.$kind==="Input"){const c=n.indexOf(e[a.Input]);if(c===-1)throw new Error("Input has not been resolved");return{...a,Input:c}}else if(a.$kind==="Result"){const c=i(a.Result);return{...a,Result:c}}else if(a.$kind==="NestedResult"){const c=i(a.NestedResult[0]);return{...a,NestedResult:[c,a.NestedResult[1]]}}return a});for(const[a,c]of t.entries())if(((o=c.$Intent)==null?void 0:o.name)==="AsyncTransactionThunk")try{c.$Intent.data.resultIndex=i(a)}catch{}};let xd=Bv;const MB={mainnet:"https://mainnet.mvr.mystenlabs.com",testnet:"https://testnet.mvr.mystenlabs.com"};class FB extends j1{constructor(e){var r,n,s;super(e),this.core=this,this.mvr=new BB({cache:this.cache.scope("core.mvr"),url:((r=e.mvr)==null?void 0:r.url)??MB[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=tB(e.parentId,Ar.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=qs(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]:kc(s.typeParams[0]),bcs:e.name.bcs},value:{type:typeof s.typeParams[1]=="string"?s.typeParams[1]:kc(s.typeParams[1]),bcs:i.slice(gu+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 jB extends Error{}class Xn extends jB{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 LB(t){return{...Nt.fromBytes(t).snapshot(),bcs:t}}function DB(t){const e=he.TransactionEffects.parse(t);switch(e.$kind){case"V1":return HB({effects:e.V1});case"V2":return zB({bytes:t,effects:e.V2});default:throw new Error(`Unknown transaction effects version: ${e.$kind}`)}}function HB(t){throw new Error("V1 effects are not supported yet")}function zB({bytes:t,effects:e}){const r=e.changedObjects.map(([n,s])=>{var i,o,a,c,l,u;return{id:n,inputState:s.inputState.$kind==="Exist"?"Exists":"DoesNotExist",inputVersion:((i=s.inputState.Exist)==null?void 0:i[0][0])??null,inputDigest:((o=s.inputState.Exist)==null?void 0:o[0][1])??null,inputOwner:((a=s.inputState.Exist)==null?void 0:a[1])??null,outputState:s.outputState.$kind==="NotExist"?"DoesNotExist":s.outputState.$kind,outputVersion:s.outputState.$kind==="PackageWrite"?(c=s.outputState.PackageWrite)==null?void 0:c[0]:s.outputState.ObjectWrite?e.lamportVersion:null,outputDigest:s.outputState.$kind==="PackageWrite"?(l=s.outputState.PackageWrite)==null?void 0:l[1]:((u=s.outputState.ObjectWrite)==null?void 0:u[0])??null,outputOwner:s.outputState.ObjectWrite?s.outputState.ObjectWrite[1]:null,idOperation:s.idOperation.$kind}});return{bcs: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 Cv=t=>{throw TypeError(t)},$v=(t,e,r)=>e.has(t)||Cv("Cannot "+r),Ht=(t,e,r)=>($v(t,e,"read from private field"),r?r.call(t):e.get(t)),VB=(t,e,r)=>e.has(t)?Cv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),qB=(t,e,r,n)=>($v(t,e,"write to private field"),e.set(t,r),r),mt;class GB extends FB{constructor({jsonRpcClient:e,mvr:r}){super({network:e.network,base:e,mvr:r}),VB(this,mt),qB(this,mt,e)}async getObjects(e){const r=mu(e.objectIds,50),n=[];for(const s of r){const i=await Ht(this,mt).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(Gm(a.data))}return{objects:n}}async getOwnedObjects(e){const r=await Ht(this,mt).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 Gm(n.data)}),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getCoins(e){const r=await Ht(this,mt).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(ZB.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,mt).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,mt).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,mt).getTransactionBlock({digest:e.digest,options:{showRawInput:!0,showObjectChanges:!0,showRawEffects:!0,showEvents:!0,showEffects:!0},signal:e.signal});return{transaction:Wm(r)}}async executeTransaction(e){const r=await Ht(this,mt).executeTransactionBlock({transactionBlock:e.transaction,signature:e.signatures,options:{showRawEffects:!0,showEvents:!0,showObjectChanges:!0,showRawInput:!0,showEffects:!0},signal:e.signal});return{transaction:Wm(r)}}async dryRunTransaction(e){const r=xd.from(e.transaction),n=await Ht(this,mt).dryRunTransactionBlock({transactionBlock:e.transaction,signal:e.signal}),{effects:s,objectTypes:i}=WB({effects:n.effects,objectChanges:n.objectChanges});return{transaction:{digest:await r.getDigest(),epoch:null,effects:s,objectTypes:Promise.resolve(i),signatures:[],transaction:LB(e.transaction)}}}async getReferenceGasPrice(e){const r=await Ht(this,mt).getReferenceGasPrice({signal:e==null?void 0:e.signal});return{referenceGasPrice:String(r)}}async getDynamicFields(e){const r=await Ht(this,mt).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,mt).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,mt).resolveNameServiceNames(e)}resolveTransactionPlugin(){return wv(Ht(this,mt))}}mt=new WeakMap;function Gm(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:hi(t.owner)}}function hi(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 Wm(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=Nt.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:DB(new Uint8Array(t.rawEffects)),objectTypes:Promise.resolve(r),transaction:{...s,bcs:n},signatures:e.txSignatures}}function WB({bytes:t,effects:e,objectChanges:r}){var o;const n=[],s=[],i={};return r==null||r.forEach(a=>{var c,l,u,f;switch(a.type){case"published":n.push({id:a.packageId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"PackageWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:null,idOperation:"Created"});break;case"transferred":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:a.digest,inputOwner:{$kind:"AddressOwner",AddressOwner:a.sender},outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:hi(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:hi(a.owner),outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:hi(a.owner),idOperation:"None"}),i[a.objectId]=a.objectType;break;case"deleted":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:((l=(c=e.deleted)==null?void 0:c.find(h=>h.objectId===a.objectId))==null?void 0:l.digest)??null,inputOwner:null,outputState:"DoesNotExist",outputVersion:null,outputDigest:null,outputOwner:null,idOperation:"Deleted"}),i[a.objectId]=a.objectType;break;case"wrapped":n.push({id:a.objectId,inputState:"Exists",inputVersion:a.version,inputDigest:null,inputOwner:{$kind:"AddressOwner",AddressOwner:a.sender},outputState:"ObjectWrite",outputVersion:a.version,outputDigest:((f=(u=e.wrapped)==null?void 0:u.find(h=>h.objectId===a.objectId))==null?void 0:f.digest)??null,outputOwner:{$kind:"ObjectOwner",ObjectOwner:a.sender},idOperation:"None"}),i[a.objectId]=a.objectType;break;case"created":n.push({id:a.objectId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:a.version,outputDigest:a.digest,outputOwner:hi(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:hi(e.gasObject.owner),idOperation:"None"},eventsDigest:e.eventsDigest??null,dependencies:e.dependencies??[],lamportVersion:e.gasObject.reference.version,changedObjects:n,unchangedSharedObjects:s,auxiliaryDataDigest:null}}}const KB=he.struct("Balance",{value:he.u64()}),ZB=he.struct("Coin",{id:he.Address,balance:KB}),XB=Symbol.for("@mysten/SuiClient");class Km extends j1{constructor(e){super({network:e.network??"unknown"}),this.jsonRpc=this,this.transport=e.transport??new Q5({url:e.url}),this.core=new GB({jsonRpcClient:this,mvr:e.mvr})}get[XB](){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(Se(r)))throw new Error("Invalid Sui address");return e&&Ut(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(Se(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(Se(e)))throw new Error("Invalid Sui address");return r&&Ut(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(Se(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&&Ut(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&&Ut(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(Se(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&&Ut(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||!Xa(wn(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||!Xa(wn(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(!$m(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(!$m(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:gt(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(Se(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||!Xa(wn(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&&Ut(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(Ov(e.transactionBlock))e.transactionBlock.setSenderIfNotSet(e.sender),r=gt(await e.transactionBlock.build({client:this,onlyTransactionKind:!0}));else if(typeof e.transactionBlock=="string")r=e.transactionBlock;else if(e.transactionBlock instanceof Uint8Array)r=gt(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:gt(e.transactionBlock)]})}async getDynamicFields(e){if(!e.parentId||!Xa(wn(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=Qo(r.digest);return Fi(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=>NO(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 YB{constructor(e,r,n){this.client=new Km({url:Pm(n)}),this.url=e instanceof b.Url?e:new b.Url(e),this.account=r,this.network=n}get htlcActorAddress(){return"accounts"in this.account?this.account.accounts[0].address:this.account.toSuiAddress()}async initiate(e){var r,n,s;if(!e)return b.Err("Order is required");if(oe.isSuiOrderResponse(e))return this.initiateWithCreateOrderResponse(e);try{const{source_swap:i}=e,o=BigInt(i.amount),a=i.asset,c=i.redeemer,l=i.secret_hash,u=await ph(i.asset,this.url);if(!u.ok)return b.Err(u.error);const{tokenAddress:f}=u.val,h=new xd;h.setSender(this.htlcActorAddress);const[d]=h.splitCoins(h.gas,[o]);h.moveCall({target:`${Qf[this.network].packageId}::${Qf[this.network].moduleName}::initiate`,typeArguments:[f],arguments:[h.object(a),h.pure.address(this.htlcActorAddress),h.pure.address(c),h.pure.vector("u8",Buffer.from(l,"hex")),h.pure.u64(o),h.pure.u256(i.timelock),h.pure.vector("u8",Buffer.from("")),d,h.object(K3)]});const m=await h.build({client:this.client}),g=await this.client.dryRunTransactionBlock({transactionBlock:m});if(g.effects.status.status==="failure")return b.Err(`${g.effects.status.error}`);let v;if("features"in this.account?v=await((r=this.account.features[Xh.SuiSignAndExecuteTransaction])==null?void 0:r.signAndExecuteTransaction({transaction:h,account:this.account.accounts[0],chain:`sui:${this.network}`})):v=await this.client.signAndExecuteTransaction({signer:this.account,transaction:h,options:{showEffects:!0}}),!v)return b.Err("Failed to initiate");const S=await this.client.waitForTransaction({digest:v.digest,options:{showEffects:!0}});return((n=S.effects)==null?void 0:n.status.status)==="failure"?b.Err(`Failed to initiate: ${(s=S.effects)==null?void 0:s.status.error}`):b.Ok(S.digest)}catch(i){return b.Err(i)}}async redeem(e,r){try{const n=await b.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:e.order_id,secret:r,perform_on:"Destination"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return n.error?b.Err(n.error):n.result?b.Ok(n.result):b.Err("Redeem: No result found")}catch(n){return b.Err(String(n))}}async initiateWithCreateOrderResponse(e){var a,c,l;const{ptb_bytes:r}=e,s=await new Km({url:Pm("testnet")}).getReferenceGasPrice(),i=1e7,o=xd.fromKind(new Uint8Array(r));o.setSender(this.htlcActorAddress),o.setGasPrice(s),o.setGasBudget(i);try{let u;if("features"in this.account?u=await((a=this.account.features[Xh.SuiSignAndExecuteTransaction])==null?void 0:a.signAndExecuteTransaction({transaction:o,account:this.account.accounts[0],chain:`sui:${this.network}`})):u=await this.client.signAndExecuteTransaction({signer:this.account,transaction:o,options:{showEffects:!0}}),!u)return b.Err("Failed to initiate");const f=await this.client.waitForTransaction({digest:u.digest,options:{showEffects:!0}});return((c=f.effects)==null?void 0:c.status.status)==="failure"?b.Err(`Failed to initiate: ${(l=f.effects)==null?void 0:l.status.error}`):b.Ok(f.digest)}catch(u){return b.Err(String(u))}}async refund(){return b.Err("Refund is taken care of by the relayer")}}const JB=t=>{if(t)if(typeof t=="string"){const e=b.DigestKey.from(t);if(!e.ok)throw new Error(e.error);return e.val}else return t},Zm=t=>typeof t=="string"?new b.ApiKey(t):t;var ms=(t=>(t.Created="Created",t.InitiateDetected="Initiate Detected",t.Initiated="Initiated",t.AwaitingRedeem="Awaiting Redeem",t.RedeemDetected="Redeem Detected",t.Redeemed="Redeemed",t.AwaitingRefund="Awaiting Refund",t.RefundDetected="Refund Detected",t.Refunded="Refunded",t.Expired="Expired",t))(ms||{});const qh=t=>{const{created_at:e,source_swap:r,destination_swap:n}=t;if(n.redeem_tx_hash)return Number(n.redeem_block_number)||oe.isBitcoin(n.chain)?"Redeemed":"Redeem Detected";if(oe.isBitcoin(n.chain)&&r.redeem_tx_hash&&!n.redeem_tx_hash)return"Redeemed";if(r.refund_tx_hash)return Number(r.refund_block_number)?"Refunded":"Refund Detected";if(n.refund_tx_hash)return"Awaiting Refund";const s=Rv(new Date(e),1);return n.initiate_tx_hash?"Awaiting Redeem":r.initiate_tx_hash?s?"Awaiting Refund":Number(r.initiate_block_number)?"Initiated":"Initiate Detected":s?"Expired":"Created"},Rv=(t,e=1)=>{const r=new Date,n=new Date(t);return n.setHours(n.getHours()+e),r>n},Nv=t=>{const e=qh(t);return e==="Redeemed"||e==="Refunded"||e==="Expired"};var Xe=(t=>(t.Initiate="Initiate",t.PostRefundSACP="PostRefundSACP",t.Redeem="Redeem",t.Refund="Refund",t.Idle="Idle",t))(Xe||{});const Uv=t=>{const{source_swap:e,destination_swap:r}=t;return r.redeem_tx_hash&&Number(r.redeem_block_number)||e.refund_tx_hash&&Number(e.refund_block_number)?"Idle":!r.refund_tx_hash&&r.initiate_tx_hash?"Redeem":"Idle"};class QB{constructor(e={}){const r={stdTTL:e.ttl?e.ttl/1e3:3600,checkperiod:600};this.cache=new Kv(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 sa,ia,oa,Ye,Ti,Yn;class e8{constructor(e,r,n,s,i,o){ls(this,sa);ls(this,ia);ls(this,oa);ls(this,Ye);ls(this,Ti);ls(this,Yn);this.isBackgroundServiceRunning=!1,this.executorStop=null,this.htlcs=r,this.events=o,fs(this,sa,e),fs(this,ia,n),fs(this,oa,Ui.fromDigestKey(e.digestKey)),fs(this,Ye,new QB),fs(this,Ti,s),fs(this,Yn,i)}async getAddressesFromHTLCs(){var n,s,i,o;const e=new Set;if([(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].filter(a=>!!a&&a.length>0).forEach(a=>e.add(a.toLowerCase())),this.htlcs.bitcoin)try{const a=await this.htlcs.bitcoin.htlcActorAddress();a&&a.length>0&&e.add(a.toLowerCase())}catch{}return Array.from(e)}startBackgroundService(e=5e3,r){this.isBackgroundServiceRunning||this.executorStop||(this.isBackgroundServiceRunning=!0,(async()=>{try{if(r){this.stopBackgroundService();return}const n=await this.execute(e);n&&(this.executorStop=n)}catch(n){console.error("Error starting background executor:",n),this.isBackgroundServiceRunning=!1}})())}stopBackgroundService(){if(this.executorStop){try{this.executorStop()}catch{console.error("Error stopping background executor")}this.executorStop=null}this.isBackgroundServiceRunning=!1}async execute(e=5e3){const r=await this.getAddressesFromHTLCs();r.length===0&&r.push(Ie(this,sa).userId.toLowerCase());let n=!1,s=null;const i=async()=>{if(!n){n=!0;try{const o=r.map(async u=>{try{const f=await Ie(this,ia).getOrders({address:u,status:oe.OrderLifecycle.pending,per_page:500});return f.ok?f.val.data:(this.events.emit("error",{},`Failed to fetch orders for address ${u}: ${f.error}`),[])}catch(f){return this.events.emit("error",{},`Failed to fetch orders for address ${u}: ${f}`),[]}}),a=await Promise.all(o),c=new Map;for(const u of a)for(const f of u)c.set(f.order_id,f);const l=Array.from(c.values()).map(u=>({...u,status:qh(u)}));this.events.emit("onPendingOrdersChanged",l),await this.processOrderActions(l)}finally{n=!1}}};return await i(),s=setInterval(i,e),()=>{s&&clearInterval(s)}}async processOrderActions(e){const r=new Set([ms.InitiateDetected,ms.AwaitingRefund,ms.Initiated,ms.RefundDetected,ms.Refunded,ms.Expired]),n=e.map(async s=>{try{oe.isBitcoin(s.source_swap.chain)&&r.has(s.status)&&!Nv(s)&&await this.postRefundSACP(s),Uv(s)===Xe.Redeem&&await this.handleRedeemAction(s)}catch(i){this.events.emit("error",s,`Error processing order ${s.order_id}: ${i}`)}});await Promise.all(n)}async handleRedeemAction(e){const r=await Ie(this,oa).generateSecret(e.nonce);if(!r.ok){this.events.emit("error",e,r.error);return}const n=b.trim0x(r.val.secretHash),s=b.trim0x(e.source_swap.secret_hash);if(n!==s){this.events.emit("log",e.order_id,"skipping redeem: secret hash mismatch");return}const i=r.val.secret,o=oe.getBlockchainType(e.destination_swap.chain),c={[oe.BlockchainType.evm]:()=>this.evmRedeem(e,i),[oe.BlockchainType.bitcoin]:()=>this.btcRedeem(e,i),[oe.BlockchainType.starknet]:()=>this.starknetRedeem(e,i),[oe.BlockchainType.solana]:()=>this.solRedeem(e,i),[oe.BlockchainType.sui]:()=>this.suiRedeem(e,i)}[o];c?await c():this.events.emit("error",e,`Unsupported chain: ${e.destination_swap.chain}`)}async evmRedeem(e,r){if(this.events.emit("log",e.order_id,"executing evm redeem"),Ie(this,Ye).getOrderExecution(e,Xe.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.evm){this.events.emit("error",e,"EVM HTLC is required");return}const s=await this.htlcs.evm.redeem(e,r);if(!s.ok){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Ie(this,Ye).setOrderExecution(e,Xe.Redeem,e.destination_swap.redeem_tx_hash);return}Ie(this,Ye).setOrderExecution(e,Xe.Redeem,s.val),this.events.emit("success",e,Xe.Redeem,s.val)}async starknetRedeem(e,r){if(this.events.emit("log",e.order_id,"executing starknet redeem"),Ie(this,Ye).getOrderExecution(e,Xe.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.starknet){this.events.emit("error",e,"Starknet HTLC is required");return}const s=await this.htlcs.starknet.redeem(e,r);if(!s.ok){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Ie(this,Ye).setOrderExecution(e,Xe.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Ie(this,Ye).setOrderExecution(e,Xe.Redeem,s.val),this.events.emit("success",e,Xe.Redeem,s.val))}async solRedeem(e,r){if(this.events.emit("log",e.order_id,"executing sol redeem"),Ie(this,Ye).getOrderExecution(e,Xe.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.solana){this.events.emit("error",e,"Solana HTLC is required");return}const s=await this.htlcs.solana.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Ie(this,Ye).setOrderExecution(e,Xe.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Ie(this,Ye).setOrderExecution(e,Xe.Redeem,s.val),this.events.emit("success",e,Xe.Redeem,s.val))}async suiRedeem(e,r){if(this.events.emit("log",e.order_id,"executing sui redeem"),Ie(this,Ye).getOrderExecution(e,Xe.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.sui){this.events.emit("error",e,"Sui HTLC is required");return}const s=await this.htlcs.sui.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Ie(this,Ye).setOrderExecution(e,Xe.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Ie(this,Ye).setOrderExecution(e,Xe.Redeem,s.val),this.events.emit("success",e,Xe.Redeem,s.val))}async btcRedeem(e,r){var a,c;const n=(a=this.htlcs.bitcoin)==null?void 0:a.getProvider();if(!n){this.events.emit("error",e,"Bitcoin provider not found");return}const s=Ie(this,Ye).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 l=await(await n).getTransaction(e.destination_swap.redeem_tx_hash);let u=!1;for(const f of l.vin)if(f.txid===i){u=!0;break}if(u){this.events.emit("log",e.order_id,"already a valid redeem");let f=0;try{const[h]=await(await n).getTransactionTimes([e.destination_swap.redeem_tx_hash]);h!==0&&(f=h)}catch{f=Date.now()}Ie(this,Ye).setBitcoinRedeem(e.order_id,{redeemedFromUTXO:i,redeemedAt:f,redeemTxHash:e.destination_swap.redeem_tx_hash});return}o=!0}catch(l){if(l.message.includes("Transaction not found"))o=!0;else{this.events.emit("error",e,"Failed to get redeem tx: "+l);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 l=await this.htlcs.bitcoin.getRedeemHex(e,b.trim0x(r),o?[i]:[]);if(!l.ok){this.events.emit("error",e,"Failed to get redeem hex");return}const u=await this.broadcastRedeemTx(l.val,e.order_id);if(!u.ok){this.events.emit("error",e,u.error||"Failed to broadcast redeem tx");return}o?(this.events.emit("log",e.order_id,"rbf: btc redeem success"),this.events.emit("rbf",e,u.val)):this.events.emit("success",e,Xe.Redeem,u.val),Ie(this,Ye).setBitcoinRedeem(e.order_id,{redeemedFromUTXO:i,redeemedAt:Date.now(),redeemTxHash:u.val})}catch(l){this.events.emit("error",e,"Failed btc redeem: "+l)}}async postRefundSACP(e){if(e.source_swap.delegate)try{if(!this.htlcs.bitcoin){this.events.emit("error",e,"Bitcoin HTLC is required");return}const n=await Ie(this,Ti).getAuthHeaders();if(n.error){this.events.emit("error",e,"Failed to get auth headers: "+n.error);return}const s=await b.Fetcher.post(new b.Url(Ie(this,Yn).baseurl).endpoint("relayer/bitcoin/instant-refund-hash"),{body:JSON.stringify({order_id:e.order_id}),headers:{"Content-Type":"application/json",...n.val}});if(s.error||!s.result){this.events.emit("error",e,"Failed to get hash while posting instant refund SACP: "+s.error);return}const i=await this.htlcs.bitcoin.generateInstantRefundSACPWithHash(s.result),o=new b.Url(Ie(this,Yn).baseurl).endpoint("relayer/bitcoin/instant-refund");(await b.Fetcher.post(o,{headers:{"Content-Type":"application/json",...n.val},body:JSON.stringify({order_id:e.order_id,signatures:i.val})})).ok&&Ie(this,Ye).setSacpCache(e.order_id,{initTxHash:e.source_swap.initiate_tx_hash})}catch(n){this.events.emit("error",e,"Failed to generate and post SACP: "+n);return}}async broadcastRedeemTx(e,r){try{if(!Ie(this,Yn))return b.Err("API not found");const n=new b.Url(Ie(this,Yn).relayer).endpoint("/bitcoin/redeem "),s=await Ie(this,Ti).getAuthHeaders(),o=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...s.val},body:JSON.stringify({redeem_tx_bytes:e,order_id:r})})).json();return o.status==="Ok"&&o.result?b.Ok(o.result):b.Err(o.error)}catch(n){return b.Err("Failed to broadcast redeem tx: "+n)}}}sa=new WeakMap,ia=new WeakMap,oa=new WeakMap,Ye=new WeakMap,Ti=new WeakMap,Yn=new WeakMap;const yf=(t,e,r,n)=>`m/${t}'/${e===qt.Mainnet?0:1}'/${r}'/0/${n??0}`,Mv={bip44:(t,e,r)=>yf("44",t,r??0,e),bip49:(t,e,r)=>yf("49",t,r??0,e),bip84:(t,e,r)=>yf("84",t,r??0,e)};function ko(t){if(t===qt.Mainnet)return pe.networks.bitcoin;if(t===qt.Testnet)return pe.networks.testnet;if(t===qt.Regtest)return pe.networks.regtest;throw new Error("Invalid network")}function t8(t,e,r){if(!Yh.validateMnemonic(t))throw new Error("Invalid mnemonic");const n=(r==null?void 0:r.path)??Mv.bip44(e,(r==null?void 0:r.index)??0),s=Zv.BIP32Factory(cr).fromSeed(Yh.mnemonicToSeedSync(t));return r8(s,n)}const r8=(t,e)=>{const r=t.derivePath(e).privateKey;if(!r)throw new Error("Unable to derive private key from mnemonic");return r.toString("hex")},uo={p2wpkh:"p2wpkh","p2wpkh-p2sh":"p2wpkh-p2sh"},dc={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 Cs{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 Jh.mixed().oneOf(["segwitV0","segwitV1","p2shSignature"]).required().validate(r),i=await Jh.mixed().oneOf(Object.values(dc)).required().validate(parseInt(n));return new Cs(s,i)}}const gs={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}`},go={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"},n8=(t,e,r=!1)=>{const n=o=>{try{o=pe.address.fromBech32(o).data.toString("hex")}catch(a){if(rd(a))(a.message.includes("Mixed-case string")||a.message.includes("too short"))&&(o=pe.address.fromBase58Check(o).hash.toString("hex"));else throw new Error(String(a))}return o},s=pe.script.fromASM(`
89
- OP_IF
90
- OP_SHA256
91
- ${t.secretHash}
92
- OP_EQUALVERIFY
93
- OP_DUP
94
- OP_HASH160
95
- ${n(t.recipientAddress.address)}
96
- OP_ELSE
97
- ${pe.script.number.encode(t.expiryBlocks).toString("hex")}
98
- OP_CHECKSEQUENCEVERIFY
99
- OP_DROP
100
- OP_DUP
101
- OP_HASH160
102
- ${n(t.refundAddress.address)}
103
- OP_ENDIF
104
- OP_EQUALVERIFY
105
- OP_CHECKSIG
106
- `.trim().replace(/\s+/g," ")),i=pe.payments[r?"p2sh":"p2wsh"]({redeem:{output:s},network:e});if(!i.address)throw new Error("Could not build address");return{script:s,address:i.address}},_o={P2SH:"p2sh",P2WSH:"p2wsh",P2TR:"p2tr"};var Fv=(t=>(t[t.Bitcoin=0]="Bitcoin",t[t.EVM=1]="EVM",t))(Fv||{});class s8{addSignatureSegwitV0(e=dc.ALL){return new Cs("segwitV0",e)}addSignatureP2sh(e=dc.ALL){return new Cs("p2shSignature",e)}addSignatureSegwitV1(e=dc.ALL){return new Cs("segwitV1",e)}chain(){return Fv.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(td(o.txid),a,s==null?void 0:s.nSequence)}return e}async suggestFee(e,r){const n=await this.getAddress();return(await this.getProvider()).suggestFee(n,e,r)}async toOutputScript(e){return pe.address.toOutputScript(e,await this.getNetwork())}totalValueFromUTXOs(e){return e.reduce((r,n)=>r+n.value,0)}async scriptToAddress(e){const r=pe.payments.p2wsh({redeem:{output:e},network:await this.getNetwork()});if(!r.address)throw new Error("Could not generate p2wsh address");return r.address}async newSwap(e){if(e.secretHash=b.trim0x(e.secretHash),e.secretHash.length!==64)throw new Error(go.INVALID_SECRET_HASH);const{script:r,address:n}=n8(e,await this.getNetwork());return new i8(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 i8{constructor(e,r){if(r.secretHash=b.trim0x(r.secretHash),r.secretHash.length!==64)throw new Error(go.INVALID_SECRET_HASH);this.wallet=e,this.swap=r}id(){return this.swap.scriptAddress}async init(){return this.wallet.send(this.swap.scriptAddress,+this.swap.amount.toString())}async redeem(e,r){e=b.trim0x(e);const n=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),Buffer.from(e,"hex"),pe.script.number.encode(1),this.swap.redeemScript],s=pe.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!s)throw new Error("Could not generate p2wsh address for redeem script");try{return await this.wallet.spend(this.swap.redeemScript,s,{witness:n,toAddress:r})}catch(i){throw rd(i)?i.message.includes("OP_EQUALVERIFY")?new Error(go.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 rd(n)?n.message.includes("OP_EQUALVERIFY")?new Error(go.INVALID_PUBKEY):n.message.includes("BIP")?new Error(go.ORDER_NOT_EXPIRED):new Error(n.message):new Error(String(n))}}}pe.initEccLib(cr);class _s extends s8{constructor({privateKey:e,provider:r,pkPath:n,pkType:s}){const i=Ja.ECPairFactory(cr),o=ko(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=Mv.bip84(r.getNetwork(),n==null?void 0:n.index),i=t8(e,r.getNetwork(),{path:s});return new _s({privateKey:i,provider:r,pkType:uo.p2wpkh,pkPath:s})}static fromPrivateKey(e,r,n){return new _s({privateKey:e,provider:r,pkType:(n==null?void 0:n.pkType)??uo.p2wpkh,pkPath:(n==null?void 0:n.pkPath)??"unknown"})}static createRandom(e){const r=Ja.ECPairFactory(cr),n=ko(e.getNetwork()),s=r.makeRandom({network:n});if(!s.privateKey)throw new Error("Failed to create random key");return new _s({privateKey:s.privateKey.toString("hex"),provider:e,pkType:uo.p2wpkh,pkPath:"unknown"})}static fromWIF(e,r,n){const s=Ja.ECPairFactory(cr),i=ko(r.getNetwork()),o=s.fromWIF(e,i);if(!o.privateKey)throw new Error("Invalid WIF");return _s.fromPrivateKey(o.privateKey.toString("hex"),r,n)}walletConfig(){return{network:this.provider.getNetwork(),path:this.path,addressType:this.pkType}}async spend(e,r,{toAddress:n,fee:s,nSequence:i,unlockScript:o,witness:a}){var h;const c=this.getScriptType(r,this.network),l=await this.provider.getBalance(r);if(l===0)throw new Error(gs.SCRIPT_NOT_FUNDED);let u=new pe.Transaction;if(u.version=2,s??(s=await this.provider.suggestFee(r,l,Si.FAST)),s>l)throw new Error(gs.FEE_EXCEEDS_AMOUNT(s,l));const f=await this.provider.getUTXOs(r);u=await this.addAllInputs(u,r,this.provider,{nSequence:i,utxos:f}),u.addOutput(await this.toOutputScript(n??await this.getAddress()),l-s);for(let d=0;d<u.ins.length;d++)if(c===_o.P2SH){if(!o)throw new Error("Unlock script is required for p2sh");const m=[];for(const v of o)if(v instanceof Cs){const S=v.sigHashType,_=u.hashForSignature(d,e,S);m.push(pe.script.signature.encode(Buffer.from(await this.sign(_.toString("hex")),"hex"),S))}else m.push(v);const g=(h=pe.payments.p2sh({redeem:{input:pe.script.compile(m),output:e},network:this.network}).redeem)==null?void 0:h.input;u.setInputScript(d,g)}else if(c===_o.P2WSH){if(!a)throw new Error("Witness is required for p2wsh");const m=[];for(const g of a)if(g instanceof Cs){const v=g.sigHashType,S=u.hashForWitnessV0(d,e,f[d].value,v);m.push(pe.script.signature.encode(Buffer.from(await this.sign(S.toString("hex")),"hex"),v))}else m.push(g);u.setWitness(d,m)}else throw new Error("Invalid script type "+c);return this.provider.broadcast(u.toHex())}async getAddress(){if(this.pkType===uo["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())}async 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,Si.FAST)),o>i)throw new Error(gs.FEE_EXCEEDS_AMOUNT(o,i));const a=await e.getUTXOs(n,i+o),c=a.reduce((f,h)=>f+h.value,0);if(c<i+o)throw new Error(gs.INSUFFICIENT_FUNDS(c,i+o));const l=new pe.Psbt({network:r});for(const f of a){const h=await e.getTransactionHex(f.txid);l.addInput({hash:td(f.txid),index:f.vout,nonWitnessUtxo:Buffer.from(h,"hex")})}const u=c-i-o;return l.addOutput({address:s,value:i}),u>546&&l.addOutput({address:n,value:u}),{txHex:l.toHex(),utxoCount:a.length}}async _send(e,r,n){var l;if(n||(n=await this.provider.suggestFee(await this.getAddress(),r,Si.FAST)),n>r)throw new Error(gs.FEE_EXCEEDS_AMOUNT(n,r));if(r<this.minAmt)throw new Error(gs.MIN_AMOUNT(this.minAmt));const s=await this.getAddress(),i=await this.provider.getUTXOs(s,r+n),o=i.reduce((u,f)=>u+f.value,0),a=new pe.Psbt({network:this.network});for(const u of i){const f=await this.provider.getTransactionHex(u.txid),h=await this.provider.getTransaction(u.txid);let d;this.pkType===uo["p2wpkh-p2sh"]&&(d={witnessUtxo:{script:Buffer.from(h.vout[u.vout].scriptpubkey,"hex"),value:u.value},redeemScript:(l=pe.payments.p2sh({redeem:pe.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network}).redeem)==null?void 0:l.output}),a.addInput({hash:td(u.txid),index:u.vout,nonWitnessUtxo:Buffer.from(f,"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 o8=t=>t.map(e=>e),a8=t=>{if(t===qt.Testnet)return c8;if(t===qt.Mainnet)return u8;throw new Error("Invalid network")},c8=["https://mempool.space/testnet4/api"],u8=["https://mempool.space/api","https://blockstream.info/api"],Xm=t=>t.sort((e,r)=>e.status.confirmed!=r.status.confirmed?e.status.confirmed?-1:1:r.value-e.value);class jv{constructor(e,r){this.cacheTimeout=2e3,this.utxosCache=new Map,this.APIs=r?o8([r]):a8(e),this.network=e}async getTxIndex(e,r){const n=this.APIs.map(i=>`${i}/tx/${e}`),{vout:s}=await b.Fetcher.getWithFallback(n);for(let i=0;i<s.length;i++)if(s[i].scriptpubkey_address===r)return i;throw new Error("failed to get tx index")}async broadcast(e){if(!/^[0-9a-fA-F]+$/.test(e))throw new Error("invalid tx hex");for(let r=0;r<5;r++)try{return b.Fetcher.postWithFallback(this.APIs.map(n=>`${n}/tx`),{body:e})}catch(n){if(r===4)throw n;await new Promise(s=>setTimeout(s,500))}throw new Error("failed to broadcast tx")}async getBalance(e){return(await this.getUTXOs(e)).reduce((r,n)=>r+n.value,0)}setTimeoutForCache(e){this.cacheTimeout=e}async getUTXOs(e,r){const n=this.utxosCache.get(e);if(n&&Date.now()-n.timestamp<this.cacheTimeout)return Ym(n.utxos,r);const s=await b.Fetcher.getWithFallback(this.APIs.map(i=>`${i}/address/${e}/utxo`),{signal:AbortSignal.timeout(5e3)});return this.utxosCache.set(e,{timestamp:Date.now(),utxos:s}),Ym(s,r)}async getTransactionHex(e){return b.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${e}/hex`))}async getTransaction(e){return b.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${e}`))}async getConfirmations(e){const r=await this.getTransaction(e);return!r.status.confirmed||!r.status.block_height?0:await this.getLatestTip()-r.status.block_height+1}async getFeeRates(){if(this.network===qt.Regtest)return{fastestFee:8,halfHourFee:7,hourFee:6,economyFee:4,minimumFee:2};let e="";this.network===qt.Testnet&&(e="testnet4/");const r=`https://mempool.space/${e}api/v1/fees/recommended`,n=`https://blockstream.info/${e}api/fee-estimates`,s=await b.Fetcher.getWithFallback([r,n],{signal:AbortSignal.timeout(5e3)});return"fastestFee"in s?s.fastestFee===1?{fastestFee:2,halfHourFee:2,hourFee:2,economyFee:2,minimumFee:2}:s:{fastestFee:s[1],halfHourFee:s[5],hourFee:s[10],economyFee:s[20],minimumFee:s[25]}}async getTransactions(e,r){const n=await b.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/address/${e}/txs`));if(r===rc.ALL)return n;if(r===rc.IN)return n.filter(s=>s.vout.find(i=>i.scriptpubkey_address===e));if(r===rc.OUT)return n.filter(s=>s.vin.find(i=>i.prevout.scriptpubkey_address===e));throw new Error("failed to get transactions: invalid bitcoin tx type")}getNetwork(){return this.network}async getLatestTip(){return b.Fetcher.getWithFallback(this.APIs.map(e=>`${e}/blocks/tip/height`))}async suggestFee(e,r,n){const i=(await this.getUTXOs(e,r)).length,o=2,a=await this.getFeeRates();return Math.floor(a[H_[n]]*1.05)*(i*70+o*31+10)}async getTransactionTimes(e){const r=e.map(s=>`txId[]=${s}`).join("&");return(await b.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/v1/transaction-times?${r}`))).map(s=>s*1e3)}}const Ym=(t,e)=>{if(Array.isArray(t)){if(e){const r=t.reduce((i,o)=>i+o.value,0);if(r<e)throw new Error(gs.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 Xm(s)}return Xm(t)}return[]};class l8 extends b.EventBroker{emit(e,...r){super.emit(e,...r)}}class Gh extends oe.Orderbook{constructor(e){const{api:r,network:n}=ed(e.environment);super(new b.Url(r.baseurl)),this.redeemServiceEnabled=!0,this.executeInterval=5e3,this.network=n,this._api=r,this._digestKey=JB(e.digestKey),this._auth=Zm(e.apiKey),this._quote=e.quote??new Dw(this._api.baseurl),this._htlcs=e.htlc??{},this._events=new l8,this._executor=this._digestKey?new e8(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.stopBackgroundService();else{if(!this._digestKey)throw new Error("Digest key is required for manual secret management");if(this._secretManager=Ui.fromDigestKey(this._digestKey.digestKey),!this._htlcs.bitcoin){const s=new jv(Hu(this.network));this._htlcs.bitcoin=new ky(_s.fromPrivateKey(this._digestKey.digestKey,s),ko(Hu(this.network)))}(n=this._executor)==null||n.startBackgroundService(this.executeInterval,this.redeemServiceEnabled)}return this}static fromWallets(e){const r=Zm(e.apiKey),{api:n,network:s}=ed(e.environment);if(!n)throw new Error("API not found, invalid environment "+e.environment);const i=e.wallets?{evm:e.wallets.evm?new Kw(n.baseurl,e.wallets.evm,r):void 0,starknet:e.wallets.starknet?new Qw(n.baseurl,e.wallets.starknet,s,r):void 0,solana:e.wallets.solana?new p1(e.wallets.solana,new b.Url(n.baseurl),s===b.Network.MAINNET?Yf.mainnet:Yf.testnet,{native:e.solanaProgramAddress&&e.solanaProgramAddress.native?e.solanaProgramAddress.native:Jf.mainnet.native,spl:e.solanaProgramAddress&&e.solanaProgramAddress.spl?e.solanaProgramAddress.spl:Jf.mainnet.spl},r):void 0,sui:e.wallets.sui?new YB(n.baseurl,e.wallets.sui,s===b.Network.MAINNET?b.Network.MAINNET:b.Network.TESTNET):void 0,bitcoin:e.wallets.bitcoin?new ky(e.wallets.bitcoin,ko(Hu(s))):void 0}:{};return new Gh({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 orderbook(){return this}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}async createSwap(e){const r=oe.ChainAsset.from(e.fromAsset).getBlockchainType(),n=await Y_(r,this._htlcs);if(!n.ok)return b.Err(n.error);const s=await this.createOrder(e);if(!s.ok)return b.Err(s.error);const i=s.val;switch(r){case oe.BlockchainType.evm:if(!this._htlcs.evm||i.type!==oe.BlockchainType.evm)return b.Err("Order type does not match EVM blockchain type");{const o=await this._htlcs.evm.initiate(i);if(!o.ok)return b.Err(`EVM HTLC initiation failed: ${o.error}`)}break;case oe.BlockchainType.solana:if(!this._htlcs.solana||i.type!==oe.BlockchainType.solana)return b.Err("Order type does not match Solana blockchain type");{const o=await this._htlcs.solana.initiate(i);if(!o.ok)return b.Err(`Solana HTLC initiation failed: ${o.error}`)}break;case oe.BlockchainType.starknet:if(!this._htlcs.starknet||i.type!==oe.BlockchainType.starknet)return b.Err("Order type does not match Starknet blockchain type");{const o=await this._htlcs.starknet.initiate(i);if(!o.ok)return b.Err(`Starknet HTLC initiation failed: ${o.error}`)}break;case oe.BlockchainType.sui:if(!this._htlcs.sui||i.type!==oe.BlockchainType.sui)return b.Err("Order type does not match Sui blockchain type");{const o=await this._htlcs.sui.initiate(i);if(!o.ok)return b.Err(`Sui HTLC initiation failed: ${o.error}`)}break;case oe.BlockchainType.bitcoin:if(!this._htlcs.bitcoin||i.type!==oe.BlockchainType.bitcoin)return b.Err("Order type does not match Bitcoin blockchain type");{const o=await this._htlcs.bitcoin.initiate(i);if(!o.ok)return b.Err(`Bitcoin HTLC initiation failed: ${o.error}`)}break;default:return b.Err("Unsupported blockchain type for swap initiation")}return b.Ok(i.order_id)}async createOrder(e,r){var g;if(b.hasKeys(e,["source","destination","nonce"]))return super.createOrder(e,r??this._auth);const n=e,s=await this.validateAndFillParams(n);if(!s.ok)return b.Err(s.error);const{sendAddress:i,receiveAddress:o}=s.val,a=Date.now().toString();let c;if(!this.redeemServiceEnabled){const v=await this.secretManager.generateSecret(a);if(!v.ok)return b.Err(v.error);c=v.val.secretHash}const l=(g=n.addresses)==null?void 0:g.bitcoin,u=oe.isBitcoin(oe.ChainAsset.from(n.fromAsset).getChain()),f=oe.isBitcoin(oe.ChainAsset.from(n.toAsset).getChain()),h=!u&&!f||!!c,d={source:{asset:oe.ChainAsset.from(n.fromAsset),owner:u?l??i:i,delegate:h&&u?i:null,amount:n.sendAmount},destination:{asset:oe.ChainAsset.from(n.toAsset),owner:f?l??o:o,delegate:h&&f?o:null,amount:n.receiveAmount},nonce:Number(a),...!this.redeemServiceEnabled&&c?{secret_hash:b.trim0x(c)}:{},affiliate_fees:X_(n.affiliateFee),slippage:50},m=await super.createOrder(d,this._auth);return m.ok?b.Ok(m.val):b.Err(m.error)}async validateAndFillParams(e){var c;if(!e.fromAsset||!e.toAsset)return b.Err("Source and destination assets are required for swap");const r=oe.ChainAsset.from(e.fromAsset),n=oe.ChainAsset.from(e.toAsset);if(r.getNetwork()!==n.getNetwork())return b.Err("Both assets should be on the same network (either mainnet or testnet)");const s=Jp(e.sendAmount);if(!s.ok)return b.Err(s.error);const i=Jp(e.receiveAmount);if(!i.ok)return b.Err(i.error);if(s<i)return b.Err("Send amount should be greater than receive amount");if((oe.isBitcoin(oe.ChainAsset.from(e.fromAsset).getChain())||oe.isBitcoin(oe.ChainAsset.from(e.toAsset).getChain()))&&!((c=e.addresses)!=null&&c.bitcoin))return b.Err("Bitcoin address in addresses is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const o=await Qp(r.getBlockchainType(),this._htlcs,e.addresses);if(!o.ok)return b.Err(o.error);const a=await Qp(n.getBlockchainType(),this._htlcs,e.addresses);return a.ok?b.Ok({sendAddress:o.val,receiveAddress:a.val}):b.Err(a.error)}on(e,r){return this._events.on(e,r),this}off(e,r){return this._events.off(e,r),this}}class f8{constructor(e,r,n){this.callData=new st.CallData(Zw),this.account=e,this.starknetProvider=new st.RpcProvider({nodeUrl:r||(n?Zo[n].nodeUrl:Zo.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 st.Contract(Jw,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=st.num.toHex(n),i=st.cairo.uint256(BigInt(e.source_swap.amount));try{const c=await Xw(this.account,s,e.source_swap.asset,BigInt(e.source_swap.amount),this.starknetProvider);if(c.error)return b.Err(c.error)}catch(c){return b.Err(`Allowance check failed: ${c}`)}const o=e.source_swap.secret_hash;if(!o)return b.Err("Invalid order: secret_hash is undefined");const a=await this.account.execute({contractAddress:e.source_swap.asset,entrypoint:"initiate",calldata:[e.source_swap.redeemer,BigInt(e.source_swap.timelock),i.low,i.high,...b.hexToU32Array(o)]});if(!a.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return b.Ok(a.transaction_hash)}catch(r){return b.Err(`HTLC Initiation Error: ${r}`)}}async redeem(e,r){try{const n=await this.getHTLCContract(e,!0),s=e.source_swap.chain.includes("starknet")?e.source_swap.swap_id:e.destination_swap.swap_id,i=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:st.CallData.compile({swap_id:s,secret:b.hexToU32Array(r)})});return i.transaction_hash?b.Ok(i.transaction_hash):b.Err("Failed to redeem HTLC transaction")}catch{return b.Err("HTLC Redeem Error")}}async refund(e){try{const r=e.source_swap.chain.includes("starknet")?e.source_swap.swap_id:e.destination_swap.swap_id,n=await this.getHTLCContract(e),s=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return s.transaction_hash?b.Ok(s.transaction_hash):b.Err("Failed to refund HTLC transaction")}catch{return b.Err("HTLC Refund Error")}}}class d8{constructor(e){if(this.provider=e,!e)throw new Error("Provider is required");this.provider=e,this.program=new ir.Program(ad,e)}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async initiate(e){if(!e)return b.Err("Order is required");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=Qn.from(e),o=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=ir.web3.PublicKey.findProgramAddressSync(o,this.program.programId)[0];const a=await this.program.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction(),c=await this.provider.sendAndConfirm(a);return c?b.Ok(c):b.Err("Failed to initiate HTLC transaction")}catch(r){return b.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(e,r){if(!e)return b.Err("Order is required");if(!r)return b.Err("Secret is required");const{secretHash:n}=Qn.from(e),s=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=ir.web3.PublicKey.findProgramAddressSync(s,this.program.programId)[0];try{const{redeemer:i}=Qn.from(e);if(!this.swapAccount)return b.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const o=await this.program.methods.redeem(h1(r)).accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey,redeemer:i}).transaction(),a=await this.provider.sendAndConfirm(o);return a?b.Ok(a):b.Err("Failed to redeem HTLC transaction")}catch(i){return b.Err(`Error redeeming swap: ${i instanceof Error?i.message:String(i)}`)}}async refund(e){if(!e)return b.Err("Order is required");const{secretHash:r}=Qn.from(e),n=[Buffer.from("swap_account"),Buffer.from(r)];this.swapAccount=ir.web3.PublicKey.findProgramAddressSync(n,this.program.programId)[0];try{if(console.log("Initiating refund for ::",e.source_swap.swap_id),!this.swapAccount)return b.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const s=await this.program.methods.refund().accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey}).transaction(),i=await this.provider.sendAndConfirm(s);return i?b.Ok(i):b.Err("Failed to refund HTLC transaction")}catch(s){return b.Err(`Error refunding swap: ${s instanceof Error?s.message:String(s)}`)}}}class h8{constructor(e,r){this.url=e.endpoint("blocknumbers").endpoint(r)}async fetchBlockNumbers(){try{const e=await b.Fetcher.get(this.url);return b.Ok(e)}catch(e){return b.Err("Failed to fetch block numbers",e)}}}var Lv=(t=>(t.Created="Created",t.Matched="Matched",t.InitiateDetected="InitiateDetected",t.Initiated="Initiated",t.CounterPartyInitiateDetected="CounterPartyInitiateDetected",t.CounterPartyInitiated="CounterPartyInitiated",t.RedeemDetected="RedeemDetected",t.Redeemed="Redeemed",t.CounterPartyRedeemDetected="CounterPartyRedeemDetected",t.CounterPartyRedeemed="CounterPartyRedeemed",t.Completed="Completed",t.CounterPartySwapExpired="CounterPartySwapExpired",t.Expired="Expired",t.RefundDetected="RefundDetected",t.Refunded="Refunded",t.CounterPartyRefundDetected="CounterPartyRefundDetected",t.CounterPartyRefunded="CounterPartyRefunded",t.Cancelled="Cancelled",t.DeadLineExceeded="DeadLineExceeded",t))(Lv||{}),Dv=(t=>(t.Idle="Idle",t.InitiateDetected="InitiateDetected",t.Initiated="Initiated",t.RedeemDetected="RedeemDetected",t.Redeemed="Redeemed",t.RefundDetected="RefundDetected",t.Refunded="Refunded",t.Expired="Expired",t))(Dv||{});class p8{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=>oe.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.startsWith(n+":")}if(r.startsWith("*:")){const n=r.slice(2);return e.endsWith(":"+n)}}return e.toString()===r}}function y8(t,e){const r={};for(const n of t)r[n.toString()]=e.getValidDestinations(n,t);return r}exports.API=tc;exports.BaseError=H;exports.BitcoinNetwork=qt;exports.BitcoinProvider=jv;exports.BitcoinWallet=_s;exports.BlockNumberFetcher=h8;exports.DEFAULT_AFFILIATE_ASSET=cw;exports.EvmRelay=Kw;exports.Garden=Gh;exports.HttpRequestError=wi;exports.OrderAction=Xe;exports.OrderStatus=Lv;exports.ParseOrderStatus=qh;exports.Quote=Dw;exports.RouteValidator=p8;exports.STARKNET_CONFIG=Zo;exports.SUI_CONFIG=Qf;exports.SecretManager=Ui;exports.SolanaHTLC=d8;exports.SolanaRelay=p1;exports.SolanaRelayerAddress=Yf;exports.StarknetHTLC=f8;exports.StarknetRelay=Qw;exports.SwapStatus=Dv;exports.botanixMainnet=Vw;exports.buildRouteMatrix=y8;exports.call=ya;exports.checkAllowance=vo;exports.checkAllowanceAndApprove=Xw;exports.concat=Kt;exports.constructOrderPair=uw;exports.decodeErrorResult=K0;exports.encodeAbiParameters=On;exports.evmToViemChainMap=au;exports.getChainNameFromChainId=Ww;exports.getUrl=Uc;exports.hyperliquid=Gw;exports.hyperliquidTestnet=qw;exports.isAddressEqual=pa;exports.isAllowanceSufficient=Yw;exports.isCompleted=Nv;exports.isDeadlinePassed=Rv;exports.isHex=Tr;exports.localBatchGatewayRequest=Kg;exports.localBatchGatewayUrl=ga;exports.parseAction=Uv;exports.resolveApiConfig=ed;exports.solanaProgramAddress=Jf;exports.stringify=Je;exports.switchOrAddNetwork=od;exports.toXOnly=Me;exports.validateBTCAddress=K_;