@bwalletx/connect 0.5.0 → 0.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/README.md +6 -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-IUDD7YTQ.js} +78 -10
- package/dist/chunk-IUDD7YTQ.js.map +1 -0
- package/dist/{chunk-GF6GUDZL.js → chunk-PI42H3XY.js} +65 -10
- package/dist/chunk-PI42H3XY.js.map +1 -0
- package/dist/element.cjs +83 -16
- package/dist/element.cjs.map +1 -1
- package/dist/element.js +1 -1
- package/dist/index.cjs +156 -32
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +30 -3
- package/dist/index.d.ts +30 -3
- package/dist/index.js +8 -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 +862 -736
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +5 -0
- package/dist/react.d.ts +5 -0
- 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/package.json +3 -3
- 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&&H>0?tn.substring(0,tn.length-D-1)+Array(D+1).join("\u2580"):tn.substring(0,tn.length-1)};return F.createASCII=function(H,W){if(H=H||1,H<2)return vn(W);H-=1,W=typeof W>"u"?H*2:W;var D=F.getModuleCount()*H+W*2,V=W,X=D-W,J,dt,ft,Ct,
|
|
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 Ob=Object.create;var Cs=Object.defineProperty;var Pb=Object.getOwnPropertyDescriptor;var Rb=Object.getOwnPropertyNames;var Nb=Object.getPrototypeOf,Bb=Object.prototype.hasOwnProperty;var ml=n=>{throw TypeError(n)};var _b=(n,t,e)=>t in n?Cs(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var xu=(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 Cb=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports),Iu=(n,t)=>{for(var e in t)Cs(n,e,{get:t[e],enumerable:!0})},bl=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Rb(t))!Bb.call(n,r)&&r!==e&&Cs(n,r,{get:()=>t[r],enumerable:!(i=Pb(t,r))||i.enumerable});return n};var Lb=(n,t,e)=>(e=n!=null?Ob(Nb(n)):{},bl(t||!n||!n.__esModule?Cs(e,"default",{value:n,enumerable:!0}):e,n)),Ub=n=>bl(Cs({},"__esModule",{value:!0}),n);var b=(n,t,e)=>_b(n,typeof t!="symbol"?t+"":t,e),Su=(n,t,e)=>t.has(n)||ml("Cannot "+e);var w=(n,t,e)=>(Su(n,t,"read from private field"),e?e.call(n):t.get(n)),G=(n,t,e)=>t.has(n)?ml("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),N=(n,t,e,i)=>(Su(n,t,"write to private field"),i?i.call(n,e):t.set(n,e),e),a=(n,t,e)=>(Su(n,t,"access private method"),e);var Sb=Cb((xb,Ib)=>{"use strict";var wb=(function(){var n=function(E,A){var k=236,B=17,_=E,$=e[A],R=null,I=0,U=null,M=[],F={},it=function(H,W){I=_*4+17,R=(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(H,W),_>=7&&It(H),U==null&&(U=ke(_,$,M)),Bt(U,W)},ot=function(H,W){for(var D=-1;D<=7;D+=1)if(!(H+D<=-1||I<=H+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?R[H+D][W+V]=!0:R[H+D][W+V]=!1)},q=function(){for(var H=0,W=0,D=0;D<8;D+=1){it(!0,D);var V=r.getLostPoint(F);(D==0||H>V)&&(H=V,W=D)}return W},z=function(){for(var H=8;H<I-8;H+=1)R[H][6]==null&&(R[H][6]=H%2==0);for(var W=8;W<I-8;W+=1)R[6][W]==null&&(R[6][W]=W%2==0)},tt=function(){for(var H=r.getPatternPosition(_),W=0;W<H.length;W+=1)for(var D=0;D<H.length;D+=1){var V=H[W],X=H[D];if(R[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?R[V+J][X+dt]=!0:R[V+J][X+dt]=!1}},It=function(H){for(var W=r.getBCHTypeNumber(_),D=0;D<18;D+=1){var V=!H&&(W>>D&1)==1;R[Math.floor(D/3)][D%3+I-8-3]=V}for(var D=0;D<18;D+=1){var V=!H&&(W>>D&1)==1;R[D%3+I-8-3][Math.floor(D/3)]=V}},ce=function(H,W){for(var D=$<<3|W,V=r.getBCHTypeInfo(D),X=0;X<15;X+=1){var J=!H&&(V>>X&1)==1;X<6?R[X][8]=J:X<8?R[X+1][8]=J:R[I-15+X][8]=J}for(var X=0;X<15;X+=1){var J=!H&&(V>>X&1)==1;X<8?R[8][I-X-1]=J:X<9?R[8][15-X-1+1]=J:R[8][15-X-1]=J}R[I-8][8]=!H},Bt=function(H,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(R[V][ft-Ct]==null){var re=!1;J<H.length&&(re=(H[J]>>>X&1)==1);var pt=dt(V,ft-Ct);pt&&(re=!re),R[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(H,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&H.getBuffer()[pt+D];D+=Ct;var Qe=r.getErrorCorrectPolynomial(re),tn=o(J[ft],Qe.getLength()-1),hl=tn.mod(Qe);dt[ft]=new Array(Qe.getLength()-1);for(var pt=0;pt<dt[ft].length;pt+=1){var pl=pt+hl.getLength()-dt[ft].length;dt[ft][pt]=pl>=0?hl.getAt(pl):0}}for(var gl=0,pt=0;pt<W.length;pt+=1)gl+=W[pt].totalCount;for(var wu=new Array(gl),ia=0,pt=0;pt<V;pt+=1)for(var ft=0;ft<W.length;ft+=1)pt<J[ft].length&&(wu[ia]=J[ft][pt],ia+=1);for(var pt=0;pt<X;pt+=1)for(var ft=0;ft<W.length;ft+=1)pt<dt[ft].length&&(wu[ia]=dt[ft][pt],ia+=1);return wu},ke=function(H,W,D){for(var V=c.getRSBlocks(H,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(),H)),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(H,W){W=W||"Byte";var D=null;switch(W){case"Numeric":D=f(H);break;case"Alphanumeric":D=l(H);break;case"Byte":D=d(H);break;case"Kanji":D=p(H);break;default:throw"mode:"+W}M.push(D),U=null},F.isDark=function(H,W){if(H<0||I<=H||W<0||I<=W)throw H+","+W;return R[H][W]},F.getModuleCount=function(){return I},F.make=function(){if(_<1){for(var H=1;H<40;H++){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(),H)),X.write(D)}for(var J=0,V=0;V<W.length;V++)J+=W[V].dataCount;if(D.getLengthInBits()<=J*8)break}_=H}it(!1,q())},F.createTableTag=function(H,W){H=H||2,W=typeof W>"u"?H*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: "+H+"px;",D+=" height: "+H+"px;",D+=" background-color: ",D+=F.isDark(V,X)?"#000000":"#ffffff",D+=";",D+='"/>';D+="</tr>"}return D+="</tbody>",D+="</table>",D},F.createSvgTag=function(H,W,D,V){var X={};typeof arguments[0]=="object"&&(X=arguments[0],H=X.cellSize,W=X.margin,D=X.alt,V=X.title),H=H||2,W=typeof W>"u"?H*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()*H+W*2,dt,ft,Ct,re,pt="",Qe;for(Qe="l"+H+",0 0,"+H+" -"+H+",0 0,-"+H+"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*H+W,dt=0;dt<F.getModuleCount();dt+=1)F.isDark(Ct,dt)&&(ft=dt*H+W,pt+="M"+ft+","+re+Qe);return pt+='" stroke="transparent" fill="black"/>',pt+="</svg>",pt},F.createDataURL=function(H,W){H=H||2,W=typeof W>"u"?H*4:W;var D=F.getModuleCount()*H+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)/H),Ct=Math.floor((dt-V)/H);return F.isDark(Ct,ft)?0:1}else return 1})},F.createImgTag=function(H,W,D){H=H||2,W=typeof W>"u"?H*4:W;var V=F.getModuleCount()*H+W*2,X="";return X+="<img",X+=' src="',X+=F.createDataURL(H,W),X+='"',X+=' width="',X+=V,X+='"',X+=' height="',X+=V,X+='"',D&&(X+=' alt="',X+=xe(D),X+='"'),X+="/>",X};var xe=function(H){for(var W="",D=0;D<H.length;D+=1){var V=H.charAt(D);switch(V){case"<":W+="<";break;case">":W+=">";break;case"&":W+="&";break;case'"':W+=""";break;default:W+=V;break}}return W},vn=function(H){var W=1;H=typeof H>"u"?W*2:H;var D=F.getModuleCount()*W+H*2,V=H,X=D-H,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+=H<1&&J+1>=X?Qe[re]:pt[re];tn+=`
|
|
2
|
+
`}return D%2&&H>0?tn.substring(0,tn.length-D-1)+Array(D+1).join("\u2580"):tn.substring(0,tn.length-1)};return F.createASCII=function(H,W){if(H=H||1,H<2)return vn(W);H-=1,W=typeof W>"u"?H*2:W;var D=F.getModuleCount()*H+W*2,V=W,X=D-W,J,dt,ft,Ct,re=Array(H+1).join("\u2588\u2588"),pt=Array(H+1).join(" "),Qe="",tn="";for(J=0;J<D;J+=1){for(ft=Math.floor((J-V)/H),tn="",dt=0;dt<D;dt+=1)Ct=1,V<=dt&&dt<X&&V<=J&&J<X&&F.isDark(ft,Math.floor((dt-V)/H))&&(Ct=0),tn+=Ct?re:pt;for(ft=0;ft<H;ft+=1)Qe+=tn+`
|
|
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 _=y(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 ce=Math.abs(100*It/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 $=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},l=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},d=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)},$},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 $=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},_},y=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=m(),It=R(tt);It.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:(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=m();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(){wb.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 xb=="object"&&(Ib.exports=n())})(function(){return wb})});var d4={};Iu(d4,{ACCESS_ERROR_STATUS:()=>eb,ACCESS_PROTOCOL:()=>hu,ACCESS_VERSION:()=>Qm,AccessError:()=>kt,BRC29_PROTOCOL:()=>il,BWALLETX_RDNS:()=>Zo,GET_URL:()=>Zd,LOGIN_PROTOCOL:()=>Wd,LOGO_URL:()=>nl,PROTOCOL_MEDIA:()=>Vd,PaymentError:()=>he,RDNS_EXTENSION:()=>Rs,RDNS_MOBILE:()=>Ud,SIGNIN_CSS:()=>tl,SIGNIN_TAG:()=>Yd,WALLET_THEME_META:()=>yu,WEB_WALLET_URL:()=>na,accessErrorMessage:()=>rb,amountInSats:()=>al,brc100Option:()=>_s,buildAuthorizeUrl:()=>el,buyToken:()=>pb,canonicalJson:()=>ea,clearPairing:()=>Jm,connectBwalletX:()=>ta,declareWalletTheme:()=>Tb,defineBwalletxSignin:()=>bu,discoverBwalletX:()=>Dr,discoverWallets:()=>yb,findBwalletX:()=>Fm,handcashAdapter:()=>bb,inOrder:()=>Jo,isIdentityKeyHex:()=>rl,isPaymail:()=>sl,isTouchDevice:()=>ll,markSvg:()=>Qd,pairBwalletX:()=>Ns,pairingModal:()=>Eb,pairingOption:()=>fl,pay:()=>ul,pickWallet:()=>kb,protocolMediaUrl:()=>nb,proveHoldings:()=>Xd,qrSvg:()=>dl,renderButton:()=>cb,requestAccess:()=>gu,resolvePaymailP2P:()=>cl,restorePairing:()=>Bs,signInWithBwalletX:()=>lu,signinText:()=>Jd,throwIfAccessError:()=>zd,tip:()=>hb,toAccessError:()=>pu});var vu=globalThis.Buffer,Mb=vu!=null&&typeof vu.from=="function",Ds=new Int8Array(256).fill(-1);for(let n=0;n<10;n++)Ds[48+n]=n;for(let n=0;n<6;n++)Ds[65+n]=10+n,Ds[97+n]=10+n;var Hs,$s,sa,oa,fi,aa,qs,Y,rt,St,P,yl,wl,xl,Il,Sl,vl,Au,_e,An,st,Al,Ls,Us,El,kl,zi,Tl,Ol,Pl,Lt,ue,Ms,ra,Ki,Eu,Rl,ku,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);b(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,Al).call(this,t,o);return}if(Array.isArray(t)){a(this,P,Ls).call(this,t,o);return}if(typeof t=="string"){a(this,P,wl).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 w(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;w(this,Y)===0n?N(this,rt,0):N(this,rt,e)}get words(){if(!Number.isSafeInteger(w(this,St))||w(this,St)<1||w(this,St)>w(Z,qs))throw new Error("BigNumber word length exceeds the supported limit");let t=w(this,P,yl);if(w(this,St)<=t.length)return t;let e=Array.from({length:w(this,St)}).fill(0);for(let i=0;i<t.length;i++)e[i]=t[i];return e}set words(t){let e=w(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<<w(Z,Hs)|BigInt(o&Number(w(Z,$s)))}N(this,Y,i),N(this,rt,e),N(this,St,r),this.normSign()}get length(){return Math.max(1,w(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,w(this,Y)),N(t,rt,w(this,rt)),N(t,St,w(this,St)),t.red=this.red}static move(t,e){N(t,Y,w(e,Y)),N(t,rt,w(e,rt)),N(t,St,w(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<=w(Z,qs),"Expand size must be a non-negative safe integer within the supported word limit"),N(this,St,Math.max(w(this,St),t,1)),this}strip(){return a(this,P,An).call(this),this.normSign()}normSign(){return w(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,El).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,kl).call(this,t,e)}toNumber(){let t=a(this,P,Lt).call(this);if(t>w(Z,sa)||t<w(Z,oa))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,Us).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 w(this,Y)===0n&&r>0?s:w(this,Y)===0n&&r===0?[]:(a(this,P,Pl).call(this,s,t==="le"),s)}bitLength(){return w(this,Y)===0n?0:w(this,Y).toString(2).length}static toBitArray(t){let e=t.bitLength();if(e===0)return[];let i=Array.from({length:e}),r=w(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(w(this,Y)===0n)return 0;let t=0,e=w(this,Y);for(;(e&1n)===0n&&e!==0n;)t++,e>>=1n;return t}byteLength(){return w(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);w(this,rt)===1&&w(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=w(this,Y);if(t>0&&(i>>e-1n&1n)!==0n&&w(this,rt)===0){let s=i-(1n<<e),o=new Z(0n);return a(r=o,P,ue).call(r,s),o}return this.clone()}isNeg(){return w(this,rt)===1&&w(this,Y)!==0n}neg(){return this.clone().ineg()}ineg(){return w(this,Y)!==0n&&N(this,rt,w(this,rt)===1?0:1),this}iuor(t){return a(this,P,Ms).call(this,t,(e,i)=>e|i)}iuand(t){return a(this,P,Ms).call(this,t,(e,i)=>e&i)}iuxor(t){return a(this,P,Ms).call(this,t,(e,i)=>e^i,!0)}ior(t){return a(this,P,ra).call(this,t,(e,i)=>e|i)}iand(t){return a(this,P,ra).call(this,t,(e,i)=>e&i)}ixor(t){return a(this,P,ra).call(this,t,(e,i)=>e^i,!0)}or(t){return a(this,P,st).call(this,w(this,rt)===0&&w(t,rt)===0),a(this,P,Ki).call(this,t,"iuor")}uor(t){return a(this,P,Ki).call(this,t,"iuor")}and(t){return a(this,P,st).call(this,w(this,rt)===0&&w(t,rt)===0),a(this,P,Ki).call(this,t,"iuand")}uand(t){return a(this,P,Ki).call(this,t,"iuand")}xor(t){return a(this,P,st).call(this,w(this,rt)===0&&w(t,rt)===0),a(this,P,Ki).call(this,t,"iuxor")}uxor(t){return a(this,P,Ki).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,~w(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(w(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,w(this,Y)|1n<<i):N(this,Y,w(this,Y)&~(1n<<i));let r=Math.floor(t/Z.wordSize)+1;return N(this,St,Math.max(w(this,St),r)),a(this,P,An).call(this),this.strip()}iadd(t){var e;return a(this,P,ue).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,ue).call(r,a(this,P,Lt).call(this)+a(i=t,P,Lt).call(i)),e}isub(t){var e;return a(this,P,ue).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,ue).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,w(this,Y)*w(t,Y)),N(e,rt,w(e,Y)===0n?0:w(this,rt)^w(t,rt)),N(e,St,this.length+t.length),e.red=null,e.normSign()}imul(t){return N(this,Y,w(this,Y)*w(t,Y)),N(this,rt,w(this,Y)===0n?0:w(this,rt)^w(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)<=w(Z,fi),"Assertion failed"),a(this,P,ue).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,w(this,Y)*w(this,Y)),N(t,rt,0),N(t,St,this.length*2),t.red=null,t}isqr(){return N(this,Y,w(this,Y)*w(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,w(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,zi,Eu).call(i,t,"Shift bits");return e===0n?this:(N(this,Y,w(this,Y)<<e),a(this,P,An).call(this),this.strip())}ishln(t){return a(this,P,st).call(this,w(this,rt)===0,"ishln requires positive number"),this.iushln(t)}iushrn(t,e,i){var s,o,c;let r=a(s=Z,zi,Eu).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=w(this,Y)&u;a(c=i,P,_e).call(c,f,0)}return N(this,Y,w(this,Y)>>r),a(this,P,An).call(this),this.strip()}ishrn(t,e,i){return a(this,P,st).call(this,w(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),(w(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,w(this,rt)===0,"imaskn works only with positive numbers");let e=BigInt(t),i=e===0n?0n:(1n<<e)-1n;N(this,Y,w(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(w(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)<=w(Z,fi),"num is too large"),a(this,P,ue).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)<=w(Z,fi),"Assertion failed"),a(this,P,ue).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,Rl).call(this,r,s,e,i);return{div:a(this,P,ku).call(this,o),mod:a(this,P,ku).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,l,d;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(l=p,P,ue).call(l,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(d=u,P,ue).call(d,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=w(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)<=w(Z,fi),"num is too large"),a(this,P,ue).call(this,a(this,P,Lt).call(this)/BigInt(t)),this}divn(t){return this.clone().idivn(t)}egcd(t){var d,p,m;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=w(t,Y),r=1n,s=0n,o=0n,c=1n;for(;i!==0n;){let g=e/i,y=i;i=e%i,e=y,y=s,s=r-g*s,r=y,y=c,c=o-g*c,o=y}let u=new Z(0n);a(d=u,P,ue).call(d,r);let f=new Z(0n);a(p=f,P,ue).call(p,o);let l=new Z(0n);return a(m=l,P,_e).call(m,e<0n?-e:e,0),{a:u,b:f,gcd:l}}gcd(t){var s,o,c;let e=w(this,Y),i=w(t,Y);if(e===0n){let u=new Z(0n);return a(s=u,P,ue).call(s,i),u.iabs()}if(i===0n){let u=new Z(0n);return a(o=u,P,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,P,_e).call(c,e,0),r}invm(t){a(this,P,st).call(this,!t.isZero()&&w(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 w(this,Y)%2n===0n}isOdd(){return w(this,Y)%2n===1n}andln(t){return a(this,P,st).call(this,t>=0),Number(w(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,ue).call(this,a(this,P,Lt).call(this)+e),this}isZero(){return w(this,Y)===0n}cmpn(t){a(this,P,st).call(this,Math.abs(t)<=w(Z,fi),"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 w(this,Y)<w(t,Y)?-1:w(this,Y)>w(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,w(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,Us).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(Mb)s=vu.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(w(this,Y)===0n)return w(this,rt)===1?[128]:[];let e=a(this,P,Us).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=Ds[e.codePointAt(o)],f=Ds[e.codePointAt(o+1)];r[c++]=(u&15)<<4|f&15}let s;return w(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,w(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,w(this,Y)*w(t,Y)),N(e,rt,w(e,Y)===0n?0:w(this,rt)^w(t,rt)),N(e,St,this.length+t.length),e.red=null,e.normSign(),e}};Hs=new WeakMap,$s=new WeakMap,sa=new WeakMap,oa=new WeakMap,fi=new WeakMap,aa=new WeakMap,qs=new WeakMap,Y=new WeakMap,rt=new WeakMap,St=new WeakMap,P=new WeakSet,yl=function(){if(w(this,Y)===0n)return[0];let t=[],e=w(this,Y);for(;e>0n;)t.push(Number(e&w(Z,$s))),e>>=w(Z,Hs);return t.length>0?t:[0]},wl=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,xl).call(this,c,o,i):a(this,P,Il).call(this,c,e,o,i)},xl=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,Ls).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()}},Il=function(t,e,i,r){try{if(a(this,P,vl).call(this,t,e),N(this,rt,i),this.normSign(),r==="le"){let s=w(this,rt);a(this,P,Ls).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}},Sl=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},vl=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,Au).call(this,f,e))),o+=u}for(;o<c;){let f=t.substring(o,o+r),l=BigInt(a(this,P,Au).call(this,f,e));N(this,Y,w(this,Y)*s+l),o+=r}a(this,P,An).call(this)},Au=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(w(this,Y)===0n)N(this,St,1),N(this,rt,0);else{let t=w(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)},Al=function(t,e="be"){if(a(this,P,st).call(this,BigInt(Math.abs(t))<=w(Z,aa),"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=w(this,rt),r=this.toArray("be");a(this,P,Ls).call(this,r,"le"),N(this,rt,i),this.normSign()}return this},Ls=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},Us=function(){return w(this,Y)===0n?"0":w(this,Y).toString(16)},El=function(t){let e=a(this,P,Us).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},kl=function(t,e){var c;if(w(this,Y)===0n)return a(c=Z,zi,Tl).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=w(this,Y);for(;o>0n;){let u=o%r;o/=r;let f=a(this,P,Sl).call(this,u,t);s=(o>0n?a(this,P,Ol).call(this,f,i):f)+s}if(e>0)for(;s.length<e;)s="0"+s;return(w(this,rt)===1?"-":"")+s},zi=new WeakSet,Tl=function(t){let e="0";if(t>1)for(;e.length<t;)e="0"+e;return e},Ol=function(t,e){let i=e-t.length;return i<=0?t:i<Z.zeros.length?Z.zeros[i]+t:"0".repeat(i)+t},Pl=function(t,e){let i=w(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 w(this,rt)===1?-w(this,Y):w(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,P,An).call(this),this.normSign()},Ms=function(t,e,i=!1){let r=e(w(this,Y),w(t,Y)),s=w(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(w(this,St),s)),this.strip()},ra=function(t,e,i=!1){return a(this,P,st).call(this,w(this,rt)===0&&w(t,rt)===0),a(this,P,Ms).call(this,t,e,i)},Ki=function(t,e){return this.length>=t.length?this.clone()[e](t):t.clone()[e](this)},Eu=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},Rl=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},ku=function(t){var i;if(t===null)return null;let e=new Z(0n);return a(i=e,P,ue).call(i,t),e},G(Z,zi),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,Hs,26n),G(Z,$s,(1n<<26n)-1n),G(Z,sa,BigInt(Number.MAX_SAFE_INTEGER)),G(Z,oa,BigInt(Number.MIN_SAFE_INTEGER)),G(Z,fi,67108863),G(Z,aa,(1n<<53n)-1n),G(Z,qs,1048576);var T=Z;var Fs=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 Ws=class extends Fs{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 y=0;y<u;++y)g[y]=c[y];e.words=g,t.words=[0];return}let f=r[9];c[u++]=f&4194303;let l=Array.from({length:u},()=>0);for(let g=0;g<u;++g)l[g]=c[g];e.words=l;let d=Array.from({length:Math.max(1,s-9)},()=>0),p=0;for(let g=10;g<s;g++){let y=Math.trunc(r[g]);p<d.length&&(d[p++]=(y&4194303)<<4|f>>>22),f=y}f>>>=22,p<d.length?d[p++]=f:f!==0&&d.length>0;let m=Array.from({length:p},()=>0);for(let g=0;g<p;++g)m[g]=d[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 Xi=class{constructor(t){b(this,"prime");b(this,"m");if(t==="k256"){let e=new Ws;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 l=this.pow(f,i),d=this.pow(t,i.addn(1).iushrn(1)),p=this.pow(t,i),m=r;for(;p.cmp(s)!==0;){let g=p,y=0;for(;g.cmp(s)!==0;)g=g.redSqr(),y++;this.assert(y<m);let S=this.pow(l,new T(1).iushln(m-y-1));d=d.redMul(S),l=S.redSqr(),p=p.redMul(l),m=y}return d}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 Vs=class extends Xi{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 wi={};Iu(wi,{Reader:()=>Qs,ReaderUint8Array:()=>bt,Writer:()=>fe,WriterUint8Array:()=>ht,base64ToArray:()=>eh,constantTimeEquals:()=>H1,encode:()=>Ta,fromBase58:()=>io,fromBase58Check:()=>oo,hexToUint8Array:()=>no,minimallyEncode:()=>Oa,toArray:()=>at,toBase58:()=>ro,toBase58Check:()=>so,toBase64:()=>ve,toHex:()=>nt,toSafeString:()=>B1,toUTF8:()=>nh,toUTF8Strict:()=>Rt,toUint8Array:()=>et,verifyNotNull:()=>ir,zero2:()=>_1});var Db=new TextEncoder;function Ie(n){return Db.encode(n)}function Fe(n){return Ie(n).byteLength}function ji(n){for(let t of n){let e=t.codePointAt(0);if(e<=31||e>=127&&e<=159)return!0}return!1}var Ea={};Iu(Ea,{RIPEMD160:()=>Xs,SHA1:()=>tr,SHA1HMAC:()=>Bu,SHA256:()=>Ru,SHA256HMAC:()=>qr,SHA512:()=>Nu,SHA512HMAC:()=>ha,hash160:()=>Ys,hash256:()=>zt,htonl:()=>Hl,pbkdf2:()=>k1,realHtonl:()=>O1,ripemd160:()=>Du,sha1:()=>Hu,sha256:()=>Te,sha256hmac:()=>Zs,sha512:()=>a1,sha512hmac:()=>$u,swapBytes32:()=>qu,toArray:()=>wa});var Hb=/^[0-9a-fA-F]*$/;function Ks(n){if(typeof n!="string")throw new TypeError("Invalid hex string");if(n.length!==0&&!Hb.test(n))throw new Error("Invalid hex string")}function Nl(n){if(Ks(n),n.length===0)return"";let t=n.toLowerCase();return t.length%2!==0&&(t="0"+t),t}var Tu=(n,t="Hash assertion failed")=>{if(!n)throw new Error(t)},la=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=wa(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=Xb(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()),Tu(this.pending===null),this._digest()}digestHex(){return this.update(this._pad()),Tu(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 l=o-1;l>=0;l--)f[l]=Number(u&0xffn),u>>=8n;for(let l=0;l<o;l++)r[s++]=f[l]}else for(let f=0;f<o;f++)r[s++]=Number(u&0xffn),u>>=8n;return r}};function $b(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 qb(n){let t=[],e=0;for(;e<n.length;)e=$b(n,e,t)+1;return t}function Fb(n){Ks(n);let t=Nl(n),e=[];for(let i=0;i<t.length;i+=2)e.push(Number.parseInt(t[i]+t[i+1],16));return e}function Wb(n){let t=[];for(let e=0;e<n.length;e++)t[e]=Math.trunc(n[e]);return t}function wa(n,t){return Array.isArray(n)?n.slice():n?typeof n=="string"?t==="hex"?Fb(n):qb(n):Wb(n):[]}function Hl(n){return qu(n)}function $l(n,t){let e="";for(let i of n)t==="little"&&(i=Hl(i)),e+=Vb(i.toString(16));return e}function Vb(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 Ou=typeof globalThis>"u"?void 0:globalThis.Buffer,Kb=Ou!=null&&typeof Ou.from=="function",Bl="0123456789abcdef",Pu=Array.from({length:256});for(let n=0;n<Pu.length;n++)Pu[n]=Bl[n>>4&15]+Bl[n&15];function zb(n){if(Kb)return Ou.from(n).toString("hex");let t=Array.from({length:n.length});for(let e=0;e<n.length;e++)t[e]=Pu[n[e]];return t.join("")}var _u=(()=>{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(wa(n,t))}function Cu(n){return typeof n=="string"?en(n,"hex"):en(n)}function xa(n,t,e){n!=null?n.update(e):t?.update(e)}function Ia(n,t){return n!=null?Array.from(n.digest()):t!=null?Array.from(t.digest()):[]}function Sa(n,t){return n!=null?n.digest("hex"):t!=null?zb(t.digest()):""}function Lu(n){let t=_u?.createHash;if(typeof t=="function")try{return t(n)}catch{return}}function Uu(n,t){let e=_u?.createHmac;if(typeof e=="function")try{return e(n,t)}catch{return}}function Mu(n,t,e){let i=Lu(n);if(i!=null)return i.update(en(t,e)),i.digest()}function ql(n,t,e,i){let r=Uu(n,Cu(t));if(r!=null)return r.update(en(e,i)),r.digest()}function Xb(n,t,e,i){let r=e-t;Tu(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 Fl(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 Gi(n,t){return n<<t|n>>>32-t}function Yt(n,t){return n+t>>>0}function zs(n,t,e){return n+t+e>>>0}function _l(n,t,e,i){return n+t+e+i>>>0}function Wl(n,t,e,i,r){return n+t+e+i+r>>>0}function jb(n,t,e,i){return n===0?Vl(t,e,i):n===1||n===3?Gb(t,e,i):n===2?Kl(t,e,i):0}function Vl(n,t,e){return n&t^~n&e}function Kl(n,t,e){return n&t^n&e^t&e}function Gb(n,t,e){return n^t^e}function Yb(n){return En(n,2)^En(n,13)^En(n,22)}function Zb(n){return En(n,6)^En(n,11)^En(n,25)}function Jb(n){return En(n,7)^En(n,18)^n>>>3}function Qb(n){return En(n,17)^En(n,19)^n>>>10}var t1=[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],e1=[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],n1=[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],i1=[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 Cl(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 r1(n){return n<=15?0:n<=31?1518500249:n<=47?1859775393:n<=63?2400959708:2840853838}function s1(n){return n<=15?1352829926:n<=31?1548603684:n<=47?1836072691:n<=63?2053994217:0}var Xs=class extends la{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,l=s,d=o,p=c,m=u,g;for(let y=0;y<80;y++)g=Yt(Gi(_l(r,Cl(y,s,o,c),e[t1[y]+i],r1(y)),n1[y]),u),r=u,u=c,c=Gi(o,10),o=s,s=g,g=Yt(Gi(_l(f,Cl(79-y,l,d,p),e[e1[y]+i],s1(y)),i1[y]),m),f=m,m=p,p=Gi(d,10),d=l,l=g;g=zs(this.h[1],o,p),this.h[1]=zs(this.h[2],c,m),this.h[2]=zs(this.h[3],u,f),this.h[3]=zs(this.h[4],r,l),this.h[4]=zs(this.h[0],s,d),this.h[0]=g}_digest(){return Fl(this.h,"little")}_digestHex(){return $l(this.h,"little")}},Yi,gi,Ru=class{constructor(){G(this,Yi);G(this,gi);N(this,gi,Lu("sha256")),w(this,gi)==null&&N(this,Yi,new js)}update(t,e){return xa(w(this,gi),w(this,Yi),en(t,e)),this}digest(){return Ia(w(this,gi),w(this,Yi))}digestHex(){return Sa(w(this,gi),w(this,Yi))}};Yi=new WeakMap,gi=new WeakMap;var tr=class extends la{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]=Gi(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],l=this.h[4];for(s=0;s<r.length;s++){let d=Math.trunc(s/20),p=Wl(Gi(o,5),jb(d,c,u,f),l,r[s],this.k[d]);l=f,f=u,u=Gi(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],l)}_digest(){return Fl(this.h,"big")}_digestHex(){return $l(this.h,"big")}},Zi,mi,Nu=class{constructor(){G(this,Zi);G(this,mi);N(this,mi,Lu("sha512")),w(this,mi)==null&&N(this,Zi,new Gs)}update(t,e){return xa(w(this,mi),w(this,Zi),en(t,e)),this}digest(){return Ia(w(this,mi),w(this,Zi))}digestHex(){return Sa(w(this,mi),w(this,Zi))}};Zi=new WeakMap,mi=new WeakMap;var Ji,bi,qr=class{constructor(t){G(this,Ji);G(this,bi);b(this,"blockSize",64);b(this,"outSize",32);let e=Cu(t);N(this,bi,Uu("sha256",e)),w(this,bi)==null&&N(this,Ji,new Fr(I1,e))}update(t,e){return xa(w(this,bi),w(this,Ji),en(t,e)),this}digest(){return Ia(w(this,bi),w(this,Ji))}digestHex(){return Sa(w(this,bi),w(this,Ji))}};Ji=new WeakMap,bi=new WeakMap;var Bu=class{constructor(t){b(this,"inner");b(this,"outer");b(this,"blockSize",64);t=wa(t,"hex"),t.length>this.blockSize&&(t=new tr().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 tr().update(t),e=0;e<t.length;e++)t[e]^=106;this.outer=new tr().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()}},Qi,yi,ha=class{constructor(t){G(this,Qi);G(this,yi);b(this,"blockSize",128);b(this,"outSize",32);let e=Cu(t);N(this,yi,Uu("sha512",e)),w(this,yi)==null&&N(this,Qi,new Fr(Yl,e))}update(t,e){return xa(w(this,yi),w(this,Qi),en(t,e)),this}digest(){return Ia(w(this,yi),w(this,Qi))}digestHex(){return Sa(w(this,yi),w(this,Qi))}};Qi=new WeakMap,yi=new WeakMap;function pa(n,t){let e=Mu("sha256",n,t);return e??new js().update(en(n,t)).digest()}function o1(n,t){let e=Mu("sha512",n,t);return e??new Gs().update(en(n,t)).digest()}function zl(n,t){return Mu("ripemd160",n,t)}var Du=(n,t)=>{let e=zl(n,t);return e!=null?Array.from(e):new Xs().update(n,t).digest()},Hu=(n,t)=>new tr().update(n,t).digest(),Te=(n,t)=>Array.from(pa(n,t)),a1=(n,t)=>Array.from(o1(n,t)),zt=(n,t)=>Array.from(pa(pa(n,t))),Ys=(n,t)=>{let e=pa(n,t),i=zl(e);return i!=null?Array.from(i):new Xs().update(e).digest()},Zs=(n,t,e)=>{let i=ql("sha256",n,t,e);return i!=null?Array.from(i):new qr(n).update(t,e).digest()},$u=(n,t,e)=>{let i=ql("sha512",n,t,e);return i!=null?Array.from(i):new ha(n).update(t,e).digest()};function c1(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function ga(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`positive integer expected, got ${n}`)}function va(n,...t){if(!c1(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 Xl(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("Hash should be wrapped by utils.createHasher");ga(n.outputLen),ga(n.blockLen)}function ma(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 u1(n,t){va(n);let e=t.outputLen;if(n.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}function er(...n){for(let t of n)t.fill(0)}function da(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Aa(n){return typeof n=="string"&&(n=f1(n)),va(n),n}function f1(n){if(typeof n!="string")throw new Error("string expected");return Ie(n)}var Ll=Aa,ba=class{};function jl(n){let t=i=>n().update(Aa(i)).digest(),e=n();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>n(),t}var ca=BigInt(2**32-1),Ul=BigInt(32);function d1(n,t=!1){return t?{h:Number(n&ca),l:Number(n>>Ul&ca)}:{h:Number(n>>Ul&ca)|0,l:Number(n&ca)|0}}function l1(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}=d1(n[s],t);i[s]=o,r[s]=c}return[i,r]}var Ml=(n,t,e)=>n>>>e,Dl=(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,ua=(n,t,e)=>n<<64-e|t>>>e-32,fa=(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 h1=(n,t,e)=>(n>>>0)+(t>>>0)+(e>>>0),p1=(n,t,e,i)=>Math.trunc(t+e+i+Math.trunc(n/2**32)),g1=(n,t,e,i)=>(n>>>0)+(t>>>0)+(e>>>0)+(i>>>0),m1=(n,t,e,i,r)=>Math.trunc(t+e+i+r+Math.trunc(n/2**32)),b1=(n,t,e,i,r)=>(n>>>0)+(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0),y1=(n,t,e,i,r,s)=>t+e+i+r+s+(n/2**32|0)|0,ya=class extends ba{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=da(this.buffer)}update(e){ma(this),e=Aa(e),va(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=da(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){ma(this),u1(e,this),this.finished=!0;let{buffer:i,view:r,blockLen:s,isLE:o}=this,{pos:c}=this;i[c++]=128,er(this.buffer.subarray(c)),this.padOffset>s-c&&(this.process(r,0),c=0);for(let p=c;p<s;p++)i[p]=0;w1(r,s-8,BigInt(this.length*8),o),this.process(r,0);let u=da(e),f=this.outputLen;if(f%4!==0)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=f/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<l;p++)u.setUint32(4*p,d[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 w1(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]),x1=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),js=class extends ya{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],y=Jb(m),S=Qb(g);li[p]=Yt(Yt(y,li[p-7]),Yt(S,li[p-16]))}let{A:r,B:s,C:o,D:c,E:u,F:f,G:l,H:d}=this;for(let p=0;p<64;p++){let m=Wl(d,Zb(u),Vl(u,f,l),x1[p],li[p]),g=Yt(Yb(r),Kl(r,s,o));d=l,l=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,l),this.H=Yt(this.H,d)}roundClean(){er(li)}destroy(){er(this.buffer),this.set(0,0,0,0,0,0,0,0)}},I1=jl(()=>new js),Se=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Gl=l1(["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)),S1=Gl[0],v1=Gl[1],hi=new Uint32Array(80),pi=new Uint32Array(80),Gs=class extends ya{constructor(e=64){super(128,e,16,!1);b(this,"Ah",Se[0]|0);b(this,"Al",Se[1]|0);b(this,"Bh",Se[2]|0);b(this,"Bl",Se[3]|0);b(this,"Ch",Se[4]|0);b(this,"Cl",Se[5]|0);b(this,"Dh",Se[6]|0);b(this,"Dl",Se[7]|0);b(this,"Eh",Se[8]|0);b(this,"El",Se[9]|0);b(this,"Fh",Se[10]|0);b(this,"Fl",Se[11]|0);b(this,"Gh",Se[12]|0);b(this,"Gl",Se[13]|0);b(this,"Hh",Se[14]|0);b(this,"Hl",Se[15]|0)}get(){let{Ah:e,Al:i,Bh:r,Bl:s,Ch:o,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:p,Fl:m,Gh:g,Gl:y,Hh:S,Hl:C}=this;return[e,i,r,s,o,c,u,f,l,d,p,m,g,y,S,C]}set(...[e,i,r,s,o,c,u,f,l,d,p,m,g,y,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=l|0,this.El=d|0,this.Fh=p|0,this.Fl=m|0,this.Gh=g|0,this.Gl=y|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,$=Hr(B,_,1)^Hr(B,_,8)^Ml(B,_,7),R=$r(B,_,1)^$r(B,_,8)^Dl(B,_,7),I=hi[k-2]|0,U=pi[k-2]|0,M=Hr(I,U,19)^ua(I,U,61)^Ml(I,U,6),F=$r(I,U,19)^fa(I,U,61)^Dl(I,U,6),it=g1(R,F,pi[k-7],pi[k-16]),ot=m1(it,$,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:l,Dl:d,Eh:p,El:m,Fh:g,Fl:y,Gh:S,Gl:C,Hh:E,Hl:A}=this;for(let k=0;k<80;k++){let B=Hr(p,m,14)^Hr(p,m,18)^ua(p,m,41),_=$r(p,m,14)^$r(p,m,18)^fa(p,m,41),$=p&g^~p&S,R=m&y^~m&C,I=b1(A,_,R,v1[k],pi[k]),U=y1(I,E,B,$,S1[k],hi[k]),M=I|0,F=Hr(r,s,28)^ua(r,s,34)^ua(r,s,39),it=$r(r,s,28)^fa(r,s,34)^fa(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=y|0,g=p|0,y=m|0,{h:p,l:m}=Wn(l|0,d|0,U|0,M|0),l=u|0,d=f|0,u=o|0,f=c|0,o=r|0,c=s|0;let z=h1(it,q,M);r=p1(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:l,l:d}=Wn(l,d,this.Dh,this.Dl),{h:p,l:m}=Wn(p,m,this.Eh,this.El),{h:g,l:y}=Wn(g,y,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,l,d,p,m,g,y,S,C,E,A)}roundClean(){er(hi,pi)}destroy(){er(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Yl=jl(()=>new Gs),Fr=class extends ba{constructor(e,i){super();b(this,"oHash");b(this,"iHash");b(this,"blockLen");b(this,"outputLen");b(this,"finished",!1);b(this,"destroyed",!1);Xl(e);let r=Aa(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),er(o)}update(e){return ma(this),this.iHash.update(e),this}digestInto(e){ma(this),va(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 A1(n,t,e,i){Xl(n);let{c:r,dkLen:s=32}={...i};if(ga(r),ga(s),r<1)throw new Error("iterations (c) should be >= 1");let o=Ll(t),c=Ll(e),u=new Uint8Array(s),f=Zl.create(n,o),l=f._cloneInto().update(c),d,p=new Uint8Array(4),m=da(p),g=new Uint8Array(f.outputLen);for(let y=1,S=0;S<s;y++,S+=f.outputLen){let C=u.subarray(S,S+f.outputLen);m.setInt32(0,y,!1),d=l._cloneInto(d),d.update(p).digestInto(g),C.set(g.subarray(0,C.length));for(let E=1;E<r;E++){f._cloneInto(d).update(g).digestInto(g);for(let A=0;A<C.length;A++)C[A]^=g[A]}}return f.destroy(),l.destroy(),d?.destroy(),er(g),u}var Zl=(n,t,e)=>new Fr(n,t).update(e).digest();Zl.create=(n,t)=>new Fr(n,t);function E1(n,t,e,i){return A1(Yl,n,t,{c:e,dkLen:i})}function k1(n,t,e,i,r="sha512"){if(r!=="sha512")throw new Error("Only sha512 is supported in this PBKDF2 implementation");let s=_u?.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=E1(o,c,e,i);return Array.from(u)}function qu(n){return(n>>>24|n>>>8&65280|n<<8&16711680|(n&255)<<24)>>>0}var T1=(()=>{let n=new ArrayBuffer(4),t=new Uint32Array(n),e=new Uint8Array(n);return t[0]=16909060,e[0]===4})();function O1(n){return T1?qu(n):n>>>0}var P1=new T(4294967295),R1=new T(2).pow(new T(64)).sub(new T(1)),N1=new T(Number.MAX_SAFE_INTEGER);function Js(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(P1))throw new Error("non-canonical varInt");if(t&&i.eq(R1))return-1;if(i.gt(N1))throw new Error("number too large to retain precision - use readVarIntBn");return i.toNumber()}var Wt,Tt,nr,ln,Vn,ht=class{constructor(t,e=256){G(this,ln);G(this,Wt);G(this,Tt);G(this,nr);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,nr,e),t!=null)for(let i of t)this.write(i)}getLength(){return w(this,Tt)}toUint8Array(){return w(this,Wt).slice(0,w(this,Tt))}toArray(){return Array.from(this.toUint8Array())}toUint8ArrayZeroCopy(){return w(this,Wt).subarray(0,w(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),w(this,Wt).set(e,w(this,Tt)),N(this,Tt,w(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--)w(this,Wt)[w(this,Tt)]=e[i],N(this,Tt,w(this,Tt)+1);return this}writeUInt8(t){return a(this,ln,Vn).call(this,1),w(this,Wt)[w(this,Tt)]=t&255,N(this,Tt,w(this,Tt)+1),this}writeInt8(t){return this.writeUInt8(t),this}writeUInt16LE(t){return a(this,ln,Vn).call(this,2),w(this,Wt)[w(this,Tt)]=t&255,w(this,Wt)[w(this,Tt)+1]=t>>8&255,N(this,Tt,w(this,Tt)+2),this}writeUInt16BE(t){return a(this,ln,Vn).call(this,2),w(this,Wt)[w(this,Tt)]=t>>8&255,w(this,Wt)[w(this,Tt)+1]=t&255,N(this,Tt,w(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),w(this,Wt)[w(this,Tt)]=t&255,w(this,Wt)[w(this,Tt)+1]=t>>8&255,w(this,Wt)[w(this,Tt)+2]=t>>16&255,w(this,Wt)[w(this,Tt)+3]=t>>24&255,N(this,Tt,w(this,Tt)+4),this}writeUInt32BE(t){return a(this,ln,Vn).call(this,4),w(this,Wt)[w(this,Tt)]=t>>24&255,w(this,Wt)[w(this,Tt)+1]=t>>16&255,w(this,Wt)[w(this,Tt)+2]=t>>8&255,w(this,Wt)[w(this,Tt)+3]=t&255,N(this,Tt,w(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,nr=new WeakMap,ln=new WeakSet,Vn=function(t){if(w(this,Tt)+t>w(this,nr)){let e=w(this,nr)*2;for(;w(this,Tt)+t>e;)e*=2;let i=new Uint8Array(e);i.set(w(this,Wt)),N(this,Wt,i),N(this,nr,e)}};var pn,We,hn,Fu=class Fu{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>w(this,pn))throw new RangeError("ReaderUint8Array position exceeds available data");this.pos=e}static makeReader(t,e=0){if(t instanceof Uint8Array)return new Fu(t,e);if(Array.isArray(t))return new Qs(t,e);throw new Error("ReaderUint8Array.makeReader: bin must be Uint8Array or number[]")}eof(){return this.pos>=w(this,pn)}read(t=w(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=w(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 w(this,pn)-this.pos}readReverse(t=w(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 Js(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>w(this,pn))throw new RangeError("ReaderUint8Array read exceeds available data")};var bt=Fu;var ka=globalThis.Buffer,Ql=ka!=null&&typeof ka.from=="function",B1=(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}},_1=n=>n.length%2===1?"0"+n:n,Jl="0123456789abcdef",th=Array.from({length:256},()=>"");for(let n=0;n<256;n++)th[n]=Jl[n>>4&15]+Jl[n&15];var nt=n=>Ql?ka.from(n).toString("hex"):n.length===0?"":Array.from(n,t=>th[t&255]).join(""),et=(n,t)=>n instanceof Uint8Array?n:typeof n=="string"&&t==="hex"?no(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 C1(n);case"base64":return eh(n);default:return M1(n)}},eo=new Int8Array(256).fill(-1);for(let n=0;n<10;n++)eo[48+n]=n;for(let n=0;n<6;n++)eo[65+n]=10+n,eo[97+n]=10+n;var C1=n=>Array.from(no(n)),no=n=>{Ks(n);let t=n.length%2===0?n:"0"+n;if(Ql){let r=ka.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=eo[t.codePointAt(r)],o=eo[t.codePointAt(r+1)];e[i++]=s<<4|o}return e},L1=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)},U1=(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 eh(n){let t=L1(n),e=[],i=0,r=0;for(let s=0;s<t.length;s++){let o=t.codePointAt(s),c=U1(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 M1(n){return Array.from(Ie(n))}var nh=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)),Ta=(n,t)=>{switch(t){case"hex":return nt(n);case"utf8":return nh(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,l=o&63;e+=t.charAt(c)+t.charAt(u),e+=i+1<n.length?t.charAt(f):"=",e+=i+2<n.length?t.charAt(l):"="}return e}var to="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",io=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=>to.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))])]},ro=n=>{let t=Array.from({length:256},()=>-1);for(let i=0;i<to.length;++i)t[to.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]=to.codePointAt(u),r=c}for(;r!==0;){let s=Math.trunc(r/58),o=r-s*58;e.push(to.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)},so=(n,t=[0])=>{let e=zt([...t,...n]);return e=[...t,...n,...e.slice(0,4)],ro(e)},oo=(n,t,e=1)=>{let i=io(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(ih)),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}},Qs=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(D1)&&(e=e.sub(ih)),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 Js(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)}}},Oa=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[]},D1=new T(2).pow(new T(63)),ih=new T(2).pow(new T(64));function ir(n,t="Expected a valid value, but got undefined or null."){if(n==null)throw new Error(t);return n}function H1(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 Wu;function rh(n,t){let e=n.andln(3)+t&3;return e===3?-1:e}function sh(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 oh(n,t){return 2*n===t+1?1-n:n}var Pa,ah,Vu=class Vu{constructor(){G(this,Pa);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(Wu===void 0)Wu=this;else return Wu;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 Xi(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=rh(t,r),c=rh(e,s),u=sh(t,r,o,c);i[0].push(u);let f=sh(e,s,c,o);i[1].push(f),r=oh(r,u),s=oh(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,Pa,ah).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]:(Vu.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 Vs(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,l,d,p,m,g,y=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(d===void 0&&C.cmp(e)<0)f=y.neg(),l=s,d=C.neg(),p=E;else if(d!==void 0&&++S===2)break;y=C,r=i,i=C,c=s,s=E,u=o,o=_}if(f===void 0||l===void 0||d===void 0||p===void 0)throw new Error("Failed to compute Endo Basis values");m=C.neg(),g=E;let A=d.sqr().add(p.sqr());return m.sqr().add(g.sqr()).cmp(A)>=0&&(m=f,g=l),d.negative!==0&&(d=d.neg(),p=p.neg()),m.negative!==0&&(m=m.neg(),g=g.neg()),[{a:d,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),l=o.mul(r.b),d=t.sub(c).sub(u),p=f.add(l).neg();return{k1:d,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}};Pa=new WeakSet,ah=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=Vu;var rr=class{constructor(t){b(this,"curve");b(this,"type");b(this,"precomputed");this.curve=new Vt,this.type=t,this.precomputed=null}};var sr=class n extends rr{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),l=c.redSub(u);if(f.cmpn(0)===0)return l.cmpn(0)===0?this.dbl():new n(null,null,null);let d=f.redSqr(),p=d.redMul(f),m=s.redMul(d),g=l.redSqr().redIAdd(p).redISub(m).redISub(m),y=l.redMul(m.redISub(g)).redISub(c.redMul(p)),S=this.z.redMul(e.z).redMul(f);return new n(g,y,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 l=u.redSqr(),d=l.redMul(u),p=r.redMul(l),m=f.redSqr().redIAdd(d).redISub(p).redISub(p),g=f.redMul(p.redISub(m)).redISub(o.redMul(d)),y=this.z.redMul(u);return new n(m,g,y)}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),l=f.redSqr().redISub(u).redISub(u),d=c.redIAdd(c);d=d.redIAdd(d),d=d.redIAdd(d),e=l,i=f.redMul(u.redISub(l)).redISub(d),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),l=f.redSqr(),d=c.redIAdd(c);d=d.redIAdd(d),d=d.redIAdd(d),e=l.redISub(u).redISub(u),i=f.redMul(u.redISub(e)).redISub(d),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 ch(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,Ku=2n,$1=3n,q1=4n,F1=8n,Tn=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,xi=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,uh=(1n<<256n)-1n;function Xu(n){let t=n>>256n;return n=(n&uh)+(t<<32n)+t*977n,t=n>>256n,n=(n&uh)+(t<<32n)+t*977n,n>=Tn&&(n-=Tn),n}var or=n=>Xu((n%Tn+Tn)%Tn),kn=(n,t)=>n>=t?n-t:Tn-(t-n),ct=(n,t)=>Xu(n*t),fh=(n,t)=>Xu(n+t),Wr=n=>{let t=Ce,e=Ut,i=or(n),r=Tn;for(;i>Ce;){let s=r/i;[t,e]=[e-t*s,t],[i,r]=[r-i*s,i]}return or(t)},W1=n=>ct(n,n),V1=(n,t)=>{let e=1n;for(n=or(n);t>0n;)(t&1n)!==0n&&(e=ct(e,n)),n=ct(n,n),t>>=1n;return e},K1=Tn+1n>>2n,z1=n=>{let t=V1(n,K1);return ct(t,t)!==or(n)?null:t},X1=n=>T.isBN(n)?BigInt("0x"+n.toString(16)):typeof n=="string"?BigInt("0x"+n):Array.isArray(n)?BigInt("0x"+nt(n)):BigInt(n),Ra=BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Na=BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),dh=new Map,ao=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(q1,ct(t,r)),o=ct($1,ct(t,t)),c=kn(ct(o,o),ct(Ku,s)),u=kn(ct(o,kn(s,c)),ct(F1,ct(r,r))),f=ct(Ku,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?ao(n):{X:Ut,Y:Ce,Z:Ut};let l=ct(u,u),d=ct(u,l),p=ct(r,l),m=kn(kn(ct(f,f),d),ct(Ku,p)),g=kn(ct(f,kn(p,m)),ct(o,d)),y=ct(u,ct(n.Z,t.Z));return{X:m,Y:g,Z:y}},j1=n=>n.Z===Ut?n:{X:n.X,Y:Tn-n.Y,Z:n.Z},G1=(n,t)=>{let e=`${n}:${t.x.toString(16)}:${t.y.toString(16)}`,i=dh.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=ao(s);for(let c=1;c<r.length;c++)r[c]=Vr(r[c-1],o);return dh.set(e,r),r},Y1=(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},Ba=(n,t,e=5)=>{let i=G1(e,t),r=Y1(n,e),s={X:Ut,Y:Ce,Z:Ut};for(let o=r.length-1;o>=0;o--){s=ao(s);let c=r[o];if(c!==0){let u=Math.abs(c)>>1,f=c>0?i[u]:j1(i[u]);s=Vr(s,f)}}return s},ar=n=>{let t=n%xi;return t<0n&&(t+=xi),t},co=(n,t)=>ar(n*t),ju=n=>{let t=1n,e=0n,i=ar(n),r=xi;for(;i>1n;){let s=r/i;[t,e]=[e-t*s,t],[i,r]=[r-i*s,i]}return ar(t)},pe,lh,hh,ph,gh,mh,zu,bh,Ot=class Ot extends rr{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=X1(e);r=or(r);let s=fh(ct(W1(r),r),7n),o=z1(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=fh(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=ao({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=or(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=Ra,c=Na):(o=BigInt("0x"+this.x.fromRed().toString(16)),c=BigInt("0x"+this.y.fromRed().toString(16)));let u=Ba(s,{x:o,y:c});if(u.Z===Ut)return new Ot(null,null);let f=Wr(u.Z),l=ct(f,f),d=ct(u.X,l),p=ct(u.Y,ct(l,f)),m=new T(d.toString(16),16),g=new T(p.toString(16),16),y=new Ot(m,g);return i?y.neg():y}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=or(s),s===0n)return new Ot(null,null);let o=this===this.curve.g?Ra:BigInt("0x"+this.getX().toString(16)),c=this===this.curve.g?Na:BigInt("0x"+this.getY().toString(16)),u={X:0n,Y:1n,Z:0n},f={X:o,Y:c,Z:1n},l=s.toString(2);for(let S of l){let C=S==="1"?1n:0n;ch(C,u,f),f=Vr(u,f),u=ao(u),ch(C,u,f)}if(u.Z===0n)return new Ot(null,null);let d=Wr(u.Z),p=ct(d,d),m=ct(u.X,p),g=ct(u.Y,ct(p,d)),y=new Ot(m.toString(16),g.toString(16));return i?y.neg():y}mulAdd(e,i,r){let s=[this,i],o=[e,r];return a(this,pe,zu).call(this,s,o)}jmulAdd(e,i,r){let s=[this,i],o=[e,r];return a(this,pe,zu).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 sr(null,null,null):new sr(this.x,this.y,this.curve.one)}_combineWnafPair(e,i,r){let{points:s,coeffs:o,wndWidth:c,wnd:u,naf:f,currentMax:l}=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(l,f[e].length,f[i].length);let d=[s[e],null,null,s[i]],p=s[e].y??new T(0),m=s[i].y??new T(0);p.cmp(m)===0?(d[1]=s[e].add(s[i]),d[2]=s[e].toJ().mixedAdd(s[i].neg())):p.cmp(m.redNeg())===0?(d[1]=s[e].toJ().mixedAdd(s[i]),d[2]=s[e].add(s[i].neg())):(d[1]=s[e].toJ().mixedAdd(s[i]),d[2]=s[e].toJ().mixedAdd(s[i].neg()));let g=[-3,-1,-5,-7,0,7,5,1,3],y=this.curve.getJSF(o[e],o[i]),S=Math.max(l,y[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(y[0][C]),A=Math.trunc(y[1][C]);f[e][C]=g[(E+1)*3+(A+1)],f[i][C]=0,u[e]=d}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,lh=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},hh=function(e,i,r,s,o){var c;for(let u=0;u<r;u++){let f=a(c=i[u],pe,bh).call(c,e);s[u]=f.wnd,o[u]=f.points}},ph=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},gh=function(e,i,r,s){let o=new T(1),c=new T(2),u=e;for(let f=0;f<i;f++){let l=r[f];if(l.cmpn(0)===0)continue;let d=l.isNeg()?s[f][l.neg().sub(o).div(c).toNumber()].neg():s[f][l.sub(o).div(c).toNumber()];u=d.type==="affine"?u.mixedAdd(d):u.add(d)}return u},mh=function(e,i,r,s,o){let c=this.curve._wnafT1.length,u=Array.from({length:c}),f=Array.from({length:c},()=>[]),l=Array.from({length:c},()=>[]);a(this,pe,hh).call(this,e,i,s,u,f);let d=a(this,pe,ph).call(this,i,r,s,u,f,l),p=new sr(null,null,null),m=this.curve._wnafT4,g=d;for(;g>=0;){let y=this._collectWnafStep(g,s,l,m);if(g=y.index,p=p.dblp(y.doubles),g<0)break;p=a(this,pe,gh).call(this,p,s,m,f),g--}for(let y=0;y<s;y++)f[y]=[];return o===!0?p:p.toP()},zu=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 l=this.curve._endoSplit(i[c]),d=e[c],p=a(f=d,pe,lh).call(f)??new Ot(null,null);l.k1.negative!==0&&(l.k1.ineg(),d=d.neg(!0)),l.k2.negative!==0&&(l.k2.ineg(),p=p.neg(!0)),s[c*2]=d,s[c*2+1]=p,o[c*2]=l.k1,o[c*2+1]=l.k2}let u=a(this,pe,mh).call(this,1,s,o,c*2,r);for(let l=0;l<c*2;l++)s[l]=null,o[l]=null;return u},bh=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 Ii(r,e,this)}toDER(t){return t==="hex"?this.encode(!0,t):this.encode(!0)}toHash(t){let e=Ys(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 so(this.toHash(),t)}deriveChild(t,e,i,r){let s;if(typeof r=="function"){let d=r(t,this);d===void 0?(s=this.deriveSharedSecret(t),typeof i=="function"&&i(t,this,s)):s=d}else s=this.deriveSharedSecret(t);let o=at(e,"utf8"),c=Zs(s.encode(!0),o),f=new Vt().g.mul(new T(c)),l=this.add(f);return new n(l.x,l.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=(d,p)=>{let m=d[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 l=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(l[0]===0){if((l[1]&128)===0)throw new Error("Invalid S-value in signature DER");l=l.slice(1)}return new n(new T(u),new T(l))}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 Ii(r,this,e)}toString(t){return this.toDER(t)}toDER(t){let e=(f,l)=>{if(l<128)f.push(l);else throw new Error("len must be < 0x80")},i=f=>{let l=0,d=f.length-1;for(;f[l]===0&&(f[l+1]&128)===0&&l<d;)l++;return l===0?f:f.slice(l)},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,l=o===0?i:i.add(u),d=Oe.fromX(l,s);if(!d.mul(u).isInfinity())throw new Error("nR is not at infinity");let m=e.neg().umod(u),g=i.invm(u),y=g.mul(r).umod(u),S=g.mul(m).umod(u),C=f.mul(S).add(d.mul(y)),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 uo=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 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 yh(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 cr(n){let t=n.toArray("be"),e=0n;for(let i of t)e=e<<8n|BigInt(i);return e}var fo=new Vt,Gu=fo.n.byteLength(),Z1=fo.n.subn(1),J1=xi>>1n;function Q1(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(Gu),16),i==null)throw new Error("k is undefined");return yh(i,!0)}function _a(n,t){if(n)throw new Error(t)}function ty(n,t,e,i,r){if(n.cmpn(1)<0||n.cmp(Z1)>0)return _a(r,"Invalid fixed custom K value (must be >1 and <N-1)");let s=fo.g.mulCT(n);if(s.isInfinity())return _a(r,"Invalid fixed custom K value (k\xB7G at infinity)");let o=ar(BigInt("0x"+s.getX().toString(16)));if(o===0n)return _a(r,"Invalid fixed custom K value (r == 0)");let c=ju(BigInt("0x"+n.toString(16))),u=ar(t+co(o,e)),f=co(c,u);return f===0n?_a(r,"Invalid fixed custom K value (s == 0)"):(i&&f>J1&&(f=xi-f),new ge(new T(o.toString(16),16),new T(f.toString(16),16)))}var wh=(n,t,e=!1,i)=>{let r=fo.n.bitLength();if(n.bitLength()>r)throw new Error(`ECDSA message is too large: expected <= ${r} bits. Callers must hash messages before signing.`);n=yh(n);let s=cr(n),o=cr(t),c=t.toArray("be",Gu),u=n.toArray("be",Gu),f=new uo(c,u),l=T.isBN(i);for(let d=0;;d++){let p=ty(Q1(i,d,f),s,o,e,l);if(p!=null)return p}},Ii=(n,t,e)=>{let i=fo.n.bitLength();if(n.bitLength()>i)return!1;let r=cr(n);if(e.x==null||e.y==null)throw new Error("Invalid public key: missing coordinates.");let s={x:cr(e.x),y:cr(e.y)},o={r:cr(t.r),s:cr(t.s)},{r:c,s:u}=o,f=r;if(c<=Ut||c>=xi||u<=Ut||u>=xi)return!1;let l=ju(u);if(l===0n)return!1;let d=co(f,l),p=co(c,l),m=Ba(d,{x:Ra,y:Na}),g=Ba(p,s),y=Vr(m,g);if(y.Z===0n)return!1;let S=Wr(y.Z),C=ct(S,S),E=ct(y.X,C);return ar(E)===c};var Yu=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)}},xh=null,ey=n=>(xh??(xh=new Yu),xh.generate(n)),Pe=ey;var Ae=255,ny=129,Ih=/^[1-9A-HJ-NP-Za-km-z]{1,64}$/;function Sh(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 ro(this.x.toArray())+"."+ro(this.y.toArray())}static fromString(t){if(typeof t!="string"||t.length>ny)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||!Ih.test(e)||!Ih.test(i))throw new TypeError("Finite-field point must use a bounded canonical Base58 representation");let s=new n(new T(io(e)),new T(io(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){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;Sh(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(Sh(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,l=this.points[o].x,d=r.sub(f).umod(e),m=l.sub(f).umod(e).invm(e),g=d.mul(m).umod(e);c=c.mul(g).umod(e)}s=s.add(c).umod(e)}return s}};var iy=256,vh=/^[1-9A-HJ-NP-Za-km-z]{1,64}$/,ry=/^(?:[2-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/,Ah=/^[0-9a-f]{8}$/;function Zu(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"||!Ah.test(e))throw new TypeError("integrity must be an 8-character lowercase hexadecimal string")}var lo=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>iy)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,l,d]=c;if(u===void 0||f===void 0||l===void 0||d===void 0||!vh.test(u)||!vh.test(f)||!ry.test(l)||!Ah.test(d))throw new TypeError(`Invalid canonical share data in share ${s.toString()}`);let p=Number(l);if(s!==0&&e!==p)throw new Error("Threshold mismatch in share "+s.toString());if(s!==0&&i!==d)throw new Error("Integrity mismatch in share "+s.toString());e=p,i=d,r.push(nn.fromString(`${u}.${f}`))}return Zu(r,e,i),new n(r,e,i)}toBackupFormat(){Zu(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}},ur=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=oo(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 wh(s,this,i,r)}verify(t,e,i){let r=new T(Te(t,i),16);return Ii(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 so([...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=Zs(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=Kr.fromPrivateKey(this,t),r=[],s=new Set,o=new Vt,c=Pe(64);for(let f=0;f<e;f++){let l,d=0;do{let m=[f,d,...Pe(32)],g=$u(c,m);if(l=new T(g).umod(o.p),d++,d>5)throw new Error("Failed to generate unique x coordinate after 5 attempts")}while(l.isZero()||s.has(l.toString()));s.add(l.toString());let p=i.valueAt(l);r.push(new nn(l,p))}let u=this.toPublicKey().toHash("hex").slice(0,8);return new lo(r,t,u)}toBackupShares(t,e){return this.toKeyShares(t,e).toBackupFormat()}static fromBackupShares(t){return n.fromKeyShares(lo.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(Zu(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 l=0;l<i;l++){if(!Object.prototype.hasOwnProperty.call(e,l))throw new TypeError("shares must be a dense array");let d=e[l];if(!(d instanceof nn)||!(d.x instanceof T)||!(d.y instanceof T))throw new TypeError("shares must contain finite-field points");if(d.x.isNeg()||d.y.isNeg()||d.x.gte(o)||d.y.gte(o))throw new TypeError("share coordinates must be canonical field elements");s.push(new nn(new T(d.x.toArray()),new T(d.y.toArray())))}for(let l=0;l<i;l++)for(let d=l+1;d<i;d++)if(s[l].x.eq(s[d].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 Ju={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},Ca=Ju;for(let n of Object.keys(Ju)){let t=Ju[n];Ca[t]??(Ca[t]=n)}var x=Ca;var Eh=typeof globalThis>"u"?void 0:globalThis.Buffer,kh=Symbol();function dr(n){return n[kh]()}function sy(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 oy(n,t){let e=sy(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,fr,te,Th,Oh,_t,Qu,Ph,Rh,Kn,tf,Nh,La,Bh,ef,_h,Ch,nf,Lh,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,fr);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,Oh).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=no(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,Qu).call(this),w(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,Lh).call(this,e);return t.slice(1)}toHex(){let t=a(this,_t,La).call(this);if(w(this,On)!=null)return w(this,On);let e=Eh==null?Ta(Array.from(t),"hex"):Eh.from(t).toString("hex");return N(this,On,e),e}toBinary(){return Array.from(this.toUint8Array())}toUint8Array(){return Uint8Array.from(a(this,_t,La).call(this))}[kh](){return a(this,_t,La).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,Ch).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;)oy(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,fr=new WeakMap,te=new WeakSet,Th=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},Oh=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(Ta(u,"hex")!==c)throw new Error("invalid hex string in script");return{chunk:{data:u,op:a(o=de,te,Th).call(o,u.length)},advance:1}}return{chunk:{op:s},advance:1}},_t=new WeakSet,Qu=function(){var t;w(this,zn)||(w(this,Ke)!=null?N(this,Ve,a(t=de,te,_h).call(t,w(this,Ke))):N(this,Ve,[]),N(this,zn,!0),a(this,_t,tf).call(this))},Ph=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},Rh=function(){var s,o;let t=this.chunks,e=a(s=de,te,Ph).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,Bh).call(o,i,r,c.op,c.data)}return i},Kn=function(){N(this,Ke,void 0),N(this,On,void 0),N(this,fr,void 0)},tf=function(){N(this,fr,w(this,Ve).map(t=>({ref:t,op:t.op,dataRef:t.data,data:t.data==null?void 0:Array.from(t.data)})))},Nh=function(){if(w(this,fr)?.length!==w(this,Ve).length)return!1;for(let t=0;t<w(this,Ve).length;t++){let e=w(this,Ve)[t],i=w(this,fr)[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},La=function(){return!w(this,zn)&&w(this,Ke)!=null?w(this,Ke):(a(this,_t,Qu).call(this),(w(this,Ke)==null||!a(this,_t,Nh).call(this))&&(N(this,Ke,a(this,_t,Rh).call(this)),N(this,On,void 0),a(this,_t,tf).call(this)),w(this,Ke))},Bh=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},ef=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}},_h=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,nf).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:l,newPos:d,hasLength:p}=a(c=de,te,ef).call(c,f,t,r,i);r=d;let m=Math.min(r+l,i),g=!p||m-r!==l;e.push({data:a(u=de,te,nf).call(u,t,r,m),op:f,invalidLength:g}),r=m}else e.push({op:f})}return e},Ch=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:l}=a(o=de,te,ef).call(o,u,t,s,r);s=l;let d=Math.min(s+f,r);if(u!==e)for(let p=c;p<d;p++)i.push(t[p]??0);s=d}else u!==e&&i.push(u)}return i},nf=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},Lh=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 ay=new Uint8Array(0),rf=Object.freeze(Array.from({length:32},()=>0));function cy(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 uy(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=cy(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 fy(n,t){if(n.allInputs!=null)return n.allInputs;let e=[...n.otherInputs];return e.splice(n.inputIndex,0,t),e}function Dh(n,t,e,i){return i===t?e:n[i]}function dy(n,t,e){let i=new fe;for(let r=0;r<n.length;r++){let s=Dh(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 ly(n,t,e){let i=new fe;for(let r=0;r<n.length;r++){let s=Dh(n,t,e,r);i.writeUInt32LE(s.sequence??4294967295)}return zt(i.toUint8Array())}function Uh(n,t){n.writeUInt64LE(t.satoshis??0);let e=t.lockingScript?.toUint8Array()??ay;n.writeVarIntNum(e.length),n.write(e)}function Mh(n,t){let e=new fe;if(t==null)for(let i of n)Uh(e,i);else{let i=n[t];if(i==null)throw new Error(`Output at index ${t} does not exist`);Uh(e,i)}return zt(e.toUint8Array())}function hy(n,t,e){if((n.scope&yt.SIGHASH_ANYONECANPAY)!==0)return[...rf];if(n.cache?.hashPrevouts!=null)return n.cache.hashPrevouts;let i=dy(t,n.inputIndex,e);return n.cache!=null&&(n.cache.hashPrevouts=i),i}function py(n,t,e){let i=n.scope&31;if((n.scope&yt.SIGHASH_ANYONECANPAY)!==0||i===yt.SIGHASH_SINGLE||i===yt.SIGHASH_NONE)return[...rf];if(n.cache?.hashSequence!=null)return n.cache.hashSequence;let r=ly(t,n.inputIndex,e);return n.cache!=null&&(n.cache.hashSequence=r),r}function gy(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=Mh(n.outputs);return n.cache!=null&&(n.cache.hashOutputsAll=s),s}if(t!==yt.SIGHASH_SINGLE||n.inputIndex>=n.outputs.length)return[...rf];let e=n.cache?.hashOutputsSingle?.get(n.inputIndex);if(e!=null)return e;let i=Mh(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=uy(e.subscript),u={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence,script:c.bytes,scriptLength:c.encodedLength},f=new fe;function l(g){f.writeVarIntNum(g.length);for(let y of g)f.writeReverse(at(y.sourceTXID,"hex")),f.writeUInt32LE(y.sourceOutputIndex),f.writeVarIntNum(y.scriptLength??y.script.length),f.write(y.script),f.writeUInt32LE(y.sequence)}function d(g){f.writeVarIntNum(g.length);for(let y of g)f.writeUInt64LE(y.satoshis),f.writeVarIntNum(y.script.length),f.write(y.script)}f.writeInt32LE(e.transactionVersion);let p=new me().toBinary();if(i)i&&l([u]);else{let g=e.allInputs==null?e.otherInputs.map(y=>({sourceTXID:y.sourceTXID??y.sourceTransaction?.id("hex")??"",sourceOutputIndex:y.sourceOutputIndex,sequence:r||s?0:y.sequence??4294967295,script:p})):e.allInputs.map((y,S)=>S===e.inputIndex?u:{sourceTXID:y.sourceTXID??y.sourceTransaction?.id("hex")??"",sourceOutputIndex:y.sourceOutputIndex,sequence:r||s?0:y.sequence??4294967295,script:p});e.allInputs==null&&g.splice(e.inputIndex,0,u),l(g)}if(o){let g=e.outputs.map(y=>({satoshis:y.satoshis??0,script:y.lockingScript.toBinary()}));d(g)}else if(r){let g=[];for(let S=0;S<e.inputIndex;S++)g.push({satoshis:-1,script:p});let y=e.outputs[e.inputIndex];y!==void 0&&g.push({satoshis:y.satoshis??0,script:y.lockingScript.toBinary()}),d(g)}else s&&d([]);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=fy(e,i),s=hy(e,r,i),o=py(e,r,i),c=gy(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 l=i.sequence??4294967295;return u.writeUInt32LE(l),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 yt=Xt;function sf(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 my(){return globalThis}function of(n){let t=my().__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 Hh(n){return n==null?"null/undef":n.length===void 0?"INVALID_STACK_ITEM":nt(n)}var ho=class extends Error{constructor(e){let i=e.stackState.map(Hh).join(", "),r=e.altStackState.map(Hh).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(l=>l.slice()),this.altStackState=e.altStackState.map(l=>l.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 by;function Ua(){return by}var yy=520,$h=1e4,qh=500,wy=0x7fffffffn,xy=75e4,Iy=32e6,Fh=1e3,Sy=Math.pow(2,31)-1,vy=BigInt(Sy),Ay=20,Wh=2147483648,af=4194304,Ey=65535,Vh=5e8,ky=Object.freeze(new T(-1).toScriptNum()),Kh=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 Ty(n,t){return vi(n&&t)}function Oy(n,t){return vi(n||t)}function Py(n,t){return n.cmp(t)<0?n:t}function Ry(n,t){return n.cmp(t)>0?n:t}function Xh(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 jh(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 Ny(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 By(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,wo,h,Si,Mt,Et,se,po,jn,go,Gh,Yh,Zh,Jh,cf,uf,Ma,zr,mo,Qh,lt,Re,Q,Kt,vt,tp,ep,Da,np,ip,le,bo,ff,rp,sp,op,df,lf,hf,pf,ap,gf,mf,cp,up,fp,dp,lp,hp,pp,gp,mp,bp,yp,bf,Ha,wp,yf,Xr,K,wf=class wf{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,wo);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,wo,t.sigHashCache==null),N(this,Gn,t.sigHashCache??{hashOutputsSingle:new Map}),this.reset()}reset(){w(this,wo)&&(delete w(this,Gn).hashPrevouts,delete w(this,Gn).hashSequence,delete w(this,Gn).hashOutputsAll,w(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,cp).call(this);let t=a(this,h,up).call(this);if(this.programCounter>=t.chunks.length)return!1;let e=t.chunks[this.programCounter],i=a(this,h,fp).call(this,e),r=!this.returningFromConditional&&!this.ifStack.includes(!1);if(a(this,h,dp).call(this,i),r&&i>=0&&i<=x.OP_PUSHDATA4)a(this,h,lp).call(this,e);else if(r||i>=x.OP_IF&&i<=x.OP_ENDIF){let s,o,c,u,f,l,d,p,m,g,y,S,C,E,A,k,B,_,$,R,I,U,M,F,it,ot;if(a(this,h,hp).call(this,i,r),a(this,h,pp).call(this,i,r))return!0;switch(a(this,h,gp).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,bo).call(this,a(this,h,Q).call(this)),z=a(this,h,bo).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,bo).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,bo).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,Ma).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,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,ky);break;case x.OP_0:a(this,h,Re).call(this,Kh[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,Kh[S]);break;case x.OP_NOP:case x.OP_NOP1:break;case x.OP_CHECKLOCKTIMEVERIFY:a(this,h,mp).call(this);break;case x.OP_CHECKSEQUENCEVERIFY:a(this,h,bp).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,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,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,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,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,np).call(this,a(this,h,Q).call(this));break;case x.OP_FROMALTSTACK:a(this,h,tp).call(this,1,"OP_FROMALTSTACK requires at least one item to be on the stack."),a(this,h,lt).call(this,a(this,h,ip).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),ce=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,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),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,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."),d=a(this,h,Q).call(this),l=a(this,h,Q).call(this),f=a(this,h,Q).call(this),a(this,h,lt).call(this,l),a(this,h,lt).call(this,d),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."),l=a(this,h,Q).call(this),f=a(this,h,Q).call(this),a(this,h,lt).call(this,l),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,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 It=new T(1).ushln(o.length*8).isubn(1);z=z.iand(It)}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,mo).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 Ty(m.cmpn(0)!==0,g.cmpn(0)!==0);case x.OP_BOOLOR:return Oy(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 Py(m,g);case x.OP_MAX:return Ry(m,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."),y=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(y)<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=Du(s):i===x.OP_SHA1?q=Hu(s):i===x.OP_SHA256?q=Te(s):i===x.OP_HASH160?q=Ys(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,df).call(this,B)||!a(this,h,gf).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,lf).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),(($.scope&yt.SIGHASH_FORKID)===0||a(this,h,Mt).call(this)&&!a(this,h,Et).call(this,"SIGHASH_FORKID"))&&k.findAndDelete(new me().writeBin(B)),R=Ht.fromDER(_),a(this,h,mf).call(this,$,R,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(Ay):vy;(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,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 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 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,df).call(this,B)||!a(this,h,gf).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,lf).call(this,B),R=Ht.fromDER(_),ot=a(this,h,mf).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,jn).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,Yh).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,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 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,le).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>wy&&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=Oa(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),ce=0;tt.length>0&&(ce=tt.at(-1)&128,tt[tt.length-1]&=127);for(let Bt=0;Bt<tt.length;Bt++)It[Bt]=tt[Bt];ce!==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=Oa(o);jh(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,yp).call(this,t),!0}validate(t){let e=Ua(),i=a(this,h,bf).call(this),r=t===void 0?void 0:Xh(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,Zh).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,wp).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,Ha).call(this,"UnlockingScript");let i=this.stack.map(r=>r.slice());a(this,h,Ha).call(this,"LockingScript"),a(this,h,yf).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,ep).call(this,i);let s=me.fromBinary(r);this.lockingScript=new Le(s.chunks),a(this,h,Ha).call(this,"LockingScript")}}finally{this.lockingScript=t}return a(this,h,Jh).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,yf).call(this),!0}async validateWith(t,e){let i=a(this,h,bf).call(this),r=e===void 0?void 0:Xh(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,wo=new WeakMap,h=new WeakSet,Si=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,Si).call(this)},po=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"UTXO_AFTER_CHRONICLE"):a(this,h,Si).call(this)},jn=function(){return!(a(this,h,Et).call(this,"CHRONICLE")&&this.transactionVersion>1)},go=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"MINIMALDATA")&&a(this,h,jn).call(this):!a(this,h,Si).call(this)},Gh=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,Si).call(this)},Yh=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"NULLDUMMY")&&a(this,h,jn).call(this):!a(this,h,Si).call(this)},Zh=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"SIGPUSHONLY")&&a(this,h,jn).call(this):!a(this,h,Si).call(this)},Jh=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"CLEANSTACK")&&a(this,h,jn).call(this):!a(this,h,Si).call(this)},cf=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},uf=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"STRICTENC")||a(this,h,Et).call(this,"SIGHASH_FORKID"):!0},Ma=function(){if(a(this,h,Mt).call(this))return a(this,h,se).call(this)?a(this,h,po).call(this)?Iy:xy:4},zr=function(){return a(this,h,Mt).call(this)&&!a(this,h,se).call(this)?yy:Number.POSITIVE_INFINITY},mo=function(t){if(this.stackMem+t>this.memoryLimit)throw new Xn("stack",this.memoryLimit,this.stackMem+t)},Qh=function(t){if(this.altStackMem+t>this.memoryLimit)throw new Xn("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)},tp=function(t,e){this.altStack.length<t&&a(this,h,K).call(this,e)},ep=function(t){this.stack=t.map(e=>e.slice()),this.stackMem=this.stack.reduce((e,i)=>e+i.length,0)},Da=function(){this.altStack=[],this.altStackMem=0},np=function(t){a(this,h,Qh).call(this,t.length),this.altStack.push(t),this.altStackMem+=t.length},ip=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,go).call(this),a(this,h,Ma).call(this))}catch(e){let i=e instanceof Error?e.message:String(e);a(this,h,K).call(this,i)}return new T(0)},bo=function(t){let e=a(this,h,Ma).call(this);e!==void 0&&t.length>e&&a(this,h,K).call(this,"script number overflow"),a(this,h,go).call(this)&&!jh(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)},ff=function(t){try{return T.fromScriptNum(t,a(this,h,go).call(this),5).toBigInt()}catch(e){a(this,h,K).call(this,e instanceof Error?e.message:String(e))}return 0n},rp=function(t){let e=t&31;return e>=yt.SIGHASH_ALL&&e<=yt.SIGHASH_SINGLE},sp=function(t){if(!a(this,h,uf).call(this))return;a(this,h,rp).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,po).call(this);e&&!i&&a(this,h,K).call(this,"The signature hash type is invalid before Chronicle.")},op=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,se).call(this)&&e&&a(this,h,K).call(this,"The signature must not use SIGHASH_FORKID.")},df=function(t){if(t.length===0)return!0;let e=a(this,h,cf).call(this);if(e&&!Ny(t))return a(this,h,K).call(this,"The signature format is invalid."),!1;try{let i=yt.fromChecksigFormat(t);if(a(this,h,sp).call(this,i),a(this,h,op).call(this,i),a(this,h,Gh).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},lf=function(t){try{return yt.fromChecksigFormat(t)}catch(e){if(a(this,h,cf).call(this))throw e;return a(this,h,ap).call(this,t)}},hf=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},pf=function(t,e,i){if(e.value>=i||t[e.value++]!==2)throw new Error("Invalid DER integer");let r=a(this,h,hf).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)},ap=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,hf).call(this,i,r),o=Math.min(r.value+s,i.length),c=a(this,h,pf).call(this,i,r,o),u=a(this,h,pf).call(this,i,r,o);return new yt(c,u,e)},gf=function(t){if(!a(this,h,uf).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},mf=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:w(this,Gn)},s=yt.usesOtdaSingleBug(r)?new T([1,...Array.from({length:31},()=>0)]):new T(zt(yt.formatBytes(r)));return Ii(s,t,e)},cp=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)},up=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,Da).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},fp=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)},dp=function(t){a(this,h,Mt).call(this)&&!a(this,h,se).call(this)&&!a(this,h,po).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.`)},lp=function(t){a(this,h,go).call(this)&&!By(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:[])},hp=function(t,e){!e||t<=x.OP_16||(this.executedOpCount++,a(this,h,Mt).call(this)&&!a(this,h,se).call(this)&&this.executedOpCount>qh&&a(this,h,K).call(this,`Script executed more than ${qh} opcodes.`))},pp=function(t,e){return!a(this,h,Mt).call(this)||a(this,h,po).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)},gp=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.`)},mp=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,ff).call(this,a(this,h,Kt).call(this));t<0n&&a(this,h,K).call(this,"Negative lock time.");let e=t<BigInt(Vh),i=this.lockTime<Vh;(e!==i||t>BigInt(this.lockTime)||this.inputSequence===4294967295)&&a(this,h,K).call(this,"OP_CHECKLOCKTIMEVERIFY lock time is unsatisfied.")},bp=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,ff).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(Wh))!==0n)return;let e=BigInt(this.inputSequence>>>0),i=BigInt(af|Ey),r=t&i,s=e&i;(this.transactionVersion>>>0<2||(e&BigInt(Wh))!==0n||(r&BigInt(af))!==(s&BigInt(af))||r>s)&&a(this,h,K).call(this,"OP_CHECKSEQUENCEVERIFY lock time is unsatisfied.")},yp=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>Fh&&a(this,h,K).call(this,`Stack item count has exceeded ${Fh}.`)},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 wf({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)})},Ha=function(t){this.context=t,this.programCounter=0,this.ifStack=[],this.elseStack=[],this.returningFromConditional=!1,a(this,h,Da).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>$h&&a(this,h,K).call(this,`Script size exceeds ${$h} 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,Da).call(this),this.lastCodeSeparator=null},wp=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},yf=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 ho({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 yo=wf;var _y=21e14,Cy=4294967295;function $a(n,t){if(!Number.isSafeInteger(n)||n<0||n>Cy)throw new Error(`${t} must be an unsigned 32-bit integer`);return n}function xf(n,t){if(!Number.isSafeInteger(n)||n<0||n>_y)throw new Error(`${t} must be a valid number of satoshis`);return n}function If(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 Sf(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 xp(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 Ip(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=$a(r.sourceOutputIndex,"input.sourceOutputIndex"),o=r.sourceTXID===void 0?void 0:If(r.sourceTXID,"input.sourceTXID"),c=r.sourceTransaction===void 0?void 0:If(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 l=e===void 0?void 0:xf(e,"sourceSatoshis"),d=f?.satoshis===void 0?void 0:xf(f.satoshis,"sourceTransaction output satoshis");if(l!==void 0&&d!==void 0&&l!==d)throw new Error("The sourceSatoshis does not match the input sourceTransaction output.");let p=l??d;if(p===void 0)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");let m=i===void 0?void 0:Sf(i,"lockingScript"),g=f?.lockingScript===void 0?void 0:Sf(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 y=m??g;if(y===void 0)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");return{sourceTXID:u,sourceSatoshis:p,lockingScript:y,allInputs:n.inputs,get otherInputs(){return n.inputs.filter((S,C)=>C!==t)}}}function Sp(n){let{tx:t,inputIndex:e,signatureScope:i,sourceTXID:r,sourceSatoshis:s,lockingScript:o,otherInputs:c,allInputs:u,inputSequence:f}=n,l=t.inputs[e];$a(l.sourceOutputIndex,"input.sourceOutputIndex"),xf(s,"sourceSatoshis"),If(r,"sourceTXID"),Sf(o,"lockingScript"),$a(i,"signatureScope");let d=f??ir(l.sequence,"input.sequence must have value");return $a(d,"inputSequence"),yt.format({sourceTXID:r,sourceOutputIndex:ir(l.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:s,transactionVersion:t.version,otherInputs:c??[],allInputs:u,inputIndex:e,outputs:t.outputs,inputSequence:d,subscript:o,lockTime:t.lockTime,scope:i,cache:t.getSignatureHashCache()})}var Yn=class{lock(t){let e;if(typeof t=="string"){let i=oo(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=xp(e,i),f=Ip(o,c,r,s),l=Sp({tx:o,inputIndex:c,signatureScope:u,sourceTXID:f.sourceTXID,sourceSatoshis:f.sourceSatoshis,lockingScript:f.lockingScript,allInputs:f.allInputs}),d=Te(l),p=of("signDigest"),m=of("publicKeyFromPrivate"),g=p===void 0&&m===void 0?void 0:Uint8Array.from(t.toArray("be",32)),y=m===void 0?t.toPublicKey().encode(!0):void 0,S=p===void 0?t.sign(d):ge.fromDER(Array.from(sf("signDigest",await p.signDigest(g,Uint8Array.from(Te(d)))))),E=new yt(S.r,S.s,u).toChecksigFormat(),A=m===void 0?y:Array.from(Ly(await m.publicKeyFromPrivate(g)));return new Ue([{op:E.length,data:E},{op:A.length,data:A}])},estimateLength:async()=>108}}};function Ly(n){let t=sf("publicKeyFromPrivate",n,33);if(t[0]!==2&&t[0]!==3)throw new Error("publicKeyFromPrivate returned an invalid compressed public key");return t}var xo=class{constructor(t){b(this,"value");vp(t),this.value=t}async computeFee(t){let e=this.value;vp(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 vp(n){if(!Number.isFinite(n)||n<0||n>21e14)throw new RangeError("Satoshis-per-kilobyte rate must be finite and non-negative.")}var qa=8*1024*1024,Fa=3e4;function Ap(n={}){let t=n.maxResponseBytes??qa,e=n.timeoutMs??Fa;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 Ep(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 kp(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:l}=await r.read();if(f)break;if(o+=l.byteLength,!Number.isSafeInteger(o)||o>t)throw await r.cancel(),new Error("HTTP response exceeds the configured size limit");s.push(l)}}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 Tp(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,l,d,p=()=>{d!==void 0&&clearTimeout(d),e.signal?.removeEventListener("abort",y)},m=S=>{f||(f=!0,p(),s(S))},g=S=>{f||(f=!0,p(),r(S))},y=()=>{let S=e.signal?.reason instanceof Error?e.signal.reason:new DOMException("HTTP request aborted","AbortError");l?.destroy?.(S),m(S)};l=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>qa)){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"?Ie(B):new Uint8Array(B);if(k+=_.byteLength,!Number.isSafeInteger(k)||k>qa){S.destroy?.(),l.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 $=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){m(B)}}),S.on("error",m),S.on("aborted",()=>m(new Error("HTTP response was aborted")))}),l.on("error",m),f||(d=setTimeout(()=>{let S=new Error("HTTP request timed out");l.destroy?.(S),m(S)},Fa)),l.setTimeout?.(Fa,()=>{let S=new Error("HTTP request timed out");l.destroy?.(S),m(S)}),e.signal?.aborted===!0?y():e.signal?.addEventListener("abort",y,{once:!0}),!f&&(o!==void 0&&l.write(o),l.end())})}var Wa=class{constructor(t){b(this,"https");this.https=t}async request(t,e){return await Tp(this.https,t,e,i=>JSON.stringify(i))}};var Io=class{constructor(t,e={}){b(this,"fetch");b(this,"limits");this.fetch=t,this.limits=Ap(e)}async request(t,e){let i=Ep(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 kp(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 lr(){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 Io(globalThis.window.fetch.bind(globalThis.window));if(typeof globalThis.fetch=="function")return new Io(globalThis.fetch.bind(globalThis));let t=typeof xu=="function"?xu:void 0;if(t===void 0)return n;try{let e=t(["node","https"].join(":"));return new Wa(e)}catch{return n}}var Pn=class Pn extends xo{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 lr().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 So=Pn;function gn(n){return n==="__proto__"||n==="constructor"||n==="prototype"}function Op(n){if(n==null||typeof n!="object"||Array.isArray(n))return!1;let t=Object.getPrototypeOf(n);return t===Object.prototype||t===null}var Va=/^[0-9a-f]{64}$/i,Pp=8192,Uy=128,My=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 vf(n,t){return typeof n=="string"&&Fe(n)<=t}function hr(){return{status:"error",code:"ERR_INVALID_RESPONSE",description:"Broadcaster returned a malformed or transaction-mismatched response."}}function Rp(n,t){if(!Va.test(t)||!Op(n))return hr();let e=Ai(n,"status").value;if(e==="success"){let u=Ai(n,"txid").value,f=Ai(n,"message").value,l=Ai(n,"competingTxs");if(typeof u!="string"||!Va.test(u)||u.toLowerCase()!==t.toLowerCase()||!vf(f,Pp))return hr();let d={status:"success",txid:t.toLowerCase(),message:f};if(l.present){if(!Array.isArray(l.value)||l.value.length>My)return hr();let p=[],m=new Set;for(let g=0;g<l.value.length;g++){let y=Object.getOwnPropertyDescriptor(l.value,g),S=y?.value;if(y==null||!Object.prototype.hasOwnProperty.call(y,"value")||typeof S!="string"||!Va.test(S))return hr();let C=S.toLowerCase();if(m.has(C))return hr();m.add(C),p.push(C)}d.competingTxs=p}return d}if(e!=="error")return hr();let i=Ai(n,"code").value,r=Ai(n,"description").value,s=Ai(n,"txid");if(!vf(i,Uy)||!vf(r,Pp)||s.present&&(typeof s.value!="string"||!Va.test(s.value)||s.value.toLowerCase()!==t.toLowerCase()))return hr();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 Np(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("Invalid offset")}var mn=(n,t)=>Math.floor(n/2**t),vo=n=>n%2===0?n+1:n-1,Af=(n,t,e)=>mn(n,e)===mn(t,e),Ef=n=>n===0?0:n.toString(2).length;function bn(n,t){return nt(zt(at((n??"")+(t??""),"hex").reverse()).reverse())}function Dy(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 Bp(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((d,p)=>{if(!Array.isArray(d))throw new TypeError(`Merkle Path level ${p} must be an array`);return d.map(m=>({...m}))});let s=Array.from({length:this.path.length}).fill(0).map(()=>new Set);if(this.path.forEach((d,p)=>{if(d.length===0&&p===0)throw new Error(`Empty level at height: ${p}`);let m=new Set;d.forEach(g=>{if(Np(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 y=1;y<this.path.length;y++)s[y].add(vo(mn(g.offset,y)))}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],y=>y.toString()).join(", ")}`)})}),!r)return;let o=this.path.map(d=>new Map(d.map(p=>[p.offset,p]))),c=new Map,u=new Map,f=this.path[0].reduce((d,p)=>Math.max(d,p.offset),0),l;this.path[0].forEach((d,p)=>{let m=this.computeRootCached(d.hash,o,c,u,f);if(p===0&&(l=m),l!==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 l=0;l<s;l++){for(f=t.readVarIntNumStrict(!1);f>0;){u=t.readVarIntNumStrict(!1),c=t.readUInt8();let d={offset:u};(c&1)===1?d.duplicate=!0:((c&2)!==0&&(d.txid=!0),d.hash=nt(t.read(32).reverse())),(!Array.isArray(o[l])||o[l].length===0)&&(o[l]=[]),o[l].push(d),f--}o[l].sort((d,p)=>d.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,Ef(s)),u=t;for(let f=0;f<c;f++){let l=`${f}:${mn(o,f)}`,d=Dy(l,u,c,r);if(d!=null)return d;r.set(l,u);let p=vo(mn(o,f)),m=this.cachedFindLeaf(f,p,e,i,s);u=Bp(u,m,p,o,f,this.path.length===1&&Af(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,Ef(r));for(let o=0;o<s;o++){let c=vo(mn(e,o));i=Bp(i,this.findOrComputeLeaf(o,c),c,e,o,this.path.length===1&&Af(e,r,o))}return i}findOrComputeLeaf(t,e){Np(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((l,d)=>Math.max(l,d.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(l=>l.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 l=this.cachedFindLeaf(u,f,i,r,s);if(l?.hash==null||l.hash===""){r.set(o,void 0);return}let d=this.cachedFindLeaf(u,f+1,i,r,s);if(d?.hash==null){if(d?.duplicate===!0||this.path.length===1&&f===mn(s,u))return c={offset:e,hash:bn(l.hash,l.hash)},r.set(o,c),c;r.set(o,void 0);return}let p=d.duplicate===!0?bn(l.hash,l.hash):bn(d.hash,l.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((d,p)=>Math.max(d,p.offset),0),r=Math.max(this.path.length,Ef(i)),s=this.createSourceLeafIndex(),o=new Map,c=this.createTxidToOffsetIndex(),u=this.createNeededLeafLevels(r);for(let d of t)this.collectExtractedLeaves(d,c,u,s,o,i,r);let f=new n(this.blockHeight,this.buildExtractedPath(u));f.trim();let l=f.computeRoot();if(l!==e)throw new Error(`Extracted path root ${l} 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=vo(u);if(!i[0].has(f)){let l=this.cachedFindLeaf(0,f,r,s,o);l!=null&&i[0].set(f,l)}for(let l=1;l<c;l++){let d=vo(mn(u,l));if(i[l].has(d))continue;let p=this.cachedFindLeaf(l,d,r,s,o);p!=null?i[l].set(d,p):Af(u,o,l)&&i[l].set(d,{offset:d,duplicate:!0})}}buildExtractedPath(t){return t.map(e=>Array.from(e.values()).sort((i,r)=>i.offset-r.offset))}};var Hy=32,$y=64;function _p(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||ji(n))throw new TypeError(`${t} must be bounded text without control characters.`);return n}}function qy(n){if(n===void 0)return;let t=_p(n,"ARC headers",$y),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 Fy(n){let t=n??lr();if(t==null||typeof t!="object"||typeof t.request!="function")throw new TypeError("ARC httpClient must provide request().");return t}function Cp(n,t){if(typeof n=="string")return Object.freeze({apiKey:jr(n,"ARC API key",16*1024),httpClient:lr(),deploymentId:t()});let e=_p(n??{},"ARC config",Hy),i=r=>e[r]?.value;return Object.freeze({apiKey:jr(i("apiKey"),"ARC API key",16*1024),httpClient:Fy(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:qy(i("headers"))})}function Lp(n){if(typeof n!="string"||n.length===0||Fe(n)>2048||ji(n))throw new TypeError("ARC URL must be nonempty bounded text without control characters.");return n}function Ka(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 Wy(){return`ts-sdk-${nt(Pe(16))}`}var Vy=new Set(["DOUBLE_SPEND_ATTEMPTED","REJECTED","INVALID","MALFORMED","MINED_IN_STALE_BLOCK"]),Gr=/^[0-9a-f]{64}$/i,$p=128,qp=8192,Ky=256,zy=32,Xy=new Set(["SUCCESS","RECEIVED","SENT_TO_NETWORK","ANNOUNCED_TO_NETWORK","ACCEPTED_BY_NETWORK","SEEN_ON_NETWORK","STORED","MINED","IMMUTABLE"]);function za(n,t,e=!0){return typeof n=="string"&&(e||n.length!==0)&&Fe(n)<=t&&!ji(n)}function Tf(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>zy||Object.values(e).some(i=>i.get!=null||i.set!=null)))return e}function jy(n){if(n===void 0||!Array.isArray(n)||n.length>Ky)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 Up(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 pr(n){return{status:"error",code:"ERR_INVALID_RESPONSE",description:n}}function Mp(n,t){let e=Tf(n);if(e===void 0)return pr("ARC returned a malformed response.");let i=p=>e[p]?.value,r=i("txid"),s=i("extraInfo"),o=i("txStatus"),c=i("competingTxs");if(!za(o,$p,!1)||s!==void 0&&!za(s,qp))return pr("ARC returned invalid transaction status metadata.");let u=jy(c);if(c!==void 0&&u===void 0)return pr("ARC returned invalid competing transaction identifiers.");let f=o.toUpperCase(),l=s?.toUpperCase().includes("ORPHAN")||f.includes("ORPHAN");if(Vy.has(f)||l){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(!Xy.has(f))return pr("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 d={status:"success",txid:t,message:`${o} ${s??""}`.trim()};return u!=null&&(d.competingTxs=u),d}function Gy(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch{return n}}function Dp(n,t,e){let r={status:"error",code:typeof n=="number"&&Number.isSafeInteger(n)||typeof n=="string"&&za(n,$p,!1)?n.toString():"ERR_UNKNOWN",description:"Unknown error"},s=Gy(t),o=Tf(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 za(c,qp)&&(r.description=c,f.detail=c),r.txid!==void 0&&(f.txid=r.txid),Object.keys(f).length!==0&&(r.more=f),r}function Hp(){return{status:"error",code:"500",description:"Internal Server Error"}}var Yr,Eo,kf,Ao=class{constructor(t,e){G(this,Eo);b(this,"URL");b(this,"apiKey");b(this,"deploymentId");b(this,"callbackUrl");b(this,"callbackToken");b(this,"headers");G(this,Yr);this.URL=Lp(t);let i=Cp(e,Wy);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,Ka(this,["URL","apiKey","deploymentId","callbackUrl","callbackToken","headers"])}async broadcast(t){let e={method:"POST",headers:a(this,Eo,kf).call(this),data:{rawTx:Up(t)}};try{let i=await w(this,Yr).request(`${this.URL}/v1/tx`,e);return i.ok?Mp(i.data,t.id("hex")):Dp(i.status,i.data,t.id("hex"))}catch{return Hp()}}async broadcastMany(t){let e=t.map(r=>({rawTx:Up(r)})),i={method:"POST",headers:a(this,Eo,kf).call(this),data:e};try{let r=await w(this,Yr).request(`${this.URL}/v1/txs`,i);if(!r.ok)return t.map(u=>Dp(r.status,r.data,u.id("hex")));if(!Array.isArray(r.data)||r.data.length!==t.length)return t.map(()=>pr("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(()=>pr("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 l=s[f]?.value,d=Tf(l);if(d===void 0)return pr("ARC returned a malformed batch result.");let p=d.txid?.value,m=typeof p=="string"&&Gr.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),Mp(l,m))})}catch{let r=Hp();return t.map(()=>r)}}};Yr=new WeakMap,Eo=new WeakSet,kf=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 Fp(n=!1,t={}){return new Ao(n?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",t)}var Wp=/^[0-9a-f]{64}$/i,Vp=2147483647,Yy=256,Kp=64;function Zy(n,t,e){if(typeof n!="string"||Fe(n)>e||ji(n))throw new TypeError(`${t} must be bounded text without control characters.`);return n}function Of(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 Qy(n){let t=n??lr();if(t==null||typeof t!="object"||typeof t.request!="function")throw new TypeError("What's On Chain httpClient must provide request().");return t}function tw(n){let t=Of(n,"What's On Chain config",8);return{apiKey:t.apiKey?.value===void 0?"":Zy(t.apiKey.value,"What's On Chain API key",16*1024),httpClient:Qy(t.httpClient?.value)}}function ew(n,t){if(typeof n!="string"||!Wp.test(n))throw new TypeError("Merkle root must be a 64-character hexadecimal string.");if(!Number.isSafeInteger(t)||t<0||t>Vp)throw new TypeError("Block height must be a nonnegative bounded integer.");return{root:n.toLowerCase(),height:t}}function nw(n){try{let e=Of(n,"What's On Chain block header",Kp).merkleroot?.value;return typeof e=="string"&&Wp.test(e)?e.toLowerCase():void 0}catch{return}}function iw(n){if(!Array.isArray(n)||n.length===0||n.length>Yy)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=Of(t[0]?.value,"What's On Chain height response",Kp).height?.value;return Number.isSafeInteger(r)&&r>=0&&r<=Vp?r:void 0}catch{return}}var ko=class{constructor(t="main",e={}){b(this,"network");b(this,"apiKey");b(this,"URL");b(this,"httpClient");this.network=Jy(t),this.URL=`https://api.whatsonchain.com/v1/bsv/${this.network}`;let i=tw(e);this.httpClient=i.httpClient,this.apiKey=i.apiKey,Ka(this,["network","URL","httpClient","apiKey"])}async isValidRootForHeight(t,e){let i=ew(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 nw(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=iw(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 ko}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 bt?n.skip(t):n.read(t)}function Pf(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 bt?n.bin.subarray(t,n.pos):Uint8Array.from(n.bin.slice(t,n.pos)),inputTxids:Array.from(i)}}function rw(n){return Pf(new bt(n)).inputTxids}function sw(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&&jp(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=Xp(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||!sw(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=rw(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}=Pf(t);r=new n(o,i,c,!0)}}else{let{rawTx:s,inputTxids:o}=Pf(t);i=t.readUInt8()===0?void 0:t.readVarIntNumStrict(!1),r=new n(s,i,o,!0)}return r}};function ow(n,t,e,i){if(t.path.length!==e)throw new Error("Mismatched roots");for(let r=0;r<e;r++)aw(n[r],t.path[r],i)}function aw(n,t,e){for(let i of t){let r=n.get(i.offset);if(r==null){n.set(i.offset,i);continue}cw(r,i,e)}}function cw(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 Gp(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,mr,es,br,ns,is,rs,yr,wr,Ln,De,Un,O,Jr,Xa,Nf,Bf,ja,Yp,Zp,Jp,Qp,Rn,t0,Nn,e0,n0,To,i0,_f,Cf,Lf,r0,Oo,Po,Ga,gr,Qr,Uf,Ya,s0,Mf,o0,a0,c0,Ro,u0,f0,Za,d0,l0,Df,h0,p0,g0,m0,b0,y0,w0,ts,Hf,x0,Ja,I0,S0,v0,A0,E0,k0,T0,O0,yn=class yn{constructor(t=4022206466){G(this,O);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,mr,new Map);G(this,es);G(this,br);G(this,ns);G(this,is);G(this,rs);G(this,yr);G(this,wr);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,gr).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,Po).call(this);if(e.size!==this.txs.length)return!1;let i=e.get(t);return i==null?!1:a(this,O,Cf).call(this,i,e).size===this.txs.length}findTxid(t){return this.synchronizeNestedTransactionMutations(),a(this,O,Oo).call(this,t)}makeTxidOnly(t){let e=a(this,O,Ga).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,Ya).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,Oo).call(this,ir(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,o0).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,Ro).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,Za).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,Ro).call(this,a(this,O,c0).call(this,s.paths,s.validateCombined));return e}mergeRawTx(t,e){return this.synchronizeNestedTransactionMutations(),a(this,O,Nn).call(this,!0),a(this,O,Za).call(this,t,e)}mergeTransaction(t){return this.synchronizeNestedTransactionMutations(),a(this,O,Nn).call(this,!0),a(this,O,Df).call(this,t)}removeExistingTxid(t){let e=a(this,O,Ga).call(this).get(t);e!==void 0&&(this.txs.splice(e,1),a(this,O,gr).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,Ro).call(this,i);for(let i of e.txs)a(this,O,h0).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,p0).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,g0).call(this,r,t)||!a(this,O,m0).call(this,r,e)||!a(this,O,b0).call(this)||!a(this,O,y0).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,To).call(this))}toUint8Array(){return new Uint8Array(a(this,O,To).call(this))}toBinaryAtomic(t){return Array.from(a(this,O,_f).call(this,t))}toUint8ArrayAtomic(t){return new Uint8Array(a(this,O,_f).call(this,t))}toHex(){let t=a(this,O,To).call(this);if(w(this,Qn)!=null)return w(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 yn(i),c=t.readVarIntNumStrict(!1);for(let l=0;l<c;l++){let d=Ei.fromReader(t,!1);o.bumps.push(d)}let u=t.readVarIntNumStrict(!1);for(let l=0;l<u;l++){let d=Xe.fromReader(t,i);o.txs.push(d)}return o.atomicTxid=r,t instanceof bt&&(N(o,je,t.bin.subarray(s,t.pos)),a(f=o,O,Xa).call(f)),o}static fromBinary(t){return yn.fromReader(new bt(Uint8Array.from(t)))}static fromBinaryStrict(t){return yn.fromBinaryView(Uint8Array.from(t))}static fromBinaryView(t){let e=new bt(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),w(this,De)!=null&&a(this,O,x0).call(this))return a(this,O,Ja).call(this,w(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,I0).call(this,s,e);s=u;let f=a(this,O,S0).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,gr).call(this);let l={missingInputs:Object.keys(c),notValid:f.map(d=>d.txid),valid:Object.keys(t),withMissingInputs:o.map(d=>d.txid),txidOnly:r.map(d=>d.txid)};return N(this,De,l),a(this,O,Hf).call(this),a(this,O,Ja).call(this,l)}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,Jn,void 0),N(t,Ln,w(this,Ln)),N(t,De,w(this,De)==null?void 0:a(this,O,Ja).call(this,w(this,De))),w(t,De)!=null&&a(e=t,O,Hf).call(e),N(t,Qn,w(this,Qn)),N(t,je,w(this,je)),w(t,je)!=null&&a(i=t,O,Xa).call(i),t}trimKnownTxids(t){let e=a(this,O,k0).call(this,new Set(t));e=a(this,O,T0).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()}
|
|
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,O,O0).call(this,t,e)}};Bn=new WeakMap,_n=new WeakMap,Cn=new WeakMap,Jn=new WeakMap,je=new WeakMap,Qn=new WeakMap,mr=new WeakMap,es=new WeakMap,br=new WeakMap,ns=new WeakMap,is=new WeakMap,rs=new WeakMap,yr=new WeakMap,wr=new WeakMap,Ln=new WeakMap,De=new WeakMap,Un=new WeakMap,O=new WeakSet,Jr=function(){N(this,je,void 0),N(this,Qn,void 0),w(this,mr).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,yr,void 0)},Xa=function(){N(this,is,this.version),N(this,rs,a(this,O,Nf).call(this)),N(this,yr,Array.from(this.bumps)),a(this,O,ja).call(this)},Nf=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}))},Bf=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},ja=function(){N(this,wr,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}))}))})))},Yp=function(t,e){return e.ref===t&&e.offset===t.offset&&e.hash===t.hash&&e.txid===t.txid&&e.duplicate===t.duplicate},Zp=function(t,e){return e.ref===t&&e.leaves.length===t.length&&t.every((i,r)=>a(this,O,Yp).call(this,i,e.leaves[r]))},Jp=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,Zp).call(this,i,e.levels[r]))},Qp=function(){return w(this,wr)?.length!==this.bumps.length?!1:this.bumps.every((t,e)=>a(this,O,Jp).call(this,t,w(this,wr)[e]))},Rn=function(){if(w(this,wr)==null){a(this,O,ja).call(this);return}a(this,O,Qp).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,Mf).call(this),a(this,O,ja).call(this))},t0=function(){if(w(this,je)==null||w(this,is)!==this.version||!a(this,O,Bf).call(this,w(this,rs))||w(this,yr)?.length!==this.bumps.length)return!1;for(let t=0;t<this.bumps.length;t++)if(w(this,yr)[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)},e0=function(){for(let t of this.txs)t.txid},n0=function(){w(this,Ln)&&this.sortTxs()},To=function(){if(this.synchronizeNestedTransactionMutations(),a(this,O,Rn).call(this),a(this,O,t0).call(this)&&w(this,je)!=null)return w(this,je);a(this,O,Jr).call(this),a(this,O,e0).call(this),a(this,O,n0).call(this);let t=new ht;return this.toWriter(t),N(this,je,t.toUint8Array()),a(this,O,Xa).call(this),w(this,je)},i0=function(t){let e=a(this,O,Po).call(this),i=e.get(t);if(i==null)throw new Error(`${t} does not exist in this Beef`);let r=a(this,O,Cf).call(this,i,e),s=a(this,O,r0).call(this,r);return s.sortTxs(),s},_f=function(t){var u;this.synchronizeNestedTransactionMutations(),a(this,O,Rn).call(this),w(this,ns)===this.version&&a(this,O,Bf).call(this,w(this,es))&&w(this,br)?.length===this.bumps.length&&this.bumps.every((f,l)=>w(this,br)?.[l]===f)||w(this,mr).clear();let i=w(this,mr).get(t);if(i!=null)return i;let r=a(u=a(this,O,i0).call(this,t),O,To).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),w(this,mr).set(t,o),N(this,es,a(this,O,Nf).call(this)),N(this,br,Array.from(this.bumps)),N(this,ns,this.version),o},Cf=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,Lf).call(this,s)||s.isTxidOnly)))for(let o of s.inputTxids){let c=e.get(o);c!=null&&r.push(c)}}return i},Lf=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},r0=function(t){let e=new yn(this.version),i=new Map;for(let r of this.txs)!t.has(r)||!a(this,O,Lf).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},Oo=function(t){return a(this,O,Po).call(this).get(t)},Po=function(){return(w(this,Bn)==null||w(this,_n)==null)&&a(this,O,gr).call(this),w(this,Bn)},Ga=function(){return(w(this,_n)==null||w(this,Bn)==null)&&a(this,O,gr).call(this),w(this,_n)},gr=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];w(this,Bn).set(e.txid,e),w(this,_n).set(e.txid,t)}},Qr=function(t,e=this.txs.length-1){w(this,Bn)?.set(t.txid,t),w(this,_n)?.set(t.txid,e)},Uf=function(t){let e=a(this,O,Ga).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))},Ya=function(){if(w(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"&&w(this,Jn).set(e.hash,t)}return w(this,Jn)},s0=function(){if(w(this,Cn)==null){N(this,Cn,new Map);for(let t=0;t<this.bumps.length;t++){let e=this.bumps[t],i=w(this,Cn).get(e.blockHeight)??[];i.push(t),w(this,Cn).set(e.blockHeight,i)}}return w(this,Cn)},Mf=function(){N(this,Cn,void 0),N(this,Jn,void 0)},o0=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,a0).call(this,c),c.sourceTransaction!=null&&i.push(c.sourceTransaction)}},a0=function(t){if(t.sourceTransaction==null){let e=a(this,O,Oo).call(this,ir(t.sourceTXID,"sourceTXID must be valid"));e!=null&&(t.sourceTransaction=e.tx)}},c0=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++)ow(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},Ro=function(t){let e=a(this,O,u0).call(this,t),i=this.bumps[e],r=a(this,O,Po).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,f0).call(this,o,i,e)}return e},u0=function(t){let e=a(this,O,s0).call(this),i=a(this,O,Ya).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),Gp(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),Gp(t,s,i),s},f0=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}},Za=function(t,e){let i=new Xe(t,e);return a(this,O,Uf).call(this,i),a(this,O,ts).call(this,i),i},d0=function(t){let e=t.merklePath==null?void 0:a(this,O,Ro).call(this,t.merklePath),i=new Xe(t,e);return a(this,O,Uf).call(this,i),a(this,O,ts).call(this,i),i},l0=function(t,e){for(let i=t.inputs.length-1;i>=0;i--){let r=t.inputs[i].sourceTransaction;r!=null&&e.push(r)}},Df=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,d0).call(this,o);c===e&&(s=u),u.bumpIndex===void 0&&a(this,O,l0).call(this,o,r)}if(s==null)throw new Error("Failed to merge root transaction");return s},h0=function(t){let e=a(this,O,Oo).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,Df).call(this,t._tx):t._rawTx!=null&&(e==null||e.isTxidOnly)&&(e=a(this,O,Za).call(this,t._rawTx)),e==null)throw new Error(`Failed to merge BeefTx for txid: ${t.txid}`);return e},p0=function(){let t=new Set;for(let e of this.txs){if(t.has(e.txid))return!0;t.add(e.txid)}return!1},g0=function(t,e){for(let i of this.txs)if(i.isTxidOnly){if(e!==!0)return!1;t[i.txid]=!0}return!0},m0=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,w0).call(this,i,r.hash,e)))return!1;return!0},b0=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},y0=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},w0=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,Ya).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},Hf=function(){N(this,Un,this.txs.map(t=>({ref:t,txid:t.txid,bumpIndex:t.bumpIndex,isTxidOnly:t.isTxidOnly,inputTxids:[...t.inputTxids]})))},x0=function(){if(w(this,Un)?.length!==this.txs.length)return!1;for(let t=0;t<this.txs.length;t++){let e=this.txs[t],i=w(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},Ja=function(t){return{missingInputs:[...t.missingInputs],notValid:[...t.notValid],valid:[...t.valid],withMissingInputs:[...t.withMissingInputs],txidOnly:[...t.txidOnly]}},I0=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}},S0=function(t,e,i){let{indegree:r,dependents:s,originalIndex:o,round:c}=a(this,O,v0).call(this,t,e),u=a(this,O,A0).call(this,t,r,s,o,c);return a(this,O,E0).call(this,t,u,c,e,i),t.filter(f=>!u.has(f.txid))},v0=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 l of u.inputTxids)if(!e[l]&&(f++,i.has(l))){let d=s.get(l)??[];d.push(u),s.set(l,d)}r.set(u.txid,f),c.set(u.txid,0)}return{indegree:r,dependents:s,originalIndex:o,round:c}},A0=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 l=(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,l));let d=(e.get(f.txid)??0)-1;e.set(f.txid,d),d===0&&o.push(f)}}return c},E0=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)},k0=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,gr).call(this),i},T0=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,Mf).call(this),!0},O0=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 xr=yn,P0=xr;var as=256*1024*1024,H0=21e14,uw=64,$f=1e6,cs=Array.isArray,rn=Array,Gf=Number,Yf=String,fw=Number.isFinite,dw=Number.isInteger,lw=Number.isSafeInteger,$0=Object.is,Co=Object.create,hw=Object.defineProperty,$t=Object.getOwnPropertyDescriptor,R0=Object.getOwnPropertyDescriptors,Zf=Object.getPrototypeOf,_o=Object.keys,Zt=Reflect.apply,Uo=Reflect.ownKeys,pw=RegExp.prototype.exec,gw=RegExp.prototype.test,mw=String.prototype.toLowerCase,q0=Uint8Array,Jf=Uint8Array.prototype,rc=Zf(Jf),N0=$t(rc,"buffer")?.get,ec=$t(rc,"length")?.get,B0=$t(rc,Symbol.toStringTag)?.get,bw=Jf.set,_0=typeof SharedArrayBuffer>"u"?void 0:$t(SharedArrayBuffer.prototype,"byteLength")?.get,yw=WeakMap.prototype.get,ww=WeakMap.prototype.set,Ff=WeakSet.prototype.add,xw=WeakSet.prototype.delete,F0=WeakSet.prototype.has,Wf=new WeakSet,Iw=me.prototype.toHex,Vf,Kf,zf,W0=/^(?:0|[1-9]\d*)$/,Sw=/^([0-9a-f]{64})\.(0|[1-9]\d*)$/i,vw=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Aw=/^(?:[0-9a-f]{2})*$/i,Ew=/^[0-9a-f]{64}$/i;function kw(){let n=[Array.prototype,Map.prototype,Set.prototype,WeakMap.prototype,WeakSet.prototype,Object,Object.prototype,Number,RegExp.prototype,String.prototype,Jf,rc],t=new rn(n.length);for(let e=0;e<n.length;e++){let i=n[e],r=Uo(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 Bo(n){for(let t=0;t<n.length;t++){let e=n[t];if(Uo(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||!$0(s.value,r.value)||s.get!==r.get||s.set!==r.set)throw new Error(`Wallet callback modified shared JavaScript intrinsics (${t}:${Yf(e.keys[i])})`)}}}function nc(n,t){return $t(n,t)!==void 0}function Ti(n){return lw(n)}function Lo(n,t){return Zt(gw,n,[t])}function Sr(n){return Zt(mw,n,[])}function us(n){return Zt(Iw,n,[])}function Tw(){Vf??(Vf=Me.fromAtomicBEEF),Kf??(Kf=Me.prototype.id),zf??(zf=Me.prototype.toAtomicBEEF)}function qf(n){if(Vf==null)throw new Error("Transaction intrinsics are unavailable");return Zt(Vf,Me,[n])}function Ow(n){if(zf==null)throw new Error("Transaction intrinsics are unavailable");return Zt(zf,n,[!0])}function V0(n){if(Kf==null)throw new Error("Transaction intrinsics are unavailable");return Zt(Kf,n,["hex"])}function C0(n,t){return Zt(F0,n.active,[t])}function Pw(n,t){Zt(Ff,n.active,[t])}function L0(n,t){Zt(xw,n.active,[t])}function Rw(n,t){return Zt(yw,n.completed,[t])}function Qa(n,t,e){Zt(ww,n.completed,[t,e])}function ki(n,t,e=!1){if(n==null||typeof n!="object"||cs(n))throw new Error(`${t} must be a plain data object`);let i=Zf(n);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain data object`);let r=Uo(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 K0(n,t,e=as){if(Zf(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>as)throw new Error(`${t} exceeds the byte limit`);if(Uo(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,Yf(u));if(f==null||!f.enumerable||!("value"in f))throw new Error(`${t} must contain only dense data arrays`);if(!dw(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=as){if(N0==null||ec==null||B0==null)return;let i,r,s;try{i=Zt(N0,n,[]),r=Zt(ec,n,[]),s=Zt(B0,n,[])}catch{return}if(s!=="Uint8Array")return;if(_0!=null){let c=!1;try{Zt(_0,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 q0(r);try{Zt(bw,o,[n])}catch{throw new Error(`${t} must contain only intrinsic byte arrays`)}return o}function Ir(n,t,e=0,i={nodes:0,active:new WeakSet,completed:new WeakMap,copiedBytes:0},r=!1){if(e>uw)throw new Error(`${t} exceeds the depth limit`);if(i.nodes+=1,i.nodes>$f)throw new Error(`${t} exceeds the node limit`);if(n==null||typeof n=="string"||typeof n=="boolean")return n;if(typeof n=="number"){if(!fw(n)||$0(n,-0))throw new Error(`${t} contains an ambiguous number`);return n}if(typeof n!="object")throw new Error(`${t} contains unsupported data`);if(C0(i,n))throw new Error(`${t} contains a cycle`);let s=Rw(i,n);if(s!==void 0)return s;let o=z0(n,t,as-i.copiedBytes);if(o!==void 0)return i.copiedBytes+=o.length,Zt(Ff,Wf,[o]),Qa(i,n,o),o;if(cs(n)){let d=K0(n,t,as-i.copiedBytes);if(d!==void 0)return i.copiedBytes+=d.length,Zt(Ff,Wf,[d]),Qa(i,n,d),d;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>$f)throw new Error(`${t} exceeds the node limit`)}if(Pw(i,n),cs(n)){let d=R0(n),p=d.length;if(p==null||!("value"in p)||!Ti(p.value)||p.value<0||p.value>$f)throw new Error(`${t} must contain only dense data arrays`);let m=p.value,g=Uo(d);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"||!Lo(W0,C)||Gf(C)>=m))throw new Error(`${t} must contain only dense data arrays`)}let y=new rn(m);for(let S=0;S<m;S++){let C=Yf(S),E=d[C];if(E==null||!E.enumerable||!("value"in E))throw new Error(`${t} must contain only dense data arrays`);y[S]=Ir(E.value,`${t}[${S}]`,e+1,i)}return L0(i,n),Qa(i,n,y),y}let c=ki(n,t,r);if(C0(i,c)&&c!==n)throw new Error(`${t} contains a cycle`);let u=Co(null),f=R0(c),l=_o(f);for(let d=0;d<l.length;d++){let p=l[d],m=f[p];if(!m.enumerable||!("value"in m))throw new Error(`${t} must contain only string-keyed data properties`);hw(u,p,{value:Ir(m.value,`${t}.${p}`,e+1,i),enumerable:!0,configurable:!0,writable:!0})}return L0(i,n),Qa(i,n,u),u}function U0(n,t){if(n!=null&&typeof n=="object"){let r=Zt(F0,Wf,[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&&ec!=null){let o;try{o=Zt(ec,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(!cs(n))throw new Error(`${t} must be a bounded non-empty byte array`);let e=K0(n,t);if(e==null||e.length===0)throw new Error(`${t} must be a bounded non-empty byte array`);let i=new q0(e.length);for(let r=0;r<e.length;r++)i[r]=e[r];return i}function tc(n,t){if(typeof n!="string"||!Lo(Ew,n))throw new Error(`${t} must be a 32-byte hexadecimal transaction ID`);return Sr(n)}function ic(n,t){if(typeof n!="string"||!Lo(Aw,n))throw new Error(`${t} must be an even-length hexadecimal string`);return Sr(n)}function Xf(n,t){if(typeof n!="string")throw new Error(`${t} must be a canonical outpoint`);let e=Zt(pw,Sw,[n]);if(e==null)throw new Error(`${t} must be a canonical outpoint`);let i=Gf(e[2]);if(!Ti(i)||i>4294967295)throw new Error(`${t} must be a canonical outpoint`);return`${Sr(e[1])}.${i}`}function jf(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:V0(e.sourceTransaction);if(e.sourceTXID!==void 0&&i!==void 0&&tc(e.sourceTXID,"Wallet input source TXID")!==tc(i,"Wallet input source transaction ID"))throw new Error("Wallet transaction input source mismatch");return`${tc(e.sourceTXID??i,"Wallet input source TXID")}.${e.sourceOutputIndex}`}function os(n,t){if(typeof n!="number"||!Ti(n)||n<0||n>H0)throw new Error(`${t} must be a valid satoshi amount`);return n}function ss(n,t,e){let i=n+t;if(!Ti(i)||i>H0)throw new Error(`${e} exceeds the maximum transaction value`);return i}function M0(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 Nw(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=Co(null);for(let A=0;A<t.inputs.length;A++){let k=jf(t,A);if(nc(s,k))throw new Error("Wallet transaction contains a duplicate input outpoint");r[A]=k,s[k]=!0}let o=[],c=Co(null);for(let A=0;A<(n.inputs?.length??0);A++){let k=n.inputs[A],B=Xf(k.outpoint,`Requested input ${A} outpoint`);if(nc(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:Sr(us($)))!==ic(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:Sr(us(k.lockingScript))}}let f=new rn(u.length),l=n.options?.randomizeOutputs===!1,d=0,p=(A,k)=>{let B=n.outputs[A],_=ic(B.lockingScript,`Requested output ${A} locking script`),$=os(B.satoshis,`Requested output ${A}`);if(l){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,d=ss(d,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,d=ss(d,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 m=0,g=new rn(t.inputs.length);for(let A=0;A<o.length;A++){let k=o[A];g[k]=!0,m=ss(m,i?.[A]??M0(t,k),"Requested input value")}let y=0;for(let A=0;A<t.inputs.length;A++)g[A]!==!0&&(y=ss(y,M0(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(m,y,"Wallet input value");if(S>C)throw new Error("Wallet signable transaction spends more than its inputs");if(S-d>y)throw new Error("Wallet used a requested input to fund an unrequested output");return o}function D0(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(jf(n,e)!==jf(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 Bw(n,t,e){try{await n.abortAction({reference:t},e)}catch{}}async function X0(n,t,e={},i,r){Tw();let s=kw(),o=Ir(t,"Create action arguments"),c=Ir(o,"Create action arguments"),u=o.inputs??[],f;if(r!==void 0){let I=Ir(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 l=ki(e,"Bound action options"),d=_o(l);for(let I=0;I<d.length;I++){let U=d[I];if(U!=="inputSigners"&&U!=="outputSatoshisRanges")throw new Error(`Unknown bound action option "${U}"`)}let p=$t(l,"inputSigners")?.value,m=ki(p??{},"Input signers"),g=Co(null),y=0,S=_o(m);for(let I=0;I<S.length;I++){let U=S[I],M=$t(m,U)?.value,F=Xf(U,"Input signer outpoint");if(nc(g,F)||typeof M!="function")throw new Error("Input signers must uniquely identify requested outpoints");g[F]=M,y++}let C=$t(l,"outputSatoshisRanges")?.value,E=ki(C??{},"Output satoshi ranges"),A=new rn(o.outputs?.length??0),k=_o(E);for(let I=0;I<k.length;I++){let U=k[I],M=$t(E,U)?.value;if(!Lo(W0,U))throw new Error("Output satoshi ranges must identify requested output indexes");let F=Gf(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=_o(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);Bo(s);let _=ki(Ir(B,"Wallet createAction result",0,void 0,!0),"Wallet createAction result",!0);Bo(s);let $=ki($t(_,"signableTransaction")?.value,"Wallet signable transaction"),R=$t($,"reference")?.value;if(typeof R!="string"||R.length===0||R.length>4096||!Lo(vw,R))throw new Error("Wallet signable transaction reference is invalid");try{let I=qf(U0($t($,"tx")?.value,"Wallet signable transaction")),U=Nw(o,I,A,f),M=qf(Ow(I)),F={},it=new rn(I.inputs.length),ot=new rn,q=Co(null),z=0;for(let ke=0;ke<u.length;ke++){let xe=u[ke],vn=Xf(xe.outpoint,`Requested input ${ke} outpoint`),H=U[ke];if(xe.unlockingScript!==void 0){it[H]=ic(xe.unlockingScript,`Requested input ${ke} unlocking script`),ot[ot.length]=H;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,H);Bo(s),D0(M,I);let V=ic(typeof D=="string"?D:us(D),`Requested input ${ke} signed unlocking script`);F[H]={unlockingScript:V},it[H]=V,ot[ot.length]=H,nc(q,vn)||(q[vn]=!0,z++)}if(z!==y)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);Bo(s);let ce=ki(Ir(It,"Wallet signAction result",0,void 0,!0),"Wallet signAction result",!0);Bo(s);let Bt=qf(U0($t(ce,"tx")?.value,"Wallet signed transaction"));D0(I,Bt);for(let ke=0;ke<ot.length;ke++){let xe=ot[ke],vn=it[xe],H=Bt.inputs[xe]?.unlockingScript;if(H==null||Sr(us(H))!==vn)throw new Error("Wallet signed transaction substituted an authorized unlocking script")}let dn=$t(ce,"txid")?.value;if(dn!==void 0&&tc(dn,"Wallet signed transaction ID")!==Sr(V0(Bt)))throw new Error("Wallet signed transaction ID does not match its transaction data");return Bt}catch(I){throw await Bw(n,R,i),I}}var Mo=class extends Error{constructor(e){super(`Transaction evidence: ${e}`);b(this,"code");this.code=e,this.name="TransactionEvidenceError"}};var PI=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 j0(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 Mo("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 _w=new WeakMap;function G0(n){return _w.get(n)}function Y0(n,t){return{supportsMemoryLimit:t.supportsMemoryLimit,shouldVerifyScripts:t.shouldVerifyScripts===void 0?void 0:e=>{n.check();let i=j0(e),r=t.shouldVerifyScripts(e);if(n.check(),j0(e)!==i)throw new Mo("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 Z0=Symbol(),J0=Symbol();function Xp(n){return n[Z0]()}function jp(n,t){n[J0](t)}var Cw=943816,Q0=21e14,Lw=1e6;function sn(n,t){if(typeof n!="number"||!Number.isSafeInteger(n)||n<0||n>Q0)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>Q0)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 Qf(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 Ar,ti,Ri,Er,Ni,Ho,ds,j,tg,eg,Mn,Do,td,wn,ed,sc,nd,ng,ig,rg,sg,og,ag,cg,vr,ug,id,fg,dg,lg,hg,oc,pg,gg,Pi,ac,mg,bg,yg,wg,xg,Ig,Sg,vg,Ag,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,Ar);G(this,ti);G(this,Ri);G(this,Er);G(this,Ni);G(this,Ho);G(this,ds);this.version=t,this.inputs=e,this.outputs=i,this.lockTime=r,this.metadata=s,this.merklePath=o}getSignatureHashCache(){return w(this,Ho)??{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,tg).call(this,r.tx,e,t);continue}a(this,j,eg).call(this,r.tx,e,t,i)}}}static fromBEEF(t,e){var r;let{tx:i}=a(r=oe,Mn,Do).call(r,t,e);return i}static fromBEEFView(t,e){var r;let{tx:i}=a(r=oe,Mn,Do).call(r,t,e,!0);return i}static fromAtomicBEEF(t){var s;let{tx:e,txid:i,beef:r}=a(s=oe,Mn,Do).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,Do).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 l=nt(e.readReverse(32)),d=e.readUInt32LE();if(d>Lw)throw new RangeError("EF source output index exceeds the allocation limit");let p=e.readVarIntNumStrict(!1),m=e.read(p),g=Ue.fromBinary(m),y=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:d+1}).fill(null),k.outputs[d]={satoshis:S,lockingScript:A},s.push({sourceTransaction:k,sourceTXID:l,sourceOutputIndex:d,unlockingScript:g,sequence:y})}let o=e.readVarIntNumStrict(!1),c=[];for(let f=0;f<o;f++){let l=e.readUInt64LEBn().toNumber(),d=e.readVarIntNumStrict(!1),p=e.read(d),m=Le.fromBinary(p);c.push({satoshis:l,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,td).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,td).call(r,e,!0);if(!e.eof())throw new Error("Serialized transaction contains trailing data");return N(i,Ri,t),a(s=i,j,sc).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,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 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=So.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,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],l=[...s.inputs],d=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,ac).call(E,i,l,d,p,m))throw new Error("Fee model mutated its transaction snapshot");let y=a(A=r,j,ng).call(A,g);if(y<0)throw new RangeError("Transaction inputs are insufficient for the requested outputs and fee.");if(!a(this,j,ac).call(this,i,o,c,u,f))throw new Error("Transaction changed while computing its fee; no change was applied");if(y===0){this.outputs=f.filter(B=>B.change!==!0),a(this,j,wn).call(this);return}a(k=r,j,ig).call(k,y,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 l=this.outputs[f];if(l.satoshis===void 0)throw l.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(l.satoshis,`Output ${f} amount`)}a(this,j,oc).call(this,this);for(let f=0;f<this.inputs.length;f++){let l=this.inputs[f];if(Ge(l.sourceOutputIndex,`Input ${f} sourceOutputIndex`),Ge(l.sequence??4294967295,`Input ${f} sequence`),l.sourceTXID!==void 0&&Oi(l.sourceTXID,`Input ${f} sourceTXID`),l.sourceTransaction!==void 0){let d=l.sourceTransaction.outputs[l.sourceOutputIndex];if(d==null)throw new RangeError(`Input ${f} references a source output that does not exist.`);if(sn(d.satoshis,`Input ${f} source amount`),l.sourceTXID!==void 0&&(l.sourceTransaction.inputs.length>0||l.sourceTransaction.merklePath!=null)&&Oi(l.sourceTXID,`Input ${f} sourceTXID`)!==l.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,l)=>{var y;if(c&&f.unlockingScript!=null)return new Ue([],Uint8Array.from(f.unlockingScript.toUint8Array()),void 0,!1);let d=s[l];if(d===void 0)return;let p=a(y=e,j,Pi).call(y,!0);for(let S=0;S<s.length;S++)p.inputs[S].unlockingScriptTemplate=s[S];N(p,Ho,{hashOutputsSingle:new Map});let m=await d.sign(p,l);if(m==null||typeof m.toUint8Array!="function")throw new TypeError(`Input ${l} signing template returned an invalid unlocking script`);let g=m.toUint8Array();if(!(g instanceof Uint8Array))throw new TypeError(`Input ${l} signing template returned an invalid unlocking script`);return new Ue([],Uint8Array.from(g),void 0,!1)})),!a(this,j,ac).call(this,e,i,r,s,o))throw new Error("Transaction changed while signing; no unlocking scripts were applied");for(let f=0,l=this.inputs.length;f<l;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=Fp()){let e=a(this,j,Pi).call(this),i=e.id("hex");return Rp(await t.broadcast(e),i)}[Z0](){return a(this,j,vr).call(this)}[J0](t){N(this,ti,t)}toBinary(){return Array.from(a(this,j,vr).call(this))}toUint8Array(){return Uint8Array.from(a(this,j,vr).call(this))}toEF(){return Array.from(a(this,j,id).call(this))}toEFUint8Array(){return this.toEFBinary()}toEFBinary(){return Uint8Array.from(a(this,j,id).call(this))}toHexEF(){return nt(this.toEFBinary())}toHex(){let t=a(this,j,vr).call(this);if(w(this,Ni)!=null)return w(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,vr).call(this);return w(this,Ar)??N(this,Ar,zt(e)),t==="hex"?nt(w(this,Ar)):Array.from(w(this,Ar))}id(t){if(a(this,j,vr).call(this),t==="hex"&&w(this,ti)!=null)return w(this,ti);let e=[...this.hash()];return e.reverse(),t==="hex"?(N(this,ti,nt(e)),w(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:G0(this);return await a(o=a(this,j,Pi).call(this),j,bg).call(o,t,e,i,r,s)}writeSerializedBEEF(t,e){this.materializeSourceTXIDs(),t.writeUInt32LE(4022206465);let{bumps:i,txs:r}=a(this,j,yg).call(this,e);t.writeVarIntNum(i.length);let s=a(this,j,Sg).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,vg).call(this,c,u);f.options=r;let l={};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;l[g]=async(y,S)=>await m.sign(y,S)}let d=await X0(t,f,{inputSigners:l},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=d.version,this.inputs=d.inputs,this.outputs=d.outputs,this.lockTime=d.lockTime,this.merklePath=d.merklePath,a(this,j,wn).call(this),this.metadata={...this.metadata,...d.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=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 l=sn(f.satoshis,"Source output amount"),d=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:l,transactionVersion:this.version,otherInputs:[],allInputs:this.inputs,inputIndex:t,outputs:this.outputs,inputSequence:d,subscript:p,lockTime:this.lockTime,scope:e})}};Ar=new WeakMap,ti=new WeakMap,Ri=new WeakMap,Er=new WeakMap,Ni=new WeakMap,Ho=new WeakMap,ds=new WeakMap,j=new WeakSet,tg=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)},eg=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,Do=function(t,e,i=!1){let r=i&&t instanceof Uint8Array?xr.fromBinaryView(t):xr.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}},td=function(t,e){let i=t.readUInt32LE(),r=t.readVarIntNumStrict(!1),s=[];for(let f=0;f<r;f++){let l=nt(t.readReverse(32)),d=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),y=t.readUInt32LE();s.push({sourceTXID:l,sourceOutputIndex:d,unlockingScript:g,sequence:y})}let o=t.readVarIntNumStrict(!1),c=[];for(let f=0;f<o;f++){let l=t.readUInt64LEBn().toNumber(),d=t.readVarIntNumStrict(!1),p=e&&t instanceof bt?t.readView(d):t.read(d),m=e&&p instanceof Uint8Array?Le.fromBinaryView(p):Le.fromBinary(p);c.push({satoshis:l,lockingScript:m})}let u=t.readUInt32LE();return new oe(i,s,c,u)},wn=function(){N(this,Ar,void 0),N(this,ti,void 0),N(this,Ri,void 0),N(this,Er,void 0),N(this,Ni,void 0),N(this,ds,void 0)},ed=function(t){return t.sourceTXID==null?t.sourceTransaction?.id("hex"):void 0},sc=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,ed).call(this,t),sourceOutputIndex:t.sourceOutputIndex,sequence:t.sequence,unlockingScript:t.unlockingScript,unlockingScriptBytes:t.unlockingScript==null?void 0:dr(t.unlockingScript),sourceOutput:e,sourceSatoshis:e?.satoshis,sourceLockingScript:e?.lockingScript,sourceLockingScriptBytes:e==null?void 0:dr(e.lockingScript)}}),outputs:this.outputs.map(t=>({ref:t,satoshis:t.satoshis,lockingScript:t.lockingScript,lockingScriptBytes:dr(t.lockingScript)}))})},nd=function(){let t=w(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,ed).call(this,i)||r.sourceOutputIndex!==i.sourceOutputIndex||r.sequence!==i.sequence||r.unlockingScript!==i.unlockingScript||r.unlockingScriptBytes!==(i.unlockingScript==null?void 0:dr(i.unlockingScript))||r.sourceOutput!==s||r.sourceSatoshis!==s?.satoshis||r.sourceLockingScript!==s?.lockingScript||r.sourceLockingScriptBytes!==(s==null?void 0:dr(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!==dr(i.lockingScript))return!1}return!0},ng=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},ig=function(t,e){let i=this.outputs.filter(r=>r.change===!0);i.length!==0&&(e==="random"?a(this,j,rg).call(this,t,i):a(this,j,sg).call(this,t,i))},rg=function(t,e){let i=t;for(let r=0;r<e.length-1;r++){let s=a(this,j,og).call(this,0,i);e[r].satoshis=s,i-=s}e.at(-1).satoshis=i},sg=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},og=function(t,e){let i=Pe(1)[0]%9+1;return Math.floor(t+(e-t)*Math.log10(1+1/i)/Math.log10(10))},ag=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)},cg=function(){let t=new ht;return a(this,j,ag).call(this,t),t.toUint8Array()},vr=function(){return(w(this,Ri)==null||!a(this,j,nd).call(this))&&(a(this,j,wn).call(this),N(this,Ri,a(this,j,cg).call(this)),a(this,j,sc).call(this)),w(this,Ri)},ug=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)},id=function(){if(w(this,Er)==null||!a(this,j,nd).call(this)){a(this,j,wn).call(this);let t=new ht;a(this,j,ug).call(this,t),N(this,Er,t.toUint8Array()),a(this,j,sc).call(this)}return w(this,Er)},fg=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()}`)},dg=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,oc).call(this,t)},lg=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))},hg=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,l=f.outputs[u.sourceOutputIndex];if(l==null)throw new RangeError(`Verification failed because input ${c} of transaction ${i()} references a source output that does not exist.`);s=fs(s,sn(l.satoshis,`Input ${c} source amount`),"Transaction input total");let d=f.id("hex");if(!r.scriptsOnly&&u.sourceTXID!==void 0&&Oi(u.sourceTXID,`Input ${c} sourceTXID`)!==d)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,lg).call(this,f,p,r),u.sourceTXID??(u.sourceTXID=p),!e&&!new yo({sourceTXID:u.sourceTXID,sourceOutputIndex:u.sourceOutputIndex,lockingScript:l.lockingScript,sourceSatoshis:l.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}},oc=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},pg=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")}`)},gg=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},ac=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||!Qf(c.unlockingScript?.toUint8Array(),u.unlockingScript?.toUint8Array()))return!1;let f=c.sourceTransaction?.outputs[c.sourceOutputIndex],l=u.sourceTransaction?.outputs[u.sourceOutputIndex];if(f==null||l==null){if(f!==l)return!1}else if(!Object.is(f.satoshis,l.satoshis)||!Qf(f.lockingScript.toUint8Array(),l.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||!Qf(c.lockingScript.toUint8Array(),u.lockingScript.toUint8Array()))return!1}return!0},mg=async function(t,e,i){let{feeModel:r,memoryLimit:s,selectedVerifier:o,verifierQueue:c}=i;a(this,j,dg).call(this,t,e),await this.verifyTransactionFee(t,r,e);let u={tx:t,blockHeight:Cw,consensus:!0,...s===void 0?{}:{memoryLimit:s}},f=o!==void 0&&(s===void 0||o.supportsMemoryLimit===!0)&&(o.shouldVerifyScripts?.(u)??!0),l=p=>a(this,j,hg).call(this,t,p,e,i),d=!f&&i.scriptWork!==void 0?i.scriptWork.work.inputs(i.scriptWork,u,l):l(f);return!d.valid||(f&&c.push(u),a(this,j,oc).call(this,t)>d.inputTotal)?!1:(i.scriptsOnly?i.verifiedTransactions.add(t):i.verifiedTxids.add(e()),!0)},bg=async function(t,e,i,r,s){let o=t==="scripts only",c=r??Ua(),u=s!==void 0&&c!==void 0?Y0(s,c):c;o||this.materializeSourceTXIDs();let f=new Set,l=new Set,d=[this],p=new Set;o||p.add(this.id("hex"));let m=new Set(d),g=[],y={scriptsOnly:o,memoryLimit:i,txQueue:d,queuedTransactions:m,queuedTxids:p,verifiedTransactions:l,verifiedTxids:f,feeModel:e,selectedVerifier:u,verifierQueue:g,scriptWork:s},S=0;for(;S<d.length;){let C=d[S++],E,A=()=>(E??(E=C.id("hex")),E);if(!a(this,j,gg).call(this,C,A,y)&&!await a(this,j,fg).call(this,C,o,t,A,l,f)&&!await a(this,j,mg).call(this,C,A,y))return!1}return await a(this,j,pg).call(this,g,u),!0},yg=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,wg).call(this,f.tx,o,s,e,i,r);continue}a(this,j,xg).call(this,f.tx,t,c,u)}}return{bumps:e,txs:s}},wg=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,Ig).call(this,t.merklePath,r,s,o)),e.add(c),i.push(u)},xg=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!")}},Ig=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},Sg=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},vg=async function(t,e){let i={description:t,inputs:[],outputs:[],lockTime:this.lockTime,version:this.version};this.materializeSourceTXIDs();let r=new xr;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,Ag).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},Ag=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 Eg=globalThis.Buffer,rd=typeof Eg?.compare=="function"?Eg.compare:void 0,cc=globalThis.SharedArrayBuffer,Uw=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||rd==null||cc!=null&&t.buffer instanceof cc||rd(t,e.bytes)!==0))return e.value}set(t,e){t instanceof Uint8Array&&t.length<=Uw&&rd!=null&&!(cc!=null&&t.buffer instanceof cc)&&(this.cached={bytes:new Uint8Array(t),value:e})}};var Dn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",kg="0123456789abcdef";function Ye(n){let t="";for(let e=0;e<n.length;e++){let i=n[e];t+=kg[i>>4]+kg[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 Tg(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 uc(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,sd=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 Mw=4294967295;function fc(n,t){return Math.floor(n/2**t)}function Dw(n){return n%2===0?n+1:n-1}function kr(n,t){return Ye(zt(ls((n??"")+(t??"")).reverse()).reverse())}function od(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,l=od(n,u,f,i,r,s);if(l?.hash==null||l.hash===""){r.set(o,void 0);return}let d=od(n,u,f+1,i,r,s);if(d?.hash==null){if(d?.duplicate===!0||n.length===1&&f===fc(s,u))return c={offset:e,hash:kr(l.hash,l.hash)},r.set(o,c),c;r.set(o,void 0);return}return c={offset:e,hash:d.duplicate===!0?kr(l.hash,l.hash):kr(d.hash,l.hash)},r.set(o,c),c}function Hw(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 l=fc(o,f),d=`${f}:${l}`,p=r.get(d);if(p!==void 0){if(p!==u)throw new Error("Mismatched roots");let y=r.get(`${c}:0`);if(y===void 0)throw new Error("Mismatched roots");return y}r.set(d,u);let m=Dw(l),g=od(n,f,m,e,i,s);if(g==null){if(n.length===1&&l===fc(s,f)){u=kr(u,u);continue}throw new Error(`Missing hash for index ${o} at height ${f}`)}g.duplicate===!0?u=kr(u,u):u=m%2===1?kr(g.hash,u):kr(u,g.hash)}return r.set(`${c}:0`,u),u}function $w(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 l=0;l<f;l++){let d=n.readVarInt(),p=n.readUInt8();e[u].push((p&1)===1?{offset:d,duplicate:!0}:{offset:d,hash:Ye(n.read(32).reverse())})}e[u].sort((l,d)=>l.offset-d.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,l=fc(Mw,u);for(let d of e[u]){if(!Number.isSafeInteger(d.offset)||d.offset<0||d.offset>l)throw new Error("Invalid Merkle Path offset");if(f.has(d.offset))throw new Error("Duplicate Merkle Path offset");f.add(d.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=Hw(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 Og(n){let t=n.pos,e=n.readUInt32LE(),i=n.readVarInt(),r=[],s=new Set;for(let d=0;d<i;d++){let p=Ye(n.readReverse(32));s.add(p);let m=n.readUInt32LE(),g=n.readVarInt(),y=n.readView(g),S=n.readUInt32LE();r.push({sourceTXID:p,sourceOutputIndex:m,unlockingScript:y,sequence:S})}let o=n.readVarInt(),c=[];for(let d=0;d<o;d++){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),l=Ye(zt(f).reverse());return{txid:l,transaction:{txid:l,version:e,inputs:r,outputs:c,lockTime:u},inputTxids:Array.from(s),txidOnly:!1}}function qw(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{...Og(n),bumpIndex:s}}let e=Og(n),i=n.readUInt8()===0?void 0:n.readVarInt();return{...e,bumpIndex:i}}function Pg(n){let t=new sd(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($w(t));let o=t.readVarInt(),c=[];for(let u=0;u<o;u++)c.push(qw(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}=Pg(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 $o(n,t=!1){let{atomicTxid:e,bumps:i,entries:r}=Pg(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 d=s.get(f.sourceTXID)?.transaction?.outputs[f.sourceOutputIndex];d!==void 0&&(f.sourceSatoshis=d.satoshis)}return o.transaction}var ps=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,Fw=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;function Ww(n,t){let e=1n;for(;t>0n;)(t&1n)!==0n&&(e=e*n%ps),n=n*n%ps,t>>=1n;return e}function dc(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=Ww(e,ps+1n>>2n);return i*i%ps===e}function Vw(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=Vw(n,t,i);if(s===0n||s>=Fw)return!1;t+=i}return t===n.length}var Ci=4294967295,ad=1e5,xn=1e3,Rg=100,Ng=32,Bg=new Bi,_g=new Bi;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>ad)return wt(t,`an object with at most ${ad} 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=ad){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 Lg(n){let t=Ne(n,"sendWith",xn).map((e,i)=>Ui(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 bs(n,t,e){return n===void 0?e:typeof n!="boolean"?wt(t,"a boolean"):n}function He(n,t){let e=Ui(n,t,66,66);return dc(e)?e:wt(t,"a valid compressed secp256k1 public key")}function cd(n,t){return n==="self"||n==="anyone"?n:He(n,t)}function ud(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=ae(n[1],`${t}[1]`,5,400);return[e,i]}function Li(n,t=!0){let e=bs(n.privileged,"privileged",!1),i=Or(n.privilegedReason,"privilegedReason",5,50);e&&i===void 0&&wt("privilegedReason","a value when 'privileged' is true"),t&&bs(n.seekPermission,"seekPermission",!0)}function Tr(n,t="args"){let e=gt(n,t);ud(e.protocolID),ae(e.keyID,"keyID",1,800),e.counterparty!==void 0&&cd(e.counterparty,"counterparty"),Li(e)}function Ug(n){let t=bc(n,"outpoint"),[e,i]=t.split(".");return{txid:e,vout:Number(i)}}function ni(n,t="value"){return bs(n,t,!0)}function be(n,t="value"){return bs(n,t,!1)}function Or(n,t,e,i){if(n!==void 0)return ae(n,t,e,i)}function Kw(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 zw(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=Ie(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 Xw(n){if(n!==void 0)return lc(n)}function lc(n){return ld(n,"basket",1,300)}function fd(n){return ld(n,"label",1,300)}function dd(n){return ld(n,"tag",1,300)}function ld(n,t,e,i){if(typeof n!="string")throw new ut(t,"a string");n=n.trim().toLowerCase();let r=Ie(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 Cg(n,t,e,i){if(n!==void 0)return on(n,t,e,i)}function ms(n){throw new ut(n,"valid base64 string")}function jw(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)&&ms(t),e++)}return e}function Gw(n,t,e){t>2&&ms(e),t>0&&n.length%4!==0&&ms(e);let i=n.length%4;i!==0&&i!==4-t&&ms(e)}function Yw(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"&&ms(t),n=n.trim(),n.length===0&&ms(t);let r=jw(n,t);Gw(n,r,t);let s=n.length-r,o=Math.floor(s*3/4);return Yw(o,t,e,i),n}function Zw(n,t,e,i){if(n!==void 0)return Ui(n,t,e,i)}var Jw=/^[0-9a-f]+$/,Qw=/^[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=Jw.test(n);if(!r&&!Qw.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 Mg(n,t){let e=Ui(n,t);return gs(ls(e))?e:wt(t,"a canonical DER-encoded ECDSA signature")}function tx(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=Zw(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:Ug(n.outpoint),inputDescription:ae(n.inputDescription,"inputDescription",5,2e3),unlockingScript:t,unlockingScriptLength:e,sequenceNumber:ee(n.sequenceNumber,"sequenceNumber",Ci,0,Ci)}}function ex(n){return gt(n,"output"),{lockingScript:Ui(n.lockingScript,"lockingScript"),satoshis:Kw(n.satoshis,"satoshis"),outputDescription:ae(n.outputDescription,"outputDescription",5,2e3),basket:Xw(n.basket),customInstructions:Or(n.customInstructions,"customInstructions"),tags:Ne(n.tags,"tags").map(e=>dd(e))}}function nx(n){n!==void 0&>(n,"options");let t=n??{};return t.trustSelf!==void 0&&t.trustSelf!=="known"&&wt("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=>Ug(i)),sendWith:Lg(t.sendWith),randomizeOutputs:ni(t.randomizeOutputs,"randomizeOutputs")}}function hc(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=>tx(r)),outputs:Ne(n.outputs,"outputs").map(r=>ex(r)),lockTime:ee(n.lockTime,"lockTime",0,0,Ci),version:ee(n.version,"version",1,0,Ci),labels:Ne(n.labels,"labels").map(r=>fd(r)),options:nx(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&&Bg.get(e.inputBEEF)!==!0)try{hs(e.inputBEEF),Bg.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(lx),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 ix(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:Lg(t.sendWith)}}function pc(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,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:ix(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 gc(n){return gt(n,"args"),{reference:on(n.reference,"reference")}}function rx(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 sx(n){return n===void 0?void 0:(gt(n,"insertionRemittance"),{basket:lc(n.basket),customInstructions:Or(n.customInstructions,"customInstructions",0,1e3),tags:Ne(n.tags,"tags").map(e=>dd(e))})}function ox(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:zw(n.outputIndex,"outputIndex"),protocol:n.protocol,paymentRemittance:rx(n.paymentRemittance),insertionRemittance:sx(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 mc(n){gt(n,"args");let t={tx:$n(n.tx,"tx"),outputs:Ne(n.outputs,"outputs").map(e=>ox(e)),description:ae(n.description,"description",5,2e3),labels:Ne(n.labels,"labels").map(e=>fd(e)),seekPermission:ni(n.seekPermission,"seekPermission")};if(_g.get(t.tx)!==!0)try{$o(t.tx),_g.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 ax(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=Ui(e[1],`${t} txid`,64,64),r=ee(Number(e[2]),`${t} vout`,void 0,0,Ci);return`${i}.${r}`}function yc(n){return gt(n,"args"),{basket:lc(n.basket),output:bc(n.output,"output")}}function wc(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 xc(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:Or(n.privilegedReason,"privilegedReason",5,50),partial:void 0}}function hd(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 cx(n,t){return n==="certifier"?n:He(n,t)}function ux(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 Ic(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:fx(n.certifierUrl),fields:hd(n.fields),privileged:be(n.privileged,"privileged"),privilegedReason:Or(n.privilegedReason,"privilegedReason",5,50),subject:""}}function fx(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 Sc(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:bc(n.revocationOutpoint,"revocationOutpoint"),fields:hd(n.fields),signature:Mg(n.signature,"signature"),keyringRevealer:cx(n.keyringRevealer,"keyringRevealer"),keyringForSubject:ux(n.keyringForSubject,"keyringForSubject"),privileged:be(n.privileged,"privileged"),privilegedReason:Or(n.privilegedReason,"privilegedReason",5,50),subject:""}}function vc(n){gt(n,"args"),gt(n.certificate,"certificate"),Li(n,!1),n.certificate.fields!==void 0&&hd(n.certificate.fields);let t={type:Cg(n.certificate.type,"certificate.type",32,32),serialNumber:Cg(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:ax(n.certificate.revocationOutpoint,"certificate.revocationOutpoint"),signature:n.certificate.signature===void 0?void 0:Mg(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:Or(n.privilegedReason,"privilegedReason",5,50)};return t.fieldsToReveal.length>Rg&&wt("fieldsToReveal",`at most ${Rg} fields`),new Set(t.fieldsToReveal).size!==t.fieldsToReveal.length&&wt("fieldsToReveal","unique field names"),t}function Ac(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 dx(n){let t=gt(n,"attributes"),e=Object.keys(t);(e.length<1||e.length>Ng)&&wt("attributes",`an object containing 1-${Ng} fields`);for(let i of e)ae(i,`field name ${i}`,1,50),ae(t[i],`attributes.${i}`,1,500);return n}function Ec(n){return gt(n,"args"),{attributes:dx(n.attributes),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0,0),seekPermission:ni(n.seekPermission,"seekPermission")}}function kc(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:lc(n.basket),tags:Ne(n.tags,"tags").map(i=>dd(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 Tc(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=>fd(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 Oc(n){let t=gt(n,"args");if(t.identityKey!==void 0&&t.identityKey!==!0&&wt("identityKey","true or undefined"),t.forSelf!==void 0&&bs(t.forSelf,"forSelf",!1),t.identityKey===!0){t.protocolID!==void 0&&ud(t.protocolID),t.keyID!==void 0&&ae(t.keyID,"keyID",1,800),t.counterparty!==void 0&&cd(t.counterparty,"counterparty"),Li(t);return}Tr(n,"args")}function Pc(n){let t=gt(n,"args");He(t.counterparty,"counterparty"),He(t.verifier,"verifier"),Li(t,!1)}function Rc(n){let t=gt(n,"args");cd(t.counterparty,"counterparty"),He(t.verifier,"verifier"),ud(t.protocolID),ae(t.keyID,"keyID",1,800),Li(t,!1)}function Nc(n){let t=gt(n,"args");Tr(n),$n(t.plaintext,"plaintext")}function Bc(n){let t=gt(n,"args");Tr(n),$n(t.ciphertext,"ciphertext")}function _c(n){let t=gt(n,"args");Tr(n),$n(t.data,"data")}function Cc(n){let t=gt(n,"args");Tr(n),$n(t.data,"data"),$n(t.hmac,"hmac",32)}function Dg(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 Lc(n){let t=gt(n,"args");Tr(n),Dg(t,"data","hashToDirectlySign")}function Uc(n){let t=gt(n,"args");Tr(n),Dg(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&&bs(t.forSelf,"forSelf",!1)}function Mc(n){let t=gt(n,"args");ee(t.height,"height",void 0,1,Ci)}function Mi(n,t="args"){gt(n,t)}var lx="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";var Dc;(function(n){n[n.Silent=0]="Silent",n[n.App=1]="App",n[n.Counterparty=2]="Counterparty"})(Dc||(Dc={}));var hx=Object.prototype.hasOwnProperty,px=new Set(["BEEF","atomicBEEF","beef","ciphertext","competingBeef","data","encryptedLinkage","encryptedLinkageProof","hashToDirectlySign","hashToDirectlyVerify","hmac","inputBEEF","payload","plaintext","signature","transaction","tx"]);function Hc(n){return n==null||typeof n!="object"||typeof ArrayBuffer>"u"?!1:ArrayBuffer.isView(n)&&Object.prototype.toString.call(n)==="[object Uint8Array]"}function Hg(n){return Number.isInteger(n)&&n>=0&&n<=255}function gx(n){return n!=null&&typeof n=="object"&&typeof ArrayBuffer<"u"&&(ArrayBuffer.isView(n)||Object.prototype.toString.call(n)==="[object ArrayBuffer]")}function mx(n){for(let t=0;t<n.length;t++)if(!hx.call(n,t)||!Hg(n[t]))return;return n}function bx(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(!Hg(r))return;e.push(r)}return e}catch{return}}function pd(n){if(Hc(n))return n;if(!gx(n))return Array.isArray(n)?mx(n):bx(n)}function yx(n,t){let e=this==null?void 0:this[n];return Hc(e)?Array.from(e):Hc(t)?Array.from(t):t}function ys(n,t){let e=JSON.stringify(n,yx,t);if(e===void 0)throw new TypeError("BRC-100 JSON payload is not serializable");return e}function wx(n,t,e,i){let r=pd(e);r!=null?n[t]=r:i(e)}function $c(n){let t=new WeakSet,e=[n];for(;e.length>0;){let i=e.pop();if(!(i==null||typeof i!="object"||Hc(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))px.has(r)?wx(i,r,s,o=>e.push(o)):e.push(s)}}return n}var xx=Number,Ix=String,Sx=Uint8Array,vx=URL,Ax=Array.prototype,Ex=Array.isArray,kx=Date.parse,Tx=Number.MAX_SAFE_INTEGER,Ox=Number.isFinite,Wc=Number.isInteger,Rr=Number.isSafeInteger,im=Object.prototype,Px=Object.prototype.hasOwnProperty,Di=Object.create,Vc=Object.defineProperty,rm=Object.freeze,we=Object.getOwnPropertyDescriptor,Kc=Object.getPrototypeOf,Sn=Object.keys,Br=Reflect.ownKeys,Rx=RegExp.prototype.exec,Nx=RegExp.prototype.test,sm=String.prototype.split,Bx=String.prototype.toLowerCase,_x=String.prototype.trim,Id=String.prototype.replace,Cx=String.prototype.normalize,Lx=String.prototype.indexOf,Ux=String.prototype.slice,Mx=String.prototype.startsWith,Dx=RegExp,$g=we(URL.prototype,"protocol")?.get,Sd=Kc(Uint8Array.prototype),qg=we(Sd,"buffer")?.get,Fg=we(Sd,"length")?.get,Wg=we(Sd,Symbol.toStringTag)?.get,Hx=Uint8Array.prototype.set,Vg=typeof SharedArrayBuffer>"u"?void 0:we(SharedArrayBuffer.prototype,"byteLength")?.get,Kg=Map,cn=Set,zg=WeakMap,$x=WeakSet,qx=Map.prototype.get,Fx=Map.prototype.set,Wx=Map.prototype.has,Vx=Map.prototype.forEach,Kx=Set.prototype.add,zx=Set.prototype.has,Xx=we(Set.prototype,"size").get,jx=WeakMap.prototype.get,Gx=WeakMap.prototype.set,Yx=WeakSet.prototype.add,Zx=WeakSet.prototype.has,Pt=Reflect.apply;function qt(n){return Ex(n)}function In(n){return xx(n)}function Be(n){return Ix(n)}function jt(n){return Pt(Bx,n,[])}function vd(n,t){return Pt(sm,n,[t])}function xs(n,t){return Pt(Nx,n,[t])}function Nr(n,t){return Pt(Rx,n,[t])}function zc(n,t){return Pt(Px,n,[t])}function Vo(n){if(!(qg==null||Fg==null||Wg==null))try{return{buffer:Pt(qg,n,[]),length:Pt(Fg,n,[]),tag:Pt(Wg,n,[])}}catch{return}}function yd(n){return Vo(n)?.tag==="Uint8Array"}function Jx(n){if(Vg==null)return!1;try{return Pt(Vg,n,[]),!0}catch{return!1}}function Pr(n,t){return Pt(qx,n,[t])}function gd(n,t,e){Pt(Fx,n,[t,e])}function Qx(n,t){return Pt(Wx,n,[t])}function t2(n,t){Pt(Vx,n,[t])}function Gt(n,t){Pt(Kx,n,[t])}function un(n,t){return Pt(zx,n,[t])}function Xc(n){return Pt(Xx,n,[])}function Xg(n,t){return Pt(jx,n,[t])}function qo(n,t,e){Pt(Gx,n,[t,e])}function md(n,t){Pt(Yx,n,[t])}function jg(n,t){return Pt(Zx,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 Yc=new cn;Gt(Yc,"unproven");Gt(Yc,"sending");Gt(Yc,"failed");var ws=1e6,Gg=ws+2,e2=16*1024*1024,n2="0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",Yg=new Bi,Ad=Symbol("createActionSourceEvidence"),Ko=Symbol("byteBudgetExceeded"),Fo=new $x,jc=rm(Di(null));function om(n){if(!qt(n))return;let t=we(n,"length");if(t==null||!("value"in t)||!Rr(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(Br(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=we(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 Zg(n){let t=At(n);if(t==null)return;let e=Di(null),i=Br(t);for(let r=0;r<i.length;r++){let s=i[r];if(typeof s!="string")continue;let o=we(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?om(n[s]):n[s]}return i}function am(n){let t=At(n);if(t==null)return jc;let e=we(t,Ad)?.value;if(e!=null)return e;let i=t.inputBEEF,r=t.inputs;if(i===void 0||!qt(r)||r.length===0)return jc;let s=ri(i,"createAction","request.inputBEEF"),o;try{o=hs(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],l=At(f);if(l==null||typeof l.outpoint!="string")continue;let d=Nr(/^([0-9a-fA-F]{64})\.(0|[1-9]\d*)$/,l.outpoint);if(d==null)continue;let p=In(d[2]);if(p>4294967295)continue;let m=jt(d[1]),g=Pr(o.transactions,m)?.outputs[p];g!==void 0&&(c[`${m}.${p}`]=g.satoshis)}return rm(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 Vc(r,Ad,{value:am(e),writable:!1,configurable:!1,enumerable:!1}),r}case"signAction":{let r=At(e.spends),s=Di(null);if(r!=null){let o=Sn(r);for(let c=0;c<o.length;c++){let u=o[c],f=r[u],l=At(f);s[u]=l==null?f:Ze(l,["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:Zg(e.fields)};case"proveCertificate":return{fieldsToReveal:om(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:Zg(r.fields)}})()};default:return t}}function L(n,t,e){throw new Error(`Invalid ${n} result ${t}: expected ${e}`)}function cm(n){let t=we(n,"length");return t!=null&&"value"in t&&Rr(t.value)&&t.value>=0?t.value:void 0}function um(n,t,e,i=e){if(t>e)return;let r=Br(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"||!Wc(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=we(n,Be(o));if(c==null||c.enumerable!==!0||!("value"in c)||!Wc(c.value)||c.value<0||c.value>255)return;s!==void 0&&(s[o]=c.value)}return s??Ko}function i2(n,t,e){let i=Kc(n);if(i!==im&&i!==null)return;let r=Br(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=we(n,c);if(u==null||u.enumerable!==!0||!("value"in u)||!Wc(u.value)||u.value<0||u.value>255)return;s!==void 0&&(s[o]=u.value)}return s??Ko}function r2(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 fm(n,t,e){let i=Vo(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 Sx(s);try{Pt(Hx,o,[n])}catch{L(t,"byte array","an intrinsic Uint8Array")}return o}function Ed(n,t,e=!1){let i=[],r=new zg,s=new zg,o=0,c=0,u=(l,d)=>{if(l==null||typeof l!="object")return typeof l=="function"&&L(t,"value","data without functions"),l;if(!qt(l)&&!yd(l)&&e&&r2(d)){let y=Xg(s,l);if(y!==void 0)return y;let S=i2(l,268435456,268435456-c);if(S===Ko&&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,md(Fo,S),qo(s,l,S),S}let p=Xg(r,l);if(p!==void 0)return p;if(o++,o>ws&&L(t,"object graph","a bounded result"),yd(l)){let y=fm(l,t,268435456-c);return c+=Vo(y).length,md(Fo,y),qo(r,l,y),y}if(qt(l)){Kc(l)!==Ax&&L(t,"array prototype","the intrinsic Array.prototype");let S=cm(l);S===void 0&&L(t,"array length","an own integer data property");let C=um(l,S,268435456,268435456-c);if(C===Ko&&L(t,"byte arrays",`at most ${268435456} total bytes`),C!==void 0)return c+=C.length,md(Fo,C),qo(r,l,C),C;S>ws&&L(t,"array length",`at most ${ws} entries`);let E=[];return E.length=S,qo(r,l,E),i[i.length]={source:l,target:E,array:!0},E}let m=Kc(l);m!==null&&m!==im&&L(t,"object prototype","Object.prototype or null");let g=m===null?Di(null):{};return qo(r,l,g),i[i.length]={source:l,target:g,array:!1},g},f=u(n);for(;i.length>0;){let l=i[i.length-1];i.length-=1;let d=Br(l.source);if(l.array){o+=d.length,o>Gg&&L(t,"object graph","a bounded result");let p=l.source,m=l.target.length;d.length!==m+1&&L(t,"array shape","a dense standard array without extra properties");for(let g=0;g<d.length;g++){let y=d[g];if(typeof y!="string"&&L(t,"array key","a string"),gn(y)&&L(t,`array key ${y}`,"a safe array key"),y!=="length"){let C=In(y);(!Wc(C)||C<0||C>=m||Be(C)!==y)&&L(t,`array key ${y}`,"a canonical in-range array index")}let S=we(p,y);(S==null||!("value"in S))&&L(t,`array property ${y}`,"a data property"),y!=="length"&&Vc(l.target,y,{value:u(S.value),enumerable:S.enumerable,configurable:!0,writable:!0})}continue}o+=d.length,o>Gg&&L(t,"object graph","a bounded result");for(let p=0;p<d.length;p++){let m=d[p];typeof m!="string"&&L(t,"object key","a string"),gn(m)&&L(t,`object key ${m}`,"a safe record key");let g=we(l.source,m);(g==null||!("value"in g))&&L(t,`object property ${m}`,"a data property"),Vc(l.target,m,{value:u(g.value,m),enumerable:g.enumerable,configurable:!0,writable:!0})}}return f}function dm(n,t){return Ed(n,t)}function lm(n,t){return Ed(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=Br(n);for(let s=0;s<r.length;s++){let o=r[s];typeof o!="string"&&L(t,`${e} key`,"a string");let c=we(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"&&yd(n)){let c=jg(Fo,n)?n:fm(n,t,268435456);Vo(c).length<=r&&(s=c)}else if(qt(n)){let c=cm(n);if(c===void 0&&L(t,e,"an own integer array length"),c>r&&L(t,e,`at most ${r} bytes`),jg(Fo,n))s=n;else{let u=um(n,c,r);u===Ko&&L(t,e,`at most ${r} bytes`),s=u}}s==null&&L(t,e,"an array of bytes");let o=qt(s)?s.length:Vo(s).length;return o>r&&L(t,e,`at most ${r} bytes`),i!==void 0&&o!==i&&L(t,e,`${i} bytes`),s}function ye(n,t,e,i=0,r){typeof n!="string"&&L(t,e,"a string");let s=Ie(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=ye(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 zo(n,t,e){let i=$e(n,t,e,33);dc(i)||L(t,e,"a valid compressed secp256k1 public key")}function ne(n,t,e,i=4294967295){return(!Rr(n)||n<0||n>i)&&L(t,e,`an integer from 0 to ${i}`),n}function kd(n,t,e,i,r){return(!Rr(n)||n<i||n>r)&&L(t,e,`an integer from ${i} to ${r}`),n}function qc(n,t,e){n[e]!==!0&&L(t,e,"true")}function hm(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 Gc(n,t,e,i,r){let s=qn(n,t,e);if(s!=null)for(let o=0;o<s.length;o++)ye(s[o],t,`${e}[${o}]`,i,r)}function s2(n,t,e){let i=ye(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=kx(i);Ox(r)||L(t,e,"a valid ISO timestamp")}function o2(n,t,e,i){let r=ye(n,t,e,1,i);try{let s=new vx(r);if($g==null)throw new Error;let o=Pt($g,s,[]);if(o!=="https:"&&o!=="http:")throw new Error}catch{L(t,e,"an absolute HTTP(S) URL")}}function a2(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(Yc,o.status)||L(t,`${s}.status`,"a supported status")}}}function pm(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 Jg(n,t,e,i,r){let s=At(e);if(s==null){wd(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 Kg;for(let y=0;y<n.inputs.length;y++){let S=pm(n,y,t,`tx.inputs[${y}]`);Qx(u,S)&&L(t,`tx.inputs[${y}]`,"a unique transaction input outpoint"),gd(u,S,y)}let f=s.inputs===void 0?[]:qn(s.inputs,t,"request.inputs"),l=new cn;for(let y=0;y<f.length;y++){let S=f[y],C=`request.inputs[${y}]`,E=qe(S,t,C),A=Is(E.outpoint,t,`${C}.outpoint`),k=`${A.txid}.${A.outputIndex}`;un(l,k)&&L(t,`${C}.outpoint`,"a unique requested input"),Gt(l,k);let B=Pr(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 d=s.outputs===void 0?[]:qn(s.outputs,t,"request.outputs"),m=At(s.options)?.randomizeOutputs===!1,g=new Kg;for(let y=0;y<n.outputs.length;y++){let S=n.outputs[y],C=ne(S.satoshis,t,`tx.outputs[${y}].satoshis`,21e14);if(d.length>0){let E=`${C}:${jt(Ye(S.lockingScript))}`;gd(g,E,(Pr(g,E)??0)+1)}}for(let y=0;y<d.length;y++){let S=d[y],C=`request.outputs[${y}]`,E=qe(S,t,C),A=ne(E.satoshis,t,`${C}.satoshis`,21e14),k=jt($e(E.lockingScript,t,`${C}.lockingScript`));if(m){let $=n.outputs[y];($==null||$.satoshis!==A||jt(Ye($.lockingScript))!==k)&&L(t,`tx.outputs[${y}]`,"the requested output at the requested position");continue}let B=`${A}:${k}`,_=Pr(g,B)??0;_===0&&L(t,"tx.outputs","every requested output with its requested amount and script"),gd(g,B,_-1)}wd(n,t,i,r)}function wd(n,t,e=jc,i=!1){let r=0,s=!1,o=new cn;for(let u=0;u<n.inputs.length;u++){let f=n.inputs[u],l=pm(n,u,t,`tx.inputs[${u}]`);un(o,l)&&L(t,`tx.inputs[${u}]`,"a unique transaction input outpoint"),Gt(o,l);let d=f.sourceSatoshis??e[l];if(d===void 0){i||L(t,`tx.inputs[${u}].sourceSatoshis`,"source transaction evidence for every completed transaction input"),s=!0;continue}r+=ne(d,t,`tx.inputs[${u}].sourceSatoshis`,21e14),(!Rr(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),(!Rr(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 c2(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),l=n.inputs[f];(!Rr(f)||l==null)&&L(t,`tx.inputs[${o}]`,"the requested input index");let d=qe(c,t,u),p=jt($e(d.unlockingScript,t,`${u}.unlockingScript`));jt(Ye(l.unlockingScript))!==p&&L(t,`tx.inputs[${f}]`,"the requested unlocking script"),d.sequenceNumber!==void 0&&l.sequence!==ne(d.sequenceNumber,t,`${u}.sequenceNumber`)&&L(t,`tx.inputs[${f}].sequence`,"the requested input sequence")}}function u2(n,t,e){let i=t==="createAction"?am(e):jc,r=n.txid===void 0?void 0:$e(n.txid,t,"txid",32),s=n.tx===void 0?void 0:Qg(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}]`);a2(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=Qg(g.tx,t,"signableTransaction.tx"),Td(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"),y=f.outputs===void 0?[]:qn(f.outputs,t,"request.outputs"),S=At(f.options),C=qt(S?.sendWith)?S.sendWith:[],E=g.length>0||y.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&&Jg(s,t,e,i,!1),u!==void 0&&Jg(u,t,e,i,!0)):s!==void 0&&(c2(s,t,e),wd(s,t));let l=u?.txid,d=r??l;if(c!=null){d===void 0&&L(t,"noSendChange","associated with a transaction");for(let g=0;g<c.length;g++){let y=c[g];an(vd(Be(y),".")[0],d)||L(t,`noSendChange[${g}]`,"an outpoint of the returned transaction")}}let p=At(At(e)?.options),m=new cn;if(d!==void 0&&Gt(m,jt(d)),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 y=0;y<n.sendWithResults.length;y++){let S=n.sendWithResults[y],C=`sendWithResults[${y}].txid`,E=jt(Be(qe(S,t,`sendWithResults[${y}]`).txid));un(g,E)&&L(t,C,"a unique transaction"),Gt(g,E),Xc(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 Qg(n,t,e,i){let r=ri(n,t,e),s=i===void 0?Yg.get(r):void 0;if(s!=null)return s;try{let o=$o(r);return i===void 0&&Yg.set(r,o),o}catch{}try{return $o(r,!0)}catch{}try{let o=hs(r),c=i===void 0?void 0:jt(i),u;t2(o.transactions,(d,p)=>{d!==void 0&&(u=p)});let f=(c!==void 0&&Pr(o.transactions,c)!==void 0?c:void 0)??o.atomicTxid??u,l=f===void 0?void 0:Pr(o.transactions,jt(f));if(l===void 0)throw new Error("BEEF subject transaction is missing");return l}catch{L(t,e,"a complete, exactly framed BEEF transaction")}}function f2(n,t,e){let i=ri(n,t,e);try{return hs(i)}catch{L(t,e,"a complete, exactly framed BEEF envelope")}}function Is(n,t,e){let i=ye(n,t,e),r=Nr(/^([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 Td(n,t,e){let i=ye(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 Fc(n){return n<253?1:n<=65535?3:n<=4294967295?5:9}function Wo(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=Ie(c).length;(f<1||f>50||gn(c))&&L(t,`${e} key`,"a safe 1\u201350 byte field name"),i?Td(u,t,`${e}.${c}`):ye(u,t,`${e}.${c}`)}return r}function xd(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 y=s[g],S=Td(i[y],t,`${e}.${y}`),C=uc(S);if(C.length!==32||Tg(C)!==S)throw new Error;r+=C.length}let o=["subject","certifier"];for(let g=0;g<o.length;g++){let y=o[g];zo(i[y],t,`${e}.${y}`),r+=33}let c=ye(i.revocationOutpoint,t,`${e}.revocationOutpoint`),u=vd(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+Fc(In(f));let l=Wo(i.fields,t,`${e}.fields`),d=Sn(l);for(let g=1;g<d.length;g++){let y=d[g],S=g;for(;S>0&&d[S-1]>y;)d[S]=d[S-1],S--;d[S]=y}r+=Fc(d.length);for(let g=0;g<d.length;g++){let y=d[g],S=Ie(y),C=Ie(l[y]);r+=Fc(S.length)+S.length+Fc(C.length)+C.length}let p=$e(i.signature,t,`${e}.signature`),m=ls(p);if(!gs(m))throw new Error;if(r+=m.length,r>e2)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=Br(t);for(let r=0;r<i.length;r++){let s=i[r],o=we(t,s);if(s===Ad){if(o==null||!("value"in o))throw new Error("Wallet result request records must contain only data properties");Vc(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 Zc(n){let t=Pt(Id,n,[/\s+/g," "]);return Pt(_x,t,[])}function tm(n){let t=Pt(Cx,n,["NFD"]);return jt(Pt(Id,t,[/\p{Mn}/gu,""]))}function gm(n,t){return Pt(Lx,n,[t])!==-1}function mm(n,t){let e=vd(Zc(t)," "),i=Pt(sm,n,[/\r\n?|\n|\u2028|\u2029/]),r=0;for(;r<i.length;){let s=0,o=0;for(;o<e.length;){let c=Pt(Id,e[o],[/[.*+?^${}()|[\]\\]/g,String.raw`\$&`]),u=new Dx(c,"gi");u.lastIndex=s;let f=Nr(u,i[r]);if(f==null)break;s=f.index+f[0].length,o++}if(o===e.length)return!0;r++}return!1}var d2=" 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 bm(n){let t=[],e=/(?:[^\p{Dash}\p{Pattern_Syntax}\p{Quotation_Mark}\p{Terminal_Punctuation}\p{White_Space}]|')+/gu,i=Nr(e,n);for(;i!=null;)gm(d2,` ${i[0]} `)||(t[t.length]=i[0]),i=Nr(e,n);return t}function l2(n,t){let e=0;for(;e<n.length;)if(n[e++]===t)return!0;return!1}function h2(n,t,e,i){let r=Pt(Mx,e,["-"])&&e.length>1;if(i!==void 0){let u=gm(t,i);if(r?u:!u)return-1;if(r)return 0}let s=bm(i??(r?Pt(Ux,e,[1]):e)),o=!1,c=0;for(;c<s.length;){let u=l2(n,s[c++]);if(r&&u)return-1;o=o||u}return o&&!r?1:0}function p2(n,t){let e=tm(n),i=tm(t),r=bm(e),s=/-?"([^"]*)"|[^\s"]+/g,o=!1,c=Nr(s,i);for(;c!=null;){let u=h2(r,e,c[0],c[1]);if(u===-1)return!1;u===1&&(o=!0),c=Nr(s,i)}return o}function g2(n){return n!=="profilePhoto"&&n!=="icon"}function m2(n,t){if(typeof t!="string")return!1;let e=Zc(t);if(e.length<2)return!1;let i=Sn(n),r="",s=0;for(;s<i.length;){let o=i[s++];if(!g2(o))continue;let c=n[o];r=r.length>0?`${r} ${c}`:c}return e.length===2?mm(r,e):p2(r,e)}function b2(n,t,e){return typeof t!="string"?!1:n==="userName"?t===Zc(e):mm(t,e)}function y2(n,t,e,i){let r=At(i);if(r==null)return;if(zc(r,"any")){m2(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"),Zc(f).length!==0&&(o++,(!zc(e,u)||!b2(u,e[u],f))&&L(n,`${t}.decryptedFields.${u}`,"the requested public attribute"))}o===0&&L(n,`${t}.decryptedFields`,"a usable requested attribute")}function w2(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 x2(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(!zc(e,c)||e[c]!==i[c])return!1}return!0}function I2(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(!zc(e,s[o]))return!1;o++}return!0}function em(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&&!w2(n.revocationOutpoint,s.revocationOutpoint,e,`${i}.revocationOutpoint`)&&L(e,`${i}.revocationOutpoint`,"the requested certificate revocation outpoint"),s.fields!==void 0&&!(r?x2(n.fields,s.fields):I2(n.fields,s.fields))&&L(e,`${i}.fields`,"the requested certificate fields")}function S2(n,t,e){let i=Od(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}]`,l=xd(u,t,f);if(s!=null&&Xc(s)>0&&(un(s,jt(Be(l.certifier)))||L(t,`${f}.certifier`,"one of the requested certifiers")),o!=null&&Xc(o)>0&&(un(o,Be(l.type))||L(t,`${f}.type`,"one of the requested types")),t==="discoverByIdentityKey"&&r?.identityKey!==void 0&&!an(l.subject,r.identityKey)&&L(t,`${f}.subject`,"the requested identity key"),l.keyring!==void 0&&Wo(l.keyring,t,`${f}.keyring`,!0),l.verifier!==void 0&&zo(l.verifier,t,`${f}.verifier`),t==="discoverByIdentityKey"||t==="discoverByAttributes"){let d=`${f}.certifierInfo`,p=qe(l.certifierInfo,t,d);ye(p.name,t,`${d}.name`,1,100),o2(p.iconUrl,t,`${d}.iconUrl`,500),ye(p.description,t,`${d}.description`,5,50),kd(p.trust,t,`${d}.trust`,1,10),Wo(l.publiclyRevealedKeyring,t,`${f}.publiclyRevealedKeyring`,!0);let m=Wo(l.decryptedFields,t,`${f}.decryptedFields`);t==="discoverByAttributes"&&y2(t,f,m,r?.attributes)}}}function Od(n,t,e,i,r){let s=ne(n[e],t,e,Tx),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){ye(n,t,e,n===""?0:5,2e3)}function v2(n,t,e){let i=Od(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}]`,l=qe(u,t,f);if($e(l.txid,t,`${f}.txid`,32),kd(l.satoshis,t,`${f}.satoshis`,-21e14,21e14),un(si,l.status)||L(t,`${f}.status`,"a supported action status"),typeof l.isOutgoing!="boolean"&&L(t,`${f}.isOutgoing`,"a boolean"),bd(l.description,t,`${f}.description`),Gc(l.labels,t,`${f}.labels`,1,300),r?.includeLabels===!0&&l.labels===void 0&&L(t,`${f}.labels`,"the explicitly requested labels"),s.length>0&&qt(l.labels)){let m=new cn;for(let y=0;y<l.labels.length;y++)Gt(m,l.labels[y]);let g=o==="all";for(let y=0;y<s.length;y++){let S=un(m,s[y]);if(o==="all"&&!S){g=!1;break}if(o==="any"&&S){g=!0;break}}g||L(t,`${f}.labels`,"the requested label query")}ne(l.version,t,`${f}.version`),ne(l.lockTime,t,`${f}.lockTime`);let d=qn(l.inputs,t,`${f}.inputs`);if((r?.includeInputs===!0||r?.includeInputSourceLockingScripts===!0||r?.includeInputUnlockingScripts===!0)&&d===void 0&&L(t,`${f}.inputs`,"the explicitly requested inputs"),d!=null)for(let m=0;m<d.length;m++){let g=d[m],y=`${f}.inputs[${m}]`,S=qe(g,t,y);Is(S.sourceOutpoint,t,`${y}.sourceOutpoint`),ne(S.sourceSatoshis,t,`${y}.sourceSatoshis`,21e14),S.sourceLockingScript!==void 0&&$e(S.sourceLockingScript,t,`${y}.sourceLockingScript`),S.unlockingScript!==void 0&&$e(S.unlockingScript,t,`${y}.unlockingScript`),r?.includeInputSourceLockingScripts===!0&&S.sourceLockingScript===void 0&&L(t,`${y}.sourceLockingScript`,"the explicitly requested source locking script"),r?.includeInputUnlockingScripts===!0&&S.unlockingScript===void 0&&L(t,`${y}.unlockingScript`,"the explicitly requested unlocking script"),bd(S.inputDescription,t,`${y}.inputDescription`),ne(S.sequenceNumber,t,`${y}.sequenceNumber`)}let p=qn(l.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],y=`${f}.outputs[${m}]`,S=qe(g,t,y);ne(S.satoshis,t,`${y}.satoshis`,21e14),S.lockingScript!==void 0&&$e(S.lockingScript,t,`${y}.lockingScript`),r?.includeOutputLockingScripts===!0&&S.lockingScript===void 0&&L(t,`${y}.lockingScript`,"the explicitly requested output locking script"),hm(S,t,"spendable"),S.customInstructions!==void 0&&ye(S.customInstructions,t,`${y}.customInstructions`),Gc(S.tags,t,`${y}.tags`,1,300),ne(S.outputIndex,t,`${y}.outputIndex`),bd(S.outputDescription,t,`${y}.outputDescription`),ye(S.basket,t,`${y}.basket`,0,300)}}}function A2(n,t,e){let i=Od(n,t,"totalOutputs","outputs",e),r=n.BEEF===void 0?void 0:f2(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 l=i[f],d=`outputs[${f}]`,p=qe(l,t,d),m=Is(p.outpoint,t,`${d}.outpoint`),g=`${m.txid}.${m.outputIndex}`;un(u,g)&&L(t,`${d}.outpoint`,"a unique output in the result page"),Gt(u,g);let y=ne(p.satoshis,t,`${d}.satoshis`,21e14);typeof p.spendable!="boolean"&&L(t,`${d}.spendable`,"a boolean");let S=p.lockingScript===void 0?void 0:$e(p.lockingScript,t,`${d}.lockingScript`);if(s?.include==="locking scripts"&&S===void 0&&L(t,`${d}.lockingScript`,"the requested locking script"),r!=null){let E=Pr(r.transactions,m.txid)?.outputs[m.outputIndex];E==null&&L(t,`${d}.outpoint`,"an output contained in BEEF"),E.satoshis!==y&&L(t,`${d}.satoshis`,"the amount committed by BEEF"),S!==void 0&&jt(Ye(E.lockingScript))!==jt(S)&&L(t,`${d}.lockingScript`,"the script committed by BEEF")}if(p.customInstructions!==void 0&&ye(p.customInstructions,t,`${d}.customInstructions`),Gc(p.tags,t,`${d}.tags`,1,300),Gc(p.labels,t,`${d}.labels`,1,300),s?.includeTags===!0&&p.tags===void 0&&L(t,`${d}.tags`,"the explicitly requested output tags"),s?.includeLabels===!0&&p.labels===void 0&&L(t,`${d}.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,`${d}.tags`,"the requested tag query")}}}function nm(n,t){let e=["prover","verifier","counterparty"];for(let i=0;i<e.length;i++){let r=e[i];zo(n[r],t,r)}ri(n.encryptedLinkage,t,"encryptedLinkage"),ri(n.encryptedLinkageProof,t,"encryptedLinkageProof")}function Ft(n,t,e){let i=Ed(t,n),r=qe(i,n),s=At(e);switch(n){case"createAction":case"signAction":u2(r,n,e);break;case"abortAction":hm(r,n,"aborted");break;case"internalizeAction":qc(r,n,"accepted");break;case"relinquishOutput":case"relinquishCertificate":qc(r,n,"relinquished");break;case"verifyHmac":case"verifySignature":qc(r,n,"valid");break;case"isAuthenticated":case"waitForAuthentication":qc(r,n,"authenticated");break;case"getPublicKey":zo(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);gs(o)||L(n,"signature","a canonical DER-encoded ECDSA signature");break}case"revealCounterpartyKeyLinkage":nm(r,n),s2(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":nm(r,n),(!qt(r.protocolID)||r.protocolID.length!==2)&&L(n,"protocolID","a [securityLevel, protocolName] tuple"),ne(r.protocolID[0],n,"protocolID[0]",2),ye(r.protocolID[1],n,"protocolID[1]",5,400),ye(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,n2)||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":v2(r,n,e);break;case"listOutputs":A2(r,n,e);break;case"listCertificates":case"discoverByIdentityKey":case"discoverByAttributes":S2(r,n,e);break;case"getHeight":kd(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":ye(r.version,n,"version",7,30);break;case"acquireCertificate":xd(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"),em(r,s,n,"certificate",s?.acquisitionProtocol!=="issuance");break;case"proveCertificate":{let o=Wo(r.keyringForVerifier,n,"keyringForVerifier",!0),c=qt(s?.fieldsToReveal)?s.fieldsToReveal:[],u=new cn;for(let d=0;d<c.length;d++)Gt(u,Be(c[d]));let f=Sn(o),l=f.length===Xc(u);for(let d=0;l&&d<f.length;d++)l=un(u,f[d]);l||L(n,"keyringForVerifier","exactly the requested certificate fields")}if(r.certificate!==void 0){let o=xd(r.certificate,n,"certificate");em(o,s?.certificate,n,"certificate")}r.verifier!==void 0&&zo(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 Pd;(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"})(Pd||(Pd={}));var Ss=Pd;function xt(n,t){switch(n){case"createAction":hc(t);return;case"signAction":pc(t);return;case"abortAction":gc(t);return;case"listActions":Tc(t);return;case"internalizeAction":mc(t);return;case"listOutputs":kc(t);return;case"relinquishOutput":yc(t);return;case"getPublicKey":Oc(t);return;case"revealCounterpartyKeyLinkage":Pc(t);return;case"revealSpecificKeyLinkage":Rc(t);return;case"encrypt":Nc(t);return;case"decrypt":Bc(t);return;case"createHmac":_c(t);return;case"verifyHmac":Cc(t);return;case"createSignature":Lc(t);return;case"verifySignature":Uc(t);return;case"acquireCertificate":{let e=t;if(e?.acquisitionProtocol==="direct")Sc(e);else if(e?.acquisitionProtocol==="issuance")Ic(e);else throw new ei("acquisitionProtocol","direct or issuance");return}case"listCertificates":xc(t);return;case"proveCertificate":vc(t);return;case"relinquishCertificate":wc(t);return;case"discoverByIdentityKey":Ac(t);return;case"discoverByAttributes":Ec(t);return;case"getHeaderForHeight":Mc(t);return;case"isAuthenticated":case"waitForAuthentication":case"getHeight":case"getNetwork":case"getVersion":Mi(t)}}var vs=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(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=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 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=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 E2=1024,ym=3600*1e3;function k2(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 As{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>ym))throw new TypeError(`XDM responseTimeout must be an integer from 1 to ${ym}.`);this.domain=e,this.responseTimeout=i}async invokeRaw(e,i,r){if(this.pendingInvocations>=E2)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,l=!0,d=()=>{if(l&&(l=!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||!k2(m.data,s)))if(d(),m.data.status==="error"){let g=m.data.code>=fn.unsupportedAction&&m.data.code<=fn.abortRefused,y=g?m.data.description:"Wallet operation failed",S=new oi(y,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(()=>{d(),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){d(),c(m)}})}};var Qc=16*1024*1024,tu=1e5,eu=1024*1024,wm=72;function xm(n,t,e){let i;try{i=uc(n)}catch{throw new Error(`Invalid certificate ${t}: expected canonical base64`)}return Sm(i,t,e),i}function T2(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>tu)throw new Error(`Certificate field count exceeds the maximum of ${tu}`);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(Rd(r,o.length),at(s.value,"utf8").length>eu)throw new Error(`Certificate field ${r} exceeds the maximum of ${eu} bytes`);i[r]=s.value}return i}function Im(n){let t=n instanceof Uint8Array?Array.from(n):n;if(!Array.isArray(t)||t.length>Qc)throw new Error(`Certificate binary must be a byte array of at most ${Qc} 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 O2(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 Rd(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 Sm(n,t,e){if(n.length!==e)throw new Error(`Invalid certificate ${t} length: expected ${e} bytes, received ${n.length}`)}function Jc(n,t){Sm(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){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=xm(this.type,"type",32);e.write(i);let r=xm(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(Jc(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(Jc(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 l=at(u,"hex");if(l.length!==32)throw new Error(`Invalid certificate revocation txid length: ${l.length}`);e.write(l),e.writeVarIntNum(Number(f));let d=T2(this.fields),p=Object.keys(d).sort((g,y)=>g.localeCompare(y));e.writeVarIntNum(p.length);for(let g of p){let y=d[g],S=at(g,"utf8");Rd(g,S.length),e.writeVarIntNum(S.length),e.write(S);let C=at(y,"utf8");e.writeVarIntNum(C.length),e.write(C)}if(t&&(this.signature??"").length>0){if(typeof this.signature!="string"||this.signature.length>wm*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>Qc)throw new Error(`Certificate binary exceeds the maximum of ${Qc} bytes`);return m}static fromBinary(t){let e=new bt(Im(t)),i=e.read(32),r=ve(i),s=e.read(32),o=ve(s),c=e.read(33);Jc(Array.from(c),"subject");let u=nt(c),f=e.read(33);Jc(Array.from(f),"certifier");let l=nt(f),d=e.read(32),p=nt(d),m=e.readVarIntNumStrict(!1),g=`${p}.${m}`,y=e.readVarIntNumStrict(!1);if(y>tu)throw new Error(`Certificate field count exceeds the maximum of ${tu}`);if(y>Math.floor(e.remaining()/3))throw new Error("Certificate field count exceeds the available data");let S=new Map;for(let E=0;E<y;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(Rd(B,A),S.has(B))throw new Error(`Duplicate certificate field name: ${B}`);let _=e.readVarIntNumStrict(!1);if(_>eu)throw new Error(`Certificate field ${B} exceeds the maximum of ${eu} bytes`);let $=e.read(_),R=Rt($);S.set(B,R)}let C;if(!e.eof()){if(e.remaining()>wm)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,l,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(!O2(e,this.toBinary(!1)))throw new Error("Certificate changed while its signature was being created");let r=Im(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 P2=1e5,R2={1:"completed",2:"unprocessed",3:"sending",4:"unproven",5:"unsigned",6:"nosend",7:"nonfinal",8:"failed"},v,Nt,vm,Am,Em,km,Tm,Om,Pm,Rm,Es,nu,Dt,ai,Cr,iu,ru,su,Nd,Nm,Bm,_m,Cm,ci,Lr,Bd,Hi,Xo,jo,Je,ui,Go,Yo,$i,Lm,Ee,Ur,qi,ou=class ou{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,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,Nm).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,Bm).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,ru).call(this,r,t.labels),a(this,v,_m).call(this,r,t.options);let s=await a(this,v,Nt).call(this,"createAction",e,r.toUint8ArrayZeroCopy());return Ft("createAction",a(this,v,vm).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 d of s){r.writeVarIntNum(Number(d));let p=t.spends[Number(d)],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,Cm).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 l=a(this,v,Nd).call(this,u);return l!=null&&(f.sendWithResults=l),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,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,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,jo).call(this,c.length,t.limit,"listActions"),c.push(a(this,v,km).call(this,s));return a(this,v,Xo).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,Pm).call(this,i,o);a(this,v,ru).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,Cr).call(this,r,t.basket),typeof t.tags=="object"){r.writeVarIntNum(t.tags.length);for(let d of t.tags)a(this,v,Cr).call(this,r,d)}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,l=[];for(;!o.eof();)a(this,v,jo).call(this,l.length,t.limit,"listOutputs"),l.push(a(this,v,Rm).call(this,o));return a(this,v,Xo).call(this,l.length,c,"listOutputs"),Ft("listOutputs",{totalOutputs:c,BEEF:f,outputs:l},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,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,Lr).call(this,t.privileged,t.privilegedReason)):(t.protocolID??(t.protocolID=[Dc.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,Ur).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,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 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"),l=o.readVarIntNumStrict(!1),d=Rt(o.read(l)),p=o.readVarIntNumStrict(!1),m=o.read(p),g=o.readVarIntNumStrict(!1),y=o.read(g);return a(this,v,Hi).call(this,o,"revealCounterpartyKeyLinkage"),Ft("revealCounterpartyKeyLinkage",{prover:c,verifier:u,counterparty:f,revelationTime:d,encryptedLinkage:Array.from(m),encryptedLinkageProof:Array.from(y)},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"),l=a(this,v,Lm).call(this,o,"revealSpecificKeyLinkage"),d=o.readVarIntNumStrict(!1),p=Rt(o.read(d)),m=o.readVarIntNumStrict(!1),g=Rt(o.read(m)),y=o.readVarIntNumStrict(!1),S=o.read(y),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:[l,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,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,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 l=et(u,"utf8"),d=et(f,"utf8");r.writeVarIntNum(l.length),r.write(l),r.writeVarIntNum(d.length),r.write(d)}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 l=Object.keys(t.keyringForSubject??{});r.writeVarIntNum(l.length);for(let d of l){let p=et(d,"utf8");r.writeVarIntNum(p.length),r.write(p);let m=et(t.keyringForSubject?.[d],"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=_r.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,Lr).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,jo).call(this,u.length,t.limit,"listCertificates");let f=o.readVarIntNumStrict(!1),l=o.read(f),d=_r.fromBinary(l),p={};if(a(this,v,ui).call(this,o,"listCertificates keyring present")){let y=o.readVarIntNumStrict(!1);a(this,v,Je).call(this,o,y,"listCertificates keyring");for(let S=0;S<y;S++){let C=o.readVarIntNumStrict(!1),E=a(this,v,Go).call(this,o,C,"listCertificates keyring"),A=o.readVarIntNumStrict(!1);a(this,v,Yo).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({...d,signature:d.signature,keyring:p,verifier:g})}return a(this,v,Xo).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,Es).call(this,t.certificate.revocationOutpoint??"");r.write(f);let l=et(t.certificate.signature,"hex");r.writeVarIntNum(l.length),r.write(l);let d=Object.entries(t.certificate.fields??{});r.writeVarIntNum(d.length);for(let[S,C]of d){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()),m=new bt(p),g=m.readVarIntNumStrict(!1);a(this,v,Je).call(this,m,g,"proveCertificate keyring");let y={};for(let S=0;S<g;S++){let C=m.readVarIntNumStrict(!1),E=a(this,v,Go).call(this,m,C,"proveCertificate keyring"),A=m.readVarIntNumStrict(!1);a(this,v,Yo).call(this,y,E,ve(m.read(A)),"proveCertificate keyring")}return a(this,v,Hi).call(this,m,"proveCertificate"),Ft("proveCertificate",{keyringForVerifier:y},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,Bd).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,Bd).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,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,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===""?"":ii(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 d=await this.wire.transmitToWallet(Array.from(c));if(!Array.isArray(d)||d.length>268435456)throw new Error("Wallet Wire response exceeds the maximum permitted size");for(let p=0;p<d.length;p++)if(!Object.prototype.hasOwnProperty.call(d,p)||!Number.isInteger(d[p])||d[p]<0||d[p]>255)throw new Error("Wallet Wire response must be a dense byte array");u=Uint8Array.from(d)}else{let d=await this.wire.transmitToWalletUint8Array(c);if(!(d instanceof Uint8Array)||d.length>268435456)throw new Error("Wallet Wire response exceeds the maximum permitted size");u=d}let f=new bt(u),l=f.readUInt8();if(l===0)return f.readView();{let d=f.readVarIntNumStrict(!1),p=f.read(d),m=Rt(p),g=f.readVarIntNumStrict(!1),y=f.read(g),S=Rt(y);throw a(this,v,Hi).call(this,f,t),new oi(m,l,S)}},vm=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,nu).call(this,e))}let s=a(this,v,Nd).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},Am=function(t){let e=R2[t];if(e==null)throw new Error(`Unknown status code: ${t}`);return e},Em=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)},km=function(t){let e=nt(t.read(32)),i=a(this,v,Em).call(this,t),r=a(this,v,Am).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 d=0;d<u;d++)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 d=0;d<f;d++)c.inputs.push(a(this,v,Tm).call(this,t))}let l=t.readVarIntNumStrict();if(l>=0){a(this,v,Je).call(this,t,l,"listActions outputs"),c.outputs=[];for(let d=0;d<l;d++)c.outputs.push(a(this,v,Om).call(this,t))}return c},Tm=function(t){let e=a(this,v,nu).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}},Om=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,l=t.readVarIntNumStrict(),d=[];if(l>=0){a(this,v,Je).call(this,t,l,"listActions output tags");for(let g=0;g<l;g++)d.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:d,customInstructions:m}},Pm=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,iu).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)}},Rm=function(t){let e=a(this,v,nu).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 l=0;l<c;l++)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 l=0;l<u;l++)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,Ee).call(this,Number(i[1]),"outpoint index",0,4294967295)),e.toUint8Array()},nu=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(ou.OPTIONAL_BOOLEAN_WIRE_VALUES.get(e))},ai=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)},iu=function(t,e){if(e!=null&&e!==""){let i=et(e,"utf8");t.writeVarIntNum(i.length),t.write(i)}else t.writeVarIntNum(-1)},ru=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)}}},su=function(t,e){if(e==null)t.writeVarIntNum(-1);else{t.writeVarIntNum(e.length);for(let i of e)t.write(et(i,"hex"))}},Nd=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},Nm=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,ai).call(this,t,e.sequenceNumber)},Bm=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,iu).call(this,t,e.basket),a(this,v,iu).call(this,t,e.customInstructions),a(this,v,ru).call(this,t,e.tags)},_m=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,su).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,su).call(this,t,e.sendWith),a(this,v,Dt).call(this,t,e.randomizeOutputs)},Cm=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,su).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,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()},Bd=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,jo).call(this,s.length,e,"discover");let o=i.readVarIntNumStrict(!1),c=i.read(o),u=_r.fromBinary(c),f=i.readVarIntNumStrict(!1),l=Rt(i.read(f)),d=i.readVarIntNumStrict(!1),p=Rt(i.read(d)),m=i.readVarIntNumStrict(!1),g=Rt(i.read(m)),y=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,Go).call(this,i,B,"discovery public keyring"),$=i.readVarIntNumStrict(!1);a(this,v,Yo).call(this,S,_,ve(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,Go).call(this,i,B,"discovery decrypted fields"),$=i.readVarIntNumStrict(!1);a(this,v,Yo).call(this,E,_,Rt(i.read($)),"discovery decrypted fields")}s.push({...u,signature:u.signature,certifierInfo:{iconUrl:p,name:l,description:g,trust:y},publiclyRevealedKeyring:S,decryptedFields:E})}return a(this,v,Xo).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`)},Xo=function(t,e,i){if(t>e)throw new Error(`Wallet Wire ${i} response returned ${t} records but declared a total of ${e}`)},jo=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=P2){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},Go=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},Yo=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)},Lm=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},Ur=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,Ur).call(this,t,0,e)},b(ou,"OPTIONAL_BOOLEAN_WIRE_VALUES",new Map([[!0,1],[!1,0],[void 0,-1]]));var ks=ou;function Um(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:"&&!N2(t.hostname))throw new TypeError("Wallet HTTP baseUrl may use cleartext HTTP only for a loopback host.");return t.origin}function N2(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){b(this,"baseUrl");b(this,"httpClient");b(this,"originator");let r=ii(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 bt(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 l=e.read(s);o=ii(Rt(l))}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 au=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 _d=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}},Mm=_d;var Cd=256*1024*1024,B2=256*1024*1024;async function _2(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>Cd)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>Cd)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>Cd)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 Ld(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 Dm(n,t){if(!Number.isSafeInteger(n)||n<0||n>21e14)throw new Error(`Invalid wallet error ${t}`);return n}function C2(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[l,d]of o.competingTxs.entries()){if(typeof d!="string"||!/^[0-9a-fA-F]{64}$/.test(d))throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs[${l}]`);let p=d.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=pd(o.competingBeef);if(f==null)throw new Error(`Invalid wallet error reviewActionResults[${r}].competingBeef`);try{let l=P0.fromBinaryStrict(f);for(let d of u)if(l.findTxid(d)==null)throw new Error}catch{throw new Error(`Invalid wallet error reviewActionResults[${r}].competingBeef`)}}}}function L2(n,t,e){if(n.isError!==!0||!Number.isSafeInteger(n.code))throw new Error("Invalid wallet error envelope");switch(n.message!==void 0&&Ld(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 C2(n.reviewActionResults,r),new au(n.reviewActionResults,n.sendWithResults,n.txid,n.tx,n.noSendChange)}case 6:{let i=Ld(n.parameter,"parameter",1,200),r=Ld(n.message,"message"),s=new ei(i);return s.message=r,s}case 7:{let i=Dm(n.totalSatoshisNeeded,"totalSatoshisNeeded"),r=Dm(n.moreSatoshisNeeded,"moreSatoshisNeeded");if(r>i)throw new Error("Invalid wallet error moreSatoshisNeeded");return new Mm(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=Ts(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=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:Um(this.originator,"http"),l=ys(o);if(et(l,"utf8").length>B2)throw new Error("HTTPWalletJSON request exceeds the maximum permitted size");let d=await this.httpClient(`${u}/${s}`,{method:"POST",redirect:"error",headers:{Accept:"application/json","Content-Type":"application/json",...f?{Origin:f,Originator:f}:{}},body:l}),p=lm(await _2(d),`HTTPWalletJSON ${s} raw response`),m=dm($c(p),`HTTPWalletJSON ${s} response`);if(m==null||typeof m!="object"||Array.isArray(m))throw new Error(`Invalid HTTPWalletJSON ${s} response: expected an object`);if(!d.ok){if(d.status===400&&Object.prototype.hasOwnProperty.call(m,"isError")){let g=L2(m,s,c);if(g!==void 0)throw g}throw new Error(`HTTPWalletJSON ${s} failed with HTTP status ${d.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 U2=1024,Hm=3600*1e3,$m=256*1024*1024,Mr=class extends As{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>Hm))throw new TypeError(`ReactNativeWebView responseTimeout must be an integer from 1 to ${Hm}.`);this.domain=D2(e),this.responseTimeout=i}async invokeRaw(e,i,r){if(this.pendingInvocations>=U2)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,l=!0,d=()=>{if(l&&(l=!1,this.pendingInvocations--,u!==void 0&&clearTimeout(u),f&&typeof globalThis.window.removeEventListener=="function"))try{globalThis.window.removeEventListener("message",p)}catch{}},p=m=>{if(!M2(m,this.domain)||typeof m.data!="string")return;if(et(m.data,"utf8").length>$m){d(),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){d(),c(new Error(`React Native wallet response origin ${m.origin} did not match ${this.domain}.`));return}if(d(),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 y=g.code>=fn.unsupportedAction&&g.code<=fn.abortRefused,S=y?g.description:"Wallet operation failed";c(new oi(S,y?g.code:fn.unknownError))}else try{let y=$c(g.result);o(Ft(e,y,r))}catch(y){c(y)}}};try{globalThis.window.addEventListener("message",p),f=!0,this.responseTimeout!==void 0&&(u=setTimeout(()=>{d(),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>$m)throw new Error("React Native wallet request exceeds the maximum permitted size.");globalThis.window.ReactNativeWebView.postMessage(m)}catch(m){d(),c(m)}})}};function M2(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 D2(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,qm=200,Wi=class{constructor(t="auto",e){b(this,"substrate");b(this,"originator");let i=ii(e);t==="Cicada"&&(t=new ks(new Os(i))),t==="window.CWI"&&(t=new vs),t==="XDM"&&(t=new Fn),t==="json-api"&&(t=new Fi(i)),t==="react-native"&&(t=new Mr),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(),l,d;try{l=await Promise.race([f.getVersion({},this.originator),new Promise((p,m)=>{d=setTimeout(()=>m(new Error("Timed out.")),c)})])}finally{clearTimeout(d)}return Ft("getVersion",l),{success:!0,sub:u?.()??f}}catch{return{success:!1}}},e=[t(()=>new vs,Ps),t(()=>new ks(new Os(this.originator)),Ps),t(()=>new Fi(this.originator,"https://localhost:2121"),Ps),t(()=>new Fi(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 Fn("*",qm),qm,()=>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){hc(t);let e=mt("createAction",t);return await this.connectToSubstrate(),await this.validatedResult("createAction",this.substrate.createAction(t,this.originator),e)}async signAction(t){pc(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 gc(t),await this.connectToSubstrate(),await this.validatedResult("abortAction",this.substrate.abortAction(t,this.originator))}async listActions(t){Tc(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 mc(t),await this.connectToSubstrate(),await this.validatedResult("internalizeAction",this.substrate.internalizeAction(t,this.originator))}async listOutputs(t){kc(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 yc(t),await this.connectToSubstrate(),await this.validatedResult("relinquishOutput",this.substrate.relinquishOutput(t,this.originator))}async getPublicKey(t){return Oc(t),await this.connectToSubstrate(),await this.validatedResult("getPublicKey",this.substrate.getPublicKey(t,this.originator))}async revealCounterpartyKeyLinkage(t){Pc(t);let e=mt("revealCounterpartyKeyLinkage",t);return await this.connectToSubstrate(),await this.validatedResult("revealCounterpartyKeyLinkage",this.substrate.revealCounterpartyKeyLinkage(t,this.originator),e)}async revealSpecificKeyLinkage(t){Rc(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 Nc(t),await this.connectToSubstrate(),await this.validatedResult("encrypt",this.substrate.encrypt(t,this.originator))}async decrypt(t){return Bc(t),await this.connectToSubstrate(),await this.validatedResult("decrypt",this.substrate.decrypt(t,this.originator))}async createHmac(t){return _c(t),await this.connectToSubstrate(),await this.validatedResult("createHmac",this.substrate.createHmac(t,this.originator))}async verifyHmac(t){return Cc(t),await this.connectToSubstrate(),await this.validatedResult("verifyHmac",this.substrate.verifyHmac(t,this.originator))}async createSignature(t){return Lc(t),await this.connectToSubstrate(),await this.validatedResult("createSignature",this.substrate.createSignature(t,this.originator))}async verifySignature(t){return Uc(t),await this.connectToSubstrate(),await this.validatedResult("verifySignature",this.substrate.verifySignature(t,this.originator))}async acquireCertificate(t){if(t.acquisitionProtocol==="direct")Sc(t);else if(t.acquisitionProtocol==="issuance")Ic(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){xc(t);let e=mt("listCertificates",t);return await this.connectToSubstrate(),await this.validatedResult("listCertificates",this.substrate.listCertificates(t,this.originator),e)}async proveCertificate(t){vc(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 wc(t),await this.connectToSubstrate(),await this.validatedResult("relinquishCertificate",this.substrate.relinquishCertificate(t,this.originator))}async discoverByIdentityKey(t){Ac(t);let e=mt("discoverByIdentityKey",t);return await this.connectToSubstrate(),await this.validatedResult("discoverByIdentityKey",this.substrate.discoverByIdentityKey(t,this.originator),e)}async discoverByAttributes(t){Ec(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 Mc(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 Rs="com.bwalletx.extension",Ud="space.bwallet.mobile",Zo=[Rs,Ud];function Dr(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&&Zo.includes(c)&&i({wallet:o.wallet,method:c===Rs?"extension":"in-app",rdns:c})};window.addEventListener("brc100:announceWallet",r),window.dispatchEvent(new Event("brc100:requestWallet")),setTimeout(()=>{let s=window.CWI;if(s)return i({wallet:s,method:"in-app",rdns:null});if(!H2())return i(null);F2(n).then(o=>i(o?{wallet:o,method:"in-app",rdns:null}:null))},n)})}async function Fm(n=1200){return(await Dr(n))?.wallet??null}var H2=()=>{try{return window.parent!==window}catch{return!0}},$2=["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"],q2=()=>{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 F2(n=1200,t=$2){let e=q2();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}}function Jo(n,t){let e=Promise.resolve();return i=>(e=e.then(()=>n(i)).catch(r=>t?.(r)),e)}var Km="1",W2="bwallet-pair-v1",V2="www.bwallet.space";var zm="relay.bwallet.space",uu=120,cu=new TextEncoder,K2=new TextDecoder,Xm=n=>{let t="";for(let e=0;e<n.length;e+=32768)t+=String.fromCharCode(...n.subarray(e,e+32768));return t},z2=n=>btoa(Xm(n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),X2=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))},Wm=n=>btoa(Xm(n)),Vm=n=>Uint8Array.from(atob(n),t=>t.charCodeAt(0)),jm=()=>z2(crypto.getRandomValues(new Uint8Array(16)));function Gm(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://${V2}/pair?${t}`}var Md=(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 Dd(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:X2(e),info:cu.encode(W2)},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){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:cu.encode(`${this.me}|${e}`)},this.key,cu.encode(JSON.stringify(t))));return{s:e,n:Wm(i),d:Wm(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:Vm(t.n),additionalData:cu.encode(`${e}|${t.s}`)},this.key,Vm(t.d));return this.lastSeen=t.s,JSON.parse(K2.decode(i))}catch{return null}}get counters(){return{sent:this.sent,lastSeen:this.lastSeen}}restore(t){this.sent=t.sent,this.lastSeen=t.lastSeen}},Hd=n=>!!n&&typeof n=="object"&&"d"in n&&"n"in n&&"s"in n;var $d="bwalletx.connect.pairing.v1",Ym=1;function du(){let n=new Map;return{getItem:t=>n.get(t)??null,setItem:(t,e)=>{n.set(t,e)},removeItem:t=>{n.delete(t)}}}function qd(){try{if(typeof localStorage<"u")return localStorage}catch{}return du()}function Zm(){return n=>{if(typeof WebSocket>"u")throw new Error("No WebSocket here. Pass options.socket.");return new WebSocket(n)}}function j2(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 fu=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=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===Ym||(this.opening??(this.opening=this.reopen().finally(()=>this.opening=null)),await this.opening)}reopen(){let t=this.socket(Md(this.p.r,this.p.c,"site",Math.floor(Date.now()/1e3)+uu-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(!Hd(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===Ym&&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?qd():n.storage??du(),e=n.storageKey??$d,i=n.socket??Zm(),r=n.relay??zm,s=n.origin??(typeof location<"u"?location.origin:"");if(!s)return Promise.reject(new Error("pairBwalletX needs options.origin outside a browser"));let o=ur.fromRandom(),c=jm(),u=Math.floor(Date.now()/1e3)+uu;return new Promise((f,l)=>{if(n.signal?.aborted)return l(new Error("cancelled"));let d;try{d=i(Md(r,c,"site",u))}catch(C){return l(C)}let p=null,m="",g=!1,y=C=>{g||(g=!0,clearTimeout(S),d.close(),l(C))},S=setTimeout(()=>y(new Error("The pairing code expired. Show a new one.")),uu*1e3);n.signal?.addEventListener("abort",()=>y(new Error("cancelled"))),d.onerror=()=>y(new Error("Could not reach the bWalletX pairing service")),d.onclose=()=>y(new Error("The connection to bWalletX closed before pairing finished")),d.onmessage=Jo(async C=>{if(g)return;let E;try{E=JSON.parse(String(C.data))}catch{return}if(E.t==="hello"&&!p){m=E.k;let k=await Dd(o,m,c);p=new Qo(k.key,"site"),n.onCode(k.code);return}if(!p||!Hd(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:m,...p.counters,pairedAt:Date.now()};await Promise.resolve(t.setItem(e,JSON.stringify(k))).catch(()=>{});let B=new fu(k,p,t,e,i,n.callTimeoutMs??12e4);B.adopt(d),f(B.wallet())}else A.t==="close"&&y(new Error("Pairing was declined in bWalletX"))}),n.onLink(Gm({v:Km,r,c,k:o.toPublicKey().toString(),o:s,e:u}))})}async function Bs(n={}){let t=n.storage===void 0?qd():n.storage??du(),e=n.storageKey??$d,i=j2(await Promise.resolve(t.getItem(e)).catch(()=>null));if(!i)return null;let{key:r}=await Dd(ur.fromHex(i.s),i.k,i.c),s=new Qo(r,"site");return s.restore({sent:i.sent,lastSeen:i.lastSeen}),new fu(i,s,t,e,n.socket??Zm(),n.callTimeoutMs??12e4).wallet()}async function Jm(n={}){let t=n.storage===void 0?qd():n.storage??du();await Promise.resolve(t.removeItem(n.storageKey??$d)).catch(()=>{})}var Wd=[2,"bwallet sign in"];async function ta(n={}){if(n.wallet)return{wallet:n.wallet,method:"wallet"};let t=await Dr(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 lu(n){let{wallet:t,method:e}=await ta(n);e!=="pairing"&&await t.waitForAuthentication({}).catch(()=>{});let{publicKey:i}=await Fd("identity",()=>t.getPublicKey({identityKey:!0})),r=await Fd("challenge",()=>n.challenge(i)),{signature:s}=await Fd("signature",()=>t.createSignature({protocolID:r.protocolID??Wd,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 Fd(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 Qm=1,hu=[2,"bwalletx access"];var tb=50,eb={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}},Vd={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 nb(n,t,e="latest"){return`https://unpkg.com/@bwalletx/connect@${e}/${Vd[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 Kd(n){return Array.from(new TextEncoder().encode(n))}var G2=/^bsv21:[0-9a-f]{64}_\d{1,6}$/,Y2=/^[1-9]\d{0,38}$/;function Z2(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(!G2.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"||!Y2.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 ib(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=Z2(t.require),ea(t)!==n)throw new kt("bad_request","challenge is not canonical");return t}function rb(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 J2=[0,"onesat"],Q2=[0,"p 1sat"];function pu(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 t4(n){let t=/^76a914([0-9a-f]{40})88ac$/i.exec(n.slice(-50));return t?t[1].toLowerCase():null}async function Xd(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=Kd(t);for(let u of s.outputs){if(o.size>=tb)break;let f={};try{f=JSON.parse(u.customInstructions??"{}")}catch{continue}if(f.id!==r||!f.keyID)continue;let l=u.lockingScript?t4(u.lockingScript):null,d=f.counterparty??"self";for(let p of f.protocolID?[f.protocolID]:[J2,Q2]){let{publicKey:m}=await n.getPublicKey({protocolID:p,keyID:f.keyID,counterparty:d}),g=wi.toHex(Ea.hash160(Ht.fromString(m).encode(!0)));if(l&&g!==l)continue;let y=o.get(m);if(y){y.outpoints.push(u.outpoint.replace(".","_"));break}let{signature:S}=await n.createSignature({protocolID:p,keyID:f.keyID,counterparty:d,data:c});o.set(m,{pubkey:m,signature:Array.from(S),outpoints:[u.outpoint.replace(".","_")]});break}}return[...o.values()]}async function gu(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"):pu(e)}try{let{publicKey:e}=await t.getPublicKey({identityKey:!0}),{challenge:i}=await n.challenge(e),r=ib(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:hu,keyID:r.nonce,counterparty:"anyone",data:Kd(i)}),o={v:1,challenge:i,identityKey:e,signature:Array.from(s)};r.require.token&&(o.holdings=await Xd(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 pu(e)}}var Yd="bwalletx-signin",Zd="https://bwalletx.com/get",na="https://web.bwalletx.com",sb={signin:"Sign in with",continue:"Continue with",connect:"Connect"};function Jd(n="signin",t="bWalletX"){return`${sb[n]??sb.signin} ${t}`}var e4=0;function Qd(n=20){let t=++e4;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 tl=`
|
|
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 ob(n){let t="";for(let e of n)t+=String.fromCharCode(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function el(n){let t=u=>ob(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",ob(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 jd(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 n4(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 i4=["size","theme","label","brand","subtitle","loading","disabled","full-width","aria-label","get-url","web-url"];function r4(){var n,t,e,i,Qt,mu,Vi,Gd,ab,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 i4}connectedCallback(){a(this,i,mu).call(this)}attributeChangedCallback(){this.isConnected&&a(this,i,mu).call(this)}get button(){return w(this,n).querySelector("button")}get notFound(){return w(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)},mu=function(){let p=a(this,i,Qt).call(this,"size")??"lg",m=a(this,i,Qt).call(this,"brand")==="bWallet"?"bWallet":"bWalletX",g=Jd(a(this,i,Qt).call(this,"label")??"signin",m),y=a(this,i,Qt).call(this,"subtitle"),C=y===null||y===""||y==="on"?y==="on"?"also works with bWallet":m==="bWalletX"&&(p==="lg"||p==="md")?"also works with bWallet":null:y==="off"?null:y,E=this.hasAttribute("loading")||w(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")??Zd,$=a(this,i,Qt).call(this,"web-url")??na,R=F=>F.replace(/[&<>"]/g,it=>({"&":"&","<":"<",">":">",'"':"""})[it]),I=p==="icon"?"":`<span class="txt" part="text"><b part="label">${R(g)}</b>${C?`<small part="subtitle">${R(C)}</small>`:""}</span>`,U=E?'<span class="spin" aria-hidden="true"></span>':Qd(k),M=w(this,t)?`<p class="nf" part="not-found" role="status">bWalletX wasn't found in this browser. <a href="${R(_)}" target="_blank" rel="noopener">Get ${m}</a> or <a href="${R($)}" target="_blank" rel="noopener">use the web wallet</a>.</p>`:"";w(this,n).innerHTML=`<style>${tl}</style><button type="button" part="button" aria-label="${R(B)}" title="${R(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,ab).call(this)})},Vi=function(p,m,g=!1){return this.dispatchEvent(new CustomEvent(p,{detail:m,bubbles:!0,composed:!0,cancelable:g}))},Gd=function(p){N(this,e,p),a(this,i,mu).call(this)},ab=async function(){if(this.hasAttribute("disabled")||this.hasAttribute("loading")||w(this,e)||!a(this,i,Vi).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 el({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,Gd).call(this,!0);try{let y=Number(a(this,i,Qt).call(this,"discover-ms"))||1200,S=await Dr(y);if(!S){N(this,t,!0),a(this,i,Vi).call(this,"bwalletx-not-found"),a(this,i,Qt).call(this,"require-token")&&a(this,i,Vi).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"),$=a(this,i,Qt).call(this,"min-bps"),R={token:{id:C,...$?{minBps:Number($)}:{min:_??"1"}}};try{let I=await gu({wallet:S.wallet,challenge:U=>jd(g,{identityKey:U,require:R}),verify:B?U=>n4(B,U):void 0});a(this,i,Vi).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,Vi).call(this,"bwalletx-access-denied",{code:U.code,message:U.message,have:U.have,need:U.need})}return}let E=await lu({wallet:S.wallet,challenge:B=>jd(g,{identityKey:B})}),A=a(this,i,Qt).call(this,"verify-url"),k=A?await jd(A,{identityKey:E.identityKey,nonce:E.nonce,signature:E.signature}):null;a(this,i,Vi).call(this,"bwalletx-signed-in",{identityKey:E.identityKey,method:S.method,nonce:E.nonce,signature:E.signature,response:k})}catch(y){a(this,i,Vi).call(this,"bwalletx-error",{error:y})}finally{a(this,i,Gd).call(this,!1)}}},f}function bu(n=Yd){if(typeof window>"u"||typeof customElements>"u")return;let t=customElements.get(n);if(t)return t;let e=r4();return customElements.define(n,e),e}var s4=`
|
|
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)}`,nl="https://bwalletx.com/logo.svg";function cb(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=s4,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=nl,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 il=[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"}},db=n=>typeof n.pay=="function"&&typeof n.createAction!="function",rl=n=>/^0[23][0-9a-fA-F]{64}$/.test(n),sl=n=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n);function ub(n){let t=new Uint8Array(n);return globalThis.crypto.getRandomValues(t),wi.toBase64(Array.from(t))}function o4(n){let t=wi.toArray(n,"utf8"),e=t.length,i=e<76?[e]:e<=255?[76,e]:[77,e&255,e>>8];return wi.toHex([0,106,...i,...t])}var ol=(n,t)=>n.length>t?n.slice(0,t-1)+"\u2026":n,fb=n=>ol(n.length<5?`${n} payment`.trim():n,50);async function a4(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 al(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 a4(t)*1e8))}throw new he("BAD_REQUEST","Give sats or usd")}async function cl(n,t,e=fetch){let[i,r]=n.split("@"),s=(d,p)=>new he("RESOLVE_FAILED",`Could not resolve ${n}: ${d}`,!1,p),o;try{o=(await(await e(`https://${r}/.well-known/bsvalias`)).json()).capabilities}catch(d){throw s("no bsvalias document (or CORS blocked it; resolve on your server and pass resolvePaymail)",d)}let c=d=>d.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 d=await e(c(u),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({satoshis:t})});if(!d.ok)throw new Error(`status ${d.status}`);f=await d.json()}catch(d){throw s(d.message,d)}if(!f.outputs?.length)throw s("no outputs returned");let l=o["5f1323cddf31"];return{outputs:f.outputs.map(d=>({script:d.script,satoshis:d.satoshis})),reference:f.reference,submit:l?async d=>{await e(c(l),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hex:d,reference:f.reference,metadata:{}})})}:void 0}}async function lb(n,t,e,i){try{return await n.createAction({description:fb(t),outputs:e.map(r=>({lockingScript:r.script,satoshis:r.satoshis,outputDescription:fb(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 ul(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 al(t,e);if(db(n))return n.pay({...t,to:i,sats:r});let s,o,c;if(rl(i)){let l=ub(8),d=ub(8),p,m;try{({publicKey:p}=await n.getPublicKey({protocolID:il,keyID:`${l} ${d}`,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:l,derivationSuffix:d,outputIndex:0}}else if(sl(i)){let l=await(e.resolvePaymail??((d,p)=>cl(d,p,e.fetch??fetch)))(i,r);s=l.outputs,c=l.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:o4(t.memo),satoshis:0,description:"memo"}]);let u=await lb(n,t.memo||`Pay ${ol(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 hb(n,t,e={}){return ul(n,{memo:"Tip",...t,labels:[...t.labels??[],"tip"]},e)}async function pb(n,t){if(db(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 lb(n,e.description??`Buy ${ol(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 mb(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 _s(n,t){let e={id:t.id,name:t.name,icon:t.icon,rdns:t.rdns,kind:"brc100",isBwalletX:t.isBwalletX??!1,connect:()=>mb(n,e)};return e}function fl(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 Bs(e)??await Ns(e);return mb(i,t)}};return t}function bb(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 c4={[Rs]:"bWalletX","space.bwallet.mobile":"bWalletX"};async function gb(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 yb(n={}){let t=[],e=n.ms??1200;if(typeof window<"u"){let r=new Map,s=l=>{let d=l.detail;if(!d?.wallet)return;let p=d.info?.rdns??d.info?.uuid??`wallet-${r.size}`;if(r.has(p))return;let m=Zo.includes(p);r.set(p,_s(d.wallet,{id:p,rdns:p,name:c4[p]??d.info?.name??p,icon:d.info?.icon,isBwalletX:m}))};window.addEventListener("brc100:announceWallet",s),window.dispatchEvent(new Event("brc100:requestWallet"));let o=n.probeLocal?Promise.all([gb("json-api",e),gb("Cicada",e)]):Promise.resolve([null,null]);await new Promise(l=>setTimeout(l,e)),window.removeEventListener("brc100:announceWallet",s),t.push(...r.values());let c=window.CWI;c&&![...r.values()].some(l=>l.rdns==="space.bwallet.mobile")&&t.push(_s(c,{id:"window.CWI",name:"This app\u2019s wallet",isBwalletX:!1}));let[u,f]=await o;u&&t.push(_s(u,{id:"localhost:3321",name:"Desktop wallet (localhost:3321)"})),f&&t.push(_s(f,{id:"localhost:3301",name:"Desktop wallet (localhost:3301)"}))}n.pairing&&t.push(fl(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 vb=Lb(Sb(),1);var u4=`
|
|
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 Ab(){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=u4;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 dl(n){let t=(0,vb.default)(0,"M");return t.addData(n),t.make(),t.createSvgTag({cellSize:4,margin:2,scalable:!0})}function ll(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 Eb(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=Ab();let o=n.mode==="app"||(n.mode??"auto")==="auto"&&ll(),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"),y=ie("a","bwx-btn bwx-primary","Open bWalletX");y.href=s,y.rel="noopener";let S=ie("button","bwx-btn","Use web.bwalletx.com instead");S.onclick=()=>{navigator.clipboard?.writeText(s).catch(()=>{}),window.open(na,"_blank","noopener"),m.textContent="Link copied. In web.bwalletx.com tap Connect and paste it, then come back here."},g.append(y,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."),l=ie("div","bwx-qr");l.innerHTML=dl(s);let d=ie("div","bwx-row"),p=ie("button","bwx-btn","Copy link");p.onclick=()=>{navigator.clipboard?.writeText(s).then(()=>p.textContent="Copied")},d.append(p,u),e.box.append(c,f,l,i,d)},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 kb(n,t={}){return typeof document>"u"?Promise.resolve(null):new Promise(e=>{let i=Ab(),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 yu="bwalletx-theme",f4=/^[a-z0-9-]{1,32}$/;function Tb(n){if(typeof document>"u")return;let t=(n??"").trim().toLowerCase(),e=document.head.querySelector(`meta[name="${yu}"]`);if(!t||!f4.test(t)){e?.remove();return}e||(e=document.createElement("meta"),e.name=yu,document.head.appendChild(e)),e.content!==t&&(e.content=t)}bu();return Ub(d4);})();
|
|
92
95
|
//# sourceMappingURL=bwalletx-connect.global.js.map
|