@omnity/ree-client-ts-sdk 0.7.8 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -73,10 +73,10 @@ ic-request`);const ZS=new TextEncoder().encode("\vic-response");new TextEncoder(
73
73
  `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239}),tr}var Zu={},Gs={},Ju={},nr={},u0;function Q1(){if(u0)return nr;u0=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.encode=nr.decode=nr.check=void 0;function e(r){if(r.length<8||r.length>72||r[0]!==48||r[1]!==r.length-2||r[2]!==2)return!1;const i=r[3];if(i===0||5+i>=r.length||r[4+i]!==2)return!1;const s=r[5+i];return!(s===0||6+i+s!==r.length||r[4]&128||i>1&&r[4]===0&&!(r[5]&128)||r[i+6]&128||s>1&&r[i+6]===0&&!(r[i+7]&128))}nr.check=e;function t(r){if(r.length<8)throw new Error("DER sequence length is too short");if(r.length>72)throw new Error("DER sequence length is too long");if(r[0]!==48)throw new Error("Expected DER sequence");if(r[1]!==r.length-2)throw new Error("DER sequence length is invalid");if(r[2]!==2)throw new Error("Expected DER integer");const i=r[3];if(i===0)throw new Error("R length is zero");if(5+i>=r.length)throw new Error("R length is too long");if(r[4+i]!==2)throw new Error("Expected DER integer (2)");const s=r[5+i];if(s===0)throw new Error("S length is zero");if(6+i+s!==r.length)throw new Error("S length is invalid");if(r[4]&128)throw new Error("R value is negative");if(i>1&&r[4]===0&&!(r[5]&128))throw new Error("R value excessively padded");if(r[i+6]&128)throw new Error("S value is negative");if(s>1&&r[i+6]===0&&!(r[i+7]&128))throw new Error("S value excessively padded");return{r:r.slice(4,4+i),s:r.slice(6+i)}}nr.decode=t;function n(r,i){const s=r.length,o=i.length;if(s===0)throw new Error("R length is zero");if(o===0)throw new Error("S length is zero");if(s>33)throw new Error("R length is too long");if(o>33)throw new Error("S length is too long");if(r[0]&128)throw new Error("R value is negative");if(i[0]&128)throw new Error("S value is negative");if(s>1&&r[0]===0&&!(r[1]&128))throw new Error("R value excessively padded");if(o>1&&i[0]===0&&!(i[1]&128))throw new Error("S value excessively padded");const c=Buffer.allocUnsafe(6+s+o);return c[0]=48,c[1]=c.length-2,c[2]=2,c[3]=r.length,r.copy(c,4),c[4+s]=2,c[5+s]=i.length,i.copy(c,6+s),c}return nr.encode=n,nr}var pi={},f0;function Gl(){if(f0)return pi;f0=1,Object.defineProperty(pi,"__esModule",{value:!0}),pi.REVERSE_OPS=pi.OPS=void 0;const e={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};pi.OPS=e;const t={};pi.REVERSE_OPS=t;for(const n of Object.keys(e)){const r=e[n];t[r]=n}return pi}var rr={},l0;function k8(){if(l0)return rr;l0=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.decode=rr.encode=rr.encodingLength=void 0;const e=Gl();function t(i){return i<e.OPS.OP_PUSHDATA1?1:i<=255?2:i<=65535?3:5}rr.encodingLength=t;function n(i,s,o){const c=t(s);return c===1?i.writeUInt8(s,o):c===2?(i.writeUInt8(e.OPS.OP_PUSHDATA1,o),i.writeUInt8(s,o+1)):c===3?(i.writeUInt8(e.OPS.OP_PUSHDATA2,o),i.writeUInt16LE(s,o+1)):(i.writeUInt8(e.OPS.OP_PUSHDATA4,o),i.writeUInt32LE(s,o+1)),c}rr.encode=n;function r(i,s){const o=i.readUInt8(s);let c,a;if(o<e.OPS.OP_PUSHDATA1)c=o,a=1;else if(o===e.OPS.OP_PUSHDATA1){if(s+2>i.length)return null;c=i.readUInt8(s+1),a=2}else if(o===e.OPS.OP_PUSHDATA2){if(s+3>i.length)return null;c=i.readUInt16LE(s+1),a=3}else{if(s+5>i.length)return null;if(o!==e.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");c=i.readUInt32LE(s+1),a=5}return{opcode:o,number:c,size:a}}return rr.decode=r,rr}var yi={},h0;function N8(){if(h0)return yi;h0=1,Object.defineProperty(yi,"__esModule",{value:!0}),yi.encode=yi.decode=void 0;function e(r,i,s){i=i||4,s=s===void 0?!0:s;const o=r.length;if(o===0)return 0;if(o>i)throw new TypeError("Script number overflow");if(s&&(r[o-1]&127)===0&&(o<=1||(r[o-2]&128)===0))throw new Error("Non-minimally encoded script number");if(o===5){const a=r.readUInt32LE(0),u=r.readUInt8(4);return u&128?-((u&-129)*4294967296+a):u*4294967296+a}let c=0;for(let a=0;a<o;++a)c|=r[a]<<8*a;return r[o-1]&128?-(c&~(128<<8*(o-1))):c}yi.decode=e;function t(r){return r>2147483647?5:r>8388607?4:r>32767?3:r>127?2:r>0?1:0}function n(r){let i=Math.abs(r);const s=t(i),o=Buffer.allocUnsafe(s),c=r<0;for(let a=0;a<s;++a)o.writeUInt8(i&255,a),i>>=8;return o[s-1]&128?o.writeUInt8(c?128:0,s-1):c&&(o[s-1]|=128),o}return yi.encode=n,yi}var gi={},Qu={},ef,d0;function Dl(){if(d0)return ef;d0=1;var e={Array:function(n){return n!=null&&n.constructor===Array},Boolean:function(n){return typeof n=="boolean"},Function:function(n){return typeof n=="function"},Nil:function(n){return n==null},Number:function(n){return typeof n=="number"},Object:function(n){return typeof n=="object"},String:function(n){return typeof n=="string"},"":function(){return!0}};e.Null=e.Nil;for(var t in e)e[t].toJSON=(function(n){return n}).bind(null,t);return ef=e,ef}var tf,p0;function ew(){if(p0)return tf;p0=1;var e=Dl();function t(p){return p.name||p.toString().match(/function (.*?)\s*\(/)[1]}function n(p){return e.Nil(p)?"":t(p.constructor)}function r(p){return e.Function(p)?"":e.String(p)?JSON.stringify(p):p&&e.Object(p)?"":p}function i(p,y){Error.captureStackTrace&&Error.captureStackTrace(p,y)}function s(p){return e.Function(p)?p.toJSON?p.toJSON():t(p):e.Array(p)?"Array":p&&e.Object(p)?"Object":p!==void 0?p:""}function o(p,y,g){var w=r(y);return"Expected "+s(p)+", got"+(g!==""?" "+g:"")+(w!==""?" "+w:"")}function c(p,y,g){g=g||n(y),this.message=o(p,y,g),i(this,c),this.__type=p,this.__value=y,this.__valueTypeName=g}c.prototype=Object.create(Error.prototype),c.prototype.constructor=c;function a(p,y,g,w,E){var S='" of type ';return y==="key"&&(S='" with key type '),o('property "'+s(g)+S+s(p),w,E)}function u(p,y,g,w,E){p?(E=E||n(w),this.message=a(p,g,y,w,E)):this.message='Unexpected property "'+y+'"',i(this,c),this.__label=g,this.__property=y,this.__type=p,this.__value=w,this.__valueTypeName=E}u.prototype=Object.create(Error.prototype),u.prototype.constructor=c;function f(p,y){return new c(p,{},y)}function l(p,y,g){return p instanceof u?(y=y+"."+p.__property,p=new u(p.__type,y,p.__label,p.__value,p.__valueTypeName)):p instanceof c&&(p=new u(p.__type,y,g,p.__value,p.__valueTypeName)),i(p),p}return tf={TfTypeError:c,TfPropertyTypeError:u,tfCustomError:f,tfSubError:l,tfJSON:s,getValueTypeName:n},tf}var nf,y0;function U8(){if(y0)return nf;y0=1;var e=Dl(),t=ew();function n(A){return Buffer.isBuffer(A)}function r(A){return typeof A=="string"&&/^([0-9a-f]{2})+$/i.test(A)}function i(A,U){var M=A.toJSON();function v(R){if(!A(R))return!1;if(R.length===U)return!0;throw t.tfCustomError(M+"(Length: "+U+")",M+"(Length: "+R.length+")")}return v.toJSON=function(){return M},v}var s=i.bind(null,e.Array),o=i.bind(null,n),c=i.bind(null,r),a=i.bind(null,e.String);function u(A,U,M){M=M||e.Number;function v(R,V){return M(R,V)&&R>A&&R<U}return v.toJSON=function(){return`${M.toJSON()} between [${A}, ${U}]`},v}var f=Math.pow(2,53)-1;function l(A){return typeof A=="number"&&isFinite(A)}function p(A){return A<<24>>24===A}function y(A){return A<<16>>16===A}function g(A){return(A|0)===A}function w(A){return typeof A=="number"&&A>=-f&&A<=f&&Math.floor(A)===A}function E(A){return(A&255)===A}function S(A){return(A&65535)===A}function _(A){return A>>>0===A}function m(A){return typeof A=="number"&&A>=0&&A<=f&&Math.floor(A)===A}var T={ArrayN:s,Buffer:n,BufferN:o,Finite:l,Hex:r,HexN:c,Int8:p,Int16:y,Int32:g,Int53:w,Range:u,StringN:a,UInt8:E,UInt16:S,UInt32:_,UInt53:m};for(var I in T)T[I].toJSON=(function(A){return A}).bind(null,I);return nf=T,nf}var rf,g0;function R8(){if(g0)return rf;g0=1;var e=ew(),t=Dl(),n=e.tfJSON,r=e.TfTypeError,i=e.TfPropertyTypeError,s=e.tfSubError,o=e.getValueTypeName,c={arrayOf:function(y,g){y=a(y),g=g||{};function w(E,S){return!t.Array(E)||t.Nil(E)||g.minLength!==void 0&&E.length<g.minLength||g.maxLength!==void 0&&E.length>g.maxLength||g.length!==void 0&&E.length!==g.length?!1:E.every(function(_,m){try{return u(y,_,S)}catch(T){throw s(T,m)}})}return w.toJSON=function(){var E="["+n(y)+"]";return g.length!==void 0?E+="{"+g.length+"}":(g.minLength!==void 0||g.maxLength!==void 0)&&(E+="{"+(g.minLength===void 0?0:g.minLength)+","+(g.maxLength===void 0?1/0:g.maxLength)+"}"),E},w},maybe:function p(y){y=a(y);function g(w,E){return t.Nil(w)||y(w,E,p)}return g.toJSON=function(){return"?"+n(y)},g},map:function(y,g){y=a(y),g&&(g=a(g));function w(E,S){if(!t.Object(E)||t.Nil(E))return!1;for(var _ in E){try{g&&u(g,_,S)}catch(T){throw s(T,_,"key")}try{var m=E[_];u(y,m,S)}catch(T){throw s(T,_)}}return!0}return g?w.toJSON=function(){return"{"+n(g)+": "+n(y)+"}"}:w.toJSON=function(){return"{"+n(y)+"}"},w},object:function(y){var g={};for(var w in y)g[w]=a(y[w]);function E(S,_){if(!t.Object(S)||t.Nil(S))return!1;var m;try{for(m in g){var T=g[m],I=S[m];u(T,I,_)}}catch(A){throw s(A,m)}if(_){for(m in S)if(!g[m])throw new i(void 0,m)}return!0}return E.toJSON=function(){return n(g)},E},anyOf:function(){var y=[].slice.call(arguments).map(a);function g(w,E){return y.some(function(S){try{return u(S,w,E)}catch{return!1}})}return g.toJSON=function(){return y.map(n).join("|")},g},allOf:function(){var y=[].slice.call(arguments).map(a);function g(w,E){return y.every(function(S){try{return u(S,w,E)}catch{return!1}})}return g.toJSON=function(){return y.map(n).join(" & ")},g},quacksLike:function(y){function g(w){return y===o(w)}return g.toJSON=function(){return y},g},tuple:function(){var y=[].slice.call(arguments).map(a);function g(w,E){return t.Nil(w)||t.Nil(w.length)||E&&w.length!==y.length?!1:y.every(function(S,_){try{return u(S,w[_],E)}catch(m){throw s(m,_)}})}return g.toJSON=function(){return"("+y.map(n).join(", ")+")"},g},value:function(y){function g(w){return w===y}return g.toJSON=function(){return y},g}};c.oneOf=c.anyOf;function a(p){if(t.String(p))return p[0]==="?"?c.maybe(p.slice(1)):t[p]||c.quacksLike(p);if(p&&t.Object(p)){if(t.Array(p)){if(p.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return c.arrayOf(p[0])}return c.object(p)}else if(t.Function(p))return p;return c.value(p)}function u(p,y,g,w){if(t.Function(p)){if(p(y,g))return!0;throw new r(w||p,y)}return u(a(p),y,g)}for(var f in t)u[f]=t[f];for(f in c)u[f]=c[f];var l=U8();for(f in l)u[f]=l[f];return u.compile=a,u.TfTypeError=r,u.TfPropertyTypeError=i,rf=u,rf}var w0;function Kt(){return w0||(w0=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.oneOf=e.Null=e.BufferN=e.Function=e.UInt32=e.UInt8=e.tuple=e.maybe=e.Hex=e.Buffer=e.String=e.Boolean=e.Array=e.Number=e.Hash256bit=e.Hash160bit=e.Buffer256bit=e.isTaptree=e.isTapleaf=e.TAPLEAF_VERSION_MASK=e.Satoshi=e.isPoint=e.stacksEqual=e.typeforce=void 0;const t=Vo();e.typeforce=R8();const n=t.Buffer.alloc(32,0),r=t.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function i(f,l){return f.length!==l.length?!1:f.every((p,y)=>p.equals(l[y]))}e.stacksEqual=i;function s(f){if(!t.Buffer.isBuffer(f)||f.length<33)return!1;const l=f[0],p=f.slice(1,33);if(p.compare(n)===0||p.compare(r)>=0)return!1;if((l===2||l===3)&&f.length===33)return!0;const y=f.slice(33);return y.compare(n)===0||y.compare(r)>=0?!1:l===4&&f.length===65}e.isPoint=s;const o=21*1e14;function c(f){return e.typeforce.UInt53(f)&&f<=o}e.Satoshi=c,e.TAPLEAF_VERSION_MASK=254;function a(f){return!f||!("output"in f)||!t.Buffer.isBuffer(f.output)?!1:f.version!==void 0?(f.version&e.TAPLEAF_VERSION_MASK)===f.version:!0}e.isTapleaf=a;function u(f){return(0,e.Array)(f)?f.length!==2?!1:f.every(l=>u(l)):a(f)}e.isTaptree=u,e.Buffer256bit=e.typeforce.BufferN(32),e.Hash160bit=e.typeforce.BufferN(20),e.Hash256bit=e.typeforce.BufferN(32),e.Number=e.typeforce.Number,e.Array=e.typeforce.Array,e.Boolean=e.typeforce.Boolean,e.String=e.typeforce.String,e.Buffer=e.typeforce.Buffer,e.Hex=e.typeforce.Hex,e.maybe=e.typeforce.maybe,e.tuple=e.typeforce.tuple,e.UInt8=e.typeforce.UInt8,e.UInt32=e.typeforce.UInt32,e.Function=e.typeforce.Function,e.BufferN=e.typeforce.BufferN,e.Null=e.typeforce.Null,e.oneOf=e.typeforce.oneOf})(Qu)),Qu}var m0;function C8(){if(m0)return gi;m0=1,Object.defineProperty(gi,"__esModule",{value:!0}),gi.encode=gi.decode=void 0;const e=Q1(),t=Jt(),n=Kt(),{typeforce:r}=n,i=Buffer.alloc(1,0);function s(u){let f=0;for(;u[f]===0;)++f;return f===u.length?i:(u=u.slice(f),u[0]&128?Buffer.concat([i,u],1+u.length):u)}function o(u){u[0]===0&&(u=u.slice(1));const f=Buffer.alloc(32,0),l=Math.max(0,32-u.length);return u.copy(f,l),f}function c(u){const f=u.readUInt8(u.length-1);if(!(0,t.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const l=e.decode(u.slice(0,-1)),p=o(l.r),y=o(l.s);return{signature:Buffer.concat([p,y],64),hashType:f}}gi.decode=c;function a(u,f){if(r({signature:n.BufferN(64),hashType:n.UInt8},{signature:u,hashType:f}),!(0,t.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const l=Buffer.allocUnsafe(1);l.writeUInt8(f,0);const p=s(u.slice(0,32)),y=s(u.slice(32,64));return Buffer.concat([e.encode(p,y),l])}return gi.encode=a,gi}var b0;function Jt(){return b0||(b0=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.signature=e.number=e.isCanonicalScriptSignature=e.isDefinedHashType=e.isCanonicalPubKey=e.toStack=e.fromASM=e.toASM=e.decompile=e.compile=e.countNonPushOnlyOPs=e.isPushOnly=e.OPS=void 0;const t=Q1(),n=Gl();Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return n.OPS}});const r=k8(),i=N8(),s=C8(),o=Kt(),{typeforce:c}=o,a=n.OPS.OP_RESERVED;function u(v){return o.Number(v)&&(v===n.OPS.OP_0||v>=n.OPS.OP_1&&v<=n.OPS.OP_16||v===n.OPS.OP_1NEGATE)}function f(v){return o.Buffer(v)||u(v)}function l(v){return o.Array(v)&&v.every(f)}e.isPushOnly=l;function p(v){return v.length-v.filter(f).length}e.countNonPushOnlyOPs=p;function y(v){if(v.length===0)return n.OPS.OP_0;if(v.length===1){if(v[0]>=1&&v[0]<=16)return a+v[0];if(v[0]===129)return n.OPS.OP_1NEGATE}}function g(v){return Buffer.isBuffer(v)}function w(v){return o.Array(v)}function E(v){return Buffer.isBuffer(v)}function S(v){if(g(v))return v;c(o.Array,v);const R=v.reduce((H,$)=>E($)?$.length===1&&y($)!==void 0?H+1:H+r.encodingLength($.length)+$.length:H+1,0),V=Buffer.allocUnsafe(R);let W=0;if(v.forEach(H=>{if(E(H)){const $=y(H);if($!==void 0){V.writeUInt8($,W),W+=1;return}W+=r.encode(V,H.length,W),H.copy(V,W),W+=H.length}else V.writeUInt8(H,W),W+=1}),W!==V.length)throw new Error("Could not decode chunks");return V}e.compile=S;function _(v){if(w(v))return v;c(o.Buffer,v);const R=[];let V=0;for(;V<v.length;){const W=v[V];if(W>n.OPS.OP_0&&W<=n.OPS.OP_PUSHDATA4){const H=r.decode(v,V);if(H===null||(V+=H.size,V+H.number>v.length))return null;const $=v.slice(V,V+H.number);V+=H.number;const N=y($);N!==void 0?R.push(N):R.push($)}else R.push(W),V+=1}return R}e.decompile=_;function m(v){if(g(v)&&(v=_(v)),!v)throw new Error("Could not convert invalid chunks to ASM");return v.map(R=>{if(E(R)){const V=y(R);if(V===void 0)return R.toString("hex");R=V}return n.REVERSE_OPS[R]}).join(" ")}e.toASM=m;function T(v){return c(o.String,v),S(v.split(" ").map(R=>n.OPS[R]!==void 0?n.OPS[R]:(c(o.Hex,R),Buffer.from(R,"hex"))))}e.fromASM=T;function I(v){return v=_(v),c(l,v),v.map(R=>E(R)?R:R===n.OPS.OP_0?Buffer.allocUnsafe(0):i.encode(R-a))}e.toStack=I;function A(v){return o.isPoint(v)}e.isCanonicalPubKey=A;function U(v){const R=v&-129;return R>0&&R<4}e.isDefinedHashType=U;function M(v){return!Buffer.isBuffer(v)||!U(v[v.length-1])?!1:t.check(v.slice(0,-1))}e.isCanonicalScriptSignature=M,e.number=i,e.signature=s})(Ju)),Ju}var wi={},E0;function ui(){if(E0)return wi;E0=1,Object.defineProperty(wi,"__esModule",{value:!0}),wi.value=wi.prop=void 0;function e(n,r,i){Object.defineProperty(n,r,{configurable:!0,enumerable:!0,get(){const s=i.call(this);return this[r]=s,s},set(s){Object.defineProperty(this,r,{configurable:!0,enumerable:!0,value:s,writable:!0})}})}wi.prop=e;function t(n){let r;return()=>(r!==void 0||(r=n()),r)}return wi.value=t,wi}var _0;function H8(){if(_0)return Gs;_0=1,Object.defineProperty(Gs,"__esModule",{value:!0}),Gs.p2data=void 0;const e=Vn(),t=Jt(),n=Kt(),r=ui(),i=t.OPS;function s(o,c){if(!o.data&&!o.output)throw new TypeError("Not enough data");c=Object.assign({validate:!0},c||{}),(0,n.typeforce)({network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.Buffer),data:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer))},o);const u={name:"embed",network:o.network||e.bitcoin};if(r.prop(u,"output",()=>{if(o.data)return t.compile([i.OP_RETURN].concat(o.data))}),r.prop(u,"data",()=>{if(o.output)return t.decompile(o.output).slice(1)}),c.validate&&o.output){const f=t.decompile(o.output);if(f[0]!==i.OP_RETURN)throw new TypeError("Output is invalid");if(!f.slice(1).every(n.typeforce.Buffer))throw new TypeError("Output is invalid");if(o.data&&!(0,n.stacksEqual)(o.data,u.data))throw new TypeError("Data mismatch")}return Object.assign(u,o)}return Gs.p2data=s,Gs}var Ds={},S0;function F8(){if(S0)return Ds;S0=1,Object.defineProperty(Ds,"__esModule",{value:!0}),Ds.p2ms=void 0;const e=Vn(),t=Jt(),n=Kt(),r=ui(),i=t.OPS,s=i.OP_RESERVED;function o(c,a){if(!c.input&&!c.output&&!(c.pubkeys&&c.m!==void 0)&&!c.signatures)throw new TypeError("Not enough data");a=Object.assign({validate:!0},a||{});function u(w){return t.isCanonicalScriptSignature(w)||(a.allowIncomplete&&w===i.OP_0)!==void 0}(0,n.typeforce)({network:n.typeforce.maybe(n.typeforce.Object),m:n.typeforce.maybe(n.typeforce.Number),n:n.typeforce.maybe(n.typeforce.Number),output:n.typeforce.maybe(n.typeforce.Buffer),pubkeys:n.typeforce.maybe(n.typeforce.arrayOf(n.isPoint)),signatures:n.typeforce.maybe(n.typeforce.arrayOf(u)),input:n.typeforce.maybe(n.typeforce.Buffer)},c);const l={network:c.network||e.bitcoin};let p=[],y=!1;function g(w){y||(y=!0,p=t.decompile(w),l.m=p[0]-s,l.n=p[p.length-2]-s,l.pubkeys=p.slice(1,-2))}if(r.prop(l,"output",()=>{if(c.m&&l.n&&c.pubkeys)return t.compile([].concat(s+c.m,c.pubkeys,s+l.n,i.OP_CHECKMULTISIG))}),r.prop(l,"m",()=>{if(l.output)return g(l.output),l.m}),r.prop(l,"n",()=>{if(l.pubkeys)return l.pubkeys.length}),r.prop(l,"pubkeys",()=>{if(c.output)return g(c.output),l.pubkeys}),r.prop(l,"signatures",()=>{if(c.input)return t.decompile(c.input).slice(1)}),r.prop(l,"input",()=>{if(c.signatures)return t.compile([i.OP_0].concat(c.signatures))}),r.prop(l,"witness",()=>{if(l.input)return[]}),r.prop(l,"name",()=>{if(!(!l.m||!l.n))return`p2ms(${l.m} of ${l.n})`}),a.validate){if(c.output){if(g(c.output),!n.typeforce.Number(p[0]))throw new TypeError("Output is invalid");if(!n.typeforce.Number(p[p.length-2]))throw new TypeError("Output is invalid");if(p[p.length-1]!==i.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(l.m<=0||l.n>16||l.m>l.n||l.n!==p.length-3)throw new TypeError("Output is invalid");if(!l.pubkeys.every(w=>(0,n.isPoint)(w)))throw new TypeError("Output is invalid");if(c.m!==void 0&&c.m!==l.m)throw new TypeError("m mismatch");if(c.n!==void 0&&c.n!==l.n)throw new TypeError("n mismatch");if(c.pubkeys&&!(0,n.stacksEqual)(c.pubkeys,l.pubkeys))throw new TypeError("Pubkeys mismatch")}if(c.pubkeys){if(c.n!==void 0&&c.n!==c.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(l.n=c.pubkeys.length,l.n<l.m)throw new TypeError("Pubkey count cannot be less than m")}if(c.signatures){if(c.signatures.length<l.m)throw new TypeError("Not enough signatures provided");if(c.signatures.length>l.m)throw new TypeError("Too many signatures provided")}if(c.input){if(c.input[0]!==i.OP_0)throw new TypeError("Input is invalid");if(l.signatures.length===0||!l.signatures.every(u))throw new TypeError("Input has invalid signature(s)");if(c.signatures&&!(0,n.stacksEqual)(c.signatures,l.signatures))throw new TypeError("Signature mismatch");if(c.m!==void 0&&c.m!==c.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(l,c)}return Ds.p2ms=o,Ds}var Xs={},T0;function M8(){if(T0)return Xs;T0=1,Object.defineProperty(Xs,"__esModule",{value:!0}),Xs.p2pk=void 0;const e=Vn(),t=Jt(),n=Kt(),r=ui(),i=t.OPS;function s(o,c){if(!o.input&&!o.output&&!o.pubkey&&!o.input&&!o.signature)throw new TypeError("Not enough data");c=Object.assign({validate:!0},c||{}),(0,n.typeforce)({network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.Buffer),pubkey:n.typeforce.maybe(n.isPoint),signature:n.typeforce.maybe(t.isCanonicalScriptSignature),input:n.typeforce.maybe(n.typeforce.Buffer)},o);const a=r.value(()=>t.decompile(o.input)),f={name:"p2pk",network:o.network||e.bitcoin};if(r.prop(f,"output",()=>{if(o.pubkey)return t.compile([o.pubkey,i.OP_CHECKSIG])}),r.prop(f,"pubkey",()=>{if(o.output)return o.output.slice(1,-1)}),r.prop(f,"signature",()=>{if(o.input)return a()[0]}),r.prop(f,"input",()=>{if(o.signature)return t.compile([o.signature])}),r.prop(f,"witness",()=>{if(f.input)return[]}),c.validate){if(o.output){if(o.output[o.output.length-1]!==i.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,n.isPoint)(f.pubkey))throw new TypeError("Output pubkey is invalid");if(o.pubkey&&!o.pubkey.equals(f.pubkey))throw new TypeError("Pubkey mismatch")}if(o.signature&&o.input&&!o.input.equals(f.input))throw new TypeError("Signature mismatch");if(o.input){if(a().length!==1)throw new TypeError("Input is invalid");if(!t.isCanonicalScriptSignature(f.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(f,o)}return Xs.p2pk=s,Xs}var zs={},sf={},mi={},Gt={},x0;function tw(){if(x0)return Gt;x0=1,Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.ripemd160=Gt.RIPEMD160=Gt.md5=Gt.MD5=Gt.sha1=Gt.SHA1=void 0;const e=Lp(),t=ni(),n=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),r=new Uint32Array(80);class i extends e.HashMD{constructor(){super(64,20,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0}get(){const{A:v,B:R,C:V,D:W,E:H}=this;return[v,R,V,W,H]}set(v,R,V,W,H){this.A=v|0,this.B=R|0,this.C=V|0,this.D=W|0,this.E=H|0}process(v,R){for(let K=0;K<16;K++,R+=4)r[K]=v.getUint32(R,!1);for(let K=16;K<80;K++)r[K]=(0,t.rotl)(r[K-3]^r[K-8]^r[K-14]^r[K-16],1);let{A:V,B:W,C:H,D:$,E:N}=this;for(let K=0;K<80;K++){let F,x;K<20?(F=(0,e.Chi)(W,H,$),x=1518500249):K<40?(F=W^H^$,x=1859775393):K<60?(F=(0,e.Maj)(W,H,$),x=2400959708):(F=W^H^$,x=3395469782);const O=(0,t.rotl)(V,5)+F+N+x+r[K]|0;N=$,$=H,H=(0,t.rotl)(W,30),W=V,V=O}V=V+this.A|0,W=W+this.B|0,H=H+this.C|0,$=$+this.D|0,N=N+this.E|0,this.set(V,W,H,$,N)}roundClean(){(0,t.clean)(r)}destroy(){this.set(0,0,0,0,0),(0,t.clean)(this.buffer)}}Gt.SHA1=i,Gt.sha1=(0,t.createHasher)(()=>new i);const s=Math.pow(2,32),o=Array.from({length:64},(M,v)=>Math.floor(s*Math.abs(Math.sin(v+1)))),c=n.slice(0,4),a=new Uint32Array(16);class u extends e.HashMD{constructor(){super(64,16,8,!0),this.A=c[0]|0,this.B=c[1]|0,this.C=c[2]|0,this.D=c[3]|0}get(){const{A:v,B:R,C:V,D:W}=this;return[v,R,V,W]}set(v,R,V,W){this.A=v|0,this.B=R|0,this.C=V|0,this.D=W|0}process(v,R){for(let N=0;N<16;N++,R+=4)a[N]=v.getUint32(R,!0);let{A:V,B:W,C:H,D:$}=this;for(let N=0;N<64;N++){let K,F,x;N<16?(K=(0,e.Chi)(W,H,$),F=N,x=[7,12,17,22]):N<32?(K=(0,e.Chi)($,W,H),F=(5*N+1)%16,x=[5,9,14,20]):N<48?(K=W^H^$,F=(3*N+5)%16,x=[4,11,16,23]):(K=H^(W|~$),F=7*N%16,x=[6,10,15,21]),K=K+V+o[N]+a[F],V=$,$=H,H=W,W=W+(0,t.rotl)(K,x[N%4])}V=V+this.A|0,W=W+this.B|0,H=H+this.C|0,$=$+this.D|0,this.set(V,W,H,$)}roundClean(){(0,t.clean)(a)}destroy(){this.set(0,0,0,0),(0,t.clean)(this.buffer)}}Gt.MD5=u,Gt.md5=(0,t.createHasher)(()=>new u);const f=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),l=Uint8Array.from(new Array(16).fill(0).map((M,v)=>v)),p=l.map(M=>(9*M+5)%16),y=(()=>{const R=[[l],[p]];for(let V=0;V<4;V++)for(let W of R)W.push(W[V].map(H=>f[H]));return R})(),g=y[0],w=y[1],E=[[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(M=>Uint8Array.from(M)),S=g.map((M,v)=>M.map(R=>E[v][R])),_=w.map((M,v)=>M.map(R=>E[v][R])),m=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),T=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function I(M,v,R,V){return M===0?v^R^V:M===1?v&R|~v&V:M===2?(v|~R)^V:M===3?v&V|R&~V:v^(R|~V)}const A=new Uint32Array(16);class U extends e.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:v,h1:R,h2:V,h3:W,h4:H}=this;return[v,R,V,W,H]}set(v,R,V,W,H){this.h0=v|0,this.h1=R|0,this.h2=V|0,this.h3=W|0,this.h4=H|0}process(v,R){for(let P=0;P<16;P++,R+=4)A[P]=v.getUint32(R,!0);let V=this.h0|0,W=V,H=this.h1|0,$=H,N=this.h2|0,K=N,F=this.h3|0,x=F,O=this.h4|0,q=O;for(let P=0;P<5;P++){const L=4-P,G=m[P],X=T[P],Y=g[P],oe=w[P],ae=S[P],ee=_[P];for(let Z=0;Z<16;Z++){const ce=(0,t.rotl)(V+I(P,H,N,F)+A[Y[Z]]+G,ae[Z])+O|0;V=O,O=F,F=(0,t.rotl)(N,10)|0,N=H,H=ce}for(let Z=0;Z<16;Z++){const ce=(0,t.rotl)(W+I(L,$,K,x)+A[oe[Z]]+X,ee[Z])+q|0;W=q,q=x,x=(0,t.rotl)(K,10)|0,K=$,$=ce}}this.set(this.h1+N+x|0,this.h2+F+q|0,this.h3+O+W|0,this.h4+V+$|0,this.h0+H+K|0)}roundClean(){(0,t.clean)(A)}destroy(){this.destroyed=!0,(0,t.clean)(this.buffer),this.set(0,0,0,0,0)}}return Gt.RIPEMD160=U,Gt.ripemd160=(0,t.createHasher)(()=>new U),Gt}var A0;function q8(){if(A0)return mi;A0=1,Object.defineProperty(mi,"__esModule",{value:!0}),mi.ripemd160=mi.RIPEMD160=void 0;const e=tw();return mi.RIPEMD160=e.RIPEMD160,mi.ripemd160=e.ripemd160,mi}var bi={},v0;function V8(){if(v0)return bi;v0=1,Object.defineProperty(bi,"__esModule",{value:!0}),bi.sha1=bi.SHA1=void 0;const e=tw();return bi.SHA1=e.SHA1,bi.sha1=e.sha1,bi}var In={},B0;function nw(){if(B0)return In;B0=1,Object.defineProperty(In,"__esModule",{value:!0}),In.sha224=In.SHA224=In.sha256=In.SHA256=void 0;const e=$p();return In.SHA256=e.SHA256,In.sha256=e.sha256,In.SHA224=e.SHA224,In.sha224=e.sha224,In}var I0;function xr(){return I0||(I0=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.taggedHash=e.TAGGED_HASH_PREFIXES=e.TAGS=e.hash256=e.hash160=e.sha256=e.sha1=e.ripemd160=void 0;const t=q8(),n=V8(),r=nw();function i(f){return Buffer.from((0,t.ripemd160)(Uint8Array.from(f)))}e.ripemd160=i;function s(f){return Buffer.from((0,n.sha1)(Uint8Array.from(f)))}e.sha1=s;function o(f){return Buffer.from((0,r.sha256)(Uint8Array.from(f)))}e.sha256=o;function c(f){return Buffer.from((0,t.ripemd160)((0,r.sha256)(Uint8Array.from(f))))}e.hash160=c;function a(f){return Buffer.from((0,r.sha256)((0,r.sha256)(Uint8Array.from(f))))}e.hash256=a,e.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],e.TAGGED_HASH_PREFIXES={"BIP0340/challenge":Buffer.from([123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124,123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124]),"BIP0340/aux":Buffer.from([241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144,241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144]),"BIP0340/nonce":Buffer.from([7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47,7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47]),TapLeaf:Buffer.from([174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238,174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238]),TapBranch:Buffer.from([25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21,25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21]),TapSighash:Buffer.from([244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49,244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49]),TapTweak:Buffer.from([232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233,232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233]),"KeyAgg list":Buffer.from([72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240,72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240]),"KeyAgg coefficient":Buffer.from([191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129,191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129])};function u(f,l){return o(Buffer.concat([e.TAGGED_HASH_PREFIXES[f],l]))}e.taggedHash=u})(sf)),sf}var of,O0;function L8(){if(O0)return of;O0=1;function e(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var c=t.length,a=t.charAt(0),u=Math.log(c)/Math.log(256),f=Math.log(256)/Math.log(c);function l(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var w=0,E=0,S=0,_=g.length;S!==_&&g[S]===0;)S++,w++;for(var m=(_-S)*f+1>>>0,T=new Uint8Array(m);S!==_;){for(var I=g[S],A=0,U=m-1;(I!==0||A<E)&&U!==-1;U--,A++)I+=256*T[U]>>>0,T[U]=I%c>>>0,I=I/c>>>0;if(I!==0)throw new Error("Non-zero carry");E=A,S++}for(var M=m-E;M!==m&&T[M]===0;)M++;for(var v=a.repeat(w);M<m;++M)v+=t.charAt(T[M]);return v}function p(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;for(var w=0,E=0,S=0;g[w]===a;)E++,w++;for(var _=(g.length-w)*u+1>>>0,m=new Uint8Array(_);g[w];){var T=g.charCodeAt(w);if(T>255)return;var I=n[T];if(I===255)return;for(var A=0,U=_-1;(I!==0||A<S)&&U!==-1;U--,A++)I+=c*m[U]>>>0,m[U]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");S=A,w++}for(var M=_-S;M!==_&&m[M]===0;)M++;for(var v=new Uint8Array(E+(_-M)),R=E;M!==_;)v[R++]=m[M++];return v}function y(g){var w=p(g);if(w)return w;throw new Error("Non-base"+c+" character")}return{encode:l,decodeUnsafe:p,decode:y}}return of=e,of}var cf,P0;function $8(){return P0||(P0=1,cf=L8()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),cf}var af,k0;function K8(){if(k0)return af;k0=1;var e=$8();return af=function(t){function n(o){var c=Uint8Array.from(o),a=t(c),u=c.length+4,f=new Uint8Array(u);return f.set(c,0),f.set(a.subarray(0,4),c.length),e.encode(f,u)}function r(o){var c=o.slice(0,-4),a=o.slice(-4),u=t(c);if(!(a[0]^u[0]|a[1]^u[1]|a[2]^u[2]|a[3]^u[3]))return c}function i(o){var c=e.decodeUnsafe(o);if(c)return r(c)}function s(o){var c=e.decode(o),a=r(c);if(!a)throw new Error("Invalid checksum");return a}return{encode:n,decode:s,decodeUnsafe:i}},af}var uf,N0;function Xl(){if(N0)return uf;N0=1;var{sha256:e}=nw(),t=K8();function n(r){return e(e(r))}return uf=t(n),uf}var U0;function j8(){if(U0)return zs;U0=1,Object.defineProperty(zs,"__esModule",{value:!0}),zs.p2pkh=void 0;const e=xr(),t=Vn(),n=Jt(),r=Kt(),i=ui(),s=Xl(),o=n.OPS;function c(a,u){if(!a.address&&!a.hash&&!a.output&&!a.pubkey&&!a.input)throw new TypeError("Not enough data");u=Object.assign({validate:!0},u||{}),(0,r.typeforce)({network:r.typeforce.maybe(r.typeforce.Object),address:r.typeforce.maybe(r.typeforce.String),hash:r.typeforce.maybe(r.typeforce.BufferN(20)),output:r.typeforce.maybe(r.typeforce.BufferN(25)),pubkey:r.typeforce.maybe(r.isPoint),signature:r.typeforce.maybe(n.isCanonicalScriptSignature),input:r.typeforce.maybe(r.typeforce.Buffer)},a);const f=i.value(()=>{const g=Buffer.from(s.decode(a.address)),w=g.readUInt8(0),E=g.slice(1);return{version:w,hash:E}}),l=i.value(()=>n.decompile(a.input)),p=a.network||t.bitcoin,y={name:"p2pkh",network:p};if(i.prop(y,"address",()=>{if(!y.hash)return;const g=Buffer.allocUnsafe(21);return g.writeUInt8(p.pubKeyHash,0),y.hash.copy(g,1),s.encode(g)}),i.prop(y,"hash",()=>{if(a.output)return a.output.slice(3,23);if(a.address)return f().hash;if(a.pubkey||y.pubkey)return e.hash160(a.pubkey||y.pubkey)}),i.prop(y,"output",()=>{if(y.hash)return n.compile([o.OP_DUP,o.OP_HASH160,y.hash,o.OP_EQUALVERIFY,o.OP_CHECKSIG])}),i.prop(y,"pubkey",()=>{if(a.input)return l()[1]}),i.prop(y,"signature",()=>{if(a.input)return l()[0]}),i.prop(y,"input",()=>{if(a.pubkey&&a.signature)return n.compile([a.signature,a.pubkey])}),i.prop(y,"witness",()=>{if(y.input)return[]}),u.validate){let g=Buffer.from([]);if(a.address){if(f().version!==p.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(f().hash.length!==20)throw new TypeError("Invalid address");g=f().hash}if(a.hash){if(g.length>0&&!g.equals(a.hash))throw new TypeError("Hash mismatch");g=a.hash}if(a.output){if(a.output.length!==25||a.output[0]!==o.OP_DUP||a.output[1]!==o.OP_HASH160||a.output[2]!==20||a.output[23]!==o.OP_EQUALVERIFY||a.output[24]!==o.OP_CHECKSIG)throw new TypeError("Output is invalid");const w=a.output.slice(3,23);if(g.length>0&&!g.equals(w))throw new TypeError("Hash mismatch");g=w}if(a.pubkey){const w=e.hash160(a.pubkey);if(g.length>0&&!g.equals(w))throw new TypeError("Hash mismatch");g=w}if(a.input){const w=l();if(w.length!==2)throw new TypeError("Input is invalid");if(!n.isCanonicalScriptSignature(w[0]))throw new TypeError("Input has invalid signature");if(!(0,r.isPoint)(w[1]))throw new TypeError("Input has invalid pubkey");if(a.signature&&!a.signature.equals(w[0]))throw new TypeError("Signature mismatch");if(a.pubkey&&!a.pubkey.equals(w[1]))throw new TypeError("Pubkey mismatch");const E=e.hash160(w[1]);if(g.length>0&&!g.equals(E))throw new TypeError("Hash mismatch")}}return Object.assign(y,a)}return zs.p2pkh=c,zs}var Ys={},R0;function W8(){if(R0)return Ys;R0=1,Object.defineProperty(Ys,"__esModule",{value:!0}),Ys.p2sh=void 0;const e=xr(),t=Vn(),n=Jt(),r=Kt(),i=ui(),s=Xl(),o=n.OPS;function c(a,u){if(!a.address&&!a.hash&&!a.output&&!a.redeem&&!a.input)throw new TypeError("Not enough data");u=Object.assign({validate:!0},u||{}),(0,r.typeforce)({network:r.typeforce.maybe(r.typeforce.Object),address:r.typeforce.maybe(r.typeforce.String),hash:r.typeforce.maybe(r.typeforce.BufferN(20)),output:r.typeforce.maybe(r.typeforce.BufferN(23)),redeem:r.typeforce.maybe({network:r.typeforce.maybe(r.typeforce.Object),output:r.typeforce.maybe(r.typeforce.Buffer),input:r.typeforce.maybe(r.typeforce.Buffer),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))}),input:r.typeforce.maybe(r.typeforce.Buffer),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))},a);let f=a.network;f||(f=a.redeem&&a.redeem.network||t.bitcoin);const l={network:f},p=i.value(()=>{const w=Buffer.from(s.decode(a.address)),E=w.readUInt8(0),S=w.slice(1);return{version:E,hash:S}}),y=i.value(()=>n.decompile(a.input)),g=i.value(()=>{const w=y(),E=w[w.length-1];return{network:f,output:E===o.OP_FALSE?Buffer.from([]):E,input:n.compile(w.slice(0,-1)),witness:a.witness||[]}});if(i.prop(l,"address",()=>{if(!l.hash)return;const w=Buffer.allocUnsafe(21);return w.writeUInt8(l.network.scriptHash,0),l.hash.copy(w,1),s.encode(w)}),i.prop(l,"hash",()=>{if(a.output)return a.output.slice(2,22);if(a.address)return p().hash;if(l.redeem&&l.redeem.output)return e.hash160(l.redeem.output)}),i.prop(l,"output",()=>{if(l.hash)return n.compile([o.OP_HASH160,l.hash,o.OP_EQUAL])}),i.prop(l,"redeem",()=>{if(a.input)return g()}),i.prop(l,"input",()=>{if(!(!a.redeem||!a.redeem.input||!a.redeem.output))return n.compile([].concat(n.decompile(a.redeem.input),a.redeem.output))}),i.prop(l,"witness",()=>{if(l.redeem&&l.redeem.witness)return l.redeem.witness;if(l.input)return[]}),i.prop(l,"name",()=>{const w=["p2sh"];return l.redeem!==void 0&&l.redeem.name!==void 0&&w.push(l.redeem.name),w.join("-")}),u.validate){let w=Buffer.from([]);if(a.address){if(p().version!==f.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(p().hash.length!==20)throw new TypeError("Invalid address");w=p().hash}if(a.hash){if(w.length>0&&!w.equals(a.hash))throw new TypeError("Hash mismatch");w=a.hash}if(a.output){if(a.output.length!==23||a.output[0]!==o.OP_HASH160||a.output[1]!==20||a.output[22]!==o.OP_EQUAL)throw new TypeError("Output is invalid");const S=a.output.slice(2,22);if(w.length>0&&!w.equals(S))throw new TypeError("Hash mismatch");w=S}const E=S=>{if(S.output){const _=n.decompile(S.output);if(!_||_.length<1)throw new TypeError("Redeem.output too short");if(S.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(n.countNonPushOnlyOPs(_)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const m=e.hash160(S.output);if(w.length>0&&!w.equals(m))throw new TypeError("Hash mismatch");w=m}if(S.input){const _=S.input.length>0,m=S.witness&&S.witness.length>0;if(!_&&!m)throw new TypeError("Empty input");if(_&&m)throw new TypeError("Input and witness provided");if(_){const T=n.decompile(S.input);if(!n.isPushOnly(T))throw new TypeError("Non push-only scriptSig")}}};if(a.input){const S=y();if(!S||S.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(g().output))throw new TypeError("Input is invalid");E(g())}if(a.redeem){if(a.redeem.network&&a.redeem.network!==f)throw new TypeError("Network mismatch");if(a.input){const S=g();if(a.redeem.output&&!a.redeem.output.equals(S.output))throw new TypeError("Redeem.output mismatch");if(a.redeem.input&&!a.redeem.input.equals(S.input))throw new TypeError("Redeem.input mismatch")}E(a.redeem)}if(a.witness&&a.redeem&&a.redeem.witness&&!(0,r.stacksEqual)(a.redeem.witness,a.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(l,a)}return Ys.p2sh=c,Ys}var Zs={},C0;function G8(){if(C0)return Zs;C0=1,Object.defineProperty(Zs,"__esModule",{value:!0}),Zs.p2wpkh=void 0;const e=xr(),t=Vn(),n=Jt(),r=Kt(),i=ui(),s=Do(),o=n.OPS,c=Buffer.alloc(0);function a(u,f){if(!u.address&&!u.hash&&!u.output&&!u.pubkey&&!u.witness)throw new TypeError("Not enough data");f=Object.assign({validate:!0},f||{}),(0,r.typeforce)({address:r.typeforce.maybe(r.typeforce.String),hash:r.typeforce.maybe(r.typeforce.BufferN(20)),input:r.typeforce.maybe(r.typeforce.BufferN(0)),network:r.typeforce.maybe(r.typeforce.Object),output:r.typeforce.maybe(r.typeforce.BufferN(22)),pubkey:r.typeforce.maybe(r.isPoint),signature:r.typeforce.maybe(n.isCanonicalScriptSignature),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))},u);const l=i.value(()=>{const g=s.bech32.decode(u.address),w=g.words.shift(),E=s.bech32.fromWords(g.words);return{version:w,prefix:g.prefix,data:Buffer.from(E)}}),p=u.network||t.bitcoin,y={name:"p2wpkh",network:p};if(i.prop(y,"address",()=>{if(!y.hash)return;const g=s.bech32.toWords(y.hash);return g.unshift(0),s.bech32.encode(p.bech32,g)}),i.prop(y,"hash",()=>{if(u.output)return u.output.slice(2,22);if(u.address)return l().data;if(u.pubkey||y.pubkey)return e.hash160(u.pubkey||y.pubkey)}),i.prop(y,"output",()=>{if(y.hash)return n.compile([o.OP_0,y.hash])}),i.prop(y,"pubkey",()=>{if(u.pubkey)return u.pubkey;if(u.witness)return u.witness[1]}),i.prop(y,"signature",()=>{if(u.witness)return u.witness[0]}),i.prop(y,"input",()=>{if(y.witness)return c}),i.prop(y,"witness",()=>{if(u.pubkey&&u.signature)return[u.signature,u.pubkey]}),f.validate){let g=Buffer.from([]);if(u.address){if(p&&p.bech32!==l().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(l().version!==0)throw new TypeError("Invalid address version");if(l().data.length!==20)throw new TypeError("Invalid address data");g=l().data}if(u.hash){if(g.length>0&&!g.equals(u.hash))throw new TypeError("Hash mismatch");g=u.hash}if(u.output){if(u.output.length!==22||u.output[0]!==o.OP_0||u.output[1]!==20)throw new TypeError("Output is invalid");if(g.length>0&&!g.equals(u.output.slice(2)))throw new TypeError("Hash mismatch");g=u.output.slice(2)}if(u.pubkey){const w=e.hash160(u.pubkey);if(g.length>0&&!g.equals(w))throw new TypeError("Hash mismatch");if(g=w,!(0,r.isPoint)(u.pubkey)||u.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(u.witness){if(u.witness.length!==2)throw new TypeError("Witness is invalid");if(!n.isCanonicalScriptSignature(u.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,r.isPoint)(u.witness[1])||u.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(u.signature&&!u.signature.equals(u.witness[0]))throw new TypeError("Signature mismatch");if(u.pubkey&&!u.pubkey.equals(u.witness[1]))throw new TypeError("Pubkey mismatch");const w=e.hash160(u.witness[1]);if(g.length>0&&!g.equals(w))throw new TypeError("Hash mismatch")}}return Object.assign(y,u)}return Zs.p2wpkh=a,Zs}var Js={},H0;function D8(){if(H0)return Js;H0=1,Object.defineProperty(Js,"__esModule",{value:!0}),Js.p2wsh=void 0;const e=xr(),t=Vn(),n=Jt(),r=Kt(),i=ui(),s=Do(),o=n.OPS,c=Buffer.alloc(0);function a(f){return!!(Buffer.isBuffer(f)&&f.length===65&&f[0]===4&&(0,r.isPoint)(f))}function u(f,l){if(!f.address&&!f.hash&&!f.output&&!f.redeem&&!f.witness)throw new TypeError("Not enough data");l=Object.assign({validate:!0},l||{}),(0,r.typeforce)({network:r.typeforce.maybe(r.typeforce.Object),address:r.typeforce.maybe(r.typeforce.String),hash:r.typeforce.maybe(r.typeforce.BufferN(32)),output:r.typeforce.maybe(r.typeforce.BufferN(34)),redeem:r.typeforce.maybe({input:r.typeforce.maybe(r.typeforce.Buffer),network:r.typeforce.maybe(r.typeforce.Object),output:r.typeforce.maybe(r.typeforce.Buffer),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))}),input:r.typeforce.maybe(r.typeforce.BufferN(0)),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))},f);const p=i.value(()=>{const E=s.bech32.decode(f.address),S=E.words.shift(),_=s.bech32.fromWords(E.words);return{version:S,prefix:E.prefix,data:Buffer.from(_)}}),y=i.value(()=>n.decompile(f.redeem.input));let g=f.network;g||(g=f.redeem&&f.redeem.network||t.bitcoin);const w={network:g};if(i.prop(w,"address",()=>{if(!w.hash)return;const E=s.bech32.toWords(w.hash);return E.unshift(0),s.bech32.encode(g.bech32,E)}),i.prop(w,"hash",()=>{if(f.output)return f.output.slice(2);if(f.address)return p().data;if(w.redeem&&w.redeem.output)return e.sha256(w.redeem.output)}),i.prop(w,"output",()=>{if(w.hash)return n.compile([o.OP_0,w.hash])}),i.prop(w,"redeem",()=>{if(f.witness)return{output:f.witness[f.witness.length-1],input:c,witness:f.witness.slice(0,-1)}}),i.prop(w,"input",()=>{if(w.witness)return c}),i.prop(w,"witness",()=>{if(f.redeem&&f.redeem.input&&f.redeem.input.length>0&&f.redeem.output&&f.redeem.output.length>0){const E=n.toStack(y());return w.redeem=Object.assign({witness:E},f.redeem),w.redeem.input=c,[].concat(E,f.redeem.output)}if(f.redeem&&f.redeem.output&&f.redeem.witness)return[].concat(f.redeem.witness,f.redeem.output)}),i.prop(w,"name",()=>{const E=["p2wsh"];return w.redeem!==void 0&&w.redeem.name!==void 0&&E.push(w.redeem.name),E.join("-")}),l.validate){let E=Buffer.from([]);if(f.address){if(p().prefix!==g.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(p().version!==0)throw new TypeError("Invalid address version");if(p().data.length!==32)throw new TypeError("Invalid address data");E=p().data}if(f.hash){if(E.length>0&&!E.equals(f.hash))throw new TypeError("Hash mismatch");E=f.hash}if(f.output){if(f.output.length!==34||f.output[0]!==o.OP_0||f.output[1]!==32)throw new TypeError("Output is invalid");const S=f.output.slice(2);if(E.length>0&&!E.equals(S))throw new TypeError("Hash mismatch");E=S}if(f.redeem){if(f.redeem.network&&f.redeem.network!==g)throw new TypeError("Network mismatch");if(f.redeem.input&&f.redeem.input.length>0&&f.redeem.witness&&f.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(f.redeem.output){const S=n.decompile(f.redeem.output);if(!S||S.length<1)throw new TypeError("Redeem.output is invalid");if(f.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(n.countNonPushOnlyOPs(S)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const _=e.sha256(f.redeem.output);if(E.length>0&&!E.equals(_))throw new TypeError("Hash mismatch");E=_}if(f.redeem.input&&!n.isPushOnly(y()))throw new TypeError("Non push-only scriptSig");if(f.witness&&f.redeem.witness&&!(0,r.stacksEqual)(f.witness,f.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(f.redeem.input&&y().some(a)||f.redeem.output&&(n.decompile(f.redeem.output)||[]).some(a))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(f.witness&&f.witness.length>0){const S=f.witness[f.witness.length-1];if(f.redeem&&f.redeem.output&&!f.redeem.output.equals(S))throw new TypeError("Witness and redeem.output mismatch");if(f.witness.some(a)||(n.decompile(S)||[]).some(a))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(w,f)}return Js.p2wsh=u,Js}var Qs={},Ei={},F0;function zl(){if(F0)return Ei;F0=1,Object.defineProperty(Ei,"__esModule",{value:!0}),Ei.getEccLib=Ei.initEccLib=void 0;const e={};function t(c,a){c?c!==e.eccLib&&(a?.DANGER_DO_NOT_VERIFY_ECCLIB||i(c),e.eccLib=c):e.eccLib=c}Ei.initEccLib=t;function n(){if(!e.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return e.eccLib}Ei.getEccLib=n;const r=c=>Buffer.from(c,"hex");function i(c){s(typeof c.isXOnlyPoint=="function"),s(c.isXOnlyPoint(r("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),s(c.isXOnlyPoint(r("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),s(c.isXOnlyPoint(r("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),s(c.isXOnlyPoint(r("0000000000000000000000000000000000000000000000000000000000000001"))),s(!c.isXOnlyPoint(r("0000000000000000000000000000000000000000000000000000000000000000"))),s(!c.isXOnlyPoint(r("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),s(typeof c.xOnlyPointAddTweak=="function"),o.forEach(a=>{const u=c.xOnlyPointAddTweak(r(a.pubkey),r(a.tweak));a.result===null?s(u===null):(s(u!==null),s(u.parity===a.parity),s(Buffer.from(u.xOnlyPubkey).equals(r(a.result))))})}function s(c){if(!c)throw new Error("ecc library invalid")}const o=[{pubkey:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",tweak:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",parity:-1,result:null},{pubkey:"1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b",tweak:"a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac",parity:1,result:"e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"},{pubkey:"2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",tweak:"823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47",parity:0,result:"9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"}];return Ei}var ff={},At={},Tc={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var M0;function X8(){return M0||(M0=1,(function(e,t){var n=Vo(),r=n.Buffer;function i(o,c){for(var a in o)c[a]=o[a]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=s);function s(o,c,a){return r(o,c,a)}s.prototype=Object.create(r.prototype),i(r,s),s.from=function(o,c,a){if(typeof o=="number")throw new TypeError("Argument must not be a number");return r(o,c,a)},s.alloc=function(o,c,a){if(typeof o!="number")throw new TypeError("Argument must be a number");var u=r(o);return c!==void 0?typeof a=="string"?u.fill(c,a):u.fill(c):u.fill(0),u},s.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r(o)},s.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return n.SlowBuffer(o)}})(Tc,Tc.exports)),Tc.exports}var lf,q0;function z8(){if(q0)return lf;q0=1;var e=X8().Buffer,t=9007199254740991;function n(o){if(o<0||o>t||o%1!==0)throw new RangeError("value out of range")}function r(o,c,a){if(n(o),c||(c=e.allocUnsafe(s(o))),!e.isBuffer(c))throw new TypeError("buffer must be a Buffer instance");return a||(a=0),o<253?(c.writeUInt8(o,a),r.bytes=1):o<=65535?(c.writeUInt8(253,a),c.writeUInt16LE(o,a+1),r.bytes=3):o<=4294967295?(c.writeUInt8(254,a),c.writeUInt32LE(o,a+1),r.bytes=5):(c.writeUInt8(255,a),c.writeUInt32LE(o>>>0,a+1),c.writeUInt32LE(o/4294967296|0,a+5),r.bytes=9),c}function i(o,c){if(!e.isBuffer(o))throw new TypeError("buffer must be a Buffer instance");c||(c=0);var a=o.readUInt8(c);if(a<253)return i.bytes=1,a;if(a===253)return i.bytes=3,o.readUInt16LE(c+1);if(a===254)return i.bytes=5,o.readUInt32LE(c+1);i.bytes=9;var u=o.readUInt32LE(c+1),f=o.readUInt32LE(c+5),l=f*4294967296+u;return n(l),l}function s(o){return n(o),o<253?1:o<=65535?3:o<=4294967295?5:9}return lf={encode:r,decode:i,encodingLength:s},lf}var V0;function iu(){if(V0)return At;V0=1,Object.defineProperty(At,"__esModule",{value:!0}),At.BufferReader=At.BufferWriter=At.cloneBuffer=At.reverseBuffer=At.writeUInt64LE=At.readUInt64LE=At.varuint=void 0;const e=Kt(),{typeforce:t}=e,n=z8();At.varuint=n;function r(f,l){if(typeof f!="number")throw new Error("cannot write a non-number as a number");if(f<0)throw new Error("specified a negative value for writing an unsigned value");if(f>l)throw new Error("RangeError: value out of range");if(Math.floor(f)!==f)throw new Error("value has a fractional component")}function i(f,l){const p=f.readUInt32LE(l);let y=f.readUInt32LE(l+4);return y*=4294967296,r(y+p,9007199254740991),y+p}At.readUInt64LE=i;function s(f,l,p){return r(l,9007199254740991),f.writeInt32LE(l&-1,p),f.writeUInt32LE(Math.floor(l/4294967296),p+4),p+8}At.writeUInt64LE=s;function o(f){if(f.length<1)return f;let l=f.length-1,p=0;for(let y=0;y<f.length/2;y++)p=f[y],f[y]=f[l],f[l]=p,l--;return f}At.reverseBuffer=o;function c(f){const l=Buffer.allocUnsafe(f.length);return f.copy(l),l}At.cloneBuffer=c;class a{static withCapacity(l){return new a(Buffer.alloc(l))}constructor(l,p=0){this.buffer=l,this.offset=p,t(e.tuple(e.Buffer,e.UInt32),[l,p])}writeUInt8(l){this.offset=this.buffer.writeUInt8(l,this.offset)}writeInt32(l){this.offset=this.buffer.writeInt32LE(l,this.offset)}writeUInt32(l){this.offset=this.buffer.writeUInt32LE(l,this.offset)}writeUInt64(l){this.offset=s(this.buffer,l,this.offset)}writeVarInt(l){n.encode(l,this.buffer,this.offset),this.offset+=n.encode.bytes}writeSlice(l){if(this.buffer.length<this.offset+l.length)throw new Error("Cannot write slice out of bounds");this.offset+=l.copy(this.buffer,this.offset)}writeVarSlice(l){this.writeVarInt(l.length),this.writeSlice(l)}writeVector(l){this.writeVarInt(l.length),l.forEach(p=>this.writeVarSlice(p))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}At.BufferWriter=a;class u{constructor(l,p=0){this.buffer=l,this.offset=p,t(e.tuple(e.Buffer,e.UInt32),[l,p])}readUInt8(){const l=this.buffer.readUInt8(this.offset);return this.offset++,l}readInt32(){const l=this.buffer.readInt32LE(this.offset);return this.offset+=4,l}readUInt32(){const l=this.buffer.readUInt32LE(this.offset);return this.offset+=4,l}readUInt64(){const l=i(this.buffer,this.offset);return this.offset+=8,l}readVarInt(){const l=n.decode(this.buffer,this.offset);return this.offset+=n.decode.bytes,l}readSlice(l){if(this.buffer.length<this.offset+l)throw new Error("Cannot read slice out of bounds");const p=this.buffer.slice(this.offset,this.offset+l);return this.offset+=l,p}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const l=this.readVarInt(),p=[];for(let y=0;y<l;y++)p.push(this.readVarSlice());return p}}return At.BufferReader=u,At}var L0;function Yl(){return L0||(L0=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.tweakKey=e.tapTweakHash=e.tapleafHash=e.findScriptPath=e.toHashTree=e.rootHashFromPath=e.MAX_TAPTREE_DEPTH=e.LEAF_VERSION_TAPSCRIPT=void 0;const t=Vo(),n=zl(),r=xr(),i=iu(),s=Kt();e.LEAF_VERSION_TAPSCRIPT=192,e.MAX_TAPTREE_DEPTH=128;const o=w=>"left"in w&&"right"in w;function c(w,E){if(w.length<33)throw new TypeError(`The control-block length is too small. Got ${w.length}, expected min 33.`);const S=(w.length-33)/32;let _=E;for(let m=0;m<S;m++){const T=w.slice(33+32*m,65+32*m);_.compare(T)<0?_=y(_,T):_=y(T,_)}return _}e.rootHashFromPath=c;function a(w){if((0,s.isTapleaf)(w))return{hash:f(w)};const E=[a(w[0]),a(w[1])];E.sort((m,T)=>m.hash.compare(T.hash));const[S,_]=E;return{hash:y(S.hash,_.hash),left:S,right:_}}e.toHashTree=a;function u(w,E){if(o(w)){const S=u(w.left,E);if(S!==void 0)return[...S,w.right.hash];const _=u(w.right,E);if(_!==void 0)return[..._,w.left.hash]}else if(w.hash.equals(E))return[]}e.findScriptPath=u;function f(w){const E=w.version||e.LEAF_VERSION_TAPSCRIPT;return r.taggedHash("TapLeaf",t.Buffer.concat([t.Buffer.from([E]),g(w.output)]))}e.tapleafHash=f;function l(w,E){return r.taggedHash("TapTweak",t.Buffer.concat(E?[w,E]:[w]))}e.tapTweakHash=l;function p(w,E){if(!t.Buffer.isBuffer(w)||w.length!==32||E&&E.length!==32)return null;const S=l(w,E),_=(0,n.getEccLib)().xOnlyPointAddTweak(w,S);return!_||_.xOnlyPubkey===null?null:{parity:_.parity,x:t.Buffer.from(_.xOnlyPubkey)}}e.tweakKey=p;function y(w,E){return r.taggedHash("TapBranch",t.Buffer.concat([w,E]))}function g(w){const E=i.varuint.encodingLength(w.length),S=t.Buffer.allocUnsafe(E);return i.varuint.encode(w.length,S),t.Buffer.concat([S,w])}})(ff)),ff}var $0;function Y8(){if($0)return Qs;$0=1,Object.defineProperty(Qs,"__esModule",{value:!0}),Qs.p2tr=void 0;const e=Vo(),t=Vn(),n=Jt(),r=Kt(),i=zl(),s=Yl(),o=ui(),c=Do(),a=Zl(),u=n.OPS,f=1,l=80;function p(y,g){if(!y.address&&!y.output&&!y.pubkey&&!y.internalPubkey&&!(y.witness&&y.witness.length>1))throw new TypeError("Not enough data");g=Object.assign({validate:!0},g||{}),(0,r.typeforce)({address:r.typeforce.maybe(r.typeforce.String),input:r.typeforce.maybe(r.typeforce.BufferN(0)),network:r.typeforce.maybe(r.typeforce.Object),output:r.typeforce.maybe(r.typeforce.BufferN(34)),internalPubkey:r.typeforce.maybe(r.typeforce.BufferN(32)),hash:r.typeforce.maybe(r.typeforce.BufferN(32)),pubkey:r.typeforce.maybe(r.typeforce.BufferN(32)),signature:r.typeforce.maybe(r.typeforce.anyOf(r.typeforce.BufferN(64),r.typeforce.BufferN(65))),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer)),scriptTree:r.typeforce.maybe(r.isTaptree),redeem:r.typeforce.maybe({output:r.typeforce.maybe(r.typeforce.Buffer),redeemVersion:r.typeforce.maybe(r.typeforce.Number),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))}),redeemVersion:r.typeforce.maybe(r.typeforce.Number)},y);const w=o.value(()=>(0,a.fromBech32)(y.address)),E=o.value(()=>{if(!(!y.witness||!y.witness.length))return y.witness.length>=2&&y.witness[y.witness.length-1][0]===l?y.witness.slice(0,-1):y.witness.slice()}),S=o.value(()=>{if(y.scriptTree)return(0,s.toHashTree)(y.scriptTree);if(y.hash)return{hash:y.hash}}),_=y.network||t.bitcoin,m={name:"p2tr",network:_};if(o.prop(m,"address",()=>{if(!m.pubkey)return;const T=c.bech32m.toWords(m.pubkey);return T.unshift(f),c.bech32m.encode(_.bech32,T)}),o.prop(m,"hash",()=>{const T=S();if(T)return T.hash;const I=E();if(I&&I.length>1){const A=I[I.length-1],U=A[0]&r.TAPLEAF_VERSION_MASK,M=I[I.length-2],v=(0,s.tapleafHash)({output:M,version:U});return(0,s.rootHashFromPath)(A,v)}return null}),o.prop(m,"output",()=>{if(m.pubkey)return n.compile([u.OP_1,m.pubkey])}),o.prop(m,"redeemVersion",()=>y.redeemVersion?y.redeemVersion:y.redeem&&y.redeem.redeemVersion!==void 0&&y.redeem.redeemVersion!==null?y.redeem.redeemVersion:s.LEAF_VERSION_TAPSCRIPT),o.prop(m,"redeem",()=>{const T=E();if(!(!T||T.length<2))return{output:T[T.length-2],witness:T.slice(0,-2),redeemVersion:T[T.length-1][0]&r.TAPLEAF_VERSION_MASK}}),o.prop(m,"pubkey",()=>{if(y.pubkey)return y.pubkey;if(y.output)return y.output.slice(2);if(y.address)return w().data;if(m.internalPubkey){const T=(0,s.tweakKey)(m.internalPubkey,m.hash);if(T)return T.x}}),o.prop(m,"internalPubkey",()=>{if(y.internalPubkey)return y.internalPubkey;const T=E();if(T&&T.length>1)return T[T.length-1].slice(1,33)}),o.prop(m,"signature",()=>{if(y.signature)return y.signature;const T=E();if(!(!T||T.length!==1))return T[0]}),o.prop(m,"witness",()=>{if(y.witness)return y.witness;const T=S();if(T&&y.redeem&&y.redeem.output&&y.internalPubkey){const I=(0,s.tapleafHash)({output:y.redeem.output,version:m.redeemVersion}),A=(0,s.findScriptPath)(T,I);if(!A)return;const U=(0,s.tweakKey)(y.internalPubkey,T.hash);if(!U)return;const M=e.Buffer.concat([e.Buffer.from([m.redeemVersion|U.parity]),y.internalPubkey].concat(A));return[y.redeem.output,M]}if(y.signature)return[y.signature]}),g.validate){let T=e.Buffer.from([]);if(y.address){if(_&&_.bech32!==w().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(w().version!==f)throw new TypeError("Invalid address version");if(w().data.length!==32)throw new TypeError("Invalid address data");T=w().data}if(y.pubkey){if(T.length>0&&!T.equals(y.pubkey))throw new TypeError("Pubkey mismatch");T=y.pubkey}if(y.output){if(y.output.length!==34||y.output[0]!==u.OP_1||y.output[1]!==32)throw new TypeError("Output is invalid");if(T.length>0&&!T.equals(y.output.slice(2)))throw new TypeError("Pubkey mismatch");T=y.output.slice(2)}if(y.internalPubkey){const U=(0,s.tweakKey)(y.internalPubkey,m.hash);if(T.length>0&&!T.equals(U.x))throw new TypeError("Pubkey mismatch");T=U.x}if(T&&T.length&&!(0,i.getEccLib)().isXOnlyPoint(T))throw new TypeError("Invalid pubkey for p2tr");const I=S();if(y.hash&&I&&!y.hash.equals(I.hash))throw new TypeError("Hash mismatch");if(y.redeem&&y.redeem.output&&I){const U=(0,s.tapleafHash)({output:y.redeem.output,version:m.redeemVersion});if(!(0,s.findScriptPath)(I,U))throw new TypeError("Redeem script not in tree")}const A=E();if(y.redeem&&m.redeem){if(y.redeem.redeemVersion&&y.redeem.redeemVersion!==m.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(y.redeem.output){if(n.decompile(y.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(m.redeem.output&&!y.redeem.output.equals(m.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(y.redeem.witness&&m.redeem.witness&&!(0,r.stacksEqual)(y.redeem.witness,m.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(A&&A.length)if(A.length===1){if(y.signature&&!y.signature.equals(A[0]))throw new TypeError("Signature mismatch")}else{const U=A[A.length-1];if(U.length<33)throw new TypeError(`The control-block length is too small. Got ${U.length}, expected min 33.`);if((U.length-33)%32!==0)throw new TypeError(`The control-block length of ${U.length} is incorrect!`);const M=(U.length-33)/32;if(M>128)throw new TypeError(`The script path is too long. Got ${M}, expected max 128.`);const v=U.slice(1,33);if(y.internalPubkey&&!y.internalPubkey.equals(v))throw new TypeError("Internal pubkey mismatch");if(!(0,i.getEccLib)().isXOnlyPoint(v))throw new TypeError("Invalid internalPubkey for p2tr witness");const R=U[0]&r.TAPLEAF_VERSION_MASK,V=A[A.length-2],W=(0,s.tapleafHash)({output:V,version:R}),H=(0,s.rootHashFromPath)(U,W),$=(0,s.tweakKey)(v,H);if(!$)throw new TypeError("Invalid outputKey for p2tr witness");if(T.length&&!T.equals($.x))throw new TypeError("Pubkey mismatch for p2tr witness");if($.parity!==(U[0]&1))throw new Error("Incorrect parity")}}return Object.assign(m,y)}return Qs.p2tr=p,Qs}var K0;function oc(){return K0||(K0=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.p2tr=e.p2wsh=e.p2wpkh=e.p2sh=e.p2pkh=e.p2pk=e.p2ms=e.embed=void 0;const t=H8();Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const n=F8();Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return n.p2ms}});const r=M8();Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return r.p2pk}});const i=j8();Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return i.p2pkh}});const s=W8();Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return s.p2sh}});const o=G8();Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const c=D8();Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return c.p2wsh}});const a=Y8();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return a.p2tr}})})(Zu)),Zu}var j0;function Zl(){if(j0)return Wt;j0=1,Object.defineProperty(Wt,"__esModule",{value:!0}),Wt.toOutputScript=Wt.fromOutputScript=Wt.toBech32=Wt.toBase58Check=Wt.fromBech32=Wt.fromBase58Check=void 0;const e=Vn(),t=oc(),n=Jt(),r=Kt(),i=Do(),s=Xl(),o=40,c=2,a=16,u=2,f=80,l="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function p(m,T){const I=m.slice(2);if(I.length<c||I.length>o)throw new TypeError("Invalid program length for segwit address");const A=m[0]-f;if(A<u||A>a)throw new TypeError("Invalid version for segwit address");if(m[1]!==I.length)throw new TypeError("Invalid script for segwit address");return console.warn(l),E(I,A,T.bech32)}function y(m){const T=Buffer.from(s.decode(m));if(T.length<21)throw new TypeError(m+" is too short");if(T.length>21)throw new TypeError(m+" is too long");const I=T.readUInt8(0),A=T.slice(1);return{version:I,hash:A}}Wt.fromBase58Check=y;function g(m){let T,I;try{T=i.bech32.decode(m)}catch{}if(T){if(I=T.words[0],I!==0)throw new TypeError(m+" uses wrong encoding")}else if(T=i.bech32m.decode(m),I=T.words[0],I===0)throw new TypeError(m+" uses wrong encoding");const A=i.bech32.fromWords(T.words.slice(1));return{version:I,prefix:T.prefix,data:Buffer.from(A)}}Wt.fromBech32=g;function w(m,T){(0,r.typeforce)((0,r.tuple)(r.Hash160bit,r.UInt8),arguments);const I=Buffer.allocUnsafe(21);return I.writeUInt8(T,0),m.copy(I,1),s.encode(I)}Wt.toBase58Check=w;function E(m,T,I){const A=i.bech32.toWords(m);return A.unshift(T),T===0?i.bech32.encode(I,A):i.bech32m.encode(I,A)}Wt.toBech32=E;function S(m,T){T=T||e.bitcoin;try{return t.p2pkh({output:m,network:T}).address}catch{}try{return t.p2sh({output:m,network:T}).address}catch{}try{return t.p2wpkh({output:m,network:T}).address}catch{}try{return t.p2wsh({output:m,network:T}).address}catch{}try{return t.p2tr({output:m,network:T}).address}catch{}try{return p(m,T)}catch{}throw new Error(n.toASM(m)+" has no matching Address")}Wt.fromOutputScript=S;function _(m,T){T=T||e.bitcoin;let I,A;try{I=y(m)}catch{}if(I){if(I.version===T.pubKeyHash)return t.p2pkh({hash:I.hash}).output;if(I.version===T.scriptHash)return t.p2sh({hash:I.hash}).output}else{try{A=g(m)}catch{}if(A){if(A.prefix!==T.bech32)throw new Error(m+" has an invalid prefix");if(A.version===0){if(A.data.length===20)return t.p2wpkh({hash:A.data}).output;if(A.data.length===32)return t.p2wsh({hash:A.data}).output}else if(A.version===1){if(A.data.length===32)return t.p2tr({pubkey:A.data}).output}else if(A.version>=u&&A.version<=a&&A.data.length>=c&&A.data.length<=o)return console.warn(l),n.compile([A.version+f,A.data])}}throw new Error(m+" has no matching Script")}return Wt.toOutputScript=_,Wt}var eo={},to={},W0;function Z8(){if(W0)return to;W0=1,Object.defineProperty(to,"__esModule",{value:!0}),to.fastMerkleRoot=void 0;function e(t,n){if(!Array.isArray(t))throw TypeError("Expected values Array");if(typeof n!="function")throw TypeError("Expected digest Function");let r=t.length;const i=t.concat();for(;r>1;){let s=0;for(let o=0;o<r;o+=2,++s){const c=i[o],a=o+1===r?c:i[o+1],u=Buffer.concat([c,a]);i[s]=n(u)}r=s}return i[0]}return to.fastMerkleRoot=e,to}var no={},G0;function cc(){if(G0)return no;G0=1,Object.defineProperty(no,"__esModule",{value:!0}),no.Transaction=void 0;const e=iu(),t=xr(),n=Jt(),r=Jt(),i=Kt(),{typeforce:s}=i;function o(E){const S=E.length;return e.varuint.encodingLength(S)+S}function c(E){const S=E.length;return e.varuint.encodingLength(S)+E.reduce((_,m)=>_+o(m),0)}const a=Buffer.allocUnsafe(0),u=[],f=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),l=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),p=Buffer.from("ffffffffffffffff","hex"),y={script:a,valueBuffer:p};function g(E){return E.value!==void 0}class w{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(S,_){const m=new e.BufferReader(S),T=new w;T.version=m.readInt32();const I=m.readUInt8(),A=m.readUInt8();let U=!1;I===w.ADVANCED_TRANSACTION_MARKER&&A===w.ADVANCED_TRANSACTION_FLAG?U=!0:m.offset-=2;const M=m.readVarInt();for(let R=0;R<M;++R)T.ins.push({hash:m.readSlice(32),index:m.readUInt32(),script:m.readVarSlice(),sequence:m.readUInt32(),witness:u});const v=m.readVarInt();for(let R=0;R<v;++R)T.outs.push({value:m.readUInt64(),script:m.readVarSlice()});if(U){for(let R=0;R<M;++R)T.ins[R].witness=m.readVector();if(!T.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(T.locktime=m.readUInt32(),_)return T;if(m.offset!==S.length)throw new Error("Transaction has unexpected data");return T}static fromHex(S){return w.fromBuffer(Buffer.from(S,"hex"),!1)}static isCoinbaseHash(S){s(i.Hash256bit,S);for(let _=0;_<32;++_)if(S[_]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&w.isCoinbaseHash(this.ins[0].hash)}addInput(S,_,m,T){return s(i.tuple(i.Hash256bit,i.UInt32,i.maybe(i.UInt32),i.maybe(i.Buffer)),arguments),i.Null(m)&&(m=w.DEFAULT_SEQUENCE),this.ins.push({hash:S,index:_,script:T||a,sequence:m,witness:u})-1}addOutput(S,_){return s(i.tuple(i.Buffer,i.Satoshi),arguments),this.outs.push({script:S,value:_})-1}hasWitnesses(){return this.ins.some(S=>S.witness.length!==0)}stripWitnesses(){this.ins.forEach(S=>{S.witness=u})}weight(){const S=this.byteLength(!1),_=this.byteLength(!0);return S*3+_}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(S=!0){const _=S&&this.hasWitnesses();return(_?10:8)+e.varuint.encodingLength(this.ins.length)+e.varuint.encodingLength(this.outs.length)+this.ins.reduce((m,T)=>m+40+o(T.script),0)+this.outs.reduce((m,T)=>m+8+o(T.script),0)+(_?this.ins.reduce((m,T)=>m+c(T.witness),0):0)}clone(){const S=new w;return S.version=this.version,S.locktime=this.locktime,S.ins=this.ins.map(_=>({hash:_.hash,index:_.index,script:_.script,sequence:_.sequence,witness:_.witness})),S.outs=this.outs.map(_=>({script:_.script,value:_.value})),S}hashForSignature(S,_,m){if(s(i.tuple(i.UInt32,i.Buffer,i.Number),arguments),S>=this.ins.length)return l;const T=n.compile(n.decompile(_).filter(U=>U!==r.OPS.OP_CODESEPARATOR)),I=this.clone();if((m&31)===w.SIGHASH_NONE)I.outs=[],I.ins.forEach((U,M)=>{M!==S&&(U.sequence=0)});else if((m&31)===w.SIGHASH_SINGLE){if(S>=this.outs.length)return l;I.outs.length=S+1;for(let U=0;U<S;U++)I.outs[U]=y;I.ins.forEach((U,M)=>{M!==S&&(U.sequence=0)})}m&w.SIGHASH_ANYONECANPAY?(I.ins=[I.ins[S]],I.ins[0].script=T):(I.ins.forEach(U=>{U.script=a}),I.ins[S].script=T);const A=Buffer.allocUnsafe(I.byteLength(!1)+4);return A.writeInt32LE(m,A.length-4),I.__toBuffer(A,0,!1),t.hash256(A)}hashForWitnessV1(S,_,m,T,I,A){if(s(i.tuple(i.UInt32,s.arrayOf(i.Buffer),s.arrayOf(i.Satoshi),i.UInt32),arguments),m.length!==this.ins.length||_.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const U=T===w.SIGHASH_DEFAULT?w.SIGHASH_ALL:T&w.SIGHASH_OUTPUT_MASK,v=(T&w.SIGHASH_INPUT_MASK)===w.SIGHASH_ANYONECANPAY,R=U===w.SIGHASH_NONE,V=U===w.SIGHASH_SINGLE;let W=a,H=a,$=a,N=a,K=a;if(!v){let q=e.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(P=>{q.writeSlice(P.hash),q.writeUInt32(P.index)}),W=t.sha256(q.end()),q=e.BufferWriter.withCapacity(8*this.ins.length),m.forEach(P=>q.writeUInt64(P)),H=t.sha256(q.end()),q=e.BufferWriter.withCapacity(_.map(o).reduce((P,L)=>P+L)),_.forEach(P=>q.writeVarSlice(P)),$=t.sha256(q.end()),q=e.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(P=>q.writeUInt32(P.sequence)),N=t.sha256(q.end())}if(R||V){if(V&&S<this.outs.length){const q=this.outs[S],P=e.BufferWriter.withCapacity(8+o(q.script));P.writeUInt64(q.value),P.writeVarSlice(q.script),K=t.sha256(P.end())}}else{const q=this.outs.map(L=>8+o(L.script)).reduce((L,G)=>L+G),P=e.BufferWriter.withCapacity(q);this.outs.forEach(L=>{P.writeUInt64(L.value),P.writeVarSlice(L.script)}),K=t.sha256(P.end())}const F=(I?2:0)+(A?1:0),x=174-(v?49:0)-(R?32:0)+(A?32:0)+(I?37:0),O=e.BufferWriter.withCapacity(x);if(O.writeUInt8(T),O.writeInt32(this.version),O.writeUInt32(this.locktime),O.writeSlice(W),O.writeSlice(H),O.writeSlice($),O.writeSlice(N),R||V||O.writeSlice(K),O.writeUInt8(F),v){const q=this.ins[S];O.writeSlice(q.hash),O.writeUInt32(q.index),O.writeUInt64(m[S]),O.writeVarSlice(_[S]),O.writeUInt32(q.sequence)}else O.writeUInt32(S);if(A){const q=e.BufferWriter.withCapacity(o(A));q.writeVarSlice(A),O.writeSlice(t.sha256(q.end()))}return V&&O.writeSlice(K),I&&(O.writeSlice(I),O.writeUInt8(0),O.writeUInt32(4294967295)),t.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),O.end()]))}hashForWitnessV0(S,_,m,T){s(i.tuple(i.UInt32,i.Buffer,i.Satoshi,i.UInt32),arguments);let I=Buffer.from([]),A,U=f,M=f,v=f;if(T&w.SIGHASH_ANYONECANPAY||(I=Buffer.allocUnsafe(36*this.ins.length),A=new e.BufferWriter(I,0),this.ins.forEach(V=>{A.writeSlice(V.hash),A.writeUInt32(V.index)}),M=t.hash256(I)),!(T&w.SIGHASH_ANYONECANPAY)&&(T&31)!==w.SIGHASH_SINGLE&&(T&31)!==w.SIGHASH_NONE&&(I=Buffer.allocUnsafe(4*this.ins.length),A=new e.BufferWriter(I,0),this.ins.forEach(V=>{A.writeUInt32(V.sequence)}),v=t.hash256(I)),(T&31)!==w.SIGHASH_SINGLE&&(T&31)!==w.SIGHASH_NONE){const V=this.outs.reduce((W,H)=>W+8+o(H.script),0);I=Buffer.allocUnsafe(V),A=new e.BufferWriter(I,0),this.outs.forEach(W=>{A.writeUInt64(W.value),A.writeVarSlice(W.script)}),U=t.hash256(I)}else if((T&31)===w.SIGHASH_SINGLE&&S<this.outs.length){const V=this.outs[S];I=Buffer.allocUnsafe(8+o(V.script)),A=new e.BufferWriter(I,0),A.writeUInt64(V.value),A.writeVarSlice(V.script),U=t.hash256(I)}I=Buffer.allocUnsafe(156+o(_)),A=new e.BufferWriter(I,0);const R=this.ins[S];return A.writeInt32(this.version),A.writeSlice(M),A.writeSlice(v),A.writeSlice(R.hash),A.writeUInt32(R.index),A.writeVarSlice(_),A.writeUInt64(m),A.writeUInt32(R.sequence),A.writeSlice(U),A.writeUInt32(this.locktime),A.writeUInt32(T),t.hash256(I)}getHash(S){return S&&this.isCoinbase()?Buffer.alloc(32,0):t.hash256(this.__toBuffer(void 0,void 0,S))}getId(){return(0,e.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(S,_){return this.__toBuffer(S,_,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(S,_){s(i.tuple(i.Number,i.Buffer),arguments),this.ins[S].script=_}setWitness(S,_){s(i.tuple(i.Number,[i.Buffer]),arguments),this.ins[S].witness=_}__toBuffer(S,_,m=!1){S||(S=Buffer.allocUnsafe(this.byteLength(m)));const T=new e.BufferWriter(S,_||0);T.writeInt32(this.version);const I=m&&this.hasWitnesses();return I&&(T.writeUInt8(w.ADVANCED_TRANSACTION_MARKER),T.writeUInt8(w.ADVANCED_TRANSACTION_FLAG)),T.writeVarInt(this.ins.length),this.ins.forEach(A=>{T.writeSlice(A.hash),T.writeUInt32(A.index),T.writeVarSlice(A.script),T.writeUInt32(A.sequence)}),T.writeVarInt(this.outs.length),this.outs.forEach(A=>{g(A)?T.writeUInt64(A.value):T.writeSlice(A.valueBuffer),T.writeVarSlice(A.script)}),I&&this.ins.forEach(A=>{T.writeVector(A.witness)}),T.writeUInt32(this.locktime),_!==void 0?S.slice(_,T.offset):S}}return no.Transaction=w,w.DEFAULT_SEQUENCE=4294967295,w.SIGHASH_DEFAULT=0,w.SIGHASH_ALL=1,w.SIGHASH_NONE=2,w.SIGHASH_SINGLE=3,w.SIGHASH_ANYONECANPAY=128,w.SIGHASH_OUTPUT_MASK=3,w.SIGHASH_INPUT_MASK=128,w.ADVANCED_TRANSACTION_MARKER=0,w.ADVANCED_TRANSACTION_FLAG=1,no}var D0;function J8(){if(D0)return eo;D0=1,Object.defineProperty(eo,"__esModule",{value:!0}),eo.Block=void 0;const e=iu(),t=xr(),n=Z8(),r=cc(),i=Kt(),{typeforce:s}=i,o=new TypeError("Cannot compute merkle root for zero transactions"),c=new TypeError("Cannot compute witness commit for non-segwit block");class a{constructor(){this.version=1,this.prevHash=void 0,this.merkleRoot=void 0,this.timestamp=0,this.witnessCommit=void 0,this.bits=0,this.nonce=0,this.transactions=void 0}static fromBuffer(p){if(p.length<80)throw new Error("Buffer too small (< 80 bytes)");const y=new e.BufferReader(p),g=new a;if(g.version=y.readInt32(),g.prevHash=y.readSlice(32),g.merkleRoot=y.readSlice(32),g.timestamp=y.readUInt32(),g.bits=y.readUInt32(),g.nonce=y.readUInt32(),p.length===80)return g;const w=()=>{const _=r.Transaction.fromBuffer(y.buffer.slice(y.offset),!0);return y.offset+=_.byteLength(),_},E=y.readVarInt();g.transactions=[];for(let _=0;_<E;++_){const m=w();g.transactions.push(m)}const S=g.getWitnessCommit();return S&&(g.witnessCommit=S),g}static fromHex(p){return a.fromBuffer(Buffer.from(p,"hex"))}static calculateTarget(p){const y=((p&4278190080)>>24)-3,g=p&8388607,w=Buffer.alloc(32,0);return w.writeUIntBE(g,29-y,3),w}static calculateMerkleRoot(p,y){if(s([{getHash:i.Function}],p),p.length===0)throw o;if(y&&!u(p))throw c;const g=p.map(E=>E.getHash(y)),w=(0,n.fastMerkleRoot)(g,t.hash256);return y?t.hash256(Buffer.concat([w,p[0].ins[0].witness[0]])):w}getWitnessCommit(){if(!u(this.transactions))return null;const p=this.transactions[0].outs.filter(g=>g.script.slice(0,6).equals(Buffer.from("6a24aa21a9ed","hex"))).map(g=>g.script.slice(6,38));if(p.length===0)return null;const y=p[p.length-1];return y instanceof Buffer&&y.length===32?y:null}hasWitnessCommit(){return this.witnessCommit instanceof Buffer&&this.witnessCommit.length===32||this.getWitnessCommit()!==null}hasWitness(){return f(this.transactions)}weight(){const p=this.byteLength(!1,!1),y=this.byteLength(!1,!0);return p*3+y}byteLength(p,y=!0){return p||!this.transactions?80:80+e.varuint.encodingLength(this.transactions.length)+this.transactions.reduce((g,w)=>g+w.byteLength(y),0)}getHash(){return t.hash256(this.toBuffer(!0))}getId(){return(0,e.reverseBuffer)(this.getHash()).toString("hex")}getUTCDate(){const p=new Date(0);return p.setUTCSeconds(this.timestamp),p}toBuffer(p){const y=Buffer.allocUnsafe(this.byteLength(p)),g=new e.BufferWriter(y);return g.writeInt32(this.version),g.writeSlice(this.prevHash),g.writeSlice(this.merkleRoot),g.writeUInt32(this.timestamp),g.writeUInt32(this.bits),g.writeUInt32(this.nonce),p||!this.transactions||(e.varuint.encode(this.transactions.length,y,g.offset),g.offset+=e.varuint.encode.bytes,this.transactions.forEach(w=>{const E=w.byteLength();w.toBuffer(y,g.offset),g.offset+=E})),y}toHex(p){return this.toBuffer(p).toString("hex")}checkTxRoots(){const p=this.hasWitnessCommit();return!p&&this.hasWitness()?!1:this.__checkMerkleRoot()&&(p?this.__checkWitnessCommit():!0)}checkProofOfWork(){const p=(0,e.reverseBuffer)(this.getHash()),y=a.calculateTarget(this.bits);return p.compare(y)<=0}__checkMerkleRoot(){if(!this.transactions)throw o;const p=a.calculateMerkleRoot(this.transactions);return this.merkleRoot.compare(p)===0}__checkWitnessCommit(){if(!this.transactions)throw o;if(!this.hasWitnessCommit())throw c;const p=a.calculateMerkleRoot(this.transactions,!0);return this.witnessCommit.compare(p)===0}}eo.Block=a;function u(l){return l instanceof Array&&l[0]&&l[0].ins&&l[0].ins instanceof Array&&l[0].ins[0]&&l[0].ins[0].witness&&l[0].ins[0].witness instanceof Array&&l[0].ins[0].witness.length>0}function f(l){return l instanceof Array&&l.some(p=>typeof p=="object"&&p.ins instanceof Array&&p.ins.some(y=>typeof y=="object"&&y.witness instanceof Array&&y.witness.length>0))}return eo}var ro={},xc={},Ac={},hf={},Qi={},es={},df={},X0;function Ut(){return X0||(X0=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),(function(t){t[t.UNSIGNED_TX=0]="UNSIGNED_TX",t[t.GLOBAL_XPUB=1]="GLOBAL_XPUB"})(e.GlobalTypes||(e.GlobalTypes={})),e.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],(function(t){t[t.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",t[t.WITNESS_UTXO=1]="WITNESS_UTXO",t[t.PARTIAL_SIG=2]="PARTIAL_SIG",t[t.SIGHASH_TYPE=3]="SIGHASH_TYPE",t[t.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",t[t.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",t[t.BIP32_DERIVATION=6]="BIP32_DERIVATION",t[t.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",t[t.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",t[t.POR_COMMITMENT=9]="POR_COMMITMENT",t[t.TAP_KEY_SIG=19]="TAP_KEY_SIG",t[t.TAP_SCRIPT_SIG=20]="TAP_SCRIPT_SIG",t[t.TAP_LEAF_SCRIPT=21]="TAP_LEAF_SCRIPT",t[t.TAP_BIP32_DERIVATION=22]="TAP_BIP32_DERIVATION",t[t.TAP_INTERNAL_KEY=23]="TAP_INTERNAL_KEY",t[t.TAP_MERKLE_ROOT=24]="TAP_MERKLE_ROOT"})(e.InputTypes||(e.InputTypes={})),e.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment","tapKeySig","tapScriptSig","tapLeafScript","tapBip32Derivation","tapInternalKey","tapMerkleRoot"],(function(t){t[t.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",t[t.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",t[t.BIP32_DERIVATION=2]="BIP32_DERIVATION",t[t.TAP_INTERNAL_KEY=5]="TAP_INTERNAL_KEY",t[t.TAP_TREE=6]="TAP_TREE",t[t.TAP_BIP32_DERIVATION=7]="TAP_BIP32_DERIVATION"})(e.OutputTypes||(e.OutputTypes={})),e.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation","tapInternalKey","tapTree","tapBip32Derivation"]})(df)),df}var Nr={},z0;function Q8(){if(z0)return Nr;z0=1,Object.defineProperty(Nr,"__esModule",{value:!0});const e=Ut(),t=o=>[...Array(o).keys()];function n(o){if(o.key[0]!==e.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+o.key.toString("hex"));if(o.key.length!==79||![2,3].includes(o.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+o.key.toString("hex"));if(o.value.length/4%1!==0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const c=o.key.slice(1),a={masterFingerprint:o.value.slice(0,4),extendedPubkey:c,path:"m"};for(const u of t(o.value.length/4-1)){const f=o.value.readUInt32LE(u*4+4),l=!!(f&2147483648),p=f&2147483647;a.path+="/"+p.toString(10)+(l?"'":"")}return a}Nr.decode=n;function r(o){const c=Buffer.from([e.GlobalTypes.GLOBAL_XPUB]),a=Buffer.concat([c,o.extendedPubkey]),u=o.path.split("/"),f=Buffer.allocUnsafe(u.length*4);o.masterFingerprint.copy(f,0);let l=4;return u.slice(1).forEach(p=>{const y=p.slice(-1)==="'";let g=2147483647&parseInt(y?p.slice(0,-1):p,10);y&&(g+=2147483648),f.writeUInt32LE(g,l),l+=4}),{key:a,value:f}}Nr.encode=r,Nr.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }";function i(o){const c=o.extendedPubkey,a=o.masterFingerprint,u=o.path;return Buffer.isBuffer(c)&&c.length===78&&[2,3].indexOf(c[45])>-1&&Buffer.isBuffer(a)&&a.length===4&&typeof u=="string"&&!!u.match(/^m(\/\d+'?)*$/)}Nr.check=i;function s(o,c,a){const u=c.extendedPubkey.toString("hex");return a.has(u)?!1:(a.add(u),o.filter(f=>f.extendedPubkey.equals(c.extendedPubkey)).length===0)}return Nr.canAddToArray=s,Nr}var vc={},Y0;function ex(){if(Y0)return vc;Y0=1,Object.defineProperty(vc,"__esModule",{value:!0});const e=Ut();function t(n){return{key:Buffer.from([e.GlobalTypes.UNSIGNED_TX]),value:n.toBuffer()}}return vc.encode=t,vc}var Ur={},Z0;function tx(){if(Z0)return Ur;Z0=1,Object.defineProperty(Ur,"__esModule",{value:!0});const e=Ut();function t(s){if(s.key[0]!==e.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+s.key.toString("hex"));return s.value}Ur.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.FINAL_SCRIPTSIG]),value:s}}Ur.encode=n,Ur.expected="Buffer";function r(s){return Buffer.isBuffer(s)}Ur.check=r;function i(s,o){return!!s&&!!o&&s.finalScriptSig===void 0}return Ur.canAdd=i,Ur}var Rr={},J0;function nx(){if(J0)return Rr;J0=1,Object.defineProperty(Rr,"__esModule",{value:!0});const e=Ut();function t(s){if(s.key[0]!==e.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+s.key.toString("hex"));return s.value}Rr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.FINAL_SCRIPTWITNESS]),value:s}}Rr.encode=n,Rr.expected="Buffer";function r(s){return Buffer.isBuffer(s)}Rr.check=r;function i(s,o){return!!s&&!!o&&s.finalScriptWitness===void 0}return Rr.canAdd=i,Rr}var Cr={},Q0;function rx(){if(Q0)return Cr;Q0=1,Object.defineProperty(Cr,"__esModule",{value:!0});const e=Ut();function t(s){if(s.key[0]!==e.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+s.key.toString("hex"));return s.value}Cr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.NON_WITNESS_UTXO]),value:s}}Cr.encode=n,Cr.expected="Buffer";function r(s){return Buffer.isBuffer(s)}Cr.check=r;function i(s,o){return!!s&&!!o&&s.nonWitnessUtxo===void 0}return Cr.canAdd=i,Cr}var Hr={},ep;function ix(){if(ep)return Hr;ep=1,Object.defineProperty(Hr,"__esModule",{value:!0});const e=Ut();function t(o){if(o.key[0]!==e.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+o.key.toString("hex"));if(!(o.key.length===34||o.key.length===66)||![2,3,4].includes(o.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+o.key.toString("hex"));return{pubkey:o.key.slice(1),signature:o.value}}Hr.decode=t;function n(o){const c=Buffer.from([e.InputTypes.PARTIAL_SIG]);return{key:Buffer.concat([c,o.pubkey]),value:o.signature}}Hr.encode=n,Hr.expected="{ pubkey: Buffer; signature: Buffer; }";function r(o){return Buffer.isBuffer(o.pubkey)&&Buffer.isBuffer(o.signature)&&[33,65].includes(o.pubkey.length)&&[2,3,4].includes(o.pubkey[0])&&i(o.signature)}Hr.check=r;function i(o){if(!Buffer.isBuffer(o)||o.length<9||o[0]!==48||o.length!==o[1]+3||o[2]!==2)return!1;const c=o[3];if(c>33||c<1||o[3+c+1]!==2)return!1;const a=o[3+c+2];return!(a>33||a<1||o.length!==3+c+2+a+2)}function s(o,c,a){const u=c.pubkey.toString("hex");return a.has(u)?!1:(a.add(u),o.filter(f=>f.pubkey.equals(c.pubkey)).length===0)}return Hr.canAddToArray=s,Hr}var Fr={},tp;function sx(){if(tp)return Fr;tp=1,Object.defineProperty(Fr,"__esModule",{value:!0});const e=Ut();function t(s){if(s.key[0]!==e.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+s.key.toString("hex"));return s.value.toString("utf8")}Fr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.POR_COMMITMENT]),value:Buffer.from(s,"utf8")}}Fr.encode=n,Fr.expected="string";function r(s){return typeof s=="string"}Fr.check=r;function i(s,o){return!!s&&!!o&&s.porCommitment===void 0}return Fr.canAdd=i,Fr}var Mr={},np;function ox(){if(np)return Mr;np=1,Object.defineProperty(Mr,"__esModule",{value:!0});const e=Ut();function t(s){if(s.key[0]!==e.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+s.key.toString("hex"));return s.value.readUInt32LE(0)}Mr.decode=t;function n(s){const o=Buffer.from([e.InputTypes.SIGHASH_TYPE]),c=Buffer.allocUnsafe(4);return c.writeUInt32LE(s,0),{key:o,value:c}}Mr.encode=n,Mr.expected="number";function r(s){return typeof s=="number"}Mr.check=r;function i(s,o){return!!s&&!!o&&s.sighashType===void 0}return Mr.canAdd=i,Mr}var qr={},rp;function cx(){if(rp)return qr;rp=1,Object.defineProperty(qr,"__esModule",{value:!0});const e=Ut();function t(s){if(s.key[0]!==e.InputTypes.TAP_KEY_SIG||s.key.length!==1)throw new Error("Decode Error: could not decode tapKeySig with key 0x"+s.key.toString("hex"));if(!r(s.value))throw new Error("Decode Error: tapKeySig not a valid 64-65-byte BIP340 signature");return s.value}qr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.TAP_KEY_SIG]),value:s}}qr.encode=n,qr.expected="Buffer";function r(s){return Buffer.isBuffer(s)&&(s.length===64||s.length===65)}qr.check=r;function i(s,o){return!!s&&!!o&&s.tapKeySig===void 0}return qr.canAdd=i,qr}var Vr={},ip;function ax(){if(ip)return Vr;ip=1,Object.defineProperty(Vr,"__esModule",{value:!0});const e=Ut();function t(s){if(s.key[0]!==e.InputTypes.TAP_LEAF_SCRIPT)throw new Error("Decode Error: could not decode tapLeafScript with key 0x"+s.key.toString("hex"));if((s.key.length-2)%32!==0)throw new Error("Decode Error: tapLeafScript has invalid control block in key 0x"+s.key.toString("hex"));const o=s.value[s.value.length-1];if((s.key[1]&254)!==o)throw new Error("Decode Error: tapLeafScript bad leaf version in key 0x"+s.key.toString("hex"));const c=s.value.slice(0,-1);return{controlBlock:s.key.slice(1),script:c,leafVersion:o}}Vr.decode=t;function n(s){const o=Buffer.from([e.InputTypes.TAP_LEAF_SCRIPT]),c=Buffer.from([s.leafVersion]);return{key:Buffer.concat([o,s.controlBlock]),value:Buffer.concat([s.script,c])}}Vr.encode=n,Vr.expected="{ controlBlock: Buffer; leafVersion: number, script: Buffer; }";function r(s){return Buffer.isBuffer(s.controlBlock)&&(s.controlBlock.length-1)%32===0&&(s.controlBlock[0]&254)===s.leafVersion&&Buffer.isBuffer(s.script)}Vr.check=r;function i(s,o,c){const a=o.controlBlock.toString("hex");return c.has(a)?!1:(c.add(a),s.filter(u=>u.controlBlock.equals(o.controlBlock)).length===0)}return Vr.canAddToArray=i,Vr}var Lr={},sp;function ux(){if(sp)return Lr;sp=1,Object.defineProperty(Lr,"__esModule",{value:!0});const e=Ut();function t(s){if(s.key[0]!==e.InputTypes.TAP_MERKLE_ROOT||s.key.length!==1)throw new Error("Decode Error: could not decode tapMerkleRoot with key 0x"+s.key.toString("hex"));if(!r(s.value))throw new Error("Decode Error: tapMerkleRoot not a 32-byte hash");return s.value}Lr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.TAP_MERKLE_ROOT]),value:s}}Lr.encode=n,Lr.expected="Buffer";function r(s){return Buffer.isBuffer(s)&&s.length===32}Lr.check=r;function i(s,o){return!!s&&!!o&&s.tapMerkleRoot===void 0}return Lr.canAdd=i,Lr}var $r={},op;function fx(){if(op)return $r;op=1,Object.defineProperty($r,"__esModule",{value:!0});const e=Ut();function t(s){if(s.key[0]!==e.InputTypes.TAP_SCRIPT_SIG)throw new Error("Decode Error: could not decode tapScriptSig with key 0x"+s.key.toString("hex"));if(s.key.length!==65)throw new Error("Decode Error: tapScriptSig has invalid key 0x"+s.key.toString("hex"));if(s.value.length!==64&&s.value.length!==65)throw new Error("Decode Error: tapScriptSig has invalid signature in key 0x"+s.key.toString("hex"));const o=s.key.slice(1,33),c=s.key.slice(33);return{pubkey:o,leafHash:c,signature:s.value}}$r.decode=t;function n(s){const o=Buffer.from([e.InputTypes.TAP_SCRIPT_SIG]);return{key:Buffer.concat([o,s.pubkey,s.leafHash]),value:s.signature}}$r.encode=n,$r.expected="{ pubkey: Buffer; leafHash: Buffer; signature: Buffer; }";function r(s){return Buffer.isBuffer(s.pubkey)&&Buffer.isBuffer(s.leafHash)&&Buffer.isBuffer(s.signature)&&s.pubkey.length===32&&s.leafHash.length===32&&(s.signature.length===64||s.signature.length===65)}$r.check=r;function i(s,o,c){const a=o.pubkey.toString("hex")+o.leafHash.toString("hex");return c.has(a)?!1:(c.add(a),s.filter(u=>u.pubkey.equals(o.pubkey)&&u.leafHash.equals(o.leafHash)).length===0)}return $r.canAddToArray=i,$r}var Kr={},ir={},ts={},cp;function Di(){if(cp)return ts;cp=1,Object.defineProperty(ts,"__esModule",{value:!0});const e=9007199254740991;function t(s){if(s<0||s>e||s%1!==0)throw new RangeError("value out of range")}function n(s,o,c){if(t(s),o||(o=Buffer.allocUnsafe(i(s))),!Buffer.isBuffer(o))throw new TypeError("buffer must be a Buffer instance");return c||(c=0),s<253?(o.writeUInt8(s,c),Object.assign(n,{bytes:1})):s<=65535?(o.writeUInt8(253,c),o.writeUInt16LE(s,c+1),Object.assign(n,{bytes:3})):s<=4294967295?(o.writeUInt8(254,c),o.writeUInt32LE(s,c+1),Object.assign(n,{bytes:5})):(o.writeUInt8(255,c),o.writeUInt32LE(s>>>0,c+1),o.writeUInt32LE(s/4294967296|0,c+5),Object.assign(n,{bytes:9})),o}ts.encode=n;function r(s,o){if(!Buffer.isBuffer(s))throw new TypeError("buffer must be a Buffer instance");o||(o=0);const c=s.readUInt8(o);if(c<253)return Object.assign(r,{bytes:1}),c;if(c===253)return Object.assign(r,{bytes:3}),s.readUInt16LE(o+1);if(c===254)return Object.assign(r,{bytes:5}),s.readUInt32LE(o+1);{Object.assign(r,{bytes:9});const a=s.readUInt32LE(o+1),f=s.readUInt32LE(o+5)*4294967296+a;return t(f),f}}ts.decode=r;function i(s){return t(s),s<253?1:s<=65535?3:s<=4294967295?5:9}return ts.encodingLength=i,ts}var ap;function Jl(){if(ap)return ir;ap=1,Object.defineProperty(ir,"__esModule",{value:!0});const e=Di();ir.range=c=>[...Array(c).keys()];function t(c){if(c.length<1)return c;let a=c.length-1,u=0;for(let f=0;f<c.length/2;f++)u=c[f],c[f]=c[a],c[a]=u,a--;return c}ir.reverseBuffer=t;function n(c){const a=c.map(r);return a.push(Buffer.from([0])),Buffer.concat(a)}ir.keyValsToBuffer=n;function r(c){const a=c.key.length,u=c.value.length,f=e.encodingLength(a),l=e.encodingLength(u),p=Buffer.allocUnsafe(f+a+l+u);return e.encode(a,p,0),c.key.copy(p,f),e.encode(u,p,f+a),c.value.copy(p,f+a+l),p}ir.keyValToBuffer=r;function i(c,a){if(typeof c!="number")throw new Error("cannot write a non-number as a number");if(c<0)throw new Error("specified a negative value for writing an unsigned value");if(c>a)throw new Error("RangeError: value out of range");if(Math.floor(c)!==c)throw new Error("value has a fractional component")}function s(c,a){const u=c.readUInt32LE(a);let f=c.readUInt32LE(a+4);return f*=4294967296,i(f+u,9007199254740991),f+u}ir.readUInt64LE=s;function o(c,a,u){return i(a,9007199254740991),c.writeInt32LE(a&-1,u),c.writeUInt32LE(Math.floor(a/4294967296),u+4),u+8}return ir.writeUInt64LE=o,ir}var up;function lx(){if(up)return Kr;up=1,Object.defineProperty(Kr,"__esModule",{value:!0});const e=Ut(),t=Jl(),n=Di();function r(c){if(c.key[0]!==e.InputTypes.WITNESS_UTXO)throw new Error("Decode Error: could not decode witnessUtxo with key 0x"+c.key.toString("hex"));const a=t.readUInt64LE(c.value,0);let u=8;const f=n.decode(c.value,u);u+=n.encodingLength(f);const l=c.value.slice(u);if(l.length!==f)throw new Error("Decode Error: WITNESS_UTXO script is not proper length");return{script:l,value:a}}Kr.decode=r;function i(c){const{script:a,value:u}=c,f=n.encodingLength(a.length),l=Buffer.allocUnsafe(8+f+a.length);return t.writeUInt64LE(l,u,0),n.encode(a.length,l,8),a.copy(l,8+f),{key:Buffer.from([e.InputTypes.WITNESS_UTXO]),value:l}}Kr.encode=i,Kr.expected="{ script: Buffer; value: number; }";function s(c){return Buffer.isBuffer(c.script)&&typeof c.value=="number"}Kr.check=s;function o(c,a){return!!c&&!!a&&c.witnessUtxo===void 0}return Kr.canAdd=o,Kr}var jr={},fp;function hx(){if(fp)return jr;fp=1,Object.defineProperty(jr,"__esModule",{value:!0});const e=Ut(),t=Di();function n(o){if(o.key[0]!==e.OutputTypes.TAP_TREE||o.key.length!==1)throw new Error("Decode Error: could not decode tapTree with key 0x"+o.key.toString("hex"));let c=0;const a=[];for(;c<o.value.length;){const u=o.value[c++],f=o.value[c++],l=t.decode(o.value,c);c+=t.encodingLength(l),a.push({depth:u,leafVersion:f,script:o.value.slice(c,c+l)}),c+=l}return{leaves:a}}jr.decode=n;function r(o){const c=Buffer.from([e.OutputTypes.TAP_TREE]),a=[].concat(...o.leaves.map(u=>[Buffer.of(u.depth,u.leafVersion),t.encode(u.script.length),u.script]));return{key:c,value:Buffer.concat(a)}}jr.encode=r,jr.expected="{ leaves: [{ depth: number; leafVersion: number, script: Buffer; }] }";function i(o){return Array.isArray(o.leaves)&&o.leaves.every(c=>c.depth>=0&&c.depth<=128&&(c.leafVersion&254)===c.leafVersion&&Buffer.isBuffer(c.script))}jr.check=i;function s(o,c){return!!o&&!!c&&o.tapTree===void 0}return jr.canAdd=s,jr}var Bc={},lp;function rw(){if(lp)return Bc;lp=1,Object.defineProperty(Bc,"__esModule",{value:!0});const e=r=>[...Array(r).keys()],t=r=>r.length===33&&[2,3].includes(r[0])||r.length===65&&r[0]===4;function n(r,i=t){function s(f){if(f.key[0]!==r)throw new Error("Decode Error: could not decode bip32Derivation with key 0x"+f.key.toString("hex"));const l=f.key.slice(1);if(!i(l))throw new Error("Decode Error: bip32Derivation has invalid pubkey in key 0x"+f.key.toString("hex"));if(f.value.length/4%1!==0)throw new Error("Decode Error: Input BIP32_DERIVATION value length should be multiple of 4");const p={masterFingerprint:f.value.slice(0,4),pubkey:l,path:"m"};for(const y of e(f.value.length/4-1)){const g=f.value.readUInt32LE(y*4+4),w=!!(g&2147483648),E=g&2147483647;p.path+="/"+E.toString(10)+(w?"'":"")}return p}function o(f){const l=Buffer.from([r]),p=Buffer.concat([l,f.pubkey]),y=f.path.split("/"),g=Buffer.allocUnsafe(y.length*4);f.masterFingerprint.copy(g,0);let w=4;return y.slice(1).forEach(E=>{const S=E.slice(-1)==="'";let _=2147483647&parseInt(S?E.slice(0,-1):E,10);S&&(_+=2147483648),g.writeUInt32LE(_,w),w+=4}),{key:p,value:g}}const c="{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }";function a(f){return Buffer.isBuffer(f.pubkey)&&Buffer.isBuffer(f.masterFingerprint)&&typeof f.path=="string"&&i(f.pubkey)&&f.masterFingerprint.length===4}function u(f,l,p){const y=l.pubkey.toString("hex");return p.has(y)?!1:(p.add(y),f.filter(g=>g.pubkey.equals(l.pubkey)).length===0)}return{decode:s,encode:o,check:a,expected:c,canAddToArray:u}}return Bc.makeConverter=n,Bc}var Ic={},hp;function dx(){if(hp)return Ic;hp=1,Object.defineProperty(Ic,"__esModule",{value:!0});function e(t){return n;function n(r){let i;if(t.includes(r.key[0])&&(i=r.key.slice(1),!(i.length===33||i.length===65)||![2,3,4].includes(i[0])))throw new Error("Format Error: invalid pubkey in key 0x"+r.key.toString("hex"));return i}}return Ic.makeChecker=e,Ic}var Oc={},dp;function px(){if(dp)return Oc;dp=1,Object.defineProperty(Oc,"__esModule",{value:!0});function e(t){function n(c){if(c.key[0]!==t)throw new Error("Decode Error: could not decode redeemScript with key 0x"+c.key.toString("hex"));return c.value}function r(c){return{key:Buffer.from([t]),value:c}}const i="Buffer";function s(c){return Buffer.isBuffer(c)}function o(c,a){return!!c&&!!a&&c.redeemScript===void 0}return{decode:n,encode:r,check:s,expected:i,canAdd:o}}return Oc.makeConverter=e,Oc}var Pc={},pp;function yx(){if(pp)return Pc;pp=1,Object.defineProperty(Pc,"__esModule",{value:!0});const e=Di(),t=rw(),n=i=>i.length===32;function r(i){const s=t.makeConverter(i,n);function o(f){const l=e.decode(f.value),p=e.encodingLength(l),y=s.decode({key:f.key,value:f.value.slice(p+l*32)}),g=new Array(l);for(let w=0,E=p;w<l;w++,E+=32)g[w]=f.value.slice(E,E+32);return Object.assign({},y,{leafHashes:g})}function c(f){const l=s.encode(f),p=e.encodingLength(f.leafHashes.length),y=Buffer.allocUnsafe(p);e.encode(f.leafHashes.length,y);const g=Buffer.concat([y,...f.leafHashes,l.value]);return Object.assign({},l,{value:g})}const a="{ masterFingerprint: Buffer; pubkey: Buffer; path: string; leafHashes: Buffer[]; }";function u(f){return Array.isArray(f.leafHashes)&&f.leafHashes.every(l=>Buffer.isBuffer(l)&&l.length===32)&&s.check(f)}return{decode:o,encode:c,check:u,expected:a,canAddToArray:s.canAddToArray}}return Pc.makeConverter=r,Pc}var kc={},yp;function gx(){if(yp)return kc;yp=1,Object.defineProperty(kc,"__esModule",{value:!0});function e(t){function n(c){if(c.key[0]!==t||c.key.length!==1)throw new Error("Decode Error: could not decode tapInternalKey with key 0x"+c.key.toString("hex"));if(c.value.length!==32)throw new Error("Decode Error: tapInternalKey not a 32-byte x-only pubkey");return c.value}function r(c){return{key:Buffer.from([t]),value:c}}const i="Buffer";function s(c){return Buffer.isBuffer(c)&&c.length===32}function o(c,a){return!!c&&!!a&&c.tapInternalKey===void 0}return{decode:n,encode:r,check:s,expected:i,canAdd:o}}return kc.makeConverter=e,kc}var Nc={},gp;function wx(){if(gp)return Nc;gp=1,Object.defineProperty(Nc,"__esModule",{value:!0});function e(t){function n(c){if(c.key[0]!==t)throw new Error("Decode Error: could not decode witnessScript with key 0x"+c.key.toString("hex"));return c.value}function r(c){return{key:Buffer.from([t]),value:c}}const i="Buffer";function s(c){return Buffer.isBuffer(c)}function o(c,a){return!!c&&!!a&&c.witnessScript===void 0}return{decode:n,encode:r,check:s,expected:i,canAdd:o}}return Nc.makeConverter=e,Nc}var wp;function Ql(){if(wp)return es;wp=1,Object.defineProperty(es,"__esModule",{value:!0});const e=Ut(),t=Q8(),n=ex(),r=tx(),i=nx(),s=rx(),o=ix(),c=sx(),a=ox(),u=cx(),f=ax(),l=ux(),p=fx(),y=lx(),g=hx(),w=rw(),E=dx(),S=px(),_=yx(),m=gx(),T=wx(),I={unsignedTx:n,globalXpub:t,checkPubkey:E.makeChecker([])};es.globals=I;const A={nonWitnessUtxo:s,partialSig:o,sighashType:a,finalScriptSig:r,finalScriptWitness:i,porCommitment:c,witnessUtxo:y,bip32Derivation:w.makeConverter(e.InputTypes.BIP32_DERIVATION),redeemScript:S.makeConverter(e.InputTypes.REDEEM_SCRIPT),witnessScript:T.makeConverter(e.InputTypes.WITNESS_SCRIPT),checkPubkey:E.makeChecker([e.InputTypes.PARTIAL_SIG,e.InputTypes.BIP32_DERIVATION]),tapKeySig:u,tapScriptSig:p,tapLeafScript:f,tapBip32Derivation:_.makeConverter(e.InputTypes.TAP_BIP32_DERIVATION),tapInternalKey:m.makeConverter(e.InputTypes.TAP_INTERNAL_KEY),tapMerkleRoot:l};es.inputs=A;const U={bip32Derivation:w.makeConverter(e.OutputTypes.BIP32_DERIVATION),redeemScript:S.makeConverter(e.OutputTypes.REDEEM_SCRIPT),witnessScript:T.makeConverter(e.OutputTypes.WITNESS_SCRIPT),checkPubkey:E.makeChecker([e.OutputTypes.BIP32_DERIVATION]),tapBip32Derivation:_.makeConverter(e.OutputTypes.TAP_BIP32_DERIVATION),tapTree:g,tapInternalKey:m.makeConverter(e.OutputTypes.TAP_INTERNAL_KEY)};return es.outputs=U,es}var mp;function mx(){if(mp)return Qi;mp=1,Object.defineProperty(Qi,"__esModule",{value:!0});const e=Ql(),t=Jl(),n=Di(),r=Ut();function i(c,a){let u=0;function f(){const U=n.decode(c,u);u+=n.encodingLength(U);const M=c.slice(u,u+U);return u+=U,M}function l(){const U=c.readUInt32BE(u);return u+=4,U}function p(){const U=c.readUInt8(u);return u+=1,U}function y(){const U=f(),M=f();return{key:U,value:M}}function g(){if(u>=c.length)throw new Error("Format Error: Unexpected End of PSBT");const U=c.readUInt8(u)===0;return U&&u++,U}if(l()!==1886610036)throw new Error("Format Error: Invalid Magic Number");if(p()!==255)throw new Error("Format Error: Magic Number must be followed by 0xff separator");const w=[],E={};for(;!g();){const U=y(),M=U.key.toString("hex");if(E[M])throw new Error("Format Error: Keys must be unique for global keymap: key "+M);E[M]=1,w.push(U)}const S=w.filter(U=>U.key[0]===r.GlobalTypes.UNSIGNED_TX);if(S.length!==1)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const _=a(S[0].value),{inputCount:m,outputCount:T}=_.getInputOutputCounts(),I=[],A=[];for(const U of t.range(m)){const M={},v=[];for(;!g();){const R=y(),V=R.key.toString("hex");if(M[V])throw new Error("Format Error: Keys must be unique for each input: input index "+U+" key "+V);M[V]=1,v.push(R)}I.push(v)}for(const U of t.range(T)){const M={},v=[];for(;!g();){const R=y(),V=R.key.toString("hex");if(M[V])throw new Error("Format Error: Keys must be unique for each output: output index "+U+" key "+V);M[V]=1,v.push(R)}A.push(v)}return o(_,{globalMapKeyVals:w,inputKeyVals:I,outputKeyVals:A})}Qi.psbtFromBuffer=i;function s(c,a,u){if(!a.equals(Buffer.from([u])))throw new Error(`Format Error: Invalid ${c} key: ${a.toString("hex")}`)}Qi.checkKeyBuffer=s;function o(c,{globalMapKeyVals:a,inputKeyVals:u,outputKeyVals:f}){const l={unsignedTx:c};let p=0;for(const S of a)switch(S.key[0]){case r.GlobalTypes.UNSIGNED_TX:if(s("global",S.key,r.GlobalTypes.UNSIGNED_TX),p>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");p++;break;case r.GlobalTypes.GLOBAL_XPUB:l.globalXpub===void 0&&(l.globalXpub=[]),l.globalXpub.push(e.globals.globalXpub.decode(S));break;default:l.unknownKeyVals||(l.unknownKeyVals=[]),l.unknownKeyVals.push(S)}const y=u.length,g=f.length,w=[],E=[];for(const S of t.range(y)){const _={};for(const m of u[S])switch(e.inputs.checkPubkey(m),m.key[0]){case r.InputTypes.NON_WITNESS_UTXO:if(s("input",m.key,r.InputTypes.NON_WITNESS_UTXO),_.nonWitnessUtxo!==void 0)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");_.nonWitnessUtxo=e.inputs.nonWitnessUtxo.decode(m);break;case r.InputTypes.WITNESS_UTXO:if(s("input",m.key,r.InputTypes.WITNESS_UTXO),_.witnessUtxo!==void 0)throw new Error("Format Error: Input has multiple WITNESS_UTXO");_.witnessUtxo=e.inputs.witnessUtxo.decode(m);break;case r.InputTypes.PARTIAL_SIG:_.partialSig===void 0&&(_.partialSig=[]),_.partialSig.push(e.inputs.partialSig.decode(m));break;case r.InputTypes.SIGHASH_TYPE:if(s("input",m.key,r.InputTypes.SIGHASH_TYPE),_.sighashType!==void 0)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");_.sighashType=e.inputs.sighashType.decode(m);break;case r.InputTypes.REDEEM_SCRIPT:if(s("input",m.key,r.InputTypes.REDEEM_SCRIPT),_.redeemScript!==void 0)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");_.redeemScript=e.inputs.redeemScript.decode(m);break;case r.InputTypes.WITNESS_SCRIPT:if(s("input",m.key,r.InputTypes.WITNESS_SCRIPT),_.witnessScript!==void 0)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");_.witnessScript=e.inputs.witnessScript.decode(m);break;case r.InputTypes.BIP32_DERIVATION:_.bip32Derivation===void 0&&(_.bip32Derivation=[]),_.bip32Derivation.push(e.inputs.bip32Derivation.decode(m));break;case r.InputTypes.FINAL_SCRIPTSIG:s("input",m.key,r.InputTypes.FINAL_SCRIPTSIG),_.finalScriptSig=e.inputs.finalScriptSig.decode(m);break;case r.InputTypes.FINAL_SCRIPTWITNESS:s("input",m.key,r.InputTypes.FINAL_SCRIPTWITNESS),_.finalScriptWitness=e.inputs.finalScriptWitness.decode(m);break;case r.InputTypes.POR_COMMITMENT:s("input",m.key,r.InputTypes.POR_COMMITMENT),_.porCommitment=e.inputs.porCommitment.decode(m);break;case r.InputTypes.TAP_KEY_SIG:s("input",m.key,r.InputTypes.TAP_KEY_SIG),_.tapKeySig=e.inputs.tapKeySig.decode(m);break;case r.InputTypes.TAP_SCRIPT_SIG:_.tapScriptSig===void 0&&(_.tapScriptSig=[]),_.tapScriptSig.push(e.inputs.tapScriptSig.decode(m));break;case r.InputTypes.TAP_LEAF_SCRIPT:_.tapLeafScript===void 0&&(_.tapLeafScript=[]),_.tapLeafScript.push(e.inputs.tapLeafScript.decode(m));break;case r.InputTypes.TAP_BIP32_DERIVATION:_.tapBip32Derivation===void 0&&(_.tapBip32Derivation=[]),_.tapBip32Derivation.push(e.inputs.tapBip32Derivation.decode(m));break;case r.InputTypes.TAP_INTERNAL_KEY:s("input",m.key,r.InputTypes.TAP_INTERNAL_KEY),_.tapInternalKey=e.inputs.tapInternalKey.decode(m);break;case r.InputTypes.TAP_MERKLE_ROOT:s("input",m.key,r.InputTypes.TAP_MERKLE_ROOT),_.tapMerkleRoot=e.inputs.tapMerkleRoot.decode(m);break;default:_.unknownKeyVals||(_.unknownKeyVals=[]),_.unknownKeyVals.push(m)}w.push(_)}for(const S of t.range(g)){const _={};for(const m of f[S])switch(e.outputs.checkPubkey(m),m.key[0]){case r.OutputTypes.REDEEM_SCRIPT:if(s("output",m.key,r.OutputTypes.REDEEM_SCRIPT),_.redeemScript!==void 0)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");_.redeemScript=e.outputs.redeemScript.decode(m);break;case r.OutputTypes.WITNESS_SCRIPT:if(s("output",m.key,r.OutputTypes.WITNESS_SCRIPT),_.witnessScript!==void 0)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");_.witnessScript=e.outputs.witnessScript.decode(m);break;case r.OutputTypes.BIP32_DERIVATION:_.bip32Derivation===void 0&&(_.bip32Derivation=[]),_.bip32Derivation.push(e.outputs.bip32Derivation.decode(m));break;case r.OutputTypes.TAP_INTERNAL_KEY:s("output",m.key,r.OutputTypes.TAP_INTERNAL_KEY),_.tapInternalKey=e.outputs.tapInternalKey.decode(m);break;case r.OutputTypes.TAP_TREE:s("output",m.key,r.OutputTypes.TAP_TREE),_.tapTree=e.outputs.tapTree.decode(m);break;case r.OutputTypes.TAP_BIP32_DERIVATION:_.tapBip32Derivation===void 0&&(_.tapBip32Derivation=[]),_.tapBip32Derivation.push(e.outputs.tapBip32Derivation.decode(m));break;default:_.unknownKeyVals||(_.unknownKeyVals=[]),_.unknownKeyVals.push(m)}E.push(_)}return{globalMap:l,inputs:w,outputs:E}}return Qi.psbtFromKeyVals=o,Qi}var io={},bp;function bx(){if(bp)return io;bp=1,Object.defineProperty(io,"__esModule",{value:!0});const e=Ql(),t=Jl();function n({globalMap:o,inputs:c,outputs:a}){const{globalKeyVals:u,inputKeyVals:f,outputKeyVals:l}=s({globalMap:o,inputs:c,outputs:a}),p=t.keyValsToBuffer(u),y=S=>S.length===0?[Buffer.from([0])]:S.map(t.keyValsToBuffer),g=y(f),w=y(l),E=Buffer.allocUnsafe(5);return E.writeUIntBE(482972169471,0,5),Buffer.concat([E,p].concat(g,w))}io.psbtToBuffer=n;const r=(o,c)=>o.key.compare(c.key);function i(o,c){const a=new Set,u=Object.entries(o).reduce((l,[p,y])=>{if(p==="unknownKeyVals")return l;const g=c[p];if(g===void 0)return l;const w=(Array.isArray(y)?y:[y]).map(g.encode);return w.map(S=>S.key.toString("hex")).forEach(S=>{if(a.has(S))throw new Error("Serialize Error: Duplicate key: "+S);a.add(S)}),l.concat(w)},[]),f=o.unknownKeyVals?o.unknownKeyVals.filter(l=>!a.has(l.key.toString("hex"))):[];return u.concat(f).sort(r)}function s({globalMap:o,inputs:c,outputs:a}){return{globalKeyVals:i(o,e.globals),inputKeyVals:c.map(u=>i(u,e.inputs)),outputKeyVals:a.map(u=>i(u,e.outputs))}}return io.psbtToKeyVals=s,io}var Ep;function iw(){return Ep||(Ep=1,(function(e){function t(n){for(var r in n)e.hasOwnProperty(r)||(e[r]=n[r])}Object.defineProperty(e,"__esModule",{value:!0}),t(mx()),t(bx())})(hf)),hf}var _p;function Ex(){if(_p)return Ac;_p=1,Object.defineProperty(Ac,"__esModule",{value:!0});const e=iw();function t(s){const o=s[0],c=e.psbtToKeyVals(o),a=s.slice(1);if(a.length===0)throw new Error("Combine: Nothing to combine");const u=r(o);if(u===void 0)throw new Error("Combine: Self missing transaction");const f=i(c.globalKeyVals),l=c.inputKeyVals.map(i),p=c.outputKeyVals.map(i);for(const y of a){const g=r(y);if(g===void 0||!g.toBuffer().equals(u.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const w=e.psbtToKeyVals(y);i(w.globalKeyVals).forEach(n(f,c.globalKeyVals,w.globalKeyVals)),w.inputKeyVals.map(i).forEach((m,T)=>m.forEach(n(l[T],c.inputKeyVals[T],w.inputKeyVals[T]))),w.outputKeyVals.map(i).forEach((m,T)=>m.forEach(n(p[T],c.outputKeyVals[T],w.outputKeyVals[T])))}return e.psbtFromKeyVals(u,{globalMapKeyVals:c.globalKeyVals,inputKeyVals:c.inputKeyVals,outputKeyVals:c.outputKeyVals})}Ac.combine=t;function n(s,o,c){return a=>{if(s.has(a))return;const u=c.filter(f=>f.key.toString("hex")===a)[0];o.push(u),s.add(a)}}function r(s){return s.globalMap.unsignedTx}function i(s){const o=new Set;return s.forEach(c=>{const a=c.key.toString("hex");if(o.has(a))throw new Error("Combine: KeyValue Map keys should be unique");o.add(a)}),o}return Ac}var pf={},Sp;function sw(){return Sp||(Sp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=Ql();function n(y,g){const w=y[g];if(w===void 0)throw new Error(`No input #${g}`);return w}e.checkForInput=n;function r(y,g){const w=y[g];if(w===void 0)throw new Error(`No output #${g}`);return w}e.checkForOutput=r;function i(y,g,w){if(y.key[0]<w)throw new Error("Use the method for your specific key instead of addUnknownKeyVal*");if(g&&g.filter(E=>E.key.equals(y.key)).length!==0)throw new Error(`Duplicate Key: ${y.key.toString("hex")}`)}e.checkHasKey=i;function s(y){let g=0;return Object.keys(y).forEach(w=>{Number(isNaN(Number(w)))&&g++}),g}e.getEnumLength=s;function o(y,g){let w=!1;if(g.nonWitnessUtxo||g.witnessUtxo){const E=!!g.redeemScript,S=!!g.witnessScript,_=!E||!!g.finalScriptSig,m=!S||!!g.finalScriptWitness,T=!!g.finalScriptSig||!!g.finalScriptWitness;w=_&&m&&T}if(w===!1)throw new Error(`Input #${y} has too much or too little data to clean`)}e.inputCheckUncleanFinalized=o;function c(y,g,w,E){throw new Error(`Data for ${y} key ${g} is incorrect: Expected ${w} and got ${JSON.stringify(E)}`)}function a(y){return(g,w)=>{for(const E of Object.keys(g)){const S=g[E],{canAdd:_,canAddToArray:m,check:T,expected:I}=t[y+"s"][E]||{},A=!!m;if(T)if(A){if(!Array.isArray(S)||w[E]&&!Array.isArray(w[E]))throw new Error(`Key type ${E} must be an array`);S.every(T)||c(y,E,I,S);const U=w[E]||[],M=new Set;if(!S.every(v=>m(U,v,M)))throw new Error("Can not add duplicate data to array");w[E]=U.concat(S)}else{if(T(S)||c(y,E,I,S),!_(w,S))throw new Error(`Can not add duplicate data to ${y}`);w[E]=S}}}}e.updateGlobal=a("global"),e.updateInput=a("input"),e.updateOutput=a("output");function u(y,g){const w=y.length-1,E=n(y,w);e.updateInput(g,E)}e.addInputAttributes=u;function f(y,g){const w=y.length-1,E=r(y,w);e.updateOutput(g,E)}e.addOutputAttributes=f;function l(y,g){if(!Buffer.isBuffer(g)||g.length<4)throw new Error("Set Version: Invalid Transaction");return g.writeUInt32LE(y,0),g}e.defaultVersionSetter=l;function p(y,g){if(!Buffer.isBuffer(g)||g.length<4)throw new Error("Set Locktime: Invalid Transaction");return g.writeUInt32LE(y,g.length-4),g}e.defaultLocktimeSetter=p})(pf)),pf}var Tp;function _x(){if(Tp)return xc;Tp=1,Object.defineProperty(xc,"__esModule",{value:!0});const e=Ex(),t=iw(),n=Ut(),r=sw();class i{constructor(o){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:o}}static fromBase64(o,c){const a=Buffer.from(o,"base64");return this.fromBuffer(a,c)}static fromHex(o,c){const a=Buffer.from(o,"hex");return this.fromBuffer(a,c)}static fromBuffer(o,c){const a=t.psbtFromBuffer(o,c),u=new this(a.globalMap.unsignedTx);return Object.assign(u,a),u}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return t.psbtToBuffer(this)}updateGlobal(o){return r.updateGlobal(o,this.globalMap),this}updateInput(o,c){const a=r.checkForInput(this.inputs,o);return r.updateInput(c,a),this}updateOutput(o,c){const a=r.checkForOutput(this.outputs,o);return r.updateOutput(c,a),this}addUnknownKeyValToGlobal(o){return r.checkHasKey(o,this.globalMap.unknownKeyVals,r.getEnumLength(n.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(o),this}addUnknownKeyValToInput(o,c){const a=r.checkForInput(this.inputs,o);return r.checkHasKey(c,a.unknownKeyVals,r.getEnumLength(n.InputTypes)),a.unknownKeyVals||(a.unknownKeyVals=[]),a.unknownKeyVals.push(c),this}addUnknownKeyValToOutput(o,c){const a=r.checkForOutput(this.outputs,o);return r.checkHasKey(c,a.unknownKeyVals,r.getEnumLength(n.OutputTypes)),a.unknownKeyVals||(a.unknownKeyVals=[]),a.unknownKeyVals.push(c),this}addInput(o){this.globalMap.unsignedTx.addInput(o),this.inputs.push({unknownKeyVals:[]});const c=o.unknownKeyVals||[],a=this.inputs.length-1;if(!Array.isArray(c))throw new Error("unknownKeyVals must be an Array");return c.forEach(u=>this.addUnknownKeyValToInput(a,u)),r.addInputAttributes(this.inputs,o),this}addOutput(o){this.globalMap.unsignedTx.addOutput(o),this.outputs.push({unknownKeyVals:[]});const c=o.unknownKeyVals||[],a=this.outputs.length-1;if(!Array.isArray(c))throw new Error("unknownKeyVals must be an Array");return c.forEach(u=>this.addUnknownKeyValToOutput(a,u)),r.addOutputAttributes(this.outputs,o),this}clearFinalizedInput(o){const c=r.checkForInput(this.inputs,o);r.inputCheckUncleanFinalized(o,c);for(const a of Object.keys(c))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(a)||delete c[a];return this}combine(...o){const c=e.combine([this].concat(o));return Object.assign(this,c),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}}return xc.Psbt=i,xc}var ze={},We={},xp;function Wf(){if(xp)return We;xp=1,Object.defineProperty(We,"__esModule",{value:!0}),We.signatureBlocksAction=We.checkInputForSig=We.pubkeyInScript=We.pubkeyPositionInScript=We.witnessStackToScriptWitness=We.isP2TR=We.isP2SHScript=We.isP2WSHScript=We.isP2WPKH=We.isP2PKH=We.isP2PK=We.isP2MS=void 0;const e=Di(),t=Jt(),n=cc(),r=xr(),i=oc();function s(y){return g=>{try{return y({output:g}),!0}catch{return!1}}}We.isP2MS=s(i.p2ms),We.isP2PK=s(i.p2pk),We.isP2PKH=s(i.p2pkh),We.isP2WPKH=s(i.p2wpkh),We.isP2WSHScript=s(i.p2wsh),We.isP2SHScript=s(i.p2sh),We.isP2TR=s(i.p2tr);function o(y){let g=Buffer.allocUnsafe(0);function w(m){g=Buffer.concat([g,Buffer.from(m)])}function E(m){const T=g.length,I=e.encodingLength(m);g=Buffer.concat([g,Buffer.allocUnsafe(I)]),e.encode(m,g,T)}function S(m){E(m.length),w(m)}function _(m){E(m.length),m.forEach(S)}return _(y),g}We.witnessStackToScriptWitness=o;function c(y,g){const w=(0,r.hash160)(y),E=y.slice(1,33),S=t.decompile(g);if(S===null)throw new Error("Unknown script error");return S.findIndex(_=>typeof _=="number"?!1:_.equals(y)||_.equals(w)||_.equals(E))}We.pubkeyPositionInScript=c;function a(y,g){return c(y,g)!==-1}We.pubkeyInScript=a;function u(y,g){return l(y).some(E=>f(E,t.signature.decode,g))}We.checkInputForSig=u;function f(y,g,w){const{hashType:E}=g(y),S=[];switch(E&n.Transaction.SIGHASH_ANYONECANPAY&&S.push("addInput"),E&31){case n.Transaction.SIGHASH_ALL:break;case n.Transaction.SIGHASH_SINGLE:case n.Transaction.SIGHASH_NONE:S.push("addOutput"),S.push("setInputSequence");break}return S.indexOf(w)===-1}We.signatureBlocksAction=f;function l(y){let g=[];if((y.partialSig||[]).length===0){if(!y.finalScriptSig&&!y.finalScriptWitness)return[];g=p(y)}else g=y.partialSig;return g.map(w=>w.signature)}function p(y){const g=y.finalScriptSig?t.decompile(y.finalScriptSig)||[]:[],w=y.finalScriptWitness?t.decompile(y.finalScriptWitness)||[]:[];return g.concat(w).filter(E=>Buffer.isBuffer(E)&&t.isCanonicalScriptSignature(E)).map(E=>({signature:E}))}return We}var Ap;function Sx(){if(Ap)return ze;Ap=1,Object.defineProperty(ze,"__esModule",{value:!0}),ze.checkTaprootInputForSigs=ze.tapTreeFromList=ze.tapTreeToList=ze.tweakInternalPubKey=ze.checkTaprootOutputFields=ze.checkTaprootInputFields=ze.isTaprootOutput=ze.isTaprootInput=ze.serializeTaprootSignature=ze.tapScriptFinalizer=ze.toXOnly=void 0;const e=Kt(),t=cc(),n=Wf(),r=Yl(),i=oc(),s=Wf(),o=x=>x.length===32?x:x.slice(1,33);ze.toXOnly=o;function c(x,O,q){const P=N(O,x,q);try{const G=H(O,P).concat(P.script).concat(P.controlBlock);return{finalScriptWitness:(0,n.witnessStackToScriptWitness)(G)}}catch(L){throw new Error(`Can not finalize taproot input #${x}: ${L}`)}}ze.tapScriptFinalizer=c;function a(x,O){const q=O?Buffer.from([O]):Buffer.from([]);return Buffer.concat([x,q])}ze.serializeTaprootSignature=a;function u(x){return x&&!!(x.tapInternalKey||x.tapMerkleRoot||x.tapLeafScript&&x.tapLeafScript.length||x.tapBip32Derivation&&x.tapBip32Derivation.length||x.witnessUtxo&&(0,n.isP2TR)(x.witnessUtxo.script))}ze.isTaprootInput=u;function f(x,O){return x&&!!(x.tapInternalKey||x.tapTree||x.tapBip32Derivation&&x.tapBip32Derivation.length||O&&(0,n.isP2TR)(O))}ze.isTaprootOutput=f;function l(x,O,q){v(x,O,q),V(x,O,q)}ze.checkTaprootInputFields=l;function p(x,O,q){R(x,O,q),y(x,O)}ze.checkTaprootOutputFields=p;function y(x,O){if(!O.tapTree&&!O.tapInternalKey)return;const q=O.tapInternalKey||x.tapInternalKey,P=O.tapTree||x.tapTree;if(q){const{script:L}=x,G=g(q,P);if(L&&!L.equals(G))throw new Error("Error adding output. Script or address missmatch.")}}function g(x,O){const q=O&&S(O.leaves),{output:P}=(0,i.p2tr)({internalPubkey:x,scriptTree:q});return P}function w(x,O){const q=O.tapInternalKey,P=q&&(0,r.tweakKey)(q,O.tapMerkleRoot);if(!P)throw new Error(`Cannot tweak tap internal key for input #${x}. Public key: ${q&&q.toString("hex")}`);return P.x}ze.tweakInternalPubKey=w;function E(x){if(!(0,e.isTaptree)(x))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return A(x)}ze.tapTreeToList=E;function S(x=[]){return x.length===1&&x[0].depth===0?{output:x[0].script,version:x[0].leafVersion}:U(x)}ze.tapTreeFromList=S;function _(x,O){return T(x).some(P=>(0,s.signatureBlocksAction)(P,m,O))}ze.checkTaprootInputForSigs=_;function m(x){return{signature:x.slice(0,64),hashType:x.slice(64)[0]||t.Transaction.SIGHASH_DEFAULT}}function T(x){const O=[];if(x.tapKeySig&&O.push(x.tapKeySig),x.tapScriptSig&&O.push(...x.tapScriptSig.map(q=>q.signature)),!O.length){const q=I(x.finalScriptWitness);q&&O.push(q)}return O}function I(x){if(!x)return;const O=x.slice(2);if(O.length===64||O.length===65)return O}function A(x,O=[],q=0){if(q>r.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return x?(0,e.isTapleaf)(x)?(O.push({depth:q,leafVersion:x.version||r.LEAF_VERSION_TAPSCRIPT,script:x.output}),O):(x[0]&&A(x[0],O,q+1),x[1]&&A(x[1],O,q+1),O):[]}function U(x){let O;for(const q of x)if(O=M(q,O),!O)throw new Error("No room left to insert tapleaf in tree");return O}function M(x,O,q=0){if(q>r.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(x.depth===q)return O?void 0:{output:x.script,version:x.leafVersion};if((0,e.isTapleaf)(O))return;const P=M(x,O&&O[0],q+1);if(P)return[P,O&&O[1]];const L=M(x,O&&O[1],q+1);if(L)return[O&&O[0],L]}function v(x,O,q){const P=u(x)&&F(O),L=F(x)&&u(O),G=x===O&&u(O)&&F(O);if(P||L||G)throw new Error(`Invalid arguments for Psbt.${q}. Cannot use both taproot and non-taproot fields.`)}function R(x,O,q){const P=f(x)&&F(O),L=F(x)&&f(O),G=x===O&&f(O)&&F(O);if(P||L||G)throw new Error(`Invalid arguments for Psbt.${q}. Cannot use both taproot and non-taproot fields.`)}function V(x,O,q){if(O.tapMerkleRoot){const P=(O.tapLeafScript||[]).every(G=>W(G,O.tapMerkleRoot)),L=(x.tapLeafScript||[]).every(G=>W(G,O.tapMerkleRoot));if(!P||!L)throw new Error(`Invalid arguments for Psbt.${q}. Tapleaf not part of taptree.`)}else if(x.tapMerkleRoot&&!(O.tapLeafScript||[]).every(L=>W(L,x.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${q}. Tapleaf not part of taptree.`)}function W(x,O){if(!O)return!0;const q=(0,r.tapleafHash)({output:x.script,version:x.leafVersion});return(0,r.rootHashFromPath)(x.controlBlock,q).equals(O)}function H(x,O){const q=(0,r.tapleafHash)({output:O.script,version:O.leafVersion});return(x.tapScriptSig||[]).filter(P=>P.leafHash.equals(q)).map(P=>$(O.script,P)).sort((P,L)=>L.positionInScript-P.positionInScript).map(P=>P.signature)}function $(x,O){return Object.assign({positionInScript:(0,n.pubkeyPositionInScript)(O.pubkey,x)},O)}function N(x,O,q){if(!x.tapScriptSig||!x.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${O}. No tapleaf script signature provided.`);const P=(x.tapLeafScript||[]).sort((L,G)=>L.controlBlock.length-G.controlBlock.length).find(L=>K(L,x.tapScriptSig,q));if(!P)throw new Error(`Can not finalize taproot input #${O}. Signature for tapleaf script not found.`);return P}function K(x,O,q){const P=(0,r.tapleafHash)({output:x.script,version:x.leafVersion});return(!q||q.equals(P))&&O.find(G=>G.leafHash.equals(P))!==void 0}function F(x){return x&&!!(x.redeemScript||x.witnessScript||x.bip32Derivation&&x.bip32Derivation.length)}return ze}var vp;function Tx(){if(vp)return ro;vp=1,Object.defineProperty(ro,"__esModule",{value:!0}),ro.Psbt=void 0;const e=_x(),t=Di(),n=sw(),r=Zl(),i=iu(),s=Vn(),o=oc(),c=Yl(),a=Jt(),u=cc(),f=Sx(),l=Wf(),p={network:s.bitcoin,maximumFeeRate:5e3};class y{static fromBase64(h,b={}){const B=Buffer.from(h,"base64");return this.fromBuffer(B,b)}static fromHex(h,b={}){const B=Buffer.from(h,"hex");return this.fromBuffer(B,b)}static fromBuffer(h,b={}){const B=e.Psbt.fromBuffer(h,g),C=new y(b,B);return V(C.__CACHE.__TX,C.__CACHE),C}constructor(h={},b=new e.Psbt(new w)){this.data=b,this.opts=Object.assign({},p,h),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},this.data.inputs.length===0&&this.setVersion(2);const B=(C,j,D,re)=>Object.defineProperty(C,j,{enumerable:D,writable:re});B(this,"__CACHE",!1,!0),B(this,"opts",!1,!0)}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(h){this.setVersion(h)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(h){this.setLocktime(h)}get txInputs(){return this.__CACHE.__TX.ins.map(h=>({hash:(0,i.cloneBuffer)(h.hash),index:h.index,sequence:h.sequence}))}get txOutputs(){return this.__CACHE.__TX.outs.map(h=>{let b;try{b=(0,r.fromOutputScript)(h.script,this.opts.network)}catch{}return{script:(0,i.cloneBuffer)(h.script),value:h.value,address:b}})}combine(...h){return this.data.combine(...h.map(b=>b.data)),this}clone(){const h=y.fromBuffer(this.data.toBuffer());return h.opts=JSON.parse(JSON.stringify(this.opts)),h}setMaximumFeeRate(h){I(h),this.opts.maximumFeeRate=h}setVersion(h){I(h),U(this.data.inputs,"setVersion");const b=this.__CACHE;return b.__TX.version=h,b.__EXTRACTED_TX=void 0,this}setLocktime(h){I(h),U(this.data.inputs,"setLocktime");const b=this.__CACHE;return b.__TX.locktime=h,b.__EXTRACTED_TX=void 0,this}setInputSequence(h,b){I(b),U(this.data.inputs,"setInputSequence");const B=this.__CACHE;if(B.__TX.ins.length<=h)throw new Error("Input index too high");return B.__TX.ins[h].sequence=b,B.__EXTRACTED_TX=void 0,this}addInputs(h){return h.forEach(b=>this.addInput(b)),this}addInput(h){if(arguments.length>1||!h||h.hash===void 0||h.index===void 0)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");(0,f.checkTaprootInputFields)(h,h,"addInput"),U(this.data.inputs,"addInput"),h.witnessScript&&te(h.witnessScript);const b=this.__CACHE;this.data.addInput(h);const B=b.__TX.ins[b.__TX.ins.length-1];W(b,B);const C=this.data.inputs.length-1,j=this.data.inputs[C];return j.nonWitnessUtxo&&pe(this.__CACHE,j,C),b.__FEE=void 0,b.__FEE_RATE=void 0,b.__EXTRACTED_TX=void 0,this}addOutputs(h){return h.forEach(b=>this.addOutput(b)),this}addOutput(h){if(arguments.length>1||!h||h.value===void 0||h.address===void 0&&h.script===void 0)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");U(this.data.inputs,"addOutput");const{address:b}=h;if(typeof b=="string"){const{network:C}=this.opts,j=(0,r.toOutputScript)(b,C);h=Object.assign({},h,{script:j})}(0,f.checkTaprootOutputFields)(h,h,"addOutput");const B=this.__CACHE;return this.data.addOutput(h),B.__FEE=void 0,B.__FEE_RATE=void 0,B.__EXTRACTED_TX=void 0,this}extractTransaction(h){if(!this.data.inputs.every(m))throw new Error("Not finalized");const b=this.__CACHE;if(h||A(this,b,this.opts),b.__EXTRACTED_TX)return b.__EXTRACTED_TX;const B=b.__TX.clone();return J(this.data.inputs,B,b,!0),B}getFeeRate(){return K("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return K("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return(0,n.checkForInput)(this.data.inputs,0),k(this.data.inputs.length).forEach(h=>this.finalizeInput(h)),this}finalizeInput(h,b){const B=(0,n.checkForInput)(this.data.inputs,h);return(0,f.isTaprootInput)(B)?this._finalizeTaprootInput(h,B,void 0,b):this._finalizeInput(h,B,b)}finalizeTaprootInput(h,b,B=f.tapScriptFinalizer){const C=(0,n.checkForInput)(this.data.inputs,h);if((0,f.isTaprootInput)(C))return this._finalizeTaprootInput(h,C,b,B);throw new Error(`Cannot finalize input #${h}. Not Taproot.`)}_finalizeInput(h,b,B=F){const{script:C,isP2SH:j,isP2WSH:D,isSegwit:re}=ae(h,b,this.__CACHE);if(!C)throw new Error(`No script found for input #${h}`);M(b);const{finalScriptSig:Q,finalScriptWitness:ue}=B(h,b,C,re,j,D);if(Q&&this.data.updateInput(h,{finalScriptSig:Q}),ue&&this.data.updateInput(h,{finalScriptWitness:ue}),!Q&&!ue)throw new Error(`Unknown error finalizing input #${h}`);return this.data.clearFinalizedInput(h),this}_finalizeTaprootInput(h,b,B,C=f.tapScriptFinalizer){if(!b.witnessUtxo)throw new Error(`Cannot finalize input #${h}. Missing withness utxo.`);if(b.tapKeySig){const j=o.p2tr({output:b.witnessUtxo.script,signature:b.tapKeySig}),D=(0,l.witnessStackToScriptWitness)(j.witness);this.data.updateInput(h,{finalScriptWitness:D})}else{const{finalScriptWitness:j}=C(h,b,B);this.data.updateInput(h,{finalScriptWitness:j})}return this.data.clearFinalizedInput(h),this}getInputType(h){const b=(0,n.checkForInput)(this.data.inputs,h),B=Se(h,b,this.__CACHE),C=se(B,h,"input",b.redeemScript||St(b.finalScriptSig),b.witnessScript||Ae(b.finalScriptWitness)),j=C.type==="raw"?"":C.type+"-",D=ne(C.meaningfulScript);return j+D}inputHasPubkey(h,b){const B=(0,n.checkForInput)(this.data.inputs,h);return Ze(b,B,h,this.__CACHE)}inputHasHDKey(h,b){const B=(0,n.checkForInput)(this.data.inputs,h),C=T(b);return!!B.bip32Derivation&&B.bip32Derivation.some(C)}outputHasPubkey(h,b){const B=(0,n.checkForOutput)(this.data.outputs,h);return st(b,B,h,this.__CACHE)}outputHasHDKey(h,b){const B=(0,n.checkForOutput)(this.data.outputs,h),C=T(b);return!!B.bip32Derivation&&B.bip32Derivation.some(C)}validateSignaturesOfAllInputs(h){return(0,n.checkForInput)(this.data.inputs,0),k(this.data.inputs.length).map(B=>this.validateSignaturesOfInput(B,h)).reduce((B,C)=>C===!0&&B,!0)}validateSignaturesOfInput(h,b,B){const C=this.data.inputs[h];return(0,f.isTaprootInput)(C)?this.validateSignaturesOfTaprootInput(h,b,B):this._validateSignaturesOfInput(h,b,B)}_validateSignaturesOfInput(h,b,B){const C=this.data.inputs[h],j=(C||{}).partialSig;if(!C||!j||j.length<1)throw new Error("No signatures to validate");if(typeof b!="function")throw new Error("Need validator function to validate signatures");const D=B?j.filter(Be=>Be.pubkey.equals(B)):j;if(D.length<1)throw new Error("No signatures for this pubkey");const re=[];let Q,ue,le;for(const Be of D){const Oe=a.signature.decode(Be.signature),{hash:Je,script:Ve}=le!==Oe.hashType?q(h,Object.assign({},C,{sighashType:Oe.hashType}),this.__CACHE,!0):{hash:Q,script:ue};le=Oe.hashType,Q=Je,ue=Ve,v(Be.pubkey,Ve,"verify"),re.push(b(Be.pubkey,Je,Oe.signature))}return re.every(Be=>Be===!0)}validateSignaturesOfTaprootInput(h,b,B){const C=this.data.inputs[h],j=(C||{}).tapKeySig,D=(C||{}).tapScriptSig;if(!C&&!j&&!(D&&!D.length))throw new Error("No signatures to validate");if(typeof b!="function")throw new Error("Need validator function to validate signatures");B=B&&(0,f.toXOnly)(B);const re=B?X(h,C,this.data.inputs,B,this.__CACHE):P(h,C,this.data.inputs,this.__CACHE);if(!re.length)throw new Error("No signatures for this pubkey");const Q=re.find(le=>!le.leafHash);let ue=0;if(j&&Q){if(!b(Q.pubkey,Q.hash,G(j)))return!1;ue++}if(D)for(const le of D){const Be=re.find(Oe=>le.pubkey.equals(Oe.pubkey));if(Be){if(!b(le.pubkey,Be.hash,G(le.signature)))return!1;ue++}}return ue>0}signAllInputsHD(h,b=[u.Transaction.SIGHASH_ALL]){if(!h||!h.publicKey||!h.fingerprint)throw new Error("Need HDSigner to sign input");const B=[];for(const C of k(this.data.inputs.length))try{this.signInputHD(C,h,b),B.push(!0)}catch{B.push(!1)}if(B.every(C=>C===!1))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(h,b=[u.Transaction.SIGHASH_ALL]){return new Promise((B,C)=>{if(!h||!h.publicKey||!h.fingerprint)return C(new Error("Need HDSigner to sign input"));const j=[],D=[];for(const re of k(this.data.inputs.length))D.push(this.signInputHDAsync(re,h,b).then(()=>{j.push(!0)},()=>{j.push(!1)}));return Promise.all(D).then(()=>{if(j.every(re=>re===!1))return C(new Error("No inputs were signed"));B()})})}signInputHD(h,b,B=[u.Transaction.SIGHASH_ALL]){if(!b||!b.publicKey||!b.fingerprint)throw new Error("Need HDSigner to sign input");return ee(h,this.data.inputs,b).forEach(j=>this.signInput(h,j,B)),this}signInputHDAsync(h,b,B=[u.Transaction.SIGHASH_ALL]){return new Promise((C,j)=>{if(!b||!b.publicKey||!b.fingerprint)return j(new Error("Need HDSigner to sign input"));const re=ee(h,this.data.inputs,b).map(Q=>this.signInputAsync(h,Q,B));return Promise.all(re).then(()=>{C()}).catch(j)})}signAllInputs(h,b){if(!h||!h.publicKey)throw new Error("Need Signer to sign input");const B=[];for(const C of k(this.data.inputs.length))try{this.signInput(C,h,b),B.push(!0)}catch{B.push(!1)}if(B.every(C=>C===!1))throw new Error("No inputs were signed");return this}signAllInputsAsync(h,b){return new Promise((B,C)=>{if(!h||!h.publicKey)return C(new Error("Need Signer to sign input"));const j=[],D=[];for(const[re]of this.data.inputs.entries())D.push(this.signInputAsync(re,h,b).then(()=>{j.push(!0)},()=>{j.push(!1)}));return Promise.all(D).then(()=>{if(j.every(re=>re===!1))return C(new Error("No inputs were signed"));B()})})}signInput(h,b,B){if(!b||!b.publicKey)throw new Error("Need Signer to sign input");const C=(0,n.checkForInput)(this.data.inputs,h);return(0,f.isTaprootInput)(C)?this._signTaprootInput(h,C,b,void 0,B):this._signInput(h,b,B)}signTaprootInput(h,b,B,C){if(!b||!b.publicKey)throw new Error("Need Signer to sign input");const j=(0,n.checkForInput)(this.data.inputs,h);if((0,f.isTaprootInput)(j))return this._signTaprootInput(h,j,b,B,C);throw new Error(`Input #${h} is not of type Taproot.`)}_signInput(h,b,B=[u.Transaction.SIGHASH_ALL]){const{hash:C,sighashType:j}=O(this.data.inputs,h,b.publicKey,this.__CACHE,B),D=[{pubkey:b.publicKey,signature:a.signature.encode(b.sign(C),j)}];return this.data.updateInput(h,{partialSig:D}),this}_signTaprootInput(h,b,B,C,j=[u.Transaction.SIGHASH_DEFAULT]){const D=this.checkTaprootHashesForSig(h,b,B,C,j),re=D.filter(ue=>!ue.leafHash).map(ue=>(0,f.serializeTaprootSignature)(B.signSchnorr(ue.hash),b.sighashType))[0],Q=D.filter(ue=>!!ue.leafHash).map(ue=>({pubkey:(0,f.toXOnly)(B.publicKey),signature:(0,f.serializeTaprootSignature)(B.signSchnorr(ue.hash),b.sighashType),leafHash:ue.leafHash}));return re&&this.data.updateInput(h,{tapKeySig:re}),Q.length&&this.data.updateInput(h,{tapScriptSig:Q}),this}signInputAsync(h,b,B){return Promise.resolve().then(()=>{if(!b||!b.publicKey)throw new Error("Need Signer to sign input");const C=(0,n.checkForInput)(this.data.inputs,h);return(0,f.isTaprootInput)(C)?this._signTaprootInputAsync(h,C,b,void 0,B):this._signInputAsync(h,b,B)})}signTaprootInputAsync(h,b,B,C){return Promise.resolve().then(()=>{if(!b||!b.publicKey)throw new Error("Need Signer to sign input");const j=(0,n.checkForInput)(this.data.inputs,h);if((0,f.isTaprootInput)(j))return this._signTaprootInputAsync(h,j,b,B,C);throw new Error(`Input #${h} is not of type Taproot.`)})}_signInputAsync(h,b,B=[u.Transaction.SIGHASH_ALL]){const{hash:C,sighashType:j}=O(this.data.inputs,h,b.publicKey,this.__CACHE,B);return Promise.resolve(b.sign(C)).then(D=>{const re=[{pubkey:b.publicKey,signature:a.signature.encode(D,j)}];this.data.updateInput(h,{partialSig:re})})}async _signTaprootInputAsync(h,b,B,C,j=[u.Transaction.SIGHASH_DEFAULT]){const D=this.checkTaprootHashesForSig(h,b,B,C,j),re=[],Q=D.filter(le=>!le.leafHash)[0];if(Q){const le=Promise.resolve(B.signSchnorr(Q.hash)).then(Be=>({tapKeySig:(0,f.serializeTaprootSignature)(Be,b.sighashType)}));re.push(le)}const ue=D.filter(le=>!!le.leafHash);if(ue.length){const le=ue.map(Be=>Promise.resolve(B.signSchnorr(Be.hash)).then(Oe=>({tapScriptSig:[{pubkey:(0,f.toXOnly)(B.publicKey),signature:(0,f.serializeTaprootSignature)(Oe,b.sighashType),leafHash:Be.leafHash}]})));re.push(...le)}return Promise.all(re).then(le=>{le.forEach(Be=>this.data.updateInput(h,Be))})}checkTaprootHashesForSig(h,b,B,C,j){if(typeof B.signSchnorr!="function")throw new Error(`Need Schnorr Signer to sign taproot input #${h}.`);const D=X(h,b,this.data.inputs,B.publicKey,this.__CACHE,C,j);if(!D||!D.length)throw new Error(`Can not sign for input #${h} with the key ${B.publicKey.toString("hex")}`);return D}toBuffer(){return S(this.__CACHE),this.data.toBuffer()}toHex(){return S(this.__CACHE),this.data.toHex()}toBase64(){return S(this.__CACHE),this.data.toBase64()}updateGlobal(h){return this.data.updateGlobal(h),this}updateInput(h,b){return b.witnessScript&&te(b.witnessScript),(0,f.checkTaprootInputFields)(this.data.inputs[h],b,"updateInput"),this.data.updateInput(h,b),b.nonWitnessUtxo&&pe(this.__CACHE,this.data.inputs[h],h),this}updateOutput(h,b){const B=this.data.outputs[h];return(0,f.checkTaprootOutputFields)(B,b,"updateOutput"),this.data.updateOutput(h,b),this}addUnknownKeyValToGlobal(h){return this.data.addUnknownKeyValToGlobal(h),this}addUnknownKeyValToInput(h,b){return this.data.addUnknownKeyValToInput(h,b),this}addUnknownKeyValToOutput(h,b){return this.data.addUnknownKeyValToOutput(h,b),this}clearFinalizedInput(h){return this.data.clearFinalizedInput(h),this}}ro.Psbt=y;const g=d=>new w(d);class w{constructor(h=Buffer.from([2,0,0,0,0,0,0,0,0,0])){this.tx=u.Transaction.fromBuffer(h),R(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(h){if(h.hash===void 0||h.index===void 0||!Buffer.isBuffer(h.hash)&&typeof h.hash!="string"||typeof h.index!="number")throw new Error("Error adding input.");const b=typeof h.hash=="string"?(0,i.reverseBuffer)(Buffer.from(h.hash,"hex")):h.hash;this.tx.addInput(b,h.index,h.sequence)}addOutput(h){if(h.script===void 0||h.value===void 0||!Buffer.isBuffer(h.script)||typeof h.value!="number")throw new Error("Error adding output.");this.tx.addOutput(h.script,h.value)}toBuffer(){return this.tx.toBuffer()}}function E(d,h,b){switch(b){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return _(1,d.partialSig);case"multisig":const B=o.p2ms({output:h});return _(B.m,d.partialSig,B.pubkeys);default:return!1}}function S(d){if(d.__UNSAFE_SIGN_NONSEGWIT!==!1)throw new Error("Not BIP174 compliant, can not export")}function _(d,h,b){if(!h)return!1;let B;if(b?B=b.map(C=>{const j=ln(C);return h.find(D=>D.pubkey.equals(j))}).filter(C=>!!C):B=h,B.length>d)throw new Error("Too many signatures");return B.length===d}function m(d){return!!d.finalScriptSig||!!d.finalScriptWitness}function T(d){return h=>!(!h.masterFingerprint.equals(d.fingerprint)||!d.derivePath(h.path).publicKey.equals(h.pubkey))}function I(d){if(typeof d!="number"||d!==Math.floor(d)||d>4294967295||d<0)throw new Error("Invalid 32 bit integer")}function A(d,h,b){const B=h.__FEE_RATE||d.getFeeRate(),C=h.__EXTRACTED_TX.virtualSize(),j=B*C;if(B>=b.maximumFeeRate)throw new Error(`Warning: You are paying around ${(j/1e8).toFixed(8)} in fees, which is ${B} satoshi per byte for a transaction with a VSize of ${C} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}function U(d,h){d.forEach(b=>{if((0,f.isTaprootInput)(b)?(0,f.checkTaprootInputForSigs)(b,h):(0,l.checkInputForSig)(b,h))throw new Error("Can not modify transaction, signatures exist.")})}function M(d){if(!d.sighashType||!d.partialSig)return;const{partialSig:h,sighashType:b}=d;h.forEach(B=>{const{hashType:C}=a.signature.decode(B.signature);if(b!==C)throw new Error("Signature sighash does not match input sighash type")})}function v(d,h,b){if(!(0,l.pubkeyInScript)(d,h))throw new Error(`Can not ${b} for this input with the key ${d.toString("hex")}`)}function R(d){if(!d.ins.every(b=>b.script&&b.script.length===0&&b.witness&&b.witness.length===0))throw new Error("Format Error: Transaction ScriptSigs are not empty")}function V(d,h){d.ins.forEach(b=>{W(h,b)})}function W(d,h){const b=(0,i.reverseBuffer)(Buffer.from(h.hash)).toString("hex")+":"+h.index;if(d.__TX_IN_CACHE[b])throw new Error("Duplicate input detected.");d.__TX_IN_CACHE[b]=1}function H(d,h){return(b,B,C,j)=>{const D=d({redeem:{output:C}}).output;if(!B.equals(D))throw new Error(`${h} for ${j} #${b} doesn't match the scriptPubKey in the prevout`)}}const $=H(o.p2sh,"Redeem script"),N=H(o.p2wsh,"Witness script");function K(d,h,b,B){if(!b.every(m))throw new Error(`PSBT must be finalized to calculate ${h}`);if(d==="__FEE_RATE"&&B.__FEE_RATE)return B.__FEE_RATE;if(d==="__FEE"&&B.__FEE)return B.__FEE;let C,j=!0;if(B.__EXTRACTED_TX?(C=B.__EXTRACTED_TX,j=!1):C=B.__TX.clone(),J(b,C,B,j),d==="__FEE_RATE")return B.__FEE_RATE;if(d==="__FEE")return B.__FEE}function F(d,h,b,B,C,j){const D=ne(b);if(!E(h,b,D))throw new Error(`Can not finalize input #${d}`);return x(b,D,h.partialSig,B,C,j)}function x(d,h,b,B,C,j){let D,re;const Q=oe(d,h,b),ue=j?o.p2wsh({redeem:Q}):null,le=C?o.p2sh({redeem:ue||Q}):null;return B?(ue?re=(0,l.witnessStackToScriptWitness)(ue.witness):re=(0,l.witnessStackToScriptWitness)(Q.witness),le&&(D=le.input)):le?D=le.input:D=Q.input,{finalScriptSig:D,finalScriptWitness:re}}function O(d,h,b,B,C){const j=(0,n.checkForInput)(d,h),{hash:D,sighashType:re,script:Q}=q(h,j,B,!1,C);return v(b,Q,"sign"),{hash:D,sighashType:re}}function q(d,h,b,B,C){const j=b.__TX,D=h.sighashType||u.Transaction.SIGHASH_ALL;Y(D,C);let re,Q;if(h.nonWitnessUtxo){const Be=fe(b,h,d),Oe=j.ins[d].hash,Je=Be.getHash();if(!Oe.equals(Je))throw new Error(`Non-witness UTXO hash for input #${d} doesn't match the hash specified in the prevout`);const Ve=j.ins[d].index;Q=Be.outs[Ve]}else if(h.witnessUtxo)Q=h.witnessUtxo;else throw new Error("Need a Utxo input item for signing");const{meaningfulScript:ue,type:le}=se(Q.script,d,"input",h.redeemScript,h.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(le)>=0)re=j.hashForWitnessV0(d,ue,Q.value,D);else if((0,l.isP2WPKH)(ue)){const Be=o.p2pkh({hash:ue.slice(2)}).output;re=j.hashForWitnessV0(d,Be,Q.value,D)}else{if(h.nonWitnessUtxo===void 0&&b.__UNSAFE_SIGN_NONSEGWIT===!1)throw new Error(`Input #${d} has witnessUtxo but non-segwit script: ${ue.toString("hex")}`);!B&&b.__UNSAFE_SIGN_NONSEGWIT!==!1&&console.warn(`Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as Psbt's predecessor (TransactionBuilder - now removed) when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.
74
74
  *********************
75
75
  PROCEED WITH CAUTION!
76
- *********************`),re=j.hashForSignature(d,ue,D)}return{script:ue,sighashType:D,hash:re}}function P(d,h,b,B){const C=[];if(h.tapInternalKey){const D=L(d,h,B);D&&C.push(D)}if(h.tapScriptSig){const D=h.tapScriptSig.map(re=>re.pubkey);C.push(...D)}return C.map(D=>X(d,h,b,D,B)).flat()}function L(d,h,b){const{script:B}=Ce(d,h,b);return(0,l.isP2TR)(B)?B.subarray(2,34):null}function G(d){return d.length===64?d:d.subarray(0,64)}function X(d,h,b,B,C,j,D){const re=C.__TX,Q=h.sighashType||u.Transaction.SIGHASH_DEFAULT;Y(Q,D);const ue=b.map((Ve,Ln)=>Ce(Ln,Ve,C)),le=ue.map(Ve=>Ve.script),Be=ue.map(Ve=>Ve.value),Oe=[];if(h.tapInternalKey&&!j){const Ve=L(d,h,C)||Buffer.from([]);if((0,f.toXOnly)(B).equals(Ve)){const Ln=re.hashForWitnessV1(d,le,Be,Q);Oe.push({pubkey:B,hash:Ln})}}const Je=(h.tapLeafScript||[]).filter(Ve=>(0,l.pubkeyInScript)(B,Ve.script)).map(Ve=>{const Ln=(0,c.tapleafHash)({output:Ve.script,version:Ve.leafVersion});return Object.assign({hash:Ln},Ve)}).filter(Ve=>!j||j.equals(Ve.hash)).map(Ve=>{const Ln=re.hashForWitnessV1(d,le,Be,Q,Ve.hash);return{pubkey:B,hash:Ln,leafHash:Ve.hash}});return Oe.concat(Je)}function Y(d,h){if(h&&h.indexOf(d)<0){const b=ge(d);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${b}`)}}function oe(d,h,b){let B;switch(h){case"multisig":const C=Z(d,b);B=o.p2ms({output:d,signatures:C});break;case"pubkey":B=o.p2pk({output:d,signature:b[0].signature});break;case"pubkeyhash":B=o.p2pkh({output:d,pubkey:b[0].pubkey,signature:b[0].signature});break;case"witnesspubkeyhash":B=o.p2wpkh({output:d,pubkey:b[0].pubkey,signature:b[0].signature});break}return B}function ae(d,h,b){const B=b.__TX,C={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(C.isP2SH=!!h.redeemScript,C.isP2WSH=!!h.witnessScript,h.witnessScript)C.script=h.witnessScript;else if(h.redeemScript)C.script=h.redeemScript;else if(h.nonWitnessUtxo){const j=fe(b,h,d),D=B.ins[d].index;C.script=j.outs[D].script}else h.witnessUtxo&&(C.script=h.witnessUtxo.script);return(h.witnessScript||(0,l.isP2WPKH)(C.script))&&(C.isSegwit=!0),C}function ee(d,h,b){const B=(0,n.checkForInput)(h,d);if(!B.bip32Derivation||B.bip32Derivation.length===0)throw new Error("Need bip32Derivation to sign with HD");const C=B.bip32Derivation.map(D=>{if(D.masterFingerprint.equals(b.fingerprint))return D}).filter(D=>!!D);if(C.length===0)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");return C.map(D=>{const re=b.derivePath(D.path);if(!D.pubkey.equals(re.publicKey))throw new Error("pubkey did not match bip32Derivation");return re})}function Z(d,h){return o.p2ms({output:d}).pubkeys.map(B=>(h.filter(C=>C.pubkey.equals(B))[0]||{}).signature).filter(B=>!!B)}function ce(d){let h=0;function b(D){return h+=D,d.slice(h-D,h)}function B(){const D=t.decode(d,h);return h+=t.decode.bytes,D}function C(){return b(B())}function j(){const D=B(),re=[];for(let Q=0;Q<D;Q++)re.push(C());return re}return j()}function ge(d){let h=d&u.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(d&31){case u.Transaction.SIGHASH_ALL:h+="SIGHASH_ALL";break;case u.Transaction.SIGHASH_SINGLE:h+="SIGHASH_SINGLE";break;case u.Transaction.SIGHASH_NONE:h+="SIGHASH_NONE";break}return h}function pe(d,h,b){d.__NON_WITNESS_UTXO_BUF_CACHE[b]=h.nonWitnessUtxo;const B=u.Transaction.fromBuffer(h.nonWitnessUtxo);d.__NON_WITNESS_UTXO_TX_CACHE[b]=B;const C=d,j=b;delete h.nonWitnessUtxo,Object.defineProperty(h,"nonWitnessUtxo",{enumerable:!0,get(){const D=C.__NON_WITNESS_UTXO_BUF_CACHE[j],re=C.__NON_WITNESS_UTXO_TX_CACHE[j];if(D!==void 0)return D;{const Q=re.toBuffer();return C.__NON_WITNESS_UTXO_BUF_CACHE[j]=Q,Q}},set(D){C.__NON_WITNESS_UTXO_BUF_CACHE[j]=D}})}function J(d,h,b,B){let C=0;d.forEach((Q,ue)=>{if(B&&Q.finalScriptSig&&(h.ins[ue].script=Q.finalScriptSig),B&&Q.finalScriptWitness&&(h.ins[ue].witness=ce(Q.finalScriptWitness)),Q.witnessUtxo)C+=Q.witnessUtxo.value;else if(Q.nonWitnessUtxo){const le=fe(b,Q,ue),Be=h.ins[ue].index,Oe=le.outs[Be];C+=Oe.value}});const j=h.outs.reduce((Q,ue)=>Q+ue.value,0),D=C-j;if(D<0)throw new Error("Outputs are spending more than Inputs");const re=h.virtualSize();b.__FEE=D,b.__EXTRACTED_TX=h,b.__FEE_RATE=Math.floor(D/re)}function fe(d,h,b){const B=d.__NON_WITNESS_UTXO_TX_CACHE;return B[b]||pe(d,h,b),B[b]}function Se(d,h,b){const{script:B}=Ce(d,h,b);return B}function Ce(d,h,b){if(h.witnessUtxo!==void 0)return{script:h.witnessUtxo.script,value:h.witnessUtxo.value};if(h.nonWitnessUtxo!==void 0){const C=fe(b,h,d).outs[b.__TX.ins[d].index];return{script:C.script,value:C.value}}else throw new Error("Can't find pubkey in input without Utxo data")}function Ze(d,h,b,B){const C=Se(b,h,B),{meaningfulScript:j}=se(C,b,"input",h.redeemScript,h.witnessScript);return(0,l.pubkeyInScript)(d,j)}function st(d,h,b,B){const C=B.__TX.outs[b].script,{meaningfulScript:j}=se(C,b,"output",h.redeemScript,h.witnessScript);return(0,l.pubkeyInScript)(d,j)}function St(d){if(!d)return;const h=a.decompile(d);if(!h)return;const b=h[h.length-1];if(!(!Buffer.isBuffer(b)||et(b)||Ne(b)||!a.decompile(b)))return b}function Ae(d){if(!d)return;const h=ce(d),b=h[h.length-1];if(!(et(b)||!a.decompile(b)))return b}function ln(d){if(d.length===65){const h=d[64]&1,b=d.slice(0,33);return b[0]=2|h,b}return d.slice()}function et(d){return d.length===33&&a.isCanonicalPubKey(d)}function Ne(d){return a.isCanonicalScriptSignature(d)}function se(d,h,b,B,C){const j=(0,l.isP2SHScript)(d),D=j&&B&&(0,l.isP2WSHScript)(B),re=(0,l.isP2WSHScript)(d);if(j&&B===void 0)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((re||D)&&C===void 0)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let Q;return D?(Q=C,$(h,d,B,b),N(h,B,C,b),te(Q)):re?(Q=C,N(h,d,C,b),te(Q)):j?(Q=B,$(h,d,B,b)):Q=d,{meaningfulScript:Q,type:D?"p2sh-p2wsh":j?"p2sh":re?"p2wsh":"raw"}}function te(d){if((0,l.isP2WPKH)(d)||(0,l.isP2SHScript)(d))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function ne(d){return(0,l.isP2WPKH)(d)?"witnesspubkeyhash":(0,l.isP2PKH)(d)?"pubkeyhash":(0,l.isP2MS)(d)?"multisig":(0,l.isP2PK)(d)?"pubkey":"nonstandard"}function k(d){return[...Array(d).keys()]}return ro}var Bp;function xx(){return Bp||(Bp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.initEccLib=e.Transaction=e.opcodes=e.Psbt=e.Block=e.script=e.payments=e.networks=e.crypto=e.address=void 0;const t=Zl();e.address=t;const n=xr();e.crypto=n;const r=Vn();e.networks=r;const i=oc();e.payments=i;const s=Jt();e.script=s;var o=J8();Object.defineProperty(e,"Block",{enumerable:!0,get:function(){return o.Block}});var c=Tx();Object.defineProperty(e,"Psbt",{enumerable:!0,get:function(){return c.Psbt}});var a=Gl();Object.defineProperty(e,"opcodes",{enumerable:!0,get:function(){return a.OPS}});var u=cc();Object.defineProperty(e,"Transaction",{enumerable:!0,get:function(){return u.Transaction}});var f=zl();Object.defineProperty(e,"initEccLib",{enumerable:!0,get:function(){return f.initEccLib}})})(Yu)),Yu}var _i={},Ip;function Ax(){if(Ip)return _i;Ip=1,Object.defineProperty(_i,"__esModule",{value:!0}),_i.base26Decode=_i.base26Encode=void 0;function e(n){let r=0n;for(let i=0;i<n.length;i++){const s=BigInt(n.charCodeAt(i)-65),o=BigInt(n.length)-1n-BigInt(i);if(o==0n)r+=s;else{const c=26n**o;r+=c*(s+1n)}}return r}_i.base26Encode=e;function t(n){if(n===340282366920938463463374607431768211455n)return"BCGDENLQRQWDSLRUGSNLBTMFIJAV";n+=1n;let r=[];for(;n>0;){const i=(n-1n)%26n;r.push("ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(Number(i))),n=(n-1n)/26n}return r.reverse().join("")}return _i.base26Decode=t,_i}var Si={},Op;function ow(){if(Op)return Si;Op=1,Object.defineProperty(Si,"__esModule",{value:!0}),Si.none=Si.some=void 0;class e{constructor(){}isSome(){return!1}map(s){return new e}value(){return null}}class t{constructor(s){this._value=s}isSome(){return!0}map(s){return new t(s(this.value()))}value(){return this._value}}function n(i){return new t(i)}Si.some=n;function r(){return new e}return Si.none=r,Si}var Ti={},Pp;function vx(){if(Pp)return Ti;Pp=1,Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.decodeLEB128=Ti.encodeLEB128=void 0;function e(n){const r=[];let i=!0;for(;i;){let s=Number(n&BigInt(127));n>>=BigInt(7),n===BigInt(0)?i=!1:s|=128,r.push(s)}return r}Ti.encodeLEB128=e;function t(n){let r=BigInt(0);for(let i=0;i<n.length;i++){const s=BigInt(n[i]);if(i>18)throw new Error("Overlong");let o=s&BigInt(127);if(i==18&&(o&BigInt(124))!=BigInt(0))throw new Error("Overflow");if(r|=o<<BigInt(7)*BigInt(i),(s&BigInt(128))==BigInt(0))return{n:r,len:i+1}}throw new Error("Unterminated")}return Ti.decodeLEB128=t,Ti}var yf={},kp;function Bx(){return kp||(kp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.toPushData=e.chunks=e.toHex=e.zero2=void 0;const t=s=>s.length%2===1?"0"+s:s;e.zero2=t;const n=s=>{let o="";for(let c=0;c<s.length;c++)o+=(0,e.zero2)(s[c].toString(16));return o};e.toHex=n;function r(s,o){const c=[];let a=0;for(;a<s.length;){const u=s.slice(a,a+o);c.push(u),a+=o}return c}e.chunks=r;function i(s){const o=[],c=s.length;if(c<76){const a=Buffer.alloc(1);a.writeUInt8(c),o.push(a)}else if(c<=255){o.push(Buffer.from("4c","hex"));const a=Buffer.alloc(1);a.writeUInt8(c),o.push(a)}else if(c<=65535){o.push(Buffer.from("4d","hex"));const a=Buffer.alloc(2);a.writeUInt16LE(c),o.push(a)}else{o.push(Buffer.from("4e","hex"));const a=Buffer.alloc(4);a.writeUInt32LE(c),o.push(a)}return o.push(s),Buffer.concat(o)}e.toPushData=i})(yf)),yf}var sr={},Np;function cw(){if(Np)return sr;Np=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.removeSpacers=sr.getSpacersVal=sr.applySpacers=void 0;function e(r,i){let s="";for(let o=0;o<r.length;o++)s+=r.charAt(o),i>0&&((i&1)===1&&(s+="•"),i>>=1);return s}sr.applySpacers=e;function t(r){let i=0,s=0;for(let o=0;o<r.length;o++)r.charAt(o)==="•"&&(i+=1<<o-1-s,s++);return i}sr.getSpacersVal=t;function n(r){return r.replace(/[•]+/g,"")}return sr.removeSpacers=n,sr}var Up;function Ix(){if(Up)return je;Up=1,Object.defineProperty(je,"__esModule",{value:!0}),je.EtchInscription=je.Message=je.Runestone=je.Etching=je.Rune=je.Terms=je.Range=je.Flaw=je.Tag=je.Flag=je.Edict=je.RuneId=void 0;const e=xx(),t=Ax(),n=ow(),r=vx(),i=Bx(),s=cw();class o{constructor(m,T){this.block=m,this.idx=T}next(m,T){if(m>BigInt(Number.MAX_SAFE_INTEGER)||T>BigInt(Number.MAX_SAFE_INTEGER))return(0,n.none)();let I=BigInt(this.block)+m;if(I>BigInt(Number.MAX_SAFE_INTEGER))return(0,n.none)();let A=m===0n?BigInt(this.idx)+T:T;return A>BigInt(Number.MAX_SAFE_INTEGER)?(0,n.none)():(0,n.some)(new o(Number(I),Number(A)))}}je.RuneId=o;class c{constructor(m,T,I){this.id=m,this.amount=T,this.output=I}static from_integers(m,T,I,A){return A>4294967295n||A<0n||Number(A)>m.outs.length?(0,n.none)():(0,n.some)(new c(T,I,Number(A)))}}je.Edict=c;var a;(function(_){_[_.Etching=0]="Etching",_[_.Terms=1]="Terms",_[_.Turbo=2]="Turbo",_[_.Cenotaph=127]="Cenotaph"})(a||(je.Flag=a={}));var u;(function(_){_[_.Body=0]="Body",_[_.Flags=2]="Flags",_[_.Rune=4]="Rune",_[_.Premine=6]="Premine",_[_.Cap=8]="Cap",_[_.Amount=10]="Amount",_[_.HeightStart=12]="HeightStart",_[_.HeightEnd=14]="HeightEnd",_[_.OffsetStart=16]="OffsetStart",_[_.OffsetEnd=18]="OffsetEnd",_[_.Mint=20]="Mint",_[_.Pointer=22]="Pointer",_[_.Cenotaph=126]="Cenotaph",_[_.Divisibility=1]="Divisibility",_[_.Spacers=3]="Spacers",_[_.Symbol=5]="Symbol",_[_.Nop=127]="Nop"})(u||(je.Tag=u={}));var f;(function(_){_[_.EdictOutput=0]="EdictOutput",_[_.EdictRuneId=1]="EdictRuneId",_[_.InvalidScript=2]="InvalidScript",_[_.Opcode=3]="Opcode",_[_.SupplyOverflow=4]="SupplyOverflow",_[_.TrailingIntegers=5]="TrailingIntegers",_[_.TruncatedField=6]="TruncatedField",_[_.UnrecognizedEvenTag=7]="UnrecognizedEvenTag",_[_.UnrecognizedFlag=8]="UnrecognizedFlag",_[_.Varint=9]="Varint"})(f||(je.Flaw=f={}));class l{constructor(m,T){this.start=m,this.end=T}}je.Range=l;class p{constructor(m,T,I,A){this.amount=m,this.cap=T,this.height=I,this.offset=A}}je.Terms=p;class y{constructor(m){this.value=m}get name(){return y.toName(this.value)}static toName(m){return(0,t.base26Decode)(m)}static fromName(m){return new y((0,t.base26Encode)((0,s.removeSpacers)(m)))}toString(){return this.name}}je.Rune=y;class g{constructor(m,T,I,A,U,M,v){this.divisibility=m,this.premine=T,this.rune=I,this.spacers=A,this.symbol=U,this.terms=M,this.turbo=v}}je.Etching=g,g.MAX_DIVISIBILITY=38,g.MAX_SPACERS=134217727;class w{constructor(m=[],T,I,A){this.edicts=m,this.etching=T,this.mint=I,this.pointer=A}static create(m,T="etch"){if(T==="etch"){m=m;const I=y.fromName(m.name),A=new p(m.amount,m.cap,new l(m.startHeight?(0,n.some)(m.startHeight):(0,n.none)(),m.endHeight?(0,n.some)(m.endHeight):(0,n.none)()),new l(m.startOffset?(0,n.some)(m.startOffset):(0,n.none)(),m.endOffset?(0,n.some)(m.endOffset):(0,n.none)())),U=m.divisibility?(0,n.some)(m.divisibility):(0,n.none)(),M=m.premine?(0,n.some)(m.premine):(0,n.none)(),v=m.name.indexOf("•")>-1?(0,n.some)((0,s.getSpacersVal)(m.name)):(0,n.none)(),R=m.symbol?(0,n.some)(m.symbol):(0,n.none)(),V=typeof m.pointer=="number"?(0,n.some)(m.pointer):(0,n.none)(),W=new g(U,M,(0,n.some)(I),v,R,(0,n.some)(A),!0);return new w([],(0,n.some)(W),(0,n.none)(),V)}else if(T==="mint"){m=m;const I=typeof m.pointer=="number"?(0,n.some)(m.pointer):(0,n.none)();return new w([],(0,n.none)(),(0,n.some)(new o(m.block,m.txIdx)),I)}else throw new Error(`not ${T} support now`)}static decipher(m){const T=e.Transaction.fromHex(m),I=w.payload(T);if(I.isSome()){const A=w.integers(I.value()),U=E.from_integers(T,A.value()),M=U.getEtching(),v=U.getMint(),R=U.getPointer();return(0,n.some)(new w(U.edicts,M,v,R))}return(0,n.none)()}encipher(){const T=this.toMessage().toBuffer(),I=Buffer.from("6a5d","hex");let A;if(T.length<76)A=Buffer.alloc(1),A.writeUInt8(T.length);else if(T.length<256)A=Buffer.alloc(2),A.writeUInt8(76),A.writeUInt8(T.length);else if(T.length<65536)A=Buffer.alloc(3),A.writeUInt8(77),A.writeUInt16LE(T.length);else if(T.length<4294967296)A=Buffer.alloc(5),A.writeUInt8(78),A.writeUInt32LE(T.length);else throw new Error("runestone too big!");return Buffer.concat([I,A,T])}static payload(m){for(const T of m.outs){const I=e.script.decompile(T.script);if(I[0]===e.script.OPS.OP_RETURN&&I[1]===w.MAGIC_NUMBER){for(let A=2;A<I.length;A++){const U=I[A];return U instanceof Uint8Array?(0,n.some)(Array.from(U)):(0,n.none)()}return(0,n.none)()}}return(0,n.none)()}static integers(m){let T=[],I=0;for(;I<m.length;){let{n:A,len:U}=(0,r.decodeLEB128)(m.slice(I));T.push(A),I+=U}return(0,n.some)(T)}toMessage(){let m=new Map;const T=this.etching.value();if(T){let U=1;if(T.terms.isSome()){let $=1<<a.Terms;U|=$}if(T.turbo){let $=1<<a.Turbo;U|=$}m.set(u.Flags,[BigInt(U)]);const M=T.rune.value();M!==null&&m.set(u.Rune,[BigInt(M.value)]);const v=T.divisibility.value();v!==null&&m.set(u.Divisibility,[BigInt(v)]);const R=T.spacers.value();R!==null&&m.set(u.Spacers,[BigInt(R)]);const V=T.symbol.value();V!==null&&m.set(u.Symbol,[BigInt(V.charCodeAt(0))]);const W=T.premine.value();W!==null&&m.set(u.Premine,[BigInt(W)]);const H=T.terms.value();if(H!==null){m.set(u.Amount,[BigInt(H.amount)]),m.set(u.Cap,[BigInt(H.cap)]);const $=H.height.start.value();$&&m.set(u.HeightStart,[BigInt($)]);const N=H.height.end.value();N&&m.set(u.HeightEnd,[BigInt(N)]);const K=H.offset.start.value();K&&m.set(u.OffsetStart,[BigInt(K)]);const F=H.offset.end.value();F&&m.set(u.OffsetEnd,[BigInt(F)])}}const I=this.mint.value();I!==null&&m.set(u.Mint,[BigInt(I.block),BigInt(I.idx)]);const A=this.pointer.value();return A!==null&&m.set(u.Pointer,[BigInt(A)]),new E(m,this.edicts,0)}}je.Runestone=w,w.MAGIC_NUMBER=93;class E{constructor(m=new Map,T=[],I=0){this.fields=m,this.edicts=T,this.flaws=I}static from_integers(m,T){let I=new Map,A=[],U=0,M=!1;for(let v=0;v<T.length;){let R=T[v];if(Number(R)===u.Body){M=!0,v+=1;continue}if(M){let V=new o(0,0);for(const W of(0,i.chunks)(T.slice(v),4)){if(W.length!=4){U|=f.TrailingIntegers;break}let H=V.next(W[0],W[1]);if(!H.isSome()){U|=f.EdictRuneId;break}const $=c.from_integers(m,H.value(),W[2],W[3]);if(!$.isSome()){U|=f.EdictOutput;break}V=H.value(),A.push($.value())}v+=4}else{let V=T[v+1];const W=I.get(Number(R))||[];W.push(V),I.set(Number(R),W),v+=2}}return new E(I,A,U)}addFieldVal(m,T){const I=this.fields.get(Number(m))||[];I.push(T),this.fields.set(Number(m),I)}addEdict(m){this.edicts.push(m)}toBuffer(){const m=[];for(const[T,I]of this.fields)for(const A of I){const U=Buffer.alloc(1);U.writeUInt8(T),m.push(U),m.push(Buffer.from((0,r.encodeLEB128)(A)))}if(this.edicts.length>0){m.push(Buffer.from("00","hex")),this.edicts.sort((A,U)=>A.id.block==U.id.block?A.id.idx-U.id.idx:A.id.block-U.id.block);let T=0n,I=0n;for(let A=0;A<this.edicts.length;A++){const U=this.edicts[A];if(A==0)T=BigInt(U.id.block),I=BigInt(U.id.idx),m.push(Buffer.from((0,r.encodeLEB128)(T))),m.push(Buffer.from((0,r.encodeLEB128)(I)));else{const M=BigInt(U.id.block),v=BigInt(U.id.idx);if(M==T){const R=v-I;I=v,m.push(Buffer.from((0,r.encodeLEB128)(0n))),m.push(Buffer.from((0,r.encodeLEB128)(R)))}else{const R=M-T;T=M,I=v,m.push(Buffer.from((0,r.encodeLEB128)(R))),m.push(Buffer.from((0,r.encodeLEB128)(v)))}}m.push(Buffer.from((0,r.encodeLEB128)(BigInt(U.amount)))),m.push(Buffer.from((0,r.encodeLEB128)(BigInt(U.output))))}}return Buffer.concat(m)}getFlags(){return Number(this.fields.get(u.Flags))}hasFlags(m){const T=this.getFlags(),I=1<<m;return(T&I)!=0}getMint(){if(!this.fields.has(u.Mint))return(0,n.none)();const[m,T]=this.fields.get(u.Mint);return(0,n.some)(new o(Number(m),Number(T)))}getEtching(){if(!this.hasFlags(a.Etching))return(0,n.none)();const m=this.getDivisibility(),T=this.getPremine(),I=this.getRune(),A=this.getSpacers(),U=this.getSymbol(),M=this.getTerms(),v=this.hasFlags(a.Turbo);return(0,n.some)(new g(m,T,I,A,U,M,v))}getDivisibility(){if(!this.fields.has(u.Divisibility))return(0,n.none)();const[m]=this.fields.get(u.Divisibility);if(m>g.MAX_DIVISIBILITY)throw new Error("invalid divisibility");return(0,n.some)(Number(m))}getPremine(){if(!this.fields.has(u.Premine))return(0,n.none)();const[m]=this.fields.get(u.Premine);return(0,n.some)(Number(m))}getRune(){if(!this.fields.has(u.Rune))return(0,n.none)();const[m]=this.fields.get(u.Rune);return(0,n.some)(new y(m))}getSpacers(){if(!this.fields.has(u.Spacers))return(0,n.none)();const[m]=this.fields.get(u.Spacers);if(m>g.MAX_SPACERS)throw new Error("invalid spacers");return(0,n.some)(Number(m))}getHeightStart(){if(!this.fields.has(u.HeightStart))return(0,n.none)();const[m]=this.fields.get(u.HeightStart);return(0,n.some)(Number(m))}getHeightEnd(){if(!this.fields.has(u.HeightEnd))return(0,n.none)();const[m]=this.fields.get(u.HeightEnd);return(0,n.some)(Number(m))}getOffsetStart(){if(!this.fields.has(u.OffsetStart))return(0,n.none)();const[m]=this.fields.get(u.OffsetStart);return(0,n.some)(Number(m))}getOffsetEnd(){if(!this.fields.has(u.OffsetEnd))return(0,n.none)();const[m]=this.fields.get(u.OffsetEnd);return(0,n.some)(Number(m))}getCap(){if(!this.fields.has(u.Cap))return(0,n.none)();const[m]=this.fields.get(u.Cap);return(0,n.some)(Number(m))}getAmount(){if(!this.fields.has(u.Amount))return(0,n.none)();const[m]=this.fields.get(u.Amount);return(0,n.some)(Number(m))}getSymbol(){if(!this.fields.has(u.Symbol))return(0,n.none)();const[m]=this.fields.get(u.Symbol);return(0,n.some)(String.fromCharCode(Number(m)))}getTerms(){if(!this.hasFlags(a.Terms))return(0,n.none)();const m=this.getCap();if(!m.isSome())throw new Error("no cap field");const T=this.getAmount();if(!T.isSome())throw new Error("no amount field");const I=this.getHeightStart(),A=this.getHeightEnd(),U=this.getOffsetStart(),M=this.getOffsetEnd(),v=new l(I,A),R=new l(U,M);return(0,n.some)(new p(T.value(),m.value(),v,R))}getPointer(){if(!this.fields.has(u.Pointer))return(0,n.none)();const[m]=this.fields.get(u.Pointer);return(0,n.some)(Number(m))}}je.Message=E;class S{constructor(m=new Map,T=Buffer.alloc(0)){this.fields=m,this.data=T}setContent(m,T){this.fields.set(1,Buffer.from(m,"utf8")),this.data=T}setRune(m){let I=(0,t.base26Encode)((0,s.removeSpacers)(m)).toString(16);I.length%2===1&&(I="0"+I),this.setField(S.Tag.RUNE,Buffer.from(I,"hex").reverse())}setField(m,T){this.fields.set(m,T)}static decipher(m,T){const U=e.Transaction.fromHex(m).ins[T].witness[1],M=e.script.decompile(U),v=new Map,R=[];let V=!1;for(let W=5;W<M.length-1;){const H=M[W];if(H===0){V=!0,W++;continue}else if(V)R.push(H),W++;else{const $=H-80,N=M[W+1];if(typeof N=="number"){const K=Buffer.alloc(1);K.writeUInt8(N),v.set($,K)}else v.set($,N);W+=2}}return new S(v,Buffer.concat(R))}encipher(){const m=[];if(this.data&&this.data.length>0){m.push(Buffer.from("0063036f7264","hex")),Array.from(this.fields.entries()).sort((I,A)=>I[0]-A[0]).forEach(([I,A])=>{const U=Buffer.alloc(1);U.writeUInt8(I),m.push(Buffer.from("01","hex")),m.push(U),A.length!=1||A[0]!=0?m.push((0,i.toPushData)(A)):m.push(A)}),m.push(Buffer.from("00","hex"));const T=(0,i.chunks)(Array.from(this.data),520);for(const I of T)m.push((0,i.toPushData)(Buffer.from(I)))}else{m.push(Buffer.from("0063","hex"));const T=this.fields.get(S.Tag.RUNE);if(!T)throw new Error("No rune found!");m.push((0,i.toPushData)(T))}return m.push(Buffer.from("68","hex")),Buffer.concat(m)}}return je.EtchInscription=S,S.Tag={CONTENT_TYPE:1,POINTER:2,PARENT:3,METADATA:5,METAPROTOCOL:7,CONTENT_ENCODING:9,DELEGATE:11,RUNE:13},je}var Rp;function Ox(){return Rp||(Rp=1,(function(e){var t=di&&di.__createBinding||(Object.create?(function(s,o,c,a){a===void 0&&(a=c);var u=Object.getOwnPropertyDescriptor(o,c);(!u||("get"in u?!o.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return o[c]}}),Object.defineProperty(s,a,u)}):(function(s,o,c,a){a===void 0&&(a=c),s[a]=o[c]})),n=di&&di.__exportStar||function(s,o){for(var c in s)c!=="default"&&!Object.prototype.hasOwnProperty.call(o,c)&&t(o,s,c)};Object.defineProperty(e,"__esModule",{value:!0}),e.removeSpacers=e.getSpacersVal=e.applySpacers=e.some=e.none=void 0,n(Ix(),e);var r=ow();Object.defineProperty(e,"none",{enumerable:!0,get:function(){return r.none}}),Object.defineProperty(e,"some",{enumerable:!0,get:function(){return r.some}});var i=cw();Object.defineProperty(e,"applySpacers",{enumerable:!0,get:function(){return i.applySpacers}}),Object.defineProperty(e,"getSpacersVal",{enumerable:!0,get:function(){return i.getSpacersVal}}),Object.defineProperty(e,"removeSpacers",{enumerable:!0,get:function(){return i.removeSpacers}})})(di)),di}var ns=Ox();function oo(e){if(e.length%2!==0)throw new Error("Hex string must have even length");const t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substr(n,2),16);return t}function ba(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function eh(e){return e===Yo.Mainnet?vn:Wp}function Ea(e,t=Yo.Testnet){const n=eh(t);return Uy(e,n)}function Zr(e){const t=vn,n=Wp,r=Mw;let i,s,o=Dt.UNKNOWN;if(e.startsWith("bc1")||e.startsWith("tb1")||e.startsWith("bcrt1"))try{return s=il(e),s.version===0?s.data.length===20?o=Dt.P2WPKH:o=Dt.P2WSH:o=Dt.P2TR,o}catch{return Dt.UNKNOWN}else try{return i=Ny(e),i.version===t.pubKeyHash||i.version===n.pubKeyHash||i.version===r.pubKeyHash?o=Dt.P2PKH:(i.version===t.scriptHash||(i.version,n.scriptHash),o=Dt.P2SH_P2WPKH),o}catch{return Dt.UNKNOWN}}function Px(e,t,n){const r=Ea(e,n),i=t.coins?.[0];return{txid:t.txid,vout:t.vout,satoshis:t.sats.toString(),height:void 0,runes:i?[{id:i.id,amount:i.value.toString()}]:[],address:e,scriptPk:ba(r)}}async function aw(e,t){try{const n=t===Yo.Mainnet?"https://mpc.omnity.network/utxo-status":"https://mpc.omnity.network/testnet4/utxo-status",r=await at.post(n,e).then(c=>c.data);if(!r)return null;const i=JSON.stringify(r),o=new TextEncoder().encode(i);return Array.from(o)}catch{return null}}const kx=Object.freeze(Object.defineProperty({__proto__:null,bytesToHex:ba,formatPoolUtxo:Px,getAddressType:Zr,getScriptByAddress:Ea,getUtxoProof:aw,hexToBytes:oo,toBitcoinNetwork:eh},Symbol.toStringTag,{value:"Module"})),Nx="kqs64-paaaa-aaaar-qamza-cai",Ux="hvyp5-5yaaa-aaaao-qjxha-cai",Wr=BigInt(546),vt="0:0",Cp={P2PKH:148,P2SH_P2WPKH:91,P2WPKH:68,P2WSH:140,P2SH:108,P2TR:58,UNKNOWN:110},Hp={P2PKH:34,P2SH_P2WPKH:32,P2WPKH:31,P2WSH:43,P2SH:32,P2TR:43,UNKNOWN:34},Rx=new Set(["P2WPKH","P2WSH","P2SH_P2WPKH","P2TR"]),Cx=2;class Jr{psbt;client;inputAddressTypes=[];outputAddressTypes=[];config;userInputUtxoDusts=BigInt(0);intentions=[];txFee=BigInt(0);additionalDustNeeded=BigInt(0);inputUtxos=[];constructor(t,n){this.config=t,this.psbt=new Qc({network:eh(t.network)}),this.client=n}addInput(t){if(this.inputUtxos.findIndex(i=>i.txid===t.txid&&i.vout===t.vout)>=0)return;const{address:n}=t;if(Zr(n)===Dt.P2TR){let i=t.pubkey;i||t.address===this.config.address&&this.config.publicKey&&(i=this.config.publicKey);const s=i?i.length===66?i.slice(2):i:void 0;s?this.psbt.data.addInput({hash:t.txid,index:t.vout,witnessUtxo:{value:BigInt(t.satoshis),script:oo(t.scriptPk)},tapInternalKey:oo(s)}):this.psbt.data.addInput({hash:t.txid,index:t.vout,witnessUtxo:{value:BigInt(t.satoshis),script:oo(t.scriptPk)}})}else this.psbt.data.addInput({hash:t.txid,index:t.vout,witnessUtxo:{value:BigInt(t.satoshis),script:oo(t.scriptPk)}});this.inputAddressTypes.push(Zr(n)),this.inputUtxos.push(t),(n===this.config.address||n===this.config.paymentAddress)&&t.runes.length!==0&&(this.userInputUtxoDusts+=BigInt(t.satoshis))}addOutput(t,n){this.psbt.addOutput({address:t,value:n}),this.outputAddressTypes.push(Zr(t))}addScriptOutput(t){this.psbt.addOutput({script:t,value:BigInt(0)}),this.outputAddressTypes.push({OpReturn:BigInt(t.length)})}selectRuneUtxos(t,n,r){const i=[];if(r==BigInt(0))return i;for(const s of t)if(s.runes.length){const o=s.runes.find(c=>c.id==n);if(o&&BigInt(o.amount)==r){i.push(s);break}}if(i.length==0){let s=BigInt(0);for(const o of t)if(o.runes.forEach(c=>{c.id==n&&(s=s+BigInt(c.amount))}),i.push(o),s>=r)break;if(s<r)throw new Error("INSUFFICIENT_RUNE_UTXOs")}return i}selectBtcUtxos(t,n,r=!1){const i=[];if(n<=BigInt(0))return i;let s=BigInt(0);for(const o of t)if(!(o.runes.length&&!r)&&(s+=BigInt(o.satoshis),i.push(o),s>=n))break;if(s<n)throw new Error(`Insufficient BTC UTXOs: need ${n}, have ${s}`);return i}async addBtcAndFees(t,n){const r=this.config.paymentAddress,i=this.additionalDustNeeded,s=Zr(r),o=this.userInputUtxoDusts,c=this.config.feeRate;let a=BigInt(0),u=BigInt(0);if(this.config.manualBuild){a=this.inputUtxos.reduce((m,T)=>m+BigInt(T.satoshis),BigInt(0));for(const m of this.psbt.txOutputs)u+=BigInt(m.value)}this.outputAddressTypes.push(s);let f=!0,l=BigInt(0),p=BigInt(0),y=[],g=BigInt(0),w=BigInt(0);const E=[...this.inputAddressTypes];do{if(l=p,c!==void 0){const m=Jr.estimateTxVirtualSize(this.inputAddressTypes,this.outputAddressTypes);p=BigInt(Math.round(c*m))}else p=(await this.client.orchestrator.estimate_min_tx_fee({input_types:this.inputAddressTypes,pool_address:this.intentions.map(T=>T.poolAddress),output_types:this.outputAddressTypes}).catch(T=>{throw console.error("estimate_min_tx_fee failed:",T),T})).Ok;if(this.config.manualBuild?g=u+p+i-a:g=n+p+i-o,p>l&&g>0){const m=this.selectBtcUtxos(t,g);if(m.length===0)throw new Error(`INSUFFICIENT_BTC_UTXOs: need ${g} more sats (inputs=${a}, outputs=${u}, fee=${p}, dust=${i})`);this.inputAddressTypes=E.concat(m.map(()=>s));const T=m.reduce((I,A)=>I+BigInt(A.satoshis),BigInt(0));T-g>0&&T-g>Wr||(this.outputAddressTypes.pop(),f=!1),y=m}}while(p>l&&g>0);this.inputAddressTypes=[...E],f&&this.outputAddressTypes.pop();let S=BigInt(0);y.forEach(m=>{this.addInput(m),S+=BigInt(m.satoshis)});let _;if(this.config.manualBuild?_=a+S-u-p-i:_=S-g,_<0)throw new Error(`Insufficient UTXO(s): shortage=${-_} sats (inputs=${this.config.manualBuild?a+S:S}, outputs=${this.config.manualBuild?u:n}, fee=${p}, dust=${i})`);_>Wr?this.addOutput(r,_):_>BigInt(0)&&(w=_),this.txFee=w+p}async getInvolvedAddressUtxos(){const t={},n={},r=new Map;r.set(this.config.paymentAddress,{needBtc:!0,runeIds:new Set});const i=s=>{const o=s.trim();return r.has(o)||r.set(o,{needBtc:!1,runeIds:new Set}),r.get(o)};for(const s of this.intentions){for(const a of s.inputCoins){const u=i(a.from);a.coin.id===vt?u.needBtc=!0:u.runeIds.add(a.coin.id)}for(const a of s.outputCoins){const u=i(a.to);a.coin.id===vt?u.needBtc=!0:u.runeIds.add(a.coin.id)}const o=i(s.poolAddress),c=[...s.inputCoins.map(a=>a.coin.id),...s.outputCoins.map(a=>a.coin.id)];for(const a of c)a===vt?o.needBtc=!0:o.runeIds.add(a)}return await Promise.all(Array.from(r.entries()).map(async([s,o])=>{if(o.needBtc)try{t[s]=await this.client.getBtcUtxos(s)}catch{t[s]=[]}o.runeIds.size>0&&(n[s]={},await Promise.all(Array.from(o.runeIds).map(async c=>{try{n[s][c]=await this.client.getRuneUtxos(s,c)}catch{n[s][c]=[]}})))})),{btc:t,rune:n}}addInputsAndCalculateOutputs(t){if(!this.intentions.length)throw new Error("No intentions added");const n=this.intentions.map(a=>a.poolAddress),r={},i={};let s=BigInt(0);const o=new Map,c=new Set;this.intentions.forEach(({poolAddress:a,inputCoins:u,outputCoins:f,poolUtxos:l})=>{const p=[...u.filter(({from:g})=>!n.includes(g))],y=[...f];if(p.forEach(({coin:g,from:w})=>{!f.find(E=>E.coin.id===g.id)&&!(n.includes(w)&&w!==a)&&y.push({coin:g,to:a})}),y.forEach(({coin:g})=>{u.find(w=>w.coin.id===g.id)||p.push({coin:g,from:a})}),p.length===0&&y.length===0&&l?.length){const g=o.get(a);o.set(a,g?g.concat(l):[...l]),c.add(a);return}p.forEach(({coin:g,from:w})=>{r[w]??={},r[w][g.id]=(r[w][g.id]??BigInt(0))+BigInt(g.value)}),y.forEach(({coin:g,to:w})=>{i[w]??={},i[w][g.id]=(i[w][g.id]??BigInt(0))+BigInt(g.value)})});for(const[a,u]of o.entries()){if(!u.length)continue;i[a]??={};const f=i[a];u.forEach(l=>{this.addInput(l),f[vt]=(f[vt]??BigInt(0))+BigInt(l.satoshis),l.runes.forEach(p=>{f[p.id]=(f[p.id]??BigInt(0))+BigInt(p.amount)})})}for(const[a,u]of Object.entries(r))for(const[f,l]of Object.entries(u))if(f===vt){if(a===this.config.paymentAddress){s+=l;continue}const p=t.btc[a]||[],y=this.selectBtcUtxos(p,l,n.includes(a)),w=y.reduce((E,S)=>E+BigInt(S.satoshis),BigInt(0))-l;w>BigInt(0)&&(i[a]??={},i[a][f]=(i[a][f]??BigInt(0))+w),y.forEach(E=>{this.addInput(E),n.includes(a)&&E.runes.forEach(S=>{(r[a]?.[S.id]??BigInt(0))>BigInt(0)||(i[a]??={},i[a][S.id]=(i[a][S.id]??BigInt(0))+BigInt(S.amount))})})}else{const p=t.rune[a]?.[f]||[],y=this.selectRuneUtxos(p,f,l),g=y.reduce((S,_)=>{const m=_.runes.find(T=>T.id===f);return S+BigInt(m?.amount??0)},BigInt(0)),w=y.reduce((S,_)=>S+BigInt(_.satoshis),BigInt(0)),E=g-l;if(n.includes(a)){i[a]??={};const S=i[a],_=(r[a]?.[vt]??BigInt(0))>BigInt(0);w>BigInt(0)&&!_&&(S[vt]=(S[vt]??BigInt(0))+w),E>BigInt(0)&&(S[f]=(S[f]??BigInt(0))+E)}else E>BigInt(0)&&(i[a]??={},i[a][f]=(i[a][f]??BigInt(0))+E);y.forEach(S=>this.addInput(S))}for(const[a,u]of Object.entries(i)){if(r[a]||!n.includes(a)||c.has(a))continue;const f=new Set;if(u[vt]!==void 0){const l=t.btc[a]||[],p=l.reduce((y,g)=>y+BigInt(g.satoshis),BigInt(0));i[a]??={},i[a][vt]=(i[a][vt]??BigInt(0))+p,l.forEach(y=>{this.addInput(y),f.add(`${y.txid}:${y.vout}`),y.runes.forEach(g=>{i[a]??={},i[a][g.id]=(i[a][g.id]??BigInt(0))+BigInt(g.amount)})})}for(const[l]of Object.entries(u)){if(l===vt)continue;const y=(t.rune[a]?.[l]||[]).filter(w=>!f.has(`${w.txid}:${w.vout}`)),g=y.reduce((w,E)=>{const S=E.runes.find(_=>_.id===l);return w+BigInt(S?.amount??0)},BigInt(0));i[a]??={},i[a][l]=(i[a][l]??BigInt(0))+g,y.forEach(w=>{this.addInput(w),f.add(`${w.txid}:${w.vout}`)})}}return{addressOutputCoinAmounts:i,paymentBtcRequired:s}}addOutputs(t){const n=this.config.mergeSelfRuneBtcOutputs===!0,r=new Set;for(const[,s]of Object.entries(t))for(const o of Object.keys(s))o!==vt&&r.add(o);const i=Array.from(r);if(i.length>0){const s=[],o=[];let c=1;i.forEach(u=>{const f=new ns.RuneId(Number(u.split(":")[0]),Number(u.split(":")[1]));for(const[l,p]of Object.entries(t)){const y=p[u]??BigInt(0);y>BigInt(0)&&(s.push(new ns.Edict(f,y,c)),o.push(l),c++)}});const a=new ns.Runestone(s,ns.none(),ns.none(),ns.none());this.addScriptOutput(new Uint8Array(a.encipher())),o.forEach(u=>{const f=t[u]?.[vt]??BigInt(0),l=u===this.config.address,p=f>BigInt(0)&&(!l||n),y=p&&f>Wr?f:Wr;this.addOutput(u,y),p?(f<Wr&&(this.additionalDustNeeded+=Wr-f),delete t[u][vt]):this.additionalDustNeeded+=Wr})}for(const[s,o]of Object.entries(t)){const c=o[vt]??BigInt(0);c>BigInt(0)&&this.addOutput(s,c)}}addIntention(t){this.intentions.push(t)}async build(){const t=await this.getInvolvedAddressUtxos(),n=this.config.paymentAddress;let r=t.btc[n]??[];if(this.config.manualBuild)await this.addBtcAndFees(r,BigInt(0));else{for(const f of this.intentions){const l=f.poolUtxos;if(!l)continue;t.btc[f.poolAddress]=l,t.rune[f.poolAddress]={};const p=t.rune[f.poolAddress];for(const y of l)for(const g of y.runes)(p[g.id]??=[]).push(y)}const{addressOutputCoinAmounts:a,paymentBtcRequired:u}=this.addInputsAndCalculateOutputs(t);this.addOutputs(a),await this.addBtcAndFees(r,u)}const s=this.psbt.__CACHE.__TX.clone(),o=[];for(let a=0;a<this.inputUtxos.length;a++){const u=this.inputUtxos[a],f=u.address;if(f!==this.config.paymentAddress||f!==this.config.address)continue;const l=this.psbt.data.inputs[a].redeemScript,p=Zr(f);if(o.push({index:a,...p===Dt.P2TR?{address:f,disableTweakSigner:!1}:{publicKey:u.pubkey,disableTweakSigner:!0}}),l&&p===Dt.P2SH_P2WPKH){const y=Zt([l]);s.setInputScript(a,y)}}const c=s.getId();return{psbt:this.psbt,txid:c,fee:this.txFee,toSignInputs:o}}static estimateTxVirtualSize(t,n){const r=t.length,i=n.length;let s=8+Jr.varIntSize(r)+Jr.varIntSize(i),o=!1;for(const c of t){const a=Jr.parseAddressType(c);if(a.key==="OpReturn")continue;const u=Cp[a.key]??Cp.UNKNOWN;s+=u,Rx.has(a.key)&&(o=!0)}for(const c of n){const a=Jr.parseAddressType(c);if(a.key==="OpReturn"){const f=Math.max(0,a.opReturnLength??0);s+=11+f;continue}const u=Hp[a.key]??Hp.UNKNOWN;s+=u}return o&&(s+=1),s+Cx}static parseAddressType(t){if("OpReturn"in t){const r=t.OpReturn!==void 0?Number(t.OpReturn):0;return{key:"OpReturn",opReturnLength:Number.isFinite(r)?r:0}}const n=["P2PKH","P2SH_P2WPKH","P2WPKH","P2WSH","P2SH","P2TR"];for(const r of n)if(r in t)return{key:r};return{key:"UNKNOWN"}}static varIntSize(t){return t<253?1:t<=65535?3:t<=4294967295?5:9}async getToSpendUtxos(){return this.inputUtxos.filter(t=>t.address===this.config.paymentAddress||t.address===this.config.address)}async getUtxoProof(){const t=await this.getToSpendUtxos(),n=await aw(t,this.config.network);if(!n)throw new Error("Failed to get utxo proof");return n}async getInvokeArgs(t){const n=await this.getUtxoProof();return{intention_set:{tx_fee_in_sats:Number(this.txFee),initiator_address:this.config.paymentAddress,intentions:this.intentions.map(({action:r,actionParams:i,poolAddress:s,inputCoins:o,outputCoins:c,exchangeId:a,nonce:u})=>({exchange_id:a??this.config.exchangeId,input_coins:o.filter(f=>f.from!==s),output_coins:c,pool_address:s,action:r,action_params:i??"",pool_utxo_spent:[],pool_utxo_received:[],nonce:Number(u)}))},initiator_utxo_proof:n,psbt_hex:t,client_info:[this.config.clientInfo??""]}}async send(t){if(!this.intentions.length)throw new Error("No itentions added");const n=await this.getInvokeArgs(t);return this.client.orchestrator.invoke(n).then(r=>{if(r?.Ok)return r.Ok;{const i=r?.Err??{},s=Object.keys(i)[0],o=i[s];throw new Error(o?s==="ErrorOccurredDuringExecution"?`${s}: ${o.execution_steps?.[0]?.result?.Err??"Unknown Error"}`:`Invoke Error: ${JSON.stringify(r)}`:`Invoke Error: ${JSON.stringify(r)}`)}})}}/*!
76
+ *********************`),re=j.hashForSignature(d,ue,D)}return{script:ue,sighashType:D,hash:re}}function P(d,h,b,B){const C=[];if(h.tapInternalKey){const D=L(d,h,B);D&&C.push(D)}if(h.tapScriptSig){const D=h.tapScriptSig.map(re=>re.pubkey);C.push(...D)}return C.map(D=>X(d,h,b,D,B)).flat()}function L(d,h,b){const{script:B}=Ce(d,h,b);return(0,l.isP2TR)(B)?B.subarray(2,34):null}function G(d){return d.length===64?d:d.subarray(0,64)}function X(d,h,b,B,C,j,D){const re=C.__TX,Q=h.sighashType||u.Transaction.SIGHASH_DEFAULT;Y(Q,D);const ue=b.map((Ve,Ln)=>Ce(Ln,Ve,C)),le=ue.map(Ve=>Ve.script),Be=ue.map(Ve=>Ve.value),Oe=[];if(h.tapInternalKey&&!j){const Ve=L(d,h,C)||Buffer.from([]);if((0,f.toXOnly)(B).equals(Ve)){const Ln=re.hashForWitnessV1(d,le,Be,Q);Oe.push({pubkey:B,hash:Ln})}}const Je=(h.tapLeafScript||[]).filter(Ve=>(0,l.pubkeyInScript)(B,Ve.script)).map(Ve=>{const Ln=(0,c.tapleafHash)({output:Ve.script,version:Ve.leafVersion});return Object.assign({hash:Ln},Ve)}).filter(Ve=>!j||j.equals(Ve.hash)).map(Ve=>{const Ln=re.hashForWitnessV1(d,le,Be,Q,Ve.hash);return{pubkey:B,hash:Ln,leafHash:Ve.hash}});return Oe.concat(Je)}function Y(d,h){if(h&&h.indexOf(d)<0){const b=ge(d);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${b}`)}}function oe(d,h,b){let B;switch(h){case"multisig":const C=Z(d,b);B=o.p2ms({output:d,signatures:C});break;case"pubkey":B=o.p2pk({output:d,signature:b[0].signature});break;case"pubkeyhash":B=o.p2pkh({output:d,pubkey:b[0].pubkey,signature:b[0].signature});break;case"witnesspubkeyhash":B=o.p2wpkh({output:d,pubkey:b[0].pubkey,signature:b[0].signature});break}return B}function ae(d,h,b){const B=b.__TX,C={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(C.isP2SH=!!h.redeemScript,C.isP2WSH=!!h.witnessScript,h.witnessScript)C.script=h.witnessScript;else if(h.redeemScript)C.script=h.redeemScript;else if(h.nonWitnessUtxo){const j=fe(b,h,d),D=B.ins[d].index;C.script=j.outs[D].script}else h.witnessUtxo&&(C.script=h.witnessUtxo.script);return(h.witnessScript||(0,l.isP2WPKH)(C.script))&&(C.isSegwit=!0),C}function ee(d,h,b){const B=(0,n.checkForInput)(h,d);if(!B.bip32Derivation||B.bip32Derivation.length===0)throw new Error("Need bip32Derivation to sign with HD");const C=B.bip32Derivation.map(D=>{if(D.masterFingerprint.equals(b.fingerprint))return D}).filter(D=>!!D);if(C.length===0)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");return C.map(D=>{const re=b.derivePath(D.path);if(!D.pubkey.equals(re.publicKey))throw new Error("pubkey did not match bip32Derivation");return re})}function Z(d,h){return o.p2ms({output:d}).pubkeys.map(B=>(h.filter(C=>C.pubkey.equals(B))[0]||{}).signature).filter(B=>!!B)}function ce(d){let h=0;function b(D){return h+=D,d.slice(h-D,h)}function B(){const D=t.decode(d,h);return h+=t.decode.bytes,D}function C(){return b(B())}function j(){const D=B(),re=[];for(let Q=0;Q<D;Q++)re.push(C());return re}return j()}function ge(d){let h=d&u.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(d&31){case u.Transaction.SIGHASH_ALL:h+="SIGHASH_ALL";break;case u.Transaction.SIGHASH_SINGLE:h+="SIGHASH_SINGLE";break;case u.Transaction.SIGHASH_NONE:h+="SIGHASH_NONE";break}return h}function pe(d,h,b){d.__NON_WITNESS_UTXO_BUF_CACHE[b]=h.nonWitnessUtxo;const B=u.Transaction.fromBuffer(h.nonWitnessUtxo);d.__NON_WITNESS_UTXO_TX_CACHE[b]=B;const C=d,j=b;delete h.nonWitnessUtxo,Object.defineProperty(h,"nonWitnessUtxo",{enumerable:!0,get(){const D=C.__NON_WITNESS_UTXO_BUF_CACHE[j],re=C.__NON_WITNESS_UTXO_TX_CACHE[j];if(D!==void 0)return D;{const Q=re.toBuffer();return C.__NON_WITNESS_UTXO_BUF_CACHE[j]=Q,Q}},set(D){C.__NON_WITNESS_UTXO_BUF_CACHE[j]=D}})}function J(d,h,b,B){let C=0;d.forEach((Q,ue)=>{if(B&&Q.finalScriptSig&&(h.ins[ue].script=Q.finalScriptSig),B&&Q.finalScriptWitness&&(h.ins[ue].witness=ce(Q.finalScriptWitness)),Q.witnessUtxo)C+=Q.witnessUtxo.value;else if(Q.nonWitnessUtxo){const le=fe(b,Q,ue),Be=h.ins[ue].index,Oe=le.outs[Be];C+=Oe.value}});const j=h.outs.reduce((Q,ue)=>Q+ue.value,0),D=C-j;if(D<0)throw new Error("Outputs are spending more than Inputs");const re=h.virtualSize();b.__FEE=D,b.__EXTRACTED_TX=h,b.__FEE_RATE=Math.floor(D/re)}function fe(d,h,b){const B=d.__NON_WITNESS_UTXO_TX_CACHE;return B[b]||pe(d,h,b),B[b]}function Se(d,h,b){const{script:B}=Ce(d,h,b);return B}function Ce(d,h,b){if(h.witnessUtxo!==void 0)return{script:h.witnessUtxo.script,value:h.witnessUtxo.value};if(h.nonWitnessUtxo!==void 0){const C=fe(b,h,d).outs[b.__TX.ins[d].index];return{script:C.script,value:C.value}}else throw new Error("Can't find pubkey in input without Utxo data")}function Ze(d,h,b,B){const C=Se(b,h,B),{meaningfulScript:j}=se(C,b,"input",h.redeemScript,h.witnessScript);return(0,l.pubkeyInScript)(d,j)}function st(d,h,b,B){const C=B.__TX.outs[b].script,{meaningfulScript:j}=se(C,b,"output",h.redeemScript,h.witnessScript);return(0,l.pubkeyInScript)(d,j)}function St(d){if(!d)return;const h=a.decompile(d);if(!h)return;const b=h[h.length-1];if(!(!Buffer.isBuffer(b)||et(b)||Ne(b)||!a.decompile(b)))return b}function Ae(d){if(!d)return;const h=ce(d),b=h[h.length-1];if(!(et(b)||!a.decompile(b)))return b}function ln(d){if(d.length===65){const h=d[64]&1,b=d.slice(0,33);return b[0]=2|h,b}return d.slice()}function et(d){return d.length===33&&a.isCanonicalPubKey(d)}function Ne(d){return a.isCanonicalScriptSignature(d)}function se(d,h,b,B,C){const j=(0,l.isP2SHScript)(d),D=j&&B&&(0,l.isP2WSHScript)(B),re=(0,l.isP2WSHScript)(d);if(j&&B===void 0)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((re||D)&&C===void 0)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let Q;return D?(Q=C,$(h,d,B,b),N(h,B,C,b),te(Q)):re?(Q=C,N(h,d,C,b),te(Q)):j?(Q=B,$(h,d,B,b)):Q=d,{meaningfulScript:Q,type:D?"p2sh-p2wsh":j?"p2sh":re?"p2wsh":"raw"}}function te(d){if((0,l.isP2WPKH)(d)||(0,l.isP2SHScript)(d))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function ne(d){return(0,l.isP2WPKH)(d)?"witnesspubkeyhash":(0,l.isP2PKH)(d)?"pubkeyhash":(0,l.isP2MS)(d)?"multisig":(0,l.isP2PK)(d)?"pubkey":"nonstandard"}function k(d){return[...Array(d).keys()]}return ro}var Bp;function xx(){return Bp||(Bp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.initEccLib=e.Transaction=e.opcodes=e.Psbt=e.Block=e.script=e.payments=e.networks=e.crypto=e.address=void 0;const t=Zl();e.address=t;const n=xr();e.crypto=n;const r=Vn();e.networks=r;const i=oc();e.payments=i;const s=Jt();e.script=s;var o=J8();Object.defineProperty(e,"Block",{enumerable:!0,get:function(){return o.Block}});var c=Tx();Object.defineProperty(e,"Psbt",{enumerable:!0,get:function(){return c.Psbt}});var a=Gl();Object.defineProperty(e,"opcodes",{enumerable:!0,get:function(){return a.OPS}});var u=cc();Object.defineProperty(e,"Transaction",{enumerable:!0,get:function(){return u.Transaction}});var f=zl();Object.defineProperty(e,"initEccLib",{enumerable:!0,get:function(){return f.initEccLib}})})(Yu)),Yu}var _i={},Ip;function Ax(){if(Ip)return _i;Ip=1,Object.defineProperty(_i,"__esModule",{value:!0}),_i.base26Decode=_i.base26Encode=void 0;function e(n){let r=0n;for(let i=0;i<n.length;i++){const s=BigInt(n.charCodeAt(i)-65),o=BigInt(n.length)-1n-BigInt(i);if(o==0n)r+=s;else{const c=26n**o;r+=c*(s+1n)}}return r}_i.base26Encode=e;function t(n){if(n===340282366920938463463374607431768211455n)return"BCGDENLQRQWDSLRUGSNLBTMFIJAV";n+=1n;let r=[];for(;n>0;){const i=(n-1n)%26n;r.push("ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(Number(i))),n=(n-1n)/26n}return r.reverse().join("")}return _i.base26Decode=t,_i}var Si={},Op;function ow(){if(Op)return Si;Op=1,Object.defineProperty(Si,"__esModule",{value:!0}),Si.none=Si.some=void 0;class e{constructor(){}isSome(){return!1}map(s){return new e}value(){return null}}class t{constructor(s){this._value=s}isSome(){return!0}map(s){return new t(s(this.value()))}value(){return this._value}}function n(i){return new t(i)}Si.some=n;function r(){return new e}return Si.none=r,Si}var Ti={},Pp;function vx(){if(Pp)return Ti;Pp=1,Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.decodeLEB128=Ti.encodeLEB128=void 0;function e(n){const r=[];let i=!0;for(;i;){let s=Number(n&BigInt(127));n>>=BigInt(7),n===BigInt(0)?i=!1:s|=128,r.push(s)}return r}Ti.encodeLEB128=e;function t(n){let r=BigInt(0);for(let i=0;i<n.length;i++){const s=BigInt(n[i]);if(i>18)throw new Error("Overlong");let o=s&BigInt(127);if(i==18&&(o&BigInt(124))!=BigInt(0))throw new Error("Overflow");if(r|=o<<BigInt(7)*BigInt(i),(s&BigInt(128))==BigInt(0))return{n:r,len:i+1}}throw new Error("Unterminated")}return Ti.decodeLEB128=t,Ti}var yf={},kp;function Bx(){return kp||(kp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.toPushData=e.chunks=e.toHex=e.zero2=void 0;const t=s=>s.length%2===1?"0"+s:s;e.zero2=t;const n=s=>{let o="";for(let c=0;c<s.length;c++)o+=(0,e.zero2)(s[c].toString(16));return o};e.toHex=n;function r(s,o){const c=[];let a=0;for(;a<s.length;){const u=s.slice(a,a+o);c.push(u),a+=o}return c}e.chunks=r;function i(s){const o=[],c=s.length;if(c<76){const a=Buffer.alloc(1);a.writeUInt8(c),o.push(a)}else if(c<=255){o.push(Buffer.from("4c","hex"));const a=Buffer.alloc(1);a.writeUInt8(c),o.push(a)}else if(c<=65535){o.push(Buffer.from("4d","hex"));const a=Buffer.alloc(2);a.writeUInt16LE(c),o.push(a)}else{o.push(Buffer.from("4e","hex"));const a=Buffer.alloc(4);a.writeUInt32LE(c),o.push(a)}return o.push(s),Buffer.concat(o)}e.toPushData=i})(yf)),yf}var sr={},Np;function cw(){if(Np)return sr;Np=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.removeSpacers=sr.getSpacersVal=sr.applySpacers=void 0;function e(r,i){let s="";for(let o=0;o<r.length;o++)s+=r.charAt(o),i>0&&((i&1)===1&&(s+="•"),i>>=1);return s}sr.applySpacers=e;function t(r){let i=0,s=0;for(let o=0;o<r.length;o++)r.charAt(o)==="•"&&(i+=1<<o-1-s,s++);return i}sr.getSpacersVal=t;function n(r){return r.replace(/[•]+/g,"")}return sr.removeSpacers=n,sr}var Up;function Ix(){if(Up)return je;Up=1,Object.defineProperty(je,"__esModule",{value:!0}),je.EtchInscription=je.Message=je.Runestone=je.Etching=je.Rune=je.Terms=je.Range=je.Flaw=je.Tag=je.Flag=je.Edict=je.RuneId=void 0;const e=xx(),t=Ax(),n=ow(),r=vx(),i=Bx(),s=cw();class o{constructor(m,T){this.block=m,this.idx=T}next(m,T){if(m>BigInt(Number.MAX_SAFE_INTEGER)||T>BigInt(Number.MAX_SAFE_INTEGER))return(0,n.none)();let I=BigInt(this.block)+m;if(I>BigInt(Number.MAX_SAFE_INTEGER))return(0,n.none)();let A=m===0n?BigInt(this.idx)+T:T;return A>BigInt(Number.MAX_SAFE_INTEGER)?(0,n.none)():(0,n.some)(new o(Number(I),Number(A)))}}je.RuneId=o;class c{constructor(m,T,I){this.id=m,this.amount=T,this.output=I}static from_integers(m,T,I,A){return A>4294967295n||A<0n||Number(A)>m.outs.length?(0,n.none)():(0,n.some)(new c(T,I,Number(A)))}}je.Edict=c;var a;(function(_){_[_.Etching=0]="Etching",_[_.Terms=1]="Terms",_[_.Turbo=2]="Turbo",_[_.Cenotaph=127]="Cenotaph"})(a||(je.Flag=a={}));var u;(function(_){_[_.Body=0]="Body",_[_.Flags=2]="Flags",_[_.Rune=4]="Rune",_[_.Premine=6]="Premine",_[_.Cap=8]="Cap",_[_.Amount=10]="Amount",_[_.HeightStart=12]="HeightStart",_[_.HeightEnd=14]="HeightEnd",_[_.OffsetStart=16]="OffsetStart",_[_.OffsetEnd=18]="OffsetEnd",_[_.Mint=20]="Mint",_[_.Pointer=22]="Pointer",_[_.Cenotaph=126]="Cenotaph",_[_.Divisibility=1]="Divisibility",_[_.Spacers=3]="Spacers",_[_.Symbol=5]="Symbol",_[_.Nop=127]="Nop"})(u||(je.Tag=u={}));var f;(function(_){_[_.EdictOutput=0]="EdictOutput",_[_.EdictRuneId=1]="EdictRuneId",_[_.InvalidScript=2]="InvalidScript",_[_.Opcode=3]="Opcode",_[_.SupplyOverflow=4]="SupplyOverflow",_[_.TrailingIntegers=5]="TrailingIntegers",_[_.TruncatedField=6]="TruncatedField",_[_.UnrecognizedEvenTag=7]="UnrecognizedEvenTag",_[_.UnrecognizedFlag=8]="UnrecognizedFlag",_[_.Varint=9]="Varint"})(f||(je.Flaw=f={}));class l{constructor(m,T){this.start=m,this.end=T}}je.Range=l;class p{constructor(m,T,I,A){this.amount=m,this.cap=T,this.height=I,this.offset=A}}je.Terms=p;class y{constructor(m){this.value=m}get name(){return y.toName(this.value)}static toName(m){return(0,t.base26Decode)(m)}static fromName(m){return new y((0,t.base26Encode)((0,s.removeSpacers)(m)))}toString(){return this.name}}je.Rune=y;class g{constructor(m,T,I,A,U,M,v){this.divisibility=m,this.premine=T,this.rune=I,this.spacers=A,this.symbol=U,this.terms=M,this.turbo=v}}je.Etching=g,g.MAX_DIVISIBILITY=38,g.MAX_SPACERS=134217727;class w{constructor(m=[],T,I,A){this.edicts=m,this.etching=T,this.mint=I,this.pointer=A}static create(m,T="etch"){if(T==="etch"){m=m;const I=y.fromName(m.name),A=new p(m.amount,m.cap,new l(m.startHeight?(0,n.some)(m.startHeight):(0,n.none)(),m.endHeight?(0,n.some)(m.endHeight):(0,n.none)()),new l(m.startOffset?(0,n.some)(m.startOffset):(0,n.none)(),m.endOffset?(0,n.some)(m.endOffset):(0,n.none)())),U=m.divisibility?(0,n.some)(m.divisibility):(0,n.none)(),M=m.premine?(0,n.some)(m.premine):(0,n.none)(),v=m.name.indexOf("•")>-1?(0,n.some)((0,s.getSpacersVal)(m.name)):(0,n.none)(),R=m.symbol?(0,n.some)(m.symbol):(0,n.none)(),V=typeof m.pointer=="number"?(0,n.some)(m.pointer):(0,n.none)(),W=new g(U,M,(0,n.some)(I),v,R,(0,n.some)(A),!0);return new w([],(0,n.some)(W),(0,n.none)(),V)}else if(T==="mint"){m=m;const I=typeof m.pointer=="number"?(0,n.some)(m.pointer):(0,n.none)();return new w([],(0,n.none)(),(0,n.some)(new o(m.block,m.txIdx)),I)}else throw new Error(`not ${T} support now`)}static decipher(m){const T=e.Transaction.fromHex(m),I=w.payload(T);if(I.isSome()){const A=w.integers(I.value()),U=E.from_integers(T,A.value()),M=U.getEtching(),v=U.getMint(),R=U.getPointer();return(0,n.some)(new w(U.edicts,M,v,R))}return(0,n.none)()}encipher(){const T=this.toMessage().toBuffer(),I=Buffer.from("6a5d","hex");let A;if(T.length<76)A=Buffer.alloc(1),A.writeUInt8(T.length);else if(T.length<256)A=Buffer.alloc(2),A.writeUInt8(76),A.writeUInt8(T.length);else if(T.length<65536)A=Buffer.alloc(3),A.writeUInt8(77),A.writeUInt16LE(T.length);else if(T.length<4294967296)A=Buffer.alloc(5),A.writeUInt8(78),A.writeUInt32LE(T.length);else throw new Error("runestone too big!");return Buffer.concat([I,A,T])}static payload(m){for(const T of m.outs){const I=e.script.decompile(T.script);if(I[0]===e.script.OPS.OP_RETURN&&I[1]===w.MAGIC_NUMBER){for(let A=2;A<I.length;A++){const U=I[A];return U instanceof Uint8Array?(0,n.some)(Array.from(U)):(0,n.none)()}return(0,n.none)()}}return(0,n.none)()}static integers(m){let T=[],I=0;for(;I<m.length;){let{n:A,len:U}=(0,r.decodeLEB128)(m.slice(I));T.push(A),I+=U}return(0,n.some)(T)}toMessage(){let m=new Map;const T=this.etching.value();if(T){let U=1;if(T.terms.isSome()){let $=1<<a.Terms;U|=$}if(T.turbo){let $=1<<a.Turbo;U|=$}m.set(u.Flags,[BigInt(U)]);const M=T.rune.value();M!==null&&m.set(u.Rune,[BigInt(M.value)]);const v=T.divisibility.value();v!==null&&m.set(u.Divisibility,[BigInt(v)]);const R=T.spacers.value();R!==null&&m.set(u.Spacers,[BigInt(R)]);const V=T.symbol.value();V!==null&&m.set(u.Symbol,[BigInt(V.charCodeAt(0))]);const W=T.premine.value();W!==null&&m.set(u.Premine,[BigInt(W)]);const H=T.terms.value();if(H!==null){m.set(u.Amount,[BigInt(H.amount)]),m.set(u.Cap,[BigInt(H.cap)]);const $=H.height.start.value();$&&m.set(u.HeightStart,[BigInt($)]);const N=H.height.end.value();N&&m.set(u.HeightEnd,[BigInt(N)]);const K=H.offset.start.value();K&&m.set(u.OffsetStart,[BigInt(K)]);const F=H.offset.end.value();F&&m.set(u.OffsetEnd,[BigInt(F)])}}const I=this.mint.value();I!==null&&m.set(u.Mint,[BigInt(I.block),BigInt(I.idx)]);const A=this.pointer.value();return A!==null&&m.set(u.Pointer,[BigInt(A)]),new E(m,this.edicts,0)}}je.Runestone=w,w.MAGIC_NUMBER=93;class E{constructor(m=new Map,T=[],I=0){this.fields=m,this.edicts=T,this.flaws=I}static from_integers(m,T){let I=new Map,A=[],U=0,M=!1;for(let v=0;v<T.length;){let R=T[v];if(Number(R)===u.Body){M=!0,v+=1;continue}if(M){let V=new o(0,0);for(const W of(0,i.chunks)(T.slice(v),4)){if(W.length!=4){U|=f.TrailingIntegers;break}let H=V.next(W[0],W[1]);if(!H.isSome()){U|=f.EdictRuneId;break}const $=c.from_integers(m,H.value(),W[2],W[3]);if(!$.isSome()){U|=f.EdictOutput;break}V=H.value(),A.push($.value())}v+=4}else{let V=T[v+1];const W=I.get(Number(R))||[];W.push(V),I.set(Number(R),W),v+=2}}return new E(I,A,U)}addFieldVal(m,T){const I=this.fields.get(Number(m))||[];I.push(T),this.fields.set(Number(m),I)}addEdict(m){this.edicts.push(m)}toBuffer(){const m=[];for(const[T,I]of this.fields)for(const A of I){const U=Buffer.alloc(1);U.writeUInt8(T),m.push(U),m.push(Buffer.from((0,r.encodeLEB128)(A)))}if(this.edicts.length>0){m.push(Buffer.from("00","hex")),this.edicts.sort((A,U)=>A.id.block==U.id.block?A.id.idx-U.id.idx:A.id.block-U.id.block);let T=0n,I=0n;for(let A=0;A<this.edicts.length;A++){const U=this.edicts[A];if(A==0)T=BigInt(U.id.block),I=BigInt(U.id.idx),m.push(Buffer.from((0,r.encodeLEB128)(T))),m.push(Buffer.from((0,r.encodeLEB128)(I)));else{const M=BigInt(U.id.block),v=BigInt(U.id.idx);if(M==T){const R=v-I;I=v,m.push(Buffer.from((0,r.encodeLEB128)(0n))),m.push(Buffer.from((0,r.encodeLEB128)(R)))}else{const R=M-T;T=M,I=v,m.push(Buffer.from((0,r.encodeLEB128)(R))),m.push(Buffer.from((0,r.encodeLEB128)(v)))}}m.push(Buffer.from((0,r.encodeLEB128)(BigInt(U.amount)))),m.push(Buffer.from((0,r.encodeLEB128)(BigInt(U.output))))}}return Buffer.concat(m)}getFlags(){return Number(this.fields.get(u.Flags))}hasFlags(m){const T=this.getFlags(),I=1<<m;return(T&I)!=0}getMint(){if(!this.fields.has(u.Mint))return(0,n.none)();const[m,T]=this.fields.get(u.Mint);return(0,n.some)(new o(Number(m),Number(T)))}getEtching(){if(!this.hasFlags(a.Etching))return(0,n.none)();const m=this.getDivisibility(),T=this.getPremine(),I=this.getRune(),A=this.getSpacers(),U=this.getSymbol(),M=this.getTerms(),v=this.hasFlags(a.Turbo);return(0,n.some)(new g(m,T,I,A,U,M,v))}getDivisibility(){if(!this.fields.has(u.Divisibility))return(0,n.none)();const[m]=this.fields.get(u.Divisibility);if(m>g.MAX_DIVISIBILITY)throw new Error("invalid divisibility");return(0,n.some)(Number(m))}getPremine(){if(!this.fields.has(u.Premine))return(0,n.none)();const[m]=this.fields.get(u.Premine);return(0,n.some)(Number(m))}getRune(){if(!this.fields.has(u.Rune))return(0,n.none)();const[m]=this.fields.get(u.Rune);return(0,n.some)(new y(m))}getSpacers(){if(!this.fields.has(u.Spacers))return(0,n.none)();const[m]=this.fields.get(u.Spacers);if(m>g.MAX_SPACERS)throw new Error("invalid spacers");return(0,n.some)(Number(m))}getHeightStart(){if(!this.fields.has(u.HeightStart))return(0,n.none)();const[m]=this.fields.get(u.HeightStart);return(0,n.some)(Number(m))}getHeightEnd(){if(!this.fields.has(u.HeightEnd))return(0,n.none)();const[m]=this.fields.get(u.HeightEnd);return(0,n.some)(Number(m))}getOffsetStart(){if(!this.fields.has(u.OffsetStart))return(0,n.none)();const[m]=this.fields.get(u.OffsetStart);return(0,n.some)(Number(m))}getOffsetEnd(){if(!this.fields.has(u.OffsetEnd))return(0,n.none)();const[m]=this.fields.get(u.OffsetEnd);return(0,n.some)(Number(m))}getCap(){if(!this.fields.has(u.Cap))return(0,n.none)();const[m]=this.fields.get(u.Cap);return(0,n.some)(Number(m))}getAmount(){if(!this.fields.has(u.Amount))return(0,n.none)();const[m]=this.fields.get(u.Amount);return(0,n.some)(Number(m))}getSymbol(){if(!this.fields.has(u.Symbol))return(0,n.none)();const[m]=this.fields.get(u.Symbol);return(0,n.some)(String.fromCharCode(Number(m)))}getTerms(){if(!this.hasFlags(a.Terms))return(0,n.none)();const m=this.getCap();if(!m.isSome())throw new Error("no cap field");const T=this.getAmount();if(!T.isSome())throw new Error("no amount field");const I=this.getHeightStart(),A=this.getHeightEnd(),U=this.getOffsetStart(),M=this.getOffsetEnd(),v=new l(I,A),R=new l(U,M);return(0,n.some)(new p(T.value(),m.value(),v,R))}getPointer(){if(!this.fields.has(u.Pointer))return(0,n.none)();const[m]=this.fields.get(u.Pointer);return(0,n.some)(Number(m))}}je.Message=E;class S{constructor(m=new Map,T=Buffer.alloc(0)){this.fields=m,this.data=T}setContent(m,T){this.fields.set(1,Buffer.from(m,"utf8")),this.data=T}setRune(m){let I=(0,t.base26Encode)((0,s.removeSpacers)(m)).toString(16);I.length%2===1&&(I="0"+I),this.setField(S.Tag.RUNE,Buffer.from(I,"hex").reverse())}setField(m,T){this.fields.set(m,T)}static decipher(m,T){const U=e.Transaction.fromHex(m).ins[T].witness[1],M=e.script.decompile(U),v=new Map,R=[];let V=!1;for(let W=5;W<M.length-1;){const H=M[W];if(H===0){V=!0,W++;continue}else if(V)R.push(H),W++;else{const $=H-80,N=M[W+1];if(typeof N=="number"){const K=Buffer.alloc(1);K.writeUInt8(N),v.set($,K)}else v.set($,N);W+=2}}return new S(v,Buffer.concat(R))}encipher(){const m=[];if(this.data&&this.data.length>0){m.push(Buffer.from("0063036f7264","hex")),Array.from(this.fields.entries()).sort((I,A)=>I[0]-A[0]).forEach(([I,A])=>{const U=Buffer.alloc(1);U.writeUInt8(I),m.push(Buffer.from("01","hex")),m.push(U),A.length!=1||A[0]!=0?m.push((0,i.toPushData)(A)):m.push(A)}),m.push(Buffer.from("00","hex"));const T=(0,i.chunks)(Array.from(this.data),520);for(const I of T)m.push((0,i.toPushData)(Buffer.from(I)))}else{m.push(Buffer.from("0063","hex"));const T=this.fields.get(S.Tag.RUNE);if(!T)throw new Error("No rune found!");m.push((0,i.toPushData)(T))}return m.push(Buffer.from("68","hex")),Buffer.concat(m)}}return je.EtchInscription=S,S.Tag={CONTENT_TYPE:1,POINTER:2,PARENT:3,METADATA:5,METAPROTOCOL:7,CONTENT_ENCODING:9,DELEGATE:11,RUNE:13},je}var Rp;function Ox(){return Rp||(Rp=1,(function(e){var t=di&&di.__createBinding||(Object.create?(function(s,o,c,a){a===void 0&&(a=c);var u=Object.getOwnPropertyDescriptor(o,c);(!u||("get"in u?!o.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return o[c]}}),Object.defineProperty(s,a,u)}):(function(s,o,c,a){a===void 0&&(a=c),s[a]=o[c]})),n=di&&di.__exportStar||function(s,o){for(var c in s)c!=="default"&&!Object.prototype.hasOwnProperty.call(o,c)&&t(o,s,c)};Object.defineProperty(e,"__esModule",{value:!0}),e.removeSpacers=e.getSpacersVal=e.applySpacers=e.some=e.none=void 0,n(Ix(),e);var r=ow();Object.defineProperty(e,"none",{enumerable:!0,get:function(){return r.none}}),Object.defineProperty(e,"some",{enumerable:!0,get:function(){return r.some}});var i=cw();Object.defineProperty(e,"applySpacers",{enumerable:!0,get:function(){return i.applySpacers}}),Object.defineProperty(e,"getSpacersVal",{enumerable:!0,get:function(){return i.getSpacersVal}}),Object.defineProperty(e,"removeSpacers",{enumerable:!0,get:function(){return i.removeSpacers}})})(di)),di}var ns=Ox();function oo(e){if(e.length%2!==0)throw new Error("Hex string must have even length");const t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substr(n,2),16);return t}function ba(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function eh(e){return e===Yo.Mainnet?vn:Wp}function Ea(e,t=Yo.Testnet){const n=eh(t);return Uy(e,n)}function Zr(e){const t=vn,n=Wp,r=Mw;let i,s,o=Dt.UNKNOWN;if(e.startsWith("bc1")||e.startsWith("tb1")||e.startsWith("bcrt1"))try{return s=il(e),s.version===0?s.data.length===20?o=Dt.P2WPKH:o=Dt.P2WSH:o=Dt.P2TR,o}catch{return Dt.UNKNOWN}else try{return i=Ny(e),i.version===t.pubKeyHash||i.version===n.pubKeyHash||i.version===r.pubKeyHash?o=Dt.P2PKH:(i.version===t.scriptHash||(i.version,n.scriptHash),o=Dt.P2SH_P2WPKH),o}catch{return Dt.UNKNOWN}}function Px(e,t,n){const r=Ea(e,n),i=t.coins?.[0];return{txid:t.txid,vout:t.vout,satoshis:t.sats.toString(),height:void 0,runes:i?[{id:i.id,amount:i.value.toString()}]:[],address:e,scriptPk:ba(r)}}async function aw(e,t){try{const n=t===Yo.Mainnet?"https://mpc.omnity.network/utxo-status":"https://mpc.omnity.network/testnet4/utxo-status",r=await at.post(n,e).then(c=>c.data);if(!r)return null;const i=JSON.stringify(r),o=new TextEncoder().encode(i);return Array.from(o)}catch{return null}}const kx=Object.freeze(Object.defineProperty({__proto__:null,bytesToHex:ba,formatPoolUtxo:Px,getAddressType:Zr,getScriptByAddress:Ea,getUtxoProof:aw,hexToBytes:oo,toBitcoinNetwork:eh},Symbol.toStringTag,{value:"Module"})),Nx="kqs64-paaaa-aaaar-qamza-cai",Ux="hvyp5-5yaaa-aaaao-qjxha-cai",Wr=BigInt(546),vt="0:0",Cp={P2PKH:148,P2SH_P2WPKH:91,P2WPKH:68,P2WSH:140,P2SH:108,P2TR:58,UNKNOWN:110},Hp={P2PKH:34,P2SH_P2WPKH:32,P2WPKH:31,P2WSH:43,P2SH:32,P2TR:43,UNKNOWN:34},Rx=new Set(["P2WPKH","P2WSH","P2SH_P2WPKH","P2TR"]),Cx=2;class Jr{psbt;client;inputAddressTypes=[];outputAddressTypes=[];config;userInputUtxoDusts=BigInt(0);intentions=[];txFee=BigInt(0);additionalDustNeeded=BigInt(0);inputUtxos=[];constructor(t,n){this.config=t,this.psbt=new Qc({network:eh(t.network)}),this.client=n}addInput(t){if(this.inputUtxos.findIndex(i=>i.txid===t.txid&&i.vout===t.vout)>=0)return;const{address:n}=t;if(Zr(n)===Dt.P2TR){let i=t.pubkey;i||t.address===this.config.address&&this.config.publicKey&&(i=this.config.publicKey);const s=i?i.length===66?i.slice(2):i:void 0;s?this.psbt.data.addInput({hash:t.txid,index:t.vout,witnessUtxo:{value:BigInt(t.satoshis),script:oo(t.scriptPk)},tapInternalKey:oo(s)}):this.psbt.data.addInput({hash:t.txid,index:t.vout,witnessUtxo:{value:BigInt(t.satoshis),script:oo(t.scriptPk)}})}else this.psbt.data.addInput({hash:t.txid,index:t.vout,witnessUtxo:{value:BigInt(t.satoshis),script:oo(t.scriptPk)}});this.inputAddressTypes.push(Zr(n)),this.inputUtxos.push(t),(n===this.config.address||n===this.config.paymentAddress)&&t.runes.length!==0&&(this.userInputUtxoDusts+=BigInt(t.satoshis))}addOutput(t,n){this.psbt.addOutput({address:t,value:n}),this.outputAddressTypes.push(Zr(t))}addScriptOutput(t){this.psbt.addOutput({script:t,value:BigInt(0)}),this.outputAddressTypes.push({OpReturn:BigInt(t.length)})}selectRuneUtxos(t,n,r){const i=[];if(r==BigInt(0))return i;for(const s of t)if(s.runes.length){const o=s.runes.find(c=>c.id==n);if(o&&BigInt(o.amount)==r){i.push(s);break}}if(i.length==0){let s=BigInt(0);for(const o of t)if(o.runes.forEach(c=>{c.id==n&&(s=s+BigInt(c.amount))}),i.push(o),s>=r)break;if(s<r)throw new Error("INSUFFICIENT_RUNE_UTXOs")}return i}selectBtcUtxos(t,n,r=!1){const i=[];if(n<=BigInt(0))return i;let s=BigInt(0);for(const o of t)if(!(o.runes.length&&!r)&&(s+=BigInt(o.satoshis),i.push(o),s>=n))break;if(s<n)throw new Error(`Insufficient BTC UTXOs: need ${n}, have ${s}`);return i}async addBtcAndFees(t,n){const r=this.config.paymentAddress,i=this.additionalDustNeeded,s=Zr(r),o=this.userInputUtxoDusts,c=this.config.feeRate;let a=BigInt(0),u=BigInt(0);if(this.config.manualBuild){a=this.inputUtxos.reduce((m,T)=>m+BigInt(T.satoshis),BigInt(0));for(const m of this.psbt.txOutputs)u+=BigInt(m.value)}this.outputAddressTypes.push(s);let f=!0,l=BigInt(0),p=BigInt(0),y=[],g=BigInt(0),w=BigInt(0);const E=[...this.inputAddressTypes];do{if(l=p,c!==void 0){const m=Jr.estimateTxVirtualSize(this.inputAddressTypes,this.outputAddressTypes);p=BigInt(Math.round(c*m))}else p=(await this.client.orchestrator.estimate_min_tx_fee({input_types:this.inputAddressTypes,pool_address:this.intentions.map(T=>T.poolAddress),output_types:this.outputAddressTypes}).catch(T=>{throw console.error("estimate_min_tx_fee failed:",T),T})).Ok;if(this.config.manualBuild?g=u+p+i-a:g=n+p+i-o,p>l&&g>0){const m=this.selectBtcUtxos(t,g);if(m.length===0)throw new Error(`INSUFFICIENT_BTC_UTXOs: need ${g} more sats (inputs=${a}, outputs=${u}, fee=${p}, dust=${i})`);this.inputAddressTypes=E.concat(m.map(()=>s));const T=m.reduce((I,A)=>I+BigInt(A.satoshis),BigInt(0));T-g>0&&T-g>Wr||(this.outputAddressTypes.pop(),f=!1),y=m}}while(p>l&&g>0);this.inputAddressTypes=[...E],f&&this.outputAddressTypes.pop();let S=BigInt(0);y.forEach(m=>{this.addInput(m),S+=BigInt(m.satoshis)});let _;if(this.config.manualBuild?_=a+S-u-p-i:_=S-g,_<0)throw new Error(`Insufficient UTXO(s): shortage=${-_} sats (inputs=${this.config.manualBuild?a+S:S}, outputs=${this.config.manualBuild?u:n}, fee=${p}, dust=${i})`);_>Wr?this.addOutput(r,_):_>BigInt(0)&&(w=_),this.txFee=w+p}async getInvolvedAddressUtxos(){const t={},n={},r=new Map;r.set(this.config.paymentAddress,{needBtc:!0,runeIds:new Set});const i=s=>{const o=s.trim();return r.has(o)||r.set(o,{needBtc:!1,runeIds:new Set}),r.get(o)};for(const s of this.intentions){for(const a of s.inputCoins){const u=i(a.from);a.coin.id===vt?u.needBtc=!0:u.runeIds.add(a.coin.id)}for(const a of s.outputCoins){const u=i(a.to);a.coin.id===vt?u.needBtc=!0:u.runeIds.add(a.coin.id)}const o=i(s.poolAddress),c=[...s.inputCoins.map(a=>a.coin.id),...s.outputCoins.map(a=>a.coin.id)];for(const a of c)a===vt?o.needBtc=!0:o.runeIds.add(a)}return await Promise.all(Array.from(r.entries()).map(async([s,o])=>{if(o.needBtc)try{t[s]=await this.client.getBtcUtxos(s)}catch{t[s]=[]}o.runeIds.size>0&&(n[s]={},await Promise.all(Array.from(o.runeIds).map(async c=>{try{n[s][c]=await this.client.getRuneUtxos(s,c)}catch{n[s][c]=[]}})))})),{btc:t,rune:n}}addInputsAndCalculateOutputs(t){if(!this.intentions.length)throw new Error("No intentions added");const n=this.intentions.map(a=>a.poolAddress),r={},i={};let s=BigInt(0);const o=new Map,c=new Set;this.intentions.forEach(({poolAddress:a,inputCoins:u,outputCoins:f,poolUtxos:l})=>{const p=[...u.filter(({from:g})=>!n.includes(g))],y=[...f];if(p.forEach(({coin:g,from:w})=>{!f.find(E=>E.coin.id===g.id)&&!(n.includes(w)&&w!==a)&&y.push({coin:g,to:a})}),y.forEach(({coin:g})=>{u.find(w=>w.coin.id===g.id)||p.push({coin:g,from:a})}),p.length===0&&y.length===0&&l?.length){const g=o.get(a);o.set(a,g?g.concat(l):[...l]),c.add(a);return}p.forEach(({coin:g,from:w})=>{r[w]??={},r[w][g.id]=(r[w][g.id]??BigInt(0))+BigInt(g.value)}),y.forEach(({coin:g,to:w})=>{i[w]??={},i[w][g.id]=(i[w][g.id]??BigInt(0))+BigInt(g.value)})});for(const[a,u]of o.entries()){if(!u.length)continue;i[a]??={};const f=i[a];u.forEach(l=>{this.addInput(l),f[vt]=(f[vt]??BigInt(0))+BigInt(l.satoshis),l.runes.forEach(p=>{f[p.id]=(f[p.id]??BigInt(0))+BigInt(p.amount)})})}for(const[a,u]of Object.entries(r))for(const[f,l]of Object.entries(u))if(f===vt){if(a===this.config.paymentAddress){s+=l;continue}const p=t.btc[a]||[],y=this.selectBtcUtxos(p,l,n.includes(a)),w=y.reduce((E,S)=>E+BigInt(S.satoshis),BigInt(0))-l;w>BigInt(0)&&(i[a]??={},i[a][f]=(i[a][f]??BigInt(0))+w),y.forEach(E=>{this.addInput(E),n.includes(a)&&E.runes.forEach(S=>{(r[a]?.[S.id]??BigInt(0))>BigInt(0)||(i[a]??={},i[a][S.id]=(i[a][S.id]??BigInt(0))+BigInt(S.amount))})})}else{const p=t.rune[a]?.[f]||[],y=this.selectRuneUtxos(p,f,l),g=y.reduce((S,_)=>{const m=_.runes.find(T=>T.id===f);return S+BigInt(m?.amount??0)},BigInt(0)),w=y.reduce((S,_)=>S+BigInt(_.satoshis),BigInt(0)),E=g-l;if(n.includes(a)){i[a]??={};const S=i[a],_=(r[a]?.[vt]??BigInt(0))>BigInt(0);w>BigInt(0)&&!_&&(S[vt]=(S[vt]??BigInt(0))+w),E>BigInt(0)&&(S[f]=(S[f]??BigInt(0))+E)}else E>BigInt(0)&&(i[a]??={},i[a][f]=(i[a][f]??BigInt(0))+E);y.forEach(S=>this.addInput(S))}for(const[a,u]of Object.entries(i)){if(r[a]||!n.includes(a)||c.has(a))continue;const f=new Set;if(u[vt]!==void 0){const l=t.btc[a]||[],p=l.reduce((y,g)=>y+BigInt(g.satoshis),BigInt(0));i[a]??={},i[a][vt]=(i[a][vt]??BigInt(0))+p,l.forEach(y=>{this.addInput(y),f.add(`${y.txid}:${y.vout}`),y.runes.forEach(g=>{i[a]??={},i[a][g.id]=(i[a][g.id]??BigInt(0))+BigInt(g.amount)})})}for(const[l]of Object.entries(u)){if(l===vt)continue;const y=(t.rune[a]?.[l]||[]).filter(w=>!f.has(`${w.txid}:${w.vout}`)),g=y.reduce((w,E)=>{const S=E.runes.find(_=>_.id===l);return w+BigInt(S?.amount??0)},BigInt(0));i[a]??={},i[a][l]=(i[a][l]??BigInt(0))+g,y.forEach(w=>{this.addInput(w),f.add(`${w.txid}:${w.vout}`)})}}return{addressOutputCoinAmounts:i,paymentBtcRequired:s}}addOutputs(t){const n=this.config.mergeSelfRuneBtcOutputs===!0,r=new Set;for(const[,s]of Object.entries(t))for(const o of Object.keys(s))o!==vt&&r.add(o);const i=Array.from(r);if(i.length>0){const s=[],o=[];let c=1;i.forEach(u=>{const f=new ns.RuneId(Number(u.split(":")[0]),Number(u.split(":")[1]));for(const[l,p]of Object.entries(t)){const y=p[u]??BigInt(0);y>BigInt(0)&&(s.push(new ns.Edict(f,y,c)),o.push(l),c++)}});const a=new ns.Runestone(s,ns.none(),ns.none(),ns.none());this.addScriptOutput(new Uint8Array(a.encipher())),o.forEach(u=>{const f=t[u]?.[vt]??BigInt(0),l=u===this.config.address,p=f>BigInt(0)&&(!l||n),y=p&&f>Wr?f:Wr;this.addOutput(u,y),p?(f<Wr&&(this.additionalDustNeeded+=Wr-f),delete t[u][vt]):this.additionalDustNeeded+=Wr})}for(const[s,o]of Object.entries(t)){const c=o[vt]??BigInt(0);c>BigInt(0)&&this.addOutput(s,c)}}addIntention(t){this.intentions.push(t)}async build(){const t=await this.getInvolvedAddressUtxos(),n=this.config.paymentAddress;let r=t.btc[n]??[];if(this.config.manualBuild)await this.addBtcAndFees(r,BigInt(0));else{for(const f of this.intentions){const l=f.poolUtxos;if(!l)continue;t.btc[f.poolAddress]=l,t.rune[f.poolAddress]={};const p=t.rune[f.poolAddress];for(const y of l)for(const g of y.runes)(p[g.id]??=[]).push(y)}const{addressOutputCoinAmounts:a,paymentBtcRequired:u}=this.addInputsAndCalculateOutputs(t);this.addOutputs(a),await this.addBtcAndFees(r,u)}const s=this.psbt.__CACHE.__TX.clone(),o=[];for(let a=0;a<this.inputUtxos.length;a++){const u=this.inputUtxos[a],f=u.address;if(f!==this.config.paymentAddress&&f!==this.config.address)continue;const l=this.psbt.data.inputs[a]?.redeemScript,p=Zr(f);let y=u.pubkey;if(!y&&f===this.config.paymentAddress&&(y=this.config.paymentPublicKey),!y&&f===this.config.address&&(y=this.config.publicKey),o.push({index:a,...p===Dt.P2TR?{address:f,disableTweakSigner:!1}:{publicKey:y,disableTweakSigner:!0}}),l&&p===Dt.P2SH_P2WPKH){const g=Zt([l]);s.setInputScript(a,g)}}const c=s.getId();return{psbt:this.psbt,txid:c,fee:this.txFee,toSignInputs:o}}static estimateTxVirtualSize(t,n){const r=t.length,i=n.length;let s=8+Jr.varIntSize(r)+Jr.varIntSize(i),o=!1;for(const c of t){const a=Jr.parseAddressType(c);if(a.key==="OpReturn")continue;const u=Cp[a.key]??Cp.UNKNOWN;s+=u,Rx.has(a.key)&&(o=!0)}for(const c of n){const a=Jr.parseAddressType(c);if(a.key==="OpReturn"){const f=Math.max(0,a.opReturnLength??0);s+=11+f;continue}const u=Hp[a.key]??Hp.UNKNOWN;s+=u}return o&&(s+=1),s+Cx}static parseAddressType(t){if("OpReturn"in t){const r=t.OpReturn!==void 0?Number(t.OpReturn):0;return{key:"OpReturn",opReturnLength:Number.isFinite(r)?r:0}}const n=["P2PKH","P2SH_P2WPKH","P2WPKH","P2WSH","P2SH","P2TR"];for(const r of n)if(r in t)return{key:r};return{key:"UNKNOWN"}}static varIntSize(t){return t<253?1:t<=65535?3:t<=4294967295?5:9}async getToSpendUtxos(){return this.inputUtxos.filter(t=>t.address===this.config.paymentAddress||t.address===this.config.address)}async getUtxoProof(){const t=await this.getToSpendUtxos(),n=await aw(t,this.config.network);if(!n)throw new Error("Failed to get utxo proof");return n}async getInvokeArgs(t){const n=await this.getUtxoProof();return{intention_set:{tx_fee_in_sats:Number(this.txFee),initiator_address:this.config.paymentAddress,intentions:this.intentions.map(({action:r,actionParams:i,poolAddress:s,inputCoins:o,outputCoins:c,exchangeId:a,nonce:u})=>({exchange_id:a??this.config.exchangeId,input_coins:o.filter(f=>f.from!==s),output_coins:c,pool_address:s,action:r,action_params:i??"",pool_utxo_spent:[],pool_utxo_received:[],nonce:Number(u)}))},initiator_utxo_proof:n,psbt_hex:t,client_info:[this.config.clientInfo??""]}}async send(t){if(!this.intentions.length)throw new Error("No itentions added");const n=await this.getInvokeArgs(t);return this.client.orchestrator.invoke(n).then(r=>{if(r?.Ok)return r.Ok;{const i=r?.Err??{},s=Object.keys(i)[0],o=i[s];throw new Error(o?s==="ErrorOccurredDuringExecution"?`${s}: ${o.execution_steps?.[0]?.result?.Err??"Unknown Error"}`:`Invoke Error: ${JSON.stringify(r)}`:`Invoke Error: ${JSON.stringify(r)}`)}})}}/*!
77
77
  * decimal.js v10.6.0
78
78
  * An arbitrary-precision Decimal type for JavaScript.
79
79
  * https://github.com/MikeMcl/decimal.js
80
80
  * Copyright (c) 2025 Michael Mclaughlin <M8ch88l@gmail.com>
81
81
  * MIT Licence
82
- */var as=9e15,fi=1e9,Gf="0123456789abcdef",_a="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Sa="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Df={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-as,maxE:as,crypto:!1},uw,gr,Te=!0,su="[DecimalError] ",oi=su+"Invalid argument: ",fw=su+"Precision limit exceeded",lw=su+"crypto unavailable",hw="[object Decimal]",$t=Math.floor,bt=Math.pow,Hx=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Fx=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,Mx=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,dw=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Fn=1e7,be=7,qx=9007199254740991,Vx=_a.length-1,Xf=Sa.length-1,ie={toStringTag:hw};ie.absoluteValue=ie.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),we(e)};ie.ceil=function(){return we(new this.constructor(this),this.e+1,2)};ie.clampedTo=ie.clamp=function(e,t){var n,r=this,i=r.constructor;if(e=new i(e),t=new i(t),!e.s||!t.s)return new i(NaN);if(e.gt(t))throw Error(oi+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new i(r)};ie.comparedTo=ie.cmp=function(e){var t,n,r,i,s=this,o=s.d,c=(e=new s.constructor(e)).d,a=s.s,u=e.s;if(!o||!c)return!a||!u?NaN:a!==u?a:o===c?0:!o^a<0?1:-1;if(!o[0]||!c[0])return o[0]?a:c[0]?-u:0;if(a!==u)return a;if(s.e!==e.e)return s.e>e.e^a<0?1:-1;for(r=o.length,i=c.length,t=0,n=r<i?r:i;t<n;++t)if(o[t]!==c[t])return o[t]>c[t]^a<0?1:-1;return r===i?0:r>i^a<0?1:-1};ie.cosine=ie.cos=function(){var e,t,n=this,r=n.constructor;return n.d?n.d[0]?(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+be,r.rounding=1,n=Lx(r,mw(r,n)),r.precision=e,r.rounding=t,we(gr==2||gr==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)};ie.cubeRoot=ie.cbrt=function(){var e,t,n,r,i,s,o,c,a,u,f=this,l=f.constructor;if(!f.isFinite()||f.isZero())return new l(f);for(Te=!1,s=f.s*bt(f.s*f,1/3),!s||Math.abs(s)==1/0?(n=kt(f.d),e=f.e,(s=(e-n.length+1)%3)&&(n+=s==1||s==-2?"0":"00"),s=bt(n,1/3),e=$t((e+1)/3)-(e%3==(e<0?-1:2)),s==1/0?n="5e"+e:(n=s.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new l(n),r.s=f.s):r=new l(s.toString()),o=(e=l.precision)+3;;)if(c=r,a=c.times(c).times(c),u=a.plus(f),r=De(u.plus(f).times(c),u.plus(a),o+2,1),kt(c.d).slice(0,o)===(n=kt(r.d)).slice(0,o))if(n=n.slice(o-3,o+1),n=="9999"||!i&&n=="4999"){if(!i&&(we(c,e+1,0),c.times(c).times(c).eq(f))){r=c;break}o+=4,i=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(we(r,e+1,1),t=!r.times(r).times(r).eq(f));break}return Te=!0,we(r,e,l.rounding,t)};ie.decimalPlaces=ie.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-$t(this.e/be))*be,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n};ie.dividedBy=ie.div=function(e){return De(this,new this.constructor(e))};ie.dividedToIntegerBy=ie.divToInt=function(e){var t=this,n=t.constructor;return we(De(t,new n(e),0,1,1),n.precision,n.rounding)};ie.equals=ie.eq=function(e){return this.cmp(e)===0};ie.floor=function(){return we(new this.constructor(this),this.e+1,3)};ie.greaterThan=ie.gt=function(e){return this.cmp(e)>0};ie.greaterThanOrEqualTo=ie.gte=function(e){var t=this.cmp(e);return t==1||t===0};ie.hyperbolicCosine=ie.cosh=function(){var e,t,n,r,i,s=this,o=s.constructor,c=new o(1);if(!s.isFinite())return new o(s.s?1/0:NaN);if(s.isZero())return c;n=o.precision,r=o.rounding,o.precision=n+Math.max(s.e,s.sd())+4,o.rounding=1,i=s.d.length,i<32?(e=Math.ceil(i/3),t=(1/cu(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),s=As(o,1,s.times(t),new o(1),!0);for(var a,u=e,f=new o(8);u--;)a=s.times(s),s=c.minus(a.times(f.minus(a.times(f))));return we(s,o.precision=n,o.rounding=r,!0)};ie.hyperbolicSine=ie.sinh=function(){var e,t,n,r,i=this,s=i.constructor;if(!i.isFinite()||i.isZero())return new s(i);if(t=s.precision,n=s.rounding,s.precision=t+Math.max(i.e,i.sd())+4,s.rounding=1,r=i.d.length,r<3)i=As(s,2,i,i,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,i=i.times(1/cu(5,e)),i=As(s,2,i,i,!0);for(var o,c=new s(5),a=new s(16),u=new s(20);e--;)o=i.times(i),i=i.times(c.plus(o.times(a.times(o).plus(u))))}return s.precision=t,s.rounding=n,we(i,t,n,!0)};ie.hyperbolicTangent=ie.tanh=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+7,r.rounding=1,De(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)};ie.inverseCosine=ie.acos=function(){var e=this,t=e.constructor,n=e.abs().cmp(1),r=t.precision,i=t.rounding;return n!==-1?n===0?e.isNeg()?Xn(t,r,i):new t(0):new t(NaN):e.isZero()?Xn(t,r+4,i).times(.5):(t.precision=r+6,t.rounding=1,e=new t(1).minus(e).div(e.plus(1)).sqrt().atan(),t.precision=r,t.rounding=i,e.times(2))};ie.inverseHyperbolicCosine=ie.acosh=function(){var e,t,n=this,r=n.constructor;return n.lte(1)?new r(n.eq(1)?0:NaN):n.isFinite()?(e=r.precision,t=r.rounding,r.precision=e+Math.max(Math.abs(n.e),n.sd())+4,r.rounding=1,Te=!1,n=n.times(n).minus(1).sqrt().plus(n),Te=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)};ie.inverseHyperbolicSine=ie.asinh=function(){var e,t,n=this,r=n.constructor;return!n.isFinite()||n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+2*Math.max(Math.abs(n.e),n.sd())+6,r.rounding=1,Te=!1,n=n.times(n).plus(1).sqrt().plus(n),Te=!0,r.precision=e,r.rounding=t,n.ln())};ie.inverseHyperbolicTangent=ie.atanh=function(){var e,t,n,r,i=this,s=i.constructor;return i.isFinite()?i.e>=0?new s(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(e=s.precision,t=s.rounding,r=i.sd(),Math.max(r,e)<2*-i.e-1?we(new s(i),e,t,!0):(s.precision=n=r-i.e,i=De(i.plus(1),new s(1).minus(i),n+e,1),s.precision=e+4,s.rounding=1,i=i.ln(),s.precision=e,s.rounding=t,i.times(.5))):new s(NaN)};ie.inverseSine=ie.asin=function(){var e,t,n,r,i=this,s=i.constructor;return i.isZero()?new s(i):(t=i.abs().cmp(1),n=s.precision,r=s.rounding,t!==-1?t===0?(e=Xn(s,n+4,r).times(.5),e.s=i.s,e):new s(NaN):(s.precision=n+6,s.rounding=1,i=i.div(new s(1).minus(i.times(i)).sqrt().plus(1)).atan(),s.precision=n,s.rounding=r,i.times(2)))};ie.inverseTangent=ie.atan=function(){var e,t,n,r,i,s,o,c,a,u=this,f=u.constructor,l=f.precision,p=f.rounding;if(u.isFinite()){if(u.isZero())return new f(u);if(u.abs().eq(1)&&l+4<=Xf)return o=Xn(f,l+4,p).times(.25),o.s=u.s,o}else{if(!u.s)return new f(NaN);if(l+4<=Xf)return o=Xn(f,l+4,p).times(.5),o.s=u.s,o}for(f.precision=c=l+10,f.rounding=1,n=Math.min(28,c/be+2|0),e=n;e;--e)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(Te=!1,t=Math.ceil(c/be),r=1,a=u.times(u),o=new f(u),i=u;e!==-1;)if(i=i.times(a),s=o.minus(i.div(r+=2)),i=i.times(a),o=s.plus(i.div(r+=2)),o.d[t]!==void 0)for(e=t;o.d[e]===s.d[e]&&e--;);return n&&(o=o.times(2<<n-1)),Te=!0,we(o,f.precision=l,f.rounding=p,!0)};ie.isFinite=function(){return!!this.d};ie.isInteger=ie.isInt=function(){return!!this.d&&$t(this.e/be)>this.d.length-2};ie.isNaN=function(){return!this.s};ie.isNegative=ie.isNeg=function(){return this.s<0};ie.isPositive=ie.isPos=function(){return this.s>0};ie.isZero=function(){return!!this.d&&this.d[0]===0};ie.lessThan=ie.lt=function(e){return this.cmp(e)<0};ie.lessThanOrEqualTo=ie.lte=function(e){return this.cmp(e)<1};ie.logarithm=ie.log=function(e){var t,n,r,i,s,o,c,a,u=this,f=u.constructor,l=f.precision,p=f.rounding,y=5;if(e==null)e=new f(10),t=!0;else{if(e=new f(e),n=e.d,e.s<0||!n||!n[0]||e.eq(1))return new f(NaN);t=e.eq(10)}if(n=u.d,u.s<0||!n||!n[0]||u.eq(1))return new f(n&&!n[0]?-1/0:u.s!=1?NaN:n?0:1/0);if(t)if(n.length>1)s=!0;else{for(i=n[0];i%10===0;)i/=10;s=i!==1}if(Te=!1,c=l+y,o=Qr(u,c),r=t?Ta(f,c+10):Qr(e,c),a=De(o,r,c,1),Po(a.d,i=l,p))do if(c+=10,o=Qr(u,c),r=t?Ta(f,c+10):Qr(e,c),a=De(o,r,c,1),!s){+kt(a.d).slice(i+1,i+15)+1==1e14&&(a=we(a,l+1,0));break}while(Po(a.d,i+=10,p));return Te=!0,we(a,l,p)};ie.minus=ie.sub=function(e){var t,n,r,i,s,o,c,a,u,f,l,p,y=this,g=y.constructor;if(e=new g(e),!y.d||!e.d)return!y.s||!e.s?e=new g(NaN):y.d?e.s=-e.s:e=new g(e.d||y.s!==e.s?y:NaN),e;if(y.s!=e.s)return e.s=-e.s,y.plus(e);if(u=y.d,p=e.d,c=g.precision,a=g.rounding,!u[0]||!p[0]){if(p[0])e.s=-e.s;else if(u[0])e=new g(y);else return new g(a===3?-0:0);return Te?we(e,c,a):e}if(n=$t(e.e/be),f=$t(y.e/be),u=u.slice(),s=f-n,s){for(l=s<0,l?(t=u,s=-s,o=p.length):(t=p,n=f,o=u.length),r=Math.max(Math.ceil(c/be),o)+2,s>r&&(s=r,t.length=1),t.reverse(),r=s;r--;)t.push(0);t.reverse()}else{for(r=u.length,o=p.length,l=r<o,l&&(o=r),r=0;r<o;r++)if(u[r]!=p[r]){l=u[r]<p[r];break}s=0}for(l&&(t=u,u=p,p=t,e.s=-e.s),o=u.length,r=p.length-o;r>0;--r)u[o++]=0;for(r=p.length;r>s;){if(u[--r]<p[r]){for(i=r;i&&u[--i]===0;)u[i]=Fn-1;--u[i],u[r]+=Fn}u[r]-=p[r]}for(;u[--o]===0;)u.pop();for(;u[0]===0;u.shift())--n;return u[0]?(e.d=u,e.e=ou(u,n),Te?we(e,c,a):e):new g(a===3?-0:0)};ie.modulo=ie.mod=function(e){var t,n=this,r=n.constructor;return e=new r(e),!n.d||!e.s||e.d&&!e.d[0]?new r(NaN):!e.d||n.d&&!n.d[0]?we(new r(n),r.precision,r.rounding):(Te=!1,r.modulo==9?(t=De(n,e.abs(),0,3,1),t.s*=e.s):t=De(n,e,0,r.modulo,1),t=t.times(e),Te=!0,n.minus(t))};ie.naturalExponential=ie.exp=function(){return zf(this)};ie.naturalLogarithm=ie.ln=function(){return Qr(this)};ie.negated=ie.neg=function(){var e=new this.constructor(this);return e.s=-e.s,we(e)};ie.plus=ie.add=function(e){var t,n,r,i,s,o,c,a,u,f,l=this,p=l.constructor;if(e=new p(e),!l.d||!e.d)return!l.s||!e.s?e=new p(NaN):l.d||(e=new p(e.d||l.s===e.s?l:NaN)),e;if(l.s!=e.s)return e.s=-e.s,l.minus(e);if(u=l.d,f=e.d,c=p.precision,a=p.rounding,!u[0]||!f[0])return f[0]||(e=new p(l)),Te?we(e,c,a):e;if(s=$t(l.e/be),r=$t(e.e/be),u=u.slice(),i=s-r,i){for(i<0?(n=u,i=-i,o=f.length):(n=f,r=s,o=u.length),s=Math.ceil(c/be),o=s>o?s+1:o+1,i>o&&(i=o,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(o=u.length,i=f.length,o-i<0&&(i=o,n=f,f=u,u=n),t=0;i;)t=(u[--i]=u[i]+f[i]+t)/Fn|0,u[i]%=Fn;for(t&&(u.unshift(t),++r),o=u.length;u[--o]==0;)u.pop();return e.d=u,e.e=ou(u,r),Te?we(e,c,a):e};ie.precision=ie.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(oi+e);return n.d?(t=pw(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t};ie.round=function(){var e=this,t=e.constructor;return we(new t(e),e.e+1,t.rounding)};ie.sine=ie.sin=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+be,r.rounding=1,n=Kx(r,mw(r,n)),r.precision=e,r.rounding=t,we(gr>2?n.neg():n,e,t,!0)):new r(NaN)};ie.squareRoot=ie.sqrt=function(){var e,t,n,r,i,s,o=this,c=o.d,a=o.e,u=o.s,f=o.constructor;if(u!==1||!c||!c[0])return new f(!u||u<0&&(!c||c[0])?NaN:c?o:1/0);for(Te=!1,u=Math.sqrt(+o),u==0||u==1/0?(t=kt(c),(t.length+a)%2==0&&(t+="0"),u=Math.sqrt(t),a=$t((a+1)/2)-(a<0||a%2),u==1/0?t="5e"+a:(t=u.toExponential(),t=t.slice(0,t.indexOf("e")+1)+a),r=new f(t)):r=new f(u.toString()),n=(a=f.precision)+3;;)if(s=r,r=s.plus(De(o,s,n+2,1)).times(.5),kt(s.d).slice(0,n)===(t=kt(r.d)).slice(0,n))if(t=t.slice(n-3,n+1),t=="9999"||!i&&t=="4999"){if(!i&&(we(s,a+1,0),s.times(s).eq(o))){r=s;break}n+=4,i=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(we(r,a+1,1),e=!r.times(r).eq(o));break}return Te=!0,we(r,a,f.rounding,e)};ie.tangent=ie.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,n=n.sin(),n.s=1,n=De(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,we(gr==2||gr==4?n.neg():n,e,t,!0)):new r(NaN)};ie.times=ie.mul=function(e){var t,n,r,i,s,o,c,a,u,f=this,l=f.constructor,p=f.d,y=(e=new l(e)).d;if(e.s*=f.s,!p||!p[0]||!y||!y[0])return new l(!e.s||p&&!p[0]&&!y||y&&!y[0]&&!p?NaN:!p||!y?e.s/0:e.s*0);for(n=$t(f.e/be)+$t(e.e/be),a=p.length,u=y.length,a<u&&(s=p,p=y,y=s,o=a,a=u,u=o),s=[],o=a+u,r=o;r--;)s.push(0);for(r=u;--r>=0;){for(t=0,i=a+r;i>r;)c=s[i]+y[r]*p[i-r-1]+t,s[i--]=c%Fn|0,t=c/Fn|0;s[i]=(s[i]+t)%Fn|0}for(;!s[--o];)s.pop();return t?++n:s.shift(),e.d=s,e.e=ou(s,n),Te?we(e,l.precision,l.rounding):e};ie.toBinary=function(e,t){return th(this,2,e,t)};ie.toDecimalPlaces=ie.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(fn(e,0,fi),t===void 0?t=r.rounding:fn(t,0,8),we(n,e+n.e+1,t))};ie.toExponential=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=Zn(r,!0):(fn(e,0,fi),t===void 0?t=i.rounding:fn(t,0,8),r=we(new i(r),e+1,t),n=Zn(r,!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};ie.toFixed=function(e,t){var n,r,i=this,s=i.constructor;return e===void 0?n=Zn(i):(fn(e,0,fi),t===void 0?t=s.rounding:fn(t,0,8),r=we(new s(i),e+i.e+1,t),n=Zn(r,!1,e+r.e+1)),i.isNeg()&&!i.isZero()?"-"+n:n};ie.toFraction=function(e){var t,n,r,i,s,o,c,a,u,f,l,p,y=this,g=y.d,w=y.constructor;if(!g)return new w(y);if(u=n=new w(1),r=a=new w(0),t=new w(r),s=t.e=pw(g)-y.e-1,o=s%be,t.d[0]=bt(10,o<0?be+o:o),e==null)e=s>0?t:u;else{if(c=new w(e),!c.isInt()||c.lt(u))throw Error(oi+c);e=c.gt(t)?s>0?t:u:c}for(Te=!1,c=new w(kt(g)),f=w.precision,w.precision=s=g.length*be*2;l=De(c,t,0,1,1),i=n.plus(l.times(r)),i.cmp(e)!=1;)n=r,r=i,i=u,u=a.plus(l.times(i)),a=i,i=t,t=c.minus(l.times(i)),c=i;return i=De(e.minus(n),r,0,1,1),a=a.plus(i.times(u)),n=n.plus(i.times(r)),a.s=u.s=y.s,p=De(u,r,s,1).minus(y).abs().cmp(De(a,n,s,1).minus(y).abs())<1?[u,r]:[a,n],w.precision=f,Te=!0,p};ie.toHexadecimal=ie.toHex=function(e,t){return th(this,16,e,t)};ie.toNearest=function(e,t){var n=this,r=n.constructor;if(n=new r(n),e==null){if(!n.d)return n;e=new r(1),t=r.rounding}else{if(e=new r(e),t===void 0?t=r.rounding:fn(t,0,8),!n.d)return e.s?n:e;if(!e.d)return e.s&&(e.s=n.s),e}return e.d[0]?(Te=!1,n=De(n,e,0,t,1).times(e),Te=!0,we(n)):(e.s=n.s,n=e),n};ie.toNumber=function(){return+this};ie.toOctal=function(e,t){return th(this,8,e,t)};ie.toPower=ie.pow=function(e){var t,n,r,i,s,o,c=this,a=c.constructor,u=+(e=new a(e));if(!c.d||!e.d||!c.d[0]||!e.d[0])return new a(bt(+c,u));if(c=new a(c),c.eq(1))return c;if(r=a.precision,s=a.rounding,e.eq(1))return we(c,r,s);if(t=$t(e.e/be),t>=e.d.length-1&&(n=u<0?-u:u)<=qx)return i=yw(a,c,n,r),e.s<0?new a(1).div(i):we(i,r,s);if(o=c.s,o<0){if(t<e.d.length-1)return new a(NaN);if((e.d[t]&1)==0&&(o=1),c.e==0&&c.d[0]==1&&c.d.length==1)return c.s=o,c}return n=bt(+c,u),t=n==0||!isFinite(n)?$t(u*(Math.log("0."+kt(c.d))/Math.LN10+c.e+1)):new a(n+"").e,t>a.maxE+1||t<a.minE-1?new a(t>0?o/0:0):(Te=!1,a.rounding=c.s=1,n=Math.min(12,(t+"").length),i=zf(e.times(Qr(c,r+n)),r),i.d&&(i=we(i,r+5,1),Po(i.d,r,s)&&(t=r+10,i=we(zf(e.times(Qr(c,t+n)),t),t+5,1),+kt(i.d).slice(r+1,r+15)+1==1e14&&(i=we(i,r+1,0)))),i.s=o,Te=!0,a.rounding=s,we(i,r,s))};ie.toPrecision=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=Zn(r,r.e<=i.toExpNeg||r.e>=i.toExpPos):(fn(e,1,fi),t===void 0?t=i.rounding:fn(t,0,8),r=we(new i(r),e,t),n=Zn(r,e<=r.e||r.e<=i.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n};ie.toSignificantDigits=ie.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(fn(e,1,fi),t===void 0?t=r.rounding:fn(t,0,8)),we(new r(n),e,t)};ie.toString=function(){var e=this,t=e.constructor,n=Zn(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n};ie.truncated=ie.trunc=function(){return we(new this.constructor(this),this.e+1,1)};ie.valueOf=ie.toJSON=function(){var e=this,t=e.constructor,n=Zn(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};function kt(e){var t,n,r,i=e.length-1,s="",o=e[0];if(i>0){for(s+=o,t=1;t<i;t++)r=e[t]+"",n=be-r.length,n&&(s+=Yr(n)),s+=r;o=e[t],r=o+"",n=be-r.length,n&&(s+=Yr(n))}else if(o===0)return"0";for(;o%10===0;)o/=10;return s+o}function fn(e,t,n){if(e!==~~e||e<t||e>n)throw Error(oi+e)}function Po(e,t,n,r){var i,s,o,c;for(s=e[0];s>=10;s/=10)--t;return--t<0?(t+=be,i=0):(i=Math.ceil((t+1)/be),t%=be),s=bt(10,be-t),c=e[i]%s|0,r==null?t<3?(t==0?c=c/100|0:t==1&&(c=c/10|0),o=n<4&&c==99999||n>3&&c==49999||c==5e4||c==0):o=(n<4&&c+1==s||n>3&&c+1==s/2)&&(e[i+1]/s/100|0)==bt(10,t-2)-1||(c==s/2||c==0)&&(e[i+1]/s/100|0)==0:t<4?(t==0?c=c/1e3|0:t==1?c=c/100|0:t==2&&(c=c/10|0),o=(r||n<4)&&c==9999||!r&&n>3&&c==4999):o=((r||n<4)&&c+1==s||!r&&n>3&&c+1==s/2)&&(e[i+1]/s/1e3|0)==bt(10,t-3)-1,o}function $c(e,t,n){for(var r,i=[0],s,o=0,c=e.length;o<c;){for(s=i.length;s--;)i[s]*=t;for(i[0]+=Gf.indexOf(e.charAt(o++)),r=0;r<i.length;r++)i[r]>n-1&&(i[r+1]===void 0&&(i[r+1]=0),i[r+1]+=i[r]/n|0,i[r]%=n)}return i.reverse()}function Lx(e,t){var n,r,i;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),i=(1/cu(4,n)).toString()):(n=16,i="2.3283064365386962890625e-10"),e.precision+=n,t=As(e,1,t.times(i),new e(1));for(var s=n;s--;){var o=t.times(t);t=o.times(o).minus(o).times(8).plus(1)}return e.precision-=n,t}var De=(function(){function e(r,i,s){var o,c=0,a=r.length;for(r=r.slice();a--;)o=r[a]*i+c,r[a]=o%s|0,c=o/s|0;return c&&r.unshift(c),r}function t(r,i,s,o){var c,a;if(s!=o)a=s>o?1:-1;else for(c=a=0;c<s;c++)if(r[c]!=i[c]){a=r[c]>i[c]?1:-1;break}return a}function n(r,i,s,o){for(var c=0;s--;)r[s]-=c,c=r[s]<i[s]?1:0,r[s]=c*o+r[s]-i[s];for(;!r[0]&&r.length>1;)r.shift()}return function(r,i,s,o,c,a){var u,f,l,p,y,g,w,E,S,_,m,T,I,A,U,M,v,R,V,W,H=r.constructor,$=r.s==i.s?1:-1,N=r.d,K=i.d;if(!N||!N[0]||!K||!K[0])return new H(!r.s||!i.s||(N?K&&N[0]==K[0]:!K)?NaN:N&&N[0]==0||!K?$*0:$/0);for(a?(y=1,f=r.e-i.e):(a=Fn,y=be,f=$t(r.e/y)-$t(i.e/y)),V=K.length,v=N.length,S=new H($),_=S.d=[],l=0;K[l]==(N[l]||0);l++);if(K[l]>(N[l]||0)&&f--,s==null?(A=s=H.precision,o=H.rounding):c?A=s+(r.e-i.e)+1:A=s,A<0)_.push(1),g=!0;else{if(A=A/y+2|0,l=0,V==1){for(p=0,K=K[0],A++;(l<v||p)&&A--;l++)U=p*a+(N[l]||0),_[l]=U/K|0,p=U%K|0;g=p||l<v}else{for(p=a/(K[0]+1)|0,p>1&&(K=e(K,p,a),N=e(N,p,a),V=K.length,v=N.length),M=V,m=N.slice(0,V),T=m.length;T<V;)m[T++]=0;W=K.slice(),W.unshift(0),R=K[0],K[1]>=a/2&&++R;do p=0,u=t(K,m,V,T),u<0?(I=m[0],V!=T&&(I=I*a+(m[1]||0)),p=I/R|0,p>1?(p>=a&&(p=a-1),w=e(K,p,a),E=w.length,T=m.length,u=t(w,m,E,T),u==1&&(p--,n(w,V<E?W:K,E,a))):(p==0&&(u=p=1),w=K.slice()),E=w.length,E<T&&w.unshift(0),n(m,w,T,a),u==-1&&(T=m.length,u=t(K,m,V,T),u<1&&(p++,n(m,V<T?W:K,T,a))),T=m.length):u===0&&(p++,m=[0]),_[l++]=p,u&&m[0]?m[T++]=N[M]||0:(m=[N[M]],T=1);while((M++<v||m[0]!==void 0)&&A--);g=m[0]!==void 0}_[0]||_.shift()}if(y==1)S.e=f,uw=g;else{for(l=1,p=_[0];p>=10;p/=10)l++;S.e=l+f*y-1,we(S,c?s+S.e+1:s,o,g)}return S}})();function we(e,t,n,r){var i,s,o,c,a,u,f,l,p,y=e.constructor;e:if(t!=null){if(l=e.d,!l)return e;for(i=1,c=l[0];c>=10;c/=10)i++;if(s=t-i,s<0)s+=be,o=t,f=l[p=0],a=f/bt(10,i-o-1)%10|0;else if(p=Math.ceil((s+1)/be),c=l.length,p>=c)if(r){for(;c++<=p;)l.push(0);f=a=0,i=1,s%=be,o=s-be+1}else break e;else{for(f=c=l[p],i=1;c>=10;c/=10)i++;s%=be,o=s-be+i,a=o<0?0:f/bt(10,i-o-1)%10|0}if(r=r||t<0||l[p+1]!==void 0||(o<0?f:f%bt(10,i-o-1)),u=n<4?(a||r)&&(n==0||n==(e.s<0?3:2)):a>5||a==5&&(n==4||r||n==6&&(s>0?o>0?f/bt(10,i-o):0:l[p-1])%10&1||n==(e.s<0?8:7)),t<1||!l[0])return l.length=0,u?(t-=e.e+1,l[0]=bt(10,(be-t%be)%be),e.e=-t||0):l[0]=e.e=0,e;if(s==0?(l.length=p,c=1,p--):(l.length=p+1,c=bt(10,be-s),l[p]=o>0?(f/bt(10,i-o)%bt(10,o)|0)*c:0),u)for(;;)if(p==0){for(s=1,o=l[0];o>=10;o/=10)s++;for(o=l[0]+=c,c=1;o>=10;o/=10)c++;s!=c&&(e.e++,l[0]==Fn&&(l[0]=1));break}else{if(l[p]+=c,l[p]!=Fn)break;l[p--]=0,c=1}for(s=l.length;l[--s]===0;)l.pop()}return Te&&(e.e>y.maxE?(e.d=null,e.e=NaN):e.e<y.minE&&(e.e=0,e.d=[0])),e}function Zn(e,t,n){if(!e.isFinite())return ww(e);var r,i=e.e,s=kt(e.d),o=s.length;return t?(n&&(r=n-o)>0?s=s.charAt(0)+"."+s.slice(1)+Yr(r):o>1&&(s=s.charAt(0)+"."+s.slice(1)),s=s+(e.e<0?"e":"e+")+e.e):i<0?(s="0."+Yr(-i-1)+s,n&&(r=n-o)>0&&(s+=Yr(r))):i>=o?(s+=Yr(i+1-o),n&&(r=n-i-1)>0&&(s=s+"."+Yr(r))):((r=i+1)<o&&(s=s.slice(0,r)+"."+s.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(s+="."),s+=Yr(r))),s}function ou(e,t){var n=e[0];for(t*=be;n>=10;n/=10)t++;return t}function Ta(e,t,n){if(t>Vx)throw Te=!0,n&&(e.precision=n),Error(fw);return we(new e(_a),t,1,!0)}function Xn(e,t,n){if(t>Xf)throw Error(fw);return we(new e(Sa),t,n,!0)}function pw(e){var t=e.length-1,n=t*be+1;if(t=e[t],t){for(;t%10==0;t/=10)n--;for(t=e[0];t>=10;t/=10)n++}return n}function Yr(e){for(var t="";e--;)t+="0";return t}function yw(e,t,n,r){var i,s=new e(1),o=Math.ceil(r/be+4);for(Te=!1;;){if(n%2&&(s=s.times(t),Mp(s.d,o)&&(i=!0)),n=$t(n/2),n===0){n=s.d.length-1,i&&s.d[n]===0&&++s.d[n];break}t=t.times(t),Mp(t.d,o)}return Te=!0,s}function Fp(e){return e.d[e.d.length-1]&1}function gw(e,t,n){for(var r,i,s=new e(t[0]),o=0;++o<t.length;){if(i=new e(t[o]),!i.s){s=i;break}r=s.cmp(i),(r===n||r===0&&s.s===n)&&(s=i)}return s}function zf(e,t){var n,r,i,s,o,c,a,u=0,f=0,l=0,p=e.constructor,y=p.rounding,g=p.precision;if(!e.d||!e.d[0]||e.e>17)return new p(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(t==null?(Te=!1,a=g):a=t,c=new p(.03125);e.e>-2;)e=e.times(c),l+=5;for(r=Math.log(bt(2,l))/Math.LN10*2+5|0,a+=r,n=s=o=new p(1),p.precision=a;;){if(s=we(s.times(e),a,1),n=n.times(++f),c=o.plus(De(s,n,a,1)),kt(c.d).slice(0,a)===kt(o.d).slice(0,a)){for(i=l;i--;)o=we(o.times(o),a,1);if(t==null)if(u<3&&Po(o.d,a-r,y,u))p.precision=a+=10,n=s=c=new p(1),f=0,u++;else return we(o,p.precision=g,y,Te=!0);else return p.precision=g,o}o=c}}function Qr(e,t){var n,r,i,s,o,c,a,u,f,l,p,y=1,g=10,w=e,E=w.d,S=w.constructor,_=S.rounding,m=S.precision;if(w.s<0||!E||!E[0]||!w.e&&E[0]==1&&E.length==1)return new S(E&&!E[0]?-1/0:w.s!=1?NaN:E?0:w);if(t==null?(Te=!1,f=m):f=t,S.precision=f+=g,n=kt(E),r=n.charAt(0),Math.abs(s=w.e)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)w=w.times(e),n=kt(w.d),r=n.charAt(0),y++;s=w.e,r>1?(w=new S("0."+n),s++):w=new S(r+"."+n.slice(1))}else return u=Ta(S,f+2,m).times(s+""),w=Qr(new S(r+"."+n.slice(1)),f-g).plus(u),S.precision=m,t==null?we(w,m,_,Te=!0):w;for(l=w,a=o=w=De(w.minus(1),w.plus(1),f,1),p=we(w.times(w),f,1),i=3;;){if(o=we(o.times(p),f,1),u=a.plus(De(o,new S(i),f,1)),kt(u.d).slice(0,f)===kt(a.d).slice(0,f))if(a=a.times(2),s!==0&&(a=a.plus(Ta(S,f+2,m).times(s+""))),a=De(a,new S(y),f,1),t==null)if(Po(a.d,f-g,_,c))S.precision=f+=g,u=o=w=De(l.minus(1),l.plus(1),f,1),p=we(w.times(w),f,1),i=c=1;else return we(a,S.precision=m,_,Te=!0);else return S.precision=m,a;a=u,i+=2}}function ww(e){return String(e.s*e.s/0)}function Kc(e,t){var n,r,i;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;r++);for(i=t.length;t.charCodeAt(i-1)===48;--i);if(t=t.slice(r,i),t){if(i-=r,e.e=n=n-r-1,e.d=[],r=(n+1)%be,n<0&&(r+=be),r<i){for(r&&e.d.push(+t.slice(0,r)),i-=be;r<i;)e.d.push(+t.slice(r,r+=be));t=t.slice(r),r=be-t.length}else r-=i;for(;r--;)t+="0";e.d.push(+t),Te&&(e.e>e.constructor.maxE?(e.d=null,e.e=NaN):e.e<e.constructor.minE&&(e.e=0,e.d=[0]))}else e.e=0,e.d=[0];return e}function $x(e,t){var n,r,i,s,o,c,a,u,f;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),dw.test(t))return Kc(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(Fx.test(t))n=16,t=t.toLowerCase();else if(Hx.test(t))n=2;else if(Mx.test(t))n=8;else throw Error(oi+t);for(s=t.search(/p/i),s>0?(a=+t.slice(s+1),t=t.substring(2,s)):t=t.slice(2),s=t.indexOf("."),o=s>=0,r=e.constructor,o&&(t=t.replace(".",""),c=t.length,s=c-s,i=yw(r,new r(n),s,s*2)),u=$c(t,n,Fn),f=u.length-1,s=f;u[s]===0;--s)u.pop();return s<0?new r(e.s*0):(e.e=ou(u,f),e.d=u,Te=!1,o&&(e=De(e,i,c*4)),a&&(e=e.times(Math.abs(a)<54?bt(2,a):ei.pow(2,a))),Te=!0,e)}function Kx(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:As(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/cu(5,n)),t=As(e,2,t,t);for(var i,s=new e(5),o=new e(16),c=new e(20);n--;)i=t.times(t),t=t.times(s.plus(i.times(o.times(i).minus(c))));return t}function As(e,t,n,r,i){var s,o,c,a,u=e.precision,f=Math.ceil(u/be);for(Te=!1,a=n.times(n),c=new e(r);;){if(o=De(c.times(a),new e(t++*t++),u,1),c=i?r.plus(o):r.minus(o),r=De(o.times(a),new e(t++*t++),u,1),o=c.plus(r),o.d[f]!==void 0){for(s=f;o.d[s]===c.d[s]&&s--;);if(s==-1)break}s=c,c=r,r=o,o=s}return Te=!0,o.d.length=f+1,o}function cu(e,t){for(var n=e;--t;)n*=e;return n}function mw(e,t){var n,r=t.s<0,i=Xn(e,e.precision,1),s=i.times(.5);if(t=t.abs(),t.lte(s))return gr=r?4:1,t;if(n=t.divToInt(i),n.isZero())gr=r?3:2;else{if(t=t.minus(n.times(i)),t.lte(s))return gr=Fp(n)?r?2:3:r?4:1,t;gr=Fp(n)?r?1:4:r?3:2}return t.minus(i).abs()}function th(e,t,n,r){var i,s,o,c,a,u,f,l,p,y=e.constructor,g=n!==void 0;if(g?(fn(n,1,fi),r===void 0?r=y.rounding:fn(r,0,8)):(n=y.precision,r=y.rounding),!e.isFinite())f=ww(e);else{for(f=Zn(e),o=f.indexOf("."),g?(i=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):i=t,o>=0&&(f=f.replace(".",""),p=new y(1),p.e=f.length-o,p.d=$c(Zn(p),10,i),p.e=p.d.length),l=$c(f,10,i),s=a=l.length;l[--a]==0;)l.pop();if(!l[0])f=g?"0p+0":"0";else{if(o<0?s--:(e=new y(e),e.d=l,e.e=s,e=De(e,p,n,r,0,i),l=e.d,s=e.e,u=uw),o=l[n],c=i/2,u=u||l[n+1]!==void 0,u=r<4?(o!==void 0||u)&&(r===0||r===(e.s<0?3:2)):o>c||o===c&&(r===4||u||r===6&&l[n-1]&1||r===(e.s<0?8:7)),l.length=n,u)for(;++l[--n]>i-1;)l[n]=0,n||(++s,l.unshift(1));for(a=l.length;!l[a-1];--a);for(o=0,f="";o<a;o++)f+=Gf.charAt(l[o]);if(g){if(a>1)if(t==16||t==8){for(o=t==16?4:3,--a;a%o;a++)f+="0";for(l=$c(f,i,t),a=l.length;!l[a-1];--a);for(o=1,f="1.";o<a;o++)f+=Gf.charAt(l[o])}else f=f.charAt(0)+"."+f.slice(1);f=f+(s<0?"p":"p+")+s}else if(s<0){for(;++s;)f="0"+f;f="0."+f}else if(++s>a)for(s-=a;s--;)f+="0";else s<a&&(f=f.slice(0,s)+"."+f.slice(s))}f=(t==16?"0x":t==2?"0b":t==8?"0o":"")+f}return e.s<0?"-"+f:f}function Mp(e,t){if(e.length>t)return e.length=t,!0}function jx(e){return new this(e).abs()}function Wx(e){return new this(e).acos()}function Gx(e){return new this(e).acosh()}function Dx(e,t){return new this(e).plus(t)}function Xx(e){return new this(e).asin()}function zx(e){return new this(e).asinh()}function Yx(e){return new this(e).atan()}function Zx(e){return new this(e).atanh()}function Jx(e,t){e=new this(e),t=new this(t);var n,r=this.precision,i=this.rounding,s=r+4;return!e.s||!t.s?n=new this(NaN):!e.d&&!t.d?(n=Xn(this,s,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?Xn(this,r,i):new this(0),n.s=e.s):!e.d||t.isZero()?(n=Xn(this,s,1).times(.5),n.s=e.s):t.s<0?(this.precision=s,this.rounding=1,n=this.atan(De(e,t,s,1)),t=Xn(this,s,1),this.precision=r,this.rounding=i,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(De(e,t,s,1)),n}function Qx(e){return new this(e).cbrt()}function e6(e){return we(e=new this(e),e.e+1,2)}function t6(e,t,n){return new this(e).clamp(t,n)}function n6(e){if(!e||typeof e!="object")throw Error(su+"Object expected");var t,n,r,i=e.defaults===!0,s=["precision",1,fi,"rounding",0,8,"toExpNeg",-as,0,"toExpPos",0,as,"maxE",0,as,"minE",-as,0,"modulo",0,9];for(t=0;t<s.length;t+=3)if(n=s[t],i&&(this[n]=Df[n]),(r=e[n])!==void 0)if($t(r)===r&&r>=s[t+1]&&r<=s[t+2])this[n]=r;else throw Error(oi+n+": "+r);if(n="crypto",i&&(this[n]=Df[n]),(r=e[n])!==void 0)if(r===!0||r===!1||r===0||r===1)if(r)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[n]=!0;else throw Error(lw);else this[n]=!1;else throw Error(oi+n+": "+r);return this}function r6(e){return new this(e).cos()}function i6(e){return new this(e).cosh()}function bw(e){var t,n,r;function i(s){var o,c,a,u=this;if(!(u instanceof i))return new i(s);if(u.constructor=i,qp(s)){u.s=s.s,Te?!s.d||s.e>i.maxE?(u.e=NaN,u.d=null):s.e<i.minE?(u.e=0,u.d=[0]):(u.e=s.e,u.d=s.d.slice()):(u.e=s.e,u.d=s.d?s.d.slice():s.d);return}if(a=typeof s,a==="number"){if(s===0){u.s=1/s<0?-1:1,u.e=0,u.d=[0];return}if(s<0?(s=-s,u.s=-1):u.s=1,s===~~s&&s<1e7){for(o=0,c=s;c>=10;c/=10)o++;Te?o>i.maxE?(u.e=NaN,u.d=null):o<i.minE?(u.e=0,u.d=[0]):(u.e=o,u.d=[s]):(u.e=o,u.d=[s]);return}if(s*0!==0){s||(u.s=NaN),u.e=NaN,u.d=null;return}return Kc(u,s.toString())}if(a==="string")return(c=s.charCodeAt(0))===45?(s=s.slice(1),u.s=-1):(c===43&&(s=s.slice(1)),u.s=1),dw.test(s)?Kc(u,s):$x(u,s);if(a==="bigint")return s<0?(s=-s,u.s=-1):u.s=1,Kc(u,s.toString());throw Error(oi+s)}if(i.prototype=ie,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.EUCLID=9,i.config=i.set=n6,i.clone=bw,i.isDecimal=qp,i.abs=jx,i.acos=Wx,i.acosh=Gx,i.add=Dx,i.asin=Xx,i.asinh=zx,i.atan=Yx,i.atanh=Zx,i.atan2=Jx,i.cbrt=Qx,i.ceil=e6,i.clamp=t6,i.cos=r6,i.cosh=i6,i.div=s6,i.exp=o6,i.floor=c6,i.hypot=a6,i.ln=u6,i.log=f6,i.log10=h6,i.log2=l6,i.max=d6,i.min=p6,i.mod=y6,i.mul=g6,i.pow=w6,i.random=m6,i.round=b6,i.sign=E6,i.sin=_6,i.sinh=S6,i.sqrt=T6,i.sub=x6,i.sum=A6,i.tan=v6,i.tanh=B6,i.trunc=I6,e===void 0&&(e={}),e&&e.defaults!==!0)for(r=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return i.config(e),i}function s6(e,t){return new this(e).div(t)}function o6(e){return new this(e).exp()}function c6(e){return we(e=new this(e),e.e+1,3)}function a6(){var e,t,n=new this(0);for(Te=!1,e=0;e<arguments.length;)if(t=new this(arguments[e++]),t.d)n.d&&(n=n.plus(t.times(t)));else{if(t.s)return Te=!0,new this(1/0);n=t}return Te=!0,n.sqrt()}function qp(e){return e instanceof ei||e&&e.toStringTag===hw||!1}function u6(e){return new this(e).ln()}function f6(e,t){return new this(e).log(t)}function l6(e){return new this(e).log(2)}function h6(e){return new this(e).log(10)}function d6(){return gw(this,arguments,-1)}function p6(){return gw(this,arguments,1)}function y6(e,t){return new this(e).mod(t)}function g6(e,t){return new this(e).mul(t)}function w6(e,t){return new this(e).pow(t)}function m6(e){var t,n,r,i,s=0,o=new this(1),c=[];if(e===void 0?e=this.precision:fn(e,1,fi),r=Math.ceil(e/be),this.crypto)if(crypto.getRandomValues)for(t=crypto.getRandomValues(new Uint32Array(r));s<r;)i=t[s],i>=429e7?t[s]=crypto.getRandomValues(new Uint32Array(1))[0]:c[s++]=i%1e7;else if(crypto.randomBytes){for(t=crypto.randomBytes(r*=4);s<r;)i=t[s]+(t[s+1]<<8)+(t[s+2]<<16)+((t[s+3]&127)<<24),i>=214e7?crypto.randomBytes(4).copy(t,s):(c.push(i%1e7),s+=4);s=r/4}else throw Error(lw);else for(;s<r;)c[s++]=Math.random()*1e7|0;for(r=c[--s],e%=be,r&&e&&(i=bt(10,be-e),c[s]=(r/i|0)*i);c[s]===0;s--)c.pop();if(s<0)n=0,c=[0];else{for(n=-1;c[0]===0;n-=be)c.shift();for(r=1,i=c[0];i>=10;i/=10)r++;r<be&&(n-=be-r)}return o.e=n,o.d=c,o}function b6(e){return we(e=new this(e),e.e+1,this.rounding)}function E6(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function _6(e){return new this(e).sin()}function S6(e){return new this(e).sinh()}function T6(e){return new this(e).sqrt()}function x6(e,t){return new this(e).sub(t)}function A6(){var e=0,t=arguments,n=new this(t[e]);for(Te=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return Te=!0,we(n,this.precision,this.rounding)}function v6(e){return new this(e).tan()}function B6(e){return new this(e).tanh()}function I6(e){return we(e=new this(e),e.e+1,1)}ie[Symbol.for("nodejs.util.inspect.custom")]=ie.toString;ie[Symbol.toStringTag]="Decimal";var ei=ie.constructor=bw(Df);_a=new ei(_a);Sa=new ei(Sa);const O6=({IDL:e})=>{const t=e.Record({exchange_id:e.Text,reason:e.Text}),n=e.Variant({Ok:e.Null,Err:e.Text}),r=e.Variant({P2WPKH:e.Null,OpReturn:e.Nat64,P2SH:e.Null,P2TR:e.Null}),i=e.Record({input_types:e.Vec(r),pool_address:e.Vec(e.Text),output_types:e.Vec(r)}),s=e.Variant({Ok:e.Nat64,Err:e.Text}),o=e.Record({user_id:e.Principal}),c=e.Record({canister_version:e.Opt(e.Nat64),canister_id:e.Principal}),a=e.Variant({from_user:o,from_canister:c}),u=e.Record({controllers:e.Vec(e.Principal)}),f=e.Variant({reinstall:e.Null,upgrade:e.Null,install:e.Null}),l=e.Record({mode:f,module_hash:e.Vec(e.Nat8)}),p=e.Record({canister_version:e.Nat64,taken_at_timestamp:e.Nat64,snapshot_id:e.Vec(e.Nat8)}),y=e.Variant({creation:u,code_deployment:l,load_snapshot:p,controllers_change:u,code_uninstall:e.Null}),g=e.Record({timestamp_nanos:e.Nat64,canister_version:e.Nat64,origin:a,details:y}),w=e.Record({controllers:e.Vec(e.Principal),module_hash:e.Opt(e.Vec(e.Nat8)),recent_changes:e.Vec(g),total_num_changes:e.Nat64}),E=e.Variant({Ok:w,Err:e.Text}),S=e.Record({exchange_id:e.Text,pool_address:e.Text,pool_key:e.Text}),_=e.Variant({All:e.Null,ByTxid:e.Text,ByStatusCode:e.Text,ByAddress:e.Text,BySecondsPassed:e.Nat64}),m=e.Variant({Ok:e.Text,Err:e.Text}),T=e.Record({result:m,exchange_id:e.Text,maybe_return_time:e.Opt(e.Text),calling_method:e.Text,calling_args:e.Text,pool_address:e.Text,calling_time:e.Text}),I=e.Record({rollback_results:e.Vec(e.Text),invoke_args:e.Text,invoke_time:e.Text,finalized_time:e.Opt(e.Text),confirmed_time:e.Opt(e.Text),execution_steps:e.Vec(T),processing_result:m,broadcasted_time:e.Opt(e.Text)}),A=e.Record({block_hash:e.Text,block_height:e.Nat32}),U=e.Record({processing_results:e.Vec(e.Text),block_basic:A,txids:e.Vec(e.Text),block_time:e.Text,received_time:e.Text}),M=e.Variant({Abandoned:e.Record({reason:e.Text}),Active:e.Null,Halted:e.Record({reason:e.Text})}),v=e.Record({status:M,exchange_id:e.Text,canister_id:e.Principal,utxo_proof_enabled:e.Bool,client_canisters:e.Vec(e.Principal)}),R=e.Record({rollback_results:e.Vec(e.Text),txid:e.Text,received_time:e.Text,reason:e.Text}),V=e.Variant({mainnet:e.Null,regtest:e.Null,testnet:e.Null}),W=e.Record({min_seconds_of_unconfirmed_tx_in_pool_for_raising_fee_rate:e.Nat32,exchange_registry_principal:e.Principal,max_input_count_of_psbt:e.Nat32,min_tx_confirmations:e.Nat32,mempool_connector_principal:e.Principal,max_unconfirmed_tx_count_in_pool:e.Nat32,min_btc_amount_for_utxo:e.Nat64,rune_indexer_principal:e.Principal,max_intentions_per_invoke:e.Nat32,mempool_connector_public_key:e.Text,max_received_blocks_count:e.Nat32,min_unconfirmed_tx_count_in_pool_for_raising_fee_rate:e.Nat32,bitcoin_network:V}),H=e.Record({low:e.Nat64,high:e.Nat64,update_time:e.Text,medium:e.Nat64}),$=e.Record({last_block:e.Opt(A),pending_tx_count:e.Nat64,mempool_tx_fee_rate:H,invoke_paused:e.Bool,concurrent_invoke_status:e.Text,last_block_time:e.Opt(e.Tuple(e.Nat64,e.Text)),failed_new_block_height:e.Opt(e.Tuple(e.Nat32,e.Text))}),N=e.Variant({Error:e.Null,AvailableUnconfirmed:e.Null,InvalidTxid:e.Null,InvalidVout:e.Null,SpentInMempool:e.Null,SpentOnChain:e.Null,AvailableConfirmed:e.Null}),K=e.Record({status:N,value:e.Opt(e.Text),txid:e.Text,vout:e.Nat32,ancestors:e.Opt(e.Nat32),address:e.Opt(e.Text)}),F=e.Record({id:e.Text,value:e.Nat}),x=e.Record({coins:e.Vec(F),sats:e.Nat64,txid:e.Text,vout:e.Nat32}),O=e.Record({status:e.Opt(K),coins:e.Vec(F),utxo:x,is_signed:e.Bool,owner_pubkey:e.Opt(e.Text),owner_address:e.Text}),q=e.Record({coins_in_inputs:e.Vec(O),txid:e.Text,signed_address_coins:e.Vec(e.Tuple(e.Text,e.Vec(F))),address_coins:e.Vec(e.Tuple(e.Text,e.Vec(F)))}),P=e.Record({is_op_return:e.Bool,utxo:x,owner_address:e.Opt(e.Text)}),L=e.Record({burned_coins:e.Vec(F),coins_in_outputs:e.Vec(P),address_coins:e.Vec(e.Tuple(e.Text,e.Vec(F)))}),G=e.Record({coin:F,from:e.Text}),X=e.Record({to:e.Text,coin:F}),Y=e.Record({input_coins:e.Vec(G),output_coins:e.Vec(X),action:e.Text,exchange_id:e.Text,pool_utxo_spent:e.Vec(e.Text),action_params:e.Text,nonce:e.Nat64,pool_address:e.Text,pool_utxo_received:e.Vec(x)}),oe=e.Record({tx_fee_in_sats:e.Nat64,initiator_address:e.Text,intentions:e.Vec(Y)}),ae=e.Record({applied_fee_rate:e.Nat64,pool_addresses:e.Vec(e.Text),coins_in_inputs:q,txid:e.Text,estimated_min_tx_fee:e.Nat64,actual_tx_fee:e.Nat64,coins_in_outputs:L,tx_vsize:e.Nat64,intention_set:oe,user_coins_in_inputs:e.Vec(F),initially_signed_addresses:e.Vec(e.Text)}),ee=e.Variant({Confirmed:e.Nat32,Rejected:e.Text,Pending:e.Null}),Z=e.Record({status:e.Opt(ee),invoke_log:I,included_block:e.Opt(A),sent_tx_hex:e.Text}),ce=e.Variant({Failed:I,NotFound:e.Null,Succeeded:Z}),ge=e.Record({maybe_rune:e.Opt(F),value:e.Nat64,script_pubkey_hex:e.Text,outpoint:e.Text}),pe=e.Record({client_info:e.Opt(e.Text),intention_set:oe,initiator_utxo_proof:e.Vec(e.Nat8),psbt_hex:e.Text}),J=e.Record({block_hash:e.Text,block_timestamp:e.Nat64,tx_ids:e.Vec(e.Text),block_height:e.Nat32}),fe=e.Variant({Ok:e.Vec(e.Text),Err:e.Text}),Se=e.Record({exchange_canister:e.Principal,exchange_id:e.Text,utxo_proof_enabled:e.Bool,client_canisters:e.Vec(e.Principal)}),Ce=e.Record({txid:e.Text,reason_code:e.Text,reason:e.Text}),Ze=e.Record({txid:e.Text,timestamp:e.Nat64,block:A}),st=e.Record({low:e.Nat64,high:e.Nat64,medium:e.Nat64});return e.Service({abandon_exchange:e.Func([t],[n],[]),clear_exchange_pools:e.Func([],[n],[]),clear_failed_invoke_logs:e.Func([e.Opt(e.Nat64),e.Vec(e.Text)],[n],[]),clear_last_block:e.Func([],[n],[]),clear_rejected_txs:e.Func([],[n],[]),clear_txs_with_min_confirmations:e.Func([e.Nat32],[n],[]),delete_tx_detail:e.Func([e.Text],[n],[]),delete_used_outpoints:e.Func([e.Text],[n],[]),estimate_min_tx_fee:e.Func([i],[s],["query"]),get_canister_info:e.Func([e.Nat64],[E],[]),get_exchange_pools:e.Func([e.Opt(e.Text)],[e.Vec(S)],["query"]),get_failed_invoke_logs:e.Func([_],[e.Vec(e.Tuple(e.Text,I))],["query"]),get_last_sent_txs:e.Func([],[e.Vec(e.Tuple(e.Text,e.Text,e.Opt(e.Nat32)))],["query"]),get_received_blocks:e.Func([e.Opt(e.Bool)],[e.Vec(U)],["query"]),get_registered_exchanges:e.Func([e.Opt(M)],[e.Vec(v)],["query"]),get_rejected_txs:e.Func([],[e.Vec(R)],["query"]),get_settings:e.Func([],[W],["query"]),get_status:e.Func([],[$],["query"]),get_tx_execution_context_view:e.Func([e.Text],[e.Opt(ae)],["query"]),get_tx_execution_result:e.Func([e.Text],[ce],["query"]),get_tx_for_outpoint:e.Func([e.Text],[e.Opt(Z)],["query"]),get_tx_queue_of_pool:e.Func([e.Text],[e.Vec(e.Tuple(e.Text,e.Opt(e.Nat32)))],["query"]),get_tx_sent:e.Func([e.Text],[e.Opt(Z)],["query"]),get_used_outpoints:e.Func([e.Opt(e.Text)],[e.Vec(e.Tuple(e.Text,e.Text))],["query"]),get_zero_confirmed_tx_count_of_pool:e.Func([e.Text],[e.Nat32],["query"]),get_zero_confirmed_txs:e.Func([e.Opt(e.Text)],[e.Vec(e.Text)],["query"]),get_zero_confirmed_utxos_of_address:e.Func([e.Text],[e.Vec(ge)],["query"]),init_status_code_message:e.Func([],[n],[]),inspect_status_code:e.Func([e.Text],[e.Text],["query"]),invoke:e.Func([pe],[m],[]),new_block_detected:e.Func([J],[n],[]),notify_exchange_for_blocks_from_height:e.Func([e.Text,e.Nat32],[fe],[]),notify_exchanges_for_block:e.Func([e.Vec(e.Text),A,e.Nat64,e.Vec(e.Text)],[fe],[]),pause_invoke:e.Func([],[n],[]),reapply_tx:e.Func([e.Text],[n],[]),register_exchange:e.Func([Se],[n],[]),reject_tx:e.Func([Ce],[n],[]),resume_invoke:e.Func([],[n],[]),rollback_tx:e.Func([e.Text],[fe],[]),save_included_block_for_tx:e.Func([Ze],[n],[]),set_bitcoin_network:e.Func([V],[n],[]),set_exchange_registry_principal:e.Func([e.Principal],[n],[]),set_max_input_count_of_psbt:e.Func([e.Nat32],[n],[]),set_max_intentions_per_invoke:e.Func([e.Nat32],[n],[]),set_max_received_blocks_count:e.Func([e.Nat32],[n],[]),set_max_unconfirmed_tx_count_in_pool:e.Func([e.Nat32],[n],[]),set_mempool_connector_principal:e.Func([e.Principal],[n],[]),set_mempool_connector_public_key:e.Func([e.Text],[n],[]),set_min_btc_amount_for_utxo:e.Func([e.Nat64],[n],[]),set_min_tx_confirmations:e.Func([e.Nat32],[n],[]),set_rune_indexer_principal:e.Func([e.Principal],[n],[]),set_tx_fee_per_vbyte:e.Func([st],[n],[]),unhalt_exchange:e.Func([e.Text],[n],[]),version:e.Func([],[e.Text],["query"])})};class P6{xverse;config;exchange;orchestrator;constructor(t){this.config=t;const n=t.network===Yo.Testnet,r=n?"https://api-testnet4.secretkeylabs.io":"https://api.secretkeylabs.io";this.xverse=new XS({baseUrl:r,apiKey:t.xverseApiKey});const i="https://icp0.io";this.exchange=ma.createActor(t.exchangeIdlFactory,{agent:yr.createSync({host:i,retryTimes:50,verifyQuerySignatures:!1}),canisterId:t.exchangeCanisterId}),this.orchestrator=ma.createActor(O6,{agent:yr.createSync({host:i,retryTimes:50,verifyQuerySignatures:!1}),canisterId:n?Ux:Nx})}async filterSpentUtxos(t,n){const r=await this.orchestrator.get_used_outpoints([t]);return n.filter(({txid:i,vout:s})=>r.findIndex(([o])=>`${i}:${s}`===o)<0)}async getPendingBtcUtxos(t){const n=await this.orchestrator.get_zero_confirmed_utxos_of_address(t),r=Zr(t);return n.filter(({maybe_rune:i})=>!i.length).map(({value:i,script_pubkey_hex:s,outpoint:o})=>{const[c,a]=o.split(":");return{txid:c,vout:Number(a),satoshis:i.toString(),scriptPk:s,addressType:r,address:t,runes:[]}})}async getPendingRuneUtxos(t,n){const r=await this.orchestrator.get_zero_confirmed_utxos_of_address(t),i=Zr(t);return r.filter(({maybe_rune:s})=>s.length).map(({value:s,script_pubkey_hex:o,outpoint:c,maybe_rune:a})=>{const[u,f]=c.split(":"),l=a[0];return{txid:u,vout:Number(f),satoshis:s.toString(),scriptPk:o,addressType:i,address:t,runes:l?[{id:l.id,amount:l.value.toString()}]:[],pubkey:n}})}async getBtcUtxos(t){let n=0;const r=60,i=[],s=await this.getPendingBtcUtxos(t);let o=!0;for(;o;){const u=await this.xverse.utxosByAddress(t,n,r);i.push(...u.items),o=u.hasMore,n+=r}const c=Ea(t,this.config.network),a=i.map(({txid:u,vout:f,value:l})=>({txid:u,vout:f,address:t,runes:[],satoshis:l.toString(),scriptPk:ba(c)})).filter(u=>Number(u.satoshis)>546);return this.filterSpentUtxos(t,a.concat(s))}async getRuneUtxos(t,n,r){let i=0;const s=60,o=[],c=await this.getPendingRuneUtxos(t,r);let a=!0;for(;a;){const l=await this.xverse.runeUtxosByAddress(t,n,i,s);o.push(...l.items),a=l.hasMore,i+=s}const u=Ea(t,this.config.network),f=o.map(({txid:l,vout:p,runes:y,amount:g})=>({txid:l,vout:p,address:t,runes:y.map(({runeId:w,amount:E})=>{const S=new ei(E).toFixed(0);return{id:w,amount:S}}),satoshis:g.toString(),scriptPk:ba(u),pubkey:r}));return this.filterSpentUtxos(t,f.concat(c))}async getBtcBalance(t){const r=(await this.getBtcUtxos(t)).reduce((i,s)=>i+BigInt(s.satoshis),BigInt(0));return new ei(r.toString()).div(1e8).toNumber()}async getRuneBalance(t,n,r){const i=await this.getRuneUtxos(t,n,r);if(!i)return;let s=new ei(0);for(const o of i)s=s.add(new ei(o.runes.find(c=>c.id===n)?.amount??0));return s.toNumber()}async getPoolList(){try{return await this.exchange.get_pool_list()??[]}catch(t){throw console.error("get pool list failed:",t),t}}async getPoolInfo(t){try{const n=await this.exchange.get_pool_info({pool_address:t});if(n.length===0)throw new Error("Pool not found");return n[0]}catch(n){throw console.error("get pool data failed:",n),n}}async createTransaction({address:t,paymentAddress:n,publicKey:r,feeRate:i,mergeSelfRuneBtcOutputs:s,clientInfo:o,manualBuild:c}){return new Jr({network:this.config.network,exchangeId:this.config.exchangeId,address:t,paymentAddress:n,publicKey:r,feeRate:i,mergeSelfRuneBtcOutputs:s,clientInfo:o,manualBuild:c},this)}async getRecommendedFeeRate(){const t=await this.orchestrator.get_status();return{min:Number(t.mempool_tx_fee_rate.medium),max:Number(t.mempool_tx_fee_rate.medium)*3}}}exports.Network=Yo;exports.ReeClient=P6;exports.Transaction=Jr;exports.utils=kx;
82
+ */var as=9e15,fi=1e9,Gf="0123456789abcdef",_a="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Sa="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Df={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-as,maxE:as,crypto:!1},uw,gr,Te=!0,su="[DecimalError] ",oi=su+"Invalid argument: ",fw=su+"Precision limit exceeded",lw=su+"crypto unavailable",hw="[object Decimal]",$t=Math.floor,bt=Math.pow,Hx=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Fx=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,Mx=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,dw=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Fn=1e7,be=7,qx=9007199254740991,Vx=_a.length-1,Xf=Sa.length-1,ie={toStringTag:hw};ie.absoluteValue=ie.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),we(e)};ie.ceil=function(){return we(new this.constructor(this),this.e+1,2)};ie.clampedTo=ie.clamp=function(e,t){var n,r=this,i=r.constructor;if(e=new i(e),t=new i(t),!e.s||!t.s)return new i(NaN);if(e.gt(t))throw Error(oi+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new i(r)};ie.comparedTo=ie.cmp=function(e){var t,n,r,i,s=this,o=s.d,c=(e=new s.constructor(e)).d,a=s.s,u=e.s;if(!o||!c)return!a||!u?NaN:a!==u?a:o===c?0:!o^a<0?1:-1;if(!o[0]||!c[0])return o[0]?a:c[0]?-u:0;if(a!==u)return a;if(s.e!==e.e)return s.e>e.e^a<0?1:-1;for(r=o.length,i=c.length,t=0,n=r<i?r:i;t<n;++t)if(o[t]!==c[t])return o[t]>c[t]^a<0?1:-1;return r===i?0:r>i^a<0?1:-1};ie.cosine=ie.cos=function(){var e,t,n=this,r=n.constructor;return n.d?n.d[0]?(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+be,r.rounding=1,n=Lx(r,mw(r,n)),r.precision=e,r.rounding=t,we(gr==2||gr==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)};ie.cubeRoot=ie.cbrt=function(){var e,t,n,r,i,s,o,c,a,u,f=this,l=f.constructor;if(!f.isFinite()||f.isZero())return new l(f);for(Te=!1,s=f.s*bt(f.s*f,1/3),!s||Math.abs(s)==1/0?(n=kt(f.d),e=f.e,(s=(e-n.length+1)%3)&&(n+=s==1||s==-2?"0":"00"),s=bt(n,1/3),e=$t((e+1)/3)-(e%3==(e<0?-1:2)),s==1/0?n="5e"+e:(n=s.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new l(n),r.s=f.s):r=new l(s.toString()),o=(e=l.precision)+3;;)if(c=r,a=c.times(c).times(c),u=a.plus(f),r=De(u.plus(f).times(c),u.plus(a),o+2,1),kt(c.d).slice(0,o)===(n=kt(r.d)).slice(0,o))if(n=n.slice(o-3,o+1),n=="9999"||!i&&n=="4999"){if(!i&&(we(c,e+1,0),c.times(c).times(c).eq(f))){r=c;break}o+=4,i=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(we(r,e+1,1),t=!r.times(r).times(r).eq(f));break}return Te=!0,we(r,e,l.rounding,t)};ie.decimalPlaces=ie.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-$t(this.e/be))*be,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n};ie.dividedBy=ie.div=function(e){return De(this,new this.constructor(e))};ie.dividedToIntegerBy=ie.divToInt=function(e){var t=this,n=t.constructor;return we(De(t,new n(e),0,1,1),n.precision,n.rounding)};ie.equals=ie.eq=function(e){return this.cmp(e)===0};ie.floor=function(){return we(new this.constructor(this),this.e+1,3)};ie.greaterThan=ie.gt=function(e){return this.cmp(e)>0};ie.greaterThanOrEqualTo=ie.gte=function(e){var t=this.cmp(e);return t==1||t===0};ie.hyperbolicCosine=ie.cosh=function(){var e,t,n,r,i,s=this,o=s.constructor,c=new o(1);if(!s.isFinite())return new o(s.s?1/0:NaN);if(s.isZero())return c;n=o.precision,r=o.rounding,o.precision=n+Math.max(s.e,s.sd())+4,o.rounding=1,i=s.d.length,i<32?(e=Math.ceil(i/3),t=(1/cu(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),s=As(o,1,s.times(t),new o(1),!0);for(var a,u=e,f=new o(8);u--;)a=s.times(s),s=c.minus(a.times(f.minus(a.times(f))));return we(s,o.precision=n,o.rounding=r,!0)};ie.hyperbolicSine=ie.sinh=function(){var e,t,n,r,i=this,s=i.constructor;if(!i.isFinite()||i.isZero())return new s(i);if(t=s.precision,n=s.rounding,s.precision=t+Math.max(i.e,i.sd())+4,s.rounding=1,r=i.d.length,r<3)i=As(s,2,i,i,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,i=i.times(1/cu(5,e)),i=As(s,2,i,i,!0);for(var o,c=new s(5),a=new s(16),u=new s(20);e--;)o=i.times(i),i=i.times(c.plus(o.times(a.times(o).plus(u))))}return s.precision=t,s.rounding=n,we(i,t,n,!0)};ie.hyperbolicTangent=ie.tanh=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+7,r.rounding=1,De(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)};ie.inverseCosine=ie.acos=function(){var e=this,t=e.constructor,n=e.abs().cmp(1),r=t.precision,i=t.rounding;return n!==-1?n===0?e.isNeg()?Xn(t,r,i):new t(0):new t(NaN):e.isZero()?Xn(t,r+4,i).times(.5):(t.precision=r+6,t.rounding=1,e=new t(1).minus(e).div(e.plus(1)).sqrt().atan(),t.precision=r,t.rounding=i,e.times(2))};ie.inverseHyperbolicCosine=ie.acosh=function(){var e,t,n=this,r=n.constructor;return n.lte(1)?new r(n.eq(1)?0:NaN):n.isFinite()?(e=r.precision,t=r.rounding,r.precision=e+Math.max(Math.abs(n.e),n.sd())+4,r.rounding=1,Te=!1,n=n.times(n).minus(1).sqrt().plus(n),Te=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)};ie.inverseHyperbolicSine=ie.asinh=function(){var e,t,n=this,r=n.constructor;return!n.isFinite()||n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+2*Math.max(Math.abs(n.e),n.sd())+6,r.rounding=1,Te=!1,n=n.times(n).plus(1).sqrt().plus(n),Te=!0,r.precision=e,r.rounding=t,n.ln())};ie.inverseHyperbolicTangent=ie.atanh=function(){var e,t,n,r,i=this,s=i.constructor;return i.isFinite()?i.e>=0?new s(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(e=s.precision,t=s.rounding,r=i.sd(),Math.max(r,e)<2*-i.e-1?we(new s(i),e,t,!0):(s.precision=n=r-i.e,i=De(i.plus(1),new s(1).minus(i),n+e,1),s.precision=e+4,s.rounding=1,i=i.ln(),s.precision=e,s.rounding=t,i.times(.5))):new s(NaN)};ie.inverseSine=ie.asin=function(){var e,t,n,r,i=this,s=i.constructor;return i.isZero()?new s(i):(t=i.abs().cmp(1),n=s.precision,r=s.rounding,t!==-1?t===0?(e=Xn(s,n+4,r).times(.5),e.s=i.s,e):new s(NaN):(s.precision=n+6,s.rounding=1,i=i.div(new s(1).minus(i.times(i)).sqrt().plus(1)).atan(),s.precision=n,s.rounding=r,i.times(2)))};ie.inverseTangent=ie.atan=function(){var e,t,n,r,i,s,o,c,a,u=this,f=u.constructor,l=f.precision,p=f.rounding;if(u.isFinite()){if(u.isZero())return new f(u);if(u.abs().eq(1)&&l+4<=Xf)return o=Xn(f,l+4,p).times(.25),o.s=u.s,o}else{if(!u.s)return new f(NaN);if(l+4<=Xf)return o=Xn(f,l+4,p).times(.5),o.s=u.s,o}for(f.precision=c=l+10,f.rounding=1,n=Math.min(28,c/be+2|0),e=n;e;--e)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(Te=!1,t=Math.ceil(c/be),r=1,a=u.times(u),o=new f(u),i=u;e!==-1;)if(i=i.times(a),s=o.minus(i.div(r+=2)),i=i.times(a),o=s.plus(i.div(r+=2)),o.d[t]!==void 0)for(e=t;o.d[e]===s.d[e]&&e--;);return n&&(o=o.times(2<<n-1)),Te=!0,we(o,f.precision=l,f.rounding=p,!0)};ie.isFinite=function(){return!!this.d};ie.isInteger=ie.isInt=function(){return!!this.d&&$t(this.e/be)>this.d.length-2};ie.isNaN=function(){return!this.s};ie.isNegative=ie.isNeg=function(){return this.s<0};ie.isPositive=ie.isPos=function(){return this.s>0};ie.isZero=function(){return!!this.d&&this.d[0]===0};ie.lessThan=ie.lt=function(e){return this.cmp(e)<0};ie.lessThanOrEqualTo=ie.lte=function(e){return this.cmp(e)<1};ie.logarithm=ie.log=function(e){var t,n,r,i,s,o,c,a,u=this,f=u.constructor,l=f.precision,p=f.rounding,y=5;if(e==null)e=new f(10),t=!0;else{if(e=new f(e),n=e.d,e.s<0||!n||!n[0]||e.eq(1))return new f(NaN);t=e.eq(10)}if(n=u.d,u.s<0||!n||!n[0]||u.eq(1))return new f(n&&!n[0]?-1/0:u.s!=1?NaN:n?0:1/0);if(t)if(n.length>1)s=!0;else{for(i=n[0];i%10===0;)i/=10;s=i!==1}if(Te=!1,c=l+y,o=Qr(u,c),r=t?Ta(f,c+10):Qr(e,c),a=De(o,r,c,1),Po(a.d,i=l,p))do if(c+=10,o=Qr(u,c),r=t?Ta(f,c+10):Qr(e,c),a=De(o,r,c,1),!s){+kt(a.d).slice(i+1,i+15)+1==1e14&&(a=we(a,l+1,0));break}while(Po(a.d,i+=10,p));return Te=!0,we(a,l,p)};ie.minus=ie.sub=function(e){var t,n,r,i,s,o,c,a,u,f,l,p,y=this,g=y.constructor;if(e=new g(e),!y.d||!e.d)return!y.s||!e.s?e=new g(NaN):y.d?e.s=-e.s:e=new g(e.d||y.s!==e.s?y:NaN),e;if(y.s!=e.s)return e.s=-e.s,y.plus(e);if(u=y.d,p=e.d,c=g.precision,a=g.rounding,!u[0]||!p[0]){if(p[0])e.s=-e.s;else if(u[0])e=new g(y);else return new g(a===3?-0:0);return Te?we(e,c,a):e}if(n=$t(e.e/be),f=$t(y.e/be),u=u.slice(),s=f-n,s){for(l=s<0,l?(t=u,s=-s,o=p.length):(t=p,n=f,o=u.length),r=Math.max(Math.ceil(c/be),o)+2,s>r&&(s=r,t.length=1),t.reverse(),r=s;r--;)t.push(0);t.reverse()}else{for(r=u.length,o=p.length,l=r<o,l&&(o=r),r=0;r<o;r++)if(u[r]!=p[r]){l=u[r]<p[r];break}s=0}for(l&&(t=u,u=p,p=t,e.s=-e.s),o=u.length,r=p.length-o;r>0;--r)u[o++]=0;for(r=p.length;r>s;){if(u[--r]<p[r]){for(i=r;i&&u[--i]===0;)u[i]=Fn-1;--u[i],u[r]+=Fn}u[r]-=p[r]}for(;u[--o]===0;)u.pop();for(;u[0]===0;u.shift())--n;return u[0]?(e.d=u,e.e=ou(u,n),Te?we(e,c,a):e):new g(a===3?-0:0)};ie.modulo=ie.mod=function(e){var t,n=this,r=n.constructor;return e=new r(e),!n.d||!e.s||e.d&&!e.d[0]?new r(NaN):!e.d||n.d&&!n.d[0]?we(new r(n),r.precision,r.rounding):(Te=!1,r.modulo==9?(t=De(n,e.abs(),0,3,1),t.s*=e.s):t=De(n,e,0,r.modulo,1),t=t.times(e),Te=!0,n.minus(t))};ie.naturalExponential=ie.exp=function(){return zf(this)};ie.naturalLogarithm=ie.ln=function(){return Qr(this)};ie.negated=ie.neg=function(){var e=new this.constructor(this);return e.s=-e.s,we(e)};ie.plus=ie.add=function(e){var t,n,r,i,s,o,c,a,u,f,l=this,p=l.constructor;if(e=new p(e),!l.d||!e.d)return!l.s||!e.s?e=new p(NaN):l.d||(e=new p(e.d||l.s===e.s?l:NaN)),e;if(l.s!=e.s)return e.s=-e.s,l.minus(e);if(u=l.d,f=e.d,c=p.precision,a=p.rounding,!u[0]||!f[0])return f[0]||(e=new p(l)),Te?we(e,c,a):e;if(s=$t(l.e/be),r=$t(e.e/be),u=u.slice(),i=s-r,i){for(i<0?(n=u,i=-i,o=f.length):(n=f,r=s,o=u.length),s=Math.ceil(c/be),o=s>o?s+1:o+1,i>o&&(i=o,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(o=u.length,i=f.length,o-i<0&&(i=o,n=f,f=u,u=n),t=0;i;)t=(u[--i]=u[i]+f[i]+t)/Fn|0,u[i]%=Fn;for(t&&(u.unshift(t),++r),o=u.length;u[--o]==0;)u.pop();return e.d=u,e.e=ou(u,r),Te?we(e,c,a):e};ie.precision=ie.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(oi+e);return n.d?(t=pw(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t};ie.round=function(){var e=this,t=e.constructor;return we(new t(e),e.e+1,t.rounding)};ie.sine=ie.sin=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+be,r.rounding=1,n=Kx(r,mw(r,n)),r.precision=e,r.rounding=t,we(gr>2?n.neg():n,e,t,!0)):new r(NaN)};ie.squareRoot=ie.sqrt=function(){var e,t,n,r,i,s,o=this,c=o.d,a=o.e,u=o.s,f=o.constructor;if(u!==1||!c||!c[0])return new f(!u||u<0&&(!c||c[0])?NaN:c?o:1/0);for(Te=!1,u=Math.sqrt(+o),u==0||u==1/0?(t=kt(c),(t.length+a)%2==0&&(t+="0"),u=Math.sqrt(t),a=$t((a+1)/2)-(a<0||a%2),u==1/0?t="5e"+a:(t=u.toExponential(),t=t.slice(0,t.indexOf("e")+1)+a),r=new f(t)):r=new f(u.toString()),n=(a=f.precision)+3;;)if(s=r,r=s.plus(De(o,s,n+2,1)).times(.5),kt(s.d).slice(0,n)===(t=kt(r.d)).slice(0,n))if(t=t.slice(n-3,n+1),t=="9999"||!i&&t=="4999"){if(!i&&(we(s,a+1,0),s.times(s).eq(o))){r=s;break}n+=4,i=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(we(r,a+1,1),e=!r.times(r).eq(o));break}return Te=!0,we(r,a,f.rounding,e)};ie.tangent=ie.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,n=n.sin(),n.s=1,n=De(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,we(gr==2||gr==4?n.neg():n,e,t,!0)):new r(NaN)};ie.times=ie.mul=function(e){var t,n,r,i,s,o,c,a,u,f=this,l=f.constructor,p=f.d,y=(e=new l(e)).d;if(e.s*=f.s,!p||!p[0]||!y||!y[0])return new l(!e.s||p&&!p[0]&&!y||y&&!y[0]&&!p?NaN:!p||!y?e.s/0:e.s*0);for(n=$t(f.e/be)+$t(e.e/be),a=p.length,u=y.length,a<u&&(s=p,p=y,y=s,o=a,a=u,u=o),s=[],o=a+u,r=o;r--;)s.push(0);for(r=u;--r>=0;){for(t=0,i=a+r;i>r;)c=s[i]+y[r]*p[i-r-1]+t,s[i--]=c%Fn|0,t=c/Fn|0;s[i]=(s[i]+t)%Fn|0}for(;!s[--o];)s.pop();return t?++n:s.shift(),e.d=s,e.e=ou(s,n),Te?we(e,l.precision,l.rounding):e};ie.toBinary=function(e,t){return th(this,2,e,t)};ie.toDecimalPlaces=ie.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(fn(e,0,fi),t===void 0?t=r.rounding:fn(t,0,8),we(n,e+n.e+1,t))};ie.toExponential=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=Zn(r,!0):(fn(e,0,fi),t===void 0?t=i.rounding:fn(t,0,8),r=we(new i(r),e+1,t),n=Zn(r,!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};ie.toFixed=function(e,t){var n,r,i=this,s=i.constructor;return e===void 0?n=Zn(i):(fn(e,0,fi),t===void 0?t=s.rounding:fn(t,0,8),r=we(new s(i),e+i.e+1,t),n=Zn(r,!1,e+r.e+1)),i.isNeg()&&!i.isZero()?"-"+n:n};ie.toFraction=function(e){var t,n,r,i,s,o,c,a,u,f,l,p,y=this,g=y.d,w=y.constructor;if(!g)return new w(y);if(u=n=new w(1),r=a=new w(0),t=new w(r),s=t.e=pw(g)-y.e-1,o=s%be,t.d[0]=bt(10,o<0?be+o:o),e==null)e=s>0?t:u;else{if(c=new w(e),!c.isInt()||c.lt(u))throw Error(oi+c);e=c.gt(t)?s>0?t:u:c}for(Te=!1,c=new w(kt(g)),f=w.precision,w.precision=s=g.length*be*2;l=De(c,t,0,1,1),i=n.plus(l.times(r)),i.cmp(e)!=1;)n=r,r=i,i=u,u=a.plus(l.times(i)),a=i,i=t,t=c.minus(l.times(i)),c=i;return i=De(e.minus(n),r,0,1,1),a=a.plus(i.times(u)),n=n.plus(i.times(r)),a.s=u.s=y.s,p=De(u,r,s,1).minus(y).abs().cmp(De(a,n,s,1).minus(y).abs())<1?[u,r]:[a,n],w.precision=f,Te=!0,p};ie.toHexadecimal=ie.toHex=function(e,t){return th(this,16,e,t)};ie.toNearest=function(e,t){var n=this,r=n.constructor;if(n=new r(n),e==null){if(!n.d)return n;e=new r(1),t=r.rounding}else{if(e=new r(e),t===void 0?t=r.rounding:fn(t,0,8),!n.d)return e.s?n:e;if(!e.d)return e.s&&(e.s=n.s),e}return e.d[0]?(Te=!1,n=De(n,e,0,t,1).times(e),Te=!0,we(n)):(e.s=n.s,n=e),n};ie.toNumber=function(){return+this};ie.toOctal=function(e,t){return th(this,8,e,t)};ie.toPower=ie.pow=function(e){var t,n,r,i,s,o,c=this,a=c.constructor,u=+(e=new a(e));if(!c.d||!e.d||!c.d[0]||!e.d[0])return new a(bt(+c,u));if(c=new a(c),c.eq(1))return c;if(r=a.precision,s=a.rounding,e.eq(1))return we(c,r,s);if(t=$t(e.e/be),t>=e.d.length-1&&(n=u<0?-u:u)<=qx)return i=yw(a,c,n,r),e.s<0?new a(1).div(i):we(i,r,s);if(o=c.s,o<0){if(t<e.d.length-1)return new a(NaN);if((e.d[t]&1)==0&&(o=1),c.e==0&&c.d[0]==1&&c.d.length==1)return c.s=o,c}return n=bt(+c,u),t=n==0||!isFinite(n)?$t(u*(Math.log("0."+kt(c.d))/Math.LN10+c.e+1)):new a(n+"").e,t>a.maxE+1||t<a.minE-1?new a(t>0?o/0:0):(Te=!1,a.rounding=c.s=1,n=Math.min(12,(t+"").length),i=zf(e.times(Qr(c,r+n)),r),i.d&&(i=we(i,r+5,1),Po(i.d,r,s)&&(t=r+10,i=we(zf(e.times(Qr(c,t+n)),t),t+5,1),+kt(i.d).slice(r+1,r+15)+1==1e14&&(i=we(i,r+1,0)))),i.s=o,Te=!0,a.rounding=s,we(i,r,s))};ie.toPrecision=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=Zn(r,r.e<=i.toExpNeg||r.e>=i.toExpPos):(fn(e,1,fi),t===void 0?t=i.rounding:fn(t,0,8),r=we(new i(r),e,t),n=Zn(r,e<=r.e||r.e<=i.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n};ie.toSignificantDigits=ie.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(fn(e,1,fi),t===void 0?t=r.rounding:fn(t,0,8)),we(new r(n),e,t)};ie.toString=function(){var e=this,t=e.constructor,n=Zn(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n};ie.truncated=ie.trunc=function(){return we(new this.constructor(this),this.e+1,1)};ie.valueOf=ie.toJSON=function(){var e=this,t=e.constructor,n=Zn(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};function kt(e){var t,n,r,i=e.length-1,s="",o=e[0];if(i>0){for(s+=o,t=1;t<i;t++)r=e[t]+"",n=be-r.length,n&&(s+=Yr(n)),s+=r;o=e[t],r=o+"",n=be-r.length,n&&(s+=Yr(n))}else if(o===0)return"0";for(;o%10===0;)o/=10;return s+o}function fn(e,t,n){if(e!==~~e||e<t||e>n)throw Error(oi+e)}function Po(e,t,n,r){var i,s,o,c;for(s=e[0];s>=10;s/=10)--t;return--t<0?(t+=be,i=0):(i=Math.ceil((t+1)/be),t%=be),s=bt(10,be-t),c=e[i]%s|0,r==null?t<3?(t==0?c=c/100|0:t==1&&(c=c/10|0),o=n<4&&c==99999||n>3&&c==49999||c==5e4||c==0):o=(n<4&&c+1==s||n>3&&c+1==s/2)&&(e[i+1]/s/100|0)==bt(10,t-2)-1||(c==s/2||c==0)&&(e[i+1]/s/100|0)==0:t<4?(t==0?c=c/1e3|0:t==1?c=c/100|0:t==2&&(c=c/10|0),o=(r||n<4)&&c==9999||!r&&n>3&&c==4999):o=((r||n<4)&&c+1==s||!r&&n>3&&c+1==s/2)&&(e[i+1]/s/1e3|0)==bt(10,t-3)-1,o}function $c(e,t,n){for(var r,i=[0],s,o=0,c=e.length;o<c;){for(s=i.length;s--;)i[s]*=t;for(i[0]+=Gf.indexOf(e.charAt(o++)),r=0;r<i.length;r++)i[r]>n-1&&(i[r+1]===void 0&&(i[r+1]=0),i[r+1]+=i[r]/n|0,i[r]%=n)}return i.reverse()}function Lx(e,t){var n,r,i;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),i=(1/cu(4,n)).toString()):(n=16,i="2.3283064365386962890625e-10"),e.precision+=n,t=As(e,1,t.times(i),new e(1));for(var s=n;s--;){var o=t.times(t);t=o.times(o).minus(o).times(8).plus(1)}return e.precision-=n,t}var De=(function(){function e(r,i,s){var o,c=0,a=r.length;for(r=r.slice();a--;)o=r[a]*i+c,r[a]=o%s|0,c=o/s|0;return c&&r.unshift(c),r}function t(r,i,s,o){var c,a;if(s!=o)a=s>o?1:-1;else for(c=a=0;c<s;c++)if(r[c]!=i[c]){a=r[c]>i[c]?1:-1;break}return a}function n(r,i,s,o){for(var c=0;s--;)r[s]-=c,c=r[s]<i[s]?1:0,r[s]=c*o+r[s]-i[s];for(;!r[0]&&r.length>1;)r.shift()}return function(r,i,s,o,c,a){var u,f,l,p,y,g,w,E,S,_,m,T,I,A,U,M,v,R,V,W,H=r.constructor,$=r.s==i.s?1:-1,N=r.d,K=i.d;if(!N||!N[0]||!K||!K[0])return new H(!r.s||!i.s||(N?K&&N[0]==K[0]:!K)?NaN:N&&N[0]==0||!K?$*0:$/0);for(a?(y=1,f=r.e-i.e):(a=Fn,y=be,f=$t(r.e/y)-$t(i.e/y)),V=K.length,v=N.length,S=new H($),_=S.d=[],l=0;K[l]==(N[l]||0);l++);if(K[l]>(N[l]||0)&&f--,s==null?(A=s=H.precision,o=H.rounding):c?A=s+(r.e-i.e)+1:A=s,A<0)_.push(1),g=!0;else{if(A=A/y+2|0,l=0,V==1){for(p=0,K=K[0],A++;(l<v||p)&&A--;l++)U=p*a+(N[l]||0),_[l]=U/K|0,p=U%K|0;g=p||l<v}else{for(p=a/(K[0]+1)|0,p>1&&(K=e(K,p,a),N=e(N,p,a),V=K.length,v=N.length),M=V,m=N.slice(0,V),T=m.length;T<V;)m[T++]=0;W=K.slice(),W.unshift(0),R=K[0],K[1]>=a/2&&++R;do p=0,u=t(K,m,V,T),u<0?(I=m[0],V!=T&&(I=I*a+(m[1]||0)),p=I/R|0,p>1?(p>=a&&(p=a-1),w=e(K,p,a),E=w.length,T=m.length,u=t(w,m,E,T),u==1&&(p--,n(w,V<E?W:K,E,a))):(p==0&&(u=p=1),w=K.slice()),E=w.length,E<T&&w.unshift(0),n(m,w,T,a),u==-1&&(T=m.length,u=t(K,m,V,T),u<1&&(p++,n(m,V<T?W:K,T,a))),T=m.length):u===0&&(p++,m=[0]),_[l++]=p,u&&m[0]?m[T++]=N[M]||0:(m=[N[M]],T=1);while((M++<v||m[0]!==void 0)&&A--);g=m[0]!==void 0}_[0]||_.shift()}if(y==1)S.e=f,uw=g;else{for(l=1,p=_[0];p>=10;p/=10)l++;S.e=l+f*y-1,we(S,c?s+S.e+1:s,o,g)}return S}})();function we(e,t,n,r){var i,s,o,c,a,u,f,l,p,y=e.constructor;e:if(t!=null){if(l=e.d,!l)return e;for(i=1,c=l[0];c>=10;c/=10)i++;if(s=t-i,s<0)s+=be,o=t,f=l[p=0],a=f/bt(10,i-o-1)%10|0;else if(p=Math.ceil((s+1)/be),c=l.length,p>=c)if(r){for(;c++<=p;)l.push(0);f=a=0,i=1,s%=be,o=s-be+1}else break e;else{for(f=c=l[p],i=1;c>=10;c/=10)i++;s%=be,o=s-be+i,a=o<0?0:f/bt(10,i-o-1)%10|0}if(r=r||t<0||l[p+1]!==void 0||(o<0?f:f%bt(10,i-o-1)),u=n<4?(a||r)&&(n==0||n==(e.s<0?3:2)):a>5||a==5&&(n==4||r||n==6&&(s>0?o>0?f/bt(10,i-o):0:l[p-1])%10&1||n==(e.s<0?8:7)),t<1||!l[0])return l.length=0,u?(t-=e.e+1,l[0]=bt(10,(be-t%be)%be),e.e=-t||0):l[0]=e.e=0,e;if(s==0?(l.length=p,c=1,p--):(l.length=p+1,c=bt(10,be-s),l[p]=o>0?(f/bt(10,i-o)%bt(10,o)|0)*c:0),u)for(;;)if(p==0){for(s=1,o=l[0];o>=10;o/=10)s++;for(o=l[0]+=c,c=1;o>=10;o/=10)c++;s!=c&&(e.e++,l[0]==Fn&&(l[0]=1));break}else{if(l[p]+=c,l[p]!=Fn)break;l[p--]=0,c=1}for(s=l.length;l[--s]===0;)l.pop()}return Te&&(e.e>y.maxE?(e.d=null,e.e=NaN):e.e<y.minE&&(e.e=0,e.d=[0])),e}function Zn(e,t,n){if(!e.isFinite())return ww(e);var r,i=e.e,s=kt(e.d),o=s.length;return t?(n&&(r=n-o)>0?s=s.charAt(0)+"."+s.slice(1)+Yr(r):o>1&&(s=s.charAt(0)+"."+s.slice(1)),s=s+(e.e<0?"e":"e+")+e.e):i<0?(s="0."+Yr(-i-1)+s,n&&(r=n-o)>0&&(s+=Yr(r))):i>=o?(s+=Yr(i+1-o),n&&(r=n-i-1)>0&&(s=s+"."+Yr(r))):((r=i+1)<o&&(s=s.slice(0,r)+"."+s.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(s+="."),s+=Yr(r))),s}function ou(e,t){var n=e[0];for(t*=be;n>=10;n/=10)t++;return t}function Ta(e,t,n){if(t>Vx)throw Te=!0,n&&(e.precision=n),Error(fw);return we(new e(_a),t,1,!0)}function Xn(e,t,n){if(t>Xf)throw Error(fw);return we(new e(Sa),t,n,!0)}function pw(e){var t=e.length-1,n=t*be+1;if(t=e[t],t){for(;t%10==0;t/=10)n--;for(t=e[0];t>=10;t/=10)n++}return n}function Yr(e){for(var t="";e--;)t+="0";return t}function yw(e,t,n,r){var i,s=new e(1),o=Math.ceil(r/be+4);for(Te=!1;;){if(n%2&&(s=s.times(t),Mp(s.d,o)&&(i=!0)),n=$t(n/2),n===0){n=s.d.length-1,i&&s.d[n]===0&&++s.d[n];break}t=t.times(t),Mp(t.d,o)}return Te=!0,s}function Fp(e){return e.d[e.d.length-1]&1}function gw(e,t,n){for(var r,i,s=new e(t[0]),o=0;++o<t.length;){if(i=new e(t[o]),!i.s){s=i;break}r=s.cmp(i),(r===n||r===0&&s.s===n)&&(s=i)}return s}function zf(e,t){var n,r,i,s,o,c,a,u=0,f=0,l=0,p=e.constructor,y=p.rounding,g=p.precision;if(!e.d||!e.d[0]||e.e>17)return new p(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(t==null?(Te=!1,a=g):a=t,c=new p(.03125);e.e>-2;)e=e.times(c),l+=5;for(r=Math.log(bt(2,l))/Math.LN10*2+5|0,a+=r,n=s=o=new p(1),p.precision=a;;){if(s=we(s.times(e),a,1),n=n.times(++f),c=o.plus(De(s,n,a,1)),kt(c.d).slice(0,a)===kt(o.d).slice(0,a)){for(i=l;i--;)o=we(o.times(o),a,1);if(t==null)if(u<3&&Po(o.d,a-r,y,u))p.precision=a+=10,n=s=c=new p(1),f=0,u++;else return we(o,p.precision=g,y,Te=!0);else return p.precision=g,o}o=c}}function Qr(e,t){var n,r,i,s,o,c,a,u,f,l,p,y=1,g=10,w=e,E=w.d,S=w.constructor,_=S.rounding,m=S.precision;if(w.s<0||!E||!E[0]||!w.e&&E[0]==1&&E.length==1)return new S(E&&!E[0]?-1/0:w.s!=1?NaN:E?0:w);if(t==null?(Te=!1,f=m):f=t,S.precision=f+=g,n=kt(E),r=n.charAt(0),Math.abs(s=w.e)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)w=w.times(e),n=kt(w.d),r=n.charAt(0),y++;s=w.e,r>1?(w=new S("0."+n),s++):w=new S(r+"."+n.slice(1))}else return u=Ta(S,f+2,m).times(s+""),w=Qr(new S(r+"."+n.slice(1)),f-g).plus(u),S.precision=m,t==null?we(w,m,_,Te=!0):w;for(l=w,a=o=w=De(w.minus(1),w.plus(1),f,1),p=we(w.times(w),f,1),i=3;;){if(o=we(o.times(p),f,1),u=a.plus(De(o,new S(i),f,1)),kt(u.d).slice(0,f)===kt(a.d).slice(0,f))if(a=a.times(2),s!==0&&(a=a.plus(Ta(S,f+2,m).times(s+""))),a=De(a,new S(y),f,1),t==null)if(Po(a.d,f-g,_,c))S.precision=f+=g,u=o=w=De(l.minus(1),l.plus(1),f,1),p=we(w.times(w),f,1),i=c=1;else return we(a,S.precision=m,_,Te=!0);else return S.precision=m,a;a=u,i+=2}}function ww(e){return String(e.s*e.s/0)}function Kc(e,t){var n,r,i;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;r++);for(i=t.length;t.charCodeAt(i-1)===48;--i);if(t=t.slice(r,i),t){if(i-=r,e.e=n=n-r-1,e.d=[],r=(n+1)%be,n<0&&(r+=be),r<i){for(r&&e.d.push(+t.slice(0,r)),i-=be;r<i;)e.d.push(+t.slice(r,r+=be));t=t.slice(r),r=be-t.length}else r-=i;for(;r--;)t+="0";e.d.push(+t),Te&&(e.e>e.constructor.maxE?(e.d=null,e.e=NaN):e.e<e.constructor.minE&&(e.e=0,e.d=[0]))}else e.e=0,e.d=[0];return e}function $x(e,t){var n,r,i,s,o,c,a,u,f;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),dw.test(t))return Kc(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(Fx.test(t))n=16,t=t.toLowerCase();else if(Hx.test(t))n=2;else if(Mx.test(t))n=8;else throw Error(oi+t);for(s=t.search(/p/i),s>0?(a=+t.slice(s+1),t=t.substring(2,s)):t=t.slice(2),s=t.indexOf("."),o=s>=0,r=e.constructor,o&&(t=t.replace(".",""),c=t.length,s=c-s,i=yw(r,new r(n),s,s*2)),u=$c(t,n,Fn),f=u.length-1,s=f;u[s]===0;--s)u.pop();return s<0?new r(e.s*0):(e.e=ou(u,f),e.d=u,Te=!1,o&&(e=De(e,i,c*4)),a&&(e=e.times(Math.abs(a)<54?bt(2,a):ei.pow(2,a))),Te=!0,e)}function Kx(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:As(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/cu(5,n)),t=As(e,2,t,t);for(var i,s=new e(5),o=new e(16),c=new e(20);n--;)i=t.times(t),t=t.times(s.plus(i.times(o.times(i).minus(c))));return t}function As(e,t,n,r,i){var s,o,c,a,u=e.precision,f=Math.ceil(u/be);for(Te=!1,a=n.times(n),c=new e(r);;){if(o=De(c.times(a),new e(t++*t++),u,1),c=i?r.plus(o):r.minus(o),r=De(o.times(a),new e(t++*t++),u,1),o=c.plus(r),o.d[f]!==void 0){for(s=f;o.d[s]===c.d[s]&&s--;);if(s==-1)break}s=c,c=r,r=o,o=s}return Te=!0,o.d.length=f+1,o}function cu(e,t){for(var n=e;--t;)n*=e;return n}function mw(e,t){var n,r=t.s<0,i=Xn(e,e.precision,1),s=i.times(.5);if(t=t.abs(),t.lte(s))return gr=r?4:1,t;if(n=t.divToInt(i),n.isZero())gr=r?3:2;else{if(t=t.minus(n.times(i)),t.lte(s))return gr=Fp(n)?r?2:3:r?4:1,t;gr=Fp(n)?r?1:4:r?3:2}return t.minus(i).abs()}function th(e,t,n,r){var i,s,o,c,a,u,f,l,p,y=e.constructor,g=n!==void 0;if(g?(fn(n,1,fi),r===void 0?r=y.rounding:fn(r,0,8)):(n=y.precision,r=y.rounding),!e.isFinite())f=ww(e);else{for(f=Zn(e),o=f.indexOf("."),g?(i=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):i=t,o>=0&&(f=f.replace(".",""),p=new y(1),p.e=f.length-o,p.d=$c(Zn(p),10,i),p.e=p.d.length),l=$c(f,10,i),s=a=l.length;l[--a]==0;)l.pop();if(!l[0])f=g?"0p+0":"0";else{if(o<0?s--:(e=new y(e),e.d=l,e.e=s,e=De(e,p,n,r,0,i),l=e.d,s=e.e,u=uw),o=l[n],c=i/2,u=u||l[n+1]!==void 0,u=r<4?(o!==void 0||u)&&(r===0||r===(e.s<0?3:2)):o>c||o===c&&(r===4||u||r===6&&l[n-1]&1||r===(e.s<0?8:7)),l.length=n,u)for(;++l[--n]>i-1;)l[n]=0,n||(++s,l.unshift(1));for(a=l.length;!l[a-1];--a);for(o=0,f="";o<a;o++)f+=Gf.charAt(l[o]);if(g){if(a>1)if(t==16||t==8){for(o=t==16?4:3,--a;a%o;a++)f+="0";for(l=$c(f,i,t),a=l.length;!l[a-1];--a);for(o=1,f="1.";o<a;o++)f+=Gf.charAt(l[o])}else f=f.charAt(0)+"."+f.slice(1);f=f+(s<0?"p":"p+")+s}else if(s<0){for(;++s;)f="0"+f;f="0."+f}else if(++s>a)for(s-=a;s--;)f+="0";else s<a&&(f=f.slice(0,s)+"."+f.slice(s))}f=(t==16?"0x":t==2?"0b":t==8?"0o":"")+f}return e.s<0?"-"+f:f}function Mp(e,t){if(e.length>t)return e.length=t,!0}function jx(e){return new this(e).abs()}function Wx(e){return new this(e).acos()}function Gx(e){return new this(e).acosh()}function Dx(e,t){return new this(e).plus(t)}function Xx(e){return new this(e).asin()}function zx(e){return new this(e).asinh()}function Yx(e){return new this(e).atan()}function Zx(e){return new this(e).atanh()}function Jx(e,t){e=new this(e),t=new this(t);var n,r=this.precision,i=this.rounding,s=r+4;return!e.s||!t.s?n=new this(NaN):!e.d&&!t.d?(n=Xn(this,s,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?Xn(this,r,i):new this(0),n.s=e.s):!e.d||t.isZero()?(n=Xn(this,s,1).times(.5),n.s=e.s):t.s<0?(this.precision=s,this.rounding=1,n=this.atan(De(e,t,s,1)),t=Xn(this,s,1),this.precision=r,this.rounding=i,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(De(e,t,s,1)),n}function Qx(e){return new this(e).cbrt()}function e6(e){return we(e=new this(e),e.e+1,2)}function t6(e,t,n){return new this(e).clamp(t,n)}function n6(e){if(!e||typeof e!="object")throw Error(su+"Object expected");var t,n,r,i=e.defaults===!0,s=["precision",1,fi,"rounding",0,8,"toExpNeg",-as,0,"toExpPos",0,as,"maxE",0,as,"minE",-as,0,"modulo",0,9];for(t=0;t<s.length;t+=3)if(n=s[t],i&&(this[n]=Df[n]),(r=e[n])!==void 0)if($t(r)===r&&r>=s[t+1]&&r<=s[t+2])this[n]=r;else throw Error(oi+n+": "+r);if(n="crypto",i&&(this[n]=Df[n]),(r=e[n])!==void 0)if(r===!0||r===!1||r===0||r===1)if(r)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[n]=!0;else throw Error(lw);else this[n]=!1;else throw Error(oi+n+": "+r);return this}function r6(e){return new this(e).cos()}function i6(e){return new this(e).cosh()}function bw(e){var t,n,r;function i(s){var o,c,a,u=this;if(!(u instanceof i))return new i(s);if(u.constructor=i,qp(s)){u.s=s.s,Te?!s.d||s.e>i.maxE?(u.e=NaN,u.d=null):s.e<i.minE?(u.e=0,u.d=[0]):(u.e=s.e,u.d=s.d.slice()):(u.e=s.e,u.d=s.d?s.d.slice():s.d);return}if(a=typeof s,a==="number"){if(s===0){u.s=1/s<0?-1:1,u.e=0,u.d=[0];return}if(s<0?(s=-s,u.s=-1):u.s=1,s===~~s&&s<1e7){for(o=0,c=s;c>=10;c/=10)o++;Te?o>i.maxE?(u.e=NaN,u.d=null):o<i.minE?(u.e=0,u.d=[0]):(u.e=o,u.d=[s]):(u.e=o,u.d=[s]);return}if(s*0!==0){s||(u.s=NaN),u.e=NaN,u.d=null;return}return Kc(u,s.toString())}if(a==="string")return(c=s.charCodeAt(0))===45?(s=s.slice(1),u.s=-1):(c===43&&(s=s.slice(1)),u.s=1),dw.test(s)?Kc(u,s):$x(u,s);if(a==="bigint")return s<0?(s=-s,u.s=-1):u.s=1,Kc(u,s.toString());throw Error(oi+s)}if(i.prototype=ie,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.EUCLID=9,i.config=i.set=n6,i.clone=bw,i.isDecimal=qp,i.abs=jx,i.acos=Wx,i.acosh=Gx,i.add=Dx,i.asin=Xx,i.asinh=zx,i.atan=Yx,i.atanh=Zx,i.atan2=Jx,i.cbrt=Qx,i.ceil=e6,i.clamp=t6,i.cos=r6,i.cosh=i6,i.div=s6,i.exp=o6,i.floor=c6,i.hypot=a6,i.ln=u6,i.log=f6,i.log10=h6,i.log2=l6,i.max=d6,i.min=p6,i.mod=y6,i.mul=g6,i.pow=w6,i.random=m6,i.round=b6,i.sign=E6,i.sin=_6,i.sinh=S6,i.sqrt=T6,i.sub=x6,i.sum=A6,i.tan=v6,i.tanh=B6,i.trunc=I6,e===void 0&&(e={}),e&&e.defaults!==!0)for(r=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return i.config(e),i}function s6(e,t){return new this(e).div(t)}function o6(e){return new this(e).exp()}function c6(e){return we(e=new this(e),e.e+1,3)}function a6(){var e,t,n=new this(0);for(Te=!1,e=0;e<arguments.length;)if(t=new this(arguments[e++]),t.d)n.d&&(n=n.plus(t.times(t)));else{if(t.s)return Te=!0,new this(1/0);n=t}return Te=!0,n.sqrt()}function qp(e){return e instanceof ei||e&&e.toStringTag===hw||!1}function u6(e){return new this(e).ln()}function f6(e,t){return new this(e).log(t)}function l6(e){return new this(e).log(2)}function h6(e){return new this(e).log(10)}function d6(){return gw(this,arguments,-1)}function p6(){return gw(this,arguments,1)}function y6(e,t){return new this(e).mod(t)}function g6(e,t){return new this(e).mul(t)}function w6(e,t){return new this(e).pow(t)}function m6(e){var t,n,r,i,s=0,o=new this(1),c=[];if(e===void 0?e=this.precision:fn(e,1,fi),r=Math.ceil(e/be),this.crypto)if(crypto.getRandomValues)for(t=crypto.getRandomValues(new Uint32Array(r));s<r;)i=t[s],i>=429e7?t[s]=crypto.getRandomValues(new Uint32Array(1))[0]:c[s++]=i%1e7;else if(crypto.randomBytes){for(t=crypto.randomBytes(r*=4);s<r;)i=t[s]+(t[s+1]<<8)+(t[s+2]<<16)+((t[s+3]&127)<<24),i>=214e7?crypto.randomBytes(4).copy(t,s):(c.push(i%1e7),s+=4);s=r/4}else throw Error(lw);else for(;s<r;)c[s++]=Math.random()*1e7|0;for(r=c[--s],e%=be,r&&e&&(i=bt(10,be-e),c[s]=(r/i|0)*i);c[s]===0;s--)c.pop();if(s<0)n=0,c=[0];else{for(n=-1;c[0]===0;n-=be)c.shift();for(r=1,i=c[0];i>=10;i/=10)r++;r<be&&(n-=be-r)}return o.e=n,o.d=c,o}function b6(e){return we(e=new this(e),e.e+1,this.rounding)}function E6(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function _6(e){return new this(e).sin()}function S6(e){return new this(e).sinh()}function T6(e){return new this(e).sqrt()}function x6(e,t){return new this(e).sub(t)}function A6(){var e=0,t=arguments,n=new this(t[e]);for(Te=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return Te=!0,we(n,this.precision,this.rounding)}function v6(e){return new this(e).tan()}function B6(e){return new this(e).tanh()}function I6(e){return we(e=new this(e),e.e+1,1)}ie[Symbol.for("nodejs.util.inspect.custom")]=ie.toString;ie[Symbol.toStringTag]="Decimal";var ei=ie.constructor=bw(Df);_a=new ei(_a);Sa=new ei(Sa);const O6=({IDL:e})=>{const t=e.Record({exchange_id:e.Text,reason:e.Text}),n=e.Variant({Ok:e.Null,Err:e.Text}),r=e.Variant({P2WPKH:e.Null,OpReturn:e.Nat64,P2SH:e.Null,P2TR:e.Null}),i=e.Record({input_types:e.Vec(r),pool_address:e.Vec(e.Text),output_types:e.Vec(r)}),s=e.Variant({Ok:e.Nat64,Err:e.Text}),o=e.Record({user_id:e.Principal}),c=e.Record({canister_version:e.Opt(e.Nat64),canister_id:e.Principal}),a=e.Variant({from_user:o,from_canister:c}),u=e.Record({controllers:e.Vec(e.Principal)}),f=e.Variant({reinstall:e.Null,upgrade:e.Null,install:e.Null}),l=e.Record({mode:f,module_hash:e.Vec(e.Nat8)}),p=e.Record({canister_version:e.Nat64,taken_at_timestamp:e.Nat64,snapshot_id:e.Vec(e.Nat8)}),y=e.Variant({creation:u,code_deployment:l,load_snapshot:p,controllers_change:u,code_uninstall:e.Null}),g=e.Record({timestamp_nanos:e.Nat64,canister_version:e.Nat64,origin:a,details:y}),w=e.Record({controllers:e.Vec(e.Principal),module_hash:e.Opt(e.Vec(e.Nat8)),recent_changes:e.Vec(g),total_num_changes:e.Nat64}),E=e.Variant({Ok:w,Err:e.Text}),S=e.Record({exchange_id:e.Text,pool_address:e.Text,pool_key:e.Text}),_=e.Variant({All:e.Null,ByTxid:e.Text,ByStatusCode:e.Text,ByAddress:e.Text,BySecondsPassed:e.Nat64}),m=e.Variant({Ok:e.Text,Err:e.Text}),T=e.Record({result:m,exchange_id:e.Text,maybe_return_time:e.Opt(e.Text),calling_method:e.Text,calling_args:e.Text,pool_address:e.Text,calling_time:e.Text}),I=e.Record({rollback_results:e.Vec(e.Text),invoke_args:e.Text,invoke_time:e.Text,finalized_time:e.Opt(e.Text),confirmed_time:e.Opt(e.Text),execution_steps:e.Vec(T),processing_result:m,broadcasted_time:e.Opt(e.Text)}),A=e.Record({block_hash:e.Text,block_height:e.Nat32}),U=e.Record({processing_results:e.Vec(e.Text),block_basic:A,txids:e.Vec(e.Text),block_time:e.Text,received_time:e.Text}),M=e.Variant({Abandoned:e.Record({reason:e.Text}),Active:e.Null,Halted:e.Record({reason:e.Text})}),v=e.Record({status:M,exchange_id:e.Text,canister_id:e.Principal,utxo_proof_enabled:e.Bool,client_canisters:e.Vec(e.Principal)}),R=e.Record({rollback_results:e.Vec(e.Text),txid:e.Text,received_time:e.Text,reason:e.Text}),V=e.Variant({mainnet:e.Null,regtest:e.Null,testnet:e.Null}),W=e.Record({min_seconds_of_unconfirmed_tx_in_pool_for_raising_fee_rate:e.Nat32,exchange_registry_principal:e.Principal,max_input_count_of_psbt:e.Nat32,min_tx_confirmations:e.Nat32,mempool_connector_principal:e.Principal,max_unconfirmed_tx_count_in_pool:e.Nat32,min_btc_amount_for_utxo:e.Nat64,rune_indexer_principal:e.Principal,max_intentions_per_invoke:e.Nat32,mempool_connector_public_key:e.Text,max_received_blocks_count:e.Nat32,min_unconfirmed_tx_count_in_pool_for_raising_fee_rate:e.Nat32,bitcoin_network:V}),H=e.Record({low:e.Nat64,high:e.Nat64,update_time:e.Text,medium:e.Nat64}),$=e.Record({last_block:e.Opt(A),pending_tx_count:e.Nat64,mempool_tx_fee_rate:H,invoke_paused:e.Bool,concurrent_invoke_status:e.Text,last_block_time:e.Opt(e.Tuple(e.Nat64,e.Text)),failed_new_block_height:e.Opt(e.Tuple(e.Nat32,e.Text))}),N=e.Variant({Error:e.Null,AvailableUnconfirmed:e.Null,InvalidTxid:e.Null,InvalidVout:e.Null,SpentInMempool:e.Null,SpentOnChain:e.Null,AvailableConfirmed:e.Null}),K=e.Record({status:N,value:e.Opt(e.Text),txid:e.Text,vout:e.Nat32,ancestors:e.Opt(e.Nat32),address:e.Opt(e.Text)}),F=e.Record({id:e.Text,value:e.Nat}),x=e.Record({coins:e.Vec(F),sats:e.Nat64,txid:e.Text,vout:e.Nat32}),O=e.Record({status:e.Opt(K),coins:e.Vec(F),utxo:x,is_signed:e.Bool,owner_pubkey:e.Opt(e.Text),owner_address:e.Text}),q=e.Record({coins_in_inputs:e.Vec(O),txid:e.Text,signed_address_coins:e.Vec(e.Tuple(e.Text,e.Vec(F))),address_coins:e.Vec(e.Tuple(e.Text,e.Vec(F)))}),P=e.Record({is_op_return:e.Bool,utxo:x,owner_address:e.Opt(e.Text)}),L=e.Record({burned_coins:e.Vec(F),coins_in_outputs:e.Vec(P),address_coins:e.Vec(e.Tuple(e.Text,e.Vec(F)))}),G=e.Record({coin:F,from:e.Text}),X=e.Record({to:e.Text,coin:F}),Y=e.Record({input_coins:e.Vec(G),output_coins:e.Vec(X),action:e.Text,exchange_id:e.Text,pool_utxo_spent:e.Vec(e.Text),action_params:e.Text,nonce:e.Nat64,pool_address:e.Text,pool_utxo_received:e.Vec(x)}),oe=e.Record({tx_fee_in_sats:e.Nat64,initiator_address:e.Text,intentions:e.Vec(Y)}),ae=e.Record({applied_fee_rate:e.Nat64,pool_addresses:e.Vec(e.Text),coins_in_inputs:q,txid:e.Text,estimated_min_tx_fee:e.Nat64,actual_tx_fee:e.Nat64,coins_in_outputs:L,tx_vsize:e.Nat64,intention_set:oe,user_coins_in_inputs:e.Vec(F),initially_signed_addresses:e.Vec(e.Text)}),ee=e.Variant({Confirmed:e.Nat32,Rejected:e.Text,Pending:e.Null}),Z=e.Record({status:e.Opt(ee),invoke_log:I,included_block:e.Opt(A),sent_tx_hex:e.Text}),ce=e.Variant({Failed:I,NotFound:e.Null,Succeeded:Z}),ge=e.Record({maybe_rune:e.Opt(F),value:e.Nat64,script_pubkey_hex:e.Text,outpoint:e.Text}),pe=e.Record({client_info:e.Opt(e.Text),intention_set:oe,initiator_utxo_proof:e.Vec(e.Nat8),psbt_hex:e.Text}),J=e.Record({block_hash:e.Text,block_timestamp:e.Nat64,tx_ids:e.Vec(e.Text),block_height:e.Nat32}),fe=e.Variant({Ok:e.Vec(e.Text),Err:e.Text}),Se=e.Record({exchange_canister:e.Principal,exchange_id:e.Text,utxo_proof_enabled:e.Bool,client_canisters:e.Vec(e.Principal)}),Ce=e.Record({txid:e.Text,reason_code:e.Text,reason:e.Text}),Ze=e.Record({txid:e.Text,timestamp:e.Nat64,block:A}),st=e.Record({low:e.Nat64,high:e.Nat64,medium:e.Nat64});return e.Service({abandon_exchange:e.Func([t],[n],[]),clear_exchange_pools:e.Func([],[n],[]),clear_failed_invoke_logs:e.Func([e.Opt(e.Nat64),e.Vec(e.Text)],[n],[]),clear_last_block:e.Func([],[n],[]),clear_rejected_txs:e.Func([],[n],[]),clear_txs_with_min_confirmations:e.Func([e.Nat32],[n],[]),delete_tx_detail:e.Func([e.Text],[n],[]),delete_used_outpoints:e.Func([e.Text],[n],[]),estimate_min_tx_fee:e.Func([i],[s],["query"]),get_canister_info:e.Func([e.Nat64],[E],[]),get_exchange_pools:e.Func([e.Opt(e.Text)],[e.Vec(S)],["query"]),get_failed_invoke_logs:e.Func([_],[e.Vec(e.Tuple(e.Text,I))],["query"]),get_last_sent_txs:e.Func([],[e.Vec(e.Tuple(e.Text,e.Text,e.Opt(e.Nat32)))],["query"]),get_received_blocks:e.Func([e.Opt(e.Bool)],[e.Vec(U)],["query"]),get_registered_exchanges:e.Func([e.Opt(M)],[e.Vec(v)],["query"]),get_rejected_txs:e.Func([],[e.Vec(R)],["query"]),get_settings:e.Func([],[W],["query"]),get_status:e.Func([],[$],["query"]),get_tx_execution_context_view:e.Func([e.Text],[e.Opt(ae)],["query"]),get_tx_execution_result:e.Func([e.Text],[ce],["query"]),get_tx_for_outpoint:e.Func([e.Text],[e.Opt(Z)],["query"]),get_tx_queue_of_pool:e.Func([e.Text],[e.Vec(e.Tuple(e.Text,e.Opt(e.Nat32)))],["query"]),get_tx_sent:e.Func([e.Text],[e.Opt(Z)],["query"]),get_used_outpoints:e.Func([e.Opt(e.Text)],[e.Vec(e.Tuple(e.Text,e.Text))],["query"]),get_zero_confirmed_tx_count_of_pool:e.Func([e.Text],[e.Nat32],["query"]),get_zero_confirmed_txs:e.Func([e.Opt(e.Text)],[e.Vec(e.Text)],["query"]),get_zero_confirmed_utxos_of_address:e.Func([e.Text],[e.Vec(ge)],["query"]),init_status_code_message:e.Func([],[n],[]),inspect_status_code:e.Func([e.Text],[e.Text],["query"]),invoke:e.Func([pe],[m],[]),new_block_detected:e.Func([J],[n],[]),notify_exchange_for_blocks_from_height:e.Func([e.Text,e.Nat32],[fe],[]),notify_exchanges_for_block:e.Func([e.Vec(e.Text),A,e.Nat64,e.Vec(e.Text)],[fe],[]),pause_invoke:e.Func([],[n],[]),reapply_tx:e.Func([e.Text],[n],[]),register_exchange:e.Func([Se],[n],[]),reject_tx:e.Func([Ce],[n],[]),resume_invoke:e.Func([],[n],[]),rollback_tx:e.Func([e.Text],[fe],[]),save_included_block_for_tx:e.Func([Ze],[n],[]),set_bitcoin_network:e.Func([V],[n],[]),set_exchange_registry_principal:e.Func([e.Principal],[n],[]),set_max_input_count_of_psbt:e.Func([e.Nat32],[n],[]),set_max_intentions_per_invoke:e.Func([e.Nat32],[n],[]),set_max_received_blocks_count:e.Func([e.Nat32],[n],[]),set_max_unconfirmed_tx_count_in_pool:e.Func([e.Nat32],[n],[]),set_mempool_connector_principal:e.Func([e.Principal],[n],[]),set_mempool_connector_public_key:e.Func([e.Text],[n],[]),set_min_btc_amount_for_utxo:e.Func([e.Nat64],[n],[]),set_min_tx_confirmations:e.Func([e.Nat32],[n],[]),set_rune_indexer_principal:e.Func([e.Principal],[n],[]),set_tx_fee_per_vbyte:e.Func([st],[n],[]),unhalt_exchange:e.Func([e.Text],[n],[]),version:e.Func([],[e.Text],["query"])})};class P6{xverse;config;exchange;orchestrator;constructor(t){this.config=t;const n=t.network===Yo.Testnet,r=n?"https://api-testnet4.secretkeylabs.io":"https://api.secretkeylabs.io";this.xverse=new XS({baseUrl:r,apiKey:t.xverseApiKey});const i="https://icp0.io";this.exchange=ma.createActor(t.exchangeIdlFactory,{agent:yr.createSync({host:i,retryTimes:50,verifyQuerySignatures:!1}),canisterId:t.exchangeCanisterId}),this.orchestrator=ma.createActor(O6,{agent:yr.createSync({host:i,retryTimes:50,verifyQuerySignatures:!1}),canisterId:n?Ux:Nx})}async filterSpentUtxos(t,n){const r=await this.orchestrator.get_used_outpoints([t]);return n.filter(({txid:i,vout:s})=>r.findIndex(([o])=>`${i}:${s}`===o)<0)}async getPendingBtcUtxos(t){const n=await this.orchestrator.get_zero_confirmed_utxos_of_address(t),r=Zr(t);return n.filter(({maybe_rune:i})=>!i.length).map(({value:i,script_pubkey_hex:s,outpoint:o})=>{const[c,a]=o.split(":");return{txid:c,vout:Number(a),satoshis:i.toString(),scriptPk:s,addressType:r,address:t,runes:[]}})}async getPendingRuneUtxos(t,n){const r=await this.orchestrator.get_zero_confirmed_utxos_of_address(t),i=Zr(t);return r.filter(({maybe_rune:s})=>s.length).map(({value:s,script_pubkey_hex:o,outpoint:c,maybe_rune:a})=>{const[u,f]=c.split(":"),l=a[0];return{txid:u,vout:Number(f),satoshis:s.toString(),scriptPk:o,addressType:i,address:t,runes:l?[{id:l.id,amount:l.value.toString()}]:[],pubkey:n}})}async getBtcUtxos(t){let n=0;const r=60,i=[],s=await this.getPendingBtcUtxos(t);let o=!0;for(;o;){const u=await this.xverse.utxosByAddress(t,n,r);i.push(...u.items),o=u.hasMore,n+=r}const c=Ea(t,this.config.network),a=i.map(({txid:u,vout:f,value:l})=>({txid:u,vout:f,address:t,runes:[],satoshis:l.toString(),scriptPk:ba(c)})).filter(u=>Number(u.satoshis)>546);return this.filterSpentUtxos(t,a.concat(s))}async getRuneUtxos(t,n,r){let i=0;const s=60,o=[],c=await this.getPendingRuneUtxos(t,r);let a=!0;for(;a;){const l=await this.xverse.runeUtxosByAddress(t,n,i,s);o.push(...l.items),a=l.hasMore,i+=s}const u=Ea(t,this.config.network),f=o.map(({txid:l,vout:p,runes:y,amount:g})=>({txid:l,vout:p,address:t,runes:y.map(({runeId:w,amount:E})=>{const S=new ei(E).toFixed(0);return{id:w,amount:S}}),satoshis:g.toString(),scriptPk:ba(u),pubkey:r}));return this.filterSpentUtxos(t,f.concat(c))}async getBtcBalance(t){const r=(await this.getBtcUtxos(t)).reduce((i,s)=>i+BigInt(s.satoshis),BigInt(0));return new ei(r.toString()).div(1e8).toNumber()}async getRuneBalance(t,n,r){const i=await this.getRuneUtxos(t,n,r);if(!i)return;let s=new ei(0);for(const o of i)s=s.add(new ei(o.runes.find(c=>c.id===n)?.amount??0));return s.toNumber()}async getPoolList(){try{return await this.exchange.get_pool_list()??[]}catch(t){throw console.error("get pool list failed:",t),t}}async getPoolInfo(t){try{const n=await this.exchange.get_pool_info({pool_address:t});if(n.length===0)throw new Error("Pool not found");return n[0]}catch(n){throw console.error("get pool data failed:",n),n}}async createTransaction({address:t,paymentAddress:n,publicKey:r,paymentPublicKey:i,feeRate:s,mergeSelfRuneBtcOutputs:o,clientInfo:c,manualBuild:a}){return new Jr({network:this.config.network,exchangeId:this.config.exchangeId,address:t,paymentAddress:n,publicKey:r,paymentPublicKey:i,feeRate:s,mergeSelfRuneBtcOutputs:o,clientInfo:c,manualBuild:a},this)}async getRecommendedFeeRate(){const t=await this.orchestrator.get_status();return{min:Number(t.mempool_tx_fee_rate.medium),max:Number(t.mempool_tx_fee_rate.medium)*3}}}exports.Network=Yo;exports.ReeClient=P6;exports.Transaction=Jr;exports.utils=kx;
package/dist/index.d.ts CHANGED
@@ -206,10 +206,11 @@ export declare class ReeClient {
206
206
  * @param params.involvedRuneId - Optional rune ID for rune swaps
207
207
  * @returns Transaction instance
208
208
  */
209
- createTransaction({ address, paymentAddress, publicKey, feeRate, mergeSelfRuneBtcOutputs, clientInfo, manualBuild, }: {
209
+ createTransaction({ address, paymentAddress, publicKey, paymentPublicKey, feeRate, mergeSelfRuneBtcOutputs, clientInfo, manualBuild, }: {
210
210
  address: string;
211
211
  paymentAddress: string;
212
212
  publicKey?: string;
213
+ paymentPublicKey?: string;
213
214
  feeRate?: number;
214
215
  mergeSelfRuneBtcOutputs?: boolean;
215
216
  clientInfo?: string;
@@ -456,6 +457,7 @@ export declare interface TransactionConfig {
456
457
  address: string;
457
458
  paymentAddress: string;
458
459
  publicKey?: string;
460
+ paymentPublicKey?: string;
459
461
  clientInfo?: string;
460
462
  /** Optional manual fee rate in satoshis per virtual byte */
461
463
  feeRate?: number;
package/dist/index.es.js CHANGED
@@ -28304,15 +28304,16 @@ class xi {
28304
28304
  const s = this.psbt.__CACHE.__TX.clone(), o = [];
28305
28305
  for (let a = 0; a < this.inputUtxos.length; a++) {
28306
28306
  const u = this.inputUtxos[a], f = u.address;
28307
- if (f !== this.config.paymentAddress || f !== this.config.address)
28307
+ if (f !== this.config.paymentAddress && f !== this.config.address)
28308
28308
  continue;
28309
- const l = this.psbt.data.inputs[a].redeemScript, p = Zr(f);
28310
- if (o.push({
28309
+ const l = this.psbt.data.inputs[a]?.redeemScript, p = Zr(f);
28310
+ let y = u.pubkey;
28311
+ if (!y && f === this.config.paymentAddress && (y = this.config.paymentPublicKey), !y && f === this.config.address && (y = this.config.publicKey), o.push({
28311
28312
  index: a,
28312
- ...p === Dt.P2TR ? { address: f, disableTweakSigner: !1 } : { publicKey: u.pubkey, disableTweakSigner: !0 }
28313
+ ...p === Dt.P2TR ? { address: f, disableTweakSigner: !1 } : { publicKey: y, disableTweakSigner: !0 }
28313
28314
  }), l && p === Dt.P2SH_P2WPKH) {
28314
- const y = Zt([l]);
28315
- s.setInputScript(a, y);
28315
+ const g = Zt([l]);
28316
+ s.setInputScript(a, g);
28316
28317
  }
28317
28318
  }
28318
28319
  const c = s.getId();
@@ -30076,10 +30077,11 @@ class Z6 {
30076
30077
  address: t,
30077
30078
  paymentAddress: n,
30078
30079
  publicKey: r,
30079
- feeRate: i,
30080
- mergeSelfRuneBtcOutputs: s,
30081
- clientInfo: o,
30082
- manualBuild: c
30080
+ paymentPublicKey: i,
30081
+ feeRate: s,
30082
+ mergeSelfRuneBtcOutputs: o,
30083
+ clientInfo: c,
30084
+ manualBuild: a
30083
30085
  }) {
30084
30086
  return new xi(
30085
30087
  {
@@ -30088,10 +30090,11 @@ class Z6 {
30088
30090
  address: t,
30089
30091
  paymentAddress: n,
30090
30092
  publicKey: r,
30091
- feeRate: i,
30092
- mergeSelfRuneBtcOutputs: s,
30093
- clientInfo: o,
30094
- manualBuild: c
30093
+ paymentPublicKey: i,
30094
+ feeRate: s,
30095
+ mergeSelfRuneBtcOutputs: o,
30096
+ clientInfo: c,
30097
+ manualBuild: a
30095
30098
  },
30096
30099
  this
30097
30100
  );
package/dist/react.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("react/jsx-runtime"),e=require("react"),v=require("./index.cjs.js"),E=e.createContext(null);function w({children:t,config:o}){if(!o)throw new Error("ReeProvider: config is required");if(!o.network)throw new Error("ReeProvider: config.network is required");if(!o.xverseApiKey)throw new Error("ReeProvider: config.xverseApiKey is required");if(!o.exchangeIdlFactory)throw new Error("ReeProvider: config.exchangeIdlFactory is required");if(!o.exchangeCanisterId)throw new Error("ReeProvider: config.exchangeCanisterId is required");const[r,i]=e.useState({address:"",paymentAddress:"",publicKey:"",paymentPublicKey:""}),s=e.useCallback(a=>{i(d=>({...d,...a}))},[]),n=e.useMemo(()=>new v.ReeClient(o),[o]),f=e.useCallback(async a=>{if(!n)throw new Error("Client not available");if(!r.address||!r.paymentAddress)throw new Error("Wallet not connected");return n.createTransaction({address:r.address,paymentAddress:r.paymentAddress,feeRate:a?.feeRate,publicKey:r.publicKey,mergeSelfRuneBtcOutputs:a?.mergeSelfRuneBtcOutputs,clientInfo:a?.clientInfo,manualBuild:a?.manualBuild})},[n,r]),u=e.useMemo(()=>({client:n,...r,exchange:n.exchange,updateWallet:s,createTransaction:f}),[n,r,s,f]);return m.jsx(E.Provider,{value:u,children:t})}function R(){const t=e.useContext(E);if(!t)throw new Error("useRee must be used within ReeProvider");return t}function x(t={}){const{refreshInterval:o=0,autoRefresh:r=!0}=t,{client:i,paymentAddress:s}=R(),[n,f]=e.useState(null),[u,a]=e.useState(!1),[d,h]=e.useState(null),l=e.useCallback(async()=>{if(!s){f(null),h("Payment address not set");return}a(!0),h(null);try{const c=await i.getBtcBalance(s);f(c)}catch(c){h(c instanceof Error?c.message:"Failed to fetch BTC balance"),f(null)}finally{a(!1)}},[i,s]);return e.useEffect(()=>{r&&l()},[s,l,r]),e.useEffect(()=>{if(o>0){const c=setInterval(l,o);return()=>clearInterval(c)}},[o,s,l]),{balance:n,loading:u,error:d,refetch:l}}function S(t,o={}){const{refreshInterval:r=0,autoRefresh:i=!0}=o,{client:s,address:n,publicKey:f}=R(),[u,a]=e.useState(null),[d,h]=e.useState(!1),[l,c]=e.useState(null),y=e.useCallback(async()=>{if(!n){a(null),c("Address not set");return}if(!t){a(null),c("Rune ID is required");return}h(!0),c(null);try{const g=await s.getRuneBalance(n,t,f);a(g??null)}catch(g){c(g instanceof Error?g.message:"Failed to fetch rune balance"),a(null)}finally{h(!1)}},[s,n,t]);return e.useEffect(()=>{i&&t&&y()},[n,t,y,i]),e.useEffect(()=>{if(r>0&&t){const g=setInterval(y,r);return()=>clearInterval(g)}},[r,n,t,y]),{balance:u,loading:d,error:l,refetch:y}}function b(t={}){const{refreshInterval:o=0,autoRefresh:r=!0}=t,{client:i,paymentAddress:s}=R(),[n,f]=e.useState([]),[u,a]=e.useState(!1),[d,h]=e.useState(null),l=e.useCallback(async()=>{if(!s){f([]),h("Payment address not set");return}a(!0),h(null);try{const c=await i.getBtcUtxos(s);f(c)}catch(c){h(c instanceof Error?c.message:"Failed to fetch BTC UTXOs"),f([])}finally{a(!1)}},[i,s]);return e.useEffect(()=>{r&&s&&l()},[s,l,r]),e.useEffect(()=>{if(o>0&&s){const c=setInterval(l,o);return()=>clearInterval(c)}},[o,s,l]),{utxos:n,loading:u,error:d,refetch:l}}function B(t,o={}){const{refreshInterval:r=0,autoRefresh:i=!0}=o,{client:s,address:n}=R(),[f,u]=e.useState([]),[a,d]=e.useState(!1),[h,l]=e.useState(null),c=e.useCallback(async()=>{if(!n){u([]),l("Address not set");return}if(!t){u([]),l("Rune ID is required");return}d(!0),l(null);try{const y=await s.getRuneUtxos(n,t);u(y)}catch(y){l(y instanceof Error?y.message:"Failed to fetch rune UTXOs"),u([])}finally{d(!1)}},[s,n,t]);return e.useEffect(()=>{i&&n&&t&&c()},[n,t,c,i]),e.useEffect(()=>{if(r>0&&n&&t){const y=setInterval(c,r);return()=>clearInterval(y)}},[r,n,t,c]),{utxos:f,loading:a,error:h,refetch:c}}function P(){const{client:t}=R(),[o,r]=e.useState([]),[i,s]=e.useState(!1),[n,f]=e.useState(null),u=e.useCallback(async()=>{s(!0),f(null);try{const a=await t.getPoolList();r(a)}catch(a){f(a instanceof Error?a.message:"Failed to fetch pool list"),r([])}finally{s(!1)}},[t]);return e.useEffect(()=>{u()},[u]),{pools:o,loading:i,error:n,refetch:u}}function C(t){const{client:o}=R(),[r,i]=e.useState(null),[s,n]=e.useState(!1),[f,u]=e.useState(null),a=e.useCallback(async()=>{if(!t){i(null),u("Pool address is required");return}n(!0),u(null);try{const d=await o.getPoolInfo(t);i(d)}catch(d){u(d instanceof Error?d.message:"Failed to fetch pool info"),i(null)}finally{n(!1)}},[o,t]);return e.useEffect(()=>{a()},[t]),{poolInfo:r,loading:s,error:f,refetch:a}}function I(t={}){const{refreshInterval:o=0,autoRefresh:r=!0}=t,{client:i}=R(),[s,n]=e.useState(null),[f,u]=e.useState(!1),[a,d]=e.useState(null),h=e.useCallback(async()=>{u(!0),d(null);try{const l=await i.getRecommendedFeeRate();n(l)}catch(l){d(l instanceof Error?l.message:"Failed to fetch recommended fee rate"),n(null)}finally{u(!1)}},[i]);return e.useEffect(()=>{r&&h()},[r,h]),e.useEffect(()=>{if(o>0){const l=setInterval(h,o);return()=>clearInterval(l)}},[o,h]),{feeRate:s,loading:f,error:a,refetch:h}}exports.Network=v.Network;exports.utils=v.utils;exports.ReeProvider=w;exports.useBtcBalance=x;exports.useBtcUtxos=b;exports.usePoolInfo=C;exports.usePoolList=P;exports.useRecommendedFeeRate=I;exports.useRee=R;exports.useRuneBalance=S;exports.useRuneUtxos=B;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("react/jsx-runtime"),e=require("react"),m=require("./index.cjs.js"),v=e.createContext(null);function w({children:t,config:o}){if(!o)throw new Error("ReeProvider: config is required");if(!o.network)throw new Error("ReeProvider: config.network is required");if(!o.xverseApiKey)throw new Error("ReeProvider: config.xverseApiKey is required");if(!o.exchangeIdlFactory)throw new Error("ReeProvider: config.exchangeIdlFactory is required");if(!o.exchangeCanisterId)throw new Error("ReeProvider: config.exchangeCanisterId is required");const[r,i]=e.useState({address:"",paymentAddress:"",publicKey:"",paymentPublicKey:""}),s=e.useCallback(a=>{i(d=>({...d,...a}))},[]),n=e.useMemo(()=>new m.ReeClient(o),[o]),f=e.useCallback(async a=>{if(!n)throw new Error("Client not available");if(!r.address||!r.paymentAddress)throw new Error("Wallet not connected");return n.createTransaction({address:r.address,paymentAddress:r.paymentAddress,feeRate:a?.feeRate,publicKey:r.publicKey,paymentPublicKey:r.paymentPublicKey,mergeSelfRuneBtcOutputs:a?.mergeSelfRuneBtcOutputs,clientInfo:a?.clientInfo,manualBuild:a?.manualBuild})},[n,r]),u=e.useMemo(()=>({client:n,...r,exchange:n.exchange,updateWallet:s,createTransaction:f}),[n,r,s,f]);return E.jsx(v.Provider,{value:u,children:t})}function R(){const t=e.useContext(v);if(!t)throw new Error("useRee must be used within ReeProvider");return t}function x(t={}){const{refreshInterval:o=0,autoRefresh:r=!0}=t,{client:i,paymentAddress:s}=R(),[n,f]=e.useState(null),[u,a]=e.useState(!1),[d,h]=e.useState(null),l=e.useCallback(async()=>{if(!s){f(null),h("Payment address not set");return}a(!0),h(null);try{const c=await i.getBtcBalance(s);f(c)}catch(c){h(c instanceof Error?c.message:"Failed to fetch BTC balance"),f(null)}finally{a(!1)}},[i,s]);return e.useEffect(()=>{r&&l()},[s,l,r]),e.useEffect(()=>{if(o>0){const c=setInterval(l,o);return()=>clearInterval(c)}},[o,s,l]),{balance:n,loading:u,error:d,refetch:l}}function b(t,o={}){const{refreshInterval:r=0,autoRefresh:i=!0}=o,{client:s,address:n,publicKey:f}=R(),[u,a]=e.useState(null),[d,h]=e.useState(!1),[l,c]=e.useState(null),y=e.useCallback(async()=>{if(!n){a(null),c("Address not set");return}if(!t){a(null),c("Rune ID is required");return}h(!0),c(null);try{const g=await s.getRuneBalance(n,t,f);a(g??null)}catch(g){c(g instanceof Error?g.message:"Failed to fetch rune balance"),a(null)}finally{h(!1)}},[s,n,t]);return e.useEffect(()=>{i&&t&&y()},[n,t,y,i]),e.useEffect(()=>{if(r>0&&t){const g=setInterval(y,r);return()=>clearInterval(g)}},[r,n,t,y]),{balance:u,loading:d,error:l,refetch:y}}function P(t={}){const{refreshInterval:o=0,autoRefresh:r=!0}=t,{client:i,paymentAddress:s}=R(),[n,f]=e.useState([]),[u,a]=e.useState(!1),[d,h]=e.useState(null),l=e.useCallback(async()=>{if(!s){f([]),h("Payment address not set");return}a(!0),h(null);try{const c=await i.getBtcUtxos(s);f(c)}catch(c){h(c instanceof Error?c.message:"Failed to fetch BTC UTXOs"),f([])}finally{a(!1)}},[i,s]);return e.useEffect(()=>{r&&s&&l()},[s,l,r]),e.useEffect(()=>{if(o>0&&s){const c=setInterval(l,o);return()=>clearInterval(c)}},[o,s,l]),{utxos:n,loading:u,error:d,refetch:l}}function S(t,o={}){const{refreshInterval:r=0,autoRefresh:i=!0}=o,{client:s,address:n}=R(),[f,u]=e.useState([]),[a,d]=e.useState(!1),[h,l]=e.useState(null),c=e.useCallback(async()=>{if(!n){u([]),l("Address not set");return}if(!t){u([]),l("Rune ID is required");return}d(!0),l(null);try{const y=await s.getRuneUtxos(n,t);u(y)}catch(y){l(y instanceof Error?y.message:"Failed to fetch rune UTXOs"),u([])}finally{d(!1)}},[s,n,t]);return e.useEffect(()=>{i&&n&&t&&c()},[n,t,c,i]),e.useEffect(()=>{if(r>0&&n&&t){const y=setInterval(c,r);return()=>clearInterval(y)}},[r,n,t,c]),{utxos:f,loading:a,error:h,refetch:c}}function B(){const{client:t}=R(),[o,r]=e.useState([]),[i,s]=e.useState(!1),[n,f]=e.useState(null),u=e.useCallback(async()=>{s(!0),f(null);try{const a=await t.getPoolList();r(a)}catch(a){f(a instanceof Error?a.message:"Failed to fetch pool list"),r([])}finally{s(!1)}},[t]);return e.useEffect(()=>{u()},[u]),{pools:o,loading:i,error:n,refetch:u}}function p(t){const{client:o}=R(),[r,i]=e.useState(null),[s,n]=e.useState(!1),[f,u]=e.useState(null),a=e.useCallback(async()=>{if(!t){i(null),u("Pool address is required");return}n(!0),u(null);try{const d=await o.getPoolInfo(t);i(d)}catch(d){u(d instanceof Error?d.message:"Failed to fetch pool info"),i(null)}finally{n(!1)}},[o,t]);return e.useEffect(()=>{a()},[t]),{poolInfo:r,loading:s,error:f,refetch:a}}function C(t={}){const{refreshInterval:o=0,autoRefresh:r=!0}=t,{client:i}=R(),[s,n]=e.useState(null),[f,u]=e.useState(!1),[a,d]=e.useState(null),h=e.useCallback(async()=>{u(!0),d(null);try{const l=await i.getRecommendedFeeRate();n(l)}catch(l){d(l instanceof Error?l.message:"Failed to fetch recommended fee rate"),n(null)}finally{u(!1)}},[i]);return e.useEffect(()=>{r&&h()},[r,h]),e.useEffect(()=>{if(o>0){const l=setInterval(h,o);return()=>clearInterval(l)}},[o,h]),{feeRate:s,loading:f,error:a,refetch:h}}exports.Network=m.Network;exports.utils=m.utils;exports.ReeProvider=w;exports.useBtcBalance=x;exports.useBtcUtxos=P;exports.usePoolInfo=p;exports.usePoolList=B;exports.useRecommendedFeeRate=C;exports.useRee=R;exports.useRuneBalance=b;exports.useRuneUtxos=S;
package/dist/react.d.ts CHANGED
@@ -208,10 +208,11 @@ declare class ReeClient {
208
208
  * @param params.involvedRuneId - Optional rune ID for rune swaps
209
209
  * @returns Transaction instance
210
210
  */
211
- createTransaction({ address, paymentAddress, publicKey, feeRate, mergeSelfRuneBtcOutputs, clientInfo, manualBuild, }: {
211
+ createTransaction({ address, paymentAddress, publicKey, paymentPublicKey, feeRate, mergeSelfRuneBtcOutputs, clientInfo, manualBuild, }: {
212
212
  address: string;
213
213
  paymentAddress: string;
214
214
  publicKey?: string;
215
+ paymentPublicKey?: string;
215
216
  feeRate?: number;
216
217
  mergeSelfRuneBtcOutputs?: boolean;
217
218
  clientInfo?: string;
@@ -485,6 +486,7 @@ declare interface TransactionConfig {
485
486
  address: string;
486
487
  paymentAddress: string;
487
488
  publicKey?: string;
489
+ paymentPublicKey?: string;
488
490
  clientInfo?: string;
489
491
  /** Optional manual fee rate in satoshis per virtual byte */
490
492
  feeRate?: number;
package/dist/react.es.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { jsx as E } from "react/jsx-runtime";
2
- import { createContext as p, useState as u, useCallback as m, useMemo as w, useContext as B, useEffect as g } from "react";
3
- import { ReeClient as P } from "./index.es.js";
2
+ import { createContext as p, useState as u, useCallback as g, useMemo as w, useContext as P, useEffect as m } from "react";
3
+ import { ReeClient as B } from "./index.es.js";
4
4
  import { Network as W, utils as D } from "./index.es.js";
5
5
  const x = p(null);
6
6
  function U({ children: e, config: o }) {
@@ -19,9 +19,9 @@ function U({ children: e, config: o }) {
19
19
  paymentAddress: "",
20
20
  publicKey: "",
21
21
  paymentPublicKey: ""
22
- }), n = m((s) => {
22
+ }), n = g((s) => {
23
23
  i((d) => ({ ...d, ...s }));
24
- }, []), t = w(() => new P(o), [o]), f = m(
24
+ }, []), t = w(() => new B(o), [o]), f = g(
25
25
  async (s) => {
26
26
  if (!t) throw new Error("Client not available");
27
27
  if (!r.address || !r.paymentAddress)
@@ -31,6 +31,7 @@ function U({ children: e, config: o }) {
31
31
  paymentAddress: r.paymentAddress,
32
32
  feeRate: s?.feeRate,
33
33
  publicKey: r.publicKey,
34
+ paymentPublicKey: r.paymentPublicKey,
34
35
  mergeSelfRuneBtcOutputs: s?.mergeSelfRuneBtcOutputs,
35
36
  clientInfo: s?.clientInfo,
36
37
  manualBuild: s?.manualBuild
@@ -50,13 +51,13 @@ function U({ children: e, config: o }) {
50
51
  return /* @__PURE__ */ E(x.Provider, { value: c, children: e });
51
52
  }
52
53
  function R() {
53
- const e = B(x);
54
+ const e = P(x);
54
55
  if (!e)
55
56
  throw new Error("useRee must be used within ReeProvider");
56
57
  return e;
57
58
  }
58
59
  function C(e = {}) {
59
- const { refreshInterval: o = 0, autoRefresh: r = !0 } = e, { client: i, paymentAddress: n } = R(), [t, f] = u(null), [c, s] = u(!1), [d, h] = u(null), a = m(async () => {
60
+ const { refreshInterval: o = 0, autoRefresh: r = !0 } = e, { client: i, paymentAddress: n } = R(), [t, f] = u(null), [c, s] = u(!1), [d, h] = u(null), a = g(async () => {
60
61
  if (!n) {
61
62
  f(null), h("Payment address not set");
62
63
  return;
@@ -73,9 +74,9 @@ function C(e = {}) {
73
74
  s(!1);
74
75
  }
75
76
  }, [i, n]);
76
- return g(() => {
77
+ return m(() => {
77
78
  r && a();
78
- }, [n, a, r]), g(() => {
79
+ }, [n, a, r]), m(() => {
79
80
  if (o > 0) {
80
81
  const l = setInterval(a, o);
81
82
  return () => clearInterval(l);
@@ -88,7 +89,7 @@ function C(e = {}) {
88
89
  };
89
90
  }
90
91
  function L(e, o = {}) {
91
- const { refreshInterval: r = 0, autoRefresh: i = !0 } = o, { client: n, address: t, publicKey: f } = R(), [c, s] = u(null), [d, h] = u(!1), [a, l] = u(null), y = m(async () => {
92
+ const { refreshInterval: r = 0, autoRefresh: i = !0 } = o, { client: n, address: t, publicKey: f } = R(), [c, s] = u(null), [d, h] = u(!1), [a, l] = u(null), y = g(async () => {
92
93
  if (!t) {
93
94
  s(null), l("Address not set");
94
95
  return;
@@ -113,9 +114,9 @@ function L(e, o = {}) {
113
114
  h(!1);
114
115
  }
115
116
  }, [n, t, e]);
116
- return g(() => {
117
+ return m(() => {
117
118
  i && e && y();
118
- }, [t, e, y, i]), g(() => {
119
+ }, [t, e, y, i]), m(() => {
119
120
  if (r > 0 && e) {
120
121
  const v = setInterval(y, r);
121
122
  return () => clearInterval(v);
@@ -127,8 +128,8 @@ function L(e, o = {}) {
127
128
  refetch: y
128
129
  };
129
130
  }
130
- function q(e = {}) {
131
- const { refreshInterval: o = 0, autoRefresh: r = !0 } = e, { client: i, paymentAddress: n } = R(), [t, f] = u([]), [c, s] = u(!1), [d, h] = u(null), a = m(async () => {
131
+ function K(e = {}) {
132
+ const { refreshInterval: o = 0, autoRefresh: r = !0 } = e, { client: i, paymentAddress: n } = R(), [t, f] = u([]), [c, s] = u(!1), [d, h] = u(null), a = g(async () => {
132
133
  if (!n) {
133
134
  f([]), h("Payment address not set");
134
135
  return;
@@ -145,9 +146,9 @@ function q(e = {}) {
145
146
  s(!1);
146
147
  }
147
148
  }, [i, n]);
148
- return g(() => {
149
+ return m(() => {
149
150
  r && n && a();
150
- }, [n, a, r]), g(() => {
151
+ }, [n, a, r]), m(() => {
151
152
  if (o > 0 && n) {
152
153
  const l = setInterval(a, o);
153
154
  return () => clearInterval(l);
@@ -159,8 +160,8 @@ function q(e = {}) {
159
160
  refetch: a
160
161
  };
161
162
  }
162
- function A(e, o = {}) {
163
- const { refreshInterval: r = 0, autoRefresh: i = !0 } = o, { client: n, address: t } = R(), [f, c] = u([]), [s, d] = u(!1), [h, a] = u(null), l = m(async () => {
163
+ function q(e, o = {}) {
164
+ const { refreshInterval: r = 0, autoRefresh: i = !0 } = o, { client: n, address: t } = R(), [f, c] = u([]), [s, d] = u(!1), [h, a] = u(null), l = g(async () => {
164
165
  if (!t) {
165
166
  c([]), a("Address not set");
166
167
  return;
@@ -181,9 +182,9 @@ function A(e, o = {}) {
181
182
  d(!1);
182
183
  }
183
184
  }, [n, t, e]);
184
- return g(() => {
185
+ return m(() => {
185
186
  i && t && e && l();
186
- }, [t, e, l, i]), g(() => {
187
+ }, [t, e, l, i]), m(() => {
187
188
  if (r > 0 && t && e) {
188
189
  const y = setInterval(l, r);
189
190
  return () => clearInterval(y);
@@ -195,8 +196,8 @@ function A(e, o = {}) {
195
196
  refetch: l
196
197
  };
197
198
  }
198
- function K() {
199
- const { client: e } = R(), [o, r] = u([]), [i, n] = u(!1), [t, f] = u(null), c = m(async () => {
199
+ function A() {
200
+ const { client: e } = R(), [o, r] = u([]), [i, n] = u(!1), [t, f] = u(null), c = g(async () => {
200
201
  n(!0), f(null);
201
202
  try {
202
203
  const s = await e.getPoolList();
@@ -209,7 +210,7 @@ function K() {
209
210
  n(!1);
210
211
  }
211
212
  }, [e]);
212
- return g(() => {
213
+ return m(() => {
213
214
  c();
214
215
  }, [c]), {
215
216
  pools: o,
@@ -219,7 +220,7 @@ function K() {
219
220
  };
220
221
  }
221
222
  function T(e) {
222
- const { client: o } = R(), [r, i] = u(null), [n, t] = u(!1), [f, c] = u(null), s = m(async () => {
223
+ const { client: o } = R(), [r, i] = u(null), [n, t] = u(!1), [f, c] = u(null), s = g(async () => {
223
224
  if (!e) {
224
225
  i(null), c("Pool address is required");
225
226
  return;
@@ -236,7 +237,7 @@ function T(e) {
236
237
  t(!1);
237
238
  }
238
239
  }, [o, e]);
239
- return g(() => {
240
+ return m(() => {
240
241
  s();
241
242
  }, [e]), {
242
243
  poolInfo: r,
@@ -248,7 +249,7 @@ function T(e) {
248
249
  function k(e = {}) {
249
250
  const { refreshInterval: o = 0, autoRefresh: r = !0 } = e, { client: i } = R(), [n, t] = u(
250
251
  null
251
- ), [f, c] = u(!1), [s, d] = u(null), h = m(async () => {
252
+ ), [f, c] = u(!1), [s, d] = u(null), h = g(async () => {
252
253
  c(!0), d(null);
253
254
  try {
254
255
  const a = await i.getRecommendedFeeRate();
@@ -261,9 +262,9 @@ function k(e = {}) {
261
262
  c(!1);
262
263
  }
263
264
  }, [i]);
264
- return g(() => {
265
+ return m(() => {
265
266
  r && h();
266
- }, [r, h]), g(() => {
267
+ }, [r, h]), m(() => {
267
268
  if (o > 0) {
268
269
  const a = setInterval(h, o);
269
270
  return () => clearInterval(a);
@@ -279,12 +280,12 @@ export {
279
280
  W as Network,
280
281
  U as ReeProvider,
281
282
  C as useBtcBalance,
282
- q as useBtcUtxos,
283
+ K as useBtcUtxos,
283
284
  T as usePoolInfo,
284
- K as usePoolList,
285
+ A as usePoolList,
285
286
  k as useRecommendedFeeRate,
286
287
  R as useRee,
287
288
  L as useRuneBalance,
288
- A as useRuneUtxos,
289
+ q as useRuneUtxos,
289
290
  D as utils
290
291
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omnity/ree-client-ts-sdk",
3
- "version": "0.7.8",
3
+ "version": "0.8.0",
4
4
  "description": "A TypeScript SDK for interacting with the Ree protocol on Bitcoin",
5
5
  "keywords": [
6
6
  "bitcoin",