@bwalletx/connect 0.5.0 → 0.5.4
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/CHANGELOG.md +18 -0
- package/README.md +10 -2
- package/dist/{access-Z6xQwKVF.d.cts → access-Dp0eKIOc.d.cts} +1 -1
- package/dist/{access-Z6xQwKVF.d.ts → access-Dp0eKIOc.d.ts} +1 -1
- package/dist/bwalletx-connect.global.js +11 -8
- package/dist/bwalletx-connect.global.js.map +1 -1
- package/dist/{chunk-CVLXFNAG.js → chunk-EXRQJTXF.js} +165 -26
- package/dist/chunk-EXRQJTXF.js.map +1 -0
- package/dist/{chunk-GF6GUDZL.js → chunk-RIOHG5JH.js} +67 -12
- package/dist/chunk-RIOHG5JH.js.map +1 -0
- package/dist/element.cjs +166 -31
- package/dist/element.cjs.map +1 -1
- package/dist/element.js +1 -1
- package/dist/index.cjs +250 -52
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +60 -9
- package/dist/index.d.ts +60 -9
- package/dist/index.js +14 -2
- package/dist/index.js.map +1 -1
- package/dist/next.d.cts +1 -1
- package/dist/next.d.ts +1 -1
- package/dist/react.cjs +887 -693
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +7 -2
- package/dist/react.d.ts +7 -2
- package/dist/react.js +11 -3
- package/dist/react.js.map +1 -1
- package/dist/server.d.cts +2 -2
- package/dist/server.d.ts +2 -2
- package/dist/shell-react.cjs.map +1 -1
- package/dist/shell-react.js.map +1 -1
- package/dist/{wallets-VOKIKBbO.d.ts → wallets-CbzMtxrf.d.cts} +1 -1
- package/dist/{wallets-VOKIKBbO.d.cts → wallets-CbzMtxrf.d.ts} +1 -1
- package/package.json +11 -12
- package/dist/chunk-CVLXFNAG.js.map +0 -1
- package/dist/chunk-GF6GUDZL.js.map +0 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
"use strict";var bWalletXConnect=(()=>{var
|
|
2
|
-
`}return D%2
|
|
3
|
-
`}return Qe.substring(0,Qe.length-1)},F.renderTo2dContext=function(H,W){W=W||2;for(var D=F.getModuleCount(),V=0;V<D;V++)for(var X=0;X<D;X++)H.fillStyle=F.isDark(V,X)?"black":"white",H.fillRect(V*W,X*W,W,W)},F};n.stringToBytesFuncs={default:function(E){for(var A=[],k=0;k<E.length;k+=1){var B=E.charCodeAt(k);A.push(B&255)}return A}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(E,A){var k=(function(){for(var _=w(E),$=function(){var z=_.read();if(z==-1)throw"eof";return z},R=0,I={};;){var U=_.read();if(U==-1)break;var M=$(),F=$(),it=$(),ot=String.fromCharCode(U<<8|M),q=F<<8|it;I[ot]=q,R+=1}if(R!=A)throw R+" != "+A;return I})(),B=63;return function(_){for(var $=[],R=0;R<_.length;R+=1){var I=_.charCodeAt(R);if(I<128)$.push(I);else{var U=k[_.charAt(R)];typeof U=="number"?(U&255)==U?$.push(U):($.push(U>>>8),$.push(U&255)):$.push(B)}}return $}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},e={L:1,M:0,Q:3,H:2},i={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var E=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],A=1335,k=7973,B=21522,_={},$=function(R){for(var I=0;R!=0;)I+=1,R>>>=1;return I};return _.getBCHTypeInfo=function(R){for(var I=R<<10;$(I)-$(A)>=0;)I^=A<<$(I)-$(A);return(R<<10|I)^B},_.getBCHTypeNumber=function(R){for(var I=R<<12;$(I)-$(k)>=0;)I^=k<<$(I)-$(k);return R<<12|I},_.getPatternPosition=function(R){return E[R-1]},_.getMaskFunction=function(R){switch(R){case i.PATTERN000:return function(I,U){return(I+U)%2==0};case i.PATTERN001:return function(I,U){return I%2==0};case i.PATTERN010:return function(I,U){return U%3==0};case i.PATTERN011:return function(I,U){return(I+U)%3==0};case i.PATTERN100:return function(I,U){return(Math.floor(I/2)+Math.floor(U/3))%2==0};case i.PATTERN101:return function(I,U){return I*U%2+I*U%3==0};case i.PATTERN110:return function(I,U){return(I*U%2+I*U%3)%2==0};case i.PATTERN111:return function(I,U){return(I*U%3+(I+U)%2)%2==0};default:throw"bad maskPattern:"+R}},_.getErrorCorrectPolynomial=function(R){for(var I=o([1],0),U=0;U<R;U+=1)I=I.multiply(o([1,s.gexp(U)],0));return I},_.getLengthInBits=function(R,I){if(1<=I&&I<10)switch(R){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+R}else if(I<27)switch(R){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+R}else if(I<41)switch(R){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+R}else throw"type:"+I},_.getLostPoint=function(R){for(var I=R.getModuleCount(),U=0,M=0;M<I;M+=1)for(var F=0;F<I;F+=1){for(var it=0,ot=R.isDark(M,F),q=-1;q<=1;q+=1)if(!(M+q<0||I<=M+q))for(var z=-1;z<=1;z+=1)F+z<0||I<=F+z||q==0&&z==0||ot==R.isDark(M+q,F+z)&&(it+=1);it>5&&(U+=3+it-5)}for(var M=0;M<I-1;M+=1)for(var F=0;F<I-1;F+=1){var tt=0;R.isDark(M,F)&&(tt+=1),R.isDark(M+1,F)&&(tt+=1),R.isDark(M,F+1)&&(tt+=1),R.isDark(M+1,F+1)&&(tt+=1),(tt==0||tt==4)&&(U+=3)}for(var M=0;M<I;M+=1)for(var F=0;F<I-6;F+=1)R.isDark(M,F)&&!R.isDark(M,F+1)&&R.isDark(M,F+2)&&R.isDark(M,F+3)&&R.isDark(M,F+4)&&!R.isDark(M,F+5)&&R.isDark(M,F+6)&&(U+=40);for(var F=0;F<I;F+=1)for(var M=0;M<I-6;M+=1)R.isDark(M,F)&&!R.isDark(M+1,F)&&R.isDark(M+2,F)&&R.isDark(M+3,F)&&R.isDark(M+4,F)&&!R.isDark(M+5,F)&&R.isDark(M+6,F)&&(U+=40);for(var It=0,F=0;F<I;F+=1)for(var M=0;M<I;M+=1)R.isDark(M,F)&&(It+=1);var ae=Math.abs(100*It/I/I-50)/5;return U+=ae*10,U},_})(),s=(function(){for(var E=new Array(256),A=new Array(256),k=0;k<8;k+=1)E[k]=1<<k;for(var k=8;k<256;k+=1)E[k]=E[k-4]^E[k-5]^E[k-6]^E[k-8];for(var k=0;k<255;k+=1)A[E[k]]=k;var B={};return B.glog=function(_){if(_<1)throw"glog("+_+")";return A[_]},B.gexp=function(_){for(;_<0;)_+=255;for(;_>=256;)_-=255;return E[_]},B})();function o(E,A){if(typeof E.length>"u")throw E.length+"/"+A;var k=(function(){for(var _=0;_<E.length&&E[_]==0;)_+=1;for(var $=new Array(E.length-_+A),R=0;R<E.length-_;R+=1)$[R]=E[R+_];return $})(),B={};return B.getAt=function(_){return k[_]},B.getLength=function(){return k.length},B.multiply=function(_){for(var $=new Array(B.getLength()+_.getLength()-1),R=0;R<B.getLength();R+=1)for(var I=0;I<_.getLength();I+=1)$[R+I]^=s.gexp(s.glog(B.getAt(R))+s.glog(_.getAt(I)));return o($,0)},B.mod=function(_){if(B.getLength()-_.getLength()<0)return B;for(var $=s.glog(B.getAt(0))-s.glog(_.getAt(0)),R=new Array(B.getLength()),I=0;I<B.getLength();I+=1)R[I]=B.getAt(I);for(var I=0;I<_.getLength();I+=1)R[I]^=s.gexp(s.glog(_.getAt(I))+$);return o(R,0).mod(_)},B}var c=(function(){var E=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],A=function(_,$){var R={};return R.totalCount=_,R.dataCount=$,R},k={},B=function(_,$){switch($){case e.L:return E[(_-1)*4+0];case e.M:return E[(_-1)*4+1];case e.Q:return E[(_-1)*4+2];case e.H:return E[(_-1)*4+3];default:return}};return k.getRSBlocks=function(_,$){var R=B(_,$);if(typeof R>"u")throw"bad rs block @ typeNumber:"+_+"/errorCorrectionLevel:"+$;for(var I=R.length/3,U=[],M=0;M<I;M+=1)for(var F=R[M*3+0],it=R[M*3+1],ot=R[M*3+2],q=0;q<F;q+=1)U.push(A(it,ot));return U},k})(),u=function(){var E=[],A=0,k={};return k.getBuffer=function(){return E},k.getAt=function(B){var _=Math.floor(B/8);return(E[_]>>>7-B%8&1)==1},k.put=function(B,_){for(var $=0;$<_;$+=1)k.putBit((B>>>_-$-1&1)==1)},k.getLengthInBits=function(){return A},k.putBit=function(B){var _=Math.floor(A/8);E.length<=_&&E.push(0),B&&(E[_]|=128>>>A%8),A+=1},k},f=function(E){var A=t.MODE_NUMBER,k=E,B={};B.getMode=function(){return A},B.getLength=function(R){return k.length},B.write=function(R){for(var I=k,U=0;U+2<I.length;)R.put(_(I.substring(U,U+3)),10),U+=3;U<I.length&&(I.length-U==1?R.put(_(I.substring(U,U+1)),4):I.length-U==2&&R.put(_(I.substring(U,U+2)),7))};var _=function(R){for(var I=0,U=0;U<R.length;U+=1)I=I*10+$(R.charAt(U));return I},$=function(R){if("0"<=R&&R<="9")return R.charCodeAt(0)-48;throw"illegal char :"+R};return B},d=function(E){var A=t.MODE_ALPHA_NUM,k=E,B={};B.getMode=function(){return A},B.getLength=function($){return k.length},B.write=function($){for(var R=k,I=0;I+1<R.length;)$.put(_(R.charAt(I))*45+_(R.charAt(I+1)),11),I+=2;I<R.length&&$.put(_(R.charAt(I)),6)};var _=function($){if("0"<=$&&$<="9")return $.charCodeAt(0)-48;if("A"<=$&&$<="Z")return $.charCodeAt(0)-65+10;switch($){case" ":return 36;case"$":return 37;case"%":return 38;case"*":return 39;case"+":return 40;case"-":return 41;case".":return 42;case"/":return 43;case":":return 44;default:throw"illegal char :"+$}};return B},l=function(E){var A=t.MODE_8BIT_BYTE,k=E,B=n.stringToBytes(E),_={};return _.getMode=function(){return A},_.getLength=function($){return B.length},_.write=function($){for(var R=0;R<B.length;R+=1)$.put(B[R],8)},_},p=function(E){var A=t.MODE_KANJI,k=E,B=n.stringToBytesFuncs.SJIS;if(!B)throw"sjis not supported.";(function(R,I){var U=B(R);if(U.length!=2||(U[0]<<8|U[1])!=I)throw"sjis not supported."})("\u53CB",38726);var _=B(E),$={};return $.getMode=function(){return A},$.getLength=function(R){return~~(_.length/2)},$.write=function(R){for(var I=_,U=0;U+1<I.length;){var M=(255&I[U])<<8|255&I[U+1];if(33088<=M&&M<=40956)M-=33088;else if(57408<=M&&M<=60351)M-=49472;else throw"illegal char at "+(U+1)+"/"+M;M=(M>>>8&255)*192+(M&255),R.put(M,13),U+=2}if(U<I.length)throw"illegal char at "+(U+1)},$},b=function(){var E=[],A={};return A.writeByte=function(k){E.push(k&255)},A.writeShort=function(k){A.writeByte(k),A.writeByte(k>>>8)},A.writeBytes=function(k,B,_){B=B||0,_=_||k.length;for(var $=0;$<_;$+=1)A.writeByte(k[$+B])},A.writeString=function(k){for(var B=0;B<k.length;B+=1)A.writeByte(k.charCodeAt(B))},A.toByteArray=function(){return E},A.toString=function(){var k="";k+="[";for(var B=0;B<E.length;B+=1)B>0&&(k+=","),k+=E[B];return k+="]",k},A},g=function(){var E=0,A=0,k=0,B="",_={},$=function(I){B+=String.fromCharCode(R(I&63))},R=function(I){if(!(I<0)){if(I<26)return 65+I;if(I<52)return 97+(I-26);if(I<62)return 48+(I-52);if(I==62)return 43;if(I==63)return 47}throw"n:"+I};return _.writeByte=function(I){for(E=E<<8|I&255,A+=8,k+=1;A>=6;)$(E>>>A-6),A-=6},_.flush=function(){if(A>0&&($(E<<6-A),E=0,A=0),k%3!=0)for(var I=3-k%3,U=0;U<I;U+=1)B+="="},_.toString=function(){return B},_},w=function(E){var A=E,k=0,B=0,_=0,$={};$.read=function(){for(;_<8;){if(k>=A.length){if(_==0)return-1;throw"unexpected end of file./"+_}var I=A.charAt(k);if(k+=1,I=="=")return _=0,-1;if(I.match(/^\s$/))continue;B=B<<6|R(I.charCodeAt(0)),_+=6}var U=B>>>_-8&255;return _-=8,U};var R=function(I){if(65<=I&&I<=90)return I-65;if(97<=I&&I<=122)return I-97+26;if(48<=I&&I<=57)return I-48+52;if(I==43)return 62;if(I==47)return 63;throw"c:"+I};return $},S=function(E,A){var k=E,B=A,_=new Array(E*A),$={};$.setPixel=function(M,F,it){_[F*k+M]=it},$.write=function(M){M.writeString("GIF87a"),M.writeShort(k),M.writeShort(B),M.writeByte(128),M.writeByte(0),M.writeByte(0),M.writeByte(0),M.writeByte(0),M.writeByte(0),M.writeByte(255),M.writeByte(255),M.writeByte(255),M.writeString(","),M.writeShort(0),M.writeShort(0),M.writeShort(k),M.writeShort(B),M.writeByte(0);var F=2,it=I(F);M.writeByte(F);for(var ot=0;it.length-ot>255;)M.writeByte(255),M.writeBytes(it,ot,255),ot+=255;M.writeByte(it.length-ot),M.writeBytes(it,ot,it.length-ot),M.writeByte(0),M.writeString(";")};var R=function(M){var F=M,it=0,ot=0,q={};return q.write=function(z,tt){if(z>>>tt)throw"length over";for(;it+tt>=8;)F.writeByte(255&(z<<it|ot)),tt-=8-it,z>>>=8-it,ot=0,it=0;ot=z<<it|ot,it=it+tt},q.flush=function(){it>0&&F.writeByte(ot)},q},I=function(M){for(var F=1<<M,it=(1<<M)+1,ot=M+1,q=U(),z=0;z<F;z+=1)q.add(String.fromCharCode(z));q.add(String.fromCharCode(F)),q.add(String.fromCharCode(it));var tt=b(),It=R(tt);It.write(F,ot);var ae=0,Bt=String.fromCharCode(_[ae]);for(ae+=1;ae<_.length;){var dn=String.fromCharCode(_[ae]);ae+=1,q.contains(Bt+dn)?Bt=Bt+dn:(It.write(q.indexOf(Bt),ot),q.size()<4095&&(q.size()==1<<ot&&(ot+=1),q.add(Bt+dn)),Bt=dn)}return It.write(q.indexOf(Bt),ot),It.write(it,ot),It.flush(),tt.toByteArray()},U=function(){var M={},F=0,it={};return it.add=function(ot){if(it.contains(ot))throw"dup key:"+ot;M[ot]=F,F+=1},it.size=function(){return F},it.indexOf=function(ot){return M[ot]},it.contains=function(ot){return typeof M[ot]<"u"},it};return $},C=function(E,A,k){for(var B=S(E,A),_=0;_<A;_+=1)for(var $=0;$<E;$+=1)B.setPixel($,_,k($,_));var R=b();B.write(R);for(var I=g(),U=R.toByteArray(),M=0;M<U.length;M+=1)I.writeByte(U[M]);return I.flush(),"data:image/gif;base64,"+I};return n})();(function(){bm.stringToBytesFuncs["UTF-8"]=function(n){function t(e){for(var i=[],r=0;r<e.length;r++){var s=e.charCodeAt(r);s<128?i.push(s):s<2048?i.push(192|s>>6,128|s&63):s<55296||s>=57344?i.push(224|s>>12,128|s>>6&63,128|s&63):(r++,s=65536+((s&1023)<<10|e.charCodeAt(r)&1023),i.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|s&63))}return i}return t(n)}})();(function(n){typeof define=="function"&&define.amd?define([],n):typeof mm=="object"&&(ym.exports=n())})(function(){return bm})});var n4={};wu(n4,{ACCESS_ERROR_STATUS:()=>Jb,ACCESS_PROTOCOL:()=>lu,ACCESS_VERSION:()=>Yb,AccessError:()=>kt,BRC29_PROTOCOL:()=>el,BWALLETX_RDNS:()=>Ls,GET_URL:()=>jd,LOGIN_PROTOCOL:()=>$d,LOGO_URL:()=>tl,PROTOCOL_MEDIA:()=>qd,PaymentError:()=>le,RDNS_EXTENSION:()=>Dr,RDNS_MOBILE:()=>Iu,SIGNIN_CSS:()=>Jd,SIGNIN_TAG:()=>Xd,WEB_WALLET_URL:()=>Gd,accessErrorMessage:()=>em,amountInSats:()=>sl,brc100Option:()=>_s,buildAuthorizeUrl:()=>Qd,buyToken:()=>dm,canonicalJson:()=>ea,clearPairing:()=>Gb,connectBwalletX:()=>ta,defineBwalletxSignin:()=>bu,discoverBwalletX:()=>Wi,discoverWallets:()=>gm,findBwalletX:()=>gl,handcashAdapter:()=>pm,inOrder:()=>Jo,isIdentityKeyHex:()=>nl,isPaymail:()=>il,markSvg:()=>Zd,pairBwalletX:()=>Ns,pairingModal:()=>Sm,pairingOption:()=>cl,pay:()=>al,pickWallet:()=>vm,protocolMediaUrl:()=>Qb,proveHoldings:()=>Vd,qrSvg:()=>ul,renderButton:()=>sm,requestAccess:()=>pu,resolvePaymailP2P:()=>ol,restorePairing:()=>Bs,signInWithBwalletX:()=>du,signinText:()=>Yd,throwIfAccessError:()=>Wd,tip:()=>fm,toAccessError:()=>hu});var Dr="com.bwalletx.extension",Iu="space.bwallet.mobile",Ls=[Dr,Iu];function Wi(n=1200){return typeof window>"u"?Promise.resolve(null):new Promise(t=>{let e=!1,i=s=>{e||(e=!0,window.removeEventListener("brc100:announceWallet",r),t(s))},r=s=>{let o=s.detail,c=o?.info?.rdns??"";o?.wallet&&Ls.includes(c)&&i({wallet:o.wallet,method:c===Dr?"extension":"in-app",rdns:c})};window.addEventListener("brc100:announceWallet",r),window.dispatchEvent(new Event("brc100:requestWallet")),setTimeout(()=>{let s=window.CWI;i(s?{wallet:s,method:"in-app",rdns:null}:null)},n)})}async function gl(n=1200){return(await Wi(n))?.wallet??null}var Su=globalThis.Buffer,_m=Su!=null&&typeof Su.from=="function",Hs=new Int8Array(256).fill(-1);for(let n=0;n<10;n++)Hs[48+n]=n;for(let n=0;n<6;n++)Hs[65+n]=10+n,Hs[97+n]=10+n;var $s,qs,ra,sa,ui,oa,Fs,Y,rt,St,P,bl,ml,yl,wl,xl,Il,vu,_e,An,st,Sl,Us,Ms,vl,Al,Ki,El,kl,Tl,Lt,ce,Ds,ia,Vi,Au,Ol,Eu,Z=class Z{constructor(t=0,e=10,i="be"){G(this,P);G(this,Y,0n);G(this,rt,0);G(this,St,1);m(this,"red",null);if(t??(t=0),typeof t=="bigint"){a(this,P,_e).call(this,t<0n?-t:t,t<0n?1:0),this.normSign();return}let r=e==="le"||e==="be",s=r?10:e,o=r?e:i;if(typeof t=="number"){a(this,P,Sl).call(this,t,o);return}if(Array.isArray(t)){a(this,P,Us).call(this,t,o);return}if(typeof t=="string"){a(this,P,ml).call(this,t,s,o);return}t!==0?a(this,P,st).call(this,!1,"Unsupported input type for BigNumber constructor"):a(this,P,_e).call(this,0n,0)}get negative(){return y(this,rt)}set negative(t){a(this,P,st).call(this,t===0||t===1,"Negative property must be 0 or 1");let e=t===1?1:0;y(this,Y)===0n?N(this,rt,0):N(this,rt,e)}get words(){if(!Number.isSafeInteger(y(this,St))||y(this,St)<1||y(this,St)>y(Z,Fs))throw new Error("BigNumber word length exceeds the supported limit");let t=y(this,P,bl);if(y(this,St)<=t.length)return t;let e=Array.from({length:y(this,St)}).fill(0);for(let i=0;i<t.length;i++)e[i]=t[i];return e}set words(t){let e=y(this,rt),i=0n,r=t.length>0?t.length:1;for(let s=r-1;s>=0;s--){let o=t[s]??0;i=i<<y(Z,$s)|BigInt(o&Number(y(Z,qs)))}N(this,Y,i),N(this,rt,e),N(this,St,r),this.normSign()}get length(){return Math.max(1,y(this,St))}static isBN(t){return t instanceof Z?!0:t!==null&&typeof t=="object"&&t.constructor?.wordSize===Z.wordSize&&Array.isArray(t.words)}static max(t,e){return t.cmp(e)>0?t:e}static min(t,e){return t.cmp(e)<0?t:e}copy(t){N(t,Y,y(this,Y)),N(t,rt,y(this,rt)),N(t,St,y(this,St)),t.red=this.red}static move(t,e){N(t,Y,y(e,Y)),N(t,rt,y(e,rt)),N(t,St,y(e,St)),t.red=e.red}clone(){let t=new Z(0n);return this.copy(t),t}expand(t){return a(this,P,st).call(this,Number.isSafeInteger(t)&&t>=0&&t<=y(Z,Fs),"Expand size must be a non-negative safe integer within the supported word limit"),N(this,St,Math.max(y(this,St),t,1)),this}strip(){return a(this,P,An).call(this),this.normSign()}normSign(){return y(this,Y)===0n&&N(this,rt,0),this}inspect(){return(this.red===null?"<BN: ":"<BN-R: ")+this.toString(16)+">"}toString(t=10,e=1){if(t===16||t==="hex")return a(this,P,vl).call(this,e);if(typeof t!="number"||t<2||t>36||t%1!==0)throw new Error("Base should be an integer between 2 and 36");return a(this,P,Al).call(this,t,e)}toNumber(){let t=a(this,P,Lt).call(this);if(t>y(Z,ra)||t<y(Z,sa))throw new Error("Number can only safely store up to 53 bits");return Number(t)}toBigInt(){return a(this,P,Lt).call(this)}toJSON(){let t=a(this,P,Ms).call(this);return(this.isNeg()?"-":"")+t}toArray(t="be",e){this.strip();let i=this.byteLength(),r=e??Math.max(1,i);a(this,P,st).call(this,i<=r,"byte array longer than desired length"),a(this,P,st).call(this,r>0,"Requested array length <= 0");let s=Array.from({length:r}).fill(0);return y(this,Y)===0n&&r>0?s:y(this,Y)===0n&&r===0?[]:(a(this,P,Tl).call(this,s,t==="le"),s)}bitLength(){return y(this,Y)===0n?0:y(this,Y).toString(2).length}static toBitArray(t){let e=t.bitLength();if(e===0)return[];let i=Array.from({length:e}),r=y(t,Y);for(let s=0;s<e;s++)i[s]=(r>>BigInt(s)&1n)===0n?0:1;return i}toBitArray(){return Z.toBitArray(this)}zeroBits(){if(y(this,Y)===0n)return 0;let t=0,e=y(this,Y);for(;(e&1n)===0n&&e!==0n;)t++,e>>=1n;return t}byteLength(){return y(this,Y)===0n?0:Math.ceil(this.bitLength()/8)}toTwos(t){var o;a(this,P,st).call(this,t>=0);let e=BigInt(t),i=a(this,P,Lt).call(this);y(this,rt)===1&&y(this,Y)!==0n&&(i=(1n<<e)+i);let r=(1n<<e)-1n;i&=r;let s=new Z(0n);return a(o=s,P,_e).call(o,i,0),s}fromTwos(t){var r;a(this,P,st).call(this,t>=0);let e=BigInt(t),i=y(this,Y);if(t>0&&(i>>e-1n&1n)!==0n&&y(this,rt)===0){let s=i-(1n<<e),o=new Z(0n);return a(r=o,P,ce).call(r,s),o}return this.clone()}isNeg(){return y(this,rt)===1&&y(this,Y)!==0n}neg(){return this.clone().ineg()}ineg(){return y(this,Y)!==0n&&N(this,rt,y(this,rt)===1?0:1),this}iuor(t){return a(this,P,Ds).call(this,t,(e,i)=>e|i)}iuand(t){return a(this,P,Ds).call(this,t,(e,i)=>e&i)}iuxor(t){return a(this,P,Ds).call(this,t,(e,i)=>e^i,!0)}ior(t){return a(this,P,ia).call(this,t,(e,i)=>e|i)}iand(t){return a(this,P,ia).call(this,t,(e,i)=>e&i)}ixor(t){return a(this,P,ia).call(this,t,(e,i)=>e^i,!0)}or(t){return a(this,P,st).call(this,y(this,rt)===0&&y(t,rt)===0),a(this,P,Vi).call(this,t,"iuor")}uor(t){return a(this,P,Vi).call(this,t,"iuor")}and(t){return a(this,P,st).call(this,y(this,rt)===0&&y(t,rt)===0),a(this,P,Vi).call(this,t,"iuand")}uand(t){return a(this,P,Vi).call(this,t,"iuand")}xor(t){return a(this,P,st).call(this,y(this,rt)===0&&y(t,rt)===0),a(this,P,Vi).call(this,t,"iuxor")}uxor(t){return a(this,P,Vi).call(this,t,"iuxor")}inotn(t){a(this,P,st).call(this,typeof t=="number"&&t>=0);let i=(1n<<BigInt(t))-1n;N(this,Y,~y(this,Y)&i);let r=t===0?1:Math.ceil(t/Z.wordSize);return N(this,St,Math.max(1,r)),this.strip(),N(this,St,Math.max(y(this,St),Math.max(1,r))),this}notn(t){return this.clone().inotn(t)}setn(t,e){a(this,P,st).call(this,typeof t=="number"&&t>=0);let i=BigInt(t);e===1||e===!0?N(this,Y,y(this,Y)|1n<<i):N(this,Y,y(this,Y)&~(1n<<i));let r=Math.floor(t/Z.wordSize)+1;return N(this,St,Math.max(y(this,St),r)),a(this,P,An).call(this),this.strip()}iadd(t){var e;return a(this,P,ce).call(this,a(this,P,Lt).call(this)+a(e=t,P,Lt).call(e)),this}add(t){var i,r;let e=new Z(0n);return a(r=e,P,ce).call(r,a(this,P,Lt).call(this)+a(i=t,P,Lt).call(i)),e}isub(t){var e;return a(this,P,ce).call(this,a(this,P,Lt).call(this)-a(e=t,P,Lt).call(e)),this}sub(t){var i,r;let e=new Z(0n);return a(r=e,P,ce).call(r,a(this,P,Lt).call(this)-a(i=t,P,Lt).call(i)),e}mul(t){let e=new Z(0n);return N(e,Y,y(this,Y)*y(t,Y)),N(e,rt,y(e,Y)===0n?0:y(this,rt)^y(t,rt)),N(e,St,this.length+t.length),e.red=null,e.normSign()}imul(t){return N(this,Y,y(this,Y)*y(t,Y)),N(this,rt,y(this,Y)===0n?0:y(this,rt)^y(t,rt)),N(this,St,this.length+t.length),this.red=null,this.normSign()}imuln(t){return a(this,P,st).call(this,typeof t=="number","Assertion failed"),a(this,P,st).call(this,Math.abs(t)<=y(Z,ui),"Assertion failed"),a(this,P,ce).call(this,a(this,P,Lt).call(this)*BigInt(t)),this}muln(t){return this.clone().imuln(t)}sqr(){let t=new Z(0n);return N(t,Y,y(this,Y)*y(this,Y)),N(t,rt,0),N(t,St,this.length*2),t.red=null,t}isqr(){return N(this,Y,y(this,Y)*y(this,Y)),N(this,rt,0),N(this,St,this.length*2),this.red=null,this}pow(t){if(a(this,P,st).call(this,y(t,rt)===0,"Exponent for pow must be non-negative"),t.isZero())return new Z(1n);let e=new Z(1n),i=this.clone(),r=t.clone(),s=i.isNeg(),o=r.isOdd();for(s&&i.ineg();!r.isZero();)r.isOdd()&&e.imul(i),i.isqr(),r.iushrn(1);return s&&o&&e.ineg(),e}iushln(t){var i;let e=a(i=Z,Ki,Au).call(i,t,"Shift bits");return e===0n?this:(N(this,Y,y(this,Y)<<e),a(this,P,An).call(this),this.strip())}ishln(t){return a(this,P,st).call(this,y(this,rt)===0,"ishln requires positive number"),this.iushln(t)}iushrn(t,e,i){var s,o,c;let r=a(s=Z,Ki,Au).call(s,t,"Shift bits");if(r===0n)return i!=null&&a(o=i,P,_e).call(o,0n,0),this;if(i!=null){let u=(1n<<r)-1n,f=y(this,Y)&u;a(c=i,P,_e).call(c,f,0)}return N(this,Y,y(this,Y)>>r),a(this,P,An).call(this),this.strip()}ishrn(t,e,i){return a(this,P,st).call(this,y(this,rt)===0,"ishrn requires positive number"),this.iushrn(t,e,i)}shln(t){return this.clone().ishln(t)}ushln(t){return this.clone().iushln(t)}shrn(t){return this.clone().ishrn(t)}ushrn(t){return this.clone().iushrn(t)}testn(t){return a(this,P,st).call(this,typeof t=="number"&&t>=0),(y(this,Y)>>BigInt(t)&1n)!==0n}imaskn(t){a(this,P,st).call(this,typeof t=="number"&&t>=0),a(this,P,st).call(this,y(this,rt)===0,"imaskn works only with positive numbers");let e=BigInt(t),i=e===0n?0n:(1n<<e)-1n;N(this,Y,y(this,Y)&i);let r=t===0?1:Math.max(1,Math.ceil(t/Z.wordSize));return N(this,St,r),a(this,P,An).call(this),N(this,St,Math.max(y(this,St),r)),this.strip()}maskn(t){return this.clone().imaskn(t)}iaddn(t){return a(this,P,st).call(this,typeof t=="number"),a(this,P,st).call(this,Math.abs(t)<=y(Z,ui),"num is too large"),a(this,P,ce).call(this,a(this,P,Lt).call(this)+BigInt(t)),this}_iaddn(t){return this.iaddn(t)}isubn(t){return a(this,P,st).call(this,typeof t=="number"),a(this,P,st).call(this,Math.abs(t)<=y(Z,ui),"Assertion failed"),a(this,P,ce).call(this,a(this,P,Lt).call(this)-BigInt(t)),this}addn(t){return this.clone().iaddn(t)}subn(t){return this.clone().isubn(t)}iabs(){return N(this,rt,0),this}abs(){return this.clone().iabs()}divmod(t,e,i){var u;if(a(this,P,st).call(this,!t.isZero(),"Division by zero"),this.isZero()){let f=new Z(0n);return{div:e==="mod"?null:f,mod:e==="div"?null:f}}let r=a(this,P,Lt).call(this),s=a(u=t,P,Lt).call(u),o=e!=="mod"?r/s:null,c=a(this,P,Ol).call(this,r,s,e,i);return{div:a(this,P,Eu).call(this,o),mod:a(this,P,Eu).call(this,c)}}div(t){return this.divmod(t,"div",!1).div}mod(t){return this.divmod(t,"mod",!1).mod}umod(t){return this.divmod(t,"mod",!0).mod}divRound(t){var f,d,l;a(this,P,st).call(this,!t.isZero());let e=a(this,P,Lt).call(this),i=a(f=t,P,Lt).call(f),r=e/i,s=e%i;if(s===0n){let p=new Z(0n);return a(d=p,P,ce).call(d,r),p}let o=s<0n?-s:s,c=i<0n?-i:i;o*2n>=c&&(e>0n&&i>0n||e<0n&&i<0n?r+=1n:r-=1n);let u=new Z(0n);return a(l=u,P,ce).call(l,r),u}modrn(t){a(this,P,st).call(this,t!==0,"Division by zero in modrn");let e=BigInt(Math.abs(t));if(e===0n)throw new Error("Division by zero in modrn");let i=y(this,Y)%e;return t<0?Number(-i):Number(i)}idivn(t){return a(this,P,st).call(this,t!==0),a(this,P,st).call(this,Math.abs(t)<=y(Z,ui),"num is too large"),a(this,P,ce).call(this,a(this,P,Lt).call(this)/BigInt(t)),this}divn(t){return this.clone().idivn(t)}egcd(t){var l,p,b;a(this,P,st).call(this,t.negative===0,"p must not be negative"),a(this,P,st).call(this,!t.isZero(),"p must not be zero");let e=a(this,P,Lt).call(this),i=y(t,Y),r=1n,s=0n,o=0n,c=1n;for(;i!==0n;){let g=e/i,w=i;i=e%i,e=w,w=s,s=r-g*s,r=w,w=c,c=o-g*c,o=w}let u=new Z(0n);a(l=u,P,ce).call(l,r);let f=new Z(0n);a(p=f,P,ce).call(p,o);let d=new Z(0n);return a(b=d,P,_e).call(b,e<0n?-e:e,0),{a:u,b:f,gcd:d}}gcd(t){var s,o,c;let e=y(this,Y),i=y(t,Y);if(e===0n){let u=new Z(0n);return a(s=u,P,ce).call(s,i),u.iabs()}if(i===0n){let u=new Z(0n);return a(o=u,P,ce).call(o,e),u.iabs()}for(;i!==0n;){let u=e%i;e=i,i=u}let r=new Z(0n);return a(c=r,P,_e).call(c,e,0),r}invm(t){a(this,P,st).call(this,!t.isZero()&&y(t,rt)===0,"Modulus for invm must be positive and non-zero");let e=this.egcd(t);if(!e.gcd.eqn(1))throw new Error("Inverse does not exist (numbers are not coprime).");return e.a.umod(t)}isEven(){return y(this,Y)%2n===0n}isOdd(){return y(this,Y)%2n===1n}andln(t){return a(this,P,st).call(this,t>=0),Number(y(this,Y)&BigInt(t))}bincn(t){a(this,P,st).call(this,typeof t=="number"&&t>=0);let e=1n<<BigInt(t);return a(this,P,ce).call(this,a(this,P,Lt).call(this)+e),this}isZero(){return y(this,Y)===0n}cmpn(t){a(this,P,st).call(this,Math.abs(t)<=y(Z,ui),"Number is too big");let e=a(this,P,Lt).call(this),i=BigInt(t);return e<i?-1:e>i?1:0}cmp(t){var r;let e=a(this,P,Lt).call(this),i=a(r=t,P,Lt).call(r);return e<i?-1:e>i?1:0}ucmp(t){return y(this,Y)<y(t,Y)?-1:y(this,Y)>y(t,Y)?1:0}gtn(t){return this.cmpn(t)===1}gt(t){return this.cmp(t)===1}gten(t){return this.cmpn(t)>=0}gte(t){return this.cmp(t)>=0}ltn(t){return this.cmpn(t)===-1}lt(t){return this.cmp(t)===-1}lten(t){return this.cmpn(t)<=0}lte(t){return this.cmp(t)<=0}eqn(t){return this.cmpn(t)===0}eq(t){return this.cmp(t)===0}toRed(t){return a(this,P,st).call(this,this.red==null,"Already a number in reduction context"),a(this,P,st).call(this,y(this,rt)===0,"toRed works only with positives"),t.convertTo(this).forceRed(t)}fromRed(){return a(this,P,st).call(this,this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)}forceRed(t){return this.red=t,this}redAdd(t){return a(this,P,st).call(this,this.red,"redAdd works only with red numbers"),this.red.add(this,t)}redIAdd(t){return a(this,P,st).call(this,this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)}redSub(t){return a(this,P,st).call(this,this.red,"redSub works only with red numbers"),this.red.sub(this,t)}redISub(t){return a(this,P,st).call(this,this.red,"redISub works only with red numbers"),this.red.isub(this,t)}redShl(t){return a(this,P,st).call(this,this.red,"redShl works only with red numbers"),this.red.shl(this,t)}redMul(t){return a(this,P,st).call(this,this.red,"redMul works only with red numbers"),this.red.verify2(this,t),this.red.mul(this,t)}redIMul(t){return a(this,P,st).call(this,this.red,"redIMul works only with red numbers"),this.red.verify2(this,t),this.red.imul(this,t)}redSqr(){return a(this,P,st).call(this,this.red,"redSqr works only with red numbers"),this.red.verify1(this),this.red.sqr(this)}redISqr(){return a(this,P,st).call(this,this.red,"redISqr works only with red numbers"),this.red.verify1(this),this.red.isqr(this)}redSqrt(){return a(this,P,st).call(this,this.red,"redSqrt works only with red numbers"),this.red.verify1(this),this.red.sqrt(this)}redInvm(){return a(this,P,st).call(this,this.red,"redInvm works only with red numbers"),this.red.verify1(this),this.red.invm(this)}redNeg(){return a(this,P,st).call(this,this.red,"redNeg works only with red numbers"),this.red.verify1(this),this.red.neg(this)}redPow(t){return a(this,P,st).call(this,this.red!=null&&t.red==null,"redPow(normalNum)"),this.red.verify1(this),this.red.pow(this,t)}static fromHex(t,e){let i="be";return(e==="little"||e==="le")&&(i="le"),new Z(t,16,i)}toHex(t=0){if(this.isZero()&&t===0)return"";let e=a(this,P,Ms).call(this);e!=="0"&&e.length%2!==0&&(e="0"+e);let i=t*2;for(;e.length<i;)e="0"+e;return(this.isNeg()?"-":"")+e}static fromJSON(t){return new Z(t,16)}static fromNumber(t){return new Z(t)}static fromString(t,e){return new Z(t,e)}static fromSm(t,e="big"){var u;if(t.length===0)return new Z(0n);let i=t.slice();e==="little"&&i.reverse();let r=0;i.length>0&&(i[0]&128)!==0&&(r=1,i[0]&=127);let s;if(_m)s=Su.from(i).toString("hex");else{s="";for(let f of i)s+=f<16?"0"+f.toString(16):f.toString(16)}let o=s.length===0?0n:BigInt("0x"+s),c=new Z(0n);return a(u=c,P,_e).call(u,o,r),c}toSm(t="big"){if(y(this,Y)===0n)return y(this,rt)===1?[128]:[];let e=a(this,P,Ms).call(this);e.length%2!==0&&(e="0"+e);let i=e.length/2,r=Array.from({length:i});for(let o=0,c=0;o<e.length;o+=2){let u=Hs[e.codePointAt(o)],f=Hs[e.codePointAt(o+1)];r[c++]=(u&15)<<4|f&15}let s;return y(this,rt)===1?(r[0]&128)===0?(s=r.slice(),s[0]|=128):s=[128,...r]:(r[0]&128)===0?s=r.slice():s=[0,...r],t==="little"?s.reverse():s}static fromBits(t,e=!1){let i=t>>>24,r=t&8388607,s=(t&8388608)!==0;if(e&&s)throw new Error("negative bit set");if(i===0&&r===0){if(s&&e)throw new Error("negative bit set for zero value");return new Z(0n)}let o=new Z(r);return i<=3?o.iushrn((3-i)*8):o.iushln((i-3)*8),s&&o.ineg(),o}toBits(){if(this.strip(),this.isZero()&&!this.isNeg())return 0;let t=this.isNeg(),i=this.abs().toArray("be"),r=0;for(;r<i.length-1&&i[r]===0;)r++;i=i.slice(r);let s=i.length,o;if(s===0)o=0;else if(s<=3){o=0;for(let u=0;u<s;u++)o=o<<8|i[u]}else o=i[0]<<16|i[1]<<8|i[2];(o&8388608)!==0&&s<=255&&(o>>>=8,s++);let c=s<<24|o;return t&&(c|=8388608),c>>>0}static fromScriptNum(t,e=!1,i){if(i!==void 0&&t.length>i)throw new Error("script number overflow");if(t.length===0)return new Z(0n);if(e&&(t.at(-1)&127)===0&&(t.length<=1||(t.at(-2)&128)===0))throw new Error("non-minimally encoded script number");return Z.fromSm(t,"little")}toScriptNum(){return this.toSm("little")}_invmp(t){a(this,P,st).call(this,y(t,rt)===0,"p must not be negative for _invmp"),a(this,P,st).call(this,!t.isZero(),"p must not be zero for _invmp");let e=this.umod(t),i=t.subn(2);if(e.red!==null)return e.redPow(i);let r=new Z(1n),s=e.clone(),o=i.clone();for(;!o.isZero();)o.isOdd()&&(r=r.mul(s).umod(t)),s=s.sqr().umod(t),o.iushrn(1);return r}mulTo(t,e){return N(e,Y,y(this,Y)*y(t,Y)),N(e,rt,y(e,Y)===0n?0:y(this,rt)^y(t,rt)),N(e,St,this.length+t.length),e.red=null,e.normSign(),e}};$s=new WeakMap,qs=new WeakMap,ra=new WeakMap,sa=new WeakMap,ui=new WeakMap,oa=new WeakMap,Fs=new WeakMap,Y=new WeakMap,rt=new WeakMap,St=new WeakMap,P=new WeakSet,bl=function(){if(y(this,Y)===0n)return[0];let t=[],e=y(this,Y);for(;e>0n;)t.push(Number(e&y(Z,qs))),e>>=y(Z,$s);return t.length>0?t:[0]},ml=function(t,e,i){e==="hex"&&(e=16),a(this,P,st).call(this,typeof e=="number"&&e===Math.trunc(e)&&e>=2&&e<=36,"Base must be an integer between 2 and 36");let r=t.toString().replace(/\s+/g,""),s=0,o=0;r.startsWith("-")?(s++,o=1):r.startsWith("+")&&s++;let c=r.substring(s);if(c.length===0){a(this,P,_e).call(this,0n,o===1&&r.startsWith("-")?1:0),this.normSign();return}e===16?a(this,P,yl).call(this,c,o,i):a(this,P,wl).call(this,c,e,o,i)},yl=function(t,e,i){if(i==="le"){let r=[],s=t;s.length%2!==0&&(s="0"+s);for(let o=0;o<s.length;o+=2){let c=s.substring(o,o+2),u=Number.parseInt(c,16);if(Number.isNaN(u))throw new Error("Invalid character in "+s);r.push(u)}a(this,P,Us).call(this,r,"le"),N(this,rt,e),this.normSign()}else{let r;try{r=BigInt("0x"+t)}catch{throw new Error("Invalid character in "+t)}a(this,P,_e).call(this,r,e),this.normSign()}},wl=function(t,e,i,r){try{if(a(this,P,Il).call(this,t,e),N(this,rt,i),this.normSign(),r==="le"){let s=y(this,rt);a(this,P,Us).call(this,this.toArray("be"),"le"),N(this,rt,s),this.normSign()}}catch(s){let o=s;throw o.message.includes("Invalid character in string")||o.message.includes("Invalid digit for base")||o.message.startsWith("Invalid character:")?new Error("Invalid character"):o}},xl=function(t,e){if(t===0n)return"0";if(e<2||e>36)throw new Error("Base must be between 2 and 36");let i="0123456789abcdefghijklmnopqrstuvwxyz",r="",s=t>0n?t:-t,o=BigInt(e);for(;s>0n;)r=i[Number(s%o)]+r,s/=o;return r},Il=function(t,e){N(this,Y,0n);let i=BigInt(e),r=Z.groupSizes[e],s=BigInt(Z.groupBases[e]);(r===0||s===0n)&&(r=Math.floor(Math.log(67108863)/Math.log(e)),r===0&&(r=1),s=i**BigInt(r));let o=0,c=t.length,u=c%r;if(u===0&&c>0&&(u=r),u>0){let f=t.substring(o,o+u);N(this,Y,BigInt(a(this,P,vu).call(this,f,e))),o+=u}for(;o<c;){let f=t.substring(o,o+r),d=BigInt(a(this,P,vu).call(this,f,e));N(this,Y,y(this,Y)*s+d),o+=r}a(this,P,An).call(this)},vu=function(t,e){let i=0;for(let r=0;r<t.length;r++){let s=t.codePointAt(r),o;if(s>=48&&s<=57)o=s-48;else if(s>=65&&s<=90)o=s-65+10;else if(s>=97&&s<=122)o=s-97+10;else throw new Error("Invalid character: "+t[r]);if(o>=e)throw new Error("Invalid character");i=i*e+o}return i},_e=function(t,e){N(this,Y,t),N(this,rt,t===0n?0:e),a(this,P,An).call(this)},An=function(){if(y(this,Y)===0n)N(this,St,1),N(this,rt,0);else{let t=y(this,Y).toString(2).length;N(this,St,Math.max(1,Math.ceil(t/Z.wordSize)))}},st=function(t,e="Assertion failed"){if(!t)throw new Error(e)},Sl=function(t,e="be"){if(a(this,P,st).call(this,BigInt(Math.abs(t))<=y(Z,oa),"The number is larger than 2 ^ 53 (unsafe)"),a(this,P,st).call(this,t%1===0,"Number must be an integer for BigNumber conversion"),a(this,P,_e).call(this,BigInt(Math.abs(t)),t<0?1:0),e==="le"){let i=y(this,rt),r=this.toArray("be");a(this,P,Us).call(this,r,"le"),N(this,rt,i),this.normSign()}return this},Us=function(t,e){if(t.length===0)return a(this,P,_e).call(this,0n,0),this;let i=0n;if(e==="be")for(let r of t)i=i<<8n|BigInt(r&255);else for(let r=t.length-1;r>=0;r--)i=i<<8n|BigInt(t[r]&255);return a(this,P,_e).call(this,i,0),this},Ms=function(){return y(this,Y)===0n?"0":y(this,Y).toString(16)},vl=function(t){let e=a(this,P,Ms).call(this);if(t>1)for(e!=="0"&&e.length%2!==0&&(e="0"+e);e.length%t!==0;)e="0"+e;return(this.isNeg()?"-":"")+e},Al=function(t,e){var c;if(y(this,Y)===0n)return a(c=Z,Ki,El).call(c,e);let i=Z.groupSizes[t],r=BigInt(Z.groupBases[t]);(i===0||r===0n)&&(i=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(t)),i===0&&(i=1),r=BigInt(t)**BigInt(i));let s="",o=y(this,Y);for(;o>0n;){let u=o%r;o/=r;let f=a(this,P,xl).call(this,u,t);s=(o>0n?a(this,P,kl).call(this,f,i):f)+s}if(e>0)for(;s.length<e;)s="0"+s;return(y(this,rt)===1?"-":"")+s},Ki=new WeakSet,El=function(t){let e="0";if(t>1)for(;e.length<t;)e="0"+e;return e},kl=function(t,e){let i=e-t.length;return i<=0?t:i<Z.zeros.length?Z.zeros[i]+t:"0".repeat(i)+t},Tl=function(t,e){let i=y(this,Y),r=e?0:t.length-1,s=e?1:-1;for(let o of t){if(i===0n&&r>=0&&r<t.length)t[r]=0;else if(r>=0&&r<t.length)t[r]=Number(i&0xffn);else break;i>>=8n,r+=s}},Lt=function(){return y(this,rt)===1?-y(this,Y):y(this,Y)},ce=function(t){t<0n?(N(this,Y,-t),N(this,rt,1)):(N(this,Y,t),N(this,rt,0)),a(this,P,An).call(this),this.normSign()},Ds=function(t,e,i=!1){let r=e(y(this,Y),y(t,Y)),s=y(this,St);return i&&(s=Math.max(this.length,t.length)),N(this,Y,r),a(this,P,An).call(this),i&&N(this,St,Math.max(y(this,St),s)),this.strip()},ia=function(t,e,i=!1){return a(this,P,st).call(this,y(this,rt)===0&&y(t,rt)===0),a(this,P,Ds).call(this,t,e,i)},Vi=function(t,e){return this.length>=t.length?this.clone()[e](t):t.clone()[e](this)},Au=function(t,e){if(typeof t=="number"){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return BigInt(t)}if(t<0n)throw new Error(`${e} must be a non-negative integer`);return t},Ol=function(t,e,i,r){if(i==="div")return null;let s=t%e;return r===!0&&s<0n&&(s+=e<0n?-e:e),s},Eu=function(t){var i;if(t===null)return null;let e=new Z(0n);return a(i=e,P,ce).call(i,t),e},G(Z,Ki),m(Z,"zeros",["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"]),m(Z,"groupSizes",[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5]),m(Z,"groupBases",[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176]),m(Z,"wordSize",26),G(Z,$s,26n),G(Z,qs,(1n<<26n)-1n),G(Z,ra,BigInt(Number.MAX_SAFE_INTEGER)),G(Z,sa,BigInt(Number.MIN_SAFE_INTEGER)),G(Z,ui,67108863),G(Z,oa,(1n<<53n)-1n),G(Z,Fs,1048576);var T=Z;var Ws=class{constructor(t,e){m(this,"name");m(this,"p");m(this,"k");m(this,"n");m(this,"tmp");this.name=t,this.p=new T(e,16),this.n=this.p.bitLength(),this.k=new T(BigInt(1)).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){let t=new T(BigInt(0)),e=Math.ceil(this.n/T.wordSize);return t.expand(Math.max(1,e)),t}ireduce(t){let e=t,i;do this.split(e,this.tmp),this.imulK(e),e.iadd(this.tmp),i=e.bitLength();while(i>this.n);let r=i<this.n?-1:e.ucmp(this.p);return r===0?e.words=[0]:r>0&&e.isub(this.p),e.strip(),e}split(t,e){t.iushrn(this.n,0,e)}imulK(t){return t.imul(this.k)}};var Vs=class extends Ws{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(t,e){let r=t.words,s=t.length,o=Math.min(s,9),c=Array.from({length:o+(s>9?1:0)},()=>0);for(let g=0;g<o;g++)c[g]=r[g];let u=o;if(s<=9){let g=Array.from({length:u},()=>0);for(let w=0;w<u;++w)g[w]=c[w];e.words=g,t.words=[0];return}let f=r[9];c[u++]=f&4194303;let d=Array.from({length:u},()=>0);for(let g=0;g<u;++g)d[g]=c[g];e.words=d;let l=Array.from({length:Math.max(1,s-9)},()=>0),p=0;for(let g=10;g<s;g++){let w=Math.trunc(r[g]);p<l.length&&(l[p++]=(w&4194303)<<4|f>>>22),f=w}f>>>=22,p<l.length?l[p++]=f:f!==0&&l.length>0;let b=Array.from({length:p},()=>0);for(let g=0;g<p;++g)b[g]=l[g];t.words=b}imulK(t){let e=t.words,i=t.length,r=i+2,s=Array.from({length:r},()=>0);for(let c=0;c<i;c++)s[c]=e[c];let o=0;for(let c=0;c<r;c++){let u=Math.trunc(s[c]);o+=u*977,s[c]=o&67108863,o=u*64+Math.trunc(o/67108864)}return t.words=s,t}};var zi=class{constructor(t){m(this,"prime");m(this,"m");if(t==="k256"){let e=new Vs;this.m=e.p,this.prime=e}else this.assert(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}assert(t,e="Assertion failed"){if(!t)throw new Error(e)}verify1(t){this.assert(t.negative===0,"red works only with positives"),this.assert(t.red,"red works only with red numbers")}verify2(t,e){this.assert((t.negative|e.negative)===0,"red works only with positives"),this.assert(t.red!=null&&t.red===e.red,"red works only with red numbers")}imod(t){return this.prime!=null?this.prime.ireduce(t).forceRed(this):(T.move(t,t.umod(this.m).forceRed(this)),t)}neg(t){return t.isZero()?t.clone():this.m.sub(t).forceRed(this)}add(t,e){this.verify2(t,e);let i=t.clone();return i.iadd(e),i.isub(this.m),i.isNeg()&&i.iadd(this.m),i}iadd(t,e){return this.verify2(t,e),t.iadd(e),t.isub(this.m),t.isNeg()&&t.iadd(this.m),t}sub(t,e){this.verify2(t,e);let i=t.sub(e);return i.cmpn(0)<0&&i.iadd(this.m),i.forceRed(this)}isub(t,e){this.verify2(t,e);let i=t.isub(e);return i.cmpn(0)<0&&i.iadd(this.m),i}shl(t,e){return this.verify1(t),this.imod(t.ushln(e))}imul(t,e){return this.verify2(t,e),this.imod(t.imul(e))}mul(t,e){return this.verify2(t,e),this.imod(t.mul(e))}isqr(t){return this.imul(t,t.clone())}sqr(t){return this.mul(t,t)}sqrt(t){if(t.isZero())return t.clone();let e=this.m.andln(3);if(this.assert(e%2===1),e===3){let g=this.m.add(new T(1)).iushrn(2);return this.pow(t,g)}let i=this.m.subn(1),r=0;for(;!i.isZero()&&i.andln(1)===0;)r++,i.iushrn(1);this.assert(!i.isZero());let s=new T(1).toRed(this),o=s.redNeg(),c=this.m.subn(1).iushrn(1),u=this.m.bitLength(),f=new T(2*u*u).toRed(this);for(;this.pow(f,c).cmp(o)!==0;)f.redIAdd(o);let d=this.pow(f,i),l=this.pow(t,i.addn(1).iushrn(1)),p=this.pow(t,i),b=r;for(;p.cmp(s)!==0;){let g=p,w=0;for(;g.cmp(s)!==0;)g=g.redSqr(),w++;this.assert(w<b);let S=this.pow(d,new T(1).iushln(b-w-1));l=l.redMul(S),d=S.redSqr(),p=p.redMul(d),b=w}return l}invm(t){let e=t._invmp(this.m);return e.negative!==0?(e.negative=0,this.imod(e).redNeg()):this.imod(e)}pow(t,e){if(this.verify1(t),e.isZero())return new T(1).toRed(this);let i=new T(1).toRed(this),r=t.clone(),s=e.bitLength();for(let o=s-1;o>=0;o--)i=this.sqr(i),e.testn(o)&&(i=this.mul(i,r));return i}convertTo(t){let e=t.umod(this.m);return e===t?e.clone():e}convertFrom(t){let e=t.clone();return e.red=null,e}};var Ks=class extends zi{constructor(e){super(e);m(this,"shift");m(this,"r");m(this,"r2");m(this,"rinv");m(this,"minv");this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new T(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}convertTo(e){return this.imod(e.ushln(this.shift))}convertFrom(e){let i=this.imod(e.mul(this.rinv));return i.red=null,i}imul(e,i){if(e.isZero()||i.isZero())return e.words[0]=0,e.length=1,e;let r=e.imul(i),s=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(s).iushrn(this.shift),c=o;return o.cmp(this.m)>=0?c=o.isub(this.m):o.cmpn(0)<0&&(c=o.iadd(this.m)),c.forceRed(this)}mul(e,i){if(e.isZero()||i.isZero())return new T(0).forceRed(this);let r=e.mul(i),s=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(s).iushrn(this.shift),c=o;return o.cmp(this.m)>=0?c=o.isub(this.m):o.cmpn(0)<0&&(c=o.iadd(this.m)),c.forceRed(this)}invm(e){return this.imod(e._invmp(this.m).mul(this.r2)).forceRed(this)}};var yi={};wu(yi,{Reader:()=>to,ReaderUint8Array:()=>mt,Writer:()=>ue,WriterUint8Array:()=>ht,base64ToArray:()=>Ql,constantTimeEquals:()=>L1,encode:()=>ka,fromBase58:()=>ro,fromBase58Check:()=>ao,hexToUint8Array:()=>io,minimallyEncode:()=>Ta,toArray:()=>at,toBase58:()=>so,toBase58Check:()=>oo,toBase64:()=>Se,toHex:()=>nt,toSafeString:()=>O1,toUTF8:()=>th,toUTF8Strict:()=>Rt,toUint8Array:()=>et,verifyNotNull:()=>nr,zero2:()=>P1});var Cm=new TextEncoder;function xe(n){return Cm.encode(n)}function Fe(n){return xe(n).byteLength}function Xi(n){for(let t of n){let e=t.codePointAt(0);if(e<=31||e>=127&&e<=159)return!0}return!1}var Aa={};wu(Aa,{RIPEMD160:()=>js,SHA1:()=>Qi,SHA1HMAC:()=>Nu,SHA256:()=>Pu,SHA256HMAC:()=>qr,SHA512:()=>Ru,SHA512HMAC:()=>la,hash160:()=>Zs,hash256:()=>zt,htonl:()=>Ml,pbkdf2:()=>S1,realHtonl:()=>A1,ripemd160:()=>Mu,sha1:()=>Du,sha256:()=>Te,sha256hmac:()=>Js,sha512:()=>i1,sha512hmac:()=>Hu,swapBytes32:()=>$u,toArray:()=>ya});var Lm=/^[0-9a-fA-F]*$/;function zs(n){if(typeof n!="string")throw new TypeError("Invalid hex string");if(n.length!==0&&!Lm.test(n))throw new Error("Invalid hex string")}function Pl(n){if(zs(n),n.length===0)return"";let t=n.toLowerCase();return t.length%2!==0&&(t="0"+t),t}var ku=(n,t="Hash assertion failed")=>{if(!n)throw new Error(t)},da=class{constructor(t,e,i,r){m(this,"pending",null);m(this,"pendingTotal",0);m(this,"blockSize");m(this,"outSize");m(this,"endian");m(this,"_delta8");m(this,"_delta32");m(this,"padLength");m(this,"hmacStrength");this.blockSize=t,this.outSize=e,this.hmacStrength=i,this.padLength=r/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}_update(t,e){throw new Error("Not implemented")}_digest(){throw new Error("Not implemented")}_digestHex(){throw new Error("Not implemented")}update(t,e){if(t=ya(t,e),this.pending==null?this.pending=t:this.pending=this.pending.concat(t),this.pendingTotal+=t.length,this.pending.length>=this._delta8){t=this.pending;let i=t.length%this._delta8;this.pending=t.slice(t.length-i,t.length),this.pending.length===0&&(this.pending=null),t=Wm(t,0,t.length-i,this.endian);for(let r=0;r<t.length;r+=this._delta32)this._update(t,r)}return this}digest(){return this.update(this._pad()),ku(this.pending===null),this._digest()}digestHex(){return this.update(this._pad()),ku(this.pending===null),this._digestHex()}_pad(){let t=this.pendingTotal;if(!Number.isSafeInteger(t)||t<0)throw new Error("Message too long for this hash function");let e=this._delta8,i=e-(t+this.padLength)%e,r=Array.from({length:i+this.padLength});r[0]=128;let s;for(s=1;s<i;s++)r[s]=0;let o=this.padLength,c=1n<<BigInt(o*8),u=BigInt(t)*8n;if(u>=c)throw new Error("Message too long for this hash function");if(this.endian==="big"){let f=Array.from({length:o});for(let d=o-1;d>=0;d--)f[d]=Number(u&0xffn),u>>=8n;for(let d=0;d<o;d++)r[s++]=f[d]}else for(let f=0;f<o;f++)r[s++]=Number(u&0xffn),u>>=8n;return r}};function Um(n,t,e){let i=n.codePointAt(t);return i<128?(e.push(i),t):i<2048?(e.push(i>>6|192,i&63|128),t):i>65535?(e.push(i>>18|240,i>>12&63|128,i>>6&63|128,i&63|128),t+1):(e.push(i>>12|224,i>>6&63|128,i&63|128),t)}function Mm(n){let t=[],e=0;for(;e<n.length;)e=Um(n,e,t)+1;return t}function Dm(n){zs(n);let t=Pl(n),e=[];for(let i=0;i<t.length;i+=2)e.push(Number.parseInt(t[i]+t[i+1],16));return e}function Hm(n){let t=[];for(let e=0;e<n.length;e++)t[e]=Math.trunc(n[e]);return t}function ya(n,t){return Array.isArray(n)?n.slice():n?typeof n=="string"?t==="hex"?Dm(n):Mm(n):Hm(n):[]}function Ml(n){return $u(n)}function Dl(n,t){let e="";for(let i of n)t==="little"&&(i=Ml(i)),e+=$m(i.toString(16));return e}function $m(n){return n.length===7?"0"+n:n.length===6?"00"+n:n.length===5?"000"+n:n.length===4?"0000"+n:n.length===3?"00000"+n:n.length===2?"000000"+n:n.length===1?"0000000"+n:n}var Tu=typeof globalThis>"u"?void 0:globalThis.Buffer,qm=Tu!=null&&typeof Tu.from=="function",Rl="0123456789abcdef",Ou=Array.from({length:256});for(let n=0;n<Ou.length;n++)Ou[n]=Rl[n>>4&15]+Rl[n&15];function Fm(n){if(qm)return Tu.from(n).toString("hex");let t=Array.from({length:n.length});for(let e=0;e<n.length;e++)t[e]=Ou[n[e]];return t.join("")}var Bu=(()=>{let n=typeof globalThis>"u"?void 0:globalThis.process,t=n?.getBuiltinModule;if(typeof t=="function")try{let e=t.call(n,"node:crypto");if(e!=null)return e}catch{}})();function en(n,t){return n instanceof Uint8Array?n:Array.isArray(n)?new Uint8Array(n):Uint8Array.from(ya(n,t))}function _u(n){return typeof n=="string"?en(n,"hex"):en(n)}function wa(n,t,e){n!=null?n.update(e):t?.update(e)}function xa(n,t){return n!=null?Array.from(n.digest()):t!=null?Array.from(t.digest()):[]}function Ia(n,t){return n!=null?n.digest("hex"):t!=null?Fm(t.digest()):""}function Cu(n){let t=Bu?.createHash;if(typeof t=="function")try{return t(n)}catch{return}}function Lu(n,t){let e=Bu?.createHmac;if(typeof e=="function")try{return e(n,t)}catch{return}}function Uu(n,t,e){let i=Cu(n);if(i!=null)return i.update(en(t,e)),i.digest()}function Hl(n,t,e,i){let r=Lu(n,_u(t));if(r!=null)return r.update(en(e,i)),r.digest()}function Wm(n,t,e,i){let r=e-t;ku(r%4===0);let s=Array.from({length:r/4});for(let o=0,c=t;o<s.length;o++,c+=4){let u;i==="big"?u=n[c]<<24|n[c+1]<<16|n[c+2]<<8|n[c+3]:u=n[c+3]<<24|n[c+2]<<16|n[c+1]<<8|n[c],s[o]=u>>>0}return s}function $l(n,t){let e=Array.from({length:n.length*4});for(let i=0,r=0;i<n.length;i++,r+=4){let s=n[i];t==="big"?(e[r]=s>>>24,e[r+1]=s>>>16&255,e[r+2]=s>>>8&255,e[r+3]=s&255):(e[r+3]=s>>>24,e[r+2]=s>>>16&255,e[r+1]=s>>>8&255,e[r]=s&255)}return e}function En(n,t){return n>>>t|n<<32-t}function ji(n,t){return n<<t|n>>>32-t}function Yt(n,t){return n+t>>>0}function Xs(n,t,e){return n+t+e>>>0}function Nl(n,t,e,i){return n+t+e+i>>>0}function ql(n,t,e,i,r){return n+t+e+i+r>>>0}function Vm(n,t,e,i){return n===0?Fl(t,e,i):n===1||n===3?Km(t,e,i):n===2?Wl(t,e,i):0}function Fl(n,t,e){return n&t^~n&e}function Wl(n,t,e){return n&t^n&e^t&e}function Km(n,t,e){return n^t^e}function zm(n){return En(n,2)^En(n,13)^En(n,22)}function Xm(n){return En(n,6)^En(n,11)^En(n,25)}function jm(n){return En(n,7)^En(n,18)^n>>>3}function Gm(n){return En(n,17)^En(n,19)^n>>>10}var Ym=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],Zm=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],Jm=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],Qm=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11];function Bl(n,t,e,i){return n<=15?t^e^i:n<=31?t&e|~t&i:n<=47?(t|~e)^i:n<=63?t&i|e&~i:t^(e|~i)}function t1(n){return n<=15?0:n<=31?1518500249:n<=47?1859775393:n<=63?2400959708:2840853838}function e1(n){return n<=15?1352829926:n<=31?1548603684:n<=47?1836072691:n<=63?2053994217:0}var js=class extends da{constructor(){super(512,160,192,64);m(this,"h");this.endian="little",this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}_update(e,i){let r=this.h[0],s=this.h[1],o=this.h[2],c=this.h[3],u=this.h[4],f=r,d=s,l=o,p=c,b=u,g;for(let w=0;w<80;w++)g=Yt(ji(Nl(r,Bl(w,s,o,c),e[Ym[w]+i],t1(w)),Jm[w]),u),r=u,u=c,c=ji(o,10),o=s,s=g,g=Yt(ji(Nl(f,Bl(79-w,d,l,p),e[Zm[w]+i],e1(w)),Qm[w]),b),f=b,b=p,p=ji(l,10),l=d,d=g;g=Xs(this.h[1],o,p),this.h[1]=Xs(this.h[2],c,b),this.h[2]=Xs(this.h[3],u,f),this.h[3]=Xs(this.h[4],r,d),this.h[4]=Xs(this.h[0],s,l),this.h[0]=g}_digest(){return $l(this.h,"little")}_digestHex(){return Dl(this.h,"little")}},Gi,pi,Pu=class{constructor(){G(this,Gi);G(this,pi);N(this,pi,Cu("sha256")),y(this,pi)==null&&N(this,Gi,new Gs)}update(t,e){return wa(y(this,pi),y(this,Gi),en(t,e)),this}digest(){return xa(y(this,pi),y(this,Gi))}digestHex(){return Ia(y(this,pi),y(this,Gi))}};Gi=new WeakMap,pi=new WeakMap;var Qi=class extends da{constructor(){super(512,160,80,64);m(this,"h");m(this,"W");m(this,"k");this.k=[1518500249,1859775393,2400959708,3395469782],this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=Array.from({length:80})}_update(e,i){let r=this.W;i??(i=0);let s;for(s=0;s<16;s++)r[s]=e[i+s];for(;s<r.length;s++)r[s]=ji(r[s-3]^r[s-8]^r[s-14]^r[s-16],1);let o=this.h[0],c=this.h[1],u=this.h[2],f=this.h[3],d=this.h[4];for(s=0;s<r.length;s++){let l=Math.trunc(s/20),p=ql(ji(o,5),Vm(l,c,u,f),d,r[s],this.k[l]);d=f,f=u,u=ji(c,30),c=o,o=p}this.h[0]=Yt(this.h[0],o),this.h[1]=Yt(this.h[1],c),this.h[2]=Yt(this.h[2],u),this.h[3]=Yt(this.h[3],f),this.h[4]=Yt(this.h[4],d)}_digest(){return $l(this.h,"big")}_digestHex(){return Dl(this.h,"big")}},Yi,gi,Ru=class{constructor(){G(this,Yi);G(this,gi);N(this,gi,Cu("sha512")),y(this,gi)==null&&N(this,Yi,new Ys)}update(t,e){return wa(y(this,gi),y(this,Yi),en(t,e)),this}digest(){return xa(y(this,gi),y(this,Yi))}digestHex(){return Ia(y(this,gi),y(this,Yi))}};Yi=new WeakMap,gi=new WeakMap;var Zi,bi,qr=class{constructor(t){G(this,Zi);G(this,bi);m(this,"blockSize",64);m(this,"outSize",32);let e=_u(t);N(this,bi,Lu("sha256",e)),y(this,bi)==null&&N(this,Zi,new Fr(m1,e))}update(t,e){return wa(y(this,bi),y(this,Zi),en(t,e)),this}digest(){return xa(y(this,bi),y(this,Zi))}digestHex(){return Ia(y(this,bi),y(this,Zi))}};Zi=new WeakMap,bi=new WeakMap;var Nu=class{constructor(t){m(this,"inner");m(this,"outer");m(this,"blockSize",64);t=ya(t,"hex"),t.length>this.blockSize&&(t=new Qi().update(t).digest());let e;for(e=t.length;e<this.blockSize;e++)t.push(0);for(e=0;e<t.length;e++)t[e]^=54;for(this.inner=new Qi().update(t),e=0;e<t.length;e++)t[e]^=106;this.outer=new Qi().update(t)}update(t,e){return this.inner.update(t,e),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}},Ji,mi,la=class{constructor(t){G(this,Ji);G(this,mi);m(this,"blockSize",128);m(this,"outSize",32);let e=_u(t);N(this,mi,Lu("sha512",e)),y(this,mi)==null&&N(this,Ji,new Fr(jl,e))}update(t,e){return wa(y(this,mi),y(this,Ji),en(t,e)),this}digest(){return xa(y(this,mi),y(this,Ji))}digestHex(){return Ia(y(this,mi),y(this,Ji))}};Ji=new WeakMap,mi=new WeakMap;function ha(n,t){let e=Uu("sha256",n,t);return e??new Gs().update(en(n,t)).digest()}function n1(n,t){let e=Uu("sha512",n,t);return e??new Ys().update(en(n,t)).digest()}function Vl(n,t){return Uu("ripemd160",n,t)}var Mu=(n,t)=>{let e=Vl(n,t);return e!=null?Array.from(e):new js().update(n,t).digest()},Du=(n,t)=>new Qi().update(n,t).digest(),Te=(n,t)=>Array.from(ha(n,t)),i1=(n,t)=>Array.from(n1(n,t)),zt=(n,t)=>Array.from(ha(ha(n,t))),Zs=(n,t)=>{let e=ha(n,t),i=Vl(e);return i!=null?Array.from(i):new js().update(e).digest()},Js=(n,t,e)=>{let i=Hl("sha256",n,t,e);return i!=null?Array.from(i):new qr(n).update(t,e).digest()},Hu=(n,t,e)=>{let i=Hl("sha512",n,t,e);return i!=null?Array.from(i):new la(n).update(t,e).digest()};function r1(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function pa(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`positive integer expected, got ${n}`)}function Sa(n,...t){if(!r1(n))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(n.length)){let e=t.join(",");throw new Error(`Uint8Array expected of length ${e}, got length=${n.length}`)}}function Kl(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("Hash should be wrapped by utils.createHasher");pa(n.outputLen),pa(n.blockLen)}function ga(n,t=!0){if(n.destroyed===!0)throw new Error("Hash instance has been destroyed");if(t&&n.finished===!0)throw new Error("Hash#digest() has already been called")}function s1(n,t){Sa(n);let e=t.outputLen;if(n.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}function tr(...n){for(let t of n)t.fill(0)}function fa(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function va(n){return typeof n=="string"&&(n=o1(n)),Sa(n),n}function o1(n){if(typeof n!="string")throw new Error("string expected");return xe(n)}var _l=va,ba=class{};function zl(n){let t=i=>n().update(va(i)).digest(),e=n();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>n(),t}var aa=BigInt(2**32-1),Cl=BigInt(32);function a1(n,t=!1){return t?{h:Number(n&aa),l:Number(n>>Cl&aa)}:{h:Number(n>>Cl&aa)|0,l:Number(n&aa)|0}}function c1(n,t=!1){let e=n.length,i=new Uint32Array(e),r=new Uint32Array(e);for(let s=0;s<e;s++){let{h:o,l:c}=a1(n[s],t);i[s]=o,r[s]=c}return[i,r]}var Ll=(n,t,e)=>n>>>e,Ul=(n,t,e)=>n<<32-e|t>>>e,Hr=(n,t,e)=>n>>>e|t<<32-e,$r=(n,t,e)=>n<<32-e|t>>>e,ca=(n,t,e)=>n<<64-e|t>>>e-32,ua=(n,t,e)=>n>>>e-32|t<<64-e;function Fn(n,t,e,i){let r=(t>>>0)+(i>>>0);return{h:n+e+(r/2**32|0)|0,l:r|0}}var u1=(n,t,e)=>(n>>>0)+(t>>>0)+(e>>>0),f1=(n,t,e,i)=>Math.trunc(t+e+i+Math.trunc(n/2**32)),d1=(n,t,e,i)=>(n>>>0)+(t>>>0)+(e>>>0)+(i>>>0),l1=(n,t,e,i,r)=>Math.trunc(t+e+i+r+Math.trunc(n/2**32)),h1=(n,t,e,i,r)=>(n>>>0)+(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0),p1=(n,t,e,i,r,s)=>t+e+i+r+s+(n/2**32|0)|0,ma=class extends ba{constructor(e,i,r,s){super();m(this,"blockLen");m(this,"outputLen");m(this,"padOffset");m(this,"isLE");m(this,"buffer");m(this,"view");m(this,"finished",!1);m(this,"length",0);m(this,"pos",0);m(this,"destroyed",!1);this.blockLen=e,this.outputLen=i,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=fa(this.buffer)}update(e){ga(this),e=va(e),Sa(e);let{view:i,buffer:r,blockLen:s}=this,o=e.length;for(let c=0;c<o;){let u=Math.min(s-this.pos,o-c);if(u===s){let f=fa(e);for(;s<=o-c;c+=s)this.process(f,c);continue}r.set(e.subarray(c,c+u),this.pos),this.pos+=u,c+=u,this.pos===s&&(this.process(i,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ga(this),s1(e,this),this.finished=!0;let{buffer:i,view:r,blockLen:s,isLE:o}=this,{pos:c}=this;i[c++]=128,tr(this.buffer.subarray(c)),this.padOffset>s-c&&(this.process(r,0),c=0);for(let p=c;p<s;p++)i[p]=0;g1(r,s-8,BigInt(this.length*8),o),this.process(r,0);let u=fa(e),f=this.outputLen;if(f%4!==0)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=f/4,l=this.get();if(d>l.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<d;p++)u.setUint32(4*p,l[p],o)}digest(){let{buffer:e,outputLen:i}=this;this.digestInto(e);let r=e.slice(0,i);return this.destroy(),r}_cloneInto(e){e??(e=new this.constructor),e.set(...this.get());let{blockLen:i,buffer:r,length:s,finished:o,destroyed:c,pos:u}=this;return e.destroyed=c,e.finished=o,e.length=s,e.pos=u,s%i!==0&&e.buffer.set(r),e}clone(){return this._cloneInto()}};function g1(n,t,e,i){if(typeof n.setBigUint64=="function")return n.setBigUint64(t,e,i);let r=BigInt(32),s=BigInt(4294967295),o=Number(e>>r&s),c=Number(e&s),u=i?4:0,f=i?0:4;n.setUint32(t+u,o,i),n.setUint32(t+f,c,i)}var fi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),b1=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),di=new Uint32Array(64),Gs=class extends ma{constructor(e=32){super(64,e,8,!1);m(this,"A",fi[0]|0);m(this,"B",fi[1]|0);m(this,"C",fi[2]|0);m(this,"D",fi[3]|0);m(this,"E",fi[4]|0);m(this,"F",fi[5]|0);m(this,"G",fi[6]|0);m(this,"H",fi[7]|0)}get(){let{A:e,B:i,C:r,D:s,E:o,F:c,G:u,H:f}=this;return[e,i,r,s,o,c,u,f]}set(...[e,i,r,s,o,c,u,f]){this.A=e|0,this.B=i|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=c|0,this.G=u|0,this.H=f|0}process(e,i){for(let p=0;p<16;p++,i+=4)di[p]=e.getUint32(i);for(let p=16;p<64;p++){let b=di[p-15],g=di[p-2],w=jm(b),S=Gm(g);di[p]=Yt(Yt(w,di[p-7]),Yt(S,di[p-16]))}let{A:r,B:s,C:o,D:c,E:u,F:f,G:d,H:l}=this;for(let p=0;p<64;p++){let b=ql(l,Xm(u),Fl(u,f,d),b1[p],di[p]),g=Yt(zm(r),Wl(r,s,o));l=d,d=f,f=u,u=Yt(c,b),c=o,o=s,s=r,r=Yt(b,g)}this.A=Yt(this.A,r),this.B=Yt(this.B,s),this.C=Yt(this.C,o),this.D=Yt(this.D,c),this.E=Yt(this.E,u),this.F=Yt(this.F,f),this.G=Yt(this.G,d),this.H=Yt(this.H,l)}roundClean(){tr(di)}destroy(){tr(this.buffer),this.set(0,0,0,0,0,0,0,0)}},m1=zl(()=>new Gs),Ie=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Xl=c1(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(BigInt)),y1=Xl[0],w1=Xl[1],li=new Uint32Array(80),hi=new Uint32Array(80),Ys=class extends ma{constructor(e=64){super(128,e,16,!1);m(this,"Ah",Ie[0]|0);m(this,"Al",Ie[1]|0);m(this,"Bh",Ie[2]|0);m(this,"Bl",Ie[3]|0);m(this,"Ch",Ie[4]|0);m(this,"Cl",Ie[5]|0);m(this,"Dh",Ie[6]|0);m(this,"Dl",Ie[7]|0);m(this,"Eh",Ie[8]|0);m(this,"El",Ie[9]|0);m(this,"Fh",Ie[10]|0);m(this,"Fl",Ie[11]|0);m(this,"Gh",Ie[12]|0);m(this,"Gl",Ie[13]|0);m(this,"Hh",Ie[14]|0);m(this,"Hl",Ie[15]|0)}get(){let{Ah:e,Al:i,Bh:r,Bl:s,Ch:o,Cl:c,Dh:u,Dl:f,Eh:d,El:l,Fh:p,Fl:b,Gh:g,Gl:w,Hh:S,Hl:C}=this;return[e,i,r,s,o,c,u,f,d,l,p,b,g,w,S,C]}set(...[e,i,r,s,o,c,u,f,d,l,p,b,g,w,S,C]){this.Ah=e|0,this.Al=i|0,this.Bh=r|0,this.Bl=s|0,this.Ch=o|0,this.Cl=c|0,this.Dh=u|0,this.Dl=f|0,this.Eh=d|0,this.El=l|0,this.Fh=p|0,this.Fl=b|0,this.Gh=g|0,this.Gl=w|0,this.Hh=S|0,this.Hl=C|0}process(e,i){for(let k=0;k<16;k++,i+=8)li[k]=e.getUint32(i),hi[k]=e.getUint32(i+4);for(let k=16;k<80;k++){let B=li[k-15]|0,_=hi[k-15]|0,$=Hr(B,_,1)^Hr(B,_,8)^Ll(B,_,7),R=$r(B,_,1)^$r(B,_,8)^Ul(B,_,7),I=li[k-2]|0,U=hi[k-2]|0,M=Hr(I,U,19)^ca(I,U,61)^Ll(I,U,6),F=$r(I,U,19)^ua(I,U,61)^Ul(I,U,6),it=d1(R,F,hi[k-7],hi[k-16]),ot=l1(it,$,M,li[k-7],li[k-16]);li[k]=ot|0,hi[k]=it|0}let{Ah:r,Al:s,Bh:o,Bl:c,Ch:u,Cl:f,Dh:d,Dl:l,Eh:p,El:b,Fh:g,Fl:w,Gh:S,Gl:C,Hh:E,Hl:A}=this;for(let k=0;k<80;k++){let B=Hr(p,b,14)^Hr(p,b,18)^ca(p,b,41),_=$r(p,b,14)^$r(p,b,18)^ua(p,b,41),$=p&g^~p&S,R=b&w^~b&C,I=h1(A,_,R,w1[k],hi[k]),U=p1(I,E,B,$,y1[k],li[k]),M=I|0,F=Hr(r,s,28)^ca(r,s,34)^ca(r,s,39),it=$r(r,s,28)^ua(r,s,34)^ua(r,s,39),ot=r&o^r&u^o&u,q=s&c^s&f^c&f;E=S|0,A=C|0,S=g|0,C=w|0,g=p|0,w=b|0,{h:p,l:b}=Fn(d|0,l|0,U|0,M|0),d=u|0,l=f|0,u=o|0,f=c|0,o=r|0,c=s|0;let z=u1(it,q,M);r=f1(z,F,ot,U),s=z|0}({h:r,l:s}=Fn(r,s,this.Ah,this.Al)),{h:o,l:c}=Fn(o,c,this.Bh,this.Bl),{h:u,l:f}=Fn(u,f,this.Ch,this.Cl),{h:d,l}=Fn(d,l,this.Dh,this.Dl),{h:p,l:b}=Fn(p,b,this.Eh,this.El),{h:g,l:w}=Fn(g,w,this.Fh,this.Fl),{h:S,l:C}=Fn(S,C,this.Gh,this.Gl),{h:E,l:A}=Fn(E,A,this.Hh,this.Hl),this.set(r,s,o,c,u,f,d,l,p,b,g,w,S,C,E,A)}roundClean(){tr(li,hi)}destroy(){tr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},jl=zl(()=>new Ys),Fr=class extends ba{constructor(e,i){super();m(this,"oHash");m(this,"iHash");m(this,"blockLen");m(this,"outputLen");m(this,"finished",!1);m(this,"destroyed",!1);Kl(e);let r=va(i);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new TypeError("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let c=0;c<o.length;c++)o[c]^=54;this.iHash.update(o),this.oHash=e.create();for(let c=0;c<o.length;c++)o[c]^=106;this.oHash.update(o),tr(o)}update(e){return ga(this),this.iHash.update(e),this}digestInto(e){ga(this),Sa(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e??(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:i,iHash:r,finished:s,destroyed:o,blockLen:c,outputLen:u}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=c,e.outputLen=u,e.oHash=i._cloneInto(e.oHash??void 0),e.iHash=r._cloneInto(e.iHash??void 0),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};function x1(n,t,e,i){Kl(n);let{c:r,dkLen:s=32}={...i};if(pa(r),pa(s),r<1)throw new Error("iterations (c) should be >= 1");let o=_l(t),c=_l(e),u=new Uint8Array(s),f=Gl.create(n,o),d=f._cloneInto().update(c),l,p=new Uint8Array(4),b=fa(p),g=new Uint8Array(f.outputLen);for(let w=1,S=0;S<s;w++,S+=f.outputLen){let C=u.subarray(S,S+f.outputLen);b.setInt32(0,w,!1),l=d._cloneInto(l),l.update(p).digestInto(g),C.set(g.subarray(0,C.length));for(let E=1;E<r;E++){f._cloneInto(l).update(g).digestInto(g);for(let A=0;A<C.length;A++)C[A]^=g[A]}}return f.destroy(),d.destroy(),l?.destroy(),tr(g),u}var Gl=(n,t,e)=>new Fr(n,t).update(e).digest();Gl.create=(n,t)=>new Fr(n,t);function I1(n,t,e,i){return x1(jl,n,t,{c:e,dkLen:i})}function S1(n,t,e,i,r="sha512"){if(r!=="sha512")throw new Error("Only sha512 is supported in this PBKDF2 implementation");let s=Bu?.pbkdf2Sync;if(typeof s=="function"){let f=s(en(n),en(t),e,i,r);return Array.from(f)}let o=Uint8Array.from(n),c=Uint8Array.from(t),u=I1(o,c,e,i);return Array.from(u)}function $u(n){return(n>>>24|n>>>8&65280|n<<8&16711680|(n&255)<<24)>>>0}var v1=(()=>{let n=new ArrayBuffer(4),t=new Uint32Array(n),e=new Uint8Array(n);return t[0]=16909060,e[0]===4})();function A1(n){return v1?$u(n):n>>>0}var E1=new T(4294967295),k1=new T(2).pow(new T(64)).sub(new T(1)),T1=new T(Number.MAX_SAFE_INTEGER);function Qs(n,t=!0){let e=n.readUInt8();if(e<253)return e;if(e===253){let r=n.readUInt16LE();if(r<253)throw new Error("non-canonical varInt");return r}if(e===254){let r=n.readUInt32LE();if(r<=65535)throw new Error("non-canonical varInt");return r}let i=n.readUInt64LEBn();if(i.lte(E1))throw new Error("non-canonical varInt");if(t&&i.eq(k1))return-1;if(i.gt(T1))throw new Error("number too large to retain precision - use readVarIntBn");return i.toNumber()}var Wt,Tt,er,ln,Wn,ht=class{constructor(t,e=256){G(this,ln);G(this,Wt);G(this,Tt);G(this,er);if(!Number.isSafeInteger(e)||e<0)throw new RangeError("WriterUint8Array initial capacity must be a non-negative safe integer");if(t!=null&&t.length>0){let i=t.reduce((r,s)=>r+s.length,0);e=Math.max(e,i)}if(e=Math.max(1,e),N(this,Wt,new Uint8Array(e)),N(this,Tt,0),N(this,er,e),t!=null)for(let i of t)this.write(i)}getLength(){return y(this,Tt)}toUint8Array(){return y(this,Wt).slice(0,y(this,Tt))}toArray(){return Array.from(this.toUint8Array())}toUint8ArrayZeroCopy(){return y(this,Wt).subarray(0,y(this,Tt))}reserve(t){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("WriterUint8Array reserve requires a non-negative safe integer");a(this,ln,Wn).call(this,t)}write(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);return a(this,ln,Wn).call(this,e.length),y(this,Wt).set(e,y(this,Tt)),N(this,Tt,y(this,Tt)+e.length),this}writeReverse(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);a(this,ln,Wn).call(this,e.length);for(let i=e.length-1;i>=0;i--)y(this,Wt)[y(this,Tt)]=e[i],N(this,Tt,y(this,Tt)+1);return this}writeUInt8(t){return a(this,ln,Wn).call(this,1),y(this,Wt)[y(this,Tt)]=t&255,N(this,Tt,y(this,Tt)+1),this}writeInt8(t){return this.writeUInt8(t),this}writeUInt16LE(t){return a(this,ln,Wn).call(this,2),y(this,Wt)[y(this,Tt)]=t&255,y(this,Wt)[y(this,Tt)+1]=t>>8&255,N(this,Tt,y(this,Tt)+2),this}writeUInt16BE(t){return a(this,ln,Wn).call(this,2),y(this,Wt)[y(this,Tt)]=t>>8&255,y(this,Wt)[y(this,Tt)+1]=t&255,N(this,Tt,y(this,Tt)+2),this}writeInt16LE(t){return this.writeUInt16LE(t&65535),this}writeInt16BE(t){return this.writeUInt16BE(t&65535),this}writeUInt32LE(t){return a(this,ln,Wn).call(this,4),y(this,Wt)[y(this,Tt)]=t&255,y(this,Wt)[y(this,Tt)+1]=t>>8&255,y(this,Wt)[y(this,Tt)+2]=t>>16&255,y(this,Wt)[y(this,Tt)+3]=t>>24&255,N(this,Tt,y(this,Tt)+4),this}writeUInt32BE(t){return a(this,ln,Wn).call(this,4),y(this,Wt)[y(this,Tt)]=t>>24&255,y(this,Wt)[y(this,Tt)+1]=t>>16&255,y(this,Wt)[y(this,Tt)+2]=t>>8&255,y(this,Wt)[y(this,Tt)+3]=t&255,N(this,Tt,y(this,Tt)+4),this}writeInt32LE(t){return this.writeUInt32LE(t>>>0),this}writeInt32BE(t){return this.writeUInt32BE(t>>>0),this}writeUInt64BEBn(t){let e=t.toArray("be",8);return this.write(e),this}writeUInt64LEBn(t){let e=t.toArray("be",8);return this.writeReverse(e),this}writeUInt64LE(t){let e=new T(t).toArray("be",8);return this.writeReverse(e),this}writeVarIntNum(t){let e=ue.varIntNum(t);return this.write(e),this}writeVarIntBn(t){let e=ue.varIntBn(t);return this.write(e),this}reset(){N(this,Tt,0)}};Wt=new WeakMap,Tt=new WeakMap,er=new WeakMap,ln=new WeakSet,Wn=function(t){if(y(this,Tt)+t>y(this,er)){let e=y(this,er)*2;for(;y(this,Tt)+t>e;)e*=2;let i=new Uint8Array(e);i.set(y(this,Wt)),N(this,Wt,i),N(this,er,e)}};var pn,We,hn,qu=class qu{constructor(t=new Uint8Array(0),e=0){G(this,We);m(this,"bin");m(this,"pos");G(this,pn);if(t instanceof Uint8Array)this.bin=t;else if(Array.isArray(t))this.bin=new Uint8Array(t);else throw new TypeError("ReaderUint8Array constructor: bin must be Uint8Array or number[]");if(N(this,pn,this.bin.length),!Number.isSafeInteger(e)||e<0||e>y(this,pn))throw new RangeError("ReaderUint8Array position exceeds available data");this.pos=e}static makeReader(t,e=0){if(t instanceof Uint8Array)return new qu(t,e);if(Array.isArray(t))return new to(t,e);throw new Error("ReaderUint8Array.makeReader: bin must be Uint8Array or number[]")}eof(){return this.pos>=y(this,pn)}read(t=y(this,pn)-this.pos){a(this,We,hn).call(this,t);let e=this.pos,i=this.pos+t;return this.pos=i,this.bin.slice(e,i)}readView(t=y(this,pn)-this.pos){a(this,We,hn).call(this,t);let e=this.pos;return this.pos+=t,this.bin.subarray(e,this.pos)}skip(t){a(this,We,hn).call(this,t),this.pos+=t}remaining(){return y(this,pn)-this.pos}readReverse(t=y(this,pn)-this.pos){a(this,We,hn).call(this,t);let e=new Uint8Array(t);for(let i=0;i<t;i++)e[i]=this.bin[this.pos+t-1-i];return this.pos+=t,e}readUInt8(){a(this,We,hn).call(this,1);let t=this.bin[this.pos];return this.pos+=1,t}readInt8(){let t=this.readUInt8();return(t&128)===0?t:t-256}readUInt16BE(){a(this,We,hn).call(this,2);let t=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,t}readInt16BE(){let t=this.readUInt16BE();return(t&32768)===0?t:t-65536}readUInt16LE(){a(this,We,hn).call(this,2);let t=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,t}readInt16LE(){let t=this.readUInt16LE();return(t&32768)===0?t:t-65536}readUInt32BE(){a(this,We,hn).call(this,4);let t=this.bin[this.pos]*16777216+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,t}readInt32BE(){let t=this.readUInt32BE();return(t&2147483648)===0?t:t-4294967296}readUInt32LE(){a(this,We,hn).call(this,4);let t=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,t}readInt32LE(){let t=this.readUInt32LE();return(t&2147483648)===0?t:t-4294967296}readUInt64BEBn(){a(this,We,hn).call(this,8);let t=Array.from(this.bin.slice(this.pos,this.pos+8)),e=new T(t);return this.pos=this.pos+8,e}readUInt64LEBn(){let t=Array.from(this.readReverse(8));return new T(t)}readInt64LEBn(){let t=new T(2).pow(new T(63)),e=new T(2).pow(new T(64)),i=Array.from(this.readReverse(8)),r=new T(i);return r.gte(t)&&(r=r.sub(e)),r}readVarIntNum(t=!0){let e=this.readUInt8(),i;switch(e){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(i=t?this.readInt64LEBn():this.readUInt64LEBn(),i.lte(new T(2).pow(new T(53))))return i.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return e}}readVarIntNumStrict(t=!0){return Qs(this,t)}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){let t=this.readUInt8();switch(t){case 253:return new T(this.readUInt16LE());case 254:return new T(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new T(t)}}};pn=new WeakMap,We=new WeakSet,hn=function(t){if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(this.pos)||this.pos<0||this.pos+t>y(this,pn))throw new RangeError("ReaderUint8Array read exceeds available data")};var mt=qu;var Ea=globalThis.Buffer,Zl=Ea!=null&&typeof Ea.from=="function",O1=(n,t="Unknown value")=>{if(n===null)return"null";if(n===void 0)return"undefined";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="bigint")return n.toString();if(typeof n=="boolean")return n?"true":"false";if(typeof n=="symbol")return n.description??n.toString();if(n instanceof Error&&n.message.length>0)return n.message;let e=n.message;if(typeof e=="string"&&e.length>0)return e;try{return JSON.stringify(n)??t}catch{return t}},P1=n=>n.length%2===1?"0"+n:n,Yl="0123456789abcdef",Jl=Array.from({length:256},()=>"");for(let n=0;n<256;n++)Jl[n]=Yl[n>>4&15]+Yl[n&15];var nt=n=>Zl?Ea.from(n).toString("hex"):n.length===0?"":Array.from(n,t=>Jl[t&255]).join(""),et=(n,t)=>n instanceof Uint8Array?n:typeof n=="string"&&t==="hex"?io(n):new Uint8Array(at(n,t)),at=(n,t)=>{if(Array.isArray(n))return n.slice();if(n===void 0)return[];if(typeof n!="string")return Array.from(n,e=>Math.trunc(e));switch(t){case"hex":return R1(n);case"base64":return Ql(n);default:return _1(n)}},no=new Int8Array(256).fill(-1);for(let n=0;n<10;n++)no[48+n]=n;for(let n=0;n<6;n++)no[65+n]=10+n,no[97+n]=10+n;var R1=n=>Array.from(io(n)),io=n=>{zs(n);let t=n.length%2===0?n:"0"+n;if(Zl){let r=Ea.from(t,"hex");return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let e=new Uint8Array(t.length/2),i=0;for(let r=0;r<t.length;r+=2){let s=no[t.codePointAt(r)],o=no[t.codePointAt(r+1)];e[i++]=s<<4|o}return e},N1=n=>{if(typeof n!="string")throw new TypeError("msg must be a string");let t=n.trim().replaceAll(/[\r\n\t\f\v ]+/g,"").replaceAll("-","+").replaceAll("_","/"),e=t.indexOf("=");if(e===-1)return t;let i=t.slice(e);if(!/^={1,2}$/.test(i)||t.slice(0,e).includes("="))throw new Error("Invalid base64 padding");return t.slice(0,e)},B1=(n,t)=>{if(n>=65&&n<=90)return n-65;if(n>=97&&n<=122)return n-97+26;if(n>=48&&n<=57)return n-48+52;if(n===43)return 62;if(n===47)return 63;throw new Error(`Invalid base64 character at index ${t}`)};function Ql(n){let t=N1(n),e=[],i=0,r=0;for(let s=0;s<t.length;s++){let o=t.codePointAt(s),c=B1(o,s);for(i=i<<6|c,r+=6;r>=8;)r-=8,e.push(i>>r&255),i&=(1<<r)-1}return e}function _1(n){return Array.from(xe(n))}var th=n=>new TextDecoder().decode(n instanceof Uint8Array?n:new Uint8Array(n)),Rt=n=>new TextDecoder("utf-8",{fatal:!0}).decode(n instanceof Uint8Array?n:new Uint8Array(n)),ka=(n,t)=>{switch(t){case"hex":return nt(n);case"utf8":return th(n);default:return n}};function Se(n){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e="",i;for(i=0;i<n.length;i+=3){let r=n[i],s=i+1<n.length?n[i+1]:0,o=i+2<n.length?n[i+2]:0,c=r>>2,u=(r&3)<<4|s>>4,f=(s&15)<<2|o>>6,d=o&63;e+=t.charAt(c)+t.charAt(u),e+=i+1<n.length?t.charAt(f):"=",e+=i+2<n.length?t.charAt(d):"="}return e}var eo="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ro=n=>{if(n===""||typeof n!="string")throw new Error(`Expected base58 string but got \u201C${n}\u201D`);let t=n.match(/[^1-9A-HJ-NP-Za-km-z]/gmu);if(t!==null)throw new Error(`Invalid base58 character \u201C${t.join("")}\u201D`);let e=n.match(/^1+/gmu),i=e===null?0:e[0].length,r=(n.length-i)*(Math.log(58)/Math.log(256))+1>>>0;return[...new Uint8Array([...new Uint8Array(i),...Array.from(n).map(o=>eo.indexOf(o)).reduce((o,c)=>(o=o.map(u=>{let f=u*58+c;return c=f>>8,f}),o),new Uint8Array(r)).reverse().filter((o=>c=>o=o||c)(!1))])]},so=n=>{let t=Array.from({length:256},()=>-1);for(let i=0;i<eo.length;++i)t[eo.codePointAt(i)]=i;let e=[];for(let i of n){let r=i;for(let s=0;s<e.length;++s){let o=(t[e[s]]<<8)+r,c=Math.trunc(o/58),u=o-c*58;e[s]=eo.codePointAt(u),r=c}for(;r!==0;){let s=Math.trunc(r/58),o=r-s*58;e.push(eo.codePointAt(o)),r=s}}for(let i of n)if(i===0)e.push("1".codePointAt(0));else break;return e.reverse(),String.fromCodePoint(...e)},oo=(n,t=[0])=>{let e=zt([...t,...n]);return e=[...t,...n,...e.slice(0,4)],so(e)},ao=(n,t,e=1)=>{let i=ro(n),r=i.slice(0,e),s=i.slice(e,-4),o=[...r,...s];return o=zt(o),i.slice(-4).forEach((c,u)=>{if(c!==o[u])throw new Error("Invalid checksum")}),t==="hex"&&(r=nt(r),s=nt(s)),{prefix:r,data:s}},ue=class n{constructor(t){m(this,"bufs");m(this,"length");this.bufs=t??[],this.length=0;for(let e of this.bufs)this.length+=e.length}getLength(){return this.length}toUint8Array(){let t=new Uint8Array(this.length),e=0;for(let i of this.bufs)t.set(i,e),e+=i.length;return t}toArray(){let t=this.length,e=Array.from({length:t},()=>0),i=0;for(let r of this.bufs)if(r instanceof Uint8Array)for(let s of r)e[i++]=s;else{let s=r;for(let o of s)e[i++]=o}return e}toHex(){return this.toArray().map(t=>t.toString(16).padStart(2,"0")).join("")}write(t){return this.bufs.push(t),this.length+=t.length,this}writeReverse(t){let e=Array.from({length:t.length},()=>0);for(let i=0;i<e.length;i++)e[i]=t[t.length-1-i];return this.write(e)}writeUInt8(t){let e=Array.from({length:1},()=>0);return e[0]=t&255,this.write(e),this}writeInt8(t){return this.writeUInt8(t)}writeUInt16BE(t){let e=[t>>8&255,t&255];return this.write(e)}writeInt16BE(t){return this.writeUInt16BE(t&65535)}writeUInt16LE(t){let e=[t&255,t>>8&255];return this.write(e)}writeInt16LE(t){return this.writeUInt16LE(t&65535)}writeUInt32BE(t){let e=[t>>24&255,t>>16&255,t>>8&255,t&255];return this.write(e)}writeInt32BE(t){return this.writeUInt32BE(t>>>0)}writeUInt32LE(t){let e=[t&255,t>>8&255,t>>16&255,t>>24&255];return this.write(e)}writeInt32LE(t){return this.writeUInt32LE(t>>>0)}writeUInt64BEBn(t){let e=t.toArray("be",8);return this.write(e),this}writeUInt64LEBn(t){let e=t.toArray("be",8);return this.writeReverse(e),this}writeUInt64LE(t){if(t===-1)this.write(Array.from({length:8},()=>255));else{let e=new T(t).toArray("be",8);this.writeReverse(e)}return this}writeVarIntNum(t){let e=n.varIntNum(t);return this.write(e),this}writeVarIntBn(t){let e=n.varIntBn(t);return this.write(e),this}static varIntNum(t){if(!Number.isFinite(t)||!Number.isInteger(t))throw new RangeError("CompactSize value must be a finite integer");let e;if(t<0)return this.varIntBn(new T(t));if(t<253)e=[t];else if(t<65536)e=[253,t&255,t>>8&255];else if(t<4294967296)e=[254,t&255,t>>8&255,t>>16&255,t>>24&255];else{let i=t&4294967295,r=Math.floor(t/4294967296)&4294967295;e=[255,i&255,i>>8&255,i>>16&255,i>>24&255,r&255,r>>8&255,r>>16&255,r>>24&255]}return e}static varIntBn(t){let e;if(t.isNeg()&&(t=t.add(eh)),t.ltn(253))e=[t.toNumber()];else if(t.ltn(65536)){let i=t.toNumber();e=[253,i&255,i>>8&255]}else if(t.lt(new T(4294967296))){let i=t.toNumber();e=[254,i&255,i>>8&255,i>>16&255,i>>24&255]}else{let i=new n;i.writeUInt8(255),i.writeUInt64LEBn(t),e=i.toArray()}return e}},to=class{constructor(t=[],e=0){m(this,"bin");m(this,"pos");m(this,"length");if(this.bin=t,this.length=t.length,!Number.isSafeInteger(e)||e<0||e>this.length)throw new RangeError("Reader position exceeds available data");this.pos=e}ensureAvailable(t){if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(this.pos)||this.pos<0||this.pos+t>this.length)throw new RangeError("Reader read exceeds available data")}eof(){return this.pos>=this.length}read(t=this.length-this.pos){this.ensureAvailable(t);let e=this.pos,i=this.pos+t;return this.pos=i,this.bin.slice(e,i)}readReverse(t=this.length-this.pos){this.ensureAvailable(t);let e=Array.from({length:t},()=>0);for(let i=0;i<t;i++)e[i]=this.bin[this.pos+t-1-i];return this.pos+=t,e}readUInt8(){this.ensureAvailable(1);let t=this.bin[this.pos];return this.pos+=1,t}readInt8(){let t=this.readUInt8();return(t&128)===0?t:t-256}readUInt16BE(){this.ensureAvailable(2);let t=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,t}readInt16BE(){let t=this.readUInt16BE();return(t&32768)===0?t:t-65536}readUInt16LE(){this.ensureAvailable(2);let t=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,t}readInt16LE(){let t=this.readUInt16LE();return(t&32768)===0?t:t-65536}readUInt32BE(){this.ensureAvailable(4);let t=this.bin[this.pos]*16777216+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,t}readInt32BE(){let t=this.readUInt32BE();return(t&2147483648)===0?t:t-4294967296}readUInt32LE(){this.ensureAvailable(4);let t=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,t}readInt32LE(){let t=this.readUInt32LE();return(t&2147483648)===0?t:t-4294967296}readUInt64BEBn(){let t=this.read(8);return new T(t)}readUInt64LEBn(){let t=this.readReverse(8);return new T(t)}readInt64LEBn(){let t=this.readReverse(8),e=new T(t);return e.gte(C1)&&(e=e.sub(eh)),e}readVarIntNum(t=!0){let e=this.readUInt8(),i;switch(e){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(i=t?this.readInt64LEBn():this.readUInt64LEBn(),i.lte(new T(2).pow(new T(53))))return i.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return e}}readVarIntNumStrict(t=!0){return Qs(this,t)}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){let t=this.readUInt8();switch(t){case 253:return new T(this.readUInt16LE());case 254:return new T(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new T(t)}}},Ta=n=>{if(n.length===0)return n;let t=n.at(-1);if((t&127)!==0)return n;if(n.length===1)return[];if((n.at(-2)&128)!==0)return n;for(let e=n.length-1;e>0;e--)if(n[e-1]!==0)return(n[e-1]&128)===0?(n[e-1]|=t,n.slice(0,e)):(n[e]=t,n.slice(0,e+1));return[]},C1=new T(2).pow(new T(63)),eh=new T(2).pow(new T(64));function nr(n,t="Expected a valid value, but got undefined or null."){if(n==null)throw new Error(t);return n}function L1(n,t){if(n.length!==t.length)return!1;let e=0;for(let i=0;i<n.length;i++)e|=n[i]^t[i];return e===0}var Fu;function nh(n,t){let e=n.andln(3)+t&3;return e===3?-1:e}function ih(n,t,e,i){if((e&1)===0)return 0;let r=n.andln(7)+t&7;return(r===3||r===5)&&i===2?-e:e}function rh(n,t){return 2*n===t+1?1-n:n}var Oa,sh,Wu=class Wu{constructor(){G(this,Oa);m(this,"p");m(this,"red");m(this,"redN");m(this,"zero");m(this,"one");m(this,"two");m(this,"g");m(this,"n");m(this,"a");m(this,"b");m(this,"tinv");m(this,"zeroA");m(this,"threeA");m(this,"endo");m(this,"_endoWnafT1");m(this,"_endoWnafT2");m(this,"_wnafT1");m(this,"_wnafT2");m(this,"_wnafT3");m(this,"_wnafT4");m(this,"_bitLength");if(Fu===void 0)Fu=this;else return Fu;let e={prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",{doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}]};this.p=new T(e.p,16),this.red=new zi(e.prime),this.zero=new T(0).toRed(this.red),this.one=new T(1).toRed(this.red),this.two=new T(2).toRed(this.red),this.n=new T(e.n,16),this.g=Oe.fromJSON(e.g,e.gRed),this._wnafT1=Array.from({length:4},()=>{}),this._wnafT2=Array.from({length:4},()=>{}),this._wnafT3=Array.from({length:4},()=>{}),this._wnafT4=Array.from({length:4},()=>{}),this._bitLength=this.n.bitLength(),this.redN=this.n.toRed(this.red),this.a=new T(e.a,16).toRed(this.red),this.b=new T(e.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=this.a.fromRed().cmpn(0)===0,this.threeA=this.a.fromRed().sub(this.p).cmpn(-3)===0,this.endo=this._getEndomorphism(e),this._endoWnafT1=Array.from({length:4},()=>{}),this._endoWnafT2=Array.from({length:4},()=>{})}static assert(t,e="Elliptic curve assertion failed"){if(!t)throw new Error(e)}getNAF(t,e,i){let r=Array.from({length:Math.max(t.bitLength(),i)+1},()=>0);r.fill(0);let s=1<<e+1,o=t.clone();for(let c=0;c<r.length;c++){let u,f=o.andln(s-1);o.isOdd()?(f>(s>>1)-1?u=(s>>1)-f:u=f,o.isubn(u)):u=0,r[c]=u,o.iushrn(1)}return r}getJSF(t,e){let i=[[],[]];t=t.clone(),e=e.clone();let r=0,s=0;for(;t.cmpn(-r)>0||e.cmpn(-s)>0;){let o=nh(t,r),c=nh(e,s),u=ih(t,r,o,c);i[0].push(u);let f=ih(e,s,c,o);i[1].push(f),r=rh(r,u),s=rh(s,f),t.iushrn(1),e.iushrn(1)}return i}static cachedProperty(t,e,i){let r="_"+e;t.prototype[e]=function(){return this[r]===void 0&&(this[r]=i.call(this)),this[r]}}static parseBytes(t){return typeof t=="string"?at(t,"hex"):t}static intFromLE(t){return new T(t,"hex","le")}_getEndomorphism(t){if(!this.zeroA||this.p.modrn(3)!==1)return;let e=this._resolveEndomorphismBeta(t),i=this._resolveEndomorphismLambda(t,e);return{beta:e,lambda:i,basis:a(this,Oa,sh).call(this,t,i)}}_resolveEndomorphismBeta(t){if(t.beta!==void 0)return new T(t.beta,16).toRed(this.red);let e=this._getEndoRoots(this.p);if(e==null)throw new Error("Failed to get endomorphism roots for beta.");return(e[0].cmp(e[1])<0?e[0]:e[1]).toRed(this.red)}_endomorphismLambdaMatches(t,e,i=!1){if(this.g==null)throw new Error("Curve generator point (g) is not defined.");let r=this.g.mul(t)?.x,s=this.g.x==null?void 0:this.g.x.redMul(e);if(r==null||s==null){if(i)throw new Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");return!1}return r.cmp(s)===0}_resolveEndomorphismLambda(t,e){if(t.lambda!==void 0)return new T(t.lambda,16);let i=this._getEndoRoots(this.n);if(i==null)throw new Error("Failed to get endomorphism roots for lambda.");return this._endomorphismLambdaMatches(i[0],e)?i[0]:(Wu.assert(this._endomorphismLambdaMatches(i[1],e,!0),"Lambda selection does not match computed beta."),i[1])}_getEndoRoots(t){let e=t===this.p?this.red:new Ks(t),i=new T(2).toRed(e).redInvm(),r=i.redNeg(),s=new T(3).toRed(e).redNeg().redSqrt().redMul(i),o=r.redAdd(s).fromRed(),c=r.redSub(s).fromRed();return[o,c]}_getEndoBasis(t){let e=this.n.ushrn(Math.floor(this.n.bitLength()/2)),i=t,r=this.n.clone(),s=new T(1),o=new T(0),c=new T(0),u=new T(1),f,d,l,p,b,g,w=new T(0),S=0,C=new T(0),E=new T(0);for(;i.cmpn(0)!==0;){let B=r.div(i);C=r.sub(B.mul(i)),E=c.sub(B.mul(s));let _=u.sub(B.mul(o));if(l===void 0&&C.cmp(e)<0)f=w.neg(),d=s,l=C.neg(),p=E;else if(l!==void 0&&++S===2)break;w=C,r=i,i=C,c=s,s=E,u=o,o=_}if(f===void 0||d===void 0||l===void 0||p===void 0)throw new Error("Failed to compute Endo Basis values");b=C.neg(),g=E;let A=l.sqr().add(p.sqr());return b.sqr().add(g.sqr()).cmp(A)>=0&&(b=f,g=d),l.negative!==0&&(l=l.neg(),p=p.neg()),b.negative!==0&&(b=b.neg(),g=g.neg()),[{a:l,b:p},{a:b,b:g}]}_endoSplit(t){if(this.endo==null)throw new Error("Endomorphism is not defined.");let e=this.endo.basis,i=e[0],r=e[1],s=r.b.mul(t).divRound(this.n),o=i.b.neg().mul(t).divRound(this.n),c=s.mul(i.a),u=o.mul(r.a),f=s.mul(i.b),d=o.mul(r.b),l=t.sub(c).sub(u),p=f.add(d).neg();return{k1:l,k2:p}}validate(t){if(t.inf)return!0;let e=t.x,i=t.y;if(e===null||i===null)throw new Error("Point coordinates cannot be null");let r=this.a.redMul(e),s=e.redSqr().redMul(e).redIAdd(r).redIAdd(this.b);return i.redSqr().redISub(s).cmpn(0)===0}};Oa=new WeakSet,sh=function(t,e){return typeof t.basis!="object"||t.basis===null?this._getEndoBasis(e):t.basis.map(i=>({a:new T(i.a,16),b:new T(i.b,16)}))};var Vt=Wu;var ir=class{constructor(t){m(this,"curve");m(this,"type");m(this,"precomputed");this.curve=new Vt,this.type=t,this.precomputed=null}};var rr=class n extends ir{constructor(e,i,r){super("jacobian");m(this,"x");m(this,"y");m(this,"z");m(this,"zOne");e===null&&i===null&&r===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new T(0)):(T.isBN(e)||(e=new T(e,16)),this.x=e,T.isBN(i)||(i=new T(i,16)),this.y=i,T.isBN(r)||(r=new T(r,16)),this.z=r),this.x.red==null&&(this.x=this.x.toRed(this.curve.red)),this.y.red==null&&(this.y=this.y.toRed(this.curve.red)),this.z.red==null&&(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.isInfinity()&&(this.x=this.curve.one,this.y=this.curve.one,this.z=new T(0).toRed(this.curve.red),this.zOne=!1)}toP(){if(this.isInfinity())return new Oe(null,null);let e=this.z.redInvm(),i=e.redSqr(),r=this.x.redMul(i),s=this.y.redMul(i).redMul(e);return new Oe(r,s)}neg(){return new n(this.x,this.y.redNeg(),this.z)}add(e){if(this.isInfinity())return e;if(e.isInfinity())return this;let i=e.z.redSqr(),r=this.z.redSqr(),s=this.x.redMul(i),o=e.x.redMul(r),c=this.y.redMul(i.redMul(e.z)),u=e.y.redMul(r.redMul(this.z)),f=s.redSub(o),d=c.redSub(u);if(f.cmpn(0)===0)return d.cmpn(0)===0?this.dbl():new n(null,null,null);let l=f.redSqr(),p=l.redMul(f),b=s.redMul(l),g=d.redSqr().redIAdd(p).redISub(b).redISub(b),w=d.redMul(b.redISub(g)).redISub(c.redMul(p)),S=this.z.redMul(e.z).redMul(f);return new n(g,w,S)}mixedAdd(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;if(e.x===null||e.y===null)throw new Error("Point coordinates cannot be null");let i=this.z.redSqr(),r=this.x,s=e.x.redMul(i),o=this.y,c=e.y.redMul(i).redMul(this.z),u=r.redSub(s),f=o.redSub(c);if(u.cmpn(0)===0)return f.cmpn(0)===0?this.dbl():new n(null,null,null);let d=u.redSqr(),l=d.redMul(u),p=r.redMul(d),b=f.redSqr().redIAdd(l).redISub(p).redISub(p),g=f.redMul(p.redISub(b)).redISub(o.redMul(l)),w=this.z.redMul(u);return new n(b,g,w)}dblp(e){if(e===0)return this;if(this.isInfinity())return this;if(e===void 0)return this.dbl();let i=this;for(let r=0;r<e;r++)i=i.dbl();return i}dbl(){if(this.isInfinity())return this;let e,i,r;if(this.zOne){let s=this.x.redSqr(),o=this.y.redSqr(),c=o.redSqr(),u=this.x.redAdd(o).redSqr().redISub(s).redISub(c);u=u.redIAdd(u);let f=s.redAdd(s).redIAdd(s),d=f.redSqr().redISub(u).redISub(u),l=c.redIAdd(c);l=l.redIAdd(l),l=l.redIAdd(l),e=d,i=f.redMul(u.redISub(d)).redISub(l),r=this.y.redAdd(this.y)}else{let s=this.x.redSqr(),o=this.y.redSqr(),c=o.redSqr(),u=this.x.redAdd(o).redSqr().redISub(s).redISub(c);u=u.redIAdd(u);let f=s.redAdd(s).redIAdd(s),d=f.redSqr(),l=c.redIAdd(c);l=l.redIAdd(l),l=l.redIAdd(l),e=d.redISub(u).redISub(u),i=f.redMul(u.redISub(e)).redISub(l),r=this.y.redMul(this.z),r=r.redIAdd(r)}return new n(e,i,r)}eq(e){if(e.type==="affine")return this.eq(e.toJ());if(this===e||(e=e,this.isInfinity()&&e.isInfinity()))return!0;if(this.isInfinity()!==e.isInfinity())return!1;let i=this.z.redSqr(),r=e.z.redSqr();if(this.x.redMul(r).redISub(e.x.redMul(i)).cmpn(0)!==0)return!1;let s=i.redMul(this.z),o=r.redMul(e.z);return this.y.redMul(o).redISub(e.y.redMul(s)).cmpn(0)===0}eqXToP(e){let i=this.z.redSqr(),r=e.toRed(this.curve?.red).redMul(i);if(this.x.cmp(r)===0)return!0;let s=e.clone();if(this.curve?.redN==null)throw new Error("Curve or redN is not initialized.");let o=this.curve.redN.redMul(i);for(;s.cmp(this.curve.p)<0;){if(s.iadd(this.curve.n),s.cmp(this.curve.p)>=0)return!1;if(r.redIAdd(o),this.x.cmp(r)===0)return!0}return!1}inspect(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"}isInfinity(){return this.z.cmpn(0)===0}};function oh(n,t,e){let i=-n,r=(t.X^e.X)&i,s=(t.Y^e.Y)&i,o=(t.Z^e.Z)&i;t.X^=r,e.X^=r,t.Y^=s,e.Y^=s,t.Z^=o,e.Z^=o}var Ut=0n,Ce=1n,Vu=2n,U1=3n,M1=4n,D1=8n,Tn=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,wi=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,ah=(1n<<256n)-1n;function zu(n){let t=n>>256n;return n=(n&ah)+(t<<32n)+t*977n,t=n>>256n,n=(n&ah)+(t<<32n)+t*977n,n>=Tn&&(n-=Tn),n}var sr=n=>zu((n%Tn+Tn)%Tn),kn=(n,t)=>n>=t?n-t:Tn-(t-n),ct=(n,t)=>zu(n*t),ch=(n,t)=>zu(n+t),Wr=n=>{let t=Ce,e=Ut,i=sr(n),r=Tn;for(;i>Ce;){let s=r/i;[t,e]=[e-t*s,t],[i,r]=[r-i*s,i]}return sr(t)},H1=n=>ct(n,n),$1=(n,t)=>{let e=1n;for(n=sr(n);t>0n;)(t&1n)!==0n&&(e=ct(e,n)),n=ct(n,n),t>>=1n;return e},q1=Tn+1n>>2n,F1=n=>{let t=$1(n,q1);return ct(t,t)!==sr(n)?null:t},W1=n=>T.isBN(n)?BigInt("0x"+n.toString(16)):typeof n=="string"?BigInt("0x"+n):Array.isArray(n)?BigInt("0x"+nt(n)):BigInt(n),Pa=BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Ra=BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),uh=new Map,co=n=>{let{X:t,Y:e,Z:i}=n;if(e===Ut)return{X:Ut,Y:Ce,Z:Ut};let r=ct(e,e),s=ct(M1,ct(t,r)),o=ct(U1,ct(t,t)),c=kn(ct(o,o),ct(Vu,s)),u=kn(ct(o,kn(s,c)),ct(D1,ct(r,r))),f=ct(Vu,ct(e,i));return{X:c,Y:u,Z:f}},Vr=(n,t)=>{if(n.Z===Ut)return t;if(t.Z===Ut)return n;let e=ct(n.Z,n.Z),i=ct(t.Z,t.Z),r=ct(n.X,i),s=ct(t.X,e),o=ct(n.Y,ct(i,t.Z)),c=ct(t.Y,ct(e,n.Z)),u=kn(s,r),f=kn(c,o);if(u===Ut)return f===Ut?co(n):{X:Ut,Y:Ce,Z:Ut};let d=ct(u,u),l=ct(u,d),p=ct(r,d),b=kn(kn(ct(f,f),l),ct(Vu,p)),g=kn(ct(f,kn(p,b)),ct(o,l)),w=ct(u,ct(n.Z,t.Z));return{X:b,Y:g,Z:w}},V1=n=>n.Z===Ut?n:{X:n.X,Y:Tn-n.Y,Z:n.Z},K1=(n,t)=>{let e=`${n}:${t.x.toString(16)}:${t.y.toString(16)}`,i=uh.get(e);if(i!==void 0)return i;let r=Array.from({length:1<<n-1},()=>({X:Ut,Y:Ce,Z:Ut})),s={X:t.x,Y:t.y,Z:Ce};r[0]=s;let o=co(s);for(let c=1;c<r.length;c++)r[c]=Vr(r[c-1],o);return uh.set(e,r),r},z1=(n,t)=>{let e=[],i=1n<<BigInt(t),r=i>>1n,s=n;for(;s>0n;){if((s&Ce)===Ut)e.push(0);else{let o=s&i-1n;o>r&&(o-=i),e.push(Number(o)),s-=o}s>>=Ce}return e},Na=(n,t,e=5)=>{let i=K1(e,t),r=z1(n,e),s={X:Ut,Y:Ce,Z:Ut};for(let o=r.length-1;o>=0;o--){s=co(s);let c=r[o];if(c!==0){let u=Math.abs(c)>>1,f=c>0?i[u]:V1(i[u]);s=Vr(s,f)}}return s},or=n=>{let t=n%wi;return t<0n&&(t+=wi),t},uo=(n,t)=>or(n*t),Xu=n=>{let t=1n,e=0n,i=or(n),r=wi;for(;i>1n;){let s=r/i;[t,e]=[e-t*s,t],[i,r]=[r-i*s,i]}return or(t)},he,fh,dh,lh,hh,ph,Ku,gh,Ot=class Ot extends ir{constructor(e,i,r=!0){super("affine");G(this,he);m(this,"x");m(this,"y");m(this,"inf");this.precomputed=null,e===null&&i===null?(this.x=null,this.y=null,this.inf=!0):(T.isBN(e)||(e=new T(e,16)),this.x=e,T.isBN(i)||(i=new T(i,16)),this.y=i,r&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red===null&&(this.x=this.x.toRed(this.curve.red)),this.y.red===null&&(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}static _assertOnCurve(e){if(!e.validate())throw new Error("Invalid point");return e}static fromDER(e){if((e[0]===4||e[0]===6||e[0]===7)&&e.length-1===64){if(e[0]===6){if(e.at(-1)%2!==0)throw new Error("Point string value is wrong length")}else if(e[0]===7&&e.at(-1)%2!==1)throw new Error("Point string value is wrong length");let r=new Ot(e.slice(1,33),e.slice(33,65));return Ot._assertOnCurve(r)}else if((e[0]===2||e[0]===3)&&e.length-1===32)return Ot._assertOnCurve(Ot.fromX(e.slice(1,33),e[0]===3));throw new Error("Unknown point format")}static fromString(e){let i=at(e,"hex");return Ot._assertOnCurve(Ot.fromDER(i))}static fromX(e,i){let r=W1(e);r=sr(r);let s=ch(ct(H1(r),r),7n),o=F1(s);if(o===null)throw new Error("Invalid point");let c=o;(c&Ce)!==(i?Ce:Ut)&&(c=kn(Tn,c));let u=new T(r.toString(16),16),f=new T(c.toString(16),16);return Ot._assertOnCurve(new Ot(u,f))}static fromJSON(e,i){typeof e=="string"&&(e=JSON.parse(e));let r=new Ot(e[0],e[1],i);if(r=Ot._assertOnCurve(r),typeof e[2]!="object"||e[2]===null)return r;let s=e[2],o=c=>{let u=new Ot(c[0],c[1],i);return Ot._assertOnCurve(u)};return r.precomputed={beta:null,doubles:typeof s.doubles=="object"&&s.doubles!==null?{step:s.doubles.step,points:[r].concat(s.doubles.points.map(o))}:void 0,naf:typeof s.naf=="object"&&s.naf!==null?{wnd:s.naf.wnd,points:[r].concat(s.naf.points.map(o))}:void 0},r}validate(){if(this.inf||this.x==null||this.y==null)return!1;try{let e=BigInt("0x"+this.x.fromRed().toString(16)),i=BigInt("0x"+this.y.fromRed().toString(16)),r=ct(i,i),s=ch(ct(ct(e,e),e),7n);return r===s}catch{return!1}}encode(e=!0,i){if(this.inf)return i==="hex"?"00":[0];let r=this.curve.p.byteLength(),s=this.getX().toArray("be",r),o;return e?o=[this.getY().isEven()?2:3].concat(s):o=[4].concat(s,this.getY().toArray("be",r)),i==="hex"?nt(o):o}toString(){return this.encode(!0,"hex")}toJSON(){return this.precomputed==null?[this.x,this.y]:[this.x,this.y,typeof this.precomputed=="object"&&this.precomputed!==null?{doubles:this.precomputed.doubles==null?void 0:{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)},naf:this.precomputed.naf==null?void 0:{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}}:void 0]}inspect(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+(this.x?.fromRed()?.toString(16,2)??"undefined")+" y: "+(this.y?.fromRed()?.toString(16,2)??"undefined")+">"}isInfinity(){return this.inf}add(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return new Ot(null,null);if(this.x?.cmp(e.x??new T(0))===0)return new Ot(null,null);let i={X:BigInt("0x"+this.x.fromRed().toString(16)),Y:BigInt("0x"+this.y.fromRed().toString(16)),Z:Ce},r={X:BigInt("0x"+e.x.fromRed().toString(16)),Y:BigInt("0x"+e.y.fromRed().toString(16)),Z:Ce},s=Vr(i,r);if(s.Z===Ut)return new Ot(null,null);let o=Wr(s.Z),c=ct(o,o),u=ct(s.X,c),f=ct(s.Y,ct(c,o));return new Ot(u.toString(16),f.toString(16))}dbl(){if(this.inf)return this;if(this.x===null||this.y===null)throw new Error("Point coordinates cannot be null");let e=BigInt("0x"+this.x.fromRed().toString(16)),i=BigInt("0x"+this.y.fromRed().toString(16));if(i===Ut)return new Ot(null,null);let r=co({X:e,Y:i,Z:Ce}),s=Wr(r.Z),o=ct(s,s),c=ct(r.X,o),u=ct(r.Y,ct(o,s));return new Ot(c.toString(16),u.toString(16))}getX(){return(this.x??new T(0)).fromRed()}getY(){return(this.y??new T(0)).fromRed()}mul(e){if(T.isBN(e)||(e=new T(e,16)),e=e,this.inf)return this;let i=e.isNeg(),r=i?e.neg():e,s=BigInt("0x"+r.toString(16));if(s=sr(s),s===Ut)return new Ot(null,null);if(s===Ut)return new Ot(null,null);if(this.x===null||this.y===null)throw new Error("Point coordinates cannot be null");let o,c;this===this.curve.g?(o=Pa,c=Ra):(o=BigInt("0x"+this.x.fromRed().toString(16)),c=BigInt("0x"+this.y.fromRed().toString(16)));let u=Na(s,{x:o,y:c});if(u.Z===Ut)return new Ot(null,null);let f=Wr(u.Z),d=ct(f,f),l=ct(u.X,d),p=ct(u.Y,ct(d,f)),b=new T(l.toString(16),16),g=new T(p.toString(16),16),w=new Ot(b,g);return i?w.neg():w}mulCT(e){if(T.isBN(e)||(e=new T(e,16)),e=e,this.inf)return new Ot(null,null);let i=e.isNeg(),r=i?e.neg():e,s=BigInt("0x"+r.toString(16));if(s=sr(s),s===0n)return new Ot(null,null);let o=this===this.curve.g?Pa:BigInt("0x"+this.getX().toString(16)),c=this===this.curve.g?Ra:BigInt("0x"+this.getY().toString(16)),u={X:0n,Y:1n,Z:0n},f={X:o,Y:c,Z:1n},d=s.toString(2);for(let S of d){let C=S==="1"?1n:0n;oh(C,u,f),f=Vr(u,f),u=co(u),oh(C,u,f)}if(u.Z===0n)return new Ot(null,null);let l=Wr(u.Z),p=ct(l,l),b=ct(u.X,p),g=ct(u.Y,ct(p,l)),w=new Ot(b.toString(16),g.toString(16));return i?w.neg():w}mulAdd(e,i,r){let s=[this,i],o=[e,r];return a(this,he,Ku).call(this,s,o)}jmulAdd(e,i,r){let s=[this,i],o=[e,r];return a(this,he,Ku).call(this,s,o,!0)}eq(e){return this===e||this.inf===e.inf&&(this.inf||(this.x??new T(0)).cmp(e.x??new T(0))===0&&(this.y??new T(0)).cmp(e.y??new T(0))===0)}neg(e){if(this.inf)return this;let i=new Ot(this.x,(this.y??new T(0)).redNeg());if(e===!0&&this.precomputed!=null){let r=this.precomputed,s=o=>o.neg();i.precomputed={naf:r.naf==null?void 0:{wnd:r.naf.wnd,points:r.naf.points.map(s)},doubles:r.doubles==null?void 0:{step:r.doubles.step,points:r.doubles.points.map(o=>o.neg())},beta:void 0}}return i}dblp(e){let i;for(let r=0;r<e;r++)i=(i??this).dbl();return i??this}toJ(){return this.inf?new rr(null,null,null):new rr(this.x,this.y,this.curve.one)}_combineWnafPair(e,i,r){let{points:s,coeffs:o,wndWidth:c,wnd:u,naf:f,currentMax:d}=r;if(c[e]!==1||c[i]!==1)return f[e]=this.curve.getNAF(o[e],c[e],this.curve._bitLength),f[i]=this.curve.getNAF(o[i],c[i],this.curve._bitLength),Math.max(d,f[e].length,f[i].length);let l=[s[e],null,null,s[i]],p=s[e].y??new T(0),b=s[i].y??new T(0);p.cmp(b)===0?(l[1]=s[e].add(s[i]),l[2]=s[e].toJ().mixedAdd(s[i].neg())):p.cmp(b.redNeg())===0?(l[1]=s[e].toJ().mixedAdd(s[i]),l[2]=s[e].add(s[i].neg())):(l[1]=s[e].toJ().mixedAdd(s[i]),l[2]=s[e].toJ().mixedAdd(s[i].neg()));let g=[-3,-1,-5,-7,0,7,5,1,3],w=this.curve.getJSF(o[e],o[i]),S=Math.max(d,w[0].length);f[e]=Array.from({length:S}),f[i]=Array.from({length:S});for(let C=0;C<S;C++){let E=Math.trunc(w[0][C]),A=Math.trunc(w[1][C]);f[e][C]=g[(E+1)*3+(A+1)],f[i][C]=0,u[e]=l}return S}_collectWnafStep(e,i,r,s){let o=e,c=0;for(;o>=0;){let u=!0;for(let f=0;f<i;f++)s[f]=new T(typeof r[f][o]=="number"?r[f][o]:0),s[f].isZero()||(u=!1);if(!u)break;c++,o--}return o>=0&&c++,{index:o,doubles:c}}_getDoubles(e,i){if(typeof this.precomputed=="object"&&this.precomputed!==null&&typeof this.precomputed.doubles=="object"&&this.precomputed.doubles!==null)return this.precomputed.doubles;let r=[this],s;for(let o=0;o<(i??0);o+=e??1){for(let c=0;c<(e??1);c++)s=(s??this).dbl();r.push(s)}return{step:e??1,points:r}}};he=new WeakSet,fh=function(){if(typeof this.curve.endo!="object")return;let e=this.precomputed;if(typeof e=="object"&&e!==null&&typeof e.beta=="object"&&e.beta!==null)return e.beta;let i=new Ot((this.x??new T(0)).redMul(this.curve.endo.beta),this.y);if(e!=null){let r=this.curve,s=o=>{let c=o;if(c.x===null)throw new Error("p.x is null");if(r.endo===void 0||r.endo===null)throw new Error("curve.endo is undefined");return new Ot(c.x.redMul(r.endo.beta),c.y)};e.beta=i,i.precomputed={beta:null,naf:e.naf==null?void 0:{wnd:e.naf.wnd,points:e.naf.points.map(s)},doubles:e.doubles==null?void 0:{step:e.doubles.step,points:e.doubles.points.map(s)}}}return i},dh=function(e,i,r,s,o){var c;for(let u=0;u<r;u++){let f=a(c=i[u],he,gh).call(c,e);s[u]=f.wnd,o[u]=f.points}},lh=function(e,i,r,s,o,c){let u=0;for(let f=r-1;f>=1;f-=2)u=this._combineWnafPair(f-1,f,{points:e,coeffs:i,wndWidth:s,wnd:o,naf:c,currentMax:u});return u},hh=function(e,i,r,s){let o=new T(1),c=new T(2),u=e;for(let f=0;f<i;f++){let d=r[f];if(d.cmpn(0)===0)continue;let l=d.isNeg()?s[f][d.neg().sub(o).div(c).toNumber()].neg():s[f][d.sub(o).div(c).toNumber()];u=l.type==="affine"?u.mixedAdd(l):u.add(l)}return u},ph=function(e,i,r,s,o){let c=this.curve._wnafT1.length,u=Array.from({length:c}),f=Array.from({length:c},()=>[]),d=Array.from({length:c},()=>[]);a(this,he,dh).call(this,e,i,s,u,f);let l=a(this,he,lh).call(this,i,r,s,u,f,d),p=new rr(null,null,null),b=this.curve._wnafT4,g=l;for(;g>=0;){let w=this._collectWnafStep(g,s,d,b);if(g=w.index,p=p.dblp(w.doubles),g<0)break;p=a(this,he,hh).call(this,p,s,b,f),g--}for(let w=0;w<s;w++)f[w]=[];return o===!0?p:p.toP()},Ku=function(e,i,r){var f;let s=Array.from({length:e.length*2}),o=Array.from({length:e.length*2}),c;for(c=0;c<e.length;c++){let d=this.curve._endoSplit(i[c]),l=e[c],p=a(f=l,he,fh).call(f)??new Ot(null,null);d.k1.negative!==0&&(d.k1.ineg(),l=l.neg(!0)),d.k2.negative!==0&&(d.k2.ineg(),p=p.neg(!0)),s[c*2]=l,s[c*2+1]=p,o[c*2]=d.k1,o[c*2+1]=d.k2}let u=a(this,he,ph).call(this,1,s,o,c*2,r);for(let d=0;d<c*2;d++)s[d]=null,o[d]=null;return u},gh=function(e){if(typeof this.precomputed=="object"&&this.precomputed!==null&&typeof this.precomputed.naf=="object"&&this.precomputed.naf!==null)return this.precomputed.naf;let i=[this],r=(1<<e)-1,s=r===1?null:this.dbl();for(let o=1;o<r;o++)s!==null&&(i[o]=i[o-1].add(s));return{wnd:e,points:i}};var Oe=Ot;var Ht=class n extends Oe{static fromPrivateKey(t){let i=new Vt().g.mul(t);return new n(i.x,i.y)}static fromString(t){let e=Oe.fromString(t);return new n(e.x,e.y)}static fromDER(t){let e=Oe.fromDER(t);return new n(e.x,e.y)}constructor(t,e=null,i=!0){if(t instanceof Oe)super(t.getX(),t.getY());else{if(e===null&&i&&typeof t=="string"&&(t.length===66||t.length===130))throw new Error('You are using the "new PublicKey()" constructor with a DER hex string. You need to use "PublicKey.fromString()" instead.');super(t,e,i)}}deriveSharedSecret(t){if(!this.validate())throw new Error("Public key not valid for ECDH secret derivation");return this.mulCT(t)}verify(t,e,i){let r=new T(Te(t,i),16);return xi(r,e,this)}toDER(t){return t==="hex"?this.encode(!0,t):this.encode(!0)}toHash(t){let e=Zs(this.encode(!0));return t==="hex"?nt(e):e}toAddress(t=[0]){if(typeof t=="string")if(t==="testnet"||t==="test")t=[111];else if(t==="mainnet"||t==="main")t=[0];else throw new Error(`Invalid prefix ${t}`);return oo(this.toHash(),t)}deriveChild(t,e,i,r){let s;if(typeof r=="function"){let l=r(t,this);l===void 0?(s=this.deriveSharedSecret(t),typeof i=="function"&&i(t,this,s)):s=l}else s=this.deriveSharedSecret(t);let o=at(e,"utf8"),c=Js(s.encode(!0),o),f=new Vt().g.mul(new T(c)),d=this.add(f);return new n(d.x,d.y)}static fromMsgHashAndCompactSignature(t,e,i){let r=at(e,i);if(r.length!==65)throw new Error("Invalid Compact Signature");let s=r[0];if(s<27||s>=35)throw new Error("Invalid Compact Byte");let o=r[0]-27;return o>3&&(o-=4),new pe(new T(r.slice(1,33)),new T(r.slice(33,65))).RecoverPublicKey(o,t)}};var pe=class n{constructor(t,e){m(this,"r");m(this,"s");this.r=t,this.s=e}static fromDER(t,e){let i=(l,p)=>{let b=l[p.place++];if((b&128)===0)return b;throw new Error("Invalid DER entity length")};class r{constructor(){m(this,"place",0)}}t=at(t,e);let s=new r;if(t[s.place++]!==48)throw new Error("Signature DER must start with 0x30");if(i(t,s)+s.place!==t.length)throw new Error("Signature DER invalid");if(t[s.place++]!==2)throw new Error("Signature DER invalid");let c=i(t,s),u=t.slice(s.place,c+s.place);if(s.place+=c,t[s.place++]!==2)throw new Error("Signature DER invalid");let f=i(t,s);if(t.length!==f+s.place)throw new Error("Invalid R-length in signature DER");let d=t.slice(s.place,f+s.place);if(u[0]===0){if((u[1]&128)===0)throw new Error("Invalid R-value in signature DER");u=u.slice(1)}if(d[0]===0){if((d[1]&128)===0)throw new Error("Invalid S-value in signature DER");d=d.slice(1)}return new n(new T(u),new T(d))}static fromCompact(t,e){if(t=at(t,e),t.length!==65)throw new Error("Invalid Compact Signature");let i=t[0];if(i<27||i>=35)throw new Error("Invalid Compact Byte");return new n(new T(t.slice(1,33)),new T(t.slice(33,65)))}verify(t,e,i){let r=new T(Te(t,i),16);return xi(r,this,e)}toString(t){return this.toDER(t)}toDER(t){let e=(f,d)=>{if(d<128)f.push(d);else throw new Error("len must be < 0x80")},i=f=>{let d=0,l=f.length-1;for(;f[d]===0&&(f[d+1]&128)===0&&d<l;)d++;return d===0?f:f.slice(d)},r=this.r.toArray(),s=this.s.toArray();for((r[0]&128)!==0&&(r=[0].concat(r)),(s[0]&128)!==0&&(s=[0].concat(s)),r=i(r),s=i(s);s[0]===0&&(s[1]&128)===0;)s=s.slice(1);let o=[2];e(o,r.length),o=o.concat(r),o.push(2),e(o,s.length);let c=o.concat(s),u=[48];return e(u,c.length),u=u.concat(c),t==="hex"?nt(u):t==="base64"?Se(u):u}toCompact(t,e,i){if(t<0||t>3)throw new Error("Invalid recovery param");if(typeof e!="boolean")throw new TypeError("Invalid compressed param");let r=27+t;e&&(r+=4);let s=[r];return s=s.concat(this.r.toArray("be",32)),s=s.concat(this.s.toArray("be",32)),i==="hex"?nt(s):i==="base64"?Se(s):s}RecoverPublicKey(t,e){let i=this.r,r=this.s,s=(t&1)!==0,o=t>>1,c=new Vt,u=c.n,f=c.g,d=o===0?i:i.add(u),l=Oe.fromX(d,s);if(!l.mul(u).isInfinity())throw new Error("nR is not at infinity");let b=e.neg().umod(u),g=i.invm(u),w=g.mul(r).umod(u),S=g.mul(b).umod(u),C=f.mul(S).add(l.mul(w)),E=new Ht(C);return E.validate(),E}CalculateRecoveryFactor(t,e){for(let i=0;i<4;i++){let r;try{r=this.RecoverPublicKey(i,e)}catch{continue}if(t.eq(r))return i}throw new Error("Unable to find valid recovery factor")}};var fo=class{constructor(t,e){m(this,"K");m(this,"V");let i=at(t,"hex"),r=at(e,"hex");if(i.length!==32)throw new Error("Entropy must be exactly 32 bytes (256 bits)");if(r.length!==32)throw new Error("Nonce must be exactly 32 bytes (256 bits)");let s=i.concat(r);this.K=Array.from({length:32}),this.V=Array.from({length:32});for(let o=0;o<32;o++)this.K[o]=0,this.V[o]=1;this.update(s)}hmac(){return new qr(this.K)}update(t){let e=this.hmac().update(this.V).update([0]);t!==void 0&&(e=e.update(t)),this.K=e.digest(),this.V=this.hmac().update(this.V).digest(),t!==void 0&&(this.K=this.hmac().update(this.V).update([1]).update(t).digest(),this.V=this.hmac().update(this.V).digest())}generate(t){let e=[];for(;e.length<t;)this.V=this.hmac().update(this.V).digest(),e=e.concat(this.V);let i=e.slice(0,t);return this.update(),nt(i)}};function bh(n,t,e=new Vt){let i=n.byteLength()*8-e.n.bitLength();return i>0&&n.iushrn(i),t!==!0&&n.cmp(e.n)>=0?n.sub(e.n):n}function ar(n){let t=n.toArray("be"),e=0n;for(let i of t)e=e<<8n|BigInt(i);return e}var lo=new Vt,ju=lo.n.byteLength(),X1=lo.n.subn(1),j1=wi>>1n;function G1(n,t,e){let i;if(typeof n=="function"?i=n(t):n!==void 0&&T.isBN(n)?i=n:i=new T(e.generate(ju),16),i==null)throw new Error("k is undefined");return bh(i,!0)}function Ba(n,t){if(n)throw new Error(t)}function Y1(n,t,e,i,r){if(n.cmpn(1)<0||n.cmp(X1)>0)return Ba(r,"Invalid fixed custom K value (must be >1 and <N-1)");let s=lo.g.mulCT(n);if(s.isInfinity())return Ba(r,"Invalid fixed custom K value (k\xB7G at infinity)");let o=or(BigInt("0x"+s.getX().toString(16)));if(o===0n)return Ba(r,"Invalid fixed custom K value (r == 0)");let c=Xu(BigInt("0x"+n.toString(16))),u=or(t+uo(o,e)),f=uo(c,u);return f===0n?Ba(r,"Invalid fixed custom K value (s == 0)"):(i&&f>j1&&(f=wi-f),new pe(new T(o.toString(16),16),new T(f.toString(16),16)))}var mh=(n,t,e=!1,i)=>{let r=lo.n.bitLength();if(n.bitLength()>r)throw new Error(`ECDSA message is too large: expected <= ${r} bits. Callers must hash messages before signing.`);n=bh(n);let s=ar(n),o=ar(t),c=t.toArray("be",ju),u=n.toArray("be",ju),f=new fo(c,u),d=T.isBN(i);for(let l=0;;l++){let p=Y1(G1(i,l,f),s,o,e,d);if(p!=null)return p}},xi=(n,t,e)=>{let i=lo.n.bitLength();if(n.bitLength()>i)return!1;let r=ar(n);if(e.x==null||e.y==null)throw new Error("Invalid public key: missing coordinates.");let s={x:ar(e.x),y:ar(e.y)},o={r:ar(t.r),s:ar(t.s)},{r:c,s:u}=o,f=r;if(c<=Ut||c>=wi||u<=Ut||u>=wi)return!1;let d=Xu(u);if(d===0n)return!1;let l=uo(f,d),p=uo(c,d),b=Na(l,{x:Pa,y:Ra}),g=Na(p,s),w=Vr(b,g);if(w.Z===0n)return!1;let S=Wr(w.Z),C=ct(S,S),E=ct(w.X,C);return or(E)===c};var Gu=class{constructor(){m(this,"_rand");let t=()=>{throw new Error("No secure random number generator is available in this environment.")};if(this._rand=t,typeof globalThis<"u"&&typeof globalThis.crypto?.getRandomValues=="function"){this._rand=e=>this.getRandomValues(globalThis,e);return}if(globalThis.self!==void 0&&typeof globalThis.self.crypto?.getRandomValues=="function"){this._rand=e=>this.getRandomValues(globalThis.self,e);return}if(globalThis.window!==void 0&&typeof globalThis.window.crypto?.getRandomValues=="function"){this._rand=e=>this.getRandomValues(globalThis.window,e);return}if(typeof process<"u"&&typeof process.getBuiltinModule=="function"){let e=process.getBuiltinModule("node:crypto");if(typeof e?.randomBytes=="function"){this._rand=i=>Array.from(e.randomBytes(i));return}}this._rand=t}getRandomValues(t,e){let i=new Uint8Array(e);return t.crypto.getRandomValues(i),Array.from(i)}generate(t){return this._rand(t)}},yh=null,Z1=n=>(yh??(yh=new Gu),yh.generate(n)),Pe=Z1;var ve=255,J1=129,wh=/^[1-9A-HJ-NP-Za-km-z]{1,64}$/;function xh(n,t,e){if(!Number.isSafeInteger(n)||n<e||n>ve)throw new TypeError(`threshold must be a safe integer from ${e} to ${ve}`);if(n>t)throw new Error("threshold cannot exceed the number of points")}var nn=class n{constructor(t,e){m(this,"x");m(this,"y");let i=new Vt().p;this.x=t.umod(i),this.y=e.umod(i)}toString(){return so(this.x.toArray())+"."+so(this.y.toArray())}static fromString(t){if(typeof t!="string"||t.length>J1)throw new TypeError("Finite-field point must use a bounded canonical Base58 representation");let[e,i,r]=t.split(".");if(r!==void 0||e===void 0||i===void 0||!wh.test(e)||!wh.test(i))throw new TypeError("Finite-field point must use a bounded canonical Base58 representation");let s=new n(new T(ro(e)),new T(ro(i)));if(s.toString()!==t)throw new TypeError("Finite-field point must use a bounded canonical Base58 representation");return s}},Kr=class n{constructor(t,e){m(this,"points");m(this,"threshold");if(!Array.isArray(t)||t.length===0||t.length>ve)throw new TypeError(`points must contain from 1 to ${ve} entries`);let i=e??t.length;xh(i,t.length,1),this.points=t.slice(),this.threshold=i}static fromPrivateKey(t,e){if(!Number.isSafeInteger(e)||e<2||e>ve)throw new TypeError(`threshold must be a safe integer from 2 to ${ve}`);let i=new Vt().p,r=[new nn(new T(0),new T(t.toArray()))];for(let s=1;s<e;s++){let o=new T(Pe(32)).umod(i),c=new T(Pe(32)).umod(i);r.push(new nn(o,c))}return new n(r)}valueAt(t){if(xh(this.threshold,this.points.length,1),!(t instanceof T))throw new TypeError("x must be a BigNumber");let e=new Vt().p,i=new Set;for(let o=0;o<this.threshold;o++){let c=this.points[o];if(!(c instanceof nn)||!(c.x instanceof T)||!(c.y instanceof T))throw new TypeError("points must contain finite-field points");if(c.x.isNeg()||c.y.isNeg()||c.x.gte(e)||c.y.gte(e))throw new TypeError("point coordinates must be canonical field elements");let u=c.x.toString(16);if(i.has(u))throw new Error("Polynomial points must have unique x coordinates");i.add(u)}let r=t.umod(e),s=new T(0);for(let o=0;o<this.threshold;o++){let c=this.points[o].y;for(let u=0;u<this.threshold;u++)if(o!==u){let f=this.points[u].x,d=this.points[o].x,l=r.sub(f).umod(e),b=d.sub(f).umod(e).invm(e),g=l.mul(b).umod(e);c=c.mul(g).umod(e)}s=s.add(c).umod(e)}return s}};var Q1=256,Ih=/^[1-9A-HJ-NP-Za-km-z]{1,64}$/,ty=/^(?:[2-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/,Sh=/^[0-9a-f]{8}$/;function Yu(n,t,e){if(!Array.isArray(n)||n.length===0||n.length>ve)throw new TypeError(`shares must contain from 1 to ${ve} entries`);if(!Number.isSafeInteger(t)||t<2||t>ve)throw new TypeError(`threshold must be a safe integer from 2 to ${ve}`);if(typeof e!="string"||!Sh.test(e))throw new TypeError("integrity must be an 8-character lowercase hexadecimal string")}var ho=class n{constructor(t,e,i){m(this,"points");m(this,"threshold");m(this,"integrity");this.points=t,this.threshold=e,this.integrity=i}static fromBackupFormat(t){if(!Array.isArray(t)||t.length===0||t.length>ve)throw new TypeError(`shares must contain from 1 to ${ve} entries`);let e=0,i="",r=[];for(let s=0;s<t.length;s++){if(!Object.prototype.hasOwnProperty.call(t,s))throw new TypeError("shares must be a dense array");let o=t[s];if(typeof o!="string"||o.length>Q1)throw new TypeError(`Invalid share format in share ${s.toString()}`);let c=o.split(".");if(c.length!==4)throw new Error(`Invalid share format in share ${s.toString()}. Expected format: "x.y.t.i"`);let[u,f,d,l]=c;if(u===void 0||f===void 0||d===void 0||l===void 0||!Ih.test(u)||!Ih.test(f)||!ty.test(d)||!Sh.test(l))throw new TypeError(`Invalid canonical share data in share ${s.toString()}`);let p=Number(d);if(s!==0&&e!==p)throw new Error("Threshold mismatch in share "+s.toString());if(s!==0&&i!==l)throw new Error("Integrity mismatch in share "+s.toString());e=p,i=l,r.push(nn.fromString(`${u}.${f}`))}return Yu(r,e,i),new n(r,e,i)}toBackupFormat(){Yu(this.points,this.threshold,this.integrity);let t=[];for(let e=0;e<this.points.length;e++){if(!Object.prototype.hasOwnProperty.call(this.points,e))throw new TypeError("shares must be a dense array");let i=this.points[e];if(!(i instanceof nn))throw new TypeError("shares must contain finite-field points");let r=i.toString();if(nn.fromString(r).toString()!==r)throw new TypeError("shares must contain canonical finite-field points");t.push(`${r}.${this.threshold.toString()}.${this.integrity}`)}return t}},cr=class n extends T{static fromRandom(){return new n(Pe(32))}static fromString(t,e="hex"){return new n(super.fromString(t,e).toArray())}static fromHex(t){return new n(super.fromHex(t,"big"))}static fromWif(t,e=1){let i=ao(t,void 0,e);if(i.data.length!==33)throw new Error("Invalid WIF length");if(i.data[32]!==1)throw new Error("Invalid WIF padding");return new n(i.data.slice(0,32))}constructor(t=0,e=10,i="be",r="apply"){if(t instanceof T?(super(),t.copy(this)):super(t,e,i),r!=="nocheck"){let s=this.checkInField();if(!s.inField){if(r==="error")throw new Error("Input is out of field");T.move(this,s.modN)}}}checkInField(){let t=new Vt,e=this.mod(t.n);return{inField:this.cmp(e)===0,modN:e}}isValid(){return this.checkInField().inField}sign(t,e,i=!0,r){let s=new T(Te(t,e),16);return mh(s,this,i,r)}verify(t,e,i){let r=new T(Te(t,i),16);return xi(r,e,this.toPublicKey())}toPublicKey(){let e=new Vt().g.mulCT(this);return new Ht(e.x,e.y)}toWif(t=[128]){if(!this.isValid())throw new Error("Value is out of field");return oo([...this.toArray("be",32),1],t)}toAddress(t=[0]){return this.toPublicKey().toAddress(t)}toHex(){return super.toHex(32)}toString(t="hex",e=64){return super.toString(t,e)}deriveSharedSecret(t){if(!t.validate())throw new Error("Public key not valid for ECDH secret derivation");return t.mulCT(this)}deriveChild(t,e,i,r){let s;if(typeof r=="function"){let f=r(this,t);f===void 0?(s=this.deriveSharedSecret(t),typeof i=="function"&&i(this,t,s)):s=f}else s=this.deriveSharedSecret(t);let o=at(e,"utf8"),c=Js(s.encode(!0),o),u=new Vt;return new n(this.add(new T(c)).mod(u.n).toArray())}toKeyShares(t,e){if(typeof t!="number"||typeof e!="number")throw new TypeError("threshold and totalShares must be numbers");if(!Number.isSafeInteger(t)||!Number.isSafeInteger(e))throw new TypeError("threshold and totalShares must be safe integers");if(t<2)throw new Error("threshold must be at least 2");if(e<2)throw new Error("totalShares must be at least 2");if(t>e)throw new Error("threshold should be less than or equal to totalShares");if(t>ve||e>ve)throw new RangeError(`threshold and totalShares cannot exceed ${ve}`);let i=Kr.fromPrivateKey(this,t),r=[],s=new Set,o=new Vt,c=Pe(64);for(let f=0;f<e;f++){let d,l=0;do{let b=[f,l,...Pe(32)],g=Hu(c,b);if(d=new T(g).umod(o.p),l++,l>5)throw new Error("Failed to generate unique x coordinate after 5 attempts")}while(d.isZero()||s.has(d.toString()));s.add(d.toString());let p=i.valueAt(d);r.push(new nn(d,p))}let u=this.toPublicKey().toHash("hex").slice(0,8);return new ho(r,t,u)}toBackupShares(t,e){return this.toKeyShares(t,e).toBackupFormat()}static fromBackupShares(t){return n.fromKeyShares(ho.fromBackupFormat(t))}static fromKeyShares(t){if(t===null||typeof t!="object")throw new TypeError("keyShares must be an object");let e=t.points,i=t.threshold,r=t.integrity;if(Yu(e,i,r),e.length<i)throw new Error(`At least ${i} shares are required to reconstruct the private key`);let s=[],o=new Vt().p;for(let d=0;d<i;d++){if(!Object.prototype.hasOwnProperty.call(e,d))throw new TypeError("shares must be a dense array");let l=e[d];if(!(l instanceof nn)||!(l.x instanceof T)||!(l.y instanceof T))throw new TypeError("shares must contain finite-field points");if(l.x.isNeg()||l.y.isNeg()||l.x.gte(o)||l.y.gte(o))throw new TypeError("share coordinates must be canonical field elements");s.push(new nn(new T(l.x.toArray()),new T(l.y.toArray())))}for(let d=0;d<i;d++)for(let l=d+1;l<i;l++)if(s[d].x.eq(s[l].x))throw new Error("Duplicate share detected, each must be unique.");let c=new Kr(s,i),u=new n(c.valueAt(new T(0)).toArray());if(u.toPublicKey().toHash("hex").slice(0,8)!==r)throw new Error("Integrity hash mismatch");return u}};var Zu={OP_0:0,OP_FALSE:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_1:81,OP_TRUE: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_SPLIT:127,OP_NUM2BIN:128,OP_BIN2NUM: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_CHECKLOCKTIMEVERIFY:177,OP_NOP2:177,OP_CHECKSEQUENCEVERIFY:178,OP_NOP3:178,OP_SUBSTR:179,OP_NOP4:179,OP_LEFT:180,OP_NOP5:180,OP_RIGHT:181,OP_NOP6:181,OP_LSHIFTNUM:182,OP_NOP7:182,OP_RSHIFTNUM:183,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_NOP11:186,OP_NOP12:187,OP_NOP13:188,OP_NOP14:189,OP_NOP15:190,OP_NOP16:191,OP_NOP17:192,OP_NOP18:193,OP_NOP19:194,OP_NOP20:195,OP_NOP21:196,OP_NOP22:197,OP_NOP23:198,OP_NOP24:199,OP_NOP25:200,OP_NOP26:201,OP_NOP27:202,OP_NOP28:203,OP_NOP29:204,OP_NOP30:205,OP_NOP31:206,OP_NOP32:207,OP_NOP33:208,OP_NOP34:209,OP_NOP35:210,OP_NOP36:211,OP_NOP37:212,OP_NOP38:213,OP_NOP39:214,OP_NOP40:215,OP_NOP41:216,OP_NOP42:217,OP_NOP43:218,OP_NOP44:219,OP_NOP45:220,OP_NOP46:221,OP_NOP47:222,OP_NOP48:223,OP_NOP49:224,OP_NOP50:225,OP_NOP51:226,OP_NOP52:227,OP_NOP53:228,OP_NOP54:229,OP_NOP55:230,OP_NOP56:231,OP_NOP57:232,OP_NOP58:233,OP_NOP59:234,OP_NOP60:235,OP_NOP61:236,OP_NOP62:237,OP_NOP63:238,OP_NOP64:239,OP_NOP65:240,OP_NOP66:241,OP_NOP67:242,OP_NOP68:243,OP_NOP69:244,OP_NOP70:245,OP_NOP71:246,OP_NOP72:247,OP_NOP73:248,OP_NOP77:252,OP_SMALLDATA:249,OP_SMALLINTEGER:250,OP_PUBKEYS:251,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},_a=Zu;for(let n of Object.keys(Zu)){let t=Zu[n];_a[t]??(_a[t]=n)}var x=_a;var vh=typeof globalThis>"u"?void 0:globalThis.Buffer,Ah=Symbol();function fr(n){return n[Ah]()}function ey(n){let t=n.data?.length??0;if(t===0||n.op===x.OP_RETURN||n.op<x.OP_PUSHDATA1)return[n.op];if(n.op===x.OP_PUSHDATA1)return[n.op,t&255];if(n.op===x.OP_PUSHDATA2)return[n.op,t&255,t>>8&255];if(n.op===x.OP_PUSHDATA4){let e=t>>>0;return[n.op,e&255,e>>8&255,e>>16&255,e>>24&255]}}function ny(n,t){let e=ey(n),i=n.data??[];if(e==null||t.length!==e.length+i.length)return!1;for(let r=0;r<e.length;r++)if(t[r]!==e[r])return!1;for(let r=0;r<i.length;r++)if(t[e.length+r]!==i[r])return!1;return!0}var Ve,Kn,Ke,On,ur,te,Eh,kh,_t,Ju,Th,Oh,Vn,Qu,Ph,Ca,Rh,tf,Nh,Bh,ef,_h,fe=class fe{constructor(t=[],e,i,r=!0){G(this,_t);G(this,Ve);G(this,Kn);G(this,Ke);G(this,On);G(this,ur);N(this,Ve,t),N(this,Kn,r),N(this,Ke,e),N(this,On,i)}static fromASM(t){var s;let e=[],i=t.split(" "),r=0;for(;r<i.length;){let{chunk:o,advance:c}=a(s=fe,te,kh).call(s,i,r);e.push(o),r+=c}return new fe(e)}static fromHex(t){if(t.length===0)return fe.fromBinary([]);if(t.length%2!==0)throw new Error("There is an uneven number of characters in the string which suggests it is not hex encoded.");let e;try{e=io(t)}catch{throw new Error("Some elements in this string are not hex encoded.")}return new fe([],e,t.toLowerCase(),!1)}static fromBinary(t){let e=Uint8Array.from(t);return new fe([],e,void 0,!1)}static fromBinaryView(t){return new fe([],t,void 0,!1)}get chunks(){return a(this,_t,Ju).call(this),y(this,Ve)}set chunks(t){N(this,Ve,t),N(this,Kn,!0),a(this,_t,Vn).call(this)}toASM(){let t="";for(let e of this.chunks)t+=a(this,_t,_h).call(this,e);return t.slice(1)}toHex(){let t=a(this,_t,Ca).call(this);if(y(this,On)!=null)return y(this,On);let e=vh==null?ka(Array.from(t),"hex"):vh.from(t).toString("hex");return N(this,On,e),e}toBinary(){return Array.from(this.toUint8Array())}toUint8Array(){return Uint8Array.from(a(this,_t,Ca).call(this))}[Ah](){return a(this,_t,Ca).call(this)}writeScript(t){return a(this,_t,Vn).call(this),this.chunks=this.chunks.concat(t.chunks),this}writeOpCode(t){return a(this,_t,Vn).call(this),this.chunks.push({op:t}),this}setChunkOpCode(t,e){return a(this,_t,Vn).call(this),this.chunks[t]={op:e},this}writeBn(t){if(a(this,_t,Vn).call(this),t.cmpn(0)===x.OP_0)this.chunks.push({op:x.OP_0});else if(t.cmpn(-1)===0)this.chunks.push({op:x.OP_1NEGATE});else if(t.cmpn(1)>=0&&t.cmpn(16)<=0)this.chunks.push({op:t.toNumber()+x.OP_1-1});else{let e=t.toSm("little");this.writeBin(e)}return this}writeBin(t){a(this,_t,Vn).call(this);let e,i=t.length>0?t:void 0;if(t.length>0&&t.length<x.OP_PUSHDATA1)e=t.length;else if(t.length===0)e=x.OP_0;else if(t.length<Math.pow(2,8))e=x.OP_PUSHDATA1;else if(t.length<Math.pow(2,16))e=x.OP_PUSHDATA2;else if(t.length<Math.pow(2,32))e=x.OP_PUSHDATA4;else throw new Error("You can't push that much data");return this.chunks.push({data:i,op:e}),this}writeNumber(t){return a(this,_t,Vn).call(this),this.writeBn(new T(t)),this}removeCodeseparators(){var e;let t=this.toUint8Array();return N(this,Ke,Uint8Array.from(a(e=fe,te,Bh).call(e,t,x.OP_CODESEPARATOR))),N(this,On,void 0),N(this,Ve,[]),N(this,Kn,!1),this}findAndDelete(t){a(this,_t,Vn).call(this);let e=t.toUint8Array();if(e.length===0)return this;for(let i=0;i<this.chunks.length;)ny(this.chunks[i],e)?this.chunks.splice(i,1):i++;return this}isPushOnly(){for(let t of this.chunks)if(t.op>x.OP_16)return!1;return!0}isLockingScript(){throw new Error("Not implemented")}isUnlockingScript(){throw new Error("Not implemented")}};Ve=new WeakMap,Kn=new WeakMap,Ke=new WeakMap,On=new WeakMap,ur=new WeakMap,te=new WeakSet,Eh=function(t){return t>=0&&t<x.OP_PUSHDATA1?t:t<Math.pow(2,8)?x.OP_PUSHDATA1:t<Math.pow(2,16)?x.OP_PUSHDATA2:x.OP_PUSHDATA4},kh=function(t,e){var o;let i=t[e];if(i==="0")return{chunk:{op:0},advance:1};if(i==="-1")return{chunk:{op:x.OP_1NEGATE},advance:1};let r=i.startsWith("OP_")&&x[i]!==void 0,s=r?x[i]:0;if(s===x.OP_PUSHDATA1||s===x.OP_PUSHDATA2||s===x.OP_PUSHDATA4)return{chunk:{data:at(t[e+2],"hex"),op:s},advance:3};if(!r){let c=i;c.length%2!==0&&(c="0"+c);let u=at(c,"hex");if(ka(u,"hex")!==c)throw new Error("invalid hex string in script");return{chunk:{data:u,op:a(o=fe,te,Eh).call(o,u.length)},advance:1}}return{chunk:{op:s},advance:1}},_t=new WeakSet,Ju=function(){var t;y(this,Kn)||(y(this,Ke)!=null?N(this,Ve,a(t=fe,te,Nh).call(t,y(this,Ke))):N(this,Ve,[]),N(this,Kn,!0),a(this,_t,Qu).call(this))},Th=function(t){let e=0;for(let i of t){if(e+=1,i.data==null)continue;let r=i.data.length;if(i.op===x.OP_RETURN){e+=r;break}i.op<x.OP_PUSHDATA1?e+=r:i.op===x.OP_PUSHDATA1?e+=1+r:i.op===x.OP_PUSHDATA2?e+=2+r:i.op===x.OP_PUSHDATA4&&(e+=4+r)}return e},Oh=function(){var s,o;let t=this.chunks,e=a(s=fe,te,Th).call(s,t),i=new Uint8Array(e),r=0;for(let c of t)if(i[r++]=c.op,c.data!=null){if(c.op===x.OP_RETURN){i.set(c.data,r);break}r=a(o=fe,te,Rh).call(o,i,r,c.op,c.data)}return i},Vn=function(){N(this,Ke,void 0),N(this,On,void 0),N(this,ur,void 0)},Qu=function(){N(this,ur,y(this,Ve).map(t=>({ref:t,op:t.op,dataRef:t.data,data:t.data==null?void 0:Array.from(t.data)})))},Ph=function(){if(y(this,ur)?.length!==y(this,Ve).length)return!1;for(let t=0;t<y(this,Ve).length;t++){let e=y(this,Ve)[t],i=y(this,ur)[t];if(i.ref!==e||i.op!==e.op||i.dataRef!==e.data||i.data?.length!==e.data?.length)return!1;if(i.data!=null&&e.data!=null){for(let r=0;r<i.data.length;r++)if(i.data[r]!==e.data[r])return!1}}return!0},Ca=function(){return!y(this,Kn)&&y(this,Ke)!=null?y(this,Ke):(a(this,_t,Ju).call(this),(y(this,Ke)==null||!a(this,_t,Ph).call(this))&&(N(this,Ke,a(this,_t,Oh).call(this)),N(this,On,void 0),a(this,_t,Qu).call(this)),y(this,Ke))},Rh=function(t,e,i,r){let s=r.length;if(i<x.OP_PUSHDATA1)return t.set(r,e),e+s;if(i===x.OP_PUSHDATA1)return t[e++]=s&255,t.set(r,e),e+s;if(i===x.OP_PUSHDATA2)return t[e++]=s&255,t[e++]=s>>8&255,t.set(r,e),e+s;if(i===x.OP_PUSHDATA4){let o=s>>>0;return t[e++]=o&255,t[e++]=o>>8&255,t[e++]=o>>16&255,t[e++]=o>>24&255,t.set(r,e),e+s}return e},tf=function(t,e,i,r){if(t>0&&t<x.OP_PUSHDATA1)return{len:t,newPos:i,hasLength:!0};if(t===x.OP_PUSHDATA1){let c=i<r;return{len:c?e[i++]??0:0,newPos:i,hasLength:c}}if(t===x.OP_PUSHDATA2){let c=i+1<r;return{len:(e[i]??0)|(e[i+1]??0)<<8,newPos:Math.min(i+2,r),hasLength:c}}let s=i+3<r;return{len:((e[i]??0)|(e[i+1]??0)<<8|(e[i+2]??0)<<16|(e[i+3]??0)<<24)>>>0,newPos:Math.min(i+4,r),hasLength:s}},Nh=function(t){var o,c,u;let e=[],i=t.length,r=0,s=0;for(;r<i;){let f=t[r++]??0;if(f===x.OP_RETURN&&s===0){e.push({op:f,data:a(o=fe,te,ef).call(o,t,r,i)});break}if(f===x.OP_IF||f===x.OP_NOTIF||f===x.OP_VERIF||f===x.OP_VERNOTIF?s++:f===x.OP_ENDIF&&s--,f>0&&f<=x.OP_PUSHDATA4){let{len:d,newPos:l,hasLength:p}=a(c=fe,te,tf).call(c,f,t,r,i);r=l;let b=Math.min(r+d,i),g=!p||b-r!==d;e.push({data:a(u=fe,te,ef).call(u,t,r,b),op:f,invalidLength:g}),r=b}else e.push({op:f})}return e},Bh=function(t,e){var o;let i=[],r=t.length,s=0;for(;s<r;){let c=s,u=t[s++]??0;if(u>0&&u<=x.OP_PUSHDATA4){let{len:f,newPos:d}=a(o=fe,te,tf).call(o,u,t,s,r);s=d;let l=Math.min(s+f,r);if(u!==e)for(let p=c;p<l;p++)i.push(t[p]??0);s=l}else u!==e&&i.push(u)}return i},ef=function(t,e,i){let r=Math.max(i-e,0),s=Array.from({length:r},()=>0);for(let o=0;o<r;o++)s[o]=t[e+o]??0;return s},_h=function(t){let e=t.op,i="";if(t.data===void 0){let r=x[e];i=`${i} ${r}`}else i=`${i} ${nt(t.data)}`;return i},G(fe,te);var ge=fe;var iy=new Uint8Array(0),nf=Object.freeze(Array.from({length:32},()=>0));function ry(n,t,e){return e>0&&e<x.OP_PUSHDATA1?{length:e,nextPosition:t}:e===x.OP_PUSHDATA1?n.length-t<1?void 0:{length:n[t],nextPosition:t+1}:e===x.OP_PUSHDATA2?n.length-t<2?void 0:{length:n[t]|n[t+1]<<8,nextPosition:t+2}:e===x.OP_PUSHDATA4?n.length-t<4?void 0:{length:(n[t]|n[t+1]<<8|n[t+2]<<16|n[t+3]<<24)>>>0,nextPosition:t+4}:{length:0,nextPosition:t}}function sy(n){let t=n.toBinary(),e=[],i=0,r=0,s=0,o=c=>{for(let u=r;u<c;u++)e.push(t[u])};for(;i<t.length;){let c=i,u=t[i++],f=ry(t,i,u);if(f==null||(i=f.nextPosition,t.length-i<f.length))break;i+=f.length,u===x.OP_CODESEPARATOR&&(o(c),r=i,s++)}return o(i),{bytes:e,encodedLength:t.length-s}}function oy(n,t){if(n.allInputs!=null)return n.allInputs;let e=[...n.otherInputs];return e.splice(n.inputIndex,0,t),e}function Uh(n,t,e,i){return i===t?e:n[i]}function ay(n,t,e){let i=new ue;for(let r=0;r<n.length;r++){let s=Uh(n,t,e,r);if(s.sourceTXID==null){if(s.sourceTransaction==null)throw new Error("Missing sourceTransaction for input");i.write(s.sourceTransaction.hash())}else i.writeReverse(at(s.sourceTXID,"hex"));i.writeUInt32LE(s.sourceOutputIndex)}return zt(i.toUint8Array())}function cy(n,t,e){let i=new ue;for(let r=0;r<n.length;r++){let s=Uh(n,t,e,r);i.writeUInt32LE(s.sequence??4294967295)}return zt(i.toUint8Array())}function Ch(n,t){n.writeUInt64LE(t.satoshis??0);let e=t.lockingScript?.toUint8Array()??iy;n.writeVarIntNum(e.length),n.write(e)}function Lh(n,t){let e=new ue;if(t==null)for(let i of n)Ch(e,i);else{let i=n[t];if(i==null)throw new Error(`Output at index ${t} does not exist`);Ch(e,i)}return zt(e.toUint8Array())}function uy(n,t,e){if((n.scope&yt.SIGHASH_ANYONECANPAY)!==0)return[...nf];if(n.cache?.hashPrevouts!=null)return n.cache.hashPrevouts;let i=ay(t,n.inputIndex,e);return n.cache!=null&&(n.cache.hashPrevouts=i),i}function fy(n,t,e){let i=n.scope&31;if((n.scope&yt.SIGHASH_ANYONECANPAY)!==0||i===yt.SIGHASH_SINGLE||i===yt.SIGHASH_NONE)return[...nf];if(n.cache?.hashSequence!=null)return n.cache.hashSequence;let r=cy(t,n.inputIndex,e);return n.cache!=null&&(n.cache.hashSequence=r),r}function dy(n){var r;let t=n.scope&31;if(t!==yt.SIGHASH_SINGLE&&t!==yt.SIGHASH_NONE){if(n.cache?.hashOutputsAll!=null)return n.cache.hashOutputsAll;let s=Lh(n.outputs);return n.cache!=null&&(n.cache.hashOutputsAll=s),s}if(t!==yt.SIGHASH_SINGLE||n.inputIndex>=n.outputs.length)return[...nf];let e=n.cache?.hashOutputsSingle?.get(n.inputIndex);if(e!=null)return e;let i=Lh(n.outputs,n.inputIndex);return n.cache!=null&&((r=n.cache).hashOutputsSingle??(r.hashOutputsSingle=new Map),n.cache.hashOutputsSingle.set(n.inputIndex,i)),i}var Xt=class Xt extends pe{constructor(e,i,r){super(e,i);m(this,"scope");this.scope=r}static formatOTDA(e){let i=(e.scope&Xt.SIGHASH_ANYONECANPAY)===Xt.SIGHASH_ANYONECANPAY,r=(e.scope&31)===Xt.SIGHASH_SINGLE,s=(e.scope&31)===Xt.SIGHASH_NONE,o=(e.scope&31)===Xt.SIGHASH_ALL||!r&&!s,c=sy(e.subscript),u={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence,script:c.bytes,scriptLength:c.encodedLength},f=new ue;function d(g){f.writeVarIntNum(g.length);for(let w of g)f.writeReverse(at(w.sourceTXID,"hex")),f.writeUInt32LE(w.sourceOutputIndex),f.writeVarIntNum(w.scriptLength??w.script.length),f.write(w.script),f.writeUInt32LE(w.sequence)}function l(g){f.writeVarIntNum(g.length);for(let w of g)f.writeUInt64LE(w.satoshis),f.writeVarIntNum(w.script.length),f.write(w.script)}f.writeInt32LE(e.transactionVersion);let p=new ge().toBinary();if(i)i&&d([u]);else{let g=e.allInputs==null?e.otherInputs.map(w=>({sourceTXID:w.sourceTXID??w.sourceTransaction?.id("hex")??"",sourceOutputIndex:w.sourceOutputIndex,sequence:r||s?0:w.sequence??4294967295,script:p})):e.allInputs.map((w,S)=>S===e.inputIndex?u:{sourceTXID:w.sourceTXID??w.sourceTransaction?.id("hex")??"",sourceOutputIndex:w.sourceOutputIndex,sequence:r||s?0:w.sequence??4294967295,script:p});e.allInputs==null&&g.splice(e.inputIndex,0,u),d(g)}if(o){let g=e.outputs.map(w=>({satoshis:w.satoshis??0,script:w.lockingScript.toBinary()}));l(g)}else if(r){let g=[];for(let S=0;S<e.inputIndex;S++)g.push({satoshis:-1,script:p});let w=e.outputs[e.inputIndex];w!==void 0&&g.push({satoshis:w.satoshis??0,script:w.lockingScript.toBinary()}),l(g)}else s&&l([]);return f.writeUInt32LE(e.lockTime),f.writeUInt32LE(e.scope>>>0),f.toUint8Array()}static formatBip143(e){let i={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence},r=oy(e,i),s=uy(e,r,i),o=fy(e,r,i),c=dy(e),u=new ue;u.writeInt32LE(e.transactionVersion),u.write(s),u.write(o),u.writeReverse(at(e.sourceTXID,"hex")),u.writeUInt32LE(e.sourceOutputIndex);let f=e.subscript.toUint8Array();u.writeVarIntNum(f.length),u.write(f),u.writeUInt64LE(e.sourceSatoshis);let d=i.sequence??4294967295;return u.writeUInt32LE(d),u.write(c),u.writeUInt32LE(e.lockTime),u.writeUInt32LE(e.scope>>>0),u.toUint8Array()}static format(e){return Array.from(this.formatBytes(e))}static formatBytes(e){let i=(e.scope&Xt.SIGHASH_FORKID)!==0,r=e.ignoreChronicle!==!0&&(e.scope&Xt.SIGHASH_CHRONICLE)!==0;return i&&e.sighashForkIdEnabled!==!1&&!r?Xt.formatBip143(e):e.sighashForkIdEnabled===!1||!i||r?Xt.formatOTDA(e):new Uint8Array(0)}static usesOtdaSingleBug(e){let i=(e.scope&Xt.SIGHASH_FORKID)!==0,r=e.ignoreChronicle!==!0&&(e.scope&Xt.SIGHASH_CHRONICLE)!==0;return(e.sighashForkIdEnabled===!1||!i||r)&&(e.scope&31)===Xt.SIGHASH_SINGLE&&e.inputIndex>=e.outputs.length}static fromChecksigFormat(e){if(e.length===0){let o=new T(1),c=new T(1),u=1;return new Xt(o,c,u)}let i=e.at(-1),r=e.slice(0,-1),s=pe.fromDER(r);return new Xt(s.r,s.s,i)}hasLowS(){return!(this.s.ltn(1)||this.s.gt(new T("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex")))}toChecksigFormat(){return[...this.toDER(),this.scope]}};m(Xt,"SIGHASH_ALL",1),m(Xt,"SIGHASH_NONE",2),m(Xt,"SIGHASH_SINGLE",3),m(Xt,"SIGHASH_CHRONICLE",32),m(Xt,"SIGHASH_FORKID",64),m(Xt,"SIGHASH_ANYONECANPAY",128);var yt=Xt;function rf(n,t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${n} returned a non-byte result`);if(e!==void 0&&t.length!==e)throw new Error(`${n} returned ${t.length} bytes; expected ${e}`);return t}function ly(){return globalThis}function sf(n){let t=ly().__bsvSdkAsyncCryptoBackendV1;if(t!==void 0){if(!t.isReady()){t.preload().catch(()=>{});return}return t.supportsCrypto(n)?t:void 0}}var Le=class extends ge{isLockingScript(){return!0}isUnlockingScript(){return!1}};var Ue=class extends ge{isLockingScript(){return!1}isUnlockingScript(){return!0}};function Mh(n){return n==null?"null/undef":n.length===void 0?"INVALID_STACK_ITEM":nt(n)}var po=class extends Error{constructor(e){let i=e.stackState.map(Mh).join(", "),r=e.altStackState.map(Mh).join(", "),s=`Context: ${e.context}, PC: ${e.programCounter}`,o=`Stack: [${i}] (len: ${e.stackState.length}, mem: ${e.stackMem})`,c=`AltStack: [${r}] (len: ${e.altStackState.length}, mem: ${e.altStackMem})`,u=`IfStack: [${e.ifStackState.join(", ")}]`,f=`Script evaluation error: ${e.message}
|
|
1
|
+
"use strict";var bWalletXConnect=(()=>{var Ub=Object.create;var Us=Object.defineProperty;var Mb=Object.getOwnPropertyDescriptor;var Db=Object.getOwnPropertyNames;var Hb=Object.getPrototypeOf,$b=Object.prototype.hasOwnProperty;var Sl=n=>{throw TypeError(n)};var qb=(n,t,e)=>t in n?Us(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var Iu=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var Fb=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports),vu=(n,t)=>{for(var e in t)Us(n,e,{get:t[e],enumerable:!0})},Il=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Db(t))!$b.call(n,r)&&r!==e&&Us(n,r,{get:()=>t[r],enumerable:!(i=Mb(t,r))||i.enumerable});return n};var Wb=(n,t,e)=>(e=n!=null?Ub(Hb(n)):{},Il(t||!n||!n.__esModule?Us(e,"default",{value:n,enumerable:!0}):e,n)),Vb=n=>Il(Us({},"__esModule",{value:!0}),n);var b=(n,t,e)=>qb(n,typeof t!="symbol"?t+"":t,e),Au=(n,t,e)=>t.has(n)||Sl("Cannot "+e);var y=(n,t,e)=>(Au(n,t,"read from private field"),e?e.call(n):t.get(n)),G=(n,t,e)=>t.has(n)?Sl("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),N=(n,t,e,i)=>(Au(n,t,"write to private field"),i?i.call(n,e):t.set(n,e),e),a=(n,t,e)=>(Au(n,t,"access private method"),e);var Rb=Fb((Ob,Pb)=>{"use strict";var Tb=(function(){var n=function(E,A){var k=236,B=17,_=E,H=e[A],O=null,I=0,U=null,M=[],F={},it=function($,W){I=_*4+17,O=(function(D){for(var V=new Array(D),X=0;X<D;X+=1){V[X]=new Array(D);for(var J=0;J<D;J+=1)V[X][J]=null}return V})(I),ot(0,0),ot(I-7,0),ot(0,I-7),tt(),z(),ce($,W),_>=7&&St($),U==null&&(U=ke(_,H,M)),Bt(U,W)},ot=function($,W){for(var D=-1;D<=7;D+=1)if(!($+D<=-1||I<=$+D))for(var V=-1;V<=7;V+=1)W+V<=-1||I<=W+V||(0<=D&&D<=6&&(V==0||V==6)||0<=V&&V<=6&&(D==0||D==6)||2<=D&&D<=4&&2<=V&&V<=4?O[$+D][W+V]=!0:O[$+D][W+V]=!1)},q=function(){for(var $=0,W=0,D=0;D<8;D+=1){it(!0,D);var V=r.getLostPoint(F);(D==0||$>V)&&($=V,W=D)}return W},z=function(){for(var $=8;$<I-8;$+=1)O[$][6]==null&&(O[$][6]=$%2==0);for(var W=8;W<I-8;W+=1)O[6][W]==null&&(O[6][W]=W%2==0)},tt=function(){for(var $=r.getPatternPosition(_),W=0;W<$.length;W+=1)for(var D=0;D<$.length;D+=1){var V=$[W],X=$[D];if(O[V][X]==null)for(var J=-2;J<=2;J+=1)for(var dt=-2;dt<=2;dt+=1)J==-2||J==2||dt==-2||dt==2||J==0&&dt==0?O[V+J][X+dt]=!0:O[V+J][X+dt]=!1}},St=function($){for(var W=r.getBCHTypeNumber(_),D=0;D<18;D+=1){var V=!$&&(W>>D&1)==1;O[Math.floor(D/3)][D%3+I-8-3]=V}for(var D=0;D<18;D+=1){var V=!$&&(W>>D&1)==1;O[D%3+I-8-3][Math.floor(D/3)]=V}},ce=function($,W){for(var D=H<<3|W,V=r.getBCHTypeInfo(D),X=0;X<15;X+=1){var J=!$&&(V>>X&1)==1;X<6?O[X][8]=J:X<8?O[X+1][8]=J:O[I-15+X][8]=J}for(var X=0;X<15;X+=1){var J=!$&&(V>>X&1)==1;X<8?O[8][I-X-1]=J:X<9?O[8][15-X-1+1]=J:O[8][15-X-1]=J}O[I-8][8]=!$},Bt=function($,W){for(var D=-1,V=I-1,X=7,J=0,dt=r.getMaskFunction(W),ft=I-1;ft>0;ft-=2)for(ft==6&&(ft-=1);;){for(var Ct=0;Ct<2;Ct+=1)if(O[V][ft-Ct]==null){var re=!1;J<$.length&&(re=($[J]>>>X&1)==1);var pt=dt(V,ft-Ct);pt&&(re=!re),O[V][ft-Ct]=re,X-=1,X==-1&&(J+=1,X=7)}if(V+=D,V<0||I<=V){V-=D,D=-D;break}}},dn=function($,W){for(var D=0,V=0,X=0,J=new Array(W.length),dt=new Array(W.length),ft=0;ft<W.length;ft+=1){var Ct=W[ft].dataCount,re=W[ft].totalCount-Ct;V=Math.max(V,Ct),X=Math.max(X,re),J[ft]=new Array(Ct);for(var pt=0;pt<J[ft].length;pt+=1)J[ft][pt]=255&$.getBuffer()[pt+D];D+=Ct;var Qe=r.getErrorCorrectPolynomial(re),tn=o(J[ft],Qe.getLength()-1),wl=tn.mod(Qe);dt[ft]=new Array(Qe.getLength()-1);for(var pt=0;pt<dt[ft].length;pt+=1){var yl=pt+wl.getLength()-dt[ft].length;dt[ft][pt]=yl>=0?wl.getAt(yl):0}}for(var xl=0,pt=0;pt<W.length;pt+=1)xl+=W[pt].totalCount;for(var Su=new Array(xl),sa=0,pt=0;pt<V;pt+=1)for(var ft=0;ft<W.length;ft+=1)pt<J[ft].length&&(Su[sa]=J[ft][pt],sa+=1);for(var pt=0;pt<X;pt+=1)for(var ft=0;ft<W.length;ft+=1)pt<dt[ft].length&&(Su[sa]=dt[ft][pt],sa+=1);return Su},ke=function($,W,D){for(var V=c.getRSBlocks($,W),X=u(),J=0;J<D.length;J+=1){var dt=D[J];X.put(dt.getMode(),4),X.put(dt.getLength(),r.getLengthInBits(dt.getMode(),$)),dt.write(X)}for(var ft=0,J=0;J<V.length;J+=1)ft+=V[J].dataCount;if(X.getLengthInBits()>ft*8)throw"code length overflow. ("+X.getLengthInBits()+">"+ft*8+")";for(X.getLengthInBits()+4<=ft*8&&X.put(0,4);X.getLengthInBits()%8!=0;)X.putBit(!1);for(;!(X.getLengthInBits()>=ft*8||(X.put(k,8),X.getLengthInBits()>=ft*8));)X.put(B,8);return dn(X,V)};F.addData=function($,W){W=W||"Byte";var D=null;switch(W){case"Numeric":D=f($);break;case"Alphanumeric":D=d($);break;case"Byte":D=l($);break;case"Kanji":D=p($);break;default:throw"mode:"+W}M.push(D),U=null},F.isDark=function($,W){if($<0||I<=$||W<0||I<=W)throw $+","+W;return O[$][W]},F.getModuleCount=function(){return I},F.make=function(){if(_<1){for(var $=1;$<40;$++){for(var W=c.getRSBlocks($,H),D=u(),V=0;V<M.length;V++){var X=M[V];D.put(X.getMode(),4),D.put(X.getLength(),r.getLengthInBits(X.getMode(),$)),X.write(D)}for(var J=0,V=0;V<W.length;V++)J+=W[V].dataCount;if(D.getLengthInBits()<=J*8)break}_=$}it(!1,q())},F.createTableTag=function($,W){$=$||2,W=typeof W>"u"?$*4:W;var D="";D+='<table style="',D+=" border-width: 0px; border-style: none;",D+=" border-collapse: collapse;",D+=" padding: 0px; margin: "+W+"px;",D+='">',D+="<tbody>";for(var V=0;V<F.getModuleCount();V+=1){D+="<tr>";for(var X=0;X<F.getModuleCount();X+=1)D+='<td style="',D+=" border-width: 0px; border-style: none;",D+=" border-collapse: collapse;",D+=" padding: 0px; margin: 0px;",D+=" width: "+$+"px;",D+=" height: "+$+"px;",D+=" background-color: ",D+=F.isDark(V,X)?"#000000":"#ffffff",D+=";",D+='"/>';D+="</tr>"}return D+="</tbody>",D+="</table>",D},F.createSvgTag=function($,W,D,V){var X={};typeof arguments[0]=="object"&&(X=arguments[0],$=X.cellSize,W=X.margin,D=X.alt,V=X.title),$=$||2,W=typeof W>"u"?$*4:W,D=typeof D=="string"?{text:D}:D||{},D.text=D.text||null,D.id=D.text?D.id||"qrcode-description":null,V=typeof V=="string"?{text:V}:V||{},V.text=V.text||null,V.id=V.text?V.id||"qrcode-title":null;var J=F.getModuleCount()*$+W*2,dt,ft,Ct,re,pt="",Qe;for(Qe="l"+$+",0 0,"+$+" -"+$+",0 0,-"+$+"z ",pt+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"',pt+=X.scalable?"":' width="'+J+'px" height="'+J+'px"',pt+=' viewBox="0 0 '+J+" "+J+'" ',pt+=' preserveAspectRatio="xMinYMin meet"',pt+=V.text||D.text?' role="img" aria-labelledby="'+xe([V.id,D.id].join(" ").trim())+'"':"",pt+=">",pt+=V.text?'<title id="'+xe(V.id)+'">'+xe(V.text)+"</title>":"",pt+=D.text?'<description id="'+xe(D.id)+'">'+xe(D.text)+"</description>":"",pt+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>',pt+='<path d="',Ct=0;Ct<F.getModuleCount();Ct+=1)for(re=Ct*$+W,dt=0;dt<F.getModuleCount();dt+=1)F.isDark(Ct,dt)&&(ft=dt*$+W,pt+="M"+ft+","+re+Qe);return pt+='" stroke="transparent" fill="black"/>',pt+="</svg>",pt},F.createDataURL=function($,W){$=$||2,W=typeof W>"u"?$*4:W;var D=F.getModuleCount()*$+W*2,V=W,X=D-W;return C(D,D,function(J,dt){if(V<=J&&J<X&&V<=dt&&dt<X){var ft=Math.floor((J-V)/$),Ct=Math.floor((dt-V)/$);return F.isDark(Ct,ft)?0:1}else return 1})},F.createImgTag=function($,W,D){$=$||2,W=typeof W>"u"?$*4:W;var V=F.getModuleCount()*$+W*2,X="";return X+="<img",X+=' src="',X+=F.createDataURL($,W),X+='"',X+=' width="',X+=V,X+='"',X+=' height="',X+=V,X+='"',D&&(X+=' alt="',X+=xe(D),X+='"'),X+="/>",X};var xe=function($){for(var W="",D=0;D<$.length;D+=1){var V=$.charAt(D);switch(V){case"<":W+="<";break;case">":W+=">";break;case"&":W+="&";break;case'"':W+=""";break;default:W+=V;break}}return W},vn=function($){var W=1;$=typeof $>"u"?W*2:$;var D=F.getModuleCount()*W+$*2,V=$,X=D-$,J,dt,ft,Ct,re,pt={"\u2588\u2588":"\u2588","\u2588 ":"\u2580"," \u2588":"\u2584"," ":" "},Qe={"\u2588\u2588":"\u2580","\u2588 ":"\u2580"," \u2588":" "," ":" "},tn="";for(J=0;J<D;J+=2){for(ft=Math.floor((J-V)/W),Ct=Math.floor((J+1-V)/W),dt=0;dt<D;dt+=1)re="\u2588",V<=dt&&dt<X&&V<=J&&J<X&&F.isDark(ft,Math.floor((dt-V)/W))&&(re=" "),V<=dt&&dt<X&&V<=J+1&&J+1<X&&F.isDark(Ct,Math.floor((dt-V)/W))?re+=" ":re+="\u2588",tn+=$<1&&J+1>=X?Qe[re]:pt[re];tn+=`
|
|
2
|
+
`}return D%2&&$>0?tn.substring(0,tn.length-D-1)+Array(D+1).join("\u2580"):tn.substring(0,tn.length-1)};return F.createASCII=function($,W){if($=$||1,$<2)return vn(W);$-=1,W=typeof W>"u"?$*2:W;var D=F.getModuleCount()*$+W*2,V=W,X=D-W,J,dt,ft,Ct,re=Array($+1).join("\u2588\u2588"),pt=Array($+1).join(" "),Qe="",tn="";for(J=0;J<D;J+=1){for(ft=Math.floor((J-V)/$),tn="",dt=0;dt<D;dt+=1)Ct=1,V<=dt&&dt<X&&V<=J&&J<X&&F.isDark(ft,Math.floor((dt-V)/$))&&(Ct=0),tn+=Ct?re:pt;for(ft=0;ft<$;ft+=1)Qe+=tn+`
|
|
3
|
+
`}return Qe.substring(0,Qe.length-1)},F.renderTo2dContext=function($,W){W=W||2;for(var D=F.getModuleCount(),V=0;V<D;V++)for(var X=0;X<D;X++)$.fillStyle=F.isDark(V,X)?"black":"white",$.fillRect(V*W,X*W,W,W)},F};n.stringToBytesFuncs={default:function(E){for(var A=[],k=0;k<E.length;k+=1){var B=E.charCodeAt(k);A.push(B&255)}return A}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(E,A){var k=(function(){for(var _=w(E),H=function(){var z=_.read();if(z==-1)throw"eof";return z},O=0,I={};;){var U=_.read();if(U==-1)break;var M=H(),F=H(),it=H(),ot=String.fromCharCode(U<<8|M),q=F<<8|it;I[ot]=q,O+=1}if(O!=A)throw O+" != "+A;return I})(),B=63;return function(_){for(var H=[],O=0;O<_.length;O+=1){var I=_.charCodeAt(O);if(I<128)H.push(I);else{var U=k[_.charAt(O)];typeof U=="number"?(U&255)==U?H.push(U):(H.push(U>>>8),H.push(U&255)):H.push(B)}}return H}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},e={L:1,M:0,Q:3,H:2},i={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var E=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],A=1335,k=7973,B=21522,_={},H=function(O){for(var I=0;O!=0;)I+=1,O>>>=1;return I};return _.getBCHTypeInfo=function(O){for(var I=O<<10;H(I)-H(A)>=0;)I^=A<<H(I)-H(A);return(O<<10|I)^B},_.getBCHTypeNumber=function(O){for(var I=O<<12;H(I)-H(k)>=0;)I^=k<<H(I)-H(k);return O<<12|I},_.getPatternPosition=function(O){return E[O-1]},_.getMaskFunction=function(O){switch(O){case i.PATTERN000:return function(I,U){return(I+U)%2==0};case i.PATTERN001:return function(I,U){return I%2==0};case i.PATTERN010:return function(I,U){return U%3==0};case i.PATTERN011:return function(I,U){return(I+U)%3==0};case i.PATTERN100:return function(I,U){return(Math.floor(I/2)+Math.floor(U/3))%2==0};case i.PATTERN101:return function(I,U){return I*U%2+I*U%3==0};case i.PATTERN110:return function(I,U){return(I*U%2+I*U%3)%2==0};case i.PATTERN111:return function(I,U){return(I*U%3+(I+U)%2)%2==0};default:throw"bad maskPattern:"+O}},_.getErrorCorrectPolynomial=function(O){for(var I=o([1],0),U=0;U<O;U+=1)I=I.multiply(o([1,s.gexp(U)],0));return I},_.getLengthInBits=function(O,I){if(1<=I&&I<10)switch(O){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+O}else if(I<27)switch(O){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+O}else if(I<41)switch(O){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+O}else throw"type:"+I},_.getLostPoint=function(O){for(var I=O.getModuleCount(),U=0,M=0;M<I;M+=1)for(var F=0;F<I;F+=1){for(var it=0,ot=O.isDark(M,F),q=-1;q<=1;q+=1)if(!(M+q<0||I<=M+q))for(var z=-1;z<=1;z+=1)F+z<0||I<=F+z||q==0&&z==0||ot==O.isDark(M+q,F+z)&&(it+=1);it>5&&(U+=3+it-5)}for(var M=0;M<I-1;M+=1)for(var F=0;F<I-1;F+=1){var tt=0;O.isDark(M,F)&&(tt+=1),O.isDark(M+1,F)&&(tt+=1),O.isDark(M,F+1)&&(tt+=1),O.isDark(M+1,F+1)&&(tt+=1),(tt==0||tt==4)&&(U+=3)}for(var M=0;M<I;M+=1)for(var F=0;F<I-6;F+=1)O.isDark(M,F)&&!O.isDark(M,F+1)&&O.isDark(M,F+2)&&O.isDark(M,F+3)&&O.isDark(M,F+4)&&!O.isDark(M,F+5)&&O.isDark(M,F+6)&&(U+=40);for(var F=0;F<I;F+=1)for(var M=0;M<I-6;M+=1)O.isDark(M,F)&&!O.isDark(M+1,F)&&O.isDark(M+2,F)&&O.isDark(M+3,F)&&O.isDark(M+4,F)&&!O.isDark(M+5,F)&&O.isDark(M+6,F)&&(U+=40);for(var St=0,F=0;F<I;F+=1)for(var M=0;M<I;M+=1)O.isDark(M,F)&&(St+=1);var ce=Math.abs(100*St/I/I-50)/5;return U+=ce*10,U},_})(),s=(function(){for(var E=new Array(256),A=new Array(256),k=0;k<8;k+=1)E[k]=1<<k;for(var k=8;k<256;k+=1)E[k]=E[k-4]^E[k-5]^E[k-6]^E[k-8];for(var k=0;k<255;k+=1)A[E[k]]=k;var B={};return B.glog=function(_){if(_<1)throw"glog("+_+")";return A[_]},B.gexp=function(_){for(;_<0;)_+=255;for(;_>=256;)_-=255;return E[_]},B})();function o(E,A){if(typeof E.length>"u")throw E.length+"/"+A;var k=(function(){for(var _=0;_<E.length&&E[_]==0;)_+=1;for(var H=new Array(E.length-_+A),O=0;O<E.length-_;O+=1)H[O]=E[O+_];return H})(),B={};return B.getAt=function(_){return k[_]},B.getLength=function(){return k.length},B.multiply=function(_){for(var H=new Array(B.getLength()+_.getLength()-1),O=0;O<B.getLength();O+=1)for(var I=0;I<_.getLength();I+=1)H[O+I]^=s.gexp(s.glog(B.getAt(O))+s.glog(_.getAt(I)));return o(H,0)},B.mod=function(_){if(B.getLength()-_.getLength()<0)return B;for(var H=s.glog(B.getAt(0))-s.glog(_.getAt(0)),O=new Array(B.getLength()),I=0;I<B.getLength();I+=1)O[I]=B.getAt(I);for(var I=0;I<_.getLength();I+=1)O[I]^=s.gexp(s.glog(_.getAt(I))+H);return o(O,0).mod(_)},B}var c=(function(){var E=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],A=function(_,H){var O={};return O.totalCount=_,O.dataCount=H,O},k={},B=function(_,H){switch(H){case e.L:return E[(_-1)*4+0];case e.M:return E[(_-1)*4+1];case e.Q:return E[(_-1)*4+2];case e.H:return E[(_-1)*4+3];default:return}};return k.getRSBlocks=function(_,H){var O=B(_,H);if(typeof O>"u")throw"bad rs block @ typeNumber:"+_+"/errorCorrectionLevel:"+H;for(var I=O.length/3,U=[],M=0;M<I;M+=1)for(var F=O[M*3+0],it=O[M*3+1],ot=O[M*3+2],q=0;q<F;q+=1)U.push(A(it,ot));return U},k})(),u=function(){var E=[],A=0,k={};return k.getBuffer=function(){return E},k.getAt=function(B){var _=Math.floor(B/8);return(E[_]>>>7-B%8&1)==1},k.put=function(B,_){for(var H=0;H<_;H+=1)k.putBit((B>>>_-H-1&1)==1)},k.getLengthInBits=function(){return A},k.putBit=function(B){var _=Math.floor(A/8);E.length<=_&&E.push(0),B&&(E[_]|=128>>>A%8),A+=1},k},f=function(E){var A=t.MODE_NUMBER,k=E,B={};B.getMode=function(){return A},B.getLength=function(O){return k.length},B.write=function(O){for(var I=k,U=0;U+2<I.length;)O.put(_(I.substring(U,U+3)),10),U+=3;U<I.length&&(I.length-U==1?O.put(_(I.substring(U,U+1)),4):I.length-U==2&&O.put(_(I.substring(U,U+2)),7))};var _=function(O){for(var I=0,U=0;U<O.length;U+=1)I=I*10+H(O.charAt(U));return I},H=function(O){if("0"<=O&&O<="9")return O.charCodeAt(0)-48;throw"illegal char :"+O};return B},d=function(E){var A=t.MODE_ALPHA_NUM,k=E,B={};B.getMode=function(){return A},B.getLength=function(H){return k.length},B.write=function(H){for(var O=k,I=0;I+1<O.length;)H.put(_(O.charAt(I))*45+_(O.charAt(I+1)),11),I+=2;I<O.length&&H.put(_(O.charAt(I)),6)};var _=function(H){if("0"<=H&&H<="9")return H.charCodeAt(0)-48;if("A"<=H&&H<="Z")return H.charCodeAt(0)-65+10;switch(H){case" ":return 36;case"$":return 37;case"%":return 38;case"*":return 39;case"+":return 40;case"-":return 41;case".":return 42;case"/":return 43;case":":return 44;default:throw"illegal char :"+H}};return B},l=function(E){var A=t.MODE_8BIT_BYTE,k=E,B=n.stringToBytes(E),_={};return _.getMode=function(){return A},_.getLength=function(H){return B.length},_.write=function(H){for(var O=0;O<B.length;O+=1)H.put(B[O],8)},_},p=function(E){var A=t.MODE_KANJI,k=E,B=n.stringToBytesFuncs.SJIS;if(!B)throw"sjis not supported.";(function(O,I){var U=B(O);if(U.length!=2||(U[0]<<8|U[1])!=I)throw"sjis not supported."})("\u53CB",38726);var _=B(E),H={};return H.getMode=function(){return A},H.getLength=function(O){return~~(_.length/2)},H.write=function(O){for(var I=_,U=0;U+1<I.length;){var M=(255&I[U])<<8|255&I[U+1];if(33088<=M&&M<=40956)M-=33088;else if(57408<=M&&M<=60351)M-=49472;else throw"illegal char at "+(U+1)+"/"+M;M=(M>>>8&255)*192+(M&255),O.put(M,13),U+=2}if(U<I.length)throw"illegal char at "+(U+1)},H},m=function(){var E=[],A={};return A.writeByte=function(k){E.push(k&255)},A.writeShort=function(k){A.writeByte(k),A.writeByte(k>>>8)},A.writeBytes=function(k,B,_){B=B||0,_=_||k.length;for(var H=0;H<_;H+=1)A.writeByte(k[H+B])},A.writeString=function(k){for(var B=0;B<k.length;B+=1)A.writeByte(k.charCodeAt(B))},A.toByteArray=function(){return E},A.toString=function(){var k="";k+="[";for(var B=0;B<E.length;B+=1)B>0&&(k+=","),k+=E[B];return k+="]",k},A},g=function(){var E=0,A=0,k=0,B="",_={},H=function(I){B+=String.fromCharCode(O(I&63))},O=function(I){if(!(I<0)){if(I<26)return 65+I;if(I<52)return 97+(I-26);if(I<62)return 48+(I-52);if(I==62)return 43;if(I==63)return 47}throw"n:"+I};return _.writeByte=function(I){for(E=E<<8|I&255,A+=8,k+=1;A>=6;)H(E>>>A-6),A-=6},_.flush=function(){if(A>0&&(H(E<<6-A),E=0,A=0),k%3!=0)for(var I=3-k%3,U=0;U<I;U+=1)B+="="},_.toString=function(){return B},_},w=function(E){var A=E,k=0,B=0,_=0,H={};H.read=function(){for(;_<8;){if(k>=A.length){if(_==0)return-1;throw"unexpected end of file./"+_}var I=A.charAt(k);if(k+=1,I=="=")return _=0,-1;if(I.match(/^\s$/))continue;B=B<<6|O(I.charCodeAt(0)),_+=6}var U=B>>>_-8&255;return _-=8,U};var O=function(I){if(65<=I&&I<=90)return I-65;if(97<=I&&I<=122)return I-97+26;if(48<=I&&I<=57)return I-48+52;if(I==43)return 62;if(I==47)return 63;throw"c:"+I};return H},S=function(E,A){var k=E,B=A,_=new Array(E*A),H={};H.setPixel=function(M,F,it){_[F*k+M]=it},H.write=function(M){M.writeString("GIF87a"),M.writeShort(k),M.writeShort(B),M.writeByte(128),M.writeByte(0),M.writeByte(0),M.writeByte(0),M.writeByte(0),M.writeByte(0),M.writeByte(255),M.writeByte(255),M.writeByte(255),M.writeString(","),M.writeShort(0),M.writeShort(0),M.writeShort(k),M.writeShort(B),M.writeByte(0);var F=2,it=I(F);M.writeByte(F);for(var ot=0;it.length-ot>255;)M.writeByte(255),M.writeBytes(it,ot,255),ot+=255;M.writeByte(it.length-ot),M.writeBytes(it,ot,it.length-ot),M.writeByte(0),M.writeString(";")};var O=function(M){var F=M,it=0,ot=0,q={};return q.write=function(z,tt){if(z>>>tt)throw"length over";for(;it+tt>=8;)F.writeByte(255&(z<<it|ot)),tt-=8-it,z>>>=8-it,ot=0,it=0;ot=z<<it|ot,it=it+tt},q.flush=function(){it>0&&F.writeByte(ot)},q},I=function(M){for(var F=1<<M,it=(1<<M)+1,ot=M+1,q=U(),z=0;z<F;z+=1)q.add(String.fromCharCode(z));q.add(String.fromCharCode(F)),q.add(String.fromCharCode(it));var tt=m(),St=O(tt);St.write(F,ot);var ce=0,Bt=String.fromCharCode(_[ce]);for(ce+=1;ce<_.length;){var dn=String.fromCharCode(_[ce]);ce+=1,q.contains(Bt+dn)?Bt=Bt+dn:(St.write(q.indexOf(Bt),ot),q.size()<4095&&(q.size()==1<<ot&&(ot+=1),q.add(Bt+dn)),Bt=dn)}return St.write(q.indexOf(Bt),ot),St.write(it,ot),St.flush(),tt.toByteArray()},U=function(){var M={},F=0,it={};return it.add=function(ot){if(it.contains(ot))throw"dup key:"+ot;M[ot]=F,F+=1},it.size=function(){return F},it.indexOf=function(ot){return M[ot]},it.contains=function(ot){return typeof M[ot]<"u"},it};return H},C=function(E,A,k){for(var B=S(E,A),_=0;_<A;_+=1)for(var H=0;H<E;H+=1)B.setPixel(H,_,k(H,_));var O=m();B.write(O);for(var I=g(),U=O.toByteArray(),M=0;M<U.length;M+=1)I.writeByte(U[M]);return I.flush(),"data:image/gif;base64,"+I};return n})();(function(){Tb.stringToBytesFuncs["UTF-8"]=function(n){function t(e){for(var i=[],r=0;r<e.length;r++){var s=e.charCodeAt(r);s<128?i.push(s):s<2048?i.push(192|s>>6,128|s&63):s<55296||s>=57344?i.push(224|s>>12,128|s>>6&63,128|s&63):(r++,s=65536+((s&1023)<<10|e.charCodeAt(r)&1023),i.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|s&63))}return i}return t(n)}})();(function(n){typeof define=="function"&&define.amd?define([],n):typeof Ob=="object"&&(Pb.exports=n())})(function(){return Tb})});var x4={};vu(x4,{ACCESS_ERROR_STATUS:()=>ub,ACCESS_PROTOCOL:()=>gu,ACCESS_VERSION:()=>ab,AccessError:()=>kt,BRC29_PROTOCOL:()=>cl,BWALLETX_RDNS:()=>Qo,DEFAULT_DISCOVER_MS:()=>Vi,GET_URL:()=>nl,LOGIN_PROTOCOL:()=>jd,LOGO_URL:()=>al,PROTOCOL_MEDIA:()=>Gd,PaymentError:()=>he,RDNS_EXTENSION:()=>Ns,RDNS_MOBILE:()=>Dd,SIGNIN_CSS:()=>sl,SIGNIN_TAG:()=>el,WALLET_THEME_META:()=>xu,WEB_WALLET_URL:()=>ra,accessErrorMessage:()=>lb,amountInSats:()=>ll,bindPrewarm:()=>fu,brc100Option:()=>Ls,buildAuthorizeUrl:()=>ol,buyToken:()=>Ib,canonicalJson:()=>ia,clearPairing:()=>ob,connectBwalletX:()=>na,declareWalletTheme:()=>Lb,defineBwalletxSignin:()=>yu,discoverBwalletX:()=>Ki,discoverWallets:()=>kb,findBwalletX:()=>jm,handcashAdapter:()=>Eb,inOrder:()=>ta,isIdentityKeyHex:()=>ul,isPaymail:()=>fl,isTouchDevice:()=>bl,markSvg:()=>rl,pairBwalletX:()=>_s,pairingModal:()=>_b,pairingOption:()=>gl,pay:()=>pl,pickWallet:()=>Cb,prewarmBwalletX:()=>Hd,protocolMediaUrl:()=>fb,proveHoldings:()=>Jd,qrSvg:()=>ml,renderButton:()=>mb,requestAccess:()=>bu,resolvePaymailP2P:()=>hl,restorePairing:()=>Cs,signInWithBwalletX:()=>pu,signinText:()=>il,throwIfAccessError:()=>Zd,tip:()=>Sb,toAccessError:()=>mu});var Eu=globalThis.Buffer,Kb=Eu!=null&&typeof Eu.from=="function",$s=new Int8Array(256).fill(-1);for(let n=0;n<10;n++)$s[48+n]=n;for(let n=0;n<6;n++)$s[65+n]=10+n,$s[97+n]=10+n;var qs,Fs,aa,ca,fi,ua,Ws,Y,rt,It,R,vl,Al,El,kl,Tl,Ol,ku,_e,An,st,Pl,Ms,Ds,Rl,Nl,ji,Bl,_l,Cl,Lt,ue,Hs,oa,Xi,Tu,Ll,Ou,Z=class Z{constructor(t=0,e=10,i="be"){G(this,R);G(this,Y,0n);G(this,rt,0);G(this,It,1);b(this,"red",null);if(t??(t=0),typeof t=="bigint"){a(this,R,_e).call(this,t<0n?-t:t,t<0n?1:0),this.normSign();return}let r=e==="le"||e==="be",s=r?10:e,o=r?e:i;if(typeof t=="number"){a(this,R,Pl).call(this,t,o);return}if(Array.isArray(t)){a(this,R,Ms).call(this,t,o);return}if(typeof t=="string"){a(this,R,Al).call(this,t,s,o);return}t!==0?a(this,R,st).call(this,!1,"Unsupported input type for BigNumber constructor"):a(this,R,_e).call(this,0n,0)}get negative(){return y(this,rt)}set negative(t){a(this,R,st).call(this,t===0||t===1,"Negative property must be 0 or 1");let e=t===1?1:0;y(this,Y)===0n?N(this,rt,0):N(this,rt,e)}get words(){if(!Number.isSafeInteger(y(this,It))||y(this,It)<1||y(this,It)>y(Z,Ws))throw new Error("BigNumber word length exceeds the supported limit");let t=y(this,R,vl);if(y(this,It)<=t.length)return t;let e=Array.from({length:y(this,It)}).fill(0);for(let i=0;i<t.length;i++)e[i]=t[i];return e}set words(t){let e=y(this,rt),i=0n,r=t.length>0?t.length:1;for(let s=r-1;s>=0;s--){let o=t[s]??0;i=i<<y(Z,qs)|BigInt(o&Number(y(Z,Fs)))}N(this,Y,i),N(this,rt,e),N(this,It,r),this.normSign()}get length(){return Math.max(1,y(this,It))}static isBN(t){return t instanceof Z?!0:t!==null&&typeof t=="object"&&t.constructor?.wordSize===Z.wordSize&&Array.isArray(t.words)}static max(t,e){return t.cmp(e)>0?t:e}static min(t,e){return t.cmp(e)<0?t:e}copy(t){N(t,Y,y(this,Y)),N(t,rt,y(this,rt)),N(t,It,y(this,It)),t.red=this.red}static move(t,e){N(t,Y,y(e,Y)),N(t,rt,y(e,rt)),N(t,It,y(e,It)),t.red=e.red}clone(){let t=new Z(0n);return this.copy(t),t}expand(t){return a(this,R,st).call(this,Number.isSafeInteger(t)&&t>=0&&t<=y(Z,Ws),"Expand size must be a non-negative safe integer within the supported word limit"),N(this,It,Math.max(y(this,It),t,1)),this}strip(){return a(this,R,An).call(this),this.normSign()}normSign(){return y(this,Y)===0n&&N(this,rt,0),this}inspect(){return(this.red===null?"<BN: ":"<BN-R: ")+this.toString(16)+">"}toString(t=10,e=1){if(t===16||t==="hex")return a(this,R,Rl).call(this,e);if(typeof t!="number"||t<2||t>36||t%1!==0)throw new Error("Base should be an integer between 2 and 36");return a(this,R,Nl).call(this,t,e)}toNumber(){let t=a(this,R,Lt).call(this);if(t>y(Z,aa)||t<y(Z,ca))throw new Error("Number can only safely store up to 53 bits");return Number(t)}toBigInt(){return a(this,R,Lt).call(this)}toJSON(){let t=a(this,R,Ds).call(this);return(this.isNeg()?"-":"")+t}toArray(t="be",e){this.strip();let i=this.byteLength(),r=e??Math.max(1,i);a(this,R,st).call(this,i<=r,"byte array longer than desired length"),a(this,R,st).call(this,r>0,"Requested array length <= 0");let s=Array.from({length:r}).fill(0);return y(this,Y)===0n&&r>0?s:y(this,Y)===0n&&r===0?[]:(a(this,R,Cl).call(this,s,t==="le"),s)}bitLength(){return y(this,Y)===0n?0:y(this,Y).toString(2).length}static toBitArray(t){let e=t.bitLength();if(e===0)return[];let i=Array.from({length:e}),r=y(t,Y);for(let s=0;s<e;s++)i[s]=(r>>BigInt(s)&1n)===0n?0:1;return i}toBitArray(){return Z.toBitArray(this)}zeroBits(){if(y(this,Y)===0n)return 0;let t=0,e=y(this,Y);for(;(e&1n)===0n&&e!==0n;)t++,e>>=1n;return t}byteLength(){return y(this,Y)===0n?0:Math.ceil(this.bitLength()/8)}toTwos(t){var o;a(this,R,st).call(this,t>=0);let e=BigInt(t),i=a(this,R,Lt).call(this);y(this,rt)===1&&y(this,Y)!==0n&&(i=(1n<<e)+i);let r=(1n<<e)-1n;i&=r;let s=new Z(0n);return a(o=s,R,_e).call(o,i,0),s}fromTwos(t){var r;a(this,R,st).call(this,t>=0);let e=BigInt(t),i=y(this,Y);if(t>0&&(i>>e-1n&1n)!==0n&&y(this,rt)===0){let s=i-(1n<<e),o=new Z(0n);return a(r=o,R,ue).call(r,s),o}return this.clone()}isNeg(){return y(this,rt)===1&&y(this,Y)!==0n}neg(){return this.clone().ineg()}ineg(){return y(this,Y)!==0n&&N(this,rt,y(this,rt)===1?0:1),this}iuor(t){return a(this,R,Hs).call(this,t,(e,i)=>e|i)}iuand(t){return a(this,R,Hs).call(this,t,(e,i)=>e&i)}iuxor(t){return a(this,R,Hs).call(this,t,(e,i)=>e^i,!0)}ior(t){return a(this,R,oa).call(this,t,(e,i)=>e|i)}iand(t){return a(this,R,oa).call(this,t,(e,i)=>e&i)}ixor(t){return a(this,R,oa).call(this,t,(e,i)=>e^i,!0)}or(t){return a(this,R,st).call(this,y(this,rt)===0&&y(t,rt)===0),a(this,R,Xi).call(this,t,"iuor")}uor(t){return a(this,R,Xi).call(this,t,"iuor")}and(t){return a(this,R,st).call(this,y(this,rt)===0&&y(t,rt)===0),a(this,R,Xi).call(this,t,"iuand")}uand(t){return a(this,R,Xi).call(this,t,"iuand")}xor(t){return a(this,R,st).call(this,y(this,rt)===0&&y(t,rt)===0),a(this,R,Xi).call(this,t,"iuxor")}uxor(t){return a(this,R,Xi).call(this,t,"iuxor")}inotn(t){a(this,R,st).call(this,typeof t=="number"&&t>=0);let i=(1n<<BigInt(t))-1n;N(this,Y,~y(this,Y)&i);let r=t===0?1:Math.ceil(t/Z.wordSize);return N(this,It,Math.max(1,r)),this.strip(),N(this,It,Math.max(y(this,It),Math.max(1,r))),this}notn(t){return this.clone().inotn(t)}setn(t,e){a(this,R,st).call(this,typeof t=="number"&&t>=0);let i=BigInt(t);e===1||e===!0?N(this,Y,y(this,Y)|1n<<i):N(this,Y,y(this,Y)&~(1n<<i));let r=Math.floor(t/Z.wordSize)+1;return N(this,It,Math.max(y(this,It),r)),a(this,R,An).call(this),this.strip()}iadd(t){var e;return a(this,R,ue).call(this,a(this,R,Lt).call(this)+a(e=t,R,Lt).call(e)),this}add(t){var i,r;let e=new Z(0n);return a(r=e,R,ue).call(r,a(this,R,Lt).call(this)+a(i=t,R,Lt).call(i)),e}isub(t){var e;return a(this,R,ue).call(this,a(this,R,Lt).call(this)-a(e=t,R,Lt).call(e)),this}sub(t){var i,r;let e=new Z(0n);return a(r=e,R,ue).call(r,a(this,R,Lt).call(this)-a(i=t,R,Lt).call(i)),e}mul(t){let e=new Z(0n);return N(e,Y,y(this,Y)*y(t,Y)),N(e,rt,y(e,Y)===0n?0:y(this,rt)^y(t,rt)),N(e,It,this.length+t.length),e.red=null,e.normSign()}imul(t){return N(this,Y,y(this,Y)*y(t,Y)),N(this,rt,y(this,Y)===0n?0:y(this,rt)^y(t,rt)),N(this,It,this.length+t.length),this.red=null,this.normSign()}imuln(t){return a(this,R,st).call(this,typeof t=="number","Assertion failed"),a(this,R,st).call(this,Math.abs(t)<=y(Z,fi),"Assertion failed"),a(this,R,ue).call(this,a(this,R,Lt).call(this)*BigInt(t)),this}muln(t){return this.clone().imuln(t)}sqr(){let t=new Z(0n);return N(t,Y,y(this,Y)*y(this,Y)),N(t,rt,0),N(t,It,this.length*2),t.red=null,t}isqr(){return N(this,Y,y(this,Y)*y(this,Y)),N(this,rt,0),N(this,It,this.length*2),this.red=null,this}pow(t){if(a(this,R,st).call(this,y(t,rt)===0,"Exponent for pow must be non-negative"),t.isZero())return new Z(1n);let e=new Z(1n),i=this.clone(),r=t.clone(),s=i.isNeg(),o=r.isOdd();for(s&&i.ineg();!r.isZero();)r.isOdd()&&e.imul(i),i.isqr(),r.iushrn(1);return s&&o&&e.ineg(),e}iushln(t){var i;let e=a(i=Z,ji,Tu).call(i,t,"Shift bits");return e===0n?this:(N(this,Y,y(this,Y)<<e),a(this,R,An).call(this),this.strip())}ishln(t){return a(this,R,st).call(this,y(this,rt)===0,"ishln requires positive number"),this.iushln(t)}iushrn(t,e,i){var s,o,c;let r=a(s=Z,ji,Tu).call(s,t,"Shift bits");if(r===0n)return i!=null&&a(o=i,R,_e).call(o,0n,0),this;if(i!=null){let u=(1n<<r)-1n,f=y(this,Y)&u;a(c=i,R,_e).call(c,f,0)}return N(this,Y,y(this,Y)>>r),a(this,R,An).call(this),this.strip()}ishrn(t,e,i){return a(this,R,st).call(this,y(this,rt)===0,"ishrn requires positive number"),this.iushrn(t,e,i)}shln(t){return this.clone().ishln(t)}ushln(t){return this.clone().iushln(t)}shrn(t){return this.clone().ishrn(t)}ushrn(t){return this.clone().iushrn(t)}testn(t){return a(this,R,st).call(this,typeof t=="number"&&t>=0),(y(this,Y)>>BigInt(t)&1n)!==0n}imaskn(t){a(this,R,st).call(this,typeof t=="number"&&t>=0),a(this,R,st).call(this,y(this,rt)===0,"imaskn works only with positive numbers");let e=BigInt(t),i=e===0n?0n:(1n<<e)-1n;N(this,Y,y(this,Y)&i);let r=t===0?1:Math.max(1,Math.ceil(t/Z.wordSize));return N(this,It,r),a(this,R,An).call(this),N(this,It,Math.max(y(this,It),r)),this.strip()}maskn(t){return this.clone().imaskn(t)}iaddn(t){return a(this,R,st).call(this,typeof t=="number"),a(this,R,st).call(this,Math.abs(t)<=y(Z,fi),"num is too large"),a(this,R,ue).call(this,a(this,R,Lt).call(this)+BigInt(t)),this}_iaddn(t){return this.iaddn(t)}isubn(t){return a(this,R,st).call(this,typeof t=="number"),a(this,R,st).call(this,Math.abs(t)<=y(Z,fi),"Assertion failed"),a(this,R,ue).call(this,a(this,R,Lt).call(this)-BigInt(t)),this}addn(t){return this.clone().iaddn(t)}subn(t){return this.clone().isubn(t)}iabs(){return N(this,rt,0),this}abs(){return this.clone().iabs()}divmod(t,e,i){var u;if(a(this,R,st).call(this,!t.isZero(),"Division by zero"),this.isZero()){let f=new Z(0n);return{div:e==="mod"?null:f,mod:e==="div"?null:f}}let r=a(this,R,Lt).call(this),s=a(u=t,R,Lt).call(u),o=e!=="mod"?r/s:null,c=a(this,R,Ll).call(this,r,s,e,i);return{div:a(this,R,Ou).call(this,o),mod:a(this,R,Ou).call(this,c)}}div(t){return this.divmod(t,"div",!1).div}mod(t){return this.divmod(t,"mod",!1).mod}umod(t){return this.divmod(t,"mod",!0).mod}divRound(t){var f,d,l;a(this,R,st).call(this,!t.isZero());let e=a(this,R,Lt).call(this),i=a(f=t,R,Lt).call(f),r=e/i,s=e%i;if(s===0n){let p=new Z(0n);return a(d=p,R,ue).call(d,r),p}let o=s<0n?-s:s,c=i<0n?-i:i;o*2n>=c&&(e>0n&&i>0n||e<0n&&i<0n?r+=1n:r-=1n);let u=new Z(0n);return a(l=u,R,ue).call(l,r),u}modrn(t){a(this,R,st).call(this,t!==0,"Division by zero in modrn");let e=BigInt(Math.abs(t));if(e===0n)throw new Error("Division by zero in modrn");let i=y(this,Y)%e;return t<0?Number(-i):Number(i)}idivn(t){return a(this,R,st).call(this,t!==0),a(this,R,st).call(this,Math.abs(t)<=y(Z,fi),"num is too large"),a(this,R,ue).call(this,a(this,R,Lt).call(this)/BigInt(t)),this}divn(t){return this.clone().idivn(t)}egcd(t){var l,p,m;a(this,R,st).call(this,t.negative===0,"p must not be negative"),a(this,R,st).call(this,!t.isZero(),"p must not be zero");let e=a(this,R,Lt).call(this),i=y(t,Y),r=1n,s=0n,o=0n,c=1n;for(;i!==0n;){let g=e/i,w=i;i=e%i,e=w,w=s,s=r-g*s,r=w,w=c,c=o-g*c,o=w}let u=new Z(0n);a(l=u,R,ue).call(l,r);let f=new Z(0n);a(p=f,R,ue).call(p,o);let d=new Z(0n);return a(m=d,R,_e).call(m,e<0n?-e:e,0),{a:u,b:f,gcd:d}}gcd(t){var s,o,c;let e=y(this,Y),i=y(t,Y);if(e===0n){let u=new Z(0n);return a(s=u,R,ue).call(s,i),u.iabs()}if(i===0n){let u=new Z(0n);return a(o=u,R,ue).call(o,e),u.iabs()}for(;i!==0n;){let u=e%i;e=i,i=u}let r=new Z(0n);return a(c=r,R,_e).call(c,e,0),r}invm(t){a(this,R,st).call(this,!t.isZero()&&y(t,rt)===0,"Modulus for invm must be positive and non-zero");let e=this.egcd(t);if(!e.gcd.eqn(1))throw new Error("Inverse does not exist (numbers are not coprime).");return e.a.umod(t)}isEven(){return y(this,Y)%2n===0n}isOdd(){return y(this,Y)%2n===1n}andln(t){return a(this,R,st).call(this,t>=0),Number(y(this,Y)&BigInt(t))}bincn(t){a(this,R,st).call(this,typeof t=="number"&&t>=0);let e=1n<<BigInt(t);return a(this,R,ue).call(this,a(this,R,Lt).call(this)+e),this}isZero(){return y(this,Y)===0n}cmpn(t){a(this,R,st).call(this,Math.abs(t)<=y(Z,fi),"Number is too big");let e=a(this,R,Lt).call(this),i=BigInt(t);return e<i?-1:e>i?1:0}cmp(t){var r;let e=a(this,R,Lt).call(this),i=a(r=t,R,Lt).call(r);return e<i?-1:e>i?1:0}ucmp(t){return y(this,Y)<y(t,Y)?-1:y(this,Y)>y(t,Y)?1:0}gtn(t){return this.cmpn(t)===1}gt(t){return this.cmp(t)===1}gten(t){return this.cmpn(t)>=0}gte(t){return this.cmp(t)>=0}ltn(t){return this.cmpn(t)===-1}lt(t){return this.cmp(t)===-1}lten(t){return this.cmpn(t)<=0}lte(t){return this.cmp(t)<=0}eqn(t){return this.cmpn(t)===0}eq(t){return this.cmp(t)===0}toRed(t){return a(this,R,st).call(this,this.red==null,"Already a number in reduction context"),a(this,R,st).call(this,y(this,rt)===0,"toRed works only with positives"),t.convertTo(this).forceRed(t)}fromRed(){return a(this,R,st).call(this,this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)}forceRed(t){return this.red=t,this}redAdd(t){return a(this,R,st).call(this,this.red,"redAdd works only with red numbers"),this.red.add(this,t)}redIAdd(t){return a(this,R,st).call(this,this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)}redSub(t){return a(this,R,st).call(this,this.red,"redSub works only with red numbers"),this.red.sub(this,t)}redISub(t){return a(this,R,st).call(this,this.red,"redISub works only with red numbers"),this.red.isub(this,t)}redShl(t){return a(this,R,st).call(this,this.red,"redShl works only with red numbers"),this.red.shl(this,t)}redMul(t){return a(this,R,st).call(this,this.red,"redMul works only with red numbers"),this.red.verify2(this,t),this.red.mul(this,t)}redIMul(t){return a(this,R,st).call(this,this.red,"redIMul works only with red numbers"),this.red.verify2(this,t),this.red.imul(this,t)}redSqr(){return a(this,R,st).call(this,this.red,"redSqr works only with red numbers"),this.red.verify1(this),this.red.sqr(this)}redISqr(){return a(this,R,st).call(this,this.red,"redISqr works only with red numbers"),this.red.verify1(this),this.red.isqr(this)}redSqrt(){return a(this,R,st).call(this,this.red,"redSqrt works only with red numbers"),this.red.verify1(this),this.red.sqrt(this)}redInvm(){return a(this,R,st).call(this,this.red,"redInvm works only with red numbers"),this.red.verify1(this),this.red.invm(this)}redNeg(){return a(this,R,st).call(this,this.red,"redNeg works only with red numbers"),this.red.verify1(this),this.red.neg(this)}redPow(t){return a(this,R,st).call(this,this.red!=null&&t.red==null,"redPow(normalNum)"),this.red.verify1(this),this.red.pow(this,t)}static fromHex(t,e){let i="be";return(e==="little"||e==="le")&&(i="le"),new Z(t,16,i)}toHex(t=0){if(this.isZero()&&t===0)return"";let e=a(this,R,Ds).call(this);e!=="0"&&e.length%2!==0&&(e="0"+e);let i=t*2;for(;e.length<i;)e="0"+e;return(this.isNeg()?"-":"")+e}static fromJSON(t){return new Z(t,16)}static fromNumber(t){return new Z(t)}static fromString(t,e){return new Z(t,e)}static fromSm(t,e="big"){var u;if(t.length===0)return new Z(0n);let i=t.slice();e==="little"&&i.reverse();let r=0;i.length>0&&(i[0]&128)!==0&&(r=1,i[0]&=127);let s;if(Kb)s=Eu.from(i).toString("hex");else{s="";for(let f of i)s+=f<16?"0"+f.toString(16):f.toString(16)}let o=s.length===0?0n:BigInt("0x"+s),c=new Z(0n);return a(u=c,R,_e).call(u,o,r),c}toSm(t="big"){if(y(this,Y)===0n)return y(this,rt)===1?[128]:[];let e=a(this,R,Ds).call(this);e.length%2!==0&&(e="0"+e);let i=e.length/2,r=Array.from({length:i});for(let o=0,c=0;o<e.length;o+=2){let u=$s[e.codePointAt(o)],f=$s[e.codePointAt(o+1)];r[c++]=(u&15)<<4|f&15}let s;return y(this,rt)===1?(r[0]&128)===0?(s=r.slice(),s[0]|=128):s=[128,...r]:(r[0]&128)===0?s=r.slice():s=[0,...r],t==="little"?s.reverse():s}static fromBits(t,e=!1){let i=t>>>24,r=t&8388607,s=(t&8388608)!==0;if(e&&s)throw new Error("negative bit set");if(i===0&&r===0){if(s&&e)throw new Error("negative bit set for zero value");return new Z(0n)}let o=new Z(r);return i<=3?o.iushrn((3-i)*8):o.iushln((i-3)*8),s&&o.ineg(),o}toBits(){if(this.strip(),this.isZero()&&!this.isNeg())return 0;let t=this.isNeg(),i=this.abs().toArray("be"),r=0;for(;r<i.length-1&&i[r]===0;)r++;i=i.slice(r);let s=i.length,o;if(s===0)o=0;else if(s<=3){o=0;for(let u=0;u<s;u++)o=o<<8|i[u]}else o=i[0]<<16|i[1]<<8|i[2];(o&8388608)!==0&&s<=255&&(o>>>=8,s++);let c=s<<24|o;return t&&(c|=8388608),c>>>0}static fromScriptNum(t,e=!1,i){if(i!==void 0&&t.length>i)throw new Error("script number overflow");if(t.length===0)return new Z(0n);if(e&&(t.at(-1)&127)===0&&(t.length<=1||(t.at(-2)&128)===0))throw new Error("non-minimally encoded script number");return Z.fromSm(t,"little")}toScriptNum(){return this.toSm("little")}_invmp(t){a(this,R,st).call(this,y(t,rt)===0,"p must not be negative for _invmp"),a(this,R,st).call(this,!t.isZero(),"p must not be zero for _invmp");let e=this.umod(t),i=t.subn(2);if(e.red!==null)return e.redPow(i);let r=new Z(1n),s=e.clone(),o=i.clone();for(;!o.isZero();)o.isOdd()&&(r=r.mul(s).umod(t)),s=s.sqr().umod(t),o.iushrn(1);return r}mulTo(t,e){return N(e,Y,y(this,Y)*y(t,Y)),N(e,rt,y(e,Y)===0n?0:y(this,rt)^y(t,rt)),N(e,It,this.length+t.length),e.red=null,e.normSign(),e}};qs=new WeakMap,Fs=new WeakMap,aa=new WeakMap,ca=new WeakMap,fi=new WeakMap,ua=new WeakMap,Ws=new WeakMap,Y=new WeakMap,rt=new WeakMap,It=new WeakMap,R=new WeakSet,vl=function(){if(y(this,Y)===0n)return[0];let t=[],e=y(this,Y);for(;e>0n;)t.push(Number(e&y(Z,Fs))),e>>=y(Z,qs);return t.length>0?t:[0]},Al=function(t,e,i){e==="hex"&&(e=16),a(this,R,st).call(this,typeof e=="number"&&e===Math.trunc(e)&&e>=2&&e<=36,"Base must be an integer between 2 and 36");let r=t.toString().replace(/\s+/g,""),s=0,o=0;r.startsWith("-")?(s++,o=1):r.startsWith("+")&&s++;let c=r.substring(s);if(c.length===0){a(this,R,_e).call(this,0n,o===1&&r.startsWith("-")?1:0),this.normSign();return}e===16?a(this,R,El).call(this,c,o,i):a(this,R,kl).call(this,c,e,o,i)},El=function(t,e,i){if(i==="le"){let r=[],s=t;s.length%2!==0&&(s="0"+s);for(let o=0;o<s.length;o+=2){let c=s.substring(o,o+2),u=Number.parseInt(c,16);if(Number.isNaN(u))throw new Error("Invalid character in "+s);r.push(u)}a(this,R,Ms).call(this,r,"le"),N(this,rt,e),this.normSign()}else{let r;try{r=BigInt("0x"+t)}catch{throw new Error("Invalid character in "+t)}a(this,R,_e).call(this,r,e),this.normSign()}},kl=function(t,e,i,r){try{if(a(this,R,Ol).call(this,t,e),N(this,rt,i),this.normSign(),r==="le"){let s=y(this,rt);a(this,R,Ms).call(this,this.toArray("be"),"le"),N(this,rt,s),this.normSign()}}catch(s){let o=s;throw o.message.includes("Invalid character in string")||o.message.includes("Invalid digit for base")||o.message.startsWith("Invalid character:")?new Error("Invalid character"):o}},Tl=function(t,e){if(t===0n)return"0";if(e<2||e>36)throw new Error("Base must be between 2 and 36");let i="0123456789abcdefghijklmnopqrstuvwxyz",r="",s=t>0n?t:-t,o=BigInt(e);for(;s>0n;)r=i[Number(s%o)]+r,s/=o;return r},Ol=function(t,e){N(this,Y,0n);let i=BigInt(e),r=Z.groupSizes[e],s=BigInt(Z.groupBases[e]);(r===0||s===0n)&&(r=Math.floor(Math.log(67108863)/Math.log(e)),r===0&&(r=1),s=i**BigInt(r));let o=0,c=t.length,u=c%r;if(u===0&&c>0&&(u=r),u>0){let f=t.substring(o,o+u);N(this,Y,BigInt(a(this,R,ku).call(this,f,e))),o+=u}for(;o<c;){let f=t.substring(o,o+r),d=BigInt(a(this,R,ku).call(this,f,e));N(this,Y,y(this,Y)*s+d),o+=r}a(this,R,An).call(this)},ku=function(t,e){let i=0;for(let r=0;r<t.length;r++){let s=t.codePointAt(r),o;if(s>=48&&s<=57)o=s-48;else if(s>=65&&s<=90)o=s-65+10;else if(s>=97&&s<=122)o=s-97+10;else throw new Error("Invalid character: "+t[r]);if(o>=e)throw new Error("Invalid character");i=i*e+o}return i},_e=function(t,e){N(this,Y,t),N(this,rt,t===0n?0:e),a(this,R,An).call(this)},An=function(){if(y(this,Y)===0n)N(this,It,1),N(this,rt,0);else{let t=y(this,Y).toString(2).length;N(this,It,Math.max(1,Math.ceil(t/Z.wordSize)))}},st=function(t,e="Assertion failed"){if(!t)throw new Error(e)},Pl=function(t,e="be"){if(a(this,R,st).call(this,BigInt(Math.abs(t))<=y(Z,ua),"The number is larger than 2 ^ 53 (unsafe)"),a(this,R,st).call(this,t%1===0,"Number must be an integer for BigNumber conversion"),a(this,R,_e).call(this,BigInt(Math.abs(t)),t<0?1:0),e==="le"){let i=y(this,rt),r=this.toArray("be");a(this,R,Ms).call(this,r,"le"),N(this,rt,i),this.normSign()}return this},Ms=function(t,e){if(t.length===0)return a(this,R,_e).call(this,0n,0),this;let i=0n;if(e==="be")for(let r of t)i=i<<8n|BigInt(r&255);else for(let r=t.length-1;r>=0;r--)i=i<<8n|BigInt(t[r]&255);return a(this,R,_e).call(this,i,0),this},Ds=function(){return y(this,Y)===0n?"0":y(this,Y).toString(16)},Rl=function(t){let e=a(this,R,Ds).call(this);if(t>1)for(e!=="0"&&e.length%2!==0&&(e="0"+e);e.length%t!==0;)e="0"+e;return(this.isNeg()?"-":"")+e},Nl=function(t,e){var c;if(y(this,Y)===0n)return a(c=Z,ji,Bl).call(c,e);let i=Z.groupSizes[t],r=BigInt(Z.groupBases[t]);(i===0||r===0n)&&(i=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(t)),i===0&&(i=1),r=BigInt(t)**BigInt(i));let s="",o=y(this,Y);for(;o>0n;){let u=o%r;o/=r;let f=a(this,R,Tl).call(this,u,t);s=(o>0n?a(this,R,_l).call(this,f,i):f)+s}if(e>0)for(;s.length<e;)s="0"+s;return(y(this,rt)===1?"-":"")+s},ji=new WeakSet,Bl=function(t){let e="0";if(t>1)for(;e.length<t;)e="0"+e;return e},_l=function(t,e){let i=e-t.length;return i<=0?t:i<Z.zeros.length?Z.zeros[i]+t:"0".repeat(i)+t},Cl=function(t,e){let i=y(this,Y),r=e?0:t.length-1,s=e?1:-1;for(let o of t){if(i===0n&&r>=0&&r<t.length)t[r]=0;else if(r>=0&&r<t.length)t[r]=Number(i&0xffn);else break;i>>=8n,r+=s}},Lt=function(){return y(this,rt)===1?-y(this,Y):y(this,Y)},ue=function(t){t<0n?(N(this,Y,-t),N(this,rt,1)):(N(this,Y,t),N(this,rt,0)),a(this,R,An).call(this),this.normSign()},Hs=function(t,e,i=!1){let r=e(y(this,Y),y(t,Y)),s=y(this,It);return i&&(s=Math.max(this.length,t.length)),N(this,Y,r),a(this,R,An).call(this),i&&N(this,It,Math.max(y(this,It),s)),this.strip()},oa=function(t,e,i=!1){return a(this,R,st).call(this,y(this,rt)===0&&y(t,rt)===0),a(this,R,Hs).call(this,t,e,i)},Xi=function(t,e){return this.length>=t.length?this.clone()[e](t):t.clone()[e](this)},Tu=function(t,e){if(typeof t=="number"){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return BigInt(t)}if(t<0n)throw new Error(`${e} must be a non-negative integer`);return t},Ll=function(t,e,i,r){if(i==="div")return null;let s=t%e;return r===!0&&s<0n&&(s+=e<0n?-e:e),s},Ou=function(t){var i;if(t===null)return null;let e=new Z(0n);return a(i=e,R,ue).call(i,t),e},G(Z,ji),b(Z,"zeros",["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"]),b(Z,"groupSizes",[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5]),b(Z,"groupBases",[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176]),b(Z,"wordSize",26),G(Z,qs,26n),G(Z,Fs,(1n<<26n)-1n),G(Z,aa,BigInt(Number.MAX_SAFE_INTEGER)),G(Z,ca,BigInt(Number.MIN_SAFE_INTEGER)),G(Z,fi,67108863),G(Z,ua,(1n<<53n)-1n),G(Z,Ws,1048576);var T=Z;var Vs=class{constructor(t,e){b(this,"name");b(this,"p");b(this,"k");b(this,"n");b(this,"tmp");this.name=t,this.p=new T(e,16),this.n=this.p.bitLength(),this.k=new T(BigInt(1)).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){let t=new T(BigInt(0)),e=Math.ceil(this.n/T.wordSize);return t.expand(Math.max(1,e)),t}ireduce(t){let e=t,i;do this.split(e,this.tmp),this.imulK(e),e.iadd(this.tmp),i=e.bitLength();while(i>this.n);let r=i<this.n?-1:e.ucmp(this.p);return r===0?e.words=[0]:r>0&&e.isub(this.p),e.strip(),e}split(t,e){t.iushrn(this.n,0,e)}imulK(t){return t.imul(this.k)}};var Ks=class extends Vs{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(t,e){let r=t.words,s=t.length,o=Math.min(s,9),c=Array.from({length:o+(s>9?1:0)},()=>0);for(let g=0;g<o;g++)c[g]=r[g];let u=o;if(s<=9){let g=Array.from({length:u},()=>0);for(let w=0;w<u;++w)g[w]=c[w];e.words=g,t.words=[0];return}let f=r[9];c[u++]=f&4194303;let d=Array.from({length:u},()=>0);for(let g=0;g<u;++g)d[g]=c[g];e.words=d;let l=Array.from({length:Math.max(1,s-9)},()=>0),p=0;for(let g=10;g<s;g++){let w=Math.trunc(r[g]);p<l.length&&(l[p++]=(w&4194303)<<4|f>>>22),f=w}f>>>=22,p<l.length?l[p++]=f:f!==0&&l.length>0;let m=Array.from({length:p},()=>0);for(let g=0;g<p;++g)m[g]=l[g];t.words=m}imulK(t){let e=t.words,i=t.length,r=i+2,s=Array.from({length:r},()=>0);for(let c=0;c<i;c++)s[c]=e[c];let o=0;for(let c=0;c<r;c++){let u=Math.trunc(s[c]);o+=u*977,s[c]=o&67108863,o=u*64+Math.trunc(o/67108864)}return t.words=s,t}};var Gi=class{constructor(t){b(this,"prime");b(this,"m");if(t==="k256"){let e=new Ks;this.m=e.p,this.prime=e}else this.assert(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}assert(t,e="Assertion failed"){if(!t)throw new Error(e)}verify1(t){this.assert(t.negative===0,"red works only with positives"),this.assert(t.red,"red works only with red numbers")}verify2(t,e){this.assert((t.negative|e.negative)===0,"red works only with positives"),this.assert(t.red!=null&&t.red===e.red,"red works only with red numbers")}imod(t){return this.prime!=null?this.prime.ireduce(t).forceRed(this):(T.move(t,t.umod(this.m).forceRed(this)),t)}neg(t){return t.isZero()?t.clone():this.m.sub(t).forceRed(this)}add(t,e){this.verify2(t,e);let i=t.clone();return i.iadd(e),i.isub(this.m),i.isNeg()&&i.iadd(this.m),i}iadd(t,e){return this.verify2(t,e),t.iadd(e),t.isub(this.m),t.isNeg()&&t.iadd(this.m),t}sub(t,e){this.verify2(t,e);let i=t.sub(e);return i.cmpn(0)<0&&i.iadd(this.m),i.forceRed(this)}isub(t,e){this.verify2(t,e);let i=t.isub(e);return i.cmpn(0)<0&&i.iadd(this.m),i}shl(t,e){return this.verify1(t),this.imod(t.ushln(e))}imul(t,e){return this.verify2(t,e),this.imod(t.imul(e))}mul(t,e){return this.verify2(t,e),this.imod(t.mul(e))}isqr(t){return this.imul(t,t.clone())}sqr(t){return this.mul(t,t)}sqrt(t){if(t.isZero())return t.clone();let e=this.m.andln(3);if(this.assert(e%2===1),e===3){let g=this.m.add(new T(1)).iushrn(2);return this.pow(t,g)}let i=this.m.subn(1),r=0;for(;!i.isZero()&&i.andln(1)===0;)r++,i.iushrn(1);this.assert(!i.isZero());let s=new T(1).toRed(this),o=s.redNeg(),c=this.m.subn(1).iushrn(1),u=this.m.bitLength(),f=new T(2*u*u).toRed(this);for(;this.pow(f,c).cmp(o)!==0;)f.redIAdd(o);let d=this.pow(f,i),l=this.pow(t,i.addn(1).iushrn(1)),p=this.pow(t,i),m=r;for(;p.cmp(s)!==0;){let g=p,w=0;for(;g.cmp(s)!==0;)g=g.redSqr(),w++;this.assert(w<m);let S=this.pow(d,new T(1).iushln(m-w-1));l=l.redMul(S),d=S.redSqr(),p=p.redMul(d),m=w}return l}invm(t){let e=t._invmp(this.m);return e.negative!==0?(e.negative=0,this.imod(e).redNeg()):this.imod(e)}pow(t,e){if(this.verify1(t),e.isZero())return new T(1).toRed(this);let i=new T(1).toRed(this),r=t.clone(),s=e.bitLength();for(let o=s-1;o>=0;o--)i=this.sqr(i),e.testn(o)&&(i=this.mul(i,r));return i}convertTo(t){let e=t.umod(this.m);return e===t?e.clone():e}convertFrom(t){let e=t.clone();return e.red=null,e}};var zs=class extends Gi{constructor(e){super(e);b(this,"shift");b(this,"r");b(this,"r2");b(this,"rinv");b(this,"minv");this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new T(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}convertTo(e){return this.imod(e.ushln(this.shift))}convertFrom(e){let i=this.imod(e.mul(this.rinv));return i.red=null,i}imul(e,i){if(e.isZero()||i.isZero())return e.words[0]=0,e.length=1,e;let r=e.imul(i),s=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(s).iushrn(this.shift),c=o;return o.cmp(this.m)>=0?c=o.isub(this.m):o.cmpn(0)<0&&(c=o.iadd(this.m)),c.forceRed(this)}mul(e,i){if(e.isZero()||i.isZero())return new T(0).forceRed(this);let r=e.mul(i),s=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(s).iushrn(this.shift),c=o;return o.cmp(this.m)>=0?c=o.isub(this.m):o.cmpn(0)<0&&(c=o.iadd(this.m)),c.forceRed(this)}invm(e){return this.imod(e._invmp(this.m).mul(this.r2)).forceRed(this)}};var yi={};vu(yi,{Reader:()=>eo,ReaderUint8Array:()=>bt,Writer:()=>fe,WriterUint8Array:()=>ht,base64ToArray:()=>oh,constantTimeEquals:()=>X1,encode:()=>Pa,fromBase58:()=>so,fromBase58Check:()=>co,hexToUint8Array:()=>ro,minimallyEncode:()=>Ra,toArray:()=>at,toBase58:()=>oo,toBase58Check:()=>ao,toBase64:()=>ve,toHex:()=>nt,toSafeString:()=>$1,toUTF8:()=>ah,toUTF8Strict:()=>Rt,toUint8Array:()=>et,verifyNotNull:()=>sr,zero2:()=>q1});var zb=new TextEncoder;function Se(n){return zb.encode(n)}function Fe(n){return Se(n).byteLength}function Yi(n){for(let t of n){let e=t.codePointAt(0);if(e<=31||e>=127&&e<=159)return!0}return!1}var Ta={};vu(Ta,{RIPEMD160:()=>Gs,SHA1:()=>nr,SHA1HMAC:()=>Cu,SHA256:()=>Bu,SHA256HMAC:()=>Fr,SHA512:()=>_u,SHA512HMAC:()=>ga,hash160:()=>Js,hash256:()=>zt,htonl:()=>Vl,pbkdf2:()=>C1,realHtonl:()=>U1,ripemd160:()=>$u,sha1:()=>qu,sha256:()=>Te,sha256hmac:()=>Qs,sha512:()=>g1,sha512hmac:()=>Fu,swapBytes32:()=>Wu,toArray:()=>Sa});var Xb=/^[0-9a-fA-F]*$/;function Xs(n){if(typeof n!="string")throw new TypeError("Invalid hex string");if(n.length!==0&&!Xb.test(n))throw new Error("Invalid hex string")}function Ul(n){if(Xs(n),n.length===0)return"";let t=n.toLowerCase();return t.length%2!==0&&(t="0"+t),t}var Pu=(n,t="Hash assertion failed")=>{if(!n)throw new Error(t)},pa=class{constructor(t,e,i,r){b(this,"pending",null);b(this,"pendingTotal",0);b(this,"blockSize");b(this,"outSize");b(this,"endian");b(this,"_delta8");b(this,"_delta32");b(this,"padLength");b(this,"hmacStrength");this.blockSize=t,this.outSize=e,this.hmacStrength=i,this.padLength=r/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}_update(t,e){throw new Error("Not implemented")}_digest(){throw new Error("Not implemented")}_digestHex(){throw new Error("Not implemented")}update(t,e){if(t=Sa(t,e),this.pending==null?this.pending=t:this.pending=this.pending.concat(t),this.pendingTotal+=t.length,this.pending.length>=this._delta8){t=this.pending;let i=t.length%this._delta8;this.pending=t.slice(t.length-i,t.length),this.pending.length===0&&(this.pending=null),t=e1(t,0,t.length-i,this.endian);for(let r=0;r<t.length;r+=this._delta32)this._update(t,r)}return this}digest(){return this.update(this._pad()),Pu(this.pending===null),this._digest()}digestHex(){return this.update(this._pad()),Pu(this.pending===null),this._digestHex()}_pad(){let t=this.pendingTotal;if(!Number.isSafeInteger(t)||t<0)throw new Error("Message too long for this hash function");let e=this._delta8,i=e-(t+this.padLength)%e,r=Array.from({length:i+this.padLength});r[0]=128;let s;for(s=1;s<i;s++)r[s]=0;let o=this.padLength,c=1n<<BigInt(o*8),u=BigInt(t)*8n;if(u>=c)throw new Error("Message too long for this hash function");if(this.endian==="big"){let f=Array.from({length:o});for(let d=o-1;d>=0;d--)f[d]=Number(u&0xffn),u>>=8n;for(let d=0;d<o;d++)r[s++]=f[d]}else for(let f=0;f<o;f++)r[s++]=Number(u&0xffn),u>>=8n;return r}};function jb(n,t,e){let i=n.codePointAt(t);return i<128?(e.push(i),t):i<2048?(e.push(i>>6|192,i&63|128),t):i>65535?(e.push(i>>18|240,i>>12&63|128,i>>6&63|128,i&63|128),t+1):(e.push(i>>12|224,i>>6&63|128,i&63|128),t)}function Gb(n){let t=[],e=0;for(;e<n.length;)e=jb(n,e,t)+1;return t}function Yb(n){Xs(n);let t=Ul(n),e=[];for(let i=0;i<t.length;i+=2)e.push(Number.parseInt(t[i]+t[i+1],16));return e}function Zb(n){let t=[];for(let e=0;e<n.length;e++)t[e]=Math.trunc(n[e]);return t}function Sa(n,t){return Array.isArray(n)?n.slice():n?typeof n=="string"?t==="hex"?Yb(n):Gb(n):Zb(n):[]}function Vl(n){return Wu(n)}function Kl(n,t){let e="";for(let i of n)t==="little"&&(i=Vl(i)),e+=Jb(i.toString(16));return e}function Jb(n){return n.length===7?"0"+n:n.length===6?"00"+n:n.length===5?"000"+n:n.length===4?"0000"+n:n.length===3?"00000"+n:n.length===2?"000000"+n:n.length===1?"0000000"+n:n}var Ru=typeof globalThis>"u"?void 0:globalThis.Buffer,Qb=Ru!=null&&typeof Ru.from=="function",Ml="0123456789abcdef",Nu=Array.from({length:256});for(let n=0;n<Nu.length;n++)Nu[n]=Ml[n>>4&15]+Ml[n&15];function t1(n){if(Qb)return Ru.from(n).toString("hex");let t=Array.from({length:n.length});for(let e=0;e<n.length;e++)t[e]=Nu[n[e]];return t.join("")}var Lu=(()=>{let n=typeof globalThis>"u"?void 0:globalThis.process,t=n?.getBuiltinModule;if(typeof t=="function")try{let e=t.call(n,"node:crypto");if(e!=null)return e}catch{}})();function en(n,t){return n instanceof Uint8Array?n:Array.isArray(n)?new Uint8Array(n):Uint8Array.from(Sa(n,t))}function Uu(n){return typeof n=="string"?en(n,"hex"):en(n)}function Ia(n,t,e){n!=null?n.update(e):t?.update(e)}function va(n,t){return n!=null?Array.from(n.digest()):t!=null?Array.from(t.digest()):[]}function Aa(n,t){return n!=null?n.digest("hex"):t!=null?t1(t.digest()):""}function Mu(n){let t=Lu?.createHash;if(typeof t=="function")try{return t(n)}catch{return}}function Du(n,t){let e=Lu?.createHmac;if(typeof e=="function")try{return e(n,t)}catch{return}}function Hu(n,t,e){let i=Mu(n);if(i!=null)return i.update(en(t,e)),i.digest()}function zl(n,t,e,i){let r=Du(n,Uu(t));if(r!=null)return r.update(en(e,i)),r.digest()}function e1(n,t,e,i){let r=e-t;Pu(r%4===0);let s=Array.from({length:r/4});for(let o=0,c=t;o<s.length;o++,c+=4){let u;i==="big"?u=n[c]<<24|n[c+1]<<16|n[c+2]<<8|n[c+3]:u=n[c+3]<<24|n[c+2]<<16|n[c+1]<<8|n[c],s[o]=u>>>0}return s}function Xl(n,t){let e=Array.from({length:n.length*4});for(let i=0,r=0;i<n.length;i++,r+=4){let s=n[i];t==="big"?(e[r]=s>>>24,e[r+1]=s>>>16&255,e[r+2]=s>>>8&255,e[r+3]=s&255):(e[r+3]=s>>>24,e[r+2]=s>>>16&255,e[r+1]=s>>>8&255,e[r]=s&255)}return e}function En(n,t){return n>>>t|n<<32-t}function Zi(n,t){return n<<t|n>>>32-t}function Yt(n,t){return n+t>>>0}function js(n,t,e){return n+t+e>>>0}function Dl(n,t,e,i){return n+t+e+i>>>0}function jl(n,t,e,i,r){return n+t+e+i+r>>>0}function n1(n,t,e,i){return n===0?Gl(t,e,i):n===1||n===3?i1(t,e,i):n===2?Yl(t,e,i):0}function Gl(n,t,e){return n&t^~n&e}function Yl(n,t,e){return n&t^n&e^t&e}function i1(n,t,e){return n^t^e}function r1(n){return En(n,2)^En(n,13)^En(n,22)}function s1(n){return En(n,6)^En(n,11)^En(n,25)}function o1(n){return En(n,7)^En(n,18)^n>>>3}function a1(n){return En(n,17)^En(n,19)^n>>>10}var c1=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],u1=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],f1=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],d1=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11];function Hl(n,t,e,i){return n<=15?t^e^i:n<=31?t&e|~t&i:n<=47?(t|~e)^i:n<=63?t&i|e&~i:t^(e|~i)}function l1(n){return n<=15?0:n<=31?1518500249:n<=47?1859775393:n<=63?2400959708:2840853838}function h1(n){return n<=15?1352829926:n<=31?1548603684:n<=47?1836072691:n<=63?2053994217:0}var Gs=class extends pa{constructor(){super(512,160,192,64);b(this,"h");this.endian="little",this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}_update(e,i){let r=this.h[0],s=this.h[1],o=this.h[2],c=this.h[3],u=this.h[4],f=r,d=s,l=o,p=c,m=u,g;for(let w=0;w<80;w++)g=Yt(Zi(Dl(r,Hl(w,s,o,c),e[c1[w]+i],l1(w)),f1[w]),u),r=u,u=c,c=Zi(o,10),o=s,s=g,g=Yt(Zi(Dl(f,Hl(79-w,d,l,p),e[u1[w]+i],h1(w)),d1[w]),m),f=m,m=p,p=Zi(l,10),l=d,d=g;g=js(this.h[1],o,p),this.h[1]=js(this.h[2],c,m),this.h[2]=js(this.h[3],u,f),this.h[3]=js(this.h[4],r,d),this.h[4]=js(this.h[0],s,l),this.h[0]=g}_digest(){return Xl(this.h,"little")}_digestHex(){return Kl(this.h,"little")}},Ji,gi,Bu=class{constructor(){G(this,Ji);G(this,gi);N(this,gi,Mu("sha256")),y(this,gi)==null&&N(this,Ji,new Ys)}update(t,e){return Ia(y(this,gi),y(this,Ji),en(t,e)),this}digest(){return va(y(this,gi),y(this,Ji))}digestHex(){return Aa(y(this,gi),y(this,Ji))}};Ji=new WeakMap,gi=new WeakMap;var nr=class extends pa{constructor(){super(512,160,80,64);b(this,"h");b(this,"W");b(this,"k");this.k=[1518500249,1859775393,2400959708,3395469782],this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=Array.from({length:80})}_update(e,i){let r=this.W;i??(i=0);let s;for(s=0;s<16;s++)r[s]=e[i+s];for(;s<r.length;s++)r[s]=Zi(r[s-3]^r[s-8]^r[s-14]^r[s-16],1);let o=this.h[0],c=this.h[1],u=this.h[2],f=this.h[3],d=this.h[4];for(s=0;s<r.length;s++){let l=Math.trunc(s/20),p=jl(Zi(o,5),n1(l,c,u,f),d,r[s],this.k[l]);d=f,f=u,u=Zi(c,30),c=o,o=p}this.h[0]=Yt(this.h[0],o),this.h[1]=Yt(this.h[1],c),this.h[2]=Yt(this.h[2],u),this.h[3]=Yt(this.h[3],f),this.h[4]=Yt(this.h[4],d)}_digest(){return Xl(this.h,"big")}_digestHex(){return Kl(this.h,"big")}},Qi,mi,_u=class{constructor(){G(this,Qi);G(this,mi);N(this,mi,Mu("sha512")),y(this,mi)==null&&N(this,Qi,new Zs)}update(t,e){return Ia(y(this,mi),y(this,Qi),en(t,e)),this}digest(){return va(y(this,mi),y(this,Qi))}digestHex(){return Aa(y(this,mi),y(this,Qi))}};Qi=new WeakMap,mi=new WeakMap;var tr,bi,Fr=class{constructor(t){G(this,tr);G(this,bi);b(this,"blockSize",64);b(this,"outSize",32);let e=Uu(t);N(this,bi,Du("sha256",e)),y(this,bi)==null&&N(this,tr,new Wr(P1,e))}update(t,e){return Ia(y(this,bi),y(this,tr),en(t,e)),this}digest(){return va(y(this,bi),y(this,tr))}digestHex(){return Aa(y(this,bi),y(this,tr))}};tr=new WeakMap,bi=new WeakMap;var Cu=class{constructor(t){b(this,"inner");b(this,"outer");b(this,"blockSize",64);t=Sa(t,"hex"),t.length>this.blockSize&&(t=new nr().update(t).digest());let e;for(e=t.length;e<this.blockSize;e++)t.push(0);for(e=0;e<t.length;e++)t[e]^=54;for(this.inner=new nr().update(t),e=0;e<t.length;e++)t[e]^=106;this.outer=new nr().update(t)}update(t,e){return this.inner.update(t,e),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}},er,wi,ga=class{constructor(t){G(this,er);G(this,wi);b(this,"blockSize",128);b(this,"outSize",32);let e=Uu(t);N(this,wi,Du("sha512",e)),y(this,wi)==null&&N(this,er,new Wr(eh,e))}update(t,e){return Ia(y(this,wi),y(this,er),en(t,e)),this}digest(){return va(y(this,wi),y(this,er))}digestHex(){return Aa(y(this,wi),y(this,er))}};er=new WeakMap,wi=new WeakMap;function ma(n,t){let e=Hu("sha256",n,t);return e??new Ys().update(en(n,t)).digest()}function p1(n,t){let e=Hu("sha512",n,t);return e??new Zs().update(en(n,t)).digest()}function Zl(n,t){return Hu("ripemd160",n,t)}var $u=(n,t)=>{let e=Zl(n,t);return e!=null?Array.from(e):new Gs().update(n,t).digest()},qu=(n,t)=>new nr().update(n,t).digest(),Te=(n,t)=>Array.from(ma(n,t)),g1=(n,t)=>Array.from(p1(n,t)),zt=(n,t)=>Array.from(ma(ma(n,t))),Js=(n,t)=>{let e=ma(n,t),i=Zl(e);return i!=null?Array.from(i):new Gs().update(e).digest()},Qs=(n,t,e)=>{let i=zl("sha256",n,t,e);return i!=null?Array.from(i):new Fr(n).update(t,e).digest()},Fu=(n,t,e)=>{let i=zl("sha512",n,t,e);return i!=null?Array.from(i):new ga(n).update(t,e).digest()};function m1(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function ba(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`positive integer expected, got ${n}`)}function Ea(n,...t){if(!m1(n))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(n.length)){let e=t.join(",");throw new Error(`Uint8Array expected of length ${e}, got length=${n.length}`)}}function Jl(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("Hash should be wrapped by utils.createHasher");ba(n.outputLen),ba(n.blockLen)}function wa(n,t=!0){if(n.destroyed===!0)throw new Error("Hash instance has been destroyed");if(t&&n.finished===!0)throw new Error("Hash#digest() has already been called")}function b1(n,t){Ea(n);let e=t.outputLen;if(n.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}function ir(...n){for(let t of n)t.fill(0)}function ha(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function ka(n){return typeof n=="string"&&(n=w1(n)),Ea(n),n}function w1(n){if(typeof n!="string")throw new Error("string expected");return Se(n)}var $l=ka,ya=class{};function Ql(n){let t=i=>n().update(ka(i)).digest(),e=n();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>n(),t}var fa=BigInt(2**32-1),ql=BigInt(32);function y1(n,t=!1){return t?{h:Number(n&fa),l:Number(n>>ql&fa)}:{h:Number(n>>ql&fa)|0,l:Number(n&fa)|0}}function x1(n,t=!1){let e=n.length,i=new Uint32Array(e),r=new Uint32Array(e);for(let s=0;s<e;s++){let{h:o,l:c}=y1(n[s],t);i[s]=o,r[s]=c}return[i,r]}var Fl=(n,t,e)=>n>>>e,Wl=(n,t,e)=>n<<32-e|t>>>e,$r=(n,t,e)=>n>>>e|t<<32-e,qr=(n,t,e)=>n<<32-e|t>>>e,da=(n,t,e)=>n<<64-e|t>>>e-32,la=(n,t,e)=>n>>>e-32|t<<64-e;function Wn(n,t,e,i){let r=(t>>>0)+(i>>>0);return{h:n+e+(r/2**32|0)|0,l:r|0}}var S1=(n,t,e)=>(n>>>0)+(t>>>0)+(e>>>0),I1=(n,t,e,i)=>Math.trunc(t+e+i+Math.trunc(n/2**32)),v1=(n,t,e,i)=>(n>>>0)+(t>>>0)+(e>>>0)+(i>>>0),A1=(n,t,e,i,r)=>Math.trunc(t+e+i+r+Math.trunc(n/2**32)),E1=(n,t,e,i,r)=>(n>>>0)+(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0),k1=(n,t,e,i,r,s)=>t+e+i+r+s+(n/2**32|0)|0,xa=class extends ya{constructor(e,i,r,s){super();b(this,"blockLen");b(this,"outputLen");b(this,"padOffset");b(this,"isLE");b(this,"buffer");b(this,"view");b(this,"finished",!1);b(this,"length",0);b(this,"pos",0);b(this,"destroyed",!1);this.blockLen=e,this.outputLen=i,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=ha(this.buffer)}update(e){wa(this),e=ka(e),Ea(e);let{view:i,buffer:r,blockLen:s}=this,o=e.length;for(let c=0;c<o;){let u=Math.min(s-this.pos,o-c);if(u===s){let f=ha(e);for(;s<=o-c;c+=s)this.process(f,c);continue}r.set(e.subarray(c,c+u),this.pos),this.pos+=u,c+=u,this.pos===s&&(this.process(i,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){wa(this),b1(e,this),this.finished=!0;let{buffer:i,view:r,blockLen:s,isLE:o}=this,{pos:c}=this;i[c++]=128,ir(this.buffer.subarray(c)),this.padOffset>s-c&&(this.process(r,0),c=0);for(let p=c;p<s;p++)i[p]=0;T1(r,s-8,BigInt(this.length*8),o),this.process(r,0);let u=ha(e),f=this.outputLen;if(f%4!==0)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=f/4,l=this.get();if(d>l.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<d;p++)u.setUint32(4*p,l[p],o)}digest(){let{buffer:e,outputLen:i}=this;this.digestInto(e);let r=e.slice(0,i);return this.destroy(),r}_cloneInto(e){e??(e=new this.constructor),e.set(...this.get());let{blockLen:i,buffer:r,length:s,finished:o,destroyed:c,pos:u}=this;return e.destroyed=c,e.finished=o,e.length=s,e.pos=u,s%i!==0&&e.buffer.set(r),e}clone(){return this._cloneInto()}};function T1(n,t,e,i){if(typeof n.setBigUint64=="function")return n.setBigUint64(t,e,i);let r=BigInt(32),s=BigInt(4294967295),o=Number(e>>r&s),c=Number(e&s),u=i?4:0,f=i?0:4;n.setUint32(t+u,o,i),n.setUint32(t+f,c,i)}var di=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),O1=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),li=new Uint32Array(64),Ys=class extends xa{constructor(e=32){super(64,e,8,!1);b(this,"A",di[0]|0);b(this,"B",di[1]|0);b(this,"C",di[2]|0);b(this,"D",di[3]|0);b(this,"E",di[4]|0);b(this,"F",di[5]|0);b(this,"G",di[6]|0);b(this,"H",di[7]|0)}get(){let{A:e,B:i,C:r,D:s,E:o,F:c,G:u,H:f}=this;return[e,i,r,s,o,c,u,f]}set(...[e,i,r,s,o,c,u,f]){this.A=e|0,this.B=i|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=c|0,this.G=u|0,this.H=f|0}process(e,i){for(let p=0;p<16;p++,i+=4)li[p]=e.getUint32(i);for(let p=16;p<64;p++){let m=li[p-15],g=li[p-2],w=o1(m),S=a1(g);li[p]=Yt(Yt(w,li[p-7]),Yt(S,li[p-16]))}let{A:r,B:s,C:o,D:c,E:u,F:f,G:d,H:l}=this;for(let p=0;p<64;p++){let m=jl(l,s1(u),Gl(u,f,d),O1[p],li[p]),g=Yt(r1(r),Yl(r,s,o));l=d,d=f,f=u,u=Yt(c,m),c=o,o=s,s=r,r=Yt(m,g)}this.A=Yt(this.A,r),this.B=Yt(this.B,s),this.C=Yt(this.C,o),this.D=Yt(this.D,c),this.E=Yt(this.E,u),this.F=Yt(this.F,f),this.G=Yt(this.G,d),this.H=Yt(this.H,l)}roundClean(){ir(li)}destroy(){ir(this.buffer),this.set(0,0,0,0,0,0,0,0)}},P1=Ql(()=>new Ys),Ie=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),th=x1(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(BigInt)),R1=th[0],N1=th[1],hi=new Uint32Array(80),pi=new Uint32Array(80),Zs=class extends xa{constructor(e=64){super(128,e,16,!1);b(this,"Ah",Ie[0]|0);b(this,"Al",Ie[1]|0);b(this,"Bh",Ie[2]|0);b(this,"Bl",Ie[3]|0);b(this,"Ch",Ie[4]|0);b(this,"Cl",Ie[5]|0);b(this,"Dh",Ie[6]|0);b(this,"Dl",Ie[7]|0);b(this,"Eh",Ie[8]|0);b(this,"El",Ie[9]|0);b(this,"Fh",Ie[10]|0);b(this,"Fl",Ie[11]|0);b(this,"Gh",Ie[12]|0);b(this,"Gl",Ie[13]|0);b(this,"Hh",Ie[14]|0);b(this,"Hl",Ie[15]|0)}get(){let{Ah:e,Al:i,Bh:r,Bl:s,Ch:o,Cl:c,Dh:u,Dl:f,Eh:d,El:l,Fh:p,Fl:m,Gh:g,Gl:w,Hh:S,Hl:C}=this;return[e,i,r,s,o,c,u,f,d,l,p,m,g,w,S,C]}set(...[e,i,r,s,o,c,u,f,d,l,p,m,g,w,S,C]){this.Ah=e|0,this.Al=i|0,this.Bh=r|0,this.Bl=s|0,this.Ch=o|0,this.Cl=c|0,this.Dh=u|0,this.Dl=f|0,this.Eh=d|0,this.El=l|0,this.Fh=p|0,this.Fl=m|0,this.Gh=g|0,this.Gl=w|0,this.Hh=S|0,this.Hl=C|0}process(e,i){for(let k=0;k<16;k++,i+=8)hi[k]=e.getUint32(i),pi[k]=e.getUint32(i+4);for(let k=16;k<80;k++){let B=hi[k-15]|0,_=pi[k-15]|0,H=$r(B,_,1)^$r(B,_,8)^Fl(B,_,7),O=qr(B,_,1)^qr(B,_,8)^Wl(B,_,7),I=hi[k-2]|0,U=pi[k-2]|0,M=$r(I,U,19)^da(I,U,61)^Fl(I,U,6),F=qr(I,U,19)^la(I,U,61)^Wl(I,U,6),it=v1(O,F,pi[k-7],pi[k-16]),ot=A1(it,H,M,hi[k-7],hi[k-16]);hi[k]=ot|0,pi[k]=it|0}let{Ah:r,Al:s,Bh:o,Bl:c,Ch:u,Cl:f,Dh:d,Dl:l,Eh:p,El:m,Fh:g,Fl:w,Gh:S,Gl:C,Hh:E,Hl:A}=this;for(let k=0;k<80;k++){let B=$r(p,m,14)^$r(p,m,18)^da(p,m,41),_=qr(p,m,14)^qr(p,m,18)^la(p,m,41),H=p&g^~p&S,O=m&w^~m&C,I=E1(A,_,O,N1[k],pi[k]),U=k1(I,E,B,H,R1[k],hi[k]),M=I|0,F=$r(r,s,28)^da(r,s,34)^da(r,s,39),it=qr(r,s,28)^la(r,s,34)^la(r,s,39),ot=r&o^r&u^o&u,q=s&c^s&f^c&f;E=S|0,A=C|0,S=g|0,C=w|0,g=p|0,w=m|0,{h:p,l:m}=Wn(d|0,l|0,U|0,M|0),d=u|0,l=f|0,u=o|0,f=c|0,o=r|0,c=s|0;let z=S1(it,q,M);r=I1(z,F,ot,U),s=z|0}({h:r,l:s}=Wn(r,s,this.Ah,this.Al)),{h:o,l:c}=Wn(o,c,this.Bh,this.Bl),{h:u,l:f}=Wn(u,f,this.Ch,this.Cl),{h:d,l}=Wn(d,l,this.Dh,this.Dl),{h:p,l:m}=Wn(p,m,this.Eh,this.El),{h:g,l:w}=Wn(g,w,this.Fh,this.Fl),{h:S,l:C}=Wn(S,C,this.Gh,this.Gl),{h:E,l:A}=Wn(E,A,this.Hh,this.Hl),this.set(r,s,o,c,u,f,d,l,p,m,g,w,S,C,E,A)}roundClean(){ir(hi,pi)}destroy(){ir(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},eh=Ql(()=>new Zs),Wr=class extends ya{constructor(e,i){super();b(this,"oHash");b(this,"iHash");b(this,"blockLen");b(this,"outputLen");b(this,"finished",!1);b(this,"destroyed",!1);Jl(e);let r=ka(i);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new TypeError("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let c=0;c<o.length;c++)o[c]^=54;this.iHash.update(o),this.oHash=e.create();for(let c=0;c<o.length;c++)o[c]^=106;this.oHash.update(o),ir(o)}update(e){return wa(this),this.iHash.update(e),this}digestInto(e){wa(this),Ea(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e??(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:i,iHash:r,finished:s,destroyed:o,blockLen:c,outputLen:u}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=c,e.outputLen=u,e.oHash=i._cloneInto(e.oHash??void 0),e.iHash=r._cloneInto(e.iHash??void 0),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};function B1(n,t,e,i){Jl(n);let{c:r,dkLen:s=32}={...i};if(ba(r),ba(s),r<1)throw new Error("iterations (c) should be >= 1");let o=$l(t),c=$l(e),u=new Uint8Array(s),f=nh.create(n,o),d=f._cloneInto().update(c),l,p=new Uint8Array(4),m=ha(p),g=new Uint8Array(f.outputLen);for(let w=1,S=0;S<s;w++,S+=f.outputLen){let C=u.subarray(S,S+f.outputLen);m.setInt32(0,w,!1),l=d._cloneInto(l),l.update(p).digestInto(g),C.set(g.subarray(0,C.length));for(let E=1;E<r;E++){f._cloneInto(l).update(g).digestInto(g);for(let A=0;A<C.length;A++)C[A]^=g[A]}}return f.destroy(),d.destroy(),l?.destroy(),ir(g),u}var nh=(n,t,e)=>new Wr(n,t).update(e).digest();nh.create=(n,t)=>new Wr(n,t);function _1(n,t,e,i){return B1(eh,n,t,{c:e,dkLen:i})}function C1(n,t,e,i,r="sha512"){if(r!=="sha512")throw new Error("Only sha512 is supported in this PBKDF2 implementation");let s=Lu?.pbkdf2Sync;if(typeof s=="function"){let f=s(en(n),en(t),e,i,r);return Array.from(f)}let o=Uint8Array.from(n),c=Uint8Array.from(t),u=_1(o,c,e,i);return Array.from(u)}function Wu(n){return(n>>>24|n>>>8&65280|n<<8&16711680|(n&255)<<24)>>>0}var L1=(()=>{let n=new ArrayBuffer(4),t=new Uint32Array(n),e=new Uint8Array(n);return t[0]=16909060,e[0]===4})();function U1(n){return L1?Wu(n):n>>>0}var M1=new T(4294967295),D1=new T(2).pow(new T(64)).sub(new T(1)),H1=new T(Number.MAX_SAFE_INTEGER);function to(n,t=!0){let e=n.readUInt8();if(e<253)return e;if(e===253){let r=n.readUInt16LE();if(r<253)throw new Error("non-canonical varInt");return r}if(e===254){let r=n.readUInt32LE();if(r<=65535)throw new Error("non-canonical varInt");return r}let i=n.readUInt64LEBn();if(i.lte(M1))throw new Error("non-canonical varInt");if(t&&i.eq(D1))return-1;if(i.gt(H1))throw new Error("number too large to retain precision - use readVarIntBn");return i.toNumber()}var Wt,Tt,rr,ln,Vn,ht=class{constructor(t,e=256){G(this,ln);G(this,Wt);G(this,Tt);G(this,rr);if(!Number.isSafeInteger(e)||e<0)throw new RangeError("WriterUint8Array initial capacity must be a non-negative safe integer");if(t!=null&&t.length>0){let i=t.reduce((r,s)=>r+s.length,0);e=Math.max(e,i)}if(e=Math.max(1,e),N(this,Wt,new Uint8Array(e)),N(this,Tt,0),N(this,rr,e),t!=null)for(let i of t)this.write(i)}getLength(){return y(this,Tt)}toUint8Array(){return y(this,Wt).slice(0,y(this,Tt))}toArray(){return Array.from(this.toUint8Array())}toUint8ArrayZeroCopy(){return y(this,Wt).subarray(0,y(this,Tt))}reserve(t){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("WriterUint8Array reserve requires a non-negative safe integer");a(this,ln,Vn).call(this,t)}write(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);return a(this,ln,Vn).call(this,e.length),y(this,Wt).set(e,y(this,Tt)),N(this,Tt,y(this,Tt)+e.length),this}writeReverse(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);a(this,ln,Vn).call(this,e.length);for(let i=e.length-1;i>=0;i--)y(this,Wt)[y(this,Tt)]=e[i],N(this,Tt,y(this,Tt)+1);return this}writeUInt8(t){return a(this,ln,Vn).call(this,1),y(this,Wt)[y(this,Tt)]=t&255,N(this,Tt,y(this,Tt)+1),this}writeInt8(t){return this.writeUInt8(t),this}writeUInt16LE(t){return a(this,ln,Vn).call(this,2),y(this,Wt)[y(this,Tt)]=t&255,y(this,Wt)[y(this,Tt)+1]=t>>8&255,N(this,Tt,y(this,Tt)+2),this}writeUInt16BE(t){return a(this,ln,Vn).call(this,2),y(this,Wt)[y(this,Tt)]=t>>8&255,y(this,Wt)[y(this,Tt)+1]=t&255,N(this,Tt,y(this,Tt)+2),this}writeInt16LE(t){return this.writeUInt16LE(t&65535),this}writeInt16BE(t){return this.writeUInt16BE(t&65535),this}writeUInt32LE(t){return a(this,ln,Vn).call(this,4),y(this,Wt)[y(this,Tt)]=t&255,y(this,Wt)[y(this,Tt)+1]=t>>8&255,y(this,Wt)[y(this,Tt)+2]=t>>16&255,y(this,Wt)[y(this,Tt)+3]=t>>24&255,N(this,Tt,y(this,Tt)+4),this}writeUInt32BE(t){return a(this,ln,Vn).call(this,4),y(this,Wt)[y(this,Tt)]=t>>24&255,y(this,Wt)[y(this,Tt)+1]=t>>16&255,y(this,Wt)[y(this,Tt)+2]=t>>8&255,y(this,Wt)[y(this,Tt)+3]=t&255,N(this,Tt,y(this,Tt)+4),this}writeInt32LE(t){return this.writeUInt32LE(t>>>0),this}writeInt32BE(t){return this.writeUInt32BE(t>>>0),this}writeUInt64BEBn(t){let e=t.toArray("be",8);return this.write(e),this}writeUInt64LEBn(t){let e=t.toArray("be",8);return this.writeReverse(e),this}writeUInt64LE(t){let e=new T(t).toArray("be",8);return this.writeReverse(e),this}writeVarIntNum(t){let e=fe.varIntNum(t);return this.write(e),this}writeVarIntBn(t){let e=fe.varIntBn(t);return this.write(e),this}reset(){N(this,Tt,0)}};Wt=new WeakMap,Tt=new WeakMap,rr=new WeakMap,ln=new WeakSet,Vn=function(t){if(y(this,Tt)+t>y(this,rr)){let e=y(this,rr)*2;for(;y(this,Tt)+t>e;)e*=2;let i=new Uint8Array(e);i.set(y(this,Wt)),N(this,Wt,i),N(this,rr,e)}};var pn,We,hn,Vu=class Vu{constructor(t=new Uint8Array(0),e=0){G(this,We);b(this,"bin");b(this,"pos");G(this,pn);if(t instanceof Uint8Array)this.bin=t;else if(Array.isArray(t))this.bin=new Uint8Array(t);else throw new TypeError("ReaderUint8Array constructor: bin must be Uint8Array or number[]");if(N(this,pn,this.bin.length),!Number.isSafeInteger(e)||e<0||e>y(this,pn))throw new RangeError("ReaderUint8Array position exceeds available data");this.pos=e}static makeReader(t,e=0){if(t instanceof Uint8Array)return new Vu(t,e);if(Array.isArray(t))return new eo(t,e);throw new Error("ReaderUint8Array.makeReader: bin must be Uint8Array or number[]")}eof(){return this.pos>=y(this,pn)}read(t=y(this,pn)-this.pos){a(this,We,hn).call(this,t);let e=this.pos,i=this.pos+t;return this.pos=i,this.bin.slice(e,i)}readView(t=y(this,pn)-this.pos){a(this,We,hn).call(this,t);let e=this.pos;return this.pos+=t,this.bin.subarray(e,this.pos)}skip(t){a(this,We,hn).call(this,t),this.pos+=t}remaining(){return y(this,pn)-this.pos}readReverse(t=y(this,pn)-this.pos){a(this,We,hn).call(this,t);let e=new Uint8Array(t);for(let i=0;i<t;i++)e[i]=this.bin[this.pos+t-1-i];return this.pos+=t,e}readUInt8(){a(this,We,hn).call(this,1);let t=this.bin[this.pos];return this.pos+=1,t}readInt8(){let t=this.readUInt8();return(t&128)===0?t:t-256}readUInt16BE(){a(this,We,hn).call(this,2);let t=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,t}readInt16BE(){let t=this.readUInt16BE();return(t&32768)===0?t:t-65536}readUInt16LE(){a(this,We,hn).call(this,2);let t=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,t}readInt16LE(){let t=this.readUInt16LE();return(t&32768)===0?t:t-65536}readUInt32BE(){a(this,We,hn).call(this,4);let t=this.bin[this.pos]*16777216+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,t}readInt32BE(){let t=this.readUInt32BE();return(t&2147483648)===0?t:t-4294967296}readUInt32LE(){a(this,We,hn).call(this,4);let t=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,t}readInt32LE(){let t=this.readUInt32LE();return(t&2147483648)===0?t:t-4294967296}readUInt64BEBn(){a(this,We,hn).call(this,8);let t=Array.from(this.bin.slice(this.pos,this.pos+8)),e=new T(t);return this.pos=this.pos+8,e}readUInt64LEBn(){let t=Array.from(this.readReverse(8));return new T(t)}readInt64LEBn(){let t=new T(2).pow(new T(63)),e=new T(2).pow(new T(64)),i=Array.from(this.readReverse(8)),r=new T(i);return r.gte(t)&&(r=r.sub(e)),r}readVarIntNum(t=!0){let e=this.readUInt8(),i;switch(e){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(i=t?this.readInt64LEBn():this.readUInt64LEBn(),i.lte(new T(2).pow(new T(53))))return i.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return e}}readVarIntNumStrict(t=!0){return to(this,t)}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){let t=this.readUInt8();switch(t){case 253:return new T(this.readUInt16LE());case 254:return new T(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new T(t)}}};pn=new WeakMap,We=new WeakSet,hn=function(t){if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(this.pos)||this.pos<0||this.pos+t>y(this,pn))throw new RangeError("ReaderUint8Array read exceeds available data")};var bt=Vu;var Oa=globalThis.Buffer,rh=Oa!=null&&typeof Oa.from=="function",$1=(n,t="Unknown value")=>{if(n===null)return"null";if(n===void 0)return"undefined";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="bigint")return n.toString();if(typeof n=="boolean")return n?"true":"false";if(typeof n=="symbol")return n.description??n.toString();if(n instanceof Error&&n.message.length>0)return n.message;let e=n.message;if(typeof e=="string"&&e.length>0)return e;try{return JSON.stringify(n)??t}catch{return t}},q1=n=>n.length%2===1?"0"+n:n,ih="0123456789abcdef",sh=Array.from({length:256},()=>"");for(let n=0;n<256;n++)sh[n]=ih[n>>4&15]+ih[n&15];var nt=n=>rh?Oa.from(n).toString("hex"):n.length===0?"":Array.from(n,t=>sh[t&255]).join(""),et=(n,t)=>n instanceof Uint8Array?n:typeof n=="string"&&t==="hex"?ro(n):new Uint8Array(at(n,t)),at=(n,t)=>{if(Array.isArray(n))return n.slice();if(n===void 0)return[];if(typeof n!="string")return Array.from(n,e=>Math.trunc(e));switch(t){case"hex":return F1(n);case"base64":return oh(n);default:return K1(n)}},io=new Int8Array(256).fill(-1);for(let n=0;n<10;n++)io[48+n]=n;for(let n=0;n<6;n++)io[65+n]=10+n,io[97+n]=10+n;var F1=n=>Array.from(ro(n)),ro=n=>{Xs(n);let t=n.length%2===0?n:"0"+n;if(rh){let r=Oa.from(t,"hex");return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let e=new Uint8Array(t.length/2),i=0;for(let r=0;r<t.length;r+=2){let s=io[t.codePointAt(r)],o=io[t.codePointAt(r+1)];e[i++]=s<<4|o}return e},W1=n=>{if(typeof n!="string")throw new TypeError("msg must be a string");let t=n.trim().replaceAll(/[\r\n\t\f\v ]+/g,"").replaceAll("-","+").replaceAll("_","/"),e=t.indexOf("=");if(e===-1)return t;let i=t.slice(e);if(!/^={1,2}$/.test(i)||t.slice(0,e).includes("="))throw new Error("Invalid base64 padding");return t.slice(0,e)},V1=(n,t)=>{if(n>=65&&n<=90)return n-65;if(n>=97&&n<=122)return n-97+26;if(n>=48&&n<=57)return n-48+52;if(n===43)return 62;if(n===47)return 63;throw new Error(`Invalid base64 character at index ${t}`)};function oh(n){let t=W1(n),e=[],i=0,r=0;for(let s=0;s<t.length;s++){let o=t.codePointAt(s),c=V1(o,s);for(i=i<<6|c,r+=6;r>=8;)r-=8,e.push(i>>r&255),i&=(1<<r)-1}return e}function K1(n){return Array.from(Se(n))}var ah=n=>new TextDecoder().decode(n instanceof Uint8Array?n:new Uint8Array(n)),Rt=n=>new TextDecoder("utf-8",{fatal:!0}).decode(n instanceof Uint8Array?n:new Uint8Array(n)),Pa=(n,t)=>{switch(t){case"hex":return nt(n);case"utf8":return ah(n);default:return n}};function ve(n){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e="",i;for(i=0;i<n.length;i+=3){let r=n[i],s=i+1<n.length?n[i+1]:0,o=i+2<n.length?n[i+2]:0,c=r>>2,u=(r&3)<<4|s>>4,f=(s&15)<<2|o>>6,d=o&63;e+=t.charAt(c)+t.charAt(u),e+=i+1<n.length?t.charAt(f):"=",e+=i+2<n.length?t.charAt(d):"="}return e}var no="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",so=n=>{if(n===""||typeof n!="string")throw new Error(`Expected base58 string but got \u201C${n}\u201D`);let t=n.match(/[^1-9A-HJ-NP-Za-km-z]/gmu);if(t!==null)throw new Error(`Invalid base58 character \u201C${t.join("")}\u201D`);let e=n.match(/^1+/gmu),i=e===null?0:e[0].length,r=(n.length-i)*(Math.log(58)/Math.log(256))+1>>>0;return[...new Uint8Array([...new Uint8Array(i),...Array.from(n).map(o=>no.indexOf(o)).reduce((o,c)=>(o=o.map(u=>{let f=u*58+c;return c=f>>8,f}),o),new Uint8Array(r)).reverse().filter((o=>c=>o=o||c)(!1))])]},oo=n=>{let t=Array.from({length:256},()=>-1);for(let i=0;i<no.length;++i)t[no.codePointAt(i)]=i;let e=[];for(let i of n){let r=i;for(let s=0;s<e.length;++s){let o=(t[e[s]]<<8)+r,c=Math.trunc(o/58),u=o-c*58;e[s]=no.codePointAt(u),r=c}for(;r!==0;){let s=Math.trunc(r/58),o=r-s*58;e.push(no.codePointAt(o)),r=s}}for(let i of n)if(i===0)e.push("1".codePointAt(0));else break;return e.reverse(),String.fromCodePoint(...e)},ao=(n,t=[0])=>{let e=zt([...t,...n]);return e=[...t,...n,...e.slice(0,4)],oo(e)},co=(n,t,e=1)=>{let i=so(n),r=i.slice(0,e),s=i.slice(e,-4),o=[...r,...s];return o=zt(o),i.slice(-4).forEach((c,u)=>{if(c!==o[u])throw new Error("Invalid checksum")}),t==="hex"&&(r=nt(r),s=nt(s)),{prefix:r,data:s}},fe=class n{constructor(t){b(this,"bufs");b(this,"length");this.bufs=t??[],this.length=0;for(let e of this.bufs)this.length+=e.length}getLength(){return this.length}toUint8Array(){let t=new Uint8Array(this.length),e=0;for(let i of this.bufs)t.set(i,e),e+=i.length;return t}toArray(){let t=this.length,e=Array.from({length:t},()=>0),i=0;for(let r of this.bufs)if(r instanceof Uint8Array)for(let s of r)e[i++]=s;else{let s=r;for(let o of s)e[i++]=o}return e}toHex(){return this.toArray().map(t=>t.toString(16).padStart(2,"0")).join("")}write(t){return this.bufs.push(t),this.length+=t.length,this}writeReverse(t){let e=Array.from({length:t.length},()=>0);for(let i=0;i<e.length;i++)e[i]=t[t.length-1-i];return this.write(e)}writeUInt8(t){let e=Array.from({length:1},()=>0);return e[0]=t&255,this.write(e),this}writeInt8(t){return this.writeUInt8(t)}writeUInt16BE(t){let e=[t>>8&255,t&255];return this.write(e)}writeInt16BE(t){return this.writeUInt16BE(t&65535)}writeUInt16LE(t){let e=[t&255,t>>8&255];return this.write(e)}writeInt16LE(t){return this.writeUInt16LE(t&65535)}writeUInt32BE(t){let e=[t>>24&255,t>>16&255,t>>8&255,t&255];return this.write(e)}writeInt32BE(t){return this.writeUInt32BE(t>>>0)}writeUInt32LE(t){let e=[t&255,t>>8&255,t>>16&255,t>>24&255];return this.write(e)}writeInt32LE(t){return this.writeUInt32LE(t>>>0)}writeUInt64BEBn(t){let e=t.toArray("be",8);return this.write(e),this}writeUInt64LEBn(t){let e=t.toArray("be",8);return this.writeReverse(e),this}writeUInt64LE(t){if(t===-1)this.write(Array.from({length:8},()=>255));else{let e=new T(t).toArray("be",8);this.writeReverse(e)}return this}writeVarIntNum(t){let e=n.varIntNum(t);return this.write(e),this}writeVarIntBn(t){let e=n.varIntBn(t);return this.write(e),this}static varIntNum(t){if(!Number.isFinite(t)||!Number.isInteger(t))throw new RangeError("CompactSize value must be a finite integer");let e;if(t<0)return this.varIntBn(new T(t));if(t<253)e=[t];else if(t<65536)e=[253,t&255,t>>8&255];else if(t<4294967296)e=[254,t&255,t>>8&255,t>>16&255,t>>24&255];else{let i=t&4294967295,r=Math.floor(t/4294967296)&4294967295;e=[255,i&255,i>>8&255,i>>16&255,i>>24&255,r&255,r>>8&255,r>>16&255,r>>24&255]}return e}static varIntBn(t){let e;if(t.isNeg()&&(t=t.add(ch)),t.ltn(253))e=[t.toNumber()];else if(t.ltn(65536)){let i=t.toNumber();e=[253,i&255,i>>8&255]}else if(t.lt(new T(4294967296))){let i=t.toNumber();e=[254,i&255,i>>8&255,i>>16&255,i>>24&255]}else{let i=new n;i.writeUInt8(255),i.writeUInt64LEBn(t),e=i.toArray()}return e}},eo=class{constructor(t=[],e=0){b(this,"bin");b(this,"pos");b(this,"length");if(this.bin=t,this.length=t.length,!Number.isSafeInteger(e)||e<0||e>this.length)throw new RangeError("Reader position exceeds available data");this.pos=e}ensureAvailable(t){if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(this.pos)||this.pos<0||this.pos+t>this.length)throw new RangeError("Reader read exceeds available data")}eof(){return this.pos>=this.length}read(t=this.length-this.pos){this.ensureAvailable(t);let e=this.pos,i=this.pos+t;return this.pos=i,this.bin.slice(e,i)}readReverse(t=this.length-this.pos){this.ensureAvailable(t);let e=Array.from({length:t},()=>0);for(let i=0;i<t;i++)e[i]=this.bin[this.pos+t-1-i];return this.pos+=t,e}readUInt8(){this.ensureAvailable(1);let t=this.bin[this.pos];return this.pos+=1,t}readInt8(){let t=this.readUInt8();return(t&128)===0?t:t-256}readUInt16BE(){this.ensureAvailable(2);let t=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,t}readInt16BE(){let t=this.readUInt16BE();return(t&32768)===0?t:t-65536}readUInt16LE(){this.ensureAvailable(2);let t=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,t}readInt16LE(){let t=this.readUInt16LE();return(t&32768)===0?t:t-65536}readUInt32BE(){this.ensureAvailable(4);let t=this.bin[this.pos]*16777216+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,t}readInt32BE(){let t=this.readUInt32BE();return(t&2147483648)===0?t:t-4294967296}readUInt32LE(){this.ensureAvailable(4);let t=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,t}readInt32LE(){let t=this.readUInt32LE();return(t&2147483648)===0?t:t-4294967296}readUInt64BEBn(){let t=this.read(8);return new T(t)}readUInt64LEBn(){let t=this.readReverse(8);return new T(t)}readInt64LEBn(){let t=this.readReverse(8),e=new T(t);return e.gte(z1)&&(e=e.sub(ch)),e}readVarIntNum(t=!0){let e=this.readUInt8(),i;switch(e){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(i=t?this.readInt64LEBn():this.readUInt64LEBn(),i.lte(new T(2).pow(new T(53))))return i.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return e}}readVarIntNumStrict(t=!0){return to(this,t)}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){let t=this.readUInt8();switch(t){case 253:return new T(this.readUInt16LE());case 254:return new T(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new T(t)}}},Ra=n=>{if(n.length===0)return n;let t=n.at(-1);if((t&127)!==0)return n;if(n.length===1)return[];if((n.at(-2)&128)!==0)return n;for(let e=n.length-1;e>0;e--)if(n[e-1]!==0)return(n[e-1]&128)===0?(n[e-1]|=t,n.slice(0,e)):(n[e]=t,n.slice(0,e+1));return[]},z1=new T(2).pow(new T(63)),ch=new T(2).pow(new T(64));function sr(n,t="Expected a valid value, but got undefined or null."){if(n==null)throw new Error(t);return n}function X1(n,t){if(n.length!==t.length)return!1;let e=0;for(let i=0;i<n.length;i++)e|=n[i]^t[i];return e===0}var Ku;function uh(n,t){let e=n.andln(3)+t&3;return e===3?-1:e}function fh(n,t,e,i){if((e&1)===0)return 0;let r=n.andln(7)+t&7;return(r===3||r===5)&&i===2?-e:e}function dh(n,t){return 2*n===t+1?1-n:n}var Na,lh,zu=class zu{constructor(){G(this,Na);b(this,"p");b(this,"red");b(this,"redN");b(this,"zero");b(this,"one");b(this,"two");b(this,"g");b(this,"n");b(this,"a");b(this,"b");b(this,"tinv");b(this,"zeroA");b(this,"threeA");b(this,"endo");b(this,"_endoWnafT1");b(this,"_endoWnafT2");b(this,"_wnafT1");b(this,"_wnafT2");b(this,"_wnafT3");b(this,"_wnafT4");b(this,"_bitLength");if(Ku===void 0)Ku=this;else return Ku;let e={prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",{doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}]};this.p=new T(e.p,16),this.red=new Gi(e.prime),this.zero=new T(0).toRed(this.red),this.one=new T(1).toRed(this.red),this.two=new T(2).toRed(this.red),this.n=new T(e.n,16),this.g=Oe.fromJSON(e.g,e.gRed),this._wnafT1=Array.from({length:4},()=>{}),this._wnafT2=Array.from({length:4},()=>{}),this._wnafT3=Array.from({length:4},()=>{}),this._wnafT4=Array.from({length:4},()=>{}),this._bitLength=this.n.bitLength(),this.redN=this.n.toRed(this.red),this.a=new T(e.a,16).toRed(this.red),this.b=new T(e.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=this.a.fromRed().cmpn(0)===0,this.threeA=this.a.fromRed().sub(this.p).cmpn(-3)===0,this.endo=this._getEndomorphism(e),this._endoWnafT1=Array.from({length:4},()=>{}),this._endoWnafT2=Array.from({length:4},()=>{})}static assert(t,e="Elliptic curve assertion failed"){if(!t)throw new Error(e)}getNAF(t,e,i){let r=Array.from({length:Math.max(t.bitLength(),i)+1},()=>0);r.fill(0);let s=1<<e+1,o=t.clone();for(let c=0;c<r.length;c++){let u,f=o.andln(s-1);o.isOdd()?(f>(s>>1)-1?u=(s>>1)-f:u=f,o.isubn(u)):u=0,r[c]=u,o.iushrn(1)}return r}getJSF(t,e){let i=[[],[]];t=t.clone(),e=e.clone();let r=0,s=0;for(;t.cmpn(-r)>0||e.cmpn(-s)>0;){let o=uh(t,r),c=uh(e,s),u=fh(t,r,o,c);i[0].push(u);let f=fh(e,s,c,o);i[1].push(f),r=dh(r,u),s=dh(s,f),t.iushrn(1),e.iushrn(1)}return i}static cachedProperty(t,e,i){let r="_"+e;t.prototype[e]=function(){return this[r]===void 0&&(this[r]=i.call(this)),this[r]}}static parseBytes(t){return typeof t=="string"?at(t,"hex"):t}static intFromLE(t){return new T(t,"hex","le")}_getEndomorphism(t){if(!this.zeroA||this.p.modrn(3)!==1)return;let e=this._resolveEndomorphismBeta(t),i=this._resolveEndomorphismLambda(t,e);return{beta:e,lambda:i,basis:a(this,Na,lh).call(this,t,i)}}_resolveEndomorphismBeta(t){if(t.beta!==void 0)return new T(t.beta,16).toRed(this.red);let e=this._getEndoRoots(this.p);if(e==null)throw new Error("Failed to get endomorphism roots for beta.");return(e[0].cmp(e[1])<0?e[0]:e[1]).toRed(this.red)}_endomorphismLambdaMatches(t,e,i=!1){if(this.g==null)throw new Error("Curve generator point (g) is not defined.");let r=this.g.mul(t)?.x,s=this.g.x==null?void 0:this.g.x.redMul(e);if(r==null||s==null){if(i)throw new Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");return!1}return r.cmp(s)===0}_resolveEndomorphismLambda(t,e){if(t.lambda!==void 0)return new T(t.lambda,16);let i=this._getEndoRoots(this.n);if(i==null)throw new Error("Failed to get endomorphism roots for lambda.");return this._endomorphismLambdaMatches(i[0],e)?i[0]:(zu.assert(this._endomorphismLambdaMatches(i[1],e,!0),"Lambda selection does not match computed beta."),i[1])}_getEndoRoots(t){let e=t===this.p?this.red:new zs(t),i=new T(2).toRed(e).redInvm(),r=i.redNeg(),s=new T(3).toRed(e).redNeg().redSqrt().redMul(i),o=r.redAdd(s).fromRed(),c=r.redSub(s).fromRed();return[o,c]}_getEndoBasis(t){let e=this.n.ushrn(Math.floor(this.n.bitLength()/2)),i=t,r=this.n.clone(),s=new T(1),o=new T(0),c=new T(0),u=new T(1),f,d,l,p,m,g,w=new T(0),S=0,C=new T(0),E=new T(0);for(;i.cmpn(0)!==0;){let B=r.div(i);C=r.sub(B.mul(i)),E=c.sub(B.mul(s));let _=u.sub(B.mul(o));if(l===void 0&&C.cmp(e)<0)f=w.neg(),d=s,l=C.neg(),p=E;else if(l!==void 0&&++S===2)break;w=C,r=i,i=C,c=s,s=E,u=o,o=_}if(f===void 0||d===void 0||l===void 0||p===void 0)throw new Error("Failed to compute Endo Basis values");m=C.neg(),g=E;let A=l.sqr().add(p.sqr());return m.sqr().add(g.sqr()).cmp(A)>=0&&(m=f,g=d),l.negative!==0&&(l=l.neg(),p=p.neg()),m.negative!==0&&(m=m.neg(),g=g.neg()),[{a:l,b:p},{a:m,b:g}]}_endoSplit(t){if(this.endo==null)throw new Error("Endomorphism is not defined.");let e=this.endo.basis,i=e[0],r=e[1],s=r.b.mul(t).divRound(this.n),o=i.b.neg().mul(t).divRound(this.n),c=s.mul(i.a),u=o.mul(r.a),f=s.mul(i.b),d=o.mul(r.b),l=t.sub(c).sub(u),p=f.add(d).neg();return{k1:l,k2:p}}validate(t){if(t.inf)return!0;let e=t.x,i=t.y;if(e===null||i===null)throw new Error("Point coordinates cannot be null");let r=this.a.redMul(e),s=e.redSqr().redMul(e).redIAdd(r).redIAdd(this.b);return i.redSqr().redISub(s).cmpn(0)===0}};Na=new WeakSet,lh=function(t,e){return typeof t.basis!="object"||t.basis===null?this._getEndoBasis(e):t.basis.map(i=>({a:new T(i.a,16),b:new T(i.b,16)}))};var Vt=zu;var or=class{constructor(t){b(this,"curve");b(this,"type");b(this,"precomputed");this.curve=new Vt,this.type=t,this.precomputed=null}};var ar=class n extends or{constructor(e,i,r){super("jacobian");b(this,"x");b(this,"y");b(this,"z");b(this,"zOne");e===null&&i===null&&r===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new T(0)):(T.isBN(e)||(e=new T(e,16)),this.x=e,T.isBN(i)||(i=new T(i,16)),this.y=i,T.isBN(r)||(r=new T(r,16)),this.z=r),this.x.red==null&&(this.x=this.x.toRed(this.curve.red)),this.y.red==null&&(this.y=this.y.toRed(this.curve.red)),this.z.red==null&&(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.isInfinity()&&(this.x=this.curve.one,this.y=this.curve.one,this.z=new T(0).toRed(this.curve.red),this.zOne=!1)}toP(){if(this.isInfinity())return new Oe(null,null);let e=this.z.redInvm(),i=e.redSqr(),r=this.x.redMul(i),s=this.y.redMul(i).redMul(e);return new Oe(r,s)}neg(){return new n(this.x,this.y.redNeg(),this.z)}add(e){if(this.isInfinity())return e;if(e.isInfinity())return this;let i=e.z.redSqr(),r=this.z.redSqr(),s=this.x.redMul(i),o=e.x.redMul(r),c=this.y.redMul(i.redMul(e.z)),u=e.y.redMul(r.redMul(this.z)),f=s.redSub(o),d=c.redSub(u);if(f.cmpn(0)===0)return d.cmpn(0)===0?this.dbl():new n(null,null,null);let l=f.redSqr(),p=l.redMul(f),m=s.redMul(l),g=d.redSqr().redIAdd(p).redISub(m).redISub(m),w=d.redMul(m.redISub(g)).redISub(c.redMul(p)),S=this.z.redMul(e.z).redMul(f);return new n(g,w,S)}mixedAdd(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;if(e.x===null||e.y===null)throw new Error("Point coordinates cannot be null");let i=this.z.redSqr(),r=this.x,s=e.x.redMul(i),o=this.y,c=e.y.redMul(i).redMul(this.z),u=r.redSub(s),f=o.redSub(c);if(u.cmpn(0)===0)return f.cmpn(0)===0?this.dbl():new n(null,null,null);let d=u.redSqr(),l=d.redMul(u),p=r.redMul(d),m=f.redSqr().redIAdd(l).redISub(p).redISub(p),g=f.redMul(p.redISub(m)).redISub(o.redMul(l)),w=this.z.redMul(u);return new n(m,g,w)}dblp(e){if(e===0)return this;if(this.isInfinity())return this;if(e===void 0)return this.dbl();let i=this;for(let r=0;r<e;r++)i=i.dbl();return i}dbl(){if(this.isInfinity())return this;let e,i,r;if(this.zOne){let s=this.x.redSqr(),o=this.y.redSqr(),c=o.redSqr(),u=this.x.redAdd(o).redSqr().redISub(s).redISub(c);u=u.redIAdd(u);let f=s.redAdd(s).redIAdd(s),d=f.redSqr().redISub(u).redISub(u),l=c.redIAdd(c);l=l.redIAdd(l),l=l.redIAdd(l),e=d,i=f.redMul(u.redISub(d)).redISub(l),r=this.y.redAdd(this.y)}else{let s=this.x.redSqr(),o=this.y.redSqr(),c=o.redSqr(),u=this.x.redAdd(o).redSqr().redISub(s).redISub(c);u=u.redIAdd(u);let f=s.redAdd(s).redIAdd(s),d=f.redSqr(),l=c.redIAdd(c);l=l.redIAdd(l),l=l.redIAdd(l),e=d.redISub(u).redISub(u),i=f.redMul(u.redISub(e)).redISub(l),r=this.y.redMul(this.z),r=r.redIAdd(r)}return new n(e,i,r)}eq(e){if(e.type==="affine")return this.eq(e.toJ());if(this===e||(e=e,this.isInfinity()&&e.isInfinity()))return!0;if(this.isInfinity()!==e.isInfinity())return!1;let i=this.z.redSqr(),r=e.z.redSqr();if(this.x.redMul(r).redISub(e.x.redMul(i)).cmpn(0)!==0)return!1;let s=i.redMul(this.z),o=r.redMul(e.z);return this.y.redMul(o).redISub(e.y.redMul(s)).cmpn(0)===0}eqXToP(e){let i=this.z.redSqr(),r=e.toRed(this.curve?.red).redMul(i);if(this.x.cmp(r)===0)return!0;let s=e.clone();if(this.curve?.redN==null)throw new Error("Curve or redN is not initialized.");let o=this.curve.redN.redMul(i);for(;s.cmp(this.curve.p)<0;){if(s.iadd(this.curve.n),s.cmp(this.curve.p)>=0)return!1;if(r.redIAdd(o),this.x.cmp(r)===0)return!0}return!1}inspect(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"}isInfinity(){return this.z.cmpn(0)===0}};function hh(n,t,e){let i=-n,r=(t.X^e.X)&i,s=(t.Y^e.Y)&i,o=(t.Z^e.Z)&i;t.X^=r,e.X^=r,t.Y^=s,e.Y^=s,t.Z^=o,e.Z^=o}var Ut=0n,Ce=1n,Xu=2n,j1=3n,G1=4n,Y1=8n,Tn=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,xi=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,ph=(1n<<256n)-1n;function Gu(n){let t=n>>256n;return n=(n&ph)+(t<<32n)+t*977n,t=n>>256n,n=(n&ph)+(t<<32n)+t*977n,n>=Tn&&(n-=Tn),n}var cr=n=>Gu((n%Tn+Tn)%Tn),kn=(n,t)=>n>=t?n-t:Tn-(t-n),ct=(n,t)=>Gu(n*t),gh=(n,t)=>Gu(n+t),Vr=n=>{let t=Ce,e=Ut,i=cr(n),r=Tn;for(;i>Ce;){let s=r/i;[t,e]=[e-t*s,t],[i,r]=[r-i*s,i]}return cr(t)},Z1=n=>ct(n,n),J1=(n,t)=>{let e=1n;for(n=cr(n);t>0n;)(t&1n)!==0n&&(e=ct(e,n)),n=ct(n,n),t>>=1n;return e},Q1=Tn+1n>>2n,tw=n=>{let t=J1(n,Q1);return ct(t,t)!==cr(n)?null:t},ew=n=>T.isBN(n)?BigInt("0x"+n.toString(16)):typeof n=="string"?BigInt("0x"+n):Array.isArray(n)?BigInt("0x"+nt(n)):BigInt(n),Ba=BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),_a=BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),mh=new Map,uo=n=>{let{X:t,Y:e,Z:i}=n;if(e===Ut)return{X:Ut,Y:Ce,Z:Ut};let r=ct(e,e),s=ct(G1,ct(t,r)),o=ct(j1,ct(t,t)),c=kn(ct(o,o),ct(Xu,s)),u=kn(ct(o,kn(s,c)),ct(Y1,ct(r,r))),f=ct(Xu,ct(e,i));return{X:c,Y:u,Z:f}},Kr=(n,t)=>{if(n.Z===Ut)return t;if(t.Z===Ut)return n;let e=ct(n.Z,n.Z),i=ct(t.Z,t.Z),r=ct(n.X,i),s=ct(t.X,e),o=ct(n.Y,ct(i,t.Z)),c=ct(t.Y,ct(e,n.Z)),u=kn(s,r),f=kn(c,o);if(u===Ut)return f===Ut?uo(n):{X:Ut,Y:Ce,Z:Ut};let d=ct(u,u),l=ct(u,d),p=ct(r,d),m=kn(kn(ct(f,f),l),ct(Xu,p)),g=kn(ct(f,kn(p,m)),ct(o,l)),w=ct(u,ct(n.Z,t.Z));return{X:m,Y:g,Z:w}},nw=n=>n.Z===Ut?n:{X:n.X,Y:Tn-n.Y,Z:n.Z},iw=(n,t)=>{let e=`${n}:${t.x.toString(16)}:${t.y.toString(16)}`,i=mh.get(e);if(i!==void 0)return i;let r=Array.from({length:1<<n-1},()=>({X:Ut,Y:Ce,Z:Ut})),s={X:t.x,Y:t.y,Z:Ce};r[0]=s;let o=uo(s);for(let c=1;c<r.length;c++)r[c]=Kr(r[c-1],o);return mh.set(e,r),r},rw=(n,t)=>{let e=[],i=1n<<BigInt(t),r=i>>1n,s=n;for(;s>0n;){if((s&Ce)===Ut)e.push(0);else{let o=s&i-1n;o>r&&(o-=i),e.push(Number(o)),s-=o}s>>=Ce}return e},Ca=(n,t,e=5)=>{let i=iw(e,t),r=rw(n,e),s={X:Ut,Y:Ce,Z:Ut};for(let o=r.length-1;o>=0;o--){s=uo(s);let c=r[o];if(c!==0){let u=Math.abs(c)>>1,f=c>0?i[u]:nw(i[u]);s=Kr(s,f)}}return s},ur=n=>{let t=n%xi;return t<0n&&(t+=xi),t},fo=(n,t)=>ur(n*t),Yu=n=>{let t=1n,e=0n,i=ur(n),r=xi;for(;i>1n;){let s=r/i;[t,e]=[e-t*s,t],[i,r]=[r-i*s,i]}return ur(t)},pe,bh,wh,yh,xh,Sh,ju,Ih,Ot=class Ot extends or{constructor(e,i,r=!0){super("affine");G(this,pe);b(this,"x");b(this,"y");b(this,"inf");this.precomputed=null,e===null&&i===null?(this.x=null,this.y=null,this.inf=!0):(T.isBN(e)||(e=new T(e,16)),this.x=e,T.isBN(i)||(i=new T(i,16)),this.y=i,r&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red===null&&(this.x=this.x.toRed(this.curve.red)),this.y.red===null&&(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}static _assertOnCurve(e){if(!e.validate())throw new Error("Invalid point");return e}static fromDER(e){if((e[0]===4||e[0]===6||e[0]===7)&&e.length-1===64){if(e[0]===6){if(e.at(-1)%2!==0)throw new Error("Point string value is wrong length")}else if(e[0]===7&&e.at(-1)%2!==1)throw new Error("Point string value is wrong length");let r=new Ot(e.slice(1,33),e.slice(33,65));return Ot._assertOnCurve(r)}else if((e[0]===2||e[0]===3)&&e.length-1===32)return Ot._assertOnCurve(Ot.fromX(e.slice(1,33),e[0]===3));throw new Error("Unknown point format")}static fromString(e){let i=at(e,"hex");return Ot._assertOnCurve(Ot.fromDER(i))}static fromX(e,i){let r=ew(e);r=cr(r);let s=gh(ct(Z1(r),r),7n),o=tw(s);if(o===null)throw new Error("Invalid point");let c=o;(c&Ce)!==(i?Ce:Ut)&&(c=kn(Tn,c));let u=new T(r.toString(16),16),f=new T(c.toString(16),16);return Ot._assertOnCurve(new Ot(u,f))}static fromJSON(e,i){typeof e=="string"&&(e=JSON.parse(e));let r=new Ot(e[0],e[1],i);if(r=Ot._assertOnCurve(r),typeof e[2]!="object"||e[2]===null)return r;let s=e[2],o=c=>{let u=new Ot(c[0],c[1],i);return Ot._assertOnCurve(u)};return r.precomputed={beta:null,doubles:typeof s.doubles=="object"&&s.doubles!==null?{step:s.doubles.step,points:[r].concat(s.doubles.points.map(o))}:void 0,naf:typeof s.naf=="object"&&s.naf!==null?{wnd:s.naf.wnd,points:[r].concat(s.naf.points.map(o))}:void 0},r}validate(){if(this.inf||this.x==null||this.y==null)return!1;try{let e=BigInt("0x"+this.x.fromRed().toString(16)),i=BigInt("0x"+this.y.fromRed().toString(16)),r=ct(i,i),s=gh(ct(ct(e,e),e),7n);return r===s}catch{return!1}}encode(e=!0,i){if(this.inf)return i==="hex"?"00":[0];let r=this.curve.p.byteLength(),s=this.getX().toArray("be",r),o;return e?o=[this.getY().isEven()?2:3].concat(s):o=[4].concat(s,this.getY().toArray("be",r)),i==="hex"?nt(o):o}toString(){return this.encode(!0,"hex")}toJSON(){return this.precomputed==null?[this.x,this.y]:[this.x,this.y,typeof this.precomputed=="object"&&this.precomputed!==null?{doubles:this.precomputed.doubles==null?void 0:{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)},naf:this.precomputed.naf==null?void 0:{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}}:void 0]}inspect(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+(this.x?.fromRed()?.toString(16,2)??"undefined")+" y: "+(this.y?.fromRed()?.toString(16,2)??"undefined")+">"}isInfinity(){return this.inf}add(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return new Ot(null,null);if(this.x?.cmp(e.x??new T(0))===0)return new Ot(null,null);let i={X:BigInt("0x"+this.x.fromRed().toString(16)),Y:BigInt("0x"+this.y.fromRed().toString(16)),Z:Ce},r={X:BigInt("0x"+e.x.fromRed().toString(16)),Y:BigInt("0x"+e.y.fromRed().toString(16)),Z:Ce},s=Kr(i,r);if(s.Z===Ut)return new Ot(null,null);let o=Vr(s.Z),c=ct(o,o),u=ct(s.X,c),f=ct(s.Y,ct(c,o));return new Ot(u.toString(16),f.toString(16))}dbl(){if(this.inf)return this;if(this.x===null||this.y===null)throw new Error("Point coordinates cannot be null");let e=BigInt("0x"+this.x.fromRed().toString(16)),i=BigInt("0x"+this.y.fromRed().toString(16));if(i===Ut)return new Ot(null,null);let r=uo({X:e,Y:i,Z:Ce}),s=Vr(r.Z),o=ct(s,s),c=ct(r.X,o),u=ct(r.Y,ct(o,s));return new Ot(c.toString(16),u.toString(16))}getX(){return(this.x??new T(0)).fromRed()}getY(){return(this.y??new T(0)).fromRed()}mul(e){if(T.isBN(e)||(e=new T(e,16)),e=e,this.inf)return this;let i=e.isNeg(),r=i?e.neg():e,s=BigInt("0x"+r.toString(16));if(s=cr(s),s===Ut)return new Ot(null,null);if(s===Ut)return new Ot(null,null);if(this.x===null||this.y===null)throw new Error("Point coordinates cannot be null");let o,c;this===this.curve.g?(o=Ba,c=_a):(o=BigInt("0x"+this.x.fromRed().toString(16)),c=BigInt("0x"+this.y.fromRed().toString(16)));let u=Ca(s,{x:o,y:c});if(u.Z===Ut)return new Ot(null,null);let f=Vr(u.Z),d=ct(f,f),l=ct(u.X,d),p=ct(u.Y,ct(d,f)),m=new T(l.toString(16),16),g=new T(p.toString(16),16),w=new Ot(m,g);return i?w.neg():w}mulCT(e){if(T.isBN(e)||(e=new T(e,16)),e=e,this.inf)return new Ot(null,null);let i=e.isNeg(),r=i?e.neg():e,s=BigInt("0x"+r.toString(16));if(s=cr(s),s===0n)return new Ot(null,null);let o=this===this.curve.g?Ba:BigInt("0x"+this.getX().toString(16)),c=this===this.curve.g?_a:BigInt("0x"+this.getY().toString(16)),u={X:0n,Y:1n,Z:0n},f={X:o,Y:c,Z:1n},d=s.toString(2);for(let S of d){let C=S==="1"?1n:0n;hh(C,u,f),f=Kr(u,f),u=uo(u),hh(C,u,f)}if(u.Z===0n)return new Ot(null,null);let l=Vr(u.Z),p=ct(l,l),m=ct(u.X,p),g=ct(u.Y,ct(p,l)),w=new Ot(m.toString(16),g.toString(16));return i?w.neg():w}mulAdd(e,i,r){let s=[this,i],o=[e,r];return a(this,pe,ju).call(this,s,o)}jmulAdd(e,i,r){let s=[this,i],o=[e,r];return a(this,pe,ju).call(this,s,o,!0)}eq(e){return this===e||this.inf===e.inf&&(this.inf||(this.x??new T(0)).cmp(e.x??new T(0))===0&&(this.y??new T(0)).cmp(e.y??new T(0))===0)}neg(e){if(this.inf)return this;let i=new Ot(this.x,(this.y??new T(0)).redNeg());if(e===!0&&this.precomputed!=null){let r=this.precomputed,s=o=>o.neg();i.precomputed={naf:r.naf==null?void 0:{wnd:r.naf.wnd,points:r.naf.points.map(s)},doubles:r.doubles==null?void 0:{step:r.doubles.step,points:r.doubles.points.map(o=>o.neg())},beta:void 0}}return i}dblp(e){let i;for(let r=0;r<e;r++)i=(i??this).dbl();return i??this}toJ(){return this.inf?new ar(null,null,null):new ar(this.x,this.y,this.curve.one)}_combineWnafPair(e,i,r){let{points:s,coeffs:o,wndWidth:c,wnd:u,naf:f,currentMax:d}=r;if(c[e]!==1||c[i]!==1)return f[e]=this.curve.getNAF(o[e],c[e],this.curve._bitLength),f[i]=this.curve.getNAF(o[i],c[i],this.curve._bitLength),Math.max(d,f[e].length,f[i].length);let l=[s[e],null,null,s[i]],p=s[e].y??new T(0),m=s[i].y??new T(0);p.cmp(m)===0?(l[1]=s[e].add(s[i]),l[2]=s[e].toJ().mixedAdd(s[i].neg())):p.cmp(m.redNeg())===0?(l[1]=s[e].toJ().mixedAdd(s[i]),l[2]=s[e].add(s[i].neg())):(l[1]=s[e].toJ().mixedAdd(s[i]),l[2]=s[e].toJ().mixedAdd(s[i].neg()));let g=[-3,-1,-5,-7,0,7,5,1,3],w=this.curve.getJSF(o[e],o[i]),S=Math.max(d,w[0].length);f[e]=Array.from({length:S}),f[i]=Array.from({length:S});for(let C=0;C<S;C++){let E=Math.trunc(w[0][C]),A=Math.trunc(w[1][C]);f[e][C]=g[(E+1)*3+(A+1)],f[i][C]=0,u[e]=l}return S}_collectWnafStep(e,i,r,s){let o=e,c=0;for(;o>=0;){let u=!0;for(let f=0;f<i;f++)s[f]=new T(typeof r[f][o]=="number"?r[f][o]:0),s[f].isZero()||(u=!1);if(!u)break;c++,o--}return o>=0&&c++,{index:o,doubles:c}}_getDoubles(e,i){if(typeof this.precomputed=="object"&&this.precomputed!==null&&typeof this.precomputed.doubles=="object"&&this.precomputed.doubles!==null)return this.precomputed.doubles;let r=[this],s;for(let o=0;o<(i??0);o+=e??1){for(let c=0;c<(e??1);c++)s=(s??this).dbl();r.push(s)}return{step:e??1,points:r}}};pe=new WeakSet,bh=function(){if(typeof this.curve.endo!="object")return;let e=this.precomputed;if(typeof e=="object"&&e!==null&&typeof e.beta=="object"&&e.beta!==null)return e.beta;let i=new Ot((this.x??new T(0)).redMul(this.curve.endo.beta),this.y);if(e!=null){let r=this.curve,s=o=>{let c=o;if(c.x===null)throw new Error("p.x is null");if(r.endo===void 0||r.endo===null)throw new Error("curve.endo is undefined");return new Ot(c.x.redMul(r.endo.beta),c.y)};e.beta=i,i.precomputed={beta:null,naf:e.naf==null?void 0:{wnd:e.naf.wnd,points:e.naf.points.map(s)},doubles:e.doubles==null?void 0:{step:e.doubles.step,points:e.doubles.points.map(s)}}}return i},wh=function(e,i,r,s,o){var c;for(let u=0;u<r;u++){let f=a(c=i[u],pe,Ih).call(c,e);s[u]=f.wnd,o[u]=f.points}},yh=function(e,i,r,s,o,c){let u=0;for(let f=r-1;f>=1;f-=2)u=this._combineWnafPair(f-1,f,{points:e,coeffs:i,wndWidth:s,wnd:o,naf:c,currentMax:u});return u},xh=function(e,i,r,s){let o=new T(1),c=new T(2),u=e;for(let f=0;f<i;f++){let d=r[f];if(d.cmpn(0)===0)continue;let l=d.isNeg()?s[f][d.neg().sub(o).div(c).toNumber()].neg():s[f][d.sub(o).div(c).toNumber()];u=l.type==="affine"?u.mixedAdd(l):u.add(l)}return u},Sh=function(e,i,r,s,o){let c=this.curve._wnafT1.length,u=Array.from({length:c}),f=Array.from({length:c},()=>[]),d=Array.from({length:c},()=>[]);a(this,pe,wh).call(this,e,i,s,u,f);let l=a(this,pe,yh).call(this,i,r,s,u,f,d),p=new ar(null,null,null),m=this.curve._wnafT4,g=l;for(;g>=0;){let w=this._collectWnafStep(g,s,d,m);if(g=w.index,p=p.dblp(w.doubles),g<0)break;p=a(this,pe,xh).call(this,p,s,m,f),g--}for(let w=0;w<s;w++)f[w]=[];return o===!0?p:p.toP()},ju=function(e,i,r){var f;let s=Array.from({length:e.length*2}),o=Array.from({length:e.length*2}),c;for(c=0;c<e.length;c++){let d=this.curve._endoSplit(i[c]),l=e[c],p=a(f=l,pe,bh).call(f)??new Ot(null,null);d.k1.negative!==0&&(d.k1.ineg(),l=l.neg(!0)),d.k2.negative!==0&&(d.k2.ineg(),p=p.neg(!0)),s[c*2]=l,s[c*2+1]=p,o[c*2]=d.k1,o[c*2+1]=d.k2}let u=a(this,pe,Sh).call(this,1,s,o,c*2,r);for(let d=0;d<c*2;d++)s[d]=null,o[d]=null;return u},Ih=function(e){if(typeof this.precomputed=="object"&&this.precomputed!==null&&typeof this.precomputed.naf=="object"&&this.precomputed.naf!==null)return this.precomputed.naf;let i=[this],r=(1<<e)-1,s=r===1?null:this.dbl();for(let o=1;o<r;o++)s!==null&&(i[o]=i[o-1].add(s));return{wnd:e,points:i}};var Oe=Ot;var Ht=class n extends Oe{static fromPrivateKey(t){let i=new Vt().g.mul(t);return new n(i.x,i.y)}static fromString(t){let e=Oe.fromString(t);return new n(e.x,e.y)}static fromDER(t){let e=Oe.fromDER(t);return new n(e.x,e.y)}constructor(t,e=null,i=!0){if(t instanceof Oe)super(t.getX(),t.getY());else{if(e===null&&i&&typeof t=="string"&&(t.length===66||t.length===130))throw new Error('You are using the "new PublicKey()" constructor with a DER hex string. You need to use "PublicKey.fromString()" instead.');super(t,e,i)}}deriveSharedSecret(t){if(!this.validate())throw new Error("Public key not valid for ECDH secret derivation");return this.mulCT(t)}verify(t,e,i){let r=new T(Te(t,i),16);return Si(r,e,this)}toDER(t){return t==="hex"?this.encode(!0,t):this.encode(!0)}toHash(t){let e=Js(this.encode(!0));return t==="hex"?nt(e):e}toAddress(t=[0]){if(typeof t=="string")if(t==="testnet"||t==="test")t=[111];else if(t==="mainnet"||t==="main")t=[0];else throw new Error(`Invalid prefix ${t}`);return ao(this.toHash(),t)}deriveChild(t,e,i,r){let s;if(typeof r=="function"){let l=r(t,this);l===void 0?(s=this.deriveSharedSecret(t),typeof i=="function"&&i(t,this,s)):s=l}else s=this.deriveSharedSecret(t);let o=at(e,"utf8"),c=Qs(s.encode(!0),o),f=new Vt().g.mul(new T(c)),d=this.add(f);return new n(d.x,d.y)}static fromMsgHashAndCompactSignature(t,e,i){let r=at(e,i);if(r.length!==65)throw new Error("Invalid Compact Signature");let s=r[0];if(s<27||s>=35)throw new Error("Invalid Compact Byte");let o=r[0]-27;return o>3&&(o-=4),new ge(new T(r.slice(1,33)),new T(r.slice(33,65))).RecoverPublicKey(o,t)}};var ge=class n{constructor(t,e){b(this,"r");b(this,"s");this.r=t,this.s=e}static fromDER(t,e){let i=(l,p)=>{let m=l[p.place++];if((m&128)===0)return m;throw new Error("Invalid DER entity length")};class r{constructor(){b(this,"place",0)}}t=at(t,e);let s=new r;if(t[s.place++]!==48)throw new Error("Signature DER must start with 0x30");if(i(t,s)+s.place!==t.length)throw new Error("Signature DER invalid");if(t[s.place++]!==2)throw new Error("Signature DER invalid");let c=i(t,s),u=t.slice(s.place,c+s.place);if(s.place+=c,t[s.place++]!==2)throw new Error("Signature DER invalid");let f=i(t,s);if(t.length!==f+s.place)throw new Error("Invalid R-length in signature DER");let d=t.slice(s.place,f+s.place);if(u[0]===0){if((u[1]&128)===0)throw new Error("Invalid R-value in signature DER");u=u.slice(1)}if(d[0]===0){if((d[1]&128)===0)throw new Error("Invalid S-value in signature DER");d=d.slice(1)}return new n(new T(u),new T(d))}static fromCompact(t,e){if(t=at(t,e),t.length!==65)throw new Error("Invalid Compact Signature");let i=t[0];if(i<27||i>=35)throw new Error("Invalid Compact Byte");return new n(new T(t.slice(1,33)),new T(t.slice(33,65)))}verify(t,e,i){let r=new T(Te(t,i),16);return Si(r,this,e)}toString(t){return this.toDER(t)}toDER(t){let e=(f,d)=>{if(d<128)f.push(d);else throw new Error("len must be < 0x80")},i=f=>{let d=0,l=f.length-1;for(;f[d]===0&&(f[d+1]&128)===0&&d<l;)d++;return d===0?f:f.slice(d)},r=this.r.toArray(),s=this.s.toArray();for((r[0]&128)!==0&&(r=[0].concat(r)),(s[0]&128)!==0&&(s=[0].concat(s)),r=i(r),s=i(s);s[0]===0&&(s[1]&128)===0;)s=s.slice(1);let o=[2];e(o,r.length),o=o.concat(r),o.push(2),e(o,s.length);let c=o.concat(s),u=[48];return e(u,c.length),u=u.concat(c),t==="hex"?nt(u):t==="base64"?ve(u):u}toCompact(t,e,i){if(t<0||t>3)throw new Error("Invalid recovery param");if(typeof e!="boolean")throw new TypeError("Invalid compressed param");let r=27+t;e&&(r+=4);let s=[r];return s=s.concat(this.r.toArray("be",32)),s=s.concat(this.s.toArray("be",32)),i==="hex"?nt(s):i==="base64"?ve(s):s}RecoverPublicKey(t,e){let i=this.r,r=this.s,s=(t&1)!==0,o=t>>1,c=new Vt,u=c.n,f=c.g,d=o===0?i:i.add(u),l=Oe.fromX(d,s);if(!l.mul(u).isInfinity())throw new Error("nR is not at infinity");let m=e.neg().umod(u),g=i.invm(u),w=g.mul(r).umod(u),S=g.mul(m).umod(u),C=f.mul(S).add(l.mul(w)),E=new Ht(C);return E.validate(),E}CalculateRecoveryFactor(t,e){for(let i=0;i<4;i++){let r;try{r=this.RecoverPublicKey(i,e)}catch{continue}if(t.eq(r))return i}throw new Error("Unable to find valid recovery factor")}};var lo=class{constructor(t,e){b(this,"K");b(this,"V");let i=at(t,"hex"),r=at(e,"hex");if(i.length!==32)throw new Error("Entropy must be exactly 32 bytes (256 bits)");if(r.length!==32)throw new Error("Nonce must be exactly 32 bytes (256 bits)");let s=i.concat(r);this.K=Array.from({length:32}),this.V=Array.from({length:32});for(let o=0;o<32;o++)this.K[o]=0,this.V[o]=1;this.update(s)}hmac(){return new Fr(this.K)}update(t){let e=this.hmac().update(this.V).update([0]);t!==void 0&&(e=e.update(t)),this.K=e.digest(),this.V=this.hmac().update(this.V).digest(),t!==void 0&&(this.K=this.hmac().update(this.V).update([1]).update(t).digest(),this.V=this.hmac().update(this.V).digest())}generate(t){let e=[];for(;e.length<t;)this.V=this.hmac().update(this.V).digest(),e=e.concat(this.V);let i=e.slice(0,t);return this.update(),nt(i)}};function vh(n,t,e=new Vt){let i=n.byteLength()*8-e.n.bitLength();return i>0&&n.iushrn(i),t!==!0&&n.cmp(e.n)>=0?n.sub(e.n):n}function fr(n){let t=n.toArray("be"),e=0n;for(let i of t)e=e<<8n|BigInt(i);return e}var ho=new Vt,Zu=ho.n.byteLength(),sw=ho.n.subn(1),ow=xi>>1n;function aw(n,t,e){let i;if(typeof n=="function"?i=n(t):n!==void 0&&T.isBN(n)?i=n:i=new T(e.generate(Zu),16),i==null)throw new Error("k is undefined");return vh(i,!0)}function La(n,t){if(n)throw new Error(t)}function cw(n,t,e,i,r){if(n.cmpn(1)<0||n.cmp(sw)>0)return La(r,"Invalid fixed custom K value (must be >1 and <N-1)");let s=ho.g.mulCT(n);if(s.isInfinity())return La(r,"Invalid fixed custom K value (k\xB7G at infinity)");let o=ur(BigInt("0x"+s.getX().toString(16)));if(o===0n)return La(r,"Invalid fixed custom K value (r == 0)");let c=Yu(BigInt("0x"+n.toString(16))),u=ur(t+fo(o,e)),f=fo(c,u);return f===0n?La(r,"Invalid fixed custom K value (s == 0)"):(i&&f>ow&&(f=xi-f),new ge(new T(o.toString(16),16),new T(f.toString(16),16)))}var Ah=(n,t,e=!1,i)=>{let r=ho.n.bitLength();if(n.bitLength()>r)throw new Error(`ECDSA message is too large: expected <= ${r} bits. Callers must hash messages before signing.`);n=vh(n);let s=fr(n),o=fr(t),c=t.toArray("be",Zu),u=n.toArray("be",Zu),f=new lo(c,u),d=T.isBN(i);for(let l=0;;l++){let p=cw(aw(i,l,f),s,o,e,d);if(p!=null)return p}},Si=(n,t,e)=>{let i=ho.n.bitLength();if(n.bitLength()>i)return!1;let r=fr(n);if(e.x==null||e.y==null)throw new Error("Invalid public key: missing coordinates.");let s={x:fr(e.x),y:fr(e.y)},o={r:fr(t.r),s:fr(t.s)},{r:c,s:u}=o,f=r;if(c<=Ut||c>=xi||u<=Ut||u>=xi)return!1;let d=Yu(u);if(d===0n)return!1;let l=fo(f,d),p=fo(c,d),m=Ca(l,{x:Ba,y:_a}),g=Ca(p,s),w=Kr(m,g);if(w.Z===0n)return!1;let S=Vr(w.Z),C=ct(S,S),E=ct(w.X,C);return ur(E)===c};var Ju=class{constructor(){b(this,"_rand");let t=()=>{throw new Error("No secure random number generator is available in this environment.")};if(this._rand=t,typeof globalThis<"u"&&typeof globalThis.crypto?.getRandomValues=="function"){this._rand=e=>this.getRandomValues(globalThis,e);return}if(globalThis.self!==void 0&&typeof globalThis.self.crypto?.getRandomValues=="function"){this._rand=e=>this.getRandomValues(globalThis.self,e);return}if(globalThis.window!==void 0&&typeof globalThis.window.crypto?.getRandomValues=="function"){this._rand=e=>this.getRandomValues(globalThis.window,e);return}if(typeof process<"u"&&typeof process.getBuiltinModule=="function"){let e=process.getBuiltinModule("node:crypto");if(typeof e?.randomBytes=="function"){this._rand=i=>Array.from(e.randomBytes(i));return}}this._rand=t}getRandomValues(t,e){let i=new Uint8Array(e);return t.crypto.getRandomValues(i),Array.from(i)}generate(t){return this._rand(t)}},Eh=null,uw=n=>(Eh??(Eh=new Ju),Eh.generate(n)),Pe=uw;var Ae=255,fw=129,kh=/^[1-9A-HJ-NP-Za-km-z]{1,64}$/;function Th(n,t,e){if(!Number.isSafeInteger(n)||n<e||n>Ae)throw new TypeError(`threshold must be a safe integer from ${e} to ${Ae}`);if(n>t)throw new Error("threshold cannot exceed the number of points")}var nn=class n{constructor(t,e){b(this,"x");b(this,"y");let i=new Vt().p;this.x=t.umod(i),this.y=e.umod(i)}toString(){return oo(this.x.toArray())+"."+oo(this.y.toArray())}static fromString(t){if(typeof t!="string"||t.length>fw)throw new TypeError("Finite-field point must use a bounded canonical Base58 representation");let[e,i,r]=t.split(".");if(r!==void 0||e===void 0||i===void 0||!kh.test(e)||!kh.test(i))throw new TypeError("Finite-field point must use a bounded canonical Base58 representation");let s=new n(new T(so(e)),new T(so(i)));if(s.toString()!==t)throw new TypeError("Finite-field point must use a bounded canonical Base58 representation");return s}},zr=class n{constructor(t,e){b(this,"points");b(this,"threshold");if(!Array.isArray(t)||t.length===0||t.length>Ae)throw new TypeError(`points must contain from 1 to ${Ae} entries`);let i=e??t.length;Th(i,t.length,1),this.points=t.slice(),this.threshold=i}static fromPrivateKey(t,e){if(!Number.isSafeInteger(e)||e<2||e>Ae)throw new TypeError(`threshold must be a safe integer from 2 to ${Ae}`);let i=new Vt().p,r=[new nn(new T(0),new T(t.toArray()))];for(let s=1;s<e;s++){let o=new T(Pe(32)).umod(i),c=new T(Pe(32)).umod(i);r.push(new nn(o,c))}return new n(r)}valueAt(t){if(Th(this.threshold,this.points.length,1),!(t instanceof T))throw new TypeError("x must be a BigNumber");let e=new Vt().p,i=new Set;for(let o=0;o<this.threshold;o++){let c=this.points[o];if(!(c instanceof nn)||!(c.x instanceof T)||!(c.y instanceof T))throw new TypeError("points must contain finite-field points");if(c.x.isNeg()||c.y.isNeg()||c.x.gte(e)||c.y.gte(e))throw new TypeError("point coordinates must be canonical field elements");let u=c.x.toString(16);if(i.has(u))throw new Error("Polynomial points must have unique x coordinates");i.add(u)}let r=t.umod(e),s=new T(0);for(let o=0;o<this.threshold;o++){let c=this.points[o].y;for(let u=0;u<this.threshold;u++)if(o!==u){let f=this.points[u].x,d=this.points[o].x,l=r.sub(f).umod(e),m=d.sub(f).umod(e).invm(e),g=l.mul(m).umod(e);c=c.mul(g).umod(e)}s=s.add(c).umod(e)}return s}};var dw=256,Oh=/^[1-9A-HJ-NP-Za-km-z]{1,64}$/,lw=/^(?:[2-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/,Ph=/^[0-9a-f]{8}$/;function Qu(n,t,e){if(!Array.isArray(n)||n.length===0||n.length>Ae)throw new TypeError(`shares must contain from 1 to ${Ae} entries`);if(!Number.isSafeInteger(t)||t<2||t>Ae)throw new TypeError(`threshold must be a safe integer from 2 to ${Ae}`);if(typeof e!="string"||!Ph.test(e))throw new TypeError("integrity must be an 8-character lowercase hexadecimal string")}var po=class n{constructor(t,e,i){b(this,"points");b(this,"threshold");b(this,"integrity");this.points=t,this.threshold=e,this.integrity=i}static fromBackupFormat(t){if(!Array.isArray(t)||t.length===0||t.length>Ae)throw new TypeError(`shares must contain from 1 to ${Ae} entries`);let e=0,i="",r=[];for(let s=0;s<t.length;s++){if(!Object.prototype.hasOwnProperty.call(t,s))throw new TypeError("shares must be a dense array");let o=t[s];if(typeof o!="string"||o.length>dw)throw new TypeError(`Invalid share format in share ${s.toString()}`);let c=o.split(".");if(c.length!==4)throw new Error(`Invalid share format in share ${s.toString()}. Expected format: "x.y.t.i"`);let[u,f,d,l]=c;if(u===void 0||f===void 0||d===void 0||l===void 0||!Oh.test(u)||!Oh.test(f)||!lw.test(d)||!Ph.test(l))throw new TypeError(`Invalid canonical share data in share ${s.toString()}`);let p=Number(d);if(s!==0&&e!==p)throw new Error("Threshold mismatch in share "+s.toString());if(s!==0&&i!==l)throw new Error("Integrity mismatch in share "+s.toString());e=p,i=l,r.push(nn.fromString(`${u}.${f}`))}return Qu(r,e,i),new n(r,e,i)}toBackupFormat(){Qu(this.points,this.threshold,this.integrity);let t=[];for(let e=0;e<this.points.length;e++){if(!Object.prototype.hasOwnProperty.call(this.points,e))throw new TypeError("shares must be a dense array");let i=this.points[e];if(!(i instanceof nn))throw new TypeError("shares must contain finite-field points");let r=i.toString();if(nn.fromString(r).toString()!==r)throw new TypeError("shares must contain canonical finite-field points");t.push(`${r}.${this.threshold.toString()}.${this.integrity}`)}return t}},dr=class n extends T{static fromRandom(){return new n(Pe(32))}static fromString(t,e="hex"){return new n(super.fromString(t,e).toArray())}static fromHex(t){return new n(super.fromHex(t,"big"))}static fromWif(t,e=1){let i=co(t,void 0,e);if(i.data.length!==33)throw new Error("Invalid WIF length");if(i.data[32]!==1)throw new Error("Invalid WIF padding");return new n(i.data.slice(0,32))}constructor(t=0,e=10,i="be",r="apply"){if(t instanceof T?(super(),t.copy(this)):super(t,e,i),r!=="nocheck"){let s=this.checkInField();if(!s.inField){if(r==="error")throw new Error("Input is out of field");T.move(this,s.modN)}}}checkInField(){let t=new Vt,e=this.mod(t.n);return{inField:this.cmp(e)===0,modN:e}}isValid(){return this.checkInField().inField}sign(t,e,i=!0,r){let s=new T(Te(t,e),16);return Ah(s,this,i,r)}verify(t,e,i){let r=new T(Te(t,i),16);return Si(r,e,this.toPublicKey())}toPublicKey(){let e=new Vt().g.mulCT(this);return new Ht(e.x,e.y)}toWif(t=[128]){if(!this.isValid())throw new Error("Value is out of field");return ao([...this.toArray("be",32),1],t)}toAddress(t=[0]){return this.toPublicKey().toAddress(t)}toHex(){return super.toHex(32)}toString(t="hex",e=64){return super.toString(t,e)}deriveSharedSecret(t){if(!t.validate())throw new Error("Public key not valid for ECDH secret derivation");return t.mulCT(this)}deriveChild(t,e,i,r){let s;if(typeof r=="function"){let f=r(this,t);f===void 0?(s=this.deriveSharedSecret(t),typeof i=="function"&&i(this,t,s)):s=f}else s=this.deriveSharedSecret(t);let o=at(e,"utf8"),c=Qs(s.encode(!0),o),u=new Vt;return new n(this.add(new T(c)).mod(u.n).toArray())}toKeyShares(t,e){if(typeof t!="number"||typeof e!="number")throw new TypeError("threshold and totalShares must be numbers");if(!Number.isSafeInteger(t)||!Number.isSafeInteger(e))throw new TypeError("threshold and totalShares must be safe integers");if(t<2)throw new Error("threshold must be at least 2");if(e<2)throw new Error("totalShares must be at least 2");if(t>e)throw new Error("threshold should be less than or equal to totalShares");if(t>Ae||e>Ae)throw new RangeError(`threshold and totalShares cannot exceed ${Ae}`);let i=zr.fromPrivateKey(this,t),r=[],s=new Set,o=new Vt,c=Pe(64);for(let f=0;f<e;f++){let d,l=0;do{let m=[f,l,...Pe(32)],g=Fu(c,m);if(d=new T(g).umod(o.p),l++,l>5)throw new Error("Failed to generate unique x coordinate after 5 attempts")}while(d.isZero()||s.has(d.toString()));s.add(d.toString());let p=i.valueAt(d);r.push(new nn(d,p))}let u=this.toPublicKey().toHash("hex").slice(0,8);return new po(r,t,u)}toBackupShares(t,e){return this.toKeyShares(t,e).toBackupFormat()}static fromBackupShares(t){return n.fromKeyShares(po.fromBackupFormat(t))}static fromKeyShares(t){if(t===null||typeof t!="object")throw new TypeError("keyShares must be an object");let e=t.points,i=t.threshold,r=t.integrity;if(Qu(e,i,r),e.length<i)throw new Error(`At least ${i} shares are required to reconstruct the private key`);let s=[],o=new Vt().p;for(let d=0;d<i;d++){if(!Object.prototype.hasOwnProperty.call(e,d))throw new TypeError("shares must be a dense array");let l=e[d];if(!(l instanceof nn)||!(l.x instanceof T)||!(l.y instanceof T))throw new TypeError("shares must contain finite-field points");if(l.x.isNeg()||l.y.isNeg()||l.x.gte(o)||l.y.gte(o))throw new TypeError("share coordinates must be canonical field elements");s.push(new nn(new T(l.x.toArray()),new T(l.y.toArray())))}for(let d=0;d<i;d++)for(let l=d+1;l<i;l++)if(s[d].x.eq(s[l].x))throw new Error("Duplicate share detected, each must be unique.");let c=new zr(s,i),u=new n(c.valueAt(new T(0)).toArray());if(u.toPublicKey().toHash("hex").slice(0,8)!==r)throw new Error("Integrity hash mismatch");return u}};var tf={OP_0:0,OP_FALSE:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_1:81,OP_TRUE: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_SPLIT:127,OP_NUM2BIN:128,OP_BIN2NUM: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_CHECKLOCKTIMEVERIFY:177,OP_NOP2:177,OP_CHECKSEQUENCEVERIFY:178,OP_NOP3:178,OP_SUBSTR:179,OP_NOP4:179,OP_LEFT:180,OP_NOP5:180,OP_RIGHT:181,OP_NOP6:181,OP_LSHIFTNUM:182,OP_NOP7:182,OP_RSHIFTNUM:183,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_NOP11:186,OP_NOP12:187,OP_NOP13:188,OP_NOP14:189,OP_NOP15:190,OP_NOP16:191,OP_NOP17:192,OP_NOP18:193,OP_NOP19:194,OP_NOP20:195,OP_NOP21:196,OP_NOP22:197,OP_NOP23:198,OP_NOP24:199,OP_NOP25:200,OP_NOP26:201,OP_NOP27:202,OP_NOP28:203,OP_NOP29:204,OP_NOP30:205,OP_NOP31:206,OP_NOP32:207,OP_NOP33:208,OP_NOP34:209,OP_NOP35:210,OP_NOP36:211,OP_NOP37:212,OP_NOP38:213,OP_NOP39:214,OP_NOP40:215,OP_NOP41:216,OP_NOP42:217,OP_NOP43:218,OP_NOP44:219,OP_NOP45:220,OP_NOP46:221,OP_NOP47:222,OP_NOP48:223,OP_NOP49:224,OP_NOP50:225,OP_NOP51:226,OP_NOP52:227,OP_NOP53:228,OP_NOP54:229,OP_NOP55:230,OP_NOP56:231,OP_NOP57:232,OP_NOP58:233,OP_NOP59:234,OP_NOP60:235,OP_NOP61:236,OP_NOP62:237,OP_NOP63:238,OP_NOP64:239,OP_NOP65:240,OP_NOP66:241,OP_NOP67:242,OP_NOP68:243,OP_NOP69:244,OP_NOP70:245,OP_NOP71:246,OP_NOP72:247,OP_NOP73:248,OP_NOP77:252,OP_SMALLDATA:249,OP_SMALLINTEGER:250,OP_PUBKEYS:251,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},Ua=tf;for(let n of Object.keys(tf)){let t=tf[n];Ua[t]??(Ua[t]=n)}var x=Ua;var Rh=typeof globalThis>"u"?void 0:globalThis.Buffer,Nh=Symbol();function hr(n){return n[Nh]()}function hw(n){let t=n.data?.length??0;if(t===0||n.op===x.OP_RETURN||n.op<x.OP_PUSHDATA1)return[n.op];if(n.op===x.OP_PUSHDATA1)return[n.op,t&255];if(n.op===x.OP_PUSHDATA2)return[n.op,t&255,t>>8&255];if(n.op===x.OP_PUSHDATA4){let e=t>>>0;return[n.op,e&255,e>>8&255,e>>16&255,e>>24&255]}}function pw(n,t){let e=hw(n),i=n.data??[];if(e==null||t.length!==e.length+i.length)return!1;for(let r=0;r<e.length;r++)if(t[r]!==e[r])return!1;for(let r=0;r<i.length;r++)if(t[e.length+r]!==i[r])return!1;return!0}var Ve,zn,Ke,On,lr,te,Bh,_h,_t,ef,Ch,Lh,Kn,nf,Uh,Ma,Mh,rf,Dh,Hh,sf,$h,de=class de{constructor(t=[],e,i,r=!0){G(this,_t);G(this,Ve);G(this,zn);G(this,Ke);G(this,On);G(this,lr);N(this,Ve,t),N(this,zn,r),N(this,Ke,e),N(this,On,i)}static fromASM(t){var s;let e=[],i=t.split(" "),r=0;for(;r<i.length;){let{chunk:o,advance:c}=a(s=de,te,_h).call(s,i,r);e.push(o),r+=c}return new de(e)}static fromHex(t){if(t.length===0)return de.fromBinary([]);if(t.length%2!==0)throw new Error("There is an uneven number of characters in the string which suggests it is not hex encoded.");let e;try{e=ro(t)}catch{throw new Error("Some elements in this string are not hex encoded.")}return new de([],e,t.toLowerCase(),!1)}static fromBinary(t){let e=Uint8Array.from(t);return new de([],e,void 0,!1)}static fromBinaryView(t){return new de([],t,void 0,!1)}get chunks(){return a(this,_t,ef).call(this),y(this,Ve)}set chunks(t){N(this,Ve,t),N(this,zn,!0),a(this,_t,Kn).call(this)}toASM(){let t="";for(let e of this.chunks)t+=a(this,_t,$h).call(this,e);return t.slice(1)}toHex(){let t=a(this,_t,Ma).call(this);if(y(this,On)!=null)return y(this,On);let e=Rh==null?Pa(Array.from(t),"hex"):Rh.from(t).toString("hex");return N(this,On,e),e}toBinary(){return Array.from(this.toUint8Array())}toUint8Array(){return Uint8Array.from(a(this,_t,Ma).call(this))}[Nh](){return a(this,_t,Ma).call(this)}writeScript(t){return a(this,_t,Kn).call(this),this.chunks=this.chunks.concat(t.chunks),this}writeOpCode(t){return a(this,_t,Kn).call(this),this.chunks.push({op:t}),this}setChunkOpCode(t,e){return a(this,_t,Kn).call(this),this.chunks[t]={op:e},this}writeBn(t){if(a(this,_t,Kn).call(this),t.cmpn(0)===x.OP_0)this.chunks.push({op:x.OP_0});else if(t.cmpn(-1)===0)this.chunks.push({op:x.OP_1NEGATE});else if(t.cmpn(1)>=0&&t.cmpn(16)<=0)this.chunks.push({op:t.toNumber()+x.OP_1-1});else{let e=t.toSm("little");this.writeBin(e)}return this}writeBin(t){a(this,_t,Kn).call(this);let e,i=t.length>0?t:void 0;if(t.length>0&&t.length<x.OP_PUSHDATA1)e=t.length;else if(t.length===0)e=x.OP_0;else if(t.length<Math.pow(2,8))e=x.OP_PUSHDATA1;else if(t.length<Math.pow(2,16))e=x.OP_PUSHDATA2;else if(t.length<Math.pow(2,32))e=x.OP_PUSHDATA4;else throw new Error("You can't push that much data");return this.chunks.push({data:i,op:e}),this}writeNumber(t){return a(this,_t,Kn).call(this),this.writeBn(new T(t)),this}removeCodeseparators(){var e;let t=this.toUint8Array();return N(this,Ke,Uint8Array.from(a(e=de,te,Hh).call(e,t,x.OP_CODESEPARATOR))),N(this,On,void 0),N(this,Ve,[]),N(this,zn,!1),this}findAndDelete(t){a(this,_t,Kn).call(this);let e=t.toUint8Array();if(e.length===0)return this;for(let i=0;i<this.chunks.length;)pw(this.chunks[i],e)?this.chunks.splice(i,1):i++;return this}isPushOnly(){for(let t of this.chunks)if(t.op>x.OP_16)return!1;return!0}isLockingScript(){throw new Error("Not implemented")}isUnlockingScript(){throw new Error("Not implemented")}};Ve=new WeakMap,zn=new WeakMap,Ke=new WeakMap,On=new WeakMap,lr=new WeakMap,te=new WeakSet,Bh=function(t){return t>=0&&t<x.OP_PUSHDATA1?t:t<Math.pow(2,8)?x.OP_PUSHDATA1:t<Math.pow(2,16)?x.OP_PUSHDATA2:x.OP_PUSHDATA4},_h=function(t,e){var o;let i=t[e];if(i==="0")return{chunk:{op:0},advance:1};if(i==="-1")return{chunk:{op:x.OP_1NEGATE},advance:1};let r=i.startsWith("OP_")&&x[i]!==void 0,s=r?x[i]:0;if(s===x.OP_PUSHDATA1||s===x.OP_PUSHDATA2||s===x.OP_PUSHDATA4)return{chunk:{data:at(t[e+2],"hex"),op:s},advance:3};if(!r){let c=i;c.length%2!==0&&(c="0"+c);let u=at(c,"hex");if(Pa(u,"hex")!==c)throw new Error("invalid hex string in script");return{chunk:{data:u,op:a(o=de,te,Bh).call(o,u.length)},advance:1}}return{chunk:{op:s},advance:1}},_t=new WeakSet,ef=function(){var t;y(this,zn)||(y(this,Ke)!=null?N(this,Ve,a(t=de,te,Dh).call(t,y(this,Ke))):N(this,Ve,[]),N(this,zn,!0),a(this,_t,nf).call(this))},Ch=function(t){let e=0;for(let i of t){if(e+=1,i.data==null)continue;let r=i.data.length;if(i.op===x.OP_RETURN){e+=r;break}i.op<x.OP_PUSHDATA1?e+=r:i.op===x.OP_PUSHDATA1?e+=1+r:i.op===x.OP_PUSHDATA2?e+=2+r:i.op===x.OP_PUSHDATA4&&(e+=4+r)}return e},Lh=function(){var s,o;let t=this.chunks,e=a(s=de,te,Ch).call(s,t),i=new Uint8Array(e),r=0;for(let c of t)if(i[r++]=c.op,c.data!=null){if(c.op===x.OP_RETURN){i.set(c.data,r);break}r=a(o=de,te,Mh).call(o,i,r,c.op,c.data)}return i},Kn=function(){N(this,Ke,void 0),N(this,On,void 0),N(this,lr,void 0)},nf=function(){N(this,lr,y(this,Ve).map(t=>({ref:t,op:t.op,dataRef:t.data,data:t.data==null?void 0:Array.from(t.data)})))},Uh=function(){if(y(this,lr)?.length!==y(this,Ve).length)return!1;for(let t=0;t<y(this,Ve).length;t++){let e=y(this,Ve)[t],i=y(this,lr)[t];if(i.ref!==e||i.op!==e.op||i.dataRef!==e.data||i.data?.length!==e.data?.length)return!1;if(i.data!=null&&e.data!=null){for(let r=0;r<i.data.length;r++)if(i.data[r]!==e.data[r])return!1}}return!0},Ma=function(){return!y(this,zn)&&y(this,Ke)!=null?y(this,Ke):(a(this,_t,ef).call(this),(y(this,Ke)==null||!a(this,_t,Uh).call(this))&&(N(this,Ke,a(this,_t,Lh).call(this)),N(this,On,void 0),a(this,_t,nf).call(this)),y(this,Ke))},Mh=function(t,e,i,r){let s=r.length;if(i<x.OP_PUSHDATA1)return t.set(r,e),e+s;if(i===x.OP_PUSHDATA1)return t[e++]=s&255,t.set(r,e),e+s;if(i===x.OP_PUSHDATA2)return t[e++]=s&255,t[e++]=s>>8&255,t.set(r,e),e+s;if(i===x.OP_PUSHDATA4){let o=s>>>0;return t[e++]=o&255,t[e++]=o>>8&255,t[e++]=o>>16&255,t[e++]=o>>24&255,t.set(r,e),e+s}return e},rf=function(t,e,i,r){if(t>0&&t<x.OP_PUSHDATA1)return{len:t,newPos:i,hasLength:!0};if(t===x.OP_PUSHDATA1){let c=i<r;return{len:c?e[i++]??0:0,newPos:i,hasLength:c}}if(t===x.OP_PUSHDATA2){let c=i+1<r;return{len:(e[i]??0)|(e[i+1]??0)<<8,newPos:Math.min(i+2,r),hasLength:c}}let s=i+3<r;return{len:((e[i]??0)|(e[i+1]??0)<<8|(e[i+2]??0)<<16|(e[i+3]??0)<<24)>>>0,newPos:Math.min(i+4,r),hasLength:s}},Dh=function(t){var o,c,u;let e=[],i=t.length,r=0,s=0;for(;r<i;){let f=t[r++]??0;if(f===x.OP_RETURN&&s===0){e.push({op:f,data:a(o=de,te,sf).call(o,t,r,i)});break}if(f===x.OP_IF||f===x.OP_NOTIF||f===x.OP_VERIF||f===x.OP_VERNOTIF?s++:f===x.OP_ENDIF&&s--,f>0&&f<=x.OP_PUSHDATA4){let{len:d,newPos:l,hasLength:p}=a(c=de,te,rf).call(c,f,t,r,i);r=l;let m=Math.min(r+d,i),g=!p||m-r!==d;e.push({data:a(u=de,te,sf).call(u,t,r,m),op:f,invalidLength:g}),r=m}else e.push({op:f})}return e},Hh=function(t,e){var o;let i=[],r=t.length,s=0;for(;s<r;){let c=s,u=t[s++]??0;if(u>0&&u<=x.OP_PUSHDATA4){let{len:f,newPos:d}=a(o=de,te,rf).call(o,u,t,s,r);s=d;let l=Math.min(s+f,r);if(u!==e)for(let p=c;p<l;p++)i.push(t[p]??0);s=l}else u!==e&&i.push(u)}return i},sf=function(t,e,i){let r=Math.max(i-e,0),s=Array.from({length:r},()=>0);for(let o=0;o<r;o++)s[o]=t[e+o]??0;return s},$h=function(t){let e=t.op,i="";if(t.data===void 0){let r=x[e];i=`${i} ${r}`}else i=`${i} ${nt(t.data)}`;return i},G(de,te);var me=de;var gw=new Uint8Array(0),of=Object.freeze(Array.from({length:32},()=>0));function mw(n,t,e){return e>0&&e<x.OP_PUSHDATA1?{length:e,nextPosition:t}:e===x.OP_PUSHDATA1?n.length-t<1?void 0:{length:n[t],nextPosition:t+1}:e===x.OP_PUSHDATA2?n.length-t<2?void 0:{length:n[t]|n[t+1]<<8,nextPosition:t+2}:e===x.OP_PUSHDATA4?n.length-t<4?void 0:{length:(n[t]|n[t+1]<<8|n[t+2]<<16|n[t+3]<<24)>>>0,nextPosition:t+4}:{length:0,nextPosition:t}}function bw(n){let t=n.toBinary(),e=[],i=0,r=0,s=0,o=c=>{for(let u=r;u<c;u++)e.push(t[u])};for(;i<t.length;){let c=i,u=t[i++],f=mw(t,i,u);if(f==null||(i=f.nextPosition,t.length-i<f.length))break;i+=f.length,u===x.OP_CODESEPARATOR&&(o(c),r=i,s++)}return o(i),{bytes:e,encodedLength:t.length-s}}function ww(n,t){if(n.allInputs!=null)return n.allInputs;let e=[...n.otherInputs];return e.splice(n.inputIndex,0,t),e}function Wh(n,t,e,i){return i===t?e:n[i]}function yw(n,t,e){let i=new fe;for(let r=0;r<n.length;r++){let s=Wh(n,t,e,r);if(s.sourceTXID==null){if(s.sourceTransaction==null)throw new Error("Missing sourceTransaction for input");i.write(s.sourceTransaction.hash())}else i.writeReverse(at(s.sourceTXID,"hex"));i.writeUInt32LE(s.sourceOutputIndex)}return zt(i.toUint8Array())}function xw(n,t,e){let i=new fe;for(let r=0;r<n.length;r++){let s=Wh(n,t,e,r);i.writeUInt32LE(s.sequence??4294967295)}return zt(i.toUint8Array())}function qh(n,t){n.writeUInt64LE(t.satoshis??0);let e=t.lockingScript?.toUint8Array()??gw;n.writeVarIntNum(e.length),n.write(e)}function Fh(n,t){let e=new fe;if(t==null)for(let i of n)qh(e,i);else{let i=n[t];if(i==null)throw new Error(`Output at index ${t} does not exist`);qh(e,i)}return zt(e.toUint8Array())}function Sw(n,t,e){if((n.scope&wt.SIGHASH_ANYONECANPAY)!==0)return[...of];if(n.cache?.hashPrevouts!=null)return n.cache.hashPrevouts;let i=yw(t,n.inputIndex,e);return n.cache!=null&&(n.cache.hashPrevouts=i),i}function Iw(n,t,e){let i=n.scope&31;if((n.scope&wt.SIGHASH_ANYONECANPAY)!==0||i===wt.SIGHASH_SINGLE||i===wt.SIGHASH_NONE)return[...of];if(n.cache?.hashSequence!=null)return n.cache.hashSequence;let r=xw(t,n.inputIndex,e);return n.cache!=null&&(n.cache.hashSequence=r),r}function vw(n){var r;let t=n.scope&31;if(t!==wt.SIGHASH_SINGLE&&t!==wt.SIGHASH_NONE){if(n.cache?.hashOutputsAll!=null)return n.cache.hashOutputsAll;let s=Fh(n.outputs);return n.cache!=null&&(n.cache.hashOutputsAll=s),s}if(t!==wt.SIGHASH_SINGLE||n.inputIndex>=n.outputs.length)return[...of];let e=n.cache?.hashOutputsSingle?.get(n.inputIndex);if(e!=null)return e;let i=Fh(n.outputs,n.inputIndex);return n.cache!=null&&((r=n.cache).hashOutputsSingle??(r.hashOutputsSingle=new Map),n.cache.hashOutputsSingle.set(n.inputIndex,i)),i}var Xt=class Xt extends ge{constructor(e,i,r){super(e,i);b(this,"scope");this.scope=r}static formatOTDA(e){let i=(e.scope&Xt.SIGHASH_ANYONECANPAY)===Xt.SIGHASH_ANYONECANPAY,r=(e.scope&31)===Xt.SIGHASH_SINGLE,s=(e.scope&31)===Xt.SIGHASH_NONE,o=(e.scope&31)===Xt.SIGHASH_ALL||!r&&!s,c=bw(e.subscript),u={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence,script:c.bytes,scriptLength:c.encodedLength},f=new fe;function d(g){f.writeVarIntNum(g.length);for(let w of g)f.writeReverse(at(w.sourceTXID,"hex")),f.writeUInt32LE(w.sourceOutputIndex),f.writeVarIntNum(w.scriptLength??w.script.length),f.write(w.script),f.writeUInt32LE(w.sequence)}function l(g){f.writeVarIntNum(g.length);for(let w of g)f.writeUInt64LE(w.satoshis),f.writeVarIntNum(w.script.length),f.write(w.script)}f.writeInt32LE(e.transactionVersion);let p=new me().toBinary();if(i)i&&d([u]);else{let g=e.allInputs==null?e.otherInputs.map(w=>({sourceTXID:w.sourceTXID??w.sourceTransaction?.id("hex")??"",sourceOutputIndex:w.sourceOutputIndex,sequence:r||s?0:w.sequence??4294967295,script:p})):e.allInputs.map((w,S)=>S===e.inputIndex?u:{sourceTXID:w.sourceTXID??w.sourceTransaction?.id("hex")??"",sourceOutputIndex:w.sourceOutputIndex,sequence:r||s?0:w.sequence??4294967295,script:p});e.allInputs==null&&g.splice(e.inputIndex,0,u),d(g)}if(o){let g=e.outputs.map(w=>({satoshis:w.satoshis??0,script:w.lockingScript.toBinary()}));l(g)}else if(r){let g=[];for(let S=0;S<e.inputIndex;S++)g.push({satoshis:-1,script:p});let w=e.outputs[e.inputIndex];w!==void 0&&g.push({satoshis:w.satoshis??0,script:w.lockingScript.toBinary()}),l(g)}else s&&l([]);return f.writeUInt32LE(e.lockTime),f.writeUInt32LE(e.scope>>>0),f.toUint8Array()}static formatBip143(e){let i={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence},r=ww(e,i),s=Sw(e,r,i),o=Iw(e,r,i),c=vw(e),u=new fe;u.writeInt32LE(e.transactionVersion),u.write(s),u.write(o),u.writeReverse(at(e.sourceTXID,"hex")),u.writeUInt32LE(e.sourceOutputIndex);let f=e.subscript.toUint8Array();u.writeVarIntNum(f.length),u.write(f),u.writeUInt64LE(e.sourceSatoshis);let d=i.sequence??4294967295;return u.writeUInt32LE(d),u.write(c),u.writeUInt32LE(e.lockTime),u.writeUInt32LE(e.scope>>>0),u.toUint8Array()}static format(e){return Array.from(this.formatBytes(e))}static formatBytes(e){let i=(e.scope&Xt.SIGHASH_FORKID)!==0,r=e.ignoreChronicle!==!0&&(e.scope&Xt.SIGHASH_CHRONICLE)!==0;return i&&e.sighashForkIdEnabled!==!1&&!r?Xt.formatBip143(e):e.sighashForkIdEnabled===!1||!i||r?Xt.formatOTDA(e):new Uint8Array(0)}static usesOtdaSingleBug(e){let i=(e.scope&Xt.SIGHASH_FORKID)!==0,r=e.ignoreChronicle!==!0&&(e.scope&Xt.SIGHASH_CHRONICLE)!==0;return(e.sighashForkIdEnabled===!1||!i||r)&&(e.scope&31)===Xt.SIGHASH_SINGLE&&e.inputIndex>=e.outputs.length}static fromChecksigFormat(e){if(e.length===0){let o=new T(1),c=new T(1),u=1;return new Xt(o,c,u)}let i=e.at(-1),r=e.slice(0,-1),s=ge.fromDER(r);return new Xt(s.r,s.s,i)}hasLowS(){return!(this.s.ltn(1)||this.s.gt(new T("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex")))}toChecksigFormat(){return[...this.toDER(),this.scope]}};b(Xt,"SIGHASH_ALL",1),b(Xt,"SIGHASH_NONE",2),b(Xt,"SIGHASH_SINGLE",3),b(Xt,"SIGHASH_CHRONICLE",32),b(Xt,"SIGHASH_FORKID",64),b(Xt,"SIGHASH_ANYONECANPAY",128);var wt=Xt;function af(n,t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${n} returned a non-byte result`);if(e!==void 0&&t.length!==e)throw new Error(`${n} returned ${t.length} bytes; expected ${e}`);return t}function Aw(){return globalThis}function cf(n){let t=Aw().__bsvSdkAsyncCryptoBackendV1;if(t!==void 0){if(!t.isReady()){t.preload().catch(()=>{});return}return t.supportsCrypto(n)?t:void 0}}var Le=class extends me{isLockingScript(){return!0}isUnlockingScript(){return!1}};var Ue=class extends me{isLockingScript(){return!1}isUnlockingScript(){return!0}};function Vh(n){return n==null?"null/undef":n.length===void 0?"INVALID_STACK_ITEM":nt(n)}var go=class extends Error{constructor(e){let i=e.stackState.map(Vh).join(", "),r=e.altStackState.map(Vh).join(", "),s=`Context: ${e.context}, PC: ${e.programCounter}`,o=`Stack: [${i}] (len: ${e.stackState.length}, mem: ${e.stackMem})`,c=`AltStack: [${r}] (len: ${e.altStackState.length}, mem: ${e.altStackMem})`,u=`IfStack: [${e.ifStackState.join(", ")}]`,f=`Script evaluation error: ${e.message}
|
|
4
4
|
TXID: ${e.txid}, OutputIdx: ${e.outputIndex}
|
|
5
5
|
${s}
|
|
6
6
|
${o}
|
|
7
7
|
${c}
|
|
8
|
-
${u}`;super(f);m(this,"txid");m(this,"outputIndex");m(this,"context");m(this,"programCounter");m(this,"stackState");m(this,"altStackState");m(this,"ifStackState");m(this,"stackMem");m(this,"altStackMem");this.name=this.constructor.name,this.txid=e.txid,this.outputIndex=e.outputIndex,this.context=e.context,this.programCounter=e.programCounter,this.stackState=e.stackState.map(d=>d.slice()),this.altStackState=e.altStackState.map(d=>d.slice()),this.ifStackState=e.ifStackState.slice(),this.stackMem=e.stackMem,this.altStackMem=e.altStackMem}};var zn=class extends Error{constructor(e,i,r){let o={stack:"Stack memory usage","alt-stack":"Alt stack memory usage","element-size":"Script element allocation"}[e];super(`${o} has exceeded ${i} bytes`);m(this,"resource");m(this,"limit");m(this,"attempted");this.resource=e,this.limit=i,this.attempted=r,this.name="ScriptResourceLimitError"}};var hy;function La(){return hy}var py=520,Dh=1e4,Hh=500,gy=0x7fffffffn,by=75e4,my=32e6,$h=1e3,yy=Math.pow(2,31)-1,wy=BigInt(yy),xy=20,qh=2147483648,of=4194304,Iy=65535,Fh=5e8,Sy=Object.freeze(new T(-1).toScriptNum()),Wh=Object.freeze(Array.from({length:17},(n,t)=>Object.freeze(new T(t).toScriptNum())));function Vh(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}function Si(n){return new T(n?1:0)}function vy(n,t){return Si(n&&t)}function Ay(n,t){return Si(n||t)}function Ey(n,t){return n.cmp(t)<0?n:t}function ky(n,t){return n.cmp(t)>0?n:t}function Kh(n){if(typeof n.consensus!="boolean")throw new TypeError("Spend verification consensus must be boolean");for(let[e,i]of[["blockHeight",n.blockHeight],["utxoHeight",n.utxoHeight]])if(i!==void 0&&(!Number.isSafeInteger(i)||i<0||i>4294967295))throw new RangeError(`Spend verification ${e} must be an unsigned 32-bit integer`);let t=Array.isArray(n.verifyFlags)?Array.from(n.verifyFlags):n.verifyFlags;if(t!==void 0&&typeof t!="string"&&(!Array.isArray(t)||t.some(e=>typeof e!="string")))throw new TypeError("Spend verification flags must be a string or an array of strings");return{consensus:n.consensus,blockHeight:n.blockHeight,utxoHeight:n.utxoHeight,verifyFlags:t}}function zh(n,t=Number.MAX_SAFE_INTEGER){return!(n.length>t||n.length>0&&(n.at(-1)&127)===0&&(n.length<=1||(n.at(-2)&128)===0))}function Ty(n){if(n.length<9||n.length>73||n[0]!==48||n[1]!==n.length-3)return!1;let t=n[2],e=n[3];if(t!==2||e===0||5+e>=n.length)return!1;let i=4+e,r=n[i],s=n[i+1];if(r!==2||s===0||(n[4]&128)!==0||e>1&&n[4]===0&&(n[5]&128)===0)return!1;let o=i+2;return!((n[o]&128)!==0||s>1&&n[o]===0&&(n[o+1]&128)===0||e+s+7!==n.length)}function Oy(n){let t=n.data,e=n.op;return Array.isArray(t)?t.length===0?e===x.OP_0:t.length===1&&t[0]>=1&&t[0]<=16?e===x.OP_1+(t[0]-1):t.length===1&&t[0]===129?e===x.OP_1NEGATE:t.length<=75?e===t.length:t.length<=255?e===x.OP_PUSHDATA1:t.length<=65535?e===x.OP_PUSHDATA2:!0:!0}var jn,xo,h,Ii,Mt,Et,re,go,Xn,bo,Xh,jh,Gh,Yh,af,cf,Ua,zr,mo,Zh,lt,Re,Q,Kt,vt,Jh,Qh,Ma,tp,ep,de,yo,uf,np,ip,rp,ff,df,lf,hf,sp,pf,gf,op,ap,cp,up,fp,dp,lp,hp,pp,gp,bp,bf,Da,mp,mf,Xr,K,yf=class yf{constructor(t){G(this,h);m(this,"sourceTXID");m(this,"sourceOutputIndex");m(this,"sourceSatoshis");m(this,"lockingScript");m(this,"transactionVersion");m(this,"otherInputs");m(this,"allInputs");m(this,"outputs");m(this,"inputIndex");m(this,"unlockingScript");m(this,"inputSequence");m(this,"lockTime");m(this,"context");m(this,"programCounter");m(this,"lastCodeSeparator");m(this,"stack");m(this,"altStack");m(this,"ifStack");m(this,"elseStack");m(this,"memoryLimit");m(this,"hasExplicitMemoryLimit");m(this,"stackMem");m(this,"altStackMem");m(this,"isRelaxedOverride");m(this,"verifyFlags");m(this,"executedOpCount");m(this,"returningFromConditional");G(this,jn);G(this,xo);if(this.sourceTXID=t.sourceTXID,this.sourceOutputIndex=t.sourceOutputIndex,this.sourceSatoshis=t.sourceSatoshis,this.lockingScript=t.lockingScript,this.transactionVersion=t.transactionVersion,this.otherInputs=t.otherInputs,this.allInputs=t.allInputs,this.outputs=t.outputs,this.inputIndex=t.inputIndex,this.unlockingScript=t.unlockingScript,this.inputSequence=t.inputSequence,this.lockTime=t.lockTime,this.hasExplicitMemoryLimit=t.memoryLimit!==void 0,this.memoryLimit=t.memoryLimit??Number.POSITIVE_INFINITY,this.isRelaxedOverride=t.isRelaxed===!0,t.verifyFlags===void 0)this.verifyFlags=void 0;else{let e=Array.isArray(t.verifyFlags)?t.verifyFlags:t.verifyFlags.split(",");this.verifyFlags=new Set(e.map(i=>i.trim()).filter(i=>i.length>0))}this.stack=[],this.altStack=[],this.ifStack=[],this.elseStack=[],this.stackMem=0,this.altStackMem=0,this.executedOpCount=0,this.returningFromConditional=!1,N(this,xo,t.sigHashCache==null),N(this,jn,t.sigHashCache??{hashOutputsSingle:new Map}),this.reset()}reset(){y(this,xo)&&(delete y(this,jn).hashPrevouts,delete y(this,jn).hashSequence,delete y(this,jn).hashOutputsAll,y(this,jn).hashOutputsSingle?.clear()),this.context="UnlockingScript",this.programCounter=0,this.lastCodeSeparator=null,this.stack=[],this.altStack=[],this.ifStack=[],this.elseStack=[],this.stackMem=0,this.altStackMem=0,this.executedOpCount=0,this.returningFromConditional=!1}step(){a(this,h,op).call(this);let t=a(this,h,ap).call(this);if(this.programCounter>=t.chunks.length)return!1;let e=t.chunks[this.programCounter],i=a(this,h,cp).call(this,e),r=!this.returningFromConditional&&!this.ifStack.includes(!1);if(a(this,h,up).call(this,i),r&&i>=0&&i<=x.OP_PUSHDATA4)a(this,h,fp).call(this,e);else if(r||i>=x.OP_IF&&i<=x.OP_ENDIF){let s,o,c,u,f,d,l,p,b,g,w,S,C,E,A,k,B,_,$,R,I,U,M,F,it,ot;if(a(this,h,dp).call(this,i,r),a(this,h,lp).call(this,i,r))return!0;switch(a(this,h,hp).call(this,i,r),i){case x.OP_VER:{let q=this.transactionVersion;a(this,h,lt).call(this,[q&255,q>>>8&255,q>>>16&255,q>>>24&255]);break}case x.OP_SUBSTR:{(()=>{this.stack.length<3&&a(this,h,K).call(this,"OP_SUBSTR requires at least three items to be on the stack.");let q=a(this,h,yo).call(this,a(this,h,Q).call(this)),z=a(this,h,yo).call(this,a(this,h,Q).call(this));s=a(this,h,Q).call(this);let tt=s.length;(z<0||z>=tt||q<0||q>tt-z)&&a(this,h,K).call(this,`OP_SUBSTR offset (${z}) must be in range [0, ${tt}) and length (${q}) must be in range [0, ${tt-z}]`),a(this,h,lt).call(this,s.slice(z,z+q))})();break}case x.OP_LEFT:{(()=>{this.stack.length<2&&a(this,h,K).call(this,"OP_LEFT requires at least two items to be on the stack.");let q=a(this,h,yo).call(this,a(this,h,Q).call(this));s=a(this,h,Q).call(this);let z=s.length;(q<0||q>z)&&a(this,h,K).call(this,`OP_LEFT length (${q}) must be in range [0, ${z}]`),a(this,h,lt).call(this,s.slice(0,q))})();break}case x.OP_RIGHT:{(()=>{this.stack.length<2&&a(this,h,K).call(this,"OP_RIGHT requires at least two items to be on the stack.");let q=a(this,h,yo).call(this,a(this,h,Q).call(this));s=a(this,h,Q).call(this);let z=s.length;(q<0||q>z)&&a(this,h,K).call(this,`OP_RIGHT length (${q}) must be in range [0, ${z}]`),a(this,h,lt).call(this,s.slice(z-q))})();break}case x.OP_LSHIFTNUM:{(()=>{this.stack.length<2&&a(this,h,K).call(this,"OP_LSHIFTNUM requires at least two items to be on the stack.");let q=a(this,h,de).call(this,a(this,h,Q).call(this)).toBigInt();q<0&&a(this,h,K).call(this,"OP_LSHIFTNUM bits to shift must not be negative."),q>0x7fffffffn&&a(this,h,K).call(this,"OP_LSHIFTNUM shift count exceeds INT_MAX.");let z=a(this,h,de).call(this,a(this,h,Q).call(this)).toBigInt(),tt=a(this,h,Ua).call(this);tt!==void 0&&z!==0n&&q>=BigInt(tt)*8n&&a(this,h,K).call(this,"script number overflow");let It=new T(z<<q).toScriptNum();tt!==void 0&&It.length>tt&&a(this,h,K).call(this,"script number overflow"),a(this,h,lt).call(this,It)})();break}case x.OP_RSHIFTNUM:{(()=>{this.stack.length<2&&a(this,h,K).call(this,"OP_RSHIFTNUM requires at least two items to be on the stack.");let q=a(this,h,de).call(this,a(this,h,Q).call(this)).toBigInt();q<0&&a(this,h,K).call(this,"OP_RSHIFTNUM bits to shift must not be negative."),q>0x7fffffffn&&a(this,h,K).call(this,"OP_RSHIFTNUM shift count exceeds INT_MAX.");let z=a(this,h,de).call(this,a(this,h,Q).call(this)).toBigInt(),tt;z<0?tt=new T(-(-z>>q)):tt=new T(z>>q),a(this,h,lt).call(this,tt.toScriptNum())})();break}case x.OP_1NEGATE:a(this,h,Re).call(this,Sy);break;case x.OP_0:a(this,h,Re).call(this,Wh[0]);break;case x.OP_1:case x.OP_2:case x.OP_3:case x.OP_4:case x.OP_5:case x.OP_6:case x.OP_7:case x.OP_8:case x.OP_9:case x.OP_10:case x.OP_11:case x.OP_12:case x.OP_13:case x.OP_14:case x.OP_15:case x.OP_16:S=i-(x.OP_1-1),a(this,h,Re).call(this,Wh[S]);break;case x.OP_NOP:case x.OP_NOP1:break;case x.OP_CHECKLOCKTIMEVERIFY:a(this,h,pp).call(this);break;case x.OP_CHECKSEQUENCEVERIFY:a(this,h,gp).call(this);break;case x.OP_NOP9:case x.OP_NOP10:break;case x.OP_VERIF:case x.OP_VERNOTIF:(()=>{if(E=!1,r){if(this.stack.length<1&&a(this,h,K).call(this,"OP_VERIF and OP_VERNOTIF require at least one item on the stack when they are used!"),o=a(this,h,Q).call(this),o.length===4){let q=this.transactionVersion;c=[q&255,q>>>8&255,q>>>16&255,q>>>24&255],E=Vh(o,c)}i===x.OP_VERNOTIF&&(E=!E)}this.ifStack.push(E),this.elseStack.push(!1)})();break;case x.OP_IF:case x.OP_NOTIF:E=!1,r&&(this.stack.length<1&&a(this,h,K).call(this,"OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),s=a(this,h,Q).call(this),a(this,h,Et).call(this,"MINIMALIF")&&a(this,h,Xn).call(this)&&s.length>0&&!(s.length===1&&s[0]===1)&&a(this,h,K).call(this,"OP_IF and OP_NOTIF require minimal truth values."),E=a(this,h,Xr).call(this,s),i===x.OP_NOTIF&&(E=!E)),this.ifStack.push(E),this.elseStack.push(!1);break;case x.OP_ELSE:this.ifStack.length===0&&a(this,h,K).call(this,"OP_ELSE requires a preceeding OP_IF."),a(this,h,Mt).call(this)&&a(this,h,re).call(this)&&this.elseStack.at(-1)===!0&&a(this,h,K).call(this,"OP_ELSE may only be used once for each OP_IF or OP_NOTIF after Genesis."),this.elseStack[this.elseStack.length-1]=!0,this.ifStack[this.ifStack.length-1]=this.ifStack.at(-1)!==!0;break;case x.OP_ENDIF:this.ifStack.length===0&&a(this,h,K).call(this,"OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop(),this.elseStack.pop();break;case x.OP_VERIFY:this.stack.length<1&&a(this,h,K).call(this,"OP_VERIFY requires at least one item to be on the stack."),o=a(this,h,Kt).call(this),E=a(this,h,Xr).call(this,o),E||a(this,h,K).call(this,"OP_VERIFY requires the top stack value to be truthy."),a(this,h,Q).call(this);break;case x.OP_RETURN:a(this,h,Mt).call(this)&&!a(this,h,re).call(this)&&a(this,h,K).call(this,"OP_RETURN is invalid before Genesis."),this.ifStack.length>0?this.returningFromConditional=!0:(this.context==="UnlockingScript"?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.programCounter--);break;case x.OP_TOALTSTACK:a(this,h,vt).call(this,1,"OP_TOALTSTACK requires at oeast one item to be on the stack."),a(this,h,tp).call(this,a(this,h,Q).call(this));break;case x.OP_FROMALTSTACK:a(this,h,Jh).call(this,1,"OP_FROMALTSTACK requires at least one item to be on the stack."),a(this,h,lt).call(this,a(this,h,ep).call(this));break;case x.OP_2DROP:a(this,h,vt).call(this,2,"OP_2DROP requires at least two items to be on the stack."),a(this,h,Q).call(this),a(this,h,Q).call(this);break;case x.OP_2DUP:a(this,h,vt).call(this,2,"OP_2DUP requires at least two items to be on the stack."),o=a(this,h,Kt).call(this,-2),c=a(this,h,Kt).call(this,-1),a(this,h,Re).call(this,o),a(this,h,Re).call(this,c);break;case x.OP_3DUP:a(this,h,vt).call(this,3,"OP_3DUP requires at least three items to be on the stack."),o=a(this,h,Kt).call(this,-3),c=a(this,h,Kt).call(this,-2),u=a(this,h,Kt).call(this,-1),a(this,h,Re).call(this,o),a(this,h,Re).call(this,c),a(this,h,Re).call(this,u);break;case x.OP_2OVER:a(this,h,vt).call(this,4,"OP_2OVER requires at least four items to be on the stack."),o=a(this,h,Kt).call(this,-4),c=a(this,h,Kt).call(this,-3),a(this,h,Re).call(this,o),a(this,h,Re).call(this,c);break;case x.OP_2ROT:{a(this,h,vt).call(this,6,"OP_2ROT requires at least six items to be on the stack.");let q=a(this,h,Q).call(this),z=a(this,h,Q).call(this),tt=a(this,h,Q).call(this),It=a(this,h,Q).call(this),ae=a(this,h,Q).call(this),Bt=a(this,h,Q).call(this);a(this,h,lt).call(this,It),a(this,h,lt).call(this,tt),a(this,h,lt).call(this,z),a(this,h,lt).call(this,q),a(this,h,lt).call(this,Bt),a(this,h,lt).call(this,ae);break}case x.OP_2SWAP:{a(this,h,vt).call(this,4,"OP_2SWAP requires at least four items to be on the stack.");let q=a(this,h,Q).call(this),z=a(this,h,Q).call(this),tt=a(this,h,Q).call(this),It=a(this,h,Q).call(this);a(this,h,lt).call(this,z),a(this,h,lt).call(this,q),a(this,h,lt).call(this,It),a(this,h,lt).call(this,tt);break}case x.OP_IFDUP:a(this,h,vt).call(this,1,"OP_IFDUP requires at least one item to be on the stack."),o=a(this,h,Kt).call(this),a(this,h,Xr).call(this,o)&&a(this,h,Re).call(this,o);break;case x.OP_DEPTH:a(this,h,lt).call(this,new T(this.stack.length).toScriptNum());break;case x.OP_DROP:a(this,h,vt).call(this,1,"OP_DROP requires at least one item to be on the stack."),a(this,h,Q).call(this);break;case x.OP_DUP:a(this,h,vt).call(this,1,"OP_DUP requires at least one item to be on the stack."),a(this,h,Re).call(this,a(this,h,Kt).call(this));break;case x.OP_NIP:a(this,h,vt).call(this,2,"OP_NIP requires at least two items to be on the stack."),c=a(this,h,Q).call(this),a(this,h,Q).call(this),a(this,h,lt).call(this,c);break;case x.OP_OVER:a(this,h,vt).call(this,2,"OP_OVER requires at least two items to be on the stack."),a(this,h,Re).call(this,a(this,h,Kt).call(this,-2));break;case x.OP_PICK:case x.OP_ROLL:{(()=>{a(this,h,vt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),p=a(this,h,de).call(this,a(this,h,Q).call(this));let q=p.toBigInt();(q<0n||q>=BigInt(this.stack.length))&&a(this,h,K).call(this,`${x[i]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);let z=Number(q),tt=this.stack[this.stack.length-1-z];i===x.OP_ROLL?(this.stack.splice(this.stack.length-1-z,1),this.stackMem-=tt.length,a(this,h,lt).call(this,tt)):a(this,h,Re).call(this,tt)})();break}case x.OP_ROT:a(this,h,vt).call(this,3,"OP_ROT requires at least three items to be on the stack."),l=a(this,h,Q).call(this),d=a(this,h,Q).call(this),f=a(this,h,Q).call(this),a(this,h,lt).call(this,d),a(this,h,lt).call(this,l),a(this,h,lt).call(this,f);break;case x.OP_SWAP:a(this,h,vt).call(this,2,"OP_SWAP requires at least two items to be on the stack."),d=a(this,h,Q).call(this),f=a(this,h,Q).call(this),a(this,h,lt).call(this,d),a(this,h,lt).call(this,f);break;case x.OP_TUCK:a(this,h,vt).call(this,2,"OP_TUCK requires at least two items to be on the stack."),o=a(this,h,Kt).call(this,-1),a(this,h,mo).call(this,o.length),this.stack.splice(-2,0,o.slice()),this.stackMem+=o.length;break;case x.OP_SIZE:a(this,h,vt).call(this,1,"OP_SIZE requires at least one item to be on the stack."),a(this,h,lt).call(this,new T(a(this,h,Kt).call(this).length).toScriptNum());break;case x.OP_AND:case x.OP_OR:case x.OP_XOR:{(()=>{a(this,h,vt).call(this,2,`${x[i]} requires at least two items on the stack.`),c=a(this,h,Q).call(this),o=a(this,h,Q).call(this),o.length!==c.length&&a(this,h,K).call(this,`${x[i]} requires the top two stack items to be the same size.`);let q=Array.from({length:o.length},()=>0);for(let z=0;z<o.length;z++)i===x.OP_AND?q[z]=o[z]&c[z]:i===x.OP_OR?q[z]=o[z]|c[z]:q[z]=o[z]^c[z];a(this,h,lt).call(this,q)})();break}case x.OP_INVERT:{(()=>{a(this,h,vt).call(this,1,"OP_INVERT requires at least one item to be on the stack."),s=a(this,h,Q).call(this);let q=Array.from({length:s.length},()=>0);for(let z=0;z<s.length;z++)q[z]=~s[z]&255;a(this,h,lt).call(this,q)})();break}case x.OP_LSHIFT:case x.OP_RSHIFT:{(()=>{a(this,h,vt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),g=a(this,h,de).call(this,a(this,h,Q).call(this)),o=a(this,h,Q).call(this);let q=g.toBigInt();if(q<0n&&a(this,h,K).call(this,`${x[i]} requires the top item on the stack not to be negative.`),o.length===0){a(this,h,lt).call(this,[]);return}if(q>=BigInt(o.length)*8n){a(this,h,lt).call(this,Array.from({length:o.length},()=>0));return}b=new T(o);let z;if(i===x.OP_LSHIFT){z=b.ushln(q);let It=new T(1).ushln(o.length*8).isubn(1);z=z.iand(It)}else z=b.ushrn(q);let tt=z.toArray("be",o.length);a(this,h,lt).call(this,tt)})();break}case x.OP_EQUAL:case x.OP_EQUALVERIFY:a(this,h,vt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),c=a(this,h,Q).call(this),o=a(this,h,Q).call(this),E=Vh(o,c),a(this,h,lt).call(this,E?[1]:[]),i===x.OP_EQUALVERIFY&&(E||a(this,h,K).call(this,"OP_EQUALVERIFY requires the top two stack items to be equal."),a(this,h,Q).call(this));break;case x.OP_1ADD:case x.OP_1SUB:case x.OP_2MUL:case x.OP_2DIV:case x.OP_NEGATE:case x.OP_ABS:case x.OP_NOT:case x.OP_0NOTEQUAL:(()=>{switch(a(this,h,vt).call(this,1,`${x[i]} requires at least one item to be on the stack.`),p=a(this,h,de).call(this,a(this,h,Q).call(this)),i){case x.OP_1ADD:p=p.add(new T(1));break;case x.OP_1SUB:p=p.sub(new T(1));break;case x.OP_2MUL:p=p.mul(new T(2));break;case x.OP_2DIV:p=p.div(new T(2));break;case x.OP_NEGATE:p=p.neg();break;case x.OP_ABS:p.isNeg()&&(p=p.neg());break;case x.OP_NOT:p=new T(p.cmpn(0)===0?1:0);break;case x.OP_0NOTEQUAL:p=new T(p.cmpn(0)===0?0:1);break}a(this,h,lt).call(this,p.toScriptNum())})();break;case x.OP_ADD:case x.OP_SUB:case x.OP_MUL:case x.OP_DIV:case x.OP_MOD:case x.OP_BOOLAND:case x.OP_BOOLOR:case x.OP_NUMEQUAL:case x.OP_NUMEQUALVERIFY:case x.OP_NUMNOTEQUAL:case x.OP_LESSTHAN:case x.OP_GREATERTHAN:case x.OP_LESSTHANOREQUAL:case x.OP_GREATERTHANOREQUAL:case x.OP_MIN:case x.OP_MAX:{(()=>{a(this,h,vt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),c=a(this,h,Q).call(this),o=a(this,h,Q).call(this),g=a(this,h,de).call(this,c),b=a(this,h,de).call(this,o);let q=(()=>{switch(i){case x.OP_MUL:return b.byteLength()+g.byteLength();case x.OP_ADD:case x.OP_SUB:return Math.max(b.byteLength(),g.byteLength())+1;default:return Math.max(b.byteLength(),g.byteLength())}})();a(this,h,mo).call(this,q);let z=(()=>{switch(i){case x.OP_ADD:return b.add(g);case x.OP_SUB:return b.sub(g);case x.OP_MUL:return b.mul(g);case x.OP_DIV:return g.cmpn(0)===0&&a(this,h,K).call(this,"OP_DIV cannot divide by zero!"),b.div(g);case x.OP_MOD:return g.cmpn(0)===0&&a(this,h,K).call(this,"OP_MOD cannot divide by zero!"),b.mod(g);case x.OP_BOOLAND:return vy(b.cmpn(0)!==0,g.cmpn(0)!==0);case x.OP_BOOLOR:return Ay(b.cmpn(0)!==0,g.cmpn(0)!==0);case x.OP_NUMEQUAL:case x.OP_NUMEQUALVERIFY:return Si(b.cmp(g)===0);case x.OP_NUMNOTEQUAL:return Si(b.cmp(g)!==0);case x.OP_LESSTHAN:return Si(b.cmp(g)<0);case x.OP_GREATERTHAN:return Si(b.cmp(g)>0);case x.OP_LESSTHANOREQUAL:return Si(b.cmp(g)<=0);case x.OP_GREATERTHANOREQUAL:return Si(b.cmp(g)>=0);case x.OP_MIN:return Ey(b,g);case x.OP_MAX:return ky(b,g);default:return new T(0)}})();a(this,h,lt).call(this,z.toScriptNum()),i===x.OP_NUMEQUALVERIFY&&(a(this,h,Xr).call(this,a(this,h,Kt).call(this))||a(this,h,K).call(this,"OP_NUMEQUALVERIFY requires the top stack item to be truthy."),a(this,h,Q).call(this))})();break}case x.OP_WITHIN:a(this,h,vt).call(this,3,"OP_WITHIN requires at least three items to be on the stack."),w=a(this,h,de).call(this,a(this,h,Q).call(this)),g=a(this,h,de).call(this,a(this,h,Q).call(this)),b=a(this,h,de).call(this,a(this,h,Q).call(this)),E=b.cmp(g)>=0&&b.cmp(w)<0,a(this,h,lt).call(this,E?[1]:[]);break;case x.OP_RIPEMD160:case x.OP_SHA1:case x.OP_SHA256:case x.OP_HASH160:case x.OP_HASH256:{(()=>{a(this,h,vt).call(this,1,`${x[i]} requires at least one item to be on the stack.`),s=a(this,h,Q).call(this);let q=[];i===x.OP_RIPEMD160?q=Mu(s):i===x.OP_SHA1?q=Du(s):i===x.OP_SHA256?q=Te(s):i===x.OP_HASH160?q=Zs(s):i===x.OP_HASH256&&(q=zt(s)),a(this,h,lt).call(this,q)})();break}case x.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case x.OP_CHECKSIG:case x.OP_CHECKSIGVERIFY:{a(this,h,vt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),_=a(this,h,Q).call(this),B=a(this,h,Q).call(this),(!a(this,h,ff).call(this,B)||!a(this,h,pf).call(this,_))&&a(this,h,K).call(this,`${x[i]} requires correct encoding for the public key and signature.`),A=(()=>{if(B.length===0)return!1;try{$=a(this,h,df).call(this,B);let z=(this.context==="UnlockingScript"?this.unlockingScript:this.lockingScript).chunks.slice(this.lastCodeSeparator===null?0:this.lastCodeSeparator+1);return this.context==="UnlockingScript"&&(z=z.concat(this.lockingScript.chunks)),k=new ge(z),(($.scope&yt.SIGHASH_FORKID)===0||a(this,h,Mt).call(this)&&!a(this,h,Et).call(this,"SIGHASH_FORKID"))&&k.findAndDelete(new ge().writeBin(B)),R=Ht.fromDER(_),a(this,h,gf).call(this,$,R,k)}catch{return!1}})(),!A&&a(this,h,Et).call(this,"NULLFAIL")&&a(this,h,Xn).call(this)&&B.length>0&&a(this,h,K).call(this,`${x[i]} requires failing signatures to be empty.`),a(this,h,lt).call(this,A?[1]:[]),i===x.OP_CHECKSIGVERIFY&&(A||a(this,h,K).call(this,"OP_CHECKSIGVERIFY requires that a valid signature is provided."),a(this,h,Q).call(this));break}case x.OP_CHECKMULTISIG:case x.OP_CHECKMULTISIGVERIFY:{(()=>{I=1,this.stack.length<I&&a(this,h,K).call(this,`${x[i]} requires at least 1 item for nKeys.`);let z=a(this,h,de).call(this,a(this,h,Kt).call(this,-I)).toBigInt(),tt=a(this,h,Mt).call(this)&&!a(this,h,re).call(this)?BigInt(xy):wy;(z<0n||z>tt)&&a(this,h,K).call(this,`${x[i]} requires a key count between 0 and ${tt.toString()}.`),F=Number(z);let It=F;U=++I,I+=F,this.stack.length<I&&a(this,h,K).call(this,`${x[i]} stack too small for nKeys and keys. Need ${I}, have ${this.stack.length}.`);let Bt=a(this,h,de).call(this,a(this,h,Kt).call(this,-I)).toBigInt();(Bt<0n||Bt>BigInt(F))&&a(this,h,K).call(this,`${x[i]} requires the number of signatures to be no greater than the number of keys.`),it=Number(Bt);let dn=it;M=++I,I+=it,this.stack.length<I&&a(this,h,K).call(this,`${x[i]} stack too small for N, keys, M, sigs, and dummy. Need ${I}, have ${this.stack.length}.`);let we=(this.context==="UnlockingScript"?this.unlockingScript:this.lockingScript).chunks.slice(this.lastCodeSeparator===null?0:this.lastCodeSeparator+1);k=new ge(we);let vn=!1;for(let H=0;H<it;H++)B=a(this,h,Kt).call(this,-M-H),B.length>0&&(vn=!0),((B.at(-1)&yt.SIGHASH_FORKID)===0||a(this,h,Mt).call(this)&&!a(this,h,Et).call(this,"SIGHASH_FORKID"))&&k.findAndDelete(new ge().writeBin(B));(()=>{for(A=!0;A&&it>0;){if(F===0){A=!1;break}if(B=a(this,h,Kt).call(this,-M),_=a(this,h,Kt).call(this,-U),(!a(this,h,ff).call(this,B)||!a(this,h,pf).call(this,_))&&a(this,h,K).call(this,`${x[i]} requires correct encoding for the public key and signature.`),ot=!1,B.length>0)try{$=a(this,h,df).call(this,B),R=Ht.fromDER(_),ot=a(this,h,gf).call(this,$,R,k)}catch{ot=!1}ot&&(M++,it--),U++,F--,it>F&&(A=!1)}})(),(()=>{!A&&a(this,h,Et).call(this,"NULLFAIL")&&a(this,h,Xn).call(this)&&vn&&a(this,h,K).call(this,`${x[i]} requires failing signatures to be empty.`);let W=1+It+1+dn+1-1;for(;W>0;)a(this,h,Q).call(this),W--;a(this,h,vt).call(this,1,`${x[i]} requires an extra item (dummy) to be on the stack.`);let D=a(this,h,Q).call(this);a(this,h,jh).call(this)&&D.length>0&&a(this,h,K).call(this,`${x[i]} requires the extra stack item (dummy) to be empty.`),a(this,h,lt).call(this,A?[1]:[]),i===x.OP_CHECKMULTISIGVERIFY&&(A||a(this,h,K).call(this,"OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),a(this,h,Q).call(this))})()})();break}case x.OP_CAT:{(()=>{a(this,h,vt).call(this,2,"OP_CAT requires at least two items to be on the stack."),c=a(this,h,Q).call(this),o=a(this,h,Q).call(this);let q=o.concat(c);q.length>a(this,h,zr).call(this)&&a(this,h,K).call(this,`It's not currently possible to push data larger than ${a(this,h,zr).call(this)} bytes.`),a(this,h,lt).call(this,q)})();break}case x.OP_SPLIT:{(()=>{a(this,h,vt).call(this,2,"OP_SPLIT requires at least two items to be on the stack.");let q=a(this,h,Q).call(this),z=a(this,h,Q).call(this),tt=a(this,h,de).call(this,q).toBigInt();(tt<0n||tt>BigInt(z.length))&&a(this,h,K).call(this,"OP_SPLIT requires the first stack item to be a non-negative number less than or equal to the size of the second-from-top stack item.");let It=Number(tt);a(this,h,lt).call(this,z.slice(0,It)),a(this,h,lt).call(this,z.slice(It))})();break}case x.OP_NUM2BIN:{(()=>{a(this,h,vt).call(this,2,"OP_NUM2BIN requires at least two items to be on the stack.");let q=a(this,h,de).call(this,a(this,h,Q).call(this)).toBigInt(),z=a(this,h,zr).call(this);if((Number.isFinite(z)&&q>BigInt(z)||q<0n)&&a(this,h,K).call(this,`It's not currently possible to push data larger than ${z} bytes or negative size.`),q>gy&&a(this,h,K).call(this,"OP_NUM2BIN size exceeds the node int32 push limit."),this.hasExplicitMemoryLimit&&Number.isFinite(this.memoryLimit)){let Bt=Math.max(0,Math.floor(this.memoryLimit));if(q>BigInt(Bt))throw new zn("element-size",Bt,q)}C=Number(q);let tt=a(this,h,Q).call(this);if(tt=Ta(tt),tt.length>C&&a(this,h,K).call(this,"OP_NUM2BIN requires that the size expressed in the top stack item is large enough to hold the value expressed in the second-from-top stack item."),tt.length===C){a(this,h,lt).call(this,tt);return}let It=Array.from({length:C},()=>0),ae=0;tt.length>0&&(ae=tt.at(-1)&128,tt[tt.length-1]&=127);for(let Bt=0;Bt<tt.length;Bt++)It[Bt]=tt[Bt];ae!==0&&(It[C-1]|=128),a(this,h,lt).call(this,It)})();break}case x.OP_BIN2NUM:{(()=>{a(this,h,vt).call(this,1,"OP_BIN2NUM requires at least one item to be on the stack."),o=a(this,h,Q).call(this);let q=Ta(o);zh(q)||a(this,h,K).call(this,"OP_BIN2NUM requires that the resulting number is valid."),a(this,h,lt).call(this,q)})();break}default:a(this,h,K).call(this,`Invalid opcode ${i} (pc=${this.programCounter}).`)}}return a(this,h,bp).call(this,t),!0}validate(t){let e=La(),i=a(this,h,bf).call(this),r=t===void 0?void 0:Kh(t);return e?.verifySpendSync!==void 0&&(e.isReady?.()??!0)&&(r===void 0?e.shouldVerifySpend?.(i):e.shouldVerifySpend?.(i,r))!==!1?((r===void 0?e.verifySpendSync(i):e.verifySpendSync(i,r))!==!0&&a(this,h,K).call(this,"The selected script-verification backend rejected the spend."),!0):this.validateJavaScript()}validateJavaScript(){this.reset(),a(this,h,Gh).call(this)&&!this.unlockingScript.isPushOnly()&&a(this,h,K).call(this,"Unlocking scripts can only contain push operations, and no other opcodes.");let t=this.lockingScript,e=a(this,h,Et).call(this,"P2SH")&&!a(this,h,re).call(this)&&a(this,h,mp).call(this,this.lockingScript);e&&!this.unlockingScript.isPushOnly()&&a(this,h,K).call(this,"P2SH unlocking scripts can only contain push operations."),a(this,h,Da).call(this,"UnlockingScript");let i=this.stack.map(r=>r.slice());a(this,h,Da).call(this,"LockingScript"),a(this,h,mf).call(this);try{if(e){i.length===0&&a(this,h,K).call(this,"P2SH evaluation requires a redeem script on the stack.");let r=i.pop();if(r===void 0)return a(this,h,K).call(this,"P2SH evaluation requires a redeem script on the stack."),!1;a(this,h,Qh).call(this,i);let s=ge.fromBinary(r);this.lockingScript=new Le(s.chunks),a(this,h,Da).call(this,"LockingScript")}}finally{this.lockingScript=t}return a(this,h,Yh).call(this)&&this.stack.length!==1&&a(this,h,K).call(this,`The clean stack rule requires exactly one item to be on the stack after script execution, found ${this.stack.length}.`),a(this,h,mf).call(this),!0}async validateWith(t,e){let i=a(this,h,bf).call(this),r=e===void 0?void 0:Kh(e),s=r===void 0?t.shouldVerifySpend?.(i):t.shouldVerifySpend?.(i,r);if(s!==void 0&&typeof s!="boolean")throw new TypeError("Spend verifier selection must be boolean");if(s===!1)return i.validateJavaScript();let o=r===void 0?await t.verifySpend(i):await t.verifySpend(i,r);if(typeof o!="boolean")throw new TypeError("Spend verifier returned a non-boolean verdict");return o}toTransactionUint8Array(){let t={sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,unlockingScript:this.unlockingScript,sequence:this.inputSequence},e=this.allInputs??[...this.otherInputs.slice(0,this.inputIndex),t,...this.otherInputs.slice(this.inputIndex)];if(this.inputIndex<0||this.inputIndex>=e.length)throw new RangeError("Spend input index is out of range");let i=new ht;i.writeUInt32LE(this.transactionVersion),i.writeVarIntNum(e.length);for(let r=0;r<e.length;r++){let s=r===this.inputIndex?t:e[r],o=s.sourceTXID??s.sourceTransaction?.id("hex");if(o===void 0)throw new Error(`Input ${r} is missing its source transaction ID`);if(s.unlockingScript===void 0)throw new Error(`Input ${r} is missing its unlocking script`);i.writeReverse(at(o,"hex")),i.writeUInt32LE(s.sourceOutputIndex);let c=s.unlockingScript.toUint8Array();i.writeVarIntNum(c.length),i.write(c),i.writeUInt32LE(s.sequence??4294967295)}i.writeVarIntNum(this.outputs.length);for(let r of this.outputs){i.writeUInt64LE(r.satoshis??0);let s=r.lockingScript.toUint8Array();i.writeVarIntNum(s.length),i.write(s)}return i.writeUInt32LE(this.lockTime),i.toUint8Array()}};jn=new WeakMap,xo=new WeakMap,h=new WeakSet,Ii=function(){return this.isRelaxedOverride||this.transactionVersion>1},Mt=function(){return this.verifyFlags!==void 0},Et=function(t){return this.verifyFlags?.has(t)===!0},re=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"UTXO_AFTER_GENESIS")||a(this,h,Et).call(this,"UTXO_AFTER_CHRONICLE"):a(this,h,Ii).call(this)},go=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"UTXO_AFTER_CHRONICLE"):a(this,h,Ii).call(this)},Xn=function(){return!(a(this,h,Et).call(this,"CHRONICLE")&&this.transactionVersion>1)},bo=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"MINIMALDATA")&&a(this,h,Xn).call(this):!a(this,h,Ii).call(this)},Xh=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"LOW_S")&&a(this,h,Xn).call(this):!a(this,h,Ii).call(this)},jh=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"NULLDUMMY")&&a(this,h,Xn).call(this):!a(this,h,Ii).call(this)},Gh=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"SIGPUSHONLY")&&a(this,h,Xn).call(this):!a(this,h,Ii).call(this)},Yh=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"CLEANSTACK")&&a(this,h,Xn).call(this):!a(this,h,Ii).call(this)},af=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"DERSIG")||a(this,h,Et).call(this,"STRICTENC")||a(this,h,Et).call(this,"LOW_S")||a(this,h,Et).call(this,"SIGHASH_FORKID"):!0},cf=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"STRICTENC")||a(this,h,Et).call(this,"SIGHASH_FORKID"):!0},Ua=function(){if(a(this,h,Mt).call(this))return a(this,h,re).call(this)?a(this,h,go).call(this)?my:by:4},zr=function(){return a(this,h,Mt).call(this)&&!a(this,h,re).call(this)?py:Number.POSITIVE_INFINITY},mo=function(t){if(this.stackMem+t>this.memoryLimit)throw new zn("stack",this.memoryLimit,this.stackMem+t)},Zh=function(t){if(this.altStackMem+t>this.memoryLimit)throw new zn("alt-stack",this.memoryLimit,this.altStackMem+t)},lt=function(t){a(this,h,mo).call(this,t.length),this.stack.push(t),this.stackMem+=t.length},Re=function(t){a(this,h,mo).call(this,t.length);let e=t.slice();this.stack.push(e),this.stackMem+=e.length},Q=function(){this.stack.length===0&&a(this,h,K).call(this,"Attempted to pop from an empty stack.");let t=this.stack.pop();return t===void 0?(a(this,h,K).call(this,"Attempted to pop from an empty stack."),[]):(this.stackMem-=t.length,t)},Kt=function(t=-1){return(this.stack.length===0||this.stack.length<Math.abs(t)||t>=0&&t>=this.stack.length)&&a(this,h,K).call(this,`Stack underflow accessing element at index ${t}. Stack length is ${this.stack.length}.`),this.stack[this.stack.length+t]},vt=function(t,e){this.stack.length<t&&a(this,h,K).call(this,e)},Jh=function(t,e){this.altStack.length<t&&a(this,h,K).call(this,e)},Qh=function(t){this.stack=t.map(e=>e.slice()),this.stackMem=this.stack.reduce((e,i)=>e+i.length,0)},Ma=function(){this.altStack=[],this.altStackMem=0},tp=function(t){a(this,h,Zh).call(this,t.length),this.altStack.push(t),this.altStackMem+=t.length},ep=function(){this.altStack.length===0&&a(this,h,K).call(this,"Attempted to pop from an empty alt stack.");let t=this.altStack.pop();return t===void 0?(a(this,h,K).call(this,"Attempted to pop from an empty alt stack."),[]):(this.altStackMem-=t.length,t)},de=function(t){try{return T.fromScriptNum(t,a(this,h,bo).call(this),a(this,h,Ua).call(this))}catch(e){let i=e instanceof Error?e.message:String(e);a(this,h,K).call(this,i)}return new T(0)},yo=function(t){let e=a(this,h,Ua).call(this);e!==void 0&&t.length>e&&a(this,h,K).call(this,"script number overflow"),a(this,h,bo).call(this)&&!zh(t)&&a(this,h,K).call(this,"non-minimally encoded script number");let i;if(t.length>8){i=0n;for(let r=0;r<8;r++)i|=BigInt(t[r])<<BigInt(r*8);i=BigInt.asIntN(64,i)}else i=a(this,h,de).call(this,t).toBigInt();return i>0x7fffffffn?2147483647:i<-0x80000000n?-2147483648:Number(i)},uf=function(t){try{return T.fromScriptNum(t,a(this,h,bo).call(this),5).toBigInt()}catch(e){a(this,h,K).call(this,e instanceof Error?e.message:String(e))}return 0n},np=function(t){let e=t&31;return e>=yt.SIGHASH_ALL&&e<=yt.SIGHASH_SINGLE},ip=function(t){if(!a(this,h,cf).call(this))return;a(this,h,np).call(this,t.scope)||a(this,h,K).call(this,"The signature hash type is invalid.");let e=(t.scope&yt.SIGHASH_CHRONICLE)!==0,i=a(this,h,Mt).call(this)?a(this,h,Et).call(this,"CHRONICLE"):a(this,h,go).call(this);e&&!i&&a(this,h,K).call(this,"The signature hash type is invalid before Chronicle.")},rp=function(t){if(!a(this,h,Mt).call(this)||!a(this,h,Et).call(this,"STRICTENC"))return;let e=(t.scope&yt.SIGHASH_FORKID)!==0;a(this,h,Et).call(this,"SIGHASH_FORKID")&&!e&&a(this,h,K).call(this,"The signature must use SIGHASH_FORKID."),!a(this,h,Et).call(this,"SIGHASH_FORKID")&&!a(this,h,re).call(this)&&e&&a(this,h,K).call(this,"The signature must not use SIGHASH_FORKID.")},ff=function(t){if(t.length===0)return!0;let e=a(this,h,af).call(this);if(e&&!Ty(t))return a(this,h,K).call(this,"The signature format is invalid."),!1;try{let i=yt.fromChecksigFormat(t);if(a(this,h,ip).call(this,i),a(this,h,rp).call(this,i),a(this,h,Xh).call(this)&&!i.hasLowS())return a(this,h,K).call(this,"The signature must have a low S value."),!1}catch{if(e)return a(this,h,K).call(this,"The signature format is invalid."),!1}return!0},df=function(t){try{return yt.fromChecksigFormat(t)}catch(e){if(a(this,h,af).call(this))throw e;return a(this,h,sp).call(this,t)}},lf=function(t,e){let i=t[e.value++];if(i===void 0)throw new Error("Invalid DER length");if((i&128)===0)return i;let r=i&127;if(r===0||e.value+r>t.length)throw new Error("Invalid DER length");let s=0;for(let o=0;o<r;o++)s=s<<8|(t[e.value++]??0);return s},hf=function(t,e,i){if(e.value>=i||t[e.value++]!==2)throw new Error("Invalid DER integer");let r=a(this,h,lf).call(this,t,e);if(e.value+r>i)throw new Error("Invalid DER integer length");let s=t.slice(e.value,e.value+r);for(e.value+=r;s.length>1&&s[0]===0;)s=s.slice(1);return s.length===0&&(s=[0]),new T(s)},sp=function(t){if(t.length===0)return yt.fromChecksigFormat(t);let e=t.at(-1),i=t.slice(0,-1),r={value:0};if(i[r.value++]!==48)throw new Error("Signature DER must start with 0x30");let s=a(this,h,lf).call(this,i,r),o=Math.min(r.value+s,i.length),c=a(this,h,hf).call(this,i,r,o),u=a(this,h,hf).call(this,i,r,o);return new yt(c,u,e)},pf=function(t){if(!a(this,h,cf).call(this))return!0;if(t.length===0)return a(this,h,K).call(this,"Public key is empty."),!1;if(t.length<33)return a(this,h,K).call(this,"The public key is too short, it must be at least 33 bytes."),!1;if(t[0]===4){if(t.length!==65)return a(this,h,K).call(this,"The non-compressed public key must be 65 bytes."),!1}else if(t[0]===2||t[0]===3){if(t.length!==33)return a(this,h,K).call(this,"The compressed public key must be 33 bytes."),!1}else return a(this,h,K).call(this,"The public key is in an unknown format."),!1;try{Ht.fromDER(t)}catch{return a(this,h,K).call(this,"The public key is in an unknown format."),!1}return!0},gf=function(t,e,i){let r={sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,transactionVersion:this.transactionVersion,otherInputs:this.otherInputs,allInputs:this.allInputs,outputs:this.outputs,inputIndex:this.inputIndex,subscript:i,inputSequence:this.inputSequence,lockTime:this.lockTime,scope:t.scope,sighashForkIdEnabled:!a(this,h,Mt).call(this)||a(this,h,Et).call(this,"SIGHASH_FORKID"),cache:y(this,jn)},s=yt.usesOtdaSingleBug(r)?new T([1,...Array.from({length:31},()=>0)]):new T(zt(yt.formatBytes(r)));return xi(s,t,e)},op=function(){if(this.stackMem>this.memoryLimit)throw new zn("stack",this.memoryLimit,this.stackMem);if(this.altStackMem>this.memoryLimit)throw new zn("alt-stack",this.memoryLimit,this.altStackMem)},ap=function(){return this.context==="UnlockingScript"&&this.programCounter>=this.unlockingScript.chunks.length&&(this.ifStack.length>0&&a(this,h,K).call(this,"Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the unlocking script."),a(this,h,Ma).call(this),this.ifStack=[],this.elseStack=[],this.returningFromConditional=!1,this.lastCodeSeparator=null,this.context="LockingScript",this.programCounter=0),this.context==="UnlockingScript"?this.unlockingScript:this.lockingScript},cp=function(t){let e=t.op;return e===void 0?(a(this,h,K).call(this,`Missing opcode in ${this.context} at pc=${this.programCounter}.`),0):(t.invalidLength===!0&&a(this,h,K).call(this,`Malformed push data in ${this.context} at pc=${this.programCounter}.`),Array.isArray(t.data)&&t.data.length>a(this,h,zr).call(this)&&a(this,h,K).call(this,`Data push > ${a(this,h,zr).call(this)} bytes (pc=${this.programCounter}).`),e)},up=function(t){a(this,h,Mt).call(this)&&!a(this,h,re).call(this)&&!a(this,h,go).call(this)&&(t===x.OP_2MUL||t===x.OP_2DIV||t===x.OP_VERIF||t===x.OP_VERNOTIF)&&a(this,h,K).call(this,`${x[t]} is disabled until Chronicle.`)},fp=function(t){a(this,h,bo).call(this)&&!Oy(t)&&a(this,h,K).call(this,`This data is not minimally-encoded. (PC: ${this.programCounter})`),a(this,h,lt).call(this,Array.isArray(t.data)?t.data:[])},dp=function(t,e){!e||t<=x.OP_16||(this.executedOpCount++,a(this,h,Mt).call(this)&&!a(this,h,re).call(this)&&this.executedOpCount>Hh&&a(this,h,K).call(this,`Script executed more than ${Hh} opcodes.`))},lp=function(t,e){return!a(this,h,Mt).call(this)||a(this,h,go).call(this)?!1:e&&(t===x.OP_SUBSTR||t===x.OP_LEFT||t===x.OP_RIGHT||t===x.OP_LSHIFTNUM||t===x.OP_RSHIFTNUM)?(a(this,h,Et).call(this,"DISCOURAGE_UPGRADABLE_NOPS")&&a(this,h,K).call(this,`${x[t]} is discouraged by verification flags.`),this.programCounter++,!0):((e||!a(this,h,re).call(this))&&(t===x.OP_2MUL||t===x.OP_2DIV)&&a(this,h,K).call(this,`${x[t]} is disabled until Chronicle.`),(e||!a(this,h,re).call(this))&&(t===x.OP_VER||t===x.OP_VERIF||t===x.OP_VERNOTIF)&&a(this,h,K).call(this,`${x[t]} is disabled until Chronicle.`),!e&&a(this,h,re).call(this)&&(t===x.OP_VERIF||t===x.OP_VERNOTIF)?(this.programCounter++,!0):!1)},hp=function(t,e){let i=t===x.OP_CHECKLOCKTIMEVERIFY&&(!a(this,h,Et).call(this,"CHECKLOCKTIMEVERIFY")||a(this,h,re).call(this)),r=t===x.OP_CHECKSEQUENCEVERIFY&&(!a(this,h,Et).call(this,"CHECKSEQUENCEVERIFY")||a(this,h,re).call(this));e&&a(this,h,Et).call(this,"DISCOURAGE_UPGRADABLE_NOPS")&&(t===x.OP_NOP1||i||r||t===x.OP_NOP9||t===x.OP_NOP10)&&a(this,h,K).call(this,`${x[t]} is discouraged by verification flags.`)},pp=function(){if(!a(this,h,Et).call(this,"CHECKLOCKTIMEVERIFY")||a(this,h,re).call(this))return;a(this,h,vt).call(this,1,"OP_CHECKLOCKTIMEVERIFY requires one stack item.");let t=a(this,h,uf).call(this,a(this,h,Kt).call(this));t<0n&&a(this,h,K).call(this,"Negative lock time.");let e=t<BigInt(Fh),i=this.lockTime<Fh;(e!==i||t>BigInt(this.lockTime)||this.inputSequence===4294967295)&&a(this,h,K).call(this,"OP_CHECKLOCKTIMEVERIFY lock time is unsatisfied.")},gp=function(){if(!a(this,h,Et).call(this,"CHECKSEQUENCEVERIFY")||a(this,h,re).call(this))return;a(this,h,vt).call(this,1,"OP_CHECKSEQUENCEVERIFY requires at least one item to be on the stack.");let t=a(this,h,uf).call(this,a(this,h,Kt).call(this));if(t<0n&&a(this,h,K).call(this,"OP_CHECKSEQUENCEVERIFY requires a non-negative lock time."),(t&BigInt(qh))!==0n)return;let e=BigInt(this.inputSequence>>>0),i=BigInt(of|Iy),r=t&i,s=e&i;(this.transactionVersion>>>0<2||(e&BigInt(qh))!==0n||(r&BigInt(of))!==(s&BigInt(of))||r>s)&&a(this,h,K).call(this,"OP_CHECKSEQUENCEVERIFY lock time is unsatisfied.")},bp=function(t){this.returningFromConditional&&this.ifStack.length===0?this.programCounter=t.chunks.length:this.programCounter++,a(this,h,Mt).call(this)&&!a(this,h,re).call(this)&&this.stack.length+this.altStack.length>$h&&a(this,h,K).call(this,`Stack item count has exceeded ${$h}.`)},bf=function(){let t=r=>new Le(r.chunks.map(s=>({op:s.op,data:s.data===void 0?void 0:Array.from(s.data),invalidLength:s.invalidLength}))),e=r=>new Ue(r.chunks.map(s=>({op:s.op,data:s.data===void 0?void 0:Array.from(s.data),invalidLength:s.invalidLength}))),i=r=>({sourceTXID:r.sourceTXID??r.sourceTransaction?.id("hex"),sourceOutputIndex:r.sourceOutputIndex,unlockingScript:r.unlockingScript===void 0?void 0:e(r.unlockingScript),sequence:r.sequence});return new yf({sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,lockingScript:t(this.lockingScript),transactionVersion:this.transactionVersion,otherInputs:this.otherInputs.map(i),allInputs:this.allInputs?.map(i),outputs:this.outputs.map(r=>({satoshis:r.satoshis,lockingScript:t(r.lockingScript),change:r.change})),inputIndex:this.inputIndex,unlockingScript:e(this.unlockingScript),inputSequence:this.inputSequence,lockTime:this.lockTime,memoryLimit:this.hasExplicitMemoryLimit?this.memoryLimit:void 0,isRelaxed:this.isRelaxedOverride,verifyFlags:this.verifyFlags===void 0?void 0:Array.from(this.verifyFlags)})},Da=function(t){this.context=t,this.programCounter=0,this.ifStack=[],this.elseStack=[],this.returningFromConditional=!1,a(this,h,Ma).call(this),this.lastCodeSeparator=null;let e=t==="UnlockingScript"?this.unlockingScript:this.lockingScript;for(a(this,h,Mt).call(this)&&!a(this,h,re).call(this)&&e.toUint8Array().length>Dh&&a(this,h,K).call(this,`Script size exceeds ${Dh} bytes.`);this.programCounter<e.chunks.length;)this.step();this.ifStack.length>0&&a(this,h,K).call(this,"Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the script."),this.ifStack=[],this.elseStack=[],a(this,h,Ma).call(this),this.lastCodeSeparator=null},mp=function(t){let e=t.chunks;return e.length===3&&e[0].op===x.OP_HASH160&&e[1].op===20&&Array.isArray(e[1].data)&&e[1].data.length===20&&e[2].op===x.OP_EQUAL},mf=function(){this.stack.length===0?a(this,h,K).call(this,"The top stack element must be truthy after script evaluation (stack is empty)."):a(this,h,Xr).call(this,a(this,h,Kt).call(this))||a(this,h,K).call(this,"The top stack element must be truthy after script evaluation.")},Xr=function(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(t[e]!==0)return!(e===t.length-1&&t[e]===128);return!1},K=function(t){throw new po({message:t,txid:this.sourceTXID,outputIndex:this.sourceOutputIndex,context:this.context,programCounter:this.programCounter,stackState:this.stack,altStackState:this.altStack,ifStackState:this.ifStack,stackMem:this.stackMem,altStackMem:this.altStackMem})};var wo=yf;var Py=21e14,Ry=4294967295;function Ha(n,t){if(!Number.isSafeInteger(n)||n<0||n>Ry)throw new Error(`${t} must be an unsigned 32-bit integer`);return n}function wf(n,t){if(!Number.isSafeInteger(n)||n<0||n>Py)throw new Error(`${t} must be a valid number of satoshis`);return n}function xf(n,t){if(typeof n!="string"||!/^[0-9a-fA-F]{64}$/.test(n))throw new Error(`${t} must be a 32-byte hexadecimal transaction ID`);return n.toLowerCase()}function If(n,t){if(n==null||typeof n!="object"||typeof n.toHex!="function")throw new Error(`${t} must be a Script`);let e=n.toHex();if(typeof e!="string"||!/^(?:[0-9a-fA-F]{2})*$/.test(e))throw new Error(`${t} must serialize to a valid hexadecimal script`);return n}function yp(n,t){if(n!=="all"&&n!=="none"&&n!=="single")throw new Error('signOutputs must be "all", "none", or "single"');if(typeof t!="boolean")throw new TypeError("anyoneCanPay must be a boolean");let e=yt.SIGHASH_FORKID;return n==="all"&&(e|=yt.SIGHASH_ALL),n==="none"&&(e|=yt.SIGHASH_NONE),n==="single"&&(e|=yt.SIGHASH_SINGLE),t&&(e|=yt.SIGHASH_ANYONECANPAY),e}function wp(n,t,e,i){if(n==null||!Array.isArray(n.inputs))throw new Error("A transaction with inputs is required for transaction signing.");if(!Number.isSafeInteger(t)||t<0||t>=n.inputs.length)throw new Error(`inputIndex ${t} is outside the transaction input range`);let r=n.inputs[t],s=Ha(r.sourceOutputIndex,"input.sourceOutputIndex"),o=r.sourceTXID===void 0?void 0:xf(r.sourceTXID,"input.sourceTXID"),c=r.sourceTransaction===void 0?void 0:xf(r.sourceTransaction.id("hex"),"input.sourceTransaction ID");if(o!==void 0&&c!==void 0&&o!==c)throw new Error("The input sourceTXID does not match the input sourceTransaction.");let u=o??c;if(u===void 0)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");let f=r.sourceTransaction?.outputs[s];if(r.sourceTransaction!==void 0&&f==null)throw new Error(`The input sourceTransaction has no output at index ${s}.`);let d=e===void 0?void 0:wf(e,"sourceSatoshis"),l=f?.satoshis===void 0?void 0:wf(f.satoshis,"sourceTransaction output satoshis");if(d!==void 0&&l!==void 0&&d!==l)throw new Error("The sourceSatoshis does not match the input sourceTransaction output.");let p=d??l;if(p===void 0)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");let b=i===void 0?void 0:If(i,"lockingScript"),g=f?.lockingScript===void 0?void 0:If(f.lockingScript,"sourceTransaction output lockingScript");if(b!==void 0&&g!==void 0&&b.toHex().toLowerCase()!==g.toHex().toLowerCase())throw new Error("The lockingScript does not match the input sourceTransaction output.");let w=b??g;if(w===void 0)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");return{sourceTXID:u,sourceSatoshis:p,lockingScript:w,allInputs:n.inputs,get otherInputs(){return n.inputs.filter((S,C)=>C!==t)}}}function xp(n){let{tx:t,inputIndex:e,signatureScope:i,sourceTXID:r,sourceSatoshis:s,lockingScript:o,otherInputs:c,allInputs:u,inputSequence:f}=n,d=t.inputs[e];Ha(d.sourceOutputIndex,"input.sourceOutputIndex"),wf(s,"sourceSatoshis"),xf(r,"sourceTXID"),If(o,"lockingScript"),Ha(i,"signatureScope");let l=f??nr(d.sequence,"input.sequence must have value");return Ha(l,"inputSequence"),yt.format({sourceTXID:r,sourceOutputIndex:nr(d.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:s,transactionVersion:t.version,otherInputs:c??[],allInputs:u,inputIndex:e,outputs:t.outputs,inputSequence:l,subscript:o,lockTime:t.lockTime,scope:i,cache:t.getSignatureHashCache()})}var Gn=class{lock(t){let e;if(typeof t=="string"){let i=ao(t);if(i.prefix.length!==1||i.prefix[0]!==0&&i.prefix[0]!==111)throw new Error("only P2PKH is supported");e=i.data}else{if(!Array.isArray(t))throw new Error("P2PKH hash must be a dense byte array");for(let i=0;i<t.length;i++){let r=t[i];if(!Number.isInteger(r)||r<0||r>255)throw new Error("P2PKH hash must be a dense byte array")}e=t}if(e.length!==20)throw new Error("P2PKH hash length must be 20 bytes");return new Le([{op:x.OP_DUP},{op:x.OP_HASH160},{op:e.length,data:e},{op:x.OP_EQUALVERIFY},{op:x.OP_CHECKSIG}])}unlock(t,e="all",i=!1,r,s){return{sign:async(o,c)=>{let u=yp(e,i),f=wp(o,c,r,s),d=xp({tx:o,inputIndex:c,signatureScope:u,sourceTXID:f.sourceTXID,sourceSatoshis:f.sourceSatoshis,lockingScript:f.lockingScript,allInputs:f.allInputs}),l=Te(d),p=sf("signDigest"),b=sf("publicKeyFromPrivate"),g=p===void 0&&b===void 0?void 0:Uint8Array.from(t.toArray("be",32)),w=b===void 0?t.toPublicKey().encode(!0):void 0,S=p===void 0?t.sign(l):pe.fromDER(Array.from(rf("signDigest",await p.signDigest(g,Uint8Array.from(Te(l)))))),E=new yt(S.r,S.s,u).toChecksigFormat(),A=b===void 0?w:Array.from(Ny(await b.publicKeyFromPrivate(g)));return new Ue([{op:E.length,data:E},{op:A.length,data:A}])},estimateLength:async()=>108}}};function Ny(n){let t=rf("publicKeyFromPrivate",n,33);if(t[0]!==2&&t[0]!==3)throw new Error("publicKeyFromPrivate returned an invalid compressed public key");return t}var Io=class{constructor(t){m(this,"value");Ip(t),this.value=t}async computeFee(t){let e=this.value;Ip(e);let i=o=>o>4294967295?9:o>65535?5:o>=253?3:1,r=4;r+=i(t.inputs.length);for(let o=0;o<t.inputs.length;o++){let c=t.inputs[o];r+=40;let u;if(typeof c.unlockingScript=="object")u=c.unlockingScript.toBinary().length;else if(typeof c.unlockingScriptTemplate=="object")u=await c.unlockingScriptTemplate.estimateLength(t,o);else throw new TypeError("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");if(!Number.isSafeInteger(u)||u<0)throw new RangeError("Unlocking script length must be a non-negative safe integer.");r+=i(u),r+=u}r+=i(t.outputs.length);for(let o of t.outputs){r+=8;let c=o.lockingScript.toBinary().length;if(!Number.isSafeInteger(c)||c<0)throw new RangeError("Locking script length must be a non-negative safe integer.");r+=i(c),r+=c}r+=4;let s=Math.ceil(r/1e3*e);if(!Number.isSafeInteger(s)||s<0||s>21e14)throw new RangeError("Computed transaction fee is outside the valid satoshi range.");return s}};function Ip(n){if(!Number.isFinite(n)||n<0||n>21e14)throw new RangeError("Satoshis-per-kilobyte rate must be finite and non-negative.")}var $a=8*1024*1024,qa=3e4;function Sp(n={}){let t=n.maxResponseBytes??$a,e=n.timeoutMs??qa;if(!Number.isSafeInteger(t)||t<1)throw new RangeError("maxResponseBytes must be a positive safe integer");if(!Number.isSafeInteger(e)||e<1||e>10*6e4)throw new RangeError("timeoutMs must be an integer from 1 through 600000");return{maxResponseBytes:t,timeoutMs:e}}function vp(n,t){let e=new AbortController,i=()=>e.abort(n?.reason);n?.aborted===!0?i():n?.addEventListener("abort",i,{once:!0});let r=setTimeout(()=>e.abort(new DOMException("HTTP request timed out","TimeoutError")),t);return{signal:e.signal,dispose(){clearTimeout(r),n?.removeEventListener("abort",i)}}}async function Ap(n,t){let e=n,i=n.headers?.get?.("content-length")??null;if(i!==null&&(!/^(0|[1-9]\d*)$/.test(i)||Number(i)>t))throw await n.body?.cancel().catch(()=>{}),new Error("HTTP response exceeds the configured size limit");if(!("body"in e)){let f=await e.text?.()??"";if(Fe(f)>t)throw new Error("HTTP response exceeds the configured size limit");return f}if(n.body==null)return"";let r=n.body.getReader(),s=[],o=0;try{for(;;){let{done:f,value:d}=await r.read();if(f)break;if(o+=d.byteLength,!Number.isSafeInteger(o)||o>t)throw await r.cancel(),new Error("HTTP response exceeds the configured size limit");s.push(d)}}finally{r.releaseLock()}let c=new Uint8Array(o),u=0;for(let f of s)c.set(f,u),u+=f.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(c)}catch(f){throw new Error("HTTP response is not valid UTF-8",{cause:f})}}function Ep(n,t,e,i){return new Promise((r,s)=>{let o;try{o=e.data===null||e.data===void 0?void 0:i(e.data)}catch(S){s(S);return}let{data:c,...u}=e,f=!1,d,l,p=()=>{l!==void 0&&clearTimeout(l),e.signal?.removeEventListener("abort",w)},b=S=>{f||(f=!0,p(),s(S))},g=S=>{f||(f=!0,p(),r(S))},w=()=>{let S=e.signal?.reason instanceof Error?e.signal.reason:new DOMException("HTTP request aborted","AbortError");d?.destroy?.(S),b(S)};d=n.request(t,u,S=>{let C=S.headers?.["content-length"],E=typeof C=="string"?Number(C):void 0;if(typeof C=="string"&&!/^(0|[1-9]\d*)$/.test(C)||E!==void 0&&(!Number.isSafeInteger(E)||E>$a)){S.destroy?.(),b(new Error("HTTP response exceeds the configured size limit"));return}let A=[],k=0;S.on("data",B=>{if(f)return;let _=typeof B=="string"?xe(B):new Uint8Array(B);if(k+=_.byteLength,!Number.isSafeInteger(k)||k>$a){S.destroy?.(),d.destroy?.(),b(new Error("HTTP response exceeds the configured size limit"));return}A.push(_)}),S.on("end",()=>{if(!f)try{if(E!==void 0&&E!==k)throw new Error("HTTP response differs from its declared length");if(!Number.isInteger(S.statusCode)||S.statusCode<100||S.statusCode>599)throw new Error("HTTP response returned an invalid status code");let B=new Uint8Array(k),_=0;for(let M of A)B.set(M,_),_+=M.byteLength;let $=new TextDecoder("utf-8",{fatal:!0}).decode(B),R=S.statusCode>=200&&S.statusCode<=299,I=S.headers["content-type"],U=$!==""&&typeof I=="string"&&I.startsWith("application/json")?JSON.parse($):$;g({status:S.statusCode,statusText:S.statusMessage??"",ok:R,data:U})}catch(B){b(B)}}),S.on("error",b),S.on("aborted",()=>b(new Error("HTTP response was aborted")))}),d.on("error",b),f||(l=setTimeout(()=>{let S=new Error("HTTP request timed out");d.destroy?.(S),b(S)},qa)),d.setTimeout?.(qa,()=>{let S=new Error("HTTP request timed out");d.destroy?.(S),b(S)}),e.signal?.aborted===!0?w():e.signal?.addEventListener("abort",w,{once:!0}),!f&&(o!==void 0&&d.write(o),d.end())})}var Fa=class{constructor(t){m(this,"https");this.https=t}async request(t,e){return await Ep(this.https,t,e,i=>JSON.stringify(i))}};var So=class{constructor(t,e={}){m(this,"fetch");m(this,"limits");this.fetch=t,this.limits=Sp(e)}async request(t,e){let i=vp(e.signal,this.limits.timeoutMs),r={method:e.method,headers:e.headers,body:e.data===void 0?null:JSON.stringify(e.data),redirect:"error",signal:i.signal};try{let s=await this.fetch(t,r),o=s,c=o.headers?.get?.("Content-Type"),u;if(!("body"in o)&&typeof o.json=="function"&&(c==null||c.startsWith("application/json"))){if(u=await o.json(),Fe(JSON.stringify(u))>this.limits.maxResponseBytes)throw new Error("HTTP response exceeds the configured size limit")}else{let f=await Ap(s,this.limits.maxResponseBytes);u=f!==""&&(c?.startsWith("application/json")??!1)?JSON.parse(f):f}return{ok:s.ok,status:s.status,statusText:s.statusText,data:u}}finally{i.dispose()}}};function dr(){let n={async request(...e){throw new Error("No method available to perform HTTP request")}};if(globalThis.window!==void 0&&typeof globalThis.window.fetch=="function")return new So(globalThis.window.fetch.bind(globalThis.window));if(typeof globalThis.fetch=="function")return new So(globalThis.fetch.bind(globalThis));let t=typeof yu=="function"?yu:void 0;if(t===void 0)return n;try{let e=t(["node","https"].join(":"));return new Fa(e)}catch{return n}}var Pn=class Pn extends Io{constructor(e=300*1e3){super(100);m(this,"cachedRate",null);m(this,"cacheTimestamp",0);m(this,"cacheValidityMs");if(!Number.isSafeInteger(e)||e<0)throw new RangeError("cacheValidityMs must be a non-negative safe integer");this.cacheValidityMs=e}static getInstance(e=300*1e3){return Pn.instance??(Pn.instance=new Pn(e)),Pn.instance}async fetchFeeRate(){let e=Date.now();if(this.cachedRate!==null&&e-this.cacheTimestamp<this.cacheValidityMs)return this.cachedRate;try{let i=await dr().request(Pn.ARC_POLICY_URL,{method:"GET",headers:{Accept:"application/json"}});if(!i.ok)throw new Error("Fee-policy provider request failed");let r=i.data,s=r?.policy?.miningFee?.satoshis,o=r?.policy?.miningFee?.bytes;if(!Number.isSafeInteger(s)||s<1||s>21e14||!Number.isSafeInteger(o)||o<1||o>1e9)throw new Error("Invalid policy response format");let c=s/o*1e3;if(!Number.isFinite(c)||c<=0||c>1e9)throw new Error("Invalid policy fee rate");return this.cachedRate=c,this.cacheTimestamp=e,c}catch{return this.cachedRate!==null?(console.warn("Failed to fetch live fee rate; using cached value."),this.cachedRate):(console.warn("Failed to fetch live fee rate; using default 100 sat/kb."),100)}}async computeFee(e){let i=await this.fetchFeeRate();return this.value=i,super.computeFee(e)}};m(Pn,"ARC_POLICY_URL","https://arc.gorillapool.io/v1/policy"),m(Pn,"instance",null);var vo=Pn;function gn(n){return n==="__proto__"||n==="constructor"||n==="prototype"}function kp(n){if(n==null||typeof n!="object"||Array.isArray(n))return!1;let t=Object.getPrototypeOf(n);return t===Object.prototype||t===null}var Wa=/^[0-9a-f]{64}$/i,Tp=8192,By=128,_y=256;function vi(n,t){let e=Object.getOwnPropertyDescriptor(n,t);return e==null?{present:!1}:Object.prototype.hasOwnProperty.call(e,"value")?{present:!0,value:e.value}:{present:!0}}function Sf(n,t){return typeof n=="string"&&Fe(n)<=t}function lr(){return{status:"error",code:"ERR_INVALID_RESPONSE",description:"Broadcaster returned a malformed or transaction-mismatched response."}}function Op(n,t){if(!Wa.test(t)||!kp(n))return lr();let e=vi(n,"status").value;if(e==="success"){let u=vi(n,"txid").value,f=vi(n,"message").value,d=vi(n,"competingTxs");if(typeof u!="string"||!Wa.test(u)||u.toLowerCase()!==t.toLowerCase()||!Sf(f,Tp))return lr();let l={status:"success",txid:t.toLowerCase(),message:f};if(d.present){if(!Array.isArray(d.value)||d.value.length>_y)return lr();let p=[],b=new Set;for(let g=0;g<d.value.length;g++){let w=Object.getOwnPropertyDescriptor(d.value,g),S=w?.value;if(w==null||!Object.prototype.hasOwnProperty.call(w,"value")||typeof S!="string"||!Wa.test(S))return lr();let C=S.toLowerCase();if(b.has(C))return lr();b.add(C),p.push(C)}l.competingTxs=p}return l}if(e!=="error")return lr();let i=vi(n,"code").value,r=vi(n,"description").value,s=vi(n,"txid");if(!Sf(i,By)||!Sf(r,Tp)||s.present&&(typeof s.value!="string"||!Wa.test(s.value)||s.value.toLowerCase()!==t.toLowerCase()))return lr();let o={status:"error",code:i,description:r};s.present&&(o.txid=t.toLowerCase());let c=vi(n,"more");return c.present&&c.value!=null&&typeof c.value=="object"&&(o.more=c.value),o}function Pp(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("Invalid offset")}var bn=(n,t)=>Math.floor(n/2**t),Ao=n=>n%2===0?n+1:n-1,vf=(n,t,e)=>bn(n,e)===bn(t,e),Af=n=>n===0?0:n.toString(2).length;function mn(n,t){return nt(zt(at((n??"")+(t??""),"hex").reverse()).reverse())}function Cy(n,t,e,i){let r=i.get(n);if(r==null)return;if(r!==t)throw new Error("Mismatched roots");let s=i.get(`${e}:0`);if(s==null)throw new Error("Mismatched roots");return s}function Rp(n,t,e,i,r,s){if(t==null){if(s)return mn(n,n);throw new Error(`Missing hash for index ${i} at height ${r}`)}return t.duplicate===!0?mn(n,n):e%2===1?mn(t.hash,n):mn(n,t.hash)}var Ai=class n{constructor(t,e,i=!0,r=!0){m(this,"blockHeight");m(this,"path");if(!Array.isArray(e)||e.length===0||e.length>54)throw new Error("Merkle Path must contain between 1 and 54 levels");this.blockHeight=t,this.path=e.map((l,p)=>{if(!Array.isArray(l))throw new TypeError(`Merkle Path level ${p} must be an array`);return l.map(b=>({...b}))});let s=Array.from({length:this.path.length}).fill(0).map(()=>new Set);if(this.path.forEach((l,p)=>{if(l.length===0&&p===0)throw new Error(`Empty level at height: ${p}`);let b=new Set;l.forEach(g=>{if(Pp(g.offset),b.has(g.offset))throw new Error(`Duplicate offset: ${g.offset}, at height: ${p}`);if(b.add(g.offset),p===0){if(g.duplicate!==!0)for(let w=1;w<this.path.length;w++)s[w].add(Ao(bn(g.offset,w)))}else if(i&&!s[p].has(g.offset))throw new Error(`Invalid offset: ${g.offset}, at height: ${p}, with legal offsets: ${Array.from(s[p],w=>w.toString()).join(", ")}`)})}),!r)return;let o=this.path.map(l=>new Map(l.map(p=>[p.offset,p]))),c=new Map,u=new Map,f=this.path[0].reduce((l,p)=>Math.max(l,p.offset),0),d;this.path[0].forEach((l,p)=>{let b=this.computeRootCached(l.hash,o,c,u,f);if(p===0&&(d=b),d!==b)throw new Error("Mismatched roots")})}static fromHex(t){return n.fromBinary(at(t,"hex"))}static fromReader(t,e=!0,i=!0){let r=t.readVarIntNumStrict(!1),s=t.readUInt8(),o=Array.from({length:s}).fill(null).map(()=>[]),c,u,f;for(let d=0;d<s;d++){for(f=t.readVarIntNumStrict(!1);f>0;){u=t.readVarIntNumStrict(!1),c=t.readUInt8();let l={offset:u};(c&1)===1?l.duplicate=!0:((c&2)!==0&&(l.txid=!0),l.hash=nt(t.read(32).reverse())),(!Array.isArray(o[d])||o[d].length===0)&&(o[d]=[]),o[d].push(l),f--}o[d].sort((l,p)=>l.offset-p.offset)}return new n(r,o,e,i)}static fromBinary(t,e=!0,i=!0){let r=new mt(t);return n.fromReader(r,e,i)}static fromCoinbaseTxidAndHeight(t,e){return new n(e,[[{offset:0,hash:t,txid:!0}]])}toWriter(t){t.writeVarIntNum(this.blockHeight);let e=this.path.length;t.writeUInt8(e);for(let i=0;i<e;i++){let r=Object.keys(this.path[i]).length;t.writeVarIntNum(r);for(let s of this.path[i]){t.writeVarIntNum(s.offset);let o=0;s?.duplicate===!0&&(o|=1),s?.txid!==void 0&&s.txid!==null&&(o|=2),t.writeUInt8(o),(o&1)===0&&t.write(at(s.hash,"hex").reverse())}}}toBinary(){let t=new ue;return this.toWriter(t),t.toArray()}toBinaryUint8Array(){let t=new ht;return this.toWriter(t),t.toUint8Array()}toHex(){return nt(this.toBinaryUint8Array())}indexOf(t){let e=this.path[0].find(i=>i.hash===t);if(e==null)throw new Error(`Transaction ID ${t} not found in the Merkle Path`);return e.offset}computeRootCached(t,e,i,r,s){if(typeof t!="string"&&(t=this.path[0].find(f=>!!f.hash)?.hash),typeof t!="string")throw new TypeError("Transaction ID is undefined");let o=this.indexOf(t);if(this.path.length===1&&this.path[0].length===1)return t;let c=Math.max(this.path.length,Af(s)),u=t;for(let f=0;f<c;f++){let d=`${f}:${bn(o,f)}`,l=Cy(d,u,c,r);if(l!=null)return l;r.set(d,u);let p=Ao(bn(o,f)),b=this.cachedFindLeaf(f,p,e,i,s);u=Rp(u,b,p,o,f,this.path.length===1&&vf(o,s,f))}return r.set(`${c}:0`,u),u}computeRoot(t){if(typeof t!="string"){let o=this.path[0].find(c=>!!c?.hash);if(o==null)throw new Error("No valid leaf found in the Merkle Path");t=o.hash}if(typeof t!="string")throw new TypeError("Transaction ID is undefined");let e=this.indexOf(t),i=t;if(this.path.length===1&&this.path[0].length===1)return i;let r=this.path[0].reduce((o,c)=>Math.max(o,c.offset),0),s=Math.max(this.path.length,Af(r));for(let o=0;o<s;o++){let c=Ao(bn(e,o));i=Rp(i,this.findOrComputeLeaf(o,c),c,e,o,this.path.length===1&&vf(e,r,o))}return i}findOrComputeLeaf(t,e){Pp(e);let i=t<this.path.length?this.path[t].find(f=>f.offset===e):void 0;if(i!=null)return i;if(t===0)return;let r=t-1,s=e*2;if(!Number.isSafeInteger(s))return;let o=this.findOrComputeLeaf(r,s);if(o?.hash==null||o.hash==="")return;let c=this.findOrComputeLeaf(r,s+1);if(c?.hash==null){if(c?.duplicate===!0)return{offset:e,hash:mn(o.hash,o.hash)};if(this.path.length===1){let f=this.path[0].reduce((d,l)=>Math.max(d,l.offset),0);if(s===bn(f,r))return{offset:e,hash:mn(o.hash,o.hash)}}return}let u;return c.duplicate===!0?u=mn(o.hash,o.hash):u=mn(c.hash,o.hash),i={offset:e,hash:u},i}async verify(t,e){let i=this.blockHeight;if(!Number.isSafeInteger(i)||i<0)throw new Error("Merkle Path block height must be a non-negative safe integer");let r=e?.currentHeight,s=e?.isValidRootForHeight;if(typeof r!="function"||typeof s!="function")throw new TypeError("A valid ChainTracker is required");let o=this.computeRoot(t);if(this.indexOf(t)===0){let u=await r.call(e);if(!Number.isSafeInteger(u)||u<0)throw new Error("ChainTracker current height must be a non-negative safe integer");if(i+100>u)return!1}return await s.call(e,o,i)===!0}combine(t){if(this.blockHeight!==t.blockHeight)throw new Error("You cannot combine paths which do not have the same block height.");let e=this.computeRoot(),i=t.computeRoot();if(e!==i)throw new Error("You cannot combine paths which do not have the same root.");let r=[];for(let s=0;s<this.path.length;s++){r.push([]);for(let o of this.path[s])r[s].push({...o});for(let o of t.path[s]){let c=r[s].find(u=>u.offset===o.offset);c===void 0?r[s].push({...o}):o?.txid!==void 0&&o?.txid!==null&&(c.txid=!0)}}this.path=r,this.trim()}trim(){let t=(o,c)=>{(c.length===0||c.at(-1)!==o)&&c.push(o)},e=(o,c)=>{for(let u=o.length;u>=0;u--){let f=this.path[c].findIndex(d=>d.offset===o[u]);f>=0&&this.path[c].splice(f,1)}},i=o=>{let c=[];for(let u of o)t(bn(u,1),c);return c},r=[],s=[];for(let o of this.path)o.sort((c,u)=>c.offset-u.offset);for(let o=0;o<this.path[0].length;o++){let c=this.path[0][o];if(c.txid===!0)t(bn(c.offset,1),r);else{let u=c.offset%2===1,f=this.path[0][o+(u?-1:1)];(f.txid===void 0||f.txid===null||!f.txid)&&t(f.offset,s)}}e(s,0);for(let o=1;o<this.path.length;o++)s=r,r=i(r),e(s,o)}cachedFindLeaf(t,e,i,r,s){let o=`${t}:${e}`;if(r.has(o))return r.get(o);let c=t<i.length?i[t].get(e):void 0;if(c!=null)return r.set(o,c),c;if(t===0){r.set(o,void 0);return}let u=t-1,f=e*2;if(!Number.isSafeInteger(f))return;let d=this.cachedFindLeaf(u,f,i,r,s);if(d?.hash==null||d.hash===""){r.set(o,void 0);return}let l=this.cachedFindLeaf(u,f+1,i,r,s);if(l?.hash==null){if(l?.duplicate===!0||this.path.length===1&&f===bn(s,u))return c={offset:e,hash:mn(d.hash,d.hash)},r.set(o,c),c;r.set(o,void 0);return}let p=l.duplicate===!0?mn(d.hash,d.hash):mn(l.hash,d.hash);return c={offset:e,hash:p},r.set(o,c),c}extract(t){if(t.length===0)throw new Error("At least one txid must be provided to extract");let e=this.computeRoot(),i=this.path[0].reduce((l,p)=>Math.max(l,p.offset),0),r=Math.max(this.path.length,Af(i)),s=this.createSourceLeafIndex(),o=new Map,c=this.createTxidToOffsetIndex(),u=this.createNeededLeafLevels(r);for(let l of t)this.collectExtractedLeaves(l,c,u,s,o,i,r);let f=new n(this.blockHeight,this.buildExtractedPath(u));f.trim();let d=f.computeRoot();if(d!==e)throw new Error(`Extracted path root ${d} does not match original root ${e}`);return f}createSourceLeafIndex(){let t=Array.from({length:this.path.length});for(let e=0;e<this.path.length;e++){let i=new Map;for(let r of this.path[e])i.set(r.offset,r);t[e]=i}return t}createTxidToOffsetIndex(){let t=new Map;for(let e of this.path[0])e.hash!=null&&t.set(e.hash,e.offset);return t}createNeededLeafLevels(t){let e=Array.from({length:t});for(let i=0;i<t;i++)e[i]=new Map;return e}collectExtractedLeaves(t,e,i,r,s,o,c){let u=e.get(t);if(u===void 0)throw new Error(`Transaction ID ${t} not found in the Merkle Path`);i[0].set(u,{offset:u,txid:!0,hash:t});let f=Ao(u);if(!i[0].has(f)){let d=this.cachedFindLeaf(0,f,r,s,o);d!=null&&i[0].set(f,d)}for(let d=1;d<c;d++){let l=Ao(bn(u,d));if(i[d].has(l))continue;let p=this.cachedFindLeaf(d,l,r,s,o);p!=null?i[d].set(l,p):vf(u,o,d)&&i[d].set(l,{offset:l,duplicate:!0})}}buildExtractedPath(t){return t.map(e=>Array.from(e.values()).sort((i,r)=>i.offset-r.offset))}};var Ly=32,Uy=64;function Np(n,t,e){if(n==null||typeof n!="object"||Array.isArray(n))throw new TypeError(`${t} must be an accessor-free plain data object.`);let i=Object.getPrototypeOf(n),r=Object.getOwnPropertyDescriptors(n);if(i!==Object.prototype&&i!==null||Object.getOwnPropertySymbols(n).length!==0||Object.keys(r).length>e||Object.values(r).some(s=>s.get!=null||s.set!=null))throw new TypeError(`${t} must be an accessor-free plain data object.`);return r}function jr(n,t,e){if(n!==void 0){if(typeof n!="string"||Fe(n)>e||Xi(n))throw new TypeError(`${t} must be bounded text without control characters.`);return n}}function My(n){if(n===void 0)return;let t=Np(n,"ARC headers",Uy),e=Object.create(null);for(let[i,r]of Object.entries(t)){if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/.test(i))throw new TypeError(`ARC header name is invalid: ${i}`);let s=jr(r.value,`ARC header ${i}`,8192);if(s===void 0)throw new TypeError(`ARC header ${i} must be a string.`);e[i]=s}return Object.freeze(e)}function Dy(n){let t=n??dr();if(t==null||typeof t!="object"||typeof t.request!="function")throw new TypeError("ARC httpClient must provide request().");return t}function Bp(n,t){if(typeof n=="string")return Object.freeze({apiKey:jr(n,"ARC API key",16*1024),httpClient:dr(),deploymentId:t()});let e=Np(n??{},"ARC config",Ly),i=r=>e[r]?.value;return Object.freeze({apiKey:jr(i("apiKey"),"ARC API key",16*1024),httpClient:Dy(i("httpClient")),deploymentId:jr(i("deploymentId"),"ARC deployment ID",256)??t(),callbackUrl:jr(i("callbackUrl"),"ARC callback URL",2048),callbackToken:jr(i("callbackToken"),"ARC callback token",16*1024),headers:My(i("headers"))})}function _p(n){if(typeof n!="string"||n.length===0||Fe(n)>2048||Xi(n))throw new TypeError("ARC URL must be nonempty bounded text without control characters.");return n}function Va(n,t){for(let e of t){if(!Object.prototype.hasOwnProperty.call(n,e))throw new Error(`Cannot lock missing configuration property ${e}.`);Object.defineProperty(n,e,{configurable:!1,writable:!1})}}function Hy(){return`ts-sdk-${nt(Pe(16))}`}var $y=new Set(["DOUBLE_SPEND_ATTEMPTED","REJECTED","INVALID","MALFORMED","MINED_IN_STALE_BLOCK"]),Gr=/^[0-9a-f]{64}$/i,Dp=128,Hp=8192,qy=256,Fy=32,Wy=new Set(["SUCCESS","RECEIVED","SENT_TO_NETWORK","ANNOUNCED_TO_NETWORK","ACCEPTED_BY_NETWORK","SEEN_ON_NETWORK","STORED","MINED","IMMUTABLE"]);function Ka(n,t,e=!0){return typeof n=="string"&&(e||n.length!==0)&&Fe(n)<=t&&!Xi(n)}function kf(n){if(n==null||typeof n!="object"||Array.isArray(n))return;let t=Object.getPrototypeOf(n);if(t!==Object.prototype&&t!==null)return;let e=Object.getOwnPropertyDescriptors(n);if(!(Object.getOwnPropertySymbols(n).length!==0||Object.keys(e).length>Fy||Object.values(e).some(i=>i.get!=null||i.set!=null)))return e}function Vy(n){if(n===void 0||!Array.isArray(n)||n.length>qy)return;let t=Object.getOwnPropertyDescriptors(n),e=new Set(["length",...Array.from({length:n.length},(s,o)=>String(o))]);if(Object.getOwnPropertySymbols(n).length!==0||Object.keys(t).length!==e.size||Object.keys(t).some(s=>!e.has(s))||Object.values(t).some(s=>s.get!=null||s.set!=null))return;let i=[],r=new Set;for(let s=0;s<n.length;s++){let o=t[s]?.value;if(typeof o!="string"||!Gr.test(o))return;let c=o.toLowerCase();if(r.has(c))return;r.add(c),i.push(c)}return i}function Cp(n){try{return n.toHexEF()}catch(t){if(t.message==="All inputs must have source transactions when serializing to EF format")return n.toHex();throw t}}function hr(n){return{status:"error",code:"ERR_INVALID_RESPONSE",description:n}}function Lp(n,t){let e=kf(n);if(e===void 0)return hr("ARC returned a malformed response.");let i=p=>e[p]?.value,r=i("txid"),s=i("extraInfo"),o=i("txStatus"),c=i("competingTxs");if(!Ka(o,Dp,!1)||s!==void 0&&!Ka(s,Hp))return hr("ARC returned invalid transaction status metadata.");let u=Vy(c);if(c!==void 0&&u===void 0)return hr("ARC returned invalid competing transaction identifiers.");let f=o.toUpperCase(),d=s?.toUpperCase().includes("ORPHAN")||f.includes("ORPHAN");if($y.has(f)||d){if(typeof r=="string"&&Gr.test(r)&&r.toLowerCase()!==t.toLowerCase())return{status:"error",code:"ERR_TXID_MISMATCH",description:"ARC returned a failure for another transaction."};let p={status:"error",code:o,description:`${o} ${s??""}`.trim()};return typeof r=="string"&&Gr.test(r)&&(p.txid=t.toLowerCase()),u!=null&&(p.more={competingTxs:u}),p}if(!Wy.has(f))return hr("ARC returned an unknown transaction status.");if(typeof r!="string"||!Gr.test(r)||r.toLowerCase()!==t.toLowerCase())return{status:"error",code:"ERR_TXID_MISMATCH",description:"ARC acknowledged a transaction other than the submitted transaction."};let l={status:"success",txid:t,message:`${o} ${s??""}`.trim()};return u!=null&&(l.competingTxs=u),l}function Ky(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch{return n}}function Up(n,t,e){let r={status:"error",code:typeof n=="number"&&Number.isSafeInteger(n)||typeof n=="string"&&Ka(n,Dp,!1)?n.toString():"ERR_UNKNOWN",description:"Unknown error"},s=Ky(t),o=kf(s);if(o===void 0)return r;let c=o.detail?.value,u=o.txid?.value;if(typeof u=="string"&&Gr.test(u)){if(e!==void 0&&u.toLowerCase()!==e.toLowerCase())return{status:"error",code:"ERR_TXID_MISMATCH",description:"ARC returned a failure for another transaction."};r.txid=u.toLowerCase()}let f={};return Ka(c,Hp)&&(r.description=c,f.detail=c),r.txid!==void 0&&(f.txid=r.txid),Object.keys(f).length!==0&&(r.more=f),r}function Mp(){return{status:"error",code:"500",description:"Internal Server Error"}}var Yr,ko,Ef,Eo=class{constructor(t,e){G(this,ko);m(this,"URL");m(this,"apiKey");m(this,"deploymentId");m(this,"callbackUrl");m(this,"callbackToken");m(this,"headers");G(this,Yr);this.URL=_p(t);let i=Bp(e,Hy);this.apiKey=i.apiKey,N(this,Yr,i.httpClient),this.deploymentId=i.deploymentId,this.callbackToken=i.callbackToken,this.callbackUrl=i.callbackUrl,this.headers=i.headers,Va(this,["URL","apiKey","deploymentId","callbackUrl","callbackToken","headers"])}async broadcast(t){let e={method:"POST",headers:a(this,ko,Ef).call(this),data:{rawTx:Cp(t)}};try{let i=await y(this,Yr).request(`${this.URL}/v1/tx`,e);return i.ok?Lp(i.data,t.id("hex")):Up(i.status,i.data,t.id("hex"))}catch{return Mp()}}async broadcastMany(t){let e=t.map(r=>({rawTx:Cp(r)})),i={method:"POST",headers:a(this,ko,Ef).call(this),data:e};try{let r=await y(this,Yr).request(`${this.URL}/v1/txs`,i);if(!r.ok)return t.map(u=>Up(r.status,r.data,u.id("hex")));if(!Array.isArray(r.data)||r.data.length!==t.length)return t.map(()=>hr("ARC returned a malformed batch response."));let s=Object.getOwnPropertyDescriptors(r.data),o=new Set(["length",...Array.from({length:r.data.length},(u,f)=>String(f))]);if(Object.getOwnPropertySymbols(r.data).length!==0||Object.keys(s).length!==o.size||Object.keys(s).some(u=>!o.has(u))||Object.values(s).some(u=>u.get!=null||u.set!=null))return t.map(()=>hr("ARC returned a malformed batch response."));let c=new Map;for(let u of t){let f=u.id("hex").toLowerCase();c.set(f,(c.get(f)??0)+1)}return Array.from({length:r.data.length},(u,f)=>{let d=s[f]?.value,l=kf(d);if(l===void 0)return hr("ARC returned a malformed batch result.");let p=l.txid?.value,b=typeof p=="string"&&Gr.test(p)?p.toLowerCase():"",g=c.get(b)??0;return g<1?{status:"error",code:"ERR_TXID_MISMATCH",description:"ARC batch acknowledged a transaction that was not submitted."}:(g===1?c.delete(b):c.set(b,g-1),Lp(d,b))})}catch{let r=Mp();return t.map(()=>r)}}};Yr=new WeakMap,ko=new WeakSet,Ef=function(){let t={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(this.apiKey!=null&&this.apiKey!==""&&(t.Authorization=`Bearer ${this.apiKey}`),this.callbackUrl!=null&&this.callbackUrl!==""&&(t["X-CallbackUrl"]=this.callbackUrl),this.callbackToken!=null&&this.callbackToken!==""&&(t["X-CallbackToken"]=this.callbackToken),this.headers!=null)for(let[e,i]of Object.entries(this.headers))t[e]=i;return t};function $p(n=!1,t={}){return new Eo(n?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",t)}var qp=/^[0-9a-f]{64}$/i,Fp=2147483647,zy=256,Wp=64;function Xy(n,t,e){if(typeof n!="string"||Fe(n)>e||Xi(n))throw new TypeError(`${t} must be bounded text without control characters.`);return n}function Tf(n,t,e){if(n==null||typeof n!="object"||Array.isArray(n))throw new TypeError(`${t} must be an accessor-free plain data object.`);let i=Object.getPrototypeOf(n),r=Object.getOwnPropertyDescriptors(n);if(i!==Object.prototype&&i!==null||Object.getOwnPropertySymbols(n).length!==0||Object.keys(r).length>e||Object.values(r).some(s=>s.get!=null||s.set!=null))throw new TypeError(`${t} must be an accessor-free plain data object.`);return r}function jy(n){if(n!=="main"&&n!=="test"&&n!=="stn")throw new TypeError("What's On Chain network must be 'main', 'test', or 'stn'.");return n}function Gy(n){let t=n??dr();if(t==null||typeof t!="object"||typeof t.request!="function")throw new TypeError("What's On Chain httpClient must provide request().");return t}function Yy(n){let t=Tf(n,"What's On Chain config",8);return{apiKey:t.apiKey?.value===void 0?"":Xy(t.apiKey.value,"What's On Chain API key",16*1024),httpClient:Gy(t.httpClient?.value)}}function Zy(n,t){if(typeof n!="string"||!qp.test(n))throw new TypeError("Merkle root must be a 64-character hexadecimal string.");if(!Number.isSafeInteger(t)||t<0||t>Fp)throw new TypeError("Block height must be a nonnegative bounded integer.");return{root:n.toLowerCase(),height:t}}function Jy(n){try{let e=Tf(n,"What's On Chain block header",Wp).merkleroot?.value;return typeof e=="string"&&qp.test(e)?e.toLowerCase():void 0}catch{return}}function Qy(n){if(!Array.isArray(n)||n.length===0||n.length>zy)return;let t=Object.getOwnPropertyDescriptors(n),e=new Set(["length",...Array.from({length:n.length},(i,r)=>String(r))]);if(!(Object.getOwnPropertySymbols(n).length!==0||Object.keys(t).length!==e.size||Object.keys(t).some(i=>!e.has(i))||Object.values(t).some(i=>i.get!=null||i.set!=null)))try{let r=Tf(t[0]?.value,"What's On Chain height response",Wp).height?.value;return Number.isSafeInteger(r)&&r>=0&&r<=Fp?r:void 0}catch{return}}var To=class{constructor(t="main",e={}){m(this,"network");m(this,"apiKey");m(this,"URL");m(this,"httpClient");this.network=jy(t),this.URL=`https://api.whatsonchain.com/v1/bsv/${this.network}`;let i=Yy(e);this.httpClient=i.httpClient,this.apiKey=i.apiKey,Va(this,["network","URL","httpClient","apiKey"])}async isValidRootForHeight(t,e){let i=Zy(t,e),r={method:"GET",headers:this.getHttpHeaders()};try{let s=await this.httpClient.request(`${this.URL}/block/${i.height}/header`,r);if(s.ok)return Jy(s.data)===i.root;if(s.status===404)return!1;throw new Error("provider request failed")}catch{throw new Error(`Failed to verify merkleroot for height ${i.height}.`)}}async currentHeight(){try{let t={method:"GET",headers:this.getHttpHeaders()},e=await this.httpClient.request(`${this.URL}/block/headers`,t);if(e.ok){let i=Qy(e.data);if(i!==void 0)return i}throw new Error("provider response was invalid")}catch{throw new Error("Failed to get current height from What's On Chain.")}}getHttpHeaders(){let t={Accept:"application/json"};return typeof this.apiKey=="string"&&this.apiKey.trim()!==""&&(t.Authorization=this.apiKey),t}};function Vp(){return new To}var ze;(function(n){n[n.RAWTX=0]="RAWTX",n[n.RAWTX_AND_BUMP_INDEX=1]="RAWTX_AND_BUMP_INDEX",n[n.TXID_ONLY=2]="TXID_ONLY"})(ze||(ze={}));function Zr(n,t){if(!Number.isSafeInteger(t)||t<0||n.pos+t>n.bin.length)throw new RangeError("Serialized transaction exceeds available BEEF data");n instanceof mt?n.skip(t):n.read(t)}function Of(n){let t=n.pos;Zr(n,4);let e=n.readVarIntNumStrict(!1),i=new Set;for(let o=0;o<e;o++){i.add(nt(n.readReverse(32))),Zr(n,4);let c=n.readVarIntNumStrict(!1);Zr(n,c+4)}let r=n.readVarIntNumStrict(!1);for(let o=0;o<r;o++){Zr(n,8);let c=n.readVarIntNumStrict(!1);Zr(n,c)}return Zr(n,4),{rawTx:n instanceof mt?n.bin.subarray(t,n.pos):Uint8Array.from(n.bin.slice(t,n.pos)),inputTxids:Array.from(i)}}function tw(n){return Of(new mt(n)).inputTxids}function ew(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}var Xe=class n{constructor(t,e,i,r=!1){m(this,"_bumpIndex");m(this,"_tx");m(this,"_rawTx");m(this,"_txid");m(this,"inputTxids",[]);m(this,"isValid");if(typeof t=="string")this._txid=t;else if(t instanceof Uint8Array)this._rawTx=r?t:Uint8Array.from(t);else if(Array.isArray(t))this._rawTx=new Uint8Array(t);else if(t instanceof Me)this._tx=t;else throw new TypeError("Invalid transaction data type");this._bumpIndex=e,this.hasProof?this.inputTxids=[]:i!=null?this.inputTxids=Array.from(i):this.updateInputTxids()}get bumpIndex(){return this._bumpIndex}set bumpIndex(t){this._bumpIndex=t,this.updateInputTxids()}get hasProof(){return this._bumpIndex!==void 0}get isTxidOnly(){return this._txid!==void 0&&this._txid!==null&&this._rawTx==null&&this._tx==null}get txid(){if(this._txid!==void 0&&this._txid!==null&&this._txid!=="")return this._txid;if(this._tx!=null)return this._txid=this._tx.id("hex"),this._txid;if(this._rawTx!=null)return this._txid=nt(zt(this._rawTx).reverse()),this._txid;throw new Error("Internal")}get tx(){if(this._tx!=null)return this._tx;if(this._rawTx!=null)return this._tx=Me.fromBinaryView(this._rawTx),this._txid!=null&&zp(this._tx,this._txid),this._tx}get rawTx(){let t=this.rawTxUint8Array;return t==null?void 0:Array.from(t)}get rawTxUint8Array(){let t=this.getRawTxBytes();return t==null?void 0:Uint8Array.from(t)}getRawTxBytes(){return this._tx!=null?(this._rawTx==null?this._rawTx=this._tx.toUint8Array():this.syncRawTxFromTransaction(),this._rawTx):this._rawTx}syncRawTxFromTransaction(){if(this._tx==null)return!1;let t=Kp(this._tx);if(this._rawTx!=null)return t===this._rawTx?!1:(this._rawTx=t,this._txid=this._tx.id("hex"),this.updateInputTxids(),!0);let e=this._tx.id("hex"),i=this._txid!=null&&this._txid!==e,r=this.inputTxids;return this._txid=e,this.updateInputTxids(),i||!ew(r,this.inputTxids)}static fromTx(t,e){return new n(t,e)}static fromRawTx(t,e){return new n(t,e)}static fromTxid(t,e){return new n(t,e)}updateInputTxids(){if(this.hasProof)this.inputTxids=[];else if(this._tx!=null){let t=new Set;for(let e of this._tx.inputs)e.sourceTXID!==void 0&&e.sourceTXID!==null&&e.sourceTXID!==""&&t.add(e.sourceTXID);this.inputTxids=Array.from(t)}else this._rawTx!=null?this.inputTxids=tw(this._rawTx):this.inputTxids=[]}toWriter(t,e){let i=c=>{t.writeUInt8(c)},r=()=>{if(this._txid==null)throw new Error("Transaction ID (_txid) is undefined");t.writeReverse(at(this._txid,"hex"))},s=()=>{let c=this.getRawTxBytes();if(c==null)throw new Error("a valid serialized Transaction is expected");t.write(c)},o=()=>{this.bumpIndex===void 0?i(ze.RAWTX):(i(ze.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex))};e===4022206466?this.isTxidOnly?(i(ze.TXID_ONLY),r()):this.bumpIndex!==void 0?(i(ze.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex),s()):(i(ze.RAWTX),s()):(s(),o())}static fromReader(t,e){let i,r;if(e===4022206466){let s=t.readUInt8();if(s===ze.TXID_ONLY)r=n.fromTxid(nt(t.readReverse(32)));else{s===ze.RAWTX_AND_BUMP_INDEX&&(i=t.readVarIntNumStrict(!1));let{rawTx:o,inputTxids:c}=Of(t);r=new n(o,i,c,!0)}}else{let{rawTx:s,inputTxids:o}=Of(t);i=t.readUInt8()===0?void 0:t.readVarIntNumStrict(!1),r=new n(s,i,o,!0)}return r}};function nw(n,t,e,i){if(t.path.length!==e)throw new Error("Mismatched roots");for(let r=0;r<e;r++)iw(n[r],t.path[r],i)}function iw(n,t,e){for(let i of t){let r=n.get(i.offset);if(r==null){n.set(i.offset,i);continue}rw(r,i,e)}}function rw(n,t,e){if(e&&(n.hash!==t.hash||n.duplicate!==t.duplicate))throw new Error("Mismatched roots");t.txid!=null&&(n.txid=!0)}function Xp(n,t,e){for(let i of n.path[0])typeof i.hash=="string"&&e.set(i.hash,t)}var Bn,_n,Cn,Zn,je,Jn,gr,es,br,ns,is,rs,mr,yr,Ln,De,Un,O,Jr,za,Rf,Nf,Xa,jp,Gp,Yp,Zp,Rn,Jp,Nn,Qp,t0,Oo,e0,Bf,_f,Cf,n0,Po,Ro,ja,pr,Qr,Lf,Ga,i0,Uf,r0,s0,o0,No,a0,c0,Ya,u0,f0,Mf,d0,l0,h0,p0,g0,b0,m0,ts,Df,y0,Za,w0,x0,I0,S0,v0,A0,E0,k0,yn=class yn{constructor(t=4022206466){G(this,O);m(this,"bumps",[]);m(this,"txs",[]);m(this,"version",4022206466);m(this,"atomicTxid");G(this,Bn);G(this,_n);G(this,Cn);G(this,Zn);G(this,je);G(this,Jn);G(this,gr,new Map);G(this,es);G(this,br);G(this,ns);G(this,is);G(this,rs);G(this,mr);G(this,yr);G(this,Ln,!0);G(this,De);G(this,Un);this.version=t}synchronizeNestedTransactionMutations(){let t=!1;for(let e of this.txs)t=e.syncRawTxFromTransaction()||t;t&&(a(this,O,Jr).call(this),N(this,De,void 0),N(this,Un,void 0),N(this,Ln,!0),a(this,O,pr).call(this))}isAtomic(t=this.atomicTxid??""){if(this.synchronizeNestedTransactionMutations(),a(this,O,Rn).call(this),t.length===0)return!1;let e=a(this,O,Ro).call(this);if(e.size!==this.txs.length)return!1;let i=e.get(t);return i==null?!1:a(this,O,_f).call(this,i,e).size===this.txs.length}findTxid(t){return this.synchronizeNestedTransactionMutations(),a(this,O,Po).call(this,t)}makeTxidOnly(t){let e=a(this,O,ja).call(this).get(t);if(e===void 0)return;let i=this.txs[e];return i.isTxidOnly||(i=Xe.fromTxid(t),this.txs[e]=i,a(this,O,Qr).call(this,i,e),a(this,O,ts).call(this,i),a(this,O,Nn).call(this,!0)),i}findBump(t){a(this,O,Rn).call(this);let e=a(this,O,Ga).call(this).get(t);return e===void 0?void 0:this.bumps[e]}findTransactionForSigning(t){let e=this.findTxid(t);if(e?.tx!=null){for(let i of e.tx.inputs)if(i.sourceTransaction==null){let r=a(this,O,Po).call(this,nr(i.sourceTXID,"sourceTXID must be valid"));r!=null&&(i.sourceTransaction=r.tx)}return e.tx}}findAtomicTransaction(t){let e=this.findTxid(t);if(e?.tx!=null)return a(this,O,r0).call(this,e.tx),e.tx}mergeBump(t){return this.synchronizeNestedTransactionMutations(),a(this,O,Rn).call(this),a(this,O,Nn).call(this,!1),a(this,O,No).call(this,t)}mergeProvenTxs(t){if(t.length===0)return[];this.synchronizeNestedTransactionMutations(),a(this,O,Rn).call(this),a(this,O,Nn).call(this,!0);let e=[];for(let s of t)e.push(a(this,O,Ya).call(this,s.rawTx));let i=new Map;for(let s of t){let o=s.merklePath.blockHeight;i.set(o,(i.get(o)??0)+1)}let r=new Map;for(let s=0;s<t.length;s++){let o=t[s].merklePath,c=t[s].merkleRoot,u=i.get(o.blockHeight)===1?`${o.blockHeight}:single:${s}`:`${o.blockHeight}:${c??o.computeRoot()}`,f=r.get(u);f==null?r.set(u,{first:s,paths:[o],validateCombined:c!=null}):(f.paths.push(o),f.validateCombined=f.validateCombined||c!=null)}for(let s of[...r.values()].sort((o,c)=>o.first-c.first))a(this,O,No).call(this,a(this,O,o0).call(this,s.paths,s.validateCombined));return e}mergeRawTx(t,e){return this.synchronizeNestedTransactionMutations(),a(this,O,Nn).call(this,!0),a(this,O,Ya).call(this,t,e)}mergeTransaction(t){return this.synchronizeNestedTransactionMutations(),a(this,O,Nn).call(this,!0),a(this,O,Mf).call(this,t)}removeExistingTxid(t){let e=a(this,O,ja).call(this).get(t);e!==void 0&&(this.txs.splice(e,1),a(this,O,pr).call(this),a(this,O,Nn).call(this,!0))}mergeTxidOnly(t){let e=this.findTxid(t);return e==null&&(e=new Xe(t),this.txs.push(e),a(this,O,Qr).call(this,e),a(this,O,ts).call(this,e),a(this,O,Nn).call(this,!0)),e}mergeBeefTx(t){let e=this.findTxid(t.txid);if(t.isTxidOnly&&e==null?e=this.mergeTxidOnly(t.txid):t._tx!=null&&(e==null||e.isTxidOnly)?e=this.mergeTransaction(t._tx):t._rawTx!=null&&(e==null||e.isTxidOnly)&&(e=this.mergeRawTx(t._rawTx)),e==null)throw new Error(`Failed to merge BeefTx for txid: ${t.txid}`);return e}mergeBeef(t){let e=yn.fromBinaryStrict(t instanceof yn?t.toBinary():t);this.synchronizeNestedTransactionMutations(),a(this,O,Rn).call(this),a(this,O,Nn).call(this,!0);for(let i of e.bumps)a(this,O,No).call(this,i);for(let i of e.txs)a(this,O,d0).call(this,i)}isValid(t){return this.verifyValid(t).valid}async verify(t,e){let i=this.verifyValid(e);if(!i.valid)return!1;for(let r of Object.keys(i.roots))if(await t.isValidRootForHeight(i.roots[r],Number(r))!==!0)return!1;return!0}verifyValid(t){a(this,O,Rn).call(this);let e={valid:!1,roots:{}};if(this.atomicTxid!=null&&!this.isAtomic(this.atomicTxid))return e;let i=this.sortTxs();if(a(this,O,l0).call(this)||i.missingInputs.length>0||i.notValid.length>0||i.txidOnly.length>0&&t!==!0||i.withMissingInputs.length>0)return e;let r={};return!a(this,O,h0).call(this,r,t)||!a(this,O,p0).call(this,r,e)||!a(this,O,g0).call(this)||!a(this,O,b0).call(this,r)||(e.valid=!0),e}toWriter(t){t.writeUInt32LE(this.version),t.writeVarIntNum(this.bumps.length);for(let e of this.bumps)t.write(t instanceof ht?e.toBinaryUint8Array():e.toBinary());t.writeVarIntNum(this.txs.length);for(let e of this.txs)e.toWriter(t,this.version)}toBinary(){return Array.from(a(this,O,Oo).call(this))}toUint8Array(){return new Uint8Array(a(this,O,Oo).call(this))}toBinaryAtomic(t){return Array.from(a(this,O,Bf).call(this,t))}toUint8ArrayAtomic(t){return new Uint8Array(a(this,O,Bf).call(this,t))}toHex(){let t=a(this,O,Oo).call(this);if(y(this,Jn)!=null)return y(this,Jn);let e=nt(t);return N(this,Jn,e),e}static fromReader(t){var f;let e=t.pos,i=t.readUInt32LE(),r,s=e;if(i===16843009&&(r=nt(t.readReverse(32)),s=t.pos,i=t.readUInt32LE()),i!==4022206465&&i!==4022206466)throw new Error(`Serialized BEEF must start with ${4022206465} or ${4022206466} but starts with ${i}`);let o=new yn(i),c=t.readVarIntNumStrict(!1);for(let d=0;d<c;d++){let l=Ai.fromReader(t,!1);o.bumps.push(l)}let u=t.readVarIntNumStrict(!1);for(let d=0;d<u;d++){let l=Xe.fromReader(t,i);o.txs.push(l)}return o.atomicTxid=r,t instanceof mt&&(N(o,je,t.bin.subarray(s,t.pos)),a(f=o,O,za).call(f)),o}static fromBinary(t){return yn.fromReader(new mt(Uint8Array.from(t)))}static fromBinaryStrict(t){return yn.fromBinaryView(Uint8Array.from(t))}static fromBinaryView(t){let e=new mt(t),i=yn.fromReader(e);if(!e.eof())throw new Error("Serialized BEEF contains trailing data");return i}static fromString(t,e="hex"){let i=et(t,e);return yn.fromBinaryStrict(i)}sortTxs(){if(this.synchronizeNestedTransactionMutations(),a(this,O,Rn).call(this),y(this,De)!=null&&a(this,O,y0).call(this))return a(this,O,Za).call(this,y(this,De));N(this,De,void 0),N(this,Un,void 0);let t={},e={},i=[],r=[],s=this.partitionTxs(e,t,i,r),{txsMissingInputs:o,missingInputs:c,remaining:u}=a(this,O,w0).call(this,s,e);s=u;let f=a(this,O,x0).call(this,s,t,i);this.txs=o.concat(f).concat(r).concat(i),N(this,Ln,!1),a(this,O,Jr).call(this),a(this,O,pr).call(this);let d={missingInputs:Object.keys(c),notValid:f.map(l=>l.txid),valid:Object.keys(t),withMissingInputs:o.map(l=>l.txid),txidOnly:r.map(l=>l.txid)};return N(this,De,d),a(this,O,Df).call(this),a(this,O,Za).call(this,d)}partitionTxs(t,e,i,r){let s=[];for(let o of this.txs)t[o.txid]=o,o.isValid=o.hasProof,o.isValid?(e[o.txid]=!0,i.push(o)):o.isTxidOnly&&o.inputTxids.length===0?(e[o.txid]=!0,r.push(o)):s.push(o);return s}clone(){var e,i;let t=new yn;return t.version=this.version,t.bumps=Array.from(this.bumps),t.txs=Array.from(this.txs),N(t,Bn,void 0),N(t,_n,void 0),N(t,Cn,void 0),N(t,Zn,void 0),N(t,Ln,y(this,Ln)),N(t,De,y(this,De)==null?void 0:a(this,O,Za).call(this,y(this,De))),y(t,De)!=null&&a(e=t,O,Df).call(e),N(t,Jn,y(this,Jn)),N(t,je,y(this,je)),y(t,je)!=null&&a(i=t,O,za).call(i),t}trimKnownTxids(t){let e=a(this,O,A0).call(this,new Set(t));e=a(this,O,E0).call(this)||e,e&&a(this,O,Nn).call(this,!0)}getValidTxids(){return this.sortTxs().valid}toLogString(){let t="";t+=`BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}
|
|
8
|
+
${u}`;super(f);b(this,"txid");b(this,"outputIndex");b(this,"context");b(this,"programCounter");b(this,"stackState");b(this,"altStackState");b(this,"ifStackState");b(this,"stackMem");b(this,"altStackMem");this.name=this.constructor.name,this.txid=e.txid,this.outputIndex=e.outputIndex,this.context=e.context,this.programCounter=e.programCounter,this.stackState=e.stackState.map(d=>d.slice()),this.altStackState=e.altStackState.map(d=>d.slice()),this.ifStackState=e.ifStackState.slice(),this.stackMem=e.stackMem,this.altStackMem=e.altStackMem}};var Xn=class extends Error{constructor(e,i,r){let o={stack:"Stack memory usage","alt-stack":"Alt stack memory usage","element-size":"Script element allocation"}[e];super(`${o} has exceeded ${i} bytes`);b(this,"resource");b(this,"limit");b(this,"attempted");this.resource=e,this.limit=i,this.attempted=r,this.name="ScriptResourceLimitError"}};var Ew;function Da(){return Ew}var kw=520,Kh=1e4,zh=500,Tw=0x7fffffffn,Ow=75e4,Pw=32e6,Xh=1e3,Rw=Math.pow(2,31)-1,Nw=BigInt(Rw),Bw=20,jh=2147483648,uf=4194304,_w=65535,Gh=5e8,Cw=Object.freeze(new T(-1).toScriptNum()),Yh=Object.freeze(Array.from({length:17},(n,t)=>Object.freeze(new T(t).toScriptNum())));function Zh(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}function vi(n){return new T(n?1:0)}function Lw(n,t){return vi(n&&t)}function Uw(n,t){return vi(n||t)}function Mw(n,t){return n.cmp(t)<0?n:t}function Dw(n,t){return n.cmp(t)>0?n:t}function Jh(n){if(typeof n.consensus!="boolean")throw new TypeError("Spend verification consensus must be boolean");for(let[e,i]of[["blockHeight",n.blockHeight],["utxoHeight",n.utxoHeight]])if(i!==void 0&&(!Number.isSafeInteger(i)||i<0||i>4294967295))throw new RangeError(`Spend verification ${e} must be an unsigned 32-bit integer`);let t=Array.isArray(n.verifyFlags)?Array.from(n.verifyFlags):n.verifyFlags;if(t!==void 0&&typeof t!="string"&&(!Array.isArray(t)||t.some(e=>typeof e!="string")))throw new TypeError("Spend verification flags must be a string or an array of strings");return{consensus:n.consensus,blockHeight:n.blockHeight,utxoHeight:n.utxoHeight,verifyFlags:t}}function Qh(n,t=Number.MAX_SAFE_INTEGER){return!(n.length>t||n.length>0&&(n.at(-1)&127)===0&&(n.length<=1||(n.at(-2)&128)===0))}function Hw(n){if(n.length<9||n.length>73||n[0]!==48||n[1]!==n.length-3)return!1;let t=n[2],e=n[3];if(t!==2||e===0||5+e>=n.length)return!1;let i=4+e,r=n[i],s=n[i+1];if(r!==2||s===0||(n[4]&128)!==0||e>1&&n[4]===0&&(n[5]&128)===0)return!1;let o=i+2;return!((n[o]&128)!==0||s>1&&n[o]===0&&(n[o+1]&128)===0||e+s+7!==n.length)}function $w(n){let t=n.data,e=n.op;return Array.isArray(t)?t.length===0?e===x.OP_0:t.length===1&&t[0]>=1&&t[0]<=16?e===x.OP_1+(t[0]-1):t.length===1&&t[0]===129?e===x.OP_1NEGATE:t.length<=75?e===t.length:t.length<=255?e===x.OP_PUSHDATA1:t.length<=65535?e===x.OP_PUSHDATA2:!0:!0}var Gn,So,h,Ii,Mt,Et,se,mo,jn,bo,tp,ep,np,ip,ff,df,Ha,Xr,wo,rp,lt,Re,Q,Kt,vt,sp,op,$a,ap,cp,le,yo,lf,up,fp,dp,hf,pf,gf,mf,lp,bf,wf,hp,pp,gp,mp,bp,wp,yp,xp,Sp,Ip,vp,yf,qa,Ap,xf,jr,K,Sf=class Sf{constructor(t){G(this,h);b(this,"sourceTXID");b(this,"sourceOutputIndex");b(this,"sourceSatoshis");b(this,"lockingScript");b(this,"transactionVersion");b(this,"otherInputs");b(this,"allInputs");b(this,"outputs");b(this,"inputIndex");b(this,"unlockingScript");b(this,"inputSequence");b(this,"lockTime");b(this,"context");b(this,"programCounter");b(this,"lastCodeSeparator");b(this,"stack");b(this,"altStack");b(this,"ifStack");b(this,"elseStack");b(this,"memoryLimit");b(this,"hasExplicitMemoryLimit");b(this,"stackMem");b(this,"altStackMem");b(this,"isRelaxedOverride");b(this,"verifyFlags");b(this,"executedOpCount");b(this,"returningFromConditional");G(this,Gn);G(this,So);if(this.sourceTXID=t.sourceTXID,this.sourceOutputIndex=t.sourceOutputIndex,this.sourceSatoshis=t.sourceSatoshis,this.lockingScript=t.lockingScript,this.transactionVersion=t.transactionVersion,this.otherInputs=t.otherInputs,this.allInputs=t.allInputs,this.outputs=t.outputs,this.inputIndex=t.inputIndex,this.unlockingScript=t.unlockingScript,this.inputSequence=t.inputSequence,this.lockTime=t.lockTime,this.hasExplicitMemoryLimit=t.memoryLimit!==void 0,this.memoryLimit=t.memoryLimit??Number.POSITIVE_INFINITY,this.isRelaxedOverride=t.isRelaxed===!0,t.verifyFlags===void 0)this.verifyFlags=void 0;else{let e=Array.isArray(t.verifyFlags)?t.verifyFlags:t.verifyFlags.split(",");this.verifyFlags=new Set(e.map(i=>i.trim()).filter(i=>i.length>0))}this.stack=[],this.altStack=[],this.ifStack=[],this.elseStack=[],this.stackMem=0,this.altStackMem=0,this.executedOpCount=0,this.returningFromConditional=!1,N(this,So,t.sigHashCache==null),N(this,Gn,t.sigHashCache??{hashOutputsSingle:new Map}),this.reset()}reset(){y(this,So)&&(delete y(this,Gn).hashPrevouts,delete y(this,Gn).hashSequence,delete y(this,Gn).hashOutputsAll,y(this,Gn).hashOutputsSingle?.clear()),this.context="UnlockingScript",this.programCounter=0,this.lastCodeSeparator=null,this.stack=[],this.altStack=[],this.ifStack=[],this.elseStack=[],this.stackMem=0,this.altStackMem=0,this.executedOpCount=0,this.returningFromConditional=!1}step(){a(this,h,hp).call(this);let t=a(this,h,pp).call(this);if(this.programCounter>=t.chunks.length)return!1;let e=t.chunks[this.programCounter],i=a(this,h,gp).call(this,e),r=!this.returningFromConditional&&!this.ifStack.includes(!1);if(a(this,h,mp).call(this,i),r&&i>=0&&i<=x.OP_PUSHDATA4)a(this,h,bp).call(this,e);else if(r||i>=x.OP_IF&&i<=x.OP_ENDIF){let s,o,c,u,f,d,l,p,m,g,w,S,C,E,A,k,B,_,H,O,I,U,M,F,it,ot;if(a(this,h,wp).call(this,i,r),a(this,h,yp).call(this,i,r))return!0;switch(a(this,h,xp).call(this,i,r),i){case x.OP_VER:{let q=this.transactionVersion;a(this,h,lt).call(this,[q&255,q>>>8&255,q>>>16&255,q>>>24&255]);break}case x.OP_SUBSTR:{(()=>{this.stack.length<3&&a(this,h,K).call(this,"OP_SUBSTR requires at least three items to be on the stack.");let q=a(this,h,yo).call(this,a(this,h,Q).call(this)),z=a(this,h,yo).call(this,a(this,h,Q).call(this));s=a(this,h,Q).call(this);let tt=s.length;(z<0||z>=tt||q<0||q>tt-z)&&a(this,h,K).call(this,`OP_SUBSTR offset (${z}) must be in range [0, ${tt}) and length (${q}) must be in range [0, ${tt-z}]`),a(this,h,lt).call(this,s.slice(z,z+q))})();break}case x.OP_LEFT:{(()=>{this.stack.length<2&&a(this,h,K).call(this,"OP_LEFT requires at least two items to be on the stack.");let q=a(this,h,yo).call(this,a(this,h,Q).call(this));s=a(this,h,Q).call(this);let z=s.length;(q<0||q>z)&&a(this,h,K).call(this,`OP_LEFT length (${q}) must be in range [0, ${z}]`),a(this,h,lt).call(this,s.slice(0,q))})();break}case x.OP_RIGHT:{(()=>{this.stack.length<2&&a(this,h,K).call(this,"OP_RIGHT requires at least two items to be on the stack.");let q=a(this,h,yo).call(this,a(this,h,Q).call(this));s=a(this,h,Q).call(this);let z=s.length;(q<0||q>z)&&a(this,h,K).call(this,`OP_RIGHT length (${q}) must be in range [0, ${z}]`),a(this,h,lt).call(this,s.slice(z-q))})();break}case x.OP_LSHIFTNUM:{(()=>{this.stack.length<2&&a(this,h,K).call(this,"OP_LSHIFTNUM requires at least two items to be on the stack.");let q=a(this,h,le).call(this,a(this,h,Q).call(this)).toBigInt();q<0&&a(this,h,K).call(this,"OP_LSHIFTNUM bits to shift must not be negative."),q>0x7fffffffn&&a(this,h,K).call(this,"OP_LSHIFTNUM shift count exceeds INT_MAX.");let z=a(this,h,le).call(this,a(this,h,Q).call(this)).toBigInt(),tt=a(this,h,Ha).call(this);tt!==void 0&&z!==0n&&q>=BigInt(tt)*8n&&a(this,h,K).call(this,"script number overflow");let St=new T(z<<q).toScriptNum();tt!==void 0&&St.length>tt&&a(this,h,K).call(this,"script number overflow"),a(this,h,lt).call(this,St)})();break}case x.OP_RSHIFTNUM:{(()=>{this.stack.length<2&&a(this,h,K).call(this,"OP_RSHIFTNUM requires at least two items to be on the stack.");let q=a(this,h,le).call(this,a(this,h,Q).call(this)).toBigInt();q<0&&a(this,h,K).call(this,"OP_RSHIFTNUM bits to shift must not be negative."),q>0x7fffffffn&&a(this,h,K).call(this,"OP_RSHIFTNUM shift count exceeds INT_MAX.");let z=a(this,h,le).call(this,a(this,h,Q).call(this)).toBigInt(),tt;z<0?tt=new T(-(-z>>q)):tt=new T(z>>q),a(this,h,lt).call(this,tt.toScriptNum())})();break}case x.OP_1NEGATE:a(this,h,Re).call(this,Cw);break;case x.OP_0:a(this,h,Re).call(this,Yh[0]);break;case x.OP_1:case x.OP_2:case x.OP_3:case x.OP_4:case x.OP_5:case x.OP_6:case x.OP_7:case x.OP_8:case x.OP_9:case x.OP_10:case x.OP_11:case x.OP_12:case x.OP_13:case x.OP_14:case x.OP_15:case x.OP_16:S=i-(x.OP_1-1),a(this,h,Re).call(this,Yh[S]);break;case x.OP_NOP:case x.OP_NOP1:break;case x.OP_CHECKLOCKTIMEVERIFY:a(this,h,Sp).call(this);break;case x.OP_CHECKSEQUENCEVERIFY:a(this,h,Ip).call(this);break;case x.OP_NOP9:case x.OP_NOP10:break;case x.OP_VERIF:case x.OP_VERNOTIF:(()=>{if(E=!1,r){if(this.stack.length<1&&a(this,h,K).call(this,"OP_VERIF and OP_VERNOTIF require at least one item on the stack when they are used!"),o=a(this,h,Q).call(this),o.length===4){let q=this.transactionVersion;c=[q&255,q>>>8&255,q>>>16&255,q>>>24&255],E=Zh(o,c)}i===x.OP_VERNOTIF&&(E=!E)}this.ifStack.push(E),this.elseStack.push(!1)})();break;case x.OP_IF:case x.OP_NOTIF:E=!1,r&&(this.stack.length<1&&a(this,h,K).call(this,"OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),s=a(this,h,Q).call(this),a(this,h,Et).call(this,"MINIMALIF")&&a(this,h,jn).call(this)&&s.length>0&&!(s.length===1&&s[0]===1)&&a(this,h,K).call(this,"OP_IF and OP_NOTIF require minimal truth values."),E=a(this,h,jr).call(this,s),i===x.OP_NOTIF&&(E=!E)),this.ifStack.push(E),this.elseStack.push(!1);break;case x.OP_ELSE:this.ifStack.length===0&&a(this,h,K).call(this,"OP_ELSE requires a preceeding OP_IF."),a(this,h,Mt).call(this)&&a(this,h,se).call(this)&&this.elseStack.at(-1)===!0&&a(this,h,K).call(this,"OP_ELSE may only be used once for each OP_IF or OP_NOTIF after Genesis."),this.elseStack[this.elseStack.length-1]=!0,this.ifStack[this.ifStack.length-1]=this.ifStack.at(-1)!==!0;break;case x.OP_ENDIF:this.ifStack.length===0&&a(this,h,K).call(this,"OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop(),this.elseStack.pop();break;case x.OP_VERIFY:this.stack.length<1&&a(this,h,K).call(this,"OP_VERIFY requires at least one item to be on the stack."),o=a(this,h,Kt).call(this),E=a(this,h,jr).call(this,o),E||a(this,h,K).call(this,"OP_VERIFY requires the top stack value to be truthy."),a(this,h,Q).call(this);break;case x.OP_RETURN:a(this,h,Mt).call(this)&&!a(this,h,se).call(this)&&a(this,h,K).call(this,"OP_RETURN is invalid before Genesis."),this.ifStack.length>0?this.returningFromConditional=!0:(this.context==="UnlockingScript"?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.programCounter--);break;case x.OP_TOALTSTACK:a(this,h,vt).call(this,1,"OP_TOALTSTACK requires at oeast one item to be on the stack."),a(this,h,ap).call(this,a(this,h,Q).call(this));break;case x.OP_FROMALTSTACK:a(this,h,sp).call(this,1,"OP_FROMALTSTACK requires at least one item to be on the stack."),a(this,h,lt).call(this,a(this,h,cp).call(this));break;case x.OP_2DROP:a(this,h,vt).call(this,2,"OP_2DROP requires at least two items to be on the stack."),a(this,h,Q).call(this),a(this,h,Q).call(this);break;case x.OP_2DUP:a(this,h,vt).call(this,2,"OP_2DUP requires at least two items to be on the stack."),o=a(this,h,Kt).call(this,-2),c=a(this,h,Kt).call(this,-1),a(this,h,Re).call(this,o),a(this,h,Re).call(this,c);break;case x.OP_3DUP:a(this,h,vt).call(this,3,"OP_3DUP requires at least three items to be on the stack."),o=a(this,h,Kt).call(this,-3),c=a(this,h,Kt).call(this,-2),u=a(this,h,Kt).call(this,-1),a(this,h,Re).call(this,o),a(this,h,Re).call(this,c),a(this,h,Re).call(this,u);break;case x.OP_2OVER:a(this,h,vt).call(this,4,"OP_2OVER requires at least four items to be on the stack."),o=a(this,h,Kt).call(this,-4),c=a(this,h,Kt).call(this,-3),a(this,h,Re).call(this,o),a(this,h,Re).call(this,c);break;case x.OP_2ROT:{a(this,h,vt).call(this,6,"OP_2ROT requires at least six items to be on the stack.");let q=a(this,h,Q).call(this),z=a(this,h,Q).call(this),tt=a(this,h,Q).call(this),St=a(this,h,Q).call(this),ce=a(this,h,Q).call(this),Bt=a(this,h,Q).call(this);a(this,h,lt).call(this,St),a(this,h,lt).call(this,tt),a(this,h,lt).call(this,z),a(this,h,lt).call(this,q),a(this,h,lt).call(this,Bt),a(this,h,lt).call(this,ce);break}case x.OP_2SWAP:{a(this,h,vt).call(this,4,"OP_2SWAP requires at least four items to be on the stack.");let q=a(this,h,Q).call(this),z=a(this,h,Q).call(this),tt=a(this,h,Q).call(this),St=a(this,h,Q).call(this);a(this,h,lt).call(this,z),a(this,h,lt).call(this,q),a(this,h,lt).call(this,St),a(this,h,lt).call(this,tt);break}case x.OP_IFDUP:a(this,h,vt).call(this,1,"OP_IFDUP requires at least one item to be on the stack."),o=a(this,h,Kt).call(this),a(this,h,jr).call(this,o)&&a(this,h,Re).call(this,o);break;case x.OP_DEPTH:a(this,h,lt).call(this,new T(this.stack.length).toScriptNum());break;case x.OP_DROP:a(this,h,vt).call(this,1,"OP_DROP requires at least one item to be on the stack."),a(this,h,Q).call(this);break;case x.OP_DUP:a(this,h,vt).call(this,1,"OP_DUP requires at least one item to be on the stack."),a(this,h,Re).call(this,a(this,h,Kt).call(this));break;case x.OP_NIP:a(this,h,vt).call(this,2,"OP_NIP requires at least two items to be on the stack."),c=a(this,h,Q).call(this),a(this,h,Q).call(this),a(this,h,lt).call(this,c);break;case x.OP_OVER:a(this,h,vt).call(this,2,"OP_OVER requires at least two items to be on the stack."),a(this,h,Re).call(this,a(this,h,Kt).call(this,-2));break;case x.OP_PICK:case x.OP_ROLL:{(()=>{a(this,h,vt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),p=a(this,h,le).call(this,a(this,h,Q).call(this));let q=p.toBigInt();(q<0n||q>=BigInt(this.stack.length))&&a(this,h,K).call(this,`${x[i]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);let z=Number(q),tt=this.stack[this.stack.length-1-z];i===x.OP_ROLL?(this.stack.splice(this.stack.length-1-z,1),this.stackMem-=tt.length,a(this,h,lt).call(this,tt)):a(this,h,Re).call(this,tt)})();break}case x.OP_ROT:a(this,h,vt).call(this,3,"OP_ROT requires at least three items to be on the stack."),l=a(this,h,Q).call(this),d=a(this,h,Q).call(this),f=a(this,h,Q).call(this),a(this,h,lt).call(this,d),a(this,h,lt).call(this,l),a(this,h,lt).call(this,f);break;case x.OP_SWAP:a(this,h,vt).call(this,2,"OP_SWAP requires at least two items to be on the stack."),d=a(this,h,Q).call(this),f=a(this,h,Q).call(this),a(this,h,lt).call(this,d),a(this,h,lt).call(this,f);break;case x.OP_TUCK:a(this,h,vt).call(this,2,"OP_TUCK requires at least two items to be on the stack."),o=a(this,h,Kt).call(this,-1),a(this,h,wo).call(this,o.length),this.stack.splice(-2,0,o.slice()),this.stackMem+=o.length;break;case x.OP_SIZE:a(this,h,vt).call(this,1,"OP_SIZE requires at least one item to be on the stack."),a(this,h,lt).call(this,new T(a(this,h,Kt).call(this).length).toScriptNum());break;case x.OP_AND:case x.OP_OR:case x.OP_XOR:{(()=>{a(this,h,vt).call(this,2,`${x[i]} requires at least two items on the stack.`),c=a(this,h,Q).call(this),o=a(this,h,Q).call(this),o.length!==c.length&&a(this,h,K).call(this,`${x[i]} requires the top two stack items to be the same size.`);let q=Array.from({length:o.length},()=>0);for(let z=0;z<o.length;z++)i===x.OP_AND?q[z]=o[z]&c[z]:i===x.OP_OR?q[z]=o[z]|c[z]:q[z]=o[z]^c[z];a(this,h,lt).call(this,q)})();break}case x.OP_INVERT:{(()=>{a(this,h,vt).call(this,1,"OP_INVERT requires at least one item to be on the stack."),s=a(this,h,Q).call(this);let q=Array.from({length:s.length},()=>0);for(let z=0;z<s.length;z++)q[z]=~s[z]&255;a(this,h,lt).call(this,q)})();break}case x.OP_LSHIFT:case x.OP_RSHIFT:{(()=>{a(this,h,vt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),g=a(this,h,le).call(this,a(this,h,Q).call(this)),o=a(this,h,Q).call(this);let q=g.toBigInt();if(q<0n&&a(this,h,K).call(this,`${x[i]} requires the top item on the stack not to be negative.`),o.length===0){a(this,h,lt).call(this,[]);return}if(q>=BigInt(o.length)*8n){a(this,h,lt).call(this,Array.from({length:o.length},()=>0));return}m=new T(o);let z;if(i===x.OP_LSHIFT){z=m.ushln(q);let St=new T(1).ushln(o.length*8).isubn(1);z=z.iand(St)}else z=m.ushrn(q);let tt=z.toArray("be",o.length);a(this,h,lt).call(this,tt)})();break}case x.OP_EQUAL:case x.OP_EQUALVERIFY:a(this,h,vt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),c=a(this,h,Q).call(this),o=a(this,h,Q).call(this),E=Zh(o,c),a(this,h,lt).call(this,E?[1]:[]),i===x.OP_EQUALVERIFY&&(E||a(this,h,K).call(this,"OP_EQUALVERIFY requires the top two stack items to be equal."),a(this,h,Q).call(this));break;case x.OP_1ADD:case x.OP_1SUB:case x.OP_2MUL:case x.OP_2DIV:case x.OP_NEGATE:case x.OP_ABS:case x.OP_NOT:case x.OP_0NOTEQUAL:(()=>{switch(a(this,h,vt).call(this,1,`${x[i]} requires at least one item to be on the stack.`),p=a(this,h,le).call(this,a(this,h,Q).call(this)),i){case x.OP_1ADD:p=p.add(new T(1));break;case x.OP_1SUB:p=p.sub(new T(1));break;case x.OP_2MUL:p=p.mul(new T(2));break;case x.OP_2DIV:p=p.div(new T(2));break;case x.OP_NEGATE:p=p.neg();break;case x.OP_ABS:p.isNeg()&&(p=p.neg());break;case x.OP_NOT:p=new T(p.cmpn(0)===0?1:0);break;case x.OP_0NOTEQUAL:p=new T(p.cmpn(0)===0?0:1);break}a(this,h,lt).call(this,p.toScriptNum())})();break;case x.OP_ADD:case x.OP_SUB:case x.OP_MUL:case x.OP_DIV:case x.OP_MOD:case x.OP_BOOLAND:case x.OP_BOOLOR:case x.OP_NUMEQUAL:case x.OP_NUMEQUALVERIFY:case x.OP_NUMNOTEQUAL:case x.OP_LESSTHAN:case x.OP_GREATERTHAN:case x.OP_LESSTHANOREQUAL:case x.OP_GREATERTHANOREQUAL:case x.OP_MIN:case x.OP_MAX:{(()=>{a(this,h,vt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),c=a(this,h,Q).call(this),o=a(this,h,Q).call(this),g=a(this,h,le).call(this,c),m=a(this,h,le).call(this,o);let q=(()=>{switch(i){case x.OP_MUL:return m.byteLength()+g.byteLength();case x.OP_ADD:case x.OP_SUB:return Math.max(m.byteLength(),g.byteLength())+1;default:return Math.max(m.byteLength(),g.byteLength())}})();a(this,h,wo).call(this,q);let z=(()=>{switch(i){case x.OP_ADD:return m.add(g);case x.OP_SUB:return m.sub(g);case x.OP_MUL:return m.mul(g);case x.OP_DIV:return g.cmpn(0)===0&&a(this,h,K).call(this,"OP_DIV cannot divide by zero!"),m.div(g);case x.OP_MOD:return g.cmpn(0)===0&&a(this,h,K).call(this,"OP_MOD cannot divide by zero!"),m.mod(g);case x.OP_BOOLAND:return Lw(m.cmpn(0)!==0,g.cmpn(0)!==0);case x.OP_BOOLOR:return Uw(m.cmpn(0)!==0,g.cmpn(0)!==0);case x.OP_NUMEQUAL:case x.OP_NUMEQUALVERIFY:return vi(m.cmp(g)===0);case x.OP_NUMNOTEQUAL:return vi(m.cmp(g)!==0);case x.OP_LESSTHAN:return vi(m.cmp(g)<0);case x.OP_GREATERTHAN:return vi(m.cmp(g)>0);case x.OP_LESSTHANOREQUAL:return vi(m.cmp(g)<=0);case x.OP_GREATERTHANOREQUAL:return vi(m.cmp(g)>=0);case x.OP_MIN:return Mw(m,g);case x.OP_MAX:return Dw(m,g);default:return new T(0)}})();a(this,h,lt).call(this,z.toScriptNum()),i===x.OP_NUMEQUALVERIFY&&(a(this,h,jr).call(this,a(this,h,Kt).call(this))||a(this,h,K).call(this,"OP_NUMEQUALVERIFY requires the top stack item to be truthy."),a(this,h,Q).call(this))})();break}case x.OP_WITHIN:a(this,h,vt).call(this,3,"OP_WITHIN requires at least three items to be on the stack."),w=a(this,h,le).call(this,a(this,h,Q).call(this)),g=a(this,h,le).call(this,a(this,h,Q).call(this)),m=a(this,h,le).call(this,a(this,h,Q).call(this)),E=m.cmp(g)>=0&&m.cmp(w)<0,a(this,h,lt).call(this,E?[1]:[]);break;case x.OP_RIPEMD160:case x.OP_SHA1:case x.OP_SHA256:case x.OP_HASH160:case x.OP_HASH256:{(()=>{a(this,h,vt).call(this,1,`${x[i]} requires at least one item to be on the stack.`),s=a(this,h,Q).call(this);let q=[];i===x.OP_RIPEMD160?q=$u(s):i===x.OP_SHA1?q=qu(s):i===x.OP_SHA256?q=Te(s):i===x.OP_HASH160?q=Js(s):i===x.OP_HASH256&&(q=zt(s)),a(this,h,lt).call(this,q)})();break}case x.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case x.OP_CHECKSIG:case x.OP_CHECKSIGVERIFY:{a(this,h,vt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),_=a(this,h,Q).call(this),B=a(this,h,Q).call(this),(!a(this,h,hf).call(this,B)||!a(this,h,bf).call(this,_))&&a(this,h,K).call(this,`${x[i]} requires correct encoding for the public key and signature.`),A=(()=>{if(B.length===0)return!1;try{H=a(this,h,pf).call(this,B);let z=(this.context==="UnlockingScript"?this.unlockingScript:this.lockingScript).chunks.slice(this.lastCodeSeparator===null?0:this.lastCodeSeparator+1);return this.context==="UnlockingScript"&&(z=z.concat(this.lockingScript.chunks)),k=new me(z),((H.scope&wt.SIGHASH_FORKID)===0||a(this,h,Mt).call(this)&&!a(this,h,Et).call(this,"SIGHASH_FORKID"))&&k.findAndDelete(new me().writeBin(B)),O=Ht.fromDER(_),a(this,h,wf).call(this,H,O,k)}catch{return!1}})(),!A&&a(this,h,Et).call(this,"NULLFAIL")&&a(this,h,jn).call(this)&&B.length>0&&a(this,h,K).call(this,`${x[i]} requires failing signatures to be empty.`),a(this,h,lt).call(this,A?[1]:[]),i===x.OP_CHECKSIGVERIFY&&(A||a(this,h,K).call(this,"OP_CHECKSIGVERIFY requires that a valid signature is provided."),a(this,h,Q).call(this));break}case x.OP_CHECKMULTISIG:case x.OP_CHECKMULTISIGVERIFY:{(()=>{I=1,this.stack.length<I&&a(this,h,K).call(this,`${x[i]} requires at least 1 item for nKeys.`);let z=a(this,h,le).call(this,a(this,h,Kt).call(this,-I)).toBigInt(),tt=a(this,h,Mt).call(this)&&!a(this,h,se).call(this)?BigInt(Bw):Nw;(z<0n||z>tt)&&a(this,h,K).call(this,`${x[i]} requires a key count between 0 and ${tt.toString()}.`),F=Number(z);let St=F;U=++I,I+=F,this.stack.length<I&&a(this,h,K).call(this,`${x[i]} stack too small for nKeys and keys. Need ${I}, have ${this.stack.length}.`);let Bt=a(this,h,le).call(this,a(this,h,Kt).call(this,-I)).toBigInt();(Bt<0n||Bt>BigInt(F))&&a(this,h,K).call(this,`${x[i]} requires the number of signatures to be no greater than the number of keys.`),it=Number(Bt);let dn=it;M=++I,I+=it,this.stack.length<I&&a(this,h,K).call(this,`${x[i]} stack too small for N, keys, M, sigs, and dummy. Need ${I}, have ${this.stack.length}.`);let xe=(this.context==="UnlockingScript"?this.unlockingScript:this.lockingScript).chunks.slice(this.lastCodeSeparator===null?0:this.lastCodeSeparator+1);k=new me(xe);let vn=!1;for(let $=0;$<it;$++)B=a(this,h,Kt).call(this,-M-$),B.length>0&&(vn=!0),((B.at(-1)&wt.SIGHASH_FORKID)===0||a(this,h,Mt).call(this)&&!a(this,h,Et).call(this,"SIGHASH_FORKID"))&&k.findAndDelete(new me().writeBin(B));(()=>{for(A=!0;A&&it>0;){if(F===0){A=!1;break}if(B=a(this,h,Kt).call(this,-M),_=a(this,h,Kt).call(this,-U),(!a(this,h,hf).call(this,B)||!a(this,h,bf).call(this,_))&&a(this,h,K).call(this,`${x[i]} requires correct encoding for the public key and signature.`),ot=!1,B.length>0)try{H=a(this,h,pf).call(this,B),O=Ht.fromDER(_),ot=a(this,h,wf).call(this,H,O,k)}catch{ot=!1}ot&&(M++,it--),U++,F--,it>F&&(A=!1)}})(),(()=>{!A&&a(this,h,Et).call(this,"NULLFAIL")&&a(this,h,jn).call(this)&&vn&&a(this,h,K).call(this,`${x[i]} requires failing signatures to be empty.`);let W=1+St+1+dn+1-1;for(;W>0;)a(this,h,Q).call(this),W--;a(this,h,vt).call(this,1,`${x[i]} requires an extra item (dummy) to be on the stack.`);let D=a(this,h,Q).call(this);a(this,h,ep).call(this)&&D.length>0&&a(this,h,K).call(this,`${x[i]} requires the extra stack item (dummy) to be empty.`),a(this,h,lt).call(this,A?[1]:[]),i===x.OP_CHECKMULTISIGVERIFY&&(A||a(this,h,K).call(this,"OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),a(this,h,Q).call(this))})()})();break}case x.OP_CAT:{(()=>{a(this,h,vt).call(this,2,"OP_CAT requires at least two items to be on the stack."),c=a(this,h,Q).call(this),o=a(this,h,Q).call(this);let q=o.concat(c);q.length>a(this,h,Xr).call(this)&&a(this,h,K).call(this,`It's not currently possible to push data larger than ${a(this,h,Xr).call(this)} bytes.`),a(this,h,lt).call(this,q)})();break}case x.OP_SPLIT:{(()=>{a(this,h,vt).call(this,2,"OP_SPLIT requires at least two items to be on the stack.");let q=a(this,h,Q).call(this),z=a(this,h,Q).call(this),tt=a(this,h,le).call(this,q).toBigInt();(tt<0n||tt>BigInt(z.length))&&a(this,h,K).call(this,"OP_SPLIT requires the first stack item to be a non-negative number less than or equal to the size of the second-from-top stack item.");let St=Number(tt);a(this,h,lt).call(this,z.slice(0,St)),a(this,h,lt).call(this,z.slice(St))})();break}case x.OP_NUM2BIN:{(()=>{a(this,h,vt).call(this,2,"OP_NUM2BIN requires at least two items to be on the stack.");let q=a(this,h,le).call(this,a(this,h,Q).call(this)).toBigInt(),z=a(this,h,Xr).call(this);if((Number.isFinite(z)&&q>BigInt(z)||q<0n)&&a(this,h,K).call(this,`It's not currently possible to push data larger than ${z} bytes or negative size.`),q>Tw&&a(this,h,K).call(this,"OP_NUM2BIN size exceeds the node int32 push limit."),this.hasExplicitMemoryLimit&&Number.isFinite(this.memoryLimit)){let Bt=Math.max(0,Math.floor(this.memoryLimit));if(q>BigInt(Bt))throw new Xn("element-size",Bt,q)}C=Number(q);let tt=a(this,h,Q).call(this);if(tt=Ra(tt),tt.length>C&&a(this,h,K).call(this,"OP_NUM2BIN requires that the size expressed in the top stack item is large enough to hold the value expressed in the second-from-top stack item."),tt.length===C){a(this,h,lt).call(this,tt);return}let St=Array.from({length:C},()=>0),ce=0;tt.length>0&&(ce=tt.at(-1)&128,tt[tt.length-1]&=127);for(let Bt=0;Bt<tt.length;Bt++)St[Bt]=tt[Bt];ce!==0&&(St[C-1]|=128),a(this,h,lt).call(this,St)})();break}case x.OP_BIN2NUM:{(()=>{a(this,h,vt).call(this,1,"OP_BIN2NUM requires at least one item to be on the stack."),o=a(this,h,Q).call(this);let q=Ra(o);Qh(q)||a(this,h,K).call(this,"OP_BIN2NUM requires that the resulting number is valid."),a(this,h,lt).call(this,q)})();break}default:a(this,h,K).call(this,`Invalid opcode ${i} (pc=${this.programCounter}).`)}}return a(this,h,vp).call(this,t),!0}validate(t){let e=Da(),i=a(this,h,yf).call(this),r=t===void 0?void 0:Jh(t);return e?.verifySpendSync!==void 0&&(e.isReady?.()??!0)&&(r===void 0?e.shouldVerifySpend?.(i):e.shouldVerifySpend?.(i,r))!==!1?((r===void 0?e.verifySpendSync(i):e.verifySpendSync(i,r))!==!0&&a(this,h,K).call(this,"The selected script-verification backend rejected the spend."),!0):this.validateJavaScript()}validateJavaScript(){this.reset(),a(this,h,np).call(this)&&!this.unlockingScript.isPushOnly()&&a(this,h,K).call(this,"Unlocking scripts can only contain push operations, and no other opcodes.");let t=this.lockingScript,e=a(this,h,Et).call(this,"P2SH")&&!a(this,h,se).call(this)&&a(this,h,Ap).call(this,this.lockingScript);e&&!this.unlockingScript.isPushOnly()&&a(this,h,K).call(this,"P2SH unlocking scripts can only contain push operations."),a(this,h,qa).call(this,"UnlockingScript");let i=this.stack.map(r=>r.slice());a(this,h,qa).call(this,"LockingScript"),a(this,h,xf).call(this);try{if(e){i.length===0&&a(this,h,K).call(this,"P2SH evaluation requires a redeem script on the stack.");let r=i.pop();if(r===void 0)return a(this,h,K).call(this,"P2SH evaluation requires a redeem script on the stack."),!1;a(this,h,op).call(this,i);let s=me.fromBinary(r);this.lockingScript=new Le(s.chunks),a(this,h,qa).call(this,"LockingScript")}}finally{this.lockingScript=t}return a(this,h,ip).call(this)&&this.stack.length!==1&&a(this,h,K).call(this,`The clean stack rule requires exactly one item to be on the stack after script execution, found ${this.stack.length}.`),a(this,h,xf).call(this),!0}async validateWith(t,e){let i=a(this,h,yf).call(this),r=e===void 0?void 0:Jh(e),s=r===void 0?t.shouldVerifySpend?.(i):t.shouldVerifySpend?.(i,r);if(s!==void 0&&typeof s!="boolean")throw new TypeError("Spend verifier selection must be boolean");if(s===!1)return i.validateJavaScript();let o=r===void 0?await t.verifySpend(i):await t.verifySpend(i,r);if(typeof o!="boolean")throw new TypeError("Spend verifier returned a non-boolean verdict");return o}toTransactionUint8Array(){let t={sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,unlockingScript:this.unlockingScript,sequence:this.inputSequence},e=this.allInputs??[...this.otherInputs.slice(0,this.inputIndex),t,...this.otherInputs.slice(this.inputIndex)];if(this.inputIndex<0||this.inputIndex>=e.length)throw new RangeError("Spend input index is out of range");let i=new ht;i.writeUInt32LE(this.transactionVersion),i.writeVarIntNum(e.length);for(let r=0;r<e.length;r++){let s=r===this.inputIndex?t:e[r],o=s.sourceTXID??s.sourceTransaction?.id("hex");if(o===void 0)throw new Error(`Input ${r} is missing its source transaction ID`);if(s.unlockingScript===void 0)throw new Error(`Input ${r} is missing its unlocking script`);i.writeReverse(at(o,"hex")),i.writeUInt32LE(s.sourceOutputIndex);let c=s.unlockingScript.toUint8Array();i.writeVarIntNum(c.length),i.write(c),i.writeUInt32LE(s.sequence??4294967295)}i.writeVarIntNum(this.outputs.length);for(let r of this.outputs){i.writeUInt64LE(r.satoshis??0);let s=r.lockingScript.toUint8Array();i.writeVarIntNum(s.length),i.write(s)}return i.writeUInt32LE(this.lockTime),i.toUint8Array()}};Gn=new WeakMap,So=new WeakMap,h=new WeakSet,Ii=function(){return this.isRelaxedOverride||this.transactionVersion>1},Mt=function(){return this.verifyFlags!==void 0},Et=function(t){return this.verifyFlags?.has(t)===!0},se=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"UTXO_AFTER_GENESIS")||a(this,h,Et).call(this,"UTXO_AFTER_CHRONICLE"):a(this,h,Ii).call(this)},mo=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"UTXO_AFTER_CHRONICLE"):a(this,h,Ii).call(this)},jn=function(){return!(a(this,h,Et).call(this,"CHRONICLE")&&this.transactionVersion>1)},bo=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"MINIMALDATA")&&a(this,h,jn).call(this):!a(this,h,Ii).call(this)},tp=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"LOW_S")&&a(this,h,jn).call(this):!a(this,h,Ii).call(this)},ep=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"NULLDUMMY")&&a(this,h,jn).call(this):!a(this,h,Ii).call(this)},np=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"SIGPUSHONLY")&&a(this,h,jn).call(this):!a(this,h,Ii).call(this)},ip=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"CLEANSTACK")&&a(this,h,jn).call(this):!a(this,h,Ii).call(this)},ff=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"DERSIG")||a(this,h,Et).call(this,"STRICTENC")||a(this,h,Et).call(this,"LOW_S")||a(this,h,Et).call(this,"SIGHASH_FORKID"):!0},df=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"STRICTENC")||a(this,h,Et).call(this,"SIGHASH_FORKID"):!0},Ha=function(){if(a(this,h,Mt).call(this))return a(this,h,se).call(this)?a(this,h,mo).call(this)?Pw:Ow:4},Xr=function(){return a(this,h,Mt).call(this)&&!a(this,h,se).call(this)?kw:Number.POSITIVE_INFINITY},wo=function(t){if(this.stackMem+t>this.memoryLimit)throw new Xn("stack",this.memoryLimit,this.stackMem+t)},rp=function(t){if(this.altStackMem+t>this.memoryLimit)throw new Xn("alt-stack",this.memoryLimit,this.altStackMem+t)},lt=function(t){a(this,h,wo).call(this,t.length),this.stack.push(t),this.stackMem+=t.length},Re=function(t){a(this,h,wo).call(this,t.length);let e=t.slice();this.stack.push(e),this.stackMem+=e.length},Q=function(){this.stack.length===0&&a(this,h,K).call(this,"Attempted to pop from an empty stack.");let t=this.stack.pop();return t===void 0?(a(this,h,K).call(this,"Attempted to pop from an empty stack."),[]):(this.stackMem-=t.length,t)},Kt=function(t=-1){return(this.stack.length===0||this.stack.length<Math.abs(t)||t>=0&&t>=this.stack.length)&&a(this,h,K).call(this,`Stack underflow accessing element at index ${t}. Stack length is ${this.stack.length}.`),this.stack[this.stack.length+t]},vt=function(t,e){this.stack.length<t&&a(this,h,K).call(this,e)},sp=function(t,e){this.altStack.length<t&&a(this,h,K).call(this,e)},op=function(t){this.stack=t.map(e=>e.slice()),this.stackMem=this.stack.reduce((e,i)=>e+i.length,0)},$a=function(){this.altStack=[],this.altStackMem=0},ap=function(t){a(this,h,rp).call(this,t.length),this.altStack.push(t),this.altStackMem+=t.length},cp=function(){this.altStack.length===0&&a(this,h,K).call(this,"Attempted to pop from an empty alt stack.");let t=this.altStack.pop();return t===void 0?(a(this,h,K).call(this,"Attempted to pop from an empty alt stack."),[]):(this.altStackMem-=t.length,t)},le=function(t){try{return T.fromScriptNum(t,a(this,h,bo).call(this),a(this,h,Ha).call(this))}catch(e){let i=e instanceof Error?e.message:String(e);a(this,h,K).call(this,i)}return new T(0)},yo=function(t){let e=a(this,h,Ha).call(this);e!==void 0&&t.length>e&&a(this,h,K).call(this,"script number overflow"),a(this,h,bo).call(this)&&!Qh(t)&&a(this,h,K).call(this,"non-minimally encoded script number");let i;if(t.length>8){i=0n;for(let r=0;r<8;r++)i|=BigInt(t[r])<<BigInt(r*8);i=BigInt.asIntN(64,i)}else i=a(this,h,le).call(this,t).toBigInt();return i>0x7fffffffn?2147483647:i<-0x80000000n?-2147483648:Number(i)},lf=function(t){try{return T.fromScriptNum(t,a(this,h,bo).call(this),5).toBigInt()}catch(e){a(this,h,K).call(this,e instanceof Error?e.message:String(e))}return 0n},up=function(t){let e=t&31;return e>=wt.SIGHASH_ALL&&e<=wt.SIGHASH_SINGLE},fp=function(t){if(!a(this,h,df).call(this))return;a(this,h,up).call(this,t.scope)||a(this,h,K).call(this,"The signature hash type is invalid.");let e=(t.scope&wt.SIGHASH_CHRONICLE)!==0,i=a(this,h,Mt).call(this)?a(this,h,Et).call(this,"CHRONICLE"):a(this,h,mo).call(this);e&&!i&&a(this,h,K).call(this,"The signature hash type is invalid before Chronicle.")},dp=function(t){if(!a(this,h,Mt).call(this)||!a(this,h,Et).call(this,"STRICTENC"))return;let e=(t.scope&wt.SIGHASH_FORKID)!==0;a(this,h,Et).call(this,"SIGHASH_FORKID")&&!e&&a(this,h,K).call(this,"The signature must use SIGHASH_FORKID."),!a(this,h,Et).call(this,"SIGHASH_FORKID")&&!a(this,h,se).call(this)&&e&&a(this,h,K).call(this,"The signature must not use SIGHASH_FORKID.")},hf=function(t){if(t.length===0)return!0;let e=a(this,h,ff).call(this);if(e&&!Hw(t))return a(this,h,K).call(this,"The signature format is invalid."),!1;try{let i=wt.fromChecksigFormat(t);if(a(this,h,fp).call(this,i),a(this,h,dp).call(this,i),a(this,h,tp).call(this)&&!i.hasLowS())return a(this,h,K).call(this,"The signature must have a low S value."),!1}catch{if(e)return a(this,h,K).call(this,"The signature format is invalid."),!1}return!0},pf=function(t){try{return wt.fromChecksigFormat(t)}catch(e){if(a(this,h,ff).call(this))throw e;return a(this,h,lp).call(this,t)}},gf=function(t,e){let i=t[e.value++];if(i===void 0)throw new Error("Invalid DER length");if((i&128)===0)return i;let r=i&127;if(r===0||e.value+r>t.length)throw new Error("Invalid DER length");let s=0;for(let o=0;o<r;o++)s=s<<8|(t[e.value++]??0);return s},mf=function(t,e,i){if(e.value>=i||t[e.value++]!==2)throw new Error("Invalid DER integer");let r=a(this,h,gf).call(this,t,e);if(e.value+r>i)throw new Error("Invalid DER integer length");let s=t.slice(e.value,e.value+r);for(e.value+=r;s.length>1&&s[0]===0;)s=s.slice(1);return s.length===0&&(s=[0]),new T(s)},lp=function(t){if(t.length===0)return wt.fromChecksigFormat(t);let e=t.at(-1),i=t.slice(0,-1),r={value:0};if(i[r.value++]!==48)throw new Error("Signature DER must start with 0x30");let s=a(this,h,gf).call(this,i,r),o=Math.min(r.value+s,i.length),c=a(this,h,mf).call(this,i,r,o),u=a(this,h,mf).call(this,i,r,o);return new wt(c,u,e)},bf=function(t){if(!a(this,h,df).call(this))return!0;if(t.length===0)return a(this,h,K).call(this,"Public key is empty."),!1;if(t.length<33)return a(this,h,K).call(this,"The public key is too short, it must be at least 33 bytes."),!1;if(t[0]===4){if(t.length!==65)return a(this,h,K).call(this,"The non-compressed public key must be 65 bytes."),!1}else if(t[0]===2||t[0]===3){if(t.length!==33)return a(this,h,K).call(this,"The compressed public key must be 33 bytes."),!1}else return a(this,h,K).call(this,"The public key is in an unknown format."),!1;try{Ht.fromDER(t)}catch{return a(this,h,K).call(this,"The public key is in an unknown format."),!1}return!0},wf=function(t,e,i){let r={sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,transactionVersion:this.transactionVersion,otherInputs:this.otherInputs,allInputs:this.allInputs,outputs:this.outputs,inputIndex:this.inputIndex,subscript:i,inputSequence:this.inputSequence,lockTime:this.lockTime,scope:t.scope,sighashForkIdEnabled:!a(this,h,Mt).call(this)||a(this,h,Et).call(this,"SIGHASH_FORKID"),cache:y(this,Gn)},s=wt.usesOtdaSingleBug(r)?new T([1,...Array.from({length:31},()=>0)]):new T(zt(wt.formatBytes(r)));return Si(s,t,e)},hp=function(){if(this.stackMem>this.memoryLimit)throw new Xn("stack",this.memoryLimit,this.stackMem);if(this.altStackMem>this.memoryLimit)throw new Xn("alt-stack",this.memoryLimit,this.altStackMem)},pp=function(){return this.context==="UnlockingScript"&&this.programCounter>=this.unlockingScript.chunks.length&&(this.ifStack.length>0&&a(this,h,K).call(this,"Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the unlocking script."),a(this,h,$a).call(this),this.ifStack=[],this.elseStack=[],this.returningFromConditional=!1,this.lastCodeSeparator=null,this.context="LockingScript",this.programCounter=0),this.context==="UnlockingScript"?this.unlockingScript:this.lockingScript},gp=function(t){let e=t.op;return e===void 0?(a(this,h,K).call(this,`Missing opcode in ${this.context} at pc=${this.programCounter}.`),0):(t.invalidLength===!0&&a(this,h,K).call(this,`Malformed push data in ${this.context} at pc=${this.programCounter}.`),Array.isArray(t.data)&&t.data.length>a(this,h,Xr).call(this)&&a(this,h,K).call(this,`Data push > ${a(this,h,Xr).call(this)} bytes (pc=${this.programCounter}).`),e)},mp=function(t){a(this,h,Mt).call(this)&&!a(this,h,se).call(this)&&!a(this,h,mo).call(this)&&(t===x.OP_2MUL||t===x.OP_2DIV||t===x.OP_VERIF||t===x.OP_VERNOTIF)&&a(this,h,K).call(this,`${x[t]} is disabled until Chronicle.`)},bp=function(t){a(this,h,bo).call(this)&&!$w(t)&&a(this,h,K).call(this,`This data is not minimally-encoded. (PC: ${this.programCounter})`),a(this,h,lt).call(this,Array.isArray(t.data)?t.data:[])},wp=function(t,e){!e||t<=x.OP_16||(this.executedOpCount++,a(this,h,Mt).call(this)&&!a(this,h,se).call(this)&&this.executedOpCount>zh&&a(this,h,K).call(this,`Script executed more than ${zh} opcodes.`))},yp=function(t,e){return!a(this,h,Mt).call(this)||a(this,h,mo).call(this)?!1:e&&(t===x.OP_SUBSTR||t===x.OP_LEFT||t===x.OP_RIGHT||t===x.OP_LSHIFTNUM||t===x.OP_RSHIFTNUM)?(a(this,h,Et).call(this,"DISCOURAGE_UPGRADABLE_NOPS")&&a(this,h,K).call(this,`${x[t]} is discouraged by verification flags.`),this.programCounter++,!0):((e||!a(this,h,se).call(this))&&(t===x.OP_2MUL||t===x.OP_2DIV)&&a(this,h,K).call(this,`${x[t]} is disabled until Chronicle.`),(e||!a(this,h,se).call(this))&&(t===x.OP_VER||t===x.OP_VERIF||t===x.OP_VERNOTIF)&&a(this,h,K).call(this,`${x[t]} is disabled until Chronicle.`),!e&&a(this,h,se).call(this)&&(t===x.OP_VERIF||t===x.OP_VERNOTIF)?(this.programCounter++,!0):!1)},xp=function(t,e){let i=t===x.OP_CHECKLOCKTIMEVERIFY&&(!a(this,h,Et).call(this,"CHECKLOCKTIMEVERIFY")||a(this,h,se).call(this)),r=t===x.OP_CHECKSEQUENCEVERIFY&&(!a(this,h,Et).call(this,"CHECKSEQUENCEVERIFY")||a(this,h,se).call(this));e&&a(this,h,Et).call(this,"DISCOURAGE_UPGRADABLE_NOPS")&&(t===x.OP_NOP1||i||r||t===x.OP_NOP9||t===x.OP_NOP10)&&a(this,h,K).call(this,`${x[t]} is discouraged by verification flags.`)},Sp=function(){if(!a(this,h,Et).call(this,"CHECKLOCKTIMEVERIFY")||a(this,h,se).call(this))return;a(this,h,vt).call(this,1,"OP_CHECKLOCKTIMEVERIFY requires one stack item.");let t=a(this,h,lf).call(this,a(this,h,Kt).call(this));t<0n&&a(this,h,K).call(this,"Negative lock time.");let e=t<BigInt(Gh),i=this.lockTime<Gh;(e!==i||t>BigInt(this.lockTime)||this.inputSequence===4294967295)&&a(this,h,K).call(this,"OP_CHECKLOCKTIMEVERIFY lock time is unsatisfied.")},Ip=function(){if(!a(this,h,Et).call(this,"CHECKSEQUENCEVERIFY")||a(this,h,se).call(this))return;a(this,h,vt).call(this,1,"OP_CHECKSEQUENCEVERIFY requires at least one item to be on the stack.");let t=a(this,h,lf).call(this,a(this,h,Kt).call(this));if(t<0n&&a(this,h,K).call(this,"OP_CHECKSEQUENCEVERIFY requires a non-negative lock time."),(t&BigInt(jh))!==0n)return;let e=BigInt(this.inputSequence>>>0),i=BigInt(uf|_w),r=t&i,s=e&i;(this.transactionVersion>>>0<2||(e&BigInt(jh))!==0n||(r&BigInt(uf))!==(s&BigInt(uf))||r>s)&&a(this,h,K).call(this,"OP_CHECKSEQUENCEVERIFY lock time is unsatisfied.")},vp=function(t){this.returningFromConditional&&this.ifStack.length===0?this.programCounter=t.chunks.length:this.programCounter++,a(this,h,Mt).call(this)&&!a(this,h,se).call(this)&&this.stack.length+this.altStack.length>Xh&&a(this,h,K).call(this,`Stack item count has exceeded ${Xh}.`)},yf=function(){let t=r=>new Le(r.chunks.map(s=>({op:s.op,data:s.data===void 0?void 0:Array.from(s.data),invalidLength:s.invalidLength}))),e=r=>new Ue(r.chunks.map(s=>({op:s.op,data:s.data===void 0?void 0:Array.from(s.data),invalidLength:s.invalidLength}))),i=r=>({sourceTXID:r.sourceTXID??r.sourceTransaction?.id("hex"),sourceOutputIndex:r.sourceOutputIndex,unlockingScript:r.unlockingScript===void 0?void 0:e(r.unlockingScript),sequence:r.sequence});return new Sf({sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,lockingScript:t(this.lockingScript),transactionVersion:this.transactionVersion,otherInputs:this.otherInputs.map(i),allInputs:this.allInputs?.map(i),outputs:this.outputs.map(r=>({satoshis:r.satoshis,lockingScript:t(r.lockingScript),change:r.change})),inputIndex:this.inputIndex,unlockingScript:e(this.unlockingScript),inputSequence:this.inputSequence,lockTime:this.lockTime,memoryLimit:this.hasExplicitMemoryLimit?this.memoryLimit:void 0,isRelaxed:this.isRelaxedOverride,verifyFlags:this.verifyFlags===void 0?void 0:Array.from(this.verifyFlags)})},qa=function(t){this.context=t,this.programCounter=0,this.ifStack=[],this.elseStack=[],this.returningFromConditional=!1,a(this,h,$a).call(this),this.lastCodeSeparator=null;let e=t==="UnlockingScript"?this.unlockingScript:this.lockingScript;for(a(this,h,Mt).call(this)&&!a(this,h,se).call(this)&&e.toUint8Array().length>Kh&&a(this,h,K).call(this,`Script size exceeds ${Kh} bytes.`);this.programCounter<e.chunks.length;)this.step();this.ifStack.length>0&&a(this,h,K).call(this,"Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the script."),this.ifStack=[],this.elseStack=[],a(this,h,$a).call(this),this.lastCodeSeparator=null},Ap=function(t){let e=t.chunks;return e.length===3&&e[0].op===x.OP_HASH160&&e[1].op===20&&Array.isArray(e[1].data)&&e[1].data.length===20&&e[2].op===x.OP_EQUAL},xf=function(){this.stack.length===0?a(this,h,K).call(this,"The top stack element must be truthy after script evaluation (stack is empty)."):a(this,h,jr).call(this,a(this,h,Kt).call(this))||a(this,h,K).call(this,"The top stack element must be truthy after script evaluation.")},jr=function(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(t[e]!==0)return!(e===t.length-1&&t[e]===128);return!1},K=function(t){throw new go({message:t,txid:this.sourceTXID,outputIndex:this.sourceOutputIndex,context:this.context,programCounter:this.programCounter,stackState:this.stack,altStackState:this.altStack,ifStackState:this.ifStack,stackMem:this.stackMem,altStackMem:this.altStackMem})};var xo=Sf;var qw=21e14,Fw=4294967295;function Fa(n,t){if(!Number.isSafeInteger(n)||n<0||n>Fw)throw new Error(`${t} must be an unsigned 32-bit integer`);return n}function If(n,t){if(!Number.isSafeInteger(n)||n<0||n>qw)throw new Error(`${t} must be a valid number of satoshis`);return n}function vf(n,t){if(typeof n!="string"||!/^[0-9a-fA-F]{64}$/.test(n))throw new Error(`${t} must be a 32-byte hexadecimal transaction ID`);return n.toLowerCase()}function Af(n,t){if(n==null||typeof n!="object"||typeof n.toHex!="function")throw new Error(`${t} must be a Script`);let e=n.toHex();if(typeof e!="string"||!/^(?:[0-9a-fA-F]{2})*$/.test(e))throw new Error(`${t} must serialize to a valid hexadecimal script`);return n}function Ep(n,t){if(n!=="all"&&n!=="none"&&n!=="single")throw new Error('signOutputs must be "all", "none", or "single"');if(typeof t!="boolean")throw new TypeError("anyoneCanPay must be a boolean");let e=wt.SIGHASH_FORKID;return n==="all"&&(e|=wt.SIGHASH_ALL),n==="none"&&(e|=wt.SIGHASH_NONE),n==="single"&&(e|=wt.SIGHASH_SINGLE),t&&(e|=wt.SIGHASH_ANYONECANPAY),e}function kp(n,t,e,i){if(n==null||!Array.isArray(n.inputs))throw new Error("A transaction with inputs is required for transaction signing.");if(!Number.isSafeInteger(t)||t<0||t>=n.inputs.length)throw new Error(`inputIndex ${t} is outside the transaction input range`);let r=n.inputs[t],s=Fa(r.sourceOutputIndex,"input.sourceOutputIndex"),o=r.sourceTXID===void 0?void 0:vf(r.sourceTXID,"input.sourceTXID"),c=r.sourceTransaction===void 0?void 0:vf(r.sourceTransaction.id("hex"),"input.sourceTransaction ID");if(o!==void 0&&c!==void 0&&o!==c)throw new Error("The input sourceTXID does not match the input sourceTransaction.");let u=o??c;if(u===void 0)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");let f=r.sourceTransaction?.outputs[s];if(r.sourceTransaction!==void 0&&f==null)throw new Error(`The input sourceTransaction has no output at index ${s}.`);let d=e===void 0?void 0:If(e,"sourceSatoshis"),l=f?.satoshis===void 0?void 0:If(f.satoshis,"sourceTransaction output satoshis");if(d!==void 0&&l!==void 0&&d!==l)throw new Error("The sourceSatoshis does not match the input sourceTransaction output.");let p=d??l;if(p===void 0)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");let m=i===void 0?void 0:Af(i,"lockingScript"),g=f?.lockingScript===void 0?void 0:Af(f.lockingScript,"sourceTransaction output lockingScript");if(m!==void 0&&g!==void 0&&m.toHex().toLowerCase()!==g.toHex().toLowerCase())throw new Error("The lockingScript does not match the input sourceTransaction output.");let w=m??g;if(w===void 0)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");return{sourceTXID:u,sourceSatoshis:p,lockingScript:w,allInputs:n.inputs,get otherInputs(){return n.inputs.filter((S,C)=>C!==t)}}}function Tp(n){let{tx:t,inputIndex:e,signatureScope:i,sourceTXID:r,sourceSatoshis:s,lockingScript:o,otherInputs:c,allInputs:u,inputSequence:f}=n,d=t.inputs[e];Fa(d.sourceOutputIndex,"input.sourceOutputIndex"),If(s,"sourceSatoshis"),vf(r,"sourceTXID"),Af(o,"lockingScript"),Fa(i,"signatureScope");let l=f??sr(d.sequence,"input.sequence must have value");return Fa(l,"inputSequence"),wt.format({sourceTXID:r,sourceOutputIndex:sr(d.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:s,transactionVersion:t.version,otherInputs:c??[],allInputs:u,inputIndex:e,outputs:t.outputs,inputSequence:l,subscript:o,lockTime:t.lockTime,scope:i,cache:t.getSignatureHashCache()})}var Yn=class{lock(t){let e;if(typeof t=="string"){let i=co(t);if(i.prefix.length!==1||i.prefix[0]!==0&&i.prefix[0]!==111)throw new Error("only P2PKH is supported");e=i.data}else{if(!Array.isArray(t))throw new Error("P2PKH hash must be a dense byte array");for(let i=0;i<t.length;i++){let r=t[i];if(!Number.isInteger(r)||r<0||r>255)throw new Error("P2PKH hash must be a dense byte array")}e=t}if(e.length!==20)throw new Error("P2PKH hash length must be 20 bytes");return new Le([{op:x.OP_DUP},{op:x.OP_HASH160},{op:e.length,data:e},{op:x.OP_EQUALVERIFY},{op:x.OP_CHECKSIG}])}unlock(t,e="all",i=!1,r,s){return{sign:async(o,c)=>{let u=Ep(e,i),f=kp(o,c,r,s),d=Tp({tx:o,inputIndex:c,signatureScope:u,sourceTXID:f.sourceTXID,sourceSatoshis:f.sourceSatoshis,lockingScript:f.lockingScript,allInputs:f.allInputs}),l=Te(d),p=cf("signDigest"),m=cf("publicKeyFromPrivate"),g=p===void 0&&m===void 0?void 0:Uint8Array.from(t.toArray("be",32)),w=m===void 0?t.toPublicKey().encode(!0):void 0,S=p===void 0?t.sign(l):ge.fromDER(Array.from(af("signDigest",await p.signDigest(g,Uint8Array.from(Te(l)))))),E=new wt(S.r,S.s,u).toChecksigFormat(),A=m===void 0?w:Array.from(Ww(await m.publicKeyFromPrivate(g)));return new Ue([{op:E.length,data:E},{op:A.length,data:A}])},estimateLength:async()=>108}}};function Ww(n){let t=af("publicKeyFromPrivate",n,33);if(t[0]!==2&&t[0]!==3)throw new Error("publicKeyFromPrivate returned an invalid compressed public key");return t}var Io=class{constructor(t){b(this,"value");Op(t),this.value=t}async computeFee(t){let e=this.value;Op(e);let i=o=>o>4294967295?9:o>65535?5:o>=253?3:1,r=4;r+=i(t.inputs.length);for(let o=0;o<t.inputs.length;o++){let c=t.inputs[o];r+=40;let u;if(typeof c.unlockingScript=="object")u=c.unlockingScript.toBinary().length;else if(typeof c.unlockingScriptTemplate=="object")u=await c.unlockingScriptTemplate.estimateLength(t,o);else throw new TypeError("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");if(!Number.isSafeInteger(u)||u<0)throw new RangeError("Unlocking script length must be a non-negative safe integer.");r+=i(u),r+=u}r+=i(t.outputs.length);for(let o of t.outputs){r+=8;let c=o.lockingScript.toBinary().length;if(!Number.isSafeInteger(c)||c<0)throw new RangeError("Locking script length must be a non-negative safe integer.");r+=i(c),r+=c}r+=4;let s=Math.ceil(r/1e3*e);if(!Number.isSafeInteger(s)||s<0||s>21e14)throw new RangeError("Computed transaction fee is outside the valid satoshi range.");return s}};function Op(n){if(!Number.isFinite(n)||n<0||n>21e14)throw new RangeError("Satoshis-per-kilobyte rate must be finite and non-negative.")}var Wa=8*1024*1024,Va=3e4;function Pp(n={}){let t=n.maxResponseBytes??Wa,e=n.timeoutMs??Va;if(!Number.isSafeInteger(t)||t<1)throw new RangeError("maxResponseBytes must be a positive safe integer");if(!Number.isSafeInteger(e)||e<1||e>10*6e4)throw new RangeError("timeoutMs must be an integer from 1 through 600000");return{maxResponseBytes:t,timeoutMs:e}}function Rp(n,t){let e=new AbortController,i=()=>e.abort(n?.reason);n?.aborted===!0?i():n?.addEventListener("abort",i,{once:!0});let r=setTimeout(()=>e.abort(new DOMException("HTTP request timed out","TimeoutError")),t);return{signal:e.signal,dispose(){clearTimeout(r),n?.removeEventListener("abort",i)}}}async function Np(n,t){let e=n,i=n.headers?.get?.("content-length")??null;if(i!==null&&(!/^(0|[1-9]\d*)$/.test(i)||Number(i)>t))throw await n.body?.cancel().catch(()=>{}),new Error("HTTP response exceeds the configured size limit");if(!("body"in e)){let f=await e.text?.()??"";if(Fe(f)>t)throw new Error("HTTP response exceeds the configured size limit");return f}if(n.body==null)return"";let r=n.body.getReader(),s=[],o=0;try{for(;;){let{done:f,value:d}=await r.read();if(f)break;if(o+=d.byteLength,!Number.isSafeInteger(o)||o>t)throw await r.cancel(),new Error("HTTP response exceeds the configured size limit");s.push(d)}}finally{r.releaseLock()}let c=new Uint8Array(o),u=0;for(let f of s)c.set(f,u),u+=f.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(c)}catch(f){throw new Error("HTTP response is not valid UTF-8",{cause:f})}}function Bp(n,t,e,i){return new Promise((r,s)=>{let o;try{o=e.data===null||e.data===void 0?void 0:i(e.data)}catch(S){s(S);return}let{data:c,...u}=e,f=!1,d,l,p=()=>{l!==void 0&&clearTimeout(l),e.signal?.removeEventListener("abort",w)},m=S=>{f||(f=!0,p(),s(S))},g=S=>{f||(f=!0,p(),r(S))},w=()=>{let S=e.signal?.reason instanceof Error?e.signal.reason:new DOMException("HTTP request aborted","AbortError");d?.destroy?.(S),m(S)};d=n.request(t,u,S=>{let C=S.headers?.["content-length"],E=typeof C=="string"?Number(C):void 0;if(typeof C=="string"&&!/^(0|[1-9]\d*)$/.test(C)||E!==void 0&&(!Number.isSafeInteger(E)||E>Wa)){S.destroy?.(),m(new Error("HTTP response exceeds the configured size limit"));return}let A=[],k=0;S.on("data",B=>{if(f)return;let _=typeof B=="string"?Se(B):new Uint8Array(B);if(k+=_.byteLength,!Number.isSafeInteger(k)||k>Wa){S.destroy?.(),d.destroy?.(),m(new Error("HTTP response exceeds the configured size limit"));return}A.push(_)}),S.on("end",()=>{if(!f)try{if(E!==void 0&&E!==k)throw new Error("HTTP response differs from its declared length");if(!Number.isInteger(S.statusCode)||S.statusCode<100||S.statusCode>599)throw new Error("HTTP response returned an invalid status code");let B=new Uint8Array(k),_=0;for(let M of A)B.set(M,_),_+=M.byteLength;let H=new TextDecoder("utf-8",{fatal:!0}).decode(B),O=S.statusCode>=200&&S.statusCode<=299,I=S.headers["content-type"],U=H!==""&&typeof I=="string"&&I.startsWith("application/json")?JSON.parse(H):H;g({status:S.statusCode,statusText:S.statusMessage??"",ok:O,data:U})}catch(B){m(B)}}),S.on("error",m),S.on("aborted",()=>m(new Error("HTTP response was aborted")))}),d.on("error",m),f||(l=setTimeout(()=>{let S=new Error("HTTP request timed out");d.destroy?.(S),m(S)},Va)),d.setTimeout?.(Va,()=>{let S=new Error("HTTP request timed out");d.destroy?.(S),m(S)}),e.signal?.aborted===!0?w():e.signal?.addEventListener("abort",w,{once:!0}),!f&&(o!==void 0&&d.write(o),d.end())})}var Ka=class{constructor(t){b(this,"https");this.https=t}async request(t,e){return await Bp(this.https,t,e,i=>JSON.stringify(i))}};var vo=class{constructor(t,e={}){b(this,"fetch");b(this,"limits");this.fetch=t,this.limits=Pp(e)}async request(t,e){let i=Rp(e.signal,this.limits.timeoutMs),r={method:e.method,headers:e.headers,body:e.data===void 0?null:JSON.stringify(e.data),redirect:"error",signal:i.signal};try{let s=await this.fetch(t,r),o=s,c=o.headers?.get?.("Content-Type"),u;if(!("body"in o)&&typeof o.json=="function"&&(c==null||c.startsWith("application/json"))){if(u=await o.json(),Fe(JSON.stringify(u))>this.limits.maxResponseBytes)throw new Error("HTTP response exceeds the configured size limit")}else{let f=await Np(s,this.limits.maxResponseBytes);u=f!==""&&(c?.startsWith("application/json")??!1)?JSON.parse(f):f}return{ok:s.ok,status:s.status,statusText:s.statusText,data:u}}finally{i.dispose()}}};function pr(){let n={async request(...e){throw new Error("No method available to perform HTTP request")}};if(globalThis.window!==void 0&&typeof globalThis.window.fetch=="function")return new vo(globalThis.window.fetch.bind(globalThis.window));if(typeof globalThis.fetch=="function")return new vo(globalThis.fetch.bind(globalThis));let t=typeof Iu=="function"?Iu:void 0;if(t===void 0)return n;try{let e=t(["node","https"].join(":"));return new Ka(e)}catch{return n}}var Pn=class Pn extends Io{constructor(e=300*1e3){super(100);b(this,"cachedRate",null);b(this,"cacheTimestamp",0);b(this,"cacheValidityMs");if(!Number.isSafeInteger(e)||e<0)throw new RangeError("cacheValidityMs must be a non-negative safe integer");this.cacheValidityMs=e}static getInstance(e=300*1e3){return Pn.instance??(Pn.instance=new Pn(e)),Pn.instance}async fetchFeeRate(){let e=Date.now();if(this.cachedRate!==null&&e-this.cacheTimestamp<this.cacheValidityMs)return this.cachedRate;try{let i=await pr().request(Pn.ARC_POLICY_URL,{method:"GET",headers:{Accept:"application/json"}});if(!i.ok)throw new Error("Fee-policy provider request failed");let r=i.data,s=r?.policy?.miningFee?.satoshis,o=r?.policy?.miningFee?.bytes;if(!Number.isSafeInteger(s)||s<1||s>21e14||!Number.isSafeInteger(o)||o<1||o>1e9)throw new Error("Invalid policy response format");let c=s/o*1e3;if(!Number.isFinite(c)||c<=0||c>1e9)throw new Error("Invalid policy fee rate");return this.cachedRate=c,this.cacheTimestamp=e,c}catch{return this.cachedRate!==null?(console.warn("Failed to fetch live fee rate; using cached value."),this.cachedRate):(console.warn("Failed to fetch live fee rate; using default 100 sat/kb."),100)}}async computeFee(e){let i=await this.fetchFeeRate();return this.value=i,super.computeFee(e)}};b(Pn,"ARC_POLICY_URL","https://arc.gorillapool.io/v1/policy"),b(Pn,"instance",null);var Ao=Pn;function gn(n){return n==="__proto__"||n==="constructor"||n==="prototype"}function _p(n){if(n==null||typeof n!="object"||Array.isArray(n))return!1;let t=Object.getPrototypeOf(n);return t===Object.prototype||t===null}var za=/^[0-9a-f]{64}$/i,Cp=8192,Vw=128,Kw=256;function Ai(n,t){let e=Object.getOwnPropertyDescriptor(n,t);return e==null?{present:!1}:Object.prototype.hasOwnProperty.call(e,"value")?{present:!0,value:e.value}:{present:!0}}function Ef(n,t){return typeof n=="string"&&Fe(n)<=t}function gr(){return{status:"error",code:"ERR_INVALID_RESPONSE",description:"Broadcaster returned a malformed or transaction-mismatched response."}}function Lp(n,t){if(!za.test(t)||!_p(n))return gr();let e=Ai(n,"status").value;if(e==="success"){let u=Ai(n,"txid").value,f=Ai(n,"message").value,d=Ai(n,"competingTxs");if(typeof u!="string"||!za.test(u)||u.toLowerCase()!==t.toLowerCase()||!Ef(f,Cp))return gr();let l={status:"success",txid:t.toLowerCase(),message:f};if(d.present){if(!Array.isArray(d.value)||d.value.length>Kw)return gr();let p=[],m=new Set;for(let g=0;g<d.value.length;g++){let w=Object.getOwnPropertyDescriptor(d.value,g),S=w?.value;if(w==null||!Object.prototype.hasOwnProperty.call(w,"value")||typeof S!="string"||!za.test(S))return gr();let C=S.toLowerCase();if(m.has(C))return gr();m.add(C),p.push(C)}l.competingTxs=p}return l}if(e!=="error")return gr();let i=Ai(n,"code").value,r=Ai(n,"description").value,s=Ai(n,"txid");if(!Ef(i,Vw)||!Ef(r,Cp)||s.present&&(typeof s.value!="string"||!za.test(s.value)||s.value.toLowerCase()!==t.toLowerCase()))return gr();let o={status:"error",code:i,description:r};s.present&&(o.txid=t.toLowerCase());let c=Ai(n,"more");return c.present&&c.value!=null&&typeof c.value=="object"&&(o.more=c.value),o}function Up(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("Invalid offset")}var mn=(n,t)=>Math.floor(n/2**t),Eo=n=>n%2===0?n+1:n-1,kf=(n,t,e)=>mn(n,e)===mn(t,e),Tf=n=>n===0?0:n.toString(2).length;function bn(n,t){return nt(zt(at((n??"")+(t??""),"hex").reverse()).reverse())}function zw(n,t,e,i){let r=i.get(n);if(r==null)return;if(r!==t)throw new Error("Mismatched roots");let s=i.get(`${e}:0`);if(s==null)throw new Error("Mismatched roots");return s}function Mp(n,t,e,i,r,s){if(t==null){if(s)return bn(n,n);throw new Error(`Missing hash for index ${i} at height ${r}`)}return t.duplicate===!0?bn(n,n):e%2===1?bn(t.hash,n):bn(n,t.hash)}var Ei=class n{constructor(t,e,i=!0,r=!0){b(this,"blockHeight");b(this,"path");if(!Array.isArray(e)||e.length===0||e.length>54)throw new Error("Merkle Path must contain between 1 and 54 levels");this.blockHeight=t,this.path=e.map((l,p)=>{if(!Array.isArray(l))throw new TypeError(`Merkle Path level ${p} must be an array`);return l.map(m=>({...m}))});let s=Array.from({length:this.path.length}).fill(0).map(()=>new Set);if(this.path.forEach((l,p)=>{if(l.length===0&&p===0)throw new Error(`Empty level at height: ${p}`);let m=new Set;l.forEach(g=>{if(Up(g.offset),m.has(g.offset))throw new Error(`Duplicate offset: ${g.offset}, at height: ${p}`);if(m.add(g.offset),p===0){if(g.duplicate!==!0)for(let w=1;w<this.path.length;w++)s[w].add(Eo(mn(g.offset,w)))}else if(i&&!s[p].has(g.offset))throw new Error(`Invalid offset: ${g.offset}, at height: ${p}, with legal offsets: ${Array.from(s[p],w=>w.toString()).join(", ")}`)})}),!r)return;let o=this.path.map(l=>new Map(l.map(p=>[p.offset,p]))),c=new Map,u=new Map,f=this.path[0].reduce((l,p)=>Math.max(l,p.offset),0),d;this.path[0].forEach((l,p)=>{let m=this.computeRootCached(l.hash,o,c,u,f);if(p===0&&(d=m),d!==m)throw new Error("Mismatched roots")})}static fromHex(t){return n.fromBinary(at(t,"hex"))}static fromReader(t,e=!0,i=!0){let r=t.readVarIntNumStrict(!1),s=t.readUInt8(),o=Array.from({length:s}).fill(null).map(()=>[]),c,u,f;for(let d=0;d<s;d++){for(f=t.readVarIntNumStrict(!1);f>0;){u=t.readVarIntNumStrict(!1),c=t.readUInt8();let l={offset:u};(c&1)===1?l.duplicate=!0:((c&2)!==0&&(l.txid=!0),l.hash=nt(t.read(32).reverse())),(!Array.isArray(o[d])||o[d].length===0)&&(o[d]=[]),o[d].push(l),f--}o[d].sort((l,p)=>l.offset-p.offset)}return new n(r,o,e,i)}static fromBinary(t,e=!0,i=!0){let r=new bt(t);return n.fromReader(r,e,i)}static fromCoinbaseTxidAndHeight(t,e){return new n(e,[[{offset:0,hash:t,txid:!0}]])}toWriter(t){t.writeVarIntNum(this.blockHeight);let e=this.path.length;t.writeUInt8(e);for(let i=0;i<e;i++){let r=Object.keys(this.path[i]).length;t.writeVarIntNum(r);for(let s of this.path[i]){t.writeVarIntNum(s.offset);let o=0;s?.duplicate===!0&&(o|=1),s?.txid!==void 0&&s.txid!==null&&(o|=2),t.writeUInt8(o),(o&1)===0&&t.write(at(s.hash,"hex").reverse())}}}toBinary(){let t=new fe;return this.toWriter(t),t.toArray()}toBinaryUint8Array(){let t=new ht;return this.toWriter(t),t.toUint8Array()}toHex(){return nt(this.toBinaryUint8Array())}indexOf(t){let e=this.path[0].find(i=>i.hash===t);if(e==null)throw new Error(`Transaction ID ${t} not found in the Merkle Path`);return e.offset}computeRootCached(t,e,i,r,s){if(typeof t!="string"&&(t=this.path[0].find(f=>!!f.hash)?.hash),typeof t!="string")throw new TypeError("Transaction ID is undefined");let o=this.indexOf(t);if(this.path.length===1&&this.path[0].length===1)return t;let c=Math.max(this.path.length,Tf(s)),u=t;for(let f=0;f<c;f++){let d=`${f}:${mn(o,f)}`,l=zw(d,u,c,r);if(l!=null)return l;r.set(d,u);let p=Eo(mn(o,f)),m=this.cachedFindLeaf(f,p,e,i,s);u=Mp(u,m,p,o,f,this.path.length===1&&kf(o,s,f))}return r.set(`${c}:0`,u),u}computeRoot(t){if(typeof t!="string"){let o=this.path[0].find(c=>!!c?.hash);if(o==null)throw new Error("No valid leaf found in the Merkle Path");t=o.hash}if(typeof t!="string")throw new TypeError("Transaction ID is undefined");let e=this.indexOf(t),i=t;if(this.path.length===1&&this.path[0].length===1)return i;let r=this.path[0].reduce((o,c)=>Math.max(o,c.offset),0),s=Math.max(this.path.length,Tf(r));for(let o=0;o<s;o++){let c=Eo(mn(e,o));i=Mp(i,this.findOrComputeLeaf(o,c),c,e,o,this.path.length===1&&kf(e,r,o))}return i}findOrComputeLeaf(t,e){Up(e);let i=t<this.path.length?this.path[t].find(f=>f.offset===e):void 0;if(i!=null)return i;if(t===0)return;let r=t-1,s=e*2;if(!Number.isSafeInteger(s))return;let o=this.findOrComputeLeaf(r,s);if(o?.hash==null||o.hash==="")return;let c=this.findOrComputeLeaf(r,s+1);if(c?.hash==null){if(c?.duplicate===!0)return{offset:e,hash:bn(o.hash,o.hash)};if(this.path.length===1){let f=this.path[0].reduce((d,l)=>Math.max(d,l.offset),0);if(s===mn(f,r))return{offset:e,hash:bn(o.hash,o.hash)}}return}let u;return c.duplicate===!0?u=bn(o.hash,o.hash):u=bn(c.hash,o.hash),i={offset:e,hash:u},i}async verify(t,e){let i=this.blockHeight;if(!Number.isSafeInteger(i)||i<0)throw new Error("Merkle Path block height must be a non-negative safe integer");let r=e?.currentHeight,s=e?.isValidRootForHeight;if(typeof r!="function"||typeof s!="function")throw new TypeError("A valid ChainTracker is required");let o=this.computeRoot(t);if(this.indexOf(t)===0){let u=await r.call(e);if(!Number.isSafeInteger(u)||u<0)throw new Error("ChainTracker current height must be a non-negative safe integer");if(i+100>u)return!1}return await s.call(e,o,i)===!0}combine(t){if(this.blockHeight!==t.blockHeight)throw new Error("You cannot combine paths which do not have the same block height.");let e=this.computeRoot(),i=t.computeRoot();if(e!==i)throw new Error("You cannot combine paths which do not have the same root.");let r=[];for(let s=0;s<this.path.length;s++){r.push([]);for(let o of this.path[s])r[s].push({...o});for(let o of t.path[s]){let c=r[s].find(u=>u.offset===o.offset);c===void 0?r[s].push({...o}):o?.txid!==void 0&&o?.txid!==null&&(c.txid=!0)}}this.path=r,this.trim()}trim(){let t=(o,c)=>{(c.length===0||c.at(-1)!==o)&&c.push(o)},e=(o,c)=>{for(let u=o.length;u>=0;u--){let f=this.path[c].findIndex(d=>d.offset===o[u]);f>=0&&this.path[c].splice(f,1)}},i=o=>{let c=[];for(let u of o)t(mn(u,1),c);return c},r=[],s=[];for(let o of this.path)o.sort((c,u)=>c.offset-u.offset);for(let o=0;o<this.path[0].length;o++){let c=this.path[0][o];if(c.txid===!0)t(mn(c.offset,1),r);else{let u=c.offset%2===1,f=this.path[0][o+(u?-1:1)];(f.txid===void 0||f.txid===null||!f.txid)&&t(f.offset,s)}}e(s,0);for(let o=1;o<this.path.length;o++)s=r,r=i(r),e(s,o)}cachedFindLeaf(t,e,i,r,s){let o=`${t}:${e}`;if(r.has(o))return r.get(o);let c=t<i.length?i[t].get(e):void 0;if(c!=null)return r.set(o,c),c;if(t===0){r.set(o,void 0);return}let u=t-1,f=e*2;if(!Number.isSafeInteger(f))return;let d=this.cachedFindLeaf(u,f,i,r,s);if(d?.hash==null||d.hash===""){r.set(o,void 0);return}let l=this.cachedFindLeaf(u,f+1,i,r,s);if(l?.hash==null){if(l?.duplicate===!0||this.path.length===1&&f===mn(s,u))return c={offset:e,hash:bn(d.hash,d.hash)},r.set(o,c),c;r.set(o,void 0);return}let p=l.duplicate===!0?bn(d.hash,d.hash):bn(l.hash,d.hash);return c={offset:e,hash:p},r.set(o,c),c}extract(t){if(t.length===0)throw new Error("At least one txid must be provided to extract");let e=this.computeRoot(),i=this.path[0].reduce((l,p)=>Math.max(l,p.offset),0),r=Math.max(this.path.length,Tf(i)),s=this.createSourceLeafIndex(),o=new Map,c=this.createTxidToOffsetIndex(),u=this.createNeededLeafLevels(r);for(let l of t)this.collectExtractedLeaves(l,c,u,s,o,i,r);let f=new n(this.blockHeight,this.buildExtractedPath(u));f.trim();let d=f.computeRoot();if(d!==e)throw new Error(`Extracted path root ${d} does not match original root ${e}`);return f}createSourceLeafIndex(){let t=Array.from({length:this.path.length});for(let e=0;e<this.path.length;e++){let i=new Map;for(let r of this.path[e])i.set(r.offset,r);t[e]=i}return t}createTxidToOffsetIndex(){let t=new Map;for(let e of this.path[0])e.hash!=null&&t.set(e.hash,e.offset);return t}createNeededLeafLevels(t){let e=Array.from({length:t});for(let i=0;i<t;i++)e[i]=new Map;return e}collectExtractedLeaves(t,e,i,r,s,o,c){let u=e.get(t);if(u===void 0)throw new Error(`Transaction ID ${t} not found in the Merkle Path`);i[0].set(u,{offset:u,txid:!0,hash:t});let f=Eo(u);if(!i[0].has(f)){let d=this.cachedFindLeaf(0,f,r,s,o);d!=null&&i[0].set(f,d)}for(let d=1;d<c;d++){let l=Eo(mn(u,d));if(i[d].has(l))continue;let p=this.cachedFindLeaf(d,l,r,s,o);p!=null?i[d].set(l,p):kf(u,o,d)&&i[d].set(l,{offset:l,duplicate:!0})}}buildExtractedPath(t){return t.map(e=>Array.from(e.values()).sort((i,r)=>i.offset-r.offset))}};var Xw=32,jw=64;function Dp(n,t,e){if(n==null||typeof n!="object"||Array.isArray(n))throw new TypeError(`${t} must be an accessor-free plain data object.`);let i=Object.getPrototypeOf(n),r=Object.getOwnPropertyDescriptors(n);if(i!==Object.prototype&&i!==null||Object.getOwnPropertySymbols(n).length!==0||Object.keys(r).length>e||Object.values(r).some(s=>s.get!=null||s.set!=null))throw new TypeError(`${t} must be an accessor-free plain data object.`);return r}function Gr(n,t,e){if(n!==void 0){if(typeof n!="string"||Fe(n)>e||Yi(n))throw new TypeError(`${t} must be bounded text without control characters.`);return n}}function Gw(n){if(n===void 0)return;let t=Dp(n,"ARC headers",jw),e=Object.create(null);for(let[i,r]of Object.entries(t)){if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/.test(i))throw new TypeError(`ARC header name is invalid: ${i}`);let s=Gr(r.value,`ARC header ${i}`,8192);if(s===void 0)throw new TypeError(`ARC header ${i} must be a string.`);e[i]=s}return Object.freeze(e)}function Yw(n){let t=n??pr();if(t==null||typeof t!="object"||typeof t.request!="function")throw new TypeError("ARC httpClient must provide request().");return t}function Hp(n,t){if(typeof n=="string")return Object.freeze({apiKey:Gr(n,"ARC API key",16*1024),httpClient:pr(),deploymentId:t()});let e=Dp(n??{},"ARC config",Xw),i=r=>e[r]?.value;return Object.freeze({apiKey:Gr(i("apiKey"),"ARC API key",16*1024),httpClient:Yw(i("httpClient")),deploymentId:Gr(i("deploymentId"),"ARC deployment ID",256)??t(),callbackUrl:Gr(i("callbackUrl"),"ARC callback URL",2048),callbackToken:Gr(i("callbackToken"),"ARC callback token",16*1024),headers:Gw(i("headers"))})}function $p(n){if(typeof n!="string"||n.length===0||Fe(n)>2048||Yi(n))throw new TypeError("ARC URL must be nonempty bounded text without control characters.");return n}function Xa(n,t){for(let e of t){if(!Object.prototype.hasOwnProperty.call(n,e))throw new Error(`Cannot lock missing configuration property ${e}.`);Object.defineProperty(n,e,{configurable:!1,writable:!1})}}function Zw(){return`ts-sdk-${nt(Pe(16))}`}var Jw=new Set(["DOUBLE_SPEND_ATTEMPTED","REJECTED","INVALID","MALFORMED","MINED_IN_STALE_BLOCK"]),Yr=/^[0-9a-f]{64}$/i,Kp=128,zp=8192,Qw=256,ty=32,ey=new Set(["SUCCESS","RECEIVED","SENT_TO_NETWORK","ANNOUNCED_TO_NETWORK","ACCEPTED_BY_NETWORK","SEEN_ON_NETWORK","STORED","MINED","IMMUTABLE"]);function ja(n,t,e=!0){return typeof n=="string"&&(e||n.length!==0)&&Fe(n)<=t&&!Yi(n)}function Pf(n){if(n==null||typeof n!="object"||Array.isArray(n))return;let t=Object.getPrototypeOf(n);if(t!==Object.prototype&&t!==null)return;let e=Object.getOwnPropertyDescriptors(n);if(!(Object.getOwnPropertySymbols(n).length!==0||Object.keys(e).length>ty||Object.values(e).some(i=>i.get!=null||i.set!=null)))return e}function ny(n){if(n===void 0||!Array.isArray(n)||n.length>Qw)return;let t=Object.getOwnPropertyDescriptors(n),e=new Set(["length",...Array.from({length:n.length},(s,o)=>String(o))]);if(Object.getOwnPropertySymbols(n).length!==0||Object.keys(t).length!==e.size||Object.keys(t).some(s=>!e.has(s))||Object.values(t).some(s=>s.get!=null||s.set!=null))return;let i=[],r=new Set;for(let s=0;s<n.length;s++){let o=t[s]?.value;if(typeof o!="string"||!Yr.test(o))return;let c=o.toLowerCase();if(r.has(c))return;r.add(c),i.push(c)}return i}function qp(n){try{return n.toHexEF()}catch(t){if(t.message==="All inputs must have source transactions when serializing to EF format")return n.toHex();throw t}}function mr(n){return{status:"error",code:"ERR_INVALID_RESPONSE",description:n}}function Fp(n,t){let e=Pf(n);if(e===void 0)return mr("ARC returned a malformed response.");let i=p=>e[p]?.value,r=i("txid"),s=i("extraInfo"),o=i("txStatus"),c=i("competingTxs");if(!ja(o,Kp,!1)||s!==void 0&&!ja(s,zp))return mr("ARC returned invalid transaction status metadata.");let u=ny(c);if(c!==void 0&&u===void 0)return mr("ARC returned invalid competing transaction identifiers.");let f=o.toUpperCase(),d=s?.toUpperCase().includes("ORPHAN")||f.includes("ORPHAN");if(Jw.has(f)||d){if(typeof r=="string"&&Yr.test(r)&&r.toLowerCase()!==t.toLowerCase())return{status:"error",code:"ERR_TXID_MISMATCH",description:"ARC returned a failure for another transaction."};let p={status:"error",code:o,description:`${o} ${s??""}`.trim()};return typeof r=="string"&&Yr.test(r)&&(p.txid=t.toLowerCase()),u!=null&&(p.more={competingTxs:u}),p}if(!ey.has(f))return mr("ARC returned an unknown transaction status.");if(typeof r!="string"||!Yr.test(r)||r.toLowerCase()!==t.toLowerCase())return{status:"error",code:"ERR_TXID_MISMATCH",description:"ARC acknowledged a transaction other than the submitted transaction."};let l={status:"success",txid:t,message:`${o} ${s??""}`.trim()};return u!=null&&(l.competingTxs=u),l}function iy(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch{return n}}function Wp(n,t,e){let r={status:"error",code:typeof n=="number"&&Number.isSafeInteger(n)||typeof n=="string"&&ja(n,Kp,!1)?n.toString():"ERR_UNKNOWN",description:"Unknown error"},s=iy(t),o=Pf(s);if(o===void 0)return r;let c=o.detail?.value,u=o.txid?.value;if(typeof u=="string"&&Yr.test(u)){if(e!==void 0&&u.toLowerCase()!==e.toLowerCase())return{status:"error",code:"ERR_TXID_MISMATCH",description:"ARC returned a failure for another transaction."};r.txid=u.toLowerCase()}let f={};return ja(c,zp)&&(r.description=c,f.detail=c),r.txid!==void 0&&(f.txid=r.txid),Object.keys(f).length!==0&&(r.more=f),r}function Vp(){return{status:"error",code:"500",description:"Internal Server Error"}}var Zr,To,Of,ko=class{constructor(t,e){G(this,To);b(this,"URL");b(this,"apiKey");b(this,"deploymentId");b(this,"callbackUrl");b(this,"callbackToken");b(this,"headers");G(this,Zr);this.URL=$p(t);let i=Hp(e,Zw);this.apiKey=i.apiKey,N(this,Zr,i.httpClient),this.deploymentId=i.deploymentId,this.callbackToken=i.callbackToken,this.callbackUrl=i.callbackUrl,this.headers=i.headers,Xa(this,["URL","apiKey","deploymentId","callbackUrl","callbackToken","headers"])}async broadcast(t){let e={method:"POST",headers:a(this,To,Of).call(this),data:{rawTx:qp(t)}};try{let i=await y(this,Zr).request(`${this.URL}/v1/tx`,e);return i.ok?Fp(i.data,t.id("hex")):Wp(i.status,i.data,t.id("hex"))}catch{return Vp()}}async broadcastMany(t){let e=t.map(r=>({rawTx:qp(r)})),i={method:"POST",headers:a(this,To,Of).call(this),data:e};try{let r=await y(this,Zr).request(`${this.URL}/v1/txs`,i);if(!r.ok)return t.map(u=>Wp(r.status,r.data,u.id("hex")));if(!Array.isArray(r.data)||r.data.length!==t.length)return t.map(()=>mr("ARC returned a malformed batch response."));let s=Object.getOwnPropertyDescriptors(r.data),o=new Set(["length",...Array.from({length:r.data.length},(u,f)=>String(f))]);if(Object.getOwnPropertySymbols(r.data).length!==0||Object.keys(s).length!==o.size||Object.keys(s).some(u=>!o.has(u))||Object.values(s).some(u=>u.get!=null||u.set!=null))return t.map(()=>mr("ARC returned a malformed batch response."));let c=new Map;for(let u of t){let f=u.id("hex").toLowerCase();c.set(f,(c.get(f)??0)+1)}return Array.from({length:r.data.length},(u,f)=>{let d=s[f]?.value,l=Pf(d);if(l===void 0)return mr("ARC returned a malformed batch result.");let p=l.txid?.value,m=typeof p=="string"&&Yr.test(p)?p.toLowerCase():"",g=c.get(m)??0;return g<1?{status:"error",code:"ERR_TXID_MISMATCH",description:"ARC batch acknowledged a transaction that was not submitted."}:(g===1?c.delete(m):c.set(m,g-1),Fp(d,m))})}catch{let r=Vp();return t.map(()=>r)}}};Zr=new WeakMap,To=new WeakSet,Of=function(){let t={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(this.apiKey!=null&&this.apiKey!==""&&(t.Authorization=`Bearer ${this.apiKey}`),this.callbackUrl!=null&&this.callbackUrl!==""&&(t["X-CallbackUrl"]=this.callbackUrl),this.callbackToken!=null&&this.callbackToken!==""&&(t["X-CallbackToken"]=this.callbackToken),this.headers!=null)for(let[e,i]of Object.entries(this.headers))t[e]=i;return t};function Xp(n=!1,t={}){return new ko(n?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",t)}var jp=/^[0-9a-f]{64}$/i,Gp=2147483647,ry=256,Yp=64;function sy(n,t,e){if(typeof n!="string"||Fe(n)>e||Yi(n))throw new TypeError(`${t} must be bounded text without control characters.`);return n}function Rf(n,t,e){if(n==null||typeof n!="object"||Array.isArray(n))throw new TypeError(`${t} must be an accessor-free plain data object.`);let i=Object.getPrototypeOf(n),r=Object.getOwnPropertyDescriptors(n);if(i!==Object.prototype&&i!==null||Object.getOwnPropertySymbols(n).length!==0||Object.keys(r).length>e||Object.values(r).some(s=>s.get!=null||s.set!=null))throw new TypeError(`${t} must be an accessor-free plain data object.`);return r}function oy(n){if(n!=="main"&&n!=="test"&&n!=="stn")throw new TypeError("What's On Chain network must be 'main', 'test', or 'stn'.");return n}function ay(n){let t=n??pr();if(t==null||typeof t!="object"||typeof t.request!="function")throw new TypeError("What's On Chain httpClient must provide request().");return t}function cy(n){let t=Rf(n,"What's On Chain config",8);return{apiKey:t.apiKey?.value===void 0?"":sy(t.apiKey.value,"What's On Chain API key",16*1024),httpClient:ay(t.httpClient?.value)}}function uy(n,t){if(typeof n!="string"||!jp.test(n))throw new TypeError("Merkle root must be a 64-character hexadecimal string.");if(!Number.isSafeInteger(t)||t<0||t>Gp)throw new TypeError("Block height must be a nonnegative bounded integer.");return{root:n.toLowerCase(),height:t}}function fy(n){try{let e=Rf(n,"What's On Chain block header",Yp).merkleroot?.value;return typeof e=="string"&&jp.test(e)?e.toLowerCase():void 0}catch{return}}function dy(n){if(!Array.isArray(n)||n.length===0||n.length>ry)return;let t=Object.getOwnPropertyDescriptors(n),e=new Set(["length",...Array.from({length:n.length},(i,r)=>String(r))]);if(!(Object.getOwnPropertySymbols(n).length!==0||Object.keys(t).length!==e.size||Object.keys(t).some(i=>!e.has(i))||Object.values(t).some(i=>i.get!=null||i.set!=null)))try{let r=Rf(t[0]?.value,"What's On Chain height response",Yp).height?.value;return Number.isSafeInteger(r)&&r>=0&&r<=Gp?r:void 0}catch{return}}var Oo=class{constructor(t="main",e={}){b(this,"network");b(this,"apiKey");b(this,"URL");b(this,"httpClient");this.network=oy(t),this.URL=`https://api.whatsonchain.com/v1/bsv/${this.network}`;let i=cy(e);this.httpClient=i.httpClient,this.apiKey=i.apiKey,Xa(this,["network","URL","httpClient","apiKey"])}async isValidRootForHeight(t,e){let i=uy(t,e),r={method:"GET",headers:this.getHttpHeaders()};try{let s=await this.httpClient.request(`${this.URL}/block/${i.height}/header`,r);if(s.ok)return fy(s.data)===i.root;if(s.status===404)return!1;throw new Error("provider request failed")}catch{throw new Error(`Failed to verify merkleroot for height ${i.height}.`)}}async currentHeight(){try{let t={method:"GET",headers:this.getHttpHeaders()},e=await this.httpClient.request(`${this.URL}/block/headers`,t);if(e.ok){let i=dy(e.data);if(i!==void 0)return i}throw new Error("provider response was invalid")}catch{throw new Error("Failed to get current height from What's On Chain.")}}getHttpHeaders(){let t={Accept:"application/json"};return typeof this.apiKey=="string"&&this.apiKey.trim()!==""&&(t.Authorization=this.apiKey),t}};function Zp(){return new Oo}var ze;(function(n){n[n.RAWTX=0]="RAWTX",n[n.RAWTX_AND_BUMP_INDEX=1]="RAWTX_AND_BUMP_INDEX",n[n.TXID_ONLY=2]="TXID_ONLY"})(ze||(ze={}));function Jr(n,t){if(!Number.isSafeInteger(t)||t<0||n.pos+t>n.bin.length)throw new RangeError("Serialized transaction exceeds available BEEF data");n instanceof bt?n.skip(t):n.read(t)}function Nf(n){let t=n.pos;Jr(n,4);let e=n.readVarIntNumStrict(!1),i=new Set;for(let o=0;o<e;o++){i.add(nt(n.readReverse(32))),Jr(n,4);let c=n.readVarIntNumStrict(!1);Jr(n,c+4)}let r=n.readVarIntNumStrict(!1);for(let o=0;o<r;o++){Jr(n,8);let c=n.readVarIntNumStrict(!1);Jr(n,c)}return Jr(n,4),{rawTx:n instanceof bt?n.bin.subarray(t,n.pos):Uint8Array.from(n.bin.slice(t,n.pos)),inputTxids:Array.from(i)}}function ly(n){return Nf(new bt(n)).inputTxids}function hy(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}var Xe=class n{constructor(t,e,i,r=!1){b(this,"_bumpIndex");b(this,"_tx");b(this,"_rawTx");b(this,"_txid");b(this,"inputTxids",[]);b(this,"isValid");if(typeof t=="string")this._txid=t;else if(t instanceof Uint8Array)this._rawTx=r?t:Uint8Array.from(t);else if(Array.isArray(t))this._rawTx=new Uint8Array(t);else if(t instanceof Me)this._tx=t;else throw new TypeError("Invalid transaction data type");this._bumpIndex=e,this.hasProof?this.inputTxids=[]:i!=null?this.inputTxids=Array.from(i):this.updateInputTxids()}get bumpIndex(){return this._bumpIndex}set bumpIndex(t){this._bumpIndex=t,this.updateInputTxids()}get hasProof(){return this._bumpIndex!==void 0}get isTxidOnly(){return this._txid!==void 0&&this._txid!==null&&this._rawTx==null&&this._tx==null}get txid(){if(this._txid!==void 0&&this._txid!==null&&this._txid!=="")return this._txid;if(this._tx!=null)return this._txid=this._tx.id("hex"),this._txid;if(this._rawTx!=null)return this._txid=nt(zt(this._rawTx).reverse()),this._txid;throw new Error("Internal")}get tx(){if(this._tx!=null)return this._tx;if(this._rawTx!=null)return this._tx=Me.fromBinaryView(this._rawTx),this._txid!=null&&Qp(this._tx,this._txid),this._tx}get rawTx(){let t=this.rawTxUint8Array;return t==null?void 0:Array.from(t)}get rawTxUint8Array(){let t=this.getRawTxBytes();return t==null?void 0:Uint8Array.from(t)}getRawTxBytes(){return this._tx!=null?(this._rawTx==null?this._rawTx=this._tx.toUint8Array():this.syncRawTxFromTransaction(),this._rawTx):this._rawTx}syncRawTxFromTransaction(){if(this._tx==null)return!1;let t=Jp(this._tx);if(this._rawTx!=null)return t===this._rawTx?!1:(this._rawTx=t,this._txid=this._tx.id("hex"),this.updateInputTxids(),!0);let e=this._tx.id("hex"),i=this._txid!=null&&this._txid!==e,r=this.inputTxids;return this._txid=e,this.updateInputTxids(),i||!hy(r,this.inputTxids)}static fromTx(t,e){return new n(t,e)}static fromRawTx(t,e){return new n(t,e)}static fromTxid(t,e){return new n(t,e)}updateInputTxids(){if(this.hasProof)this.inputTxids=[];else if(this._tx!=null){let t=new Set;for(let e of this._tx.inputs)e.sourceTXID!==void 0&&e.sourceTXID!==null&&e.sourceTXID!==""&&t.add(e.sourceTXID);this.inputTxids=Array.from(t)}else this._rawTx!=null?this.inputTxids=ly(this._rawTx):this.inputTxids=[]}toWriter(t,e){let i=c=>{t.writeUInt8(c)},r=()=>{if(this._txid==null)throw new Error("Transaction ID (_txid) is undefined");t.writeReverse(at(this._txid,"hex"))},s=()=>{let c=this.getRawTxBytes();if(c==null)throw new Error("a valid serialized Transaction is expected");t.write(c)},o=()=>{this.bumpIndex===void 0?i(ze.RAWTX):(i(ze.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex))};e===4022206466?this.isTxidOnly?(i(ze.TXID_ONLY),r()):this.bumpIndex!==void 0?(i(ze.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex),s()):(i(ze.RAWTX),s()):(s(),o())}static fromReader(t,e){let i,r;if(e===4022206466){let s=t.readUInt8();if(s===ze.TXID_ONLY)r=n.fromTxid(nt(t.readReverse(32)));else{s===ze.RAWTX_AND_BUMP_INDEX&&(i=t.readVarIntNumStrict(!1));let{rawTx:o,inputTxids:c}=Nf(t);r=new n(o,i,c,!0)}}else{let{rawTx:s,inputTxids:o}=Nf(t);i=t.readUInt8()===0?void 0:t.readVarIntNumStrict(!1),r=new n(s,i,o,!0)}return r}};function py(n,t,e,i){if(t.path.length!==e)throw new Error("Mismatched roots");for(let r=0;r<e;r++)gy(n[r],t.path[r],i)}function gy(n,t,e){for(let i of t){let r=n.get(i.offset);if(r==null){n.set(i.offset,i);continue}my(r,i,e)}}function my(n,t,e){if(e&&(n.hash!==t.hash||n.duplicate!==t.duplicate))throw new Error("Mismatched roots");t.txid!=null&&(n.txid=!0)}function t0(n,t,e){for(let i of n.path[0])typeof i.hash=="string"&&e.set(i.hash,t)}var Bn,_n,Cn,Jn,je,Qn,wr,ns,yr,is,rs,ss,xr,Sr,Ln,De,Un,P,Qr,Ga,_f,Cf,Ya,e0,n0,i0,r0,Rn,s0,Nn,o0,a0,Po,c0,Lf,Uf,Mf,u0,Ro,No,Za,br,ts,Df,Ja,f0,Hf,d0,l0,h0,Bo,p0,g0,Qa,m0,b0,$f,w0,y0,x0,S0,I0,v0,A0,es,qf,E0,tc,k0,T0,O0,P0,R0,N0,B0,_0,wn=class wn{constructor(t=4022206466){G(this,P);b(this,"bumps",[]);b(this,"txs",[]);b(this,"version",4022206466);b(this,"atomicTxid");G(this,Bn);G(this,_n);G(this,Cn);G(this,Jn);G(this,je);G(this,Qn);G(this,wr,new Map);G(this,ns);G(this,yr);G(this,is);G(this,rs);G(this,ss);G(this,xr);G(this,Sr);G(this,Ln,!0);G(this,De);G(this,Un);this.version=t}synchronizeNestedTransactionMutations(){let t=!1;for(let e of this.txs)t=e.syncRawTxFromTransaction()||t;t&&(a(this,P,Qr).call(this),N(this,De,void 0),N(this,Un,void 0),N(this,Ln,!0),a(this,P,br).call(this))}isAtomic(t=this.atomicTxid??""){if(this.synchronizeNestedTransactionMutations(),a(this,P,Rn).call(this),t.length===0)return!1;let e=a(this,P,No).call(this);if(e.size!==this.txs.length)return!1;let i=e.get(t);return i==null?!1:a(this,P,Uf).call(this,i,e).size===this.txs.length}findTxid(t){return this.synchronizeNestedTransactionMutations(),a(this,P,Ro).call(this,t)}makeTxidOnly(t){let e=a(this,P,Za).call(this).get(t);if(e===void 0)return;let i=this.txs[e];return i.isTxidOnly||(i=Xe.fromTxid(t),this.txs[e]=i,a(this,P,ts).call(this,i,e),a(this,P,es).call(this,i),a(this,P,Nn).call(this,!0)),i}findBump(t){a(this,P,Rn).call(this);let e=a(this,P,Ja).call(this).get(t);return e===void 0?void 0:this.bumps[e]}findTransactionForSigning(t){let e=this.findTxid(t);if(e?.tx!=null){for(let i of e.tx.inputs)if(i.sourceTransaction==null){let r=a(this,P,Ro).call(this,sr(i.sourceTXID,"sourceTXID must be valid"));r!=null&&(i.sourceTransaction=r.tx)}return e.tx}}findAtomicTransaction(t){let e=this.findTxid(t);if(e?.tx!=null)return a(this,P,d0).call(this,e.tx),e.tx}mergeBump(t){return this.synchronizeNestedTransactionMutations(),a(this,P,Rn).call(this),a(this,P,Nn).call(this,!1),a(this,P,Bo).call(this,t)}mergeProvenTxs(t){if(t.length===0)return[];this.synchronizeNestedTransactionMutations(),a(this,P,Rn).call(this),a(this,P,Nn).call(this,!0);let e=[];for(let s of t)e.push(a(this,P,Qa).call(this,s.rawTx));let i=new Map;for(let s of t){let o=s.merklePath.blockHeight;i.set(o,(i.get(o)??0)+1)}let r=new Map;for(let s=0;s<t.length;s++){let o=t[s].merklePath,c=t[s].merkleRoot,u=i.get(o.blockHeight)===1?`${o.blockHeight}:single:${s}`:`${o.blockHeight}:${c??o.computeRoot()}`,f=r.get(u);f==null?r.set(u,{first:s,paths:[o],validateCombined:c!=null}):(f.paths.push(o),f.validateCombined=f.validateCombined||c!=null)}for(let s of[...r.values()].sort((o,c)=>o.first-c.first))a(this,P,Bo).call(this,a(this,P,h0).call(this,s.paths,s.validateCombined));return e}mergeRawTx(t,e){return this.synchronizeNestedTransactionMutations(),a(this,P,Nn).call(this,!0),a(this,P,Qa).call(this,t,e)}mergeTransaction(t){return this.synchronizeNestedTransactionMutations(),a(this,P,Nn).call(this,!0),a(this,P,$f).call(this,t)}removeExistingTxid(t){let e=a(this,P,Za).call(this).get(t);e!==void 0&&(this.txs.splice(e,1),a(this,P,br).call(this),a(this,P,Nn).call(this,!0))}mergeTxidOnly(t){let e=this.findTxid(t);return e==null&&(e=new Xe(t),this.txs.push(e),a(this,P,ts).call(this,e),a(this,P,es).call(this,e),a(this,P,Nn).call(this,!0)),e}mergeBeefTx(t){let e=this.findTxid(t.txid);if(t.isTxidOnly&&e==null?e=this.mergeTxidOnly(t.txid):t._tx!=null&&(e==null||e.isTxidOnly)?e=this.mergeTransaction(t._tx):t._rawTx!=null&&(e==null||e.isTxidOnly)&&(e=this.mergeRawTx(t._rawTx)),e==null)throw new Error(`Failed to merge BeefTx for txid: ${t.txid}`);return e}mergeBeef(t){let e=wn.fromBinaryStrict(t instanceof wn?t.toBinary():t);this.synchronizeNestedTransactionMutations(),a(this,P,Rn).call(this),a(this,P,Nn).call(this,!0);for(let i of e.bumps)a(this,P,Bo).call(this,i);for(let i of e.txs)a(this,P,w0).call(this,i)}isValid(t){return this.verifyValid(t).valid}async verify(t,e){let i=this.verifyValid(e);if(!i.valid)return!1;for(let r of Object.keys(i.roots))if(await t.isValidRootForHeight(i.roots[r],Number(r))!==!0)return!1;return!0}verifyValid(t){a(this,P,Rn).call(this);let e={valid:!1,roots:{}};if(this.atomicTxid!=null&&!this.isAtomic(this.atomicTxid))return e;let i=this.sortTxs();if(a(this,P,y0).call(this)||i.missingInputs.length>0||i.notValid.length>0||i.txidOnly.length>0&&t!==!0||i.withMissingInputs.length>0)return e;let r={};return!a(this,P,x0).call(this,r,t)||!a(this,P,S0).call(this,r,e)||!a(this,P,I0).call(this)||!a(this,P,v0).call(this,r)||(e.valid=!0),e}toWriter(t){t.writeUInt32LE(this.version),t.writeVarIntNum(this.bumps.length);for(let e of this.bumps)t.write(t instanceof ht?e.toBinaryUint8Array():e.toBinary());t.writeVarIntNum(this.txs.length);for(let e of this.txs)e.toWriter(t,this.version)}toBinary(){return Array.from(a(this,P,Po).call(this))}toUint8Array(){return new Uint8Array(a(this,P,Po).call(this))}toBinaryAtomic(t){return Array.from(a(this,P,Lf).call(this,t))}toUint8ArrayAtomic(t){return new Uint8Array(a(this,P,Lf).call(this,t))}toHex(){let t=a(this,P,Po).call(this);if(y(this,Qn)!=null)return y(this,Qn);let e=nt(t);return N(this,Qn,e),e}static fromReader(t){var f;let e=t.pos,i=t.readUInt32LE(),r,s=e;if(i===16843009&&(r=nt(t.readReverse(32)),s=t.pos,i=t.readUInt32LE()),i!==4022206465&&i!==4022206466)throw new Error(`Serialized BEEF must start with ${4022206465} or ${4022206466} but starts with ${i}`);let o=new wn(i),c=t.readVarIntNumStrict(!1);for(let d=0;d<c;d++){let l=Ei.fromReader(t,!1);o.bumps.push(l)}let u=t.readVarIntNumStrict(!1);for(let d=0;d<u;d++){let l=Xe.fromReader(t,i);o.txs.push(l)}return o.atomicTxid=r,t instanceof bt&&(N(o,je,t.bin.subarray(s,t.pos)),a(f=o,P,Ga).call(f)),o}static fromBinary(t){return wn.fromReader(new bt(Uint8Array.from(t)))}static fromBinaryStrict(t){return wn.fromBinaryView(Uint8Array.from(t))}static fromBinaryView(t){let e=new bt(t),i=wn.fromReader(e);if(!e.eof())throw new Error("Serialized BEEF contains trailing data");return i}static fromString(t,e="hex"){let i=et(t,e);return wn.fromBinaryStrict(i)}sortTxs(){if(this.synchronizeNestedTransactionMutations(),a(this,P,Rn).call(this),y(this,De)!=null&&a(this,P,E0).call(this))return a(this,P,tc).call(this,y(this,De));N(this,De,void 0),N(this,Un,void 0);let t={},e={},i=[],r=[],s=this.partitionTxs(e,t,i,r),{txsMissingInputs:o,missingInputs:c,remaining:u}=a(this,P,k0).call(this,s,e);s=u;let f=a(this,P,T0).call(this,s,t,i);this.txs=o.concat(f).concat(r).concat(i),N(this,Ln,!1),a(this,P,Qr).call(this),a(this,P,br).call(this);let d={missingInputs:Object.keys(c),notValid:f.map(l=>l.txid),valid:Object.keys(t),withMissingInputs:o.map(l=>l.txid),txidOnly:r.map(l=>l.txid)};return N(this,De,d),a(this,P,qf).call(this),a(this,P,tc).call(this,d)}partitionTxs(t,e,i,r){let s=[];for(let o of this.txs)t[o.txid]=o,o.isValid=o.hasProof,o.isValid?(e[o.txid]=!0,i.push(o)):o.isTxidOnly&&o.inputTxids.length===0?(e[o.txid]=!0,r.push(o)):s.push(o);return s}clone(){var e,i;let t=new wn;return t.version=this.version,t.bumps=Array.from(this.bumps),t.txs=Array.from(this.txs),N(t,Bn,void 0),N(t,_n,void 0),N(t,Cn,void 0),N(t,Jn,void 0),N(t,Ln,y(this,Ln)),N(t,De,y(this,De)==null?void 0:a(this,P,tc).call(this,y(this,De))),y(t,De)!=null&&a(e=t,P,qf).call(e),N(t,Qn,y(this,Qn)),N(t,je,y(this,je)),y(t,je)!=null&&a(i=t,P,Ga).call(i),t}trimKnownTxids(t){let e=a(this,P,N0).call(this,new Set(t));e=a(this,P,B0).call(this)||e,e&&a(this,P,Nn).call(this,!0)}getValidTxids(){return this.sortTxs().valid}toLogString(){let t="";t+=`BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}
|
|
9
9
|
`;let e=-1;for(let i of this.bumps)e++,t+=` BUMP ${e}
|
|
10
10
|
block: ${i.blockHeight}
|
|
11
11
|
txids: [
|
|
@@ -21,7 +21,7 @@ ${i.path[0].filter(r=>r.txid===!0).map(r=>` '${r.hash??""}'`).join(`,
|
|
|
21
21
|
`);t+=` inputs: [
|
|
22
22
|
${r}
|
|
23
23
|
]
|
|
24
|
-
`}return t}addComputedLeaves(){for(let t of this.bumps)for(let e=1;e<t.path.length;e++)a(this,O,k0).call(this,t,e)}};Bn=new WeakMap,_n=new WeakMap,Cn=new WeakMap,Zn=new WeakMap,je=new WeakMap,Jn=new WeakMap,gr=new WeakMap,es=new WeakMap,br=new WeakMap,ns=new WeakMap,is=new WeakMap,rs=new WeakMap,mr=new WeakMap,yr=new WeakMap,Ln=new WeakMap,De=new WeakMap,Un=new WeakMap,O=new WeakSet,Jr=function(){N(this,je,void 0),N(this,Jn,void 0),y(this,gr).clear(),N(this,es,void 0),N(this,br,void 0),N(this,ns,void 0),N(this,is,void 0),N(this,rs,void 0),N(this,mr,void 0)},za=function(){N(this,is,this.version),N(this,rs,a(this,O,Rf).call(this)),N(this,mr,Array.from(this.bumps)),a(this,O,Xa).call(this)},Rf=function(){return this.txs.map(t=>({ref:t,bumpIndex:t._bumpIndex,rawTx:t._rawTx,tx:t._rawTx==null?t._tx:void 0,txid:t._rawTx==null&&t._tx==null?t._txid:void 0}))},Nf=function(t){if(t?.length!==this.txs.length)return!1;for(let e=0;e<this.txs.length;e++){let i=this.txs[e],r=t[e];if(r.ref!==i||r.bumpIndex!==i._bumpIndex||r.rawTx!==i._rawTx||r.tx!==(i._rawTx==null?i._tx:void 0)||r.txid!==(i._rawTx==null&&i._tx==null?i._txid:void 0))return!1}return!0},Xa=function(){N(this,yr,this.bumps.map(t=>({ref:t,blockHeight:t.blockHeight,levels:t.path.map(e=>({ref:e,leaves:e.map(i=>({ref:i,offset:i.offset,hash:i.hash,txid:i.txid,duplicate:i.duplicate}))}))})))},jp=function(t,e){return e.ref===t&&e.offset===t.offset&&e.hash===t.hash&&e.txid===t.txid&&e.duplicate===t.duplicate},Gp=function(t,e){return e.ref===t&&e.leaves.length===t.length&&t.every((i,r)=>a(this,O,jp).call(this,i,e.leaves[r]))},Yp=function(t,e){return e.ref===t&&e.blockHeight===t.blockHeight&&e.levels.length===t.path.length&&t.path.every((i,r)=>a(this,O,Gp).call(this,i,e.levels[r]))},Zp=function(){return y(this,yr)?.length!==this.bumps.length?!1:this.bumps.every((t,e)=>a(this,O,Yp).call(this,t,y(this,yr)[e]))},Rn=function(){if(y(this,yr)==null){a(this,O,Xa).call(this);return}a(this,O,Zp).call(this)||(a(this,O,Jr).call(this),N(this,De,void 0),N(this,Un,void 0),N(this,Ln,!0),a(this,O,Uf).call(this),a(this,O,Xa).call(this))},Jp=function(){if(y(this,je)==null||y(this,is)!==this.version||!a(this,O,Nf).call(this,y(this,rs))||y(this,mr)?.length!==this.bumps.length)return!1;for(let t=0;t<this.bumps.length;t++)if(y(this,mr)[t]!==this.bumps[t])return!1;return!0},Nn=function(t=!0){a(this,O,Jr).call(this),N(this,De,void 0),N(this,Un,void 0),t&&N(this,Ln,!0)},Qp=function(){for(let t of this.txs)t.txid},t0=function(){y(this,Ln)&&this.sortTxs()},Oo=function(){if(this.synchronizeNestedTransactionMutations(),a(this,O,Rn).call(this),a(this,O,Jp).call(this)&&y(this,je)!=null)return y(this,je);a(this,O,Jr).call(this),a(this,O,Qp).call(this),a(this,O,t0).call(this);let t=new ht;return this.toWriter(t),N(this,je,t.toUint8Array()),a(this,O,za).call(this),y(this,je)},e0=function(t){let e=a(this,O,Ro).call(this),i=e.get(t);if(i==null)throw new Error(`${t} does not exist in this Beef`);let r=a(this,O,_f).call(this,i,e),s=a(this,O,n0).call(this,r);return s.sortTxs(),s},Bf=function(t){var u;this.synchronizeNestedTransactionMutations(),a(this,O,Rn).call(this),y(this,ns)===this.version&&a(this,O,Nf).call(this,y(this,es))&&y(this,br)?.length===this.bumps.length&&this.bumps.every((f,d)=>y(this,br)?.[d]===f)||y(this,gr).clear();let i=y(this,gr).get(t);if(i!=null)return i;let r=a(u=a(this,O,e0).call(this,t),O,Oo).call(u),s=et(t,"hex"),o=new Uint8Array(4+s.length+r.length);new DataView(o.buffer).setUint32(0,16843009,!0);for(let f=0;f<s.length;f++)o[4+f]=s[s.length-1-f];return o.set(r,4+s.length),y(this,gr).set(t,o),N(this,es,a(this,O,Rf).call(this)),N(this,br,Array.from(this.bumps)),N(this,ns,this.version),o},_f=function(t,e){let i=new Set,r=[t];for(;r.length>0;){let s=r.pop();if(!(s==null||i.has(s))&&(i.add(s),!(a(this,O,Cf).call(this,s)||s.isTxidOnly)))for(let o of s.inputTxids){let c=e.get(o);c!=null&&r.push(c)}}return i},Cf=function(t){let e=t.bumpIndex;return e==null||!Number.isSafeInteger(e)||e<0||e>=this.bumps.length?!1:this.bumps[e]?.path[0]?.some(i=>i.hash===t.txid)??!1},n0=function(t){let e=new yn(this.version),i=new Map;for(let r of this.txs)!t.has(r)||!a(this,O,Cf).call(this,r)||r.bumpIndex==null||i.has(r.bumpIndex)||(i.set(r.bumpIndex,e.bumps.length),e.bumps.push(this.bumps[r.bumpIndex]));for(let r of this.txs){if(!t.has(r))continue;let s=r.bumpIndex==null?void 0:i.get(r.bumpIndex),o;r._rawTx!=null?o=new Xe(r._rawTx,s,Array.from(r.inputTxids)):r._tx!=null?o=Xe.fromTx(r._tx,s):o=Xe.fromTxid(r.txid,s),e.txs.push(o)}return e},Po=function(t){return a(this,O,Ro).call(this).get(t)},Ro=function(){return(y(this,Bn)==null||y(this,_n)==null)&&a(this,O,pr).call(this),y(this,Bn)},ja=function(){return(y(this,_n)==null||y(this,Bn)==null)&&a(this,O,pr).call(this),y(this,_n)},pr=function(){N(this,Bn,new Map),N(this,_n,new Map);for(let t=0;t<this.txs.length;t++){let e=this.txs[t];y(this,Bn).set(e.txid,e),y(this,_n).set(e.txid,t)}},Qr=function(t,e=this.txs.length-1){y(this,Bn)?.set(t.txid,t),y(this,_n)?.set(t.txid,e)},Lf=function(t){let e=a(this,O,ja).call(this).get(t.txid);e===void 0?(this.txs.push(t),a(this,O,Qr).call(this,t)):(this.txs[e]=t,a(this,O,Qr).call(this,t,e))},Ga=function(){if(y(this,Zn)==null){N(this,Zn,new Map);for(let t=0;t<this.bumps.length;t++)for(let e of this.bumps[t].path[0])typeof e.hash=="string"&&y(this,Zn).set(e.hash,t)}return y(this,Zn)},i0=function(){if(y(this,Cn)==null){N(this,Cn,new Map);for(let t=0;t<this.bumps.length;t++){let e=this.bumps[t],i=y(this,Cn).get(e.blockHeight)??[];i.push(t),y(this,Cn).set(e.blockHeight,i)}}return y(this,Cn)},Uf=function(){N(this,Cn,void 0),N(this,Zn,void 0)},r0=function(t){let e=new Set,i=[t];for(;i.length>0;){let r=i.pop();if(r==null)continue;let s=r.id("hex");if(e.has(s))continue;e.add(s);let o=this.findBump(s);if(o!=null){r.merklePath=o;continue}for(let c of r.inputs)a(this,O,s0).call(this,c),c.sourceTransaction!=null&&i.push(c.sourceTransaction)}},s0=function(t){if(t.sourceTransaction==null){let e=a(this,O,Po).call(this,nr(t.sourceTXID,"sourceTXID must be valid"));e!=null&&(t.sourceTransaction=e.tx)}},o0=function(t,e=!1){let i=t[0];if(t.length===1&&!e)return i;let r=i.path.map(o=>new Map(o.map(c=>[c.offset,c])));for(let o=1;o<t.length;o++)nw(r,t[o],i.path.length,e);let s=r.map(o=>[...o.values()]);if(e){let o=new Ai(i.blockHeight,s);return o.trim(),o}return i.path=s,i.trim(),i},No=function(t){let e=a(this,O,a0).call(this,t),i=this.bumps[e],r=a(this,O,Ro).call(this);for(let s of i.path[0]){if(typeof s.hash!="string")continue;let o=r.get(s.hash);o!=null&&o.bumpIndex==null&&a(this,O,c0).call(this,o,i,e)}return e},a0=function(t){let e=a(this,O,i0).call(this),i=a(this,O,Ga).call(this),r=e.get(t.blockHeight)??[];if(r.length>0){let o=t.computeRoot();for(let c of r)if(this.bumps[c].computeRoot()===o)return this.bumps[c].combine(t),Xp(this.bumps[c],c,i),c}this.bumps.push(t);let s=this.bumps.length-1;return r.push(s),e.set(t.blockHeight,r),Xp(t,s,i),s},c0=function(t,e,i){let r=t.txid;for(let s of e.path[0])if(s.hash===r){t.bumpIndex=i,s.txid=!0;break}},Ya=function(t,e){let i=new Xe(t,e);return a(this,O,Lf).call(this,i),a(this,O,ts).call(this,i),i},u0=function(t){let e=t.merklePath==null?void 0:a(this,O,No).call(this,t.merklePath),i=new Xe(t,e);return a(this,O,Lf).call(this,i),a(this,O,ts).call(this,i),i},f0=function(t,e){for(let i=t.inputs.length-1;i>=0;i--){let r=t.inputs[i].sourceTransaction;r!=null&&e.push(r)}},Mf=function(t){t.materializeSourceTXIDs();let e=t.id("hex"),i=new Set,r=[t],s;for(;r.length>0;){let o=r.pop();if(o==null)continue;let c=o.id("hex");if(i.has(c))continue;i.add(c);let u=a(this,O,u0).call(this,o);c===e&&(s=u),u.bumpIndex===void 0&&a(this,O,f0).call(this,o,r)}if(s==null)throw new Error("Failed to merge root transaction");return s},d0=function(t){let e=a(this,O,Po).call(this,t.txid);if(t.isTxidOnly&&e==null?(e=Xe.fromTxid(t.txid),this.txs.push(e),a(this,O,Qr).call(this,e),a(this,O,ts).call(this,e)):t._tx!=null&&(e==null||e.isTxidOnly)?e=a(this,O,Mf).call(this,t._tx):t._rawTx!=null&&(e==null||e.isTxidOnly)&&(e=a(this,O,Ya).call(this,t._rawTx)),e==null)throw new Error(`Failed to merge BeefTx for txid: ${t.txid}`);return e},l0=function(){let t=new Set;for(let e of this.txs){if(t.has(e.txid))return!0;t.add(e.txid)}return!1},h0=function(t,e){for(let i of this.txs)if(i.isTxidOnly){if(e!==!0)return!1;t[i.txid]=!0}return!0},p0=function(t,e){for(let i of this.bumps)for(let r of i.path[0])if(!(r.txid!==!0||typeof r.hash!="string"||r.hash.length===0)&&(t[r.hash]=!0,!a(this,O,m0).call(this,i,r.hash,e)))return!1;return!0},g0=function(){for(let t of this.txs){if(t.bumpIndex===void 0)continue;if(!Number.isSafeInteger(t.bumpIndex)||t.bumpIndex<0||t.bumpIndex>=this.bumps.length||this.bumps[t.bumpIndex]?.path[0]?.find(i=>i.hash===t.txid)==null)return!1}return!0},b0=function(t){for(let e of this.txs){for(let i of e.inputTxids)if(!t[i])return!1;t[e.txid]=!0}return!0},m0=function(t,e,i){let r=t.computeRoot(e);return(i.roots[t.blockHeight]===void 0||i.roots[t.blockHeight]==="")&&(i.roots[t.blockHeight]=r),i.roots[t.blockHeight]===r},ts=function(t){if(t.bumpIndex!==void 0)return!0;let e=t.txid,i=a(this,O,Ga).call(this).get(e);if(i===void 0)return!1;t.bumpIndex=i;let r=this.bumps[i].path[0].find(s=>s.hash===e);return r!=null&&(r.txid=!0),!0},Df=function(){N(this,Un,this.txs.map(t=>({ref:t,txid:t.txid,bumpIndex:t.bumpIndex,isTxidOnly:t.isTxidOnly,inputTxids:[...t.inputTxids]})))},y0=function(){if(y(this,Un)?.length!==this.txs.length)return!1;for(let t=0;t<this.txs.length;t++){let e=this.txs[t],i=y(this,Un)[t];if(i.ref!==e||i.txid!==e.txid||i.bumpIndex!==e.bumpIndex||i.isTxidOnly!==e.isTxidOnly||i.inputTxids.length!==e.inputTxids.length)return!1;for(let r=0;r<e.inputTxids.length;r++)if(i.inputTxids[r]!==e.inputTxids[r])return!1}return!0},Za=function(t){return{missingInputs:[...t.missingInputs],notValid:[...t.notValid],valid:[...t.valid],withMissingInputs:[...t.withMissingInputs],txidOnly:[...t.txidOnly]}},w0=function(t,e){let i={},r=[],s=[];for(let o of t){let c=!1;for(let u of o.inputTxids)e[u]===void 0&&(i[u]=!0,c=!0);c?r.push(o):s.push(o)}return{txsMissingInputs:r,missingInputs:i,remaining:s}},x0=function(t,e,i){let{indegree:r,dependents:s,originalIndex:o,round:c}=a(this,O,I0).call(this,t,e),u=a(this,O,S0).call(this,t,r,s,o,c);return a(this,O,v0).call(this,t,u,c,e,i),t.filter(f=>!u.has(f.txid))},I0=function(t,e){let i=new Set(t.map(u=>u.txid)),r=new Map,s=new Map,o=new Map(t.map((u,f)=>[u.txid,f])),c=new Map;for(let u of t){let f=0;for(let d of u.inputTxids)if(!e[d]&&(f++,i.has(d))){let l=s.get(d)??[];l.push(u),s.set(d,l)}r.set(u.txid,f),c.set(u.txid,0)}return{indegree:r,dependents:s,originalIndex:o,round:c}},S0=function(t,e,i,r,s){let o=t.filter(u=>e.get(u.txid)===0),c=new Set;for(let u of o)if(!c.has(u.txid)){c.add(u.txid);for(let f of i.get(u.txid)??[]){let d=(s.get(u.txid)??0)+((r.get(u.txid)??0)>(r.get(f.txid)??0)?1:0);s.set(f.txid,Math.max(s.get(f.txid)??0,d));let l=(e.get(f.txid)??0)-1;e.set(f.txid,l),l===0&&o.push(f)}}return c},v0=function(t,e,i,r,s){let o=[];for(let c of t){if(!e.has(c.txid))continue;let u=i.get(c.txid)??0,f=o[u]??[];f.push(c),o[u]=f}for(let c of o)for(let u of c??[])r[u.txid]=!0,s.push(u)},A0=function(t){let e=this.txs.length;this.txs=this.txs.filter(r=>!(r.isTxidOnly&&t.has(r.txid)));let i=this.txs.length!==e;return i&&a(this,O,pr).call(this),i},E0=function(){let t=new Set;for(let r of this.txs)r.bumpIndex!==void 0&&t.add(r.bumpIndex);if(t.size>=this.bumps.length)return!1;let e=new Map,i=0;for(let r=0;r<this.bumps.length;r++)t.has(r)&&(e.set(r,i),i++);this.bumps=this.bumps.filter((r,s)=>t.has(s));for(let r of this.txs){if(r.bumpIndex===void 0)continue;let s=e.get(r.bumpIndex);if(s===void 0)throw new Error(`Internal error: bumpIndex ${r.bumpIndex} not found in indexMap`);r.bumpIndex=s}return a(this,O,Uf).call(this),!0},k0=function(t,e){let i=r=>nt(zt(at(r,"hex").reverse()).reverse());for(let r of t.path[e-1]){if(typeof r.hash!="string"||(r.offset&1)!==0)continue;let s=t.path[e-1].find(c=>c.offset===r.offset+1);if(s===void 0||typeof s.hash!="string")continue;let o=r.offset>>1;t.path[e].every(c=>c.offset!==o)&&t.path[e].push({offset:o,hash:i(s.hash+r.hash)})}};var wr=yn,T0=wr;var as=256*1024*1024,M0=21e14,sw=64,Hf=1e6,cs=Array.isArray,rn=Array,jf=Number,Gf=String,ow=Number.isFinite,aw=Number.isInteger,cw=Number.isSafeInteger,D0=Object.is,Lo=Object.create,uw=Object.defineProperty,$t=Object.getOwnPropertyDescriptor,O0=Object.getOwnPropertyDescriptors,Yf=Object.getPrototypeOf,Co=Object.keys,Zt=Reflect.apply,Mo=Reflect.ownKeys,fw=RegExp.prototype.exec,dw=RegExp.prototype.test,lw=String.prototype.toLowerCase,H0=Uint8Array,Zf=Uint8Array.prototype,ic=Yf(Zf),P0=$t(ic,"buffer")?.get,tc=$t(ic,"length")?.get,R0=$t(ic,Symbol.toStringTag)?.get,hw=Zf.set,N0=typeof SharedArrayBuffer>"u"?void 0:$t(SharedArrayBuffer.prototype,"byteLength")?.get,pw=WeakMap.prototype.get,gw=WeakMap.prototype.set,qf=WeakSet.prototype.add,bw=WeakSet.prototype.delete,$0=WeakSet.prototype.has,Ff=new WeakSet,mw=ge.prototype.toHex,Wf,Vf,Kf,q0=/^(?:0|[1-9]\d*)$/,yw=/^([0-9a-f]{64})\.(0|[1-9]\d*)$/i,ww=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,xw=/^(?:[0-9a-f]{2})*$/i,Iw=/^[0-9a-f]{64}$/i;function Sw(){let n=[Array.prototype,Map.prototype,Set.prototype,WeakMap.prototype,WeakSet.prototype,Object,Object.prototype,Number,RegExp.prototype,String.prototype,Zf,ic],t=new rn(n.length);for(let e=0;e<n.length;e++){let i=n[e],r=Mo(i),s=new rn(r.length);for(let o=0;o<r.length;o++)s[o]=$t(i,r[o]);t[e]={owner:i,keys:r,descriptors:s}}return t}function _o(n){for(let t=0;t<n.length;t++){let e=n[t];if(Mo(e.owner).length!==e.keys.length)throw new Error("Wallet callback modified shared JavaScript intrinsics");for(let i=0;i<e.keys.length;i++){let r=e.descriptors[i],s=$t(e.owner,e.keys[i]);if(s==null||s.configurable!==r.configurable||s.enumerable!==r.enumerable||s.writable!==r.writable||!D0(s.value,r.value)||s.get!==r.get||s.set!==r.set)throw new Error(`Wallet callback modified shared JavaScript intrinsics (${t}:${Gf(e.keys[i])})`)}}}function ec(n,t){return $t(n,t)!==void 0}function ki(n){return cw(n)}function Uo(n,t){return Zt(dw,n,[t])}function Ir(n){return Zt(lw,n,[])}function us(n){return Zt(mw,n,[])}function vw(){Wf??(Wf=Me.fromAtomicBEEF),Vf??(Vf=Me.prototype.id),Kf??(Kf=Me.prototype.toAtomicBEEF)}function $f(n){if(Wf==null)throw new Error("Transaction intrinsics are unavailable");return Zt(Wf,Me,[n])}function Aw(n){if(Kf==null)throw new Error("Transaction intrinsics are unavailable");return Zt(Kf,n,[!0])}function F0(n){if(Vf==null)throw new Error("Transaction intrinsics are unavailable");return Zt(Vf,n,["hex"])}function B0(n,t){return Zt($0,n.active,[t])}function Ew(n,t){Zt(qf,n.active,[t])}function _0(n,t){Zt(bw,n.active,[t])}function kw(n,t){return Zt(pw,n.completed,[t])}function Ja(n,t,e){Zt(gw,n.completed,[t,e])}function Ei(n,t,e=!1){if(n==null||typeof n!="object"||cs(n))throw new Error(`${t} must be a plain data object`);let i=Yf(n);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain data object`);let r=Mo(n);for(let s=0;s<r.length;s++){let o=r[s],c=$t(n,o);if(typeof o=="symbol"&&e){if(c==null||!("value"in c))throw new Error(`${t} symbol metadata must be a data property`);continue}if(typeof o!="string"||c==null||!c.enumerable||!("value"in c))throw new Error(`${t} must contain only string-keyed data properties`)}return n}function W0(n,t,e=as){if(Yf(n)!==Array.prototype)throw new Error(`${t} must contain only dense data arrays`);let i=$t(n,"length");if(i==null||!("value"in i)||!ki(i.value)||i.value<0)throw new Error(`${t} must contain only dense data arrays`);let r=i.value;if(r>as)throw new Error(`${t} exceeds the byte limit`);if(Mo(n).length!==r+1)throw new Error(`${t} must contain only dense data arrays`);let o=r>e,c=o?void 0:new rn(r);for(let u=0;u<r;u++){let f=$t(n,Gf(u));if(f==null||!f.enumerable||!("value"in f))throw new Error(`${t} must contain only dense data arrays`);if(!aw(f.value)||f.value<0||f.value>255)return;c!==void 0&&(c[u]=f.value)}if(o)throw new Error(`${t} exceeds the aggregate byte limit`);return c}function V0(n,t,e=as){if(P0==null||tc==null||R0==null)return;let i,r,s;try{i=Zt(P0,n,[]),r=Zt(tc,n,[]),s=Zt(R0,n,[])}catch{return}if(s!=="Uint8Array")return;if(N0!=null){let c=!1;try{Zt(N0,i,[]),c=!0}catch{}if(c)throw new Error(`${t} must not use shared byte storage`)}if(r>as)throw new Error(`${t} exceeds the byte limit`);if(r>e)throw new Error(`${t} exceeds the aggregate byte limit`);let o=new H0(r);try{Zt(hw,o,[n])}catch{throw new Error(`${t} must contain only intrinsic byte arrays`)}return o}function xr(n,t,e=0,i={nodes:0,active:new WeakSet,completed:new WeakMap,copiedBytes:0},r=!1){if(e>sw)throw new Error(`${t} exceeds the depth limit`);if(i.nodes+=1,i.nodes>Hf)throw new Error(`${t} exceeds the node limit`);if(n==null||typeof n=="string"||typeof n=="boolean")return n;if(typeof n=="number"){if(!ow(n)||D0(n,-0))throw new Error(`${t} contains an ambiguous number`);return n}if(typeof n!="object")throw new Error(`${t} contains unsupported data`);if(B0(i,n))throw new Error(`${t} contains a cycle`);let s=kw(i,n);if(s!==void 0)return s;let o=V0(n,t,as-i.copiedBytes);if(o!==void 0)return i.copiedBytes+=o.length,Zt(qf,Ff,[o]),Ja(i,n,o),o;if(cs(n)){let l=W0(n,t,as-i.copiedBytes);if(l!==void 0)return i.copiedBytes+=l.length,Zt(qf,Ff,[l]),Ja(i,n,l),l;let p=$t(n,"length");if(p==null||!("value"in p)||!ki(p.value)||p.value<0)throw new Error(`${t} must contain only dense data arrays`);if(p.value>Hf)throw new Error(`${t} exceeds the node limit`)}if(Ew(i,n),cs(n)){let l=O0(n),p=l.length;if(p==null||!("value"in p)||!ki(p.value)||p.value<0||p.value>Hf)throw new Error(`${t} must contain only dense data arrays`);let b=p.value,g=Mo(l);if(g.length!==b+1)throw new Error(`${t} must contain only dense data arrays`);for(let S=0;S<g.length;S++){let C=g[S];if(C!=="length"&&(typeof C!="string"||!Uo(q0,C)||jf(C)>=b))throw new Error(`${t} must contain only dense data arrays`)}let w=new rn(b);for(let S=0;S<b;S++){let C=Gf(S),E=l[C];if(E==null||!E.enumerable||!("value"in E))throw new Error(`${t} must contain only dense data arrays`);w[S]=xr(E.value,`${t}[${S}]`,e+1,i)}return _0(i,n),Ja(i,n,w),w}let c=Ei(n,t,r);if(B0(i,c)&&c!==n)throw new Error(`${t} contains a cycle`);let u=Lo(null),f=O0(c),d=Co(f);for(let l=0;l<d.length;l++){let p=d[l],b=f[p];if(!b.enumerable||!("value"in b))throw new Error(`${t} must contain only string-keyed data properties`);uw(u,p,{value:xr(b.value,`${t}.${p}`,e+1,i),enumerable:!0,configurable:!0,writable:!0})}return _0(i,n),Ja(i,n,u),u}function C0(n,t){if(n!=null&&typeof n=="object"){let r=Zt($0,Ff,[n]);if(r&&cs(n)){let o=$t(n,"length")?.value;if(typeof o!="number"||o===0)throw new Error(`${t} must be a bounded non-empty byte array`);return n}if(r&&tc!=null){let o;try{o=Zt(tc,n,[])}catch{throw new Error(`${t} must be a bounded non-empty byte array`)}if(o===0)throw new Error(`${t} must be a bounded non-empty byte array`);return n}let s=V0(n,t);if(s!==void 0){if(s.length===0)throw new Error(`${t} must be a bounded non-empty byte array`);return s}}if(!cs(n))throw new Error(`${t} must be a bounded non-empty byte array`);let e=W0(n,t);if(e==null||e.length===0)throw new Error(`${t} must be a bounded non-empty byte array`);let i=new H0(e.length);for(let r=0;r<e.length;r++)i[r]=e[r];return i}function Qa(n,t){if(typeof n!="string"||!Uo(Iw,n))throw new Error(`${t} must be a 32-byte hexadecimal transaction ID`);return Ir(n)}function nc(n,t){if(typeof n!="string"||!Uo(xw,n))throw new Error(`${t} must be an even-length hexadecimal string`);return Ir(n)}function zf(n,t){if(typeof n!="string")throw new Error(`${t} must be a canonical outpoint`);let e=Zt(fw,yw,[n]);if(e==null)throw new Error(`${t} must be a canonical outpoint`);let i=jf(e[2]);if(!ki(i)||i>4294967295)throw new Error(`${t} must be a canonical outpoint`);return`${Ir(e[1])}.${i}`}function Xf(n,t){let e=n.inputs[t];if(e==null||!ki(e.sourceOutputIndex)||e.sourceOutputIndex<0||e.sourceOutputIndex>4294967295)throw new Error("Wallet transaction input is malformed");let i=e.sourceTransaction==null?void 0:F0(e.sourceTransaction);if(e.sourceTXID!==void 0&&i!==void 0&&Qa(e.sourceTXID,"Wallet input source TXID")!==Qa(i,"Wallet input source transaction ID"))throw new Error("Wallet transaction input source mismatch");return`${Qa(e.sourceTXID??i,"Wallet input source TXID")}.${e.sourceOutputIndex}`}function os(n,t){if(typeof n!="number"||!ki(n)||n<0||n>M0)throw new Error(`${t} must be a valid satoshi amount`);return n}function ss(n,t,e){let i=n+t;if(!ki(i)||i>M0)throw new Error(`${e} exceeds the maximum transaction value`);return i}function L0(n,t){let e=n.inputs[t],i=e?.sourceTransaction?.outputs[e.sourceOutputIndex];if(i==null)throw new Error("Wallet signable transaction omitted an input source output");return os(i.satoshis,`Wallet input ${t} source output`)}function Tw(n,t,e,i){if(t.version!==(n.version??1))throw new Error("Wallet transaction substituted the requested version");if(t.lockTime!==(n.lockTime??0))throw new Error("Wallet transaction substituted the requested lock time");let r=new rn(t.inputs.length),s=Lo(null);for(let A=0;A<t.inputs.length;A++){let k=Xf(t,A);if(ec(s,k))throw new Error("Wallet transaction contains a duplicate input outpoint");r[A]=k,s[k]=!0}let o=[],c=Lo(null);for(let A=0;A<(n.inputs?.length??0);A++){let k=n.inputs[A],B=zf(k.outpoint,`Requested input ${A} outpoint`);if(ec(c,B))throw new Error("Action requests the same input outpoint more than once");c[B]=!0;let _=-1;for(let R=0;R<r.length;R++)if(r[R]===B){if(_!==-1)throw new Error("Wallet transaction does not contain each requested input exactly once");_=R}if(_===-1)throw new Error("Wallet transaction does not contain each requested input exactly once");if(o[A]=_,(t.inputs[_].sequence??4294967295)!==(k.sequenceNumber??4294967295))throw new Error("Wallet transaction substituted a requested input sequence");let $=t.inputs[_].unlockingScript;if(k.unlockingScript!==void 0&&($==null?void 0:Ir(us($)))!==nc(k.unlockingScript,`Requested input ${A} unlocking script`))throw new Error("Wallet transaction substituted a requested unlocking script")}let u=new rn(t.outputs.length);for(let A=0;A<t.outputs.length;A++){let k=t.outputs[A];u[A]={satoshis:os(k.satoshis,`Wallet output ${A}`),lockingScript:Ir(us(k.lockingScript))}}let f=new rn(u.length),d=n.options?.randomizeOutputs===!1,l=0,p=(A,k)=>{let B=n.outputs[A],_=nc(B.lockingScript,`Requested output ${A} locking script`),$=os(B.satoshis,`Requested output ${A}`);if(d){let I=u[A],U=I!=null&&(k==null?I.satoshis===$:I.satoshis>=k.minimumSatoshis&&I.satoshis<=k.maximumSatoshis);if(I==null||I.lockingScript!==_||!U)throw new Error("Wallet transaction substituted a requested output position");f[A]=!0,l=ss(l,I.satoshis,"Requested output value");return}let R=-1;for(let I=0;I<u.length;I++){let U=u[I];if(!(f[I]===!0||U.lockingScript!==_||!(k==null?U.satoshis===$:U.satoshis>=k.minimumSatoshis&&U.satoshis<=k.maximumSatoshis))){if(k==null){R=I;break}if(R!==-1)throw new Error("Wallet transaction omitted or substituted a requested output");R=I}}if(R===-1)throw new Error("Wallet transaction omitted or substituted a requested output");f[R]=!0,l=ss(l,u[R].satoshis,"Requested output value")};for(let A=0;A<(n.outputs?.length??0);A++)e[A]===void 0&&p(A);for(let A=0;A<(n.outputs?.length??0);A++){let k=e[A];k!=null&&p(A,k)}let b=0,g=new rn(t.inputs.length);for(let A=0;A<o.length;A++){let k=o[A];g[k]=!0,b=ss(b,i?.[A]??L0(t,k),"Requested input value")}let w=0;for(let A=0;A<t.inputs.length;A++)g[A]!==!0&&(w=ss(w,L0(t,A),"Wallet-added input value"));let S=0;for(let A=0;A<u.length;A++)S=ss(S,u[A].satoshis,"Wallet output value");let C=ss(b,w,"Wallet input value");if(S>C)throw new Error("Wallet signable transaction spends more than its inputs");if(S-l>w)throw new Error("Wallet used a requested input to fund an unrequested output");return o}function U0(n,t){if(n.version!==t.version||n.lockTime!==t.lockTime||n.inputs.length!==t.inputs.length||n.outputs.length!==t.outputs.length)throw new Error("Wallet signed transaction substituted the authorized template");for(let e=0;e<n.inputs.length;e++)if(Xf(n,e)!==Xf(t,e)||(n.inputs[e].sequence??4294967295)!==(t.inputs[e].sequence??4294967295))throw new Error("Wallet signed transaction substituted an authorized input");for(let e=0;e<n.outputs.length;e++)if(n.outputs[e].satoshis!==t.outputs[e].satoshis||us(n.outputs[e].lockingScript)!==us(t.outputs[e].lockingScript))throw new Error("Wallet signed transaction substituted an authorized output")}async function Ow(n,t,e){try{await n.abortAction({reference:t},e)}catch{}}async function K0(n,t,e={},i,r){vw();let s=Sw(),o=xr(t,"Create action arguments"),c=xr(o,"Create action arguments"),u=o.inputs??[],f;if(r!==void 0){let I=xr(r,"Trusted requested input satoshis");if(!cs(I)||I.length!==u.length)throw new Error("Trusted requested input satoshis must match the requested inputs");let U=new rn(I.length);for(let M=0;M<I.length;M++)U[M]=os(I[M],`Trusted requested input ${M}`);f=U}let d=Ei(e,"Bound action options"),l=Co(d);for(let I=0;I<l.length;I++){let U=l[I];if(U!=="inputSigners"&&U!=="outputSatoshisRanges")throw new Error(`Unknown bound action option "${U}"`)}let p=$t(d,"inputSigners")?.value,b=Ei(p??{},"Input signers"),g=Lo(null),w=0,S=Co(b);for(let I=0;I<S.length;I++){let U=S[I],M=$t(b,U)?.value,F=zf(U,"Input signer outpoint");if(ec(g,F)||typeof M!="function")throw new Error("Input signers must uniquely identify requested outpoints");g[F]=M,w++}let C=$t(d,"outputSatoshisRanges")?.value,E=Ei(C??{},"Output satoshi ranges"),A=new rn(o.outputs?.length??0),k=Co(E);for(let I=0;I<k.length;I++){let U=k[I],M=$t(E,U)?.value;if(!Uo(q0,U))throw new Error("Output satoshi ranges must identify requested output indexes");let F=jf(U);if(!ki(F)||F>=(o.outputs?.length??0))throw new Error("Output satoshi ranges must identify requested output indexes");let it=Ei(M,`Output satoshi range ${F}`),ot=Co(it);for(let tt=0;tt<ot.length;tt++){let It=ot[tt];if(It!=="minimumSatoshis"&&It!=="maximumSatoshis")throw new Error(`Unknown output satoshi range option "${It}"`)}let q=os($t(it,"minimumSatoshis")?.value,`Output satoshi range ${F} minimum`),z=os($t(it,"maximumSatoshis")?.value,`Output satoshi range ${F} maximum`);if(q>z)throw new Error(`Output satoshi range ${F} minimum exceeds its maximum`);A[F]={minimumSatoshis:q,maximumSatoshis:z}}let B=await n.createAction({...c,options:{...c.options,signAndProcess:!1,returnTXIDOnly:!1}},i);_o(s);let _=Ei(xr(B,"Wallet createAction result",0,void 0,!0),"Wallet createAction result",!0);_o(s);let $=Ei($t(_,"signableTransaction")?.value,"Wallet signable transaction"),R=$t($,"reference")?.value;if(typeof R!="string"||R.length===0||R.length>4096||!Uo(ww,R))throw new Error("Wallet signable transaction reference is invalid");try{let I=$f(C0($t($,"tx")?.value,"Wallet signable transaction")),U=Tw(o,I,A,f),M=$f(Aw(I)),F={},it=new rn(I.inputs.length),ot=new rn,q=Lo(null),z=0;for(let ke=0;ke<u.length;ke++){let we=u[ke],vn=zf(we.outpoint,`Requested input ${ke} outpoint`),H=U[ke];if(we.unlockingScript!==void 0){it[H]=nc(we.unlockingScript,`Requested input ${ke} unlocking script`),ot[ot.length]=H;continue}let W=$t(g,vn)?.value;if(we.unlockingScriptLength===void 0||W==null)throw new Error(`Requested input ${ke} has no authorized signer`);let D=await W(I,H);_o(s),U0(M,I);let V=nc(typeof D=="string"?D:us(D),`Requested input ${ke} signed unlocking script`);F[H]={unlockingScript:V},it[H]=V,ot[ot.length]=H,ec(q,vn)||(q[vn]=!0,z++)}if(z!==w)throw new Error("An input signer does not match a requested signable input");let tt={acceptDelayedBroadcast:o.options?.acceptDelayedBroadcast,returnTXIDOnly:!1,noSend:o.options?.noSend,sendWith:o.options?.sendWith},It=await n.signAction({reference:R,spends:F,options:tt},i);_o(s);let ae=Ei(xr(It,"Wallet signAction result",0,void 0,!0),"Wallet signAction result",!0);_o(s);let Bt=$f(C0($t(ae,"tx")?.value,"Wallet signed transaction"));U0(I,Bt);for(let ke=0;ke<ot.length;ke++){let we=ot[ke],vn=it[we],H=Bt.inputs[we]?.unlockingScript;if(H==null||Ir(us(H))!==vn)throw new Error("Wallet signed transaction substituted an authorized unlocking script")}let dn=$t(ae,"txid")?.value;if(dn!==void 0&&Qa(dn,"Wallet signed transaction ID")!==Ir(F0(Bt)))throw new Error("Wallet signed transaction ID does not match its transaction data");return Bt}catch(I){throw await Ow(n,R,i),I}}var Do=class extends Error{constructor(e){super(`Transaction evidence: ${e}`);m(this,"code");this.code=e,this.name="TransactionEvidenceError"}};var II=Object.freeze({candidateBytes:1024*1024,retainedBytes:16*1024*1024,transactions:256,inputs:4096,scriptBytes:256*1024,scriptMemoryBytes:16*1024*1024,candidatesPerTransaction:8,pendingTransactions:32,concurrentTransactions:4,pendingChainCalls:8,consumers:128,cacheEntries:128,cacheAgeMs:6e4,attemptTimeoutMs:5e3,requestTimeoutMs:15e3});function z0(n){let t=n.tx,e=t.inputs.map(i=>{let r=i.sourceTransaction,s=r?.outputs[i.sourceOutputIndex];if(r===void 0||s===void 0)throw new Do("invalid-evidence");return[r.id("hex"),i.sourceOutputIndex,s.satoshis,s.lockingScript.toHex()]});return nt(Te(at(JSON.stringify([t.toHex(),e,n.blockHeight,n.consensus,n.verifyFlags,n.memoryLimit]),"utf8")))}var Pw=new WeakMap;function X0(n){return Pw.get(n)}function j0(n,t){return{supportsMemoryLimit:t.supportsMemoryLimit,shouldVerifyScripts:t.shouldVerifyScripts===void 0?void 0:e=>{n.check();let i=z0(e),r=t.shouldVerifyScripts(e);if(n.check(),z0(e)!==i)throw new Do("invalid-evidence");return r},verifyScripts:async e=>(await n.work.batch(n,[e],t))[0],verifyScriptsBatch:async e=>await n.work.batch(n,e,t)}}var G0=Symbol(),Y0=Symbol();function Kp(n){return n[G0]()}function zp(n,t){n[Y0](t)}var Rw=943816,Z0=21e14,Nw=1e6;function sn(n,t){if(typeof n!="number"||!Number.isSafeInteger(n)||n<0||n>Z0)throw new RangeError(`${t} must be a non-negative safe integer no greater than 21e14.`);return n}function fs(n,t,e){let i=n+t;if(!Number.isSafeInteger(i)||i>Z0)throw new RangeError(`${e} exceeds the maximum valid monetary range.`);return i}function Ge(n,t){if(typeof n!="number"||!Number.isInteger(n)||n<0||n>4294967295)throw new RangeError(`${t} must be an unsigned 32-bit integer.`);return n}function Ti(n,t){if(typeof n!="string"||!/^[0-9a-fA-F]{64}$/.test(n))throw new TypeError(`${t} must be a 32-byte hexadecimal transaction ID.`);return n.toLowerCase()}function Jf(n,t){if(n===void 0||t===void 0)return n===t;if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}var vr,Qn,Pi,Ar,Ri,$o,ds,j,J0,Q0,Mn,Ho,Qf,wn,td,rc,ed,tg,eg,ng,ig,rg,sg,og,Sr,ag,nd,cg,ug,fg,dg,sc,lg,hg,Oi,oc,pg,gg,bg,mg,yg,wg,xg,Ig,Sg,se=class se{constructor(t=1,e=[],i=[],r=0,s=new Map,o){G(this,j);m(this,"version");m(this,"inputs");m(this,"outputs");m(this,"lockTime");m(this,"metadata");m(this,"merklePath");G(this,vr);G(this,Qn);G(this,Pi);G(this,Ar);G(this,Ri);G(this,$o);G(this,ds);this.version=t,this.inputs=e,this.outputs=i,this.lockTime=r,this.metadata=s,this.merklePath=o}getSignatureHashCache(){return y(this,$o)??{hashOutputsSingle:new Map}}materializeSourceTXIDs(){let t=new Set,e=new Set,i=[{tx:this,expanded:!1}];for(;i.length>0;){let r=i.pop();if(r!=null&&!t.has(r.tx)){if(r.expanded){a(this,j,J0).call(this,r.tx,e,t);continue}a(this,j,Q0).call(this,r.tx,e,t,i)}}}static fromBEEF(t,e){var r;let{tx:i}=a(r=se,Mn,Ho).call(r,t,e);return i}static fromBEEFView(t,e){var r;let{tx:i}=a(r=se,Mn,Ho).call(r,t,e,!0);return i}static fromAtomicBEEF(t){var s;let{tx:e,txid:i,beef:r}=a(s=se,Mn,Ho).call(s,t);if(i!==r.atomicTxid)throw r.atomicTxid==null?new Error("beef must conform to BRC-95 and must contain the subject txid."):new Error(`Transaction with TXID ${r.atomicTxid} not found in BEEF data.`);if(!r.isAtomic(i))throw new Error("Atomic BEEF contains unrelated transaction data.");return e}static fromAtomicBEEFView(t){var s;let{tx:e,txid:i,beef:r}=a(s=se,Mn,Ho).call(s,t,void 0,!0);if(i!==r.atomicTxid)throw r.atomicTxid==null?new Error("beef must conform to BRC-95 and must contain the subject txid."):new Error(`Transaction with TXID ${r.atomicTxid} not found in BEEF data.`);if(!r.isAtomic(i))throw new Error("Atomic BEEF contains unrelated transaction data.");return e}static fromEF(t){let e=mt.makeReader(t),i=e.readUInt32LE();if(nt(e.read(6))!=="0000000000ef")throw new Error("Invalid EF marker");let r=e.readVarIntNumStrict(!1),s=[];for(let f=0;f<r;f++){let d=nt(e.readReverse(32)),l=e.readUInt32LE();if(l>Nw)throw new RangeError("EF source output index exceeds the allocation limit");let p=e.readVarIntNumStrict(!1),b=e.read(p),g=Ue.fromBinary(b),w=e.readUInt32LE(),S=e.readUInt64LEBn().toNumber(),C=e.readVarIntNumStrict(!1),E=e.read(C),A=Le.fromBinary(E),k=new se(void 0,[],[],void 0);k.outputs=Array.from({length:l+1}).fill(null),k.outputs[l]={satoshis:S,lockingScript:A},s.push({sourceTransaction:k,sourceTXID:d,sourceOutputIndex:l,unlockingScript:g,sequence:w})}let o=e.readVarIntNumStrict(!1),c=[];for(let f=0;f<o;f++){let d=e.readUInt64LEBn().toNumber(),l=e.readVarIntNumStrict(!1),p=e.read(l),b=Le.fromBinary(p);c.push({satoshis:d,lockingScript:b})}let u=e.readUInt32LE();if(!e.eof())throw new Error("Serialized EF transaction contains trailing data");return new se(i,s,c,u)}static parseScriptOffsets(t){let e=mt.makeReader(t),i=[],r=[];e.read(4);let s=e.readVarIntNumStrict(!1);for(let c=0;c<s;c++){e.read(36);let u=e.readVarIntNumStrict(!1);i.push({vin:c,offset:e.pos,length:u}),e.read(u+4)}let o=e.readVarIntNumStrict(!1);for(let c=0;c<o;c++){e.read(8);let u=e.readVarIntNumStrict(!1);r.push({vout:c,offset:e.pos,length:u}),e.read(u)}if(e.read(4),!e.eof())throw new Error("Serialized transaction contains trailing data");return{inputs:i,outputs:r}}static fromReader(t){var e;return a(e=se,Mn,Qf).call(e,t,!1)}static fromBinary(t){let e=Uint8Array.from(t);return se.fromBinaryView(e)}static fromBinaryView(t){var r,s;let e=new mt(t),i=a(r=se,Mn,Qf).call(r,e,!0);if(!e.eof())throw new Error("Serialized transaction contains trailing data");return N(i,Pi,t),a(s=i,j,rc).call(s),i}static fromHex(t){let e=et(t,"hex"),i=se.fromBinaryView(e);return N(i,Ri,nt(e)),i}static fromHexEF(t){return se.fromEF(et(t,"hex"))}static fromHexBEEF(t,e){return se.fromBEEF(at(t,"hex"),e)}addInput(t){if(t.sourceTXID===void 0&&t.sourceTransaction===void 0)throw new TypeError("A reference to an an input transaction is required. If the input transaction itself cannot be referenced, its TXID must still be provided.");Ge(t.sourceOutputIndex,"sourceOutputIndex"),t.sourceTXID!==void 0&&(t.sourceTXID=Ti(t.sourceTXID,"sourceTXID")),t.sequence!==void 0&&Ge(t.sequence,"sequence"),t.sequence??(t.sequence=4294967295),a(this,j,wn).call(this),this.inputs.push(t)}addOutput(t){if(a(this,j,wn).call(this),t.satoshis===void 0&&t.change!==!0)throw new TypeError("either satoshis must be defined or change must be set to true");if(t.satoshis!==void 0&&sn(t.satoshis,"satoshis"),t.lockingScript==null)throw new Error("lockingScript must be defined");this.outputs.push(t)}addP2PKHOutput(t,e){let i=new Gn().lock(t);if(e===void 0)return this.addOutput({lockingScript:i,change:!0});this.addOutput({lockingScript:i,satoshis:e})}updateMetadata(t){this.metadata={...this.metadata,...t}}async fee(t=vo.getInstance(),e="equal"){var S,C,E,A,k;if(a(this,j,wn).call(this),e!=="equal"&&e!=="random")throw new TypeError('changeDistribution must be either "equal" or "random".');if(typeof t=="number"){let B=t;t={computeFee:async()=>B}}let i=a(this,j,Oi).call(this,!0),r=a(S=i,j,Oi).call(S,!0),s=a(C=i,j,Oi).call(C,!0),o=[...this.inputs],c=this.inputs.map(B=>B.sourceTransaction),u=this.inputs.map(B=>B.unlockingScriptTemplate),f=[...this.outputs],d=[...s.inputs],l=s.inputs.map(B=>B.sourceTransaction),p=s.inputs.map(B=>B.unlockingScriptTemplate),b=[...s.outputs],g=sn(await t.computeFee(s),"Computed transaction fee");if(!a(E=s,j,oc).call(E,i,d,l,p,b))throw new Error("Fee model mutated its transaction snapshot");let w=a(A=r,j,tg).call(A,g);if(w<0)throw new RangeError("Transaction inputs are insufficient for the requested outputs and fee.");if(!a(this,j,oc).call(this,i,o,c,u,f))throw new Error("Transaction changed while computing its fee; no change was applied");if(w===0){this.outputs=f.filter(B=>B.change!==!0),a(this,j,wn).call(this);return}a(k=r,j,eg).call(k,w,e);for(let B=0;B<f.length;B++)f[B].change===!0&&(f[B].satoshis=r.outputs[B].satoshis);a(this,j,wn).call(this)}getFee(){let t=0;for(let i=0;i<this.inputs.length;i++){let r=this.inputs[i];if(typeof r.sourceTransaction!="object")throw new TypeError("Source transactions or sourceSatoshis are required for all inputs to calculate fee");Ge(r.sourceOutputIndex,`Input ${i} sourceOutputIndex`);let s=r.sourceTransaction.outputs[r.sourceOutputIndex];if(s==null)throw new RangeError(`Input ${i} references a source output that does not exist.`);t=fs(t,sn(s.satoshis,`Input ${i} source amount`),"Transaction input total")}let e=0;for(let i=0;i<this.outputs.length;i++)e=fs(e,sn(this.outputs[i].satoshis,`Output ${i} amount`),"Transaction output total");return t-e}async sign(t={}){a(this,j,wn).call(this);for(let f=0;f<this.outputs.length;f++){let d=this.outputs[f];if(d.satoshis===void 0)throw d.change===!0?new Error("There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing."):new Error("One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.");sn(d.satoshis,`Output ${f} amount`)}a(this,j,sc).call(this,this);for(let f=0;f<this.inputs.length;f++){let d=this.inputs[f];if(Ge(d.sourceOutputIndex,`Input ${f} sourceOutputIndex`),Ge(d.sequence??4294967295,`Input ${f} sequence`),d.sourceTXID!==void 0&&Ti(d.sourceTXID,`Input ${f} sourceTXID`),d.sourceTransaction!==void 0){let l=d.sourceTransaction.outputs[d.sourceOutputIndex];if(l==null)throw new RangeError(`Input ${f} references a source output that does not exist.`);if(sn(l.satoshis,`Input ${f} source amount`),d.sourceTXID!==void 0&&(d.sourceTransaction.inputs.length>0||d.sourceTransaction.merklePath!=null)&&Ti(d.sourceTXID,`Input ${f} sourceTXID`)!==d.sourceTransaction.id("hex"))throw new Error(`Input ${f} sourceTXID does not reference its supplied source transaction.`)}}this.materializeSourceTXIDs();let e=a(this,j,Oi).call(this,!0),i=[...this.inputs],r=this.inputs.map(f=>f.sourceTransaction),s=this.inputs.map(f=>f.unlockingScriptTemplate),o=[...this.outputs],c=t.skipExistingSignatures===!0,u;if(u=await Promise.all(e.inputs.map(async(f,d)=>{var w;if(c&&f.unlockingScript!=null)return new Ue([],Uint8Array.from(f.unlockingScript.toUint8Array()),void 0,!1);let l=s[d];if(l===void 0)return;let p=a(w=e,j,Oi).call(w,!0);for(let S=0;S<s.length;S++)p.inputs[S].unlockingScriptTemplate=s[S];N(p,$o,{hashOutputsSingle:new Map});let b=await l.sign(p,d);if(b==null||typeof b.toUint8Array!="function")throw new TypeError(`Input ${d} signing template returned an invalid unlocking script`);let g=b.toUint8Array();if(!(g instanceof Uint8Array))throw new TypeError(`Input ${d} signing template returned an invalid unlocking script`);return new Ue([],Uint8Array.from(g),void 0,!1)})),!a(this,j,oc).call(this,e,i,r,s,o))throw new Error("Transaction changed while signing; no unlocking scripts were applied");for(let f=0,d=this.inputs.length;f<d;f++)s[f]!==void 0&&!(c&&i[f].unlockingScript!=null)&&(this.inputs[f].unlockingScript=u[f]);a(this,j,wn).call(this)}async broadcast(t=$p()){let e=a(this,j,Oi).call(this),i=e.id("hex");return Op(await t.broadcast(e),i)}[G0](){return a(this,j,Sr).call(this)}[Y0](t){N(this,Qn,t)}toBinary(){return Array.from(a(this,j,Sr).call(this))}toUint8Array(){return Uint8Array.from(a(this,j,Sr).call(this))}toEF(){return Array.from(a(this,j,nd).call(this))}toEFUint8Array(){return this.toEFBinary()}toEFBinary(){return Uint8Array.from(a(this,j,nd).call(this))}toHexEF(){return nt(this.toEFBinary())}toHex(){let t=a(this,j,Sr).call(this);if(y(this,Ri)!=null)return y(this,Ri);let e=nt(t);return N(this,Ri,e),e}toHexBEEF(){return nt(this.toBEEF())}toHexAtomicBEEF(){return nt(this.toAtomicBEEF())}hash(t){let e=a(this,j,Sr).call(this);return y(this,vr)??N(this,vr,zt(e)),t==="hex"?nt(y(this,vr)):Array.from(y(this,vr))}id(t){if(a(this,j,Sr).call(this),t==="hex"&&y(this,Qn)!=null)return y(this,Qn);let e=[...this.hash()];return e.reverse(),t==="hex"?(N(this,Qn,nt(e)),y(this,Qn)):e}async verifyTransactionFee(t,e,i){if(e===void 0)return;if(t===void 0)throw new Error("Transaction is undefined");let r=se.fromEF(t.toEF());if(delete r.outputs[0].satoshis,r.outputs[0].change=!0,await r.fee(e),t.getFee()<r.getFee())throw new Error(`Verification failed because the transaction ${i()} has an insufficient fee and has not been mined.`)}async verify(t=Vp(),e,i,r){var o;t!=="scripts only"&&this.materializeSourceTXIDs();let s=t==="scripts only"?void 0:X0(this);return await a(o=a(this,j,Oi).call(this),j,gg).call(o,t,e,i,r,s)}writeSerializedBEEF(t,e){this.materializeSourceTXIDs(),t.writeUInt32LE(4022206465);let{bumps:i,txs:r}=a(this,j,bg).call(this,e);t.writeVarIntNum(i.length);let s=a(this,j,xg).call(this,t,i,r);for(let o=0;o<i.length;o++)t.write(s?.[o]??i[o].toBinary());t.writeVarIntNum(r.length);for(let o of r)t.write(o.tx.toUint8Array()),typeof o.pathIndex=="number"?(t.writeUInt8(1),t.writeVarIntNum(o.pathIndex)):t.writeUInt8(0)}toBEEF(t){let e=new ue;return this.writeSerializedBEEF(e,t),e.toArray()}toBEEFUint8Array(t){let e=new ht;return this.writeSerializedBEEF(e,t),e.toArray()}toBEEFBytes(t){let e=new ht;return this.writeSerializedBEEF(e,t),e.toUint8Array()}toAtomicBEEF(t){this.materializeSourceTXIDs();let e=[1,1,1,1],i=this.hash(),r=this.toBEEF(t);return e.concat(i,r)}toAtomicBEEFUint8Array(t){this.materializeSourceTXIDs();let e=new ht,i=[1,1,1,1];e.write(i);let r=this.hash();return e.write(r),this.writeSerializedBEEF(e,t),e.toUint8Array()}async completeWithWallet(t,e,i,r){let s=this.inputs.length,o=this.outputs.length,c=e??`Transaction with ${s} input(s) and ${o} output(s)`,u=this.inputs.some(p=>p.unlockingScriptTemplate!=null),f=await a(this,j,Ig).call(this,c,u);f.options=r;let d={};for(let p=0;p<this.inputs.length;p++){let b=this.inputs[p].unlockingScriptTemplate;if(b==null)continue;let g=f.inputs[p].outpoint;d[g]=async(w,S)=>await b.sign(w,S)}let l=await K0(t,f,{inputSigners:d},i,this.inputs.map((p,b)=>{let g=p.sourceTransaction?.outputs[p.sourceOutputIndex];if(g==null)throw new Error(`Input ${b} references a source output that does not exist`);return sn(g.satoshis,`Input ${b} source amount`)}));this.version=l.version,this.inputs=l.inputs,this.outputs=l.outputs,this.lockTime=l.lockTime,this.merklePath=l.merklePath,a(this,j,wn).call(this),this.metadata={...this.metadata,...l.metadata}}preimage(t,e,i){if(t??(t=0),e??(e=yt.SIGHASH_FORKID|yt.SIGHASH_ALL),!Number.isSafeInteger(t)||t<0||t>=this.inputs.length)throw new Error("Invalid input index");Ge(e,"signatureScope");let r=e&240;if(r!==224&&r!==192&&r!==64)throw new Error("FORKID must be set");let s=e&15;if(s<1||s>3)throw new Error("Invalid signature coverage, must be all, none or single");let o=this.inputs[t],c=Ge(o.sourceOutputIndex,"sourceOutputIndex");if(o.sourceTransaction==null)throw new Error("Source transaction is required");let u=Ti(o.sourceTransaction.id("hex"),"sourceTransaction ID");if(o.sourceTXID!==void 0&&Ti(o.sourceTXID,"sourceTXID")!==u)throw new Error("sourceTXID does not match sourceTransaction");let f=o.sourceTransaction.outputs[c];if(f==null)throw new Error(`Source transaction's output at index ${c} is required`);let d=sn(f.satoshis,"Source output amount"),l=Ge(o.sequence??4294967295,"inputSequence"),p=i??f.lockingScript;if(p==null||typeof p.toUint8Array!="function")throw new Error("subscript must be a locking script");return yt.format({sourceTXID:u,sourceOutputIndex:c,sourceSatoshis:d,transactionVersion:this.version,otherInputs:[],allInputs:this.inputs,inputIndex:t,outputs:this.outputs,inputSequence:l,subscript:p,lockTime:this.lockTime,scope:e})}};vr=new WeakMap,Qn=new WeakMap,Pi=new WeakMap,Ar=new WeakMap,Ri=new WeakMap,$o=new WeakMap,ds=new WeakMap,j=new WeakSet,J0=function(t,e,i){for(let r of t.inputs)r.sourceTXID==null&&r.sourceTransaction!=null&&(r.sourceTXID=r.sourceTransaction.id("hex"));e.delete(t),i.add(t)},Q0=function(t,e,i,r){if(e.has(t))throw new Error("Cyclic source transaction graph");e.add(t),r.push({tx:t,expanded:!0});for(let s=t.inputs.length-1;s>=0;s--){let o=t.inputs[s].sourceTransaction;t.inputs[s].sourceTXID==null&&o!=null&&!i.has(o)&&r.push({tx:o,expanded:!1})}},Mn=new WeakSet,Ho=function(t,e,i=!1){let r=i&&t instanceof Uint8Array?wr.fromBinaryView(t):wr.fromBinaryStrict(t);if(r.txs.length<1)throw new Error("beef must include at least one transaction.");let s=r.txs.at(-1);if(s==null)throw new Error("beef must include at least one transaction.");let o=e??r.atomicTxid??s.txid,c=r.findAtomicTransaction(o);if(c==null)throw e==null?new Error("beef does not contain transaction for atomic txid."):new Error(`Transaction with TXID ${String(o)} not found in BEEF data.`);return{tx:c,beef:r,txid:o}},Qf=function(t,e){let i=t.readUInt32LE(),r=t.readVarIntNumStrict(!1),s=[];for(let f=0;f<r;f++){let d=nt(t.readReverse(32)),l=t.readUInt32LE(),p=t.readVarIntNumStrict(!1),b=e&&t instanceof mt?t.readView(p):t.read(p),g=e&&b instanceof Uint8Array?Ue.fromBinaryView(b):Ue.fromBinary(b),w=t.readUInt32LE();s.push({sourceTXID:d,sourceOutputIndex:l,unlockingScript:g,sequence:w})}let o=t.readVarIntNumStrict(!1),c=[];for(let f=0;f<o;f++){let d=t.readUInt64LEBn().toNumber(),l=t.readVarIntNumStrict(!1),p=e&&t instanceof mt?t.readView(l):t.read(l),b=e&&p instanceof Uint8Array?Le.fromBinaryView(p):Le.fromBinary(p);c.push({satoshis:d,lockingScript:b})}let u=t.readUInt32LE();return new se(i,s,c,u)},wn=function(){N(this,vr,void 0),N(this,Qn,void 0),N(this,Pi,void 0),N(this,Ar,void 0),N(this,Ri,void 0),N(this,ds,void 0)},td=function(t){return t.sourceTXID==null?t.sourceTransaction?.id("hex"):void 0},rc=function(){N(this,ds,{version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(t=>{let e=t.sourceTransaction?.outputs[t.sourceOutputIndex];return{ref:t,sourceTXID:t.sourceTXID,sourceTransactionId:a(this,j,td).call(this,t),sourceOutputIndex:t.sourceOutputIndex,sequence:t.sequence,unlockingScript:t.unlockingScript,unlockingScriptBytes:t.unlockingScript==null?void 0:fr(t.unlockingScript),sourceOutput:e,sourceSatoshis:e?.satoshis,sourceLockingScript:e?.lockingScript,sourceLockingScriptBytes:e==null?void 0:fr(e.lockingScript)}}),outputs:this.outputs.map(t=>({ref:t,satoshis:t.satoshis,lockingScript:t.lockingScript,lockingScriptBytes:fr(t.lockingScript)}))})},ed=function(){let t=y(this,ds);if(t?.version!==this.version||t.lockTime!==this.lockTime||t.inputs.length!==this.inputs.length||t.outputs.length!==this.outputs.length)return!1;for(let e=0;e<this.inputs.length;e++){let i=this.inputs[e],r=t.inputs[e],s=i.sourceTransaction?.outputs[i.sourceOutputIndex];if(r.ref!==i||r.sourceTXID!==i.sourceTXID||r.sourceTransactionId!==a(this,j,td).call(this,i)||r.sourceOutputIndex!==i.sourceOutputIndex||r.sequence!==i.sequence||r.unlockingScript!==i.unlockingScript||r.unlockingScriptBytes!==(i.unlockingScript==null?void 0:fr(i.unlockingScript))||r.sourceOutput!==s||r.sourceSatoshis!==s?.satoshis||r.sourceLockingScript!==s?.lockingScript||r.sourceLockingScriptBytes!==(s==null?void 0:fr(s.lockingScript)))return!1}for(let e=0;e<this.outputs.length;e++){let i=this.outputs[e],r=t.outputs[e];if(r.ref!==i||r.satoshis!==i.satoshis||r.lockingScript!==i.lockingScript||r.lockingScriptBytes!==fr(i.lockingScript))return!1}return!0},tg=function(t){let e=0;for(let r=0;r<this.inputs.length;r++){let s=this.inputs[r];if(typeof s.sourceTransaction!="object")throw new TypeError("Source transactions are required for all inputs during fee computation");Ge(s.sourceOutputIndex,`Input ${r} sourceOutputIndex`);let o=s.sourceTransaction.outputs[s.sourceOutputIndex];if(o==null)throw new RangeError(`Input ${r} references a source output that does not exist.`);let c=sn(o.satoshis,`Input ${r} source amount`);e=fs(e,c,"Transaction input total")}let i=0;for(let r=0;r<this.outputs.length;r++){let s=this.outputs[r];if(s.change!==!0){let o=sn(s.satoshis,`Output ${r} amount`);i=fs(i,o,"Transaction output total")}}if(i+t>e)throw new RangeError("Transaction inputs are insufficient for the requested outputs and fee.");return e-i-t},eg=function(t,e){let i=this.outputs.filter(r=>r.change===!0);i.length!==0&&(e==="random"?a(this,j,ng).call(this,t,i):a(this,j,ig).call(this,t,i))},ng=function(t,e){let i=t;for(let r=0;r<e.length-1;r++){let s=a(this,j,rg).call(this,0,i);e[r].satoshis=s,i-=s}e.at(-1).satoshis=i},ig=function(t,e){let i=Math.floor(t/e.length);for(let r of e)r.satoshis=i;e.at(-1).satoshis+=t-i*e.length},rg=function(t,e){let i=Pe(1)[0]%9+1;return Math.floor(t+(e-t)*Math.log10(1+1/i)/Math.log10(10))},sg=function(t){t.writeUInt32LE(this.version),t.writeVarIntNum(this.inputs.length);for(let e of this.inputs){if(e.sourceTXID===void 0){if(e.sourceTransaction==null)throw new Error("sourceTransaction is undefined");t.write(e.sourceTransaction.hash())}else t.writeReverse(at(Ti(e.sourceTXID,"sourceTXID"),"hex"));if(t.writeUInt32LE(Ge(e.sourceOutputIndex,"sourceOutputIndex")),e.unlockingScript==null)throw new Error("unlockingScript is undefined");let i=e.unlockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i),t.writeUInt32LE(Ge(e.sequence??4294967295,"sequence"))}t.writeVarIntNum(this.outputs.length);for(let e of this.outputs){t.writeUInt64LE(e.satoshis??0);let i=e.lockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i)}t.writeUInt32LE(this.lockTime)},og=function(){let t=new ht;return a(this,j,sg).call(this,t),t.toUint8Array()},Sr=function(){return(y(this,Pi)==null||!a(this,j,ed).call(this))&&(a(this,j,wn).call(this),N(this,Pi,a(this,j,og).call(this)),a(this,j,rc).call(this)),y(this,Pi)},ag=function(t){t.writeUInt32LE(this.version),t.write([0,0,0,0,0,239]),t.writeVarIntNum(this.inputs.length);for(let e of this.inputs){if(e.sourceTransaction===void 0)throw new TypeError("All inputs must have source transactions when serializing to EF format");if(e.sourceTXID===void 0?t.write(e.sourceTransaction.hash()):t.write(at(e.sourceTXID,"hex").reverse()),t.writeUInt32LE(e.sourceOutputIndex),e.unlockingScript==null)throw new Error("unlockingScript is undefined");let i=e.unlockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i),t.writeUInt32LE(e.sequence??4294967295),t.writeUInt64LE(e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0);let r=e.sourceTransaction.outputs[e.sourceOutputIndex].lockingScript.toUint8Array();t.writeVarIntNum(r.length),t.write(r)}t.writeVarIntNum(this.outputs.length);for(let e of this.outputs){t.writeUInt64LE(e.satoshis??0);let i=e.lockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i)}t.writeUInt32LE(this.lockTime)},nd=function(){if(y(this,Ar)==null||!a(this,j,ed).call(this)){a(this,j,wn).call(this);let t=new ht;a(this,j,ag).call(this,t),N(this,Ar,t.toUint8Array()),a(this,j,rc).call(this)}return y(this,Ar)},cg=async function(t,e,i,r,s,o){if(typeof t.merklePath!="object")return!1;if(e)return s.add(t),!0;if(await t.merklePath.verify(r(),i))return o.add(r()),!0;throw new Error(`Invalid merkle path for transaction ${r()}`)},ug=function(t,e){if(t.inputs.length===0)throw new Error(`Verification failed because transaction ${e()} has no inputs.`);if(t.outputs.length===0)throw new Error(`Verification failed because transaction ${e()} has no outputs.`);let i=new Set;for(let r=0;r<t.inputs.length;r++){let s=t.inputs[r],o=Ge(s.sourceOutputIndex,`Input ${r} sourceOutputIndex`);Ge(s.sequence??4294967295,`Input ${r} sequence`);let c=Ti(s.sourceTXID??s.sourceTransaction?.id("hex"),`Input ${r} sourceTXID`);if(/^0{64}$/.test(c)&&o===4294967295)throw new Error(`Verification failed because unmined transaction ${e()} contains a coinbase input.`);let u=`${c}:${o}`;if(i.has(u))throw new Error(`Verification failed because transaction ${e()} spends outpoint ${u} more than once.`);i.add(u)}a(this,j,sc).call(this,t)},fg=function(t,e,i){if(i.scriptsOnly){!i.verifiedTransactions.has(t)&&!i.queuedTransactions.has(t)&&(i.txQueue.push(t),i.queuedTransactions.add(t));return}!i.verifiedTxids.has(e)&&!i.queuedTxids.has(e)&&(i.txQueue.push(t),i.queuedTxids.add(e))},dg=function(t,e,i,r){let s=0,o={hashOutputsSingle:new Map};for(let c=0;c<t.inputs.length;c++){let u=t.inputs[c];if(typeof u.sourceTransaction!="object")throw new TypeError(`Verification failed because the input at index ${c} of transaction ${i()} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`);if(typeof u.unlockingScript!="object")throw new TypeError(`Verification failed because the input at index ${c} of transaction ${i()} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);let f=u.sourceTransaction,d=f.outputs[u.sourceOutputIndex];if(d==null)throw new RangeError(`Verification failed because input ${c} of transaction ${i()} references a source output that does not exist.`);s=fs(s,sn(d.satoshis,`Input ${c} source amount`),"Transaction input total");let l=f.id("hex");if(!r.scriptsOnly&&u.sourceTXID!==void 0&&Ti(u.sourceTXID,`Input ${c} sourceTXID`)!==l)throw new Error(`Verification failed because input ${c} of transaction ${i()} does not reference its supplied source transaction.`);let p=r.scriptsOnly&&u.sourceTXID!==void 0?u.sourceTXID:f.id("hex");if(a(this,j,fg).call(this,f,p,r),u.sourceTXID??(u.sourceTXID=p),!e&&!new wo({sourceTXID:u.sourceTXID,sourceOutputIndex:u.sourceOutputIndex,lockingScript:d.lockingScript,sourceSatoshis:d.satoshis??0,transactionVersion:t.version,otherInputs:[],allInputs:t.inputs,unlockingScript:u.unlockingScript,inputSequence:u.sequence??4294967295,inputIndex:c,outputs:t.outputs,lockTime:t.lockTime,memoryLimit:r.memoryLimit,sigHashCache:o}).validateJavaScript())return{valid:!1,inputTotal:s}}return{valid:!0,inputTotal:s}},sc=function(t){let e=0;for(let i=0;i<t.outputs.length;i++)e=fs(e,sn(t.outputs[i].satoshis,`Output ${i} amount`),"Transaction output total");return e},lg=async function(t,e){if(t.length===0||e===void 0)return;let i=e.verifyScriptsBatch===void 0?await Promise.all(t.map(async o=>await e.verifyScripts(o))):await e.verifyScriptsBatch(t);if(!Array.isArray(i)||i.length!==t.length)throw new Error("Script verifier returned an invalid batch result count");let r=[];for(let o=0;o<i.length;o++){if(!Object.prototype.hasOwnProperty.call(i,o)||typeof i[o]!="boolean")throw new TypeError("Script verifier returned a non-boolean verdict");r.push(i[o])}let s=r.findIndex(o=>!o);if(s>=0)throw new Error(`Script verification failed for transaction ${t[s].tx.id("hex")}`)},hg=function(t,e,i){return i.scriptsOnly?i.verifiedTransactions.has(t):i.verifiedTxids.has(e())},Oi=function(t=!1){let e=new Map,i=[this];e.set(this,new se(this.version,[],[],this.lockTime));for(let s=0;s<i.length;s++){let o=i[s],c=e.get(o);if(c===void 0)throw new Error("Transaction snapshot is incomplete");c.version=o.version,c.lockTime=o.lockTime,c.merklePath=o.merklePath===void 0?void 0:new Ai(o.merklePath.blockHeight,o.merklePath.path.map(u=>u.map(f=>({...f})))),c.outputs=Array.from(o.outputs,u=>u==null?u:{satoshis:u.satoshis,lockingScript:new Le([],Uint8Array.from(u.lockingScript.toUint8Array()),void 0,!1),change:u.change}),c.inputs=Array.from(o.inputs,u=>{let f;return u.sourceTransaction!==void 0&&(f=e.get(u.sourceTransaction),f===void 0&&(f=new se(u.sourceTransaction.version,[],[],u.sourceTransaction.lockTime),e.set(u.sourceTransaction,f),i.push(u.sourceTransaction))),{sourceTransaction:f,sourceTXID:u.sourceTXID,sourceOutputIndex:u.sourceOutputIndex,unlockingScript:u.unlockingScript===void 0?void 0:new Ue([],Uint8Array.from(u.unlockingScript.toUint8Array()),void 0,!1),unlockingScriptTemplate:t?u.unlockingScriptTemplate:void 0,sequence:u.sequence}})}let r=e.get(this);if(r===void 0)throw new Error("Transaction snapshot is incomplete");return r},oc=function(t,e,i,r,s){if(this.version!==t.version||this.lockTime!==t.lockTime||this.inputs.length!==t.inputs.length||this.outputs.length!==t.outputs.length)return!1;for(let o=0;o<this.inputs.length;o++){let c=this.inputs[o],u=t.inputs[o];if(c!==e[o]||c.sourceTransaction!==i[o]||c.unlockingScriptTemplate!==r[o]||c.sourceTXID!==u.sourceTXID||c.sourceOutputIndex!==u.sourceOutputIndex||c.sequence!==u.sequence||!Jf(c.unlockingScript?.toUint8Array(),u.unlockingScript?.toUint8Array()))return!1;let f=c.sourceTransaction?.outputs[c.sourceOutputIndex],d=u.sourceTransaction?.outputs[u.sourceOutputIndex];if(f==null||d==null){if(f!==d)return!1}else if(!Object.is(f.satoshis,d.satoshis)||!Jf(f.lockingScript.toUint8Array(),d.lockingScript.toUint8Array()))return!1}for(let o=0;o<this.outputs.length;o++){let c=this.outputs[o],u=t.outputs[o];if(c!==s[o]||!Object.is(c.satoshis,u.satoshis)||c.change!==u.change||!Jf(c.lockingScript.toUint8Array(),u.lockingScript.toUint8Array()))return!1}return!0},pg=async function(t,e,i){let{feeModel:r,memoryLimit:s,selectedVerifier:o,verifierQueue:c}=i;a(this,j,ug).call(this,t,e),await this.verifyTransactionFee(t,r,e);let u={tx:t,blockHeight:Rw,consensus:!0,...s===void 0?{}:{memoryLimit:s}},f=o!==void 0&&(s===void 0||o.supportsMemoryLimit===!0)&&(o.shouldVerifyScripts?.(u)??!0),d=p=>a(this,j,dg).call(this,t,p,e,i),l=!f&&i.scriptWork!==void 0?i.scriptWork.work.inputs(i.scriptWork,u,d):d(f);return!l.valid||(f&&c.push(u),a(this,j,sc).call(this,t)>l.inputTotal)?!1:(i.scriptsOnly?i.verifiedTransactions.add(t):i.verifiedTxids.add(e()),!0)},gg=async function(t,e,i,r,s){let o=t==="scripts only",c=r??La(),u=s!==void 0&&c!==void 0?j0(s,c):c;o||this.materializeSourceTXIDs();let f=new Set,d=new Set,l=[this],p=new Set;o||p.add(this.id("hex"));let b=new Set(l),g=[],w={scriptsOnly:o,memoryLimit:i,txQueue:l,queuedTransactions:b,queuedTxids:p,verifiedTransactions:d,verifiedTxids:f,feeModel:e,selectedVerifier:u,verifierQueue:g,scriptWork:s},S=0;for(;S<l.length;){let C=l[S++],E,A=()=>(E??(E=C.id("hex")),E);if(!a(this,j,hg).call(this,C,A,w)&&!await a(this,j,cg).call(this,C,o,t,A,d,f)&&!await a(this,j,pg).call(this,C,A,w))return!1}return await a(this,j,lg).call(this,g,u),!0},bg=function(t){let e=[],i=new Map,r=new Map,s=[],o=new Set,c=new Set,u=[{tx:this,expanded:!1}];for(;u.length>0;){let f=u.pop();if(f!=null){if(f.expanded){a(this,j,mg).call(this,f.tx,o,s,e,i,r);continue}a(this,j,yg).call(this,f.tx,t,c,u)}}return{bumps:e,txs:s}},mg=function(t,e,i,r,s,o){let c=t.id("hex");if(e.has(c))return;let u={tx:t};t.merklePath!=null&&(u.pathIndex=a(this,j,wg).call(this,t.merklePath,r,s,o)),e.add(c),i.push(u)},yg=function(t,e,i,r){let s=t.id("hex");if(!i.has(s)&&(i.add(s),r.push({tx:t,expanded:!0}),t.merklePath==null))for(let o of t.inputs){let c=o.sourceTransaction;if(c!=null)r.push({tx:c,expanded:!1});else if(e===!1)throw new Error("A required source transaction is missing!")}},wg=function(t,e,i,r){let s=i.get(t);if(s!==void 0)return s;let o=`${t.blockHeight}:${t.computeRoot()}`,c=r.get(o);if(c!==void 0)return e[c].combine(t),i.set(t,c),c;let u=e.length;return e.push(t),i.set(t,u),r.set(o,u),u},xg=function(t,e,i){let r;if(t instanceof ht){r=e.map(o=>o.toBinaryUint8Array());let s=16;for(let o of r)s+=o.length;for(let o of i)s+=o.tx.toUint8Array().length+10;t.reserve(s)}return r},Ig=async function(t,e){let i={description:t,inputs:[],outputs:[],lockTime:this.lockTime,version:this.version};this.materializeSourceTXIDs();let r=new wr;for(let s=0;s<this.inputs.length;s++){let o=this.inputs[s];if(o.sourceTransaction==null)throw new Error("All inputs must have a sourceTransaction when using completeWithWallet");r.mergeTransaction(o.sourceTransaction),i.inputs.push(await a(this,j,Sg).call(this,o,s,e))}return this.inputs.length>0&&(i.inputBEEF=r.toUint8Array()),i.outputs=this.outputs.map(s=>({satoshis:s.satoshis,lockingScript:s.lockingScript.toHex(),outputDescription:"Output from source transaction"})),Array.isArray(this.metadata?.labels)&&(i.labels=this.metadata.labels),i},Sg=async function(t,e,i){let r={outpoint:`${t.sourceTransaction.id("hex")}.${t.sourceOutputIndex}`,inputDescription:"Input from source transaction",sequenceNumber:t.sequence};if(!i){if(t.unlockingScript==null)throw new Error("All inputs must have an unlockingScript when using completeWithWallet");return r.unlockingScript=t.unlockingScript.toHex(),r}if(t.unlockingScriptTemplate!=null)r.unlockingScriptLength=await t.unlockingScriptTemplate.estimateLength(this,e);else if(t.unlockingScript!=null)r.unlockingScript=t.unlockingScript.toHex();else throw new Error(`Input ${e} must have either an unlockingScript or unlockingScriptTemplate`);return r},G(se,Mn);var Me=se;var ti=class extends Error{constructor(e,i){super(`The ${e} parameter must be ${i??"valid."}`);m(this,"parameter");m(this,"code");m(this,"isError",!0);this.parameter=e,this.code=6,this.name=this.constructor.name}},ut=ti;var vg=globalThis.Buffer,id=typeof vg?.compare=="function"?vg.compare:void 0,ac=globalThis.SharedArrayBuffer,Bw=16*1024*1024,Ni=class{constructor(){m(this,"cached")}get(t){let e=this.cached;if(!(e==null||!(t instanceof Uint8Array)||t.length!==e.bytes.length||id==null||ac!=null&&t.buffer instanceof ac||id(t,e.bytes)!==0))return e.value}set(t,e){t instanceof Uint8Array&&t.length<=Bw&&id!=null&&!(ac!=null&&t.buffer instanceof ac)&&(this.cached={bytes:new Uint8Array(t),value:e})}};var Dn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ag="0123456789abcdef";function Ye(n){let t="";for(let e=0;e<n.length;e++){let i=n[e];t+=Ag[i>>4]+Ag[i&15]}return t}function ls(n){if(typeof n!="string"||n.length%2!==0||!/^[0-9a-f]*$/iu.test(n))throw new TypeError("Invalid hexadecimal byte string");let t=Array.from({length:n.length/2});for(let e=0;e<t.length;e++)t[e]=Number.parseInt(n.slice(e*2,e*2+2),16);return t}function Eg(n){let t="";for(let e=0;e<n.length;e+=3){let i=n[e],r=e+1<n.length?n[e+1]:0,s=e+2<n.length?n[e+2]:0;t+=Dn[i>>2],t+=Dn[(i&3)<<4|r>>4],t+=e+1<n.length?Dn[(r&15)<<2|s>>6]:"=",t+=e+2<n.length?Dn[s&63]:"="}return t}function cc(n){if(typeof n!="string"||n.length%4!==0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(n))throw new TypeError("Invalid canonical base64 string");if(n.endsWith("==")&&(Dn.indexOf(n[n.length-3])&15)!==0)throw new TypeError("Invalid canonical base64 string");if(n.endsWith("=")&&!n.endsWith("==")&&(Dn.indexOf(n[n.length-2])&3)!==0)throw new TypeError("Invalid canonical base64 string");let t=[];for(let e=0;e<n.length;e+=4){let i=Dn.indexOf(n[e]),r=Dn.indexOf(n[e+1]),s=n[e+2]==="="?0:Dn.indexOf(n[e+2]),o=n[e+3]==="="?0:Dn.indexOf(n[e+3]);t.push(i<<2|r>>4),n[e+2]!=="="&&t.push((r&15)<<4|s>>2),n[e+3]!=="="&&t.push((s&3)<<6|o)}return t}var Hn,Bi,rd=class{constructor(t){G(this,Hn);m(this,"bytes");m(this,"pos",0);this.bytes=Uint8Array.from(t)}read(t){let e=a(this,Hn,Bi).call(this,t);return this.bytes.slice(e,this.pos)}readView(t){let e=a(this,Hn,Bi).call(this,t);return this.bytes.subarray(e,this.pos)}readReverse(t){return this.read(t).reverse()}readUInt8(){return this.bytes[a(this,Hn,Bi).call(this,1)]}readUInt16LE(){let t=a(this,Hn,Bi).call(this,2);return this.bytes[t]|this.bytes[t+1]<<8}readUInt32LE(){let t=a(this,Hn,Bi).call(this,4);return(this.bytes[t]|this.bytes[t+1]<<8|this.bytes[t+2]<<16|this.bytes[t+3]<<24)>>>0}readUInt64LE(){let t=a(this,Hn,Bi).call(this,8),e=0n;for(let i=7;i>=0;i--)e=e<<8n|BigInt(this.bytes[t+i]);return Number(e)}readVarInt(){let t=this.readUInt8();if(t<253)return t;if(t===253){let r=this.readUInt16LE();if(r<253)throw new Error("non-canonical varInt");return r}if(t===254){let r=this.readUInt32LE();if(r<=65535)throw new Error("non-canonical varInt");return r}let e=a(this,Hn,Bi).call(this,8),i=0n;for(let r=7;r>=0;r--)i=i<<8n|BigInt(this.bytes[e+r]);if(i<=0xffffffffn)throw new Error("non-canonical varInt");if(i>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("varInt is too large");return Number(i)}eof(){return this.pos===this.bytes.length}};Hn=new WeakSet,Bi=function(t){let e=this.pos;if(!Number.isSafeInteger(t)||t<0||e+t>this.bytes.length)throw new RangeError("Serialized BEEF exceeds available data");return this.pos+=t,e};var _w=4294967295;function uc(n,t){return Math.floor(n/2**t)}function Cw(n){return n%2===0?n+1:n-1}function Er(n,t){return Ye(zt(ls((n??"")+(t??"")).reverse()).reverse())}function sd(n,t,e,i,r,s){let o=`${t}:${e}`;if(r.has(o))return r.get(o);let c=t<i.length?i[t].get(e):void 0;if(c!==void 0||t===0)return r.set(o,c),c;let u=t-1,f=e*2,d=sd(n,u,f,i,r,s);if(d?.hash==null||d.hash===""){r.set(o,void 0);return}let l=sd(n,u,f+1,i,r,s);if(l?.hash==null){if(l?.duplicate===!0||n.length===1&&f===uc(s,u))return c={offset:e,hash:Er(d.hash,d.hash)},r.set(o,c),c;r.set(o,void 0);return}return c={offset:e,hash:l.duplicate===!0?Er(d.hash,d.hash):Er(l.hash,d.hash)},r.set(o,c),c}function Lw(n,t,e,i,r,s){if(typeof t!="string"&&(t=n[0].find(f=>!!f.hash)?.hash),typeof t!="string")throw new TypeError("Transaction ID is undefined");let o=n[0].find(f=>f.hash===t)?.offset;if(o===void 0)throw new Error("Transaction ID not found in Merkle Path");if(n.length===1&&n[0].length===1)return t;let c=Math.max(n.length,32-Math.clz32(s)),u=t;for(let f=0;f<c;f++){let d=uc(o,f),l=`${f}:${d}`,p=r.get(l);if(p!==void 0){if(p!==u)throw new Error("Mismatched roots");let w=r.get(`${c}:0`);if(w===void 0)throw new Error("Mismatched roots");return w}r.set(l,u);let b=Cw(d),g=sd(n,f,b,e,i,s);if(g==null){if(n.length===1&&d===uc(s,f)){u=Er(u,u);continue}throw new Error(`Missing hash for index ${o} at height ${f}`)}g.duplicate===!0?u=Er(u,u):u=b%2===1?Er(g.hash,u):Er(u,g.hash)}return r.set(`${c}:0`,u),u}function Uw(n){n.readVarInt();let t=n.readUInt8(),e=Array.from({length:t},()=>[]);for(let u=0;u<t;u++){let f=n.readVarInt();for(let d=0;d<f;d++){let l=n.readVarInt(),p=n.readUInt8();e[u].push((p&1)===1?{offset:l,duplicate:!0}:{offset:l,hash:Ye(n.read(32).reverse())})}e[u].sort((d,l)=>d.offset-l.offset)}if(e.length===0||e.length>32||e[0].length===0)throw new Error("Invalid Merkle Path height");for(let u=0;u<e.length;u++){let f=new Set,d=uc(_w,u);for(let l of e[u]){if(!Number.isSafeInteger(l.offset)||l.offset<0||l.offset>d)throw new Error("Invalid Merkle Path offset");if(f.has(l.offset))throw new Error("Duplicate Merkle Path offset");f.add(l.offset)}}let i=e.map(u=>new Map(u.map(f=>[f.offset,f]))),r=new Map,s=new Map,o=e[0].reduce((u,f)=>Math.max(u,f.offset),0),c;for(let u of e[0]){let f=Lw(e,u.hash,i,r,s,o);if(c===void 0)c=f;else if(c!==f)throw new Error("Mismatched roots")}return new Set(e[0].flatMap(u=>u.hash===void 0?[]:[u.hash]))}function kg(n){let t=n.pos,e=n.readUInt32LE(),i=n.readVarInt(),r=[],s=new Set;for(let l=0;l<i;l++){let p=Ye(n.readReverse(32));s.add(p);let b=n.readUInt32LE(),g=n.readVarInt(),w=n.readView(g),S=n.readUInt32LE();r.push({sourceTXID:p,sourceOutputIndex:b,unlockingScript:w,sequence:S})}let o=n.readVarInt(),c=[];for(let l=0;l<o;l++){let p=n.readUInt64LE(),b=n.readVarInt();c.push({satoshis:p,lockingScript:n.readView(b)})}let u=n.readUInt32LE(),f=n.bytes.subarray(t,n.pos),d=Ye(zt(f).reverse());return{txid:d,transaction:{txid:d,version:e,inputs:r,outputs:c,lockTime:u},inputTxids:Array.from(s),txidOnly:!1}}function Mw(n,t){if(t===4022206466){let r=n.readUInt8();if(r===ze.TXID_ONLY)return{txid:Ye(n.readReverse(32)),inputTxids:[],txidOnly:!0};let s=r===ze.RAWTX_AND_BUMP_INDEX?n.readVarInt():void 0;return{...kg(n),bumpIndex:s}}let e=kg(n),i=n.readUInt8()===0?void 0:n.readVarInt();return{...e,bumpIndex:i}}function Tg(n){let t=new rd(n),e=t.readUInt32LE(),i;if(e===16843009&&(i=Ye(t.readReverse(32)),e=t.readUInt32LE()),e!==4022206465&&e!==4022206466)throw new Error("Invalid BEEF version");let r=t.readVarInt(),s=[];for(let u=0;u<r;u++)s.push(Uw(t));let o=t.readVarInt(),c=[];for(let u=0;u<o;u++)c.push(Mw(t,e));if(!t.eof())throw new Error("Serialized BEEF contains trailing data");return{atomicTxid:i,bumps:s,entries:c}}function hs(n){let{atomicTxid:t,entries:e}=Tg(n),i=new Map;for(let r of e){if(i.has(r.txid))throw new Error("BEEF contains duplicate transactions");i.set(r.txid,r.transaction)}for(let r of e)if(r.transaction!==void 0)for(let s of r.transaction.inputs){let c=i.get(s.sourceTXID)?.outputs[s.sourceOutputIndex];c!==void 0&&(s.sourceSatoshis=c.satoshis)}return{atomicTxid:t,transactions:i}}function qo(n,t=!1){let{atomicTxid:e,bumps:i,entries:r}=Tg(n);if(e===void 0)throw new Error("Atomic BEEF subject is missing");let s=new Map(r.map(f=>[f.txid,f]));if(s.size!==r.length)throw new Error("Atomic BEEF contains duplicate transactions");let o=s.get(e);if(o?.transaction===void 0)throw new Error("Atomic BEEF subject is missing");let c=new Set,u=[o];for(;u.length>0;){let f=u.pop();if(!(c.has(f)||(c.add(f),(f.bumpIndex===void 0?void 0:i[f.bumpIndex])?.has(f.txid)===!0||f.txidOnly)))for(let p of f.inputTxids){let b=s.get(p);if(b===void 0){if(t)continue;throw new Error("Atomic BEEF omits a required dependency")}u.push(b)}}if(c.size!==r.length)throw new Error("Atomic BEEF contains unrelated transaction data");for(let f of o.transaction.inputs){let l=s.get(f.sourceTXID)?.transaction?.outputs[f.sourceOutputIndex];l!==void 0&&(f.sourceSatoshis=l.satoshis)}return o.transaction}var ps=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,Dw=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;function Hw(n,t){let e=1n;for(;t>0n;)(t&1n)!==0n&&(e=e*n%ps),n=n*n%ps,t>>=1n;return e}function fc(n){if(!/^0[23][0-9a-f]{64}$/iu.test(n))return!1;let t=BigInt(`0x${n.slice(2)}`);if(t>=ps)return!1;let e=(t*t*t+7n)%ps,i=Hw(e,ps+1n>>2n);return i*i%ps===e}function $w(n,t,e){let i=0n;for(let r=t;r<t+e;r++)i=i<<8n|BigInt(n[r]);return i}function gs(n){if(n.length<8||n.length>72||n[0]!==48||n[1]!==n.length-2)return!1;let t=2;for(let e=0;e<2;e++){if(n[t++]!==2)return!1;let i=n[t++];if(i<1||i>33||t+i>n.length)return!1;let r=n[t];if((r&128)!==0||i>1&&r===0&&(n[t+1]&128)===0)return!1;let s=$w(n,t,i);if(s===0n||s>=Dw)return!1;t+=i}return t===n.length}var _i=4294967295,od=1e5,xn=1e3,Og=100,Pg=32,Rg=new Ni,Ng=new Ni;function wt(n,t){throw new ut(n,t)}function gt(n,t){if(n==null||typeof n!="object"||Array.isArray(n))return wt(t,"a plain object");let e=Object.getPrototypeOf(n);if(e!==null&&e!==Object.prototype)return wt(t,"a plain object");let i=Reflect.ownKeys(n);if(i.length>od)return wt(t,`an object with at most ${od} properties`);for(let r of i){if(typeof r!="string"||gn(r))return wt(t,"an object with safe string keys");let s=Object.getOwnPropertyDescriptor(n,r);if(s==null||!("value"in s))return wt(`${t}.${r}`,"a data property")}return n}function Ne(n,t,e=od){if(n===void 0)return[];if(!Array.isArray(n))return wt(t,"an array");if(e!==void 0&&n.length>e)return wt(t,`an array of at most ${e} items`);let i=Object.getOwnPropertyDescriptors(n),r=new Set(["length",...Array.from({length:n.length},(s,o)=>String(o))]);if(Object.getOwnPropertySymbols(n).length!==0||Object.keys(i).length!==r.size||Object.keys(i).some(s=>!r.has(s))||Object.values(i).some(s=>s.get!=null||s.set!=null))return wt(t,"an accessor-free dense array without extra properties");for(let s=0;s<n.length;s++)if(!Object.prototype.hasOwnProperty.call(n,s))return wt(t,"a dense array");return n}function _g(n){let t=Ne(n,"sendWith",xn).map((e,i)=>Li(e,`sendWith[${i}]`,64,64));return new Set(t).size!==t.length?wt("sendWith","unique transaction IDs"):t}function $n(n,t,e,i=268435456){if(n instanceof Uint8Array)return n.length>i?wt(t,`at most ${i} bytes`):e!==void 0&&n.length!==e?wt(t,`exactly ${e} bytes`):n;if(!Array.isArray(n))return wt(t,"an array of bytes");if(n.length>i)return wt(t,`at most ${i} bytes`);for(let r=0;r<n.length;r++)if(!Object.prototype.hasOwnProperty.call(n,r)||!Number.isInteger(n[r])||n[r]<0||n[r]>255)return wt(t,"a dense array of bytes");return e!==void 0&&n.length!==e?wt(t,`exactly ${e} bytes`):n}function ms(n,t,e){return n===void 0?e:typeof n!="boolean"?wt(t,"a boolean"):n}function He(n,t){let e=Li(n,t,66,66);return fc(e)?e:wt(t,"a valid compressed secp256k1 public key")}function ad(n,t){return n==="self"||n==="anyone"?n:He(n,t)}function cd(n,t="protocolID"){if(!Array.isArray(n)||n.length!==2)return wt(t,"a [securityLevel, protocolName] tuple");let e=ee(n[0],`${t}[0]`,void 0,0,2),i=oe(n[1],`${t}[1]`,5,400);return[e,i]}function Ci(n,t=!0){let e=ms(n.privileged,"privileged",!1),i=Tr(n.privilegedReason,"privilegedReason",5,50);e&&i===void 0&&wt("privilegedReason","a value when 'privileged' is true"),t&&ms(n.seekPermission,"seekPermission",!0)}function kr(n,t="args"){let e=gt(n,t);cd(e.protocolID),oe(e.keyID,"keyID",1,800),e.counterparty!==void 0&&ad(e.counterparty,"counterparty"),Ci(e)}function Cg(n){let t=bc(n,"outpoint"),[e,i]=t.split(".");return{txid:e,vout:Number(i)}}function ei(n,t="value"){return ms(n,t,!0)}function be(n,t="value"){return ms(n,t,!1)}function Tr(n,t,e,i){if(n!==void 0)return oe(n,t,e,i)}function qw(n,t,e){if(n===void 0||!Number.isSafeInteger(n)||n<0||n>21e14)throw new ut(t,"a valid number of satoshis");if(e!==void 0&&n<e)throw new ut(t,`at least ${e} satoshis.`);return n}function ee(n,t,e,i,r){if(n===void 0){if(e!==void 0)return e;throw new ut(t,"a valid integer")}if(!Number.isSafeInteger(n))throw new ut(t,"a safe integer");if(n=Number(n),i!==void 0&&n<i)throw new ut(t,`at least ${i} length.`);if(r!==void 0&&n>r)throw new ut(t,`no more than ${r} length.`);return n}function Fw(n,t){return ee(n,t,0,0)}function oe(n,t,e,i){if(typeof n!="string")throw new ut(t,"a string");let r=xe(n).length;if(e!==void 0&&r<e)throw new ut(t,`at least ${e} length.`);if(i!==void 0&&r>i)throw new ut(t,`no more than ${i} length.`);return n}function Ww(n){if(n!==void 0)return dc(n)}function dc(n){return dd(n,"basket",1,300)}function ud(n){return dd(n,"label",1,300)}function fd(n){return dd(n,"tag",1,300)}function dd(n,t,e,i){if(typeof n!="string")throw new ut(t,"a string");n=n.trim().toLowerCase();let r=xe(n).length;if(e!==void 0&&r<e)throw new ut(t,`at least ${e} length.`);if(i!==void 0&&r>i)throw new ut(t,`no more than ${i} length.`);return n}function Bg(n,t,e,i){if(n!==void 0)return on(n,t,e,i)}function bs(n){throw new ut(n,"valid base64 string")}function Vw(n,t){let e=0;for(let i=0;i<n.length;i++){let r=n.codePointAt(i)??0,s=r>=65&&r<=90||r>=97&&r<=122,o=r>=48&&r<=57;s||o||r===43||r===47||((r!==61||i<n.length-2)&&bs(t),e++)}return e}function Kw(n,t,e){t>2&&bs(e),t>0&&n.length%4!==0&&bs(e);let i=n.length%4;i!==0&&i!==4-t&&bs(e)}function zw(n,t,e,i){if(e!==void 0&&n<e)throw new ut(t,`at least ${e} bytes`);if(i!==void 0&&n>i)throw new ut(t,`no more than ${i} bytes`)}function on(n,t,e,i){typeof n!="string"&&bs(t),n=n.trim(),n.length===0&&bs(t);let r=Vw(n,t);Kw(n,r,t);let s=n.length-r,o=Math.floor(s*3/4);return zw(o,t,e,i),n}function Xw(n,t,e,i){if(n!==void 0)return Li(n,t,e,i)}var jw=/^[0-9a-f]+$/,Gw=/^[0-9A-Fa-f]+$/;function Li(n,t,e,i){if(typeof n!="string")throw new ut(t,"a hexadecimal string");if(n=n.trim(),n.length%2===1)throw new ut(t,`even length, not ${n.length}.`);let r=jw.test(n);if(!r&&!Gw.test(n))throw new ut(t,"hexadecimal string.");if(e!==void 0&&n.length<e)throw new ut(t,`at least ${e} length.`);if(i!==void 0&&n.length>i)throw new ut(t,`no more than ${i} length.`);return r?n:n.toLowerCase()}function Lg(n,t){let e=Li(n,t);return gs(ls(e))?e:wt(t,"a canonical DER-encoded ECDSA signature")}function Yw(n){if(gt(n,"input"),n.unlockingScript===void 0&&n.unlockingScriptLength===void 0)throw new ut("unlockingScript, unlockingScriptLength","at least one valid value.");let t=Xw(n.unlockingScript,"unlockingScript"),e=n.unlockingScriptLength??(t==null?0:t.length/2);if(ee(e,"unlockingScriptLength",void 0,0),t&&e!==t.length/2)throw new ut("unlockingScriptLength","length unlockingScript if both valid.");return{outpoint:Cg(n.outpoint),inputDescription:oe(n.inputDescription,"inputDescription",5,2e3),unlockingScript:t,unlockingScriptLength:e,sequenceNumber:ee(n.sequenceNumber,"sequenceNumber",_i,0,_i)}}function Zw(n){return gt(n,"output"),{lockingScript:Li(n.lockingScript,"lockingScript"),satoshis:qw(n.satoshis,"satoshis"),outputDescription:oe(n.outputDescription,"outputDescription",5,2e3),basket:Ww(n.basket),customInstructions:Tr(n.customInstructions,"customInstructions"),tags:Ne(n.tags,"tags").map(e=>fd(e))}}function Jw(n){n!==void 0&>(n,"options");let t=n??{};return t.trustSelf!==void 0&&t.trustSelf!=="known"&&wt("trustSelf","undefined or 'known'"),{signAndProcess:ei(t.signAndProcess,"signAndProcess"),acceptDelayedBroadcast:ei(t.acceptDelayedBroadcast,"acceptDelayedBroadcast"),trustSelf:t.trustSelf,knownTxids:Ne(t.knownTxids,"knownTxids").map(i=>Li(i,"knownTxids",64,64)),returnTXIDOnly:be(t.returnTXIDOnly,"returnTXIDOnly"),noSend:be(t.noSend,"noSend"),noSendChange:Ne(t.noSendChange,"noSendChange").map(i=>Cg(i)),sendWith:_g(t.sendWith),randomizeOutputs:ei(t.randomizeOutputs,"randomizeOutputs")}}function lc(n,t){gt(n,"args");let e={description:oe(n.description,"description",5,2e3),inputBEEF:n.inputBEEF===void 0?void 0:$n(n.inputBEEF,"inputBEEF"),inputs:Ne(n.inputs,"inputs").map(r=>Yw(r)),outputs:Ne(n.outputs,"outputs").map(r=>Zw(r)),lockTime:ee(n.lockTime,"lockTime",0,0,_i),version:ee(n.version,"version",1,0,_i),labels:Ne(n.labels,"labels").map(r=>ud(r)),options:Jw(n.options),logger:t,isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!1,isRemixChange:!1,isSignAction:!1,randomVals:void 0,includeAllSourceTransactions:!1,isTestWerrReviewActions:!1};if(e.inputBEEF!==void 0&&Rg.get(e.inputBEEF)!==!0)try{hs(e.inputBEEF),Rg.set(e.inputBEEF,!0)}catch{throw new ut("inputBEEF","a complete, exactly framed BEEF envelope")}let i=new Set;for(let r of e.inputs){let s=`${r.outpoint.txid.toLowerCase()}.${r.outpoint.vout}`;i.has(s)&&wt("inputs","unique input outpoints"),i.add(s)}return e.isTestWerrReviewActions=e.labels.includes(cx),e.isSendWith=e.options.sendWith.length>0,e.isRemixChange=!e.isSendWith&&e.inputs.length===0&&e.outputs.length===0,e.isNewTx=e.isRemixChange||e.inputs.length>0||e.outputs.length>0,e.isNewTx&&e.options.sendWith.length>=xn&&wt("sendWith",`at most ${xn-1} transaction IDs when the new transaction joins the broadcast set`),e.isSignAction=e.isNewTx&&(!e.options.signAndProcess||e.inputs.some(r=>r.unlockingScript===void 0)),e.isDelayed=e.options.acceptDelayedBroadcast,e.isNoSend=e.options.noSend,e}function Qw(n){n!==void 0&>(n,"options");let t=n??{};return{acceptDelayedBroadcast:ei(t.acceptDelayedBroadcast,"acceptDelayedBroadcast"),returnTXIDOnly:be(t.returnTXIDOnly,"returnTXIDOnly"),noSend:be(t.noSend,"noSend"),sendWith:_g(t.sendWith)}}function hc(n){gt(n,"args");let t=gt(n.spends,"spends"),e=Object.create(null);for(let[r,s]of Object.entries(t)){/^(?:0|[1-9]\d*)$/.test(r)||wt("spends key","a canonical input index");let o=ee(Number(r),"spends key",void 0,0,_i),c=gt(s,`spends.${r}`);e[o]={unlockingScript:Li(c.unlockingScript,`spends.${r}.unlockingScript`),sequenceNumber:c.sequenceNumber===void 0?void 0:ee(c.sequenceNumber,`spends.${r}.sequenceNumber`,void 0,0,_i)}}let i={spends:e,reference:on(n.reference,"reference"),options:Qw(n.options),isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!0,isRemixChange:!1,isTestWerrReviewActions:!1};return i.isSendWith=i.options.sendWith.length>0,i.options.sendWith.length>=xn&&wt("sendWith",`at most ${xn-1} transaction IDs when the signed transaction joins the broadcast set`),i.isDelayed=i.options.acceptDelayedBroadcast,i.isNoSend=i.options.noSend,i}function pc(n){return gt(n,"args"),{reference:on(n.reference,"reference")}}function tx(n){return n===void 0?void 0:(gt(n,"paymentRemittance"),{derivationPrefix:on(n.derivationPrefix,"derivationPrefix"),derivationSuffix:on(n.derivationSuffix,"derivationSuffix"),senderIdentityKey:He(n.senderIdentityKey,"senderIdentityKey")})}function ex(n){return n===void 0?void 0:(gt(n,"insertionRemittance"),{basket:dc(n.basket),customInstructions:Tr(n.customInstructions,"customInstructions",0,1e3),tags:Ne(n.tags,"tags").map(e=>fd(e))})}function nx(n){if(gt(n,"output"),n.protocol!=="basket insertion"&&n.protocol!=="wallet payment")throw new ut("protocol","'basket insertion' or 'wallet payment'");return n.protocol==="wallet payment"?(n.paymentRemittance===void 0||n.insertionRemittance!==void 0)&&wt("output remittance","only paymentRemittance for wallet payment"):(n.insertionRemittance===void 0||n.paymentRemittance!==void 0)&&wt("output remittance","only insertionRemittance for basket insertion"),{outputIndex:Fw(n.outputIndex,"outputIndex"),protocol:n.protocol,paymentRemittance:tx(n.paymentRemittance),insertionRemittance:ex(n.insertionRemittance)}}function ni(n){if(n===void 0)return;n=n.trim().toLowerCase(),oe(n,"originator",1,250);let t=n.lastIndexOf(":"),e=n;if(t!==-1){if(n.indexOf(":")!==t)throw new ut("originator","a canonical DNS hostname with an optional port");let r=n.slice(t+1);if(!/^\d{1,5}$/.test(r)||Number(r)>65535)throw new ut("originator","a canonical DNS hostname with an optional port");e=n.slice(0,t)}oe(e,"originator hostname",1,250);let i=e.split(".");for(let r of i)if(oe(r,"originator part",1,63),!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(r))throw new ut("originator","a canonical DNS hostname with an optional port");return e}function gc(n){gt(n,"args");let t={tx:$n(n.tx,"tx"),outputs:Ne(n.outputs,"outputs").map(e=>nx(e)),description:oe(n.description,"description",5,2e3),labels:Ne(n.labels,"labels").map(e=>ud(e)),seekPermission:ei(n.seekPermission,"seekPermission")};if(Ng.get(t.tx)!==!0)try{qo(t.tx),Ng.set(t.tx,!0)}catch{throw new ut("tx","a complete, exactly framed Atomic BEEF transaction")}if(t.outputs.length<1)throw new ut("outputs","at least one output to internalize from the transaction");return t}function ix(n,t){if(n!==void 0)return bc(n,t)}function bc(n,t){if(typeof n!="string")throw new ut(t,"txid as hex string and numeric output index joined with '.'");let e=/^([0-9A-Fa-f]{64})\.(0|[1-9]\d*)$/.exec(n);if(e===null)throw new ut(t,"a 32-byte txid and canonical numeric output index joined with '.'");let i=Li(e[1],`${t} txid`,64,64),r=ee(Number(e[2]),`${t} vout`,void 0,0,_i);return`${i}.${r}`}function mc(n){return gt(n,"args"),{basket:dc(n.basket),output:bc(n.output,"output")}}function yc(n){return gt(n,"args"),{type:on(n.type,"type",32,32),serialNumber:on(n.serialNumber,"serialNumber",32,32),certifier:He(n.certifier,"certifier")}}function wc(n){return gt(n,"args"),Ci(n,!1),{certifiers:Ne(n.certifiers,"certifiers").map(e=>He(e,"certifiers")),types:Ne(n.types,"types").map(e=>on(e,"types",32,32)),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0,0),privileged:be(n.privileged,"privileged"),privilegedReason:Tr(n.privilegedReason,"privilegedReason",5,50),partial:void 0}}function ld(n){let t=gt(n,"fields");for(let e of Object.keys(t))oe(e,"field name",1,50),oe(t[e],`fields.${e}`);return n}function rx(n,t){return n==="certifier"?n:He(n,t)}function sx(n,t){let e=gt(n,t);for(let i of Object.keys(e))oe(i,`${t} field name`,1,50),on(e[i],`${t} field value`);return n}function xc(n){if(gt(n,"args"),Ci(n,!1),n.acquisitionProtocol!=="issuance")throw new Error("Only acquire certificate via issuance requests allowed here.");if(n.serialNumber)throw new ut("serialNumber",'valid when acquisitionProtocol is "direct"');if(n.signature)throw new ut("signature",'valid when acquisitionProtocol is "direct"');if(n.revocationOutpoint)throw new ut("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(n.keyringRevealer)throw new ut("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(n.keyringForSubject!=null)throw new ut("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!n.certifierUrl)throw new ut("certifierUrl",'valid when acquisitionProtocol is "issuance"');return{type:on(n.type,"type",32,32),certifier:He(n.certifier,"certifier"),certifierUrl:ox(n.certifierUrl),fields:ld(n.fields),privileged:be(n.privileged,"privileged"),privilegedReason:Tr(n.privilegedReason,"privilegedReason",5,50),subject:""}}function ox(n){let t=oe(n,"certifierUrl",1,2048);if(t!==t.trim())throw new ut("certifierUrl","an exact HTTPS URL without whitespace");let e;try{e=new URL(t)}catch{throw new ut("certifierUrl","an absolute HTTPS URL")}if(e.protocol!=="https:")throw new ut("certifierUrl","an HTTPS URL");if(e.username!==""||e.password!=="")throw new ut("certifierUrl","a URL without credentials");if(e.search!==""||e.hash!=="")throw new ut("certifierUrl","a URL without a query or fragment");let i=e.hostname.toLowerCase();if(i==="localhost"||i.endsWith(".localhost")||i==="[::1]"||/^\d+(?:\.\d+){0,3}$/.test(i)||i.includes(":"))throw new ut("certifierUrl","a public DNS hostname");let r=i.split(".");if(r.length<2||r.some(s=>!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(s)))throw new ut("certifierUrl","a public DNS hostname");return t.replace(/\/+$/,"")}function Ic(n){if(gt(n,"args"),Ci(n,!1),n.acquisitionProtocol!=="direct")throw new Error("Only acquire direct certificate requests allowed here.");if(!n.serialNumber)throw new ut("serialNumber",'valid when acquisitionProtocol is "direct"');if(!n.signature)throw new ut("signature",'valid when acquisitionProtocol is "direct"');if(!n.revocationOutpoint)throw new ut("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!n.keyringRevealer)throw new ut("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(n.keyringForSubject==null)throw new ut("keyringForSubject",'valid when acquisitionProtocol is "direct"');return{type:on(n.type,"type",32,32),serialNumber:on(n.serialNumber,"serialNumber",32,32),certifier:He(n.certifier,"certifier"),revocationOutpoint:bc(n.revocationOutpoint,"revocationOutpoint"),fields:ld(n.fields),signature:Lg(n.signature,"signature"),keyringRevealer:rx(n.keyringRevealer,"keyringRevealer"),keyringForSubject:sx(n.keyringForSubject,"keyringForSubject"),privileged:be(n.privileged,"privileged"),privilegedReason:Tr(n.privilegedReason,"privilegedReason",5,50),subject:""}}function Sc(n){gt(n,"args"),gt(n.certificate,"certificate"),Ci(n,!1),n.certificate.fields!==void 0&&ld(n.certificate.fields);let t={type:Bg(n.certificate.type,"certificate.type",32,32),serialNumber:Bg(n.certificate.serialNumber,"certificate.serialNumber",32,32),certifier:n.certificate.certifier===void 0?void 0:He(n.certificate.certifier,"certificate.certifier"),subject:n.certificate.subject===void 0?void 0:He(n.certificate.subject,"certificate.subject"),revocationOutpoint:ix(n.certificate.revocationOutpoint,"certificate.revocationOutpoint"),signature:n.certificate.signature===void 0?void 0:Lg(n.certificate.signature,"certificate.signature"),fieldsToReveal:Ne(n.fieldsToReveal,"fieldsToReveal").map(e=>oe(e,`fieldsToReveal ${e}`,1,50)),verifier:He(n.verifier,"verifier"),privileged:be(n.privileged,"privileged"),privilegedReason:Tr(n.privilegedReason,"privilegedReason",5,50)};return t.fieldsToReveal.length>Og&&wt("fieldsToReveal",`at most ${Og} fields`),new Set(t.fieldsToReveal).size!==t.fieldsToReveal.length&&wt("fieldsToReveal","unique field names"),t}function vc(n){return gt(n,"args"),{identityKey:He(n.identityKey,"identityKey"),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0,0),seekPermission:ei(n.seekPermission,"seekPermission")}}function ax(n){let t=gt(n,"attributes"),e=Object.keys(t);(e.length<1||e.length>Pg)&&wt("attributes",`an object containing 1-${Pg} fields`);for(let i of e)oe(i,`field name ${i}`,1,50),oe(t[i],`attributes.${i}`,1,500);return n}function Ac(n){return gt(n,"args"),{attributes:ax(n.attributes),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0,0),seekPermission:ei(n.seekPermission,"seekPermission")}}function Ec(n){gt(n,"args");let t;if(n.tagQueryMode===void 0||n.tagQueryMode==="any")t="any";else if(n.tagQueryMode==="all")t="all";else throw new ut("tagQueryMode","undefined, 'any', or 'all'");return n.include!==void 0&&n.include!=="locking scripts"&&n.include!=="entire transactions"&&wt("include","undefined, 'locking scripts', or 'entire transactions'"),{basket:dc(n.basket),tags:Ne(n.tags,"tags").map(i=>fd(i)),tagQueryMode:t,includeLockingScripts:n.include==="locking scripts",includeTransactions:n.include==="entire transactions",includeCustomInstructions:be(n.includeCustomInstructions,"includeCustomInstructions"),includeTags:be(n.includeTags,"includeTags"),includeLabels:be(n.includeLabels,"includeLabels"),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0),seekPermission:ei(n.seekPermission,"seekPermission"),knownTxids:[]}}function kc(n){gt(n,"args");let t;if(n.labelQueryMode===void 0||n.labelQueryMode==="any")t="any";else if(n.labelQueryMode==="all")t="all";else throw new ut("labelQueryMode","undefined, 'any', or 'all'");return{labels:Ne(n.labels,"labels").map(i=>ud(i)),labelQueryMode:t,includeLabels:be(n.includeLabels,"includeLabels"),includeInputs:be(n.includeInputs,"includeInputs"),includeInputSourceLockingScripts:be(n.includeInputSourceLockingScripts,"includeInputSourceLockingScripts"),includeInputUnlockingScripts:be(n.includeInputUnlockingScripts,"includeInputUnlockingScripts"),includeOutputs:be(n.includeOutputs,"includeOutputs"),includeOutputLockingScripts:be(n.includeOutputLockingScripts,"includeOutputLockingScripts"),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0,0),seekPermission:ei(n.seekPermission,"seekPermission")}}function Tc(n){let t=gt(n,"args");if(t.identityKey!==void 0&&t.identityKey!==!0&&wt("identityKey","true or undefined"),t.forSelf!==void 0&&ms(t.forSelf,"forSelf",!1),t.identityKey===!0){t.protocolID!==void 0&&cd(t.protocolID),t.keyID!==void 0&&oe(t.keyID,"keyID",1,800),t.counterparty!==void 0&&ad(t.counterparty,"counterparty"),Ci(t);return}kr(n,"args")}function Oc(n){let t=gt(n,"args");He(t.counterparty,"counterparty"),He(t.verifier,"verifier"),Ci(t,!1)}function Pc(n){let t=gt(n,"args");ad(t.counterparty,"counterparty"),He(t.verifier,"verifier"),cd(t.protocolID),oe(t.keyID,"keyID",1,800),Ci(t,!1)}function Rc(n){let t=gt(n,"args");kr(n),$n(t.plaintext,"plaintext")}function Nc(n){let t=gt(n,"args");kr(n),$n(t.ciphertext,"ciphertext")}function Bc(n){let t=gt(n,"args");kr(n),$n(t.data,"data")}function _c(n){let t=gt(n,"args");kr(n),$n(t.data,"data"),$n(t.hmac,"hmac",32)}function Ug(n,t,e){let i=n[t]!==void 0,r=n[e]!==void 0;i===r&&wt(`${t}, ${e}`,"exactly one value"),i&&$n(n[t],t),r&&$n(n[e],e,32)}function Cc(n){let t=gt(n,"args");kr(n),Ug(t,"data","hashToDirectlySign")}function Lc(n){let t=gt(n,"args");kr(n),Ug(t,"data","hashToDirectlyVerify");let e=$n(t.signature,"signature",void 0,72);gs(e)||wt("signature","a canonical DER-encoded ECDSA signature"),t.forSelf!==void 0&&ms(t.forSelf,"forSelf",!1)}function Uc(n){let t=gt(n,"args");ee(t.height,"height",void 0,1,_i)}function Ui(n,t="args"){gt(n,t)}var cx="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";var Mc;(function(n){n[n.Silent=0]="Silent",n[n.App=1]="App",n[n.Counterparty=2]="Counterparty"})(Mc||(Mc={}));var ux=Object.prototype.hasOwnProperty,fx=new Set(["BEEF","atomicBEEF","beef","ciphertext","competingBeef","data","encryptedLinkage","encryptedLinkageProof","hashToDirectlySign","hashToDirectlyVerify","hmac","inputBEEF","payload","plaintext","signature","transaction","tx"]);function Dc(n){return n==null||typeof n!="object"||typeof ArrayBuffer>"u"?!1:ArrayBuffer.isView(n)&&Object.prototype.toString.call(n)==="[object Uint8Array]"}function Mg(n){return Number.isInteger(n)&&n>=0&&n<=255}function dx(n){return n!=null&&typeof n=="object"&&typeof ArrayBuffer<"u"&&(ArrayBuffer.isView(n)||Object.prototype.toString.call(n)==="[object ArrayBuffer]")}function lx(n){for(let t=0;t<n.length;t++)if(!ux.call(n,t)||!Mg(n[t]))return;return n}function hx(n){if(!(n==null||typeof n!="object"))try{let t=Object.keys(n);if(t.length===0)return;let e=[];for(let i=0;i<t.length;i++){if(t[i]!==String(i))return;let r=n[t[i]];if(!Mg(r))return;e.push(r)}return e}catch{return}}function hd(n){if(Dc(n))return n;if(!dx(n))return Array.isArray(n)?lx(n):hx(n)}function px(n,t){let e=this==null?void 0:this[n];return Dc(e)?Array.from(e):Dc(t)?Array.from(t):t}function ys(n,t){let e=JSON.stringify(n,px,t);if(e===void 0)throw new TypeError("BRC-100 JSON payload is not serializable");return e}function gx(n,t,e,i){let r=hd(e);r!=null?n[t]=r:i(e)}function Hc(n){let t=new WeakSet,e=[n];for(;e.length>0;){let i=e.pop();if(!(i==null||typeof i!="object"||Dc(i))&&!t.has(i)){if(t.add(i),Array.isArray(i)){for(let r of i)e.push(r);continue}for(let[r,s]of Object.entries(i))fx.has(r)?gx(i,r,s,o=>e.push(o)):e.push(s)}}return n}var bx=Number,mx=String,yx=Uint8Array,wx=URL,xx=Array.prototype,Ix=Array.isArray,Sx=Date.parse,vx=Number.MAX_SAFE_INTEGER,Ax=Number.isFinite,Fc=Number.isInteger,Pr=Number.isSafeInteger,eb=Object.prototype,Ex=Object.prototype.hasOwnProperty,Mi=Object.create,Wc=Object.defineProperty,nb=Object.freeze,ye=Object.getOwnPropertyDescriptor,Vc=Object.getPrototypeOf,Sn=Object.keys,Nr=Reflect.ownKeys,kx=RegExp.prototype.exec,Tx=RegExp.prototype.test,ib=String.prototype.split,Ox=String.prototype.toLowerCase,Px=String.prototype.trim,xd=String.prototype.replace,Rx=String.prototype.normalize,Nx=String.prototype.indexOf,Bx=String.prototype.slice,_x=String.prototype.startsWith,Cx=RegExp,Dg=ye(URL.prototype,"protocol")?.get,Id=Vc(Uint8Array.prototype),Hg=ye(Id,"buffer")?.get,$g=ye(Id,"length")?.get,qg=ye(Id,Symbol.toStringTag)?.get,Lx=Uint8Array.prototype.set,Fg=typeof SharedArrayBuffer>"u"?void 0:ye(SharedArrayBuffer.prototype,"byteLength")?.get,Wg=Map,cn=Set,Vg=WeakMap,Ux=WeakSet,Mx=Map.prototype.get,Dx=Map.prototype.set,Hx=Map.prototype.has,$x=Map.prototype.forEach,qx=Set.prototype.add,Fx=Set.prototype.has,Wx=ye(Set.prototype,"size").get,Vx=WeakMap.prototype.get,Kx=WeakMap.prototype.set,zx=WeakSet.prototype.add,Xx=WeakSet.prototype.has,Pt=Reflect.apply;function qt(n){return Ix(n)}function In(n){return bx(n)}function Be(n){return mx(n)}function jt(n){return Pt(Ox,n,[])}function Sd(n,t){return Pt(ib,n,[t])}function xs(n,t){return Pt(Tx,n,[t])}function Rr(n,t){return Pt(kx,n,[t])}function Kc(n,t){return Pt(Ex,n,[t])}function Ko(n){if(!(Hg==null||$g==null||qg==null))try{return{buffer:Pt(Hg,n,[]),length:Pt($g,n,[]),tag:Pt(qg,n,[])}}catch{return}}function md(n){return Ko(n)?.tag==="Uint8Array"}function jx(n){if(Fg==null)return!1;try{return Pt(Fg,n,[]),!0}catch{return!1}}function Or(n,t){return Pt(Mx,n,[t])}function pd(n,t,e){Pt(Dx,n,[t,e])}function Gx(n,t){return Pt(Hx,n,[t])}function Yx(n,t){Pt($x,n,[t])}function Gt(n,t){Pt(qx,n,[t])}function un(n,t){return Pt(Fx,n,[t])}function zc(n){return Pt(Wx,n,[])}function Kg(n,t){return Pt(Vx,n,[t])}function Fo(n,t,e){Pt(Kx,n,[t,e])}function gd(n,t){Pt(zx,n,[t])}function zg(n,t){return Pt(Xx,n,[t])}var ri=new cn;Gt(ri,"completed");Gt(ri,"unprocessed");Gt(ri,"sending");Gt(ri,"unproven");Gt(ri,"unsigned");Gt(ri,"nosend");Gt(ri,"nonfinal");Gt(ri,"failed");var Gc=new cn;Gt(Gc,"unproven");Gt(Gc,"sending");Gt(Gc,"failed");var ws=1e6,Xg=ws+2,Zx=16*1024*1024,Jx="0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",jg=new Ni,vd=Symbol("createActionSourceEvidence"),zo=Symbol("byteBudgetExceeded"),Wo=new Ux,Xc=nb(Mi(null));function rb(n){if(!qt(n))return;let t=ye(n,"length");if(t==null||!("value"in t)||!Pr(t.value)||t.value<0||t.value>ws)throw new Error("Wallet request arrays must have a bounded own length");let e=t.value;if(Nr(n).length!==e+1)throw new Error("Wallet request arrays must contain only dense data properties");let r=[];r.length=e;for(let s=0;s<e;s++){let o=ye(n,Be(s));if(o==null||!("value"in o))throw new Error("Wallet request arrays must contain only dense data properties");r[s]=o.value}return r}function Gg(n){let t=At(n);if(t==null)return;let e=Mi(null),i=Nr(t);for(let r=0;r<i.length;r++){let s=i[r];if(typeof s!="string")continue;let o=ye(t,s);o!=null&&"value"in o&&(e[s]=o.value)}return e}function Ze(n,t,e=[]){let i=Mi(null);for(let r=0;r<t.length;r++){let s=t[r],o=!1;for(let c=0;c<e.length;c++)if(e[c]===s){o=!0;break}i[s]=o?rb(n[s]):n[s]}return i}function sb(n){let t=At(n);if(t==null)return Xc;let e=ye(t,vd)?.value;if(e!=null)return e;let i=t.inputBEEF,r=t.inputs;if(i===void 0||!qt(r)||r.length===0)return Xc;let s=ii(i,"createAction","request.inputBEEF"),o;try{o=hs(s)}catch{L("createAction","request.inputBEEF","an exactly framed BEEF envelope")}let c=Mi(null);for(let u=0;u<r.length;u++){let f=r[u],d=At(f);if(d==null||typeof d.outpoint!="string")continue;let l=Rr(/^([0-9a-fA-F]{64})\.(0|[1-9]\d*)$/,d.outpoint);if(l==null)continue;let p=In(l[2]);if(p>4294967295)continue;let b=jt(l[1]),g=Or(o.transactions,b)?.outputs[p];g!==void 0&&(c[`${b}.${p}`]=g.satoshis)}return nb(c)}function bt(n,t){let e=At(t);if(e==null)return t;let i=At(e.options);switch(n){case"createAction":{let r={inputs:qt(e.inputs)?(()=>{let s=[];s.length=e.inputs.length;for(let o=0;o<e.inputs.length;o++){let c=e.inputs[o],u=At(c);s[o]=u==null?c:Ze(u,["outpoint","unlockingScript","sequenceNumber"])}return s})():e.inputs,outputs:qt(e.outputs)?(()=>{let s=[];s.length=e.outputs.length;for(let o=0;o<e.outputs.length;o++){let c=e.outputs[o],u=At(c);s[o]=u==null?c:Ze(u,["satoshis","lockingScript"])}return s})():e.outputs,version:e.version,lockTime:e.lockTime,options:i==null?{signAndProcess:void 0,returnTXIDOnly:void 0,sendWith:void 0,randomizeOutputs:void 0,knownTxids:void 0}:Ze(i,["signAndProcess","returnTXIDOnly","sendWith","randomizeOutputs","knownTxids"],["sendWith","knownTxids"])};return Wc(r,vd,{value:sb(e),writable:!1,configurable:!1,enumerable:!1}),r}case"signAction":{let r=At(e.spends),s=Mi(null);if(r!=null){let o=Sn(r);for(let c=0;c<o.length;c++){let u=o[c],f=r[u],d=At(f);s[u]=d==null?f:Ze(d,["unlockingScript","sequenceNumber"])}}return{spends:s,options:i==null?{returnTXIDOnly:void 0,sendWith:void 0}:Ze(i,["returnTXIDOnly","sendWith"],["sendWith"])}}case"listActions":return Ze(e,["labels","labelQueryMode","includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts","limit"],["labels"]);case"listOutputs":return Ze(e,["basket","tags","tagQueryMode","include","includeCustomInstructions","includeTags","includeLabels","limit"],["tags"]);case"listCertificates":return Ze(e,["limit","certifiers","types"],["certifiers","types"]);case"discoverByIdentityKey":return Ze(e,["limit","identityKey"]);case"discoverByAttributes":{let r=At(e.attributes);return{limit:e.limit,attributes:r==null?e.attributes:{...r}}}case"revealCounterpartyKeyLinkage":return Ze(e,["verifier","counterparty"]);case"revealSpecificKeyLinkage":return Ze(e,["verifier","counterparty","protocolID","keyID"],["protocolID"]);case"acquireCertificate":return{...Ze(e,["acquisitionProtocol","type","certifier","serialNumber","revocationOutpoint","signature"]),fields:Gg(e.fields)};case"proveCertificate":return{fieldsToReveal:rb(e.fieldsToReveal),verifier:e.verifier,certificate:(()=>{let r=At(e.certificate);return r==null?e.certificate:{...Ze(r,["type","serialNumber","subject","certifier","revocationOutpoint","signature"]),fields:Gg(r.fields)}})()};default:return t}}function L(n,t,e){throw new Error(`Invalid ${n} result ${t}: expected ${e}`)}function ob(n){let t=ye(n,"length");return t!=null&&"value"in t&&Pr(t.value)&&t.value>=0?t.value:void 0}function ab(n,t,e,i=e){if(t>e)return;let r=Nr(n);if(r.length!==t+1)return;for(let o=0;o<r.length;o++){let c=r[o];if(c!=="length"&&(typeof c!="string"||!Fc(In(c))||In(c)<0||In(c)>=t||Be(In(c))!==c))return}let s=t<=i?[]:void 0;s!==void 0&&(s.length=t);for(let o=0;o<t;o++){let c=ye(n,Be(o));if(c==null||c.enumerable!==!0||!("value"in c)||!Fc(c.value)||c.value<0||c.value>255)return;s!==void 0&&(s[o]=c.value)}return s??zo}function Qx(n,t,e){let i=Vc(n);if(i!==eb&&i!==null)return;let r=Nr(n);if(r.length===0||r.length>t)return;let s=r.length<=e?[]:void 0;s!==void 0&&(s.length=r.length);for(let o=0;o<r.length;o++){let c=r[o];if(c!==Be(o))return;let u=ye(n,c);if(u==null||u.enumerable!==!0||!("value"in u)||!Fc(u.value)||u.value<0||u.value>255)return;s!==void 0&&(s[o]=u.value)}return s??zo}function t2(n){switch(n){case"BEEF":case"atomicBEEF":case"beef":case"ciphertext":case"competingBeef":case"data":case"encryptedLinkage":case"encryptedLinkageProof":case"hashToDirectlySign":case"hashToDirectlyVerify":case"hmac":case"inputBEEF":case"payload":case"plaintext":case"signature":case"transaction":case"tx":return!0;default:return!1}}function cb(n,t,e){let i=Ko(n);i?.tag!=="Uint8Array"&&L(t,"byte array","an intrinsic Uint8Array");let{buffer:r,length:s}=i;jx(r)&&L(t,"byte array","an unshared Uint8Array"),s>268435456&&L(t,"byte array",`at most ${268435456} bytes`),s>e&&L(t,"byte arrays",`at most ${268435456} total bytes`);let o=new yx(s);try{Pt(Lx,o,[n])}catch{L(t,"byte array","an intrinsic Uint8Array")}return o}function Ad(n,t,e=!1){let i=[],r=new Vg,s=new Vg,o=0,c=0,u=(d,l)=>{if(d==null||typeof d!="object")return typeof d=="function"&&L(t,"value","data without functions"),d;if(!qt(d)&&!md(d)&&e&&t2(l)){let w=Kg(s,d);if(w!==void 0)return w;let S=Qx(d,268435456,268435456-c);if(S===zo&&L(t,"byte arrays",`at most ${268435456} total bytes`),S!==void 0)return o++,o>ws&&L(t,"object graph","a bounded result"),S.length>268435456-c&&L(t,"byte arrays",`at most ${268435456} total bytes`),c+=S.length,gd(Wo,S),Fo(s,d,S),S}let p=Kg(r,d);if(p!==void 0)return p;if(o++,o>ws&&L(t,"object graph","a bounded result"),md(d)){let w=cb(d,t,268435456-c);return c+=Ko(w).length,gd(Wo,w),Fo(r,d,w),w}if(qt(d)){Vc(d)!==xx&&L(t,"array prototype","the intrinsic Array.prototype");let S=ob(d);S===void 0&&L(t,"array length","an own integer data property");let C=ab(d,S,268435456,268435456-c);if(C===zo&&L(t,"byte arrays",`at most ${268435456} total bytes`),C!==void 0)return c+=C.length,gd(Wo,C),Fo(r,d,C),C;S>ws&&L(t,"array length",`at most ${ws} entries`);let E=[];return E.length=S,Fo(r,d,E),i[i.length]={source:d,target:E,array:!0},E}let b=Vc(d);b!==null&&b!==eb&&L(t,"object prototype","Object.prototype or null");let g=b===null?Mi(null):{};return Fo(r,d,g),i[i.length]={source:d,target:g,array:!1},g},f=u(n);for(;i.length>0;){let d=i[i.length-1];i.length-=1;let l=Nr(d.source);if(d.array){o+=l.length,o>Xg&&L(t,"object graph","a bounded result");let p=d.source,b=d.target.length;l.length!==b+1&&L(t,"array shape","a dense standard array without extra properties");for(let g=0;g<l.length;g++){let w=l[g];if(typeof w!="string"&&L(t,"array key","a string"),gn(w)&&L(t,`array key ${w}`,"a safe array key"),w!=="length"){let C=In(w);(!Fc(C)||C<0||C>=b||Be(C)!==w)&&L(t,`array key ${w}`,"a canonical in-range array index")}let S=ye(p,w);(S==null||!("value"in S))&&L(t,`array property ${w}`,"a data property"),w!=="length"&&Wc(d.target,w,{value:u(S.value),enumerable:S.enumerable,configurable:!0,writable:!0})}continue}o+=l.length,o>Xg&&L(t,"object graph","a bounded result");for(let p=0;p<l.length;p++){let b=l[p];typeof b!="string"&&L(t,"object key","a string"),gn(b)&&L(t,`object key ${b}`,"a safe record key");let g=ye(d.source,b);(g==null||!("value"in g))&&L(t,`object property ${b}`,"a data property"),Wc(d.target,b,{value:u(g.value,b),enumerable:g.enumerable,configurable:!0,writable:!0})}}return f}function ub(n,t){return Ad(n,t)}function fb(n,t){return Ad(n,t,!0)}function qe(n,t,e="value"){(n==null||typeof n!="object"||qt(n))&&L(t,e,"an object");let i=Mi(null),r=Nr(n);for(let s=0;s<r.length;s++){let o=r[s];typeof o!="string"&&L(t,`${e} key`,"a string");let c=ye(n,o);(c==null||!("value"in c))&&L(t,`${e}.${o}`,"a data property"),i[o]=c.value}return i}function ii(n,t,e,i,r=268435456){let s;if(n!=null&&typeof n=="object"&&md(n)){let c=zg(Wo,n)?n:cb(n,t,268435456);Ko(c).length<=r&&(s=c)}else if(qt(n)){let c=ob(n);if(c===void 0&&L(t,e,"an own integer array length"),c>r&&L(t,e,`at most ${r} bytes`),zg(Wo,n))s=n;else{let u=ab(n,c,r);u===zo&&L(t,e,`at most ${r} bytes`),s=u}}s==null&&L(t,e,"an array of bytes");let o=qt(s)?s.length:Ko(s).length;return o>r&&L(t,e,`at most ${r} bytes`),i!==void 0&&o!==i&&L(t,e,`${i} bytes`),s}function me(n,t,e,i=0,r){typeof n!="string"&&L(t,e,"a string");let s=xe(n).length;return(s<i||r!==void 0&&s>r)&&L(t,e,`${i}${r===void 0?"+":`\u2013${r}`} UTF-8 bytes`),n}function $e(n,t,e,i){let r=me(n,t,e);return xs(/^(?:[0-9a-fA-F]{2})*$/,r)||L(t,e,"an even-length hex string"),i!==void 0&&r.length!==i*2&&L(t,e,`${i} hexadecimal bytes`),r}function Xo(n,t,e){let i=$e(n,t,e,33);fc(i)||L(t,e,"a valid compressed secp256k1 public key")}function ne(n,t,e,i=4294967295){return(!Pr(n)||n<0||n>i)&&L(t,e,`an integer from 0 to ${i}`),n}function Ed(n,t,e,i,r){return(!Pr(n)||n<i||n>r)&&L(t,e,`an integer from ${i} to ${r}`),n}function $c(n,t,e){n[e]!==!0&&L(t,e,"true")}function db(n,t,e){typeof n[e]!="boolean"&&L(t,e,"a boolean")}function qn(n,t,e){if(n!==void 0)return qt(n)||L(t,e,"an array"),n.length>1e5&&L(t,e,"at most 100000 entries"),n}function jc(n,t,e,i,r){let s=qn(n,t,e);if(s!=null)for(let o=0;o<s.length;o++)me(s[o],t,`${e}[${o}]`,i,r)}function e2(n,t,e){let i=me(n,t,e,1,64);xs(/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/,i)||L(t,e,"an ISO timestamp with a timezone");let r=Sx(i);Ax(r)||L(t,e,"a valid ISO timestamp")}function n2(n,t,e,i){let r=me(n,t,e,1,i);try{let s=new wx(r);if(Dg==null)throw new Error;let o=Pt(Dg,s,[]);if(o!=="https:"&&o!=="http:")throw new Error}catch{L(t,e,"an absolute HTTP(S) URL")}}function i2(n,t){let e=qn(n,t,"sendWithResults");if(e!=null){e.length>xn+1&&L(t,"sendWithResults",`at most ${xn+1} transaction results`);for(let i=0;i<e.length;i++){let r=e[i],s=`sendWithResults[${i}]`,o=qe(r,t,s);$e(o.txid,t,`${s}.txid`,32),un(Gc,o.status)||L(t,`${s}.status`,"a supported status")}}}function lb(n,t,e,i){let r=n.inputs[t];r==null&&L(e,i,"a transaction input");let s=jt($e(r.sourceTXID,e,`${i}.sourceTXID`,32)),o=ne(r.sourceOutputIndex,e,`${i}.sourceOutputIndex`);return`${s}.${o}`}function Yg(n,t,e,i,r){let s=At(e);if(s==null){yd(n,t,i,r);return}let o=s.version===void 0?1:ne(s.version,t,"request.version"),c=s.lockTime===void 0?0:ne(s.lockTime,t,"request.lockTime");n.version!==o&&L(t,"tx.version","the requested transaction version"),n.lockTime!==c&&L(t,"tx.lockTime","the requested transaction lock time");let u=new Wg;for(let w=0;w<n.inputs.length;w++){let S=lb(n,w,t,`tx.inputs[${w}]`);Gx(u,S)&&L(t,`tx.inputs[${w}]`,"a unique transaction input outpoint"),pd(u,S,w)}let f=s.inputs===void 0?[]:qn(s.inputs,t,"request.inputs"),d=new cn;for(let w=0;w<f.length;w++){let S=f[w],C=`request.inputs[${w}]`,E=qe(S,t,C),A=Is(E.outpoint,t,`${C}.outpoint`),k=`${A.txid}.${A.outputIndex}`;un(d,k)&&L(t,`${C}.outpoint`,"a unique requested input"),Gt(d,k);let B=Or(u,k);B===void 0&&L(t,"tx.inputs","every requested input exactly once");let _=n.inputs[B],$=E.sequenceNumber===void 0?4294967295:ne(E.sequenceNumber,t,`${C}.sequenceNumber`);if((_.sequence??4294967295)!==$&&L(t,`tx.inputs[${B}].sequence`,"the requested input sequence"),E.unlockingScript!==void 0){let R=jt($e(E.unlockingScript,t,`${C}.unlockingScript`));jt(Ye(_.unlockingScript))!==R&&L(t,`tx.inputs[${B}].unlockingScript`,"the requested unlocking script")}}let l=s.outputs===void 0?[]:qn(s.outputs,t,"request.outputs"),b=At(s.options)?.randomizeOutputs===!1,g=new Wg;for(let w=0;w<n.outputs.length;w++){let S=n.outputs[w],C=ne(S.satoshis,t,`tx.outputs[${w}].satoshis`,21e14);if(l.length>0){let E=`${C}:${jt(Ye(S.lockingScript))}`;pd(g,E,(Or(g,E)??0)+1)}}for(let w=0;w<l.length;w++){let S=l[w],C=`request.outputs[${w}]`,E=qe(S,t,C),A=ne(E.satoshis,t,`${C}.satoshis`,21e14),k=jt($e(E.lockingScript,t,`${C}.lockingScript`));if(b){let $=n.outputs[w];($==null||$.satoshis!==A||jt(Ye($.lockingScript))!==k)&&L(t,`tx.outputs[${w}]`,"the requested output at the requested position");continue}let B=`${A}:${k}`,_=Or(g,B)??0;_===0&&L(t,"tx.outputs","every requested output with its requested amount and script"),pd(g,B,_-1)}yd(n,t,i,r)}function yd(n,t,e=Xc,i=!1){let r=0,s=!1,o=new cn;for(let u=0;u<n.inputs.length;u++){let f=n.inputs[u],d=lb(n,u,t,`tx.inputs[${u}]`);un(o,d)&&L(t,`tx.inputs[${u}]`,"a unique transaction input outpoint"),Gt(o,d);let l=f.sourceSatoshis??e[d];if(l===void 0){i||L(t,`tx.inputs[${u}].sourceSatoshis`,"source transaction evidence for every completed transaction input"),s=!0;continue}r+=ne(l,t,`tx.inputs[${u}].sourceSatoshis`,21e14),(!Pr(r)||r>21e14)&&L(t,"tx.inputs","a valid total input value")}let c=0;for(let u=0;u<n.outputs.length;u++){let f=n.outputs[u];c+=ne(f.satoshis,t,`tx.outputs[${u}].satoshis`,21e14),(!Pr(c)||c>21e14)&&L(t,"tx.outputs","a valid total output value")}!s&&c>r&&L(t,"tx.outputs","a total value no greater than the transaction inputs")}function r2(n,t,e){let i=At(At(e)?.spends);if(i==null)return;let r=Sn(i);for(let s=0;s<r.length;s++){let o=r[s],c=i[o],u=`request.spends.${o}`;xs(/^(?:0|[1-9]\d*)$/,o)||L(t,u,"a canonical input index");let f=In(o),d=n.inputs[f];(!Pr(f)||d==null)&&L(t,`tx.inputs[${o}]`,"the requested input index");let l=qe(c,t,u),p=jt($e(l.unlockingScript,t,`${u}.unlockingScript`));jt(Ye(d.unlockingScript))!==p&&L(t,`tx.inputs[${f}]`,"the requested unlocking script"),l.sequenceNumber!==void 0&&d.sequence!==ne(l.sequenceNumber,t,`${u}.sequenceNumber`)&&L(t,`tx.inputs[${f}].sequence`,"the requested input sequence")}}function s2(n,t,e){let i=t==="createAction"?sb(e):Xc,r=n.txid===void 0?void 0:$e(n.txid,t,"txid",32),s=n.tx===void 0?void 0:Zg(n.tx,t,"tx",r),o=s?.txid;r!==void 0&&o!==void 0&&!an(r,o)&&L(t,"tx","a BEEF transaction matching txid");let c=qn(n.noSendChange,t,"noSendChange");if(c!=null)for(let g=0;g<c.length;g++)Is(c[g],t,`noSendChange[${g}]`);i2(n.sendWithResults,t);let u;if(n.signableTransaction!==void 0){t!=="createAction"&&L(t,"signableTransaction","an absent field"),(n.txid!==void 0||n.tx!==void 0)&&L(t,"signableTransaction","exclusive of txid and tx");let g=qe(n.signableTransaction,t,"signableTransaction");u=Zg(g.tx,t,"signableTransaction.tx"),kd(g.reference,t,"signableTransaction.reference")}let f=At(e);if(f!==void 0&&t==="createAction"){let g=f.inputs===void 0?[]:qn(f.inputs,t,"request.inputs"),w=f.outputs===void 0?[]:qn(f.outputs,t,"request.outputs"),S=At(f.options),C=qt(S?.sendWith)?S.sendWith:[],E=g.length>0||w.length>0||C.length===0,A=!1;for(let B=0;B<g.length;B++)if(At(g[B])?.unlockingScript===void 0){A=!0;break}let k=E&&(S?.signAndProcess===!1||A);E&&k&&u===void 0&&L(t,"signableTransaction","the requested deferred-signing transaction"),E&&!k&&r===void 0&&L(t,"txid","the requested completed transaction"),E&&!k&&u!==void 0&&L(t,"signableTransaction","absent for a completed transaction request")}f!==void 0&&t==="signAction"&&r===void 0&&L(t,"txid","the completed signed transaction"),t==="createAction"?(s!==void 0&&Yg(s,t,e,i,!1),u!==void 0&&Yg(u,t,e,i,!0)):s!==void 0&&(r2(s,t,e),yd(s,t));let d=u?.txid,l=r??d;if(c!=null){l===void 0&&L(t,"noSendChange","associated with a transaction");for(let g=0;g<c.length;g++){let w=c[g];an(Sd(Be(w),".")[0],l)||L(t,`noSendChange[${g}]`,"an outpoint of the returned transaction")}}let p=At(At(e)?.options),b=new cn;if(l!==void 0&&Gt(b,jt(l)),qt(p?.sendWith))for(let g=0;g<p.sendWith.length;g++)Gt(b,jt(Be(p.sendWith[g])));if(qt(n.sendWithResults)){let g=new cn;for(let w=0;w<n.sendWithResults.length;w++){let S=n.sendWithResults[w],C=`sendWithResults[${w}].txid`,E=jt(Be(qe(S,t,`sendWithResults[${w}]`).txid));un(g,E)&&L(t,C,"a unique transaction"),Gt(g,E),zc(b)>0&&!un(b,E)&&L(t,C,"a submitted or returned transaction")}}n.tx!==void 0&&n.txid===void 0&&L(t,"txid","present with tx"),At(e)!==void 0&&n.txid!==void 0&&n.tx===void 0&&At(At(e)?.options)?.returnTXIDOnly!==!0&&L(t,"tx","transaction evidence unless returnTXIDOnly was explicitly requested"),t==="signAction"&&n.noSendChange!==void 0&&L(t,"noSendChange","an absent field"),n.txid===void 0&&n.signableTransaction===void 0&&(!qt(n.sendWithResults)||n.sendWithResults.length===0)&&L(t,"outcome","a transaction, signable transaction, or batch-send result")}function Zg(n,t,e,i){let r=ii(n,t,e),s=i===void 0?jg.get(r):void 0;if(s!=null)return s;try{let o=qo(r);return i===void 0&&jg.set(r,o),o}catch{}try{return qo(r,!0)}catch{}try{let o=hs(r),c=i===void 0?void 0:jt(i),u;Yx(o.transactions,(l,p)=>{l!==void 0&&(u=p)});let f=(c!==void 0&&Or(o.transactions,c)!==void 0?c:void 0)??o.atomicTxid??u,d=f===void 0?void 0:Or(o.transactions,jt(f));if(d===void 0)throw new Error("BEEF subject transaction is missing");return d}catch{L(t,e,"a complete, exactly framed BEEF transaction")}}function o2(n,t,e){let i=ii(n,t,e);try{return hs(i)}catch{L(t,e,"a complete, exactly framed BEEF envelope")}}function Is(n,t,e){let i=me(n,t,e),r=Rr(/^([0-9a-fA-F]{64})\.(0|[1-9]\d*)$/,i);return(r==null||In(r[2])>4294967295)&&L(t,e,"a canonical transaction outpoint"),{txid:jt(r[1]),outputIndex:In(r[2])}}function kd(n,t,e){let i=me(n,t,e,1);return xs(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,i)||L(t,e,"a canonical base64 string"),i}function qc(n){return n<253?1:n<=65535?3:n<=4294967295?5:9}function Vo(n,t,e,i=!1){let r=qe(n,t,e),s=Sn(r);for(let o=0;o<s.length;o++){let c=s[o],u=r[c],f=xe(c).length;(f<1||f>50||gn(c))&&L(t,`${e} key`,"a safe 1\u201350 byte field name"),i?kd(u,t,`${e}.${c}`):me(u,t,`${e}.${c}`)}return r}function wd(n,t,e){let i=qe(n,t,e);try{let r=0,s=["type","serialNumber"];for(let g=0;g<s.length;g++){let w=s[g],S=kd(i[w],t,`${e}.${w}`),C=cc(S);if(C.length!==32||Eg(C)!==S)throw new Error;r+=C.length}let o=["subject","certifier"];for(let g=0;g<o.length;g++){let w=o[g];Xo(i[w],t,`${e}.${w}`),r+=33}let c=me(i.revocationOutpoint,t,`${e}.revocationOutpoint`),u=Sd(c,"."),f=u[1]??"0";if(u.length>2||!xs(/^[0-9a-fA-F]{64}$/,u[0])||!xs(/^(?:0|[1-9]\d*)$/,f)||In(f)>4294967295)throw new Error;r+=32+qc(In(f));let d=Vo(i.fields,t,`${e}.fields`),l=Sn(d);for(let g=1;g<l.length;g++){let w=l[g],S=g;for(;S>0&&l[S-1]>w;)l[S]=l[S-1],S--;l[S]=w}r+=qc(l.length);for(let g=0;g<l.length;g++){let w=l[g],S=xe(w),C=xe(d[w]);r+=qc(S.length)+S.length+qc(C.length)+C.length}let p=$e(i.signature,t,`${e}.signature`),b=ls(p);if(!gs(b))throw new Error;if(r+=b.length,r>Zx)throw new Error}catch{L(t,e,"a canonical signed wallet certificate")}return i}function At(n){if(n==null||typeof n!="object"||qt(n))return;let t=n,e=Mi(null),i=Nr(t);for(let r=0;r<i.length;r++){let s=i[r],o=ye(t,s);if(s===vd){if(o==null||!("value"in o))throw new Error("Wallet result request records must contain only data properties");Wc(e,s,{value:o.value,enumerable:!1,configurable:!1,writable:!1});continue}if(typeof s!="string"||gn(s))throw new Error("Wallet result request records must contain only safe string keys");if(o==null||!("value"in o))throw new Error("Wallet result request records must contain only data properties");e[s]=o.value}return e}function an(n,t){return typeof n=="string"&&typeof t=="string"&&jt(n)===jt(t)}function Yc(n){let t=Pt(xd,n,[/\s+/g," "]);return Pt(Px,t,[])}function Jg(n){let t=Pt(Rx,n,["NFD"]);return jt(Pt(xd,t,[/\p{Mn}/gu,""]))}function hb(n,t){return Pt(Nx,n,[t])!==-1}function pb(n,t){let e=Sd(Yc(t)," "),i=Pt(ib,n,[/\r\n?|\n|\u2028|\u2029/]),r=0;for(;r<i.length;){let s=0,o=0;for(;o<e.length;){let c=Pt(xd,e[o],[/[.*+?^${}()|[\]\\]/g,String.raw`\$&`]),u=new Cx(c,"gi");u.lastIndex=s;let f=Rr(u,i[r]);if(f==null)break;s=f.index+f[0].length,o++}if(o===e.length)return!0;r++}return!1}var a2=" a about above after again against all am an and any are aren't as at be because been before being below between both but by can't cannot could couldn't did didn't do does doesn't doing don't down during each few for from further had hadn't has hasn't have haven't having he he'd he'll he's her here here's hers herself him himself his how how's i i'd i'll i'm i've if in into is isn't it it's its itself let's me more most mustn't my myself no nor not of off on once only or other ought our ours ourselves out over own same shan't she she'd she'll she's should shouldn't so some such than that that's the their theirs them themselves then there there's these they they'd they'll they're they've this those through to too under until up very was wasn't we we'd we'll we're we've were weren't what what's when when's where where's which while who who's whom why why's with won't would wouldn't you you'd you'll you're you've your yours yourself yourselves ";function gb(n){let t=[],e=/(?:[^\p{Dash}\p{Pattern_Syntax}\p{Quotation_Mark}\p{Terminal_Punctuation}\p{White_Space}]|')+/gu,i=Rr(e,n);for(;i!=null;)hb(a2,` ${i[0]} `)||(t[t.length]=i[0]),i=Rr(e,n);return t}function c2(n,t){let e=0;for(;e<n.length;)if(n[e++]===t)return!0;return!1}function u2(n,t,e,i){let r=Pt(_x,e,["-"])&&e.length>1;if(i!==void 0){let u=hb(t,i);if(r?u:!u)return-1;if(r)return 0}let s=gb(i??(r?Pt(Bx,e,[1]):e)),o=!1,c=0;for(;c<s.length;){let u=c2(n,s[c++]);if(r&&u)return-1;o=o||u}return o&&!r?1:0}function f2(n,t){let e=Jg(n),i=Jg(t),r=gb(e),s=/-?"([^"]*)"|[^\s"]+/g,o=!1,c=Rr(s,i);for(;c!=null;){let u=u2(r,e,c[0],c[1]);if(u===-1)return!1;u===1&&(o=!0),c=Rr(s,i)}return o}function d2(n){return n!=="profilePhoto"&&n!=="icon"}function l2(n,t){if(typeof t!="string")return!1;let e=Yc(t);if(e.length<2)return!1;let i=Sn(n),r="",s=0;for(;s<i.length;){let o=i[s++];if(!d2(o))continue;let c=n[o];r=r.length>0?`${r} ${c}`:c}return e.length===2?pb(r,e):f2(r,e)}function h2(n,t,e){return typeof t!="string"?!1:n==="userName"?t===Yc(e):pb(t,e)}function p2(n,t,e,i){let r=At(i);if(r==null)return;if(Kc(r,"any")){l2(e,r.any)||L(n,`${t}.decryptedFields`,"a match for the requested any attribute");return}let s=Sn(r),o=0,c=0;for(;c<s.length;){let u=s[c++],f=r[u];typeof f!="string"&&L(n,`request.attributes.${u}`,"a string"),Yc(f).length!==0&&(o++,(!Kc(e,u)||!h2(u,e[u],f))&&L(n,`${t}.decryptedFields.${u}`,"the requested public attribute"))}o===0&&L(n,`${t}.decryptedFields`,"a usable requested attribute")}function g2(n,t,e,i){let r=Is(n,e,i),s=Is(t,e,`request.${i}`);return r.txid===s.txid&&r.outputIndex===s.outputIndex}function b2(n,t){let e=At(n),i=At(t);if(e==null||i==null)return!1;let r=Sn(e),s=Sn(i);if(r.length!==s.length)return!1;for(let o=0;o<s.length;o++){let c=s[o];if(!Kc(e,c)||e[c]!==i[c])return!1}return!0}function m2(n,t){let e=At(n),i=At(t);if(e==null||i==null)return!1;let r=Sn(e),s=Sn(i);if(r.length!==s.length)return!1;let o=0;for(;o<s.length;){if(!Kc(e,s[o]))return!1;o++}return!0}function Qg(n,t,e,i,r=!0){let s=At(t);if(s==null)return;let o=["type","serialNumber"];for(let u=0;u<o.length;u++){let f=o[u];s[f]!==void 0&&n[f]!==s[f]&&L(e,`${i}.${f}`,`the requested certificate ${f}`)}let c=["subject","certifier","signature"];for(let u=0;u<c.length;u++){let f=c[u];s[f]!==void 0&&!an(n[f],s[f])&&L(e,`${i}.${f}`,`the requested certificate ${f}`)}s.revocationOutpoint!==void 0&&!g2(n.revocationOutpoint,s.revocationOutpoint,e,`${i}.revocationOutpoint`)&&L(e,`${i}.revocationOutpoint`,"the requested certificate revocation outpoint"),s.fields!==void 0&&!(r?b2(n.fields,s.fields):m2(n.fields,s.fields))&&L(e,`${i}.fields`,"the requested certificate fields")}function y2(n,t,e){let i=Td(n,t,"totalCertificates","certificates",e),r=At(e),s;if(t==="listCertificates"&&qt(r?.certifiers)){s=new cn;for(let c=0;c<r.certifiers.length;c++)Gt(s,jt(Be(r.certifiers[c])))}let o;if(t==="listCertificates"&&qt(r?.types)){o=new cn;for(let c=0;c<r.types.length;c++)Gt(o,Be(r.types[c]))}for(let c=0;c<i.length;c++){let u=i[c],f=`certificates[${c}]`,d=wd(u,t,f);if(s!=null&&zc(s)>0&&(un(s,jt(Be(d.certifier)))||L(t,`${f}.certifier`,"one of the requested certifiers")),o!=null&&zc(o)>0&&(un(o,Be(d.type))||L(t,`${f}.type`,"one of the requested types")),t==="discoverByIdentityKey"&&r?.identityKey!==void 0&&!an(d.subject,r.identityKey)&&L(t,`${f}.subject`,"the requested identity key"),d.keyring!==void 0&&Vo(d.keyring,t,`${f}.keyring`,!0),d.verifier!==void 0&&Xo(d.verifier,t,`${f}.verifier`),t==="discoverByIdentityKey"||t==="discoverByAttributes"){let l=`${f}.certifierInfo`,p=qe(d.certifierInfo,t,l);me(p.name,t,`${l}.name`,1,100),n2(p.iconUrl,t,`${l}.iconUrl`,500),me(p.description,t,`${l}.description`,5,50),Ed(p.trust,t,`${l}.trust`,1,10),Vo(d.publiclyRevealedKeyring,t,`${f}.publiclyRevealedKeyring`,!0);let b=Vo(d.decryptedFields,t,`${f}.decryptedFields`);t==="discoverByAttributes"&&p2(t,f,b,r?.attributes)}}}function Td(n,t,e,i,r){let s=ne(n[e],t,e,vx),o=qn(n[i],t,i);o==null&&L(t,i,"an array"),o.length>s&&L(t,e,`at least ${o.length}`);let c=At(r);if(c!=null){let u=c.limit===void 0?10:ne(c.limit,t,"limit",1e4);o.length>u&&L(t,i,`at most the requested limit of ${u}`)}return o}function bd(n,t,e){me(n,t,e,n===""?0:5,2e3)}function w2(n,t,e){let i=Td(n,t,"totalActions","actions",e),r=At(e),s=[];if(qt(r?.labels))for(let c=0;c<r.labels.length;c++)s[c]=Be(r.labels[c]);let o=r?.labelQueryMode==="all"?"all":"any";for(let c=0;c<i.length;c++){let u=i[c],f=`actions[${c}]`,d=qe(u,t,f);if($e(d.txid,t,`${f}.txid`,32),Ed(d.satoshis,t,`${f}.satoshis`,-21e14,21e14),un(ri,d.status)||L(t,`${f}.status`,"a supported action status"),typeof d.isOutgoing!="boolean"&&L(t,`${f}.isOutgoing`,"a boolean"),bd(d.description,t,`${f}.description`),jc(d.labels,t,`${f}.labels`,1,300),r?.includeLabels===!0&&d.labels===void 0&&L(t,`${f}.labels`,"the explicitly requested labels"),s.length>0&&qt(d.labels)){let b=new cn;for(let w=0;w<d.labels.length;w++)Gt(b,d.labels[w]);let g=o==="all";for(let w=0;w<s.length;w++){let S=un(b,s[w]);if(o==="all"&&!S){g=!1;break}if(o==="any"&&S){g=!0;break}}g||L(t,`${f}.labels`,"the requested label query")}ne(d.version,t,`${f}.version`),ne(d.lockTime,t,`${f}.lockTime`);let l=qn(d.inputs,t,`${f}.inputs`);if((r?.includeInputs===!0||r?.includeInputSourceLockingScripts===!0||r?.includeInputUnlockingScripts===!0)&&l===void 0&&L(t,`${f}.inputs`,"the explicitly requested inputs"),l!=null)for(let b=0;b<l.length;b++){let g=l[b],w=`${f}.inputs[${b}]`,S=qe(g,t,w);Is(S.sourceOutpoint,t,`${w}.sourceOutpoint`),ne(S.sourceSatoshis,t,`${w}.sourceSatoshis`,21e14),S.sourceLockingScript!==void 0&&$e(S.sourceLockingScript,t,`${w}.sourceLockingScript`),S.unlockingScript!==void 0&&$e(S.unlockingScript,t,`${w}.unlockingScript`),r?.includeInputSourceLockingScripts===!0&&S.sourceLockingScript===void 0&&L(t,`${w}.sourceLockingScript`,"the explicitly requested source locking script"),r?.includeInputUnlockingScripts===!0&&S.unlockingScript===void 0&&L(t,`${w}.unlockingScript`,"the explicitly requested unlocking script"),bd(S.inputDescription,t,`${w}.inputDescription`),ne(S.sequenceNumber,t,`${w}.sequenceNumber`)}let p=qn(d.outputs,t,`${f}.outputs`);if((r?.includeOutputs===!0||r?.includeOutputLockingScripts===!0)&&p===void 0&&L(t,`${f}.outputs`,"the explicitly requested outputs"),p!=null)for(let b=0;b<p.length;b++){let g=p[b],w=`${f}.outputs[${b}]`,S=qe(g,t,w);ne(S.satoshis,t,`${w}.satoshis`,21e14),S.lockingScript!==void 0&&$e(S.lockingScript,t,`${w}.lockingScript`),r?.includeOutputLockingScripts===!0&&S.lockingScript===void 0&&L(t,`${w}.lockingScript`,"the explicitly requested output locking script"),db(S,t,"spendable"),S.customInstructions!==void 0&&me(S.customInstructions,t,`${w}.customInstructions`),jc(S.tags,t,`${w}.tags`,1,300),ne(S.outputIndex,t,`${w}.outputIndex`),bd(S.outputDescription,t,`${w}.outputDescription`),me(S.basket,t,`${w}.basket`,0,300)}}}function x2(n,t,e){let i=Td(n,t,"totalOutputs","outputs",e),r=n.BEEF===void 0?void 0:o2(n.BEEF,t,"BEEF"),s=At(e),o=[];if(qt(s?.tags))for(let f=0;f<s.tags.length;f++)o[f]=Be(s.tags[f]);let c=s?.tagQueryMode==="all"?"all":"any";i.length>0&&s?.include==="entire transactions"&&r==null&&L(t,"BEEF","the requested complete output transactions");let u=new cn;for(let f=0;f<i.length;f++){let d=i[f],l=`outputs[${f}]`,p=qe(d,t,l),b=Is(p.outpoint,t,`${l}.outpoint`),g=`${b.txid}.${b.outputIndex}`;un(u,g)&&L(t,`${l}.outpoint`,"a unique output in the result page"),Gt(u,g);let w=ne(p.satoshis,t,`${l}.satoshis`,21e14);typeof p.spendable!="boolean"&&L(t,`${l}.spendable`,"a boolean");let S=p.lockingScript===void 0?void 0:$e(p.lockingScript,t,`${l}.lockingScript`);if(s?.include==="locking scripts"&&S===void 0&&L(t,`${l}.lockingScript`,"the requested locking script"),r!=null){let E=Or(r.transactions,b.txid)?.outputs[b.outputIndex];E==null&&L(t,`${l}.outpoint`,"an output contained in BEEF"),E.satoshis!==w&&L(t,`${l}.satoshis`,"the amount committed by BEEF"),S!==void 0&&jt(Ye(E.lockingScript))!==jt(S)&&L(t,`${l}.lockingScript`,"the script committed by BEEF")}if(p.customInstructions!==void 0&&me(p.customInstructions,t,`${l}.customInstructions`),jc(p.tags,t,`${l}.tags`,1,300),jc(p.labels,t,`${l}.labels`,1,300),s?.includeTags===!0&&p.tags===void 0&&L(t,`${l}.tags`,"the explicitly requested output tags"),s?.includeLabels===!0&&p.labels===void 0&&L(t,`${l}.labels`,"the explicitly requested transaction labels"),o.length>0&&qt(p.tags)){let C=new cn;for(let A=0;A<p.tags.length;A++)Gt(C,p.tags[A]);let E=c==="all";for(let A=0;A<o.length;A++){let k=un(C,o[A]);if(c==="all"&&!k){E=!1;break}if(c==="any"&&k){E=!0;break}}E||L(t,`${l}.tags`,"the requested tag query")}}}function tb(n,t){let e=["prover","verifier","counterparty"];for(let i=0;i<e.length;i++){let r=e[i];Xo(n[r],t,r)}ii(n.encryptedLinkage,t,"encryptedLinkage"),ii(n.encryptedLinkageProof,t,"encryptedLinkageProof")}function Ft(n,t,e){let i=Ad(t,n),r=qe(i,n),s=At(e);switch(n){case"createAction":case"signAction":s2(r,n,e);break;case"abortAction":db(r,n,"aborted");break;case"internalizeAction":$c(r,n,"accepted");break;case"relinquishOutput":case"relinquishCertificate":$c(r,n,"relinquished");break;case"verifyHmac":case"verifySignature":$c(r,n,"valid");break;case"isAuthenticated":case"waitForAuthentication":$c(r,n,"authenticated");break;case"getPublicKey":Xo(r.publicKey,n,"publicKey");break;case"encrypt":ii(r.ciphertext,n,"ciphertext");break;case"decrypt":ii(r.plaintext,n,"plaintext");break;case"createHmac":ii(r.hmac,n,"hmac",32);break;case"createSignature":{let o=ii(r.signature,n,"signature",void 0,72);gs(o)||L(n,"signature","a canonical DER-encoded ECDSA signature");break}case"revealCounterpartyKeyLinkage":tb(r,n),e2(r.revelationTime,n,"revelationTime"),s?.verifier!==void 0&&!an(r.verifier,s?.verifier)&&L(n,"verifier","the requested verifier"),s?.counterparty!==void 0&&!an(r.counterparty,s?.counterparty)&&L(n,"counterparty","the requested counterparty");break;case"revealSpecificKeyLinkage":tb(r,n),(!qt(r.protocolID)||r.protocolID.length!==2)&&L(n,"protocolID","a [securityLevel, protocolName] tuple"),ne(r.protocolID[0],n,"protocolID[0]",2),me(r.protocolID[1],n,"protocolID[1]",5,400),me(r.keyID,n,"keyID",1,800),ne(r.proofType,n,"proofType",255),s?.verifier!==void 0&&!an(r.verifier,s?.verifier)&&L(n,"verifier","the requested verifier"),s?.counterparty==="self"?an(r.counterparty,r.prover)||L(n,"counterparty","the prover's identity key for counterparty self"):s?.counterparty==="anyone"?an(r.counterparty,Jx)||L(n,"counterparty","the canonical anyone public key"):typeof s?.counterparty=="string"&&!an(r.counterparty,s.counterparty)&&L(n,"counterparty","the requested counterparty"),qt(s?.protocolID)&&(r.protocolID[0]!==s.protocolID[0]||r.protocolID[1]!==s.protocolID[1])&&L(n,"protocolID","the requested protocol"),s?.keyID!==void 0&&r.keyID!==s?.keyID&&L(n,"keyID","the requested key ID");break;case"listActions":w2(r,n,e);break;case"listOutputs":x2(r,n,e);break;case"listCertificates":case"discoverByIdentityKey":case"discoverByAttributes":y2(r,n,e);break;case"getHeight":Ed(r.height,n,"height",1,4294967295);break;case"getHeaderForHeight":$e(r.header,n,"header",80);break;case"getNetwork":r.network!=="mainnet"&&r.network!=="testnet"&&L(n,"network","mainnet or testnet");break;case"getVersion":me(r.version,n,"version",7,30);break;case"acquireCertificate":wd(r,n,"certificate"),s?.type!==void 0&&r.type!==s?.type&&L(n,"certificate.type","the requested certificate type"),s?.certifier!==void 0&&!an(r.certifier,s?.certifier)&&L(n,"certificate.certifier","the requested certifier"),Qg(r,s,n,"certificate",s?.acquisitionProtocol!=="issuance");break;case"proveCertificate":{let o=Vo(r.keyringForVerifier,n,"keyringForVerifier",!0),c=qt(s?.fieldsToReveal)?s.fieldsToReveal:[],u=new cn;for(let l=0;l<c.length;l++)Gt(u,Be(c[l]));let f=Sn(o),d=f.length===zc(u);for(let l=0;d&&l<f.length;l++)d=un(u,f[l]);d||L(n,"keyringForVerifier","exactly the requested certificate fields")}if(r.certificate!==void 0){let o=wd(r.certificate,n,"certificate");Qg(o,s?.certificate,n,"certificate")}r.verifier!==void 0&&Xo(r.verifier,n,"verifier"),r.verifier!==void 0&&s?.verifier!==void 0&&!an(r.verifier,s?.verifier)&&L(n,"verifier","the requested verifier");break}return i}var Od;(function(n){n[n.createAction=1]="createAction",n[n.signAction=2]="signAction",n[n.abortAction=3]="abortAction",n[n.listActions=4]="listActions",n[n.internalizeAction=5]="internalizeAction",n[n.listOutputs=6]="listOutputs",n[n.relinquishOutput=7]="relinquishOutput",n[n.getPublicKey=8]="getPublicKey",n[n.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",n[n.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",n[n.encrypt=11]="encrypt",n[n.decrypt=12]="decrypt",n[n.createHmac=13]="createHmac",n[n.verifyHmac=14]="verifyHmac",n[n.createSignature=15]="createSignature",n[n.verifySignature=16]="verifySignature",n[n.acquireCertificate=17]="acquireCertificate",n[n.listCertificates=18]="listCertificates",n[n.proveCertificate=19]="proveCertificate",n[n.relinquishCertificate=20]="relinquishCertificate",n[n.discoverByIdentityKey=21]="discoverByIdentityKey",n[n.discoverByAttributes=22]="discoverByAttributes",n[n.isAuthenticated=23]="isAuthenticated",n[n.waitForAuthentication=24]="waitForAuthentication",n[n.getHeight=25]="getHeight",n[n.getHeaderForHeight=26]="getHeaderForHeight",n[n.getNetwork=27]="getNetwork",n[n.getVersion=28]="getVersion"})(Od||(Od={}));var Ss=Od;function xt(n,t){switch(n){case"createAction":lc(t);return;case"signAction":hc(t);return;case"abortAction":pc(t);return;case"listActions":kc(t);return;case"internalizeAction":gc(t);return;case"listOutputs":Ec(t);return;case"relinquishOutput":mc(t);return;case"getPublicKey":Tc(t);return;case"revealCounterpartyKeyLinkage":Oc(t);return;case"revealSpecificKeyLinkage":Pc(t);return;case"encrypt":Rc(t);return;case"decrypt":Nc(t);return;case"createHmac":Bc(t);return;case"verifyHmac":_c(t);return;case"createSignature":Cc(t);return;case"verifySignature":Lc(t);return;case"acquireCertificate":{let e=t;if(e?.acquisitionProtocol==="direct")Ic(e);else if(e?.acquisitionProtocol==="issuance")xc(e);else throw new ti("acquisitionProtocol","direct or issuance");return}case"listCertificates":wc(t);return;case"proveCertificate":Sc(t);return;case"relinquishCertificate":yc(t);return;case"discoverByIdentityKey":vc(t);return;case"discoverByAttributes":Ac(t);return;case"getHeaderForHeight":Uc(t);return;case"isAuthenticated":case"waitForAuthentication":case"getHeight":case"getNetwork":case"getVersion":Ui(t)}}var vs=class{constructor(){m(this,"CWI");if(typeof window!="object")throw new TypeError("The window.CWI substrate requires a global window object.");if(typeof window.CWI!="object")throw new TypeError("The window.CWI interface does not appear to be bound to the window object.");let t=window.CWI;this.CWI=new Proxy(t,{get(e,i,r){let s=Reflect.get(e,i,r);return typeof i!="string"||!Object.prototype.hasOwnProperty.call(Ss,i)||typeof s!="function"?s:(o,...c)=>(xt(i,o),Reflect.apply(s,e,[o,...c]))}})}async validatedResult(t,e,i){return Ft(t,await e,i)}async createAction(t,e){let i=bt("createAction",t);return await this.validatedResult("createAction",this.CWI.createAction(t,e),i)}async signAction(t,e){let i=bt("signAction",t);return await this.validatedResult("signAction",this.CWI.signAction(t,e),i)}async abortAction(t,e){return await this.validatedResult("abortAction",this.CWI.abortAction(t,e))}async listActions(t,e){let i=bt("listActions",t);return await this.validatedResult("listActions",this.CWI.listActions(t,e),i)}async internalizeAction(t,e){return await this.validatedResult("internalizeAction",this.CWI.internalizeAction(t,e))}async listOutputs(t,e){let i=bt("listOutputs",t);return await this.validatedResult("listOutputs",this.CWI.listOutputs(t,e),i)}async relinquishOutput(t,e){return await this.validatedResult("relinquishOutput",this.CWI.relinquishOutput(t,e))}async getPublicKey(t,e){return await this.validatedResult("getPublicKey",this.CWI.getPublicKey(t,e))}async revealCounterpartyKeyLinkage(t,e){let i=bt("revealCounterpartyKeyLinkage",t);return await this.validatedResult("revealCounterpartyKeyLinkage",this.CWI.revealCounterpartyKeyLinkage(t,e),i)}async revealSpecificKeyLinkage(t,e){let i=bt("revealSpecificKeyLinkage",t);return await this.validatedResult("revealSpecificKeyLinkage",this.CWI.revealSpecificKeyLinkage(t,e),i)}async encrypt(t,e){return await this.validatedResult("encrypt",this.CWI.encrypt(t,e))}async decrypt(t,e){return await this.validatedResult("decrypt",this.CWI.decrypt(t,e))}async createHmac(t,e){return await this.validatedResult("createHmac",this.CWI.createHmac(t,e))}async verifyHmac(t,e){return await this.validatedResult("verifyHmac",this.CWI.verifyHmac(t,e))}async createSignature(t,e){return await this.validatedResult("createSignature",this.CWI.createSignature(t,e))}async verifySignature(t,e){return await this.validatedResult("verifySignature",this.CWI.verifySignature(t,e))}async acquireCertificate(t,e){let i=bt("acquireCertificate",t);return await this.validatedResult("acquireCertificate",this.CWI.acquireCertificate(t,e),i)}async listCertificates(t,e){let i=bt("listCertificates",t);return await this.validatedResult("listCertificates",this.CWI.listCertificates(t,e),i)}async proveCertificate(t,e){let i=bt("proveCertificate",t);return await this.validatedResult("proveCertificate",this.CWI.proveCertificate(t,e),i)}async relinquishCertificate(t,e){return await this.validatedResult("relinquishCertificate",this.CWI.relinquishCertificate(t,e))}async discoverByIdentityKey(t,e){let i=bt("discoverByIdentityKey",t);return await this.validatedResult("discoverByIdentityKey",this.CWI.discoverByIdentityKey(t,e),i)}async discoverByAttributes(t,e){let i=bt("discoverByAttributes",t);return await this.validatedResult("discoverByAttributes",this.CWI.discoverByAttributes(t,e),i)}async isAuthenticated(t,e){return await this.validatedResult("isAuthenticated",this.CWI.isAuthenticated(t,e))}async waitForAuthentication(t,e){return await this.validatedResult("waitForAuthentication",this.CWI.waitForAuthentication(t,e))}async getHeight(t,e){return await this.validatedResult("getHeight",this.CWI.getHeight(t,e))}async getHeaderForHeight(t,e){return await this.validatedResult("getHeaderForHeight",this.CWI.getHeaderForHeight(t,e))}async getNetwork(t,e){return await this.validatedResult("getNetwork",this.CWI.getNetwork(t,e))}async getVersion(t,e){return await this.validatedResult("getVersion",this.CWI.getVersion(t,e))}};var si=class extends Error{constructor(e,i=1,r){super(e);m(this,"code");m(this,"isError",!0);this.code=i,this.name=this.constructor.name,r!=null&&r!==""?this.stack=r:Error.captureStackTrace(this,this.constructor)}static unknownToJson(e){let i;return e.isError===!0&&String(e.name).startsWith("WERR_")?(i={name:e.name,message:e.message,isError:!0},i.name==="WERR_REVIEW_ACTIONS"?(i.reviewActionResults=e.reviewActionResults,i.sendWithResults=e.sendWithResults,i.txid=e.txid,i.tx=e.tx,i.noSendChange=e.noSendChange,i.code=5):i.name==="WERR_INVALID_PARAMETER"?(i.parameter=e.parameter,i.code=6):i.name==="WERR_INSUFFICIENT_FUNDS"&&(i.totalSatoshisNeeded=e.totalSatoshisNeeded,i.moreSatoshisNeeded=e.moreSatoshisNeeded,i.code=7)):e instanceof Error?i={name:e.constructor.name,message:e.message,isError:!0}:i={name:"WERR_UNKNOWN",message:String(e),isError:!0},ys(i)}},fn;(function(n){n[n.unknownError=1]="unknownError",n[n.unsupportedAction=2]="unsupportedAction",n[n.invalidHmac=3]="invalidHmac",n[n.invalidSignature=4]="invalidSignature",n[n.reviewActions=5]="reviewActions",n[n.invalidParameter=6]="invalidParameter",n[n.insufficientFunds=7]="insufficientFunds",n[n.abortRefused=8]="abortRefused"})(fn||(fn={}));var As=class{async invokeRaw(t,e,i){throw new Error("This substrate must implement invoke() or invokeRaw().")}async invoke(t,e){xt(t,e);let i=bt(t,e);return await this.invokeRaw(t,e,i)}async createAction(t){return await this.invoke("createAction",t)}async signAction(t){return await this.invoke("signAction",t)}async abortAction(t){return await this.invoke("abortAction",t)}async listActions(t){return await this.invoke("listActions",t)}async internalizeAction(t){return await this.invoke("internalizeAction",t)}async listOutputs(t){return await this.invoke("listOutputs",t)}async relinquishOutput(t){return await this.invoke("relinquishOutput",t)}async getPublicKey(t){return await this.invoke("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.invoke("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.invoke("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.invoke("encrypt",t)}async decrypt(t){return await this.invoke("decrypt",t)}async createHmac(t){return await this.invoke("createHmac",t)}async verifyHmac(t){return await this.invoke("verifyHmac",t)}async createSignature(t){return await this.invoke("createSignature",t)}async verifySignature(t){return await this.invoke("verifySignature",t)}async acquireCertificate(t){return await this.invoke("acquireCertificate",t)}async listCertificates(t){return await this.invoke("listCertificates",t)}async proveCertificate(t){return await this.invoke("proveCertificate",t)}async relinquishCertificate(t){return await this.invoke("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.invoke("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.invoke("discoverByAttributes",t)}async isAuthenticated(t){return await this.invoke("isAuthenticated",t)}async waitForAuthentication(t){return await this.invoke("waitForAuthentication",t)}async getHeight(t){return await this.invoke("getHeight",t)}async getHeaderForHeight(t){return await this.invoke("getHeaderForHeight",t)}async getNetwork(t){return await this.invoke("getNetwork",t)}async getVersion(t){return await this.invoke("getVersion",t)}};var I2=1024,bb=3600*1e3;function S2(n,t){if(typeof n!="object"||n===null)return!1;let e=n;return e.type!=="CWI"||e.isInvocation!==!1||e.id!==t?!1:e.status==="success"?!0:e.status==="error"&&typeof e.description=="string"&&at(e.description,"utf8").length<=4096&&typeof e.code=="number"&&Number.isSafeInteger(e.code)&&e.code>=1&&e.code<=255}var Br=class extends As{constructor(e="*",i){super();m(this,"domain");m(this,"responseTimeout");m(this,"pendingInvocations",0);if(typeof globalThis.window!="object")throw new TypeError("The XDM substrate requires a global window object.");if(typeof globalThis.window.postMessage!="function")throw new TypeError("The window object does not seem to support postMessage calls.");if(i!==void 0&&(!Number.isSafeInteger(i)||i<1||i>bb))throw new TypeError(`XDM responseTimeout must be an integer from 1 to ${bb}.`);this.domain=e,this.responseTimeout=i}async invokeRaw(e,i,r){if(this.pendingInvocations>=I2)throw new Error("XDM wallet pending invocation limit reached.");let s=Se(Pe(12));return this.pendingInvocations++,await new Promise((o,c)=>{let u,f=!1,d=!0,l=()=>{if(d&&(d=!1,this.pendingInvocations--,u!==void 0&&clearTimeout(u),f&&typeof window.removeEventListener=="function"))try{window.removeEventListener("message",p)}catch{}},p=b=>{if(!(!b.isTrusted||b.source!==window.parent||this.domain!=="*"&&b.origin!==this.domain||!S2(b.data,s)))if(l(),b.data.status==="error"){let g=b.data.code>=fn.unsupportedAction&&b.data.code<=fn.abortRefused,w=g?b.data.description:"Wallet operation failed",S=new si(w,g?b.data.code:fn.unknownError);c(S)}else try{o(Ft(e,b.data.result,r))}catch(g){c(g)}};try{window.addEventListener("message",p),f=!0,this.responseTimeout!==void 0&&(u=setTimeout(()=>{l(),c(new Error("XDM wallet response timed out."))},this.responseTimeout)),window.parent.postMessage({type:"CWI",isInvocation:!0,id:s,call:e,args:i},this.domain)}catch(b){l(),c(b)}})}};var Jc=16*1024*1024,Qc=1e5,tu=1024*1024,mb=72;function yb(n,t,e){let i;try{i=cc(n)}catch{throw new Error(`Invalid certificate ${t}: expected canonical base64`)}return xb(i,t,e),i}function v2(n){if(n==null||typeof n!="object"||Array.isArray(n))throw new Error("Certificate fields must be a plain object");let t=Object.getPrototypeOf(n);if(t!==Object.prototype&&t!==null)throw new Error("Certificate fields must be a plain object");let e=Reflect.ownKeys(n);if(e.length>Qc)throw new Error(`Certificate field count exceeds the maximum of ${Qc}`);let i=Object.create(null);for(let r of e){if(typeof r!="string")throw new Error("Certificate fields cannot contain symbol keys");let s=Object.getOwnPropertyDescriptor(n,r);if(s==null||!Object.hasOwn(s,"value")||typeof s.value!="string")throw new Error(`Certificate field ${r} must be an own string data property`);let o=at(r,"utf8");if(Pd(r,o.length),at(s.value,"utf8").length>tu)throw new Error(`Certificate field ${r} exceeds the maximum of ${tu} bytes`);i[r]=s.value}return i}function wb(n){let t=n instanceof Uint8Array?Array.from(n):n;if(!Array.isArray(t)||t.length>Jc)throw new Error(`Certificate binary must be a byte array of at most ${Jc} bytes`);let e=Array.from({length:t.length});for(let i=0;i<t.length;i++){let r=Object.getOwnPropertyDescriptor(t,i);if(r==null||!Object.hasOwn(r,"value")||!Number.isInteger(r.value)||r.value<0||r.value>255)throw new Error("Certificate binary must be a dense byte array");e[i]=r.value}return e}function A2(n,t){if(n.length!==t.length)return!1;let e=0;for(let i=0;i<n.length;i++)e|=n[i]^t[i];return e===0}function Pd(n,t){if(t<1||t>50)throw new Error(`Invalid certificate field name length: expected 1\u201350 bytes, received ${t}`);if(gn(n))throw new Error(`Unsafe certificate field name: ${n}`)}function xb(n,t,e){if(n.length!==e)throw new Error(`Invalid certificate ${t} length: expected ${e} bytes, received ${n.length}`)}function Zc(n,t){xb(n,t,33);try{Ht.fromDER(n)}catch{throw new Error(`Invalid certificate ${t}: expected a compressed secp256k1 public key`)}}var _r=class n{constructor(t,e,i,r,s,o,c){m(this,"type");m(this,"serialNumber");m(this,"subject");m(this,"certifier");m(this,"revocationOutpoint");m(this,"fields");m(this,"signature");this.type=t,this.serialNumber=e,this.subject=i,this.certifier=r,this.revocationOutpoint=s,this.fields=o,this.signature=c}toBinary(t=!0){let e=new ue,i=yb(this.type,"type",32);e.write(i);let r=yb(this.serialNumber,"serial number",32);if(e.write(r),!/^(02|03)[0-9a-fA-F]{64}$/.test(this.subject))throw new Error("Invalid certificate subject: expected compressed public key hex");let s=at(this.subject,"hex");if(Zc(s,"subject"),e.write(s),!/^(02|03)[0-9a-fA-F]{64}$/.test(this.certifier))throw new Error("Invalid certificate certifier: expected compressed public key hex");let o=at(this.certifier,"hex");if(Zc(o,"certifier"),e.write(o),typeof this.revocationOutpoint!="string")throw new Error("Invalid certificate revocation outpoint");let c=this.revocationOutpoint.split("."),[u,f="0"]=c;if(c.length>2||!/^[0-9a-fA-F]{64}$/.test(u)||!/^(?:0|[1-9]\d*)$/.test(f)||Number(f)>4294967295)throw new Error(`Invalid certificate revocation outpoint: ${this.revocationOutpoint}`);let d=at(u,"hex");if(d.length!==32)throw new Error(`Invalid certificate revocation txid length: ${d.length}`);e.write(d),e.writeVarIntNum(Number(f));let l=v2(this.fields),p=Object.keys(l).sort((g,w)=>g.localeCompare(w));e.writeVarIntNum(p.length);for(let g of p){let w=l[g],S=at(g,"utf8");Pd(g,S.length),e.writeVarIntNum(S.length),e.write(S);let C=at(w,"utf8");e.writeVarIntNum(C.length),e.write(C)}if(t&&(this.signature??"").length>0){if(typeof this.signature!="string"||this.signature.length>mb*2||!/^(?:[0-9a-fA-F]{2})+$/.test(this.signature))throw new Error("Invalid certificate signature encoding");let g=at(this.signature,"hex");pe.fromDER(g),e.write(g)}let b=e.toArray();if(b.length>Jc)throw new Error(`Certificate binary exceeds the maximum of ${Jc} bytes`);return b}static fromBinary(t){let e=new mt(wb(t)),i=e.read(32),r=Se(i),s=e.read(32),o=Se(s),c=e.read(33);Zc(Array.from(c),"subject");let u=nt(c),f=e.read(33);Zc(Array.from(f),"certifier");let d=nt(f),l=e.read(32),p=nt(l),b=e.readVarIntNumStrict(!1),g=`${p}.${b}`,w=e.readVarIntNumStrict(!1);if(w>Qc)throw new Error(`Certificate field count exceeds the maximum of ${Qc}`);if(w>Math.floor(e.remaining()/3))throw new Error("Certificate field count exceeds the available data");let S=new Map;for(let E=0;E<w;E++){let A=e.readVarIntNumStrict(!1);if(A<1||A>50)throw new Error(`Invalid certificate field name length: received ${A}`);let k=e.read(A),B=Rt(k);if(Pd(B,A),S.has(B))throw new Error(`Duplicate certificate field name: ${B}`);let _=e.readVarIntNumStrict(!1);if(_>tu)throw new Error(`Certificate field ${B} exceeds the maximum of ${tu} bytes`);let $=e.read(_),R=Rt($);S.set(B,R)}let C;if(!e.eof()){if(e.remaining()>mb)throw new Error("Certificate signature exceeds the DER size limit");let E=e.read();C=pe.fromDER(Array.from(E)).toString("hex")}return new n(r,o,u,d,g,Object.fromEntries(S),C)}async verify(){try{let t=this.toBinary(!1);return Ht.fromString(this.certifier).deriveChild(new T(1),`2-certificate signature-${this.type} ${this.serialNumber}`).verify(t,pe.fromDER(at(this.signature??"","hex")))}catch{return!1}}async sign(t){if(this.signature!=null&&this.signature.length>0)throw new Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await t.getPublicKey({identityKey:!0})).publicKey;let e=this.toBinary(!1),{signature:i}=await t.createSignature({data:e,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});if(!A2(e,this.toBinary(!1)))throw new Error("Certificate changed while its signature was being created");let r=wb(i),s=pe.fromDER(r);this.signature=s.toString("hex")}static getCertificateFieldEncryptionDetails(t,e){return{protocolID:[2,"certificate field encryption"],keyID:e?`${e} ${t}`:t}}static fromObject(t){return new n(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,t.signature)}};var E2=1e5,k2={1:"completed",2:"unprocessed",3:"sending",4:"unproven",5:"unsigned",6:"nosend",7:"nonfinal",8:"failed"},v,Nt,Ib,Sb,vb,Ab,Eb,kb,Tb,Ob,Es,eu,Dt,oi,Cr,nu,iu,ru,Rd,Pb,Rb,Nb,Bb,ai,Lr,Nd,Di,jo,Go,Je,ci,Yo,Zo,Hi,_b,Ae,Ur,$i,su=class su{constructor(t){G(this,v);m(this,"wire");this.wire=t}async createAction(t,e){xt("createAction",t);let i=bt("createAction",t),r=new ht(void 0,Math.max(256,Math.ceil((t.inputBEEF?.length??0)+(t.inputs??[]).reduce((o,c)=>o+(c.unlockingScript?.length??0)/2,0)+(t.outputs??[]).reduce((o,c)=>o+c.lockingScript.length/2,0)+4096)));if(a(this,v,Cr).call(this,r,t.description),t.inputBEEF==null?r.writeVarIntNum(-1):(r.writeVarIntNum(t.inputBEEF.length),r.write(t.inputBEEF)),t.inputs==null)r.writeVarIntNum(-1);else{r.writeVarIntNum(t.inputs.length);for(let o of t.inputs)a(this,v,Pb).call(this,r,o)}if(t.outputs==null)r.writeVarIntNum(-1);else{r.writeVarIntNum(t.outputs.length);for(let o of t.outputs)a(this,v,Rb).call(this,r,o)}a(this,v,oi).call(this,r,t.lockTime),a(this,v,oi).call(this,r,t.version),a(this,v,iu).call(this,r,t.labels),a(this,v,Nb).call(this,r,t.options);let s=await a(this,v,Nt).call(this,"createAction",e,r.toUint8ArrayZeroCopy());return Ft("createAction",a(this,v,Ib).call(this,s),i)}async signAction(t,e){xt("signAction",t);let i=bt("signAction",t),r=new ht,s=Object.keys(t.spends);r.writeVarIntNum(s.length);for(let l of s){r.writeVarIntNum(Number(l));let p=t.spends[Number(l)],b=et(p.unlockingScript,"hex");r.writeVarIntNum(b.length),r.write(b),a(this,v,oi).call(this,r,p.sequenceNumber)}let o=et(t.reference,"base64");r.writeVarIntNum(o.length),r.write(o),a(this,v,Bb).call(this,r,t.options);let c=await a(this,v,Nt).call(this,"signAction",e,r.toUint8ArrayZeroCopy()),u=new mt(c),f={};a(this,v,ci).call(this,u,"signAction txid present")&&(f.txid=nt(u.read(32))),a(this,v,ci).call(this,u,"signAction tx present")&&(f.tx=u.readView(u.readVarIntNumStrict(!1)));let d=a(this,v,Rd).call(this,u);return d!=null&&(f.sendWithResults=d),a(this,v,Di).call(this,u,"signAction"),Ft("signAction",f,i)}async abortAction(t,e){xt("abortAction",t);try{let i=await a(this,v,Nt).call(this,"abortAction",e,et(t.reference,"base64"));return a(this,v,$i).call(this,i,"abortAction"),{aborted:!0}}catch(i){if(i instanceof si&&i.code===fn.abortRefused)return{aborted:!1};throw i}}async listActions(t,e){xt("listActions",t);let i=new ht;i.writeVarIntNum(t.labels.length);for(let u of t.labels)a(this,v,Cr).call(this,i,u);t.labelQueryMode==="any"?i.writeInt8(1):t.labelQueryMode==="all"?i.writeInt8(2):i.writeInt8(-1);for(let u of[t.includeLabels,t.includeInputs,t.includeInputSourceLockingScripts,t.includeInputUnlockingScripts,t.includeOutputs,t.includeOutputLockingScripts])a(this,v,Dt).call(this,i,u);a(this,v,oi).call(this,i,t.limit),a(this,v,oi).call(this,i,t.offset),a(this,v,Dt).call(this,i,t.seekPermission);let r=await a(this,v,Nt).call(this,"listActions",e,i.toUint8Array()),s=new mt(r),o=a(this,v,Ae).call(this,s.readVarIntNumStrict(!1),"listActions totalActions",0,4294967295),c=[];for(;!s.eof();)a(this,v,Go).call(this,c.length,t.limit,"listActions"),c.push(a(this,v,Ab).call(this,s));return a(this,v,jo).call(this,c.length,o,"listActions"),{totalActions:o,actions:c}}async internalizeAction(t,e){xt("internalizeAction",t);let i=new ht(void 0,Math.max(256,t.tx.length+4096));i.writeVarIntNum(t.tx.length),i.write(t.tx),i.writeVarIntNum(t.outputs.length);for(let o of t.outputs)a(this,v,Tb).call(this,i,o);a(this,v,iu).call(this,i,typeof t.labels=="object"?t.labels:void 0);let r=et(t.description);i.writeVarIntNum(r.length),i.write(r),a(this,v,Dt).call(this,i,t.seekPermission);let s=await a(this,v,Nt).call(this,"internalizeAction",e,i.toUint8ArrayZeroCopy());return a(this,v,$i).call(this,s,"internalizeAction"),{accepted:!0}}async listOutputs(t,e){xt("listOutputs",t);let i=bt("listOutputs",t),r=new ht;if(a(this,v,Cr).call(this,r,t.basket),typeof t.tags=="object"){r.writeVarIntNum(t.tags.length);for(let l of t.tags)a(this,v,Cr).call(this,r,l)}else r.writeVarIntNum(0);t.tagQueryMode==="all"?r.writeInt8(1):t.tagQueryMode==="any"?r.writeInt8(2):r.writeInt8(-1),t.include==="locking scripts"?r.writeInt8(1):t.include==="entire transactions"?r.writeInt8(2):r.writeInt8(-1),a(this,v,Dt).call(this,r,t.includeCustomInstructions),a(this,v,Dt).call(this,r,t.includeTags),a(this,v,Dt).call(this,r,t.includeLabels),a(this,v,oi).call(this,r,t.limit),a(this,v,oi).call(this,r,t.offset),a(this,v,Dt).call(this,r,t.seekPermission);let s=await a(this,v,Nt).call(this,"listOutputs",e,r.toUint8Array()),o=new mt(s),c=a(this,v,Ae).call(this,o.readVarIntNumStrict(!1),"listOutputs totalOutputs",0,4294967295),u=o.readVarIntNumStrict(),f=u>=0?o.readView(u):void 0,d=[];for(;!o.eof();)a(this,v,Go).call(this,d.length,t.limit,"listOutputs"),d.push(a(this,v,Ob).call(this,o));return a(this,v,jo).call(this,d.length,c,"listOutputs"),Ft("listOutputs",{totalOutputs:c,BEEF:f,outputs:d},i)}async relinquishOutput(t,e){xt("relinquishOutput",t);let i=new ht,r=et(t.basket,"utf8");i.writeVarIntNum(r.length),i.write(r),i.write(a(this,v,Es).call(this,t.output));let s=await a(this,v,Nt).call(this,"relinquishOutput",e,i.toUint8Array());return a(this,v,$i).call(this,s,"relinquishOutput"),{relinquished:!0}}async getPublicKey(t,e){xt("getPublicKey",t);let i=new ht;i.writeUInt8(t.identityKey?1:0),t.identityKey?i.write(a(this,v,Lr).call(this,t.privileged,t.privilegedReason)):(t.protocolID??(t.protocolID=[Mc.Silent,"default"]),t.keyID??(t.keyID=""),i.write(a(this,v,ai).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),typeof t.forSelf=="boolean"?i.writeInt8(t.forSelf?1:0):i.writeInt8(-1)),a(this,v,Dt).call(this,i,t.seekPermission);let r=await a(this,v,Nt).call(this,"getPublicKey",e,i.toUint8Array());return a(this,v,Ur).call(this,r,33,"getPublicKey"),Ht.fromDER(Array.from(r)),{publicKey:nt(r)}}async revealCounterpartyKeyLinkage(t,e){xt("revealCounterpartyKeyLinkage",t);let i=bt("revealCounterpartyKeyLinkage",t),r=new ht;r.write(a(this,v,Lr).call(this,t.privileged,t.privilegedReason)),r.write(et(t.counterparty,"hex")),r.write(et(t.verifier,"hex"));let s=await a(this,v,Nt).call(this,"revealCounterpartyKeyLinkage",e,r.toUint8Array()),o=new mt(s),c=a(this,v,Hi).call(this,o,"revealCounterpartyKeyLinkage prover"),u=a(this,v,Hi).call(this,o,"revealCounterpartyKeyLinkage verifier"),f=a(this,v,Hi).call(this,o,"revealCounterpartyKeyLinkage counterparty"),d=o.readVarIntNumStrict(!1),l=Rt(o.read(d)),p=o.readVarIntNumStrict(!1),b=o.read(p),g=o.readVarIntNumStrict(!1),w=o.read(g);return a(this,v,Di).call(this,o,"revealCounterpartyKeyLinkage"),Ft("revealCounterpartyKeyLinkage",{prover:c,verifier:u,counterparty:f,revelationTime:l,encryptedLinkage:Array.from(b),encryptedLinkageProof:Array.from(w)},i)}async revealSpecificKeyLinkage(t,e){xt("revealSpecificKeyLinkage",t);let i=bt("revealSpecificKeyLinkage",t),r=new ht;r.write(a(this,v,ai).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),r.write(et(t.verifier,"hex"));let s=await a(this,v,Nt).call(this,"revealSpecificKeyLinkage",e,r.toUint8Array()),o=new mt(s),c=a(this,v,Hi).call(this,o,"revealSpecificKeyLinkage prover"),u=a(this,v,Hi).call(this,o,"revealSpecificKeyLinkage verifier"),f=a(this,v,Hi).call(this,o,"revealSpecificKeyLinkage counterparty"),d=a(this,v,_b).call(this,o,"revealSpecificKeyLinkage"),l=o.readVarIntNumStrict(!1),p=Rt(o.read(l)),b=o.readVarIntNumStrict(!1),g=Rt(o.read(b)),w=o.readVarIntNumStrict(!1),S=o.read(w),C=o.readVarIntNumStrict(!1),E=o.read(C),A=o.readUInt8();return a(this,v,Di).call(this,o,"revealSpecificKeyLinkage"),Ft("revealSpecificKeyLinkage",{prover:c,verifier:u,counterparty:f,protocolID:[d,p],keyID:g,encryptedLinkage:Array.from(S),encryptedLinkageProof:Array.from(E),proofType:A},i)}async encrypt(t,e){xt("encrypt",t);let i=new ht;return i.write(a(this,v,ai).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.plaintext.length),i.write(t.plaintext),a(this,v,Dt).call(this,i,t.seekPermission),{ciphertext:Array.from(await a(this,v,Nt).call(this,"encrypt",e,i.toUint8Array()))}}async decrypt(t,e){xt("decrypt",t);let i=new ht;return i.write(a(this,v,ai).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.ciphertext.length),i.write(t.ciphertext),a(this,v,Dt).call(this,i,t.seekPermission),{plaintext:Array.from(await a(this,v,Nt).call(this,"decrypt",e,i.toUint8Array()))}}async createHmac(t,e){xt("createHmac",t);let i=new ht;i.write(a(this,v,ai).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.data.length),i.write(t.data),a(this,v,Dt).call(this,i,t.seekPermission);let r=await a(this,v,Nt).call(this,"createHmac",e,i.toUint8Array());return a(this,v,Ur).call(this,r,32,"createHmac"),{hmac:Array.from(r)}}async verifyHmac(t,e){xt("verifyHmac",t);let i=new ht;i.write(a(this,v,ai).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.write(t.hmac),i.writeVarIntNum(t.data.length),i.write(t.data),a(this,v,Dt).call(this,i,t.seekPermission);let r=await a(this,v,Nt).call(this,"verifyHmac",e,i.toUint8Array());return a(this,v,$i).call(this,r,"verifyHmac"),{valid:!0}}async createSignature(t,e){xt("createSignature",t);let i=new ht;return i.write(a(this,v,ai).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),typeof t.data=="object"?(i.writeUInt8(1),i.writeVarIntNum(t.data.length),i.write(t.data)):(t.hashToDirectlySign??(t.hashToDirectlySign=[]),i.writeUInt8(2),i.write(t.hashToDirectlySign)),a(this,v,Dt).call(this,i,t.seekPermission),Ft("createSignature",{signature:Array.from(await a(this,v,Nt).call(this,"createSignature",e,i.toUint8Array()))},t)}async verifySignature(t,e){xt("verifySignature",t);let i=new ht;i.write(a(this,v,ai).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),typeof t.forSelf=="boolean"?i.writeInt8(t.forSelf?1:0):i.writeInt8(-1),i.writeVarIntNum(t.signature.length),i.write(t.signature),typeof t.data=="object"?(i.writeUInt8(1),i.writeVarIntNum(t.data.length),i.write(t.data)):(i.writeUInt8(2),i.write(t.hashToDirectlyVerify??[])),a(this,v,Dt).call(this,i,t.seekPermission);let r=await a(this,v,Nt).call(this,"verifySignature",e,i.toUint8Array());return a(this,v,$i).call(this,r,"verifySignature"),{valid:!0}}async acquireCertificate(t,e){xt("acquireCertificate",t);let i=bt("acquireCertificate",t),r=new ht;r.write(et(t.type,"base64")),r.write(et(t.certifier,"hex"));let s=Object.entries(t.fields);r.writeVarIntNum(s.length);for(let[u,f]of s){let d=et(u,"utf8"),l=et(f,"utf8");r.writeVarIntNum(d.length),r.write(d),r.writeVarIntNum(l.length),r.write(l)}if(r.write(a(this,v,Lr).call(this,t.privileged,t.privilegedReason)),r.writeUInt8(t.acquisitionProtocol==="direct"?1:2),t.acquisitionProtocol==="direct"){r.write(et(t.serialNumber,"base64")),r.write(a(this,v,Es).call(this,t.revocationOutpoint??""));let u=et(t.signature,"hex");r.writeVarIntNum(u.length),r.write(u);let f=t.keyringRevealer==="certifier"?[11]:et(t.keyringRevealer,"hex");r.write(f);let d=Object.keys(t.keyringForSubject??{});r.writeVarIntNum(d.length);for(let l of d){let p=et(l,"utf8");r.writeVarIntNum(p.length),r.write(p);let b=et(t.keyringForSubject?.[l],"base64");r.writeVarIntNum(b.length),r.write(b)}}else{let u=et(t.certifierUrl,"utf8");r.writeVarIntNum(u.length),r.write(u)}let o=await a(this,v,Nt).call(this,"acquireCertificate",e,r.toUint8Array()),c=_r.fromBinary(o);return Ft("acquireCertificate",{...c,signature:c.signature},i)}async listCertificates(t,e){xt("listCertificates",t);let i=bt("listCertificates",t),r=new ht;r.writeVarIntNum(t.certifiers.length);for(let f of t.certifiers)r.write(et(f,"hex"));r.writeVarIntNum(t.types.length);for(let f of t.types)r.write(et(f,"base64"));typeof t.limit=="number"?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),typeof t.offset=="number"?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),r.write(a(this,v,Lr).call(this,t.privileged,t.privilegedReason));let s=await a(this,v,Nt).call(this,"listCertificates",e,r.toUint8Array()),o=new mt(s),c=a(this,v,Ae).call(this,o.readVarIntNumStrict(!1),"listCertificates totalCertificates",0,4294967295),u=[];for(;!o.eof();){a(this,v,Go).call(this,u.length,t.limit,"listCertificates");let f=o.readVarIntNumStrict(!1),d=o.read(f),l=_r.fromBinary(d),p={};if(a(this,v,ci).call(this,o,"listCertificates keyring present")){let w=o.readVarIntNumStrict(!1);a(this,v,Je).call(this,o,w,"listCertificates keyring");for(let S=0;S<w;S++){let C=o.readVarIntNumStrict(!1),E=a(this,v,Yo).call(this,o,C,"listCertificates keyring"),A=o.readVarIntNumStrict(!1);a(this,v,Zo).call(this,p,E,Se(o.read(A)),"listCertificates keyring")}}let b=o.readVarIntNumStrict(!1),g;if(b>0){if(b!==33)throw new Error(`Invalid listCertificates verifier length: expected 33 bytes, received ${b}`);g=a(this,v,Hi).call(this,o,"listCertificates verifier")}u.push({...l,signature:l.signature,keyring:p,verifier:g})}return a(this,v,jo).call(this,u.length,c,"listCertificates"),Ft("listCertificates",{totalCertificates:c,certificates:u},i)}async proveCertificate(t,e){xt("proveCertificate",t);let i=bt("proveCertificate",t),r=new ht,s=et(t.certificate.type,"base64");r.write(s);let o=et(t.certificate.subject,"hex");r.write(o);let c=et(t.certificate.serialNumber,"base64");r.write(c);let u=et(t.certificate.certifier,"hex");r.write(u);let f=a(this,v,Es).call(this,t.certificate.revocationOutpoint??"");r.write(f);let d=et(t.certificate.signature,"hex");r.writeVarIntNum(d.length),r.write(d);let l=Object.entries(t.certificate.fields??{});r.writeVarIntNum(l.length);for(let[S,C]of l){let E=et(S,"utf8"),A=et(C,"utf8");r.writeVarIntNum(E.length),r.write(E),r.writeVarIntNum(A.length),r.write(A)}r.writeVarIntNum(t.fieldsToReveal.length);for(let S of t.fieldsToReveal){let C=et(S,"utf8");r.writeVarIntNum(C.length),r.write(C)}r.write(et(t.verifier,"hex")),r.write(a(this,v,Lr).call(this,t.privileged,t.privilegedReason));let p=await a(this,v,Nt).call(this,"proveCertificate",e,r.toUint8Array()),b=new mt(p),g=b.readVarIntNumStrict(!1);a(this,v,Je).call(this,b,g,"proveCertificate keyring");let w={};for(let S=0;S<g;S++){let C=b.readVarIntNumStrict(!1),E=a(this,v,Yo).call(this,b,C,"proveCertificate keyring"),A=b.readVarIntNumStrict(!1);a(this,v,Zo).call(this,w,E,Se(b.read(A)),"proveCertificate keyring")}return a(this,v,Di).call(this,b,"proveCertificate"),Ft("proveCertificate",{keyringForVerifier:w},i)}async relinquishCertificate(t,e){xt("relinquishCertificate",t);let i=new ht,r=et(t.type,"base64");i.write(r);let s=et(t.serialNumber,"base64");i.write(s);let o=et(t.certifier,"hex");i.write(o);let c=await a(this,v,Nt).call(this,"relinquishCertificate",e,i.toUint8Array());return a(this,v,$i).call(this,c,"relinquishCertificate"),{relinquished:!0}}async discoverByIdentityKey(t,e){xt("discoverByIdentityKey",t);let i=bt("discoverByIdentityKey",t),r=new ht;r.write(et(t.identityKey,"hex")),typeof t.limit=="number"?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),typeof t.offset=="number"?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),a(this,v,Dt).call(this,r,t.seekPermission);let s=await a(this,v,Nt).call(this,"discoverByIdentityKey",e,r.toUint8Array());return Ft("discoverByIdentityKey",a(this,v,Nd).call(this,s,t.limit),i)}async discoverByAttributes(t,e){xt("discoverByAttributes",t);let i=bt("discoverByAttributes",t),r=new ht,s=Object.keys(t.attributes);r.writeVarIntNum(s.length);for(let c of s){let u=et(c,"utf8"),f=et(t.attributes[c],"utf8");r.writeVarIntNum(u.length),r.write(u),r.writeVarIntNum(f.length),r.write(f)}typeof t.limit=="number"?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),typeof t.offset=="number"?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),a(this,v,Dt).call(this,r,t.seekPermission);let o=await a(this,v,Nt).call(this,"discoverByAttributes",e,r.toUint8Array());return Ft("discoverByAttributes",a(this,v,Nd).call(this,o,t.limit),i)}async isAuthenticated(t,e){xt("isAuthenticated",t);let i=await a(this,v,Nt).call(this,"isAuthenticated",e);if(a(this,v,Ur).call(this,i,1,"isAuthenticated"),i[0]!==0&&i[0]!==1)throw new Error("Wallet returned an invalid authentication verdict");return{authenticated:i[0]===1}}async waitForAuthentication(t,e){xt("waitForAuthentication",t);let i=await a(this,v,Nt).call(this,"waitForAuthentication",e);return a(this,v,$i).call(this,i,"waitForAuthentication"),{authenticated:!0}}async getHeight(t,e){xt("getHeight",t);let i=await a(this,v,Nt).call(this,"getHeight",e),r=new mt(i),s=r.readVarIntNumStrict(!1);if(a(this,v,Di).call(this,r,"getHeight"),s<1||s>4294967295)throw new Error("Wallet returned an invalid height");return{height:s}}async getHeaderForHeight(t,e){if(xt("getHeaderForHeight",t),!Number.isInteger(t.height)||t.height<1||t.height>4294967295)throw new Error("getHeaderForHeight requires a height from 1 to 4294967295");let i=new ht;i.writeVarIntNum(t.height);let r=await a(this,v,Nt).call(this,"getHeaderForHeight",e,i.toUint8Array());return a(this,v,Ur).call(this,r,80,"getHeaderForHeight"),{header:nt(r)}}async getNetwork(t,e){xt("getNetwork",t);let i=await a(this,v,Nt).call(this,"getNetwork",e);if(a(this,v,Ur).call(this,i,1,"getNetwork"),i[0]!==0&&i[0]!==1)throw new Error("Wallet returned an invalid network");return{network:i[0]===0?"mainnet":"testnet"}}async getVersion(t,e){xt("getVersion",t);let i=await a(this,v,Nt).call(this,"getVersion",e);if(i.length<7||i.length>30)throw new Error("Wallet returned an invalid version");return{version:Rt(i)}}};v=new WeakSet,Nt=async function(t,e="",i=[]){let r=e===""?"":ni(e),s=et(r,"utf8"),o=new ht(void 0,2+s.length+i.length);o.writeUInt8(Ss[t]),o.writeUInt8(s.length),o.write(s),i.length>0&&o.write(i);let c=o.toUint8ArrayZeroCopy();if(c.length>268435456)throw new Error("Wallet Wire request exceeds the maximum permitted size");let u;if(this.wire.transmitToWalletUint8Array===void 0){let l=await this.wire.transmitToWallet(Array.from(c));if(!Array.isArray(l)||l.length>268435456)throw new Error("Wallet Wire response exceeds the maximum permitted size");for(let p=0;p<l.length;p++)if(!Object.prototype.hasOwnProperty.call(l,p)||!Number.isInteger(l[p])||l[p]<0||l[p]>255)throw new Error("Wallet Wire response must be a dense byte array");u=Uint8Array.from(l)}else{let l=await this.wire.transmitToWalletUint8Array(c);if(!(l instanceof Uint8Array)||l.length>268435456)throw new Error("Wallet Wire response exceeds the maximum permitted size");u=l}let f=new mt(u),d=f.readUInt8();if(d===0)return f.readView();{let l=f.readVarIntNumStrict(!1),p=f.read(l),b=Rt(p),g=f.readVarIntNumStrict(!1),w=f.read(g),S=Rt(w);throw a(this,v,Di).call(this,f,t),new si(b,d,S)}},Ib=function(t){let e=new mt(t),i={};a(this,v,ci).call(this,e,"createAction txid present")&&(i.txid=nt(e.read(32))),a(this,v,ci).call(this,e,"createAction tx present")&&(i.tx=e.readView(e.readVarIntNumStrict(!1)));let r=e.readVarIntNumStrict();if(r>=0){a(this,v,Je).call(this,e,r,"createAction noSendChange",33),i.noSendChange=[];for(let o=0;o<r;o++)i.noSendChange.push(a(this,v,eu).call(this,e))}let s=a(this,v,Rd).call(this,e);if(s!=null&&(i.sendWithResults=s),a(this,v,ci).call(this,e,"createAction signableTransaction present")){let o=e.readView(e.readVarIntNumStrict(!1)),c=e.read(e.readVarIntNumStrict(!1));i.signableTransaction={tx:o,reference:Se(c)}}return a(this,v,Di).call(this,e,"createAction"),i},Sb=function(t){let e=k2[t];if(e==null)throw new Error(`Unknown status code: ${t}`);return e},vb=function(t){let e;return t.remaining()>=9&&t.bin[t.pos]===255&&t.bin[t.pos+8]>=128?(t.skip(1),e=t.readInt64LEBn().toNumber()):e=t.readVarIntNumStrict(!1),a(this,v,Ae).call(this,e,"listActions satoshis",-21e14,21e14)},Ab=function(t){let e=nt(t.read(32)),i=a(this,v,vb).call(this,t),r=a(this,v,Sb).call(this,t.readInt8()),s=a(this,v,ci).call(this,t,"listActions isOutgoing"),o=Rt(t.read(t.readVarIntNumStrict(!1))),c={txid:e,satoshis:i,status:r,isOutgoing:s,description:o,version:0,lockTime:0},u=t.readVarIntNumStrict();if(u>=0){a(this,v,Je).call(this,t,u,"listActions labels"),c.labels=[];for(let l=0;l<u;l++)c.labels.push(Rt(t.read(t.readVarIntNumStrict(!1))))}c.version=a(this,v,Ae).call(this,t.readVarIntNumStrict(!1),"listActions version",0,4294967295),c.lockTime=a(this,v,Ae).call(this,t.readVarIntNumStrict(!1),"listActions lockTime",0,4294967295);let f=t.readVarIntNumStrict();if(f>=0){a(this,v,Je).call(this,t,f,"listActions inputs"),c.inputs=[];for(let l=0;l<f;l++)c.inputs.push(a(this,v,Eb).call(this,t))}let d=t.readVarIntNumStrict();if(d>=0){a(this,v,Je).call(this,t,d,"listActions outputs"),c.outputs=[];for(let l=0;l<d;l++)c.outputs.push(a(this,v,kb).call(this,t))}return c},Eb=function(t){let e=a(this,v,eu).call(this,t),i=a(this,v,Ae).call(this,t.readVarIntNumStrict(!1),"listActions input sourceSatoshis",0,21e14),r=t.readVarIntNumStrict(),s=r>=0?nt(t.read(r)):void 0,o=t.readVarIntNumStrict(),c=o>=0?nt(t.read(o)):void 0,u=Rt(t.read(t.readVarIntNumStrict(!1))),f=a(this,v,Ae).call(this,t.readVarIntNumStrict(!1),"listActions input sequenceNumber",0,4294967295);return{sourceOutpoint:e,sourceSatoshis:i,sourceLockingScript:s,unlockingScript:c,inputDescription:u,sequenceNumber:f}},kb=function(t){let e=a(this,v,Ae).call(this,t.readVarIntNumStrict(!1),"listActions output outputIndex",0,4294967295),i=a(this,v,Ae).call(this,t.readVarIntNumStrict(!1),"listActions output satoshis",0,21e14),r=t.readVarIntNumStrict(),s=r>=0?nt(t.read(r)):void 0,o=a(this,v,ci).call(this,t,"listOutputs spendable"),c=Rt(t.read(t.readVarIntNumStrict(!1))),u=t.readVarIntNumStrict(),f=u>=0?Rt(t.read(u)):void 0,d=t.readVarIntNumStrict(),l=[];if(d>=0){a(this,v,Je).call(this,t,d,"listActions output tags");for(let g=0;g<d;g++)l.push(Rt(t.read(t.readVarIntNumStrict(!1))))}let p=t.readVarIntNumStrict(),b=p>=0?Rt(t.read(p)):void 0;return{outputIndex:e,satoshis:i,lockingScript:s,spendable:o,outputDescription:c,basket:f,tags:l,customInstructions:b}},Tb=function(t,e){if(t.writeVarIntNum(e.outputIndex),e.protocol==="wallet payment"){if(e.paymentRemittance==null)throw new Error("Payment remittance is required for wallet payment");t.writeUInt8(1),t.write(et(e.paymentRemittance.senderIdentityKey,"hex"));let i=et(e.paymentRemittance.derivationPrefix,"base64");t.writeVarIntNum(i.length),t.write(i);let r=et(e.paymentRemittance.derivationSuffix,"base64");t.writeVarIntNum(r.length),t.write(r)}else{t.writeUInt8(2);let i=et(e.insertionRemittance?.basket,"utf8");t.writeVarIntNum(i.length),t.write(i),a(this,v,nu).call(this,t,e.insertionRemittance?.customInstructions);let r=e.insertionRemittance?.tags;if(typeof r=="object"){t.writeVarIntNum(r.length);for(let s of r){let o=et(s,"utf8");t.writeVarIntNum(o.length),t.write(o)}}else t.writeVarIntNum(0)}},Ob=function(t){let e=a(this,v,eu).call(this,t),i=a(this,v,Ae).call(this,t.readVarIntNumStrict(!1),"listOutputs satoshis",0,21e14),r={spendable:!0,outpoint:e,satoshis:i},s=t.readVarIntNumStrict();s>=0&&(r.lockingScript=nt(t.read(s)));let o=t.readVarIntNumStrict();o>=0&&(r.customInstructions=Rt(t.read(o)));let c=t.readVarIntNumStrict();if(c!==-1){a(this,v,Je).call(this,t,c,"listOutputs tags");let f=[];for(let d=0;d<c;d++)f.push(Rt(t.read(t.readVarIntNumStrict(!1))));r.tags=f}let u=t.readVarIntNumStrict();if(u!==-1){a(this,v,Je).call(this,t,u,"listOutputs labels");let f=[];for(let d=0;d<u;d++)f.push(Rt(t.read(t.readVarIntNumStrict(!1))));r.labels=f}return r},Es=function(t){let e=new ht;if(typeof t!="string")throw new Error("Invalid outpoint: expected a string");let i=t.split(".");if(i.length!==2||!/^(?:0|[1-9]\d*)$/.test(i[1]))throw new Error(`Invalid outpoint: ${t}`);let r=et(i[0],"hex");if(r.length!==32)throw new Error("Invalid outpoint txid length");return e.write(r),e.writeVarIntNum(a(this,v,Ae).call(this,Number(i[1]),"outpoint index",0,4294967295)),e.toUint8Array()},eu=function(t){let e=nt(t.read(32)),i=a(this,v,Ae).call(this,t.readVarIntNumStrict(!1),"outpoint index",0,4294967295);return`${e}.${i}`},Dt=function(t,e){t.writeInt8(su.OPTIONAL_BOOLEAN_WIRE_VALUES.get(e))},oi=function(t,e){typeof e=="number"?t.writeVarIntNum(e):t.writeVarIntNum(-1)},Cr=function(t,e){let i=et(e??"","utf8");t.writeVarIntNum(i.length),t.write(i)},nu=function(t,e){if(e!=null&&e!==""){let i=et(e,"utf8");t.writeVarIntNum(i.length),t.write(i)}else t.writeVarIntNum(-1)},iu=function(t,e){if(e==null)t.writeVarIntNum(-1);else{t.writeVarIntNum(e.length);for(let i of e){let r=et(i,"utf8");t.writeVarIntNum(r.length),t.write(r)}}},ru=function(t,e){if(e==null)t.writeVarIntNum(-1);else{t.writeVarIntNum(e.length);for(let i of e)t.write(et(i,"hex"))}},Rd=function(t){let e=t.readVarIntNumStrict();if(e<0)return;a(this,v,Je).call(this,t,e,"sendWithResults",33,1001);let i=[];for(let r=0;r<e;r++){let s=nt(t.read(32)),o=t.readInt8(),c="unproven";if(o===2)c="sending";else if(o===3)c="failed";else if(o!==1)throw new Error(`Unknown sendWith result status code: ${o}`);i.push({txid:s,status:c})}return i},Pb=function(t,e){if(t.write(a(this,v,Es).call(this,e.outpoint)),e.unlockingScript!=null&&e.unlockingScript!==""){let i=et(e.unlockingScript,"hex");t.writeVarIntNum(i.length),t.write(i)}else t.writeVarIntNum(-1),t.writeVarIntNum(e.unlockingScriptLength??0);a(this,v,Cr).call(this,t,e.inputDescription),a(this,v,oi).call(this,t,e.sequenceNumber)},Rb=function(t,e){let i=et(e.lockingScript,"hex");t.writeVarIntNum(i.length),t.write(i),t.writeVarIntNum(e.satoshis),a(this,v,Cr).call(this,t,e.outputDescription),a(this,v,nu).call(this,t,e.basket),a(this,v,nu).call(this,t,e.customInstructions),a(this,v,iu).call(this,t,e.tags)},Nb=function(t,e){if(e==null){t.writeInt8(0);return}if(t.writeInt8(1),a(this,v,Dt).call(this,t,e.signAndProcess),a(this,v,Dt).call(this,t,e.acceptDelayedBroadcast),t.writeInt8(e.trustSelf==="known"?1:-1),a(this,v,ru).call(this,t,e.knownTxids),a(this,v,Dt).call(this,t,e.returnTXIDOnly),a(this,v,Dt).call(this,t,e.noSend),e.noSendChange==null)t.writeVarIntNum(-1);else{t.writeVarIntNum(e.noSendChange.length);for(let i of e.noSendChange)t.write(a(this,v,Es).call(this,i))}a(this,v,ru).call(this,t,e.sendWith),a(this,v,Dt).call(this,t,e.randomizeOutputs)},Bb=function(t,e){if(e==null){t.writeInt8(0);return}t.writeInt8(1),a(this,v,Dt).call(this,t,e.acceptDelayedBroadcast),a(this,v,Dt).call(this,t,e.returnTXIDOnly),a(this,v,Dt).call(this,t,e.noSend),a(this,v,ru).call(this,t,e.sendWith)},ai=function(t,e,i,r,s){let o=new ht;o.writeUInt8(t[0]);let c=et(t[1],"utf8");o.writeVarIntNum(c.length),o.write(c);let u=et(e,"utf8");return o.writeVarIntNum(u.length),o.write(u),typeof i!="string"?o.writeUInt8(0):i==="self"?o.writeUInt8(11):i==="anyone"?o.writeUInt8(12):o.write(et(i,"hex")),o.write(a(this,v,Lr).call(this,r,s)),o.toUint8Array()},Lr=function(t,e){let i=new ht;if(typeof t=="boolean"?i.writeInt8(t?1:0):i.writeInt8(-1),typeof e=="string"){let r=et(e,"utf8");i.writeInt8(r.length),i.write(r)}else i.writeInt8(-1);return i.toUint8Array()},Nd=function(t,e){let i=new mt(t),r=a(this,v,Ae).call(this,i.readVarIntNumStrict(!1),"discovery totalCertificates",0,4294967295),s=[];for(;!i.eof();){a(this,v,Go).call(this,s.length,e,"discover");let o=i.readVarIntNumStrict(!1),c=i.read(o),u=_r.fromBinary(c),f=i.readVarIntNumStrict(!1),d=Rt(i.read(f)),l=i.readVarIntNumStrict(!1),p=Rt(i.read(l)),b=i.readVarIntNumStrict(!1),g=Rt(i.read(b)),w=a(this,v,Ae).call(this,i.readUInt8(),"discovery trust",1,10),S={},C=i.readVarIntNumStrict(!1);a(this,v,Je).call(this,i,C,"discovery public keyring");for(let k=0;k<C;k++){let B=i.readVarIntNumStrict(!1),_=a(this,v,Yo).call(this,i,B,"discovery public keyring"),$=i.readVarIntNumStrict(!1);a(this,v,Zo).call(this,S,_,Se(i.read($)),"discovery public keyring")}let E={},A=i.readVarIntNumStrict(!1);a(this,v,Je).call(this,i,A,"discovery decrypted fields");for(let k=0;k<A;k++){let B=i.readVarIntNumStrict(!1),_=a(this,v,Yo).call(this,i,B,"discovery decrypted fields"),$=i.readVarIntNumStrict(!1);a(this,v,Zo).call(this,E,_,Rt(i.read($)),"discovery decrypted fields")}s.push({...u,signature:u.signature,certifierInfo:{iconUrl:p,name:d,description:g,trust:w},publiclyRevealedKeyring:S,decryptedFields:E})}return a(this,v,jo).call(this,s.length,r,"discover"),{totalCertificates:r,certificates:s}},Di=function(t,e){if(!t.eof())throw new Error(`Wallet Wire ${e} response contains trailing data`)},jo=function(t,e,i){if(t>e)throw new Error(`Wallet Wire ${i} response returned ${t} records but declared a total of ${e}`)},Go=function(t,e,i){let r=e??10;if(t>=r)throw new Error(`Wallet Wire ${i} response exceeds the requested page limit of ${r}`)},Je=function(t,e,i,r=1,s=E2){if(!Number.isSafeInteger(e)||e<0||e>s)throw new Error(`Wallet Wire ${i} exceeds the maximum collection size of ${s}`);if(e>Math.floor(t.remaining()/r))throw new Error(`Wallet Wire ${i} count exceeds the remaining response data`);return e},ci=function(t,e){let i=t.readInt8();if(i!==0&&i!==1)throw new Error(`Invalid ${e} flag: expected 0 or 1, received ${i}`);return i===1},Yo=function(t,e,i){if(e<1||e>50)throw new Error(`Invalid ${i} key length: expected 1\u201350 bytes, received ${e}`);let r=Rt(t.read(e));if(gn(r))throw new Error(`Unsafe ${i} key: ${r}`);return r},Zo=function(t,e,i,r){if(Object.prototype.hasOwnProperty.call(t,e))throw new Error(`Duplicate ${r} key: ${e}`);t[e]=i},Hi=function(t,e){let i=t.read(33);return Ht.fromDER(Array.from(i)),nt(i)},_b=function(t,e){let i=t.readUInt8();if(i!==0&&i!==1&&i!==2)throw new Error(`Invalid ${e} security level: ${i}`);return i},Ae=function(t,e,i,r){if(!Number.isSafeInteger(t)||t<i||t>r)throw new Error(`Invalid ${e}: expected an integer from ${i} to ${r}, received ${String(t)}`);return t},Ur=function(t,e,i){if(t.length!==e)throw new Error(`Wallet Wire ${i} response has an invalid length`)},$i=function(t,e){a(this,v,Ur).call(this,t,0,e)},m(su,"OPTIONAL_BOOLEAN_WIRE_VALUES",new Map([[!0,1],[!1,0],[void 0,-1]]));var ks=su;function Cb(n,t="http"){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(n))try{return new URL(n).origin}catch{}try{return new URL(`${t}://${n}`).origin}catch{throw new Error(`Invalid originator value: ${n}`)}}function Ts(n){if(typeof n!="string"||n.length<1||n.length>2048||n!==n.trim())throw new TypeError("Wallet HTTP baseUrl must be an exact HTTP(S) origin.");let t;try{t=new URL(n)}catch{throw new TypeError("Wallet HTTP baseUrl must be an exact HTTP(S) origin.")}if(t.protocol!=="https:"&&t.protocol!=="http:"||t.username!==""||t.password!==""||t.pathname!=="/"||t.search!==""||t.hash!==""||t.origin==="null")throw new TypeError("Wallet HTTP baseUrl must be an HTTP(S) origin without credentials, path, query, or fragment.");if(t.protocol==="http:"&&!T2(t.hostname))throw new TypeError("Wallet HTTP baseUrl may use cleartext HTTP only for a loopback host.");return t.origin}function T2(n){let t=n.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="[::1]"}var Os=class{constructor(t,e="http://localhost:3301",i){m(this,"baseUrl");m(this,"httpClient");m(this,"originator");let r=ni(t);this.baseUrl=Ts(e),this.httpClient=i??globalThis.fetch.bind(globalThis),this.originator=r}async transmitToWallet(t){return Array.from(await this.transmitToWalletUint8Array(Uint8Array.from(t)))}async transmitToWalletUint8Array(t){if(!(t instanceof Uint8Array)||t.length>268435456)throw new Error("HTTPWalletWire request exceeds the maximum permitted size");let e=new mt(t),i=e.readUInt8(),r=Ss[i];if(r===void 0||r==="")throw new Error(`Invalid call code: ${i}`);let s=e.readUInt8();if(s>250)throw new Error(`Invalid originator length: expected at most 250 bytes, received ${s}`);let o;if(s>0){let d=e.read(s);o=ni(Rt(d))}if(this.originator!==void 0&&o!==this.originator)throw new Error("Wallet Wire frame originator does not match the configured originator");let c=e.readView(),u=Ts(this.baseUrl),f=await this.httpClient(`${u}/${r}`,{method:"POST",redirect:"error",headers:{"Content-Type":"application/octet-stream",Origin:o??""},body:c});return await this.readResponse(f)}async readResponse(t){if(t.ok===!1)throw new Error(`HTTPWalletWire request failed with HTTP status ${String(t.status)}`);let e=t.headers?.get("content-length");if(e!=null){if(!/^\d+$/.test(e))throw new Error("HTTPWalletWire response has an invalid Content-Length");let u=Number(e);if(!Number.isSafeInteger(u)||u>268435456)throw new Error("HTTPWalletWire response exceeds the maximum permitted size")}if(t.body==null){let u=await t.arrayBuffer();if(u.byteLength>268435456)throw new Error("HTTPWalletWire response exceeds the maximum permitted size");return new Uint8Array(u)}let i=t.body.getReader(),r=[],s=0;for(;;){let{value:u,done:f}=await i.read();if(f)break;if(u!=null){if(s+=u.byteLength,s>268435456)throw await i.cancel().catch(()=>{}),new Error("HTTPWalletWire response exceeds the maximum permitted size");r.push(u)}}let o=new Uint8Array(s),c=0;for(let u of r)o.set(u,c),c+=u.byteLength;return o}};var ou=class extends Error{constructor(e,i,r,s,o){super("Undelayed createAction or signAction results require review.");m(this,"reviewActionResults");m(this,"sendWithResults");m(this,"txid");m(this,"tx");m(this,"noSendChange");m(this,"code");m(this,"isError",!0);this.reviewActionResults=e,this.sendWithResults=i,this.txid=r,this.tx=s,this.noSendChange=o,this.code=5,this.name=this.constructor.name}};var Bd=class extends Error{constructor(e,i){super(`Insufficient funds in the available inputs to cover the cost of the required outputs and the transaction fee (${i} more satoshis are needed, for a total of ${e}), plus whatever would be required in order to pay the fee to unlock and spend the outputs used to provide the additional satoshis.`);m(this,"totalSatoshisNeeded");m(this,"moreSatoshisNeeded");m(this,"code");m(this,"isError",!0);this.totalSatoshisNeeded=e,this.moreSatoshisNeeded=i,this.code=7,this.name=this.constructor.name}},Lb=Bd;var _d=256*1024*1024,O2=256*1024*1024;async function P2(n){let t=n.headers?.get("content-length");if(t!=null){if(!/^\d+$/.test(t))throw new Error("HTTPWalletJSON response has an invalid Content-Length");let i=Number(t);if(!Number.isSafeInteger(i)||i>_d)throw new Error("HTTPWalletJSON response exceeds the maximum permitted size")}let e;if(n.body!=null&&typeof n.body.getReader=="function"){let i=n.body.getReader(),r=[],s=0;for(;;){let{value:c,done:u}=await i.read();if(u)break;if(c!=null){if(s+=c.byteLength,s>_d)throw await i.cancel().catch(()=>{}),new Error("HTTPWalletJSON response exceeds the maximum permitted size");r.push(c)}}e=new Uint8Array(s);let o=0;for(let c of r)e.set(c,o),o+=c.byteLength}else if(typeof n.arrayBuffer=="function"){let i=await n.arrayBuffer();if(i.byteLength>_d)throw new Error("HTTPWalletJSON response exceeds the maximum permitted size");e=new Uint8Array(i)}return e!==void 0?JSON.parse(Rt(e)):await n.json()}function Cd(n,t,e=0,i=4096){if(typeof n!="string")throw new Error(`Invalid wallet error ${t}`);let r=at(n,"utf8").length;if(r<e||r>i)throw new Error(`Invalid wallet error ${t}`);return n}function Ub(n,t){if(!Number.isSafeInteger(n)||n<0||n>21e14)throw new Error(`Invalid wallet error ${t}`);return n}function R2(n,t){if(!Array.isArray(n))throw new Error("Invalid wallet error reviewActionResults");if(n.length>xn+1)throw new Error("Invalid wallet error reviewActionResults");let e=new Set(["success","doubleSpend","serviceError","invalidTx"]),i=new Set;for(let[r,s]of n.entries()){if(s==null||typeof s!="object"||Array.isArray(s))throw new Error(`Invalid wallet error reviewActionResults[${r}]`);let o=s;if(typeof o.txid!="string"||!/^[0-9a-fA-F]{64}$/.test(o.txid))throw new Error(`Invalid wallet error reviewActionResults[${r}].txid`);let c=o.txid.toLowerCase();if(i.has(c)||!t.has(c))throw new Error(`Invalid wallet error reviewActionResults[${r}].txid`);if(i.add(c),!e.has(o.status))throw new Error(`Invalid wallet error reviewActionResults[${r}].status`);if(o.status!=="doubleSpend"&&(o.competingTxs!==void 0||o.competingBeef!==void 0))throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs`);let u;if(o.competingTxs!==void 0){if(!Array.isArray(o.competingTxs)||o.competingTxs.length>xn)throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs`);u=[];let f=new Set;for(let[d,l]of o.competingTxs.entries()){if(typeof l!="string"||!/^[0-9a-fA-F]{64}$/.test(l))throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs[${d}]`);let p=l.toLowerCase();if(p===c||f.has(p))throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs`);f.add(p),u.push(p)}}if(o.competingBeef!==void 0){if(u==null||u.length===0)throw new Error(`Invalid wallet error reviewActionResults[${r}].competingBeef`);let f=hd(o.competingBeef);if(f==null)throw new Error(`Invalid wallet error reviewActionResults[${r}].competingBeef`);try{let d=T0.fromBinaryStrict(f);for(let l of u)if(d.findTxid(l)==null)throw new Error}catch{throw new Error(`Invalid wallet error reviewActionResults[${r}].competingBeef`)}}}}function N2(n,t,e){if(n.isError!==!0||!Number.isSafeInteger(n.code))throw new Error("Invalid wallet error envelope");switch(n.message!==void 0&&Cd(n.message,"message"),n.code){case 5:{if(t!=="createAction"&&t!=="signAction")throw new Error(`Invalid ${t} wallet error code`);if(!Array.isArray(n.sendWithResults))throw new Error("Invalid wallet error sendWithResults");let i={...e,options:{...e.options,returnTXIDOnly:!0}};Ft(t,{txid:n.txid,tx:n.tx,noSendChange:n.noSendChange,sendWithResults:n.sendWithResults},i);let r=new Set;typeof n.txid=="string"&&r.add(n.txid.toLowerCase());let s=e.options;if(Array.isArray(s?.sendWith))for(let o of s.sendWith)r.add(String(o).toLowerCase());return R2(n.reviewActionResults,r),new ou(n.reviewActionResults,n.sendWithResults,n.txid,n.tx,n.noSendChange)}case 6:{let i=Cd(n.parameter,"parameter",1,200),r=Cd(n.message,"message"),s=new ti(i);return s.message=r,s}case 7:{let i=Ub(n.totalSatoshisNeeded,"totalSatoshisNeeded"),r=Ub(n.moreSatoshisNeeded,"moreSatoshisNeeded");if(r>i)throw new Error("Invalid wallet error moreSatoshisNeeded");return new Lb(i,r)}default:return}}var qi=class{constructor(t,e="http://localhost:3321",i=globalThis.fetch.bind(globalThis)){m(this,"baseUrl");m(this,"httpClient");m(this,"originator");m(this,"api");this.baseUrl=Ts(e),this.originator=ni(t),this.httpClient=i;let r=typeof window<"u"&&typeof document<"u"&&window.origin!=="file://";this.api=async(s,o)=>{xt(s,o);let c=bt(s,o),u=Ts(this.baseUrl);if(!r&&!this.originator)throw new Error('HTTPWalletJSON: originator is required when using the HTTP substrate in Node.js. Pass an originator (e.g. "example.com") to the constructor.');let f=r?void 0:Cb(this.originator,"http"),d=ys(o);if(et(d,"utf8").length>O2)throw new Error("HTTPWalletJSON request exceeds the maximum permitted size");let l=await this.httpClient(`${u}/${s}`,{method:"POST",redirect:"error",headers:{Accept:"application/json","Content-Type":"application/json",...f?{Origin:f,Originator:f}:{}},body:d}),p=fb(await P2(l),`HTTPWalletJSON ${s} raw response`),b=ub(Hc(p),`HTTPWalletJSON ${s} response`);if(b==null||typeof b!="object"||Array.isArray(b))throw new Error(`Invalid HTTPWalletJSON ${s} response: expected an object`);if(!l.ok){if(l.status===400&&Object.prototype.hasOwnProperty.call(b,"isError")){let g=N2(b,s,c);if(g!==void 0)throw g}throw new Error(`HTTPWalletJSON ${s} failed with HTTP status ${l.status}`)}return Ft(s,b,c)}}async createAction(t){return await this.api("createAction",t)}async signAction(t){return await this.api("signAction",t)}async abortAction(t){return await this.api("abortAction",t)}async listActions(t){return await this.api("listActions",t)}async internalizeAction(t){return await this.api("internalizeAction",t)}async listOutputs(t){return await this.api("listOutputs",t)}async relinquishOutput(t){return await this.api("relinquishOutput",t)}async getPublicKey(t){return await this.api("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.api("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.api("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.api("encrypt",t)}async decrypt(t){return await this.api("decrypt",t)}async createHmac(t){return await this.api("createHmac",t)}async verifyHmac(t){return await this.api("verifyHmac",t)}async createSignature(t){return await this.api("createSignature",t)}async verifySignature(t){return await this.api("verifySignature",t)}async acquireCertificate(t){return await this.api("acquireCertificate",t)}async listCertificates(t){return await this.api("listCertificates",t)}async proveCertificate(t){return await this.api("proveCertificate",t)}async relinquishCertificate(t){return await this.api("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.api("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.api("discoverByAttributes",t)}async isAuthenticated(t){return await this.api("isAuthenticated",t)}async waitForAuthentication(t){return await this.api("waitForAuthentication",t)}async getHeight(t){return await this.api("getHeight",t)}async getHeaderForHeight(t){return await this.api("getHeaderForHeight",t)}async getNetwork(t){return await this.api("getNetwork",t)}async getVersion(t){return await this.api("getVersion",t)}};var B2=1024,Mb=3600*1e3,Db=256*1024*1024,Mr=class extends As{constructor(e="*",i){super();m(this,"domain");m(this,"responseTimeout");m(this,"pendingInvocations",0);if(typeof globalThis.window!="object")throw new TypeError("The XDM substrate requires a global window object.");if(!Object.prototype.hasOwnProperty.call(globalThis.window,"ReactNativeWebView"))throw new Error("The window object does not have a ReactNativeWebView property.");if(typeof globalThis.window.ReactNativeWebView.postMessage!="function")throw new TypeError("The window.ReactNativeWebView property does not seem to support postMessage calls.");if(i!==void 0&&(!Number.isSafeInteger(i)||i<1||i>Mb))throw new TypeError(`ReactNativeWebView responseTimeout must be an integer from 1 to ${Mb}.`);this.domain=C2(e),this.responseTimeout=i}async invokeRaw(e,i,r){if(this.pendingInvocations>=B2)throw new Error("React Native wallet pending invocation limit reached.");let s=Se(Pe(12));return this.pendingInvocations++,await new Promise((o,c)=>{let u,f=!1,d=!0,l=()=>{if(d&&(d=!1,this.pendingInvocations--,u!==void 0&&clearTimeout(u),f&&typeof globalThis.window.removeEventListener=="function"))try{globalThis.window.removeEventListener("message",p)}catch{}},p=b=>{if(!_2(b,this.domain)||typeof b.data!="string")return;if(et(b.data,"utf8").length>Db){l(),c(new Error("React Native wallet response exceeds the maximum permitted size."));return}let g;try{g=JSON.parse(b.data)}catch{return}if(!(g?.type!=="CWI"||g.id!==s||g.isInvocation!==!1||g.status!=="success"&&g.status!=="error")){if(this.domain!=="*"&&b.origin!=null&&b.origin!==""&&b.origin!==this.domain){l(),c(new Error(`React Native wallet response origin ${b.origin} did not match ${this.domain}.`));return}if(l(),g.status==="error")if(typeof g.description!="string"||at(g.description,"utf8").length>4096||!Number.isSafeInteger(g.code)||g.code<1||g.code>255)c(new Error("Invalid React Native wallet error response."));else{let w=g.code>=fn.unsupportedAction&&g.code<=fn.abortRefused,S=w?g.description:"Wallet operation failed";c(new si(S,w?g.code:fn.unknownError))}else try{let w=Hc(g.result);o(Ft(e,w,r))}catch(w){c(w)}}};try{globalThis.window.addEventListener("message",p),f=!0,this.responseTimeout!==void 0&&(u=setTimeout(()=>{l(),c(new Error("React Native wallet response timed out."))},this.responseTimeout));let b=ys({type:"CWI",isInvocation:!0,id:s,call:e,args:i});if(et(b,"utf8").length>Db)throw new Error("React Native wallet request exceeds the maximum permitted size.");globalThis.window.ReactNativeWebView.postMessage(b)}catch(b){l(),c(b)}})}};function _2(n,t){let e=globalThis.window,i=n.source;return i==null||i===e?!0:i===e.parent&&(n.origin===e.origin||n.origin===t)}function C2(n){if(n==="*")return n;try{if(/^[a-z][a-z\d+.-]*:\/\//i.test(n)&&!/^https?:\/\//i.test(n))throw new TypeError("Only HTTP(S) origins are supported.");let t=/^https?:\/\//i.test(n)?n:`https://${n}`,e=new URL(t).origin;if(e==="null")throw new TypeError("The origin could not be normalized.");return e}catch{throw new TypeError("ReactNativeWebView domain must be an HTTP(S) origin or domain name.")}}var Ps=1e3,Hb=200,Rs=class{constructor(t="auto",e){m(this,"substrate");m(this,"originator");let i=ni(e);t==="Cicada"&&(t=new ks(new Os(i))),t==="window.CWI"&&(t=new vs),t==="XDM"&&(t=new Br),t==="json-api"&&(t=new qi(i)),t==="react-native"&&(t=new Mr),t==="secure-json-api"&&(t=new qi(i,"https://localhost:2121")),this.substrate=t,this.originator=i}async validatedResult(t,e,i){return Ft(t,await e,i)}async connectToSubstrate(){if(typeof this.substrate=="object")return;let t=async(o,c,u)=>{try{let f=o(),d,l;try{d=await Promise.race([f.getVersion({},this.originator),new Promise((p,b)=>{l=setTimeout(()=>b(new Error("Timed out.")),c)})])}finally{clearTimeout(l)}return Ft("getVersion",d),{success:!0,sub:u?.()??f}}catch{return{success:!1}}},e=[t(()=>new vs,Ps),t(()=>new ks(new Os(this.originator)),Ps),t(()=>new qi(this.originator,"https://localhost:2121"),Ps),t(()=>new qi(this.originator),Ps),t(()=>new Mr("*",Ps),Ps,()=>new Mr)],r=(await Promise.allSettled(e)).filter(o=>o.status==="fulfilled"&&o.value.success&&o.value.sub!==void 0).map(o=>o.value.sub);if(r.length>0){this.substrate=r[0];return}let s=await t(()=>new Br("*",Hb),Hb,()=>new Br);if(s.success&&s.sub!==void 0)this.substrate=s.sub;else throw new Error("No wallet available over any communication substrate. Install a BSV wallet today!")}async createAction(t){lc(t);let e=bt("createAction",t);return await this.connectToSubstrate(),await this.validatedResult("createAction",this.substrate.createAction(t,this.originator),e)}async signAction(t){hc(t);let e=bt("signAction",t);return await this.connectToSubstrate(),await this.validatedResult("signAction",this.substrate.signAction(t,this.originator),e)}async abortAction(t){return pc(t),await this.connectToSubstrate(),await this.validatedResult("abortAction",this.substrate.abortAction(t,this.originator))}async listActions(t){kc(t);let e=bt("listActions",t);return await this.connectToSubstrate(),await this.validatedResult("listActions",this.substrate.listActions(t,this.originator),e)}async internalizeAction(t){return gc(t),await this.connectToSubstrate(),await this.validatedResult("internalizeAction",this.substrate.internalizeAction(t,this.originator))}async listOutputs(t){Ec(t);let e=bt("listOutputs",t);return await this.connectToSubstrate(),await this.validatedResult("listOutputs",this.substrate.listOutputs(t,this.originator),e)}async relinquishOutput(t){return mc(t),await this.connectToSubstrate(),await this.validatedResult("relinquishOutput",this.substrate.relinquishOutput(t,this.originator))}async getPublicKey(t){return Tc(t),await this.connectToSubstrate(),await this.validatedResult("getPublicKey",this.substrate.getPublicKey(t,this.originator))}async revealCounterpartyKeyLinkage(t){Oc(t);let e=bt("revealCounterpartyKeyLinkage",t);return await this.connectToSubstrate(),await this.validatedResult("revealCounterpartyKeyLinkage",this.substrate.revealCounterpartyKeyLinkage(t,this.originator),e)}async revealSpecificKeyLinkage(t){Pc(t);let e=bt("revealSpecificKeyLinkage",t);return await this.connectToSubstrate(),await this.validatedResult("revealSpecificKeyLinkage",this.substrate.revealSpecificKeyLinkage(t,this.originator),e)}async encrypt(t){return Rc(t),await this.connectToSubstrate(),await this.validatedResult("encrypt",this.substrate.encrypt(t,this.originator))}async decrypt(t){return Nc(t),await this.connectToSubstrate(),await this.validatedResult("decrypt",this.substrate.decrypt(t,this.originator))}async createHmac(t){return Bc(t),await this.connectToSubstrate(),await this.validatedResult("createHmac",this.substrate.createHmac(t,this.originator))}async verifyHmac(t){return _c(t),await this.connectToSubstrate(),await this.validatedResult("verifyHmac",this.substrate.verifyHmac(t,this.originator))}async createSignature(t){return Cc(t),await this.connectToSubstrate(),await this.validatedResult("createSignature",this.substrate.createSignature(t,this.originator))}async verifySignature(t){return Lc(t),await this.connectToSubstrate(),await this.validatedResult("verifySignature",this.substrate.verifySignature(t,this.originator))}async acquireCertificate(t){if(t.acquisitionProtocol==="direct")Ic(t);else if(t.acquisitionProtocol==="issuance")xc(t);else throw new ti("acquisitionProtocol",`valid. ${String(t.acquisitionProtocol)} is unrecognized.`);let e=bt("acquireCertificate",t);return await this.connectToSubstrate(),await this.validatedResult("acquireCertificate",this.substrate.acquireCertificate(t,this.originator),e)}async listCertificates(t){wc(t);let e=bt("listCertificates",t);return await this.connectToSubstrate(),await this.validatedResult("listCertificates",this.substrate.listCertificates(t,this.originator),e)}async proveCertificate(t){Sc(t);let e=bt("proveCertificate",t);return await this.connectToSubstrate(),await this.validatedResult("proveCertificate",this.substrate.proveCertificate(t,this.originator),e)}async relinquishCertificate(t){return yc(t),await this.connectToSubstrate(),await this.validatedResult("relinquishCertificate",this.substrate.relinquishCertificate(t,this.originator))}async discoverByIdentityKey(t){vc(t);let e=bt("discoverByIdentityKey",t);return await this.connectToSubstrate(),await this.validatedResult("discoverByIdentityKey",this.substrate.discoverByIdentityKey(t,this.originator),e)}async discoverByAttributes(t){Ac(t);let e=bt("discoverByAttributes",t);return await this.connectToSubstrate(),await this.validatedResult("discoverByAttributes",this.substrate.discoverByAttributes(t,this.originator),e)}async isAuthenticated(t={}){return Ui(t),await this.connectToSubstrate(),await this.validatedResult("isAuthenticated",this.substrate.isAuthenticated(t,this.originator))}async waitForAuthentication(t={}){return Ui(t),await this.connectToSubstrate(),await this.validatedResult("waitForAuthentication",this.substrate.waitForAuthentication(t,this.originator))}async getHeight(t={}){return Ui(t),await this.connectToSubstrate(),await this.validatedResult("getHeight",this.substrate.getHeight(t,this.originator))}async getHeaderForHeight(t){return Uc(t),await this.connectToSubstrate(),await this.validatedResult("getHeaderForHeight",this.substrate.getHeaderForHeight(t,this.originator))}async getNetwork(t={}){return Ui(t),await this.connectToSubstrate(),await this.validatedResult("getNetwork",this.substrate.getNetwork(t,this.originator))}async getVersion(t={}){return Ui(t),await this.connectToSubstrate(),await this.validatedResult("getVersion",this.substrate.getVersion(t,this.originator))}};function Jo(n,t){let e=Promise.resolve();return i=>(e=e.then(()=>n(i)).catch(r=>t?.(r)),e)}var Fb="1",L2="bwallet-pair-v1",U2="www.bwallet.space";var Wb="relay.bwallet.space",cu=120,au=new TextEncoder,M2=new TextDecoder,Vb=n=>{let t="";for(let e=0;e<n.length;e+=32768)t+=String.fromCharCode(...n.subarray(e,e+32768));return t},D2=n=>btoa(Vb(n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),H2=n=>{let t=n.replace(/-/g,"+").replace(/_/g,"/"),e=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(e,i=>i.charCodeAt(0))},$b=n=>btoa(Vb(n)),qb=n=>Uint8Array.from(atob(n),t=>t.charCodeAt(0)),Kb=()=>D2(crypto.getRandomValues(new Uint8Array(16)));function zb(n){let t=new URLSearchParams({v:n.v,r:n.r,c:n.c,k:n.k,o:n.o,e:String(n.e)});return`https://${U2}/pair?${t}`}var Ld=(n,t,e,i)=>{let r=/^(localhost|127\.0\.0\.1)(:\d+)?$/.test(n),s=new URLSearchParams({role:e});return i&&s.set("e",String(i)),`${r?"ws":"wss"}://${n}/v1/c/${t}?${s}`};async function Ud(n,t,e){let i=n.deriveSharedSecret(Ht.fromString(t)),r=new Uint8Array(i.encode(!0)),s=await crypto.subtle.importKey("raw",r,"HKDF",!1,["deriveBits"]),o=new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:H2(e),info:au.encode(L2)},s,256)),c=await crypto.subtle.importKey("raw",o,"AES-GCM",!1,["encrypt","decrypt"]),u=new Uint8Array(await crypto.subtle.digest("SHA-256",o)),f=String((u[0]<<8|u[1])%1e4).padStart(4,"0");return{key:c,code:f}}var Qo=class{constructor(t,e){m(this,"key",t);m(this,"me",e);m(this,"sent",0);m(this,"lastSeen",0)}async seal(t){let e=++this.sent,i=crypto.getRandomValues(new Uint8Array(12)),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:i,additionalData:au.encode(`${this.me}|${e}`)},this.key,au.encode(JSON.stringify(t))));return{s:e,n:$b(i),d:$b(r)}}async open(t){if(!Number.isInteger(t.s)||t.s<=this.lastSeen)return null;let e=this.me==="site"?"wallet":"site";try{let i=await crypto.subtle.decrypt({name:"AES-GCM",iv:qb(t.n),additionalData:au.encode(`${e}|${t.s}`)},this.key,qb(t.d));return this.lastSeen=t.s,JSON.parse(M2.decode(i))}catch{return null}}get counters(){return{sent:this.sent,lastSeen:this.lastSeen}}restore(t){this.sent=t.sent,this.lastSeen=t.lastSeen}},Md=n=>!!n&&typeof n=="object"&&"d"in n&&"n"in n&&"s"in n;var Dd="bwalletx.connect.pairing.v1",Xb=1;function fu(){let n=new Map;return{getItem:t=>n.get(t)??null,setItem:(t,e)=>{n.set(t,e)},removeItem:t=>{n.delete(t)}}}function Hd(){try{if(typeof localStorage<"u")return localStorage}catch{}return fu()}function jb(){return n=>{if(typeof WebSocket>"u")throw new Error("No WebSocket here. Pass options.socket.");return new WebSocket(n)}}function $2(n){if(!n)return null;try{let t=JSON.parse(n),e=i=>Number.isInteger(i)&&i>=0;return t.v!==1||typeof t.c!="string"||!/^[A-Za-z0-9_-]{22}$/.test(t.c)||typeof t.r!="string"||!/^[a-z0-9.-]+(:\d+)?$/i.test(t.r)||typeof t.s!="string"||!/^[0-9a-f]{64}$/i.test(t.s)||typeof t.k!="string"||!/^0[23][0-9a-f]{64}$/i.test(t.k)||!e(t.sent)||!e(t.lastSeen)||!e(t.pairedAt)?null:t}catch{return null}}var uu=class{constructor(t,e,i,r,s,o){m(this,"p",t);m(this,"sealer",e);m(this,"storage",i);m(this,"key",r);m(this,"socket",s);m(this,"timeoutMs",o);m(this,"ws",null);m(this,"opening",null);m(this,"waiting",new Map);m(this,"forgotten",!1)}adopt(t){this.ws=t,this.wire(t)}wire(t){t.onmessage=Jo(e=>this.onFrame(String(e.data))),t.onerror=null,t.onclose=()=>{this.ws===t&&(this.ws=null),this.failAll(new Error("The connection to bWalletX closed"))}}persist(){this.forgotten||(this.p={...this.p,...this.sealer.counters},Promise.resolve(this.storage.setItem(this.key,JSON.stringify(this.p))).catch(()=>{}))}failAll(t){for(let e of this.waiting.values())clearTimeout(e.timer),e.reject(t);this.waiting.clear()}async ensure(){if(this.forgotten)throw new Error("This pairing was removed. Pair again.");this.ws&&this.ws.readyState===Xb||(this.opening??(this.opening=this.reopen().finally(()=>this.opening=null)),await this.opening)}reopen(){let t=this.socket(Ld(this.p.r,this.p.c,"site",Math.floor(Date.now()/1e3)+cu-10));return new Promise((e,i)=>{t.onopen=()=>{this.ws=t,this.wire(t),e()},t.onerror=()=>i(new Error("Could not reach the bWalletX pairing service")),t.onclose=()=>i(new Error("Could not reach the bWalletX pairing service"))})}async onFrame(t){let e;try{e=JSON.parse(t)}catch{return}if(e.t==="relay"&&e.error)return this.failAll(new Error(`bWalletX pairing service: ${e.error}`));if(!Md(e))return;let r=await this.sealer.open(e);if(r)if(this.persist(),r.t==="res"){let s=this.waiting.get(r.id);if(!s)return;clearTimeout(s.timer),this.waiting.delete(r.id),r.error?s.reject(Object.assign(new Error(r.error.message),{code:r.error.code})):s.resolve(r.result)}else r.t==="close"&&(this.drop(),this.failAll(new Error("bWalletX disconnected this site. Pair again.")))}async call(t,e){await this.ensure();let i=this.ws,r=`${t}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,s=new Promise((o,c)=>{let u=setTimeout(()=>{this.waiting.delete(r)&&c(new Error("No answer from bWalletX. Open it, unlocked, and approve."))},this.timeoutMs);this.waiting.set(r,{resolve:o,reject:c,timer:u})});return i.send(JSON.stringify(await this.sealer.seal({t:"req",id:r,action:t,params:e}))),this.persist(),s}close(){let t=this.ws;this.ws=null,t?.close()}drop(){this.forgotten=!0,Promise.resolve(this.storage.removeItem(this.key)).catch(()=>{}),this.close()}async forget(){if(!this.forgotten){try{this.ws&&this.ws.readyState===Xb&&this.ws.send(JSON.stringify(await this.sealer.seal({t:"close",reason:"site unpaired"})))}catch{}this.drop()}}wallet(){return new Proxy({},{get:(t,e)=>{if(e==="close")return()=>this.close();if(e==="forget")return()=>this.forget();if(!(typeof e!="string"||e==="then"||e==="toJSON"))return i=>this.call(e,i??{})}})}};function Ns(n){let t=n.storage===void 0?Hd():n.storage??fu(),e=n.storageKey??Dd,i=n.socket??jb(),r=n.relay??Wb,s=n.origin??(typeof location<"u"?location.origin:"");if(!s)return Promise.reject(new Error("pairBwalletX needs options.origin outside a browser"));let o=cr.fromRandom(),c=Kb(),u=Math.floor(Date.now()/1e3)+cu;return new Promise((f,d)=>{if(n.signal?.aborted)return d(new Error("cancelled"));let l;try{l=i(Ld(r,c,"site",u))}catch(C){return d(C)}let p=null,b="",g=!1,w=C=>{g||(g=!0,clearTimeout(S),l.close(),d(C))},S=setTimeout(()=>w(new Error("The pairing code expired. Show a new one.")),cu*1e3);n.signal?.addEventListener("abort",()=>w(new Error("cancelled"))),l.onerror=()=>w(new Error("Could not reach the bWalletX pairing service")),l.onclose=()=>w(new Error("The connection to bWalletX closed before pairing finished")),l.onmessage=Jo(async C=>{if(g)return;let E;try{E=JSON.parse(String(C.data))}catch{return}if(E.t==="hello"&&!p){b=E.k;let k=await Ud(o,b,c);p=new Qo(k.key,"site"),n.onCode(k.code);return}if(!p||!Md(E))return;let A=await p.open(E);if(A)if(A.t==="ready"){g=!0,clearTimeout(S);let k={v:1,c,r,s:o.toHex(),k:b,...p.counters,pairedAt:Date.now()};await Promise.resolve(t.setItem(e,JSON.stringify(k))).catch(()=>{});let B=new uu(k,p,t,e,i,n.callTimeoutMs??12e4);B.adopt(l),f(B.wallet())}else A.t==="close"&&w(new Error("Pairing was declined in bWalletX"))}),n.onLink(zb({v:Fb,r,c,k:o.toPublicKey().toString(),o:s,e:u}))})}async function Bs(n={}){let t=n.storage===void 0?Hd():n.storage??fu(),e=n.storageKey??Dd,i=$2(await Promise.resolve(t.getItem(e)).catch(()=>null));if(!i)return null;let{key:r}=await Ud(cr.fromHex(i.s),i.k,i.c),s=new Qo(r,"site");return s.restore({sent:i.sent,lastSeen:i.lastSeen}),new uu(i,s,t,e,n.socket??jb(),n.callTimeoutMs??12e4).wallet()}async function Gb(n={}){let t=n.storage===void 0?Hd():n.storage??fu();await Promise.resolve(t.removeItem(n.storageKey??Dd)).catch(()=>{})}var $d=[2,"bwallet sign in"];async function ta(n={}){if(n.wallet)return{wallet:n.wallet,method:"wallet"};let t=await Wi(n.discoverMs);if(t)return{wallet:t.wallet,method:t.method};if(n.reusePairing!==!1){let e=await Bs(n.pairing??{});if(e)return{wallet:e,method:"pairing"}}if(!n.pairing)throw Object.assign(new Error("bWalletX was not found in this browser"),{code:"NOT_FOUND"});return{wallet:await Ns(n.pairing),method:"pairing"}}async function du(n){let{wallet:t,method:e}=await ta(n);e!=="pairing"&&await t.waitForAuthentication({}).catch(()=>{});let{publicKey:i}=await t.getPublicKey({identityKey:!0}),r=await n.challenge(i),{signature:s}=await t.createSignature({protocolID:r.protocolID??$d,keyID:r.keyID,counterparty:"anyone",data:Array.from(new TextEncoder().encode(r.message))});return{identityKey:i,signature:Array.from(s),nonce:r.nonce,method:e,wallet:t}}var Yb=1,lu=[2,"bwalletx access"];var Zb=50,Jb={not_installed:424,user_rejected:403,wrong_account:409,insufficient_tokens:403,identity_level_too_low:403,kyc_required:403,indexer_unavailable:503,expired:401,replay:401,invalid_signature:401,bad_request:400},kt=class extends Error{constructor(e,i,r={}){super(i??e);m(this,"code");m(this,"have");m(this,"need");this.name="AccessError",this.code=e,this.have=r.have,this.need=r.need}toJSON(){let e={error:this.code,message:this.message};return this.have!==void 0&&(e.have=this.have),this.need!==void 0&&(e.need=this.need),e}},qd={401:{name:"Identity",color:"#22c55e",video:"assets/protocol/401.mp4",poster:"assets/protocol/401.jpg"},402:{name:"Payment",color:"#3b82f6",video:"assets/protocol/402.mp4",poster:"assets/protocol/402.jpg"},403:{name:"Access",color:"#ef4444",video:"assets/protocol/403.mp4",poster:"assets/protocol/403.jpg"}};function Qb(n,t,e="latest"){return`https://unpkg.com/@bwalletx/connect@${e}/${qd[n][t]}`}function ea(n){if(n===null)return"null";if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="number"){if(!Number.isFinite(n))throw new Error("canonicalJson: non-finite number");return JSON.stringify(n)}if(Array.isArray(n))return`[${n.map(t=>ea(t)).join(",")}]`;if(typeof n=="object"){let t=n;return`{${Object.keys(t).filter(i=>t[i]!==void 0).sort().map(i=>`${JSON.stringify(i)}:${ea(t[i])}`).join(",")}}`}throw new Error(`canonicalJson: unsupported ${typeof n}`)}function Fd(n){return Array.from(new TextEncoder().encode(n))}var q2=/^bsv21:[0-9a-f]{64}_\d{1,6}$/,F2=/^[1-9]\d{0,38}$/;function W2(n){if(!n||typeof n!="object")throw new kt("bad_request","require must be an object");let t=n,e={};if(t.token!==void 0){let i=t.token;if(!i||typeof i!="object"||typeof i.id!="string")throw new kt("bad_request","require.token.id is required");let r=i.id.trim().toLowerCase();if(!q2.test(r))throw new kt("bad_request","require.token.id must be 'bsv21:<txid>_<vout>'");let s=i.min!==void 0,o=i.minBps!==void 0;if(s===o)throw new kt("bad_request","require.token needs exactly one of min or minBps");if(e.token={id:r},s){if(typeof i.min!="string"||!F2.test(i.min))throw new kt("bad_request","require.token.min must be a positive integer string (raw units)");e.token.min=i.min}else{if(!Number.isInteger(i.minBps)||i.minBps<1||i.minBps>1e4)throw new kt("bad_request","require.token.minBps must be an integer 1..10000");e.token.minBps=i.minBps}}if(t.identityLevel!==void 0){if(!Number.isInteger(t.identityLevel)||t.identityLevel<1||t.identityLevel>10)throw new kt("bad_request","require.identityLevel must be an integer 1..10");e.identityLevel=t.identityLevel}if(t.kyc!==void 0){if(typeof t.kyc!="boolean")throw new kt("bad_request","require.kyc must be a boolean");t.kyc&&(e.kyc=!0)}if(!e.token&&!e.identityLevel&&!e.kyc)throw new kt("bad_request","require is empty");return e}function tm(n){if(typeof n!="string"||n.length>4096)throw new kt("bad_request","challenge must be a string");let t;try{t=JSON.parse(n)}catch{throw new kt("bad_request","challenge is not JSON")}if(!t||typeof t!="object"||t.v!==1)throw new kt("bad_request","unsupported challenge version");if(t.kind!=="401"&&t.kind!=="402"&&t.kind!=="403")throw new kt("bad_request","bad kind");if(typeof t.origin!="string"||typeof t.nonce!="string"||!/^[A-Za-z0-9_-]{16,64}$/.test(t.nonce))throw new kt("bad_request","bad origin or nonce");if(!Number.isInteger(t.iat)||!Number.isInteger(t.exp)||t.exp<=t.iat)throw new kt("bad_request","bad iat/exp");if(t.sub!==void 0&&(typeof t.sub!="string"||!/^0[23][0-9a-f]{64}$/.test(t.sub)))throw new kt("bad_request","bad sub");if(t.require=W2(t.require),ea(t)!==n)throw new kt("bad_request","challenge is not canonical");return t}function em(n,t={}){switch(n){case"not_installed":return"No bWalletX (or other BRC-100 wallet) was found.";case"user_rejected":return"The request was declined in the wallet.";case"wrong_account":return"The wallet is signed in to a different account than this site expects.";case"insufficient_tokens":return`Not enough tokens: holding ${t.have??0}, need ${t.need??"?"}.`;case"identity_level_too_low":return`Identity level ${t.have??0} is below the required level ${t.need??"?"}.`;case"kyc_required":return"A verified identity (KYC) is required.";case"indexer_unavailable":return"Holdings could not be checked right now. Try again shortly.";case"expired":return"The request expired. Try again.";case"replay":return"That request was already used. Try again.";case"invalid_signature":return"The wallet signature did not verify.";case"bad_request":return"The request was malformed."}}var V2=[0,"onesat"],K2=[0,"p 1sat"];function hu(n){if(n instanceof kt)return n;let t=n,e=String(t?.message??n??"");return t?.code==="NOT_FOUND"?new kt("not_installed",e):/reject|denied|declin|cancel|user/i.test(e)||t?.code==="ERR_USER_REJECTED"||t?.status===4001?new kt("user_rejected",e):new kt("bad_request",e||"access failed")}function Wd(n){let t=n;if(t&&typeof t.error=="string")throw new kt(t.error,t.message,{have:t.have,need:t.need})}function z2(n){let t=/^76a914([0-9a-f]{40})88ac$/i.exec(n.slice(-50));return t?t[1].toLowerCase():null}async function Vd(n,t,e,i="bsv21"){let r=e.replace(/^bsv21:/,""),s=await n.listOutputs({basket:i,include:"locking scripts",includeCustomInstructions:!0,limit:1e4}),o=new Map,c=Fd(t);for(let u of s.outputs){if(o.size>=Zb)break;let f={};try{f=JSON.parse(u.customInstructions??"{}")}catch{continue}if(f.id!==r||!f.keyID)continue;let d=u.lockingScript?z2(u.lockingScript):null,l=f.counterparty??"self";for(let p of f.protocolID?[f.protocolID]:[V2,K2]){let{publicKey:b}=await n.getPublicKey({protocolID:p,keyID:f.keyID,counterparty:l}),g=yi.toHex(Aa.hash160(Ht.fromString(b).encode(!0)));if(d&&g!==d)continue;let w=o.get(b);if(w){w.outpoints.push(u.outpoint.replace(".","_"));break}let{signature:S}=await n.createSignature({protocolID:p,keyID:f.keyID,counterparty:l,data:c});o.set(b,{pubkey:b,signature:Array.from(S),outpoints:[u.outpoint.replace(".","_")]});break}}return[...o.values()]}async function pu(n){let t;try{({wallet:t}=await ta({wallet:n.wallet,pairing:n.pairing,discoverMs:n.discoverMs}))}catch(e){throw e?.code==="NOT_FOUND"?new kt("not_installed"):hu(e)}try{let{publicKey:e}=await t.getPublicKey({identityKey:!0}),{challenge:i}=await n.challenge(e),r=tm(i);if(r.sub&&r.sub!==e.toLowerCase())throw new kt("wrong_account");if(Date.now()/1e3>=r.exp)throw new kt("expired");let{signature:s}=await t.createSignature({protocolID:lu,keyID:r.nonce,counterparty:"anyone",data:Fd(i)}),o={v:1,challenge:i,identityKey:e,signature:Array.from(s)};r.require.token&&(o.holdings=await Vd(t,i,r.require.token.id,n.tokenBasket));let c;return n.verify&&(c=await n.verify(o),Wd(c)),{response:o,verified:c,wallet:t}}catch(e){throw hu(e)}}var Xd="bwalletx-signin",jd="https://bwalletx.com/get",Gd="https://web.bwalletx.com",nm={signin:"Sign in with",continue:"Continue with",connect:"Connect"};function Yd(n="signin",t="bWalletX"){return`${nm[n]??nm.signin} ${t}`}var X2=0;function Zd(n=20){let t=++X2;return`<svg viewBox="23 8 74 100" width="${Math.round(n*.74)}" height="${n}" aria-hidden="true" focusable="false"><defs><linearGradient id="bwxg${t}" gradientUnits="userSpaceOnUse" x1="0" y1="12" x2="0" y2="105"><stop offset="0" stop-color="#FFE58A"/><stop offset=".55" stop-color="#FFD24D"/><stop offset="1" stop-color="#C98F00"/></linearGradient><mask id="bwxh${t}"><rect width="140" height="140" fill="#fff"/><circle cx="60" cy="72" r="15" fill="#000"/></mask></defs><g fill="url(#bwxg${t})" mask="url(#bwxh${t})"><polygon points="45,12 45,76 27,76 27,30"/><circle cx="60" cy="72" r="33"/></g></svg>`}var Jd=`
|
|
24
|
+
`}return t}addComputedLeaves(){for(let t of this.bumps)for(let e=1;e<t.path.length;e++)a(this,P,_0).call(this,t,e)}};Bn=new WeakMap,_n=new WeakMap,Cn=new WeakMap,Jn=new WeakMap,je=new WeakMap,Qn=new WeakMap,wr=new WeakMap,ns=new WeakMap,yr=new WeakMap,is=new WeakMap,rs=new WeakMap,ss=new WeakMap,xr=new WeakMap,Sr=new WeakMap,Ln=new WeakMap,De=new WeakMap,Un=new WeakMap,P=new WeakSet,Qr=function(){N(this,je,void 0),N(this,Qn,void 0),y(this,wr).clear(),N(this,ns,void 0),N(this,yr,void 0),N(this,is,void 0),N(this,rs,void 0),N(this,ss,void 0),N(this,xr,void 0)},Ga=function(){N(this,rs,this.version),N(this,ss,a(this,P,_f).call(this)),N(this,xr,Array.from(this.bumps)),a(this,P,Ya).call(this)},_f=function(){return this.txs.map(t=>({ref:t,bumpIndex:t._bumpIndex,rawTx:t._rawTx,tx:t._rawTx==null?t._tx:void 0,txid:t._rawTx==null&&t._tx==null?t._txid:void 0}))},Cf=function(t){if(t?.length!==this.txs.length)return!1;for(let e=0;e<this.txs.length;e++){let i=this.txs[e],r=t[e];if(r.ref!==i||r.bumpIndex!==i._bumpIndex||r.rawTx!==i._rawTx||r.tx!==(i._rawTx==null?i._tx:void 0)||r.txid!==(i._rawTx==null&&i._tx==null?i._txid:void 0))return!1}return!0},Ya=function(){N(this,Sr,this.bumps.map(t=>({ref:t,blockHeight:t.blockHeight,levels:t.path.map(e=>({ref:e,leaves:e.map(i=>({ref:i,offset:i.offset,hash:i.hash,txid:i.txid,duplicate:i.duplicate}))}))})))},e0=function(t,e){return e.ref===t&&e.offset===t.offset&&e.hash===t.hash&&e.txid===t.txid&&e.duplicate===t.duplicate},n0=function(t,e){return e.ref===t&&e.leaves.length===t.length&&t.every((i,r)=>a(this,P,e0).call(this,i,e.leaves[r]))},i0=function(t,e){return e.ref===t&&e.blockHeight===t.blockHeight&&e.levels.length===t.path.length&&t.path.every((i,r)=>a(this,P,n0).call(this,i,e.levels[r]))},r0=function(){return y(this,Sr)?.length!==this.bumps.length?!1:this.bumps.every((t,e)=>a(this,P,i0).call(this,t,y(this,Sr)[e]))},Rn=function(){if(y(this,Sr)==null){a(this,P,Ya).call(this);return}a(this,P,r0).call(this)||(a(this,P,Qr).call(this),N(this,De,void 0),N(this,Un,void 0),N(this,Ln,!0),a(this,P,Hf).call(this),a(this,P,Ya).call(this))},s0=function(){if(y(this,je)==null||y(this,rs)!==this.version||!a(this,P,Cf).call(this,y(this,ss))||y(this,xr)?.length!==this.bumps.length)return!1;for(let t=0;t<this.bumps.length;t++)if(y(this,xr)[t]!==this.bumps[t])return!1;return!0},Nn=function(t=!0){a(this,P,Qr).call(this),N(this,De,void 0),N(this,Un,void 0),t&&N(this,Ln,!0)},o0=function(){for(let t of this.txs)t.txid},a0=function(){y(this,Ln)&&this.sortTxs()},Po=function(){if(this.synchronizeNestedTransactionMutations(),a(this,P,Rn).call(this),a(this,P,s0).call(this)&&y(this,je)!=null)return y(this,je);a(this,P,Qr).call(this),a(this,P,o0).call(this),a(this,P,a0).call(this);let t=new ht;return this.toWriter(t),N(this,je,t.toUint8Array()),a(this,P,Ga).call(this),y(this,je)},c0=function(t){let e=a(this,P,No).call(this),i=e.get(t);if(i==null)throw new Error(`${t} does not exist in this Beef`);let r=a(this,P,Uf).call(this,i,e),s=a(this,P,u0).call(this,r);return s.sortTxs(),s},Lf=function(t){var u;this.synchronizeNestedTransactionMutations(),a(this,P,Rn).call(this),y(this,is)===this.version&&a(this,P,Cf).call(this,y(this,ns))&&y(this,yr)?.length===this.bumps.length&&this.bumps.every((f,d)=>y(this,yr)?.[d]===f)||y(this,wr).clear();let i=y(this,wr).get(t);if(i!=null)return i;let r=a(u=a(this,P,c0).call(this,t),P,Po).call(u),s=et(t,"hex"),o=new Uint8Array(4+s.length+r.length);new DataView(o.buffer).setUint32(0,16843009,!0);for(let f=0;f<s.length;f++)o[4+f]=s[s.length-1-f];return o.set(r,4+s.length),y(this,wr).set(t,o),N(this,ns,a(this,P,_f).call(this)),N(this,yr,Array.from(this.bumps)),N(this,is,this.version),o},Uf=function(t,e){let i=new Set,r=[t];for(;r.length>0;){let s=r.pop();if(!(s==null||i.has(s))&&(i.add(s),!(a(this,P,Mf).call(this,s)||s.isTxidOnly)))for(let o of s.inputTxids){let c=e.get(o);c!=null&&r.push(c)}}return i},Mf=function(t){let e=t.bumpIndex;return e==null||!Number.isSafeInteger(e)||e<0||e>=this.bumps.length?!1:this.bumps[e]?.path[0]?.some(i=>i.hash===t.txid)??!1},u0=function(t){let e=new wn(this.version),i=new Map;for(let r of this.txs)!t.has(r)||!a(this,P,Mf).call(this,r)||r.bumpIndex==null||i.has(r.bumpIndex)||(i.set(r.bumpIndex,e.bumps.length),e.bumps.push(this.bumps[r.bumpIndex]));for(let r of this.txs){if(!t.has(r))continue;let s=r.bumpIndex==null?void 0:i.get(r.bumpIndex),o;r._rawTx!=null?o=new Xe(r._rawTx,s,Array.from(r.inputTxids)):r._tx!=null?o=Xe.fromTx(r._tx,s):o=Xe.fromTxid(r.txid,s),e.txs.push(o)}return e},Ro=function(t){return a(this,P,No).call(this).get(t)},No=function(){return(y(this,Bn)==null||y(this,_n)==null)&&a(this,P,br).call(this),y(this,Bn)},Za=function(){return(y(this,_n)==null||y(this,Bn)==null)&&a(this,P,br).call(this),y(this,_n)},br=function(){N(this,Bn,new Map),N(this,_n,new Map);for(let t=0;t<this.txs.length;t++){let e=this.txs[t];y(this,Bn).set(e.txid,e),y(this,_n).set(e.txid,t)}},ts=function(t,e=this.txs.length-1){y(this,Bn)?.set(t.txid,t),y(this,_n)?.set(t.txid,e)},Df=function(t){let e=a(this,P,Za).call(this).get(t.txid);e===void 0?(this.txs.push(t),a(this,P,ts).call(this,t)):(this.txs[e]=t,a(this,P,ts).call(this,t,e))},Ja=function(){if(y(this,Jn)==null){N(this,Jn,new Map);for(let t=0;t<this.bumps.length;t++)for(let e of this.bumps[t].path[0])typeof e.hash=="string"&&y(this,Jn).set(e.hash,t)}return y(this,Jn)},f0=function(){if(y(this,Cn)==null){N(this,Cn,new Map);for(let t=0;t<this.bumps.length;t++){let e=this.bumps[t],i=y(this,Cn).get(e.blockHeight)??[];i.push(t),y(this,Cn).set(e.blockHeight,i)}}return y(this,Cn)},Hf=function(){N(this,Cn,void 0),N(this,Jn,void 0)},d0=function(t){let e=new Set,i=[t];for(;i.length>0;){let r=i.pop();if(r==null)continue;let s=r.id("hex");if(e.has(s))continue;e.add(s);let o=this.findBump(s);if(o!=null){r.merklePath=o;continue}for(let c of r.inputs)a(this,P,l0).call(this,c),c.sourceTransaction!=null&&i.push(c.sourceTransaction)}},l0=function(t){if(t.sourceTransaction==null){let e=a(this,P,Ro).call(this,sr(t.sourceTXID,"sourceTXID must be valid"));e!=null&&(t.sourceTransaction=e.tx)}},h0=function(t,e=!1){let i=t[0];if(t.length===1&&!e)return i;let r=i.path.map(o=>new Map(o.map(c=>[c.offset,c])));for(let o=1;o<t.length;o++)py(r,t[o],i.path.length,e);let s=r.map(o=>[...o.values()]);if(e){let o=new Ei(i.blockHeight,s);return o.trim(),o}return i.path=s,i.trim(),i},Bo=function(t){let e=a(this,P,p0).call(this,t),i=this.bumps[e],r=a(this,P,No).call(this);for(let s of i.path[0]){if(typeof s.hash!="string")continue;let o=r.get(s.hash);o!=null&&o.bumpIndex==null&&a(this,P,g0).call(this,o,i,e)}return e},p0=function(t){let e=a(this,P,f0).call(this),i=a(this,P,Ja).call(this),r=e.get(t.blockHeight)??[];if(r.length>0){let o=t.computeRoot();for(let c of r)if(this.bumps[c].computeRoot()===o)return this.bumps[c].combine(t),t0(this.bumps[c],c,i),c}this.bumps.push(t);let s=this.bumps.length-1;return r.push(s),e.set(t.blockHeight,r),t0(t,s,i),s},g0=function(t,e,i){let r=t.txid;for(let s of e.path[0])if(s.hash===r){t.bumpIndex=i,s.txid=!0;break}},Qa=function(t,e){let i=new Xe(t,e);return a(this,P,Df).call(this,i),a(this,P,es).call(this,i),i},m0=function(t){let e=t.merklePath==null?void 0:a(this,P,Bo).call(this,t.merklePath),i=new Xe(t,e);return a(this,P,Df).call(this,i),a(this,P,es).call(this,i),i},b0=function(t,e){for(let i=t.inputs.length-1;i>=0;i--){let r=t.inputs[i].sourceTransaction;r!=null&&e.push(r)}},$f=function(t){t.materializeSourceTXIDs();let e=t.id("hex"),i=new Set,r=[t],s;for(;r.length>0;){let o=r.pop();if(o==null)continue;let c=o.id("hex");if(i.has(c))continue;i.add(c);let u=a(this,P,m0).call(this,o);c===e&&(s=u),u.bumpIndex===void 0&&a(this,P,b0).call(this,o,r)}if(s==null)throw new Error("Failed to merge root transaction");return s},w0=function(t){let e=a(this,P,Ro).call(this,t.txid);if(t.isTxidOnly&&e==null?(e=Xe.fromTxid(t.txid),this.txs.push(e),a(this,P,ts).call(this,e),a(this,P,es).call(this,e)):t._tx!=null&&(e==null||e.isTxidOnly)?e=a(this,P,$f).call(this,t._tx):t._rawTx!=null&&(e==null||e.isTxidOnly)&&(e=a(this,P,Qa).call(this,t._rawTx)),e==null)throw new Error(`Failed to merge BeefTx for txid: ${t.txid}`);return e},y0=function(){let t=new Set;for(let e of this.txs){if(t.has(e.txid))return!0;t.add(e.txid)}return!1},x0=function(t,e){for(let i of this.txs)if(i.isTxidOnly){if(e!==!0)return!1;t[i.txid]=!0}return!0},S0=function(t,e){for(let i of this.bumps)for(let r of i.path[0])if(!(r.txid!==!0||typeof r.hash!="string"||r.hash.length===0)&&(t[r.hash]=!0,!a(this,P,A0).call(this,i,r.hash,e)))return!1;return!0},I0=function(){for(let t of this.txs){if(t.bumpIndex===void 0)continue;if(!Number.isSafeInteger(t.bumpIndex)||t.bumpIndex<0||t.bumpIndex>=this.bumps.length||this.bumps[t.bumpIndex]?.path[0]?.find(i=>i.hash===t.txid)==null)return!1}return!0},v0=function(t){for(let e of this.txs){for(let i of e.inputTxids)if(!t[i])return!1;t[e.txid]=!0}return!0},A0=function(t,e,i){let r=t.computeRoot(e);return(i.roots[t.blockHeight]===void 0||i.roots[t.blockHeight]==="")&&(i.roots[t.blockHeight]=r),i.roots[t.blockHeight]===r},es=function(t){if(t.bumpIndex!==void 0)return!0;let e=t.txid,i=a(this,P,Ja).call(this).get(e);if(i===void 0)return!1;t.bumpIndex=i;let r=this.bumps[i].path[0].find(s=>s.hash===e);return r!=null&&(r.txid=!0),!0},qf=function(){N(this,Un,this.txs.map(t=>({ref:t,txid:t.txid,bumpIndex:t.bumpIndex,isTxidOnly:t.isTxidOnly,inputTxids:[...t.inputTxids]})))},E0=function(){if(y(this,Un)?.length!==this.txs.length)return!1;for(let t=0;t<this.txs.length;t++){let e=this.txs[t],i=y(this,Un)[t];if(i.ref!==e||i.txid!==e.txid||i.bumpIndex!==e.bumpIndex||i.isTxidOnly!==e.isTxidOnly||i.inputTxids.length!==e.inputTxids.length)return!1;for(let r=0;r<e.inputTxids.length;r++)if(i.inputTxids[r]!==e.inputTxids[r])return!1}return!0},tc=function(t){return{missingInputs:[...t.missingInputs],notValid:[...t.notValid],valid:[...t.valid],withMissingInputs:[...t.withMissingInputs],txidOnly:[...t.txidOnly]}},k0=function(t,e){let i={},r=[],s=[];for(let o of t){let c=!1;for(let u of o.inputTxids)e[u]===void 0&&(i[u]=!0,c=!0);c?r.push(o):s.push(o)}return{txsMissingInputs:r,missingInputs:i,remaining:s}},T0=function(t,e,i){let{indegree:r,dependents:s,originalIndex:o,round:c}=a(this,P,O0).call(this,t,e),u=a(this,P,P0).call(this,t,r,s,o,c);return a(this,P,R0).call(this,t,u,c,e,i),t.filter(f=>!u.has(f.txid))},O0=function(t,e){let i=new Set(t.map(u=>u.txid)),r=new Map,s=new Map,o=new Map(t.map((u,f)=>[u.txid,f])),c=new Map;for(let u of t){let f=0;for(let d of u.inputTxids)if(!e[d]&&(f++,i.has(d))){let l=s.get(d)??[];l.push(u),s.set(d,l)}r.set(u.txid,f),c.set(u.txid,0)}return{indegree:r,dependents:s,originalIndex:o,round:c}},P0=function(t,e,i,r,s){let o=t.filter(u=>e.get(u.txid)===0),c=new Set;for(let u of o)if(!c.has(u.txid)){c.add(u.txid);for(let f of i.get(u.txid)??[]){let d=(s.get(u.txid)??0)+((r.get(u.txid)??0)>(r.get(f.txid)??0)?1:0);s.set(f.txid,Math.max(s.get(f.txid)??0,d));let l=(e.get(f.txid)??0)-1;e.set(f.txid,l),l===0&&o.push(f)}}return c},R0=function(t,e,i,r,s){let o=[];for(let c of t){if(!e.has(c.txid))continue;let u=i.get(c.txid)??0,f=o[u]??[];f.push(c),o[u]=f}for(let c of o)for(let u of c??[])r[u.txid]=!0,s.push(u)},N0=function(t){let e=this.txs.length;this.txs=this.txs.filter(r=>!(r.isTxidOnly&&t.has(r.txid)));let i=this.txs.length!==e;return i&&a(this,P,br).call(this),i},B0=function(){let t=new Set;for(let r of this.txs)r.bumpIndex!==void 0&&t.add(r.bumpIndex);if(t.size>=this.bumps.length)return!1;let e=new Map,i=0;for(let r=0;r<this.bumps.length;r++)t.has(r)&&(e.set(r,i),i++);this.bumps=this.bumps.filter((r,s)=>t.has(s));for(let r of this.txs){if(r.bumpIndex===void 0)continue;let s=e.get(r.bumpIndex);if(s===void 0)throw new Error(`Internal error: bumpIndex ${r.bumpIndex} not found in indexMap`);r.bumpIndex=s}return a(this,P,Hf).call(this),!0},_0=function(t,e){let i=r=>nt(zt(at(r,"hex").reverse()).reverse());for(let r of t.path[e-1]){if(typeof r.hash!="string"||(r.offset&1)!==0)continue;let s=t.path[e-1].find(c=>c.offset===r.offset+1);if(s===void 0||typeof s.hash!="string")continue;let o=r.offset>>1;t.path[e].every(c=>c.offset!==o)&&t.path[e].push({offset:o,hash:i(s.hash+r.hash)})}};var Ir=wn,C0=Ir;var cs=256*1024*1024,V0=21e14,by=64,Ff=1e6,us=Array.isArray,rn=Array,Zf=Number,Jf=String,wy=Number.isFinite,yy=Number.isInteger,xy=Number.isSafeInteger,K0=Object.is,Uo=Object.create,Sy=Object.defineProperty,$t=Object.getOwnPropertyDescriptor,L0=Object.getOwnPropertyDescriptors,Qf=Object.getPrototypeOf,Lo=Object.keys,Zt=Reflect.apply,Do=Reflect.ownKeys,Iy=RegExp.prototype.exec,vy=RegExp.prototype.test,Ay=String.prototype.toLowerCase,z0=Uint8Array,td=Uint8Array.prototype,oc=Qf(td),U0=$t(oc,"buffer")?.get,ic=$t(oc,"length")?.get,M0=$t(oc,Symbol.toStringTag)?.get,Ey=td.set,D0=typeof SharedArrayBuffer>"u"?void 0:$t(SharedArrayBuffer.prototype,"byteLength")?.get,ky=WeakMap.prototype.get,Ty=WeakMap.prototype.set,Vf=WeakSet.prototype.add,Oy=WeakSet.prototype.delete,X0=WeakSet.prototype.has,Kf=new WeakSet,Py=me.prototype.toHex,zf,Xf,jf,j0=/^(?:0|[1-9]\d*)$/,Ry=/^([0-9a-f]{64})\.(0|[1-9]\d*)$/i,Ny=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,By=/^(?:[0-9a-f]{2})*$/i,_y=/^[0-9a-f]{64}$/i;function Cy(){let n=[Array.prototype,Map.prototype,Set.prototype,WeakMap.prototype,WeakSet.prototype,Object,Object.prototype,Number,RegExp.prototype,String.prototype,td,oc],t=new rn(n.length);for(let e=0;e<n.length;e++){let i=n[e],r=Do(i),s=new rn(r.length);for(let o=0;o<r.length;o++)s[o]=$t(i,r[o]);t[e]={owner:i,keys:r,descriptors:s}}return t}function Co(n){for(let t=0;t<n.length;t++){let e=n[t];if(Do(e.owner).length!==e.keys.length)throw new Error("Wallet callback modified shared JavaScript intrinsics");for(let i=0;i<e.keys.length;i++){let r=e.descriptors[i],s=$t(e.owner,e.keys[i]);if(s==null||s.configurable!==r.configurable||s.enumerable!==r.enumerable||s.writable!==r.writable||!K0(s.value,r.value)||s.get!==r.get||s.set!==r.set)throw new Error(`Wallet callback modified shared JavaScript intrinsics (${t}:${Jf(e.keys[i])})`)}}}function rc(n,t){return $t(n,t)!==void 0}function Ti(n){return xy(n)}function Mo(n,t){return Zt(vy,n,[t])}function Ar(n){return Zt(Ay,n,[])}function fs(n){return Zt(Py,n,[])}function Ly(){zf??(zf=Me.fromAtomicBEEF),Xf??(Xf=Me.prototype.id),jf??(jf=Me.prototype.toAtomicBEEF)}function Wf(n){if(zf==null)throw new Error("Transaction intrinsics are unavailable");return Zt(zf,Me,[n])}function Uy(n){if(jf==null)throw new Error("Transaction intrinsics are unavailable");return Zt(jf,n,[!0])}function G0(n){if(Xf==null)throw new Error("Transaction intrinsics are unavailable");return Zt(Xf,n,["hex"])}function H0(n,t){return Zt(X0,n.active,[t])}function My(n,t){Zt(Vf,n.active,[t])}function $0(n,t){Zt(Oy,n.active,[t])}function Dy(n,t){return Zt(ky,n.completed,[t])}function ec(n,t,e){Zt(Ty,n.completed,[t,e])}function ki(n,t,e=!1){if(n==null||typeof n!="object"||us(n))throw new Error(`${t} must be a plain data object`);let i=Qf(n);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain data object`);let r=Do(n);for(let s=0;s<r.length;s++){let o=r[s],c=$t(n,o);if(typeof o=="symbol"&&e){if(c==null||!("value"in c))throw new Error(`${t} symbol metadata must be a data property`);continue}if(typeof o!="string"||c==null||!c.enumerable||!("value"in c))throw new Error(`${t} must contain only string-keyed data properties`)}return n}function Y0(n,t,e=cs){if(Qf(n)!==Array.prototype)throw new Error(`${t} must contain only dense data arrays`);let i=$t(n,"length");if(i==null||!("value"in i)||!Ti(i.value)||i.value<0)throw new Error(`${t} must contain only dense data arrays`);let r=i.value;if(r>cs)throw new Error(`${t} exceeds the byte limit`);if(Do(n).length!==r+1)throw new Error(`${t} must contain only dense data arrays`);let o=r>e,c=o?void 0:new rn(r);for(let u=0;u<r;u++){let f=$t(n,Jf(u));if(f==null||!f.enumerable||!("value"in f))throw new Error(`${t} must contain only dense data arrays`);if(!yy(f.value)||f.value<0||f.value>255)return;c!==void 0&&(c[u]=f.value)}if(o)throw new Error(`${t} exceeds the aggregate byte limit`);return c}function Z0(n,t,e=cs){if(U0==null||ic==null||M0==null)return;let i,r,s;try{i=Zt(U0,n,[]),r=Zt(ic,n,[]),s=Zt(M0,n,[])}catch{return}if(s!=="Uint8Array")return;if(D0!=null){let c=!1;try{Zt(D0,i,[]),c=!0}catch{}if(c)throw new Error(`${t} must not use shared byte storage`)}if(r>cs)throw new Error(`${t} exceeds the byte limit`);if(r>e)throw new Error(`${t} exceeds the aggregate byte limit`);let o=new z0(r);try{Zt(Ey,o,[n])}catch{throw new Error(`${t} must contain only intrinsic byte arrays`)}return o}function vr(n,t,e=0,i={nodes:0,active:new WeakSet,completed:new WeakMap,copiedBytes:0},r=!1){if(e>by)throw new Error(`${t} exceeds the depth limit`);if(i.nodes+=1,i.nodes>Ff)throw new Error(`${t} exceeds the node limit`);if(n==null||typeof n=="string"||typeof n=="boolean")return n;if(typeof n=="number"){if(!wy(n)||K0(n,-0))throw new Error(`${t} contains an ambiguous number`);return n}if(typeof n!="object")throw new Error(`${t} contains unsupported data`);if(H0(i,n))throw new Error(`${t} contains a cycle`);let s=Dy(i,n);if(s!==void 0)return s;let o=Z0(n,t,cs-i.copiedBytes);if(o!==void 0)return i.copiedBytes+=o.length,Zt(Vf,Kf,[o]),ec(i,n,o),o;if(us(n)){let l=Y0(n,t,cs-i.copiedBytes);if(l!==void 0)return i.copiedBytes+=l.length,Zt(Vf,Kf,[l]),ec(i,n,l),l;let p=$t(n,"length");if(p==null||!("value"in p)||!Ti(p.value)||p.value<0)throw new Error(`${t} must contain only dense data arrays`);if(p.value>Ff)throw new Error(`${t} exceeds the node limit`)}if(My(i,n),us(n)){let l=L0(n),p=l.length;if(p==null||!("value"in p)||!Ti(p.value)||p.value<0||p.value>Ff)throw new Error(`${t} must contain only dense data arrays`);let m=p.value,g=Do(l);if(g.length!==m+1)throw new Error(`${t} must contain only dense data arrays`);for(let S=0;S<g.length;S++){let C=g[S];if(C!=="length"&&(typeof C!="string"||!Mo(j0,C)||Zf(C)>=m))throw new Error(`${t} must contain only dense data arrays`)}let w=new rn(m);for(let S=0;S<m;S++){let C=Jf(S),E=l[C];if(E==null||!E.enumerable||!("value"in E))throw new Error(`${t} must contain only dense data arrays`);w[S]=vr(E.value,`${t}[${S}]`,e+1,i)}return $0(i,n),ec(i,n,w),w}let c=ki(n,t,r);if(H0(i,c)&&c!==n)throw new Error(`${t} contains a cycle`);let u=Uo(null),f=L0(c),d=Lo(f);for(let l=0;l<d.length;l++){let p=d[l],m=f[p];if(!m.enumerable||!("value"in m))throw new Error(`${t} must contain only string-keyed data properties`);Sy(u,p,{value:vr(m.value,`${t}.${p}`,e+1,i),enumerable:!0,configurable:!0,writable:!0})}return $0(i,n),ec(i,n,u),u}function q0(n,t){if(n!=null&&typeof n=="object"){let r=Zt(X0,Kf,[n]);if(r&&us(n)){let o=$t(n,"length")?.value;if(typeof o!="number"||o===0)throw new Error(`${t} must be a bounded non-empty byte array`);return n}if(r&&ic!=null){let o;try{o=Zt(ic,n,[])}catch{throw new Error(`${t} must be a bounded non-empty byte array`)}if(o===0)throw new Error(`${t} must be a bounded non-empty byte array`);return n}let s=Z0(n,t);if(s!==void 0){if(s.length===0)throw new Error(`${t} must be a bounded non-empty byte array`);return s}}if(!us(n))throw new Error(`${t} must be a bounded non-empty byte array`);let e=Y0(n,t);if(e==null||e.length===0)throw new Error(`${t} must be a bounded non-empty byte array`);let i=new z0(e.length);for(let r=0;r<e.length;r++)i[r]=e[r];return i}function nc(n,t){if(typeof n!="string"||!Mo(_y,n))throw new Error(`${t} must be a 32-byte hexadecimal transaction ID`);return Ar(n)}function sc(n,t){if(typeof n!="string"||!Mo(By,n))throw new Error(`${t} must be an even-length hexadecimal string`);return Ar(n)}function Gf(n,t){if(typeof n!="string")throw new Error(`${t} must be a canonical outpoint`);let e=Zt(Iy,Ry,[n]);if(e==null)throw new Error(`${t} must be a canonical outpoint`);let i=Zf(e[2]);if(!Ti(i)||i>4294967295)throw new Error(`${t} must be a canonical outpoint`);return`${Ar(e[1])}.${i}`}function Yf(n,t){let e=n.inputs[t];if(e==null||!Ti(e.sourceOutputIndex)||e.sourceOutputIndex<0||e.sourceOutputIndex>4294967295)throw new Error("Wallet transaction input is malformed");let i=e.sourceTransaction==null?void 0:G0(e.sourceTransaction);if(e.sourceTXID!==void 0&&i!==void 0&&nc(e.sourceTXID,"Wallet input source TXID")!==nc(i,"Wallet input source transaction ID"))throw new Error("Wallet transaction input source mismatch");return`${nc(e.sourceTXID??i,"Wallet input source TXID")}.${e.sourceOutputIndex}`}function as(n,t){if(typeof n!="number"||!Ti(n)||n<0||n>V0)throw new Error(`${t} must be a valid satoshi amount`);return n}function os(n,t,e){let i=n+t;if(!Ti(i)||i>V0)throw new Error(`${e} exceeds the maximum transaction value`);return i}function F0(n,t){let e=n.inputs[t],i=e?.sourceTransaction?.outputs[e.sourceOutputIndex];if(i==null)throw new Error("Wallet signable transaction omitted an input source output");return as(i.satoshis,`Wallet input ${t} source output`)}function Hy(n,t,e,i){if(t.version!==(n.version??1))throw new Error("Wallet transaction substituted the requested version");if(t.lockTime!==(n.lockTime??0))throw new Error("Wallet transaction substituted the requested lock time");let r=new rn(t.inputs.length),s=Uo(null);for(let A=0;A<t.inputs.length;A++){let k=Yf(t,A);if(rc(s,k))throw new Error("Wallet transaction contains a duplicate input outpoint");r[A]=k,s[k]=!0}let o=[],c=Uo(null);for(let A=0;A<(n.inputs?.length??0);A++){let k=n.inputs[A],B=Gf(k.outpoint,`Requested input ${A} outpoint`);if(rc(c,B))throw new Error("Action requests the same input outpoint more than once");c[B]=!0;let _=-1;for(let O=0;O<r.length;O++)if(r[O]===B){if(_!==-1)throw new Error("Wallet transaction does not contain each requested input exactly once");_=O}if(_===-1)throw new Error("Wallet transaction does not contain each requested input exactly once");if(o[A]=_,(t.inputs[_].sequence??4294967295)!==(k.sequenceNumber??4294967295))throw new Error("Wallet transaction substituted a requested input sequence");let H=t.inputs[_].unlockingScript;if(k.unlockingScript!==void 0&&(H==null?void 0:Ar(fs(H)))!==sc(k.unlockingScript,`Requested input ${A} unlocking script`))throw new Error("Wallet transaction substituted a requested unlocking script")}let u=new rn(t.outputs.length);for(let A=0;A<t.outputs.length;A++){let k=t.outputs[A];u[A]={satoshis:as(k.satoshis,`Wallet output ${A}`),lockingScript:Ar(fs(k.lockingScript))}}let f=new rn(u.length),d=n.options?.randomizeOutputs===!1,l=0,p=(A,k)=>{let B=n.outputs[A],_=sc(B.lockingScript,`Requested output ${A} locking script`),H=as(B.satoshis,`Requested output ${A}`);if(d){let I=u[A],U=I!=null&&(k==null?I.satoshis===H:I.satoshis>=k.minimumSatoshis&&I.satoshis<=k.maximumSatoshis);if(I==null||I.lockingScript!==_||!U)throw new Error("Wallet transaction substituted a requested output position");f[A]=!0,l=os(l,I.satoshis,"Requested output value");return}let O=-1;for(let I=0;I<u.length;I++){let U=u[I];if(!(f[I]===!0||U.lockingScript!==_||!(k==null?U.satoshis===H:U.satoshis>=k.minimumSatoshis&&U.satoshis<=k.maximumSatoshis))){if(k==null){O=I;break}if(O!==-1)throw new Error("Wallet transaction omitted or substituted a requested output");O=I}}if(O===-1)throw new Error("Wallet transaction omitted or substituted a requested output");f[O]=!0,l=os(l,u[O].satoshis,"Requested output value")};for(let A=0;A<(n.outputs?.length??0);A++)e[A]===void 0&&p(A);for(let A=0;A<(n.outputs?.length??0);A++){let k=e[A];k!=null&&p(A,k)}let m=0,g=new rn(t.inputs.length);for(let A=0;A<o.length;A++){let k=o[A];g[k]=!0,m=os(m,i?.[A]??F0(t,k),"Requested input value")}let w=0;for(let A=0;A<t.inputs.length;A++)g[A]!==!0&&(w=os(w,F0(t,A),"Wallet-added input value"));let S=0;for(let A=0;A<u.length;A++)S=os(S,u[A].satoshis,"Wallet output value");let C=os(m,w,"Wallet input value");if(S>C)throw new Error("Wallet signable transaction spends more than its inputs");if(S-l>w)throw new Error("Wallet used a requested input to fund an unrequested output");return o}function W0(n,t){if(n.version!==t.version||n.lockTime!==t.lockTime||n.inputs.length!==t.inputs.length||n.outputs.length!==t.outputs.length)throw new Error("Wallet signed transaction substituted the authorized template");for(let e=0;e<n.inputs.length;e++)if(Yf(n,e)!==Yf(t,e)||(n.inputs[e].sequence??4294967295)!==(t.inputs[e].sequence??4294967295))throw new Error("Wallet signed transaction substituted an authorized input");for(let e=0;e<n.outputs.length;e++)if(n.outputs[e].satoshis!==t.outputs[e].satoshis||fs(n.outputs[e].lockingScript)!==fs(t.outputs[e].lockingScript))throw new Error("Wallet signed transaction substituted an authorized output")}async function $y(n,t,e){try{await n.abortAction({reference:t},e)}catch{}}async function J0(n,t,e={},i,r){Ly();let s=Cy(),o=vr(t,"Create action arguments"),c=vr(o,"Create action arguments"),u=o.inputs??[],f;if(r!==void 0){let I=vr(r,"Trusted requested input satoshis");if(!us(I)||I.length!==u.length)throw new Error("Trusted requested input satoshis must match the requested inputs");let U=new rn(I.length);for(let M=0;M<I.length;M++)U[M]=as(I[M],`Trusted requested input ${M}`);f=U}let d=ki(e,"Bound action options"),l=Lo(d);for(let I=0;I<l.length;I++){let U=l[I];if(U!=="inputSigners"&&U!=="outputSatoshisRanges")throw new Error(`Unknown bound action option "${U}"`)}let p=$t(d,"inputSigners")?.value,m=ki(p??{},"Input signers"),g=Uo(null),w=0,S=Lo(m);for(let I=0;I<S.length;I++){let U=S[I],M=$t(m,U)?.value,F=Gf(U,"Input signer outpoint");if(rc(g,F)||typeof M!="function")throw new Error("Input signers must uniquely identify requested outpoints");g[F]=M,w++}let C=$t(d,"outputSatoshisRanges")?.value,E=ki(C??{},"Output satoshi ranges"),A=new rn(o.outputs?.length??0),k=Lo(E);for(let I=0;I<k.length;I++){let U=k[I],M=$t(E,U)?.value;if(!Mo(j0,U))throw new Error("Output satoshi ranges must identify requested output indexes");let F=Zf(U);if(!Ti(F)||F>=(o.outputs?.length??0))throw new Error("Output satoshi ranges must identify requested output indexes");let it=ki(M,`Output satoshi range ${F}`),ot=Lo(it);for(let tt=0;tt<ot.length;tt++){let St=ot[tt];if(St!=="minimumSatoshis"&&St!=="maximumSatoshis")throw new Error(`Unknown output satoshi range option "${St}"`)}let q=as($t(it,"minimumSatoshis")?.value,`Output satoshi range ${F} minimum`),z=as($t(it,"maximumSatoshis")?.value,`Output satoshi range ${F} maximum`);if(q>z)throw new Error(`Output satoshi range ${F} minimum exceeds its maximum`);A[F]={minimumSatoshis:q,maximumSatoshis:z}}let B=await n.createAction({...c,options:{...c.options,signAndProcess:!1,returnTXIDOnly:!1}},i);Co(s);let _=ki(vr(B,"Wallet createAction result",0,void 0,!0),"Wallet createAction result",!0);Co(s);let H=ki($t(_,"signableTransaction")?.value,"Wallet signable transaction"),O=$t(H,"reference")?.value;if(typeof O!="string"||O.length===0||O.length>4096||!Mo(Ny,O))throw new Error("Wallet signable transaction reference is invalid");try{let I=Wf(q0($t(H,"tx")?.value,"Wallet signable transaction")),U=Hy(o,I,A,f),M=Wf(Uy(I)),F={},it=new rn(I.inputs.length),ot=new rn,q=Uo(null),z=0;for(let ke=0;ke<u.length;ke++){let xe=u[ke],vn=Gf(xe.outpoint,`Requested input ${ke} outpoint`),$=U[ke];if(xe.unlockingScript!==void 0){it[$]=sc(xe.unlockingScript,`Requested input ${ke} unlocking script`),ot[ot.length]=$;continue}let W=$t(g,vn)?.value;if(xe.unlockingScriptLength===void 0||W==null)throw new Error(`Requested input ${ke} has no authorized signer`);let D=await W(I,$);Co(s),W0(M,I);let V=sc(typeof D=="string"?D:fs(D),`Requested input ${ke} signed unlocking script`);F[$]={unlockingScript:V},it[$]=V,ot[ot.length]=$,rc(q,vn)||(q[vn]=!0,z++)}if(z!==w)throw new Error("An input signer does not match a requested signable input");let tt={acceptDelayedBroadcast:o.options?.acceptDelayedBroadcast,returnTXIDOnly:!1,noSend:o.options?.noSend,sendWith:o.options?.sendWith},St=await n.signAction({reference:O,spends:F,options:tt},i);Co(s);let ce=ki(vr(St,"Wallet signAction result",0,void 0,!0),"Wallet signAction result",!0);Co(s);let Bt=Wf(q0($t(ce,"tx")?.value,"Wallet signed transaction"));W0(I,Bt);for(let ke=0;ke<ot.length;ke++){let xe=ot[ke],vn=it[xe],$=Bt.inputs[xe]?.unlockingScript;if($==null||Ar(fs($))!==vn)throw new Error("Wallet signed transaction substituted an authorized unlocking script")}let dn=$t(ce,"txid")?.value;if(dn!==void 0&&nc(dn,"Wallet signed transaction ID")!==Ar(G0(Bt)))throw new Error("Wallet signed transaction ID does not match its transaction data");return Bt}catch(I){throw await $y(n,O,i),I}}var Ho=class extends Error{constructor(e){super(`Transaction evidence: ${e}`);b(this,"code");this.code=e,this.name="TransactionEvidenceError"}};var DS=Object.freeze({candidateBytes:1024*1024,retainedBytes:16*1024*1024,transactions:256,inputs:4096,scriptBytes:256*1024,scriptMemoryBytes:16*1024*1024,candidatesPerTransaction:8,pendingTransactions:32,concurrentTransactions:4,pendingChainCalls:8,consumers:128,cacheEntries:128,cacheAgeMs:6e4,attemptTimeoutMs:5e3,requestTimeoutMs:15e3});function Q0(n){let t=n.tx,e=t.inputs.map(i=>{let r=i.sourceTransaction,s=r?.outputs[i.sourceOutputIndex];if(r===void 0||s===void 0)throw new Ho("invalid-evidence");return[r.id("hex"),i.sourceOutputIndex,s.satoshis,s.lockingScript.toHex()]});return nt(Te(at(JSON.stringify([t.toHex(),e,n.blockHeight,n.consensus,n.verifyFlags,n.memoryLimit]),"utf8")))}var qy=new WeakMap;function tg(n){return qy.get(n)}function eg(n,t){return{supportsMemoryLimit:t.supportsMemoryLimit,shouldVerifyScripts:t.shouldVerifyScripts===void 0?void 0:e=>{n.check();let i=Q0(e),r=t.shouldVerifyScripts(e);if(n.check(),Q0(e)!==i)throw new Ho("invalid-evidence");return r},verifyScripts:async e=>(await n.work.batch(n,[e],t))[0],verifyScriptsBatch:async e=>await n.work.batch(n,e,t)}}var ng=Symbol(),ig=Symbol();function Jp(n){return n[ng]()}function Qp(n,t){n[ig](t)}var Fy=943816,rg=21e14,Wy=1e6;function sn(n,t){if(typeof n!="number"||!Number.isSafeInteger(n)||n<0||n>rg)throw new RangeError(`${t} must be a non-negative safe integer no greater than 21e14.`);return n}function ds(n,t,e){let i=n+t;if(!Number.isSafeInteger(i)||i>rg)throw new RangeError(`${e} exceeds the maximum valid monetary range.`);return i}function Ge(n,t){if(typeof n!="number"||!Number.isInteger(n)||n<0||n>4294967295)throw new RangeError(`${t} must be an unsigned 32-bit integer.`);return n}function Oi(n,t){if(typeof n!="string"||!/^[0-9a-fA-F]{64}$/.test(n))throw new TypeError(`${t} must be a 32-byte hexadecimal transaction ID.`);return n.toLowerCase()}function ed(n,t){if(n===void 0||t===void 0)return n===t;if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}var kr,ti,Ri,Tr,Ni,qo,ls,j,sg,og,Mn,$o,nd,yn,id,ac,rd,ag,cg,ug,fg,dg,lg,hg,Er,pg,sd,gg,mg,bg,wg,cc,yg,xg,Pi,uc,Sg,Ig,vg,Ag,Eg,kg,Tg,Og,Pg,oe=class oe{constructor(t=1,e=[],i=[],r=0,s=new Map,o){G(this,j);b(this,"version");b(this,"inputs");b(this,"outputs");b(this,"lockTime");b(this,"metadata");b(this,"merklePath");G(this,kr);G(this,ti);G(this,Ri);G(this,Tr);G(this,Ni);G(this,qo);G(this,ls);this.version=t,this.inputs=e,this.outputs=i,this.lockTime=r,this.metadata=s,this.merklePath=o}getSignatureHashCache(){return y(this,qo)??{hashOutputsSingle:new Map}}materializeSourceTXIDs(){let t=new Set,e=new Set,i=[{tx:this,expanded:!1}];for(;i.length>0;){let r=i.pop();if(r!=null&&!t.has(r.tx)){if(r.expanded){a(this,j,sg).call(this,r.tx,e,t);continue}a(this,j,og).call(this,r.tx,e,t,i)}}}static fromBEEF(t,e){var r;let{tx:i}=a(r=oe,Mn,$o).call(r,t,e);return i}static fromBEEFView(t,e){var r;let{tx:i}=a(r=oe,Mn,$o).call(r,t,e,!0);return i}static fromAtomicBEEF(t){var s;let{tx:e,txid:i,beef:r}=a(s=oe,Mn,$o).call(s,t);if(i!==r.atomicTxid)throw r.atomicTxid==null?new Error("beef must conform to BRC-95 and must contain the subject txid."):new Error(`Transaction with TXID ${r.atomicTxid} not found in BEEF data.`);if(!r.isAtomic(i))throw new Error("Atomic BEEF contains unrelated transaction data.");return e}static fromAtomicBEEFView(t){var s;let{tx:e,txid:i,beef:r}=a(s=oe,Mn,$o).call(s,t,void 0,!0);if(i!==r.atomicTxid)throw r.atomicTxid==null?new Error("beef must conform to BRC-95 and must contain the subject txid."):new Error(`Transaction with TXID ${r.atomicTxid} not found in BEEF data.`);if(!r.isAtomic(i))throw new Error("Atomic BEEF contains unrelated transaction data.");return e}static fromEF(t){let e=bt.makeReader(t),i=e.readUInt32LE();if(nt(e.read(6))!=="0000000000ef")throw new Error("Invalid EF marker");let r=e.readVarIntNumStrict(!1),s=[];for(let f=0;f<r;f++){let d=nt(e.readReverse(32)),l=e.readUInt32LE();if(l>Wy)throw new RangeError("EF source output index exceeds the allocation limit");let p=e.readVarIntNumStrict(!1),m=e.read(p),g=Ue.fromBinary(m),w=e.readUInt32LE(),S=e.readUInt64LEBn().toNumber(),C=e.readVarIntNumStrict(!1),E=e.read(C),A=Le.fromBinary(E),k=new oe(void 0,[],[],void 0);k.outputs=Array.from({length:l+1}).fill(null),k.outputs[l]={satoshis:S,lockingScript:A},s.push({sourceTransaction:k,sourceTXID:d,sourceOutputIndex:l,unlockingScript:g,sequence:w})}let o=e.readVarIntNumStrict(!1),c=[];for(let f=0;f<o;f++){let d=e.readUInt64LEBn().toNumber(),l=e.readVarIntNumStrict(!1),p=e.read(l),m=Le.fromBinary(p);c.push({satoshis:d,lockingScript:m})}let u=e.readUInt32LE();if(!e.eof())throw new Error("Serialized EF transaction contains trailing data");return new oe(i,s,c,u)}static parseScriptOffsets(t){let e=bt.makeReader(t),i=[],r=[];e.read(4);let s=e.readVarIntNumStrict(!1);for(let c=0;c<s;c++){e.read(36);let u=e.readVarIntNumStrict(!1);i.push({vin:c,offset:e.pos,length:u}),e.read(u+4)}let o=e.readVarIntNumStrict(!1);for(let c=0;c<o;c++){e.read(8);let u=e.readVarIntNumStrict(!1);r.push({vout:c,offset:e.pos,length:u}),e.read(u)}if(e.read(4),!e.eof())throw new Error("Serialized transaction contains trailing data");return{inputs:i,outputs:r}}static fromReader(t){var e;return a(e=oe,Mn,nd).call(e,t,!1)}static fromBinary(t){let e=Uint8Array.from(t);return oe.fromBinaryView(e)}static fromBinaryView(t){var r,s;let e=new bt(t),i=a(r=oe,Mn,nd).call(r,e,!0);if(!e.eof())throw new Error("Serialized transaction contains trailing data");return N(i,Ri,t),a(s=i,j,ac).call(s),i}static fromHex(t){let e=et(t,"hex"),i=oe.fromBinaryView(e);return N(i,Ni,nt(e)),i}static fromHexEF(t){return oe.fromEF(et(t,"hex"))}static fromHexBEEF(t,e){return oe.fromBEEF(at(t,"hex"),e)}addInput(t){if(t.sourceTXID===void 0&&t.sourceTransaction===void 0)throw new TypeError("A reference to an an input transaction is required. If the input transaction itself cannot be referenced, its TXID must still be provided.");Ge(t.sourceOutputIndex,"sourceOutputIndex"),t.sourceTXID!==void 0&&(t.sourceTXID=Oi(t.sourceTXID,"sourceTXID")),t.sequence!==void 0&&Ge(t.sequence,"sequence"),t.sequence??(t.sequence=4294967295),a(this,j,yn).call(this),this.inputs.push(t)}addOutput(t){if(a(this,j,yn).call(this),t.satoshis===void 0&&t.change!==!0)throw new TypeError("either satoshis must be defined or change must be set to true");if(t.satoshis!==void 0&&sn(t.satoshis,"satoshis"),t.lockingScript==null)throw new Error("lockingScript must be defined");this.outputs.push(t)}addP2PKHOutput(t,e){let i=new Yn().lock(t);if(e===void 0)return this.addOutput({lockingScript:i,change:!0});this.addOutput({lockingScript:i,satoshis:e})}updateMetadata(t){this.metadata={...this.metadata,...t}}async fee(t=Ao.getInstance(),e="equal"){var S,C,E,A,k;if(a(this,j,yn).call(this),e!=="equal"&&e!=="random")throw new TypeError('changeDistribution must be either "equal" or "random".');if(typeof t=="number"){let B=t;t={computeFee:async()=>B}}let i=a(this,j,Pi).call(this,!0),r=a(S=i,j,Pi).call(S,!0),s=a(C=i,j,Pi).call(C,!0),o=[...this.inputs],c=this.inputs.map(B=>B.sourceTransaction),u=this.inputs.map(B=>B.unlockingScriptTemplate),f=[...this.outputs],d=[...s.inputs],l=s.inputs.map(B=>B.sourceTransaction),p=s.inputs.map(B=>B.unlockingScriptTemplate),m=[...s.outputs],g=sn(await t.computeFee(s),"Computed transaction fee");if(!a(E=s,j,uc).call(E,i,d,l,p,m))throw new Error("Fee model mutated its transaction snapshot");let w=a(A=r,j,ag).call(A,g);if(w<0)throw new RangeError("Transaction inputs are insufficient for the requested outputs and fee.");if(!a(this,j,uc).call(this,i,o,c,u,f))throw new Error("Transaction changed while computing its fee; no change was applied");if(w===0){this.outputs=f.filter(B=>B.change!==!0),a(this,j,yn).call(this);return}a(k=r,j,cg).call(k,w,e);for(let B=0;B<f.length;B++)f[B].change===!0&&(f[B].satoshis=r.outputs[B].satoshis);a(this,j,yn).call(this)}getFee(){let t=0;for(let i=0;i<this.inputs.length;i++){let r=this.inputs[i];if(typeof r.sourceTransaction!="object")throw new TypeError("Source transactions or sourceSatoshis are required for all inputs to calculate fee");Ge(r.sourceOutputIndex,`Input ${i} sourceOutputIndex`);let s=r.sourceTransaction.outputs[r.sourceOutputIndex];if(s==null)throw new RangeError(`Input ${i} references a source output that does not exist.`);t=ds(t,sn(s.satoshis,`Input ${i} source amount`),"Transaction input total")}let e=0;for(let i=0;i<this.outputs.length;i++)e=ds(e,sn(this.outputs[i].satoshis,`Output ${i} amount`),"Transaction output total");return t-e}async sign(t={}){a(this,j,yn).call(this);for(let f=0;f<this.outputs.length;f++){let d=this.outputs[f];if(d.satoshis===void 0)throw d.change===!0?new Error("There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing."):new Error("One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.");sn(d.satoshis,`Output ${f} amount`)}a(this,j,cc).call(this,this);for(let f=0;f<this.inputs.length;f++){let d=this.inputs[f];if(Ge(d.sourceOutputIndex,`Input ${f} sourceOutputIndex`),Ge(d.sequence??4294967295,`Input ${f} sequence`),d.sourceTXID!==void 0&&Oi(d.sourceTXID,`Input ${f} sourceTXID`),d.sourceTransaction!==void 0){let l=d.sourceTransaction.outputs[d.sourceOutputIndex];if(l==null)throw new RangeError(`Input ${f} references a source output that does not exist.`);if(sn(l.satoshis,`Input ${f} source amount`),d.sourceTXID!==void 0&&(d.sourceTransaction.inputs.length>0||d.sourceTransaction.merklePath!=null)&&Oi(d.sourceTXID,`Input ${f} sourceTXID`)!==d.sourceTransaction.id("hex"))throw new Error(`Input ${f} sourceTXID does not reference its supplied source transaction.`)}}this.materializeSourceTXIDs();let e=a(this,j,Pi).call(this,!0),i=[...this.inputs],r=this.inputs.map(f=>f.sourceTransaction),s=this.inputs.map(f=>f.unlockingScriptTemplate),o=[...this.outputs],c=t.skipExistingSignatures===!0,u;if(u=await Promise.all(e.inputs.map(async(f,d)=>{var w;if(c&&f.unlockingScript!=null)return new Ue([],Uint8Array.from(f.unlockingScript.toUint8Array()),void 0,!1);let l=s[d];if(l===void 0)return;let p=a(w=e,j,Pi).call(w,!0);for(let S=0;S<s.length;S++)p.inputs[S].unlockingScriptTemplate=s[S];N(p,qo,{hashOutputsSingle:new Map});let m=await l.sign(p,d);if(m==null||typeof m.toUint8Array!="function")throw new TypeError(`Input ${d} signing template returned an invalid unlocking script`);let g=m.toUint8Array();if(!(g instanceof Uint8Array))throw new TypeError(`Input ${d} signing template returned an invalid unlocking script`);return new Ue([],Uint8Array.from(g),void 0,!1)})),!a(this,j,uc).call(this,e,i,r,s,o))throw new Error("Transaction changed while signing; no unlocking scripts were applied");for(let f=0,d=this.inputs.length;f<d;f++)s[f]!==void 0&&!(c&&i[f].unlockingScript!=null)&&(this.inputs[f].unlockingScript=u[f]);a(this,j,yn).call(this)}async broadcast(t=Xp()){let e=a(this,j,Pi).call(this),i=e.id("hex");return Lp(await t.broadcast(e),i)}[ng](){return a(this,j,Er).call(this)}[ig](t){N(this,ti,t)}toBinary(){return Array.from(a(this,j,Er).call(this))}toUint8Array(){return Uint8Array.from(a(this,j,Er).call(this))}toEF(){return Array.from(a(this,j,sd).call(this))}toEFUint8Array(){return this.toEFBinary()}toEFBinary(){return Uint8Array.from(a(this,j,sd).call(this))}toHexEF(){return nt(this.toEFBinary())}toHex(){let t=a(this,j,Er).call(this);if(y(this,Ni)!=null)return y(this,Ni);let e=nt(t);return N(this,Ni,e),e}toHexBEEF(){return nt(this.toBEEF())}toHexAtomicBEEF(){return nt(this.toAtomicBEEF())}hash(t){let e=a(this,j,Er).call(this);return y(this,kr)??N(this,kr,zt(e)),t==="hex"?nt(y(this,kr)):Array.from(y(this,kr))}id(t){if(a(this,j,Er).call(this),t==="hex"&&y(this,ti)!=null)return y(this,ti);let e=[...this.hash()];return e.reverse(),t==="hex"?(N(this,ti,nt(e)),y(this,ti)):e}async verifyTransactionFee(t,e,i){if(e===void 0)return;if(t===void 0)throw new Error("Transaction is undefined");let r=oe.fromEF(t.toEF());if(delete r.outputs[0].satoshis,r.outputs[0].change=!0,await r.fee(e),t.getFee()<r.getFee())throw new Error(`Verification failed because the transaction ${i()} has an insufficient fee and has not been mined.`)}async verify(t=Zp(),e,i,r){var o;t!=="scripts only"&&this.materializeSourceTXIDs();let s=t==="scripts only"?void 0:tg(this);return await a(o=a(this,j,Pi).call(this),j,Ig).call(o,t,e,i,r,s)}writeSerializedBEEF(t,e){this.materializeSourceTXIDs(),t.writeUInt32LE(4022206465);let{bumps:i,txs:r}=a(this,j,vg).call(this,e);t.writeVarIntNum(i.length);let s=a(this,j,Tg).call(this,t,i,r);for(let o=0;o<i.length;o++)t.write(s?.[o]??i[o].toBinary());t.writeVarIntNum(r.length);for(let o of r)t.write(o.tx.toUint8Array()),typeof o.pathIndex=="number"?(t.writeUInt8(1),t.writeVarIntNum(o.pathIndex)):t.writeUInt8(0)}toBEEF(t){let e=new fe;return this.writeSerializedBEEF(e,t),e.toArray()}toBEEFUint8Array(t){let e=new ht;return this.writeSerializedBEEF(e,t),e.toArray()}toBEEFBytes(t){let e=new ht;return this.writeSerializedBEEF(e,t),e.toUint8Array()}toAtomicBEEF(t){this.materializeSourceTXIDs();let e=[1,1,1,1],i=this.hash(),r=this.toBEEF(t);return e.concat(i,r)}toAtomicBEEFUint8Array(t){this.materializeSourceTXIDs();let e=new ht,i=[1,1,1,1];e.write(i);let r=this.hash();return e.write(r),this.writeSerializedBEEF(e,t),e.toUint8Array()}async completeWithWallet(t,e,i,r){let s=this.inputs.length,o=this.outputs.length,c=e??`Transaction with ${s} input(s) and ${o} output(s)`,u=this.inputs.some(p=>p.unlockingScriptTemplate!=null),f=await a(this,j,Og).call(this,c,u);f.options=r;let d={};for(let p=0;p<this.inputs.length;p++){let m=this.inputs[p].unlockingScriptTemplate;if(m==null)continue;let g=f.inputs[p].outpoint;d[g]=async(w,S)=>await m.sign(w,S)}let l=await J0(t,f,{inputSigners:d},i,this.inputs.map((p,m)=>{let g=p.sourceTransaction?.outputs[p.sourceOutputIndex];if(g==null)throw new Error(`Input ${m} references a source output that does not exist`);return sn(g.satoshis,`Input ${m} source amount`)}));this.version=l.version,this.inputs=l.inputs,this.outputs=l.outputs,this.lockTime=l.lockTime,this.merklePath=l.merklePath,a(this,j,yn).call(this),this.metadata={...this.metadata,...l.metadata}}preimage(t,e,i){if(t??(t=0),e??(e=wt.SIGHASH_FORKID|wt.SIGHASH_ALL),!Number.isSafeInteger(t)||t<0||t>=this.inputs.length)throw new Error("Invalid input index");Ge(e,"signatureScope");let r=e&240;if(r!==224&&r!==192&&r!==64)throw new Error("FORKID must be set");let s=e&15;if(s<1||s>3)throw new Error("Invalid signature coverage, must be all, none or single");let o=this.inputs[t],c=Ge(o.sourceOutputIndex,"sourceOutputIndex");if(o.sourceTransaction==null)throw new Error("Source transaction is required");let u=Oi(o.sourceTransaction.id("hex"),"sourceTransaction ID");if(o.sourceTXID!==void 0&&Oi(o.sourceTXID,"sourceTXID")!==u)throw new Error("sourceTXID does not match sourceTransaction");let f=o.sourceTransaction.outputs[c];if(f==null)throw new Error(`Source transaction's output at index ${c} is required`);let d=sn(f.satoshis,"Source output amount"),l=Ge(o.sequence??4294967295,"inputSequence"),p=i??f.lockingScript;if(p==null||typeof p.toUint8Array!="function")throw new Error("subscript must be a locking script");return wt.format({sourceTXID:u,sourceOutputIndex:c,sourceSatoshis:d,transactionVersion:this.version,otherInputs:[],allInputs:this.inputs,inputIndex:t,outputs:this.outputs,inputSequence:l,subscript:p,lockTime:this.lockTime,scope:e})}};kr=new WeakMap,ti=new WeakMap,Ri=new WeakMap,Tr=new WeakMap,Ni=new WeakMap,qo=new WeakMap,ls=new WeakMap,j=new WeakSet,sg=function(t,e,i){for(let r of t.inputs)r.sourceTXID==null&&r.sourceTransaction!=null&&(r.sourceTXID=r.sourceTransaction.id("hex"));e.delete(t),i.add(t)},og=function(t,e,i,r){if(e.has(t))throw new Error("Cyclic source transaction graph");e.add(t),r.push({tx:t,expanded:!0});for(let s=t.inputs.length-1;s>=0;s--){let o=t.inputs[s].sourceTransaction;t.inputs[s].sourceTXID==null&&o!=null&&!i.has(o)&&r.push({tx:o,expanded:!1})}},Mn=new WeakSet,$o=function(t,e,i=!1){let r=i&&t instanceof Uint8Array?Ir.fromBinaryView(t):Ir.fromBinaryStrict(t);if(r.txs.length<1)throw new Error("beef must include at least one transaction.");let s=r.txs.at(-1);if(s==null)throw new Error("beef must include at least one transaction.");let o=e??r.atomicTxid??s.txid,c=r.findAtomicTransaction(o);if(c==null)throw e==null?new Error("beef does not contain transaction for atomic txid."):new Error(`Transaction with TXID ${String(o)} not found in BEEF data.`);return{tx:c,beef:r,txid:o}},nd=function(t,e){let i=t.readUInt32LE(),r=t.readVarIntNumStrict(!1),s=[];for(let f=0;f<r;f++){let d=nt(t.readReverse(32)),l=t.readUInt32LE(),p=t.readVarIntNumStrict(!1),m=e&&t instanceof bt?t.readView(p):t.read(p),g=e&&m instanceof Uint8Array?Ue.fromBinaryView(m):Ue.fromBinary(m),w=t.readUInt32LE();s.push({sourceTXID:d,sourceOutputIndex:l,unlockingScript:g,sequence:w})}let o=t.readVarIntNumStrict(!1),c=[];for(let f=0;f<o;f++){let d=t.readUInt64LEBn().toNumber(),l=t.readVarIntNumStrict(!1),p=e&&t instanceof bt?t.readView(l):t.read(l),m=e&&p instanceof Uint8Array?Le.fromBinaryView(p):Le.fromBinary(p);c.push({satoshis:d,lockingScript:m})}let u=t.readUInt32LE();return new oe(i,s,c,u)},yn=function(){N(this,kr,void 0),N(this,ti,void 0),N(this,Ri,void 0),N(this,Tr,void 0),N(this,Ni,void 0),N(this,ls,void 0)},id=function(t){return t.sourceTXID==null?t.sourceTransaction?.id("hex"):void 0},ac=function(){N(this,ls,{version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(t=>{let e=t.sourceTransaction?.outputs[t.sourceOutputIndex];return{ref:t,sourceTXID:t.sourceTXID,sourceTransactionId:a(this,j,id).call(this,t),sourceOutputIndex:t.sourceOutputIndex,sequence:t.sequence,unlockingScript:t.unlockingScript,unlockingScriptBytes:t.unlockingScript==null?void 0:hr(t.unlockingScript),sourceOutput:e,sourceSatoshis:e?.satoshis,sourceLockingScript:e?.lockingScript,sourceLockingScriptBytes:e==null?void 0:hr(e.lockingScript)}}),outputs:this.outputs.map(t=>({ref:t,satoshis:t.satoshis,lockingScript:t.lockingScript,lockingScriptBytes:hr(t.lockingScript)}))})},rd=function(){let t=y(this,ls);if(t?.version!==this.version||t.lockTime!==this.lockTime||t.inputs.length!==this.inputs.length||t.outputs.length!==this.outputs.length)return!1;for(let e=0;e<this.inputs.length;e++){let i=this.inputs[e],r=t.inputs[e],s=i.sourceTransaction?.outputs[i.sourceOutputIndex];if(r.ref!==i||r.sourceTXID!==i.sourceTXID||r.sourceTransactionId!==a(this,j,id).call(this,i)||r.sourceOutputIndex!==i.sourceOutputIndex||r.sequence!==i.sequence||r.unlockingScript!==i.unlockingScript||r.unlockingScriptBytes!==(i.unlockingScript==null?void 0:hr(i.unlockingScript))||r.sourceOutput!==s||r.sourceSatoshis!==s?.satoshis||r.sourceLockingScript!==s?.lockingScript||r.sourceLockingScriptBytes!==(s==null?void 0:hr(s.lockingScript)))return!1}for(let e=0;e<this.outputs.length;e++){let i=this.outputs[e],r=t.outputs[e];if(r.ref!==i||r.satoshis!==i.satoshis||r.lockingScript!==i.lockingScript||r.lockingScriptBytes!==hr(i.lockingScript))return!1}return!0},ag=function(t){let e=0;for(let r=0;r<this.inputs.length;r++){let s=this.inputs[r];if(typeof s.sourceTransaction!="object")throw new TypeError("Source transactions are required for all inputs during fee computation");Ge(s.sourceOutputIndex,`Input ${r} sourceOutputIndex`);let o=s.sourceTransaction.outputs[s.sourceOutputIndex];if(o==null)throw new RangeError(`Input ${r} references a source output that does not exist.`);let c=sn(o.satoshis,`Input ${r} source amount`);e=ds(e,c,"Transaction input total")}let i=0;for(let r=0;r<this.outputs.length;r++){let s=this.outputs[r];if(s.change!==!0){let o=sn(s.satoshis,`Output ${r} amount`);i=ds(i,o,"Transaction output total")}}if(i+t>e)throw new RangeError("Transaction inputs are insufficient for the requested outputs and fee.");return e-i-t},cg=function(t,e){let i=this.outputs.filter(r=>r.change===!0);i.length!==0&&(e==="random"?a(this,j,ug).call(this,t,i):a(this,j,fg).call(this,t,i))},ug=function(t,e){let i=t;for(let r=0;r<e.length-1;r++){let s=a(this,j,dg).call(this,0,i);e[r].satoshis=s,i-=s}e.at(-1).satoshis=i},fg=function(t,e){let i=Math.floor(t/e.length);for(let r of e)r.satoshis=i;e.at(-1).satoshis+=t-i*e.length},dg=function(t,e){let i=Pe(1)[0]%9+1;return Math.floor(t+(e-t)*Math.log10(1+1/i)/Math.log10(10))},lg=function(t){t.writeUInt32LE(this.version),t.writeVarIntNum(this.inputs.length);for(let e of this.inputs){if(e.sourceTXID===void 0){if(e.sourceTransaction==null)throw new Error("sourceTransaction is undefined");t.write(e.sourceTransaction.hash())}else t.writeReverse(at(Oi(e.sourceTXID,"sourceTXID"),"hex"));if(t.writeUInt32LE(Ge(e.sourceOutputIndex,"sourceOutputIndex")),e.unlockingScript==null)throw new Error("unlockingScript is undefined");let i=e.unlockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i),t.writeUInt32LE(Ge(e.sequence??4294967295,"sequence"))}t.writeVarIntNum(this.outputs.length);for(let e of this.outputs){t.writeUInt64LE(e.satoshis??0);let i=e.lockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i)}t.writeUInt32LE(this.lockTime)},hg=function(){let t=new ht;return a(this,j,lg).call(this,t),t.toUint8Array()},Er=function(){return(y(this,Ri)==null||!a(this,j,rd).call(this))&&(a(this,j,yn).call(this),N(this,Ri,a(this,j,hg).call(this)),a(this,j,ac).call(this)),y(this,Ri)},pg=function(t){t.writeUInt32LE(this.version),t.write([0,0,0,0,0,239]),t.writeVarIntNum(this.inputs.length);for(let e of this.inputs){if(e.sourceTransaction===void 0)throw new TypeError("All inputs must have source transactions when serializing to EF format");if(e.sourceTXID===void 0?t.write(e.sourceTransaction.hash()):t.write(at(e.sourceTXID,"hex").reverse()),t.writeUInt32LE(e.sourceOutputIndex),e.unlockingScript==null)throw new Error("unlockingScript is undefined");let i=e.unlockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i),t.writeUInt32LE(e.sequence??4294967295),t.writeUInt64LE(e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0);let r=e.sourceTransaction.outputs[e.sourceOutputIndex].lockingScript.toUint8Array();t.writeVarIntNum(r.length),t.write(r)}t.writeVarIntNum(this.outputs.length);for(let e of this.outputs){t.writeUInt64LE(e.satoshis??0);let i=e.lockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i)}t.writeUInt32LE(this.lockTime)},sd=function(){if(y(this,Tr)==null||!a(this,j,rd).call(this)){a(this,j,yn).call(this);let t=new ht;a(this,j,pg).call(this,t),N(this,Tr,t.toUint8Array()),a(this,j,ac).call(this)}return y(this,Tr)},gg=async function(t,e,i,r,s,o){if(typeof t.merklePath!="object")return!1;if(e)return s.add(t),!0;if(await t.merklePath.verify(r(),i))return o.add(r()),!0;throw new Error(`Invalid merkle path for transaction ${r()}`)},mg=function(t,e){if(t.inputs.length===0)throw new Error(`Verification failed because transaction ${e()} has no inputs.`);if(t.outputs.length===0)throw new Error(`Verification failed because transaction ${e()} has no outputs.`);let i=new Set;for(let r=0;r<t.inputs.length;r++){let s=t.inputs[r],o=Ge(s.sourceOutputIndex,`Input ${r} sourceOutputIndex`);Ge(s.sequence??4294967295,`Input ${r} sequence`);let c=Oi(s.sourceTXID??s.sourceTransaction?.id("hex"),`Input ${r} sourceTXID`);if(/^0{64}$/.test(c)&&o===4294967295)throw new Error(`Verification failed because unmined transaction ${e()} contains a coinbase input.`);let u=`${c}:${o}`;if(i.has(u))throw new Error(`Verification failed because transaction ${e()} spends outpoint ${u} more than once.`);i.add(u)}a(this,j,cc).call(this,t)},bg=function(t,e,i){if(i.scriptsOnly){!i.verifiedTransactions.has(t)&&!i.queuedTransactions.has(t)&&(i.txQueue.push(t),i.queuedTransactions.add(t));return}!i.verifiedTxids.has(e)&&!i.queuedTxids.has(e)&&(i.txQueue.push(t),i.queuedTxids.add(e))},wg=function(t,e,i,r){let s=0,o={hashOutputsSingle:new Map};for(let c=0;c<t.inputs.length;c++){let u=t.inputs[c];if(typeof u.sourceTransaction!="object")throw new TypeError(`Verification failed because the input at index ${c} of transaction ${i()} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`);if(typeof u.unlockingScript!="object")throw new TypeError(`Verification failed because the input at index ${c} of transaction ${i()} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);let f=u.sourceTransaction,d=f.outputs[u.sourceOutputIndex];if(d==null)throw new RangeError(`Verification failed because input ${c} of transaction ${i()} references a source output that does not exist.`);s=ds(s,sn(d.satoshis,`Input ${c} source amount`),"Transaction input total");let l=f.id("hex");if(!r.scriptsOnly&&u.sourceTXID!==void 0&&Oi(u.sourceTXID,`Input ${c} sourceTXID`)!==l)throw new Error(`Verification failed because input ${c} of transaction ${i()} does not reference its supplied source transaction.`);let p=r.scriptsOnly&&u.sourceTXID!==void 0?u.sourceTXID:f.id("hex");if(a(this,j,bg).call(this,f,p,r),u.sourceTXID??(u.sourceTXID=p),!e&&!new xo({sourceTXID:u.sourceTXID,sourceOutputIndex:u.sourceOutputIndex,lockingScript:d.lockingScript,sourceSatoshis:d.satoshis??0,transactionVersion:t.version,otherInputs:[],allInputs:t.inputs,unlockingScript:u.unlockingScript,inputSequence:u.sequence??4294967295,inputIndex:c,outputs:t.outputs,lockTime:t.lockTime,memoryLimit:r.memoryLimit,sigHashCache:o}).validateJavaScript())return{valid:!1,inputTotal:s}}return{valid:!0,inputTotal:s}},cc=function(t){let e=0;for(let i=0;i<t.outputs.length;i++)e=ds(e,sn(t.outputs[i].satoshis,`Output ${i} amount`),"Transaction output total");return e},yg=async function(t,e){if(t.length===0||e===void 0)return;let i=e.verifyScriptsBatch===void 0?await Promise.all(t.map(async o=>await e.verifyScripts(o))):await e.verifyScriptsBatch(t);if(!Array.isArray(i)||i.length!==t.length)throw new Error("Script verifier returned an invalid batch result count");let r=[];for(let o=0;o<i.length;o++){if(!Object.prototype.hasOwnProperty.call(i,o)||typeof i[o]!="boolean")throw new TypeError("Script verifier returned a non-boolean verdict");r.push(i[o])}let s=r.findIndex(o=>!o);if(s>=0)throw new Error(`Script verification failed for transaction ${t[s].tx.id("hex")}`)},xg=function(t,e,i){return i.scriptsOnly?i.verifiedTransactions.has(t):i.verifiedTxids.has(e())},Pi=function(t=!1){let e=new Map,i=[this];e.set(this,new oe(this.version,[],[],this.lockTime));for(let s=0;s<i.length;s++){let o=i[s],c=e.get(o);if(c===void 0)throw new Error("Transaction snapshot is incomplete");c.version=o.version,c.lockTime=o.lockTime,c.merklePath=o.merklePath===void 0?void 0:new Ei(o.merklePath.blockHeight,o.merklePath.path.map(u=>u.map(f=>({...f})))),c.outputs=Array.from(o.outputs,u=>u==null?u:{satoshis:u.satoshis,lockingScript:new Le([],Uint8Array.from(u.lockingScript.toUint8Array()),void 0,!1),change:u.change}),c.inputs=Array.from(o.inputs,u=>{let f;return u.sourceTransaction!==void 0&&(f=e.get(u.sourceTransaction),f===void 0&&(f=new oe(u.sourceTransaction.version,[],[],u.sourceTransaction.lockTime),e.set(u.sourceTransaction,f),i.push(u.sourceTransaction))),{sourceTransaction:f,sourceTXID:u.sourceTXID,sourceOutputIndex:u.sourceOutputIndex,unlockingScript:u.unlockingScript===void 0?void 0:new Ue([],Uint8Array.from(u.unlockingScript.toUint8Array()),void 0,!1),unlockingScriptTemplate:t?u.unlockingScriptTemplate:void 0,sequence:u.sequence}})}let r=e.get(this);if(r===void 0)throw new Error("Transaction snapshot is incomplete");return r},uc=function(t,e,i,r,s){if(this.version!==t.version||this.lockTime!==t.lockTime||this.inputs.length!==t.inputs.length||this.outputs.length!==t.outputs.length)return!1;for(let o=0;o<this.inputs.length;o++){let c=this.inputs[o],u=t.inputs[o];if(c!==e[o]||c.sourceTransaction!==i[o]||c.unlockingScriptTemplate!==r[o]||c.sourceTXID!==u.sourceTXID||c.sourceOutputIndex!==u.sourceOutputIndex||c.sequence!==u.sequence||!ed(c.unlockingScript?.toUint8Array(),u.unlockingScript?.toUint8Array()))return!1;let f=c.sourceTransaction?.outputs[c.sourceOutputIndex],d=u.sourceTransaction?.outputs[u.sourceOutputIndex];if(f==null||d==null){if(f!==d)return!1}else if(!Object.is(f.satoshis,d.satoshis)||!ed(f.lockingScript.toUint8Array(),d.lockingScript.toUint8Array()))return!1}for(let o=0;o<this.outputs.length;o++){let c=this.outputs[o],u=t.outputs[o];if(c!==s[o]||!Object.is(c.satoshis,u.satoshis)||c.change!==u.change||!ed(c.lockingScript.toUint8Array(),u.lockingScript.toUint8Array()))return!1}return!0},Sg=async function(t,e,i){let{feeModel:r,memoryLimit:s,selectedVerifier:o,verifierQueue:c}=i;a(this,j,mg).call(this,t,e),await this.verifyTransactionFee(t,r,e);let u={tx:t,blockHeight:Fy,consensus:!0,...s===void 0?{}:{memoryLimit:s}},f=o!==void 0&&(s===void 0||o.supportsMemoryLimit===!0)&&(o.shouldVerifyScripts?.(u)??!0),d=p=>a(this,j,wg).call(this,t,p,e,i),l=!f&&i.scriptWork!==void 0?i.scriptWork.work.inputs(i.scriptWork,u,d):d(f);return!l.valid||(f&&c.push(u),a(this,j,cc).call(this,t)>l.inputTotal)?!1:(i.scriptsOnly?i.verifiedTransactions.add(t):i.verifiedTxids.add(e()),!0)},Ig=async function(t,e,i,r,s){let o=t==="scripts only",c=r??Da(),u=s!==void 0&&c!==void 0?eg(s,c):c;o||this.materializeSourceTXIDs();let f=new Set,d=new Set,l=[this],p=new Set;o||p.add(this.id("hex"));let m=new Set(l),g=[],w={scriptsOnly:o,memoryLimit:i,txQueue:l,queuedTransactions:m,queuedTxids:p,verifiedTransactions:d,verifiedTxids:f,feeModel:e,selectedVerifier:u,verifierQueue:g,scriptWork:s},S=0;for(;S<l.length;){let C=l[S++],E,A=()=>(E??(E=C.id("hex")),E);if(!a(this,j,xg).call(this,C,A,w)&&!await a(this,j,gg).call(this,C,o,t,A,d,f)&&!await a(this,j,Sg).call(this,C,A,w))return!1}return await a(this,j,yg).call(this,g,u),!0},vg=function(t){let e=[],i=new Map,r=new Map,s=[],o=new Set,c=new Set,u=[{tx:this,expanded:!1}];for(;u.length>0;){let f=u.pop();if(f!=null){if(f.expanded){a(this,j,Ag).call(this,f.tx,o,s,e,i,r);continue}a(this,j,Eg).call(this,f.tx,t,c,u)}}return{bumps:e,txs:s}},Ag=function(t,e,i,r,s,o){let c=t.id("hex");if(e.has(c))return;let u={tx:t};t.merklePath!=null&&(u.pathIndex=a(this,j,kg).call(this,t.merklePath,r,s,o)),e.add(c),i.push(u)},Eg=function(t,e,i,r){let s=t.id("hex");if(!i.has(s)&&(i.add(s),r.push({tx:t,expanded:!0}),t.merklePath==null))for(let o of t.inputs){let c=o.sourceTransaction;if(c!=null)r.push({tx:c,expanded:!1});else if(e===!1)throw new Error("A required source transaction is missing!")}},kg=function(t,e,i,r){let s=i.get(t);if(s!==void 0)return s;let o=`${t.blockHeight}:${t.computeRoot()}`,c=r.get(o);if(c!==void 0)return e[c].combine(t),i.set(t,c),c;let u=e.length;return e.push(t),i.set(t,u),r.set(o,u),u},Tg=function(t,e,i){let r;if(t instanceof ht){r=e.map(o=>o.toBinaryUint8Array());let s=16;for(let o of r)s+=o.length;for(let o of i)s+=o.tx.toUint8Array().length+10;t.reserve(s)}return r},Og=async function(t,e){let i={description:t,inputs:[],outputs:[],lockTime:this.lockTime,version:this.version};this.materializeSourceTXIDs();let r=new Ir;for(let s=0;s<this.inputs.length;s++){let o=this.inputs[s];if(o.sourceTransaction==null)throw new Error("All inputs must have a sourceTransaction when using completeWithWallet");r.mergeTransaction(o.sourceTransaction),i.inputs.push(await a(this,j,Pg).call(this,o,s,e))}return this.inputs.length>0&&(i.inputBEEF=r.toUint8Array()),i.outputs=this.outputs.map(s=>({satoshis:s.satoshis,lockingScript:s.lockingScript.toHex(),outputDescription:"Output from source transaction"})),Array.isArray(this.metadata?.labels)&&(i.labels=this.metadata.labels),i},Pg=async function(t,e,i){let r={outpoint:`${t.sourceTransaction.id("hex")}.${t.sourceOutputIndex}`,inputDescription:"Input from source transaction",sequenceNumber:t.sequence};if(!i){if(t.unlockingScript==null)throw new Error("All inputs must have an unlockingScript when using completeWithWallet");return r.unlockingScript=t.unlockingScript.toHex(),r}if(t.unlockingScriptTemplate!=null)r.unlockingScriptLength=await t.unlockingScriptTemplate.estimateLength(this,e);else if(t.unlockingScript!=null)r.unlockingScript=t.unlockingScript.toHex();else throw new Error(`Input ${e} must have either an unlockingScript or unlockingScriptTemplate`);return r},G(oe,Mn);var Me=oe;var ei=class extends Error{constructor(e,i){super(`The ${e} parameter must be ${i??"valid."}`);b(this,"parameter");b(this,"code");b(this,"isError",!0);this.parameter=e,this.code=6,this.name=this.constructor.name}},ut=ei;var Rg=globalThis.Buffer,od=typeof Rg?.compare=="function"?Rg.compare:void 0,fc=globalThis.SharedArrayBuffer,Vy=16*1024*1024,Bi=class{constructor(){b(this,"cached")}get(t){let e=this.cached;if(!(e==null||!(t instanceof Uint8Array)||t.length!==e.bytes.length||od==null||fc!=null&&t.buffer instanceof fc||od(t,e.bytes)!==0))return e.value}set(t,e){t instanceof Uint8Array&&t.length<=Vy&&od!=null&&!(fc!=null&&t.buffer instanceof fc)&&(this.cached={bytes:new Uint8Array(t),value:e})}};var Dn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ng="0123456789abcdef";function Ye(n){let t="";for(let e=0;e<n.length;e++){let i=n[e];t+=Ng[i>>4]+Ng[i&15]}return t}function hs(n){if(typeof n!="string"||n.length%2!==0||!/^[0-9a-f]*$/iu.test(n))throw new TypeError("Invalid hexadecimal byte string");let t=Array.from({length:n.length/2});for(let e=0;e<t.length;e++)t[e]=Number.parseInt(n.slice(e*2,e*2+2),16);return t}function Bg(n){let t="";for(let e=0;e<n.length;e+=3){let i=n[e],r=e+1<n.length?n[e+1]:0,s=e+2<n.length?n[e+2]:0;t+=Dn[i>>2],t+=Dn[(i&3)<<4|r>>4],t+=e+1<n.length?Dn[(r&15)<<2|s>>6]:"=",t+=e+2<n.length?Dn[s&63]:"="}return t}function dc(n){if(typeof n!="string"||n.length%4!==0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(n))throw new TypeError("Invalid canonical base64 string");if(n.endsWith("==")&&(Dn.indexOf(n[n.length-3])&15)!==0)throw new TypeError("Invalid canonical base64 string");if(n.endsWith("=")&&!n.endsWith("==")&&(Dn.indexOf(n[n.length-2])&3)!==0)throw new TypeError("Invalid canonical base64 string");let t=[];for(let e=0;e<n.length;e+=4){let i=Dn.indexOf(n[e]),r=Dn.indexOf(n[e+1]),s=n[e+2]==="="?0:Dn.indexOf(n[e+2]),o=n[e+3]==="="?0:Dn.indexOf(n[e+3]);t.push(i<<2|r>>4),n[e+2]!=="="&&t.push((r&15)<<4|s>>2),n[e+3]!=="="&&t.push((s&3)<<6|o)}return t}var Hn,_i,ad=class{constructor(t){G(this,Hn);b(this,"bytes");b(this,"pos",0);this.bytes=Uint8Array.from(t)}read(t){let e=a(this,Hn,_i).call(this,t);return this.bytes.slice(e,this.pos)}readView(t){let e=a(this,Hn,_i).call(this,t);return this.bytes.subarray(e,this.pos)}readReverse(t){return this.read(t).reverse()}readUInt8(){return this.bytes[a(this,Hn,_i).call(this,1)]}readUInt16LE(){let t=a(this,Hn,_i).call(this,2);return this.bytes[t]|this.bytes[t+1]<<8}readUInt32LE(){let t=a(this,Hn,_i).call(this,4);return(this.bytes[t]|this.bytes[t+1]<<8|this.bytes[t+2]<<16|this.bytes[t+3]<<24)>>>0}readUInt64LE(){let t=a(this,Hn,_i).call(this,8),e=0n;for(let i=7;i>=0;i--)e=e<<8n|BigInt(this.bytes[t+i]);return Number(e)}readVarInt(){let t=this.readUInt8();if(t<253)return t;if(t===253){let r=this.readUInt16LE();if(r<253)throw new Error("non-canonical varInt");return r}if(t===254){let r=this.readUInt32LE();if(r<=65535)throw new Error("non-canonical varInt");return r}let e=a(this,Hn,_i).call(this,8),i=0n;for(let r=7;r>=0;r--)i=i<<8n|BigInt(this.bytes[e+r]);if(i<=0xffffffffn)throw new Error("non-canonical varInt");if(i>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("varInt is too large");return Number(i)}eof(){return this.pos===this.bytes.length}};Hn=new WeakSet,_i=function(t){let e=this.pos;if(!Number.isSafeInteger(t)||t<0||e+t>this.bytes.length)throw new RangeError("Serialized BEEF exceeds available data");return this.pos+=t,e};var Ky=4294967295;function lc(n,t){return Math.floor(n/2**t)}function zy(n){return n%2===0?n+1:n-1}function Or(n,t){return Ye(zt(hs((n??"")+(t??"")).reverse()).reverse())}function cd(n,t,e,i,r,s){let o=`${t}:${e}`;if(r.has(o))return r.get(o);let c=t<i.length?i[t].get(e):void 0;if(c!==void 0||t===0)return r.set(o,c),c;let u=t-1,f=e*2,d=cd(n,u,f,i,r,s);if(d?.hash==null||d.hash===""){r.set(o,void 0);return}let l=cd(n,u,f+1,i,r,s);if(l?.hash==null){if(l?.duplicate===!0||n.length===1&&f===lc(s,u))return c={offset:e,hash:Or(d.hash,d.hash)},r.set(o,c),c;r.set(o,void 0);return}return c={offset:e,hash:l.duplicate===!0?Or(d.hash,d.hash):Or(l.hash,d.hash)},r.set(o,c),c}function Xy(n,t,e,i,r,s){if(typeof t!="string"&&(t=n[0].find(f=>!!f.hash)?.hash),typeof t!="string")throw new TypeError("Transaction ID is undefined");let o=n[0].find(f=>f.hash===t)?.offset;if(o===void 0)throw new Error("Transaction ID not found in Merkle Path");if(n.length===1&&n[0].length===1)return t;let c=Math.max(n.length,32-Math.clz32(s)),u=t;for(let f=0;f<c;f++){let d=lc(o,f),l=`${f}:${d}`,p=r.get(l);if(p!==void 0){if(p!==u)throw new Error("Mismatched roots");let w=r.get(`${c}:0`);if(w===void 0)throw new Error("Mismatched roots");return w}r.set(l,u);let m=zy(d),g=cd(n,f,m,e,i,s);if(g==null){if(n.length===1&&d===lc(s,f)){u=Or(u,u);continue}throw new Error(`Missing hash for index ${o} at height ${f}`)}g.duplicate===!0?u=Or(u,u):u=m%2===1?Or(g.hash,u):Or(u,g.hash)}return r.set(`${c}:0`,u),u}function jy(n){n.readVarInt();let t=n.readUInt8(),e=Array.from({length:t},()=>[]);for(let u=0;u<t;u++){let f=n.readVarInt();for(let d=0;d<f;d++){let l=n.readVarInt(),p=n.readUInt8();e[u].push((p&1)===1?{offset:l,duplicate:!0}:{offset:l,hash:Ye(n.read(32).reverse())})}e[u].sort((d,l)=>d.offset-l.offset)}if(e.length===0||e.length>32||e[0].length===0)throw new Error("Invalid Merkle Path height");for(let u=0;u<e.length;u++){let f=new Set,d=lc(Ky,u);for(let l of e[u]){if(!Number.isSafeInteger(l.offset)||l.offset<0||l.offset>d)throw new Error("Invalid Merkle Path offset");if(f.has(l.offset))throw new Error("Duplicate Merkle Path offset");f.add(l.offset)}}let i=e.map(u=>new Map(u.map(f=>[f.offset,f]))),r=new Map,s=new Map,o=e[0].reduce((u,f)=>Math.max(u,f.offset),0),c;for(let u of e[0]){let f=Xy(e,u.hash,i,r,s,o);if(c===void 0)c=f;else if(c!==f)throw new Error("Mismatched roots")}return new Set(e[0].flatMap(u=>u.hash===void 0?[]:[u.hash]))}function _g(n){let t=n.pos,e=n.readUInt32LE(),i=n.readVarInt(),r=[],s=new Set;for(let l=0;l<i;l++){let p=Ye(n.readReverse(32));s.add(p);let m=n.readUInt32LE(),g=n.readVarInt(),w=n.readView(g),S=n.readUInt32LE();r.push({sourceTXID:p,sourceOutputIndex:m,unlockingScript:w,sequence:S})}let o=n.readVarInt(),c=[];for(let l=0;l<o;l++){let p=n.readUInt64LE(),m=n.readVarInt();c.push({satoshis:p,lockingScript:n.readView(m)})}let u=n.readUInt32LE(),f=n.bytes.subarray(t,n.pos),d=Ye(zt(f).reverse());return{txid:d,transaction:{txid:d,version:e,inputs:r,outputs:c,lockTime:u},inputTxids:Array.from(s),txidOnly:!1}}function Gy(n,t){if(t===4022206466){let r=n.readUInt8();if(r===ze.TXID_ONLY)return{txid:Ye(n.readReverse(32)),inputTxids:[],txidOnly:!0};let s=r===ze.RAWTX_AND_BUMP_INDEX?n.readVarInt():void 0;return{..._g(n),bumpIndex:s}}let e=_g(n),i=n.readUInt8()===0?void 0:n.readVarInt();return{...e,bumpIndex:i}}function Cg(n){let t=new ad(n),e=t.readUInt32LE(),i;if(e===16843009&&(i=Ye(t.readReverse(32)),e=t.readUInt32LE()),e!==4022206465&&e!==4022206466)throw new Error("Invalid BEEF version");let r=t.readVarInt(),s=[];for(let u=0;u<r;u++)s.push(jy(t));let o=t.readVarInt(),c=[];for(let u=0;u<o;u++)c.push(Gy(t,e));if(!t.eof())throw new Error("Serialized BEEF contains trailing data");return{atomicTxid:i,bumps:s,entries:c}}function ps(n){let{atomicTxid:t,entries:e}=Cg(n),i=new Map;for(let r of e){if(i.has(r.txid))throw new Error("BEEF contains duplicate transactions");i.set(r.txid,r.transaction)}for(let r of e)if(r.transaction!==void 0)for(let s of r.transaction.inputs){let c=i.get(s.sourceTXID)?.outputs[s.sourceOutputIndex];c!==void 0&&(s.sourceSatoshis=c.satoshis)}return{atomicTxid:t,transactions:i}}function Fo(n,t=!1){let{atomicTxid:e,bumps:i,entries:r}=Cg(n);if(e===void 0)throw new Error("Atomic BEEF subject is missing");let s=new Map(r.map(f=>[f.txid,f]));if(s.size!==r.length)throw new Error("Atomic BEEF contains duplicate transactions");let o=s.get(e);if(o?.transaction===void 0)throw new Error("Atomic BEEF subject is missing");let c=new Set,u=[o];for(;u.length>0;){let f=u.pop();if(!(c.has(f)||(c.add(f),(f.bumpIndex===void 0?void 0:i[f.bumpIndex])?.has(f.txid)===!0||f.txidOnly)))for(let p of f.inputTxids){let m=s.get(p);if(m===void 0){if(t)continue;throw new Error("Atomic BEEF omits a required dependency")}u.push(m)}}if(c.size!==r.length)throw new Error("Atomic BEEF contains unrelated transaction data");for(let f of o.transaction.inputs){let l=s.get(f.sourceTXID)?.transaction?.outputs[f.sourceOutputIndex];l!==void 0&&(f.sourceSatoshis=l.satoshis)}return o.transaction}var gs=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,Yy=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;function Zy(n,t){let e=1n;for(;t>0n;)(t&1n)!==0n&&(e=e*n%gs),n=n*n%gs,t>>=1n;return e}function hc(n){if(!/^0[23][0-9a-f]{64}$/iu.test(n))return!1;let t=BigInt(`0x${n.slice(2)}`);if(t>=gs)return!1;let e=(t*t*t+7n)%gs,i=Zy(e,gs+1n>>2n);return i*i%gs===e}function Jy(n,t,e){let i=0n;for(let r=t;r<t+e;r++)i=i<<8n|BigInt(n[r]);return i}function ms(n){if(n.length<8||n.length>72||n[0]!==48||n[1]!==n.length-2)return!1;let t=2;for(let e=0;e<2;e++){if(n[t++]!==2)return!1;let i=n[t++];if(i<1||i>33||t+i>n.length)return!1;let r=n[t];if((r&128)!==0||i>1&&r===0&&(n[t+1]&128)===0)return!1;let s=Jy(n,t,i);if(s===0n||s>=Yy)return!1;t+=i}return t===n.length}var Ci=4294967295,ud=1e5,xn=1e3,Lg=100,Ug=32,Mg=new Bi,Dg=new Bi;function yt(n,t){throw new ut(n,t)}function gt(n,t){if(n==null||typeof n!="object"||Array.isArray(n))return yt(t,"a plain object");let e=Object.getPrototypeOf(n);if(e!==null&&e!==Object.prototype)return yt(t,"a plain object");let i=Reflect.ownKeys(n);if(i.length>ud)return yt(t,`an object with at most ${ud} properties`);for(let r of i){if(typeof r!="string"||gn(r))return yt(t,"an object with safe string keys");let s=Object.getOwnPropertyDescriptor(n,r);if(s==null||!("value"in s))return yt(`${t}.${r}`,"a data property")}return n}function Ne(n,t,e=ud){if(n===void 0)return[];if(!Array.isArray(n))return yt(t,"an array");if(e!==void 0&&n.length>e)return yt(t,`an array of at most ${e} items`);let i=Object.getOwnPropertyDescriptors(n),r=new Set(["length",...Array.from({length:n.length},(s,o)=>String(o))]);if(Object.getOwnPropertySymbols(n).length!==0||Object.keys(i).length!==r.size||Object.keys(i).some(s=>!r.has(s))||Object.values(i).some(s=>s.get!=null||s.set!=null))return yt(t,"an accessor-free dense array without extra properties");for(let s=0;s<n.length;s++)if(!Object.prototype.hasOwnProperty.call(n,s))return yt(t,"a dense array");return n}function $g(n){let t=Ne(n,"sendWith",xn).map((e,i)=>Ui(e,`sendWith[${i}]`,64,64));return new Set(t).size!==t.length?yt("sendWith","unique transaction IDs"):t}function $n(n,t,e,i=268435456){if(n instanceof Uint8Array)return n.length>i?yt(t,`at most ${i} bytes`):e!==void 0&&n.length!==e?yt(t,`exactly ${e} bytes`):n;if(!Array.isArray(n))return yt(t,"an array of bytes");if(n.length>i)return yt(t,`at most ${i} bytes`);for(let r=0;r<n.length;r++)if(!Object.prototype.hasOwnProperty.call(n,r)||!Number.isInteger(n[r])||n[r]<0||n[r]>255)return yt(t,"a dense array of bytes");return e!==void 0&&n.length!==e?yt(t,`exactly ${e} bytes`):n}function ws(n,t,e){return n===void 0?e:typeof n!="boolean"?yt(t,"a boolean"):n}function He(n,t){let e=Ui(n,t,66,66);return hc(e)?e:yt(t,"a valid compressed secp256k1 public key")}function fd(n,t){return n==="self"||n==="anyone"?n:He(n,t)}function dd(n,t="protocolID"){if(!Array.isArray(n)||n.length!==2)return yt(t,"a [securityLevel, protocolName] tuple");let e=ee(n[0],`${t}[0]`,void 0,0,2),i=ae(n[1],`${t}[1]`,5,400);return[e,i]}function Li(n,t=!0){let e=ws(n.privileged,"privileged",!1),i=Rr(n.privilegedReason,"privilegedReason",5,50);e&&i===void 0&&yt("privilegedReason","a value when 'privileged' is true"),t&&ws(n.seekPermission,"seekPermission",!0)}function Pr(n,t="args"){let e=gt(n,t);dd(e.protocolID),ae(e.keyID,"keyID",1,800),e.counterparty!==void 0&&fd(e.counterparty,"counterparty"),Li(e)}function qg(n){let t=yc(n,"outpoint"),[e,i]=t.split(".");return{txid:e,vout:Number(i)}}function ni(n,t="value"){return ws(n,t,!0)}function be(n,t="value"){return ws(n,t,!1)}function Rr(n,t,e,i){if(n!==void 0)return ae(n,t,e,i)}function Qy(n,t,e){if(n===void 0||!Number.isSafeInteger(n)||n<0||n>21e14)throw new ut(t,"a valid number of satoshis");if(e!==void 0&&n<e)throw new ut(t,`at least ${e} satoshis.`);return n}function ee(n,t,e,i,r){if(n===void 0){if(e!==void 0)return e;throw new ut(t,"a valid integer")}if(!Number.isSafeInteger(n))throw new ut(t,"a safe integer");if(n=Number(n),i!==void 0&&n<i)throw new ut(t,`at least ${i} length.`);if(r!==void 0&&n>r)throw new ut(t,`no more than ${r} length.`);return n}function tx(n,t){return ee(n,t,0,0)}function ae(n,t,e,i){if(typeof n!="string")throw new ut(t,"a string");let r=Se(n).length;if(e!==void 0&&r<e)throw new ut(t,`at least ${e} length.`);if(i!==void 0&&r>i)throw new ut(t,`no more than ${i} length.`);return n}function ex(n){if(n!==void 0)return pc(n)}function pc(n){return pd(n,"basket",1,300)}function ld(n){return pd(n,"label",1,300)}function hd(n){return pd(n,"tag",1,300)}function pd(n,t,e,i){if(typeof n!="string")throw new ut(t,"a string");n=n.trim().toLowerCase();let r=Se(n).length;if(e!==void 0&&r<e)throw new ut(t,`at least ${e} length.`);if(i!==void 0&&r>i)throw new ut(t,`no more than ${i} length.`);return n}function Hg(n,t,e,i){if(n!==void 0)return on(n,t,e,i)}function bs(n){throw new ut(n,"valid base64 string")}function nx(n,t){let e=0;for(let i=0;i<n.length;i++){let r=n.codePointAt(i)??0,s=r>=65&&r<=90||r>=97&&r<=122,o=r>=48&&r<=57;s||o||r===43||r===47||((r!==61||i<n.length-2)&&bs(t),e++)}return e}function ix(n,t,e){t>2&&bs(e),t>0&&n.length%4!==0&&bs(e);let i=n.length%4;i!==0&&i!==4-t&&bs(e)}function rx(n,t,e,i){if(e!==void 0&&n<e)throw new ut(t,`at least ${e} bytes`);if(i!==void 0&&n>i)throw new ut(t,`no more than ${i} bytes`)}function on(n,t,e,i){typeof n!="string"&&bs(t),n=n.trim(),n.length===0&&bs(t);let r=nx(n,t);ix(n,r,t);let s=n.length-r,o=Math.floor(s*3/4);return rx(o,t,e,i),n}function sx(n,t,e,i){if(n!==void 0)return Ui(n,t,e,i)}var ox=/^[0-9a-f]+$/,ax=/^[0-9A-Fa-f]+$/;function Ui(n,t,e,i){if(typeof n!="string")throw new ut(t,"a hexadecimal string");if(n=n.trim(),n.length%2===1)throw new ut(t,`even length, not ${n.length}.`);let r=ox.test(n);if(!r&&!ax.test(n))throw new ut(t,"hexadecimal string.");if(e!==void 0&&n.length<e)throw new ut(t,`at least ${e} length.`);if(i!==void 0&&n.length>i)throw new ut(t,`no more than ${i} length.`);return r?n:n.toLowerCase()}function Fg(n,t){let e=Ui(n,t);return ms(hs(e))?e:yt(t,"a canonical DER-encoded ECDSA signature")}function cx(n){if(gt(n,"input"),n.unlockingScript===void 0&&n.unlockingScriptLength===void 0)throw new ut("unlockingScript, unlockingScriptLength","at least one valid value.");let t=sx(n.unlockingScript,"unlockingScript"),e=n.unlockingScriptLength??(t==null?0:t.length/2);if(ee(e,"unlockingScriptLength",void 0,0),t&&e!==t.length/2)throw new ut("unlockingScriptLength","length unlockingScript if both valid.");return{outpoint:qg(n.outpoint),inputDescription:ae(n.inputDescription,"inputDescription",5,2e3),unlockingScript:t,unlockingScriptLength:e,sequenceNumber:ee(n.sequenceNumber,"sequenceNumber",Ci,0,Ci)}}function ux(n){return gt(n,"output"),{lockingScript:Ui(n.lockingScript,"lockingScript"),satoshis:Qy(n.satoshis,"satoshis"),outputDescription:ae(n.outputDescription,"outputDescription",5,2e3),basket:ex(n.basket),customInstructions:Rr(n.customInstructions,"customInstructions"),tags:Ne(n.tags,"tags").map(e=>hd(e))}}function fx(n){n!==void 0&>(n,"options");let t=n??{};return t.trustSelf!==void 0&&t.trustSelf!=="known"&&yt("trustSelf","undefined or 'known'"),{signAndProcess:ni(t.signAndProcess,"signAndProcess"),acceptDelayedBroadcast:ni(t.acceptDelayedBroadcast,"acceptDelayedBroadcast"),trustSelf:t.trustSelf,knownTxids:Ne(t.knownTxids,"knownTxids").map(i=>Ui(i,"knownTxids",64,64)),returnTXIDOnly:be(t.returnTXIDOnly,"returnTXIDOnly"),noSend:be(t.noSend,"noSend"),noSendChange:Ne(t.noSendChange,"noSendChange").map(i=>qg(i)),sendWith:$g(t.sendWith),randomizeOutputs:ni(t.randomizeOutputs,"randomizeOutputs")}}function gc(n,t){gt(n,"args");let e={description:ae(n.description,"description",5,2e3),inputBEEF:n.inputBEEF===void 0?void 0:$n(n.inputBEEF,"inputBEEF"),inputs:Ne(n.inputs,"inputs").map(r=>cx(r)),outputs:Ne(n.outputs,"outputs").map(r=>ux(r)),lockTime:ee(n.lockTime,"lockTime",0,0,Ci),version:ee(n.version,"version",1,0,Ci),labels:Ne(n.labels,"labels").map(r=>ld(r)),options:fx(n.options),logger:t,isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!1,isRemixChange:!1,isSignAction:!1,randomVals:void 0,includeAllSourceTransactions:!1,isTestWerrReviewActions:!1};if(e.inputBEEF!==void 0&&Mg.get(e.inputBEEF)!==!0)try{ps(e.inputBEEF),Mg.set(e.inputBEEF,!0)}catch{throw new ut("inputBEEF","a complete, exactly framed BEEF envelope")}let i=new Set;for(let r of e.inputs){let s=`${r.outpoint.txid.toLowerCase()}.${r.outpoint.vout}`;i.has(s)&&yt("inputs","unique input outpoints"),i.add(s)}return e.isTestWerrReviewActions=e.labels.includes(xx),e.isSendWith=e.options.sendWith.length>0,e.isRemixChange=!e.isSendWith&&e.inputs.length===0&&e.outputs.length===0,e.isNewTx=e.isRemixChange||e.inputs.length>0||e.outputs.length>0,e.isNewTx&&e.options.sendWith.length>=xn&&yt("sendWith",`at most ${xn-1} transaction IDs when the new transaction joins the broadcast set`),e.isSignAction=e.isNewTx&&(!e.options.signAndProcess||e.inputs.some(r=>r.unlockingScript===void 0)),e.isDelayed=e.options.acceptDelayedBroadcast,e.isNoSend=e.options.noSend,e}function dx(n){n!==void 0&>(n,"options");let t=n??{};return{acceptDelayedBroadcast:ni(t.acceptDelayedBroadcast,"acceptDelayedBroadcast"),returnTXIDOnly:be(t.returnTXIDOnly,"returnTXIDOnly"),noSend:be(t.noSend,"noSend"),sendWith:$g(t.sendWith)}}function mc(n){gt(n,"args");let t=gt(n.spends,"spends"),e=Object.create(null);for(let[r,s]of Object.entries(t)){/^(?:0|[1-9]\d*)$/.test(r)||yt("spends key","a canonical input index");let o=ee(Number(r),"spends key",void 0,0,Ci),c=gt(s,`spends.${r}`);e[o]={unlockingScript:Ui(c.unlockingScript,`spends.${r}.unlockingScript`),sequenceNumber:c.sequenceNumber===void 0?void 0:ee(c.sequenceNumber,`spends.${r}.sequenceNumber`,void 0,0,Ci)}}let i={spends:e,reference:on(n.reference,"reference"),options:dx(n.options),isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!0,isRemixChange:!1,isTestWerrReviewActions:!1};return i.isSendWith=i.options.sendWith.length>0,i.options.sendWith.length>=xn&&yt("sendWith",`at most ${xn-1} transaction IDs when the signed transaction joins the broadcast set`),i.isDelayed=i.options.acceptDelayedBroadcast,i.isNoSend=i.options.noSend,i}function bc(n){return gt(n,"args"),{reference:on(n.reference,"reference")}}function lx(n){return n===void 0?void 0:(gt(n,"paymentRemittance"),{derivationPrefix:on(n.derivationPrefix,"derivationPrefix"),derivationSuffix:on(n.derivationSuffix,"derivationSuffix"),senderIdentityKey:He(n.senderIdentityKey,"senderIdentityKey")})}function hx(n){return n===void 0?void 0:(gt(n,"insertionRemittance"),{basket:pc(n.basket),customInstructions:Rr(n.customInstructions,"customInstructions",0,1e3),tags:Ne(n.tags,"tags").map(e=>hd(e))})}function px(n){if(gt(n,"output"),n.protocol!=="basket insertion"&&n.protocol!=="wallet payment")throw new ut("protocol","'basket insertion' or 'wallet payment'");return n.protocol==="wallet payment"?(n.paymentRemittance===void 0||n.insertionRemittance!==void 0)&&yt("output remittance","only paymentRemittance for wallet payment"):(n.insertionRemittance===void 0||n.paymentRemittance!==void 0)&&yt("output remittance","only insertionRemittance for basket insertion"),{outputIndex:tx(n.outputIndex,"outputIndex"),protocol:n.protocol,paymentRemittance:lx(n.paymentRemittance),insertionRemittance:hx(n.insertionRemittance)}}function ii(n){if(n===void 0)return;n=n.trim().toLowerCase(),ae(n,"originator",1,250);let t=n.lastIndexOf(":"),e=n;if(t!==-1){if(n.indexOf(":")!==t)throw new ut("originator","a canonical DNS hostname with an optional port");let r=n.slice(t+1);if(!/^\d{1,5}$/.test(r)||Number(r)>65535)throw new ut("originator","a canonical DNS hostname with an optional port");e=n.slice(0,t)}ae(e,"originator hostname",1,250);let i=e.split(".");for(let r of i)if(ae(r,"originator part",1,63),!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(r))throw new ut("originator","a canonical DNS hostname with an optional port");return e}function wc(n){gt(n,"args");let t={tx:$n(n.tx,"tx"),outputs:Ne(n.outputs,"outputs").map(e=>px(e)),description:ae(n.description,"description",5,2e3),labels:Ne(n.labels,"labels").map(e=>ld(e)),seekPermission:ni(n.seekPermission,"seekPermission")};if(Dg.get(t.tx)!==!0)try{Fo(t.tx),Dg.set(t.tx,!0)}catch{throw new ut("tx","a complete, exactly framed Atomic BEEF transaction")}if(t.outputs.length<1)throw new ut("outputs","at least one output to internalize from the transaction");return t}function gx(n,t){if(n!==void 0)return yc(n,t)}function yc(n,t){if(typeof n!="string")throw new ut(t,"txid as hex string and numeric output index joined with '.'");let e=/^([0-9A-Fa-f]{64})\.(0|[1-9]\d*)$/.exec(n);if(e===null)throw new ut(t,"a 32-byte txid and canonical numeric output index joined with '.'");let i=Ui(e[1],`${t} txid`,64,64),r=ee(Number(e[2]),`${t} vout`,void 0,0,Ci);return`${i}.${r}`}function xc(n){return gt(n,"args"),{basket:pc(n.basket),output:yc(n.output,"output")}}function Sc(n){return gt(n,"args"),{type:on(n.type,"type",32,32),serialNumber:on(n.serialNumber,"serialNumber",32,32),certifier:He(n.certifier,"certifier")}}function Ic(n){return gt(n,"args"),Li(n,!1),{certifiers:Ne(n.certifiers,"certifiers").map(e=>He(e,"certifiers")),types:Ne(n.types,"types").map(e=>on(e,"types",32,32)),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0,0),privileged:be(n.privileged,"privileged"),privilegedReason:Rr(n.privilegedReason,"privilegedReason",5,50),partial:void 0}}function gd(n){let t=gt(n,"fields");for(let e of Object.keys(t))ae(e,"field name",1,50),ae(t[e],`fields.${e}`);return n}function mx(n,t){return n==="certifier"?n:He(n,t)}function bx(n,t){let e=gt(n,t);for(let i of Object.keys(e))ae(i,`${t} field name`,1,50),on(e[i],`${t} field value`);return n}function vc(n){if(gt(n,"args"),Li(n,!1),n.acquisitionProtocol!=="issuance")throw new Error("Only acquire certificate via issuance requests allowed here.");if(n.serialNumber)throw new ut("serialNumber",'valid when acquisitionProtocol is "direct"');if(n.signature)throw new ut("signature",'valid when acquisitionProtocol is "direct"');if(n.revocationOutpoint)throw new ut("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(n.keyringRevealer)throw new ut("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(n.keyringForSubject!=null)throw new ut("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!n.certifierUrl)throw new ut("certifierUrl",'valid when acquisitionProtocol is "issuance"');return{type:on(n.type,"type",32,32),certifier:He(n.certifier,"certifier"),certifierUrl:wx(n.certifierUrl),fields:gd(n.fields),privileged:be(n.privileged,"privileged"),privilegedReason:Rr(n.privilegedReason,"privilegedReason",5,50),subject:""}}function wx(n){let t=ae(n,"certifierUrl",1,2048);if(t!==t.trim())throw new ut("certifierUrl","an exact HTTPS URL without whitespace");let e;try{e=new URL(t)}catch{throw new ut("certifierUrl","an absolute HTTPS URL")}if(e.protocol!=="https:")throw new ut("certifierUrl","an HTTPS URL");if(e.username!==""||e.password!=="")throw new ut("certifierUrl","a URL without credentials");if(e.search!==""||e.hash!=="")throw new ut("certifierUrl","a URL without a query or fragment");let i=e.hostname.toLowerCase();if(i==="localhost"||i.endsWith(".localhost")||i==="[::1]"||/^\d+(?:\.\d+){0,3}$/.test(i)||i.includes(":"))throw new ut("certifierUrl","a public DNS hostname");let r=i.split(".");if(r.length<2||r.some(s=>!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(s)))throw new ut("certifierUrl","a public DNS hostname");return t.replace(/\/+$/,"")}function Ac(n){if(gt(n,"args"),Li(n,!1),n.acquisitionProtocol!=="direct")throw new Error("Only acquire direct certificate requests allowed here.");if(!n.serialNumber)throw new ut("serialNumber",'valid when acquisitionProtocol is "direct"');if(!n.signature)throw new ut("signature",'valid when acquisitionProtocol is "direct"');if(!n.revocationOutpoint)throw new ut("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!n.keyringRevealer)throw new ut("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(n.keyringForSubject==null)throw new ut("keyringForSubject",'valid when acquisitionProtocol is "direct"');return{type:on(n.type,"type",32,32),serialNumber:on(n.serialNumber,"serialNumber",32,32),certifier:He(n.certifier,"certifier"),revocationOutpoint:yc(n.revocationOutpoint,"revocationOutpoint"),fields:gd(n.fields),signature:Fg(n.signature,"signature"),keyringRevealer:mx(n.keyringRevealer,"keyringRevealer"),keyringForSubject:bx(n.keyringForSubject,"keyringForSubject"),privileged:be(n.privileged,"privileged"),privilegedReason:Rr(n.privilegedReason,"privilegedReason",5,50),subject:""}}function Ec(n){gt(n,"args"),gt(n.certificate,"certificate"),Li(n,!1),n.certificate.fields!==void 0&&gd(n.certificate.fields);let t={type:Hg(n.certificate.type,"certificate.type",32,32),serialNumber:Hg(n.certificate.serialNumber,"certificate.serialNumber",32,32),certifier:n.certificate.certifier===void 0?void 0:He(n.certificate.certifier,"certificate.certifier"),subject:n.certificate.subject===void 0?void 0:He(n.certificate.subject,"certificate.subject"),revocationOutpoint:gx(n.certificate.revocationOutpoint,"certificate.revocationOutpoint"),signature:n.certificate.signature===void 0?void 0:Fg(n.certificate.signature,"certificate.signature"),fieldsToReveal:Ne(n.fieldsToReveal,"fieldsToReveal").map(e=>ae(e,`fieldsToReveal ${e}`,1,50)),verifier:He(n.verifier,"verifier"),privileged:be(n.privileged,"privileged"),privilegedReason:Rr(n.privilegedReason,"privilegedReason",5,50)};return t.fieldsToReveal.length>Lg&&yt("fieldsToReveal",`at most ${Lg} fields`),new Set(t.fieldsToReveal).size!==t.fieldsToReveal.length&&yt("fieldsToReveal","unique field names"),t}function kc(n){return gt(n,"args"),{identityKey:He(n.identityKey,"identityKey"),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0,0),seekPermission:ni(n.seekPermission,"seekPermission")}}function yx(n){let t=gt(n,"attributes"),e=Object.keys(t);(e.length<1||e.length>Ug)&&yt("attributes",`an object containing 1-${Ug} fields`);for(let i of e)ae(i,`field name ${i}`,1,50),ae(t[i],`attributes.${i}`,1,500);return n}function Tc(n){return gt(n,"args"),{attributes:yx(n.attributes),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0,0),seekPermission:ni(n.seekPermission,"seekPermission")}}function Oc(n){gt(n,"args");let t;if(n.tagQueryMode===void 0||n.tagQueryMode==="any")t="any";else if(n.tagQueryMode==="all")t="all";else throw new ut("tagQueryMode","undefined, 'any', or 'all'");return n.include!==void 0&&n.include!=="locking scripts"&&n.include!=="entire transactions"&&yt("include","undefined, 'locking scripts', or 'entire transactions'"),{basket:pc(n.basket),tags:Ne(n.tags,"tags").map(i=>hd(i)),tagQueryMode:t,includeLockingScripts:n.include==="locking scripts",includeTransactions:n.include==="entire transactions",includeCustomInstructions:be(n.includeCustomInstructions,"includeCustomInstructions"),includeTags:be(n.includeTags,"includeTags"),includeLabels:be(n.includeLabels,"includeLabels"),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0),seekPermission:ni(n.seekPermission,"seekPermission"),knownTxids:[]}}function Pc(n){gt(n,"args");let t;if(n.labelQueryMode===void 0||n.labelQueryMode==="any")t="any";else if(n.labelQueryMode==="all")t="all";else throw new ut("labelQueryMode","undefined, 'any', or 'all'");return{labels:Ne(n.labels,"labels").map(i=>ld(i)),labelQueryMode:t,includeLabels:be(n.includeLabels,"includeLabels"),includeInputs:be(n.includeInputs,"includeInputs"),includeInputSourceLockingScripts:be(n.includeInputSourceLockingScripts,"includeInputSourceLockingScripts"),includeInputUnlockingScripts:be(n.includeInputUnlockingScripts,"includeInputUnlockingScripts"),includeOutputs:be(n.includeOutputs,"includeOutputs"),includeOutputLockingScripts:be(n.includeOutputLockingScripts,"includeOutputLockingScripts"),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0,0),seekPermission:ni(n.seekPermission,"seekPermission")}}function Rc(n){let t=gt(n,"args");if(t.identityKey!==void 0&&t.identityKey!==!0&&yt("identityKey","true or undefined"),t.forSelf!==void 0&&ws(t.forSelf,"forSelf",!1),t.identityKey===!0){t.protocolID!==void 0&&dd(t.protocolID),t.keyID!==void 0&&ae(t.keyID,"keyID",1,800),t.counterparty!==void 0&&fd(t.counterparty,"counterparty"),Li(t);return}Pr(n,"args")}function Nc(n){let t=gt(n,"args");He(t.counterparty,"counterparty"),He(t.verifier,"verifier"),Li(t,!1)}function Bc(n){let t=gt(n,"args");fd(t.counterparty,"counterparty"),He(t.verifier,"verifier"),dd(t.protocolID),ae(t.keyID,"keyID",1,800),Li(t,!1)}function _c(n){let t=gt(n,"args");Pr(n),$n(t.plaintext,"plaintext")}function Cc(n){let t=gt(n,"args");Pr(n),$n(t.ciphertext,"ciphertext")}function Lc(n){let t=gt(n,"args");Pr(n),$n(t.data,"data")}function Uc(n){let t=gt(n,"args");Pr(n),$n(t.data,"data"),$n(t.hmac,"hmac",32)}function Wg(n,t,e){let i=n[t]!==void 0,r=n[e]!==void 0;i===r&&yt(`${t}, ${e}`,"exactly one value"),i&&$n(n[t],t),r&&$n(n[e],e,32)}function Mc(n){let t=gt(n,"args");Pr(n),Wg(t,"data","hashToDirectlySign")}function Dc(n){let t=gt(n,"args");Pr(n),Wg(t,"data","hashToDirectlyVerify");let e=$n(t.signature,"signature",void 0,72);ms(e)||yt("signature","a canonical DER-encoded ECDSA signature"),t.forSelf!==void 0&&ws(t.forSelf,"forSelf",!1)}function Hc(n){let t=gt(n,"args");ee(t.height,"height",void 0,1,Ci)}function Mi(n,t="args"){gt(n,t)}var xx="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";var $c;(function(n){n[n.Silent=0]="Silent",n[n.App=1]="App",n[n.Counterparty=2]="Counterparty"})($c||($c={}));var Sx=Object.prototype.hasOwnProperty,Ix=new Set(["BEEF","atomicBEEF","beef","ciphertext","competingBeef","data","encryptedLinkage","encryptedLinkageProof","hashToDirectlySign","hashToDirectlyVerify","hmac","inputBEEF","payload","plaintext","signature","transaction","tx"]);function qc(n){return n==null||typeof n!="object"||typeof ArrayBuffer>"u"?!1:ArrayBuffer.isView(n)&&Object.prototype.toString.call(n)==="[object Uint8Array]"}function Vg(n){return Number.isInteger(n)&&n>=0&&n<=255}function vx(n){return n!=null&&typeof n=="object"&&typeof ArrayBuffer<"u"&&(ArrayBuffer.isView(n)||Object.prototype.toString.call(n)==="[object ArrayBuffer]")}function Ax(n){for(let t=0;t<n.length;t++)if(!Sx.call(n,t)||!Vg(n[t]))return;return n}function Ex(n){if(!(n==null||typeof n!="object"))try{let t=Object.keys(n);if(t.length===0)return;let e=[];for(let i=0;i<t.length;i++){if(t[i]!==String(i))return;let r=n[t[i]];if(!Vg(r))return;e.push(r)}return e}catch{return}}function md(n){if(qc(n))return n;if(!vx(n))return Array.isArray(n)?Ax(n):Ex(n)}function kx(n,t){let e=this==null?void 0:this[n];return qc(e)?Array.from(e):qc(t)?Array.from(t):t}function ys(n,t){let e=JSON.stringify(n,kx,t);if(e===void 0)throw new TypeError("BRC-100 JSON payload is not serializable");return e}function Tx(n,t,e,i){let r=md(e);r!=null?n[t]=r:i(e)}function Fc(n){let t=new WeakSet,e=[n];for(;e.length>0;){let i=e.pop();if(!(i==null||typeof i!="object"||qc(i))&&!t.has(i)){if(t.add(i),Array.isArray(i)){for(let r of i)e.push(r);continue}for(let[r,s]of Object.entries(i))Ix.has(r)?Tx(i,r,s,o=>e.push(o)):e.push(s)}}return n}var Ox=Number,Px=String,Rx=Uint8Array,Nx=URL,Bx=Array.prototype,_x=Array.isArray,Cx=Date.parse,Lx=Number.MAX_SAFE_INTEGER,Ux=Number.isFinite,Kc=Number.isInteger,Br=Number.isSafeInteger,cm=Object.prototype,Mx=Object.prototype.hasOwnProperty,Di=Object.create,zc=Object.defineProperty,um=Object.freeze,ye=Object.getOwnPropertyDescriptor,Xc=Object.getPrototypeOf,In=Object.keys,Cr=Reflect.ownKeys,Dx=RegExp.prototype.exec,Hx=RegExp.prototype.test,fm=String.prototype.split,$x=String.prototype.toLowerCase,qx=String.prototype.trim,vd=String.prototype.replace,Fx=String.prototype.normalize,Wx=String.prototype.indexOf,Vx=String.prototype.slice,Kx=String.prototype.startsWith,zx=RegExp,Kg=ye(URL.prototype,"protocol")?.get,Ad=Xc(Uint8Array.prototype),zg=ye(Ad,"buffer")?.get,Xg=ye(Ad,"length")?.get,jg=ye(Ad,Symbol.toStringTag)?.get,Xx=Uint8Array.prototype.set,Gg=typeof SharedArrayBuffer>"u"?void 0:ye(SharedArrayBuffer.prototype,"byteLength")?.get,Yg=Map,cn=Set,Zg=WeakMap,jx=WeakSet,Gx=Map.prototype.get,Yx=Map.prototype.set,Zx=Map.prototype.has,Jx=Map.prototype.forEach,Qx=Set.prototype.add,t2=Set.prototype.has,e2=ye(Set.prototype,"size").get,n2=WeakMap.prototype.get,i2=WeakMap.prototype.set,r2=WeakSet.prototype.add,s2=WeakSet.prototype.has,Pt=Reflect.apply;function qt(n){return _x(n)}function Sn(n){return Ox(n)}function Be(n){return Px(n)}function jt(n){return Pt($x,n,[])}function Ed(n,t){return Pt(fm,n,[t])}function Ss(n,t){return Pt(Hx,n,[t])}function _r(n,t){return Pt(Dx,n,[t])}function jc(n,t){return Pt(Mx,n,[t])}function zo(n){if(!(zg==null||Xg==null||jg==null))try{return{buffer:Pt(zg,n,[]),length:Pt(Xg,n,[]),tag:Pt(jg,n,[])}}catch{return}}function xd(n){return zo(n)?.tag==="Uint8Array"}function o2(n){if(Gg==null)return!1;try{return Pt(Gg,n,[]),!0}catch{return!1}}function Nr(n,t){return Pt(Gx,n,[t])}function bd(n,t,e){Pt(Yx,n,[t,e])}function a2(n,t){return Pt(Zx,n,[t])}function c2(n,t){Pt(Jx,n,[t])}function Gt(n,t){Pt(Qx,n,[t])}function un(n,t){return Pt(t2,n,[t])}function Gc(n){return Pt(e2,n,[])}function Jg(n,t){return Pt(n2,n,[t])}function Wo(n,t,e){Pt(i2,n,[t,e])}function wd(n,t){Pt(r2,n,[t])}function Qg(n,t){return Pt(s2,n,[t])}var si=new cn;Gt(si,"completed");Gt(si,"unprocessed");Gt(si,"sending");Gt(si,"unproven");Gt(si,"unsigned");Gt(si,"nosend");Gt(si,"nonfinal");Gt(si,"failed");var Jc=new cn;Gt(Jc,"unproven");Gt(Jc,"sending");Gt(Jc,"failed");var xs=1e6,tm=xs+2,u2=16*1024*1024,f2="0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",em=new Bi,kd=Symbol("createActionSourceEvidence"),Xo=Symbol("byteBudgetExceeded"),Vo=new jx,Yc=um(Di(null));function dm(n){if(!qt(n))return;let t=ye(n,"length");if(t==null||!("value"in t)||!Br(t.value)||t.value<0||t.value>xs)throw new Error("Wallet request arrays must have a bounded own length");let e=t.value;if(Cr(n).length!==e+1)throw new Error("Wallet request arrays must contain only dense data properties");let r=[];r.length=e;for(let s=0;s<e;s++){let o=ye(n,Be(s));if(o==null||!("value"in o))throw new Error("Wallet request arrays must contain only dense data properties");r[s]=o.value}return r}function nm(n){let t=At(n);if(t==null)return;let e=Di(null),i=Cr(t);for(let r=0;r<i.length;r++){let s=i[r];if(typeof s!="string")continue;let o=ye(t,s);o!=null&&"value"in o&&(e[s]=o.value)}return e}function Ze(n,t,e=[]){let i=Di(null);for(let r=0;r<t.length;r++){let s=t[r],o=!1;for(let c=0;c<e.length;c++)if(e[c]===s){o=!0;break}i[s]=o?dm(n[s]):n[s]}return i}function lm(n){let t=At(n);if(t==null)return Yc;let e=ye(t,kd)?.value;if(e!=null)return e;let i=t.inputBEEF,r=t.inputs;if(i===void 0||!qt(r)||r.length===0)return Yc;let s=ri(i,"createAction","request.inputBEEF"),o;try{o=ps(s)}catch{L("createAction","request.inputBEEF","an exactly framed BEEF envelope")}let c=Di(null);for(let u=0;u<r.length;u++){let f=r[u],d=At(f);if(d==null||typeof d.outpoint!="string")continue;let l=_r(/^([0-9a-fA-F]{64})\.(0|[1-9]\d*)$/,d.outpoint);if(l==null)continue;let p=Sn(l[2]);if(p>4294967295)continue;let m=jt(l[1]),g=Nr(o.transactions,m)?.outputs[p];g!==void 0&&(c[`${m}.${p}`]=g.satoshis)}return um(c)}function mt(n,t){let e=At(t);if(e==null)return t;let i=At(e.options);switch(n){case"createAction":{let r={inputs:qt(e.inputs)?(()=>{let s=[];s.length=e.inputs.length;for(let o=0;o<e.inputs.length;o++){let c=e.inputs[o],u=At(c);s[o]=u==null?c:Ze(u,["outpoint","unlockingScript","sequenceNumber"])}return s})():e.inputs,outputs:qt(e.outputs)?(()=>{let s=[];s.length=e.outputs.length;for(let o=0;o<e.outputs.length;o++){let c=e.outputs[o],u=At(c);s[o]=u==null?c:Ze(u,["satoshis","lockingScript"])}return s})():e.outputs,version:e.version,lockTime:e.lockTime,options:i==null?{signAndProcess:void 0,returnTXIDOnly:void 0,sendWith:void 0,randomizeOutputs:void 0,knownTxids:void 0}:Ze(i,["signAndProcess","returnTXIDOnly","sendWith","randomizeOutputs","knownTxids"],["sendWith","knownTxids"])};return zc(r,kd,{value:lm(e),writable:!1,configurable:!1,enumerable:!1}),r}case"signAction":{let r=At(e.spends),s=Di(null);if(r!=null){let o=In(r);for(let c=0;c<o.length;c++){let u=o[c],f=r[u],d=At(f);s[u]=d==null?f:Ze(d,["unlockingScript","sequenceNumber"])}}return{spends:s,options:i==null?{returnTXIDOnly:void 0,sendWith:void 0}:Ze(i,["returnTXIDOnly","sendWith"],["sendWith"])}}case"listActions":return Ze(e,["labels","labelQueryMode","includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts","limit"],["labels"]);case"listOutputs":return Ze(e,["basket","tags","tagQueryMode","include","includeCustomInstructions","includeTags","includeLabels","limit"],["tags"]);case"listCertificates":return Ze(e,["limit","certifiers","types"],["certifiers","types"]);case"discoverByIdentityKey":return Ze(e,["limit","identityKey"]);case"discoverByAttributes":{let r=At(e.attributes);return{limit:e.limit,attributes:r==null?e.attributes:{...r}}}case"revealCounterpartyKeyLinkage":return Ze(e,["verifier","counterparty"]);case"revealSpecificKeyLinkage":return Ze(e,["verifier","counterparty","protocolID","keyID"],["protocolID"]);case"acquireCertificate":return{...Ze(e,["acquisitionProtocol","type","certifier","serialNumber","revocationOutpoint","signature"]),fields:nm(e.fields)};case"proveCertificate":return{fieldsToReveal:dm(e.fieldsToReveal),verifier:e.verifier,certificate:(()=>{let r=At(e.certificate);return r==null?e.certificate:{...Ze(r,["type","serialNumber","subject","certifier","revocationOutpoint","signature"]),fields:nm(r.fields)}})()};default:return t}}function L(n,t,e){throw new Error(`Invalid ${n} result ${t}: expected ${e}`)}function hm(n){let t=ye(n,"length");return t!=null&&"value"in t&&Br(t.value)&&t.value>=0?t.value:void 0}function pm(n,t,e,i=e){if(t>e)return;let r=Cr(n);if(r.length!==t+1)return;for(let o=0;o<r.length;o++){let c=r[o];if(c!=="length"&&(typeof c!="string"||!Kc(Sn(c))||Sn(c)<0||Sn(c)>=t||Be(Sn(c))!==c))return}let s=t<=i?[]:void 0;s!==void 0&&(s.length=t);for(let o=0;o<t;o++){let c=ye(n,Be(o));if(c==null||c.enumerable!==!0||!("value"in c)||!Kc(c.value)||c.value<0||c.value>255)return;s!==void 0&&(s[o]=c.value)}return s??Xo}function d2(n,t,e){let i=Xc(n);if(i!==cm&&i!==null)return;let r=Cr(n);if(r.length===0||r.length>t)return;let s=r.length<=e?[]:void 0;s!==void 0&&(s.length=r.length);for(let o=0;o<r.length;o++){let c=r[o];if(c!==Be(o))return;let u=ye(n,c);if(u==null||u.enumerable!==!0||!("value"in u)||!Kc(u.value)||u.value<0||u.value>255)return;s!==void 0&&(s[o]=u.value)}return s??Xo}function l2(n){switch(n){case"BEEF":case"atomicBEEF":case"beef":case"ciphertext":case"competingBeef":case"data":case"encryptedLinkage":case"encryptedLinkageProof":case"hashToDirectlySign":case"hashToDirectlyVerify":case"hmac":case"inputBEEF":case"payload":case"plaintext":case"signature":case"transaction":case"tx":return!0;default:return!1}}function gm(n,t,e){let i=zo(n);i?.tag!=="Uint8Array"&&L(t,"byte array","an intrinsic Uint8Array");let{buffer:r,length:s}=i;o2(r)&&L(t,"byte array","an unshared Uint8Array"),s>268435456&&L(t,"byte array",`at most ${268435456} bytes`),s>e&&L(t,"byte arrays",`at most ${268435456} total bytes`);let o=new Rx(s);try{Pt(Xx,o,[n])}catch{L(t,"byte array","an intrinsic Uint8Array")}return o}function Td(n,t,e=!1){let i=[],r=new Zg,s=new Zg,o=0,c=0,u=(d,l)=>{if(d==null||typeof d!="object")return typeof d=="function"&&L(t,"value","data without functions"),d;if(!qt(d)&&!xd(d)&&e&&l2(l)){let w=Jg(s,d);if(w!==void 0)return w;let S=d2(d,268435456,268435456-c);if(S===Xo&&L(t,"byte arrays",`at most ${268435456} total bytes`),S!==void 0)return o++,o>xs&&L(t,"object graph","a bounded result"),S.length>268435456-c&&L(t,"byte arrays",`at most ${268435456} total bytes`),c+=S.length,wd(Vo,S),Wo(s,d,S),S}let p=Jg(r,d);if(p!==void 0)return p;if(o++,o>xs&&L(t,"object graph","a bounded result"),xd(d)){let w=gm(d,t,268435456-c);return c+=zo(w).length,wd(Vo,w),Wo(r,d,w),w}if(qt(d)){Xc(d)!==Bx&&L(t,"array prototype","the intrinsic Array.prototype");let S=hm(d);S===void 0&&L(t,"array length","an own integer data property");let C=pm(d,S,268435456,268435456-c);if(C===Xo&&L(t,"byte arrays",`at most ${268435456} total bytes`),C!==void 0)return c+=C.length,wd(Vo,C),Wo(r,d,C),C;S>xs&&L(t,"array length",`at most ${xs} entries`);let E=[];return E.length=S,Wo(r,d,E),i[i.length]={source:d,target:E,array:!0},E}let m=Xc(d);m!==null&&m!==cm&&L(t,"object prototype","Object.prototype or null");let g=m===null?Di(null):{};return Wo(r,d,g),i[i.length]={source:d,target:g,array:!1},g},f=u(n);for(;i.length>0;){let d=i[i.length-1];i.length-=1;let l=Cr(d.source);if(d.array){o+=l.length,o>tm&&L(t,"object graph","a bounded result");let p=d.source,m=d.target.length;l.length!==m+1&&L(t,"array shape","a dense standard array without extra properties");for(let g=0;g<l.length;g++){let w=l[g];if(typeof w!="string"&&L(t,"array key","a string"),gn(w)&&L(t,`array key ${w}`,"a safe array key"),w!=="length"){let C=Sn(w);(!Kc(C)||C<0||C>=m||Be(C)!==w)&&L(t,`array key ${w}`,"a canonical in-range array index")}let S=ye(p,w);(S==null||!("value"in S))&&L(t,`array property ${w}`,"a data property"),w!=="length"&&zc(d.target,w,{value:u(S.value),enumerable:S.enumerable,configurable:!0,writable:!0})}continue}o+=l.length,o>tm&&L(t,"object graph","a bounded result");for(let p=0;p<l.length;p++){let m=l[p];typeof m!="string"&&L(t,"object key","a string"),gn(m)&&L(t,`object key ${m}`,"a safe record key");let g=ye(d.source,m);(g==null||!("value"in g))&&L(t,`object property ${m}`,"a data property"),zc(d.target,m,{value:u(g.value,m),enumerable:g.enumerable,configurable:!0,writable:!0})}}return f}function mm(n,t){return Td(n,t)}function bm(n,t){return Td(n,t,!0)}function qe(n,t,e="value"){(n==null||typeof n!="object"||qt(n))&&L(t,e,"an object");let i=Di(null),r=Cr(n);for(let s=0;s<r.length;s++){let o=r[s];typeof o!="string"&&L(t,`${e} key`,"a string");let c=ye(n,o);(c==null||!("value"in c))&&L(t,`${e}.${o}`,"a data property"),i[o]=c.value}return i}function ri(n,t,e,i,r=268435456){let s;if(n!=null&&typeof n=="object"&&xd(n)){let c=Qg(Vo,n)?n:gm(n,t,268435456);zo(c).length<=r&&(s=c)}else if(qt(n)){let c=hm(n);if(c===void 0&&L(t,e,"an own integer array length"),c>r&&L(t,e,`at most ${r} bytes`),Qg(Vo,n))s=n;else{let u=pm(n,c,r);u===Xo&&L(t,e,`at most ${r} bytes`),s=u}}s==null&&L(t,e,"an array of bytes");let o=qt(s)?s.length:zo(s).length;return o>r&&L(t,e,`at most ${r} bytes`),i!==void 0&&o!==i&&L(t,e,`${i} bytes`),s}function we(n,t,e,i=0,r){typeof n!="string"&&L(t,e,"a string");let s=Se(n).length;return(s<i||r!==void 0&&s>r)&&L(t,e,`${i}${r===void 0?"+":`\u2013${r}`} UTF-8 bytes`),n}function $e(n,t,e,i){let r=we(n,t,e);return Ss(/^(?:[0-9a-fA-F]{2})*$/,r)||L(t,e,"an even-length hex string"),i!==void 0&&r.length!==i*2&&L(t,e,`${i} hexadecimal bytes`),r}function jo(n,t,e){let i=$e(n,t,e,33);hc(i)||L(t,e,"a valid compressed secp256k1 public key")}function ne(n,t,e,i=4294967295){return(!Br(n)||n<0||n>i)&&L(t,e,`an integer from 0 to ${i}`),n}function Od(n,t,e,i,r){return(!Br(n)||n<i||n>r)&&L(t,e,`an integer from ${i} to ${r}`),n}function Wc(n,t,e){n[e]!==!0&&L(t,e,"true")}function wm(n,t,e){typeof n[e]!="boolean"&&L(t,e,"a boolean")}function qn(n,t,e){if(n!==void 0)return qt(n)||L(t,e,"an array"),n.length>1e5&&L(t,e,"at most 100000 entries"),n}function Zc(n,t,e,i,r){let s=qn(n,t,e);if(s!=null)for(let o=0;o<s.length;o++)we(s[o],t,`${e}[${o}]`,i,r)}function h2(n,t,e){let i=we(n,t,e,1,64);Ss(/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/,i)||L(t,e,"an ISO timestamp with a timezone");let r=Cx(i);Ux(r)||L(t,e,"a valid ISO timestamp")}function p2(n,t,e,i){let r=we(n,t,e,1,i);try{let s=new Nx(r);if(Kg==null)throw new Error;let o=Pt(Kg,s,[]);if(o!=="https:"&&o!=="http:")throw new Error}catch{L(t,e,"an absolute HTTP(S) URL")}}function g2(n,t){let e=qn(n,t,"sendWithResults");if(e!=null){e.length>xn+1&&L(t,"sendWithResults",`at most ${xn+1} transaction results`);for(let i=0;i<e.length;i++){let r=e[i],s=`sendWithResults[${i}]`,o=qe(r,t,s);$e(o.txid,t,`${s}.txid`,32),un(Jc,o.status)||L(t,`${s}.status`,"a supported status")}}}function ym(n,t,e,i){let r=n.inputs[t];r==null&&L(e,i,"a transaction input");let s=jt($e(r.sourceTXID,e,`${i}.sourceTXID`,32)),o=ne(r.sourceOutputIndex,e,`${i}.sourceOutputIndex`);return`${s}.${o}`}function im(n,t,e,i,r){let s=At(e);if(s==null){Sd(n,t,i,r);return}let o=s.version===void 0?1:ne(s.version,t,"request.version"),c=s.lockTime===void 0?0:ne(s.lockTime,t,"request.lockTime");n.version!==o&&L(t,"tx.version","the requested transaction version"),n.lockTime!==c&&L(t,"tx.lockTime","the requested transaction lock time");let u=new Yg;for(let w=0;w<n.inputs.length;w++){let S=ym(n,w,t,`tx.inputs[${w}]`);a2(u,S)&&L(t,`tx.inputs[${w}]`,"a unique transaction input outpoint"),bd(u,S,w)}let f=s.inputs===void 0?[]:qn(s.inputs,t,"request.inputs"),d=new cn;for(let w=0;w<f.length;w++){let S=f[w],C=`request.inputs[${w}]`,E=qe(S,t,C),A=Is(E.outpoint,t,`${C}.outpoint`),k=`${A.txid}.${A.outputIndex}`;un(d,k)&&L(t,`${C}.outpoint`,"a unique requested input"),Gt(d,k);let B=Nr(u,k);B===void 0&&L(t,"tx.inputs","every requested input exactly once");let _=n.inputs[B],H=E.sequenceNumber===void 0?4294967295:ne(E.sequenceNumber,t,`${C}.sequenceNumber`);if((_.sequence??4294967295)!==H&&L(t,`tx.inputs[${B}].sequence`,"the requested input sequence"),E.unlockingScript!==void 0){let O=jt($e(E.unlockingScript,t,`${C}.unlockingScript`));jt(Ye(_.unlockingScript))!==O&&L(t,`tx.inputs[${B}].unlockingScript`,"the requested unlocking script")}}let l=s.outputs===void 0?[]:qn(s.outputs,t,"request.outputs"),m=At(s.options)?.randomizeOutputs===!1,g=new Yg;for(let w=0;w<n.outputs.length;w++){let S=n.outputs[w],C=ne(S.satoshis,t,`tx.outputs[${w}].satoshis`,21e14);if(l.length>0){let E=`${C}:${jt(Ye(S.lockingScript))}`;bd(g,E,(Nr(g,E)??0)+1)}}for(let w=0;w<l.length;w++){let S=l[w],C=`request.outputs[${w}]`,E=qe(S,t,C),A=ne(E.satoshis,t,`${C}.satoshis`,21e14),k=jt($e(E.lockingScript,t,`${C}.lockingScript`));if(m){let H=n.outputs[w];(H==null||H.satoshis!==A||jt(Ye(H.lockingScript))!==k)&&L(t,`tx.outputs[${w}]`,"the requested output at the requested position");continue}let B=`${A}:${k}`,_=Nr(g,B)??0;_===0&&L(t,"tx.outputs","every requested output with its requested amount and script"),bd(g,B,_-1)}Sd(n,t,i,r)}function Sd(n,t,e=Yc,i=!1){let r=0,s=!1,o=new cn;for(let u=0;u<n.inputs.length;u++){let f=n.inputs[u],d=ym(n,u,t,`tx.inputs[${u}]`);un(o,d)&&L(t,`tx.inputs[${u}]`,"a unique transaction input outpoint"),Gt(o,d);let l=f.sourceSatoshis??e[d];if(l===void 0){i||L(t,`tx.inputs[${u}].sourceSatoshis`,"source transaction evidence for every completed transaction input"),s=!0;continue}r+=ne(l,t,`tx.inputs[${u}].sourceSatoshis`,21e14),(!Br(r)||r>21e14)&&L(t,"tx.inputs","a valid total input value")}let c=0;for(let u=0;u<n.outputs.length;u++){let f=n.outputs[u];c+=ne(f.satoshis,t,`tx.outputs[${u}].satoshis`,21e14),(!Br(c)||c>21e14)&&L(t,"tx.outputs","a valid total output value")}!s&&c>r&&L(t,"tx.outputs","a total value no greater than the transaction inputs")}function m2(n,t,e){let i=At(At(e)?.spends);if(i==null)return;let r=In(i);for(let s=0;s<r.length;s++){let o=r[s],c=i[o],u=`request.spends.${o}`;Ss(/^(?:0|[1-9]\d*)$/,o)||L(t,u,"a canonical input index");let f=Sn(o),d=n.inputs[f];(!Br(f)||d==null)&&L(t,`tx.inputs[${o}]`,"the requested input index");let l=qe(c,t,u),p=jt($e(l.unlockingScript,t,`${u}.unlockingScript`));jt(Ye(d.unlockingScript))!==p&&L(t,`tx.inputs[${f}]`,"the requested unlocking script"),l.sequenceNumber!==void 0&&d.sequence!==ne(l.sequenceNumber,t,`${u}.sequenceNumber`)&&L(t,`tx.inputs[${f}].sequence`,"the requested input sequence")}}function b2(n,t,e){let i=t==="createAction"?lm(e):Yc,r=n.txid===void 0?void 0:$e(n.txid,t,"txid",32),s=n.tx===void 0?void 0:rm(n.tx,t,"tx",r),o=s?.txid;r!==void 0&&o!==void 0&&!an(r,o)&&L(t,"tx","a BEEF transaction matching txid");let c=qn(n.noSendChange,t,"noSendChange");if(c!=null)for(let g=0;g<c.length;g++)Is(c[g],t,`noSendChange[${g}]`);g2(n.sendWithResults,t);let u;if(n.signableTransaction!==void 0){t!=="createAction"&&L(t,"signableTransaction","an absent field"),(n.txid!==void 0||n.tx!==void 0)&&L(t,"signableTransaction","exclusive of txid and tx");let g=qe(n.signableTransaction,t,"signableTransaction");u=rm(g.tx,t,"signableTransaction.tx"),Pd(g.reference,t,"signableTransaction.reference")}let f=At(e);if(f!==void 0&&t==="createAction"){let g=f.inputs===void 0?[]:qn(f.inputs,t,"request.inputs"),w=f.outputs===void 0?[]:qn(f.outputs,t,"request.outputs"),S=At(f.options),C=qt(S?.sendWith)?S.sendWith:[],E=g.length>0||w.length>0||C.length===0,A=!1;for(let B=0;B<g.length;B++)if(At(g[B])?.unlockingScript===void 0){A=!0;break}let k=E&&(S?.signAndProcess===!1||A);E&&k&&u===void 0&&L(t,"signableTransaction","the requested deferred-signing transaction"),E&&!k&&r===void 0&&L(t,"txid","the requested completed transaction"),E&&!k&&u!==void 0&&L(t,"signableTransaction","absent for a completed transaction request")}f!==void 0&&t==="signAction"&&r===void 0&&L(t,"txid","the completed signed transaction"),t==="createAction"?(s!==void 0&&im(s,t,e,i,!1),u!==void 0&&im(u,t,e,i,!0)):s!==void 0&&(m2(s,t,e),Sd(s,t));let d=u?.txid,l=r??d;if(c!=null){l===void 0&&L(t,"noSendChange","associated with a transaction");for(let g=0;g<c.length;g++){let w=c[g];an(Ed(Be(w),".")[0],l)||L(t,`noSendChange[${g}]`,"an outpoint of the returned transaction")}}let p=At(At(e)?.options),m=new cn;if(l!==void 0&&Gt(m,jt(l)),qt(p?.sendWith))for(let g=0;g<p.sendWith.length;g++)Gt(m,jt(Be(p.sendWith[g])));if(qt(n.sendWithResults)){let g=new cn;for(let w=0;w<n.sendWithResults.length;w++){let S=n.sendWithResults[w],C=`sendWithResults[${w}].txid`,E=jt(Be(qe(S,t,`sendWithResults[${w}]`).txid));un(g,E)&&L(t,C,"a unique transaction"),Gt(g,E),Gc(m)>0&&!un(m,E)&&L(t,C,"a submitted or returned transaction")}}n.tx!==void 0&&n.txid===void 0&&L(t,"txid","present with tx"),At(e)!==void 0&&n.txid!==void 0&&n.tx===void 0&&At(At(e)?.options)?.returnTXIDOnly!==!0&&L(t,"tx","transaction evidence unless returnTXIDOnly was explicitly requested"),t==="signAction"&&n.noSendChange!==void 0&&L(t,"noSendChange","an absent field"),n.txid===void 0&&n.signableTransaction===void 0&&(!qt(n.sendWithResults)||n.sendWithResults.length===0)&&L(t,"outcome","a transaction, signable transaction, or batch-send result")}function rm(n,t,e,i){let r=ri(n,t,e),s=i===void 0?em.get(r):void 0;if(s!=null)return s;try{let o=Fo(r);return i===void 0&&em.set(r,o),o}catch{}try{return Fo(r,!0)}catch{}try{let o=ps(r),c=i===void 0?void 0:jt(i),u;c2(o.transactions,(l,p)=>{l!==void 0&&(u=p)});let f=(c!==void 0&&Nr(o.transactions,c)!==void 0?c:void 0)??o.atomicTxid??u,d=f===void 0?void 0:Nr(o.transactions,jt(f));if(d===void 0)throw new Error("BEEF subject transaction is missing");return d}catch{L(t,e,"a complete, exactly framed BEEF transaction")}}function w2(n,t,e){let i=ri(n,t,e);try{return ps(i)}catch{L(t,e,"a complete, exactly framed BEEF envelope")}}function Is(n,t,e){let i=we(n,t,e),r=_r(/^([0-9a-fA-F]{64})\.(0|[1-9]\d*)$/,i);return(r==null||Sn(r[2])>4294967295)&&L(t,e,"a canonical transaction outpoint"),{txid:jt(r[1]),outputIndex:Sn(r[2])}}function Pd(n,t,e){let i=we(n,t,e,1);return Ss(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,i)||L(t,e,"a canonical base64 string"),i}function Vc(n){return n<253?1:n<=65535?3:n<=4294967295?5:9}function Ko(n,t,e,i=!1){let r=qe(n,t,e),s=In(r);for(let o=0;o<s.length;o++){let c=s[o],u=r[c],f=Se(c).length;(f<1||f>50||gn(c))&&L(t,`${e} key`,"a safe 1\u201350 byte field name"),i?Pd(u,t,`${e}.${c}`):we(u,t,`${e}.${c}`)}return r}function Id(n,t,e){let i=qe(n,t,e);try{let r=0,s=["type","serialNumber"];for(let g=0;g<s.length;g++){let w=s[g],S=Pd(i[w],t,`${e}.${w}`),C=dc(S);if(C.length!==32||Bg(C)!==S)throw new Error;r+=C.length}let o=["subject","certifier"];for(let g=0;g<o.length;g++){let w=o[g];jo(i[w],t,`${e}.${w}`),r+=33}let c=we(i.revocationOutpoint,t,`${e}.revocationOutpoint`),u=Ed(c,"."),f=u[1]??"0";if(u.length>2||!Ss(/^[0-9a-fA-F]{64}$/,u[0])||!Ss(/^(?:0|[1-9]\d*)$/,f)||Sn(f)>4294967295)throw new Error;r+=32+Vc(Sn(f));let d=Ko(i.fields,t,`${e}.fields`),l=In(d);for(let g=1;g<l.length;g++){let w=l[g],S=g;for(;S>0&&l[S-1]>w;)l[S]=l[S-1],S--;l[S]=w}r+=Vc(l.length);for(let g=0;g<l.length;g++){let w=l[g],S=Se(w),C=Se(d[w]);r+=Vc(S.length)+S.length+Vc(C.length)+C.length}let p=$e(i.signature,t,`${e}.signature`),m=hs(p);if(!ms(m))throw new Error;if(r+=m.length,r>u2)throw new Error}catch{L(t,e,"a canonical signed wallet certificate")}return i}function At(n){if(n==null||typeof n!="object"||qt(n))return;let t=n,e=Di(null),i=Cr(t);for(let r=0;r<i.length;r++){let s=i[r],o=ye(t,s);if(s===kd){if(o==null||!("value"in o))throw new Error("Wallet result request records must contain only data properties");zc(e,s,{value:o.value,enumerable:!1,configurable:!1,writable:!1});continue}if(typeof s!="string"||gn(s))throw new Error("Wallet result request records must contain only safe string keys");if(o==null||!("value"in o))throw new Error("Wallet result request records must contain only data properties");e[s]=o.value}return e}function an(n,t){return typeof n=="string"&&typeof t=="string"&&jt(n)===jt(t)}function Qc(n){let t=Pt(vd,n,[/\s+/g," "]);return Pt(qx,t,[])}function sm(n){let t=Pt(Fx,n,["NFD"]);return jt(Pt(vd,t,[/\p{Mn}/gu,""]))}function xm(n,t){return Pt(Wx,n,[t])!==-1}function Sm(n,t){let e=Ed(Qc(t)," "),i=Pt(fm,n,[/\r\n?|\n|\u2028|\u2029/]),r=0;for(;r<i.length;){let s=0,o=0;for(;o<e.length;){let c=Pt(vd,e[o],[/[.*+?^${}()|[\]\\]/g,String.raw`\$&`]),u=new zx(c,"gi");u.lastIndex=s;let f=_r(u,i[r]);if(f==null)break;s=f.index+f[0].length,o++}if(o===e.length)return!0;r++}return!1}var y2=" a about above after again against all am an and any are aren't as at be because been before being below between both but by can't cannot could couldn't did didn't do does doesn't doing don't down during each few for from further had hadn't has hasn't have haven't having he he'd he'll he's her here here's hers herself him himself his how how's i i'd i'll i'm i've if in into is isn't it it's its itself let's me more most mustn't my myself no nor not of off on once only or other ought our ours ourselves out over own same shan't she she'd she'll she's should shouldn't so some such than that that's the their theirs them themselves then there there's these they they'd they'll they're they've this those through to too under until up very was wasn't we we'd we'll we're we've were weren't what what's when when's where where's which while who who's whom why why's with won't would wouldn't you you'd you'll you're you've your yours yourself yourselves ";function Im(n){let t=[],e=/(?:[^\p{Dash}\p{Pattern_Syntax}\p{Quotation_Mark}\p{Terminal_Punctuation}\p{White_Space}]|')+/gu,i=_r(e,n);for(;i!=null;)xm(y2,` ${i[0]} `)||(t[t.length]=i[0]),i=_r(e,n);return t}function x2(n,t){let e=0;for(;e<n.length;)if(n[e++]===t)return!0;return!1}function S2(n,t,e,i){let r=Pt(Kx,e,["-"])&&e.length>1;if(i!==void 0){let u=xm(t,i);if(r?u:!u)return-1;if(r)return 0}let s=Im(i??(r?Pt(Vx,e,[1]):e)),o=!1,c=0;for(;c<s.length;){let u=x2(n,s[c++]);if(r&&u)return-1;o=o||u}return o&&!r?1:0}function I2(n,t){let e=sm(n),i=sm(t),r=Im(e),s=/-?"([^"]*)"|[^\s"]+/g,o=!1,c=_r(s,i);for(;c!=null;){let u=S2(r,e,c[0],c[1]);if(u===-1)return!1;u===1&&(o=!0),c=_r(s,i)}return o}function v2(n){return n!=="profilePhoto"&&n!=="icon"}function A2(n,t){if(typeof t!="string")return!1;let e=Qc(t);if(e.length<2)return!1;let i=In(n),r="",s=0;for(;s<i.length;){let o=i[s++];if(!v2(o))continue;let c=n[o];r=r.length>0?`${r} ${c}`:c}return e.length===2?Sm(r,e):I2(r,e)}function E2(n,t,e){return typeof t!="string"?!1:n==="userName"?t===Qc(e):Sm(t,e)}function k2(n,t,e,i){let r=At(i);if(r==null)return;if(jc(r,"any")){A2(e,r.any)||L(n,`${t}.decryptedFields`,"a match for the requested any attribute");return}let s=In(r),o=0,c=0;for(;c<s.length;){let u=s[c++],f=r[u];typeof f!="string"&&L(n,`request.attributes.${u}`,"a string"),Qc(f).length!==0&&(o++,(!jc(e,u)||!E2(u,e[u],f))&&L(n,`${t}.decryptedFields.${u}`,"the requested public attribute"))}o===0&&L(n,`${t}.decryptedFields`,"a usable requested attribute")}function T2(n,t,e,i){let r=Is(n,e,i),s=Is(t,e,`request.${i}`);return r.txid===s.txid&&r.outputIndex===s.outputIndex}function O2(n,t){let e=At(n),i=At(t);if(e==null||i==null)return!1;let r=In(e),s=In(i);if(r.length!==s.length)return!1;for(let o=0;o<s.length;o++){let c=s[o];if(!jc(e,c)||e[c]!==i[c])return!1}return!0}function P2(n,t){let e=At(n),i=At(t);if(e==null||i==null)return!1;let r=In(e),s=In(i);if(r.length!==s.length)return!1;let o=0;for(;o<s.length;){if(!jc(e,s[o]))return!1;o++}return!0}function om(n,t,e,i,r=!0){let s=At(t);if(s==null)return;let o=["type","serialNumber"];for(let u=0;u<o.length;u++){let f=o[u];s[f]!==void 0&&n[f]!==s[f]&&L(e,`${i}.${f}`,`the requested certificate ${f}`)}let c=["subject","certifier","signature"];for(let u=0;u<c.length;u++){let f=c[u];s[f]!==void 0&&!an(n[f],s[f])&&L(e,`${i}.${f}`,`the requested certificate ${f}`)}s.revocationOutpoint!==void 0&&!T2(n.revocationOutpoint,s.revocationOutpoint,e,`${i}.revocationOutpoint`)&&L(e,`${i}.revocationOutpoint`,"the requested certificate revocation outpoint"),s.fields!==void 0&&!(r?O2(n.fields,s.fields):P2(n.fields,s.fields))&&L(e,`${i}.fields`,"the requested certificate fields")}function R2(n,t,e){let i=Rd(n,t,"totalCertificates","certificates",e),r=At(e),s;if(t==="listCertificates"&&qt(r?.certifiers)){s=new cn;for(let c=0;c<r.certifiers.length;c++)Gt(s,jt(Be(r.certifiers[c])))}let o;if(t==="listCertificates"&&qt(r?.types)){o=new cn;for(let c=0;c<r.types.length;c++)Gt(o,Be(r.types[c]))}for(let c=0;c<i.length;c++){let u=i[c],f=`certificates[${c}]`,d=Id(u,t,f);if(s!=null&&Gc(s)>0&&(un(s,jt(Be(d.certifier)))||L(t,`${f}.certifier`,"one of the requested certifiers")),o!=null&&Gc(o)>0&&(un(o,Be(d.type))||L(t,`${f}.type`,"one of the requested types")),t==="discoverByIdentityKey"&&r?.identityKey!==void 0&&!an(d.subject,r.identityKey)&&L(t,`${f}.subject`,"the requested identity key"),d.keyring!==void 0&&Ko(d.keyring,t,`${f}.keyring`,!0),d.verifier!==void 0&&jo(d.verifier,t,`${f}.verifier`),t==="discoverByIdentityKey"||t==="discoverByAttributes"){let l=`${f}.certifierInfo`,p=qe(d.certifierInfo,t,l);we(p.name,t,`${l}.name`,1,100),p2(p.iconUrl,t,`${l}.iconUrl`,500),we(p.description,t,`${l}.description`,5,50),Od(p.trust,t,`${l}.trust`,1,10),Ko(d.publiclyRevealedKeyring,t,`${f}.publiclyRevealedKeyring`,!0);let m=Ko(d.decryptedFields,t,`${f}.decryptedFields`);t==="discoverByAttributes"&&k2(t,f,m,r?.attributes)}}}function Rd(n,t,e,i,r){let s=ne(n[e],t,e,Lx),o=qn(n[i],t,i);o==null&&L(t,i,"an array"),o.length>s&&L(t,e,`at least ${o.length}`);let c=At(r);if(c!=null){let u=c.limit===void 0?10:ne(c.limit,t,"limit",1e4);o.length>u&&L(t,i,`at most the requested limit of ${u}`)}return o}function yd(n,t,e){we(n,t,e,n===""?0:5,2e3)}function N2(n,t,e){let i=Rd(n,t,"totalActions","actions",e),r=At(e),s=[];if(qt(r?.labels))for(let c=0;c<r.labels.length;c++)s[c]=Be(r.labels[c]);let o=r?.labelQueryMode==="all"?"all":"any";for(let c=0;c<i.length;c++){let u=i[c],f=`actions[${c}]`,d=qe(u,t,f);if($e(d.txid,t,`${f}.txid`,32),Od(d.satoshis,t,`${f}.satoshis`,-21e14,21e14),un(si,d.status)||L(t,`${f}.status`,"a supported action status"),typeof d.isOutgoing!="boolean"&&L(t,`${f}.isOutgoing`,"a boolean"),yd(d.description,t,`${f}.description`),Zc(d.labels,t,`${f}.labels`,1,300),r?.includeLabels===!0&&d.labels===void 0&&L(t,`${f}.labels`,"the explicitly requested labels"),s.length>0&&qt(d.labels)){let m=new cn;for(let w=0;w<d.labels.length;w++)Gt(m,d.labels[w]);let g=o==="all";for(let w=0;w<s.length;w++){let S=un(m,s[w]);if(o==="all"&&!S){g=!1;break}if(o==="any"&&S){g=!0;break}}g||L(t,`${f}.labels`,"the requested label query")}ne(d.version,t,`${f}.version`),ne(d.lockTime,t,`${f}.lockTime`);let l=qn(d.inputs,t,`${f}.inputs`);if((r?.includeInputs===!0||r?.includeInputSourceLockingScripts===!0||r?.includeInputUnlockingScripts===!0)&&l===void 0&&L(t,`${f}.inputs`,"the explicitly requested inputs"),l!=null)for(let m=0;m<l.length;m++){let g=l[m],w=`${f}.inputs[${m}]`,S=qe(g,t,w);Is(S.sourceOutpoint,t,`${w}.sourceOutpoint`),ne(S.sourceSatoshis,t,`${w}.sourceSatoshis`,21e14),S.sourceLockingScript!==void 0&&$e(S.sourceLockingScript,t,`${w}.sourceLockingScript`),S.unlockingScript!==void 0&&$e(S.unlockingScript,t,`${w}.unlockingScript`),r?.includeInputSourceLockingScripts===!0&&S.sourceLockingScript===void 0&&L(t,`${w}.sourceLockingScript`,"the explicitly requested source locking script"),r?.includeInputUnlockingScripts===!0&&S.unlockingScript===void 0&&L(t,`${w}.unlockingScript`,"the explicitly requested unlocking script"),yd(S.inputDescription,t,`${w}.inputDescription`),ne(S.sequenceNumber,t,`${w}.sequenceNumber`)}let p=qn(d.outputs,t,`${f}.outputs`);if((r?.includeOutputs===!0||r?.includeOutputLockingScripts===!0)&&p===void 0&&L(t,`${f}.outputs`,"the explicitly requested outputs"),p!=null)for(let m=0;m<p.length;m++){let g=p[m],w=`${f}.outputs[${m}]`,S=qe(g,t,w);ne(S.satoshis,t,`${w}.satoshis`,21e14),S.lockingScript!==void 0&&$e(S.lockingScript,t,`${w}.lockingScript`),r?.includeOutputLockingScripts===!0&&S.lockingScript===void 0&&L(t,`${w}.lockingScript`,"the explicitly requested output locking script"),wm(S,t,"spendable"),S.customInstructions!==void 0&&we(S.customInstructions,t,`${w}.customInstructions`),Zc(S.tags,t,`${w}.tags`,1,300),ne(S.outputIndex,t,`${w}.outputIndex`),yd(S.outputDescription,t,`${w}.outputDescription`),we(S.basket,t,`${w}.basket`,0,300)}}}function B2(n,t,e){let i=Rd(n,t,"totalOutputs","outputs",e),r=n.BEEF===void 0?void 0:w2(n.BEEF,t,"BEEF"),s=At(e),o=[];if(qt(s?.tags))for(let f=0;f<s.tags.length;f++)o[f]=Be(s.tags[f]);let c=s?.tagQueryMode==="all"?"all":"any";i.length>0&&s?.include==="entire transactions"&&r==null&&L(t,"BEEF","the requested complete output transactions");let u=new cn;for(let f=0;f<i.length;f++){let d=i[f],l=`outputs[${f}]`,p=qe(d,t,l),m=Is(p.outpoint,t,`${l}.outpoint`),g=`${m.txid}.${m.outputIndex}`;un(u,g)&&L(t,`${l}.outpoint`,"a unique output in the result page"),Gt(u,g);let w=ne(p.satoshis,t,`${l}.satoshis`,21e14);typeof p.spendable!="boolean"&&L(t,`${l}.spendable`,"a boolean");let S=p.lockingScript===void 0?void 0:$e(p.lockingScript,t,`${l}.lockingScript`);if(s?.include==="locking scripts"&&S===void 0&&L(t,`${l}.lockingScript`,"the requested locking script"),r!=null){let E=Nr(r.transactions,m.txid)?.outputs[m.outputIndex];E==null&&L(t,`${l}.outpoint`,"an output contained in BEEF"),E.satoshis!==w&&L(t,`${l}.satoshis`,"the amount committed by BEEF"),S!==void 0&&jt(Ye(E.lockingScript))!==jt(S)&&L(t,`${l}.lockingScript`,"the script committed by BEEF")}if(p.customInstructions!==void 0&&we(p.customInstructions,t,`${l}.customInstructions`),Zc(p.tags,t,`${l}.tags`,1,300),Zc(p.labels,t,`${l}.labels`,1,300),s?.includeTags===!0&&p.tags===void 0&&L(t,`${l}.tags`,"the explicitly requested output tags"),s?.includeLabels===!0&&p.labels===void 0&&L(t,`${l}.labels`,"the explicitly requested transaction labels"),o.length>0&&qt(p.tags)){let C=new cn;for(let A=0;A<p.tags.length;A++)Gt(C,p.tags[A]);let E=c==="all";for(let A=0;A<o.length;A++){let k=un(C,o[A]);if(c==="all"&&!k){E=!1;break}if(c==="any"&&k){E=!0;break}}E||L(t,`${l}.tags`,"the requested tag query")}}}function am(n,t){let e=["prover","verifier","counterparty"];for(let i=0;i<e.length;i++){let r=e[i];jo(n[r],t,r)}ri(n.encryptedLinkage,t,"encryptedLinkage"),ri(n.encryptedLinkageProof,t,"encryptedLinkageProof")}function Ft(n,t,e){let i=Td(t,n),r=qe(i,n),s=At(e);switch(n){case"createAction":case"signAction":b2(r,n,e);break;case"abortAction":wm(r,n,"aborted");break;case"internalizeAction":Wc(r,n,"accepted");break;case"relinquishOutput":case"relinquishCertificate":Wc(r,n,"relinquished");break;case"verifyHmac":case"verifySignature":Wc(r,n,"valid");break;case"isAuthenticated":case"waitForAuthentication":Wc(r,n,"authenticated");break;case"getPublicKey":jo(r.publicKey,n,"publicKey");break;case"encrypt":ri(r.ciphertext,n,"ciphertext");break;case"decrypt":ri(r.plaintext,n,"plaintext");break;case"createHmac":ri(r.hmac,n,"hmac",32);break;case"createSignature":{let o=ri(r.signature,n,"signature",void 0,72);ms(o)||L(n,"signature","a canonical DER-encoded ECDSA signature");break}case"revealCounterpartyKeyLinkage":am(r,n),h2(r.revelationTime,n,"revelationTime"),s?.verifier!==void 0&&!an(r.verifier,s?.verifier)&&L(n,"verifier","the requested verifier"),s?.counterparty!==void 0&&!an(r.counterparty,s?.counterparty)&&L(n,"counterparty","the requested counterparty");break;case"revealSpecificKeyLinkage":am(r,n),(!qt(r.protocolID)||r.protocolID.length!==2)&&L(n,"protocolID","a [securityLevel, protocolName] tuple"),ne(r.protocolID[0],n,"protocolID[0]",2),we(r.protocolID[1],n,"protocolID[1]",5,400),we(r.keyID,n,"keyID",1,800),ne(r.proofType,n,"proofType",255),s?.verifier!==void 0&&!an(r.verifier,s?.verifier)&&L(n,"verifier","the requested verifier"),s?.counterparty==="self"?an(r.counterparty,r.prover)||L(n,"counterparty","the prover's identity key for counterparty self"):s?.counterparty==="anyone"?an(r.counterparty,f2)||L(n,"counterparty","the canonical anyone public key"):typeof s?.counterparty=="string"&&!an(r.counterparty,s.counterparty)&&L(n,"counterparty","the requested counterparty"),qt(s?.protocolID)&&(r.protocolID[0]!==s.protocolID[0]||r.protocolID[1]!==s.protocolID[1])&&L(n,"protocolID","the requested protocol"),s?.keyID!==void 0&&r.keyID!==s?.keyID&&L(n,"keyID","the requested key ID");break;case"listActions":N2(r,n,e);break;case"listOutputs":B2(r,n,e);break;case"listCertificates":case"discoverByIdentityKey":case"discoverByAttributes":R2(r,n,e);break;case"getHeight":Od(r.height,n,"height",1,4294967295);break;case"getHeaderForHeight":$e(r.header,n,"header",80);break;case"getNetwork":r.network!=="mainnet"&&r.network!=="testnet"&&L(n,"network","mainnet or testnet");break;case"getVersion":we(r.version,n,"version",7,30);break;case"acquireCertificate":Id(r,n,"certificate"),s?.type!==void 0&&r.type!==s?.type&&L(n,"certificate.type","the requested certificate type"),s?.certifier!==void 0&&!an(r.certifier,s?.certifier)&&L(n,"certificate.certifier","the requested certifier"),om(r,s,n,"certificate",s?.acquisitionProtocol!=="issuance");break;case"proveCertificate":{let o=Ko(r.keyringForVerifier,n,"keyringForVerifier",!0),c=qt(s?.fieldsToReveal)?s.fieldsToReveal:[],u=new cn;for(let l=0;l<c.length;l++)Gt(u,Be(c[l]));let f=In(o),d=f.length===Gc(u);for(let l=0;d&&l<f.length;l++)d=un(u,f[l]);d||L(n,"keyringForVerifier","exactly the requested certificate fields")}if(r.certificate!==void 0){let o=Id(r.certificate,n,"certificate");om(o,s?.certificate,n,"certificate")}r.verifier!==void 0&&jo(r.verifier,n,"verifier"),r.verifier!==void 0&&s?.verifier!==void 0&&!an(r.verifier,s?.verifier)&&L(n,"verifier","the requested verifier");break}return i}var Nd;(function(n){n[n.createAction=1]="createAction",n[n.signAction=2]="signAction",n[n.abortAction=3]="abortAction",n[n.listActions=4]="listActions",n[n.internalizeAction=5]="internalizeAction",n[n.listOutputs=6]="listOutputs",n[n.relinquishOutput=7]="relinquishOutput",n[n.getPublicKey=8]="getPublicKey",n[n.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",n[n.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",n[n.encrypt=11]="encrypt",n[n.decrypt=12]="decrypt",n[n.createHmac=13]="createHmac",n[n.verifyHmac=14]="verifyHmac",n[n.createSignature=15]="createSignature",n[n.verifySignature=16]="verifySignature",n[n.acquireCertificate=17]="acquireCertificate",n[n.listCertificates=18]="listCertificates",n[n.proveCertificate=19]="proveCertificate",n[n.relinquishCertificate=20]="relinquishCertificate",n[n.discoverByIdentityKey=21]="discoverByIdentityKey",n[n.discoverByAttributes=22]="discoverByAttributes",n[n.isAuthenticated=23]="isAuthenticated",n[n.waitForAuthentication=24]="waitForAuthentication",n[n.getHeight=25]="getHeight",n[n.getHeaderForHeight=26]="getHeaderForHeight",n[n.getNetwork=27]="getNetwork",n[n.getVersion=28]="getVersion"})(Nd||(Nd={}));var vs=Nd;function xt(n,t){switch(n){case"createAction":gc(t);return;case"signAction":mc(t);return;case"abortAction":bc(t);return;case"listActions":Pc(t);return;case"internalizeAction":wc(t);return;case"listOutputs":Oc(t);return;case"relinquishOutput":xc(t);return;case"getPublicKey":Rc(t);return;case"revealCounterpartyKeyLinkage":Nc(t);return;case"revealSpecificKeyLinkage":Bc(t);return;case"encrypt":_c(t);return;case"decrypt":Cc(t);return;case"createHmac":Lc(t);return;case"verifyHmac":Uc(t);return;case"createSignature":Mc(t);return;case"verifySignature":Dc(t);return;case"acquireCertificate":{let e=t;if(e?.acquisitionProtocol==="direct")Ac(e);else if(e?.acquisitionProtocol==="issuance")vc(e);else throw new ei("acquisitionProtocol","direct or issuance");return}case"listCertificates":Ic(t);return;case"proveCertificate":Ec(t);return;case"relinquishCertificate":Sc(t);return;case"discoverByIdentityKey":kc(t);return;case"discoverByAttributes":Tc(t);return;case"getHeaderForHeight":Hc(t);return;case"isAuthenticated":case"waitForAuthentication":case"getHeight":case"getNetwork":case"getVersion":Mi(t)}}var As=class{constructor(){b(this,"CWI");if(typeof window!="object")throw new TypeError("The window.CWI substrate requires a global window object.");if(typeof window.CWI!="object")throw new TypeError("The window.CWI interface does not appear to be bound to the window object.");let t=window.CWI;this.CWI=new Proxy(t,{get(e,i,r){let s=Reflect.get(e,i,r);return typeof i!="string"||!Object.prototype.hasOwnProperty.call(vs,i)||typeof s!="function"?s:(o,...c)=>(xt(i,o),Reflect.apply(s,e,[o,...c]))}})}async validatedResult(t,e,i){return Ft(t,await e,i)}async createAction(t,e){let i=mt("createAction",t);return await this.validatedResult("createAction",this.CWI.createAction(t,e),i)}async signAction(t,e){let i=mt("signAction",t);return await this.validatedResult("signAction",this.CWI.signAction(t,e),i)}async abortAction(t,e){return await this.validatedResult("abortAction",this.CWI.abortAction(t,e))}async listActions(t,e){let i=mt("listActions",t);return await this.validatedResult("listActions",this.CWI.listActions(t,e),i)}async internalizeAction(t,e){return await this.validatedResult("internalizeAction",this.CWI.internalizeAction(t,e))}async listOutputs(t,e){let i=mt("listOutputs",t);return await this.validatedResult("listOutputs",this.CWI.listOutputs(t,e),i)}async relinquishOutput(t,e){return await this.validatedResult("relinquishOutput",this.CWI.relinquishOutput(t,e))}async getPublicKey(t,e){return await this.validatedResult("getPublicKey",this.CWI.getPublicKey(t,e))}async revealCounterpartyKeyLinkage(t,e){let i=mt("revealCounterpartyKeyLinkage",t);return await this.validatedResult("revealCounterpartyKeyLinkage",this.CWI.revealCounterpartyKeyLinkage(t,e),i)}async revealSpecificKeyLinkage(t,e){let i=mt("revealSpecificKeyLinkage",t);return await this.validatedResult("revealSpecificKeyLinkage",this.CWI.revealSpecificKeyLinkage(t,e),i)}async encrypt(t,e){return await this.validatedResult("encrypt",this.CWI.encrypt(t,e))}async decrypt(t,e){return await this.validatedResult("decrypt",this.CWI.decrypt(t,e))}async createHmac(t,e){return await this.validatedResult("createHmac",this.CWI.createHmac(t,e))}async verifyHmac(t,e){return await this.validatedResult("verifyHmac",this.CWI.verifyHmac(t,e))}async createSignature(t,e){return await this.validatedResult("createSignature",this.CWI.createSignature(t,e))}async verifySignature(t,e){return await this.validatedResult("verifySignature",this.CWI.verifySignature(t,e))}async acquireCertificate(t,e){let i=mt("acquireCertificate",t);return await this.validatedResult("acquireCertificate",this.CWI.acquireCertificate(t,e),i)}async listCertificates(t,e){let i=mt("listCertificates",t);return await this.validatedResult("listCertificates",this.CWI.listCertificates(t,e),i)}async proveCertificate(t,e){let i=mt("proveCertificate",t);return await this.validatedResult("proveCertificate",this.CWI.proveCertificate(t,e),i)}async relinquishCertificate(t,e){return await this.validatedResult("relinquishCertificate",this.CWI.relinquishCertificate(t,e))}async discoverByIdentityKey(t,e){let i=mt("discoverByIdentityKey",t);return await this.validatedResult("discoverByIdentityKey",this.CWI.discoverByIdentityKey(t,e),i)}async discoverByAttributes(t,e){let i=mt("discoverByAttributes",t);return await this.validatedResult("discoverByAttributes",this.CWI.discoverByAttributes(t,e),i)}async isAuthenticated(t,e){return await this.validatedResult("isAuthenticated",this.CWI.isAuthenticated(t,e))}async waitForAuthentication(t,e){return await this.validatedResult("waitForAuthentication",this.CWI.waitForAuthentication(t,e))}async getHeight(t,e){return await this.validatedResult("getHeight",this.CWI.getHeight(t,e))}async getHeaderForHeight(t,e){return await this.validatedResult("getHeaderForHeight",this.CWI.getHeaderForHeight(t,e))}async getNetwork(t,e){return await this.validatedResult("getNetwork",this.CWI.getNetwork(t,e))}async getVersion(t,e){return await this.validatedResult("getVersion",this.CWI.getVersion(t,e))}};var oi=class extends Error{constructor(e,i=1,r){super(e);b(this,"code");b(this,"isError",!0);this.code=i,this.name=this.constructor.name,r!=null&&r!==""?this.stack=r:Error.captureStackTrace(this,this.constructor)}static unknownToJson(e){let i;return e.isError===!0&&String(e.name).startsWith("WERR_")?(i={name:e.name,message:e.message,isError:!0},i.name==="WERR_REVIEW_ACTIONS"?(i.reviewActionResults=e.reviewActionResults,i.sendWithResults=e.sendWithResults,i.txid=e.txid,i.tx=e.tx,i.noSendChange=e.noSendChange,i.code=5):i.name==="WERR_INVALID_PARAMETER"?(i.parameter=e.parameter,i.code=6):i.name==="WERR_INSUFFICIENT_FUNDS"&&(i.totalSatoshisNeeded=e.totalSatoshisNeeded,i.moreSatoshisNeeded=e.moreSatoshisNeeded,i.code=7)):e instanceof Error?i={name:e.constructor.name,message:e.message,isError:!0}:i={name:"WERR_UNKNOWN",message:String(e),isError:!0},ys(i)}},fn;(function(n){n[n.unknownError=1]="unknownError",n[n.unsupportedAction=2]="unsupportedAction",n[n.invalidHmac=3]="invalidHmac",n[n.invalidSignature=4]="invalidSignature",n[n.reviewActions=5]="reviewActions",n[n.invalidParameter=6]="invalidParameter",n[n.insufficientFunds=7]="insufficientFunds",n[n.abortRefused=8]="abortRefused"})(fn||(fn={}));var Es=class{async invokeRaw(t,e,i){throw new Error("This substrate must implement invoke() or invokeRaw().")}async invoke(t,e){xt(t,e);let i=mt(t,e);return await this.invokeRaw(t,e,i)}async createAction(t){return await this.invoke("createAction",t)}async signAction(t){return await this.invoke("signAction",t)}async abortAction(t){return await this.invoke("abortAction",t)}async listActions(t){return await this.invoke("listActions",t)}async internalizeAction(t){return await this.invoke("internalizeAction",t)}async listOutputs(t){return await this.invoke("listOutputs",t)}async relinquishOutput(t){return await this.invoke("relinquishOutput",t)}async getPublicKey(t){return await this.invoke("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.invoke("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.invoke("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.invoke("encrypt",t)}async decrypt(t){return await this.invoke("decrypt",t)}async createHmac(t){return await this.invoke("createHmac",t)}async verifyHmac(t){return await this.invoke("verifyHmac",t)}async createSignature(t){return await this.invoke("createSignature",t)}async verifySignature(t){return await this.invoke("verifySignature",t)}async acquireCertificate(t){return await this.invoke("acquireCertificate",t)}async listCertificates(t){return await this.invoke("listCertificates",t)}async proveCertificate(t){return await this.invoke("proveCertificate",t)}async relinquishCertificate(t){return await this.invoke("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.invoke("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.invoke("discoverByAttributes",t)}async isAuthenticated(t){return await this.invoke("isAuthenticated",t)}async waitForAuthentication(t){return await this.invoke("waitForAuthentication",t)}async getHeight(t){return await this.invoke("getHeight",t)}async getHeaderForHeight(t){return await this.invoke("getHeaderForHeight",t)}async getNetwork(t){return await this.invoke("getNetwork",t)}async getVersion(t){return await this.invoke("getVersion",t)}};var _2=1024,vm=3600*1e3;function C2(n,t){if(typeof n!="object"||n===null)return!1;let e=n;return e.type!=="CWI"||e.isInvocation!==!1||e.id!==t?!1:e.status==="success"?!0:e.status==="error"&&typeof e.description=="string"&&at(e.description,"utf8").length<=4096&&typeof e.code=="number"&&Number.isSafeInteger(e.code)&&e.code>=1&&e.code<=255}var Fn=class extends Es{constructor(e="*",i){super();b(this,"domain");b(this,"responseTimeout");b(this,"pendingInvocations",0);if(typeof globalThis.window!="object")throw new TypeError("The XDM substrate requires a global window object.");if(typeof globalThis.window.postMessage!="function")throw new TypeError("The window object does not seem to support postMessage calls.");if(i!==void 0&&(!Number.isSafeInteger(i)||i<1||i>vm))throw new TypeError(`XDM responseTimeout must be an integer from 1 to ${vm}.`);this.domain=e,this.responseTimeout=i}async invokeRaw(e,i,r){if(this.pendingInvocations>=_2)throw new Error("XDM wallet pending invocation limit reached.");let s=ve(Pe(12));return this.pendingInvocations++,await new Promise((o,c)=>{let u,f=!1,d=!0,l=()=>{if(d&&(d=!1,this.pendingInvocations--,u!==void 0&&clearTimeout(u),f&&typeof window.removeEventListener=="function"))try{window.removeEventListener("message",p)}catch{}},p=m=>{if(!(!m.isTrusted||m.source!==window.parent||this.domain!=="*"&&m.origin!==this.domain||!C2(m.data,s)))if(l(),m.data.status==="error"){let g=m.data.code>=fn.unsupportedAction&&m.data.code<=fn.abortRefused,w=g?m.data.description:"Wallet operation failed",S=new oi(w,g?m.data.code:fn.unknownError);c(S)}else try{o(Ft(e,m.data.result,r))}catch(g){c(g)}};try{window.addEventListener("message",p),f=!0,this.responseTimeout!==void 0&&(u=setTimeout(()=>{l(),c(new Error("XDM wallet response timed out."))},this.responseTimeout)),window.parent.postMessage({type:"CWI",isInvocation:!0,id:s,call:e,args:i},this.domain)}catch(m){l(),c(m)}})}};var eu=16*1024*1024,nu=1e5,iu=1024*1024,Am=72;function Em(n,t,e){let i;try{i=dc(n)}catch{throw new Error(`Invalid certificate ${t}: expected canonical base64`)}return Tm(i,t,e),i}function L2(n){if(n==null||typeof n!="object"||Array.isArray(n))throw new Error("Certificate fields must be a plain object");let t=Object.getPrototypeOf(n);if(t!==Object.prototype&&t!==null)throw new Error("Certificate fields must be a plain object");let e=Reflect.ownKeys(n);if(e.length>nu)throw new Error(`Certificate field count exceeds the maximum of ${nu}`);let i=Object.create(null);for(let r of e){if(typeof r!="string")throw new Error("Certificate fields cannot contain symbol keys");let s=Object.getOwnPropertyDescriptor(n,r);if(s==null||!Object.hasOwn(s,"value")||typeof s.value!="string")throw new Error(`Certificate field ${r} must be an own string data property`);let o=at(r,"utf8");if(Bd(r,o.length),at(s.value,"utf8").length>iu)throw new Error(`Certificate field ${r} exceeds the maximum of ${iu} bytes`);i[r]=s.value}return i}function km(n){let t=n instanceof Uint8Array?Array.from(n):n;if(!Array.isArray(t)||t.length>eu)throw new Error(`Certificate binary must be a byte array of at most ${eu} bytes`);let e=Array.from({length:t.length});for(let i=0;i<t.length;i++){let r=Object.getOwnPropertyDescriptor(t,i);if(r==null||!Object.hasOwn(r,"value")||!Number.isInteger(r.value)||r.value<0||r.value>255)throw new Error("Certificate binary must be a dense byte array");e[i]=r.value}return e}function U2(n,t){if(n.length!==t.length)return!1;let e=0;for(let i=0;i<n.length;i++)e|=n[i]^t[i];return e===0}function Bd(n,t){if(t<1||t>50)throw new Error(`Invalid certificate field name length: expected 1\u201350 bytes, received ${t}`);if(gn(n))throw new Error(`Unsafe certificate field name: ${n}`)}function Tm(n,t,e){if(n.length!==e)throw new Error(`Invalid certificate ${t} length: expected ${e} bytes, received ${n.length}`)}function tu(n,t){Tm(n,t,33);try{Ht.fromDER(n)}catch{throw new Error(`Invalid certificate ${t}: expected a compressed secp256k1 public key`)}}var Lr=class n{constructor(t,e,i,r,s,o,c){b(this,"type");b(this,"serialNumber");b(this,"subject");b(this,"certifier");b(this,"revocationOutpoint");b(this,"fields");b(this,"signature");this.type=t,this.serialNumber=e,this.subject=i,this.certifier=r,this.revocationOutpoint=s,this.fields=o,this.signature=c}toBinary(t=!0){let e=new fe,i=Em(this.type,"type",32);e.write(i);let r=Em(this.serialNumber,"serial number",32);if(e.write(r),!/^(02|03)[0-9a-fA-F]{64}$/.test(this.subject))throw new Error("Invalid certificate subject: expected compressed public key hex");let s=at(this.subject,"hex");if(tu(s,"subject"),e.write(s),!/^(02|03)[0-9a-fA-F]{64}$/.test(this.certifier))throw new Error("Invalid certificate certifier: expected compressed public key hex");let o=at(this.certifier,"hex");if(tu(o,"certifier"),e.write(o),typeof this.revocationOutpoint!="string")throw new Error("Invalid certificate revocation outpoint");let c=this.revocationOutpoint.split("."),[u,f="0"]=c;if(c.length>2||!/^[0-9a-fA-F]{64}$/.test(u)||!/^(?:0|[1-9]\d*)$/.test(f)||Number(f)>4294967295)throw new Error(`Invalid certificate revocation outpoint: ${this.revocationOutpoint}`);let d=at(u,"hex");if(d.length!==32)throw new Error(`Invalid certificate revocation txid length: ${d.length}`);e.write(d),e.writeVarIntNum(Number(f));let l=L2(this.fields),p=Object.keys(l).sort((g,w)=>g.localeCompare(w));e.writeVarIntNum(p.length);for(let g of p){let w=l[g],S=at(g,"utf8");Bd(g,S.length),e.writeVarIntNum(S.length),e.write(S);let C=at(w,"utf8");e.writeVarIntNum(C.length),e.write(C)}if(t&&(this.signature??"").length>0){if(typeof this.signature!="string"||this.signature.length>Am*2||!/^(?:[0-9a-fA-F]{2})+$/.test(this.signature))throw new Error("Invalid certificate signature encoding");let g=at(this.signature,"hex");ge.fromDER(g),e.write(g)}let m=e.toArray();if(m.length>eu)throw new Error(`Certificate binary exceeds the maximum of ${eu} bytes`);return m}static fromBinary(t){let e=new bt(km(t)),i=e.read(32),r=ve(i),s=e.read(32),o=ve(s),c=e.read(33);tu(Array.from(c),"subject");let u=nt(c),f=e.read(33);tu(Array.from(f),"certifier");let d=nt(f),l=e.read(32),p=nt(l),m=e.readVarIntNumStrict(!1),g=`${p}.${m}`,w=e.readVarIntNumStrict(!1);if(w>nu)throw new Error(`Certificate field count exceeds the maximum of ${nu}`);if(w>Math.floor(e.remaining()/3))throw new Error("Certificate field count exceeds the available data");let S=new Map;for(let E=0;E<w;E++){let A=e.readVarIntNumStrict(!1);if(A<1||A>50)throw new Error(`Invalid certificate field name length: received ${A}`);let k=e.read(A),B=Rt(k);if(Bd(B,A),S.has(B))throw new Error(`Duplicate certificate field name: ${B}`);let _=e.readVarIntNumStrict(!1);if(_>iu)throw new Error(`Certificate field ${B} exceeds the maximum of ${iu} bytes`);let H=e.read(_),O=Rt(H);S.set(B,O)}let C;if(!e.eof()){if(e.remaining()>Am)throw new Error("Certificate signature exceeds the DER size limit");let E=e.read();C=ge.fromDER(Array.from(E)).toString("hex")}return new n(r,o,u,d,g,Object.fromEntries(S),C)}async verify(){try{let t=this.toBinary(!1);return Ht.fromString(this.certifier).deriveChild(new T(1),`2-certificate signature-${this.type} ${this.serialNumber}`).verify(t,ge.fromDER(at(this.signature??"","hex")))}catch{return!1}}async sign(t){if(this.signature!=null&&this.signature.length>0)throw new Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await t.getPublicKey({identityKey:!0})).publicKey;let e=this.toBinary(!1),{signature:i}=await t.createSignature({data:e,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});if(!U2(e,this.toBinary(!1)))throw new Error("Certificate changed while its signature was being created");let r=km(i),s=ge.fromDER(r);this.signature=s.toString("hex")}static getCertificateFieldEncryptionDetails(t,e){return{protocolID:[2,"certificate field encryption"],keyID:e?`${e} ${t}`:t}}static fromObject(t){return new n(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,t.signature)}};var M2=1e5,D2={1:"completed",2:"unprocessed",3:"sending",4:"unproven",5:"unsigned",6:"nosend",7:"nonfinal",8:"failed"},v,Nt,Om,Pm,Rm,Nm,Bm,_m,Cm,Lm,ks,ru,Dt,ai,Ur,su,ou,au,_d,Um,Mm,Dm,Hm,ci,Mr,Cd,Hi,Go,Yo,Je,ui,Zo,Jo,$i,$m,Ee,Dr,qi,cu=class cu{constructor(t){G(this,v);b(this,"wire");this.wire=t}async createAction(t,e){xt("createAction",t);let i=mt("createAction",t),r=new ht(void 0,Math.max(256,Math.ceil((t.inputBEEF?.length??0)+(t.inputs??[]).reduce((o,c)=>o+(c.unlockingScript?.length??0)/2,0)+(t.outputs??[]).reduce((o,c)=>o+c.lockingScript.length/2,0)+4096)));if(a(this,v,Ur).call(this,r,t.description),t.inputBEEF==null?r.writeVarIntNum(-1):(r.writeVarIntNum(t.inputBEEF.length),r.write(t.inputBEEF)),t.inputs==null)r.writeVarIntNum(-1);else{r.writeVarIntNum(t.inputs.length);for(let o of t.inputs)a(this,v,Um).call(this,r,o)}if(t.outputs==null)r.writeVarIntNum(-1);else{r.writeVarIntNum(t.outputs.length);for(let o of t.outputs)a(this,v,Mm).call(this,r,o)}a(this,v,ai).call(this,r,t.lockTime),a(this,v,ai).call(this,r,t.version),a(this,v,ou).call(this,r,t.labels),a(this,v,Dm).call(this,r,t.options);let s=await a(this,v,Nt).call(this,"createAction",e,r.toUint8ArrayZeroCopy());return Ft("createAction",a(this,v,Om).call(this,s),i)}async signAction(t,e){xt("signAction",t);let i=mt("signAction",t),r=new ht,s=Object.keys(t.spends);r.writeVarIntNum(s.length);for(let l of s){r.writeVarIntNum(Number(l));let p=t.spends[Number(l)],m=et(p.unlockingScript,"hex");r.writeVarIntNum(m.length),r.write(m),a(this,v,ai).call(this,r,p.sequenceNumber)}let o=et(t.reference,"base64");r.writeVarIntNum(o.length),r.write(o),a(this,v,Hm).call(this,r,t.options);let c=await a(this,v,Nt).call(this,"signAction",e,r.toUint8ArrayZeroCopy()),u=new bt(c),f={};a(this,v,ui).call(this,u,"signAction txid present")&&(f.txid=nt(u.read(32))),a(this,v,ui).call(this,u,"signAction tx present")&&(f.tx=u.readView(u.readVarIntNumStrict(!1)));let d=a(this,v,_d).call(this,u);return d!=null&&(f.sendWithResults=d),a(this,v,Hi).call(this,u,"signAction"),Ft("signAction",f,i)}async abortAction(t,e){xt("abortAction",t);try{let i=await a(this,v,Nt).call(this,"abortAction",e,et(t.reference,"base64"));return a(this,v,qi).call(this,i,"abortAction"),{aborted:!0}}catch(i){if(i instanceof oi&&i.code===fn.abortRefused)return{aborted:!1};throw i}}async listActions(t,e){xt("listActions",t);let i=new ht;i.writeVarIntNum(t.labels.length);for(let u of t.labels)a(this,v,Ur).call(this,i,u);t.labelQueryMode==="any"?i.writeInt8(1):t.labelQueryMode==="all"?i.writeInt8(2):i.writeInt8(-1);for(let u of[t.includeLabels,t.includeInputs,t.includeInputSourceLockingScripts,t.includeInputUnlockingScripts,t.includeOutputs,t.includeOutputLockingScripts])a(this,v,Dt).call(this,i,u);a(this,v,ai).call(this,i,t.limit),a(this,v,ai).call(this,i,t.offset),a(this,v,Dt).call(this,i,t.seekPermission);let r=await a(this,v,Nt).call(this,"listActions",e,i.toUint8Array()),s=new bt(r),o=a(this,v,Ee).call(this,s.readVarIntNumStrict(!1),"listActions totalActions",0,4294967295),c=[];for(;!s.eof();)a(this,v,Yo).call(this,c.length,t.limit,"listActions"),c.push(a(this,v,Nm).call(this,s));return a(this,v,Go).call(this,c.length,o,"listActions"),{totalActions:o,actions:c}}async internalizeAction(t,e){xt("internalizeAction",t);let i=new ht(void 0,Math.max(256,t.tx.length+4096));i.writeVarIntNum(t.tx.length),i.write(t.tx),i.writeVarIntNum(t.outputs.length);for(let o of t.outputs)a(this,v,Cm).call(this,i,o);a(this,v,ou).call(this,i,typeof t.labels=="object"?t.labels:void 0);let r=et(t.description);i.writeVarIntNum(r.length),i.write(r),a(this,v,Dt).call(this,i,t.seekPermission);let s=await a(this,v,Nt).call(this,"internalizeAction",e,i.toUint8ArrayZeroCopy());return a(this,v,qi).call(this,s,"internalizeAction"),{accepted:!0}}async listOutputs(t,e){xt("listOutputs",t);let i=mt("listOutputs",t),r=new ht;if(a(this,v,Ur).call(this,r,t.basket),typeof t.tags=="object"){r.writeVarIntNum(t.tags.length);for(let l of t.tags)a(this,v,Ur).call(this,r,l)}else r.writeVarIntNum(0);t.tagQueryMode==="all"?r.writeInt8(1):t.tagQueryMode==="any"?r.writeInt8(2):r.writeInt8(-1),t.include==="locking scripts"?r.writeInt8(1):t.include==="entire transactions"?r.writeInt8(2):r.writeInt8(-1),a(this,v,Dt).call(this,r,t.includeCustomInstructions),a(this,v,Dt).call(this,r,t.includeTags),a(this,v,Dt).call(this,r,t.includeLabels),a(this,v,ai).call(this,r,t.limit),a(this,v,ai).call(this,r,t.offset),a(this,v,Dt).call(this,r,t.seekPermission);let s=await a(this,v,Nt).call(this,"listOutputs",e,r.toUint8Array()),o=new bt(s),c=a(this,v,Ee).call(this,o.readVarIntNumStrict(!1),"listOutputs totalOutputs",0,4294967295),u=o.readVarIntNumStrict(),f=u>=0?o.readView(u):void 0,d=[];for(;!o.eof();)a(this,v,Yo).call(this,d.length,t.limit,"listOutputs"),d.push(a(this,v,Lm).call(this,o));return a(this,v,Go).call(this,d.length,c,"listOutputs"),Ft("listOutputs",{totalOutputs:c,BEEF:f,outputs:d},i)}async relinquishOutput(t,e){xt("relinquishOutput",t);let i=new ht,r=et(t.basket,"utf8");i.writeVarIntNum(r.length),i.write(r),i.write(a(this,v,ks).call(this,t.output));let s=await a(this,v,Nt).call(this,"relinquishOutput",e,i.toUint8Array());return a(this,v,qi).call(this,s,"relinquishOutput"),{relinquished:!0}}async getPublicKey(t,e){xt("getPublicKey",t);let i=new ht;i.writeUInt8(t.identityKey?1:0),t.identityKey?i.write(a(this,v,Mr).call(this,t.privileged,t.privilegedReason)):(t.protocolID??(t.protocolID=[$c.Silent,"default"]),t.keyID??(t.keyID=""),i.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),typeof t.forSelf=="boolean"?i.writeInt8(t.forSelf?1:0):i.writeInt8(-1)),a(this,v,Dt).call(this,i,t.seekPermission);let r=await a(this,v,Nt).call(this,"getPublicKey",e,i.toUint8Array());return a(this,v,Dr).call(this,r,33,"getPublicKey"),Ht.fromDER(Array.from(r)),{publicKey:nt(r)}}async revealCounterpartyKeyLinkage(t,e){xt("revealCounterpartyKeyLinkage",t);let i=mt("revealCounterpartyKeyLinkage",t),r=new ht;r.write(a(this,v,Mr).call(this,t.privileged,t.privilegedReason)),r.write(et(t.counterparty,"hex")),r.write(et(t.verifier,"hex"));let s=await a(this,v,Nt).call(this,"revealCounterpartyKeyLinkage",e,r.toUint8Array()),o=new bt(s),c=a(this,v,$i).call(this,o,"revealCounterpartyKeyLinkage prover"),u=a(this,v,$i).call(this,o,"revealCounterpartyKeyLinkage verifier"),f=a(this,v,$i).call(this,o,"revealCounterpartyKeyLinkage counterparty"),d=o.readVarIntNumStrict(!1),l=Rt(o.read(d)),p=o.readVarIntNumStrict(!1),m=o.read(p),g=o.readVarIntNumStrict(!1),w=o.read(g);return a(this,v,Hi).call(this,o,"revealCounterpartyKeyLinkage"),Ft("revealCounterpartyKeyLinkage",{prover:c,verifier:u,counterparty:f,revelationTime:l,encryptedLinkage:Array.from(m),encryptedLinkageProof:Array.from(w)},i)}async revealSpecificKeyLinkage(t,e){xt("revealSpecificKeyLinkage",t);let i=mt("revealSpecificKeyLinkage",t),r=new ht;r.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),r.write(et(t.verifier,"hex"));let s=await a(this,v,Nt).call(this,"revealSpecificKeyLinkage",e,r.toUint8Array()),o=new bt(s),c=a(this,v,$i).call(this,o,"revealSpecificKeyLinkage prover"),u=a(this,v,$i).call(this,o,"revealSpecificKeyLinkage verifier"),f=a(this,v,$i).call(this,o,"revealSpecificKeyLinkage counterparty"),d=a(this,v,$m).call(this,o,"revealSpecificKeyLinkage"),l=o.readVarIntNumStrict(!1),p=Rt(o.read(l)),m=o.readVarIntNumStrict(!1),g=Rt(o.read(m)),w=o.readVarIntNumStrict(!1),S=o.read(w),C=o.readVarIntNumStrict(!1),E=o.read(C),A=o.readUInt8();return a(this,v,Hi).call(this,o,"revealSpecificKeyLinkage"),Ft("revealSpecificKeyLinkage",{prover:c,verifier:u,counterparty:f,protocolID:[d,p],keyID:g,encryptedLinkage:Array.from(S),encryptedLinkageProof:Array.from(E),proofType:A},i)}async encrypt(t,e){xt("encrypt",t);let i=new ht;return i.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.plaintext.length),i.write(t.plaintext),a(this,v,Dt).call(this,i,t.seekPermission),{ciphertext:Array.from(await a(this,v,Nt).call(this,"encrypt",e,i.toUint8Array()))}}async decrypt(t,e){xt("decrypt",t);let i=new ht;return i.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.ciphertext.length),i.write(t.ciphertext),a(this,v,Dt).call(this,i,t.seekPermission),{plaintext:Array.from(await a(this,v,Nt).call(this,"decrypt",e,i.toUint8Array()))}}async createHmac(t,e){xt("createHmac",t);let i=new ht;i.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.data.length),i.write(t.data),a(this,v,Dt).call(this,i,t.seekPermission);let r=await a(this,v,Nt).call(this,"createHmac",e,i.toUint8Array());return a(this,v,Dr).call(this,r,32,"createHmac"),{hmac:Array.from(r)}}async verifyHmac(t,e){xt("verifyHmac",t);let i=new ht;i.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.write(t.hmac),i.writeVarIntNum(t.data.length),i.write(t.data),a(this,v,Dt).call(this,i,t.seekPermission);let r=await a(this,v,Nt).call(this,"verifyHmac",e,i.toUint8Array());return a(this,v,qi).call(this,r,"verifyHmac"),{valid:!0}}async createSignature(t,e){xt("createSignature",t);let i=new ht;return i.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),typeof t.data=="object"?(i.writeUInt8(1),i.writeVarIntNum(t.data.length),i.write(t.data)):(t.hashToDirectlySign??(t.hashToDirectlySign=[]),i.writeUInt8(2),i.write(t.hashToDirectlySign)),a(this,v,Dt).call(this,i,t.seekPermission),Ft("createSignature",{signature:Array.from(await a(this,v,Nt).call(this,"createSignature",e,i.toUint8Array()))},t)}async verifySignature(t,e){xt("verifySignature",t);let i=new ht;i.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),typeof t.forSelf=="boolean"?i.writeInt8(t.forSelf?1:0):i.writeInt8(-1),i.writeVarIntNum(t.signature.length),i.write(t.signature),typeof t.data=="object"?(i.writeUInt8(1),i.writeVarIntNum(t.data.length),i.write(t.data)):(i.writeUInt8(2),i.write(t.hashToDirectlyVerify??[])),a(this,v,Dt).call(this,i,t.seekPermission);let r=await a(this,v,Nt).call(this,"verifySignature",e,i.toUint8Array());return a(this,v,qi).call(this,r,"verifySignature"),{valid:!0}}async acquireCertificate(t,e){xt("acquireCertificate",t);let i=mt("acquireCertificate",t),r=new ht;r.write(et(t.type,"base64")),r.write(et(t.certifier,"hex"));let s=Object.entries(t.fields);r.writeVarIntNum(s.length);for(let[u,f]of s){let d=et(u,"utf8"),l=et(f,"utf8");r.writeVarIntNum(d.length),r.write(d),r.writeVarIntNum(l.length),r.write(l)}if(r.write(a(this,v,Mr).call(this,t.privileged,t.privilegedReason)),r.writeUInt8(t.acquisitionProtocol==="direct"?1:2),t.acquisitionProtocol==="direct"){r.write(et(t.serialNumber,"base64")),r.write(a(this,v,ks).call(this,t.revocationOutpoint??""));let u=et(t.signature,"hex");r.writeVarIntNum(u.length),r.write(u);let f=t.keyringRevealer==="certifier"?[11]:et(t.keyringRevealer,"hex");r.write(f);let d=Object.keys(t.keyringForSubject??{});r.writeVarIntNum(d.length);for(let l of d){let p=et(l,"utf8");r.writeVarIntNum(p.length),r.write(p);let m=et(t.keyringForSubject?.[l],"base64");r.writeVarIntNum(m.length),r.write(m)}}else{let u=et(t.certifierUrl,"utf8");r.writeVarIntNum(u.length),r.write(u)}let o=await a(this,v,Nt).call(this,"acquireCertificate",e,r.toUint8Array()),c=Lr.fromBinary(o);return Ft("acquireCertificate",{...c,signature:c.signature},i)}async listCertificates(t,e){xt("listCertificates",t);let i=mt("listCertificates",t),r=new ht;r.writeVarIntNum(t.certifiers.length);for(let f of t.certifiers)r.write(et(f,"hex"));r.writeVarIntNum(t.types.length);for(let f of t.types)r.write(et(f,"base64"));typeof t.limit=="number"?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),typeof t.offset=="number"?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),r.write(a(this,v,Mr).call(this,t.privileged,t.privilegedReason));let s=await a(this,v,Nt).call(this,"listCertificates",e,r.toUint8Array()),o=new bt(s),c=a(this,v,Ee).call(this,o.readVarIntNumStrict(!1),"listCertificates totalCertificates",0,4294967295),u=[];for(;!o.eof();){a(this,v,Yo).call(this,u.length,t.limit,"listCertificates");let f=o.readVarIntNumStrict(!1),d=o.read(f),l=Lr.fromBinary(d),p={};if(a(this,v,ui).call(this,o,"listCertificates keyring present")){let w=o.readVarIntNumStrict(!1);a(this,v,Je).call(this,o,w,"listCertificates keyring");for(let S=0;S<w;S++){let C=o.readVarIntNumStrict(!1),E=a(this,v,Zo).call(this,o,C,"listCertificates keyring"),A=o.readVarIntNumStrict(!1);a(this,v,Jo).call(this,p,E,ve(o.read(A)),"listCertificates keyring")}}let m=o.readVarIntNumStrict(!1),g;if(m>0){if(m!==33)throw new Error(`Invalid listCertificates verifier length: expected 33 bytes, received ${m}`);g=a(this,v,$i).call(this,o,"listCertificates verifier")}u.push({...l,signature:l.signature,keyring:p,verifier:g})}return a(this,v,Go).call(this,u.length,c,"listCertificates"),Ft("listCertificates",{totalCertificates:c,certificates:u},i)}async proveCertificate(t,e){xt("proveCertificate",t);let i=mt("proveCertificate",t),r=new ht,s=et(t.certificate.type,"base64");r.write(s);let o=et(t.certificate.subject,"hex");r.write(o);let c=et(t.certificate.serialNumber,"base64");r.write(c);let u=et(t.certificate.certifier,"hex");r.write(u);let f=a(this,v,ks).call(this,t.certificate.revocationOutpoint??"");r.write(f);let d=et(t.certificate.signature,"hex");r.writeVarIntNum(d.length),r.write(d);let l=Object.entries(t.certificate.fields??{});r.writeVarIntNum(l.length);for(let[S,C]of l){let E=et(S,"utf8"),A=et(C,"utf8");r.writeVarIntNum(E.length),r.write(E),r.writeVarIntNum(A.length),r.write(A)}r.writeVarIntNum(t.fieldsToReveal.length);for(let S of t.fieldsToReveal){let C=et(S,"utf8");r.writeVarIntNum(C.length),r.write(C)}r.write(et(t.verifier,"hex")),r.write(a(this,v,Mr).call(this,t.privileged,t.privilegedReason));let p=await a(this,v,Nt).call(this,"proveCertificate",e,r.toUint8Array()),m=new bt(p),g=m.readVarIntNumStrict(!1);a(this,v,Je).call(this,m,g,"proveCertificate keyring");let w={};for(let S=0;S<g;S++){let C=m.readVarIntNumStrict(!1),E=a(this,v,Zo).call(this,m,C,"proveCertificate keyring"),A=m.readVarIntNumStrict(!1);a(this,v,Jo).call(this,w,E,ve(m.read(A)),"proveCertificate keyring")}return a(this,v,Hi).call(this,m,"proveCertificate"),Ft("proveCertificate",{keyringForVerifier:w},i)}async relinquishCertificate(t,e){xt("relinquishCertificate",t);let i=new ht,r=et(t.type,"base64");i.write(r);let s=et(t.serialNumber,"base64");i.write(s);let o=et(t.certifier,"hex");i.write(o);let c=await a(this,v,Nt).call(this,"relinquishCertificate",e,i.toUint8Array());return a(this,v,qi).call(this,c,"relinquishCertificate"),{relinquished:!0}}async discoverByIdentityKey(t,e){xt("discoverByIdentityKey",t);let i=mt("discoverByIdentityKey",t),r=new ht;r.write(et(t.identityKey,"hex")),typeof t.limit=="number"?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),typeof t.offset=="number"?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),a(this,v,Dt).call(this,r,t.seekPermission);let s=await a(this,v,Nt).call(this,"discoverByIdentityKey",e,r.toUint8Array());return Ft("discoverByIdentityKey",a(this,v,Cd).call(this,s,t.limit),i)}async discoverByAttributes(t,e){xt("discoverByAttributes",t);let i=mt("discoverByAttributes",t),r=new ht,s=Object.keys(t.attributes);r.writeVarIntNum(s.length);for(let c of s){let u=et(c,"utf8"),f=et(t.attributes[c],"utf8");r.writeVarIntNum(u.length),r.write(u),r.writeVarIntNum(f.length),r.write(f)}typeof t.limit=="number"?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),typeof t.offset=="number"?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),a(this,v,Dt).call(this,r,t.seekPermission);let o=await a(this,v,Nt).call(this,"discoverByAttributes",e,r.toUint8Array());return Ft("discoverByAttributes",a(this,v,Cd).call(this,o,t.limit),i)}async isAuthenticated(t,e){xt("isAuthenticated",t);let i=await a(this,v,Nt).call(this,"isAuthenticated",e);if(a(this,v,Dr).call(this,i,1,"isAuthenticated"),i[0]!==0&&i[0]!==1)throw new Error("Wallet returned an invalid authentication verdict");return{authenticated:i[0]===1}}async waitForAuthentication(t,e){xt("waitForAuthentication",t);let i=await a(this,v,Nt).call(this,"waitForAuthentication",e);return a(this,v,qi).call(this,i,"waitForAuthentication"),{authenticated:!0}}async getHeight(t,e){xt("getHeight",t);let i=await a(this,v,Nt).call(this,"getHeight",e),r=new bt(i),s=r.readVarIntNumStrict(!1);if(a(this,v,Hi).call(this,r,"getHeight"),s<1||s>4294967295)throw new Error("Wallet returned an invalid height");return{height:s}}async getHeaderForHeight(t,e){if(xt("getHeaderForHeight",t),!Number.isInteger(t.height)||t.height<1||t.height>4294967295)throw new Error("getHeaderForHeight requires a height from 1 to 4294967295");let i=new ht;i.writeVarIntNum(t.height);let r=await a(this,v,Nt).call(this,"getHeaderForHeight",e,i.toUint8Array());return a(this,v,Dr).call(this,r,80,"getHeaderForHeight"),{header:nt(r)}}async getNetwork(t,e){xt("getNetwork",t);let i=await a(this,v,Nt).call(this,"getNetwork",e);if(a(this,v,Dr).call(this,i,1,"getNetwork"),i[0]!==0&&i[0]!==1)throw new Error("Wallet returned an invalid network");return{network:i[0]===0?"mainnet":"testnet"}}async getVersion(t,e){xt("getVersion",t);let i=await a(this,v,Nt).call(this,"getVersion",e);if(i.length<7||i.length>30)throw new Error("Wallet returned an invalid version");return{version:Rt(i)}}};v=new WeakSet,Nt=async function(t,e="",i=[]){let r=e===""?"":ii(e),s=et(r,"utf8"),o=new ht(void 0,2+s.length+i.length);o.writeUInt8(vs[t]),o.writeUInt8(s.length),o.write(s),i.length>0&&o.write(i);let c=o.toUint8ArrayZeroCopy();if(c.length>268435456)throw new Error("Wallet Wire request exceeds the maximum permitted size");let u;if(this.wire.transmitToWalletUint8Array===void 0){let l=await this.wire.transmitToWallet(Array.from(c));if(!Array.isArray(l)||l.length>268435456)throw new Error("Wallet Wire response exceeds the maximum permitted size");for(let p=0;p<l.length;p++)if(!Object.prototype.hasOwnProperty.call(l,p)||!Number.isInteger(l[p])||l[p]<0||l[p]>255)throw new Error("Wallet Wire response must be a dense byte array");u=Uint8Array.from(l)}else{let l=await this.wire.transmitToWalletUint8Array(c);if(!(l instanceof Uint8Array)||l.length>268435456)throw new Error("Wallet Wire response exceeds the maximum permitted size");u=l}let f=new bt(u),d=f.readUInt8();if(d===0)return f.readView();{let l=f.readVarIntNumStrict(!1),p=f.read(l),m=Rt(p),g=f.readVarIntNumStrict(!1),w=f.read(g),S=Rt(w);throw a(this,v,Hi).call(this,f,t),new oi(m,d,S)}},Om=function(t){let e=new bt(t),i={};a(this,v,ui).call(this,e,"createAction txid present")&&(i.txid=nt(e.read(32))),a(this,v,ui).call(this,e,"createAction tx present")&&(i.tx=e.readView(e.readVarIntNumStrict(!1)));let r=e.readVarIntNumStrict();if(r>=0){a(this,v,Je).call(this,e,r,"createAction noSendChange",33),i.noSendChange=[];for(let o=0;o<r;o++)i.noSendChange.push(a(this,v,ru).call(this,e))}let s=a(this,v,_d).call(this,e);if(s!=null&&(i.sendWithResults=s),a(this,v,ui).call(this,e,"createAction signableTransaction present")){let o=e.readView(e.readVarIntNumStrict(!1)),c=e.read(e.readVarIntNumStrict(!1));i.signableTransaction={tx:o,reference:ve(c)}}return a(this,v,Hi).call(this,e,"createAction"),i},Pm=function(t){let e=D2[t];if(e==null)throw new Error(`Unknown status code: ${t}`);return e},Rm=function(t){let e;return t.remaining()>=9&&t.bin[t.pos]===255&&t.bin[t.pos+8]>=128?(t.skip(1),e=t.readInt64LEBn().toNumber()):e=t.readVarIntNumStrict(!1),a(this,v,Ee).call(this,e,"listActions satoshis",-21e14,21e14)},Nm=function(t){let e=nt(t.read(32)),i=a(this,v,Rm).call(this,t),r=a(this,v,Pm).call(this,t.readInt8()),s=a(this,v,ui).call(this,t,"listActions isOutgoing"),o=Rt(t.read(t.readVarIntNumStrict(!1))),c={txid:e,satoshis:i,status:r,isOutgoing:s,description:o,version:0,lockTime:0},u=t.readVarIntNumStrict();if(u>=0){a(this,v,Je).call(this,t,u,"listActions labels"),c.labels=[];for(let l=0;l<u;l++)c.labels.push(Rt(t.read(t.readVarIntNumStrict(!1))))}c.version=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"listActions version",0,4294967295),c.lockTime=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"listActions lockTime",0,4294967295);let f=t.readVarIntNumStrict();if(f>=0){a(this,v,Je).call(this,t,f,"listActions inputs"),c.inputs=[];for(let l=0;l<f;l++)c.inputs.push(a(this,v,Bm).call(this,t))}let d=t.readVarIntNumStrict();if(d>=0){a(this,v,Je).call(this,t,d,"listActions outputs"),c.outputs=[];for(let l=0;l<d;l++)c.outputs.push(a(this,v,_m).call(this,t))}return c},Bm=function(t){let e=a(this,v,ru).call(this,t),i=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"listActions input sourceSatoshis",0,21e14),r=t.readVarIntNumStrict(),s=r>=0?nt(t.read(r)):void 0,o=t.readVarIntNumStrict(),c=o>=0?nt(t.read(o)):void 0,u=Rt(t.read(t.readVarIntNumStrict(!1))),f=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"listActions input sequenceNumber",0,4294967295);return{sourceOutpoint:e,sourceSatoshis:i,sourceLockingScript:s,unlockingScript:c,inputDescription:u,sequenceNumber:f}},_m=function(t){let e=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"listActions output outputIndex",0,4294967295),i=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"listActions output satoshis",0,21e14),r=t.readVarIntNumStrict(),s=r>=0?nt(t.read(r)):void 0,o=a(this,v,ui).call(this,t,"listOutputs spendable"),c=Rt(t.read(t.readVarIntNumStrict(!1))),u=t.readVarIntNumStrict(),f=u>=0?Rt(t.read(u)):void 0,d=t.readVarIntNumStrict(),l=[];if(d>=0){a(this,v,Je).call(this,t,d,"listActions output tags");for(let g=0;g<d;g++)l.push(Rt(t.read(t.readVarIntNumStrict(!1))))}let p=t.readVarIntNumStrict(),m=p>=0?Rt(t.read(p)):void 0;return{outputIndex:e,satoshis:i,lockingScript:s,spendable:o,outputDescription:c,basket:f,tags:l,customInstructions:m}},Cm=function(t,e){if(t.writeVarIntNum(e.outputIndex),e.protocol==="wallet payment"){if(e.paymentRemittance==null)throw new Error("Payment remittance is required for wallet payment");t.writeUInt8(1),t.write(et(e.paymentRemittance.senderIdentityKey,"hex"));let i=et(e.paymentRemittance.derivationPrefix,"base64");t.writeVarIntNum(i.length),t.write(i);let r=et(e.paymentRemittance.derivationSuffix,"base64");t.writeVarIntNum(r.length),t.write(r)}else{t.writeUInt8(2);let i=et(e.insertionRemittance?.basket,"utf8");t.writeVarIntNum(i.length),t.write(i),a(this,v,su).call(this,t,e.insertionRemittance?.customInstructions);let r=e.insertionRemittance?.tags;if(typeof r=="object"){t.writeVarIntNum(r.length);for(let s of r){let o=et(s,"utf8");t.writeVarIntNum(o.length),t.write(o)}}else t.writeVarIntNum(0)}},Lm=function(t){let e=a(this,v,ru).call(this,t),i=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"listOutputs satoshis",0,21e14),r={spendable:!0,outpoint:e,satoshis:i},s=t.readVarIntNumStrict();s>=0&&(r.lockingScript=nt(t.read(s)));let o=t.readVarIntNumStrict();o>=0&&(r.customInstructions=Rt(t.read(o)));let c=t.readVarIntNumStrict();if(c!==-1){a(this,v,Je).call(this,t,c,"listOutputs tags");let f=[];for(let d=0;d<c;d++)f.push(Rt(t.read(t.readVarIntNumStrict(!1))));r.tags=f}let u=t.readVarIntNumStrict();if(u!==-1){a(this,v,Je).call(this,t,u,"listOutputs labels");let f=[];for(let d=0;d<u;d++)f.push(Rt(t.read(t.readVarIntNumStrict(!1))));r.labels=f}return r},ks=function(t){let e=new ht;if(typeof t!="string")throw new Error("Invalid outpoint: expected a string");let i=t.split(".");if(i.length!==2||!/^(?:0|[1-9]\d*)$/.test(i[1]))throw new Error(`Invalid outpoint: ${t}`);let r=et(i[0],"hex");if(r.length!==32)throw new Error("Invalid outpoint txid length");return e.write(r),e.writeVarIntNum(a(this,v,Ee).call(this,Number(i[1]),"outpoint index",0,4294967295)),e.toUint8Array()},ru=function(t){let e=nt(t.read(32)),i=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"outpoint index",0,4294967295);return`${e}.${i}`},Dt=function(t,e){t.writeInt8(cu.OPTIONAL_BOOLEAN_WIRE_VALUES.get(e))},ai=function(t,e){typeof e=="number"?t.writeVarIntNum(e):t.writeVarIntNum(-1)},Ur=function(t,e){let i=et(e??"","utf8");t.writeVarIntNum(i.length),t.write(i)},su=function(t,e){if(e!=null&&e!==""){let i=et(e,"utf8");t.writeVarIntNum(i.length),t.write(i)}else t.writeVarIntNum(-1)},ou=function(t,e){if(e==null)t.writeVarIntNum(-1);else{t.writeVarIntNum(e.length);for(let i of e){let r=et(i,"utf8");t.writeVarIntNum(r.length),t.write(r)}}},au=function(t,e){if(e==null)t.writeVarIntNum(-1);else{t.writeVarIntNum(e.length);for(let i of e)t.write(et(i,"hex"))}},_d=function(t){let e=t.readVarIntNumStrict();if(e<0)return;a(this,v,Je).call(this,t,e,"sendWithResults",33,1001);let i=[];for(let r=0;r<e;r++){let s=nt(t.read(32)),o=t.readInt8(),c="unproven";if(o===2)c="sending";else if(o===3)c="failed";else if(o!==1)throw new Error(`Unknown sendWith result status code: ${o}`);i.push({txid:s,status:c})}return i},Um=function(t,e){if(t.write(a(this,v,ks).call(this,e.outpoint)),e.unlockingScript!=null&&e.unlockingScript!==""){let i=et(e.unlockingScript,"hex");t.writeVarIntNum(i.length),t.write(i)}else t.writeVarIntNum(-1),t.writeVarIntNum(e.unlockingScriptLength??0);a(this,v,Ur).call(this,t,e.inputDescription),a(this,v,ai).call(this,t,e.sequenceNumber)},Mm=function(t,e){let i=et(e.lockingScript,"hex");t.writeVarIntNum(i.length),t.write(i),t.writeVarIntNum(e.satoshis),a(this,v,Ur).call(this,t,e.outputDescription),a(this,v,su).call(this,t,e.basket),a(this,v,su).call(this,t,e.customInstructions),a(this,v,ou).call(this,t,e.tags)},Dm=function(t,e){if(e==null){t.writeInt8(0);return}if(t.writeInt8(1),a(this,v,Dt).call(this,t,e.signAndProcess),a(this,v,Dt).call(this,t,e.acceptDelayedBroadcast),t.writeInt8(e.trustSelf==="known"?1:-1),a(this,v,au).call(this,t,e.knownTxids),a(this,v,Dt).call(this,t,e.returnTXIDOnly),a(this,v,Dt).call(this,t,e.noSend),e.noSendChange==null)t.writeVarIntNum(-1);else{t.writeVarIntNum(e.noSendChange.length);for(let i of e.noSendChange)t.write(a(this,v,ks).call(this,i))}a(this,v,au).call(this,t,e.sendWith),a(this,v,Dt).call(this,t,e.randomizeOutputs)},Hm=function(t,e){if(e==null){t.writeInt8(0);return}t.writeInt8(1),a(this,v,Dt).call(this,t,e.acceptDelayedBroadcast),a(this,v,Dt).call(this,t,e.returnTXIDOnly),a(this,v,Dt).call(this,t,e.noSend),a(this,v,au).call(this,t,e.sendWith)},ci=function(t,e,i,r,s){let o=new ht;o.writeUInt8(t[0]);let c=et(t[1],"utf8");o.writeVarIntNum(c.length),o.write(c);let u=et(e,"utf8");return o.writeVarIntNum(u.length),o.write(u),typeof i!="string"?o.writeUInt8(0):i==="self"?o.writeUInt8(11):i==="anyone"?o.writeUInt8(12):o.write(et(i,"hex")),o.write(a(this,v,Mr).call(this,r,s)),o.toUint8Array()},Mr=function(t,e){let i=new ht;if(typeof t=="boolean"?i.writeInt8(t?1:0):i.writeInt8(-1),typeof e=="string"){let r=et(e,"utf8");i.writeInt8(r.length),i.write(r)}else i.writeInt8(-1);return i.toUint8Array()},Cd=function(t,e){let i=new bt(t),r=a(this,v,Ee).call(this,i.readVarIntNumStrict(!1),"discovery totalCertificates",0,4294967295),s=[];for(;!i.eof();){a(this,v,Yo).call(this,s.length,e,"discover");let o=i.readVarIntNumStrict(!1),c=i.read(o),u=Lr.fromBinary(c),f=i.readVarIntNumStrict(!1),d=Rt(i.read(f)),l=i.readVarIntNumStrict(!1),p=Rt(i.read(l)),m=i.readVarIntNumStrict(!1),g=Rt(i.read(m)),w=a(this,v,Ee).call(this,i.readUInt8(),"discovery trust",1,10),S={},C=i.readVarIntNumStrict(!1);a(this,v,Je).call(this,i,C,"discovery public keyring");for(let k=0;k<C;k++){let B=i.readVarIntNumStrict(!1),_=a(this,v,Zo).call(this,i,B,"discovery public keyring"),H=i.readVarIntNumStrict(!1);a(this,v,Jo).call(this,S,_,ve(i.read(H)),"discovery public keyring")}let E={},A=i.readVarIntNumStrict(!1);a(this,v,Je).call(this,i,A,"discovery decrypted fields");for(let k=0;k<A;k++){let B=i.readVarIntNumStrict(!1),_=a(this,v,Zo).call(this,i,B,"discovery decrypted fields"),H=i.readVarIntNumStrict(!1);a(this,v,Jo).call(this,E,_,Rt(i.read(H)),"discovery decrypted fields")}s.push({...u,signature:u.signature,certifierInfo:{iconUrl:p,name:d,description:g,trust:w},publiclyRevealedKeyring:S,decryptedFields:E})}return a(this,v,Go).call(this,s.length,r,"discover"),{totalCertificates:r,certificates:s}},Hi=function(t,e){if(!t.eof())throw new Error(`Wallet Wire ${e} response contains trailing data`)},Go=function(t,e,i){if(t>e)throw new Error(`Wallet Wire ${i} response returned ${t} records but declared a total of ${e}`)},Yo=function(t,e,i){let r=e??10;if(t>=r)throw new Error(`Wallet Wire ${i} response exceeds the requested page limit of ${r}`)},Je=function(t,e,i,r=1,s=M2){if(!Number.isSafeInteger(e)||e<0||e>s)throw new Error(`Wallet Wire ${i} exceeds the maximum collection size of ${s}`);if(e>Math.floor(t.remaining()/r))throw new Error(`Wallet Wire ${i} count exceeds the remaining response data`);return e},ui=function(t,e){let i=t.readInt8();if(i!==0&&i!==1)throw new Error(`Invalid ${e} flag: expected 0 or 1, received ${i}`);return i===1},Zo=function(t,e,i){if(e<1||e>50)throw new Error(`Invalid ${i} key length: expected 1\u201350 bytes, received ${e}`);let r=Rt(t.read(e));if(gn(r))throw new Error(`Unsafe ${i} key: ${r}`);return r},Jo=function(t,e,i,r){if(Object.prototype.hasOwnProperty.call(t,e))throw new Error(`Duplicate ${r} key: ${e}`);t[e]=i},$i=function(t,e){let i=t.read(33);return Ht.fromDER(Array.from(i)),nt(i)},$m=function(t,e){let i=t.readUInt8();if(i!==0&&i!==1&&i!==2)throw new Error(`Invalid ${e} security level: ${i}`);return i},Ee=function(t,e,i,r){if(!Number.isSafeInteger(t)||t<i||t>r)throw new Error(`Invalid ${e}: expected an integer from ${i} to ${r}, received ${String(t)}`);return t},Dr=function(t,e,i){if(t.length!==e)throw new Error(`Wallet Wire ${i} response has an invalid length`)},qi=function(t,e){a(this,v,Dr).call(this,t,0,e)},b(cu,"OPTIONAL_BOOLEAN_WIRE_VALUES",new Map([[!0,1],[!1,0],[void 0,-1]]));var Ts=cu;function qm(n,t="http"){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(n))try{return new URL(n).origin}catch{}try{return new URL(`${t}://${n}`).origin}catch{throw new Error(`Invalid originator value: ${n}`)}}function Os(n){if(typeof n!="string"||n.length<1||n.length>2048||n!==n.trim())throw new TypeError("Wallet HTTP baseUrl must be an exact HTTP(S) origin.");let t;try{t=new URL(n)}catch{throw new TypeError("Wallet HTTP baseUrl must be an exact HTTP(S) origin.")}if(t.protocol!=="https:"&&t.protocol!=="http:"||t.username!==""||t.password!==""||t.pathname!=="/"||t.search!==""||t.hash!==""||t.origin==="null")throw new TypeError("Wallet HTTP baseUrl must be an HTTP(S) origin without credentials, path, query, or fragment.");if(t.protocol==="http:"&&!H2(t.hostname))throw new TypeError("Wallet HTTP baseUrl may use cleartext HTTP only for a loopback host.");return t.origin}function H2(n){let t=n.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="[::1]"}var Ps=class{constructor(t,e="http://localhost:3301",i){b(this,"baseUrl");b(this,"httpClient");b(this,"originator");let r=ii(t);this.baseUrl=Os(e),this.httpClient=i??globalThis.fetch.bind(globalThis),this.originator=r}async transmitToWallet(t){return Array.from(await this.transmitToWalletUint8Array(Uint8Array.from(t)))}async transmitToWalletUint8Array(t){if(!(t instanceof Uint8Array)||t.length>268435456)throw new Error("HTTPWalletWire request exceeds the maximum permitted size");let e=new bt(t),i=e.readUInt8(),r=vs[i];if(r===void 0||r==="")throw new Error(`Invalid call code: ${i}`);let s=e.readUInt8();if(s>250)throw new Error(`Invalid originator length: expected at most 250 bytes, received ${s}`);let o;if(s>0){let d=e.read(s);o=ii(Rt(d))}if(this.originator!==void 0&&o!==this.originator)throw new Error("Wallet Wire frame originator does not match the configured originator");let c=e.readView(),u=Os(this.baseUrl),f=await this.httpClient(`${u}/${r}`,{method:"POST",redirect:"error",headers:{"Content-Type":"application/octet-stream",Origin:o??""},body:c});return await this.readResponse(f)}async readResponse(t){if(t.ok===!1)throw new Error(`HTTPWalletWire request failed with HTTP status ${String(t.status)}`);let e=t.headers?.get("content-length");if(e!=null){if(!/^\d+$/.test(e))throw new Error("HTTPWalletWire response has an invalid Content-Length");let u=Number(e);if(!Number.isSafeInteger(u)||u>268435456)throw new Error("HTTPWalletWire response exceeds the maximum permitted size")}if(t.body==null){let u=await t.arrayBuffer();if(u.byteLength>268435456)throw new Error("HTTPWalletWire response exceeds the maximum permitted size");return new Uint8Array(u)}let i=t.body.getReader(),r=[],s=0;for(;;){let{value:u,done:f}=await i.read();if(f)break;if(u!=null){if(s+=u.byteLength,s>268435456)throw await i.cancel().catch(()=>{}),new Error("HTTPWalletWire response exceeds the maximum permitted size");r.push(u)}}let o=new Uint8Array(s),c=0;for(let u of r)o.set(u,c),c+=u.byteLength;return o}};var uu=class extends Error{constructor(e,i,r,s,o){super("Undelayed createAction or signAction results require review.");b(this,"reviewActionResults");b(this,"sendWithResults");b(this,"txid");b(this,"tx");b(this,"noSendChange");b(this,"code");b(this,"isError",!0);this.reviewActionResults=e,this.sendWithResults=i,this.txid=r,this.tx=s,this.noSendChange=o,this.code=5,this.name=this.constructor.name}};var Ld=class extends Error{constructor(e,i){super(`Insufficient funds in the available inputs to cover the cost of the required outputs and the transaction fee (${i} more satoshis are needed, for a total of ${e}), plus whatever would be required in order to pay the fee to unlock and spend the outputs used to provide the additional satoshis.`);b(this,"totalSatoshisNeeded");b(this,"moreSatoshisNeeded");b(this,"code");b(this,"isError",!0);this.totalSatoshisNeeded=e,this.moreSatoshisNeeded=i,this.code=7,this.name=this.constructor.name}},Fm=Ld;var Ud=256*1024*1024,$2=256*1024*1024;async function q2(n){let t=n.headers?.get("content-length");if(t!=null){if(!/^\d+$/.test(t))throw new Error("HTTPWalletJSON response has an invalid Content-Length");let i=Number(t);if(!Number.isSafeInteger(i)||i>Ud)throw new Error("HTTPWalletJSON response exceeds the maximum permitted size")}let e;if(n.body!=null&&typeof n.body.getReader=="function"){let i=n.body.getReader(),r=[],s=0;for(;;){let{value:c,done:u}=await i.read();if(u)break;if(c!=null){if(s+=c.byteLength,s>Ud)throw await i.cancel().catch(()=>{}),new Error("HTTPWalletJSON response exceeds the maximum permitted size");r.push(c)}}e=new Uint8Array(s);let o=0;for(let c of r)e.set(c,o),o+=c.byteLength}else if(typeof n.arrayBuffer=="function"){let i=await n.arrayBuffer();if(i.byteLength>Ud)throw new Error("HTTPWalletJSON response exceeds the maximum permitted size");e=new Uint8Array(i)}return e!==void 0?JSON.parse(Rt(e)):await n.json()}function Md(n,t,e=0,i=4096){if(typeof n!="string")throw new Error(`Invalid wallet error ${t}`);let r=at(n,"utf8").length;if(r<e||r>i)throw new Error(`Invalid wallet error ${t}`);return n}function Wm(n,t){if(!Number.isSafeInteger(n)||n<0||n>21e14)throw new Error(`Invalid wallet error ${t}`);return n}function F2(n,t){if(!Array.isArray(n))throw new Error("Invalid wallet error reviewActionResults");if(n.length>xn+1)throw new Error("Invalid wallet error reviewActionResults");let e=new Set(["success","doubleSpend","serviceError","invalidTx"]),i=new Set;for(let[r,s]of n.entries()){if(s==null||typeof s!="object"||Array.isArray(s))throw new Error(`Invalid wallet error reviewActionResults[${r}]`);let o=s;if(typeof o.txid!="string"||!/^[0-9a-fA-F]{64}$/.test(o.txid))throw new Error(`Invalid wallet error reviewActionResults[${r}].txid`);let c=o.txid.toLowerCase();if(i.has(c)||!t.has(c))throw new Error(`Invalid wallet error reviewActionResults[${r}].txid`);if(i.add(c),!e.has(o.status))throw new Error(`Invalid wallet error reviewActionResults[${r}].status`);if(o.status!=="doubleSpend"&&(o.competingTxs!==void 0||o.competingBeef!==void 0))throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs`);let u;if(o.competingTxs!==void 0){if(!Array.isArray(o.competingTxs)||o.competingTxs.length>xn)throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs`);u=[];let f=new Set;for(let[d,l]of o.competingTxs.entries()){if(typeof l!="string"||!/^[0-9a-fA-F]{64}$/.test(l))throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs[${d}]`);let p=l.toLowerCase();if(p===c||f.has(p))throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs`);f.add(p),u.push(p)}}if(o.competingBeef!==void 0){if(u==null||u.length===0)throw new Error(`Invalid wallet error reviewActionResults[${r}].competingBeef`);let f=md(o.competingBeef);if(f==null)throw new Error(`Invalid wallet error reviewActionResults[${r}].competingBeef`);try{let d=C0.fromBinaryStrict(f);for(let l of u)if(d.findTxid(l)==null)throw new Error}catch{throw new Error(`Invalid wallet error reviewActionResults[${r}].competingBeef`)}}}}function W2(n,t,e){if(n.isError!==!0||!Number.isSafeInteger(n.code))throw new Error("Invalid wallet error envelope");switch(n.message!==void 0&&Md(n.message,"message"),n.code){case 5:{if(t!=="createAction"&&t!=="signAction")throw new Error(`Invalid ${t} wallet error code`);if(!Array.isArray(n.sendWithResults))throw new Error("Invalid wallet error sendWithResults");let i={...e,options:{...e.options,returnTXIDOnly:!0}};Ft(t,{txid:n.txid,tx:n.tx,noSendChange:n.noSendChange,sendWithResults:n.sendWithResults},i);let r=new Set;typeof n.txid=="string"&&r.add(n.txid.toLowerCase());let s=e.options;if(Array.isArray(s?.sendWith))for(let o of s.sendWith)r.add(String(o).toLowerCase());return F2(n.reviewActionResults,r),new uu(n.reviewActionResults,n.sendWithResults,n.txid,n.tx,n.noSendChange)}case 6:{let i=Md(n.parameter,"parameter",1,200),r=Md(n.message,"message"),s=new ei(i);return s.message=r,s}case 7:{let i=Wm(n.totalSatoshisNeeded,"totalSatoshisNeeded"),r=Wm(n.moreSatoshisNeeded,"moreSatoshisNeeded");if(r>i)throw new Error("Invalid wallet error moreSatoshisNeeded");return new Fm(i,r)}default:return}}var Fi=class{constructor(t,e="http://localhost:3321",i=globalThis.fetch.bind(globalThis)){b(this,"baseUrl");b(this,"httpClient");b(this,"originator");b(this,"api");this.baseUrl=Os(e),this.originator=ii(t),this.httpClient=i;let r=typeof window<"u"&&typeof document<"u"&&window.origin!=="file://";this.api=async(s,o)=>{xt(s,o);let c=mt(s,o),u=Os(this.baseUrl);if(!r&&!this.originator)throw new Error('HTTPWalletJSON: originator is required when using the HTTP substrate in Node.js. Pass an originator (e.g. "example.com") to the constructor.');let f=r?void 0:qm(this.originator,"http"),d=ys(o);if(et(d,"utf8").length>$2)throw new Error("HTTPWalletJSON request exceeds the maximum permitted size");let l=await this.httpClient(`${u}/${s}`,{method:"POST",redirect:"error",headers:{Accept:"application/json","Content-Type":"application/json",...f?{Origin:f,Originator:f}:{}},body:d}),p=bm(await q2(l),`HTTPWalletJSON ${s} raw response`),m=mm(Fc(p),`HTTPWalletJSON ${s} response`);if(m==null||typeof m!="object"||Array.isArray(m))throw new Error(`Invalid HTTPWalletJSON ${s} response: expected an object`);if(!l.ok){if(l.status===400&&Object.prototype.hasOwnProperty.call(m,"isError")){let g=W2(m,s,c);if(g!==void 0)throw g}throw new Error(`HTTPWalletJSON ${s} failed with HTTP status ${l.status}`)}return Ft(s,m,c)}}async createAction(t){return await this.api("createAction",t)}async signAction(t){return await this.api("signAction",t)}async abortAction(t){return await this.api("abortAction",t)}async listActions(t){return await this.api("listActions",t)}async internalizeAction(t){return await this.api("internalizeAction",t)}async listOutputs(t){return await this.api("listOutputs",t)}async relinquishOutput(t){return await this.api("relinquishOutput",t)}async getPublicKey(t){return await this.api("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.api("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.api("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.api("encrypt",t)}async decrypt(t){return await this.api("decrypt",t)}async createHmac(t){return await this.api("createHmac",t)}async verifyHmac(t){return await this.api("verifyHmac",t)}async createSignature(t){return await this.api("createSignature",t)}async verifySignature(t){return await this.api("verifySignature",t)}async acquireCertificate(t){return await this.api("acquireCertificate",t)}async listCertificates(t){return await this.api("listCertificates",t)}async proveCertificate(t){return await this.api("proveCertificate",t)}async relinquishCertificate(t){return await this.api("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.api("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.api("discoverByAttributes",t)}async isAuthenticated(t){return await this.api("isAuthenticated",t)}async waitForAuthentication(t){return await this.api("waitForAuthentication",t)}async getHeight(t){return await this.api("getHeight",t)}async getHeaderForHeight(t){return await this.api("getHeaderForHeight",t)}async getNetwork(t){return await this.api("getNetwork",t)}async getVersion(t){return await this.api("getVersion",t)}};var V2=1024,Vm=3600*1e3,Km=256*1024*1024,Hr=class extends Es{constructor(e="*",i){super();b(this,"domain");b(this,"responseTimeout");b(this,"pendingInvocations",0);if(typeof globalThis.window!="object")throw new TypeError("The XDM substrate requires a global window object.");if(!Object.prototype.hasOwnProperty.call(globalThis.window,"ReactNativeWebView"))throw new Error("The window object does not have a ReactNativeWebView property.");if(typeof globalThis.window.ReactNativeWebView.postMessage!="function")throw new TypeError("The window.ReactNativeWebView property does not seem to support postMessage calls.");if(i!==void 0&&(!Number.isSafeInteger(i)||i<1||i>Vm))throw new TypeError(`ReactNativeWebView responseTimeout must be an integer from 1 to ${Vm}.`);this.domain=z2(e),this.responseTimeout=i}async invokeRaw(e,i,r){if(this.pendingInvocations>=V2)throw new Error("React Native wallet pending invocation limit reached.");let s=ve(Pe(12));return this.pendingInvocations++,await new Promise((o,c)=>{let u,f=!1,d=!0,l=()=>{if(d&&(d=!1,this.pendingInvocations--,u!==void 0&&clearTimeout(u),f&&typeof globalThis.window.removeEventListener=="function"))try{globalThis.window.removeEventListener("message",p)}catch{}},p=m=>{if(!K2(m,this.domain)||typeof m.data!="string")return;if(et(m.data,"utf8").length>Km){l(),c(new Error("React Native wallet response exceeds the maximum permitted size."));return}let g;try{g=JSON.parse(m.data)}catch{return}if(!(g?.type!=="CWI"||g.id!==s||g.isInvocation!==!1||g.status!=="success"&&g.status!=="error")){if(this.domain!=="*"&&m.origin!=null&&m.origin!==""&&m.origin!==this.domain){l(),c(new Error(`React Native wallet response origin ${m.origin} did not match ${this.domain}.`));return}if(l(),g.status==="error")if(typeof g.description!="string"||at(g.description,"utf8").length>4096||!Number.isSafeInteger(g.code)||g.code<1||g.code>255)c(new Error("Invalid React Native wallet error response."));else{let w=g.code>=fn.unsupportedAction&&g.code<=fn.abortRefused,S=w?g.description:"Wallet operation failed";c(new oi(S,w?g.code:fn.unknownError))}else try{let w=Fc(g.result);o(Ft(e,w,r))}catch(w){c(w)}}};try{globalThis.window.addEventListener("message",p),f=!0,this.responseTimeout!==void 0&&(u=setTimeout(()=>{l(),c(new Error("React Native wallet response timed out."))},this.responseTimeout));let m=ys({type:"CWI",isInvocation:!0,id:s,call:e,args:i});if(et(m,"utf8").length>Km)throw new Error("React Native wallet request exceeds the maximum permitted size.");globalThis.window.ReactNativeWebView.postMessage(m)}catch(m){l(),c(m)}})}};function K2(n,t){let e=globalThis.window,i=n.source;return i==null||i===e?!0:i===e.parent&&(n.origin===e.origin||n.origin===t)}function z2(n){if(n==="*")return n;try{if(/^[a-z][a-z\d+.-]*:\/\//i.test(n)&&!/^https?:\/\//i.test(n))throw new TypeError("Only HTTP(S) origins are supported.");let t=/^https?:\/\//i.test(n)?n:`https://${n}`,e=new URL(t).origin;if(e==="null")throw new TypeError("The origin could not be normalized.");return e}catch{throw new TypeError("ReactNativeWebView domain must be an HTTP(S) origin or domain name.")}}var Rs=1e3,zm=200,Wi=class{constructor(t="auto",e){b(this,"substrate");b(this,"originator");let i=ii(e);t==="Cicada"&&(t=new Ts(new Ps(i))),t==="window.CWI"&&(t=new As),t==="XDM"&&(t=new Fn),t==="json-api"&&(t=new Fi(i)),t==="react-native"&&(t=new Hr),t==="secure-json-api"&&(t=new Fi(i,"https://localhost:2121")),this.substrate=t,this.originator=i}async validatedResult(t,e,i){return Ft(t,await e,i)}async connectToSubstrate(){if(typeof this.substrate=="object")return;let t=async(o,c,u)=>{try{let f=o(),d,l;try{d=await Promise.race([f.getVersion({},this.originator),new Promise((p,m)=>{l=setTimeout(()=>m(new Error("Timed out.")),c)})])}finally{clearTimeout(l)}return Ft("getVersion",d),{success:!0,sub:u?.()??f}}catch{return{success:!1}}},e=[t(()=>new As,Rs),t(()=>new Ts(new Ps(this.originator)),Rs),t(()=>new Fi(this.originator,"https://localhost:2121"),Rs),t(()=>new Fi(this.originator),Rs),t(()=>new Hr("*",Rs),Rs,()=>new Hr)],r=(await Promise.allSettled(e)).filter(o=>o.status==="fulfilled"&&o.value.success&&o.value.sub!==void 0).map(o=>o.value.sub);if(r.length>0){this.substrate=r[0];return}let s=await t(()=>new Fn("*",zm),zm,()=>new Fn);if(s.success&&s.sub!==void 0)this.substrate=s.sub;else throw new Error("No wallet available over any communication substrate. Install a BSV wallet today!")}async createAction(t){gc(t);let e=mt("createAction",t);return await this.connectToSubstrate(),await this.validatedResult("createAction",this.substrate.createAction(t,this.originator),e)}async signAction(t){mc(t);let e=mt("signAction",t);return await this.connectToSubstrate(),await this.validatedResult("signAction",this.substrate.signAction(t,this.originator),e)}async abortAction(t){return bc(t),await this.connectToSubstrate(),await this.validatedResult("abortAction",this.substrate.abortAction(t,this.originator))}async listActions(t){Pc(t);let e=mt("listActions",t);return await this.connectToSubstrate(),await this.validatedResult("listActions",this.substrate.listActions(t,this.originator),e)}async internalizeAction(t){return wc(t),await this.connectToSubstrate(),await this.validatedResult("internalizeAction",this.substrate.internalizeAction(t,this.originator))}async listOutputs(t){Oc(t);let e=mt("listOutputs",t);return await this.connectToSubstrate(),await this.validatedResult("listOutputs",this.substrate.listOutputs(t,this.originator),e)}async relinquishOutput(t){return xc(t),await this.connectToSubstrate(),await this.validatedResult("relinquishOutput",this.substrate.relinquishOutput(t,this.originator))}async getPublicKey(t){return Rc(t),await this.connectToSubstrate(),await this.validatedResult("getPublicKey",this.substrate.getPublicKey(t,this.originator))}async revealCounterpartyKeyLinkage(t){Nc(t);let e=mt("revealCounterpartyKeyLinkage",t);return await this.connectToSubstrate(),await this.validatedResult("revealCounterpartyKeyLinkage",this.substrate.revealCounterpartyKeyLinkage(t,this.originator),e)}async revealSpecificKeyLinkage(t){Bc(t);let e=mt("revealSpecificKeyLinkage",t);return await this.connectToSubstrate(),await this.validatedResult("revealSpecificKeyLinkage",this.substrate.revealSpecificKeyLinkage(t,this.originator),e)}async encrypt(t){return _c(t),await this.connectToSubstrate(),await this.validatedResult("encrypt",this.substrate.encrypt(t,this.originator))}async decrypt(t){return Cc(t),await this.connectToSubstrate(),await this.validatedResult("decrypt",this.substrate.decrypt(t,this.originator))}async createHmac(t){return Lc(t),await this.connectToSubstrate(),await this.validatedResult("createHmac",this.substrate.createHmac(t,this.originator))}async verifyHmac(t){return Uc(t),await this.connectToSubstrate(),await this.validatedResult("verifyHmac",this.substrate.verifyHmac(t,this.originator))}async createSignature(t){return Mc(t),await this.connectToSubstrate(),await this.validatedResult("createSignature",this.substrate.createSignature(t,this.originator))}async verifySignature(t){return Dc(t),await this.connectToSubstrate(),await this.validatedResult("verifySignature",this.substrate.verifySignature(t,this.originator))}async acquireCertificate(t){if(t.acquisitionProtocol==="direct")Ac(t);else if(t.acquisitionProtocol==="issuance")vc(t);else throw new ei("acquisitionProtocol",`valid. ${String(t.acquisitionProtocol)} is unrecognized.`);let e=mt("acquireCertificate",t);return await this.connectToSubstrate(),await this.validatedResult("acquireCertificate",this.substrate.acquireCertificate(t,this.originator),e)}async listCertificates(t){Ic(t);let e=mt("listCertificates",t);return await this.connectToSubstrate(),await this.validatedResult("listCertificates",this.substrate.listCertificates(t,this.originator),e)}async proveCertificate(t){Ec(t);let e=mt("proveCertificate",t);return await this.connectToSubstrate(),await this.validatedResult("proveCertificate",this.substrate.proveCertificate(t,this.originator),e)}async relinquishCertificate(t){return Sc(t),await this.connectToSubstrate(),await this.validatedResult("relinquishCertificate",this.substrate.relinquishCertificate(t,this.originator))}async discoverByIdentityKey(t){kc(t);let e=mt("discoverByIdentityKey",t);return await this.connectToSubstrate(),await this.validatedResult("discoverByIdentityKey",this.substrate.discoverByIdentityKey(t,this.originator),e)}async discoverByAttributes(t){Tc(t);let e=mt("discoverByAttributes",t);return await this.connectToSubstrate(),await this.validatedResult("discoverByAttributes",this.substrate.discoverByAttributes(t,this.originator),e)}async isAuthenticated(t={}){return Mi(t),await this.connectToSubstrate(),await this.validatedResult("isAuthenticated",this.substrate.isAuthenticated(t,this.originator))}async waitForAuthentication(t={}){return Mi(t),await this.connectToSubstrate(),await this.validatedResult("waitForAuthentication",this.substrate.waitForAuthentication(t,this.originator))}async getHeight(t={}){return Mi(t),await this.connectToSubstrate(),await this.validatedResult("getHeight",this.substrate.getHeight(t,this.originator))}async getHeaderForHeight(t){return Hc(t),await this.connectToSubstrate(),await this.validatedResult("getHeaderForHeight",this.substrate.getHeaderForHeight(t,this.originator))}async getNetwork(t={}){return Mi(t),await this.connectToSubstrate(),await this.validatedResult("getNetwork",this.substrate.getNetwork(t,this.originator))}async getVersion(t={}){return Mi(t),await this.connectToSubstrate(),await this.validatedResult("getVersion",this.substrate.getVersion(t,this.originator))}};var Ns="com.bwalletx.extension",Dd="space.bwallet.mobile",Qo=[Ns,Dd],Vi=300;function Ki(n=Vi){return typeof window>"u"?Promise.resolve(null):new Promise(t=>{let e=!1,i,r=c=>{e||(e=!0,i!==void 0&&clearTimeout(i),window.removeEventListener("brc100:announceWallet",s),t(c))},s=c=>{let u=c.detail,f=u?.info?.rdns??"";u?.wallet&&Qo.includes(f)&&r({wallet:u.wallet,method:f===Ns?"extension":"in-app",rdns:f})},o=()=>{let c=window.CWI;return c&&r({wallet:c,method:"in-app",rdns:null}),!!c};if(window.addEventListener("brc100:announceWallet",s),window.dispatchEvent(new Event("brc100:requestWallet")),!(e||o())){if(X2()){Y2(Math.max(n,1200)).then(c=>r(c?{wallet:c,method:"in-app",rdns:null}:null));return}i=setTimeout(()=>{i=void 0,o()||r(null)},n)}})}async function jm(n=Vi){return(await Ki(n))?.wallet??null}var X2=()=>{try{return window.parent!==window}catch{return!0}},j2=["https://web.bwalletx.com","https://desktop.bwalletx.com","https://bwalletx.com","https://www.bwallet.space","https://bwallet.space","capacitor://localhost","https://localhost","tauri://localhost","https://tauri.localhost","chrome-extension://bombmmcjghjdlbmcclnhjodgcelnehgl"],G2=()=>{try{let n=window.location.ancestorOrigins;if(n&&n.length>0)return n[0]??null;if(!document.referrer)return null;let t=new URL(document.referrer);return`${t.protocol}//${t.host}`}catch{return null}};async function Y2(n=1200,t=j2){let e=G2();if(!e||!t.includes(e))return null;try{let i=new Wi(new Fn(e));return await Promise.race([i.isAuthenticated({}).then(()=>!0,()=>!1),new Promise(s=>setTimeout(()=>s(!1),n))])?i:null}catch{return null}}var Xm=0;function Hd(){typeof window>"u"||Date.now()-Xm<2e4||(Xm=Date.now(),Ki(0).then(n=>{n&&n.method==="extension"&&n.wallet.isAuthenticated({}).catch(()=>{})}))}function fu(n){let t=()=>Hd(),e=["pointerenter","focus","touchstart"];for(let i of e)n.addEventListener(i,t,{passive:!0});return()=>e.forEach(i=>n.removeEventListener(i,t))}function ta(n,t){let e=Promise.resolve();return i=>(e=e.then(()=>n(i)).catch(r=>t?.(r)),e)}var Zm="1",Z2="bwallet-pair-v1",J2="www.bwallet.space";var Jm="relay.bwallet.space",du=120,Bs=new TextEncoder,Q2=new TextDecoder,Qm=n=>{let t="";for(let e=0;e<n.length;e+=32768)t+=String.fromCharCode(...n.subarray(e,e+32768));return t},$d=n=>btoa(Qm(n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),t4=n=>{let t=n.replace(/-/g,"+").replace(/_/g,"/"),e=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(e,i=>i.charCodeAt(0))},Gm=n=>btoa(Qm(n)),Ym=n=>Uint8Array.from(atob(n),t=>t.charCodeAt(0)),tb=()=>$d(crypto.getRandomValues(new Uint8Array(16)));function eb(n){let t=new URLSearchParams({v:n.v,r:n.r,c:n.c,k:n.k,o:n.o,e:String(n.e)});return`https://${J2}/pair?${t}`}var qd=()=>$d(crypto.getRandomValues(new Uint8Array(16))),e4="bwallet-pair-wallet-claim-v1",n4=n=>Array.from(n,t=>t.toString(16).padStart(2,"0")).join("");async function nb(n,t){let e=await crypto.subtle.digest("SHA-256",Bs.encode(`${e4}|${n}|${t}`));return $d(new Uint8Array(e))}async function ib(n){return n4(new Uint8Array(await crypto.subtle.digest("SHA-256",Bs.encode(n))))}var Fd=(n,t,e,i,r,s)=>{let o=/^(localhost|127\.0\.0\.1)(:\d+)?$/.test(n),c=new URLSearchParams({role:e});return i&&c.set("e",String(i)),r&&c.set("claim",r),s&&e==="site"&&c.set("wc",s),`${o?"ws":"wss"}://${n}/v1/c/${t}?${c}`};async function Wd(n,t,e){let i=n.deriveSharedSecret(Ht.fromString(t)),r=new Uint8Array(i.encode(!0)),s=await crypto.subtle.importKey("raw",r,"HKDF",!1,["deriveBits"]),o=new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:t4(e),info:Bs.encode(Z2)},s,256)),c=await crypto.subtle.importKey("raw",o,"AES-GCM",!1,["encrypt","decrypt"]),u=new Uint8Array(await crypto.subtle.digest("SHA-256",o)),f=String((u[0]<<8|u[1])%1e4).padStart(4,"0");return{key:c,code:f}}var ea=class{constructor(t,e){b(this,"key",t);b(this,"me",e);b(this,"sent",0);b(this,"lastSeen",0)}async seal(t){let e=++this.sent,i=crypto.getRandomValues(new Uint8Array(12)),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:i,additionalData:Bs.encode(`${this.me}|${e}`)},this.key,Bs.encode(JSON.stringify(t))));return{s:e,n:Gm(i),d:Gm(r)}}async open(t){if(!Number.isInteger(t.s)||t.s<=this.lastSeen)return null;let e=this.me==="site"?"wallet":"site";try{let i=await crypto.subtle.decrypt({name:"AES-GCM",iv:Ym(t.n),additionalData:Bs.encode(`${e}|${t.s}`)},this.key,Ym(t.d));return this.lastSeen=t.s,JSON.parse(Q2.decode(i))}catch{return null}}get counters(){return{sent:this.sent,lastSeen:this.lastSeen}}restore(t){this.sent=t.sent,this.lastSeen=t.lastSeen}},Vd=n=>!!n&&typeof n=="object"&&"d"in n&&"n"in n&&"s"in n;var Kd="bwalletx.connect.pairing.v1",rb=1;function hu(){let n=new Map;return{getItem:t=>n.get(t)??null,setItem:(t,e)=>{n.set(t,e)},removeItem:t=>{n.delete(t)}}}function zd(){try{if(typeof localStorage<"u")return localStorage}catch{}return hu()}function sb(){return n=>{if(typeof WebSocket>"u")throw new Error("No WebSocket here. Pass options.socket.");return new WebSocket(n)}}function i4(n){if(!n)return null;try{let t=JSON.parse(n),e=i=>Number.isInteger(i)&&i>=0;return t.v!==1||typeof t.c!="string"||!/^[A-Za-z0-9_-]{22}$/.test(t.c)||typeof t.r!="string"||!/^[a-z0-9.-]+(:\d+)?$/i.test(t.r)||typeof t.s!="string"||!/^[0-9a-f]{64}$/i.test(t.s)||typeof t.k!="string"||!/^0[23][0-9a-f]{64}$/i.test(t.k)||!e(t.sent)||!e(t.lastSeen)||!e(t.pairedAt)||t.sc!==void 0&&(typeof t.sc!="string"||!/^[A-Za-z0-9_-]{22,64}$/.test(t.sc))?null:t}catch{return null}}var lu=class{constructor(t,e,i,r,s,o){b(this,"p",t);b(this,"sealer",e);b(this,"storage",i);b(this,"key",r);b(this,"socket",s);b(this,"timeoutMs",o);b(this,"ws",null);b(this,"opening",null);b(this,"waiting",new Map);b(this,"forgotten",!1)}adopt(t){this.ws=t,this.wire(t)}wire(t){t.onmessage=ta(e=>this.onFrame(String(e.data))),t.onerror=null,t.onclose=()=>{this.ws===t&&(this.ws=null),this.failAll(new Error("The connection to bWalletX closed"))}}persist(){this.forgotten||(this.p={...this.p,...this.sealer.counters},Promise.resolve(this.storage.setItem(this.key,JSON.stringify(this.p))).catch(()=>{}))}failAll(t){for(let e of this.waiting.values())clearTimeout(e.timer),e.reject(t);this.waiting.clear()}async ensure(){if(this.forgotten)throw new Error("This pairing was removed. Pair again.");this.ws&&this.ws.readyState===rb||(this.opening??(this.opening=this.reopen().finally(()=>this.opening=null)),await this.opening)}reopen(){this.p.sc||(this.p={...this.p,sc:qd()},this.persist());let t=Math.floor(Date.now()/1e3)+du-10,e=this.socket(Fd(this.p.r,this.p.c,"site",t,this.p.sc));return new Promise((i,r)=>{e.onopen=()=>{this.ws=e,this.wire(e),i()},e.onerror=()=>r(new Error("Could not reach the bWalletX pairing service")),e.onclose=()=>r(new Error("Could not reach the bWalletX pairing service"))})}async onFrame(t){let e;try{e=JSON.parse(t)}catch{return}if(e.t==="relay"&&e.error)return this.failAll(new Error(`bWalletX pairing service: ${e.error}`));if(!Vd(e))return;let r=await this.sealer.open(e);if(r)if(this.persist(),r.t==="res"){let s=this.waiting.get(r.id);if(!s)return;clearTimeout(s.timer),this.waiting.delete(r.id),r.error?s.reject(Object.assign(new Error(r.error.message),{code:r.error.code})):s.resolve(r.result)}else r.t==="close"&&(this.drop(),this.failAll(new Error("bWalletX disconnected this site. Pair again.")))}async call(t,e){await this.ensure();let i=this.ws,r=`${t}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,s=new Promise((o,c)=>{let u=setTimeout(()=>{this.waiting.delete(r)&&c(new Error("No answer from bWalletX. Open it, unlocked, and approve."))},this.timeoutMs);this.waiting.set(r,{resolve:o,reject:c,timer:u})});return i.send(JSON.stringify(await this.sealer.seal({t:"req",id:r,action:t,params:e}))),this.persist(),s}close(){let t=this.ws;this.ws=null,t?.close()}drop(){this.forgotten=!0,Promise.resolve(this.storage.removeItem(this.key)).catch(()=>{}),this.close()}async forget(){if(!this.forgotten){try{this.ws&&this.ws.readyState===rb&&this.ws.send(JSON.stringify(await this.sealer.seal({t:"close",reason:"site unpaired"})))}catch{}this.drop()}}wallet(){return new Proxy({},{get:(t,e)=>{if(e==="close")return()=>this.close();if(e==="forget")return()=>this.forget();if(!(typeof e!="string"||e==="then"||e==="toJSON"))return i=>this.call(e,i??{})}})}};function _s(n){let t=n.storage===void 0?zd():n.storage??hu(),e=n.storageKey??Kd,i=n.socket??sb(),r=n.relay??Jm,s=n.origin??(typeof location<"u"?location.origin:"");if(!s)return Promise.reject(new Error("pairBwalletX needs options.origin outside a browser"));let o=dr.fromRandom(),c=tb(),u=Math.floor(Date.now()/1e3)+du,f=qd(),d=o.toPublicKey().toString();return nb(c,d).then(ib).then(l=>new Promise((p,m)=>{if(n.signal?.aborted)return m(new Error("cancelled"));let g;try{g=i(Fd(r,c,"site",u,f,l))}catch(k){return m(k)}let w=null,S="",C=!1,E=k=>{C||(C=!0,clearTimeout(A),g.close(),m(k))},A=setTimeout(()=>E(new Error("The pairing code expired. Show a new one.")),du*1e3);n.signal?.addEventListener("abort",()=>E(new Error("cancelled"))),g.onerror=()=>E(new Error("Could not reach the bWalletX pairing service")),g.onclose=()=>E(new Error("The connection to bWalletX closed before pairing finished")),g.onmessage=ta(async k=>{if(C)return;let B;try{B=JSON.parse(String(k.data))}catch{return}if(B.t==="hello"&&!w){S=B.k;let H=await Wd(o,S,c);w=new ea(H.key,"site"),n.onCode(H.code);return}if(!w||!Vd(B))return;let _=await w.open(B);if(_)if(_.t==="ready"){C=!0,clearTimeout(A);let H={v:1,c,r,s:o.toHex(),k:S,...w.counters,pairedAt:Date.now(),sc:f};await Promise.resolve(t.setItem(e,JSON.stringify(H))).catch(()=>{});let O=new lu(H,w,t,e,i,n.callTimeoutMs??12e4);O.adopt(g),p(O.wallet())}else _.t==="close"&&E(new Error("Pairing was declined in bWalletX"))}),n.onLink(eb({v:Zm,r,c,k:d,o:s,e:u}))}))}async function Cs(n={}){let t=n.storage===void 0?zd():n.storage??hu(),e=n.storageKey??Kd,i=i4(await Promise.resolve(t.getItem(e)).catch(()=>null));if(!i)return null;let{key:r}=await Wd(dr.fromHex(i.s),i.k,i.c),s=new ea(r,"site");return s.restore({sent:i.sent,lastSeen:i.lastSeen}),new lu(i,s,t,e,n.socket??sb(),n.callTimeoutMs??12e4).wallet()}async function ob(n={}){let t=n.storage===void 0?zd():n.storage??hu();await Promise.resolve(t.removeItem(n.storageKey??Kd)).catch(()=>{})}var jd=[2,"bwallet sign in"];async function na(n={}){let t=i=>{try{n.onStatus?.(i)}catch{}};if(n.wallet)return t("opening"),{wallet:n.wallet,method:"wallet"};t("finding");let e=await Ki(n.discoverMs??Vi);if(e)return t("opening"),{wallet:e.wallet,method:e.method};if(n.reusePairing!==!1){let i=await Cs(n.pairing??{});if(i)return t("opening"),{wallet:i,method:"pairing"}}if(!n.pairing)throw Object.assign(new Error("bWalletX was not found in this browser"),{code:"NOT_FOUND"});return t("pairing"),{wallet:await _s(n.pairing),method:"pairing"}}async function pu(n){let{wallet:t,method:e}=await na(n);e!=="pairing"&&await t.waitForAuthentication({}).catch(()=>{});let{publicKey:i}=await Xd("identity",()=>t.getPublicKey({identityKey:!0}));try{n.onStatus?.("signing")}catch{}let r=await Xd("challenge",()=>n.challenge(i)),{signature:s}=await Xd("signature",()=>t.createSignature({protocolID:r.protocolID??jd,keyID:r.keyID,counterparty:"anyone",data:Array.from(new TextEncoder().encode(r.message))}));return{identityKey:i,signature:Array.from(s),nonce:r.nonce,method:e,wallet:t}}async function Xd(n,t){try{return await t()}catch(e){let i=e instanceof Error?e:new Error(String(e));throw i.stage||Object.assign(i,{stage:n}),i}}var ab=1,gu=[2,"bwalletx access"];var cb=50,ub={not_installed:424,user_rejected:403,wrong_account:409,insufficient_tokens:403,identity_level_too_low:403,kyc_required:403,indexer_unavailable:503,expired:401,replay:401,invalid_signature:401,bad_request:400},kt=class extends Error{constructor(e,i,r={}){super(i??e);b(this,"code");b(this,"have");b(this,"need");this.name="AccessError",this.code=e,this.have=r.have,this.need=r.need}toJSON(){let e={error:this.code,message:this.message};return this.have!==void 0&&(e.have=this.have),this.need!==void 0&&(e.need=this.need),e}},Gd={401:{name:"Identity",color:"#22c55e",video:"assets/protocol/401.mp4",poster:"assets/protocol/401.jpg"},402:{name:"Payment",color:"#3b82f6",video:"assets/protocol/402.mp4",poster:"assets/protocol/402.jpg"},403:{name:"Access",color:"#ef4444",video:"assets/protocol/403.mp4",poster:"assets/protocol/403.jpg"}};function fb(n,t,e="latest"){return`https://unpkg.com/@bwalletx/connect@${e}/${Gd[n][t]}`}function ia(n){if(n===null)return"null";if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="number"){if(!Number.isFinite(n))throw new Error("canonicalJson: non-finite number");return JSON.stringify(n)}if(Array.isArray(n))return`[${n.map(t=>ia(t)).join(",")}]`;if(typeof n=="object"){let t=n;return`{${Object.keys(t).filter(i=>t[i]!==void 0).sort().map(i=>`${JSON.stringify(i)}:${ia(t[i])}`).join(",")}}`}throw new Error(`canonicalJson: unsupported ${typeof n}`)}function Yd(n){return Array.from(new TextEncoder().encode(n))}var r4=/^bsv21:[0-9a-f]{64}_\d{1,6}$/,s4=/^[1-9]\d{0,38}$/;function o4(n){if(!n||typeof n!="object")throw new kt("bad_request","require must be an object");let t=n,e={};if(t.token!==void 0){let i=t.token;if(!i||typeof i!="object"||typeof i.id!="string")throw new kt("bad_request","require.token.id is required");let r=i.id.trim().toLowerCase();if(!r4.test(r))throw new kt("bad_request","require.token.id must be 'bsv21:<txid>_<vout>'");let s=i.min!==void 0,o=i.minBps!==void 0;if(s===o)throw new kt("bad_request","require.token needs exactly one of min or minBps");if(e.token={id:r},s){if(typeof i.min!="string"||!s4.test(i.min))throw new kt("bad_request","require.token.min must be a positive integer string (raw units)");e.token.min=i.min}else{if(!Number.isInteger(i.minBps)||i.minBps<1||i.minBps>1e4)throw new kt("bad_request","require.token.minBps must be an integer 1..10000");e.token.minBps=i.minBps}}if(t.identityLevel!==void 0){if(!Number.isInteger(t.identityLevel)||t.identityLevel<1||t.identityLevel>10)throw new kt("bad_request","require.identityLevel must be an integer 1..10");e.identityLevel=t.identityLevel}if(t.kyc!==void 0){if(typeof t.kyc!="boolean")throw new kt("bad_request","require.kyc must be a boolean");t.kyc&&(e.kyc=!0)}if(!e.token&&!e.identityLevel&&!e.kyc)throw new kt("bad_request","require is empty");return e}function db(n){if(typeof n!="string"||n.length>4096)throw new kt("bad_request","challenge must be a string");let t;try{t=JSON.parse(n)}catch{throw new kt("bad_request","challenge is not JSON")}if(!t||typeof t!="object"||t.v!==1)throw new kt("bad_request","unsupported challenge version");if(t.kind!=="401"&&t.kind!=="402"&&t.kind!=="403")throw new kt("bad_request","bad kind");if(typeof t.origin!="string"||typeof t.nonce!="string"||!/^[A-Za-z0-9_-]{16,64}$/.test(t.nonce))throw new kt("bad_request","bad origin or nonce");if(!Number.isInteger(t.iat)||!Number.isInteger(t.exp)||t.exp<=t.iat)throw new kt("bad_request","bad iat/exp");if(t.sub!==void 0&&(typeof t.sub!="string"||!/^0[23][0-9a-f]{64}$/.test(t.sub)))throw new kt("bad_request","bad sub");if(t.require=o4(t.require),ia(t)!==n)throw new kt("bad_request","challenge is not canonical");return t}function lb(n,t={}){switch(n){case"not_installed":return"No bWalletX (or other BRC-100 wallet) was found.";case"user_rejected":return"The request was declined in the wallet.";case"wrong_account":return"The wallet is signed in to a different account than this site expects.";case"insufficient_tokens":return`Not enough tokens: holding ${t.have??0}, need ${t.need??"?"}.`;case"identity_level_too_low":return`Identity level ${t.have??0} is below the required level ${t.need??"?"}.`;case"kyc_required":return"A verified identity (KYC) is required.";case"indexer_unavailable":return"Holdings could not be checked right now. Try again shortly.";case"expired":return"The request expired. Try again.";case"replay":return"That request was already used. Try again.";case"invalid_signature":return"The wallet signature did not verify.";case"bad_request":return"The request was malformed."}}var a4=[0,"onesat"],c4=[0,"p 1sat"];function mu(n){if(n instanceof kt)return n;let t=n,e=String(t?.message??n??"");return t?.code==="NOT_FOUND"?new kt("not_installed",e):/reject|denied|declin|cancel|user/i.test(e)||t?.code==="ERR_USER_REJECTED"||t?.status===4001?new kt("user_rejected",e):new kt("bad_request",e||"access failed")}function Zd(n){let t=n;if(t&&typeof t.error=="string")throw new kt(t.error,t.message,{have:t.have,need:t.need})}function u4(n){let t=/^76a914([0-9a-f]{40})88ac$/i.exec(n.slice(-50));return t?t[1].toLowerCase():null}async function Jd(n,t,e,i="bsv21"){let r=e.replace(/^bsv21:/,""),s=await n.listOutputs({basket:i,include:"locking scripts",includeCustomInstructions:!0,limit:1e4}),o=new Map,c=Yd(t);for(let u of s.outputs){if(o.size>=cb)break;let f={};try{f=JSON.parse(u.customInstructions??"{}")}catch{continue}if(f.id!==r||!f.keyID)continue;let d=u.lockingScript?u4(u.lockingScript):null,l=f.counterparty??"self";for(let p of f.protocolID?[f.protocolID]:[a4,c4]){let{publicKey:m}=await n.getPublicKey({protocolID:p,keyID:f.keyID,counterparty:l}),g=yi.toHex(Ta.hash160(Ht.fromString(m).encode(!0)));if(d&&g!==d)continue;let w=o.get(m);if(w){w.outpoints.push(u.outpoint.replace(".","_"));break}let{signature:S}=await n.createSignature({protocolID:p,keyID:f.keyID,counterparty:l,data:c});o.set(m,{pubkey:m,signature:Array.from(S),outpoints:[u.outpoint.replace(".","_")]});break}}return[...o.values()]}async function bu(n){let t;try{({wallet:t}=await na({wallet:n.wallet,pairing:n.pairing,discoverMs:n.discoverMs}))}catch(e){throw e?.code==="NOT_FOUND"?new kt("not_installed"):mu(e)}try{let{publicKey:e}=await t.getPublicKey({identityKey:!0}),{challenge:i}=await n.challenge(e),r=db(i);if(r.sub&&r.sub!==e.toLowerCase())throw new kt("wrong_account");if(Date.now()/1e3>=r.exp)throw new kt("expired");let{signature:s}=await t.createSignature({protocolID:gu,keyID:r.nonce,counterparty:"anyone",data:Yd(i)}),o={v:1,challenge:i,identityKey:e,signature:Array.from(s)};r.require.token&&(o.holdings=await Jd(t,i,r.require.token.id,n.tokenBasket));let c;return n.verify&&(c=await n.verify(o),Zd(c)),{response:o,verified:c,wallet:t}}catch(e){throw mu(e)}}var el="bwalletx-signin",nl="https://bwalletx.com/get",ra="https://web.bwalletx.com",hb={signin:"Sign in with",continue:"Continue with",connect:"Connect"};function il(n="signin",t="bWalletX"){return`${hb[n]??hb.signin} ${t}`}var f4=0;function rl(n=20){let t=++f4;return`<svg viewBox="23 8 74 100" width="${Math.round(n*.74)}" height="${n}" aria-hidden="true" focusable="false"><defs><linearGradient id="bwxg${t}" gradientUnits="userSpaceOnUse" x1="0" y1="12" x2="0" y2="105"><stop offset="0" stop-color="#FFE58A"/><stop offset=".55" stop-color="#FFD24D"/><stop offset="1" stop-color="#C98F00"/></linearGradient><mask id="bwxh${t}"><rect width="140" height="140" fill="#fff"/><circle cx="60" cy="72" r="15" fill="#000"/></mask></defs><g fill="url(#bwxg${t})" mask="url(#bwxh${t})"><polygon points="45,12 45,76 27,76 27,30"/><circle cx="60" cy="72" r="33"/></g></svg>`}var sl=`
|
|
25
25
|
:host{display:inline-block;vertical-align:middle;font-family:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
|
26
26
|
:host([full-width]){display:block;width:100%}
|
|
27
27
|
:host([hidden]){display:none}
|
|
@@ -67,13 +67,13 @@ button[aria-busy=true]{cursor:wait}
|
|
|
67
67
|
.nf a:focus-visible{outline:2px solid #b45309;outline-offset:2px;border-radius:2px}
|
|
68
68
|
:host([theme=dark]) .nf,:host-context(.dark) .nf{color:#a1a1aa}
|
|
69
69
|
.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
|
|
70
|
-
`;function
|
|
70
|
+
`;function pb(n){let t="";for(let e of n)t+=String.fromCharCode(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ol(n){let t=u=>pb(crypto.getRandomValues(new Uint8Array(u))),e=t(32),i=t(16),r=t(16),s=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))),o=new URL(n.authorizeUrl,typeof location<"u"?location.href:void 0),c=(u,f)=>{f&&o.searchParams.set(u,f)};c("response_type","code"),c("client_id",n.clientId),c("redirect_uri",n.redirectUri),c("scope",n.scope||"openid profile"),c("state",i),c("nonce",r),c("code_challenge",pb(s)),c("code_challenge_method","S256");try{sessionStorage.setItem("bwalletx:oauth",JSON.stringify({verifier:e,state:i,nonce:r}))}catch{}return o.toString()}async function Qd(n,t){let e=await fetch(n,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),i=await e.json().catch(()=>({}));if(!e.ok)throw new Error(i.error??`HTTP ${e.status}`);return i}async function d4(n,t){let e=await fetch(n,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify(t)});return e.json().catch(()=>({error:"bad_request",message:`HTTP ${e.status}`}))}var l4=["size","theme","label","brand","subtitle","loading","disabled","full-width","aria-label","get-url","web-url"];function h4(){var n,t,e,i,Qt,wu,zi,tl,gb,f;return f=class extends HTMLElement{constructor(){super();G(this,i);G(this,n);G(this,t,!1);G(this,e,!1);N(this,n,this.attachShadow({mode:"open"}))}static get observedAttributes(){return l4}connectedCallback(){a(this,i,wu).call(this)}attributeChangedCallback(){this.isConnected&&a(this,i,wu).call(this)}get button(){return y(this,n).querySelector("button")}get notFound(){return y(this,t)}focus(p){this.button?.focus(p)}},n=new WeakMap,t=new WeakMap,e=new WeakMap,i=new WeakSet,Qt=function(p){return this.getAttribute(p)},wu=function(){let p=a(this,i,Qt).call(this,"size")??"lg",m=a(this,i,Qt).call(this,"brand")==="bWallet"?"bWallet":"bWalletX",g=il(a(this,i,Qt).call(this,"label")??"signin",m),w=a(this,i,Qt).call(this,"subtitle"),C=w===null||w===""||w==="on"?w==="on"?"also works with bWallet":m==="bWalletX"&&(p==="lg"||p==="md")?"also works with bWallet":null:w==="off"?null:w,E=this.hasAttribute("loading")||y(this,e),A=this.hasAttribute("disabled"),k=p==="icon"?24:p==="sm"?15:p==="md"?17:20,B=a(this,i,Qt).call(this,"aria-label")??(C&&p!=="icon"?`${g}, ${C}`:g),_=a(this,i,Qt).call(this,"get-url")??nl,H=a(this,i,Qt).call(this,"web-url")??ra,O=F=>F.replace(/[&<>"]/g,it=>({"&":"&","<":"<",">":">",'"':"""})[it]),I=p==="icon"?"":`<span class="txt" part="text"><b part="label">${O(g)}</b>${C?`<small part="subtitle">${O(C)}</small>`:""}</span>`,U=E?'<span class="spin" aria-hidden="true"></span>':rl(k),M=y(this,t)?`<p class="nf" part="not-found" role="status">bWalletX wasn't found in this browser. <a href="${O(_)}" target="_blank" rel="noopener">Get ${m}</a> or <a href="${O(H)}" target="_blank" rel="noopener">use the web wallet</a>.</p>`:"";y(this,n).innerHTML=`<style>${sl}</style><button type="button" part="button" aria-label="${O(B)}" title="${O(C?`${g} (${C})`:g)}"${A?" disabled":""}${E?' aria-busy="true"':""}><span class="mark" part="mark">${U}</span>${I}</button>${E?'<span class="sr" role="status">Connecting to bWalletX\u2026</span>':""}${M}`,this.button.addEventListener("click",()=>{a(this,i,gb).call(this)}),fu(this.button)},zi=function(p,m,g=!1){return this.dispatchEvent(new CustomEvent(p,{detail:m,bubbles:!0,composed:!0,cancelable:g}))},tl=function(p){N(this,e,p),a(this,i,wu).call(this)},gb=async function(){if(this.hasAttribute("disabled")||this.hasAttribute("loading")||y(this,e)||!a(this,i,zi).call(this,"bwalletx-signin",{element:this},!0))return;let p=a(this,i,Qt).call(this,"href"),m=a(this,i,Qt).call(this,"authorize-url");if(m){location.assign(await ol({authorizeUrl:m,clientId:a(this,i,Qt).call(this,"client-id"),redirectUri:a(this,i,Qt).call(this,"redirect-uri"),scope:a(this,i,Qt).call(this,"scope")}));return}if(p){location.assign(p);return}let g=a(this,i,Qt).call(this,"challenge-url");if(g){N(this,t,!1),a(this,i,tl).call(this,!0);try{let w=Number(a(this,i,Qt).call(this,"discover-ms"))||Vi,S=await Ki(w);if(!S){N(this,t,!0),a(this,i,zi).call(this,"bwalletx-not-found"),a(this,i,Qt).call(this,"require-token")&&a(this,i,zi).call(this,"bwalletx-access-denied",{code:"not_installed",message:"No wallet found"});return}let C=a(this,i,Qt).call(this,"require-token");if(C){let B=a(this,i,Qt).call(this,"verify-url"),_=a(this,i,Qt).call(this,"min"),H=a(this,i,Qt).call(this,"min-bps"),O={token:{id:C,...H?{minBps:Number(H)}:{min:_??"1"}}};try{let I=await bu({wallet:S.wallet,challenge:U=>Qd(g,{identityKey:U,require:O}),verify:B?U=>d4(B,U):void 0});a(this,i,zi).call(this,"bwalletx-access-granted",{identityKey:I.response.identityKey,response:I.verified})}catch(I){let U=I instanceof kt?I:new kt("bad_request",String(I));a(this,i,zi).call(this,"bwalletx-access-denied",{code:U.code,message:U.message,have:U.have,need:U.need})}return}let E=await pu({wallet:S.wallet,challenge:B=>Qd(g,{identityKey:B})}),A=a(this,i,Qt).call(this,"verify-url"),k=A?await Qd(A,{identityKey:E.identityKey,nonce:E.nonce,signature:E.signature}):null;a(this,i,zi).call(this,"bwalletx-signed-in",{identityKey:E.identityKey,method:S.method,nonce:E.nonce,signature:E.signature,response:k})}catch(w){a(this,i,zi).call(this,"bwalletx-error",{error:w})}finally{a(this,i,tl).call(this,!1)}}},f}function yu(n=el){if(typeof window>"u"||typeof customElements>"u")return;let t=customElements.get(n);if(t)return t;let e=h4();return customElements.define(n,e),e}var p4=`
|
|
71
71
|
.bwx-signin{display:inline-flex;align-items:center;gap:12px;min-height:48px;padding:10px 22px 10px 10px;border:0;border-radius:12px;cursor:pointer;background:linear-gradient(180deg,#fcd34d,#f59e0b);color:#000;text-align:left;font:700 16px/1.2 system-ui,-apple-system,"Segoe UI",sans-serif;box-shadow:0 8px 24px rgba(245,158,11,.2)}
|
|
72
72
|
.bwx-signin:hover{background:linear-gradient(180deg,#fde68a,#fbbf24)}
|
|
73
73
|
.bwx-signin:focus-visible{outline:2px solid #ffd24d;outline-offset:3px}
|
|
74
74
|
.bwx-signin:disabled{opacity:.6;cursor:wait}
|
|
75
75
|
.bwx-signin .bwx-mark{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:50%;background:#000;flex:none}
|
|
76
|
-
.bwx-signin small{display:block;font-size:11px;font-weight:500;color:rgba(0,0,0,.6)}`,
|
|
76
|
+
.bwx-signin small{display:block;font-size:11px;font-weight:500;color:rgba(0,0,0,.6)}`,al="https://bwalletx.com/logo.svg";function mb(n,t={}){let e=typeof n=="string"?document.querySelector(n):n;if(!e)throw new Error(`renderButton: no element ${String(n)}`);if(!document.getElementById("bwx-signin-css")){let u=document.createElement("style");u.id="bwx-signin-css",u.textContent=p4,document.head.appendChild(u)}let i=document.createElement("button");i.type="button",i.className="bwx-signin";let r=document.createElement("span");r.className="bwx-mark";let s=document.createElement("img");s.src=al,s.alt="",s.width=15,s.height=20,r.appendChild(s);let o=document.createElement("span");o.className="bwx-label",o.textContent="Sign in with bWalletX";let c=t.subtitle===void 0?"also works with bWallet":t.subtitle;if(c){let u=document.createElement("small");u.textContent=c,o.appendChild(u)}return i.append(r,o),t.onClick&&i.addEventListener("click",()=>t.onClick(i)),e.replaceChildren(i),i}var cl=[2,"3241645161d8"],he=class extends Error{constructor(e,i,r=!1,s){super(i);b(this,"code",e);b(this,"maybeSent",r);b(this,"cause",s);this.name="PaymentError"}},yb=n=>typeof n.pay=="function"&&typeof n.createAction!="function",ul=n=>/^0[23][0-9a-fA-F]{64}$/.test(n),fl=n=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n);function bb(n){let t=new Uint8Array(n);return globalThis.crypto.getRandomValues(t),yi.toBase64(Array.from(t))}function g4(n){let t=yi.toArray(n,"utf8"),e=t.length,i=e<76?[e]:e<=255?[76,e]:[77,e&255,e>>8];return yi.toHex([0,106,...i,...t])}var dl=(n,t)=>n.length>t?n.slice(0,t-1)+"\u2026":n,wb=n=>dl(n.length<5?`${n} payment`.trim():n,50);async function m4(n){if(typeof n.usdPerBsv=="number")return n.usdPerBsv;try{if(typeof n.usdPerBsv=="function")return await n.usdPerBsv();let t=await(n.fetch??fetch)("https://api.whatsonchain.com/v1/bsv/main/exchangerate"),e=await t.json();if(!t.ok||!(Number(e.rate)>0))throw new Error(`status ${t.status}`);return Number(e.rate)}catch(t){throw new he("RATE_FAILED",`Could not get the BSV/USD rate: ${t.message}`,!1,t)}}async function ll(n,t={}){if(n.sats!=null){if(!Number.isSafeInteger(n.sats)||n.sats<=0)throw new he("BAD_REQUEST","sats must be a positive integer");return n.sats}if(n.usd!=null){if(!(n.usd>0))throw new he("BAD_REQUEST","usd must be positive");return Math.max(1,Math.ceil(n.usd/await m4(t)*1e8))}throw new he("BAD_REQUEST","Give sats or usd")}async function hl(n,t,e=fetch){let[i,r]=n.split("@"),s=(l,p)=>new he("RESOLVE_FAILED",`Could not resolve ${n}: ${l}`,!1,p),o;try{o=(await(await e(`https://${r}/.well-known/bsvalias`)).json()).capabilities}catch(l){throw s("no bsvalias document (or CORS blocked it; resolve on your server and pass resolvePaymail)",l)}let c=l=>l.replace("{alias}",encodeURIComponent(i)).replace("{domain.tld}",r),u=o?.["2a40af698840"];if(!u)throw s("it does not offer P2P payment destinations");let f;try{let l=await e(c(u),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({satoshis:t})});if(!l.ok)throw new Error(`status ${l.status}`);f=await l.json()}catch(l){throw s(l.message,l)}if(!f.outputs?.length)throw s("no outputs returned");let d=o["5f1323cddf31"];return{outputs:f.outputs.map(l=>({script:l.script,satoshis:l.satoshis})),reference:f.reference,submit:d?async l=>{await e(c(d),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hex:l,reference:f.reference,metadata:{}})})}:void 0}}async function xb(n,t,e,i){try{return await n.createAction({description:wb(t),outputs:e.map(r=>({lockingScript:r.script,satoshis:r.satoshis,outputDescription:wb(r.description??"payment")})),labels:i?.length?i:void 0,options:{randomizeOutputs:!1}})}catch(r){let s=r?.message??String(r),o=/denied|reject|cancel|abort|user/i.test(s)||r?.code===4001;throw new he(o?"WALLET_REJECTED":"WALLET_ERROR",o?"The payment was declined in the wallet.":`The wallet could not make the payment: ${s}`,!o,r)}}async function pl(n,t,e={}){let i=(t.to??"").trim();if(!i)throw new he("BAD_REQUEST","Give a recipient (to)");if(t.memo&&t.memo.length>1e3)throw new he("BAD_REQUEST","memo is too long");let r=await ll(t,e);if(yb(n))return n.pay({...t,to:i,sats:r});let s,o,c;if(ul(i)){let d=bb(8),l=bb(8),p,m;try{({publicKey:p}=await n.getPublicKey({protocolID:cl,keyID:`${d} ${l}`,counterparty:i.toLowerCase()})),{publicKey:m}=await n.getPublicKey({identityKey:!0})}catch(g){throw new he("WALLET_ERROR",`The wallet could not derive the payment key: ${g.message}`,!1,g)}s=[{script:new Yn().lock(Ht.fromString(p).toHash()).toHex(),satoshis:r,description:"payment"}],o={senderIdentityKey:m,derivationPrefix:d,derivationSuffix:l,outputIndex:0}}else if(fl(i)){let d=await(e.resolvePaymail??((l,p)=>hl(l,p,e.fetch??fetch)))(i,r);s=d.outputs,c=d.submit}else try{s=[{script:new Yn().lock(i).toHex(),satoshis:r,description:"payment"}]}catch{throw new he("BAD_REQUEST",`Not a paymail, address or identity key: ${i}`)}t.memo&&t.memoOnChain&&(s=[...s,{script:g4(t.memo),satoshis:0,description:"memo"}]);let u=await xb(n,t.memo||`Pay ${dl(i,30)}`,s,t.labels);if(!u.txid)throw new he("WALLET_ERROR","The wallet did not return a txid",!0);let f=u.tx?Array.from(u.tx):void 0;return c&&f&&await c(Me.fromAtomicBEEF(f).toHex()).catch(()=>{}),{txid:u.txid,tx:f,sats:r,outputs:s,remittance:o}}function Sb(n,t,e={}){return pl(n,{memo:"Tip",...t,labels:[...t.labels??[],"tip"]},e)}async function Ib(n,t){if(yb(n))throw new he("NOT_SUPPORTED","This wallet cannot buy tokens. Use a BRC-100 wallet such as bWalletX.");let e=await t.quote({token:t.token,amount:t.amount});if(!e?.outputs?.length)throw new he("BAD_REQUEST","The quote returned no outputs");let i=e.outputs.reduce((o,c)=>o+c.satoshis,0),r=await xb(n,e.description??`Buy ${dl(t.token,30)}`,e.outputs,[...t.labels??[],"token-buy"]);if(!r.txid)throw new he("WALLET_ERROR","The wallet did not return a txid",!0);let s={txid:r.txid,tx:r.tx?Array.from(r.tx):void 0,sats:i,outputs:e.outputs};return await e.onPaid?.(s),s}async function Ab(n,t){await n.waitForAuthentication({}).catch(()=>{});let{publicKey:e}=await n.getPublicKey({identityKey:!0});return{wallet:n,payer:n,identityKey:e,optionId:t.id,kind:t.kind}}function Ls(n,t){let e={id:t.id,name:t.name,icon:t.icon,rdns:t.rdns,kind:"brc100",isBwalletX:t.isBwalletX??!1,connect:()=>Ab(n,e)};return e}function gl(n){let t={id:"bwalletx-pairing",name:"bWalletX on your phone",kind:"pairing",isBwalletX:!0,async connect(){let e=typeof n=="function"?n():n,i=await Cs(e)??await _s(e);return Ab(i,t)}};return t}function Eb(n){let t={id:"handcash",name:"HandCash",icon:n.icon,kind:"handcash",isBwalletX:!1,async connect(){let e=await n.login();return{wallet:null,payer:n.pay?{pay:n.pay}:null,identityKey:e.identityKey??null,handle:e.handle,paymail:e.paymail??`${e.handle.replace(/^\$/,"")}@handcash.io`,optionId:t.id,kind:"handcash",transitional:!0}}};return t}var b4={[Ns]:"bWalletX","space.bwallet.mobile":"bWalletX"};async function vb(n,t){try{let e=new Wi(n);return await Promise.race([e.isAuthenticated({}).then(()=>!0),new Promise(r=>setTimeout(()=>r(!1),t))])?e:null}catch{return null}}async function kb(n={}){let t=[],e=n.ms??300;if(typeof window<"u"){let r=new Map,s=d=>{let l=d.detail;if(!l?.wallet)return;let p=l.info?.rdns??l.info?.uuid??`wallet-${r.size}`;if(r.has(p))return;let m=Qo.includes(p);r.set(p,Ls(l.wallet,{id:p,rdns:p,name:b4[p]??l.info?.name??p,icon:l.info?.icon,isBwalletX:m}))};window.addEventListener("brc100:announceWallet",s),window.dispatchEvent(new Event("brc100:requestWallet"));let o=n.probeLocal?Promise.all([vb("json-api",e),vb("Cicada",e)]):Promise.resolve([null,null]);await new Promise(d=>setTimeout(d,r.size>0||window.CWI?Math.min(e,50):e)),window.removeEventListener("brc100:announceWallet",s),t.push(...r.values());let c=window.CWI;c&&![...r.values()].some(d=>d.rdns==="space.bwallet.mobile")&&t.push(Ls(c,{id:"window.CWI",name:"This app\u2019s wallet",isBwalletX:!1}));let[u,f]=await o;u&&t.push(Ls(u,{id:"localhost:3321",name:"Desktop wallet (localhost:3321)"})),f&&t.push(Ls(f,{id:"localhost:3301",name:"Desktop wallet (localhost:3301)"}))}n.pairing&&t.push(gl(n.pairing)),t.push(...n.extra??[]);let i=r=>r.isBwalletX?0:r.kind==="handcash"?2:1;return t.map((r,s)=>({w:r,i:s})).sort((r,s)=>i(r.w)-i(s.w)||r.i-s.i).map(r=>r.w)}var Nb=Wb(Rb(),1);var w4=`
|
|
77
77
|
.bwx-ov{position:fixed;inset:0;z-index:2147483000;background:rgba(0,0,0,.6);display:flex;align-items:center;justify-content:center;padding:16px;font:15px/1.4 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
|
|
78
78
|
.bwx-box{background:#0b0b0b;color:#f4f1e8;border:1px solid #3a3220;border-radius:16px;width:min(360px,100%);padding:20px;box-shadow:0 20px 60px rgba(0,0,0,.5)}
|
|
79
79
|
.bwx-box h2{margin:0 0 6px;font-size:18px;color:#e8c766}
|
|
@@ -84,9 +84,12 @@ button[aria-busy=true]{cursor:wait}
|
|
|
84
84
|
.bwx-row{display:flex;gap:8px;margin-top:14px}
|
|
85
85
|
.bwx-btn{flex:1;border:1px solid #3a3220;background:#15130e;color:#f4f1e8;border-radius:10px;padding:10px 12px;font:inherit;cursor:pointer}
|
|
86
86
|
.bwx-btn:hover{border-color:#e8c766}
|
|
87
|
+
a.bwx-btn{display:block;text-align:center;text-decoration:none;box-sizing:border-box}
|
|
88
|
+
.bwx-primary{background:linear-gradient(180deg,#fcd34d,#f59e0b);color:#000;border:0;font-weight:700;min-height:48px;padding:13px 12px}
|
|
89
|
+
.bwx-stack{display:flex;flex-direction:column;gap:8px}
|
|
87
90
|
.bwx-list{display:flex;flex-direction:column;gap:8px}
|
|
88
91
|
.bwx-opt{display:flex;align-items:center;gap:10px;text-align:left}
|
|
89
92
|
.bwx-opt img{width:24px;height:24px;border-radius:6px}
|
|
90
93
|
.bwx-tag{margin-left:auto;font-size:11px;color:#8d866f}
|
|
91
|
-
`;function
|
|
94
|
+
`;function Bb(){let n=document.createElement("div");n.className="bwx-ov",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true");let t=document.createElement("style");t.textContent=w4;let e=document.createElement("div");return e.className="bwx-box",n.append(t,e),document.body.appendChild(n),{root:n,box:e,close:()=>n.remove()}}function ie(n,t,e){let i=document.createElement(n);return t&&(i.className=t),e!=null&&(i.textContent=e),i}function ml(n){let t=(0,Nb.default)(0,"M");return t.addData(n),t.make(),t.createSvgTag({cellSize:4,margin:2,scalable:!0})}function bl(n=globalThis){let t=n.navigator;if(!t)return!1;let e=t.userAgent??"";if(/Android|iPhone|iPad|iPod|Mobile|Silk|Kindle/i.test(e)||/Macintosh/.test(e)&&(t.maxTouchPoints??0)>1)return!0;try{return!!n.matchMedia?.("(pointer: coarse)").matches&&!n.matchMedia?.("(hover: hover)").matches}catch{return!1}}function _b(n={}){let t=new AbortController,e=null,i=null,r=()=>{e?.close(),e=null};return t.signal.addEventListener("abort",r),{signal:t.signal,close:r,onLink(s){if(typeof document>"u")return;r(),e=Bb();let o=n.mode==="app"||(n.mode??"auto")==="auto"&&bl(),c=ie("h2","",n.title??"Connect bWalletX"),u=ie("button","bwx-btn","Cancel");if(u.onclick=()=>{n.onCancel?.(),t.abort()},i=ie("div","bwx-code",""),i.setAttribute("aria-live","polite"),o){let m=ie("p","","Open bWalletX, approve, then come back to this page."),g=ie("div","bwx-stack"),w=ie("a","bwx-btn bwx-primary","Open bWalletX");w.href=s,w.rel="noopener";let S=ie("button","bwx-btn","Use web.bwalletx.com instead");S.onclick=()=>{navigator.clipboard?.writeText(s).catch(()=>{}),window.open(ra,"_blank","noopener"),m.textContent="Link copied. In web.bwalletx.com tap Connect and paste it, then come back here."},g.append(w,S,u),e.box.append(c,m,i,g);return}let f=ie("p","","Scan with bWalletX on your phone, or paste the link into web.bwalletx.com."),d=ie("div","bwx-qr");d.innerHTML=ml(s);let l=ie("div","bwx-row"),p=ie("button","bwx-btn","Copy link");p.onclick=()=>{navigator.clipboard?.writeText(s).then(()=>p.textContent="Copied")},l.append(p,u),e.box.append(c,f,d,i,l)},onCode(s){if(i){i.textContent=s;let o=e?.box.querySelector("p");o&&(o.textContent="Check bWalletX shows the same code, then tap Connect.")}}}}function Cb(n,t={}){return typeof document>"u"?Promise.resolve(null):new Promise(e=>{let i=Bb(),r=c=>{i.close(),e(c)};i.box.append(ie("h2","",t.title??"Choose a wallet")),n.length||i.box.append(ie("p","","No wallet found. Get bWalletX at bwalletx.com."));let s=ie("div","bwx-list");for(let c of n){let u=ie("button","bwx-btn bwx-opt");if(c.icon){let f=ie("img");f.src=c.icon,f.alt="",u.append(f)}u.append(ie("span","",c.name)),c.kind==="handcash"&&u.append(ie("span","bwx-tag","until BRC-100")),u.onclick=()=>r(c),s.append(u)}let o=ie("button","bwx-btn","Cancel");o.onclick=()=>r(null),i.root.onclick=c=>c.target===i.root&&r(null),i.box.append(s,ie("div","bwx-row")),i.box.lastChild.append(o)})}var xu="bwalletx-theme",y4=/^[a-z0-9-]{1,32}$/;function Lb(n){if(typeof document>"u")return;let t=(n??"").trim().toLowerCase(),e=document.head.querySelector(`meta[name="${xu}"]`);if(!t||!y4.test(t)){e?.remove();return}e||(e=document.createElement("meta"),e.name=xu,document.head.appendChild(e)),e.content!==t&&(e.content=t)}yu();return Vb(x4);})();
|
|
92
95
|
//# sourceMappingURL=bwalletx-connect.global.js.map
|