@bwalletx/connect 0.5.4 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +97 -9
  3. package/dist/bwalletx-connect.global.js +97 -25
  4. package/dist/bwalletx-connect.global.js.map +1 -1
  5. package/dist/choice-B97AjqF4.d.cts +442 -0
  6. package/dist/choice-B97AjqF4.d.ts +442 -0
  7. package/dist/chunk-6EFFOIHK.js +2441 -0
  8. package/dist/chunk-6EFFOIHK.js.map +1 -0
  9. package/dist/{chunk-QRXFL66W.js → chunk-A2WLGS25.js} +6 -4
  10. package/dist/chunk-A2WLGS25.js.map +1 -0
  11. package/dist/chunk-DIKJFKND.js +239 -0
  12. package/dist/chunk-DIKJFKND.js.map +1 -0
  13. package/dist/chunk-TNRI7ARM.js +206 -0
  14. package/dist/chunk-TNRI7ARM.js.map +1 -0
  15. package/dist/element-BXEoOdXY.d.cts +53 -0
  16. package/dist/element-BXEoOdXY.d.ts +53 -0
  17. package/dist/element.cjs +1576 -60
  18. package/dist/element.cjs.map +1 -1
  19. package/dist/element.d.cts +26 -26
  20. package/dist/element.d.ts +26 -26
  21. package/dist/element.js +35 -2
  22. package/dist/element.js.map +1 -1
  23. package/dist/index.cjs +2046 -454
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +323 -16
  26. package/dist/index.d.ts +323 -16
  27. package/dist/index.js +186 -12
  28. package/dist/index.js.map +1 -1
  29. package/dist/next.cjs +5 -3
  30. package/dist/next.cjs.map +1 -1
  31. package/dist/next.js +1 -1
  32. package/dist/react.cjs +1601 -210
  33. package/dist/react.cjs.map +1 -1
  34. package/dist/react.d.cts +115 -9
  35. package/dist/react.d.ts +115 -9
  36. package/dist/react.js +262 -46
  37. package/dist/react.js.map +1 -1
  38. package/dist/server.cjs +5 -3
  39. package/dist/server.cjs.map +1 -1
  40. package/dist/server.d.cts +8 -3
  41. package/dist/server.d.ts +8 -3
  42. package/dist/server.js +1 -1
  43. package/package.json +10 -9
  44. package/dist/chunk-EXRQJTXF.js +0 -910
  45. package/dist/chunk-EXRQJTXF.js.map +0 -1
  46. package/dist/chunk-QRXFL66W.js.map +0 -1
  47. package/dist/chunk-RIOHG5JH.js +0 -459
  48. package/dist/chunk-RIOHG5JH.js.map +0 -1
  49. package/dist/wallets-CbzMtxrf.d.cts +0 -250
  50. package/dist/wallets-CbzMtxrf.d.ts +0 -250
@@ -1,11 +1,11 @@
1
- "use strict";var bWalletXConnect=(()=>{var Ub=Object.create;var Us=Object.defineProperty;var Mb=Object.getOwnPropertyDescriptor;var Db=Object.getOwnPropertyNames;var Hb=Object.getPrototypeOf,$b=Object.prototype.hasOwnProperty;var Sl=n=>{throw TypeError(n)};var qb=(n,t,e)=>t in n?Us(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var Iu=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var Fb=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports),vu=(n,t)=>{for(var e in t)Us(n,e,{get:t[e],enumerable:!0})},Il=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Db(t))!$b.call(n,r)&&r!==e&&Us(n,r,{get:()=>t[r],enumerable:!(i=Mb(t,r))||i.enumerable});return n};var Wb=(n,t,e)=>(e=n!=null?Ub(Hb(n)):{},Il(t||!n||!n.__esModule?Us(e,"default",{value:n,enumerable:!0}):e,n)),Vb=n=>Il(Us({},"__esModule",{value:!0}),n);var b=(n,t,e)=>qb(n,typeof t!="symbol"?t+"":t,e),Au=(n,t,e)=>t.has(n)||Sl("Cannot "+e);var y=(n,t,e)=>(Au(n,t,"read from private field"),e?e.call(n):t.get(n)),G=(n,t,e)=>t.has(n)?Sl("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),N=(n,t,e,i)=>(Au(n,t,"write to private field"),i?i.call(n,e):t.set(n,e),e),a=(n,t,e)=>(Au(n,t,"access private method"),e);var Rb=Fb((Ob,Pb)=>{"use strict";var Tb=(function(){var n=function(E,A){var k=236,B=17,_=E,H=e[A],O=null,I=0,U=null,M=[],F={},it=function($,W){I=_*4+17,O=(function(D){for(var V=new Array(D),X=0;X<D;X+=1){V[X]=new Array(D);for(var J=0;J<D;J+=1)V[X][J]=null}return V})(I),ot(0,0),ot(I-7,0),ot(0,I-7),tt(),z(),ce($,W),_>=7&&St($),U==null&&(U=ke(_,H,M)),Bt(U,W)},ot=function($,W){for(var D=-1;D<=7;D+=1)if(!($+D<=-1||I<=$+D))for(var V=-1;V<=7;V+=1)W+V<=-1||I<=W+V||(0<=D&&D<=6&&(V==0||V==6)||0<=V&&V<=6&&(D==0||D==6)||2<=D&&D<=4&&2<=V&&V<=4?O[$+D][W+V]=!0:O[$+D][W+V]=!1)},q=function(){for(var $=0,W=0,D=0;D<8;D+=1){it(!0,D);var V=r.getLostPoint(F);(D==0||$>V)&&($=V,W=D)}return W},z=function(){for(var $=8;$<I-8;$+=1)O[$][6]==null&&(O[$][6]=$%2==0);for(var W=8;W<I-8;W+=1)O[6][W]==null&&(O[6][W]=W%2==0)},tt=function(){for(var $=r.getPatternPosition(_),W=0;W<$.length;W+=1)for(var D=0;D<$.length;D+=1){var V=$[W],X=$[D];if(O[V][X]==null)for(var J=-2;J<=2;J+=1)for(var dt=-2;dt<=2;dt+=1)J==-2||J==2||dt==-2||dt==2||J==0&&dt==0?O[V+J][X+dt]=!0:O[V+J][X+dt]=!1}},St=function($){for(var W=r.getBCHTypeNumber(_),D=0;D<18;D+=1){var V=!$&&(W>>D&1)==1;O[Math.floor(D/3)][D%3+I-8-3]=V}for(var D=0;D<18;D+=1){var V=!$&&(W>>D&1)==1;O[D%3+I-8-3][Math.floor(D/3)]=V}},ce=function($,W){for(var D=H<<3|W,V=r.getBCHTypeInfo(D),X=0;X<15;X+=1){var J=!$&&(V>>X&1)==1;X<6?O[X][8]=J:X<8?O[X+1][8]=J:O[I-15+X][8]=J}for(var X=0;X<15;X+=1){var J=!$&&(V>>X&1)==1;X<8?O[8][I-X-1]=J:X<9?O[8][15-X-1+1]=J:O[8][15-X-1]=J}O[I-8][8]=!$},Bt=function($,W){for(var D=-1,V=I-1,X=7,J=0,dt=r.getMaskFunction(W),ft=I-1;ft>0;ft-=2)for(ft==6&&(ft-=1);;){for(var Ct=0;Ct<2;Ct+=1)if(O[V][ft-Ct]==null){var re=!1;J<$.length&&(re=($[J]>>>X&1)==1);var pt=dt(V,ft-Ct);pt&&(re=!re),O[V][ft-Ct]=re,X-=1,X==-1&&(J+=1,X=7)}if(V+=D,V<0||I<=V){V-=D,D=-D;break}}},dn=function($,W){for(var D=0,V=0,X=0,J=new Array(W.length),dt=new Array(W.length),ft=0;ft<W.length;ft+=1){var Ct=W[ft].dataCount,re=W[ft].totalCount-Ct;V=Math.max(V,Ct),X=Math.max(X,re),J[ft]=new Array(Ct);for(var pt=0;pt<J[ft].length;pt+=1)J[ft][pt]=255&$.getBuffer()[pt+D];D+=Ct;var Qe=r.getErrorCorrectPolynomial(re),tn=o(J[ft],Qe.getLength()-1),wl=tn.mod(Qe);dt[ft]=new Array(Qe.getLength()-1);for(var pt=0;pt<dt[ft].length;pt+=1){var yl=pt+wl.getLength()-dt[ft].length;dt[ft][pt]=yl>=0?wl.getAt(yl):0}}for(var xl=0,pt=0;pt<W.length;pt+=1)xl+=W[pt].totalCount;for(var Su=new Array(xl),sa=0,pt=0;pt<V;pt+=1)for(var ft=0;ft<W.length;ft+=1)pt<J[ft].length&&(Su[sa]=J[ft][pt],sa+=1);for(var pt=0;pt<X;pt+=1)for(var ft=0;ft<W.length;ft+=1)pt<dt[ft].length&&(Su[sa]=dt[ft][pt],sa+=1);return Su},ke=function($,W,D){for(var V=c.getRSBlocks($,W),X=u(),J=0;J<D.length;J+=1){var dt=D[J];X.put(dt.getMode(),4),X.put(dt.getLength(),r.getLengthInBits(dt.getMode(),$)),dt.write(X)}for(var ft=0,J=0;J<V.length;J+=1)ft+=V[J].dataCount;if(X.getLengthInBits()>ft*8)throw"code length overflow. ("+X.getLengthInBits()+">"+ft*8+")";for(X.getLengthInBits()+4<=ft*8&&X.put(0,4);X.getLengthInBits()%8!=0;)X.putBit(!1);for(;!(X.getLengthInBits()>=ft*8||(X.put(k,8),X.getLengthInBits()>=ft*8));)X.put(B,8);return dn(X,V)};F.addData=function($,W){W=W||"Byte";var D=null;switch(W){case"Numeric":D=f($);break;case"Alphanumeric":D=d($);break;case"Byte":D=l($);break;case"Kanji":D=p($);break;default:throw"mode:"+W}M.push(D),U=null},F.isDark=function($,W){if($<0||I<=$||W<0||I<=W)throw $+","+W;return O[$][W]},F.getModuleCount=function(){return I},F.make=function(){if(_<1){for(var $=1;$<40;$++){for(var W=c.getRSBlocks($,H),D=u(),V=0;V<M.length;V++){var X=M[V];D.put(X.getMode(),4),D.put(X.getLength(),r.getLengthInBits(X.getMode(),$)),X.write(D)}for(var J=0,V=0;V<W.length;V++)J+=W[V].dataCount;if(D.getLengthInBits()<=J*8)break}_=$}it(!1,q())},F.createTableTag=function($,W){$=$||2,W=typeof W>"u"?$*4:W;var D="";D+='<table style="',D+=" border-width: 0px; border-style: none;",D+=" border-collapse: collapse;",D+=" padding: 0px; margin: "+W+"px;",D+='">',D+="<tbody>";for(var V=0;V<F.getModuleCount();V+=1){D+="<tr>";for(var X=0;X<F.getModuleCount();X+=1)D+='<td style="',D+=" border-width: 0px; border-style: none;",D+=" border-collapse: collapse;",D+=" padding: 0px; margin: 0px;",D+=" width: "+$+"px;",D+=" height: "+$+"px;",D+=" background-color: ",D+=F.isDark(V,X)?"#000000":"#ffffff",D+=";",D+='"/>';D+="</tr>"}return D+="</tbody>",D+="</table>",D},F.createSvgTag=function($,W,D,V){var X={};typeof arguments[0]=="object"&&(X=arguments[0],$=X.cellSize,W=X.margin,D=X.alt,V=X.title),$=$||2,W=typeof W>"u"?$*4:W,D=typeof D=="string"?{text:D}:D||{},D.text=D.text||null,D.id=D.text?D.id||"qrcode-description":null,V=typeof V=="string"?{text:V}:V||{},V.text=V.text||null,V.id=V.text?V.id||"qrcode-title":null;var J=F.getModuleCount()*$+W*2,dt,ft,Ct,re,pt="",Qe;for(Qe="l"+$+",0 0,"+$+" -"+$+",0 0,-"+$+"z ",pt+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"',pt+=X.scalable?"":' width="'+J+'px" height="'+J+'px"',pt+=' viewBox="0 0 '+J+" "+J+'" ',pt+=' preserveAspectRatio="xMinYMin meet"',pt+=V.text||D.text?' role="img" aria-labelledby="'+xe([V.id,D.id].join(" ").trim())+'"':"",pt+=">",pt+=V.text?'<title id="'+xe(V.id)+'">'+xe(V.text)+"</title>":"",pt+=D.text?'<description id="'+xe(D.id)+'">'+xe(D.text)+"</description>":"",pt+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>',pt+='<path d="',Ct=0;Ct<F.getModuleCount();Ct+=1)for(re=Ct*$+W,dt=0;dt<F.getModuleCount();dt+=1)F.isDark(Ct,dt)&&(ft=dt*$+W,pt+="M"+ft+","+re+Qe);return pt+='" stroke="transparent" fill="black"/>',pt+="</svg>",pt},F.createDataURL=function($,W){$=$||2,W=typeof W>"u"?$*4:W;var D=F.getModuleCount()*$+W*2,V=W,X=D-W;return C(D,D,function(J,dt){if(V<=J&&J<X&&V<=dt&&dt<X){var ft=Math.floor((J-V)/$),Ct=Math.floor((dt-V)/$);return F.isDark(Ct,ft)?0:1}else return 1})},F.createImgTag=function($,W,D){$=$||2,W=typeof W>"u"?$*4:W;var V=F.getModuleCount()*$+W*2,X="";return X+="<img",X+=' src="',X+=F.createDataURL($,W),X+='"',X+=' width="',X+=V,X+='"',X+=' height="',X+=V,X+='"',D&&(X+=' alt="',X+=xe(D),X+='"'),X+="/>",X};var xe=function($){for(var W="",D=0;D<$.length;D+=1){var V=$.charAt(D);switch(V){case"<":W+="&lt;";break;case">":W+="&gt;";break;case"&":W+="&amp;";break;case'"':W+="&quot;";break;default:W+=V;break}}return W},vn=function($){var W=1;$=typeof $>"u"?W*2:$;var D=F.getModuleCount()*W+$*2,V=$,X=D-$,J,dt,ft,Ct,re,pt={"\u2588\u2588":"\u2588","\u2588 ":"\u2580"," \u2588":"\u2584"," ":" "},Qe={"\u2588\u2588":"\u2580","\u2588 ":"\u2580"," \u2588":" "," ":" "},tn="";for(J=0;J<D;J+=2){for(ft=Math.floor((J-V)/W),Ct=Math.floor((J+1-V)/W),dt=0;dt<D;dt+=1)re="\u2588",V<=dt&&dt<X&&V<=J&&J<X&&F.isDark(ft,Math.floor((dt-V)/W))&&(re=" "),V<=dt&&dt<X&&V<=J+1&&J+1<X&&F.isDark(Ct,Math.floor((dt-V)/W))?re+=" ":re+="\u2588",tn+=$<1&&J+1>=X?Qe[re]:pt[re];tn+=`
2
- `}return D%2&&$>0?tn.substring(0,tn.length-D-1)+Array(D+1).join("\u2580"):tn.substring(0,tn.length-1)};return F.createASCII=function($,W){if($=$||1,$<2)return vn(W);$-=1,W=typeof W>"u"?$*2:W;var D=F.getModuleCount()*$+W*2,V=W,X=D-W,J,dt,ft,Ct,re=Array($+1).join("\u2588\u2588"),pt=Array($+1).join(" "),Qe="",tn="";for(J=0;J<D;J+=1){for(ft=Math.floor((J-V)/$),tn="",dt=0;dt<D;dt+=1)Ct=1,V<=dt&&dt<X&&V<=J&&J<X&&F.isDark(ft,Math.floor((dt-V)/$))&&(Ct=0),tn+=Ct?re:pt;for(ft=0;ft<$;ft+=1)Qe+=tn+`
3
- `}return Qe.substring(0,Qe.length-1)},F.renderTo2dContext=function($,W){W=W||2;for(var D=F.getModuleCount(),V=0;V<D;V++)for(var X=0;X<D;X++)$.fillStyle=F.isDark(V,X)?"black":"white",$.fillRect(V*W,X*W,W,W)},F};n.stringToBytesFuncs={default:function(E){for(var A=[],k=0;k<E.length;k+=1){var B=E.charCodeAt(k);A.push(B&255)}return A}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(E,A){var k=(function(){for(var _=w(E),H=function(){var z=_.read();if(z==-1)throw"eof";return z},O=0,I={};;){var U=_.read();if(U==-1)break;var M=H(),F=H(),it=H(),ot=String.fromCharCode(U<<8|M),q=F<<8|it;I[ot]=q,O+=1}if(O!=A)throw O+" != "+A;return I})(),B=63;return function(_){for(var H=[],O=0;O<_.length;O+=1){var I=_.charCodeAt(O);if(I<128)H.push(I);else{var U=k[_.charAt(O)];typeof U=="number"?(U&255)==U?H.push(U):(H.push(U>>>8),H.push(U&255)):H.push(B)}}return H}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},e={L:1,M:0,Q:3,H:2},i={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var E=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],A=1335,k=7973,B=21522,_={},H=function(O){for(var I=0;O!=0;)I+=1,O>>>=1;return I};return _.getBCHTypeInfo=function(O){for(var I=O<<10;H(I)-H(A)>=0;)I^=A<<H(I)-H(A);return(O<<10|I)^B},_.getBCHTypeNumber=function(O){for(var I=O<<12;H(I)-H(k)>=0;)I^=k<<H(I)-H(k);return O<<12|I},_.getPatternPosition=function(O){return E[O-1]},_.getMaskFunction=function(O){switch(O){case i.PATTERN000:return function(I,U){return(I+U)%2==0};case i.PATTERN001:return function(I,U){return I%2==0};case i.PATTERN010:return function(I,U){return U%3==0};case i.PATTERN011:return function(I,U){return(I+U)%3==0};case i.PATTERN100:return function(I,U){return(Math.floor(I/2)+Math.floor(U/3))%2==0};case i.PATTERN101:return function(I,U){return I*U%2+I*U%3==0};case i.PATTERN110:return function(I,U){return(I*U%2+I*U%3)%2==0};case i.PATTERN111:return function(I,U){return(I*U%3+(I+U)%2)%2==0};default:throw"bad maskPattern:"+O}},_.getErrorCorrectPolynomial=function(O){for(var I=o([1],0),U=0;U<O;U+=1)I=I.multiply(o([1,s.gexp(U)],0));return I},_.getLengthInBits=function(O,I){if(1<=I&&I<10)switch(O){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+O}else if(I<27)switch(O){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+O}else if(I<41)switch(O){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+O}else throw"type:"+I},_.getLostPoint=function(O){for(var I=O.getModuleCount(),U=0,M=0;M<I;M+=1)for(var F=0;F<I;F+=1){for(var it=0,ot=O.isDark(M,F),q=-1;q<=1;q+=1)if(!(M+q<0||I<=M+q))for(var z=-1;z<=1;z+=1)F+z<0||I<=F+z||q==0&&z==0||ot==O.isDark(M+q,F+z)&&(it+=1);it>5&&(U+=3+it-5)}for(var M=0;M<I-1;M+=1)for(var F=0;F<I-1;F+=1){var tt=0;O.isDark(M,F)&&(tt+=1),O.isDark(M+1,F)&&(tt+=1),O.isDark(M,F+1)&&(tt+=1),O.isDark(M+1,F+1)&&(tt+=1),(tt==0||tt==4)&&(U+=3)}for(var M=0;M<I;M+=1)for(var F=0;F<I-6;F+=1)O.isDark(M,F)&&!O.isDark(M,F+1)&&O.isDark(M,F+2)&&O.isDark(M,F+3)&&O.isDark(M,F+4)&&!O.isDark(M,F+5)&&O.isDark(M,F+6)&&(U+=40);for(var F=0;F<I;F+=1)for(var M=0;M<I-6;M+=1)O.isDark(M,F)&&!O.isDark(M+1,F)&&O.isDark(M+2,F)&&O.isDark(M+3,F)&&O.isDark(M+4,F)&&!O.isDark(M+5,F)&&O.isDark(M+6,F)&&(U+=40);for(var St=0,F=0;F<I;F+=1)for(var M=0;M<I;M+=1)O.isDark(M,F)&&(St+=1);var ce=Math.abs(100*St/I/I-50)/5;return U+=ce*10,U},_})(),s=(function(){for(var E=new Array(256),A=new Array(256),k=0;k<8;k+=1)E[k]=1<<k;for(var k=8;k<256;k+=1)E[k]=E[k-4]^E[k-5]^E[k-6]^E[k-8];for(var k=0;k<255;k+=1)A[E[k]]=k;var B={};return B.glog=function(_){if(_<1)throw"glog("+_+")";return A[_]},B.gexp=function(_){for(;_<0;)_+=255;for(;_>=256;)_-=255;return E[_]},B})();function o(E,A){if(typeof E.length>"u")throw E.length+"/"+A;var k=(function(){for(var _=0;_<E.length&&E[_]==0;)_+=1;for(var H=new Array(E.length-_+A),O=0;O<E.length-_;O+=1)H[O]=E[O+_];return H})(),B={};return B.getAt=function(_){return k[_]},B.getLength=function(){return k.length},B.multiply=function(_){for(var H=new Array(B.getLength()+_.getLength()-1),O=0;O<B.getLength();O+=1)for(var I=0;I<_.getLength();I+=1)H[O+I]^=s.gexp(s.glog(B.getAt(O))+s.glog(_.getAt(I)));return o(H,0)},B.mod=function(_){if(B.getLength()-_.getLength()<0)return B;for(var H=s.glog(B.getAt(0))-s.glog(_.getAt(0)),O=new Array(B.getLength()),I=0;I<B.getLength();I+=1)O[I]=B.getAt(I);for(var I=0;I<_.getLength();I+=1)O[I]^=s.gexp(s.glog(_.getAt(I))+H);return o(O,0).mod(_)},B}var c=(function(){var E=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],A=function(_,H){var O={};return O.totalCount=_,O.dataCount=H,O},k={},B=function(_,H){switch(H){case e.L:return E[(_-1)*4+0];case e.M:return E[(_-1)*4+1];case e.Q:return E[(_-1)*4+2];case e.H:return E[(_-1)*4+3];default:return}};return k.getRSBlocks=function(_,H){var O=B(_,H);if(typeof O>"u")throw"bad rs block @ typeNumber:"+_+"/errorCorrectionLevel:"+H;for(var I=O.length/3,U=[],M=0;M<I;M+=1)for(var F=O[M*3+0],it=O[M*3+1],ot=O[M*3+2],q=0;q<F;q+=1)U.push(A(it,ot));return U},k})(),u=function(){var E=[],A=0,k={};return k.getBuffer=function(){return E},k.getAt=function(B){var _=Math.floor(B/8);return(E[_]>>>7-B%8&1)==1},k.put=function(B,_){for(var H=0;H<_;H+=1)k.putBit((B>>>_-H-1&1)==1)},k.getLengthInBits=function(){return A},k.putBit=function(B){var _=Math.floor(A/8);E.length<=_&&E.push(0),B&&(E[_]|=128>>>A%8),A+=1},k},f=function(E){var A=t.MODE_NUMBER,k=E,B={};B.getMode=function(){return A},B.getLength=function(O){return k.length},B.write=function(O){for(var I=k,U=0;U+2<I.length;)O.put(_(I.substring(U,U+3)),10),U+=3;U<I.length&&(I.length-U==1?O.put(_(I.substring(U,U+1)),4):I.length-U==2&&O.put(_(I.substring(U,U+2)),7))};var _=function(O){for(var I=0,U=0;U<O.length;U+=1)I=I*10+H(O.charAt(U));return I},H=function(O){if("0"<=O&&O<="9")return O.charCodeAt(0)-48;throw"illegal char :"+O};return B},d=function(E){var A=t.MODE_ALPHA_NUM,k=E,B={};B.getMode=function(){return A},B.getLength=function(H){return k.length},B.write=function(H){for(var O=k,I=0;I+1<O.length;)H.put(_(O.charAt(I))*45+_(O.charAt(I+1)),11),I+=2;I<O.length&&H.put(_(O.charAt(I)),6)};var _=function(H){if("0"<=H&&H<="9")return H.charCodeAt(0)-48;if("A"<=H&&H<="Z")return H.charCodeAt(0)-65+10;switch(H){case" ":return 36;case"$":return 37;case"%":return 38;case"*":return 39;case"+":return 40;case"-":return 41;case".":return 42;case"/":return 43;case":":return 44;default:throw"illegal char :"+H}};return B},l=function(E){var A=t.MODE_8BIT_BYTE,k=E,B=n.stringToBytes(E),_={};return _.getMode=function(){return A},_.getLength=function(H){return B.length},_.write=function(H){for(var O=0;O<B.length;O+=1)H.put(B[O],8)},_},p=function(E){var A=t.MODE_KANJI,k=E,B=n.stringToBytesFuncs.SJIS;if(!B)throw"sjis not supported.";(function(O,I){var U=B(O);if(U.length!=2||(U[0]<<8|U[1])!=I)throw"sjis not supported."})("\u53CB",38726);var _=B(E),H={};return H.getMode=function(){return A},H.getLength=function(O){return~~(_.length/2)},H.write=function(O){for(var I=_,U=0;U+1<I.length;){var M=(255&I[U])<<8|255&I[U+1];if(33088<=M&&M<=40956)M-=33088;else if(57408<=M&&M<=60351)M-=49472;else throw"illegal char at "+(U+1)+"/"+M;M=(M>>>8&255)*192+(M&255),O.put(M,13),U+=2}if(U<I.length)throw"illegal char at "+(U+1)},H},m=function(){var E=[],A={};return A.writeByte=function(k){E.push(k&255)},A.writeShort=function(k){A.writeByte(k),A.writeByte(k>>>8)},A.writeBytes=function(k,B,_){B=B||0,_=_||k.length;for(var H=0;H<_;H+=1)A.writeByte(k[H+B])},A.writeString=function(k){for(var B=0;B<k.length;B+=1)A.writeByte(k.charCodeAt(B))},A.toByteArray=function(){return E},A.toString=function(){var k="";k+="[";for(var B=0;B<E.length;B+=1)B>0&&(k+=","),k+=E[B];return k+="]",k},A},g=function(){var E=0,A=0,k=0,B="",_={},H=function(I){B+=String.fromCharCode(O(I&63))},O=function(I){if(!(I<0)){if(I<26)return 65+I;if(I<52)return 97+(I-26);if(I<62)return 48+(I-52);if(I==62)return 43;if(I==63)return 47}throw"n:"+I};return _.writeByte=function(I){for(E=E<<8|I&255,A+=8,k+=1;A>=6;)H(E>>>A-6),A-=6},_.flush=function(){if(A>0&&(H(E<<6-A),E=0,A=0),k%3!=0)for(var I=3-k%3,U=0;U<I;U+=1)B+="="},_.toString=function(){return B},_},w=function(E){var A=E,k=0,B=0,_=0,H={};H.read=function(){for(;_<8;){if(k>=A.length){if(_==0)return-1;throw"unexpected end of file./"+_}var I=A.charAt(k);if(k+=1,I=="=")return _=0,-1;if(I.match(/^\s$/))continue;B=B<<6|O(I.charCodeAt(0)),_+=6}var U=B>>>_-8&255;return _-=8,U};var O=function(I){if(65<=I&&I<=90)return I-65;if(97<=I&&I<=122)return I-97+26;if(48<=I&&I<=57)return I-48+52;if(I==43)return 62;if(I==47)return 63;throw"c:"+I};return H},S=function(E,A){var k=E,B=A,_=new Array(E*A),H={};H.setPixel=function(M,F,it){_[F*k+M]=it},H.write=function(M){M.writeString("GIF87a"),M.writeShort(k),M.writeShort(B),M.writeByte(128),M.writeByte(0),M.writeByte(0),M.writeByte(0),M.writeByte(0),M.writeByte(0),M.writeByte(255),M.writeByte(255),M.writeByte(255),M.writeString(","),M.writeShort(0),M.writeShort(0),M.writeShort(k),M.writeShort(B),M.writeByte(0);var F=2,it=I(F);M.writeByte(F);for(var ot=0;it.length-ot>255;)M.writeByte(255),M.writeBytes(it,ot,255),ot+=255;M.writeByte(it.length-ot),M.writeBytes(it,ot,it.length-ot),M.writeByte(0),M.writeString(";")};var O=function(M){var F=M,it=0,ot=0,q={};return q.write=function(z,tt){if(z>>>tt)throw"length over";for(;it+tt>=8;)F.writeByte(255&(z<<it|ot)),tt-=8-it,z>>>=8-it,ot=0,it=0;ot=z<<it|ot,it=it+tt},q.flush=function(){it>0&&F.writeByte(ot)},q},I=function(M){for(var F=1<<M,it=(1<<M)+1,ot=M+1,q=U(),z=0;z<F;z+=1)q.add(String.fromCharCode(z));q.add(String.fromCharCode(F)),q.add(String.fromCharCode(it));var tt=m(),St=O(tt);St.write(F,ot);var ce=0,Bt=String.fromCharCode(_[ce]);for(ce+=1;ce<_.length;){var dn=String.fromCharCode(_[ce]);ce+=1,q.contains(Bt+dn)?Bt=Bt+dn:(St.write(q.indexOf(Bt),ot),q.size()<4095&&(q.size()==1<<ot&&(ot+=1),q.add(Bt+dn)),Bt=dn)}return St.write(q.indexOf(Bt),ot),St.write(it,ot),St.flush(),tt.toByteArray()},U=function(){var M={},F=0,it={};return it.add=function(ot){if(it.contains(ot))throw"dup key:"+ot;M[ot]=F,F+=1},it.size=function(){return F},it.indexOf=function(ot){return M[ot]},it.contains=function(ot){return typeof M[ot]<"u"},it};return H},C=function(E,A,k){for(var B=S(E,A),_=0;_<A;_+=1)for(var H=0;H<E;H+=1)B.setPixel(H,_,k(H,_));var O=m();B.write(O);for(var I=g(),U=O.toByteArray(),M=0;M<U.length;M+=1)I.writeByte(U[M]);return I.flush(),"data:image/gif;base64,"+I};return n})();(function(){Tb.stringToBytesFuncs["UTF-8"]=function(n){function t(e){for(var i=[],r=0;r<e.length;r++){var s=e.charCodeAt(r);s<128?i.push(s):s<2048?i.push(192|s>>6,128|s&63):s<55296||s>=57344?i.push(224|s>>12,128|s>>6&63,128|s&63):(r++,s=65536+((s&1023)<<10|e.charCodeAt(r)&1023),i.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|s&63))}return i}return t(n)}})();(function(n){typeof define=="function"&&define.amd?define([],n):typeof Ob=="object"&&(Pb.exports=n())})(function(){return Tb})});var x4={};vu(x4,{ACCESS_ERROR_STATUS:()=>ub,ACCESS_PROTOCOL:()=>gu,ACCESS_VERSION:()=>ab,AccessError:()=>kt,BRC29_PROTOCOL:()=>cl,BWALLETX_RDNS:()=>Qo,DEFAULT_DISCOVER_MS:()=>Vi,GET_URL:()=>nl,LOGIN_PROTOCOL:()=>jd,LOGO_URL:()=>al,PROTOCOL_MEDIA:()=>Gd,PaymentError:()=>he,RDNS_EXTENSION:()=>Ns,RDNS_MOBILE:()=>Dd,SIGNIN_CSS:()=>sl,SIGNIN_TAG:()=>el,WALLET_THEME_META:()=>xu,WEB_WALLET_URL:()=>ra,accessErrorMessage:()=>lb,amountInSats:()=>ll,bindPrewarm:()=>fu,brc100Option:()=>Ls,buildAuthorizeUrl:()=>ol,buyToken:()=>Ib,canonicalJson:()=>ia,clearPairing:()=>ob,connectBwalletX:()=>na,declareWalletTheme:()=>Lb,defineBwalletxSignin:()=>yu,discoverBwalletX:()=>Ki,discoverWallets:()=>kb,findBwalletX:()=>jm,handcashAdapter:()=>Eb,inOrder:()=>ta,isIdentityKeyHex:()=>ul,isPaymail:()=>fl,isTouchDevice:()=>bl,markSvg:()=>rl,pairBwalletX:()=>_s,pairingModal:()=>_b,pairingOption:()=>gl,pay:()=>pl,pickWallet:()=>Cb,prewarmBwalletX:()=>Hd,protocolMediaUrl:()=>fb,proveHoldings:()=>Jd,qrSvg:()=>ml,renderButton:()=>mb,requestAccess:()=>bu,resolvePaymailP2P:()=>hl,restorePairing:()=>Cs,signInWithBwalletX:()=>pu,signinText:()=>il,throwIfAccessError:()=>Zd,tip:()=>Sb,toAccessError:()=>mu});var Eu=globalThis.Buffer,Kb=Eu!=null&&typeof Eu.from=="function",$s=new Int8Array(256).fill(-1);for(let n=0;n<10;n++)$s[48+n]=n;for(let n=0;n<6;n++)$s[65+n]=10+n,$s[97+n]=10+n;var qs,Fs,aa,ca,fi,ua,Ws,Y,rt,It,R,vl,Al,El,kl,Tl,Ol,ku,_e,An,st,Pl,Ms,Ds,Rl,Nl,ji,Bl,_l,Cl,Lt,ue,Hs,oa,Xi,Tu,Ll,Ou,Z=class Z{constructor(t=0,e=10,i="be"){G(this,R);G(this,Y,0n);G(this,rt,0);G(this,It,1);b(this,"red",null);if(t??(t=0),typeof t=="bigint"){a(this,R,_e).call(this,t<0n?-t:t,t<0n?1:0),this.normSign();return}let r=e==="le"||e==="be",s=r?10:e,o=r?e:i;if(typeof t=="number"){a(this,R,Pl).call(this,t,o);return}if(Array.isArray(t)){a(this,R,Ms).call(this,t,o);return}if(typeof t=="string"){a(this,R,Al).call(this,t,s,o);return}t!==0?a(this,R,st).call(this,!1,"Unsupported input type for BigNumber constructor"):a(this,R,_e).call(this,0n,0)}get negative(){return y(this,rt)}set negative(t){a(this,R,st).call(this,t===0||t===1,"Negative property must be 0 or 1");let e=t===1?1:0;y(this,Y)===0n?N(this,rt,0):N(this,rt,e)}get words(){if(!Number.isSafeInteger(y(this,It))||y(this,It)<1||y(this,It)>y(Z,Ws))throw new Error("BigNumber word length exceeds the supported limit");let t=y(this,R,vl);if(y(this,It)<=t.length)return t;let e=Array.from({length:y(this,It)}).fill(0);for(let i=0;i<t.length;i++)e[i]=t[i];return e}set words(t){let e=y(this,rt),i=0n,r=t.length>0?t.length:1;for(let s=r-1;s>=0;s--){let o=t[s]??0;i=i<<y(Z,qs)|BigInt(o&Number(y(Z,Fs)))}N(this,Y,i),N(this,rt,e),N(this,It,r),this.normSign()}get length(){return Math.max(1,y(this,It))}static isBN(t){return t instanceof Z?!0:t!==null&&typeof t=="object"&&t.constructor?.wordSize===Z.wordSize&&Array.isArray(t.words)}static max(t,e){return t.cmp(e)>0?t:e}static min(t,e){return t.cmp(e)<0?t:e}copy(t){N(t,Y,y(this,Y)),N(t,rt,y(this,rt)),N(t,It,y(this,It)),t.red=this.red}static move(t,e){N(t,Y,y(e,Y)),N(t,rt,y(e,rt)),N(t,It,y(e,It)),t.red=e.red}clone(){let t=new Z(0n);return this.copy(t),t}expand(t){return a(this,R,st).call(this,Number.isSafeInteger(t)&&t>=0&&t<=y(Z,Ws),"Expand size must be a non-negative safe integer within the supported word limit"),N(this,It,Math.max(y(this,It),t,1)),this}strip(){return a(this,R,An).call(this),this.normSign()}normSign(){return y(this,Y)===0n&&N(this,rt,0),this}inspect(){return(this.red===null?"<BN: ":"<BN-R: ")+this.toString(16)+">"}toString(t=10,e=1){if(t===16||t==="hex")return a(this,R,Rl).call(this,e);if(typeof t!="number"||t<2||t>36||t%1!==0)throw new Error("Base should be an integer between 2 and 36");return a(this,R,Nl).call(this,t,e)}toNumber(){let t=a(this,R,Lt).call(this);if(t>y(Z,aa)||t<y(Z,ca))throw new Error("Number can only safely store up to 53 bits");return Number(t)}toBigInt(){return a(this,R,Lt).call(this)}toJSON(){let t=a(this,R,Ds).call(this);return(this.isNeg()?"-":"")+t}toArray(t="be",e){this.strip();let i=this.byteLength(),r=e??Math.max(1,i);a(this,R,st).call(this,i<=r,"byte array longer than desired length"),a(this,R,st).call(this,r>0,"Requested array length <= 0");let s=Array.from({length:r}).fill(0);return y(this,Y)===0n&&r>0?s:y(this,Y)===0n&&r===0?[]:(a(this,R,Cl).call(this,s,t==="le"),s)}bitLength(){return y(this,Y)===0n?0:y(this,Y).toString(2).length}static toBitArray(t){let e=t.bitLength();if(e===0)return[];let i=Array.from({length:e}),r=y(t,Y);for(let s=0;s<e;s++)i[s]=(r>>BigInt(s)&1n)===0n?0:1;return i}toBitArray(){return Z.toBitArray(this)}zeroBits(){if(y(this,Y)===0n)return 0;let t=0,e=y(this,Y);for(;(e&1n)===0n&&e!==0n;)t++,e>>=1n;return t}byteLength(){return y(this,Y)===0n?0:Math.ceil(this.bitLength()/8)}toTwos(t){var o;a(this,R,st).call(this,t>=0);let e=BigInt(t),i=a(this,R,Lt).call(this);y(this,rt)===1&&y(this,Y)!==0n&&(i=(1n<<e)+i);let r=(1n<<e)-1n;i&=r;let s=new Z(0n);return a(o=s,R,_e).call(o,i,0),s}fromTwos(t){var r;a(this,R,st).call(this,t>=0);let e=BigInt(t),i=y(this,Y);if(t>0&&(i>>e-1n&1n)!==0n&&y(this,rt)===0){let s=i-(1n<<e),o=new Z(0n);return a(r=o,R,ue).call(r,s),o}return this.clone()}isNeg(){return y(this,rt)===1&&y(this,Y)!==0n}neg(){return this.clone().ineg()}ineg(){return y(this,Y)!==0n&&N(this,rt,y(this,rt)===1?0:1),this}iuor(t){return a(this,R,Hs).call(this,t,(e,i)=>e|i)}iuand(t){return a(this,R,Hs).call(this,t,(e,i)=>e&i)}iuxor(t){return a(this,R,Hs).call(this,t,(e,i)=>e^i,!0)}ior(t){return a(this,R,oa).call(this,t,(e,i)=>e|i)}iand(t){return a(this,R,oa).call(this,t,(e,i)=>e&i)}ixor(t){return a(this,R,oa).call(this,t,(e,i)=>e^i,!0)}or(t){return a(this,R,st).call(this,y(this,rt)===0&&y(t,rt)===0),a(this,R,Xi).call(this,t,"iuor")}uor(t){return a(this,R,Xi).call(this,t,"iuor")}and(t){return a(this,R,st).call(this,y(this,rt)===0&&y(t,rt)===0),a(this,R,Xi).call(this,t,"iuand")}uand(t){return a(this,R,Xi).call(this,t,"iuand")}xor(t){return a(this,R,st).call(this,y(this,rt)===0&&y(t,rt)===0),a(this,R,Xi).call(this,t,"iuxor")}uxor(t){return a(this,R,Xi).call(this,t,"iuxor")}inotn(t){a(this,R,st).call(this,typeof t=="number"&&t>=0);let i=(1n<<BigInt(t))-1n;N(this,Y,~y(this,Y)&i);let r=t===0?1:Math.ceil(t/Z.wordSize);return N(this,It,Math.max(1,r)),this.strip(),N(this,It,Math.max(y(this,It),Math.max(1,r))),this}notn(t){return this.clone().inotn(t)}setn(t,e){a(this,R,st).call(this,typeof t=="number"&&t>=0);let i=BigInt(t);e===1||e===!0?N(this,Y,y(this,Y)|1n<<i):N(this,Y,y(this,Y)&~(1n<<i));let r=Math.floor(t/Z.wordSize)+1;return N(this,It,Math.max(y(this,It),r)),a(this,R,An).call(this),this.strip()}iadd(t){var e;return a(this,R,ue).call(this,a(this,R,Lt).call(this)+a(e=t,R,Lt).call(e)),this}add(t){var i,r;let e=new Z(0n);return a(r=e,R,ue).call(r,a(this,R,Lt).call(this)+a(i=t,R,Lt).call(i)),e}isub(t){var e;return a(this,R,ue).call(this,a(this,R,Lt).call(this)-a(e=t,R,Lt).call(e)),this}sub(t){var i,r;let e=new Z(0n);return a(r=e,R,ue).call(r,a(this,R,Lt).call(this)-a(i=t,R,Lt).call(i)),e}mul(t){let e=new Z(0n);return N(e,Y,y(this,Y)*y(t,Y)),N(e,rt,y(e,Y)===0n?0:y(this,rt)^y(t,rt)),N(e,It,this.length+t.length),e.red=null,e.normSign()}imul(t){return N(this,Y,y(this,Y)*y(t,Y)),N(this,rt,y(this,Y)===0n?0:y(this,rt)^y(t,rt)),N(this,It,this.length+t.length),this.red=null,this.normSign()}imuln(t){return a(this,R,st).call(this,typeof t=="number","Assertion failed"),a(this,R,st).call(this,Math.abs(t)<=y(Z,fi),"Assertion failed"),a(this,R,ue).call(this,a(this,R,Lt).call(this)*BigInt(t)),this}muln(t){return this.clone().imuln(t)}sqr(){let t=new Z(0n);return N(t,Y,y(this,Y)*y(this,Y)),N(t,rt,0),N(t,It,this.length*2),t.red=null,t}isqr(){return N(this,Y,y(this,Y)*y(this,Y)),N(this,rt,0),N(this,It,this.length*2),this.red=null,this}pow(t){if(a(this,R,st).call(this,y(t,rt)===0,"Exponent for pow must be non-negative"),t.isZero())return new Z(1n);let e=new Z(1n),i=this.clone(),r=t.clone(),s=i.isNeg(),o=r.isOdd();for(s&&i.ineg();!r.isZero();)r.isOdd()&&e.imul(i),i.isqr(),r.iushrn(1);return s&&o&&e.ineg(),e}iushln(t){var i;let e=a(i=Z,ji,Tu).call(i,t,"Shift bits");return e===0n?this:(N(this,Y,y(this,Y)<<e),a(this,R,An).call(this),this.strip())}ishln(t){return a(this,R,st).call(this,y(this,rt)===0,"ishln requires positive number"),this.iushln(t)}iushrn(t,e,i){var s,o,c;let r=a(s=Z,ji,Tu).call(s,t,"Shift bits");if(r===0n)return i!=null&&a(o=i,R,_e).call(o,0n,0),this;if(i!=null){let u=(1n<<r)-1n,f=y(this,Y)&u;a(c=i,R,_e).call(c,f,0)}return N(this,Y,y(this,Y)>>r),a(this,R,An).call(this),this.strip()}ishrn(t,e,i){return a(this,R,st).call(this,y(this,rt)===0,"ishrn requires positive number"),this.iushrn(t,e,i)}shln(t){return this.clone().ishln(t)}ushln(t){return this.clone().iushln(t)}shrn(t){return this.clone().ishrn(t)}ushrn(t){return this.clone().iushrn(t)}testn(t){return a(this,R,st).call(this,typeof t=="number"&&t>=0),(y(this,Y)>>BigInt(t)&1n)!==0n}imaskn(t){a(this,R,st).call(this,typeof t=="number"&&t>=0),a(this,R,st).call(this,y(this,rt)===0,"imaskn works only with positive numbers");let e=BigInt(t),i=e===0n?0n:(1n<<e)-1n;N(this,Y,y(this,Y)&i);let r=t===0?1:Math.max(1,Math.ceil(t/Z.wordSize));return N(this,It,r),a(this,R,An).call(this),N(this,It,Math.max(y(this,It),r)),this.strip()}maskn(t){return this.clone().imaskn(t)}iaddn(t){return a(this,R,st).call(this,typeof t=="number"),a(this,R,st).call(this,Math.abs(t)<=y(Z,fi),"num is too large"),a(this,R,ue).call(this,a(this,R,Lt).call(this)+BigInt(t)),this}_iaddn(t){return this.iaddn(t)}isubn(t){return a(this,R,st).call(this,typeof t=="number"),a(this,R,st).call(this,Math.abs(t)<=y(Z,fi),"Assertion failed"),a(this,R,ue).call(this,a(this,R,Lt).call(this)-BigInt(t)),this}addn(t){return this.clone().iaddn(t)}subn(t){return this.clone().isubn(t)}iabs(){return N(this,rt,0),this}abs(){return this.clone().iabs()}divmod(t,e,i){var u;if(a(this,R,st).call(this,!t.isZero(),"Division by zero"),this.isZero()){let f=new Z(0n);return{div:e==="mod"?null:f,mod:e==="div"?null:f}}let r=a(this,R,Lt).call(this),s=a(u=t,R,Lt).call(u),o=e!=="mod"?r/s:null,c=a(this,R,Ll).call(this,r,s,e,i);return{div:a(this,R,Ou).call(this,o),mod:a(this,R,Ou).call(this,c)}}div(t){return this.divmod(t,"div",!1).div}mod(t){return this.divmod(t,"mod",!1).mod}umod(t){return this.divmod(t,"mod",!0).mod}divRound(t){var f,d,l;a(this,R,st).call(this,!t.isZero());let e=a(this,R,Lt).call(this),i=a(f=t,R,Lt).call(f),r=e/i,s=e%i;if(s===0n){let p=new Z(0n);return a(d=p,R,ue).call(d,r),p}let o=s<0n?-s:s,c=i<0n?-i:i;o*2n>=c&&(e>0n&&i>0n||e<0n&&i<0n?r+=1n:r-=1n);let u=new Z(0n);return a(l=u,R,ue).call(l,r),u}modrn(t){a(this,R,st).call(this,t!==0,"Division by zero in modrn");let e=BigInt(Math.abs(t));if(e===0n)throw new Error("Division by zero in modrn");let i=y(this,Y)%e;return t<0?Number(-i):Number(i)}idivn(t){return a(this,R,st).call(this,t!==0),a(this,R,st).call(this,Math.abs(t)<=y(Z,fi),"num is too large"),a(this,R,ue).call(this,a(this,R,Lt).call(this)/BigInt(t)),this}divn(t){return this.clone().idivn(t)}egcd(t){var l,p,m;a(this,R,st).call(this,t.negative===0,"p must not be negative"),a(this,R,st).call(this,!t.isZero(),"p must not be zero");let e=a(this,R,Lt).call(this),i=y(t,Y),r=1n,s=0n,o=0n,c=1n;for(;i!==0n;){let g=e/i,w=i;i=e%i,e=w,w=s,s=r-g*s,r=w,w=c,c=o-g*c,o=w}let u=new Z(0n);a(l=u,R,ue).call(l,r);let f=new Z(0n);a(p=f,R,ue).call(p,o);let d=new Z(0n);return a(m=d,R,_e).call(m,e<0n?-e:e,0),{a:u,b:f,gcd:d}}gcd(t){var s,o,c;let e=y(this,Y),i=y(t,Y);if(e===0n){let u=new Z(0n);return a(s=u,R,ue).call(s,i),u.iabs()}if(i===0n){let u=new Z(0n);return a(o=u,R,ue).call(o,e),u.iabs()}for(;i!==0n;){let u=e%i;e=i,i=u}let r=new Z(0n);return a(c=r,R,_e).call(c,e,0),r}invm(t){a(this,R,st).call(this,!t.isZero()&&y(t,rt)===0,"Modulus for invm must be positive and non-zero");let e=this.egcd(t);if(!e.gcd.eqn(1))throw new Error("Inverse does not exist (numbers are not coprime).");return e.a.umod(t)}isEven(){return y(this,Y)%2n===0n}isOdd(){return y(this,Y)%2n===1n}andln(t){return a(this,R,st).call(this,t>=0),Number(y(this,Y)&BigInt(t))}bincn(t){a(this,R,st).call(this,typeof t=="number"&&t>=0);let e=1n<<BigInt(t);return a(this,R,ue).call(this,a(this,R,Lt).call(this)+e),this}isZero(){return y(this,Y)===0n}cmpn(t){a(this,R,st).call(this,Math.abs(t)<=y(Z,fi),"Number is too big");let e=a(this,R,Lt).call(this),i=BigInt(t);return e<i?-1:e>i?1:0}cmp(t){var r;let e=a(this,R,Lt).call(this),i=a(r=t,R,Lt).call(r);return e<i?-1:e>i?1:0}ucmp(t){return y(this,Y)<y(t,Y)?-1:y(this,Y)>y(t,Y)?1:0}gtn(t){return this.cmpn(t)===1}gt(t){return this.cmp(t)===1}gten(t){return this.cmpn(t)>=0}gte(t){return this.cmp(t)>=0}ltn(t){return this.cmpn(t)===-1}lt(t){return this.cmp(t)===-1}lten(t){return this.cmpn(t)<=0}lte(t){return this.cmp(t)<=0}eqn(t){return this.cmpn(t)===0}eq(t){return this.cmp(t)===0}toRed(t){return a(this,R,st).call(this,this.red==null,"Already a number in reduction context"),a(this,R,st).call(this,y(this,rt)===0,"toRed works only with positives"),t.convertTo(this).forceRed(t)}fromRed(){return a(this,R,st).call(this,this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)}forceRed(t){return this.red=t,this}redAdd(t){return a(this,R,st).call(this,this.red,"redAdd works only with red numbers"),this.red.add(this,t)}redIAdd(t){return a(this,R,st).call(this,this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)}redSub(t){return a(this,R,st).call(this,this.red,"redSub works only with red numbers"),this.red.sub(this,t)}redISub(t){return a(this,R,st).call(this,this.red,"redISub works only with red numbers"),this.red.isub(this,t)}redShl(t){return a(this,R,st).call(this,this.red,"redShl works only with red numbers"),this.red.shl(this,t)}redMul(t){return a(this,R,st).call(this,this.red,"redMul works only with red numbers"),this.red.verify2(this,t),this.red.mul(this,t)}redIMul(t){return a(this,R,st).call(this,this.red,"redIMul works only with red numbers"),this.red.verify2(this,t),this.red.imul(this,t)}redSqr(){return a(this,R,st).call(this,this.red,"redSqr works only with red numbers"),this.red.verify1(this),this.red.sqr(this)}redISqr(){return a(this,R,st).call(this,this.red,"redISqr works only with red numbers"),this.red.verify1(this),this.red.isqr(this)}redSqrt(){return a(this,R,st).call(this,this.red,"redSqrt works only with red numbers"),this.red.verify1(this),this.red.sqrt(this)}redInvm(){return a(this,R,st).call(this,this.red,"redInvm works only with red numbers"),this.red.verify1(this),this.red.invm(this)}redNeg(){return a(this,R,st).call(this,this.red,"redNeg works only with red numbers"),this.red.verify1(this),this.red.neg(this)}redPow(t){return a(this,R,st).call(this,this.red!=null&&t.red==null,"redPow(normalNum)"),this.red.verify1(this),this.red.pow(this,t)}static fromHex(t,e){let i="be";return(e==="little"||e==="le")&&(i="le"),new Z(t,16,i)}toHex(t=0){if(this.isZero()&&t===0)return"";let e=a(this,R,Ds).call(this);e!=="0"&&e.length%2!==0&&(e="0"+e);let i=t*2;for(;e.length<i;)e="0"+e;return(this.isNeg()?"-":"")+e}static fromJSON(t){return new Z(t,16)}static fromNumber(t){return new Z(t)}static fromString(t,e){return new Z(t,e)}static fromSm(t,e="big"){var u;if(t.length===0)return new Z(0n);let i=t.slice();e==="little"&&i.reverse();let r=0;i.length>0&&(i[0]&128)!==0&&(r=1,i[0]&=127);let s;if(Kb)s=Eu.from(i).toString("hex");else{s="";for(let f of i)s+=f<16?"0"+f.toString(16):f.toString(16)}let o=s.length===0?0n:BigInt("0x"+s),c=new Z(0n);return a(u=c,R,_e).call(u,o,r),c}toSm(t="big"){if(y(this,Y)===0n)return y(this,rt)===1?[128]:[];let e=a(this,R,Ds).call(this);e.length%2!==0&&(e="0"+e);let i=e.length/2,r=Array.from({length:i});for(let o=0,c=0;o<e.length;o+=2){let u=$s[e.codePointAt(o)],f=$s[e.codePointAt(o+1)];r[c++]=(u&15)<<4|f&15}let s;return y(this,rt)===1?(r[0]&128)===0?(s=r.slice(),s[0]|=128):s=[128,...r]:(r[0]&128)===0?s=r.slice():s=[0,...r],t==="little"?s.reverse():s}static fromBits(t,e=!1){let i=t>>>24,r=t&8388607,s=(t&8388608)!==0;if(e&&s)throw new Error("negative bit set");if(i===0&&r===0){if(s&&e)throw new Error("negative bit set for zero value");return new Z(0n)}let o=new Z(r);return i<=3?o.iushrn((3-i)*8):o.iushln((i-3)*8),s&&o.ineg(),o}toBits(){if(this.strip(),this.isZero()&&!this.isNeg())return 0;let t=this.isNeg(),i=this.abs().toArray("be"),r=0;for(;r<i.length-1&&i[r]===0;)r++;i=i.slice(r);let s=i.length,o;if(s===0)o=0;else if(s<=3){o=0;for(let u=0;u<s;u++)o=o<<8|i[u]}else o=i[0]<<16|i[1]<<8|i[2];(o&8388608)!==0&&s<=255&&(o>>>=8,s++);let c=s<<24|o;return t&&(c|=8388608),c>>>0}static fromScriptNum(t,e=!1,i){if(i!==void 0&&t.length>i)throw new Error("script number overflow");if(t.length===0)return new Z(0n);if(e&&(t.at(-1)&127)===0&&(t.length<=1||(t.at(-2)&128)===0))throw new Error("non-minimally encoded script number");return Z.fromSm(t,"little")}toScriptNum(){return this.toSm("little")}_invmp(t){a(this,R,st).call(this,y(t,rt)===0,"p must not be negative for _invmp"),a(this,R,st).call(this,!t.isZero(),"p must not be zero for _invmp");let e=this.umod(t),i=t.subn(2);if(e.red!==null)return e.redPow(i);let r=new Z(1n),s=e.clone(),o=i.clone();for(;!o.isZero();)o.isOdd()&&(r=r.mul(s).umod(t)),s=s.sqr().umod(t),o.iushrn(1);return r}mulTo(t,e){return N(e,Y,y(this,Y)*y(t,Y)),N(e,rt,y(e,Y)===0n?0:y(this,rt)^y(t,rt)),N(e,It,this.length+t.length),e.red=null,e.normSign(),e}};qs=new WeakMap,Fs=new WeakMap,aa=new WeakMap,ca=new WeakMap,fi=new WeakMap,ua=new WeakMap,Ws=new WeakMap,Y=new WeakMap,rt=new WeakMap,It=new WeakMap,R=new WeakSet,vl=function(){if(y(this,Y)===0n)return[0];let t=[],e=y(this,Y);for(;e>0n;)t.push(Number(e&y(Z,Fs))),e>>=y(Z,qs);return t.length>0?t:[0]},Al=function(t,e,i){e==="hex"&&(e=16),a(this,R,st).call(this,typeof e=="number"&&e===Math.trunc(e)&&e>=2&&e<=36,"Base must be an integer between 2 and 36");let r=t.toString().replace(/\s+/g,""),s=0,o=0;r.startsWith("-")?(s++,o=1):r.startsWith("+")&&s++;let c=r.substring(s);if(c.length===0){a(this,R,_e).call(this,0n,o===1&&r.startsWith("-")?1:0),this.normSign();return}e===16?a(this,R,El).call(this,c,o,i):a(this,R,kl).call(this,c,e,o,i)},El=function(t,e,i){if(i==="le"){let r=[],s=t;s.length%2!==0&&(s="0"+s);for(let o=0;o<s.length;o+=2){let c=s.substring(o,o+2),u=Number.parseInt(c,16);if(Number.isNaN(u))throw new Error("Invalid character in "+s);r.push(u)}a(this,R,Ms).call(this,r,"le"),N(this,rt,e),this.normSign()}else{let r;try{r=BigInt("0x"+t)}catch{throw new Error("Invalid character in "+t)}a(this,R,_e).call(this,r,e),this.normSign()}},kl=function(t,e,i,r){try{if(a(this,R,Ol).call(this,t,e),N(this,rt,i),this.normSign(),r==="le"){let s=y(this,rt);a(this,R,Ms).call(this,this.toArray("be"),"le"),N(this,rt,s),this.normSign()}}catch(s){let o=s;throw o.message.includes("Invalid character in string")||o.message.includes("Invalid digit for base")||o.message.startsWith("Invalid character:")?new Error("Invalid character"):o}},Tl=function(t,e){if(t===0n)return"0";if(e<2||e>36)throw new Error("Base must be between 2 and 36");let i="0123456789abcdefghijklmnopqrstuvwxyz",r="",s=t>0n?t:-t,o=BigInt(e);for(;s>0n;)r=i[Number(s%o)]+r,s/=o;return r},Ol=function(t,e){N(this,Y,0n);let i=BigInt(e),r=Z.groupSizes[e],s=BigInt(Z.groupBases[e]);(r===0||s===0n)&&(r=Math.floor(Math.log(67108863)/Math.log(e)),r===0&&(r=1),s=i**BigInt(r));let o=0,c=t.length,u=c%r;if(u===0&&c>0&&(u=r),u>0){let f=t.substring(o,o+u);N(this,Y,BigInt(a(this,R,ku).call(this,f,e))),o+=u}for(;o<c;){let f=t.substring(o,o+r),d=BigInt(a(this,R,ku).call(this,f,e));N(this,Y,y(this,Y)*s+d),o+=r}a(this,R,An).call(this)},ku=function(t,e){let i=0;for(let r=0;r<t.length;r++){let s=t.codePointAt(r),o;if(s>=48&&s<=57)o=s-48;else if(s>=65&&s<=90)o=s-65+10;else if(s>=97&&s<=122)o=s-97+10;else throw new Error("Invalid character: "+t[r]);if(o>=e)throw new Error("Invalid character");i=i*e+o}return i},_e=function(t,e){N(this,Y,t),N(this,rt,t===0n?0:e),a(this,R,An).call(this)},An=function(){if(y(this,Y)===0n)N(this,It,1),N(this,rt,0);else{let t=y(this,Y).toString(2).length;N(this,It,Math.max(1,Math.ceil(t/Z.wordSize)))}},st=function(t,e="Assertion failed"){if(!t)throw new Error(e)},Pl=function(t,e="be"){if(a(this,R,st).call(this,BigInt(Math.abs(t))<=y(Z,ua),"The number is larger than 2 ^ 53 (unsafe)"),a(this,R,st).call(this,t%1===0,"Number must be an integer for BigNumber conversion"),a(this,R,_e).call(this,BigInt(Math.abs(t)),t<0?1:0),e==="le"){let i=y(this,rt),r=this.toArray("be");a(this,R,Ms).call(this,r,"le"),N(this,rt,i),this.normSign()}return this},Ms=function(t,e){if(t.length===0)return a(this,R,_e).call(this,0n,0),this;let i=0n;if(e==="be")for(let r of t)i=i<<8n|BigInt(r&255);else for(let r=t.length-1;r>=0;r--)i=i<<8n|BigInt(t[r]&255);return a(this,R,_e).call(this,i,0),this},Ds=function(){return y(this,Y)===0n?"0":y(this,Y).toString(16)},Rl=function(t){let e=a(this,R,Ds).call(this);if(t>1)for(e!=="0"&&e.length%2!==0&&(e="0"+e);e.length%t!==0;)e="0"+e;return(this.isNeg()?"-":"")+e},Nl=function(t,e){var c;if(y(this,Y)===0n)return a(c=Z,ji,Bl).call(c,e);let i=Z.groupSizes[t],r=BigInt(Z.groupBases[t]);(i===0||r===0n)&&(i=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(t)),i===0&&(i=1),r=BigInt(t)**BigInt(i));let s="",o=y(this,Y);for(;o>0n;){let u=o%r;o/=r;let f=a(this,R,Tl).call(this,u,t);s=(o>0n?a(this,R,_l).call(this,f,i):f)+s}if(e>0)for(;s.length<e;)s="0"+s;return(y(this,rt)===1?"-":"")+s},ji=new WeakSet,Bl=function(t){let e="0";if(t>1)for(;e.length<t;)e="0"+e;return e},_l=function(t,e){let i=e-t.length;return i<=0?t:i<Z.zeros.length?Z.zeros[i]+t:"0".repeat(i)+t},Cl=function(t,e){let i=y(this,Y),r=e?0:t.length-1,s=e?1:-1;for(let o of t){if(i===0n&&r>=0&&r<t.length)t[r]=0;else if(r>=0&&r<t.length)t[r]=Number(i&0xffn);else break;i>>=8n,r+=s}},Lt=function(){return y(this,rt)===1?-y(this,Y):y(this,Y)},ue=function(t){t<0n?(N(this,Y,-t),N(this,rt,1)):(N(this,Y,t),N(this,rt,0)),a(this,R,An).call(this),this.normSign()},Hs=function(t,e,i=!1){let r=e(y(this,Y),y(t,Y)),s=y(this,It);return i&&(s=Math.max(this.length,t.length)),N(this,Y,r),a(this,R,An).call(this),i&&N(this,It,Math.max(y(this,It),s)),this.strip()},oa=function(t,e,i=!1){return a(this,R,st).call(this,y(this,rt)===0&&y(t,rt)===0),a(this,R,Hs).call(this,t,e,i)},Xi=function(t,e){return this.length>=t.length?this.clone()[e](t):t.clone()[e](this)},Tu=function(t,e){if(typeof t=="number"){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return BigInt(t)}if(t<0n)throw new Error(`${e} must be a non-negative integer`);return t},Ll=function(t,e,i,r){if(i==="div")return null;let s=t%e;return r===!0&&s<0n&&(s+=e<0n?-e:e),s},Ou=function(t){var i;if(t===null)return null;let e=new Z(0n);return a(i=e,R,ue).call(i,t),e},G(Z,ji),b(Z,"zeros",["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"]),b(Z,"groupSizes",[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5]),b(Z,"groupBases",[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176]),b(Z,"wordSize",26),G(Z,qs,26n),G(Z,Fs,(1n<<26n)-1n),G(Z,aa,BigInt(Number.MAX_SAFE_INTEGER)),G(Z,ca,BigInt(Number.MIN_SAFE_INTEGER)),G(Z,fi,67108863),G(Z,ua,(1n<<53n)-1n),G(Z,Ws,1048576);var T=Z;var Vs=class{constructor(t,e){b(this,"name");b(this,"p");b(this,"k");b(this,"n");b(this,"tmp");this.name=t,this.p=new T(e,16),this.n=this.p.bitLength(),this.k=new T(BigInt(1)).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){let t=new T(BigInt(0)),e=Math.ceil(this.n/T.wordSize);return t.expand(Math.max(1,e)),t}ireduce(t){let e=t,i;do this.split(e,this.tmp),this.imulK(e),e.iadd(this.tmp),i=e.bitLength();while(i>this.n);let r=i<this.n?-1:e.ucmp(this.p);return r===0?e.words=[0]:r>0&&e.isub(this.p),e.strip(),e}split(t,e){t.iushrn(this.n,0,e)}imulK(t){return t.imul(this.k)}};var Ks=class extends Vs{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(t,e){let r=t.words,s=t.length,o=Math.min(s,9),c=Array.from({length:o+(s>9?1:0)},()=>0);for(let g=0;g<o;g++)c[g]=r[g];let u=o;if(s<=9){let g=Array.from({length:u},()=>0);for(let w=0;w<u;++w)g[w]=c[w];e.words=g,t.words=[0];return}let f=r[9];c[u++]=f&4194303;let d=Array.from({length:u},()=>0);for(let g=0;g<u;++g)d[g]=c[g];e.words=d;let l=Array.from({length:Math.max(1,s-9)},()=>0),p=0;for(let g=10;g<s;g++){let w=Math.trunc(r[g]);p<l.length&&(l[p++]=(w&4194303)<<4|f>>>22),f=w}f>>>=22,p<l.length?l[p++]=f:f!==0&&l.length>0;let m=Array.from({length:p},()=>0);for(let g=0;g<p;++g)m[g]=l[g];t.words=m}imulK(t){let e=t.words,i=t.length,r=i+2,s=Array.from({length:r},()=>0);for(let c=0;c<i;c++)s[c]=e[c];let o=0;for(let c=0;c<r;c++){let u=Math.trunc(s[c]);o+=u*977,s[c]=o&67108863,o=u*64+Math.trunc(o/67108864)}return t.words=s,t}};var Gi=class{constructor(t){b(this,"prime");b(this,"m");if(t==="k256"){let e=new Ks;this.m=e.p,this.prime=e}else this.assert(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}assert(t,e="Assertion failed"){if(!t)throw new Error(e)}verify1(t){this.assert(t.negative===0,"red works only with positives"),this.assert(t.red,"red works only with red numbers")}verify2(t,e){this.assert((t.negative|e.negative)===0,"red works only with positives"),this.assert(t.red!=null&&t.red===e.red,"red works only with red numbers")}imod(t){return this.prime!=null?this.prime.ireduce(t).forceRed(this):(T.move(t,t.umod(this.m).forceRed(this)),t)}neg(t){return t.isZero()?t.clone():this.m.sub(t).forceRed(this)}add(t,e){this.verify2(t,e);let i=t.clone();return i.iadd(e),i.isub(this.m),i.isNeg()&&i.iadd(this.m),i}iadd(t,e){return this.verify2(t,e),t.iadd(e),t.isub(this.m),t.isNeg()&&t.iadd(this.m),t}sub(t,e){this.verify2(t,e);let i=t.sub(e);return i.cmpn(0)<0&&i.iadd(this.m),i.forceRed(this)}isub(t,e){this.verify2(t,e);let i=t.isub(e);return i.cmpn(0)<0&&i.iadd(this.m),i}shl(t,e){return this.verify1(t),this.imod(t.ushln(e))}imul(t,e){return this.verify2(t,e),this.imod(t.imul(e))}mul(t,e){return this.verify2(t,e),this.imod(t.mul(e))}isqr(t){return this.imul(t,t.clone())}sqr(t){return this.mul(t,t)}sqrt(t){if(t.isZero())return t.clone();let e=this.m.andln(3);if(this.assert(e%2===1),e===3){let g=this.m.add(new T(1)).iushrn(2);return this.pow(t,g)}let i=this.m.subn(1),r=0;for(;!i.isZero()&&i.andln(1)===0;)r++,i.iushrn(1);this.assert(!i.isZero());let s=new T(1).toRed(this),o=s.redNeg(),c=this.m.subn(1).iushrn(1),u=this.m.bitLength(),f=new T(2*u*u).toRed(this);for(;this.pow(f,c).cmp(o)!==0;)f.redIAdd(o);let d=this.pow(f,i),l=this.pow(t,i.addn(1).iushrn(1)),p=this.pow(t,i),m=r;for(;p.cmp(s)!==0;){let g=p,w=0;for(;g.cmp(s)!==0;)g=g.redSqr(),w++;this.assert(w<m);let S=this.pow(d,new T(1).iushln(m-w-1));l=l.redMul(S),d=S.redSqr(),p=p.redMul(d),m=w}return l}invm(t){let e=t._invmp(this.m);return e.negative!==0?(e.negative=0,this.imod(e).redNeg()):this.imod(e)}pow(t,e){if(this.verify1(t),e.isZero())return new T(1).toRed(this);let i=new T(1).toRed(this),r=t.clone(),s=e.bitLength();for(let o=s-1;o>=0;o--)i=this.sqr(i),e.testn(o)&&(i=this.mul(i,r));return i}convertTo(t){let e=t.umod(this.m);return e===t?e.clone():e}convertFrom(t){let e=t.clone();return e.red=null,e}};var zs=class extends Gi{constructor(e){super(e);b(this,"shift");b(this,"r");b(this,"r2");b(this,"rinv");b(this,"minv");this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new T(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}convertTo(e){return this.imod(e.ushln(this.shift))}convertFrom(e){let i=this.imod(e.mul(this.rinv));return i.red=null,i}imul(e,i){if(e.isZero()||i.isZero())return e.words[0]=0,e.length=1,e;let r=e.imul(i),s=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(s).iushrn(this.shift),c=o;return o.cmp(this.m)>=0?c=o.isub(this.m):o.cmpn(0)<0&&(c=o.iadd(this.m)),c.forceRed(this)}mul(e,i){if(e.isZero()||i.isZero())return new T(0).forceRed(this);let r=e.mul(i),s=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(s).iushrn(this.shift),c=o;return o.cmp(this.m)>=0?c=o.isub(this.m):o.cmpn(0)<0&&(c=o.iadd(this.m)),c.forceRed(this)}invm(e){return this.imod(e._invmp(this.m).mul(this.r2)).forceRed(this)}};var yi={};vu(yi,{Reader:()=>eo,ReaderUint8Array:()=>bt,Writer:()=>fe,WriterUint8Array:()=>ht,base64ToArray:()=>oh,constantTimeEquals:()=>X1,encode:()=>Pa,fromBase58:()=>so,fromBase58Check:()=>co,hexToUint8Array:()=>ro,minimallyEncode:()=>Ra,toArray:()=>at,toBase58:()=>oo,toBase58Check:()=>ao,toBase64:()=>ve,toHex:()=>nt,toSafeString:()=>$1,toUTF8:()=>ah,toUTF8Strict:()=>Rt,toUint8Array:()=>et,verifyNotNull:()=>sr,zero2:()=>q1});var zb=new TextEncoder;function Se(n){return zb.encode(n)}function Fe(n){return Se(n).byteLength}function Yi(n){for(let t of n){let e=t.codePointAt(0);if(e<=31||e>=127&&e<=159)return!0}return!1}var Ta={};vu(Ta,{RIPEMD160:()=>Gs,SHA1:()=>nr,SHA1HMAC:()=>Cu,SHA256:()=>Bu,SHA256HMAC:()=>Fr,SHA512:()=>_u,SHA512HMAC:()=>ga,hash160:()=>Js,hash256:()=>zt,htonl:()=>Vl,pbkdf2:()=>C1,realHtonl:()=>U1,ripemd160:()=>$u,sha1:()=>qu,sha256:()=>Te,sha256hmac:()=>Qs,sha512:()=>g1,sha512hmac:()=>Fu,swapBytes32:()=>Wu,toArray:()=>Sa});var Xb=/^[0-9a-fA-F]*$/;function Xs(n){if(typeof n!="string")throw new TypeError("Invalid hex string");if(n.length!==0&&!Xb.test(n))throw new Error("Invalid hex string")}function Ul(n){if(Xs(n),n.length===0)return"";let t=n.toLowerCase();return t.length%2!==0&&(t="0"+t),t}var Pu=(n,t="Hash assertion failed")=>{if(!n)throw new Error(t)},pa=class{constructor(t,e,i,r){b(this,"pending",null);b(this,"pendingTotal",0);b(this,"blockSize");b(this,"outSize");b(this,"endian");b(this,"_delta8");b(this,"_delta32");b(this,"padLength");b(this,"hmacStrength");this.blockSize=t,this.outSize=e,this.hmacStrength=i,this.padLength=r/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}_update(t,e){throw new Error("Not implemented")}_digest(){throw new Error("Not implemented")}_digestHex(){throw new Error("Not implemented")}update(t,e){if(t=Sa(t,e),this.pending==null?this.pending=t:this.pending=this.pending.concat(t),this.pendingTotal+=t.length,this.pending.length>=this._delta8){t=this.pending;let i=t.length%this._delta8;this.pending=t.slice(t.length-i,t.length),this.pending.length===0&&(this.pending=null),t=e1(t,0,t.length-i,this.endian);for(let r=0;r<t.length;r+=this._delta32)this._update(t,r)}return this}digest(){return this.update(this._pad()),Pu(this.pending===null),this._digest()}digestHex(){return this.update(this._pad()),Pu(this.pending===null),this._digestHex()}_pad(){let t=this.pendingTotal;if(!Number.isSafeInteger(t)||t<0)throw new Error("Message too long for this hash function");let e=this._delta8,i=e-(t+this.padLength)%e,r=Array.from({length:i+this.padLength});r[0]=128;let s;for(s=1;s<i;s++)r[s]=0;let o=this.padLength,c=1n<<BigInt(o*8),u=BigInt(t)*8n;if(u>=c)throw new Error("Message too long for this hash function");if(this.endian==="big"){let f=Array.from({length:o});for(let d=o-1;d>=0;d--)f[d]=Number(u&0xffn),u>>=8n;for(let d=0;d<o;d++)r[s++]=f[d]}else for(let f=0;f<o;f++)r[s++]=Number(u&0xffn),u>>=8n;return r}};function jb(n,t,e){let i=n.codePointAt(t);return i<128?(e.push(i),t):i<2048?(e.push(i>>6|192,i&63|128),t):i>65535?(e.push(i>>18|240,i>>12&63|128,i>>6&63|128,i&63|128),t+1):(e.push(i>>12|224,i>>6&63|128,i&63|128),t)}function Gb(n){let t=[],e=0;for(;e<n.length;)e=jb(n,e,t)+1;return t}function Yb(n){Xs(n);let t=Ul(n),e=[];for(let i=0;i<t.length;i+=2)e.push(Number.parseInt(t[i]+t[i+1],16));return e}function Zb(n){let t=[];for(let e=0;e<n.length;e++)t[e]=Math.trunc(n[e]);return t}function Sa(n,t){return Array.isArray(n)?n.slice():n?typeof n=="string"?t==="hex"?Yb(n):Gb(n):Zb(n):[]}function Vl(n){return Wu(n)}function Kl(n,t){let e="";for(let i of n)t==="little"&&(i=Vl(i)),e+=Jb(i.toString(16));return e}function Jb(n){return n.length===7?"0"+n:n.length===6?"00"+n:n.length===5?"000"+n:n.length===4?"0000"+n:n.length===3?"00000"+n:n.length===2?"000000"+n:n.length===1?"0000000"+n:n}var Ru=typeof globalThis>"u"?void 0:globalThis.Buffer,Qb=Ru!=null&&typeof Ru.from=="function",Ml="0123456789abcdef",Nu=Array.from({length:256});for(let n=0;n<Nu.length;n++)Nu[n]=Ml[n>>4&15]+Ml[n&15];function t1(n){if(Qb)return Ru.from(n).toString("hex");let t=Array.from({length:n.length});for(let e=0;e<n.length;e++)t[e]=Nu[n[e]];return t.join("")}var Lu=(()=>{let n=typeof globalThis>"u"?void 0:globalThis.process,t=n?.getBuiltinModule;if(typeof t=="function")try{let e=t.call(n,"node:crypto");if(e!=null)return e}catch{}})();function en(n,t){return n instanceof Uint8Array?n:Array.isArray(n)?new Uint8Array(n):Uint8Array.from(Sa(n,t))}function Uu(n){return typeof n=="string"?en(n,"hex"):en(n)}function Ia(n,t,e){n!=null?n.update(e):t?.update(e)}function va(n,t){return n!=null?Array.from(n.digest()):t!=null?Array.from(t.digest()):[]}function Aa(n,t){return n!=null?n.digest("hex"):t!=null?t1(t.digest()):""}function Mu(n){let t=Lu?.createHash;if(typeof t=="function")try{return t(n)}catch{return}}function Du(n,t){let e=Lu?.createHmac;if(typeof e=="function")try{return e(n,t)}catch{return}}function Hu(n,t,e){let i=Mu(n);if(i!=null)return i.update(en(t,e)),i.digest()}function zl(n,t,e,i){let r=Du(n,Uu(t));if(r!=null)return r.update(en(e,i)),r.digest()}function e1(n,t,e,i){let r=e-t;Pu(r%4===0);let s=Array.from({length:r/4});for(let o=0,c=t;o<s.length;o++,c+=4){let u;i==="big"?u=n[c]<<24|n[c+1]<<16|n[c+2]<<8|n[c+3]:u=n[c+3]<<24|n[c+2]<<16|n[c+1]<<8|n[c],s[o]=u>>>0}return s}function Xl(n,t){let e=Array.from({length:n.length*4});for(let i=0,r=0;i<n.length;i++,r+=4){let s=n[i];t==="big"?(e[r]=s>>>24,e[r+1]=s>>>16&255,e[r+2]=s>>>8&255,e[r+3]=s&255):(e[r+3]=s>>>24,e[r+2]=s>>>16&255,e[r+1]=s>>>8&255,e[r]=s&255)}return e}function En(n,t){return n>>>t|n<<32-t}function Zi(n,t){return n<<t|n>>>32-t}function Yt(n,t){return n+t>>>0}function js(n,t,e){return n+t+e>>>0}function Dl(n,t,e,i){return n+t+e+i>>>0}function jl(n,t,e,i,r){return n+t+e+i+r>>>0}function n1(n,t,e,i){return n===0?Gl(t,e,i):n===1||n===3?i1(t,e,i):n===2?Yl(t,e,i):0}function Gl(n,t,e){return n&t^~n&e}function Yl(n,t,e){return n&t^n&e^t&e}function i1(n,t,e){return n^t^e}function r1(n){return En(n,2)^En(n,13)^En(n,22)}function s1(n){return En(n,6)^En(n,11)^En(n,25)}function o1(n){return En(n,7)^En(n,18)^n>>>3}function a1(n){return En(n,17)^En(n,19)^n>>>10}var c1=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],u1=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],f1=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],d1=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11];function Hl(n,t,e,i){return n<=15?t^e^i:n<=31?t&e|~t&i:n<=47?(t|~e)^i:n<=63?t&i|e&~i:t^(e|~i)}function l1(n){return n<=15?0:n<=31?1518500249:n<=47?1859775393:n<=63?2400959708:2840853838}function h1(n){return n<=15?1352829926:n<=31?1548603684:n<=47?1836072691:n<=63?2053994217:0}var Gs=class extends pa{constructor(){super(512,160,192,64);b(this,"h");this.endian="little",this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}_update(e,i){let r=this.h[0],s=this.h[1],o=this.h[2],c=this.h[3],u=this.h[4],f=r,d=s,l=o,p=c,m=u,g;for(let w=0;w<80;w++)g=Yt(Zi(Dl(r,Hl(w,s,o,c),e[c1[w]+i],l1(w)),f1[w]),u),r=u,u=c,c=Zi(o,10),o=s,s=g,g=Yt(Zi(Dl(f,Hl(79-w,d,l,p),e[u1[w]+i],h1(w)),d1[w]),m),f=m,m=p,p=Zi(l,10),l=d,d=g;g=js(this.h[1],o,p),this.h[1]=js(this.h[2],c,m),this.h[2]=js(this.h[3],u,f),this.h[3]=js(this.h[4],r,d),this.h[4]=js(this.h[0],s,l),this.h[0]=g}_digest(){return Xl(this.h,"little")}_digestHex(){return Kl(this.h,"little")}},Ji,gi,Bu=class{constructor(){G(this,Ji);G(this,gi);N(this,gi,Mu("sha256")),y(this,gi)==null&&N(this,Ji,new Ys)}update(t,e){return Ia(y(this,gi),y(this,Ji),en(t,e)),this}digest(){return va(y(this,gi),y(this,Ji))}digestHex(){return Aa(y(this,gi),y(this,Ji))}};Ji=new WeakMap,gi=new WeakMap;var nr=class extends pa{constructor(){super(512,160,80,64);b(this,"h");b(this,"W");b(this,"k");this.k=[1518500249,1859775393,2400959708,3395469782],this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=Array.from({length:80})}_update(e,i){let r=this.W;i??(i=0);let s;for(s=0;s<16;s++)r[s]=e[i+s];for(;s<r.length;s++)r[s]=Zi(r[s-3]^r[s-8]^r[s-14]^r[s-16],1);let o=this.h[0],c=this.h[1],u=this.h[2],f=this.h[3],d=this.h[4];for(s=0;s<r.length;s++){let l=Math.trunc(s/20),p=jl(Zi(o,5),n1(l,c,u,f),d,r[s],this.k[l]);d=f,f=u,u=Zi(c,30),c=o,o=p}this.h[0]=Yt(this.h[0],o),this.h[1]=Yt(this.h[1],c),this.h[2]=Yt(this.h[2],u),this.h[3]=Yt(this.h[3],f),this.h[4]=Yt(this.h[4],d)}_digest(){return Xl(this.h,"big")}_digestHex(){return Kl(this.h,"big")}},Qi,mi,_u=class{constructor(){G(this,Qi);G(this,mi);N(this,mi,Mu("sha512")),y(this,mi)==null&&N(this,Qi,new Zs)}update(t,e){return Ia(y(this,mi),y(this,Qi),en(t,e)),this}digest(){return va(y(this,mi),y(this,Qi))}digestHex(){return Aa(y(this,mi),y(this,Qi))}};Qi=new WeakMap,mi=new WeakMap;var tr,bi,Fr=class{constructor(t){G(this,tr);G(this,bi);b(this,"blockSize",64);b(this,"outSize",32);let e=Uu(t);N(this,bi,Du("sha256",e)),y(this,bi)==null&&N(this,tr,new Wr(P1,e))}update(t,e){return Ia(y(this,bi),y(this,tr),en(t,e)),this}digest(){return va(y(this,bi),y(this,tr))}digestHex(){return Aa(y(this,bi),y(this,tr))}};tr=new WeakMap,bi=new WeakMap;var Cu=class{constructor(t){b(this,"inner");b(this,"outer");b(this,"blockSize",64);t=Sa(t,"hex"),t.length>this.blockSize&&(t=new nr().update(t).digest());let e;for(e=t.length;e<this.blockSize;e++)t.push(0);for(e=0;e<t.length;e++)t[e]^=54;for(this.inner=new nr().update(t),e=0;e<t.length;e++)t[e]^=106;this.outer=new nr().update(t)}update(t,e){return this.inner.update(t,e),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}},er,wi,ga=class{constructor(t){G(this,er);G(this,wi);b(this,"blockSize",128);b(this,"outSize",32);let e=Uu(t);N(this,wi,Du("sha512",e)),y(this,wi)==null&&N(this,er,new Wr(eh,e))}update(t,e){return Ia(y(this,wi),y(this,er),en(t,e)),this}digest(){return va(y(this,wi),y(this,er))}digestHex(){return Aa(y(this,wi),y(this,er))}};er=new WeakMap,wi=new WeakMap;function ma(n,t){let e=Hu("sha256",n,t);return e??new Ys().update(en(n,t)).digest()}function p1(n,t){let e=Hu("sha512",n,t);return e??new Zs().update(en(n,t)).digest()}function Zl(n,t){return Hu("ripemd160",n,t)}var $u=(n,t)=>{let e=Zl(n,t);return e!=null?Array.from(e):new Gs().update(n,t).digest()},qu=(n,t)=>new nr().update(n,t).digest(),Te=(n,t)=>Array.from(ma(n,t)),g1=(n,t)=>Array.from(p1(n,t)),zt=(n,t)=>Array.from(ma(ma(n,t))),Js=(n,t)=>{let e=ma(n,t),i=Zl(e);return i!=null?Array.from(i):new Gs().update(e).digest()},Qs=(n,t,e)=>{let i=zl("sha256",n,t,e);return i!=null?Array.from(i):new Fr(n).update(t,e).digest()},Fu=(n,t,e)=>{let i=zl("sha512",n,t,e);return i!=null?Array.from(i):new ga(n).update(t,e).digest()};function m1(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function ba(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`positive integer expected, got ${n}`)}function Ea(n,...t){if(!m1(n))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(n.length)){let e=t.join(",");throw new Error(`Uint8Array expected of length ${e}, got length=${n.length}`)}}function Jl(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("Hash should be wrapped by utils.createHasher");ba(n.outputLen),ba(n.blockLen)}function wa(n,t=!0){if(n.destroyed===!0)throw new Error("Hash instance has been destroyed");if(t&&n.finished===!0)throw new Error("Hash#digest() has already been called")}function b1(n,t){Ea(n);let e=t.outputLen;if(n.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}function ir(...n){for(let t of n)t.fill(0)}function ha(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function ka(n){return typeof n=="string"&&(n=w1(n)),Ea(n),n}function w1(n){if(typeof n!="string")throw new Error("string expected");return Se(n)}var $l=ka,ya=class{};function Ql(n){let t=i=>n().update(ka(i)).digest(),e=n();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>n(),t}var fa=BigInt(2**32-1),ql=BigInt(32);function y1(n,t=!1){return t?{h:Number(n&fa),l:Number(n>>ql&fa)}:{h:Number(n>>ql&fa)|0,l:Number(n&fa)|0}}function x1(n,t=!1){let e=n.length,i=new Uint32Array(e),r=new Uint32Array(e);for(let s=0;s<e;s++){let{h:o,l:c}=y1(n[s],t);i[s]=o,r[s]=c}return[i,r]}var Fl=(n,t,e)=>n>>>e,Wl=(n,t,e)=>n<<32-e|t>>>e,$r=(n,t,e)=>n>>>e|t<<32-e,qr=(n,t,e)=>n<<32-e|t>>>e,da=(n,t,e)=>n<<64-e|t>>>e-32,la=(n,t,e)=>n>>>e-32|t<<64-e;function Wn(n,t,e,i){let r=(t>>>0)+(i>>>0);return{h:n+e+(r/2**32|0)|0,l:r|0}}var S1=(n,t,e)=>(n>>>0)+(t>>>0)+(e>>>0),I1=(n,t,e,i)=>Math.trunc(t+e+i+Math.trunc(n/2**32)),v1=(n,t,e,i)=>(n>>>0)+(t>>>0)+(e>>>0)+(i>>>0),A1=(n,t,e,i,r)=>Math.trunc(t+e+i+r+Math.trunc(n/2**32)),E1=(n,t,e,i,r)=>(n>>>0)+(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0),k1=(n,t,e,i,r,s)=>t+e+i+r+s+(n/2**32|0)|0,xa=class extends ya{constructor(e,i,r,s){super();b(this,"blockLen");b(this,"outputLen");b(this,"padOffset");b(this,"isLE");b(this,"buffer");b(this,"view");b(this,"finished",!1);b(this,"length",0);b(this,"pos",0);b(this,"destroyed",!1);this.blockLen=e,this.outputLen=i,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=ha(this.buffer)}update(e){wa(this),e=ka(e),Ea(e);let{view:i,buffer:r,blockLen:s}=this,o=e.length;for(let c=0;c<o;){let u=Math.min(s-this.pos,o-c);if(u===s){let f=ha(e);for(;s<=o-c;c+=s)this.process(f,c);continue}r.set(e.subarray(c,c+u),this.pos),this.pos+=u,c+=u,this.pos===s&&(this.process(i,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){wa(this),b1(e,this),this.finished=!0;let{buffer:i,view:r,blockLen:s,isLE:o}=this,{pos:c}=this;i[c++]=128,ir(this.buffer.subarray(c)),this.padOffset>s-c&&(this.process(r,0),c=0);for(let p=c;p<s;p++)i[p]=0;T1(r,s-8,BigInt(this.length*8),o),this.process(r,0);let u=ha(e),f=this.outputLen;if(f%4!==0)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=f/4,l=this.get();if(d>l.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<d;p++)u.setUint32(4*p,l[p],o)}digest(){let{buffer:e,outputLen:i}=this;this.digestInto(e);let r=e.slice(0,i);return this.destroy(),r}_cloneInto(e){e??(e=new this.constructor),e.set(...this.get());let{blockLen:i,buffer:r,length:s,finished:o,destroyed:c,pos:u}=this;return e.destroyed=c,e.finished=o,e.length=s,e.pos=u,s%i!==0&&e.buffer.set(r),e}clone(){return this._cloneInto()}};function T1(n,t,e,i){if(typeof n.setBigUint64=="function")return n.setBigUint64(t,e,i);let r=BigInt(32),s=BigInt(4294967295),o=Number(e>>r&s),c=Number(e&s),u=i?4:0,f=i?0:4;n.setUint32(t+u,o,i),n.setUint32(t+f,c,i)}var di=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),O1=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),li=new Uint32Array(64),Ys=class extends xa{constructor(e=32){super(64,e,8,!1);b(this,"A",di[0]|0);b(this,"B",di[1]|0);b(this,"C",di[2]|0);b(this,"D",di[3]|0);b(this,"E",di[4]|0);b(this,"F",di[5]|0);b(this,"G",di[6]|0);b(this,"H",di[7]|0)}get(){let{A:e,B:i,C:r,D:s,E:o,F:c,G:u,H:f}=this;return[e,i,r,s,o,c,u,f]}set(...[e,i,r,s,o,c,u,f]){this.A=e|0,this.B=i|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=c|0,this.G=u|0,this.H=f|0}process(e,i){for(let p=0;p<16;p++,i+=4)li[p]=e.getUint32(i);for(let p=16;p<64;p++){let m=li[p-15],g=li[p-2],w=o1(m),S=a1(g);li[p]=Yt(Yt(w,li[p-7]),Yt(S,li[p-16]))}let{A:r,B:s,C:o,D:c,E:u,F:f,G:d,H:l}=this;for(let p=0;p<64;p++){let m=jl(l,s1(u),Gl(u,f,d),O1[p],li[p]),g=Yt(r1(r),Yl(r,s,o));l=d,d=f,f=u,u=Yt(c,m),c=o,o=s,s=r,r=Yt(m,g)}this.A=Yt(this.A,r),this.B=Yt(this.B,s),this.C=Yt(this.C,o),this.D=Yt(this.D,c),this.E=Yt(this.E,u),this.F=Yt(this.F,f),this.G=Yt(this.G,d),this.H=Yt(this.H,l)}roundClean(){ir(li)}destroy(){ir(this.buffer),this.set(0,0,0,0,0,0,0,0)}},P1=Ql(()=>new Ys),Ie=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),th=x1(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(BigInt)),R1=th[0],N1=th[1],hi=new Uint32Array(80),pi=new Uint32Array(80),Zs=class extends xa{constructor(e=64){super(128,e,16,!1);b(this,"Ah",Ie[0]|0);b(this,"Al",Ie[1]|0);b(this,"Bh",Ie[2]|0);b(this,"Bl",Ie[3]|0);b(this,"Ch",Ie[4]|0);b(this,"Cl",Ie[5]|0);b(this,"Dh",Ie[6]|0);b(this,"Dl",Ie[7]|0);b(this,"Eh",Ie[8]|0);b(this,"El",Ie[9]|0);b(this,"Fh",Ie[10]|0);b(this,"Fl",Ie[11]|0);b(this,"Gh",Ie[12]|0);b(this,"Gl",Ie[13]|0);b(this,"Hh",Ie[14]|0);b(this,"Hl",Ie[15]|0)}get(){let{Ah:e,Al:i,Bh:r,Bl:s,Ch:o,Cl:c,Dh:u,Dl:f,Eh:d,El:l,Fh:p,Fl:m,Gh:g,Gl:w,Hh:S,Hl:C}=this;return[e,i,r,s,o,c,u,f,d,l,p,m,g,w,S,C]}set(...[e,i,r,s,o,c,u,f,d,l,p,m,g,w,S,C]){this.Ah=e|0,this.Al=i|0,this.Bh=r|0,this.Bl=s|0,this.Ch=o|0,this.Cl=c|0,this.Dh=u|0,this.Dl=f|0,this.Eh=d|0,this.El=l|0,this.Fh=p|0,this.Fl=m|0,this.Gh=g|0,this.Gl=w|0,this.Hh=S|0,this.Hl=C|0}process(e,i){for(let k=0;k<16;k++,i+=8)hi[k]=e.getUint32(i),pi[k]=e.getUint32(i+4);for(let k=16;k<80;k++){let B=hi[k-15]|0,_=pi[k-15]|0,H=$r(B,_,1)^$r(B,_,8)^Fl(B,_,7),O=qr(B,_,1)^qr(B,_,8)^Wl(B,_,7),I=hi[k-2]|0,U=pi[k-2]|0,M=$r(I,U,19)^da(I,U,61)^Fl(I,U,6),F=qr(I,U,19)^la(I,U,61)^Wl(I,U,6),it=v1(O,F,pi[k-7],pi[k-16]),ot=A1(it,H,M,hi[k-7],hi[k-16]);hi[k]=ot|0,pi[k]=it|0}let{Ah:r,Al:s,Bh:o,Bl:c,Ch:u,Cl:f,Dh:d,Dl:l,Eh:p,El:m,Fh:g,Fl:w,Gh:S,Gl:C,Hh:E,Hl:A}=this;for(let k=0;k<80;k++){let B=$r(p,m,14)^$r(p,m,18)^da(p,m,41),_=qr(p,m,14)^qr(p,m,18)^la(p,m,41),H=p&g^~p&S,O=m&w^~m&C,I=E1(A,_,O,N1[k],pi[k]),U=k1(I,E,B,H,R1[k],hi[k]),M=I|0,F=$r(r,s,28)^da(r,s,34)^da(r,s,39),it=qr(r,s,28)^la(r,s,34)^la(r,s,39),ot=r&o^r&u^o&u,q=s&c^s&f^c&f;E=S|0,A=C|0,S=g|0,C=w|0,g=p|0,w=m|0,{h:p,l:m}=Wn(d|0,l|0,U|0,M|0),d=u|0,l=f|0,u=o|0,f=c|0,o=r|0,c=s|0;let z=S1(it,q,M);r=I1(z,F,ot,U),s=z|0}({h:r,l:s}=Wn(r,s,this.Ah,this.Al)),{h:o,l:c}=Wn(o,c,this.Bh,this.Bl),{h:u,l:f}=Wn(u,f,this.Ch,this.Cl),{h:d,l}=Wn(d,l,this.Dh,this.Dl),{h:p,l:m}=Wn(p,m,this.Eh,this.El),{h:g,l:w}=Wn(g,w,this.Fh,this.Fl),{h:S,l:C}=Wn(S,C,this.Gh,this.Gl),{h:E,l:A}=Wn(E,A,this.Hh,this.Hl),this.set(r,s,o,c,u,f,d,l,p,m,g,w,S,C,E,A)}roundClean(){ir(hi,pi)}destroy(){ir(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},eh=Ql(()=>new Zs),Wr=class extends ya{constructor(e,i){super();b(this,"oHash");b(this,"iHash");b(this,"blockLen");b(this,"outputLen");b(this,"finished",!1);b(this,"destroyed",!1);Jl(e);let r=ka(i);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new TypeError("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let c=0;c<o.length;c++)o[c]^=54;this.iHash.update(o),this.oHash=e.create();for(let c=0;c<o.length;c++)o[c]^=106;this.oHash.update(o),ir(o)}update(e){return wa(this),this.iHash.update(e),this}digestInto(e){wa(this),Ea(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e??(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:i,iHash:r,finished:s,destroyed:o,blockLen:c,outputLen:u}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=c,e.outputLen=u,e.oHash=i._cloneInto(e.oHash??void 0),e.iHash=r._cloneInto(e.iHash??void 0),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};function B1(n,t,e,i){Jl(n);let{c:r,dkLen:s=32}={...i};if(ba(r),ba(s),r<1)throw new Error("iterations (c) should be >= 1");let o=$l(t),c=$l(e),u=new Uint8Array(s),f=nh.create(n,o),d=f._cloneInto().update(c),l,p=new Uint8Array(4),m=ha(p),g=new Uint8Array(f.outputLen);for(let w=1,S=0;S<s;w++,S+=f.outputLen){let C=u.subarray(S,S+f.outputLen);m.setInt32(0,w,!1),l=d._cloneInto(l),l.update(p).digestInto(g),C.set(g.subarray(0,C.length));for(let E=1;E<r;E++){f._cloneInto(l).update(g).digestInto(g);for(let A=0;A<C.length;A++)C[A]^=g[A]}}return f.destroy(),d.destroy(),l?.destroy(),ir(g),u}var nh=(n,t,e)=>new Wr(n,t).update(e).digest();nh.create=(n,t)=>new Wr(n,t);function _1(n,t,e,i){return B1(eh,n,t,{c:e,dkLen:i})}function C1(n,t,e,i,r="sha512"){if(r!=="sha512")throw new Error("Only sha512 is supported in this PBKDF2 implementation");let s=Lu?.pbkdf2Sync;if(typeof s=="function"){let f=s(en(n),en(t),e,i,r);return Array.from(f)}let o=Uint8Array.from(n),c=Uint8Array.from(t),u=_1(o,c,e,i);return Array.from(u)}function Wu(n){return(n>>>24|n>>>8&65280|n<<8&16711680|(n&255)<<24)>>>0}var L1=(()=>{let n=new ArrayBuffer(4),t=new Uint32Array(n),e=new Uint8Array(n);return t[0]=16909060,e[0]===4})();function U1(n){return L1?Wu(n):n>>>0}var M1=new T(4294967295),D1=new T(2).pow(new T(64)).sub(new T(1)),H1=new T(Number.MAX_SAFE_INTEGER);function to(n,t=!0){let e=n.readUInt8();if(e<253)return e;if(e===253){let r=n.readUInt16LE();if(r<253)throw new Error("non-canonical varInt");return r}if(e===254){let r=n.readUInt32LE();if(r<=65535)throw new Error("non-canonical varInt");return r}let i=n.readUInt64LEBn();if(i.lte(M1))throw new Error("non-canonical varInt");if(t&&i.eq(D1))return-1;if(i.gt(H1))throw new Error("number too large to retain precision - use readVarIntBn");return i.toNumber()}var Wt,Tt,rr,ln,Vn,ht=class{constructor(t,e=256){G(this,ln);G(this,Wt);G(this,Tt);G(this,rr);if(!Number.isSafeInteger(e)||e<0)throw new RangeError("WriterUint8Array initial capacity must be a non-negative safe integer");if(t!=null&&t.length>0){let i=t.reduce((r,s)=>r+s.length,0);e=Math.max(e,i)}if(e=Math.max(1,e),N(this,Wt,new Uint8Array(e)),N(this,Tt,0),N(this,rr,e),t!=null)for(let i of t)this.write(i)}getLength(){return y(this,Tt)}toUint8Array(){return y(this,Wt).slice(0,y(this,Tt))}toArray(){return Array.from(this.toUint8Array())}toUint8ArrayZeroCopy(){return y(this,Wt).subarray(0,y(this,Tt))}reserve(t){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("WriterUint8Array reserve requires a non-negative safe integer");a(this,ln,Vn).call(this,t)}write(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);return a(this,ln,Vn).call(this,e.length),y(this,Wt).set(e,y(this,Tt)),N(this,Tt,y(this,Tt)+e.length),this}writeReverse(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);a(this,ln,Vn).call(this,e.length);for(let i=e.length-1;i>=0;i--)y(this,Wt)[y(this,Tt)]=e[i],N(this,Tt,y(this,Tt)+1);return this}writeUInt8(t){return a(this,ln,Vn).call(this,1),y(this,Wt)[y(this,Tt)]=t&255,N(this,Tt,y(this,Tt)+1),this}writeInt8(t){return this.writeUInt8(t),this}writeUInt16LE(t){return a(this,ln,Vn).call(this,2),y(this,Wt)[y(this,Tt)]=t&255,y(this,Wt)[y(this,Tt)+1]=t>>8&255,N(this,Tt,y(this,Tt)+2),this}writeUInt16BE(t){return a(this,ln,Vn).call(this,2),y(this,Wt)[y(this,Tt)]=t>>8&255,y(this,Wt)[y(this,Tt)+1]=t&255,N(this,Tt,y(this,Tt)+2),this}writeInt16LE(t){return this.writeUInt16LE(t&65535),this}writeInt16BE(t){return this.writeUInt16BE(t&65535),this}writeUInt32LE(t){return a(this,ln,Vn).call(this,4),y(this,Wt)[y(this,Tt)]=t&255,y(this,Wt)[y(this,Tt)+1]=t>>8&255,y(this,Wt)[y(this,Tt)+2]=t>>16&255,y(this,Wt)[y(this,Tt)+3]=t>>24&255,N(this,Tt,y(this,Tt)+4),this}writeUInt32BE(t){return a(this,ln,Vn).call(this,4),y(this,Wt)[y(this,Tt)]=t>>24&255,y(this,Wt)[y(this,Tt)+1]=t>>16&255,y(this,Wt)[y(this,Tt)+2]=t>>8&255,y(this,Wt)[y(this,Tt)+3]=t&255,N(this,Tt,y(this,Tt)+4),this}writeInt32LE(t){return this.writeUInt32LE(t>>>0),this}writeInt32BE(t){return this.writeUInt32BE(t>>>0),this}writeUInt64BEBn(t){let e=t.toArray("be",8);return this.write(e),this}writeUInt64LEBn(t){let e=t.toArray("be",8);return this.writeReverse(e),this}writeUInt64LE(t){let e=new T(t).toArray("be",8);return this.writeReverse(e),this}writeVarIntNum(t){let e=fe.varIntNum(t);return this.write(e),this}writeVarIntBn(t){let e=fe.varIntBn(t);return this.write(e),this}reset(){N(this,Tt,0)}};Wt=new WeakMap,Tt=new WeakMap,rr=new WeakMap,ln=new WeakSet,Vn=function(t){if(y(this,Tt)+t>y(this,rr)){let e=y(this,rr)*2;for(;y(this,Tt)+t>e;)e*=2;let i=new Uint8Array(e);i.set(y(this,Wt)),N(this,Wt,i),N(this,rr,e)}};var pn,We,hn,Vu=class Vu{constructor(t=new Uint8Array(0),e=0){G(this,We);b(this,"bin");b(this,"pos");G(this,pn);if(t instanceof Uint8Array)this.bin=t;else if(Array.isArray(t))this.bin=new Uint8Array(t);else throw new TypeError("ReaderUint8Array constructor: bin must be Uint8Array or number[]");if(N(this,pn,this.bin.length),!Number.isSafeInteger(e)||e<0||e>y(this,pn))throw new RangeError("ReaderUint8Array position exceeds available data");this.pos=e}static makeReader(t,e=0){if(t instanceof Uint8Array)return new Vu(t,e);if(Array.isArray(t))return new eo(t,e);throw new Error("ReaderUint8Array.makeReader: bin must be Uint8Array or number[]")}eof(){return this.pos>=y(this,pn)}read(t=y(this,pn)-this.pos){a(this,We,hn).call(this,t);let e=this.pos,i=this.pos+t;return this.pos=i,this.bin.slice(e,i)}readView(t=y(this,pn)-this.pos){a(this,We,hn).call(this,t);let e=this.pos;return this.pos+=t,this.bin.subarray(e,this.pos)}skip(t){a(this,We,hn).call(this,t),this.pos+=t}remaining(){return y(this,pn)-this.pos}readReverse(t=y(this,pn)-this.pos){a(this,We,hn).call(this,t);let e=new Uint8Array(t);for(let i=0;i<t;i++)e[i]=this.bin[this.pos+t-1-i];return this.pos+=t,e}readUInt8(){a(this,We,hn).call(this,1);let t=this.bin[this.pos];return this.pos+=1,t}readInt8(){let t=this.readUInt8();return(t&128)===0?t:t-256}readUInt16BE(){a(this,We,hn).call(this,2);let t=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,t}readInt16BE(){let t=this.readUInt16BE();return(t&32768)===0?t:t-65536}readUInt16LE(){a(this,We,hn).call(this,2);let t=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,t}readInt16LE(){let t=this.readUInt16LE();return(t&32768)===0?t:t-65536}readUInt32BE(){a(this,We,hn).call(this,4);let t=this.bin[this.pos]*16777216+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,t}readInt32BE(){let t=this.readUInt32BE();return(t&2147483648)===0?t:t-4294967296}readUInt32LE(){a(this,We,hn).call(this,4);let t=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,t}readInt32LE(){let t=this.readUInt32LE();return(t&2147483648)===0?t:t-4294967296}readUInt64BEBn(){a(this,We,hn).call(this,8);let t=Array.from(this.bin.slice(this.pos,this.pos+8)),e=new T(t);return this.pos=this.pos+8,e}readUInt64LEBn(){let t=Array.from(this.readReverse(8));return new T(t)}readInt64LEBn(){let t=new T(2).pow(new T(63)),e=new T(2).pow(new T(64)),i=Array.from(this.readReverse(8)),r=new T(i);return r.gte(t)&&(r=r.sub(e)),r}readVarIntNum(t=!0){let e=this.readUInt8(),i;switch(e){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(i=t?this.readInt64LEBn():this.readUInt64LEBn(),i.lte(new T(2).pow(new T(53))))return i.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return e}}readVarIntNumStrict(t=!0){return to(this,t)}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){let t=this.readUInt8();switch(t){case 253:return new T(this.readUInt16LE());case 254:return new T(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new T(t)}}};pn=new WeakMap,We=new WeakSet,hn=function(t){if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(this.pos)||this.pos<0||this.pos+t>y(this,pn))throw new RangeError("ReaderUint8Array read exceeds available data")};var bt=Vu;var Oa=globalThis.Buffer,rh=Oa!=null&&typeof Oa.from=="function",$1=(n,t="Unknown value")=>{if(n===null)return"null";if(n===void 0)return"undefined";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="bigint")return n.toString();if(typeof n=="boolean")return n?"true":"false";if(typeof n=="symbol")return n.description??n.toString();if(n instanceof Error&&n.message.length>0)return n.message;let e=n.message;if(typeof e=="string"&&e.length>0)return e;try{return JSON.stringify(n)??t}catch{return t}},q1=n=>n.length%2===1?"0"+n:n,ih="0123456789abcdef",sh=Array.from({length:256},()=>"");for(let n=0;n<256;n++)sh[n]=ih[n>>4&15]+ih[n&15];var nt=n=>rh?Oa.from(n).toString("hex"):n.length===0?"":Array.from(n,t=>sh[t&255]).join(""),et=(n,t)=>n instanceof Uint8Array?n:typeof n=="string"&&t==="hex"?ro(n):new Uint8Array(at(n,t)),at=(n,t)=>{if(Array.isArray(n))return n.slice();if(n===void 0)return[];if(typeof n!="string")return Array.from(n,e=>Math.trunc(e));switch(t){case"hex":return F1(n);case"base64":return oh(n);default:return K1(n)}},io=new Int8Array(256).fill(-1);for(let n=0;n<10;n++)io[48+n]=n;for(let n=0;n<6;n++)io[65+n]=10+n,io[97+n]=10+n;var F1=n=>Array.from(ro(n)),ro=n=>{Xs(n);let t=n.length%2===0?n:"0"+n;if(rh){let r=Oa.from(t,"hex");return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let e=new Uint8Array(t.length/2),i=0;for(let r=0;r<t.length;r+=2){let s=io[t.codePointAt(r)],o=io[t.codePointAt(r+1)];e[i++]=s<<4|o}return e},W1=n=>{if(typeof n!="string")throw new TypeError("msg must be a string");let t=n.trim().replaceAll(/[\r\n\t\f\v ]+/g,"").replaceAll("-","+").replaceAll("_","/"),e=t.indexOf("=");if(e===-1)return t;let i=t.slice(e);if(!/^={1,2}$/.test(i)||t.slice(0,e).includes("="))throw new Error("Invalid base64 padding");return t.slice(0,e)},V1=(n,t)=>{if(n>=65&&n<=90)return n-65;if(n>=97&&n<=122)return n-97+26;if(n>=48&&n<=57)return n-48+52;if(n===43)return 62;if(n===47)return 63;throw new Error(`Invalid base64 character at index ${t}`)};function oh(n){let t=W1(n),e=[],i=0,r=0;for(let s=0;s<t.length;s++){let o=t.codePointAt(s),c=V1(o,s);for(i=i<<6|c,r+=6;r>=8;)r-=8,e.push(i>>r&255),i&=(1<<r)-1}return e}function K1(n){return Array.from(Se(n))}var ah=n=>new TextDecoder().decode(n instanceof Uint8Array?n:new Uint8Array(n)),Rt=n=>new TextDecoder("utf-8",{fatal:!0}).decode(n instanceof Uint8Array?n:new Uint8Array(n)),Pa=(n,t)=>{switch(t){case"hex":return nt(n);case"utf8":return ah(n);default:return n}};function ve(n){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e="",i;for(i=0;i<n.length;i+=3){let r=n[i],s=i+1<n.length?n[i+1]:0,o=i+2<n.length?n[i+2]:0,c=r>>2,u=(r&3)<<4|s>>4,f=(s&15)<<2|o>>6,d=o&63;e+=t.charAt(c)+t.charAt(u),e+=i+1<n.length?t.charAt(f):"=",e+=i+2<n.length?t.charAt(d):"="}return e}var no="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",so=n=>{if(n===""||typeof n!="string")throw new Error(`Expected base58 string but got \u201C${n}\u201D`);let t=n.match(/[^1-9A-HJ-NP-Za-km-z]/gmu);if(t!==null)throw new Error(`Invalid base58 character \u201C${t.join("")}\u201D`);let e=n.match(/^1+/gmu),i=e===null?0:e[0].length,r=(n.length-i)*(Math.log(58)/Math.log(256))+1>>>0;return[...new Uint8Array([...new Uint8Array(i),...Array.from(n).map(o=>no.indexOf(o)).reduce((o,c)=>(o=o.map(u=>{let f=u*58+c;return c=f>>8,f}),o),new Uint8Array(r)).reverse().filter((o=>c=>o=o||c)(!1))])]},oo=n=>{let t=Array.from({length:256},()=>-1);for(let i=0;i<no.length;++i)t[no.codePointAt(i)]=i;let e=[];for(let i of n){let r=i;for(let s=0;s<e.length;++s){let o=(t[e[s]]<<8)+r,c=Math.trunc(o/58),u=o-c*58;e[s]=no.codePointAt(u),r=c}for(;r!==0;){let s=Math.trunc(r/58),o=r-s*58;e.push(no.codePointAt(o)),r=s}}for(let i of n)if(i===0)e.push("1".codePointAt(0));else break;return e.reverse(),String.fromCodePoint(...e)},ao=(n,t=[0])=>{let e=zt([...t,...n]);return e=[...t,...n,...e.slice(0,4)],oo(e)},co=(n,t,e=1)=>{let i=so(n),r=i.slice(0,e),s=i.slice(e,-4),o=[...r,...s];return o=zt(o),i.slice(-4).forEach((c,u)=>{if(c!==o[u])throw new Error("Invalid checksum")}),t==="hex"&&(r=nt(r),s=nt(s)),{prefix:r,data:s}},fe=class n{constructor(t){b(this,"bufs");b(this,"length");this.bufs=t??[],this.length=0;for(let e of this.bufs)this.length+=e.length}getLength(){return this.length}toUint8Array(){let t=new Uint8Array(this.length),e=0;for(let i of this.bufs)t.set(i,e),e+=i.length;return t}toArray(){let t=this.length,e=Array.from({length:t},()=>0),i=0;for(let r of this.bufs)if(r instanceof Uint8Array)for(let s of r)e[i++]=s;else{let s=r;for(let o of s)e[i++]=o}return e}toHex(){return this.toArray().map(t=>t.toString(16).padStart(2,"0")).join("")}write(t){return this.bufs.push(t),this.length+=t.length,this}writeReverse(t){let e=Array.from({length:t.length},()=>0);for(let i=0;i<e.length;i++)e[i]=t[t.length-1-i];return this.write(e)}writeUInt8(t){let e=Array.from({length:1},()=>0);return e[0]=t&255,this.write(e),this}writeInt8(t){return this.writeUInt8(t)}writeUInt16BE(t){let e=[t>>8&255,t&255];return this.write(e)}writeInt16BE(t){return this.writeUInt16BE(t&65535)}writeUInt16LE(t){let e=[t&255,t>>8&255];return this.write(e)}writeInt16LE(t){return this.writeUInt16LE(t&65535)}writeUInt32BE(t){let e=[t>>24&255,t>>16&255,t>>8&255,t&255];return this.write(e)}writeInt32BE(t){return this.writeUInt32BE(t>>>0)}writeUInt32LE(t){let e=[t&255,t>>8&255,t>>16&255,t>>24&255];return this.write(e)}writeInt32LE(t){return this.writeUInt32LE(t>>>0)}writeUInt64BEBn(t){let e=t.toArray("be",8);return this.write(e),this}writeUInt64LEBn(t){let e=t.toArray("be",8);return this.writeReverse(e),this}writeUInt64LE(t){if(t===-1)this.write(Array.from({length:8},()=>255));else{let e=new T(t).toArray("be",8);this.writeReverse(e)}return this}writeVarIntNum(t){let e=n.varIntNum(t);return this.write(e),this}writeVarIntBn(t){let e=n.varIntBn(t);return this.write(e),this}static varIntNum(t){if(!Number.isFinite(t)||!Number.isInteger(t))throw new RangeError("CompactSize value must be a finite integer");let e;if(t<0)return this.varIntBn(new T(t));if(t<253)e=[t];else if(t<65536)e=[253,t&255,t>>8&255];else if(t<4294967296)e=[254,t&255,t>>8&255,t>>16&255,t>>24&255];else{let i=t&4294967295,r=Math.floor(t/4294967296)&4294967295;e=[255,i&255,i>>8&255,i>>16&255,i>>24&255,r&255,r>>8&255,r>>16&255,r>>24&255]}return e}static varIntBn(t){let e;if(t.isNeg()&&(t=t.add(ch)),t.ltn(253))e=[t.toNumber()];else if(t.ltn(65536)){let i=t.toNumber();e=[253,i&255,i>>8&255]}else if(t.lt(new T(4294967296))){let i=t.toNumber();e=[254,i&255,i>>8&255,i>>16&255,i>>24&255]}else{let i=new n;i.writeUInt8(255),i.writeUInt64LEBn(t),e=i.toArray()}return e}},eo=class{constructor(t=[],e=0){b(this,"bin");b(this,"pos");b(this,"length");if(this.bin=t,this.length=t.length,!Number.isSafeInteger(e)||e<0||e>this.length)throw new RangeError("Reader position exceeds available data");this.pos=e}ensureAvailable(t){if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(this.pos)||this.pos<0||this.pos+t>this.length)throw new RangeError("Reader read exceeds available data")}eof(){return this.pos>=this.length}read(t=this.length-this.pos){this.ensureAvailable(t);let e=this.pos,i=this.pos+t;return this.pos=i,this.bin.slice(e,i)}readReverse(t=this.length-this.pos){this.ensureAvailable(t);let e=Array.from({length:t},()=>0);for(let i=0;i<t;i++)e[i]=this.bin[this.pos+t-1-i];return this.pos+=t,e}readUInt8(){this.ensureAvailable(1);let t=this.bin[this.pos];return this.pos+=1,t}readInt8(){let t=this.readUInt8();return(t&128)===0?t:t-256}readUInt16BE(){this.ensureAvailable(2);let t=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,t}readInt16BE(){let t=this.readUInt16BE();return(t&32768)===0?t:t-65536}readUInt16LE(){this.ensureAvailable(2);let t=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,t}readInt16LE(){let t=this.readUInt16LE();return(t&32768)===0?t:t-65536}readUInt32BE(){this.ensureAvailable(4);let t=this.bin[this.pos]*16777216+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,t}readInt32BE(){let t=this.readUInt32BE();return(t&2147483648)===0?t:t-4294967296}readUInt32LE(){this.ensureAvailable(4);let t=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,t}readInt32LE(){let t=this.readUInt32LE();return(t&2147483648)===0?t:t-4294967296}readUInt64BEBn(){let t=this.read(8);return new T(t)}readUInt64LEBn(){let t=this.readReverse(8);return new T(t)}readInt64LEBn(){let t=this.readReverse(8),e=new T(t);return e.gte(z1)&&(e=e.sub(ch)),e}readVarIntNum(t=!0){let e=this.readUInt8(),i;switch(e){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(i=t?this.readInt64LEBn():this.readUInt64LEBn(),i.lte(new T(2).pow(new T(53))))return i.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return e}}readVarIntNumStrict(t=!0){return to(this,t)}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){let t=this.readUInt8();switch(t){case 253:return new T(this.readUInt16LE());case 254:return new T(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new T(t)}}},Ra=n=>{if(n.length===0)return n;let t=n.at(-1);if((t&127)!==0)return n;if(n.length===1)return[];if((n.at(-2)&128)!==0)return n;for(let e=n.length-1;e>0;e--)if(n[e-1]!==0)return(n[e-1]&128)===0?(n[e-1]|=t,n.slice(0,e)):(n[e]=t,n.slice(0,e+1));return[]},z1=new T(2).pow(new T(63)),ch=new T(2).pow(new T(64));function sr(n,t="Expected a valid value, but got undefined or null."){if(n==null)throw new Error(t);return n}function X1(n,t){if(n.length!==t.length)return!1;let e=0;for(let i=0;i<n.length;i++)e|=n[i]^t[i];return e===0}var Ku;function uh(n,t){let e=n.andln(3)+t&3;return e===3?-1:e}function fh(n,t,e,i){if((e&1)===0)return 0;let r=n.andln(7)+t&7;return(r===3||r===5)&&i===2?-e:e}function dh(n,t){return 2*n===t+1?1-n:n}var Na,lh,zu=class zu{constructor(){G(this,Na);b(this,"p");b(this,"red");b(this,"redN");b(this,"zero");b(this,"one");b(this,"two");b(this,"g");b(this,"n");b(this,"a");b(this,"b");b(this,"tinv");b(this,"zeroA");b(this,"threeA");b(this,"endo");b(this,"_endoWnafT1");b(this,"_endoWnafT2");b(this,"_wnafT1");b(this,"_wnafT2");b(this,"_wnafT3");b(this,"_wnafT4");b(this,"_bitLength");if(Ku===void 0)Ku=this;else return Ku;let e={prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",{doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}]};this.p=new T(e.p,16),this.red=new Gi(e.prime),this.zero=new T(0).toRed(this.red),this.one=new T(1).toRed(this.red),this.two=new T(2).toRed(this.red),this.n=new T(e.n,16),this.g=Oe.fromJSON(e.g,e.gRed),this._wnafT1=Array.from({length:4},()=>{}),this._wnafT2=Array.from({length:4},()=>{}),this._wnafT3=Array.from({length:4},()=>{}),this._wnafT4=Array.from({length:4},()=>{}),this._bitLength=this.n.bitLength(),this.redN=this.n.toRed(this.red),this.a=new T(e.a,16).toRed(this.red),this.b=new T(e.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=this.a.fromRed().cmpn(0)===0,this.threeA=this.a.fromRed().sub(this.p).cmpn(-3)===0,this.endo=this._getEndomorphism(e),this._endoWnafT1=Array.from({length:4},()=>{}),this._endoWnafT2=Array.from({length:4},()=>{})}static assert(t,e="Elliptic curve assertion failed"){if(!t)throw new Error(e)}getNAF(t,e,i){let r=Array.from({length:Math.max(t.bitLength(),i)+1},()=>0);r.fill(0);let s=1<<e+1,o=t.clone();for(let c=0;c<r.length;c++){let u,f=o.andln(s-1);o.isOdd()?(f>(s>>1)-1?u=(s>>1)-f:u=f,o.isubn(u)):u=0,r[c]=u,o.iushrn(1)}return r}getJSF(t,e){let i=[[],[]];t=t.clone(),e=e.clone();let r=0,s=0;for(;t.cmpn(-r)>0||e.cmpn(-s)>0;){let o=uh(t,r),c=uh(e,s),u=fh(t,r,o,c);i[0].push(u);let f=fh(e,s,c,o);i[1].push(f),r=dh(r,u),s=dh(s,f),t.iushrn(1),e.iushrn(1)}return i}static cachedProperty(t,e,i){let r="_"+e;t.prototype[e]=function(){return this[r]===void 0&&(this[r]=i.call(this)),this[r]}}static parseBytes(t){return typeof t=="string"?at(t,"hex"):t}static intFromLE(t){return new T(t,"hex","le")}_getEndomorphism(t){if(!this.zeroA||this.p.modrn(3)!==1)return;let e=this._resolveEndomorphismBeta(t),i=this._resolveEndomorphismLambda(t,e);return{beta:e,lambda:i,basis:a(this,Na,lh).call(this,t,i)}}_resolveEndomorphismBeta(t){if(t.beta!==void 0)return new T(t.beta,16).toRed(this.red);let e=this._getEndoRoots(this.p);if(e==null)throw new Error("Failed to get endomorphism roots for beta.");return(e[0].cmp(e[1])<0?e[0]:e[1]).toRed(this.red)}_endomorphismLambdaMatches(t,e,i=!1){if(this.g==null)throw new Error("Curve generator point (g) is not defined.");let r=this.g.mul(t)?.x,s=this.g.x==null?void 0:this.g.x.redMul(e);if(r==null||s==null){if(i)throw new Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");return!1}return r.cmp(s)===0}_resolveEndomorphismLambda(t,e){if(t.lambda!==void 0)return new T(t.lambda,16);let i=this._getEndoRoots(this.n);if(i==null)throw new Error("Failed to get endomorphism roots for lambda.");return this._endomorphismLambdaMatches(i[0],e)?i[0]:(zu.assert(this._endomorphismLambdaMatches(i[1],e,!0),"Lambda selection does not match computed beta."),i[1])}_getEndoRoots(t){let e=t===this.p?this.red:new zs(t),i=new T(2).toRed(e).redInvm(),r=i.redNeg(),s=new T(3).toRed(e).redNeg().redSqrt().redMul(i),o=r.redAdd(s).fromRed(),c=r.redSub(s).fromRed();return[o,c]}_getEndoBasis(t){let e=this.n.ushrn(Math.floor(this.n.bitLength()/2)),i=t,r=this.n.clone(),s=new T(1),o=new T(0),c=new T(0),u=new T(1),f,d,l,p,m,g,w=new T(0),S=0,C=new T(0),E=new T(0);for(;i.cmpn(0)!==0;){let B=r.div(i);C=r.sub(B.mul(i)),E=c.sub(B.mul(s));let _=u.sub(B.mul(o));if(l===void 0&&C.cmp(e)<0)f=w.neg(),d=s,l=C.neg(),p=E;else if(l!==void 0&&++S===2)break;w=C,r=i,i=C,c=s,s=E,u=o,o=_}if(f===void 0||d===void 0||l===void 0||p===void 0)throw new Error("Failed to compute Endo Basis values");m=C.neg(),g=E;let A=l.sqr().add(p.sqr());return m.sqr().add(g.sqr()).cmp(A)>=0&&(m=f,g=d),l.negative!==0&&(l=l.neg(),p=p.neg()),m.negative!==0&&(m=m.neg(),g=g.neg()),[{a:l,b:p},{a:m,b:g}]}_endoSplit(t){if(this.endo==null)throw new Error("Endomorphism is not defined.");let e=this.endo.basis,i=e[0],r=e[1],s=r.b.mul(t).divRound(this.n),o=i.b.neg().mul(t).divRound(this.n),c=s.mul(i.a),u=o.mul(r.a),f=s.mul(i.b),d=o.mul(r.b),l=t.sub(c).sub(u),p=f.add(d).neg();return{k1:l,k2:p}}validate(t){if(t.inf)return!0;let e=t.x,i=t.y;if(e===null||i===null)throw new Error("Point coordinates cannot be null");let r=this.a.redMul(e),s=e.redSqr().redMul(e).redIAdd(r).redIAdd(this.b);return i.redSqr().redISub(s).cmpn(0)===0}};Na=new WeakSet,lh=function(t,e){return typeof t.basis!="object"||t.basis===null?this._getEndoBasis(e):t.basis.map(i=>({a:new T(i.a,16),b:new T(i.b,16)}))};var Vt=zu;var or=class{constructor(t){b(this,"curve");b(this,"type");b(this,"precomputed");this.curve=new Vt,this.type=t,this.precomputed=null}};var ar=class n extends or{constructor(e,i,r){super("jacobian");b(this,"x");b(this,"y");b(this,"z");b(this,"zOne");e===null&&i===null&&r===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new T(0)):(T.isBN(e)||(e=new T(e,16)),this.x=e,T.isBN(i)||(i=new T(i,16)),this.y=i,T.isBN(r)||(r=new T(r,16)),this.z=r),this.x.red==null&&(this.x=this.x.toRed(this.curve.red)),this.y.red==null&&(this.y=this.y.toRed(this.curve.red)),this.z.red==null&&(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.isInfinity()&&(this.x=this.curve.one,this.y=this.curve.one,this.z=new T(0).toRed(this.curve.red),this.zOne=!1)}toP(){if(this.isInfinity())return new Oe(null,null);let e=this.z.redInvm(),i=e.redSqr(),r=this.x.redMul(i),s=this.y.redMul(i).redMul(e);return new Oe(r,s)}neg(){return new n(this.x,this.y.redNeg(),this.z)}add(e){if(this.isInfinity())return e;if(e.isInfinity())return this;let i=e.z.redSqr(),r=this.z.redSqr(),s=this.x.redMul(i),o=e.x.redMul(r),c=this.y.redMul(i.redMul(e.z)),u=e.y.redMul(r.redMul(this.z)),f=s.redSub(o),d=c.redSub(u);if(f.cmpn(0)===0)return d.cmpn(0)===0?this.dbl():new n(null,null,null);let l=f.redSqr(),p=l.redMul(f),m=s.redMul(l),g=d.redSqr().redIAdd(p).redISub(m).redISub(m),w=d.redMul(m.redISub(g)).redISub(c.redMul(p)),S=this.z.redMul(e.z).redMul(f);return new n(g,w,S)}mixedAdd(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;if(e.x===null||e.y===null)throw new Error("Point coordinates cannot be null");let i=this.z.redSqr(),r=this.x,s=e.x.redMul(i),o=this.y,c=e.y.redMul(i).redMul(this.z),u=r.redSub(s),f=o.redSub(c);if(u.cmpn(0)===0)return f.cmpn(0)===0?this.dbl():new n(null,null,null);let d=u.redSqr(),l=d.redMul(u),p=r.redMul(d),m=f.redSqr().redIAdd(l).redISub(p).redISub(p),g=f.redMul(p.redISub(m)).redISub(o.redMul(l)),w=this.z.redMul(u);return new n(m,g,w)}dblp(e){if(e===0)return this;if(this.isInfinity())return this;if(e===void 0)return this.dbl();let i=this;for(let r=0;r<e;r++)i=i.dbl();return i}dbl(){if(this.isInfinity())return this;let e,i,r;if(this.zOne){let s=this.x.redSqr(),o=this.y.redSqr(),c=o.redSqr(),u=this.x.redAdd(o).redSqr().redISub(s).redISub(c);u=u.redIAdd(u);let f=s.redAdd(s).redIAdd(s),d=f.redSqr().redISub(u).redISub(u),l=c.redIAdd(c);l=l.redIAdd(l),l=l.redIAdd(l),e=d,i=f.redMul(u.redISub(d)).redISub(l),r=this.y.redAdd(this.y)}else{let s=this.x.redSqr(),o=this.y.redSqr(),c=o.redSqr(),u=this.x.redAdd(o).redSqr().redISub(s).redISub(c);u=u.redIAdd(u);let f=s.redAdd(s).redIAdd(s),d=f.redSqr(),l=c.redIAdd(c);l=l.redIAdd(l),l=l.redIAdd(l),e=d.redISub(u).redISub(u),i=f.redMul(u.redISub(e)).redISub(l),r=this.y.redMul(this.z),r=r.redIAdd(r)}return new n(e,i,r)}eq(e){if(e.type==="affine")return this.eq(e.toJ());if(this===e||(e=e,this.isInfinity()&&e.isInfinity()))return!0;if(this.isInfinity()!==e.isInfinity())return!1;let i=this.z.redSqr(),r=e.z.redSqr();if(this.x.redMul(r).redISub(e.x.redMul(i)).cmpn(0)!==0)return!1;let s=i.redMul(this.z),o=r.redMul(e.z);return this.y.redMul(o).redISub(e.y.redMul(s)).cmpn(0)===0}eqXToP(e){let i=this.z.redSqr(),r=e.toRed(this.curve?.red).redMul(i);if(this.x.cmp(r)===0)return!0;let s=e.clone();if(this.curve?.redN==null)throw new Error("Curve or redN is not initialized.");let o=this.curve.redN.redMul(i);for(;s.cmp(this.curve.p)<0;){if(s.iadd(this.curve.n),s.cmp(this.curve.p)>=0)return!1;if(r.redIAdd(o),this.x.cmp(r)===0)return!0}return!1}inspect(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"}isInfinity(){return this.z.cmpn(0)===0}};function hh(n,t,e){let i=-n,r=(t.X^e.X)&i,s=(t.Y^e.Y)&i,o=(t.Z^e.Z)&i;t.X^=r,e.X^=r,t.Y^=s,e.Y^=s,t.Z^=o,e.Z^=o}var Ut=0n,Ce=1n,Xu=2n,j1=3n,G1=4n,Y1=8n,Tn=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,xi=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,ph=(1n<<256n)-1n;function Gu(n){let t=n>>256n;return n=(n&ph)+(t<<32n)+t*977n,t=n>>256n,n=(n&ph)+(t<<32n)+t*977n,n>=Tn&&(n-=Tn),n}var cr=n=>Gu((n%Tn+Tn)%Tn),kn=(n,t)=>n>=t?n-t:Tn-(t-n),ct=(n,t)=>Gu(n*t),gh=(n,t)=>Gu(n+t),Vr=n=>{let t=Ce,e=Ut,i=cr(n),r=Tn;for(;i>Ce;){let s=r/i;[t,e]=[e-t*s,t],[i,r]=[r-i*s,i]}return cr(t)},Z1=n=>ct(n,n),J1=(n,t)=>{let e=1n;for(n=cr(n);t>0n;)(t&1n)!==0n&&(e=ct(e,n)),n=ct(n,n),t>>=1n;return e},Q1=Tn+1n>>2n,tw=n=>{let t=J1(n,Q1);return ct(t,t)!==cr(n)?null:t},ew=n=>T.isBN(n)?BigInt("0x"+n.toString(16)):typeof n=="string"?BigInt("0x"+n):Array.isArray(n)?BigInt("0x"+nt(n)):BigInt(n),Ba=BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),_a=BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),mh=new Map,uo=n=>{let{X:t,Y:e,Z:i}=n;if(e===Ut)return{X:Ut,Y:Ce,Z:Ut};let r=ct(e,e),s=ct(G1,ct(t,r)),o=ct(j1,ct(t,t)),c=kn(ct(o,o),ct(Xu,s)),u=kn(ct(o,kn(s,c)),ct(Y1,ct(r,r))),f=ct(Xu,ct(e,i));return{X:c,Y:u,Z:f}},Kr=(n,t)=>{if(n.Z===Ut)return t;if(t.Z===Ut)return n;let e=ct(n.Z,n.Z),i=ct(t.Z,t.Z),r=ct(n.X,i),s=ct(t.X,e),o=ct(n.Y,ct(i,t.Z)),c=ct(t.Y,ct(e,n.Z)),u=kn(s,r),f=kn(c,o);if(u===Ut)return f===Ut?uo(n):{X:Ut,Y:Ce,Z:Ut};let d=ct(u,u),l=ct(u,d),p=ct(r,d),m=kn(kn(ct(f,f),l),ct(Xu,p)),g=kn(ct(f,kn(p,m)),ct(o,l)),w=ct(u,ct(n.Z,t.Z));return{X:m,Y:g,Z:w}},nw=n=>n.Z===Ut?n:{X:n.X,Y:Tn-n.Y,Z:n.Z},iw=(n,t)=>{let e=`${n}:${t.x.toString(16)}:${t.y.toString(16)}`,i=mh.get(e);if(i!==void 0)return i;let r=Array.from({length:1<<n-1},()=>({X:Ut,Y:Ce,Z:Ut})),s={X:t.x,Y:t.y,Z:Ce};r[0]=s;let o=uo(s);for(let c=1;c<r.length;c++)r[c]=Kr(r[c-1],o);return mh.set(e,r),r},rw=(n,t)=>{let e=[],i=1n<<BigInt(t),r=i>>1n,s=n;for(;s>0n;){if((s&Ce)===Ut)e.push(0);else{let o=s&i-1n;o>r&&(o-=i),e.push(Number(o)),s-=o}s>>=Ce}return e},Ca=(n,t,e=5)=>{let i=iw(e,t),r=rw(n,e),s={X:Ut,Y:Ce,Z:Ut};for(let o=r.length-1;o>=0;o--){s=uo(s);let c=r[o];if(c!==0){let u=Math.abs(c)>>1,f=c>0?i[u]:nw(i[u]);s=Kr(s,f)}}return s},ur=n=>{let t=n%xi;return t<0n&&(t+=xi),t},fo=(n,t)=>ur(n*t),Yu=n=>{let t=1n,e=0n,i=ur(n),r=xi;for(;i>1n;){let s=r/i;[t,e]=[e-t*s,t],[i,r]=[r-i*s,i]}return ur(t)},pe,bh,wh,yh,xh,Sh,ju,Ih,Ot=class Ot extends or{constructor(e,i,r=!0){super("affine");G(this,pe);b(this,"x");b(this,"y");b(this,"inf");this.precomputed=null,e===null&&i===null?(this.x=null,this.y=null,this.inf=!0):(T.isBN(e)||(e=new T(e,16)),this.x=e,T.isBN(i)||(i=new T(i,16)),this.y=i,r&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red===null&&(this.x=this.x.toRed(this.curve.red)),this.y.red===null&&(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}static _assertOnCurve(e){if(!e.validate())throw new Error("Invalid point");return e}static fromDER(e){if((e[0]===4||e[0]===6||e[0]===7)&&e.length-1===64){if(e[0]===6){if(e.at(-1)%2!==0)throw new Error("Point string value is wrong length")}else if(e[0]===7&&e.at(-1)%2!==1)throw new Error("Point string value is wrong length");let r=new Ot(e.slice(1,33),e.slice(33,65));return Ot._assertOnCurve(r)}else if((e[0]===2||e[0]===3)&&e.length-1===32)return Ot._assertOnCurve(Ot.fromX(e.slice(1,33),e[0]===3));throw new Error("Unknown point format")}static fromString(e){let i=at(e,"hex");return Ot._assertOnCurve(Ot.fromDER(i))}static fromX(e,i){let r=ew(e);r=cr(r);let s=gh(ct(Z1(r),r),7n),o=tw(s);if(o===null)throw new Error("Invalid point");let c=o;(c&Ce)!==(i?Ce:Ut)&&(c=kn(Tn,c));let u=new T(r.toString(16),16),f=new T(c.toString(16),16);return Ot._assertOnCurve(new Ot(u,f))}static fromJSON(e,i){typeof e=="string"&&(e=JSON.parse(e));let r=new Ot(e[0],e[1],i);if(r=Ot._assertOnCurve(r),typeof e[2]!="object"||e[2]===null)return r;let s=e[2],o=c=>{let u=new Ot(c[0],c[1],i);return Ot._assertOnCurve(u)};return r.precomputed={beta:null,doubles:typeof s.doubles=="object"&&s.doubles!==null?{step:s.doubles.step,points:[r].concat(s.doubles.points.map(o))}:void 0,naf:typeof s.naf=="object"&&s.naf!==null?{wnd:s.naf.wnd,points:[r].concat(s.naf.points.map(o))}:void 0},r}validate(){if(this.inf||this.x==null||this.y==null)return!1;try{let e=BigInt("0x"+this.x.fromRed().toString(16)),i=BigInt("0x"+this.y.fromRed().toString(16)),r=ct(i,i),s=gh(ct(ct(e,e),e),7n);return r===s}catch{return!1}}encode(e=!0,i){if(this.inf)return i==="hex"?"00":[0];let r=this.curve.p.byteLength(),s=this.getX().toArray("be",r),o;return e?o=[this.getY().isEven()?2:3].concat(s):o=[4].concat(s,this.getY().toArray("be",r)),i==="hex"?nt(o):o}toString(){return this.encode(!0,"hex")}toJSON(){return this.precomputed==null?[this.x,this.y]:[this.x,this.y,typeof this.precomputed=="object"&&this.precomputed!==null?{doubles:this.precomputed.doubles==null?void 0:{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)},naf:this.precomputed.naf==null?void 0:{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}}:void 0]}inspect(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+(this.x?.fromRed()?.toString(16,2)??"undefined")+" y: "+(this.y?.fromRed()?.toString(16,2)??"undefined")+">"}isInfinity(){return this.inf}add(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return new Ot(null,null);if(this.x?.cmp(e.x??new T(0))===0)return new Ot(null,null);let i={X:BigInt("0x"+this.x.fromRed().toString(16)),Y:BigInt("0x"+this.y.fromRed().toString(16)),Z:Ce},r={X:BigInt("0x"+e.x.fromRed().toString(16)),Y:BigInt("0x"+e.y.fromRed().toString(16)),Z:Ce},s=Kr(i,r);if(s.Z===Ut)return new Ot(null,null);let o=Vr(s.Z),c=ct(o,o),u=ct(s.X,c),f=ct(s.Y,ct(c,o));return new Ot(u.toString(16),f.toString(16))}dbl(){if(this.inf)return this;if(this.x===null||this.y===null)throw new Error("Point coordinates cannot be null");let e=BigInt("0x"+this.x.fromRed().toString(16)),i=BigInt("0x"+this.y.fromRed().toString(16));if(i===Ut)return new Ot(null,null);let r=uo({X:e,Y:i,Z:Ce}),s=Vr(r.Z),o=ct(s,s),c=ct(r.X,o),u=ct(r.Y,ct(o,s));return new Ot(c.toString(16),u.toString(16))}getX(){return(this.x??new T(0)).fromRed()}getY(){return(this.y??new T(0)).fromRed()}mul(e){if(T.isBN(e)||(e=new T(e,16)),e=e,this.inf)return this;let i=e.isNeg(),r=i?e.neg():e,s=BigInt("0x"+r.toString(16));if(s=cr(s),s===Ut)return new Ot(null,null);if(s===Ut)return new Ot(null,null);if(this.x===null||this.y===null)throw new Error("Point coordinates cannot be null");let o,c;this===this.curve.g?(o=Ba,c=_a):(o=BigInt("0x"+this.x.fromRed().toString(16)),c=BigInt("0x"+this.y.fromRed().toString(16)));let u=Ca(s,{x:o,y:c});if(u.Z===Ut)return new Ot(null,null);let f=Vr(u.Z),d=ct(f,f),l=ct(u.X,d),p=ct(u.Y,ct(d,f)),m=new T(l.toString(16),16),g=new T(p.toString(16),16),w=new Ot(m,g);return i?w.neg():w}mulCT(e){if(T.isBN(e)||(e=new T(e,16)),e=e,this.inf)return new Ot(null,null);let i=e.isNeg(),r=i?e.neg():e,s=BigInt("0x"+r.toString(16));if(s=cr(s),s===0n)return new Ot(null,null);let o=this===this.curve.g?Ba:BigInt("0x"+this.getX().toString(16)),c=this===this.curve.g?_a:BigInt("0x"+this.getY().toString(16)),u={X:0n,Y:1n,Z:0n},f={X:o,Y:c,Z:1n},d=s.toString(2);for(let S of d){let C=S==="1"?1n:0n;hh(C,u,f),f=Kr(u,f),u=uo(u),hh(C,u,f)}if(u.Z===0n)return new Ot(null,null);let l=Vr(u.Z),p=ct(l,l),m=ct(u.X,p),g=ct(u.Y,ct(p,l)),w=new Ot(m.toString(16),g.toString(16));return i?w.neg():w}mulAdd(e,i,r){let s=[this,i],o=[e,r];return a(this,pe,ju).call(this,s,o)}jmulAdd(e,i,r){let s=[this,i],o=[e,r];return a(this,pe,ju).call(this,s,o,!0)}eq(e){return this===e||this.inf===e.inf&&(this.inf||(this.x??new T(0)).cmp(e.x??new T(0))===0&&(this.y??new T(0)).cmp(e.y??new T(0))===0)}neg(e){if(this.inf)return this;let i=new Ot(this.x,(this.y??new T(0)).redNeg());if(e===!0&&this.precomputed!=null){let r=this.precomputed,s=o=>o.neg();i.precomputed={naf:r.naf==null?void 0:{wnd:r.naf.wnd,points:r.naf.points.map(s)},doubles:r.doubles==null?void 0:{step:r.doubles.step,points:r.doubles.points.map(o=>o.neg())},beta:void 0}}return i}dblp(e){let i;for(let r=0;r<e;r++)i=(i??this).dbl();return i??this}toJ(){return this.inf?new ar(null,null,null):new ar(this.x,this.y,this.curve.one)}_combineWnafPair(e,i,r){let{points:s,coeffs:o,wndWidth:c,wnd:u,naf:f,currentMax:d}=r;if(c[e]!==1||c[i]!==1)return f[e]=this.curve.getNAF(o[e],c[e],this.curve._bitLength),f[i]=this.curve.getNAF(o[i],c[i],this.curve._bitLength),Math.max(d,f[e].length,f[i].length);let l=[s[e],null,null,s[i]],p=s[e].y??new T(0),m=s[i].y??new T(0);p.cmp(m)===0?(l[1]=s[e].add(s[i]),l[2]=s[e].toJ().mixedAdd(s[i].neg())):p.cmp(m.redNeg())===0?(l[1]=s[e].toJ().mixedAdd(s[i]),l[2]=s[e].add(s[i].neg())):(l[1]=s[e].toJ().mixedAdd(s[i]),l[2]=s[e].toJ().mixedAdd(s[i].neg()));let g=[-3,-1,-5,-7,0,7,5,1,3],w=this.curve.getJSF(o[e],o[i]),S=Math.max(d,w[0].length);f[e]=Array.from({length:S}),f[i]=Array.from({length:S});for(let C=0;C<S;C++){let E=Math.trunc(w[0][C]),A=Math.trunc(w[1][C]);f[e][C]=g[(E+1)*3+(A+1)],f[i][C]=0,u[e]=l}return S}_collectWnafStep(e,i,r,s){let o=e,c=0;for(;o>=0;){let u=!0;for(let f=0;f<i;f++)s[f]=new T(typeof r[f][o]=="number"?r[f][o]:0),s[f].isZero()||(u=!1);if(!u)break;c++,o--}return o>=0&&c++,{index:o,doubles:c}}_getDoubles(e,i){if(typeof this.precomputed=="object"&&this.precomputed!==null&&typeof this.precomputed.doubles=="object"&&this.precomputed.doubles!==null)return this.precomputed.doubles;let r=[this],s;for(let o=0;o<(i??0);o+=e??1){for(let c=0;c<(e??1);c++)s=(s??this).dbl();r.push(s)}return{step:e??1,points:r}}};pe=new WeakSet,bh=function(){if(typeof this.curve.endo!="object")return;let e=this.precomputed;if(typeof e=="object"&&e!==null&&typeof e.beta=="object"&&e.beta!==null)return e.beta;let i=new Ot((this.x??new T(0)).redMul(this.curve.endo.beta),this.y);if(e!=null){let r=this.curve,s=o=>{let c=o;if(c.x===null)throw new Error("p.x is null");if(r.endo===void 0||r.endo===null)throw new Error("curve.endo is undefined");return new Ot(c.x.redMul(r.endo.beta),c.y)};e.beta=i,i.precomputed={beta:null,naf:e.naf==null?void 0:{wnd:e.naf.wnd,points:e.naf.points.map(s)},doubles:e.doubles==null?void 0:{step:e.doubles.step,points:e.doubles.points.map(s)}}}return i},wh=function(e,i,r,s,o){var c;for(let u=0;u<r;u++){let f=a(c=i[u],pe,Ih).call(c,e);s[u]=f.wnd,o[u]=f.points}},yh=function(e,i,r,s,o,c){let u=0;for(let f=r-1;f>=1;f-=2)u=this._combineWnafPair(f-1,f,{points:e,coeffs:i,wndWidth:s,wnd:o,naf:c,currentMax:u});return u},xh=function(e,i,r,s){let o=new T(1),c=new T(2),u=e;for(let f=0;f<i;f++){let d=r[f];if(d.cmpn(0)===0)continue;let l=d.isNeg()?s[f][d.neg().sub(o).div(c).toNumber()].neg():s[f][d.sub(o).div(c).toNumber()];u=l.type==="affine"?u.mixedAdd(l):u.add(l)}return u},Sh=function(e,i,r,s,o){let c=this.curve._wnafT1.length,u=Array.from({length:c}),f=Array.from({length:c},()=>[]),d=Array.from({length:c},()=>[]);a(this,pe,wh).call(this,e,i,s,u,f);let l=a(this,pe,yh).call(this,i,r,s,u,f,d),p=new ar(null,null,null),m=this.curve._wnafT4,g=l;for(;g>=0;){let w=this._collectWnafStep(g,s,d,m);if(g=w.index,p=p.dblp(w.doubles),g<0)break;p=a(this,pe,xh).call(this,p,s,m,f),g--}for(let w=0;w<s;w++)f[w]=[];return o===!0?p:p.toP()},ju=function(e,i,r){var f;let s=Array.from({length:e.length*2}),o=Array.from({length:e.length*2}),c;for(c=0;c<e.length;c++){let d=this.curve._endoSplit(i[c]),l=e[c],p=a(f=l,pe,bh).call(f)??new Ot(null,null);d.k1.negative!==0&&(d.k1.ineg(),l=l.neg(!0)),d.k2.negative!==0&&(d.k2.ineg(),p=p.neg(!0)),s[c*2]=l,s[c*2+1]=p,o[c*2]=d.k1,o[c*2+1]=d.k2}let u=a(this,pe,Sh).call(this,1,s,o,c*2,r);for(let d=0;d<c*2;d++)s[d]=null,o[d]=null;return u},Ih=function(e){if(typeof this.precomputed=="object"&&this.precomputed!==null&&typeof this.precomputed.naf=="object"&&this.precomputed.naf!==null)return this.precomputed.naf;let i=[this],r=(1<<e)-1,s=r===1?null:this.dbl();for(let o=1;o<r;o++)s!==null&&(i[o]=i[o-1].add(s));return{wnd:e,points:i}};var Oe=Ot;var Ht=class n extends Oe{static fromPrivateKey(t){let i=new Vt().g.mul(t);return new n(i.x,i.y)}static fromString(t){let e=Oe.fromString(t);return new n(e.x,e.y)}static fromDER(t){let e=Oe.fromDER(t);return new n(e.x,e.y)}constructor(t,e=null,i=!0){if(t instanceof Oe)super(t.getX(),t.getY());else{if(e===null&&i&&typeof t=="string"&&(t.length===66||t.length===130))throw new Error('You are using the "new PublicKey()" constructor with a DER hex string. You need to use "PublicKey.fromString()" instead.');super(t,e,i)}}deriveSharedSecret(t){if(!this.validate())throw new Error("Public key not valid for ECDH secret derivation");return this.mulCT(t)}verify(t,e,i){let r=new T(Te(t,i),16);return Si(r,e,this)}toDER(t){return t==="hex"?this.encode(!0,t):this.encode(!0)}toHash(t){let e=Js(this.encode(!0));return t==="hex"?nt(e):e}toAddress(t=[0]){if(typeof t=="string")if(t==="testnet"||t==="test")t=[111];else if(t==="mainnet"||t==="main")t=[0];else throw new Error(`Invalid prefix ${t}`);return ao(this.toHash(),t)}deriveChild(t,e,i,r){let s;if(typeof r=="function"){let l=r(t,this);l===void 0?(s=this.deriveSharedSecret(t),typeof i=="function"&&i(t,this,s)):s=l}else s=this.deriveSharedSecret(t);let o=at(e,"utf8"),c=Qs(s.encode(!0),o),f=new Vt().g.mul(new T(c)),d=this.add(f);return new n(d.x,d.y)}static fromMsgHashAndCompactSignature(t,e,i){let r=at(e,i);if(r.length!==65)throw new Error("Invalid Compact Signature");let s=r[0];if(s<27||s>=35)throw new Error("Invalid Compact Byte");let o=r[0]-27;return o>3&&(o-=4),new ge(new T(r.slice(1,33)),new T(r.slice(33,65))).RecoverPublicKey(o,t)}};var ge=class n{constructor(t,e){b(this,"r");b(this,"s");this.r=t,this.s=e}static fromDER(t,e){let i=(l,p)=>{let m=l[p.place++];if((m&128)===0)return m;throw new Error("Invalid DER entity length")};class r{constructor(){b(this,"place",0)}}t=at(t,e);let s=new r;if(t[s.place++]!==48)throw new Error("Signature DER must start with 0x30");if(i(t,s)+s.place!==t.length)throw new Error("Signature DER invalid");if(t[s.place++]!==2)throw new Error("Signature DER invalid");let c=i(t,s),u=t.slice(s.place,c+s.place);if(s.place+=c,t[s.place++]!==2)throw new Error("Signature DER invalid");let f=i(t,s);if(t.length!==f+s.place)throw new Error("Invalid R-length in signature DER");let d=t.slice(s.place,f+s.place);if(u[0]===0){if((u[1]&128)===0)throw new Error("Invalid R-value in signature DER");u=u.slice(1)}if(d[0]===0){if((d[1]&128)===0)throw new Error("Invalid S-value in signature DER");d=d.slice(1)}return new n(new T(u),new T(d))}static fromCompact(t,e){if(t=at(t,e),t.length!==65)throw new Error("Invalid Compact Signature");let i=t[0];if(i<27||i>=35)throw new Error("Invalid Compact Byte");return new n(new T(t.slice(1,33)),new T(t.slice(33,65)))}verify(t,e,i){let r=new T(Te(t,i),16);return Si(r,this,e)}toString(t){return this.toDER(t)}toDER(t){let e=(f,d)=>{if(d<128)f.push(d);else throw new Error("len must be < 0x80")},i=f=>{let d=0,l=f.length-1;for(;f[d]===0&&(f[d+1]&128)===0&&d<l;)d++;return d===0?f:f.slice(d)},r=this.r.toArray(),s=this.s.toArray();for((r[0]&128)!==0&&(r=[0].concat(r)),(s[0]&128)!==0&&(s=[0].concat(s)),r=i(r),s=i(s);s[0]===0&&(s[1]&128)===0;)s=s.slice(1);let o=[2];e(o,r.length),o=o.concat(r),o.push(2),e(o,s.length);let c=o.concat(s),u=[48];return e(u,c.length),u=u.concat(c),t==="hex"?nt(u):t==="base64"?ve(u):u}toCompact(t,e,i){if(t<0||t>3)throw new Error("Invalid recovery param");if(typeof e!="boolean")throw new TypeError("Invalid compressed param");let r=27+t;e&&(r+=4);let s=[r];return s=s.concat(this.r.toArray("be",32)),s=s.concat(this.s.toArray("be",32)),i==="hex"?nt(s):i==="base64"?ve(s):s}RecoverPublicKey(t,e){let i=this.r,r=this.s,s=(t&1)!==0,o=t>>1,c=new Vt,u=c.n,f=c.g,d=o===0?i:i.add(u),l=Oe.fromX(d,s);if(!l.mul(u).isInfinity())throw new Error("nR is not at infinity");let m=e.neg().umod(u),g=i.invm(u),w=g.mul(r).umod(u),S=g.mul(m).umod(u),C=f.mul(S).add(l.mul(w)),E=new Ht(C);return E.validate(),E}CalculateRecoveryFactor(t,e){for(let i=0;i<4;i++){let r;try{r=this.RecoverPublicKey(i,e)}catch{continue}if(t.eq(r))return i}throw new Error("Unable to find valid recovery factor")}};var lo=class{constructor(t,e){b(this,"K");b(this,"V");let i=at(t,"hex"),r=at(e,"hex");if(i.length!==32)throw new Error("Entropy must be exactly 32 bytes (256 bits)");if(r.length!==32)throw new Error("Nonce must be exactly 32 bytes (256 bits)");let s=i.concat(r);this.K=Array.from({length:32}),this.V=Array.from({length:32});for(let o=0;o<32;o++)this.K[o]=0,this.V[o]=1;this.update(s)}hmac(){return new Fr(this.K)}update(t){let e=this.hmac().update(this.V).update([0]);t!==void 0&&(e=e.update(t)),this.K=e.digest(),this.V=this.hmac().update(this.V).digest(),t!==void 0&&(this.K=this.hmac().update(this.V).update([1]).update(t).digest(),this.V=this.hmac().update(this.V).digest())}generate(t){let e=[];for(;e.length<t;)this.V=this.hmac().update(this.V).digest(),e=e.concat(this.V);let i=e.slice(0,t);return this.update(),nt(i)}};function vh(n,t,e=new Vt){let i=n.byteLength()*8-e.n.bitLength();return i>0&&n.iushrn(i),t!==!0&&n.cmp(e.n)>=0?n.sub(e.n):n}function fr(n){let t=n.toArray("be"),e=0n;for(let i of t)e=e<<8n|BigInt(i);return e}var ho=new Vt,Zu=ho.n.byteLength(),sw=ho.n.subn(1),ow=xi>>1n;function aw(n,t,e){let i;if(typeof n=="function"?i=n(t):n!==void 0&&T.isBN(n)?i=n:i=new T(e.generate(Zu),16),i==null)throw new Error("k is undefined");return vh(i,!0)}function La(n,t){if(n)throw new Error(t)}function cw(n,t,e,i,r){if(n.cmpn(1)<0||n.cmp(sw)>0)return La(r,"Invalid fixed custom K value (must be >1 and <N-1)");let s=ho.g.mulCT(n);if(s.isInfinity())return La(r,"Invalid fixed custom K value (k\xB7G at infinity)");let o=ur(BigInt("0x"+s.getX().toString(16)));if(o===0n)return La(r,"Invalid fixed custom K value (r == 0)");let c=Yu(BigInt("0x"+n.toString(16))),u=ur(t+fo(o,e)),f=fo(c,u);return f===0n?La(r,"Invalid fixed custom K value (s == 0)"):(i&&f>ow&&(f=xi-f),new ge(new T(o.toString(16),16),new T(f.toString(16),16)))}var Ah=(n,t,e=!1,i)=>{let r=ho.n.bitLength();if(n.bitLength()>r)throw new Error(`ECDSA message is too large: expected <= ${r} bits. Callers must hash messages before signing.`);n=vh(n);let s=fr(n),o=fr(t),c=t.toArray("be",Zu),u=n.toArray("be",Zu),f=new lo(c,u),d=T.isBN(i);for(let l=0;;l++){let p=cw(aw(i,l,f),s,o,e,d);if(p!=null)return p}},Si=(n,t,e)=>{let i=ho.n.bitLength();if(n.bitLength()>i)return!1;let r=fr(n);if(e.x==null||e.y==null)throw new Error("Invalid public key: missing coordinates.");let s={x:fr(e.x),y:fr(e.y)},o={r:fr(t.r),s:fr(t.s)},{r:c,s:u}=o,f=r;if(c<=Ut||c>=xi||u<=Ut||u>=xi)return!1;let d=Yu(u);if(d===0n)return!1;let l=fo(f,d),p=fo(c,d),m=Ca(l,{x:Ba,y:_a}),g=Ca(p,s),w=Kr(m,g);if(w.Z===0n)return!1;let S=Vr(w.Z),C=ct(S,S),E=ct(w.X,C);return ur(E)===c};var Ju=class{constructor(){b(this,"_rand");let t=()=>{throw new Error("No secure random number generator is available in this environment.")};if(this._rand=t,typeof globalThis<"u"&&typeof globalThis.crypto?.getRandomValues=="function"){this._rand=e=>this.getRandomValues(globalThis,e);return}if(globalThis.self!==void 0&&typeof globalThis.self.crypto?.getRandomValues=="function"){this._rand=e=>this.getRandomValues(globalThis.self,e);return}if(globalThis.window!==void 0&&typeof globalThis.window.crypto?.getRandomValues=="function"){this._rand=e=>this.getRandomValues(globalThis.window,e);return}if(typeof process<"u"&&typeof process.getBuiltinModule=="function"){let e=process.getBuiltinModule("node:crypto");if(typeof e?.randomBytes=="function"){this._rand=i=>Array.from(e.randomBytes(i));return}}this._rand=t}getRandomValues(t,e){let i=new Uint8Array(e);return t.crypto.getRandomValues(i),Array.from(i)}generate(t){return this._rand(t)}},Eh=null,uw=n=>(Eh??(Eh=new Ju),Eh.generate(n)),Pe=uw;var Ae=255,fw=129,kh=/^[1-9A-HJ-NP-Za-km-z]{1,64}$/;function Th(n,t,e){if(!Number.isSafeInteger(n)||n<e||n>Ae)throw new TypeError(`threshold must be a safe integer from ${e} to ${Ae}`);if(n>t)throw new Error("threshold cannot exceed the number of points")}var nn=class n{constructor(t,e){b(this,"x");b(this,"y");let i=new Vt().p;this.x=t.umod(i),this.y=e.umod(i)}toString(){return oo(this.x.toArray())+"."+oo(this.y.toArray())}static fromString(t){if(typeof t!="string"||t.length>fw)throw new TypeError("Finite-field point must use a bounded canonical Base58 representation");let[e,i,r]=t.split(".");if(r!==void 0||e===void 0||i===void 0||!kh.test(e)||!kh.test(i))throw new TypeError("Finite-field point must use a bounded canonical Base58 representation");let s=new n(new T(so(e)),new T(so(i)));if(s.toString()!==t)throw new TypeError("Finite-field point must use a bounded canonical Base58 representation");return s}},zr=class n{constructor(t,e){b(this,"points");b(this,"threshold");if(!Array.isArray(t)||t.length===0||t.length>Ae)throw new TypeError(`points must contain from 1 to ${Ae} entries`);let i=e??t.length;Th(i,t.length,1),this.points=t.slice(),this.threshold=i}static fromPrivateKey(t,e){if(!Number.isSafeInteger(e)||e<2||e>Ae)throw new TypeError(`threshold must be a safe integer from 2 to ${Ae}`);let i=new Vt().p,r=[new nn(new T(0),new T(t.toArray()))];for(let s=1;s<e;s++){let o=new T(Pe(32)).umod(i),c=new T(Pe(32)).umod(i);r.push(new nn(o,c))}return new n(r)}valueAt(t){if(Th(this.threshold,this.points.length,1),!(t instanceof T))throw new TypeError("x must be a BigNumber");let e=new Vt().p,i=new Set;for(let o=0;o<this.threshold;o++){let c=this.points[o];if(!(c instanceof nn)||!(c.x instanceof T)||!(c.y instanceof T))throw new TypeError("points must contain finite-field points");if(c.x.isNeg()||c.y.isNeg()||c.x.gte(e)||c.y.gte(e))throw new TypeError("point coordinates must be canonical field elements");let u=c.x.toString(16);if(i.has(u))throw new Error("Polynomial points must have unique x coordinates");i.add(u)}let r=t.umod(e),s=new T(0);for(let o=0;o<this.threshold;o++){let c=this.points[o].y;for(let u=0;u<this.threshold;u++)if(o!==u){let f=this.points[u].x,d=this.points[o].x,l=r.sub(f).umod(e),m=d.sub(f).umod(e).invm(e),g=l.mul(m).umod(e);c=c.mul(g).umod(e)}s=s.add(c).umod(e)}return s}};var dw=256,Oh=/^[1-9A-HJ-NP-Za-km-z]{1,64}$/,lw=/^(?:[2-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/,Ph=/^[0-9a-f]{8}$/;function Qu(n,t,e){if(!Array.isArray(n)||n.length===0||n.length>Ae)throw new TypeError(`shares must contain from 1 to ${Ae} entries`);if(!Number.isSafeInteger(t)||t<2||t>Ae)throw new TypeError(`threshold must be a safe integer from 2 to ${Ae}`);if(typeof e!="string"||!Ph.test(e))throw new TypeError("integrity must be an 8-character lowercase hexadecimal string")}var po=class n{constructor(t,e,i){b(this,"points");b(this,"threshold");b(this,"integrity");this.points=t,this.threshold=e,this.integrity=i}static fromBackupFormat(t){if(!Array.isArray(t)||t.length===0||t.length>Ae)throw new TypeError(`shares must contain from 1 to ${Ae} entries`);let e=0,i="",r=[];for(let s=0;s<t.length;s++){if(!Object.prototype.hasOwnProperty.call(t,s))throw new TypeError("shares must be a dense array");let o=t[s];if(typeof o!="string"||o.length>dw)throw new TypeError(`Invalid share format in share ${s.toString()}`);let c=o.split(".");if(c.length!==4)throw new Error(`Invalid share format in share ${s.toString()}. Expected format: "x.y.t.i"`);let[u,f,d,l]=c;if(u===void 0||f===void 0||d===void 0||l===void 0||!Oh.test(u)||!Oh.test(f)||!lw.test(d)||!Ph.test(l))throw new TypeError(`Invalid canonical share data in share ${s.toString()}`);let p=Number(d);if(s!==0&&e!==p)throw new Error("Threshold mismatch in share "+s.toString());if(s!==0&&i!==l)throw new Error("Integrity mismatch in share "+s.toString());e=p,i=l,r.push(nn.fromString(`${u}.${f}`))}return Qu(r,e,i),new n(r,e,i)}toBackupFormat(){Qu(this.points,this.threshold,this.integrity);let t=[];for(let e=0;e<this.points.length;e++){if(!Object.prototype.hasOwnProperty.call(this.points,e))throw new TypeError("shares must be a dense array");let i=this.points[e];if(!(i instanceof nn))throw new TypeError("shares must contain finite-field points");let r=i.toString();if(nn.fromString(r).toString()!==r)throw new TypeError("shares must contain canonical finite-field points");t.push(`${r}.${this.threshold.toString()}.${this.integrity}`)}return t}},dr=class n extends T{static fromRandom(){return new n(Pe(32))}static fromString(t,e="hex"){return new n(super.fromString(t,e).toArray())}static fromHex(t){return new n(super.fromHex(t,"big"))}static fromWif(t,e=1){let i=co(t,void 0,e);if(i.data.length!==33)throw new Error("Invalid WIF length");if(i.data[32]!==1)throw new Error("Invalid WIF padding");return new n(i.data.slice(0,32))}constructor(t=0,e=10,i="be",r="apply"){if(t instanceof T?(super(),t.copy(this)):super(t,e,i),r!=="nocheck"){let s=this.checkInField();if(!s.inField){if(r==="error")throw new Error("Input is out of field");T.move(this,s.modN)}}}checkInField(){let t=new Vt,e=this.mod(t.n);return{inField:this.cmp(e)===0,modN:e}}isValid(){return this.checkInField().inField}sign(t,e,i=!0,r){let s=new T(Te(t,e),16);return Ah(s,this,i,r)}verify(t,e,i){let r=new T(Te(t,i),16);return Si(r,e,this.toPublicKey())}toPublicKey(){let e=new Vt().g.mulCT(this);return new Ht(e.x,e.y)}toWif(t=[128]){if(!this.isValid())throw new Error("Value is out of field");return ao([...this.toArray("be",32),1],t)}toAddress(t=[0]){return this.toPublicKey().toAddress(t)}toHex(){return super.toHex(32)}toString(t="hex",e=64){return super.toString(t,e)}deriveSharedSecret(t){if(!t.validate())throw new Error("Public key not valid for ECDH secret derivation");return t.mulCT(this)}deriveChild(t,e,i,r){let s;if(typeof r=="function"){let f=r(this,t);f===void 0?(s=this.deriveSharedSecret(t),typeof i=="function"&&i(this,t,s)):s=f}else s=this.deriveSharedSecret(t);let o=at(e,"utf8"),c=Qs(s.encode(!0),o),u=new Vt;return new n(this.add(new T(c)).mod(u.n).toArray())}toKeyShares(t,e){if(typeof t!="number"||typeof e!="number")throw new TypeError("threshold and totalShares must be numbers");if(!Number.isSafeInteger(t)||!Number.isSafeInteger(e))throw new TypeError("threshold and totalShares must be safe integers");if(t<2)throw new Error("threshold must be at least 2");if(e<2)throw new Error("totalShares must be at least 2");if(t>e)throw new Error("threshold should be less than or equal to totalShares");if(t>Ae||e>Ae)throw new RangeError(`threshold and totalShares cannot exceed ${Ae}`);let i=zr.fromPrivateKey(this,t),r=[],s=new Set,o=new Vt,c=Pe(64);for(let f=0;f<e;f++){let d,l=0;do{let m=[f,l,...Pe(32)],g=Fu(c,m);if(d=new T(g).umod(o.p),l++,l>5)throw new Error("Failed to generate unique x coordinate after 5 attempts")}while(d.isZero()||s.has(d.toString()));s.add(d.toString());let p=i.valueAt(d);r.push(new nn(d,p))}let u=this.toPublicKey().toHash("hex").slice(0,8);return new po(r,t,u)}toBackupShares(t,e){return this.toKeyShares(t,e).toBackupFormat()}static fromBackupShares(t){return n.fromKeyShares(po.fromBackupFormat(t))}static fromKeyShares(t){if(t===null||typeof t!="object")throw new TypeError("keyShares must be an object");let e=t.points,i=t.threshold,r=t.integrity;if(Qu(e,i,r),e.length<i)throw new Error(`At least ${i} shares are required to reconstruct the private key`);let s=[],o=new Vt().p;for(let d=0;d<i;d++){if(!Object.prototype.hasOwnProperty.call(e,d))throw new TypeError("shares must be a dense array");let l=e[d];if(!(l instanceof nn)||!(l.x instanceof T)||!(l.y instanceof T))throw new TypeError("shares must contain finite-field points");if(l.x.isNeg()||l.y.isNeg()||l.x.gte(o)||l.y.gte(o))throw new TypeError("share coordinates must be canonical field elements");s.push(new nn(new T(l.x.toArray()),new T(l.y.toArray())))}for(let d=0;d<i;d++)for(let l=d+1;l<i;l++)if(s[d].x.eq(s[l].x))throw new Error("Duplicate share detected, each must be unique.");let c=new zr(s,i),u=new n(c.valueAt(new T(0)).toArray());if(u.toPublicKey().toHash("hex").slice(0,8)!==r)throw new Error("Integrity hash mismatch");return u}};var tf={OP_0:0,OP_FALSE:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_1:81,OP_TRUE:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SPLIT:127,OP_NUM2BIN:128,OP_BIN2NUM:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP2:177,OP_CHECKSEQUENCEVERIFY:178,OP_NOP3:178,OP_SUBSTR:179,OP_NOP4:179,OP_LEFT:180,OP_NOP5:180,OP_RIGHT:181,OP_NOP6:181,OP_LSHIFTNUM:182,OP_NOP7:182,OP_RSHIFTNUM:183,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_NOP11:186,OP_NOP12:187,OP_NOP13:188,OP_NOP14:189,OP_NOP15:190,OP_NOP16:191,OP_NOP17:192,OP_NOP18:193,OP_NOP19:194,OP_NOP20:195,OP_NOP21:196,OP_NOP22:197,OP_NOP23:198,OP_NOP24:199,OP_NOP25:200,OP_NOP26:201,OP_NOP27:202,OP_NOP28:203,OP_NOP29:204,OP_NOP30:205,OP_NOP31:206,OP_NOP32:207,OP_NOP33:208,OP_NOP34:209,OP_NOP35:210,OP_NOP36:211,OP_NOP37:212,OP_NOP38:213,OP_NOP39:214,OP_NOP40:215,OP_NOP41:216,OP_NOP42:217,OP_NOP43:218,OP_NOP44:219,OP_NOP45:220,OP_NOP46:221,OP_NOP47:222,OP_NOP48:223,OP_NOP49:224,OP_NOP50:225,OP_NOP51:226,OP_NOP52:227,OP_NOP53:228,OP_NOP54:229,OP_NOP55:230,OP_NOP56:231,OP_NOP57:232,OP_NOP58:233,OP_NOP59:234,OP_NOP60:235,OP_NOP61:236,OP_NOP62:237,OP_NOP63:238,OP_NOP64:239,OP_NOP65:240,OP_NOP66:241,OP_NOP67:242,OP_NOP68:243,OP_NOP69:244,OP_NOP70:245,OP_NOP71:246,OP_NOP72:247,OP_NOP73:248,OP_NOP77:252,OP_SMALLDATA:249,OP_SMALLINTEGER:250,OP_PUBKEYS:251,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},Ua=tf;for(let n of Object.keys(tf)){let t=tf[n];Ua[t]??(Ua[t]=n)}var x=Ua;var Rh=typeof globalThis>"u"?void 0:globalThis.Buffer,Nh=Symbol();function hr(n){return n[Nh]()}function hw(n){let t=n.data?.length??0;if(t===0||n.op===x.OP_RETURN||n.op<x.OP_PUSHDATA1)return[n.op];if(n.op===x.OP_PUSHDATA1)return[n.op,t&255];if(n.op===x.OP_PUSHDATA2)return[n.op,t&255,t>>8&255];if(n.op===x.OP_PUSHDATA4){let e=t>>>0;return[n.op,e&255,e>>8&255,e>>16&255,e>>24&255]}}function pw(n,t){let e=hw(n),i=n.data??[];if(e==null||t.length!==e.length+i.length)return!1;for(let r=0;r<e.length;r++)if(t[r]!==e[r])return!1;for(let r=0;r<i.length;r++)if(t[e.length+r]!==i[r])return!1;return!0}var Ve,zn,Ke,On,lr,te,Bh,_h,_t,ef,Ch,Lh,Kn,nf,Uh,Ma,Mh,rf,Dh,Hh,sf,$h,de=class de{constructor(t=[],e,i,r=!0){G(this,_t);G(this,Ve);G(this,zn);G(this,Ke);G(this,On);G(this,lr);N(this,Ve,t),N(this,zn,r),N(this,Ke,e),N(this,On,i)}static fromASM(t){var s;let e=[],i=t.split(" "),r=0;for(;r<i.length;){let{chunk:o,advance:c}=a(s=de,te,_h).call(s,i,r);e.push(o),r+=c}return new de(e)}static fromHex(t){if(t.length===0)return de.fromBinary([]);if(t.length%2!==0)throw new Error("There is an uneven number of characters in the string which suggests it is not hex encoded.");let e;try{e=ro(t)}catch{throw new Error("Some elements in this string are not hex encoded.")}return new de([],e,t.toLowerCase(),!1)}static fromBinary(t){let e=Uint8Array.from(t);return new de([],e,void 0,!1)}static fromBinaryView(t){return new de([],t,void 0,!1)}get chunks(){return a(this,_t,ef).call(this),y(this,Ve)}set chunks(t){N(this,Ve,t),N(this,zn,!0),a(this,_t,Kn).call(this)}toASM(){let t="";for(let e of this.chunks)t+=a(this,_t,$h).call(this,e);return t.slice(1)}toHex(){let t=a(this,_t,Ma).call(this);if(y(this,On)!=null)return y(this,On);let e=Rh==null?Pa(Array.from(t),"hex"):Rh.from(t).toString("hex");return N(this,On,e),e}toBinary(){return Array.from(this.toUint8Array())}toUint8Array(){return Uint8Array.from(a(this,_t,Ma).call(this))}[Nh](){return a(this,_t,Ma).call(this)}writeScript(t){return a(this,_t,Kn).call(this),this.chunks=this.chunks.concat(t.chunks),this}writeOpCode(t){return a(this,_t,Kn).call(this),this.chunks.push({op:t}),this}setChunkOpCode(t,e){return a(this,_t,Kn).call(this),this.chunks[t]={op:e},this}writeBn(t){if(a(this,_t,Kn).call(this),t.cmpn(0)===x.OP_0)this.chunks.push({op:x.OP_0});else if(t.cmpn(-1)===0)this.chunks.push({op:x.OP_1NEGATE});else if(t.cmpn(1)>=0&&t.cmpn(16)<=0)this.chunks.push({op:t.toNumber()+x.OP_1-1});else{let e=t.toSm("little");this.writeBin(e)}return this}writeBin(t){a(this,_t,Kn).call(this);let e,i=t.length>0?t:void 0;if(t.length>0&&t.length<x.OP_PUSHDATA1)e=t.length;else if(t.length===0)e=x.OP_0;else if(t.length<Math.pow(2,8))e=x.OP_PUSHDATA1;else if(t.length<Math.pow(2,16))e=x.OP_PUSHDATA2;else if(t.length<Math.pow(2,32))e=x.OP_PUSHDATA4;else throw new Error("You can't push that much data");return this.chunks.push({data:i,op:e}),this}writeNumber(t){return a(this,_t,Kn).call(this),this.writeBn(new T(t)),this}removeCodeseparators(){var e;let t=this.toUint8Array();return N(this,Ke,Uint8Array.from(a(e=de,te,Hh).call(e,t,x.OP_CODESEPARATOR))),N(this,On,void 0),N(this,Ve,[]),N(this,zn,!1),this}findAndDelete(t){a(this,_t,Kn).call(this);let e=t.toUint8Array();if(e.length===0)return this;for(let i=0;i<this.chunks.length;)pw(this.chunks[i],e)?this.chunks.splice(i,1):i++;return this}isPushOnly(){for(let t of this.chunks)if(t.op>x.OP_16)return!1;return!0}isLockingScript(){throw new Error("Not implemented")}isUnlockingScript(){throw new Error("Not implemented")}};Ve=new WeakMap,zn=new WeakMap,Ke=new WeakMap,On=new WeakMap,lr=new WeakMap,te=new WeakSet,Bh=function(t){return t>=0&&t<x.OP_PUSHDATA1?t:t<Math.pow(2,8)?x.OP_PUSHDATA1:t<Math.pow(2,16)?x.OP_PUSHDATA2:x.OP_PUSHDATA4},_h=function(t,e){var o;let i=t[e];if(i==="0")return{chunk:{op:0},advance:1};if(i==="-1")return{chunk:{op:x.OP_1NEGATE},advance:1};let r=i.startsWith("OP_")&&x[i]!==void 0,s=r?x[i]:0;if(s===x.OP_PUSHDATA1||s===x.OP_PUSHDATA2||s===x.OP_PUSHDATA4)return{chunk:{data:at(t[e+2],"hex"),op:s},advance:3};if(!r){let c=i;c.length%2!==0&&(c="0"+c);let u=at(c,"hex");if(Pa(u,"hex")!==c)throw new Error("invalid hex string in script");return{chunk:{data:u,op:a(o=de,te,Bh).call(o,u.length)},advance:1}}return{chunk:{op:s},advance:1}},_t=new WeakSet,ef=function(){var t;y(this,zn)||(y(this,Ke)!=null?N(this,Ve,a(t=de,te,Dh).call(t,y(this,Ke))):N(this,Ve,[]),N(this,zn,!0),a(this,_t,nf).call(this))},Ch=function(t){let e=0;for(let i of t){if(e+=1,i.data==null)continue;let r=i.data.length;if(i.op===x.OP_RETURN){e+=r;break}i.op<x.OP_PUSHDATA1?e+=r:i.op===x.OP_PUSHDATA1?e+=1+r:i.op===x.OP_PUSHDATA2?e+=2+r:i.op===x.OP_PUSHDATA4&&(e+=4+r)}return e},Lh=function(){var s,o;let t=this.chunks,e=a(s=de,te,Ch).call(s,t),i=new Uint8Array(e),r=0;for(let c of t)if(i[r++]=c.op,c.data!=null){if(c.op===x.OP_RETURN){i.set(c.data,r);break}r=a(o=de,te,Mh).call(o,i,r,c.op,c.data)}return i},Kn=function(){N(this,Ke,void 0),N(this,On,void 0),N(this,lr,void 0)},nf=function(){N(this,lr,y(this,Ve).map(t=>({ref:t,op:t.op,dataRef:t.data,data:t.data==null?void 0:Array.from(t.data)})))},Uh=function(){if(y(this,lr)?.length!==y(this,Ve).length)return!1;for(let t=0;t<y(this,Ve).length;t++){let e=y(this,Ve)[t],i=y(this,lr)[t];if(i.ref!==e||i.op!==e.op||i.dataRef!==e.data||i.data?.length!==e.data?.length)return!1;if(i.data!=null&&e.data!=null){for(let r=0;r<i.data.length;r++)if(i.data[r]!==e.data[r])return!1}}return!0},Ma=function(){return!y(this,zn)&&y(this,Ke)!=null?y(this,Ke):(a(this,_t,ef).call(this),(y(this,Ke)==null||!a(this,_t,Uh).call(this))&&(N(this,Ke,a(this,_t,Lh).call(this)),N(this,On,void 0),a(this,_t,nf).call(this)),y(this,Ke))},Mh=function(t,e,i,r){let s=r.length;if(i<x.OP_PUSHDATA1)return t.set(r,e),e+s;if(i===x.OP_PUSHDATA1)return t[e++]=s&255,t.set(r,e),e+s;if(i===x.OP_PUSHDATA2)return t[e++]=s&255,t[e++]=s>>8&255,t.set(r,e),e+s;if(i===x.OP_PUSHDATA4){let o=s>>>0;return t[e++]=o&255,t[e++]=o>>8&255,t[e++]=o>>16&255,t[e++]=o>>24&255,t.set(r,e),e+s}return e},rf=function(t,e,i,r){if(t>0&&t<x.OP_PUSHDATA1)return{len:t,newPos:i,hasLength:!0};if(t===x.OP_PUSHDATA1){let c=i<r;return{len:c?e[i++]??0:0,newPos:i,hasLength:c}}if(t===x.OP_PUSHDATA2){let c=i+1<r;return{len:(e[i]??0)|(e[i+1]??0)<<8,newPos:Math.min(i+2,r),hasLength:c}}let s=i+3<r;return{len:((e[i]??0)|(e[i+1]??0)<<8|(e[i+2]??0)<<16|(e[i+3]??0)<<24)>>>0,newPos:Math.min(i+4,r),hasLength:s}},Dh=function(t){var o,c,u;let e=[],i=t.length,r=0,s=0;for(;r<i;){let f=t[r++]??0;if(f===x.OP_RETURN&&s===0){e.push({op:f,data:a(o=de,te,sf).call(o,t,r,i)});break}if(f===x.OP_IF||f===x.OP_NOTIF||f===x.OP_VERIF||f===x.OP_VERNOTIF?s++:f===x.OP_ENDIF&&s--,f>0&&f<=x.OP_PUSHDATA4){let{len:d,newPos:l,hasLength:p}=a(c=de,te,rf).call(c,f,t,r,i);r=l;let m=Math.min(r+d,i),g=!p||m-r!==d;e.push({data:a(u=de,te,sf).call(u,t,r,m),op:f,invalidLength:g}),r=m}else e.push({op:f})}return e},Hh=function(t,e){var o;let i=[],r=t.length,s=0;for(;s<r;){let c=s,u=t[s++]??0;if(u>0&&u<=x.OP_PUSHDATA4){let{len:f,newPos:d}=a(o=de,te,rf).call(o,u,t,s,r);s=d;let l=Math.min(s+f,r);if(u!==e)for(let p=c;p<l;p++)i.push(t[p]??0);s=l}else u!==e&&i.push(u)}return i},sf=function(t,e,i){let r=Math.max(i-e,0),s=Array.from({length:r},()=>0);for(let o=0;o<r;o++)s[o]=t[e+o]??0;return s},$h=function(t){let e=t.op,i="";if(t.data===void 0){let r=x[e];i=`${i} ${r}`}else i=`${i} ${nt(t.data)}`;return i},G(de,te);var me=de;var gw=new Uint8Array(0),of=Object.freeze(Array.from({length:32},()=>0));function mw(n,t,e){return e>0&&e<x.OP_PUSHDATA1?{length:e,nextPosition:t}:e===x.OP_PUSHDATA1?n.length-t<1?void 0:{length:n[t],nextPosition:t+1}:e===x.OP_PUSHDATA2?n.length-t<2?void 0:{length:n[t]|n[t+1]<<8,nextPosition:t+2}:e===x.OP_PUSHDATA4?n.length-t<4?void 0:{length:(n[t]|n[t+1]<<8|n[t+2]<<16|n[t+3]<<24)>>>0,nextPosition:t+4}:{length:0,nextPosition:t}}function bw(n){let t=n.toBinary(),e=[],i=0,r=0,s=0,o=c=>{for(let u=r;u<c;u++)e.push(t[u])};for(;i<t.length;){let c=i,u=t[i++],f=mw(t,i,u);if(f==null||(i=f.nextPosition,t.length-i<f.length))break;i+=f.length,u===x.OP_CODESEPARATOR&&(o(c),r=i,s++)}return o(i),{bytes:e,encodedLength:t.length-s}}function ww(n,t){if(n.allInputs!=null)return n.allInputs;let e=[...n.otherInputs];return e.splice(n.inputIndex,0,t),e}function Wh(n,t,e,i){return i===t?e:n[i]}function yw(n,t,e){let i=new fe;for(let r=0;r<n.length;r++){let s=Wh(n,t,e,r);if(s.sourceTXID==null){if(s.sourceTransaction==null)throw new Error("Missing sourceTransaction for input");i.write(s.sourceTransaction.hash())}else i.writeReverse(at(s.sourceTXID,"hex"));i.writeUInt32LE(s.sourceOutputIndex)}return zt(i.toUint8Array())}function xw(n,t,e){let i=new fe;for(let r=0;r<n.length;r++){let s=Wh(n,t,e,r);i.writeUInt32LE(s.sequence??4294967295)}return zt(i.toUint8Array())}function qh(n,t){n.writeUInt64LE(t.satoshis??0);let e=t.lockingScript?.toUint8Array()??gw;n.writeVarIntNum(e.length),n.write(e)}function Fh(n,t){let e=new fe;if(t==null)for(let i of n)qh(e,i);else{let i=n[t];if(i==null)throw new Error(`Output at index ${t} does not exist`);qh(e,i)}return zt(e.toUint8Array())}function Sw(n,t,e){if((n.scope&wt.SIGHASH_ANYONECANPAY)!==0)return[...of];if(n.cache?.hashPrevouts!=null)return n.cache.hashPrevouts;let i=yw(t,n.inputIndex,e);return n.cache!=null&&(n.cache.hashPrevouts=i),i}function Iw(n,t,e){let i=n.scope&31;if((n.scope&wt.SIGHASH_ANYONECANPAY)!==0||i===wt.SIGHASH_SINGLE||i===wt.SIGHASH_NONE)return[...of];if(n.cache?.hashSequence!=null)return n.cache.hashSequence;let r=xw(t,n.inputIndex,e);return n.cache!=null&&(n.cache.hashSequence=r),r}function vw(n){var r;let t=n.scope&31;if(t!==wt.SIGHASH_SINGLE&&t!==wt.SIGHASH_NONE){if(n.cache?.hashOutputsAll!=null)return n.cache.hashOutputsAll;let s=Fh(n.outputs);return n.cache!=null&&(n.cache.hashOutputsAll=s),s}if(t!==wt.SIGHASH_SINGLE||n.inputIndex>=n.outputs.length)return[...of];let e=n.cache?.hashOutputsSingle?.get(n.inputIndex);if(e!=null)return e;let i=Fh(n.outputs,n.inputIndex);return n.cache!=null&&((r=n.cache).hashOutputsSingle??(r.hashOutputsSingle=new Map),n.cache.hashOutputsSingle.set(n.inputIndex,i)),i}var Xt=class Xt extends ge{constructor(e,i,r){super(e,i);b(this,"scope");this.scope=r}static formatOTDA(e){let i=(e.scope&Xt.SIGHASH_ANYONECANPAY)===Xt.SIGHASH_ANYONECANPAY,r=(e.scope&31)===Xt.SIGHASH_SINGLE,s=(e.scope&31)===Xt.SIGHASH_NONE,o=(e.scope&31)===Xt.SIGHASH_ALL||!r&&!s,c=bw(e.subscript),u={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence,script:c.bytes,scriptLength:c.encodedLength},f=new fe;function d(g){f.writeVarIntNum(g.length);for(let w of g)f.writeReverse(at(w.sourceTXID,"hex")),f.writeUInt32LE(w.sourceOutputIndex),f.writeVarIntNum(w.scriptLength??w.script.length),f.write(w.script),f.writeUInt32LE(w.sequence)}function l(g){f.writeVarIntNum(g.length);for(let w of g)f.writeUInt64LE(w.satoshis),f.writeVarIntNum(w.script.length),f.write(w.script)}f.writeInt32LE(e.transactionVersion);let p=new me().toBinary();if(i)i&&d([u]);else{let g=e.allInputs==null?e.otherInputs.map(w=>({sourceTXID:w.sourceTXID??w.sourceTransaction?.id("hex")??"",sourceOutputIndex:w.sourceOutputIndex,sequence:r||s?0:w.sequence??4294967295,script:p})):e.allInputs.map((w,S)=>S===e.inputIndex?u:{sourceTXID:w.sourceTXID??w.sourceTransaction?.id("hex")??"",sourceOutputIndex:w.sourceOutputIndex,sequence:r||s?0:w.sequence??4294967295,script:p});e.allInputs==null&&g.splice(e.inputIndex,0,u),d(g)}if(o){let g=e.outputs.map(w=>({satoshis:w.satoshis??0,script:w.lockingScript.toBinary()}));l(g)}else if(r){let g=[];for(let S=0;S<e.inputIndex;S++)g.push({satoshis:-1,script:p});let w=e.outputs[e.inputIndex];w!==void 0&&g.push({satoshis:w.satoshis??0,script:w.lockingScript.toBinary()}),l(g)}else s&&l([]);return f.writeUInt32LE(e.lockTime),f.writeUInt32LE(e.scope>>>0),f.toUint8Array()}static formatBip143(e){let i={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence},r=ww(e,i),s=Sw(e,r,i),o=Iw(e,r,i),c=vw(e),u=new fe;u.writeInt32LE(e.transactionVersion),u.write(s),u.write(o),u.writeReverse(at(e.sourceTXID,"hex")),u.writeUInt32LE(e.sourceOutputIndex);let f=e.subscript.toUint8Array();u.writeVarIntNum(f.length),u.write(f),u.writeUInt64LE(e.sourceSatoshis);let d=i.sequence??4294967295;return u.writeUInt32LE(d),u.write(c),u.writeUInt32LE(e.lockTime),u.writeUInt32LE(e.scope>>>0),u.toUint8Array()}static format(e){return Array.from(this.formatBytes(e))}static formatBytes(e){let i=(e.scope&Xt.SIGHASH_FORKID)!==0,r=e.ignoreChronicle!==!0&&(e.scope&Xt.SIGHASH_CHRONICLE)!==0;return i&&e.sighashForkIdEnabled!==!1&&!r?Xt.formatBip143(e):e.sighashForkIdEnabled===!1||!i||r?Xt.formatOTDA(e):new Uint8Array(0)}static usesOtdaSingleBug(e){let i=(e.scope&Xt.SIGHASH_FORKID)!==0,r=e.ignoreChronicle!==!0&&(e.scope&Xt.SIGHASH_CHRONICLE)!==0;return(e.sighashForkIdEnabled===!1||!i||r)&&(e.scope&31)===Xt.SIGHASH_SINGLE&&e.inputIndex>=e.outputs.length}static fromChecksigFormat(e){if(e.length===0){let o=new T(1),c=new T(1),u=1;return new Xt(o,c,u)}let i=e.at(-1),r=e.slice(0,-1),s=ge.fromDER(r);return new Xt(s.r,s.s,i)}hasLowS(){return!(this.s.ltn(1)||this.s.gt(new T("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex")))}toChecksigFormat(){return[...this.toDER(),this.scope]}};b(Xt,"SIGHASH_ALL",1),b(Xt,"SIGHASH_NONE",2),b(Xt,"SIGHASH_SINGLE",3),b(Xt,"SIGHASH_CHRONICLE",32),b(Xt,"SIGHASH_FORKID",64),b(Xt,"SIGHASH_ANYONECANPAY",128);var wt=Xt;function af(n,t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${n} returned a non-byte result`);if(e!==void 0&&t.length!==e)throw new Error(`${n} returned ${t.length} bytes; expected ${e}`);return t}function Aw(){return globalThis}function cf(n){let t=Aw().__bsvSdkAsyncCryptoBackendV1;if(t!==void 0){if(!t.isReady()){t.preload().catch(()=>{});return}return t.supportsCrypto(n)?t:void 0}}var Le=class extends me{isLockingScript(){return!0}isUnlockingScript(){return!1}};var Ue=class extends me{isLockingScript(){return!1}isUnlockingScript(){return!0}};function Vh(n){return n==null?"null/undef":n.length===void 0?"INVALID_STACK_ITEM":nt(n)}var go=class extends Error{constructor(e){let i=e.stackState.map(Vh).join(", "),r=e.altStackState.map(Vh).join(", "),s=`Context: ${e.context}, PC: ${e.programCounter}`,o=`Stack: [${i}] (len: ${e.stackState.length}, mem: ${e.stackMem})`,c=`AltStack: [${r}] (len: ${e.altStackState.length}, mem: ${e.altStackMem})`,u=`IfStack: [${e.ifStackState.join(", ")}]`,f=`Script evaluation error: ${e.message}
1
+ "use strict";var bWalletXConnect=(()=>{var S1=Object.create;var Uo=Object.defineProperty;var I1=Object.getOwnPropertyDescriptor;var v1=Object.getOwnPropertyNames;var A1=Object.getPrototypeOf,E1=Object.prototype.hasOwnProperty;var Mp=n=>{throw TypeError(n)};var k1=(n,t,e)=>t in n?Uo(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var ml=(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 T1=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports),bl=(n,t)=>{for(var e in t)Uo(n,e,{get:t[e],enumerable:!0})},Up=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of v1(t))!E1.call(n,r)&&r!==e&&Uo(n,r,{get:()=>t[r],enumerable:!(i=I1(t,r))||i.enumerable});return n};var O1=(n,t,e)=>(e=n!=null?S1(A1(n)):{},Up(t||!n||!n.__esModule?Uo(e,"default",{value:n,enumerable:!0}):e,n)),P1=n=>Up(Uo({},"__esModule",{value:!0}),n);var w=(n,t,e)=>k1(n,typeof t!="symbol"?t+"":t,e),yl=(n,t,e)=>t.has(n)||Mp("Cannot "+e);var g=(n,t,e)=>(yl(n,t,"read from private field"),e?e.call(n):t.get(n)),z=(n,t,e)=>t.has(n)?Mp("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),A=(n,t,e,i)=>(yl(n,t,"write to private field"),i?i.call(n,e):t.set(n,e),e),a=(n,t,e)=>(yl(n,t,"access private method"),e);var Ic=(n,t,e,i)=>({set _(r){A(n,t,r,e)},get _(){return g(n,t,i)}});var Uw=T1((Lw,Mw)=>{"use strict";var Bw=(function(){var n=function(T,k){var E=236,_=17,B=T,F=e[k],C=null,I=0,q=null,W=[],K={},ot=function(N,D){I=B*4+17,C=(function(M){for(var H=new Array(M),U=0;U<M;U+=1){H[U]=new Array(M);for(var Z=0;Z<M;Z+=1)H[U][Z]=null}return H})(I),ut(0,0),ut(I-7,0),ut(0,I-7),nt(),j(),be(N,D),B>=7&&Ot(N),q==null&&(q=Oe(B,F,W)),Mt(q,D)},ut=function(N,D){for(var M=-1;M<=7;M+=1)if(!(N+M<=-1||I<=N+M))for(var H=-1;H<=7;H+=1)D+H<=-1||I<=D+H||(0<=M&&M<=6&&(H==0||H==6)||0<=H&&H<=6&&(M==0||M==6)||2<=M&&M<=4&&2<=H&&H<=4?C[N+M][D+H]=!0:C[N+M][D+H]=!1)},V=function(){for(var N=0,D=0,M=0;M<8;M+=1){ot(!0,M);var H=r.getLostPoint(K);(M==0||N>H)&&(N=H,D=M)}return D},j=function(){for(var N=8;N<I-8;N+=1)C[N][6]==null&&(C[N][6]=N%2==0);for(var D=8;D<I-8;D+=1)C[6][D]==null&&(C[6][D]=D%2==0)},nt=function(){for(var N=r.getPatternPosition(B),D=0;D<N.length;D+=1)for(var M=0;M<N.length;M+=1){var H=N[D],U=N[M];if(C[H][U]==null)for(var Z=-2;Z<=2;Z+=1)for(var rt=-2;rt<=2;rt+=1)Z==-2||Z==2||rt==-2||rt==2||Z==0&&rt==0?C[H+Z][U+rt]=!0:C[H+Z][U+rt]=!1}},Ot=function(N){for(var D=r.getBCHTypeNumber(B),M=0;M<18;M+=1){var H=!N&&(D>>M&1)==1;C[Math.floor(M/3)][M%3+I-8-3]=H}for(var M=0;M<18;M+=1){var H=!N&&(D>>M&1)==1;C[M%3+I-8-3][Math.floor(M/3)]=H}},be=function(N,D){for(var M=F<<3|D,H=r.getBCHTypeInfo(M),U=0;U<15;U+=1){var Z=!N&&(H>>U&1)==1;U<6?C[U][8]=Z:U<8?C[U+1][8]=Z:C[I-15+U][8]=Z}for(var U=0;U<15;U+=1){var Z=!N&&(H>>U&1)==1;U<8?C[8][I-U-1]=Z:U<9?C[8][15-U-1+1]=Z:C[8][15-U-1]=Z}C[I-8][8]=!N},Mt=function(N,D){for(var M=-1,H=I-1,U=7,Z=0,rt=r.getMaskFunction(D),tt=I-1;tt>0;tt-=2)for(tt==6&&(tt-=1);;){for(var bt=0;bt<2;bt+=1)if(C[H][tt-bt]==null){var Et=!1;Z<N.length&&(Et=(N[Z]>>>U&1)==1);var dt=rt(H,tt-bt);dt&&(Et=!Et),C[H][tt-bt]=Et,U-=1,U==-1&&(Z+=1,U=7)}if(H+=M,H<0||I<=H){H-=M,M=-M;break}}},ln=function(N,D){for(var M=0,H=0,U=0,Z=new Array(D.length),rt=new Array(D.length),tt=0;tt<D.length;tt+=1){var bt=D[tt].dataCount,Et=D[tt].totalCount-bt;H=Math.max(H,bt),U=Math.max(U,Et),Z[tt]=new Array(bt);for(var dt=0;dt<Z[tt].length;dt+=1)Z[tt][dt]=255&N.getBuffer()[dt+M];M+=bt;var $t=r.getErrorCorrectPolynomial(Et),Wt=o(Z[tt],$t.getLength()-1),ui=Wt.mod($t);rt[tt]=new Array($t.getLength()-1);for(var dt=0;dt<rt[tt].length;dt+=1){var vn=dt+ui.getLength()-rt[tt].length;rt[tt][dt]=vn>=0?ui.getAt(vn):0}}for(var Be=0,dt=0;dt<D.length;dt+=1)Be+=D[dt].totalCount;for(var oe=new Array(Be),It=0,dt=0;dt<H;dt+=1)for(var tt=0;tt<D.length;tt+=1)dt<Z[tt].length&&(oe[It]=Z[tt][dt],It+=1);for(var dt=0;dt<U;dt+=1)for(var tt=0;tt<D.length;tt+=1)dt<rt[tt].length&&(oe[It]=rt[tt][dt],It+=1);return oe},Oe=function(N,D,M){for(var H=c.getRSBlocks(N,D),U=u(),Z=0;Z<M.length;Z+=1){var rt=M[Z];U.put(rt.getMode(),4),U.put(rt.getLength(),r.getLengthInBits(rt.getMode(),N)),rt.write(U)}for(var tt=0,Z=0;Z<H.length;Z+=1)tt+=H[Z].dataCount;if(U.getLengthInBits()>tt*8)throw"code length overflow. ("+U.getLengthInBits()+">"+tt*8+")";for(U.getLengthInBits()+4<=tt*8&&U.put(0,4);U.getLengthInBits()%8!=0;)U.putBit(!1);for(;!(U.getLengthInBits()>=tt*8||(U.put(E,8),U.getLengthInBits()>=tt*8));)U.put(_,8);return ln(U,H)};K.addData=function(N,D){D=D||"Byte";var M=null;switch(D){case"Numeric":M=f(N);break;case"Alphanumeric":M=d(N);break;case"Byte":M=h(N);break;case"Kanji":M=l(N);break;default:throw"mode:"+D}W.push(M),q=null},K.isDark=function(N,D){if(N<0||I<=N||D<0||I<=D)throw N+","+D;return C[N][D]},K.getModuleCount=function(){return I},K.make=function(){if(B<1){for(var N=1;N<40;N++){for(var D=c.getRSBlocks(N,F),M=u(),H=0;H<W.length;H++){var U=W[H];M.put(U.getMode(),4),M.put(U.getLength(),r.getLengthInBits(U.getMode(),N)),U.write(M)}for(var Z=0,H=0;H<D.length;H++)Z+=D[H].dataCount;if(M.getLengthInBits()<=Z*8)break}B=N}ot(!1,V())},K.createTableTag=function(N,D){N=N||2,D=typeof D>"u"?N*4:D;var M="";M+='<table style="',M+=" border-width: 0px; border-style: none;",M+=" border-collapse: collapse;",M+=" padding: 0px; margin: "+D+"px;",M+='">',M+="<tbody>";for(var H=0;H<K.getModuleCount();H+=1){M+="<tr>";for(var U=0;U<K.getModuleCount();U+=1)M+='<td style="',M+=" border-width: 0px; border-style: none;",M+=" border-collapse: collapse;",M+=" padding: 0px; margin: 0px;",M+=" width: "+N+"px;",M+=" height: "+N+"px;",M+=" background-color: ",M+=K.isDark(H,U)?"#000000":"#ffffff",M+=";",M+='"/>';M+="</tr>"}return M+="</tbody>",M+="</table>",M},K.createSvgTag=function(N,D,M,H){var U={};typeof arguments[0]=="object"&&(U=arguments[0],N=U.cellSize,D=U.margin,M=U.alt,H=U.title),N=N||2,D=typeof D>"u"?N*4:D,M=typeof M=="string"?{text:M}:M||{},M.text=M.text||null,M.id=M.text?M.id||"qrcode-description":null,H=typeof H=="string"?{text:H}:H||{},H.text=H.text||null,H.id=H.text?H.id||"qrcode-title":null;var Z=K.getModuleCount()*N+D*2,rt,tt,bt,Et,dt="",$t;for($t="l"+N+",0 0,"+N+" -"+N+",0 0,-"+N+"z ",dt+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"',dt+=U.scalable?"":' width="'+Z+'px" height="'+Z+'px"',dt+=' viewBox="0 0 '+Z+" "+Z+'" ',dt+=' preserveAspectRatio="xMinYMin meet"',dt+=H.text||M.text?' role="img" aria-labelledby="'+Y([H.id,M.id].join(" ").trim())+'"':"",dt+=">",dt+=H.text?'<title id="'+Y(H.id)+'">'+Y(H.text)+"</title>":"",dt+=M.text?'<description id="'+Y(M.id)+'">'+Y(M.text)+"</description>":"",dt+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>',dt+='<path d="',bt=0;bt<K.getModuleCount();bt+=1)for(Et=bt*N+D,rt=0;rt<K.getModuleCount();rt+=1)K.isDark(bt,rt)&&(tt=rt*N+D,dt+="M"+tt+","+Et+$t);return dt+='" stroke="transparent" fill="black"/>',dt+="</svg>",dt},K.createDataURL=function(N,D){N=N||2,D=typeof D>"u"?N*4:D;var M=K.getModuleCount()*N+D*2,H=D,U=M-D;return L(M,M,function(Z,rt){if(H<=Z&&Z<U&&H<=rt&&rt<U){var tt=Math.floor((Z-H)/N),bt=Math.floor((rt-H)/N);return K.isDark(bt,tt)?0:1}else return 1})},K.createImgTag=function(N,D,M){N=N||2,D=typeof D>"u"?N*4:D;var H=K.getModuleCount()*N+D*2,U="";return U+="<img",U+=' src="',U+=K.createDataURL(N,D),U+='"',U+=' width="',U+=H,U+='"',U+=' height="',U+=H,U+='"',M&&(U+=' alt="',U+=Y(M),U+='"'),U+="/>",U};var Y=function(N){for(var D="",M=0;M<N.length;M+=1){var H=N.charAt(M);switch(H){case"<":D+="&lt;";break;case">":D+="&gt;";break;case"&":D+="&amp;";break;case'"':D+="&quot;";break;default:D+=H;break}}return D},pt=function(N){var D=1;N=typeof N>"u"?D*2:N;var M=K.getModuleCount()*D+N*2,H=N,U=M-N,Z,rt,tt,bt,Et,dt={"\u2588\u2588":"\u2588","\u2588 ":"\u2580"," \u2588":"\u2584"," ":" "},$t={"\u2588\u2588":"\u2580","\u2588 ":"\u2580"," \u2588":" "," ":" "},Wt="";for(Z=0;Z<M;Z+=2){for(tt=Math.floor((Z-H)/D),bt=Math.floor((Z+1-H)/D),rt=0;rt<M;rt+=1)Et="\u2588",H<=rt&&rt<U&&H<=Z&&Z<U&&K.isDark(tt,Math.floor((rt-H)/D))&&(Et=" "),H<=rt&&rt<U&&H<=Z+1&&Z+1<U&&K.isDark(bt,Math.floor((rt-H)/D))?Et+=" ":Et+="\u2588",Wt+=N<1&&Z+1>=U?$t[Et]:dt[Et];Wt+=`
2
+ `}return M%2&&N>0?Wt.substring(0,Wt.length-M-1)+Array(M+1).join("\u2580"):Wt.substring(0,Wt.length-1)};return K.createASCII=function(N,D){if(N=N||1,N<2)return pt(D);N-=1,D=typeof D>"u"?N*2:D;var M=K.getModuleCount()*N+D*2,H=D,U=M-D,Z,rt,tt,bt,Et=Array(N+1).join("\u2588\u2588"),dt=Array(N+1).join(" "),$t="",Wt="";for(Z=0;Z<M;Z+=1){for(tt=Math.floor((Z-H)/N),Wt="",rt=0;rt<M;rt+=1)bt=1,H<=rt&&rt<U&&H<=Z&&Z<U&&K.isDark(tt,Math.floor((rt-H)/N))&&(bt=0),Wt+=bt?Et:dt;for(tt=0;tt<N;tt+=1)$t+=Wt+`
3
+ `}return $t.substring(0,$t.length-1)},K.renderTo2dContext=function(N,D){D=D||2;for(var M=K.getModuleCount(),H=0;H<M;H++)for(var U=0;U<M;U++)N.fillStyle=K.isDark(H,U)?"black":"white",N.fillRect(H*D,U*D,D,D)},K};n.stringToBytesFuncs={default:function(T){for(var k=[],E=0;E<T.length;E+=1){var _=T.charCodeAt(E);k.push(_&255)}return k}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(T,k){var E=(function(){for(var B=y(T),F=function(){var j=B.read();if(j==-1)throw"eof";return j},C=0,I={};;){var q=B.read();if(q==-1)break;var W=F(),K=F(),ot=F(),ut=String.fromCharCode(q<<8|W),V=K<<8|ot;I[ut]=V,C+=1}if(C!=k)throw C+" != "+k;return I})(),_=63;return function(B){for(var F=[],C=0;C<B.length;C+=1){var I=B.charCodeAt(C);if(I<128)F.push(I);else{var q=E[B.charAt(C)];typeof q=="number"?(q&255)==q?F.push(q):(F.push(q>>>8),F.push(q&255)):F.push(_)}}return F}};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 T=[[],[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]],k=1335,E=7973,_=21522,B={},F=function(C){for(var I=0;C!=0;)I+=1,C>>>=1;return I};return B.getBCHTypeInfo=function(C){for(var I=C<<10;F(I)-F(k)>=0;)I^=k<<F(I)-F(k);return(C<<10|I)^_},B.getBCHTypeNumber=function(C){for(var I=C<<12;F(I)-F(E)>=0;)I^=E<<F(I)-F(E);return C<<12|I},B.getPatternPosition=function(C){return T[C-1]},B.getMaskFunction=function(C){switch(C){case i.PATTERN000:return function(I,q){return(I+q)%2==0};case i.PATTERN001:return function(I,q){return I%2==0};case i.PATTERN010:return function(I,q){return q%3==0};case i.PATTERN011:return function(I,q){return(I+q)%3==0};case i.PATTERN100:return function(I,q){return(Math.floor(I/2)+Math.floor(q/3))%2==0};case i.PATTERN101:return function(I,q){return I*q%2+I*q%3==0};case i.PATTERN110:return function(I,q){return(I*q%2+I*q%3)%2==0};case i.PATTERN111:return function(I,q){return(I*q%3+(I+q)%2)%2==0};default:throw"bad maskPattern:"+C}},B.getErrorCorrectPolynomial=function(C){for(var I=o([1],0),q=0;q<C;q+=1)I=I.multiply(o([1,s.gexp(q)],0));return I},B.getLengthInBits=function(C,I){if(1<=I&&I<10)switch(C){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:"+C}else if(I<27)switch(C){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:"+C}else if(I<41)switch(C){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:"+C}else throw"type:"+I},B.getLostPoint=function(C){for(var I=C.getModuleCount(),q=0,W=0;W<I;W+=1)for(var K=0;K<I;K+=1){for(var ot=0,ut=C.isDark(W,K),V=-1;V<=1;V+=1)if(!(W+V<0||I<=W+V))for(var j=-1;j<=1;j+=1)K+j<0||I<=K+j||V==0&&j==0||ut==C.isDark(W+V,K+j)&&(ot+=1);ot>5&&(q+=3+ot-5)}for(var W=0;W<I-1;W+=1)for(var K=0;K<I-1;K+=1){var nt=0;C.isDark(W,K)&&(nt+=1),C.isDark(W+1,K)&&(nt+=1),C.isDark(W,K+1)&&(nt+=1),C.isDark(W+1,K+1)&&(nt+=1),(nt==0||nt==4)&&(q+=3)}for(var W=0;W<I;W+=1)for(var K=0;K<I-6;K+=1)C.isDark(W,K)&&!C.isDark(W,K+1)&&C.isDark(W,K+2)&&C.isDark(W,K+3)&&C.isDark(W,K+4)&&!C.isDark(W,K+5)&&C.isDark(W,K+6)&&(q+=40);for(var K=0;K<I;K+=1)for(var W=0;W<I-6;W+=1)C.isDark(W,K)&&!C.isDark(W+1,K)&&C.isDark(W+2,K)&&C.isDark(W+3,K)&&C.isDark(W+4,K)&&!C.isDark(W+5,K)&&C.isDark(W+6,K)&&(q+=40);for(var Ot=0,K=0;K<I;K+=1)for(var W=0;W<I;W+=1)C.isDark(W,K)&&(Ot+=1);var be=Math.abs(100*Ot/I/I-50)/5;return q+=be*10,q},B})(),s=(function(){for(var T=new Array(256),k=new Array(256),E=0;E<8;E+=1)T[E]=1<<E;for(var E=8;E<256;E+=1)T[E]=T[E-4]^T[E-5]^T[E-6]^T[E-8];for(var E=0;E<255;E+=1)k[T[E]]=E;var _={};return _.glog=function(B){if(B<1)throw"glog("+B+")";return k[B]},_.gexp=function(B){for(;B<0;)B+=255;for(;B>=256;)B-=255;return T[B]},_})();function o(T,k){if(typeof T.length>"u")throw T.length+"/"+k;var E=(function(){for(var B=0;B<T.length&&T[B]==0;)B+=1;for(var F=new Array(T.length-B+k),C=0;C<T.length-B;C+=1)F[C]=T[C+B];return F})(),_={};return _.getAt=function(B){return E[B]},_.getLength=function(){return E.length},_.multiply=function(B){for(var F=new Array(_.getLength()+B.getLength()-1),C=0;C<_.getLength();C+=1)for(var I=0;I<B.getLength();I+=1)F[C+I]^=s.gexp(s.glog(_.getAt(C))+s.glog(B.getAt(I)));return o(F,0)},_.mod=function(B){if(_.getLength()-B.getLength()<0)return _;for(var F=s.glog(_.getAt(0))-s.glog(B.getAt(0)),C=new Array(_.getLength()),I=0;I<_.getLength();I+=1)C[I]=_.getAt(I);for(var I=0;I<B.getLength();I+=1)C[I]^=s.gexp(s.glog(B.getAt(I))+F);return o(C,0).mod(B)},_}var c=(function(){var T=[[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]],k=function(B,F){var C={};return C.totalCount=B,C.dataCount=F,C},E={},_=function(B,F){switch(F){case e.L:return T[(B-1)*4+0];case e.M:return T[(B-1)*4+1];case e.Q:return T[(B-1)*4+2];case e.H:return T[(B-1)*4+3];default:return}};return E.getRSBlocks=function(B,F){var C=_(B,F);if(typeof C>"u")throw"bad rs block @ typeNumber:"+B+"/errorCorrectionLevel:"+F;for(var I=C.length/3,q=[],W=0;W<I;W+=1)for(var K=C[W*3+0],ot=C[W*3+1],ut=C[W*3+2],V=0;V<K;V+=1)q.push(k(ot,ut));return q},E})(),u=function(){var T=[],k=0,E={};return E.getBuffer=function(){return T},E.getAt=function(_){var B=Math.floor(_/8);return(T[B]>>>7-_%8&1)==1},E.put=function(_,B){for(var F=0;F<B;F+=1)E.putBit((_>>>B-F-1&1)==1)},E.getLengthInBits=function(){return k},E.putBit=function(_){var B=Math.floor(k/8);T.length<=B&&T.push(0),_&&(T[B]|=128>>>k%8),k+=1},E},f=function(T){var k=t.MODE_NUMBER,E=T,_={};_.getMode=function(){return k},_.getLength=function(C){return E.length},_.write=function(C){for(var I=E,q=0;q+2<I.length;)C.put(B(I.substring(q,q+3)),10),q+=3;q<I.length&&(I.length-q==1?C.put(B(I.substring(q,q+1)),4):I.length-q==2&&C.put(B(I.substring(q,q+2)),7))};var B=function(C){for(var I=0,q=0;q<C.length;q+=1)I=I*10+F(C.charAt(q));return I},F=function(C){if("0"<=C&&C<="9")return C.charCodeAt(0)-48;throw"illegal char :"+C};return _},d=function(T){var k=t.MODE_ALPHA_NUM,E=T,_={};_.getMode=function(){return k},_.getLength=function(F){return E.length},_.write=function(F){for(var C=E,I=0;I+1<C.length;)F.put(B(C.charAt(I))*45+B(C.charAt(I+1)),11),I+=2;I<C.length&&F.put(B(C.charAt(I)),6)};var B=function(F){if("0"<=F&&F<="9")return F.charCodeAt(0)-48;if("A"<=F&&F<="Z")return F.charCodeAt(0)-65+10;switch(F){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 :"+F}};return _},h=function(T){var k=t.MODE_8BIT_BYTE,E=T,_=n.stringToBytes(T),B={};return B.getMode=function(){return k},B.getLength=function(F){return _.length},B.write=function(F){for(var C=0;C<_.length;C+=1)F.put(_[C],8)},B},l=function(T){var k=t.MODE_KANJI,E=T,_=n.stringToBytesFuncs.SJIS;if(!_)throw"sjis not supported.";(function(C,I){var q=_(C);if(q.length!=2||(q[0]<<8|q[1])!=I)throw"sjis not supported."})("\u53CB",38726);var B=_(T),F={};return F.getMode=function(){return k},F.getLength=function(C){return~~(B.length/2)},F.write=function(C){for(var I=B,q=0;q+1<I.length;){var W=(255&I[q])<<8|255&I[q+1];if(33088<=W&&W<=40956)W-=33088;else if(57408<=W&&W<=60351)W-=49472;else throw"illegal char at "+(q+1)+"/"+W;W=(W>>>8&255)*192+(W&255),C.put(W,13),q+=2}if(q<I.length)throw"illegal char at "+(q+1)},F},m=function(){var T=[],k={};return k.writeByte=function(E){T.push(E&255)},k.writeShort=function(E){k.writeByte(E),k.writeByte(E>>>8)},k.writeBytes=function(E,_,B){_=_||0,B=B||E.length;for(var F=0;F<B;F+=1)k.writeByte(E[F+_])},k.writeString=function(E){for(var _=0;_<E.length;_+=1)k.writeByte(E.charCodeAt(_))},k.toByteArray=function(){return T},k.toString=function(){var E="";E+="[";for(var _=0;_<T.length;_+=1)_>0&&(E+=","),E+=T[_];return E+="]",E},k},b=function(){var T=0,k=0,E=0,_="",B={},F=function(I){_+=String.fromCharCode(C(I&63))},C=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 B.writeByte=function(I){for(T=T<<8|I&255,k+=8,E+=1;k>=6;)F(T>>>k-6),k-=6},B.flush=function(){if(k>0&&(F(T<<6-k),T=0,k=0),E%3!=0)for(var I=3-E%3,q=0;q<I;q+=1)_+="="},B.toString=function(){return _},B},y=function(T){var k=T,E=0,_=0,B=0,F={};F.read=function(){for(;B<8;){if(E>=k.length){if(B==0)return-1;throw"unexpected end of file./"+B}var I=k.charAt(E);if(E+=1,I=="=")return B=0,-1;if(I.match(/^\s$/))continue;_=_<<6|C(I.charCodeAt(0)),B+=6}var q=_>>>B-8&255;return B-=8,q};var C=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 F},S=function(T,k){var E=T,_=k,B=new Array(T*k),F={};F.setPixel=function(W,K,ot){B[K*E+W]=ot},F.write=function(W){W.writeString("GIF87a"),W.writeShort(E),W.writeShort(_),W.writeByte(128),W.writeByte(0),W.writeByte(0),W.writeByte(0),W.writeByte(0),W.writeByte(0),W.writeByte(255),W.writeByte(255),W.writeByte(255),W.writeString(","),W.writeShort(0),W.writeShort(0),W.writeShort(E),W.writeShort(_),W.writeByte(0);var K=2,ot=I(K);W.writeByte(K);for(var ut=0;ot.length-ut>255;)W.writeByte(255),W.writeBytes(ot,ut,255),ut+=255;W.writeByte(ot.length-ut),W.writeBytes(ot,ut,ot.length-ut),W.writeByte(0),W.writeString(";")};var C=function(W){var K=W,ot=0,ut=0,V={};return V.write=function(j,nt){if(j>>>nt)throw"length over";for(;ot+nt>=8;)K.writeByte(255&(j<<ot|ut)),nt-=8-ot,j>>>=8-ot,ut=0,ot=0;ut=j<<ot|ut,ot=ot+nt},V.flush=function(){ot>0&&K.writeByte(ut)},V},I=function(W){for(var K=1<<W,ot=(1<<W)+1,ut=W+1,V=q(),j=0;j<K;j+=1)V.add(String.fromCharCode(j));V.add(String.fromCharCode(K)),V.add(String.fromCharCode(ot));var nt=m(),Ot=C(nt);Ot.write(K,ut);var be=0,Mt=String.fromCharCode(B[be]);for(be+=1;be<B.length;){var ln=String.fromCharCode(B[be]);be+=1,V.contains(Mt+ln)?Mt=Mt+ln:(Ot.write(V.indexOf(Mt),ut),V.size()<4095&&(V.size()==1<<ut&&(ut+=1),V.add(Mt+ln)),Mt=ln)}return Ot.write(V.indexOf(Mt),ut),Ot.write(ot,ut),Ot.flush(),nt.toByteArray()},q=function(){var W={},K=0,ot={};return ot.add=function(ut){if(ot.contains(ut))throw"dup key:"+ut;W[ut]=K,K+=1},ot.size=function(){return K},ot.indexOf=function(ut){return W[ut]},ot.contains=function(ut){return typeof W[ut]<"u"},ot};return F},L=function(T,k,E){for(var _=S(T,k),B=0;B<k;B+=1)for(var F=0;F<T;F+=1)_.setPixel(F,B,E(F,B));var C=m();_.write(C);for(var I=b(),q=C.toByteArray(),W=0;W<q.length;W+=1)I.writeByte(q[W]);return I.flush(),"data:image/gif;base64,"+I};return n})();(function(){Bw.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 Lw=="object"&&(Mw.exports=n())})(function(){return Bw})});var hS={};bl(hS,{ACCESS_ERROR_STATUS:()=>qw,ACCESS_PROTOCOL:()=>Zf,ACCESS_VERSION:()=>Ww,AccessError:()=>Ct,BAVATAR_URL:()=>zh,BRC29_PROTOCOL:()=>Ip,BUTTON_TAG:()=>bp,BWALLETX_RDNS:()=>Qa,BWALLETX_TYPE:()=>Ci,CONNECTED_KEY:()=>fl,CONTINUE_OTHER_LABEL:()=>hp,DEFAULT_DISCOVER_MS:()=>xr,DESKTOP_OPTION_ID:()=>Ir,GET_URL:()=>dc,IDENTITY_HINT_KEY:()=>rc,KNOWN_KEYS_KEY:()=>Wf,LOGIN_PROTOCOL:()=>$h,LOGO_URL:()=>Sp,MENU_CSS:()=>rl,METANET_ANSWER_MS:()=>Gh,METANET_JSON_API:()=>kw,METANET_LABEL:()=>ac,METANET_NOTE:()=>Po,METANET_OPTION_ID:()=>Ar,METANET_REMEMBERED_NOTE:()=>cc,METANET_SILENT_MS:()=>Yh,METANET_TYPE:()=>Sn,METANET_UNREACHABLE:()=>jh,MetanetUnreachableError:()=>Oo,NOT_YOU_LABEL:()=>$f,NO_COINS_TEXT:()=>vp,PAYMAIL_LOOKUP_URL:()=>Kh,PENDING_LABEL:()=>yc,PENDING_LABEL_OTHER:()=>wc,PENDING_NOTE:()=>sl,PROTOCOL_MEDIA:()=>rp,PaymentError:()=>me,RDNS_EXTENSION:()=>Ln,RDNS_MOBILE:()=>Mn,SIGNIN_CSS:()=>Mo,SIGNIN_TAG:()=>lp,SWITCH_NOTE:()=>ol,WALLET_CHOICE_KEY:()=>fc,WALLET_THEME_META:()=>pl,WEB_WALLET_URL:()=>hc,accessErrorMessage:()=>zw,accountLabel:()=>sc,amountInSats:()=>Op,attachRemembered:()=>Cw,attemptFor:()=>ai,autoChoice:()=>Lf,avatarUrlFor:()=>Mf,bindPrewarm:()=>Of,brc100Option:()=>Ni,buildAuthorizeUrl:()=>pp,buyToken:()=>h1,canonicalJson:()=>pc,challengeWantsIdentityKey:()=>Wh,chooseWallet:()=>Yf,chooserOrder:()=>zf,claimSilentAttempt:()=>tp,clearPairing:()=>_f,connectBwalletX:()=>vs,connectMetanetDesktop:()=>Jh,cwiIsAnnounced:()=>Vh,decideWallet:()=>Xf,declareWalletTheme:()=>p1,defineBwalletxButton:()=>hl,defineBwalletxSignin:()=>al,desktopOption:()=>Iw,discoverBwalletX:()=>oi,discoverWallets:()=>ks,dropLegacyConnectedKey:()=>dl,findBwalletX:()=>uw,forgetWalletChoice:()=>Rs,getUrlFor:()=>wp,handcashAdapter:()=>Sw,handleLabel:()=>xp,hasBwalletX:()=>Ro,inAnyFrame:()=>Zh,inOrder:()=>ec,isExplicitPick:()=>_o,isFramed:()=>tc,isIdentityKeyHex:()=>Ep,isInsufficientFunds:()=>Ap,isKnownIdentityKey:()=>uc,isLocalDesktop:()=>ic,isLocalDesktopType:()=>Gf,isPaymail:()=>kp,isPresentBwalletX:()=>Bi,isRememberable:()=>jf,isTouchDevice:()=>Os,isUserRejection:()=>oc,knownIdentityKeys:()=>Ff,lookupPaymail:()=>Uf,markSvg:()=>Tr,matchRemembered:()=>Bo,metanetOffered:()=>In,metanetOption:()=>_i,migrateConnectedKey:()=>yp,needsBwalletX:()=>Co,otherDetected:()=>No,outcomeOf:()=>Er,pairBwalletX:()=>ko,pairingModal:()=>Lo,pairingOption:()=>qh,pay:()=>Rp,pickWallet:()=>$w,planAutoConnect:()=>_w,prewarmBwalletX:()=>_h,protocolMediaUrl:()=>Vw,proveHoldings:()=>ap,qrSvg:()=>ip,rememberIdentity:()=>Ts,rememberKnownIdentityKey:()=>Ps,rememberWalletChoice:()=>ci,rememberedIdentity:()=>vr,rememberedWalletChoice:()=>Li,renderButton:()=>a1,reportAttempt:()=>kr,requestAccess:()=>Qf,resetSilentAttempt:()=>Pw,resolvePaymailP2P:()=>Pp,restorePairing:()=>To,runConnect:()=>jw,runSilentMetanet:()=>tl,shortKey:()=>Xh,signInAndVerify:()=>Es,signInErrorText:()=>Df,signInWithBwalletX:()=>Cf,signinText:()=>dp,silentAttemptUsed:()=>qf,stateFor:()=>ll,substrateOf:()=>Un,tapGoesElsewhere:()=>lc,throwIfAccessError:()=>op,tip:()=>d1,toAccessError:()=>Jf,trySilentMetanet:()=>Vf,waitIfLocked:()=>As,walletTypeOf:()=>Dn,warnIfNoLogout:()=>Kf});var wl=globalThis.Buffer,R1=wl!=null&&typeof wl.from=="function",Wo=new Int8Array(256).fill(-1);for(let n=0;n<10;n++)Wo[48+n]=n;for(let n=0;n<6;n++)Wo[65+n]=10+n,Wo[97+n]=10+n;var Fo,qo,Ac,Ec,Wi,kc,Vo,J,at,Pt,R,Dp,Hp,$p,Wp,Fp,qp,xl,We,$n,ct,Vp,Do,Ho,Kp,zp,Nr,Xp,jp,Gp,Vt,ye,$o,vc,Rr,Sl,Yp,Il,Q=class Q{constructor(t=0,e=10,i="be"){z(this,R);z(this,J,0n);z(this,at,0);z(this,Pt,1);w(this,"red",null);if(t??(t=0),typeof t=="bigint"){a(this,R,We).call(this,t<0n?-t:t,t<0n?1:0),this.normSign();return}let r=e==="le"||e==="be",s=r?10:e,o=r?e:i;if(typeof t=="number"){a(this,R,Vp).call(this,t,o);return}if(Array.isArray(t)){a(this,R,Do).call(this,t,o);return}if(typeof t=="string"){a(this,R,Hp).call(this,t,s,o);return}t!==0?a(this,R,ct).call(this,!1,"Unsupported input type for BigNumber constructor"):a(this,R,We).call(this,0n,0)}get negative(){return g(this,at)}set negative(t){a(this,R,ct).call(this,t===0||t===1,"Negative property must be 0 or 1");let e=t===1?1:0;g(this,J)===0n?A(this,at,0):A(this,at,e)}get words(){if(!Number.isSafeInteger(g(this,Pt))||g(this,Pt)<1||g(this,Pt)>g(Q,Vo))throw new Error("BigNumber word length exceeds the supported limit");let t=g(this,R,Dp);if(g(this,Pt)<=t.length)return t;let e=Array.from({length:g(this,Pt)}).fill(0);for(let i=0;i<t.length;i++)e[i]=t[i];return e}set words(t){let e=g(this,at),i=0n,r=t.length>0?t.length:1;for(let s=r-1;s>=0;s--){let o=t[s]??0;i=i<<g(Q,Fo)|BigInt(o&Number(g(Q,qo)))}A(this,J,i),A(this,at,e),A(this,Pt,r),this.normSign()}get length(){return Math.max(1,g(this,Pt))}static isBN(t){return t instanceof Q?!0:t!==null&&typeof t=="object"&&t.constructor?.wordSize===Q.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){A(t,J,g(this,J)),A(t,at,g(this,at)),A(t,Pt,g(this,Pt)),t.red=this.red}static move(t,e){A(t,J,g(e,J)),A(t,at,g(e,at)),A(t,Pt,g(e,Pt)),t.red=e.red}clone(){let t=new Q(0n);return this.copy(t),t}expand(t){return a(this,R,ct).call(this,Number.isSafeInteger(t)&&t>=0&&t<=g(Q,Vo),"Expand size must be a non-negative safe integer within the supported word limit"),A(this,Pt,Math.max(g(this,Pt),t,1)),this}strip(){return a(this,R,$n).call(this),this.normSign()}normSign(){return g(this,J)===0n&&A(this,at,0),this}inspect(){return(this.red===null?"<BN: ":"<BN-R: ")+this.toString(16)+">"}toString(t=10,e=1){if(t===16||t==="hex")return a(this,R,Kp).call(this,e);if(typeof t!="number"||t<2||t>36||t%1!==0)throw new Error("Base should be an integer between 2 and 36");return a(this,R,zp).call(this,t,e)}toNumber(){let t=a(this,R,Vt).call(this);if(t>g(Q,Ac)||t<g(Q,Ec))throw new Error("Number can only safely store up to 53 bits");return Number(t)}toBigInt(){return a(this,R,Vt).call(this)}toJSON(){let t=a(this,R,Ho).call(this);return(this.isNeg()?"-":"")+t}toArray(t="be",e){this.strip();let i=this.byteLength(),r=e??Math.max(1,i);a(this,R,ct).call(this,i<=r,"byte array longer than desired length"),a(this,R,ct).call(this,r>0,"Requested array length <= 0");let s=Array.from({length:r}).fill(0);return g(this,J)===0n&&r>0?s:g(this,J)===0n&&r===0?[]:(a(this,R,Gp).call(this,s,t==="le"),s)}bitLength(){return g(this,J)===0n?0:g(this,J).toString(2).length}static toBitArray(t){let e=t.bitLength();if(e===0)return[];let i=Array.from({length:e}),r=g(t,J);for(let s=0;s<e;s++)i[s]=(r>>BigInt(s)&1n)===0n?0:1;return i}toBitArray(){return Q.toBitArray(this)}zeroBits(){if(g(this,J)===0n)return 0;let t=0,e=g(this,J);for(;(e&1n)===0n&&e!==0n;)t++,e>>=1n;return t}byteLength(){return g(this,J)===0n?0:Math.ceil(this.bitLength()/8)}toTwos(t){var o;a(this,R,ct).call(this,t>=0);let e=BigInt(t),i=a(this,R,Vt).call(this);g(this,at)===1&&g(this,J)!==0n&&(i=(1n<<e)+i);let r=(1n<<e)-1n;i&=r;let s=new Q(0n);return a(o=s,R,We).call(o,i,0),s}fromTwos(t){var r;a(this,R,ct).call(this,t>=0);let e=BigInt(t),i=g(this,J);if(t>0&&(i>>e-1n&1n)!==0n&&g(this,at)===0){let s=i-(1n<<e),o=new Q(0n);return a(r=o,R,ye).call(r,s),o}return this.clone()}isNeg(){return g(this,at)===1&&g(this,J)!==0n}neg(){return this.clone().ineg()}ineg(){return g(this,J)!==0n&&A(this,at,g(this,at)===1?0:1),this}iuor(t){return a(this,R,$o).call(this,t,(e,i)=>e|i)}iuand(t){return a(this,R,$o).call(this,t,(e,i)=>e&i)}iuxor(t){return a(this,R,$o).call(this,t,(e,i)=>e^i,!0)}ior(t){return a(this,R,vc).call(this,t,(e,i)=>e|i)}iand(t){return a(this,R,vc).call(this,t,(e,i)=>e&i)}ixor(t){return a(this,R,vc).call(this,t,(e,i)=>e^i,!0)}or(t){return a(this,R,ct).call(this,g(this,at)===0&&g(t,at)===0),a(this,R,Rr).call(this,t,"iuor")}uor(t){return a(this,R,Rr).call(this,t,"iuor")}and(t){return a(this,R,ct).call(this,g(this,at)===0&&g(t,at)===0),a(this,R,Rr).call(this,t,"iuand")}uand(t){return a(this,R,Rr).call(this,t,"iuand")}xor(t){return a(this,R,ct).call(this,g(this,at)===0&&g(t,at)===0),a(this,R,Rr).call(this,t,"iuxor")}uxor(t){return a(this,R,Rr).call(this,t,"iuxor")}inotn(t){a(this,R,ct).call(this,typeof t=="number"&&t>=0);let i=(1n<<BigInt(t))-1n;A(this,J,~g(this,J)&i);let r=t===0?1:Math.ceil(t/Q.wordSize);return A(this,Pt,Math.max(1,r)),this.strip(),A(this,Pt,Math.max(g(this,Pt),Math.max(1,r))),this}notn(t){return this.clone().inotn(t)}setn(t,e){a(this,R,ct).call(this,typeof t=="number"&&t>=0);let i=BigInt(t);e===1||e===!0?A(this,J,g(this,J)|1n<<i):A(this,J,g(this,J)&~(1n<<i));let r=Math.floor(t/Q.wordSize)+1;return A(this,Pt,Math.max(g(this,Pt),r)),a(this,R,$n).call(this),this.strip()}iadd(t){var e;return a(this,R,ye).call(this,a(this,R,Vt).call(this)+a(e=t,R,Vt).call(e)),this}add(t){var i,r;let e=new Q(0n);return a(r=e,R,ye).call(r,a(this,R,Vt).call(this)+a(i=t,R,Vt).call(i)),e}isub(t){var e;return a(this,R,ye).call(this,a(this,R,Vt).call(this)-a(e=t,R,Vt).call(e)),this}sub(t){var i,r;let e=new Q(0n);return a(r=e,R,ye).call(r,a(this,R,Vt).call(this)-a(i=t,R,Vt).call(i)),e}mul(t){let e=new Q(0n);return A(e,J,g(this,J)*g(t,J)),A(e,at,g(e,J)===0n?0:g(this,at)^g(t,at)),A(e,Pt,this.length+t.length),e.red=null,e.normSign()}imul(t){return A(this,J,g(this,J)*g(t,J)),A(this,at,g(this,J)===0n?0:g(this,at)^g(t,at)),A(this,Pt,this.length+t.length),this.red=null,this.normSign()}imuln(t){return a(this,R,ct).call(this,typeof t=="number","Assertion failed"),a(this,R,ct).call(this,Math.abs(t)<=g(Q,Wi),"Assertion failed"),a(this,R,ye).call(this,a(this,R,Vt).call(this)*BigInt(t)),this}muln(t){return this.clone().imuln(t)}sqr(){let t=new Q(0n);return A(t,J,g(this,J)*g(this,J)),A(t,at,0),A(t,Pt,this.length*2),t.red=null,t}isqr(){return A(this,J,g(this,J)*g(this,J)),A(this,at,0),A(this,Pt,this.length*2),this.red=null,this}pow(t){if(a(this,R,ct).call(this,g(t,at)===0,"Exponent for pow must be non-negative"),t.isZero())return new Q(1n);let e=new Q(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=Q,Nr,Sl).call(i,t,"Shift bits");return e===0n?this:(A(this,J,g(this,J)<<e),a(this,R,$n).call(this),this.strip())}ishln(t){return a(this,R,ct).call(this,g(this,at)===0,"ishln requires positive number"),this.iushln(t)}iushrn(t,e,i){var s,o,c;let r=a(s=Q,Nr,Sl).call(s,t,"Shift bits");if(r===0n)return i!=null&&a(o=i,R,We).call(o,0n,0),this;if(i!=null){let u=(1n<<r)-1n,f=g(this,J)&u;a(c=i,R,We).call(c,f,0)}return A(this,J,g(this,J)>>r),a(this,R,$n).call(this),this.strip()}ishrn(t,e,i){return a(this,R,ct).call(this,g(this,at)===0,"ishrn requires positive number"),this.iushrn(t,e,i)}shln(t){return this.clone().ishln(t)}ushln(t){return this.clone().iushln(t)}shrn(t){return this.clone().ishrn(t)}ushrn(t){return this.clone().iushrn(t)}testn(t){return a(this,R,ct).call(this,typeof t=="number"&&t>=0),(g(this,J)>>BigInt(t)&1n)!==0n}imaskn(t){a(this,R,ct).call(this,typeof t=="number"&&t>=0),a(this,R,ct).call(this,g(this,at)===0,"imaskn works only with positive numbers");let e=BigInt(t),i=e===0n?0n:(1n<<e)-1n;A(this,J,g(this,J)&i);let r=t===0?1:Math.max(1,Math.ceil(t/Q.wordSize));return A(this,Pt,r),a(this,R,$n).call(this),A(this,Pt,Math.max(g(this,Pt),r)),this.strip()}maskn(t){return this.clone().imaskn(t)}iaddn(t){return a(this,R,ct).call(this,typeof t=="number"),a(this,R,ct).call(this,Math.abs(t)<=g(Q,Wi),"num is too large"),a(this,R,ye).call(this,a(this,R,Vt).call(this)+BigInt(t)),this}_iaddn(t){return this.iaddn(t)}isubn(t){return a(this,R,ct).call(this,typeof t=="number"),a(this,R,ct).call(this,Math.abs(t)<=g(Q,Wi),"Assertion failed"),a(this,R,ye).call(this,a(this,R,Vt).call(this)-BigInt(t)),this}addn(t){return this.clone().iaddn(t)}subn(t){return this.clone().isubn(t)}iabs(){return A(this,at,0),this}abs(){return this.clone().iabs()}divmod(t,e,i){var u;if(a(this,R,ct).call(this,!t.isZero(),"Division by zero"),this.isZero()){let f=new Q(0n);return{div:e==="mod"?null:f,mod:e==="div"?null:f}}let r=a(this,R,Vt).call(this),s=a(u=t,R,Vt).call(u),o=e!=="mod"?r/s:null,c=a(this,R,Yp).call(this,r,s,e,i);return{div:a(this,R,Il).call(this,o),mod:a(this,R,Il).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,h;a(this,R,ct).call(this,!t.isZero());let e=a(this,R,Vt).call(this),i=a(f=t,R,Vt).call(f),r=e/i,s=e%i;if(s===0n){let l=new Q(0n);return a(d=l,R,ye).call(d,r),l}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 Q(0n);return a(h=u,R,ye).call(h,r),u}modrn(t){a(this,R,ct).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=g(this,J)%e;return t<0?Number(-i):Number(i)}idivn(t){return a(this,R,ct).call(this,t!==0),a(this,R,ct).call(this,Math.abs(t)<=g(Q,Wi),"num is too large"),a(this,R,ye).call(this,a(this,R,Vt).call(this)/BigInt(t)),this}divn(t){return this.clone().idivn(t)}egcd(t){var h,l,m;a(this,R,ct).call(this,t.negative===0,"p must not be negative"),a(this,R,ct).call(this,!t.isZero(),"p must not be zero");let e=a(this,R,Vt).call(this),i=g(t,J),r=1n,s=0n,o=0n,c=1n;for(;i!==0n;){let b=e/i,y=i;i=e%i,e=y,y=s,s=r-b*s,r=y,y=c,c=o-b*c,o=y}let u=new Q(0n);a(h=u,R,ye).call(h,r);let f=new Q(0n);a(l=f,R,ye).call(l,o);let d=new Q(0n);return a(m=d,R,We).call(m,e<0n?-e:e,0),{a:u,b:f,gcd:d}}gcd(t){var s,o,c;let e=g(this,J),i=g(t,J);if(e===0n){let u=new Q(0n);return a(s=u,R,ye).call(s,i),u.iabs()}if(i===0n){let u=new Q(0n);return a(o=u,R,ye).call(o,e),u.iabs()}for(;i!==0n;){let u=e%i;e=i,i=u}let r=new Q(0n);return a(c=r,R,We).call(c,e,0),r}invm(t){a(this,R,ct).call(this,!t.isZero()&&g(t,at)===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 g(this,J)%2n===0n}isOdd(){return g(this,J)%2n===1n}andln(t){return a(this,R,ct).call(this,t>=0),Number(g(this,J)&BigInt(t))}bincn(t){a(this,R,ct).call(this,typeof t=="number"&&t>=0);let e=1n<<BigInt(t);return a(this,R,ye).call(this,a(this,R,Vt).call(this)+e),this}isZero(){return g(this,J)===0n}cmpn(t){a(this,R,ct).call(this,Math.abs(t)<=g(Q,Wi),"Number is too big");let e=a(this,R,Vt).call(this),i=BigInt(t);return e<i?-1:e>i?1:0}cmp(t){var r;let e=a(this,R,Vt).call(this),i=a(r=t,R,Vt).call(r);return e<i?-1:e>i?1:0}ucmp(t){return g(this,J)<g(t,J)?-1:g(this,J)>g(t,J)?1:0}gtn(t){return this.cmpn(t)===1}gt(t){return this.cmp(t)===1}gten(t){return this.cmpn(t)>=0}gte(t){return this.cmp(t)>=0}ltn(t){return this.cmpn(t)===-1}lt(t){return this.cmp(t)===-1}lten(t){return this.cmpn(t)<=0}lte(t){return this.cmp(t)<=0}eqn(t){return this.cmpn(t)===0}eq(t){return this.cmp(t)===0}toRed(t){return a(this,R,ct).call(this,this.red==null,"Already a number in reduction context"),a(this,R,ct).call(this,g(this,at)===0,"toRed works only with positives"),t.convertTo(this).forceRed(t)}fromRed(){return a(this,R,ct).call(this,this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)}forceRed(t){return this.red=t,this}redAdd(t){return a(this,R,ct).call(this,this.red,"redAdd works only with red numbers"),this.red.add(this,t)}redIAdd(t){return a(this,R,ct).call(this,this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)}redSub(t){return a(this,R,ct).call(this,this.red,"redSub works only with red numbers"),this.red.sub(this,t)}redISub(t){return a(this,R,ct).call(this,this.red,"redISub works only with red numbers"),this.red.isub(this,t)}redShl(t){return a(this,R,ct).call(this,this.red,"redShl works only with red numbers"),this.red.shl(this,t)}redMul(t){return a(this,R,ct).call(this,this.red,"redMul works only with red numbers"),this.red.verify2(this,t),this.red.mul(this,t)}redIMul(t){return a(this,R,ct).call(this,this.red,"redIMul works only with red numbers"),this.red.verify2(this,t),this.red.imul(this,t)}redSqr(){return a(this,R,ct).call(this,this.red,"redSqr works only with red numbers"),this.red.verify1(this),this.red.sqr(this)}redISqr(){return a(this,R,ct).call(this,this.red,"redISqr works only with red numbers"),this.red.verify1(this),this.red.isqr(this)}redSqrt(){return a(this,R,ct).call(this,this.red,"redSqrt works only with red numbers"),this.red.verify1(this),this.red.sqrt(this)}redInvm(){return a(this,R,ct).call(this,this.red,"redInvm works only with red numbers"),this.red.verify1(this),this.red.invm(this)}redNeg(){return a(this,R,ct).call(this,this.red,"redNeg works only with red numbers"),this.red.verify1(this),this.red.neg(this)}redPow(t){return a(this,R,ct).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 Q(t,16,i)}toHex(t=0){if(this.isZero()&&t===0)return"";let e=a(this,R,Ho).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 Q(t,16)}static fromNumber(t){return new Q(t)}static fromString(t,e){return new Q(t,e)}static fromSm(t,e="big"){var u;if(t.length===0)return new Q(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(R1)s=wl.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 Q(0n);return a(u=c,R,We).call(u,o,r),c}toSm(t="big"){if(g(this,J)===0n)return g(this,at)===1?[128]:[];let e=a(this,R,Ho).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=Wo[e.codePointAt(o)],f=Wo[e.codePointAt(o+1)];r[c++]=(u&15)<<4|f&15}let s;return g(this,at)===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 Q(0n)}let o=new Q(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 Q(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 Q.fromSm(t,"little")}toScriptNum(){return this.toSm("little")}_invmp(t){a(this,R,ct).call(this,g(t,at)===0,"p must not be negative for _invmp"),a(this,R,ct).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 Q(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 A(e,J,g(this,J)*g(t,J)),A(e,at,g(e,J)===0n?0:g(this,at)^g(t,at)),A(e,Pt,this.length+t.length),e.red=null,e.normSign(),e}};Fo=new WeakMap,qo=new WeakMap,Ac=new WeakMap,Ec=new WeakMap,Wi=new WeakMap,kc=new WeakMap,Vo=new WeakMap,J=new WeakMap,at=new WeakMap,Pt=new WeakMap,R=new WeakSet,Dp=function(){if(g(this,J)===0n)return[0];let t=[],e=g(this,J);for(;e>0n;)t.push(Number(e&g(Q,qo))),e>>=g(Q,Fo);return t.length>0?t:[0]},Hp=function(t,e,i){e==="hex"&&(e=16),a(this,R,ct).call(this,typeof e=="number"&&e===Math.trunc(e)&&e>=2&&e<=36,"Base must be an integer between 2 and 36");let r=t.toString().replace(/\s+/g,""),s=0,o=0;r.startsWith("-")?(s++,o=1):r.startsWith("+")&&s++;let c=r.substring(s);if(c.length===0){a(this,R,We).call(this,0n,o===1&&r.startsWith("-")?1:0),this.normSign();return}e===16?a(this,R,$p).call(this,c,o,i):a(this,R,Wp).call(this,c,e,o,i)},$p=function(t,e,i){if(i==="le"){let r=[],s=t;s.length%2!==0&&(s="0"+s);for(let o=0;o<s.length;o+=2){let c=s.substring(o,o+2),u=Number.parseInt(c,16);if(Number.isNaN(u))throw new Error("Invalid character in "+s);r.push(u)}a(this,R,Do).call(this,r,"le"),A(this,at,e),this.normSign()}else{let r;try{r=BigInt("0x"+t)}catch{throw new Error("Invalid character in "+t)}a(this,R,We).call(this,r,e),this.normSign()}},Wp=function(t,e,i,r){try{if(a(this,R,qp).call(this,t,e),A(this,at,i),this.normSign(),r==="le"){let s=g(this,at);a(this,R,Do).call(this,this.toArray("be"),"le"),A(this,at,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}},Fp=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},qp=function(t,e){A(this,J,0n);let i=BigInt(e),r=Q.groupSizes[e],s=BigInt(Q.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);A(this,J,BigInt(a(this,R,xl).call(this,f,e))),o+=u}for(;o<c;){let f=t.substring(o,o+r),d=BigInt(a(this,R,xl).call(this,f,e));A(this,J,g(this,J)*s+d),o+=r}a(this,R,$n).call(this)},xl=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},We=function(t,e){A(this,J,t),A(this,at,t===0n?0:e),a(this,R,$n).call(this)},$n=function(){if(g(this,J)===0n)A(this,Pt,1),A(this,at,0);else{let t=g(this,J).toString(2).length;A(this,Pt,Math.max(1,Math.ceil(t/Q.wordSize)))}},ct=function(t,e="Assertion failed"){if(!t)throw new Error(e)},Vp=function(t,e="be"){if(a(this,R,ct).call(this,BigInt(Math.abs(t))<=g(Q,kc),"The number is larger than 2 ^ 53 (unsafe)"),a(this,R,ct).call(this,t%1===0,"Number must be an integer for BigNumber conversion"),a(this,R,We).call(this,BigInt(Math.abs(t)),t<0?1:0),e==="le"){let i=g(this,at),r=this.toArray("be");a(this,R,Do).call(this,r,"le"),A(this,at,i),this.normSign()}return this},Do=function(t,e){if(t.length===0)return a(this,R,We).call(this,0n,0),this;let i=0n;if(e==="be")for(let r of t)i=i<<8n|BigInt(r&255);else for(let r=t.length-1;r>=0;r--)i=i<<8n|BigInt(t[r]&255);return a(this,R,We).call(this,i,0),this},Ho=function(){return g(this,J)===0n?"0":g(this,J).toString(16)},Kp=function(t){let e=a(this,R,Ho).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},zp=function(t,e){var c;if(g(this,J)===0n)return a(c=Q,Nr,Xp).call(c,e);let i=Q.groupSizes[t],r=BigInt(Q.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=g(this,J);for(;o>0n;){let u=o%r;o/=r;let f=a(this,R,Fp).call(this,u,t);s=(o>0n?a(this,R,jp).call(this,f,i):f)+s}if(e>0)for(;s.length<e;)s="0"+s;return(g(this,at)===1?"-":"")+s},Nr=new WeakSet,Xp=function(t){let e="0";if(t>1)for(;e.length<t;)e="0"+e;return e},jp=function(t,e){let i=e-t.length;return i<=0?t:i<Q.zeros.length?Q.zeros[i]+t:"0".repeat(i)+t},Gp=function(t,e){let i=g(this,J),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}},Vt=function(){return g(this,at)===1?-g(this,J):g(this,J)},ye=function(t){t<0n?(A(this,J,-t),A(this,at,1)):(A(this,J,t),A(this,at,0)),a(this,R,$n).call(this),this.normSign()},$o=function(t,e,i=!1){let r=e(g(this,J),g(t,J)),s=g(this,Pt);return i&&(s=Math.max(this.length,t.length)),A(this,J,r),a(this,R,$n).call(this),i&&A(this,Pt,Math.max(g(this,Pt),s)),this.strip()},vc=function(t,e,i=!1){return a(this,R,ct).call(this,g(this,at)===0&&g(t,at)===0),a(this,R,$o).call(this,t,e,i)},Rr=function(t,e){return this.length>=t.length?this.clone()[e](t):t.clone()[e](this)},Sl=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},Yp=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},Il=function(t){var i;if(t===null)return null;let e=new Q(0n);return a(i=e,R,ye).call(i,t),e},z(Q,Nr),w(Q,"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"]),w(Q,"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]),w(Q,"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]),w(Q,"wordSize",26),z(Q,Fo,26n),z(Q,qo,(1n<<26n)-1n),z(Q,Ac,BigInt(Number.MAX_SAFE_INTEGER)),z(Q,Ec,BigInt(Number.MIN_SAFE_INTEGER)),z(Q,Wi,67108863),z(Q,kc,(1n<<53n)-1n),z(Q,Vo,1048576);var O=Q;var Ko=class{constructor(t,e){w(this,"name");w(this,"p");w(this,"k");w(this,"n");w(this,"tmp");this.name=t,this.p=new O(e,16),this.n=this.p.bitLength(),this.k=new O(BigInt(1)).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){let t=new O(BigInt(0)),e=Math.ceil(this.n/O.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 zo=class extends Ko{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 b=0;b<o;b++)c[b]=r[b];let u=o;if(s<=9){let b=Array.from({length:u},()=>0);for(let y=0;y<u;++y)b[y]=c[y];e.words=b,t.words=[0];return}let f=r[9];c[u++]=f&4194303;let d=Array.from({length:u},()=>0);for(let b=0;b<u;++b)d[b]=c[b];e.words=d;let h=Array.from({length:Math.max(1,s-9)},()=>0),l=0;for(let b=10;b<s;b++){let y=Math.trunc(r[b]);l<h.length&&(h[l++]=(y&4194303)<<4|f>>>22),f=y}f>>>=22,l<h.length?h[l++]=f:f!==0&&h.length>0;let m=Array.from({length:l},()=>0);for(let b=0;b<l;++b)m[b]=h[b];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 _r=class{constructor(t){w(this,"prime");w(this,"m");if(t==="k256"){let e=new zo;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):(O.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 b=this.m.add(new O(1)).iushrn(2);return this.pow(t,b)}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 O(1).toRed(this),o=s.redNeg(),c=this.m.subn(1).iushrn(1),u=this.m.bitLength(),f=new O(2*u*u).toRed(this);for(;this.pow(f,c).cmp(o)!==0;)f.redIAdd(o);let d=this.pow(f,i),h=this.pow(t,i.addn(1).iushrn(1)),l=this.pow(t,i),m=r;for(;l.cmp(s)!==0;){let b=l,y=0;for(;b.cmp(s)!==0;)b=b.redSqr(),y++;this.assert(y<m);let S=this.pow(d,new O(1).iushln(m-y-1));h=h.redMul(S),d=S.redSqr(),l=l.redMul(d),m=y}return h}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 O(1).toRed(this);let i=new O(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 Xo=class extends _r{constructor(e){super(e);w(this,"shift");w(this,"r");w(this,"r2");w(this,"rinv");w(this,"minv");this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new O(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 O(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={};bl(Yi,{Reader:()=>na,ReaderUint8Array:()=>vt,Writer:()=>we,WriterUint8Array:()=>yt,base64ToArray:()=>S0,constantTimeEquals:()=>_x,encode:()=>zc,fromBase58:()=>oa,fromBase58Check:()=>ua,hexToUint8Array:()=>sa,minimallyEncode:()=>Xc,toArray:()=>ft,toBase58:()=>aa,toBase58Check:()=>ca,toBase64:()=>Ne,toHex:()=>st,toSafeString:()=>Ex,toUTF8:()=>I0,toUTF8Strict:()=>Dt,toUint8Array:()=>it,verifyNotNull:()=>Fr,zero2:()=>kx});var N1=new TextEncoder;function Pe(n){return N1.encode(n)}function Qe(n){return Pe(n).byteLength}function Cr(n){for(let t of n){let e=t.codePointAt(0);if(e<=31||e>=127&&e<=159)return!0}return!1}var Vc={};bl(Vc,{RIPEMD160:()=>Yo,SHA1:()=>Hr,SHA1HMAC:()=>Ol,SHA256:()=>kl,SHA256HMAC:()=>Ls,SHA512:()=>Tl,SHA512HMAC:()=>_c,hash160:()=>Qo,hash256:()=>ne,htonl:()=>s0,pbkdf2:()=>wx,realHtonl:()=>Sx,ripemd160:()=>Bl,sha1:()=>Ll,sha256:()=>Le,sha256hmac:()=>ta,sha512:()=>tx,sha512hmac:()=>Ml,swapBytes32:()=>Ul,toArray:()=>Dc});var _1=/^[0-9a-fA-F]*$/;function jo(n){if(typeof n!="string")throw new TypeError("Invalid hex string");if(n.length!==0&&!_1.test(n))throw new Error("Invalid hex string")}function Zp(n){if(jo(n),n.length===0)return"";let t=n.toLowerCase();return t.length%2!==0&&(t="0"+t),t}var vl=(n,t="Hash assertion failed")=>{if(!n)throw new Error(t)},Nc=class{constructor(t,e,i,r){w(this,"pending",null);w(this,"pendingTotal",0);w(this,"blockSize");w(this,"outSize");w(this,"endian");w(this,"_delta8");w(this,"_delta32");w(this,"padLength");w(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=Dc(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=$1(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()),vl(this.pending===null),this._digest()}digestHex(){return this.update(this._pad()),vl(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 C1(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 B1(n){let t=[],e=0;for(;e<n.length;)e=C1(n,e,t)+1;return t}function L1(n){jo(n);let t=Zp(n),e=[];for(let i=0;i<t.length;i+=2)e.push(Number.parseInt(t[i]+t[i+1],16));return e}function M1(n){let t=[];for(let e=0;e<n.length;e++)t[e]=Math.trunc(n[e]);return t}function Dc(n,t){return Array.isArray(n)?n.slice():n?typeof n=="string"?t==="hex"?L1(n):B1(n):M1(n):[]}function s0(n){return Ul(n)}function o0(n,t){let e="";for(let i of n)t==="little"&&(i=s0(i)),e+=U1(i.toString(16));return e}function U1(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 Al=typeof globalThis>"u"?void 0:globalThis.Buffer,D1=Al!=null&&typeof Al.from=="function",Jp="0123456789abcdef",El=Array.from({length:256});for(let n=0;n<El.length;n++)El[n]=Jp[n>>4&15]+Jp[n&15];function H1(n){if(D1)return Al.from(n).toString("hex");let t=Array.from({length:n.length});for(let e=0;e<n.length;e++)t[e]=El[n[e]];return t.join("")}var Pl=(()=>{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 dn(n,t){return n instanceof Uint8Array?n:Array.isArray(n)?new Uint8Array(n):Uint8Array.from(Dc(n,t))}function Rl(n){return typeof n=="string"?dn(n,"hex"):dn(n)}function Hc(n,t,e){n!=null?n.update(e):t?.update(e)}function $c(n,t){return n!=null?Array.from(n.digest()):t!=null?Array.from(t.digest()):[]}function Wc(n,t){return n!=null?n.digest("hex"):t!=null?H1(t.digest()):""}function Nl(n){let t=Pl?.createHash;if(typeof t=="function")try{return t(n)}catch{return}}function _l(n,t){let e=Pl?.createHmac;if(typeof e=="function")try{return e(n,t)}catch{return}}function Cl(n,t,e){let i=Nl(n);if(i!=null)return i.update(dn(t,e)),i.digest()}function a0(n,t,e,i){let r=_l(n,Rl(t));if(r!=null)return r.update(dn(e,i)),r.digest()}function $1(n,t,e,i){let r=e-t;vl(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 c0(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 Wn(n,t){return n>>>t|n<<32-t}function Br(n,t){return n<<t|n>>>32-t}function ae(n,t){return n+t>>>0}function Go(n,t,e){return n+t+e>>>0}function Qp(n,t,e,i){return n+t+e+i>>>0}function u0(n,t,e,i,r){return n+t+e+i+r>>>0}function W1(n,t,e,i){return n===0?f0(t,e,i):n===1||n===3?F1(t,e,i):n===2?l0(t,e,i):0}function f0(n,t,e){return n&t^~n&e}function l0(n,t,e){return n&t^n&e^t&e}function F1(n,t,e){return n^t^e}function q1(n){return Wn(n,2)^Wn(n,13)^Wn(n,22)}function V1(n){return Wn(n,6)^Wn(n,11)^Wn(n,25)}function K1(n){return Wn(n,7)^Wn(n,18)^n>>>3}function z1(n){return Wn(n,17)^Wn(n,19)^n>>>10}var X1=[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],j1=[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],G1=[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],Y1=[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 t0(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 Z1(n){return n<=15?0:n<=31?1518500249:n<=47?1859775393:n<=63?2400959708:2840853838}function J1(n){return n<=15?1352829926:n<=31?1548603684:n<=47?1836072691:n<=63?2053994217:0}var Yo=class extends Nc{constructor(){super(512,160,192,64);w(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,h=o,l=c,m=u,b;for(let y=0;y<80;y++)b=ae(Br(Qp(r,t0(y,s,o,c),e[X1[y]+i],Z1(y)),G1[y]),u),r=u,u=c,c=Br(o,10),o=s,s=b,b=ae(Br(Qp(f,t0(79-y,d,h,l),e[j1[y]+i],J1(y)),Y1[y]),m),f=m,m=l,l=Br(h,10),h=d,d=b;b=Go(this.h[1],o,l),this.h[1]=Go(this.h[2],c,m),this.h[2]=Go(this.h[3],u,f),this.h[3]=Go(this.h[4],r,d),this.h[4]=Go(this.h[0],s,h),this.h[0]=b}_digest(){return c0(this.h,"little")}_digestHex(){return o0(this.h,"little")}},Lr,zi,kl=class{constructor(){z(this,Lr);z(this,zi);A(this,zi,Nl("sha256")),g(this,zi)==null&&A(this,Lr,new Zo)}update(t,e){return Hc(g(this,zi),g(this,Lr),dn(t,e)),this}digest(){return $c(g(this,zi),g(this,Lr))}digestHex(){return Wc(g(this,zi),g(this,Lr))}};Lr=new WeakMap,zi=new WeakMap;var Hr=class extends Nc{constructor(){super(512,160,80,64);w(this,"h");w(this,"W");w(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]=Br(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 h=Math.trunc(s/20),l=u0(Br(o,5),W1(h,c,u,f),d,r[s],this.k[h]);d=f,f=u,u=Br(c,30),c=o,o=l}this.h[0]=ae(this.h[0],o),this.h[1]=ae(this.h[1],c),this.h[2]=ae(this.h[2],u),this.h[3]=ae(this.h[3],f),this.h[4]=ae(this.h[4],d)}_digest(){return c0(this.h,"big")}_digestHex(){return o0(this.h,"big")}},Mr,Xi,Tl=class{constructor(){z(this,Mr);z(this,Xi);A(this,Xi,Nl("sha512")),g(this,Xi)==null&&A(this,Mr,new Jo)}update(t,e){return Hc(g(this,Xi),g(this,Mr),dn(t,e)),this}digest(){return $c(g(this,Xi),g(this,Mr))}digestHex(){return Wc(g(this,Xi),g(this,Mr))}};Mr=new WeakMap,Xi=new WeakMap;var Ur,ji,Ls=class{constructor(t){z(this,Ur);z(this,ji);w(this,"blockSize",64);w(this,"outSize",32);let e=Rl(t);A(this,ji,_l("sha256",e)),g(this,ji)==null&&A(this,Ur,new Ms(px,e))}update(t,e){return Hc(g(this,ji),g(this,Ur),dn(t,e)),this}digest(){return $c(g(this,ji),g(this,Ur))}digestHex(){return Wc(g(this,ji),g(this,Ur))}};Ur=new WeakMap,ji=new WeakMap;var Ol=class{constructor(t){w(this,"inner");w(this,"outer");w(this,"blockSize",64);t=Dc(t,"hex"),t.length>this.blockSize&&(t=new Hr().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 Hr().update(t),e=0;e<t.length;e++)t[e]^=106;this.outer=new Hr().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()}},Dr,Gi,_c=class{constructor(t){z(this,Dr);z(this,Gi);w(this,"blockSize",128);w(this,"outSize",32);let e=Rl(t);A(this,Gi,_l("sha512",e)),g(this,Gi)==null&&A(this,Dr,new Ms(m0,e))}update(t,e){return Hc(g(this,Gi),g(this,Dr),dn(t,e)),this}digest(){return $c(g(this,Gi),g(this,Dr))}digestHex(){return Wc(g(this,Gi),g(this,Dr))}};Dr=new WeakMap,Gi=new WeakMap;function Cc(n,t){let e=Cl("sha256",n,t);return e??new Zo().update(dn(n,t)).digest()}function Q1(n,t){let e=Cl("sha512",n,t);return e??new Jo().update(dn(n,t)).digest()}function d0(n,t){return Cl("ripemd160",n,t)}var Bl=(n,t)=>{let e=d0(n,t);return e!=null?Array.from(e):new Yo().update(n,t).digest()},Ll=(n,t)=>new Hr().update(n,t).digest(),Le=(n,t)=>Array.from(Cc(n,t)),tx=(n,t)=>Array.from(Q1(n,t)),ne=(n,t)=>Array.from(Cc(Cc(n,t))),Qo=(n,t)=>{let e=Cc(n,t),i=d0(e);return i!=null?Array.from(i):new Yo().update(e).digest()},ta=(n,t,e)=>{let i=a0("sha256",n,t,e);return i!=null?Array.from(i):new Ls(n).update(t,e).digest()},Ml=(n,t,e)=>{let i=a0("sha512",n,t,e);return i!=null?Array.from(i):new _c(n).update(t,e).digest()};function ex(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function Bc(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`positive integer expected, got ${n}`)}function Fc(n,...t){if(!ex(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 h0(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("Hash should be wrapped by utils.createHasher");Bc(n.outputLen),Bc(n.blockLen)}function Lc(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 nx(n,t){Fc(n);let e=t.outputLen;if(n.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}function $r(...n){for(let t of n)t.fill(0)}function Rc(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function qc(n){return typeof n=="string"&&(n=ix(n)),Fc(n),n}function ix(n){if(typeof n!="string")throw new Error("string expected");return Pe(n)}var e0=qc,Mc=class{};function p0(n){let t=i=>n().update(qc(i)).digest(),e=n();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>n(),t}var Tc=BigInt(2**32-1),n0=BigInt(32);function rx(n,t=!1){return t?{h:Number(n&Tc),l:Number(n>>n0&Tc)}:{h:Number(n>>n0&Tc)|0,l:Number(n&Tc)|0}}function sx(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}=rx(n[s],t);i[s]=o,r[s]=c}return[i,r]}var i0=(n,t,e)=>n>>>e,r0=(n,t,e)=>n<<32-e|t>>>e,Cs=(n,t,e)=>n>>>e|t<<32-e,Bs=(n,t,e)=>n<<32-e|t>>>e,Oc=(n,t,e)=>n<<64-e|t>>>e-32,Pc=(n,t,e)=>n>>>e-32|t<<64-e;function fi(n,t,e,i){let r=(t>>>0)+(i>>>0);return{h:n+e+(r/2**32|0)|0,l:r|0}}var ox=(n,t,e)=>(n>>>0)+(t>>>0)+(e>>>0),ax=(n,t,e,i)=>Math.trunc(t+e+i+Math.trunc(n/2**32)),cx=(n,t,e,i)=>(n>>>0)+(t>>>0)+(e>>>0)+(i>>>0),ux=(n,t,e,i,r)=>Math.trunc(t+e+i+r+Math.trunc(n/2**32)),fx=(n,t,e,i,r)=>(n>>>0)+(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0),lx=(n,t,e,i,r,s)=>t+e+i+r+s+(n/2**32|0)|0,Uc=class extends Mc{constructor(e,i,r,s){super();w(this,"blockLen");w(this,"outputLen");w(this,"padOffset");w(this,"isLE");w(this,"buffer");w(this,"view");w(this,"finished",!1);w(this,"length",0);w(this,"pos",0);w(this,"destroyed",!1);this.blockLen=e,this.outputLen=i,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Rc(this.buffer)}update(e){Lc(this),e=qc(e),Fc(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=Rc(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){Lc(this),nx(e,this),this.finished=!0;let{buffer:i,view:r,blockLen:s,isLE:o}=this,{pos:c}=this;i[c++]=128,$r(this.buffer.subarray(c)),this.padOffset>s-c&&(this.process(r,0),c=0);for(let l=c;l<s;l++)i[l]=0;dx(r,s-8,BigInt(this.length*8),o),this.process(r,0);let u=Rc(e),f=this.outputLen;if(f%4!==0)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=f/4,h=this.get();if(d>h.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<d;l++)u.setUint32(4*l,h[l],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 dx(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]),hx=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]),qi=new Uint32Array(64),Zo=class extends Uc{constructor(e=32){super(64,e,8,!1);w(this,"A",Fi[0]|0);w(this,"B",Fi[1]|0);w(this,"C",Fi[2]|0);w(this,"D",Fi[3]|0);w(this,"E",Fi[4]|0);w(this,"F",Fi[5]|0);w(this,"G",Fi[6]|0);w(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 l=0;l<16;l++,i+=4)qi[l]=e.getUint32(i);for(let l=16;l<64;l++){let m=qi[l-15],b=qi[l-2],y=K1(m),S=z1(b);qi[l]=ae(ae(y,qi[l-7]),ae(S,qi[l-16]))}let{A:r,B:s,C:o,D:c,E:u,F:f,G:d,H:h}=this;for(let l=0;l<64;l++){let m=u0(h,V1(u),f0(u,f,d),hx[l],qi[l]),b=ae(q1(r),l0(r,s,o));h=d,d=f,f=u,u=ae(c,m),c=o,o=s,s=r,r=ae(m,b)}this.A=ae(this.A,r),this.B=ae(this.B,s),this.C=ae(this.C,o),this.D=ae(this.D,c),this.E=ae(this.E,u),this.F=ae(this.F,f),this.G=ae(this.G,d),this.H=ae(this.H,h)}roundClean(){$r(qi)}destroy(){$r(this.buffer),this.set(0,0,0,0,0,0,0,0)}},px=p0(()=>new Zo),Re=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),g0=sx(["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)),gx=g0[0],mx=g0[1],Vi=new Uint32Array(80),Ki=new Uint32Array(80),Jo=class extends Uc{constructor(e=64){super(128,e,16,!1);w(this,"Ah",Re[0]|0);w(this,"Al",Re[1]|0);w(this,"Bh",Re[2]|0);w(this,"Bl",Re[3]|0);w(this,"Ch",Re[4]|0);w(this,"Cl",Re[5]|0);w(this,"Dh",Re[6]|0);w(this,"Dl",Re[7]|0);w(this,"Eh",Re[8]|0);w(this,"El",Re[9]|0);w(this,"Fh",Re[10]|0);w(this,"Fl",Re[11]|0);w(this,"Gh",Re[12]|0);w(this,"Gl",Re[13]|0);w(this,"Hh",Re[14]|0);w(this,"Hl",Re[15]|0)}get(){let{Ah:e,Al:i,Bh:r,Bl:s,Ch:o,Cl:c,Dh:u,Dl:f,Eh:d,El:h,Fh:l,Fl:m,Gh:b,Gl:y,Hh:S,Hl:L}=this;return[e,i,r,s,o,c,u,f,d,h,l,m,b,y,S,L]}set(...[e,i,r,s,o,c,u,f,d,h,l,m,b,y,S,L]){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=h|0,this.Fh=l|0,this.Fl=m|0,this.Gh=b|0,this.Gl=y|0,this.Hh=S|0,this.Hl=L|0}process(e,i){for(let E=0;E<16;E++,i+=8)Vi[E]=e.getUint32(i),Ki[E]=e.getUint32(i+4);for(let E=16;E<80;E++){let _=Vi[E-15]|0,B=Ki[E-15]|0,F=Cs(_,B,1)^Cs(_,B,8)^i0(_,B,7),C=Bs(_,B,1)^Bs(_,B,8)^r0(_,B,7),I=Vi[E-2]|0,q=Ki[E-2]|0,W=Cs(I,q,19)^Oc(I,q,61)^i0(I,q,6),K=Bs(I,q,19)^Pc(I,q,61)^r0(I,q,6),ot=cx(C,K,Ki[E-7],Ki[E-16]),ut=ux(ot,F,W,Vi[E-7],Vi[E-16]);Vi[E]=ut|0,Ki[E]=ot|0}let{Ah:r,Al:s,Bh:o,Bl:c,Ch:u,Cl:f,Dh:d,Dl:h,Eh:l,El:m,Fh:b,Fl:y,Gh:S,Gl:L,Hh:T,Hl:k}=this;for(let E=0;E<80;E++){let _=Cs(l,m,14)^Cs(l,m,18)^Oc(l,m,41),B=Bs(l,m,14)^Bs(l,m,18)^Pc(l,m,41),F=l&b^~l&S,C=m&y^~m&L,I=fx(k,B,C,mx[E],Ki[E]),q=lx(I,T,_,F,gx[E],Vi[E]),W=I|0,K=Cs(r,s,28)^Oc(r,s,34)^Oc(r,s,39),ot=Bs(r,s,28)^Pc(r,s,34)^Pc(r,s,39),ut=r&o^r&u^o&u,V=s&c^s&f^c&f;T=S|0,k=L|0,S=b|0,L=y|0,b=l|0,y=m|0,{h:l,l:m}=fi(d|0,h|0,q|0,W|0),d=u|0,h=f|0,u=o|0,f=c|0,o=r|0,c=s|0;let j=ox(ot,V,W);r=ax(j,K,ut,q),s=j|0}({h:r,l:s}=fi(r,s,this.Ah,this.Al)),{h:o,l:c}=fi(o,c,this.Bh,this.Bl),{h:u,l:f}=fi(u,f,this.Ch,this.Cl),{h:d,l:h}=fi(d,h,this.Dh,this.Dl),{h:l,l:m}=fi(l,m,this.Eh,this.El),{h:b,l:y}=fi(b,y,this.Fh,this.Fl),{h:S,l:L}=fi(S,L,this.Gh,this.Gl),{h:T,l:k}=fi(T,k,this.Hh,this.Hl),this.set(r,s,o,c,u,f,d,h,l,m,b,y,S,L,T,k)}roundClean(){$r(Vi,Ki)}destroy(){$r(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},m0=p0(()=>new Jo),Ms=class extends Mc{constructor(e,i){super();w(this,"oHash");w(this,"iHash");w(this,"blockLen");w(this,"outputLen");w(this,"finished",!1);w(this,"destroyed",!1);h0(e);let r=qc(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),$r(o)}update(e){return Lc(this),this.iHash.update(e),this}digestInto(e){Lc(this),Fc(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 bx(n,t,e,i){h0(n);let{c:r,dkLen:s=32}={...i};if(Bc(r),Bc(s),r<1)throw new Error("iterations (c) should be >= 1");let o=e0(t),c=e0(e),u=new Uint8Array(s),f=b0.create(n,o),d=f._cloneInto().update(c),h,l=new Uint8Array(4),m=Rc(l),b=new Uint8Array(f.outputLen);for(let y=1,S=0;S<s;y++,S+=f.outputLen){let L=u.subarray(S,S+f.outputLen);m.setInt32(0,y,!1),h=d._cloneInto(h),h.update(l).digestInto(b),L.set(b.subarray(0,L.length));for(let T=1;T<r;T++){f._cloneInto(h).update(b).digestInto(b);for(let k=0;k<L.length;k++)L[k]^=b[k]}}return f.destroy(),d.destroy(),h?.destroy(),$r(b),u}var b0=(n,t,e)=>new Ms(n,t).update(e).digest();b0.create=(n,t)=>new Ms(n,t);function yx(n,t,e,i){return bx(m0,n,t,{c:e,dkLen:i})}function wx(n,t,e,i,r="sha512"){if(r!=="sha512")throw new Error("Only sha512 is supported in this PBKDF2 implementation");let s=Pl?.pbkdf2Sync;if(typeof s=="function"){let f=s(dn(n),dn(t),e,i,r);return Array.from(f)}let o=Uint8Array.from(n),c=Uint8Array.from(t),u=yx(o,c,e,i);return Array.from(u)}function Ul(n){return(n>>>24|n>>>8&65280|n<<8&16711680|(n&255)<<24)>>>0}var xx=(()=>{let n=new ArrayBuffer(4),t=new Uint32Array(n),e=new Uint8Array(n);return t[0]=16909060,e[0]===4})();function Sx(n){return xx?Ul(n):n>>>0}var Ix=new O(4294967295),vx=new O(2).pow(new O(64)).sub(new O(1)),Ax=new O(Number.MAX_SAFE_INTEGER);function ea(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(Ix))throw new Error("non-canonical varInt");if(t&&i.eq(vx))return-1;if(i.gt(Ax))throw new Error("number too large to retain precision - use readVarIntBn");return i.toNumber()}var Qt,Bt,Wr,An,li,yt=class{constructor(t,e=256){z(this,An);z(this,Qt);z(this,Bt);z(this,Wr);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),A(this,Qt,new Uint8Array(e)),A(this,Bt,0),A(this,Wr,e),t!=null)for(let i of t)this.write(i)}getLength(){return g(this,Bt)}toUint8Array(){return g(this,Qt).slice(0,g(this,Bt))}toArray(){return Array.from(this.toUint8Array())}toUint8ArrayZeroCopy(){return g(this,Qt).subarray(0,g(this,Bt))}reserve(t){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("WriterUint8Array reserve requires a non-negative safe integer");a(this,An,li).call(this,t)}write(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);return a(this,An,li).call(this,e.length),g(this,Qt).set(e,g(this,Bt)),A(this,Bt,g(this,Bt)+e.length),this}writeReverse(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);a(this,An,li).call(this,e.length);for(let i=e.length-1;i>=0;i--)g(this,Qt)[g(this,Bt)]=e[i],A(this,Bt,g(this,Bt)+1);return this}writeUInt8(t){return a(this,An,li).call(this,1),g(this,Qt)[g(this,Bt)]=t&255,A(this,Bt,g(this,Bt)+1),this}writeInt8(t){return this.writeUInt8(t),this}writeUInt16LE(t){return a(this,An,li).call(this,2),g(this,Qt)[g(this,Bt)]=t&255,g(this,Qt)[g(this,Bt)+1]=t>>8&255,A(this,Bt,g(this,Bt)+2),this}writeUInt16BE(t){return a(this,An,li).call(this,2),g(this,Qt)[g(this,Bt)]=t>>8&255,g(this,Qt)[g(this,Bt)+1]=t&255,A(this,Bt,g(this,Bt)+2),this}writeInt16LE(t){return this.writeUInt16LE(t&65535),this}writeInt16BE(t){return this.writeUInt16BE(t&65535),this}writeUInt32LE(t){return a(this,An,li).call(this,4),g(this,Qt)[g(this,Bt)]=t&255,g(this,Qt)[g(this,Bt)+1]=t>>8&255,g(this,Qt)[g(this,Bt)+2]=t>>16&255,g(this,Qt)[g(this,Bt)+3]=t>>24&255,A(this,Bt,g(this,Bt)+4),this}writeUInt32BE(t){return a(this,An,li).call(this,4),g(this,Qt)[g(this,Bt)]=t>>24&255,g(this,Qt)[g(this,Bt)+1]=t>>16&255,g(this,Qt)[g(this,Bt)+2]=t>>8&255,g(this,Qt)[g(this,Bt)+3]=t&255,A(this,Bt,g(this,Bt)+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 O(t).toArray("be",8);return this.writeReverse(e),this}writeVarIntNum(t){let e=we.varIntNum(t);return this.write(e),this}writeVarIntBn(t){let e=we.varIntBn(t);return this.write(e),this}reset(){A(this,Bt,0)}};Qt=new WeakMap,Bt=new WeakMap,Wr=new WeakMap,An=new WeakSet,li=function(t){if(g(this,Bt)+t>g(this,Wr)){let e=g(this,Wr)*2;for(;g(this,Bt)+t>e;)e*=2;let i=new Uint8Array(e);i.set(g(this,Qt)),A(this,Qt,i),A(this,Wr,e)}};var kn,tn,En,Dl=class Dl{constructor(t=new Uint8Array(0),e=0){z(this,tn);w(this,"bin");w(this,"pos");z(this,kn);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(A(this,kn,this.bin.length),!Number.isSafeInteger(e)||e<0||e>g(this,kn))throw new RangeError("ReaderUint8Array position exceeds available data");this.pos=e}static makeReader(t,e=0){if(t instanceof Uint8Array)return new Dl(t,e);if(Array.isArray(t))return new na(t,e);throw new Error("ReaderUint8Array.makeReader: bin must be Uint8Array or number[]")}eof(){return this.pos>=g(this,kn)}read(t=g(this,kn)-this.pos){a(this,tn,En).call(this,t);let e=this.pos,i=this.pos+t;return this.pos=i,this.bin.slice(e,i)}readView(t=g(this,kn)-this.pos){a(this,tn,En).call(this,t);let e=this.pos;return this.pos+=t,this.bin.subarray(e,this.pos)}skip(t){a(this,tn,En).call(this,t),this.pos+=t}remaining(){return g(this,kn)-this.pos}readReverse(t=g(this,kn)-this.pos){a(this,tn,En).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,tn,En).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,tn,En).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,tn,En).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,tn,En).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,tn,En).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,tn,En).call(this,8);let t=Array.from(this.bin.slice(this.pos,this.pos+8)),e=new O(t);return this.pos=this.pos+8,e}readUInt64LEBn(){let t=Array.from(this.readReverse(8));return new O(t)}readInt64LEBn(){let t=new O(2).pow(new O(63)),e=new O(2).pow(new O(64)),i=Array.from(this.readReverse(8)),r=new O(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 O(2).pow(new O(53))))return i.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return e}}readVarIntNumStrict(t=!0){return ea(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 O(this.readUInt16LE());case 254:return new O(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new O(t)}}};kn=new WeakMap,tn=new WeakSet,En=function(t){if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(this.pos)||this.pos<0||this.pos+t>g(this,kn))throw new RangeError("ReaderUint8Array read exceeds available data")};var vt=Dl;var Kc=globalThis.Buffer,w0=Kc!=null&&typeof Kc.from=="function",Ex=(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}},kx=n=>n.length%2===1?"0"+n:n,y0="0123456789abcdef",x0=Array.from({length:256},()=>"");for(let n=0;n<256;n++)x0[n]=y0[n>>4&15]+y0[n&15];var st=n=>w0?Kc.from(n).toString("hex"):n.length===0?"":Array.from(n,t=>x0[t&255]).join(""),it=(n,t)=>n instanceof Uint8Array?n:typeof n=="string"&&t==="hex"?sa(n):new Uint8Array(ft(n,t)),ft=(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 Tx(n);case"base64":return S0(n);default:return Rx(n)}},ra=new Int8Array(256).fill(-1);for(let n=0;n<10;n++)ra[48+n]=n;for(let n=0;n<6;n++)ra[65+n]=10+n,ra[97+n]=10+n;var Tx=n=>Array.from(sa(n)),sa=n=>{jo(n);let t=n.length%2===0?n:"0"+n;if(w0){let r=Kc.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=ra[t.codePointAt(r)],o=ra[t.codePointAt(r+1)];e[i++]=s<<4|o}return e},Ox=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)},Px=(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 S0(n){let t=Ox(n),e=[],i=0,r=0;for(let s=0;s<t.length;s++){let o=t.codePointAt(s),c=Px(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 Rx(n){return Array.from(Pe(n))}var I0=n=>new TextDecoder().decode(n instanceof Uint8Array?n:new Uint8Array(n)),Dt=n=>new TextDecoder("utf-8",{fatal:!0}).decode(n instanceof Uint8Array?n:new Uint8Array(n)),zc=(n,t)=>{switch(t){case"hex":return st(n);case"utf8":return I0(n);default:return n}};function Ne(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 ia="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",oa=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=>ia.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))])]},aa=n=>{let t=Array.from({length:256},()=>-1);for(let i=0;i<ia.length;++i)t[ia.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]=ia.codePointAt(u),r=c}for(;r!==0;){let s=Math.trunc(r/58),o=r-s*58;e.push(ia.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)},ca=(n,t=[0])=>{let e=ne([...t,...n]);return e=[...t,...n,...e.slice(0,4)],aa(e)},ua=(n,t,e=1)=>{let i=oa(n),r=i.slice(0,e),s=i.slice(e,-4),o=[...r,...s];return o=ne(o),i.slice(-4).forEach((c,u)=>{if(c!==o[u])throw new Error("Invalid checksum")}),t==="hex"&&(r=st(r),s=st(s)),{prefix:r,data:s}},we=class n{constructor(t){w(this,"bufs");w(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 O(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 O(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(v0)),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 O(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}},na=class{constructor(t=[],e=0){w(this,"bin");w(this,"pos");w(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 O(t)}readUInt64LEBn(){let t=this.readReverse(8);return new O(t)}readInt64LEBn(){let t=this.readReverse(8),e=new O(t);return e.gte(Nx)&&(e=e.sub(v0)),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 O(2).pow(new O(53))))return i.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return e}}readVarIntNumStrict(t=!0){return ea(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 O(this.readUInt16LE());case 254:return new O(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new O(t)}}},Xc=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[]},Nx=new O(2).pow(new O(63)),v0=new O(2).pow(new O(64));function Fr(n,t="Expected a valid value, but got undefined or null."){if(n==null)throw new Error(t);return n}function _x(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 Hl;function A0(n,t){let e=n.andln(3)+t&3;return e===3?-1:e}function E0(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 k0(n,t){return 2*n===t+1?1-n:n}var jc,T0,$l=class $l{constructor(){z(this,jc);w(this,"p");w(this,"red");w(this,"redN");w(this,"zero");w(this,"one");w(this,"two");w(this,"g");w(this,"n");w(this,"a");w(this,"b");w(this,"tinv");w(this,"zeroA");w(this,"threeA");w(this,"endo");w(this,"_endoWnafT1");w(this,"_endoWnafT2");w(this,"_wnafT1");w(this,"_wnafT2");w(this,"_wnafT3");w(this,"_wnafT4");w(this,"_bitLength");if(Hl===void 0)Hl=this;else return Hl;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 O(e.p,16),this.red=new _r(e.prime),this.zero=new O(0).toRed(this.red),this.one=new O(1).toRed(this.red),this.two=new O(2).toRed(this.red),this.n=new O(e.n,16),this.g=Me.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 O(e.a,16).toRed(this.red),this.b=new O(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=A0(t,r),c=A0(e,s),u=E0(t,r,o,c);i[0].push(u);let f=E0(e,s,c,o);i[1].push(f),r=k0(r,u),s=k0(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"?ft(t,"hex"):t}static intFromLE(t){return new O(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,jc,T0).call(this,t,i)}}_resolveEndomorphismBeta(t){if(t.beta!==void 0)return new O(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 O(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]:($l.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 Xo(t),i=new O(2).toRed(e).redInvm(),r=i.redNeg(),s=new O(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 O(1),o=new O(0),c=new O(0),u=new O(1),f,d,h,l,m,b,y=new O(0),S=0,L=new O(0),T=new O(0);for(;i.cmpn(0)!==0;){let _=r.div(i);L=r.sub(_.mul(i)),T=c.sub(_.mul(s));let B=u.sub(_.mul(o));if(h===void 0&&L.cmp(e)<0)f=y.neg(),d=s,h=L.neg(),l=T;else if(h!==void 0&&++S===2)break;y=L,r=i,i=L,c=s,s=T,u=o,o=B}if(f===void 0||d===void 0||h===void 0||l===void 0)throw new Error("Failed to compute Endo Basis values");m=L.neg(),b=T;let k=h.sqr().add(l.sqr());return m.sqr().add(b.sqr()).cmp(k)>=0&&(m=f,b=d),h.negative!==0&&(h=h.neg(),l=l.neg()),m.negative!==0&&(m=m.neg(),b=b.neg()),[{a:h,b:l},{a:m,b}]}_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),h=t.sub(c).sub(u),l=f.add(d).neg();return{k1:h,k2:l}}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}};jc=new WeakSet,T0=function(t,e){return typeof t.basis!="object"||t.basis===null?this._getEndoBasis(e):t.basis.map(i=>({a:new O(i.a,16),b:new O(i.b,16)}))};var te=$l;var qr=class{constructor(t){w(this,"curve");w(this,"type");w(this,"precomputed");this.curve=new te,this.type=t,this.precomputed=null}};var Vr=class n extends qr{constructor(e,i,r){super("jacobian");w(this,"x");w(this,"y");w(this,"z");w(this,"zOne");e===null&&i===null&&r===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new O(0)):(O.isBN(e)||(e=new O(e,16)),this.x=e,O.isBN(i)||(i=new O(i,16)),this.y=i,O.isBN(r)||(r=new O(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 O(0).toRed(this.curve.red),this.zOne=!1)}toP(){if(this.isInfinity())return new Me(null,null);let e=this.z.redInvm(),i=e.redSqr(),r=this.x.redMul(i),s=this.y.redMul(i).redMul(e);return new Me(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 h=f.redSqr(),l=h.redMul(f),m=s.redMul(h),b=d.redSqr().redIAdd(l).redISub(m).redISub(m),y=d.redMul(m.redISub(b)).redISub(c.redMul(l)),S=this.z.redMul(e.z).redMul(f);return new n(b,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 d=u.redSqr(),h=d.redMul(u),l=r.redMul(d),m=f.redSqr().redIAdd(h).redISub(l).redISub(l),b=f.redMul(l.redISub(m)).redISub(o.redMul(h)),y=this.z.redMul(u);return new n(m,b,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),d=f.redSqr().redISub(u).redISub(u),h=c.redIAdd(c);h=h.redIAdd(h),h=h.redIAdd(h),e=d,i=f.redMul(u.redISub(d)).redISub(h),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(),h=c.redIAdd(c);h=h.redIAdd(h),h=h.redIAdd(h),e=d.redISub(u).redISub(u),i=f.redMul(u.redISub(e)).redISub(h),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 O0(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 Kt=0n,Fe=1n,Wl=2n,Cx=3n,Bx=4n,Lx=8n,qn=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,Zi=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,P0=(1n<<256n)-1n;function ql(n){let t=n>>256n;return n=(n&P0)+(t<<32n)+t*977n,t=n>>256n,n=(n&P0)+(t<<32n)+t*977n,n>=qn&&(n-=qn),n}var Kr=n=>ql((n%qn+qn)%qn),Fn=(n,t)=>n>=t?n-t:qn-(t-n),lt=(n,t)=>ql(n*t),R0=(n,t)=>ql(n+t),Us=n=>{let t=Fe,e=Kt,i=Kr(n),r=qn;for(;i>Fe;){let s=r/i;[t,e]=[e-t*s,t],[i,r]=[r-i*s,i]}return Kr(t)},Mx=n=>lt(n,n),Ux=(n,t)=>{let e=1n;for(n=Kr(n);t>0n;)(t&1n)!==0n&&(e=lt(e,n)),n=lt(n,n),t>>=1n;return e},Dx=qn+1n>>2n,Hx=n=>{let t=Ux(n,Dx);return lt(t,t)!==Kr(n)?null:t},$x=n=>O.isBN(n)?BigInt("0x"+n.toString(16)):typeof n=="string"?BigInt("0x"+n):Array.isArray(n)?BigInt("0x"+st(n)):BigInt(n),Gc=BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Yc=BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),N0=new Map,fa=n=>{let{X:t,Y:e,Z:i}=n;if(e===Kt)return{X:Kt,Y:Fe,Z:Kt};let r=lt(e,e),s=lt(Bx,lt(t,r)),o=lt(Cx,lt(t,t)),c=Fn(lt(o,o),lt(Wl,s)),u=Fn(lt(o,Fn(s,c)),lt(Lx,lt(r,r))),f=lt(Wl,lt(e,i));return{X:c,Y:u,Z:f}},Ds=(n,t)=>{if(n.Z===Kt)return t;if(t.Z===Kt)return n;let e=lt(n.Z,n.Z),i=lt(t.Z,t.Z),r=lt(n.X,i),s=lt(t.X,e),o=lt(n.Y,lt(i,t.Z)),c=lt(t.Y,lt(e,n.Z)),u=Fn(s,r),f=Fn(c,o);if(u===Kt)return f===Kt?fa(n):{X:Kt,Y:Fe,Z:Kt};let d=lt(u,u),h=lt(u,d),l=lt(r,d),m=Fn(Fn(lt(f,f),h),lt(Wl,l)),b=Fn(lt(f,Fn(l,m)),lt(o,h)),y=lt(u,lt(n.Z,t.Z));return{X:m,Y:b,Z:y}},Wx=n=>n.Z===Kt?n:{X:n.X,Y:qn-n.Y,Z:n.Z},Fx=(n,t)=>{let e=`${n}:${t.x.toString(16)}:${t.y.toString(16)}`,i=N0.get(e);if(i!==void 0)return i;let r=Array.from({length:1<<n-1},()=>({X:Kt,Y:Fe,Z:Kt})),s={X:t.x,Y:t.y,Z:Fe};r[0]=s;let o=fa(s);for(let c=1;c<r.length;c++)r[c]=Ds(r[c-1],o);return N0.set(e,r),r},qx=(n,t)=>{let e=[],i=1n<<BigInt(t),r=i>>1n,s=n;for(;s>0n;){if((s&Fe)===Kt)e.push(0);else{let o=s&i-1n;o>r&&(o-=i),e.push(Number(o)),s-=o}s>>=Fe}return e},Zc=(n,t,e=5)=>{let i=Fx(e,t),r=qx(n,e),s={X:Kt,Y:Fe,Z:Kt};for(let o=r.length-1;o>=0;o--){s=fa(s);let c=r[o];if(c!==0){let u=Math.abs(c)>>1,f=c>0?i[u]:Wx(i[u]);s=Ds(s,f)}}return s},zr=n=>{let t=n%Zi;return t<0n&&(t+=Zi),t},la=(n,t)=>zr(n*t),Vl=n=>{let t=1n,e=0n,i=zr(n),r=Zi;for(;i>1n;){let s=r/i;[t,e]=[e-t*s,t],[i,r]=[r-i*s,i]}return zr(t)},Ie,_0,C0,B0,L0,M0,Fl,U0,Lt=class Lt extends qr{constructor(e,i,r=!0){super("affine");z(this,Ie);w(this,"x");w(this,"y");w(this,"inf");this.precomputed=null,e===null&&i===null?(this.x=null,this.y=null,this.inf=!0):(O.isBN(e)||(e=new O(e,16)),this.x=e,O.isBN(i)||(i=new O(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 Lt(e.slice(1,33),e.slice(33,65));return Lt._assertOnCurve(r)}else if((e[0]===2||e[0]===3)&&e.length-1===32)return Lt._assertOnCurve(Lt.fromX(e.slice(1,33),e[0]===3));throw new Error("Unknown point format")}static fromString(e){let i=ft(e,"hex");return Lt._assertOnCurve(Lt.fromDER(i))}static fromX(e,i){let r=$x(e);r=Kr(r);let s=R0(lt(Mx(r),r),7n),o=Hx(s);if(o===null)throw new Error("Invalid point");let c=o;(c&Fe)!==(i?Fe:Kt)&&(c=Fn(qn,c));let u=new O(r.toString(16),16),f=new O(c.toString(16),16);return Lt._assertOnCurve(new Lt(u,f))}static fromJSON(e,i){typeof e=="string"&&(e=JSON.parse(e));let r=new Lt(e[0],e[1],i);if(r=Lt._assertOnCurve(r),typeof e[2]!="object"||e[2]===null)return r;let s=e[2],o=c=>{let u=new Lt(c[0],c[1],i);return Lt._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=lt(i,i),s=R0(lt(lt(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"?st(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 Lt(null,null);if(this.x?.cmp(e.x??new O(0))===0)return new Lt(null,null);let i={X:BigInt("0x"+this.x.fromRed().toString(16)),Y:BigInt("0x"+this.y.fromRed().toString(16)),Z:Fe},r={X:BigInt("0x"+e.x.fromRed().toString(16)),Y:BigInt("0x"+e.y.fromRed().toString(16)),Z:Fe},s=Ds(i,r);if(s.Z===Kt)return new Lt(null,null);let o=Us(s.Z),c=lt(o,o),u=lt(s.X,c),f=lt(s.Y,lt(c,o));return new Lt(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===Kt)return new Lt(null,null);let r=fa({X:e,Y:i,Z:Fe}),s=Us(r.Z),o=lt(s,s),c=lt(r.X,o),u=lt(r.Y,lt(o,s));return new Lt(c.toString(16),u.toString(16))}getX(){return(this.x??new O(0)).fromRed()}getY(){return(this.y??new O(0)).fromRed()}mul(e){if(O.isBN(e)||(e=new O(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=Kr(s),s===Kt)return new Lt(null,null);if(s===Kt)return new Lt(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=Gc,c=Yc):(o=BigInt("0x"+this.x.fromRed().toString(16)),c=BigInt("0x"+this.y.fromRed().toString(16)));let u=Zc(s,{x:o,y:c});if(u.Z===Kt)return new Lt(null,null);let f=Us(u.Z),d=lt(f,f),h=lt(u.X,d),l=lt(u.Y,lt(d,f)),m=new O(h.toString(16),16),b=new O(l.toString(16),16),y=new Lt(m,b);return i?y.neg():y}mulCT(e){if(O.isBN(e)||(e=new O(e,16)),e=e,this.inf)return new Lt(null,null);let i=e.isNeg(),r=i?e.neg():e,s=BigInt("0x"+r.toString(16));if(s=Kr(s),s===0n)return new Lt(null,null);let o=this===this.curve.g?Gc:BigInt("0x"+this.getX().toString(16)),c=this===this.curve.g?Yc: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 L=S==="1"?1n:0n;O0(L,u,f),f=Ds(u,f),u=fa(u),O0(L,u,f)}if(u.Z===0n)return new Lt(null,null);let h=Us(u.Z),l=lt(h,h),m=lt(u.X,l),b=lt(u.Y,lt(l,h)),y=new Lt(m.toString(16),b.toString(16));return i?y.neg():y}mulAdd(e,i,r){let s=[this,i],o=[e,r];return a(this,Ie,Fl).call(this,s,o)}jmulAdd(e,i,r){let s=[this,i],o=[e,r];return a(this,Ie,Fl).call(this,s,o,!0)}eq(e){return this===e||this.inf===e.inf&&(this.inf||(this.x??new O(0)).cmp(e.x??new O(0))===0&&(this.y??new O(0)).cmp(e.y??new O(0))===0)}neg(e){if(this.inf)return this;let i=new Lt(this.x,(this.y??new O(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 Vr(null,null,null):new Vr(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 h=[s[e],null,null,s[i]],l=s[e].y??new O(0),m=s[i].y??new O(0);l.cmp(m)===0?(h[1]=s[e].add(s[i]),h[2]=s[e].toJ().mixedAdd(s[i].neg())):l.cmp(m.redNeg())===0?(h[1]=s[e].toJ().mixedAdd(s[i]),h[2]=s[e].add(s[i].neg())):(h[1]=s[e].toJ().mixedAdd(s[i]),h[2]=s[e].toJ().mixedAdd(s[i].neg()));let b=[-3,-1,-5,-7,0,7,5,1,3],y=this.curve.getJSF(o[e],o[i]),S=Math.max(d,y[0].length);f[e]=Array.from({length:S}),f[i]=Array.from({length:S});for(let L=0;L<S;L++){let T=Math.trunc(y[0][L]),k=Math.trunc(y[1][L]);f[e][L]=b[(T+1)*3+(k+1)],f[i][L]=0,u[e]=h}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 O(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}}};Ie=new WeakSet,_0=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 Lt((this.x??new O(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 Lt(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},C0=function(e,i,r,s,o){var c;for(let u=0;u<r;u++){let f=a(c=i[u],Ie,U0).call(c,e);s[u]=f.wnd,o[u]=f.points}},B0=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},L0=function(e,i,r,s){let o=new O(1),c=new O(2),u=e;for(let f=0;f<i;f++){let d=r[f];if(d.cmpn(0)===0)continue;let h=d.isNeg()?s[f][d.neg().sub(o).div(c).toNumber()].neg():s[f][d.sub(o).div(c).toNumber()];u=h.type==="affine"?u.mixedAdd(h):u.add(h)}return u},M0=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,Ie,C0).call(this,e,i,s,u,f);let h=a(this,Ie,B0).call(this,i,r,s,u,f,d),l=new Vr(null,null,null),m=this.curve._wnafT4,b=h;for(;b>=0;){let y=this._collectWnafStep(b,s,d,m);if(b=y.index,l=l.dblp(y.doubles),b<0)break;l=a(this,Ie,L0).call(this,l,s,m,f),b--}for(let y=0;y<s;y++)f[y]=[];return o===!0?l:l.toP()},Fl=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]),h=e[c],l=a(f=h,Ie,_0).call(f)??new Lt(null,null);d.k1.negative!==0&&(d.k1.ineg(),h=h.neg(!0)),d.k2.negative!==0&&(d.k2.ineg(),l=l.neg(!0)),s[c*2]=h,s[c*2+1]=l,o[c*2]=d.k1,o[c*2+1]=d.k2}let u=a(this,Ie,M0).call(this,1,s,o,c*2,r);for(let d=0;d<c*2;d++)s[d]=null,o[d]=null;return u},U0=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 Me=Lt;var jt=class n extends Me{static fromPrivateKey(t){let i=new te().g.mul(t);return new n(i.x,i.y)}static fromString(t){let e=Me.fromString(t);return new n(e.x,e.y)}static fromDER(t){let e=Me.fromDER(t);return new n(e.x,e.y)}constructor(t,e=null,i=!0){if(t instanceof Me)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 O(Le(t,i),16);return Ji(r,e,this)}toDER(t){return t==="hex"?this.encode(!0,t):this.encode(!0)}toHash(t){let e=Qo(this.encode(!0));return t==="hex"?st(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 ca(this.toHash(),t)}deriveChild(t,e,i,r){let s;if(typeof r=="function"){let h=r(t,this);h===void 0?(s=this.deriveSharedSecret(t),typeof i=="function"&&i(t,this,s)):s=h}else s=this.deriveSharedSecret(t);let o=ft(e,"utf8"),c=ta(s.encode(!0),o),f=new te().g.mul(new O(c)),d=this.add(f);return new n(d.x,d.y)}static fromMsgHashAndCompactSignature(t,e,i){let r=ft(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 ve(new O(r.slice(1,33)),new O(r.slice(33,65))).RecoverPublicKey(o,t)}};var ve=class n{constructor(t,e){w(this,"r");w(this,"s");this.r=t,this.s=e}static fromDER(t,e){let i=(h,l)=>{let m=h[l.place++];if((m&128)===0)return m;throw new Error("Invalid DER entity length")};class r{constructor(){w(this,"place",0)}}t=ft(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 O(u),new O(d))}static fromCompact(t,e){if(t=ft(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 O(t.slice(1,33)),new O(t.slice(33,65)))}verify(t,e,i){let r=new O(Le(t,i),16);return Ji(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,h=f.length-1;for(;f[d]===0&&(f[d+1]&128)===0&&d<h;)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"?st(u):t==="base64"?Ne(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"?st(s):i==="base64"?Ne(s):s}RecoverPublicKey(t,e){let i=this.r,r=this.s,s=(t&1)!==0,o=t>>1,c=new te,u=c.n,f=c.g,d=o===0?i:i.add(u),h=Me.fromX(d,s);if(!h.mul(u).isInfinity())throw new Error("nR is not at infinity");let m=e.neg().umod(u),b=i.invm(u),y=b.mul(r).umod(u),S=b.mul(m).umod(u),L=f.mul(S).add(h.mul(y)),T=new jt(L);return T.validate(),T}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 da=class{constructor(t,e){w(this,"K");w(this,"V");let i=ft(t,"hex"),r=ft(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 Ls(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(),st(i)}};function D0(n,t,e=new te){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 Xr(n){let t=n.toArray("be"),e=0n;for(let i of t)e=e<<8n|BigInt(i);return e}var ha=new te,Kl=ha.n.byteLength(),Vx=ha.n.subn(1),Kx=Zi>>1n;function zx(n,t,e){let i;if(typeof n=="function"?i=n(t):n!==void 0&&O.isBN(n)?i=n:i=new O(e.generate(Kl),16),i==null)throw new Error("k is undefined");return D0(i,!0)}function Jc(n,t){if(n)throw new Error(t)}function Xx(n,t,e,i,r){if(n.cmpn(1)<0||n.cmp(Vx)>0)return Jc(r,"Invalid fixed custom K value (must be >1 and <N-1)");let s=ha.g.mulCT(n);if(s.isInfinity())return Jc(r,"Invalid fixed custom K value (k\xB7G at infinity)");let o=zr(BigInt("0x"+s.getX().toString(16)));if(o===0n)return Jc(r,"Invalid fixed custom K value (r == 0)");let c=Vl(BigInt("0x"+n.toString(16))),u=zr(t+la(o,e)),f=la(c,u);return f===0n?Jc(r,"Invalid fixed custom K value (s == 0)"):(i&&f>Kx&&(f=Zi-f),new ve(new O(o.toString(16),16),new O(f.toString(16),16)))}var H0=(n,t,e=!1,i)=>{let r=ha.n.bitLength();if(n.bitLength()>r)throw new Error(`ECDSA message is too large: expected <= ${r} bits. Callers must hash messages before signing.`);n=D0(n);let s=Xr(n),o=Xr(t),c=t.toArray("be",Kl),u=n.toArray("be",Kl),f=new da(c,u),d=O.isBN(i);for(let h=0;;h++){let l=Xx(zx(i,h,f),s,o,e,d);if(l!=null)return l}},Ji=(n,t,e)=>{let i=ha.n.bitLength();if(n.bitLength()>i)return!1;let r=Xr(n);if(e.x==null||e.y==null)throw new Error("Invalid public key: missing coordinates.");let s={x:Xr(e.x),y:Xr(e.y)},o={r:Xr(t.r),s:Xr(t.s)},{r:c,s:u}=o,f=r;if(c<=Kt||c>=Zi||u<=Kt||u>=Zi)return!1;let d=Vl(u);if(d===0n)return!1;let h=la(f,d),l=la(c,d),m=Zc(h,{x:Gc,y:Yc}),b=Zc(l,s),y=Ds(m,b);if(y.Z===0n)return!1;let S=Us(y.Z),L=lt(S,S),T=lt(y.X,L);return zr(T)===c};var zl=class{constructor(){w(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)}},$0=null,jx=n=>($0??($0=new zl),$0.generate(n)),Ue=jx;var _e=255,Gx=129,W0=/^[1-9A-HJ-NP-Za-km-z]{1,64}$/;function F0(n,t,e){if(!Number.isSafeInteger(n)||n<e||n>_e)throw new TypeError(`threshold must be a safe integer from ${e} to ${_e}`);if(n>t)throw new Error("threshold cannot exceed the number of points")}var hn=class n{constructor(t,e){w(this,"x");w(this,"y");let i=new te().p;this.x=t.umod(i),this.y=e.umod(i)}toString(){return aa(this.x.toArray())+"."+aa(this.y.toArray())}static fromString(t){if(typeof t!="string"||t.length>Gx)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||!W0.test(e)||!W0.test(i))throw new TypeError("Finite-field point must use a bounded canonical Base58 representation");let s=new n(new O(oa(e)),new O(oa(i)));if(s.toString()!==t)throw new TypeError("Finite-field point must use a bounded canonical Base58 representation");return s}},Hs=class n{constructor(t,e){w(this,"points");w(this,"threshold");if(!Array.isArray(t)||t.length===0||t.length>_e)throw new TypeError(`points must contain from 1 to ${_e} entries`);let i=e??t.length;F0(i,t.length,1),this.points=t.slice(),this.threshold=i}static fromPrivateKey(t,e){if(!Number.isSafeInteger(e)||e<2||e>_e)throw new TypeError(`threshold must be a safe integer from 2 to ${_e}`);let i=new te().p,r=[new hn(new O(0),new O(t.toArray()))];for(let s=1;s<e;s++){let o=new O(Ue(32)).umod(i),c=new O(Ue(32)).umod(i);r.push(new hn(o,c))}return new n(r)}valueAt(t){if(F0(this.threshold,this.points.length,1),!(t instanceof O))throw new TypeError("x must be a BigNumber");let e=new te().p,i=new Set;for(let o=0;o<this.threshold;o++){let c=this.points[o];if(!(c instanceof hn)||!(c.x instanceof O)||!(c.y instanceof O))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 O(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,h=r.sub(f).umod(e),m=d.sub(f).umod(e).invm(e),b=h.mul(m).umod(e);c=c.mul(b).umod(e)}s=s.add(c).umod(e)}return s}};var Yx=256,q0=/^[1-9A-HJ-NP-Za-km-z]{1,64}$/,Zx=/^(?:[2-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/,V0=/^[0-9a-f]{8}$/;function Xl(n,t,e){if(!Array.isArray(n)||n.length===0||n.length>_e)throw new TypeError(`shares must contain from 1 to ${_e} entries`);if(!Number.isSafeInteger(t)||t<2||t>_e)throw new TypeError(`threshold must be a safe integer from 2 to ${_e}`);if(typeof e!="string"||!V0.test(e))throw new TypeError("integrity must be an 8-character lowercase hexadecimal string")}var pa=class n{constructor(t,e,i){w(this,"points");w(this,"threshold");w(this,"integrity");this.points=t,this.threshold=e,this.integrity=i}static fromBackupFormat(t){if(!Array.isArray(t)||t.length===0||t.length>_e)throw new TypeError(`shares must contain from 1 to ${_e} 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>Yx)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,h]=c;if(u===void 0||f===void 0||d===void 0||h===void 0||!q0.test(u)||!q0.test(f)||!Zx.test(d)||!V0.test(h))throw new TypeError(`Invalid canonical share data in share ${s.toString()}`);let l=Number(d);if(s!==0&&e!==l)throw new Error("Threshold mismatch in share "+s.toString());if(s!==0&&i!==h)throw new Error("Integrity mismatch in share "+s.toString());e=l,i=h,r.push(hn.fromString(`${u}.${f}`))}return Xl(r,e,i),new n(r,e,i)}toBackupFormat(){Xl(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 hn))throw new TypeError("shares must contain finite-field points");let r=i.toString();if(hn.fromString(r).toString()!==r)throw new TypeError("shares must contain canonical finite-field points");t.push(`${r}.${this.threshold.toString()}.${this.integrity}`)}return t}},jr=class n extends O{static fromRandom(){return new n(Ue(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=ua(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 O?(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");O.move(this,s.modN)}}}checkInField(){let t=new te,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 O(Le(t,e),16);return H0(s,this,i,r)}verify(t,e,i){let r=new O(Le(t,i),16);return Ji(r,e,this.toPublicKey())}toPublicKey(){let e=new te().g.mulCT(this);return new jt(e.x,e.y)}toWif(t=[128]){if(!this.isValid())throw new Error("Value is out of field");return ca([...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=ft(e,"utf8"),c=ta(s.encode(!0),o),u=new te;return new n(this.add(new O(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>_e||e>_e)throw new RangeError(`threshold and totalShares cannot exceed ${_e}`);let i=Hs.fromPrivateKey(this,t),r=[],s=new Set,o=new te,c=Ue(64);for(let f=0;f<e;f++){let d,h=0;do{let m=[f,h,...Ue(32)],b=Ml(c,m);if(d=new O(b).umod(o.p),h++,h>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 l=i.valueAt(d);r.push(new hn(d,l))}let u=this.toPublicKey().toHash("hex").slice(0,8);return new pa(r,t,u)}toBackupShares(t,e){return this.toKeyShares(t,e).toBackupFormat()}static fromBackupShares(t){return n.fromKeyShares(pa.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(Xl(e,i,r),e.length<i)throw new Error(`At least ${i} shares are required to reconstruct the private key`);let s=[],o=new te().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 h=e[d];if(!(h instanceof hn)||!(h.x instanceof O)||!(h.y instanceof O))throw new TypeError("shares must contain finite-field points");if(h.x.isNeg()||h.y.isNeg()||h.x.gte(o)||h.y.gte(o))throw new TypeError("share coordinates must be canonical field elements");s.push(new hn(new O(h.x.toArray()),new O(h.y.toArray())))}for(let d=0;d<i;d++)for(let h=d+1;h<i;h++)if(s[d].x.eq(s[h].x))throw new Error("Duplicate share detected, each must be unique.");let c=new Hs(s,i),u=new n(c.valueAt(new O(0)).toArray());if(u.toPublicKey().toHash("hex").slice(0,8)!==r)throw new Error("Integrity hash mismatch");return u}};var jl={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},Qc=jl;for(let n of Object.keys(jl)){let t=jl[n];Qc[t]??(Qc[t]=n)}var x=Qc;var K0=typeof globalThis>"u"?void 0:globalThis.Buffer,z0=Symbol();function Yr(n){return n[z0]()}function Jx(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 Qx(n,t){let e=Jx(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 en,hi,nn,Vn,Gr,fe,X0,j0,Ft,Gl,G0,Y0,di,Yl,Z0,tu,J0,Zl,Q0,tg,Jl,eg,xe=class xe{constructor(t=[],e,i,r=!0){z(this,Ft);z(this,en);z(this,hi);z(this,nn);z(this,Vn);z(this,Gr);A(this,en,t),A(this,hi,r),A(this,nn,e),A(this,Vn,i)}static fromASM(t){var s;let e=[],i=t.split(" "),r=0;for(;r<i.length;){let{chunk:o,advance:c}=a(s=xe,fe,j0).call(s,i,r);e.push(o),r+=c}return new xe(e)}static fromHex(t){if(t.length===0)return xe.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=sa(t)}catch{throw new Error("Some elements in this string are not hex encoded.")}return new xe([],e,t.toLowerCase(),!1)}static fromBinary(t){let e=Uint8Array.from(t);return new xe([],e,void 0,!1)}static fromBinaryView(t){return new xe([],t,void 0,!1)}get chunks(){return a(this,Ft,Gl).call(this),g(this,en)}set chunks(t){A(this,en,t),A(this,hi,!0),a(this,Ft,di).call(this)}toASM(){let t="";for(let e of this.chunks)t+=a(this,Ft,eg).call(this,e);return t.slice(1)}toHex(){let t=a(this,Ft,tu).call(this);if(g(this,Vn)!=null)return g(this,Vn);let e=K0==null?zc(Array.from(t),"hex"):K0.from(t).toString("hex");return A(this,Vn,e),e}toBinary(){return Array.from(this.toUint8Array())}toUint8Array(){return Uint8Array.from(a(this,Ft,tu).call(this))}[z0](){return a(this,Ft,tu).call(this)}writeScript(t){return a(this,Ft,di).call(this),this.chunks=this.chunks.concat(t.chunks),this}writeOpCode(t){return a(this,Ft,di).call(this),this.chunks.push({op:t}),this}setChunkOpCode(t,e){return a(this,Ft,di).call(this),this.chunks[t]={op:e},this}writeBn(t){if(a(this,Ft,di).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,Ft,di).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,Ft,di).call(this),this.writeBn(new O(t)),this}removeCodeseparators(){var e;let t=this.toUint8Array();return A(this,nn,Uint8Array.from(a(e=xe,fe,tg).call(e,t,x.OP_CODESEPARATOR))),A(this,Vn,void 0),A(this,en,[]),A(this,hi,!1),this}findAndDelete(t){a(this,Ft,di).call(this);let e=t.toUint8Array();if(e.length===0)return this;for(let i=0;i<this.chunks.length;)Qx(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")}};en=new WeakMap,hi=new WeakMap,nn=new WeakMap,Vn=new WeakMap,Gr=new WeakMap,fe=new WeakSet,X0=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},j0=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:ft(t[e+2],"hex"),op:s},advance:3};if(!r){let c=i;c.length%2!==0&&(c="0"+c);let u=ft(c,"hex");if(zc(u,"hex")!==c)throw new Error("invalid hex string in script");return{chunk:{data:u,op:a(o=xe,fe,X0).call(o,u.length)},advance:1}}return{chunk:{op:s},advance:1}},Ft=new WeakSet,Gl=function(){var t;g(this,hi)||(g(this,nn)!=null?A(this,en,a(t=xe,fe,Q0).call(t,g(this,nn))):A(this,en,[]),A(this,hi,!0),a(this,Ft,Yl).call(this))},G0=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},Y0=function(){var s,o;let t=this.chunks,e=a(s=xe,fe,G0).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=xe,fe,J0).call(o,i,r,c.op,c.data)}return i},di=function(){A(this,nn,void 0),A(this,Vn,void 0),A(this,Gr,void 0)},Yl=function(){A(this,Gr,g(this,en).map(t=>({ref:t,op:t.op,dataRef:t.data,data:t.data==null?void 0:Array.from(t.data)})))},Z0=function(){if(g(this,Gr)?.length!==g(this,en).length)return!1;for(let t=0;t<g(this,en).length;t++){let e=g(this,en)[t],i=g(this,Gr)[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},tu=function(){return!g(this,hi)&&g(this,nn)!=null?g(this,nn):(a(this,Ft,Gl).call(this),(g(this,nn)==null||!a(this,Ft,Z0).call(this))&&(A(this,nn,a(this,Ft,Y0).call(this)),A(this,Vn,void 0),a(this,Ft,Yl).call(this)),g(this,nn))},J0=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},Zl=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}},Q0=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=xe,fe,Jl).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:h,hasLength:l}=a(c=xe,fe,Zl).call(c,f,t,r,i);r=h;let m=Math.min(r+d,i),b=!l||m-r!==d;e.push({data:a(u=xe,fe,Jl).call(u,t,r,m),op:f,invalidLength:b}),r=m}else e.push({op:f})}return e},tg=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=xe,fe,Zl).call(o,u,t,s,r);s=d;let h=Math.min(s+f,r);if(u!==e)for(let l=c;l<h;l++)i.push(t[l]??0);s=h}else u!==e&&i.push(u)}return i},Jl=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},eg=function(t){let e=t.op,i="";if(t.data===void 0){let r=x[e];i=`${i} ${r}`}else i=`${i} ${st(t.data)}`;return i},z(xe,fe);var Ae=xe;var t2=new Uint8Array(0),Ql=Object.freeze(Array.from({length:32},()=>0));function e2(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 n2(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=e2(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 i2(n,t){if(n.allInputs!=null)return n.allInputs;let e=[...n.otherInputs];return e.splice(n.inputIndex,0,t),e}function rg(n,t,e,i){return i===t?e:n[i]}function r2(n,t,e){let i=new we;for(let r=0;r<n.length;r++){let s=rg(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(ft(s.sourceTXID,"hex"));i.writeUInt32LE(s.sourceOutputIndex)}return ne(i.toUint8Array())}function s2(n,t,e){let i=new we;for(let r=0;r<n.length;r++){let s=rg(n,t,e,r);i.writeUInt32LE(s.sequence??4294967295)}return ne(i.toUint8Array())}function ng(n,t){n.writeUInt64LE(t.satoshis??0);let e=t.lockingScript?.toUint8Array()??t2;n.writeVarIntNum(e.length),n.write(e)}function ig(n,t){let e=new we;if(t==null)for(let i of n)ng(e,i);else{let i=n[t];if(i==null)throw new Error(`Output at index ${t} does not exist`);ng(e,i)}return ne(e.toUint8Array())}function o2(n,t,e){if((n.scope&At.SIGHASH_ANYONECANPAY)!==0)return[...Ql];if(n.cache?.hashPrevouts!=null)return n.cache.hashPrevouts;let i=r2(t,n.inputIndex,e);return n.cache!=null&&(n.cache.hashPrevouts=i),i}function a2(n,t,e){let i=n.scope&31;if((n.scope&At.SIGHASH_ANYONECANPAY)!==0||i===At.SIGHASH_SINGLE||i===At.SIGHASH_NONE)return[...Ql];if(n.cache?.hashSequence!=null)return n.cache.hashSequence;let r=s2(t,n.inputIndex,e);return n.cache!=null&&(n.cache.hashSequence=r),r}function c2(n){var r;let t=n.scope&31;if(t!==At.SIGHASH_SINGLE&&t!==At.SIGHASH_NONE){if(n.cache?.hashOutputsAll!=null)return n.cache.hashOutputsAll;let s=ig(n.outputs);return n.cache!=null&&(n.cache.hashOutputsAll=s),s}if(t!==At.SIGHASH_SINGLE||n.inputIndex>=n.outputs.length)return[...Ql];let e=n.cache?.hashOutputsSingle?.get(n.inputIndex);if(e!=null)return e;let i=ig(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 ie=class ie extends ve{constructor(e,i,r){super(e,i);w(this,"scope");this.scope=r}static formatOTDA(e){let i=(e.scope&ie.SIGHASH_ANYONECANPAY)===ie.SIGHASH_ANYONECANPAY,r=(e.scope&31)===ie.SIGHASH_SINGLE,s=(e.scope&31)===ie.SIGHASH_NONE,o=(e.scope&31)===ie.SIGHASH_ALL||!r&&!s,c=n2(e.subscript),u={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence,script:c.bytes,scriptLength:c.encodedLength},f=new we;function d(b){f.writeVarIntNum(b.length);for(let y of b)f.writeReverse(ft(y.sourceTXID,"hex")),f.writeUInt32LE(y.sourceOutputIndex),f.writeVarIntNum(y.scriptLength??y.script.length),f.write(y.script),f.writeUInt32LE(y.sequence)}function h(b){f.writeVarIntNum(b.length);for(let y of b)f.writeUInt64LE(y.satoshis),f.writeVarIntNum(y.script.length),f.write(y.script)}f.writeInt32LE(e.transactionVersion);let l=new Ae().toBinary();if(i)i&&d([u]);else{let b=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:l})):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:l});e.allInputs==null&&b.splice(e.inputIndex,0,u),d(b)}if(o){let b=e.outputs.map(y=>({satoshis:y.satoshis??0,script:y.lockingScript.toBinary()}));h(b)}else if(r){let b=[];for(let S=0;S<e.inputIndex;S++)b.push({satoshis:-1,script:l});let y=e.outputs[e.inputIndex];y!==void 0&&b.push({satoshis:y.satoshis??0,script:y.lockingScript.toBinary()}),h(b)}else s&&h([]);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=i2(e,i),s=o2(e,r,i),o=a2(e,r,i),c=c2(e),u=new we;u.writeInt32LE(e.transactionVersion),u.write(s),u.write(o),u.writeReverse(ft(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&ie.SIGHASH_FORKID)!==0,r=e.ignoreChronicle!==!0&&(e.scope&ie.SIGHASH_CHRONICLE)!==0;return i&&e.sighashForkIdEnabled!==!1&&!r?ie.formatBip143(e):e.sighashForkIdEnabled===!1||!i||r?ie.formatOTDA(e):new Uint8Array(0)}static usesOtdaSingleBug(e){let i=(e.scope&ie.SIGHASH_FORKID)!==0,r=e.ignoreChronicle!==!0&&(e.scope&ie.SIGHASH_CHRONICLE)!==0;return(e.sighashForkIdEnabled===!1||!i||r)&&(e.scope&31)===ie.SIGHASH_SINGLE&&e.inputIndex>=e.outputs.length}static fromChecksigFormat(e){if(e.length===0){let o=new O(1),c=new O(1),u=1;return new ie(o,c,u)}let i=e.at(-1),r=e.slice(0,-1),s=ve.fromDER(r);return new ie(s.r,s.s,i)}hasLowS(){return!(this.s.ltn(1)||this.s.gt(new O("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex")))}toChecksigFormat(){return[...this.toDER(),this.scope]}};w(ie,"SIGHASH_ALL",1),w(ie,"SIGHASH_NONE",2),w(ie,"SIGHASH_SINGLE",3),w(ie,"SIGHASH_CHRONICLE",32),w(ie,"SIGHASH_FORKID",64),w(ie,"SIGHASH_ANYONECANPAY",128);var At=ie;function td(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 u2(){return globalThis}function ed(n){let t=u2().__bsvSdkAsyncCryptoBackendV1;if(t!==void 0){if(!t.isReady()){t.preload().catch(()=>{});return}return t.supportsCrypto(n)?t:void 0}}var qe=class extends Ae{isLockingScript(){return!0}isUnlockingScript(){return!1}};var Ve=class extends Ae{isLockingScript(){return!1}isUnlockingScript(){return!0}};function sg(n){return n==null?"null/undef":n.length===void 0?"INVALID_STACK_ITEM":st(n)}var ga=class extends Error{constructor(e){let i=e.stackState.map(sg).join(", "),r=e.altStackState.map(sg).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);b(this,"txid");b(this,"outputIndex");b(this,"context");b(this,"programCounter");b(this,"stackState");b(this,"altStackState");b(this,"ifStackState");b(this,"stackMem");b(this,"altStackMem");this.name=this.constructor.name,this.txid=e.txid,this.outputIndex=e.outputIndex,this.context=e.context,this.programCounter=e.programCounter,this.stackState=e.stackState.map(d=>d.slice()),this.altStackState=e.altStackState.map(d=>d.slice()),this.ifStackState=e.ifStackState.slice(),this.stackMem=e.stackMem,this.altStackMem=e.altStackMem}};var Xn=class extends Error{constructor(e,i,r){let o={stack:"Stack memory usage","alt-stack":"Alt stack memory usage","element-size":"Script element allocation"}[e];super(`${o} has exceeded ${i} bytes`);b(this,"resource");b(this,"limit");b(this,"attempted");this.resource=e,this.limit=i,this.attempted=r,this.name="ScriptResourceLimitError"}};var Ew;function Da(){return Ew}var kw=520,Kh=1e4,zh=500,Tw=0x7fffffffn,Ow=75e4,Pw=32e6,Xh=1e3,Rw=Math.pow(2,31)-1,Nw=BigInt(Rw),Bw=20,jh=2147483648,uf=4194304,_w=65535,Gh=5e8,Cw=Object.freeze(new T(-1).toScriptNum()),Yh=Object.freeze(Array.from({length:17},(n,t)=>Object.freeze(new T(t).toScriptNum())));function Zh(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}function vi(n){return new T(n?1:0)}function Lw(n,t){return vi(n&&t)}function Uw(n,t){return vi(n||t)}function Mw(n,t){return n.cmp(t)<0?n:t}function Dw(n,t){return n.cmp(t)>0?n:t}function Jh(n){if(typeof n.consensus!="boolean")throw new TypeError("Spend verification consensus must be boolean");for(let[e,i]of[["blockHeight",n.blockHeight],["utxoHeight",n.utxoHeight]])if(i!==void 0&&(!Number.isSafeInteger(i)||i<0||i>4294967295))throw new RangeError(`Spend verification ${e} must be an unsigned 32-bit integer`);let t=Array.isArray(n.verifyFlags)?Array.from(n.verifyFlags):n.verifyFlags;if(t!==void 0&&typeof t!="string"&&(!Array.isArray(t)||t.some(e=>typeof e!="string")))throw new TypeError("Spend verification flags must be a string or an array of strings");return{consensus:n.consensus,blockHeight:n.blockHeight,utxoHeight:n.utxoHeight,verifyFlags:t}}function Qh(n,t=Number.MAX_SAFE_INTEGER){return!(n.length>t||n.length>0&&(n.at(-1)&127)===0&&(n.length<=1||(n.at(-2)&128)===0))}function Hw(n){if(n.length<9||n.length>73||n[0]!==48||n[1]!==n.length-3)return!1;let t=n[2],e=n[3];if(t!==2||e===0||5+e>=n.length)return!1;let i=4+e,r=n[i],s=n[i+1];if(r!==2||s===0||(n[4]&128)!==0||e>1&&n[4]===0&&(n[5]&128)===0)return!1;let o=i+2;return!((n[o]&128)!==0||s>1&&n[o]===0&&(n[o+1]&128)===0||e+s+7!==n.length)}function $w(n){let t=n.data,e=n.op;return Array.isArray(t)?t.length===0?e===x.OP_0:t.length===1&&t[0]>=1&&t[0]<=16?e===x.OP_1+(t[0]-1):t.length===1&&t[0]===129?e===x.OP_1NEGATE:t.length<=75?e===t.length:t.length<=255?e===x.OP_PUSHDATA1:t.length<=65535?e===x.OP_PUSHDATA2:!0:!0}var Gn,So,h,Ii,Mt,Et,se,mo,jn,bo,tp,ep,np,ip,ff,df,Ha,Xr,wo,rp,lt,Re,Q,Kt,vt,sp,op,$a,ap,cp,le,yo,lf,up,fp,dp,hf,pf,gf,mf,lp,bf,wf,hp,pp,gp,mp,bp,wp,yp,xp,Sp,Ip,vp,yf,qa,Ap,xf,jr,K,Sf=class Sf{constructor(t){G(this,h);b(this,"sourceTXID");b(this,"sourceOutputIndex");b(this,"sourceSatoshis");b(this,"lockingScript");b(this,"transactionVersion");b(this,"otherInputs");b(this,"allInputs");b(this,"outputs");b(this,"inputIndex");b(this,"unlockingScript");b(this,"inputSequence");b(this,"lockTime");b(this,"context");b(this,"programCounter");b(this,"lastCodeSeparator");b(this,"stack");b(this,"altStack");b(this,"ifStack");b(this,"elseStack");b(this,"memoryLimit");b(this,"hasExplicitMemoryLimit");b(this,"stackMem");b(this,"altStackMem");b(this,"isRelaxedOverride");b(this,"verifyFlags");b(this,"executedOpCount");b(this,"returningFromConditional");G(this,Gn);G(this,So);if(this.sourceTXID=t.sourceTXID,this.sourceOutputIndex=t.sourceOutputIndex,this.sourceSatoshis=t.sourceSatoshis,this.lockingScript=t.lockingScript,this.transactionVersion=t.transactionVersion,this.otherInputs=t.otherInputs,this.allInputs=t.allInputs,this.outputs=t.outputs,this.inputIndex=t.inputIndex,this.unlockingScript=t.unlockingScript,this.inputSequence=t.inputSequence,this.lockTime=t.lockTime,this.hasExplicitMemoryLimit=t.memoryLimit!==void 0,this.memoryLimit=t.memoryLimit??Number.POSITIVE_INFINITY,this.isRelaxedOverride=t.isRelaxed===!0,t.verifyFlags===void 0)this.verifyFlags=void 0;else{let e=Array.isArray(t.verifyFlags)?t.verifyFlags:t.verifyFlags.split(",");this.verifyFlags=new Set(e.map(i=>i.trim()).filter(i=>i.length>0))}this.stack=[],this.altStack=[],this.ifStack=[],this.elseStack=[],this.stackMem=0,this.altStackMem=0,this.executedOpCount=0,this.returningFromConditional=!1,N(this,So,t.sigHashCache==null),N(this,Gn,t.sigHashCache??{hashOutputsSingle:new Map}),this.reset()}reset(){y(this,So)&&(delete y(this,Gn).hashPrevouts,delete y(this,Gn).hashSequence,delete y(this,Gn).hashOutputsAll,y(this,Gn).hashOutputsSingle?.clear()),this.context="UnlockingScript",this.programCounter=0,this.lastCodeSeparator=null,this.stack=[],this.altStack=[],this.ifStack=[],this.elseStack=[],this.stackMem=0,this.altStackMem=0,this.executedOpCount=0,this.returningFromConditional=!1}step(){a(this,h,hp).call(this);let t=a(this,h,pp).call(this);if(this.programCounter>=t.chunks.length)return!1;let e=t.chunks[this.programCounter],i=a(this,h,gp).call(this,e),r=!this.returningFromConditional&&!this.ifStack.includes(!1);if(a(this,h,mp).call(this,i),r&&i>=0&&i<=x.OP_PUSHDATA4)a(this,h,bp).call(this,e);else if(r||i>=x.OP_IF&&i<=x.OP_ENDIF){let s,o,c,u,f,d,l,p,m,g,w,S,C,E,A,k,B,_,H,O,I,U,M,F,it,ot;if(a(this,h,wp).call(this,i,r),a(this,h,yp).call(this,i,r))return!0;switch(a(this,h,xp).call(this,i,r),i){case x.OP_VER:{let q=this.transactionVersion;a(this,h,lt).call(this,[q&255,q>>>8&255,q>>>16&255,q>>>24&255]);break}case x.OP_SUBSTR:{(()=>{this.stack.length<3&&a(this,h,K).call(this,"OP_SUBSTR requires at least three items to be on the stack.");let q=a(this,h,yo).call(this,a(this,h,Q).call(this)),z=a(this,h,yo).call(this,a(this,h,Q).call(this));s=a(this,h,Q).call(this);let tt=s.length;(z<0||z>=tt||q<0||q>tt-z)&&a(this,h,K).call(this,`OP_SUBSTR offset (${z}) must be in range [0, ${tt}) and length (${q}) must be in range [0, ${tt-z}]`),a(this,h,lt).call(this,s.slice(z,z+q))})();break}case x.OP_LEFT:{(()=>{this.stack.length<2&&a(this,h,K).call(this,"OP_LEFT requires at least two items to be on the stack.");let q=a(this,h,yo).call(this,a(this,h,Q).call(this));s=a(this,h,Q).call(this);let z=s.length;(q<0||q>z)&&a(this,h,K).call(this,`OP_LEFT length (${q}) must be in range [0, ${z}]`),a(this,h,lt).call(this,s.slice(0,q))})();break}case x.OP_RIGHT:{(()=>{this.stack.length<2&&a(this,h,K).call(this,"OP_RIGHT requires at least two items to be on the stack.");let q=a(this,h,yo).call(this,a(this,h,Q).call(this));s=a(this,h,Q).call(this);let z=s.length;(q<0||q>z)&&a(this,h,K).call(this,`OP_RIGHT length (${q}) must be in range [0, ${z}]`),a(this,h,lt).call(this,s.slice(z-q))})();break}case x.OP_LSHIFTNUM:{(()=>{this.stack.length<2&&a(this,h,K).call(this,"OP_LSHIFTNUM requires at least two items to be on the stack.");let q=a(this,h,le).call(this,a(this,h,Q).call(this)).toBigInt();q<0&&a(this,h,K).call(this,"OP_LSHIFTNUM bits to shift must not be negative."),q>0x7fffffffn&&a(this,h,K).call(this,"OP_LSHIFTNUM shift count exceeds INT_MAX.");let z=a(this,h,le).call(this,a(this,h,Q).call(this)).toBigInt(),tt=a(this,h,Ha).call(this);tt!==void 0&&z!==0n&&q>=BigInt(tt)*8n&&a(this,h,K).call(this,"script number overflow");let St=new T(z<<q).toScriptNum();tt!==void 0&&St.length>tt&&a(this,h,K).call(this,"script number overflow"),a(this,h,lt).call(this,St)})();break}case x.OP_RSHIFTNUM:{(()=>{this.stack.length<2&&a(this,h,K).call(this,"OP_RSHIFTNUM requires at least two items to be on the stack.");let q=a(this,h,le).call(this,a(this,h,Q).call(this)).toBigInt();q<0&&a(this,h,K).call(this,"OP_RSHIFTNUM bits to shift must not be negative."),q>0x7fffffffn&&a(this,h,K).call(this,"OP_RSHIFTNUM shift count exceeds INT_MAX.");let z=a(this,h,le).call(this,a(this,h,Q).call(this)).toBigInt(),tt;z<0?tt=new T(-(-z>>q)):tt=new T(z>>q),a(this,h,lt).call(this,tt.toScriptNum())})();break}case x.OP_1NEGATE:a(this,h,Re).call(this,Cw);break;case x.OP_0:a(this,h,Re).call(this,Yh[0]);break;case x.OP_1:case x.OP_2:case x.OP_3:case x.OP_4:case x.OP_5:case x.OP_6:case x.OP_7:case x.OP_8:case x.OP_9:case x.OP_10:case x.OP_11:case x.OP_12:case x.OP_13:case x.OP_14:case x.OP_15:case x.OP_16:S=i-(x.OP_1-1),a(this,h,Re).call(this,Yh[S]);break;case x.OP_NOP:case x.OP_NOP1:break;case x.OP_CHECKLOCKTIMEVERIFY:a(this,h,Sp).call(this);break;case x.OP_CHECKSEQUENCEVERIFY:a(this,h,Ip).call(this);break;case x.OP_NOP9:case x.OP_NOP10:break;case x.OP_VERIF:case x.OP_VERNOTIF:(()=>{if(E=!1,r){if(this.stack.length<1&&a(this,h,K).call(this,"OP_VERIF and OP_VERNOTIF require at least one item on the stack when they are used!"),o=a(this,h,Q).call(this),o.length===4){let q=this.transactionVersion;c=[q&255,q>>>8&255,q>>>16&255,q>>>24&255],E=Zh(o,c)}i===x.OP_VERNOTIF&&(E=!E)}this.ifStack.push(E),this.elseStack.push(!1)})();break;case x.OP_IF:case x.OP_NOTIF:E=!1,r&&(this.stack.length<1&&a(this,h,K).call(this,"OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),s=a(this,h,Q).call(this),a(this,h,Et).call(this,"MINIMALIF")&&a(this,h,jn).call(this)&&s.length>0&&!(s.length===1&&s[0]===1)&&a(this,h,K).call(this,"OP_IF and OP_NOTIF require minimal truth values."),E=a(this,h,jr).call(this,s),i===x.OP_NOTIF&&(E=!E)),this.ifStack.push(E),this.elseStack.push(!1);break;case x.OP_ELSE:this.ifStack.length===0&&a(this,h,K).call(this,"OP_ELSE requires a preceeding OP_IF."),a(this,h,Mt).call(this)&&a(this,h,se).call(this)&&this.elseStack.at(-1)===!0&&a(this,h,K).call(this,"OP_ELSE may only be used once for each OP_IF or OP_NOTIF after Genesis."),this.elseStack[this.elseStack.length-1]=!0,this.ifStack[this.ifStack.length-1]=this.ifStack.at(-1)!==!0;break;case x.OP_ENDIF:this.ifStack.length===0&&a(this,h,K).call(this,"OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop(),this.elseStack.pop();break;case x.OP_VERIFY:this.stack.length<1&&a(this,h,K).call(this,"OP_VERIFY requires at least one item to be on the stack."),o=a(this,h,Kt).call(this),E=a(this,h,jr).call(this,o),E||a(this,h,K).call(this,"OP_VERIFY requires the top stack value to be truthy."),a(this,h,Q).call(this);break;case x.OP_RETURN:a(this,h,Mt).call(this)&&!a(this,h,se).call(this)&&a(this,h,K).call(this,"OP_RETURN is invalid before Genesis."),this.ifStack.length>0?this.returningFromConditional=!0:(this.context==="UnlockingScript"?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.programCounter--);break;case x.OP_TOALTSTACK:a(this,h,vt).call(this,1,"OP_TOALTSTACK requires at oeast one item to be on the stack."),a(this,h,ap).call(this,a(this,h,Q).call(this));break;case x.OP_FROMALTSTACK:a(this,h,sp).call(this,1,"OP_FROMALTSTACK requires at least one item to be on the stack."),a(this,h,lt).call(this,a(this,h,cp).call(this));break;case x.OP_2DROP:a(this,h,vt).call(this,2,"OP_2DROP requires at least two items to be on the stack."),a(this,h,Q).call(this),a(this,h,Q).call(this);break;case x.OP_2DUP:a(this,h,vt).call(this,2,"OP_2DUP requires at least two items to be on the stack."),o=a(this,h,Kt).call(this,-2),c=a(this,h,Kt).call(this,-1),a(this,h,Re).call(this,o),a(this,h,Re).call(this,c);break;case x.OP_3DUP:a(this,h,vt).call(this,3,"OP_3DUP requires at least three items to be on the stack."),o=a(this,h,Kt).call(this,-3),c=a(this,h,Kt).call(this,-2),u=a(this,h,Kt).call(this,-1),a(this,h,Re).call(this,o),a(this,h,Re).call(this,c),a(this,h,Re).call(this,u);break;case x.OP_2OVER:a(this,h,vt).call(this,4,"OP_2OVER requires at least four items to be on the stack."),o=a(this,h,Kt).call(this,-4),c=a(this,h,Kt).call(this,-3),a(this,h,Re).call(this,o),a(this,h,Re).call(this,c);break;case x.OP_2ROT:{a(this,h,vt).call(this,6,"OP_2ROT requires at least six items to be on the stack.");let q=a(this,h,Q).call(this),z=a(this,h,Q).call(this),tt=a(this,h,Q).call(this),St=a(this,h,Q).call(this),ce=a(this,h,Q).call(this),Bt=a(this,h,Q).call(this);a(this,h,lt).call(this,St),a(this,h,lt).call(this,tt),a(this,h,lt).call(this,z),a(this,h,lt).call(this,q),a(this,h,lt).call(this,Bt),a(this,h,lt).call(this,ce);break}case x.OP_2SWAP:{a(this,h,vt).call(this,4,"OP_2SWAP requires at least four items to be on the stack.");let q=a(this,h,Q).call(this),z=a(this,h,Q).call(this),tt=a(this,h,Q).call(this),St=a(this,h,Q).call(this);a(this,h,lt).call(this,z),a(this,h,lt).call(this,q),a(this,h,lt).call(this,St),a(this,h,lt).call(this,tt);break}case x.OP_IFDUP:a(this,h,vt).call(this,1,"OP_IFDUP requires at least one item to be on the stack."),o=a(this,h,Kt).call(this),a(this,h,jr).call(this,o)&&a(this,h,Re).call(this,o);break;case x.OP_DEPTH:a(this,h,lt).call(this,new T(this.stack.length).toScriptNum());break;case x.OP_DROP:a(this,h,vt).call(this,1,"OP_DROP requires at least one item to be on the stack."),a(this,h,Q).call(this);break;case x.OP_DUP:a(this,h,vt).call(this,1,"OP_DUP requires at least one item to be on the stack."),a(this,h,Re).call(this,a(this,h,Kt).call(this));break;case x.OP_NIP:a(this,h,vt).call(this,2,"OP_NIP requires at least two items to be on the stack."),c=a(this,h,Q).call(this),a(this,h,Q).call(this),a(this,h,lt).call(this,c);break;case x.OP_OVER:a(this,h,vt).call(this,2,"OP_OVER requires at least two items to be on the stack."),a(this,h,Re).call(this,a(this,h,Kt).call(this,-2));break;case x.OP_PICK:case x.OP_ROLL:{(()=>{a(this,h,vt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),p=a(this,h,le).call(this,a(this,h,Q).call(this));let q=p.toBigInt();(q<0n||q>=BigInt(this.stack.length))&&a(this,h,K).call(this,`${x[i]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);let z=Number(q),tt=this.stack[this.stack.length-1-z];i===x.OP_ROLL?(this.stack.splice(this.stack.length-1-z,1),this.stackMem-=tt.length,a(this,h,lt).call(this,tt)):a(this,h,Re).call(this,tt)})();break}case x.OP_ROT:a(this,h,vt).call(this,3,"OP_ROT requires at least three items to be on the stack."),l=a(this,h,Q).call(this),d=a(this,h,Q).call(this),f=a(this,h,Q).call(this),a(this,h,lt).call(this,d),a(this,h,lt).call(this,l),a(this,h,lt).call(this,f);break;case x.OP_SWAP:a(this,h,vt).call(this,2,"OP_SWAP requires at least two items to be on the stack."),d=a(this,h,Q).call(this),f=a(this,h,Q).call(this),a(this,h,lt).call(this,d),a(this,h,lt).call(this,f);break;case x.OP_TUCK:a(this,h,vt).call(this,2,"OP_TUCK requires at least two items to be on the stack."),o=a(this,h,Kt).call(this,-1),a(this,h,wo).call(this,o.length),this.stack.splice(-2,0,o.slice()),this.stackMem+=o.length;break;case x.OP_SIZE:a(this,h,vt).call(this,1,"OP_SIZE requires at least one item to be on the stack."),a(this,h,lt).call(this,new T(a(this,h,Kt).call(this).length).toScriptNum());break;case x.OP_AND:case x.OP_OR:case x.OP_XOR:{(()=>{a(this,h,vt).call(this,2,`${x[i]} requires at least two items on the stack.`),c=a(this,h,Q).call(this),o=a(this,h,Q).call(this),o.length!==c.length&&a(this,h,K).call(this,`${x[i]} requires the top two stack items to be the same size.`);let q=Array.from({length:o.length},()=>0);for(let z=0;z<o.length;z++)i===x.OP_AND?q[z]=o[z]&c[z]:i===x.OP_OR?q[z]=o[z]|c[z]:q[z]=o[z]^c[z];a(this,h,lt).call(this,q)})();break}case x.OP_INVERT:{(()=>{a(this,h,vt).call(this,1,"OP_INVERT requires at least one item to be on the stack."),s=a(this,h,Q).call(this);let q=Array.from({length:s.length},()=>0);for(let z=0;z<s.length;z++)q[z]=~s[z]&255;a(this,h,lt).call(this,q)})();break}case x.OP_LSHIFT:case x.OP_RSHIFT:{(()=>{a(this,h,vt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),g=a(this,h,le).call(this,a(this,h,Q).call(this)),o=a(this,h,Q).call(this);let q=g.toBigInt();if(q<0n&&a(this,h,K).call(this,`${x[i]} requires the top item on the stack not to be negative.`),o.length===0){a(this,h,lt).call(this,[]);return}if(q>=BigInt(o.length)*8n){a(this,h,lt).call(this,Array.from({length:o.length},()=>0));return}m=new T(o);let z;if(i===x.OP_LSHIFT){z=m.ushln(q);let St=new T(1).ushln(o.length*8).isubn(1);z=z.iand(St)}else z=m.ushrn(q);let tt=z.toArray("be",o.length);a(this,h,lt).call(this,tt)})();break}case x.OP_EQUAL:case x.OP_EQUALVERIFY:a(this,h,vt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),c=a(this,h,Q).call(this),o=a(this,h,Q).call(this),E=Zh(o,c),a(this,h,lt).call(this,E?[1]:[]),i===x.OP_EQUALVERIFY&&(E||a(this,h,K).call(this,"OP_EQUALVERIFY requires the top two stack items to be equal."),a(this,h,Q).call(this));break;case x.OP_1ADD:case x.OP_1SUB:case x.OP_2MUL:case x.OP_2DIV:case x.OP_NEGATE:case x.OP_ABS:case x.OP_NOT:case x.OP_0NOTEQUAL:(()=>{switch(a(this,h,vt).call(this,1,`${x[i]} requires at least one item to be on the stack.`),p=a(this,h,le).call(this,a(this,h,Q).call(this)),i){case x.OP_1ADD:p=p.add(new T(1));break;case x.OP_1SUB:p=p.sub(new T(1));break;case x.OP_2MUL:p=p.mul(new T(2));break;case x.OP_2DIV:p=p.div(new T(2));break;case x.OP_NEGATE:p=p.neg();break;case x.OP_ABS:p.isNeg()&&(p=p.neg());break;case x.OP_NOT:p=new T(p.cmpn(0)===0?1:0);break;case x.OP_0NOTEQUAL:p=new T(p.cmpn(0)===0?0:1);break}a(this,h,lt).call(this,p.toScriptNum())})();break;case x.OP_ADD:case x.OP_SUB:case x.OP_MUL:case x.OP_DIV:case x.OP_MOD:case x.OP_BOOLAND:case x.OP_BOOLOR:case x.OP_NUMEQUAL:case x.OP_NUMEQUALVERIFY:case x.OP_NUMNOTEQUAL:case x.OP_LESSTHAN:case x.OP_GREATERTHAN:case x.OP_LESSTHANOREQUAL:case x.OP_GREATERTHANOREQUAL:case x.OP_MIN:case x.OP_MAX:{(()=>{a(this,h,vt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),c=a(this,h,Q).call(this),o=a(this,h,Q).call(this),g=a(this,h,le).call(this,c),m=a(this,h,le).call(this,o);let q=(()=>{switch(i){case x.OP_MUL:return m.byteLength()+g.byteLength();case x.OP_ADD:case x.OP_SUB:return Math.max(m.byteLength(),g.byteLength())+1;default:return Math.max(m.byteLength(),g.byteLength())}})();a(this,h,wo).call(this,q);let z=(()=>{switch(i){case x.OP_ADD:return m.add(g);case x.OP_SUB:return m.sub(g);case x.OP_MUL:return m.mul(g);case x.OP_DIV:return g.cmpn(0)===0&&a(this,h,K).call(this,"OP_DIV cannot divide by zero!"),m.div(g);case x.OP_MOD:return g.cmpn(0)===0&&a(this,h,K).call(this,"OP_MOD cannot divide by zero!"),m.mod(g);case x.OP_BOOLAND:return Lw(m.cmpn(0)!==0,g.cmpn(0)!==0);case x.OP_BOOLOR:return Uw(m.cmpn(0)!==0,g.cmpn(0)!==0);case x.OP_NUMEQUAL:case x.OP_NUMEQUALVERIFY:return vi(m.cmp(g)===0);case x.OP_NUMNOTEQUAL:return vi(m.cmp(g)!==0);case x.OP_LESSTHAN:return vi(m.cmp(g)<0);case x.OP_GREATERTHAN:return vi(m.cmp(g)>0);case x.OP_LESSTHANOREQUAL:return vi(m.cmp(g)<=0);case x.OP_GREATERTHANOREQUAL:return vi(m.cmp(g)>=0);case x.OP_MIN:return Mw(m,g);case x.OP_MAX:return Dw(m,g);default:return new T(0)}})();a(this,h,lt).call(this,z.toScriptNum()),i===x.OP_NUMEQUALVERIFY&&(a(this,h,jr).call(this,a(this,h,Kt).call(this))||a(this,h,K).call(this,"OP_NUMEQUALVERIFY requires the top stack item to be truthy."),a(this,h,Q).call(this))})();break}case x.OP_WITHIN:a(this,h,vt).call(this,3,"OP_WITHIN requires at least three items to be on the stack."),w=a(this,h,le).call(this,a(this,h,Q).call(this)),g=a(this,h,le).call(this,a(this,h,Q).call(this)),m=a(this,h,le).call(this,a(this,h,Q).call(this)),E=m.cmp(g)>=0&&m.cmp(w)<0,a(this,h,lt).call(this,E?[1]:[]);break;case x.OP_RIPEMD160:case x.OP_SHA1:case x.OP_SHA256:case x.OP_HASH160:case x.OP_HASH256:{(()=>{a(this,h,vt).call(this,1,`${x[i]} requires at least one item to be on the stack.`),s=a(this,h,Q).call(this);let q=[];i===x.OP_RIPEMD160?q=$u(s):i===x.OP_SHA1?q=qu(s):i===x.OP_SHA256?q=Te(s):i===x.OP_HASH160?q=Js(s):i===x.OP_HASH256&&(q=zt(s)),a(this,h,lt).call(this,q)})();break}case x.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case x.OP_CHECKSIG:case x.OP_CHECKSIGVERIFY:{a(this,h,vt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),_=a(this,h,Q).call(this),B=a(this,h,Q).call(this),(!a(this,h,hf).call(this,B)||!a(this,h,bf).call(this,_))&&a(this,h,K).call(this,`${x[i]} requires correct encoding for the public key and signature.`),A=(()=>{if(B.length===0)return!1;try{H=a(this,h,pf).call(this,B);let z=(this.context==="UnlockingScript"?this.unlockingScript:this.lockingScript).chunks.slice(this.lastCodeSeparator===null?0:this.lastCodeSeparator+1);return this.context==="UnlockingScript"&&(z=z.concat(this.lockingScript.chunks)),k=new me(z),((H.scope&wt.SIGHASH_FORKID)===0||a(this,h,Mt).call(this)&&!a(this,h,Et).call(this,"SIGHASH_FORKID"))&&k.findAndDelete(new me().writeBin(B)),O=Ht.fromDER(_),a(this,h,wf).call(this,H,O,k)}catch{return!1}})(),!A&&a(this,h,Et).call(this,"NULLFAIL")&&a(this,h,jn).call(this)&&B.length>0&&a(this,h,K).call(this,`${x[i]} requires failing signatures to be empty.`),a(this,h,lt).call(this,A?[1]:[]),i===x.OP_CHECKSIGVERIFY&&(A||a(this,h,K).call(this,"OP_CHECKSIGVERIFY requires that a valid signature is provided."),a(this,h,Q).call(this));break}case x.OP_CHECKMULTISIG:case x.OP_CHECKMULTISIGVERIFY:{(()=>{I=1,this.stack.length<I&&a(this,h,K).call(this,`${x[i]} requires at least 1 item for nKeys.`);let z=a(this,h,le).call(this,a(this,h,Kt).call(this,-I)).toBigInt(),tt=a(this,h,Mt).call(this)&&!a(this,h,se).call(this)?BigInt(Bw):Nw;(z<0n||z>tt)&&a(this,h,K).call(this,`${x[i]} requires a key count between 0 and ${tt.toString()}.`),F=Number(z);let St=F;U=++I,I+=F,this.stack.length<I&&a(this,h,K).call(this,`${x[i]} stack too small for nKeys and keys. Need ${I}, have ${this.stack.length}.`);let Bt=a(this,h,le).call(this,a(this,h,Kt).call(this,-I)).toBigInt();(Bt<0n||Bt>BigInt(F))&&a(this,h,K).call(this,`${x[i]} requires the number of signatures to be no greater than the number of keys.`),it=Number(Bt);let dn=it;M=++I,I+=it,this.stack.length<I&&a(this,h,K).call(this,`${x[i]} stack too small for N, keys, M, sigs, and dummy. Need ${I}, have ${this.stack.length}.`);let xe=(this.context==="UnlockingScript"?this.unlockingScript:this.lockingScript).chunks.slice(this.lastCodeSeparator===null?0:this.lastCodeSeparator+1);k=new me(xe);let vn=!1;for(let $=0;$<it;$++)B=a(this,h,Kt).call(this,-M-$),B.length>0&&(vn=!0),((B.at(-1)&wt.SIGHASH_FORKID)===0||a(this,h,Mt).call(this)&&!a(this,h,Et).call(this,"SIGHASH_FORKID"))&&k.findAndDelete(new me().writeBin(B));(()=>{for(A=!0;A&&it>0;){if(F===0){A=!1;break}if(B=a(this,h,Kt).call(this,-M),_=a(this,h,Kt).call(this,-U),(!a(this,h,hf).call(this,B)||!a(this,h,bf).call(this,_))&&a(this,h,K).call(this,`${x[i]} requires correct encoding for the public key and signature.`),ot=!1,B.length>0)try{H=a(this,h,pf).call(this,B),O=Ht.fromDER(_),ot=a(this,h,wf).call(this,H,O,k)}catch{ot=!1}ot&&(M++,it--),U++,F--,it>F&&(A=!1)}})(),(()=>{!A&&a(this,h,Et).call(this,"NULLFAIL")&&a(this,h,jn).call(this)&&vn&&a(this,h,K).call(this,`${x[i]} requires failing signatures to be empty.`);let W=1+St+1+dn+1-1;for(;W>0;)a(this,h,Q).call(this),W--;a(this,h,vt).call(this,1,`${x[i]} requires an extra item (dummy) to be on the stack.`);let D=a(this,h,Q).call(this);a(this,h,ep).call(this)&&D.length>0&&a(this,h,K).call(this,`${x[i]} requires the extra stack item (dummy) to be empty.`),a(this,h,lt).call(this,A?[1]:[]),i===x.OP_CHECKMULTISIGVERIFY&&(A||a(this,h,K).call(this,"OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),a(this,h,Q).call(this))})()})();break}case x.OP_CAT:{(()=>{a(this,h,vt).call(this,2,"OP_CAT requires at least two items to be on the stack."),c=a(this,h,Q).call(this),o=a(this,h,Q).call(this);let q=o.concat(c);q.length>a(this,h,Xr).call(this)&&a(this,h,K).call(this,`It's not currently possible to push data larger than ${a(this,h,Xr).call(this)} bytes.`),a(this,h,lt).call(this,q)})();break}case x.OP_SPLIT:{(()=>{a(this,h,vt).call(this,2,"OP_SPLIT requires at least two items to be on the stack.");let q=a(this,h,Q).call(this),z=a(this,h,Q).call(this),tt=a(this,h,le).call(this,q).toBigInt();(tt<0n||tt>BigInt(z.length))&&a(this,h,K).call(this,"OP_SPLIT requires the first stack item to be a non-negative number less than or equal to the size of the second-from-top stack item.");let St=Number(tt);a(this,h,lt).call(this,z.slice(0,St)),a(this,h,lt).call(this,z.slice(St))})();break}case x.OP_NUM2BIN:{(()=>{a(this,h,vt).call(this,2,"OP_NUM2BIN requires at least two items to be on the stack.");let q=a(this,h,le).call(this,a(this,h,Q).call(this)).toBigInt(),z=a(this,h,Xr).call(this);if((Number.isFinite(z)&&q>BigInt(z)||q<0n)&&a(this,h,K).call(this,`It's not currently possible to push data larger than ${z} bytes or negative size.`),q>Tw&&a(this,h,K).call(this,"OP_NUM2BIN size exceeds the node int32 push limit."),this.hasExplicitMemoryLimit&&Number.isFinite(this.memoryLimit)){let Bt=Math.max(0,Math.floor(this.memoryLimit));if(q>BigInt(Bt))throw new Xn("element-size",Bt,q)}C=Number(q);let tt=a(this,h,Q).call(this);if(tt=Ra(tt),tt.length>C&&a(this,h,K).call(this,"OP_NUM2BIN requires that the size expressed in the top stack item is large enough to hold the value expressed in the second-from-top stack item."),tt.length===C){a(this,h,lt).call(this,tt);return}let St=Array.from({length:C},()=>0),ce=0;tt.length>0&&(ce=tt.at(-1)&128,tt[tt.length-1]&=127);for(let Bt=0;Bt<tt.length;Bt++)St[Bt]=tt[Bt];ce!==0&&(St[C-1]|=128),a(this,h,lt).call(this,St)})();break}case x.OP_BIN2NUM:{(()=>{a(this,h,vt).call(this,1,"OP_BIN2NUM requires at least one item to be on the stack."),o=a(this,h,Q).call(this);let q=Ra(o);Qh(q)||a(this,h,K).call(this,"OP_BIN2NUM requires that the resulting number is valid."),a(this,h,lt).call(this,q)})();break}default:a(this,h,K).call(this,`Invalid opcode ${i} (pc=${this.programCounter}).`)}}return a(this,h,vp).call(this,t),!0}validate(t){let e=Da(),i=a(this,h,yf).call(this),r=t===void 0?void 0:Jh(t);return e?.verifySpendSync!==void 0&&(e.isReady?.()??!0)&&(r===void 0?e.shouldVerifySpend?.(i):e.shouldVerifySpend?.(i,r))!==!1?((r===void 0?e.verifySpendSync(i):e.verifySpendSync(i,r))!==!0&&a(this,h,K).call(this,"The selected script-verification backend rejected the spend."),!0):this.validateJavaScript()}validateJavaScript(){this.reset(),a(this,h,np).call(this)&&!this.unlockingScript.isPushOnly()&&a(this,h,K).call(this,"Unlocking scripts can only contain push operations, and no other opcodes.");let t=this.lockingScript,e=a(this,h,Et).call(this,"P2SH")&&!a(this,h,se).call(this)&&a(this,h,Ap).call(this,this.lockingScript);e&&!this.unlockingScript.isPushOnly()&&a(this,h,K).call(this,"P2SH unlocking scripts can only contain push operations."),a(this,h,qa).call(this,"UnlockingScript");let i=this.stack.map(r=>r.slice());a(this,h,qa).call(this,"LockingScript"),a(this,h,xf).call(this);try{if(e){i.length===0&&a(this,h,K).call(this,"P2SH evaluation requires a redeem script on the stack.");let r=i.pop();if(r===void 0)return a(this,h,K).call(this,"P2SH evaluation requires a redeem script on the stack."),!1;a(this,h,op).call(this,i);let s=me.fromBinary(r);this.lockingScript=new Le(s.chunks),a(this,h,qa).call(this,"LockingScript")}}finally{this.lockingScript=t}return a(this,h,ip).call(this)&&this.stack.length!==1&&a(this,h,K).call(this,`The clean stack rule requires exactly one item to be on the stack after script execution, found ${this.stack.length}.`),a(this,h,xf).call(this),!0}async validateWith(t,e){let i=a(this,h,yf).call(this),r=e===void 0?void 0:Jh(e),s=r===void 0?t.shouldVerifySpend?.(i):t.shouldVerifySpend?.(i,r);if(s!==void 0&&typeof s!="boolean")throw new TypeError("Spend verifier selection must be boolean");if(s===!1)return i.validateJavaScript();let o=r===void 0?await t.verifySpend(i):await t.verifySpend(i,r);if(typeof o!="boolean")throw new TypeError("Spend verifier returned a non-boolean verdict");return o}toTransactionUint8Array(){let t={sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,unlockingScript:this.unlockingScript,sequence:this.inputSequence},e=this.allInputs??[...this.otherInputs.slice(0,this.inputIndex),t,...this.otherInputs.slice(this.inputIndex)];if(this.inputIndex<0||this.inputIndex>=e.length)throw new RangeError("Spend input index is out of range");let i=new ht;i.writeUInt32LE(this.transactionVersion),i.writeVarIntNum(e.length);for(let r=0;r<e.length;r++){let s=r===this.inputIndex?t:e[r],o=s.sourceTXID??s.sourceTransaction?.id("hex");if(o===void 0)throw new Error(`Input ${r} is missing its source transaction ID`);if(s.unlockingScript===void 0)throw new Error(`Input ${r} is missing its unlocking script`);i.writeReverse(at(o,"hex")),i.writeUInt32LE(s.sourceOutputIndex);let c=s.unlockingScript.toUint8Array();i.writeVarIntNum(c.length),i.write(c),i.writeUInt32LE(s.sequence??4294967295)}i.writeVarIntNum(this.outputs.length);for(let r of this.outputs){i.writeUInt64LE(r.satoshis??0);let s=r.lockingScript.toUint8Array();i.writeVarIntNum(s.length),i.write(s)}return i.writeUInt32LE(this.lockTime),i.toUint8Array()}};Gn=new WeakMap,So=new WeakMap,h=new WeakSet,Ii=function(){return this.isRelaxedOverride||this.transactionVersion>1},Mt=function(){return this.verifyFlags!==void 0},Et=function(t){return this.verifyFlags?.has(t)===!0},se=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"UTXO_AFTER_GENESIS")||a(this,h,Et).call(this,"UTXO_AFTER_CHRONICLE"):a(this,h,Ii).call(this)},mo=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"UTXO_AFTER_CHRONICLE"):a(this,h,Ii).call(this)},jn=function(){return!(a(this,h,Et).call(this,"CHRONICLE")&&this.transactionVersion>1)},bo=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"MINIMALDATA")&&a(this,h,jn).call(this):!a(this,h,Ii).call(this)},tp=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"LOW_S")&&a(this,h,jn).call(this):!a(this,h,Ii).call(this)},ep=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"NULLDUMMY")&&a(this,h,jn).call(this):!a(this,h,Ii).call(this)},np=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"SIGPUSHONLY")&&a(this,h,jn).call(this):!a(this,h,Ii).call(this)},ip=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"CLEANSTACK")&&a(this,h,jn).call(this):!a(this,h,Ii).call(this)},ff=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"DERSIG")||a(this,h,Et).call(this,"STRICTENC")||a(this,h,Et).call(this,"LOW_S")||a(this,h,Et).call(this,"SIGHASH_FORKID"):!0},df=function(){return a(this,h,Mt).call(this)?a(this,h,Et).call(this,"STRICTENC")||a(this,h,Et).call(this,"SIGHASH_FORKID"):!0},Ha=function(){if(a(this,h,Mt).call(this))return a(this,h,se).call(this)?a(this,h,mo).call(this)?Pw:Ow:4},Xr=function(){return a(this,h,Mt).call(this)&&!a(this,h,se).call(this)?kw:Number.POSITIVE_INFINITY},wo=function(t){if(this.stackMem+t>this.memoryLimit)throw new Xn("stack",this.memoryLimit,this.stackMem+t)},rp=function(t){if(this.altStackMem+t>this.memoryLimit)throw new Xn("alt-stack",this.memoryLimit,this.altStackMem+t)},lt=function(t){a(this,h,wo).call(this,t.length),this.stack.push(t),this.stackMem+=t.length},Re=function(t){a(this,h,wo).call(this,t.length);let e=t.slice();this.stack.push(e),this.stackMem+=e.length},Q=function(){this.stack.length===0&&a(this,h,K).call(this,"Attempted to pop from an empty stack.");let t=this.stack.pop();return t===void 0?(a(this,h,K).call(this,"Attempted to pop from an empty stack."),[]):(this.stackMem-=t.length,t)},Kt=function(t=-1){return(this.stack.length===0||this.stack.length<Math.abs(t)||t>=0&&t>=this.stack.length)&&a(this,h,K).call(this,`Stack underflow accessing element at index ${t}. Stack length is ${this.stack.length}.`),this.stack[this.stack.length+t]},vt=function(t,e){this.stack.length<t&&a(this,h,K).call(this,e)},sp=function(t,e){this.altStack.length<t&&a(this,h,K).call(this,e)},op=function(t){this.stack=t.map(e=>e.slice()),this.stackMem=this.stack.reduce((e,i)=>e+i.length,0)},$a=function(){this.altStack=[],this.altStackMem=0},ap=function(t){a(this,h,rp).call(this,t.length),this.altStack.push(t),this.altStackMem+=t.length},cp=function(){this.altStack.length===0&&a(this,h,K).call(this,"Attempted to pop from an empty alt stack.");let t=this.altStack.pop();return t===void 0?(a(this,h,K).call(this,"Attempted to pop from an empty alt stack."),[]):(this.altStackMem-=t.length,t)},le=function(t){try{return T.fromScriptNum(t,a(this,h,bo).call(this),a(this,h,Ha).call(this))}catch(e){let i=e instanceof Error?e.message:String(e);a(this,h,K).call(this,i)}return new T(0)},yo=function(t){let e=a(this,h,Ha).call(this);e!==void 0&&t.length>e&&a(this,h,K).call(this,"script number overflow"),a(this,h,bo).call(this)&&!Qh(t)&&a(this,h,K).call(this,"non-minimally encoded script number");let i;if(t.length>8){i=0n;for(let r=0;r<8;r++)i|=BigInt(t[r])<<BigInt(r*8);i=BigInt.asIntN(64,i)}else i=a(this,h,le).call(this,t).toBigInt();return i>0x7fffffffn?2147483647:i<-0x80000000n?-2147483648:Number(i)},lf=function(t){try{return T.fromScriptNum(t,a(this,h,bo).call(this),5).toBigInt()}catch(e){a(this,h,K).call(this,e instanceof Error?e.message:String(e))}return 0n},up=function(t){let e=t&31;return e>=wt.SIGHASH_ALL&&e<=wt.SIGHASH_SINGLE},fp=function(t){if(!a(this,h,df).call(this))return;a(this,h,up).call(this,t.scope)||a(this,h,K).call(this,"The signature hash type is invalid.");let e=(t.scope&wt.SIGHASH_CHRONICLE)!==0,i=a(this,h,Mt).call(this)?a(this,h,Et).call(this,"CHRONICLE"):a(this,h,mo).call(this);e&&!i&&a(this,h,K).call(this,"The signature hash type is invalid before Chronicle.")},dp=function(t){if(!a(this,h,Mt).call(this)||!a(this,h,Et).call(this,"STRICTENC"))return;let e=(t.scope&wt.SIGHASH_FORKID)!==0;a(this,h,Et).call(this,"SIGHASH_FORKID")&&!e&&a(this,h,K).call(this,"The signature must use SIGHASH_FORKID."),!a(this,h,Et).call(this,"SIGHASH_FORKID")&&!a(this,h,se).call(this)&&e&&a(this,h,K).call(this,"The signature must not use SIGHASH_FORKID.")},hf=function(t){if(t.length===0)return!0;let e=a(this,h,ff).call(this);if(e&&!Hw(t))return a(this,h,K).call(this,"The signature format is invalid."),!1;try{let i=wt.fromChecksigFormat(t);if(a(this,h,fp).call(this,i),a(this,h,dp).call(this,i),a(this,h,tp).call(this)&&!i.hasLowS())return a(this,h,K).call(this,"The signature must have a low S value."),!1}catch{if(e)return a(this,h,K).call(this,"The signature format is invalid."),!1}return!0},pf=function(t){try{return wt.fromChecksigFormat(t)}catch(e){if(a(this,h,ff).call(this))throw e;return a(this,h,lp).call(this,t)}},gf=function(t,e){let i=t[e.value++];if(i===void 0)throw new Error("Invalid DER length");if((i&128)===0)return i;let r=i&127;if(r===0||e.value+r>t.length)throw new Error("Invalid DER length");let s=0;for(let o=0;o<r;o++)s=s<<8|(t[e.value++]??0);return s},mf=function(t,e,i){if(e.value>=i||t[e.value++]!==2)throw new Error("Invalid DER integer");let r=a(this,h,gf).call(this,t,e);if(e.value+r>i)throw new Error("Invalid DER integer length");let s=t.slice(e.value,e.value+r);for(e.value+=r;s.length>1&&s[0]===0;)s=s.slice(1);return s.length===0&&(s=[0]),new T(s)},lp=function(t){if(t.length===0)return wt.fromChecksigFormat(t);let e=t.at(-1),i=t.slice(0,-1),r={value:0};if(i[r.value++]!==48)throw new Error("Signature DER must start with 0x30");let s=a(this,h,gf).call(this,i,r),o=Math.min(r.value+s,i.length),c=a(this,h,mf).call(this,i,r,o),u=a(this,h,mf).call(this,i,r,o);return new wt(c,u,e)},bf=function(t){if(!a(this,h,df).call(this))return!0;if(t.length===0)return a(this,h,K).call(this,"Public key is empty."),!1;if(t.length<33)return a(this,h,K).call(this,"The public key is too short, it must be at least 33 bytes."),!1;if(t[0]===4){if(t.length!==65)return a(this,h,K).call(this,"The non-compressed public key must be 65 bytes."),!1}else if(t[0]===2||t[0]===3){if(t.length!==33)return a(this,h,K).call(this,"The compressed public key must be 33 bytes."),!1}else return a(this,h,K).call(this,"The public key is in an unknown format."),!1;try{Ht.fromDER(t)}catch{return a(this,h,K).call(this,"The public key is in an unknown format."),!1}return!0},wf=function(t,e,i){let r={sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,transactionVersion:this.transactionVersion,otherInputs:this.otherInputs,allInputs:this.allInputs,outputs:this.outputs,inputIndex:this.inputIndex,subscript:i,inputSequence:this.inputSequence,lockTime:this.lockTime,scope:t.scope,sighashForkIdEnabled:!a(this,h,Mt).call(this)||a(this,h,Et).call(this,"SIGHASH_FORKID"),cache:y(this,Gn)},s=wt.usesOtdaSingleBug(r)?new T([1,...Array.from({length:31},()=>0)]):new T(zt(wt.formatBytes(r)));return Si(s,t,e)},hp=function(){if(this.stackMem>this.memoryLimit)throw new Xn("stack",this.memoryLimit,this.stackMem);if(this.altStackMem>this.memoryLimit)throw new Xn("alt-stack",this.memoryLimit,this.altStackMem)},pp=function(){return this.context==="UnlockingScript"&&this.programCounter>=this.unlockingScript.chunks.length&&(this.ifStack.length>0&&a(this,h,K).call(this,"Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the unlocking script."),a(this,h,$a).call(this),this.ifStack=[],this.elseStack=[],this.returningFromConditional=!1,this.lastCodeSeparator=null,this.context="LockingScript",this.programCounter=0),this.context==="UnlockingScript"?this.unlockingScript:this.lockingScript},gp=function(t){let e=t.op;return e===void 0?(a(this,h,K).call(this,`Missing opcode in ${this.context} at pc=${this.programCounter}.`),0):(t.invalidLength===!0&&a(this,h,K).call(this,`Malformed push data in ${this.context} at pc=${this.programCounter}.`),Array.isArray(t.data)&&t.data.length>a(this,h,Xr).call(this)&&a(this,h,K).call(this,`Data push > ${a(this,h,Xr).call(this)} bytes (pc=${this.programCounter}).`),e)},mp=function(t){a(this,h,Mt).call(this)&&!a(this,h,se).call(this)&&!a(this,h,mo).call(this)&&(t===x.OP_2MUL||t===x.OP_2DIV||t===x.OP_VERIF||t===x.OP_VERNOTIF)&&a(this,h,K).call(this,`${x[t]} is disabled until Chronicle.`)},bp=function(t){a(this,h,bo).call(this)&&!$w(t)&&a(this,h,K).call(this,`This data is not minimally-encoded. (PC: ${this.programCounter})`),a(this,h,lt).call(this,Array.isArray(t.data)?t.data:[])},wp=function(t,e){!e||t<=x.OP_16||(this.executedOpCount++,a(this,h,Mt).call(this)&&!a(this,h,se).call(this)&&this.executedOpCount>zh&&a(this,h,K).call(this,`Script executed more than ${zh} opcodes.`))},yp=function(t,e){return!a(this,h,Mt).call(this)||a(this,h,mo).call(this)?!1:e&&(t===x.OP_SUBSTR||t===x.OP_LEFT||t===x.OP_RIGHT||t===x.OP_LSHIFTNUM||t===x.OP_RSHIFTNUM)?(a(this,h,Et).call(this,"DISCOURAGE_UPGRADABLE_NOPS")&&a(this,h,K).call(this,`${x[t]} is discouraged by verification flags.`),this.programCounter++,!0):((e||!a(this,h,se).call(this))&&(t===x.OP_2MUL||t===x.OP_2DIV)&&a(this,h,K).call(this,`${x[t]} is disabled until Chronicle.`),(e||!a(this,h,se).call(this))&&(t===x.OP_VER||t===x.OP_VERIF||t===x.OP_VERNOTIF)&&a(this,h,K).call(this,`${x[t]} is disabled until Chronicle.`),!e&&a(this,h,se).call(this)&&(t===x.OP_VERIF||t===x.OP_VERNOTIF)?(this.programCounter++,!0):!1)},xp=function(t,e){let i=t===x.OP_CHECKLOCKTIMEVERIFY&&(!a(this,h,Et).call(this,"CHECKLOCKTIMEVERIFY")||a(this,h,se).call(this)),r=t===x.OP_CHECKSEQUENCEVERIFY&&(!a(this,h,Et).call(this,"CHECKSEQUENCEVERIFY")||a(this,h,se).call(this));e&&a(this,h,Et).call(this,"DISCOURAGE_UPGRADABLE_NOPS")&&(t===x.OP_NOP1||i||r||t===x.OP_NOP9||t===x.OP_NOP10)&&a(this,h,K).call(this,`${x[t]} is discouraged by verification flags.`)},Sp=function(){if(!a(this,h,Et).call(this,"CHECKLOCKTIMEVERIFY")||a(this,h,se).call(this))return;a(this,h,vt).call(this,1,"OP_CHECKLOCKTIMEVERIFY requires one stack item.");let t=a(this,h,lf).call(this,a(this,h,Kt).call(this));t<0n&&a(this,h,K).call(this,"Negative lock time.");let e=t<BigInt(Gh),i=this.lockTime<Gh;(e!==i||t>BigInt(this.lockTime)||this.inputSequence===4294967295)&&a(this,h,K).call(this,"OP_CHECKLOCKTIMEVERIFY lock time is unsatisfied.")},Ip=function(){if(!a(this,h,Et).call(this,"CHECKSEQUENCEVERIFY")||a(this,h,se).call(this))return;a(this,h,vt).call(this,1,"OP_CHECKSEQUENCEVERIFY requires at least one item to be on the stack.");let t=a(this,h,lf).call(this,a(this,h,Kt).call(this));if(t<0n&&a(this,h,K).call(this,"OP_CHECKSEQUENCEVERIFY requires a non-negative lock time."),(t&BigInt(jh))!==0n)return;let e=BigInt(this.inputSequence>>>0),i=BigInt(uf|_w),r=t&i,s=e&i;(this.transactionVersion>>>0<2||(e&BigInt(jh))!==0n||(r&BigInt(uf))!==(s&BigInt(uf))||r>s)&&a(this,h,K).call(this,"OP_CHECKSEQUENCEVERIFY lock time is unsatisfied.")},vp=function(t){this.returningFromConditional&&this.ifStack.length===0?this.programCounter=t.chunks.length:this.programCounter++,a(this,h,Mt).call(this)&&!a(this,h,se).call(this)&&this.stack.length+this.altStack.length>Xh&&a(this,h,K).call(this,`Stack item count has exceeded ${Xh}.`)},yf=function(){let t=r=>new Le(r.chunks.map(s=>({op:s.op,data:s.data===void 0?void 0:Array.from(s.data),invalidLength:s.invalidLength}))),e=r=>new Ue(r.chunks.map(s=>({op:s.op,data:s.data===void 0?void 0:Array.from(s.data),invalidLength:s.invalidLength}))),i=r=>({sourceTXID:r.sourceTXID??r.sourceTransaction?.id("hex"),sourceOutputIndex:r.sourceOutputIndex,unlockingScript:r.unlockingScript===void 0?void 0:e(r.unlockingScript),sequence:r.sequence});return new Sf({sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,lockingScript:t(this.lockingScript),transactionVersion:this.transactionVersion,otherInputs:this.otherInputs.map(i),allInputs:this.allInputs?.map(i),outputs:this.outputs.map(r=>({satoshis:r.satoshis,lockingScript:t(r.lockingScript),change:r.change})),inputIndex:this.inputIndex,unlockingScript:e(this.unlockingScript),inputSequence:this.inputSequence,lockTime:this.lockTime,memoryLimit:this.hasExplicitMemoryLimit?this.memoryLimit:void 0,isRelaxed:this.isRelaxedOverride,verifyFlags:this.verifyFlags===void 0?void 0:Array.from(this.verifyFlags)})},qa=function(t){this.context=t,this.programCounter=0,this.ifStack=[],this.elseStack=[],this.returningFromConditional=!1,a(this,h,$a).call(this),this.lastCodeSeparator=null;let e=t==="UnlockingScript"?this.unlockingScript:this.lockingScript;for(a(this,h,Mt).call(this)&&!a(this,h,se).call(this)&&e.toUint8Array().length>Kh&&a(this,h,K).call(this,`Script size exceeds ${Kh} bytes.`);this.programCounter<e.chunks.length;)this.step();this.ifStack.length>0&&a(this,h,K).call(this,"Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the script."),this.ifStack=[],this.elseStack=[],a(this,h,$a).call(this),this.lastCodeSeparator=null},Ap=function(t){let e=t.chunks;return e.length===3&&e[0].op===x.OP_HASH160&&e[1].op===20&&Array.isArray(e[1].data)&&e[1].data.length===20&&e[2].op===x.OP_EQUAL},xf=function(){this.stack.length===0?a(this,h,K).call(this,"The top stack element must be truthy after script evaluation (stack is empty)."):a(this,h,jr).call(this,a(this,h,Kt).call(this))||a(this,h,K).call(this,"The top stack element must be truthy after script evaluation.")},jr=function(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(t[e]!==0)return!(e===t.length-1&&t[e]===128);return!1},K=function(t){throw new go({message:t,txid:this.sourceTXID,outputIndex:this.sourceOutputIndex,context:this.context,programCounter:this.programCounter,stackState:this.stack,altStackState:this.altStack,ifStackState:this.ifStack,stackMem:this.stackMem,altStackMem:this.altStackMem})};var xo=Sf;var qw=21e14,Fw=4294967295;function Fa(n,t){if(!Number.isSafeInteger(n)||n<0||n>Fw)throw new Error(`${t} must be an unsigned 32-bit integer`);return n}function If(n,t){if(!Number.isSafeInteger(n)||n<0||n>qw)throw new Error(`${t} must be a valid number of satoshis`);return n}function vf(n,t){if(typeof n!="string"||!/^[0-9a-fA-F]{64}$/.test(n))throw new Error(`${t} must be a 32-byte hexadecimal transaction ID`);return n.toLowerCase()}function Af(n,t){if(n==null||typeof n!="object"||typeof n.toHex!="function")throw new Error(`${t} must be a Script`);let e=n.toHex();if(typeof e!="string"||!/^(?:[0-9a-fA-F]{2})*$/.test(e))throw new Error(`${t} must serialize to a valid hexadecimal script`);return n}function Ep(n,t){if(n!=="all"&&n!=="none"&&n!=="single")throw new Error('signOutputs must be "all", "none", or "single"');if(typeof t!="boolean")throw new TypeError("anyoneCanPay must be a boolean");let e=wt.SIGHASH_FORKID;return n==="all"&&(e|=wt.SIGHASH_ALL),n==="none"&&(e|=wt.SIGHASH_NONE),n==="single"&&(e|=wt.SIGHASH_SINGLE),t&&(e|=wt.SIGHASH_ANYONECANPAY),e}function kp(n,t,e,i){if(n==null||!Array.isArray(n.inputs))throw new Error("A transaction with inputs is required for transaction signing.");if(!Number.isSafeInteger(t)||t<0||t>=n.inputs.length)throw new Error(`inputIndex ${t} is outside the transaction input range`);let r=n.inputs[t],s=Fa(r.sourceOutputIndex,"input.sourceOutputIndex"),o=r.sourceTXID===void 0?void 0:vf(r.sourceTXID,"input.sourceTXID"),c=r.sourceTransaction===void 0?void 0:vf(r.sourceTransaction.id("hex"),"input.sourceTransaction ID");if(o!==void 0&&c!==void 0&&o!==c)throw new Error("The input sourceTXID does not match the input sourceTransaction.");let u=o??c;if(u===void 0)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");let f=r.sourceTransaction?.outputs[s];if(r.sourceTransaction!==void 0&&f==null)throw new Error(`The input sourceTransaction has no output at index ${s}.`);let d=e===void 0?void 0:If(e,"sourceSatoshis"),l=f?.satoshis===void 0?void 0:If(f.satoshis,"sourceTransaction output satoshis");if(d!==void 0&&l!==void 0&&d!==l)throw new Error("The sourceSatoshis does not match the input sourceTransaction output.");let p=d??l;if(p===void 0)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");let m=i===void 0?void 0:Af(i,"lockingScript"),g=f?.lockingScript===void 0?void 0:Af(f.lockingScript,"sourceTransaction output lockingScript");if(m!==void 0&&g!==void 0&&m.toHex().toLowerCase()!==g.toHex().toLowerCase())throw new Error("The lockingScript does not match the input sourceTransaction output.");let w=m??g;if(w===void 0)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");return{sourceTXID:u,sourceSatoshis:p,lockingScript:w,allInputs:n.inputs,get otherInputs(){return n.inputs.filter((S,C)=>C!==t)}}}function Tp(n){let{tx:t,inputIndex:e,signatureScope:i,sourceTXID:r,sourceSatoshis:s,lockingScript:o,otherInputs:c,allInputs:u,inputSequence:f}=n,d=t.inputs[e];Fa(d.sourceOutputIndex,"input.sourceOutputIndex"),If(s,"sourceSatoshis"),vf(r,"sourceTXID"),Af(o,"lockingScript"),Fa(i,"signatureScope");let l=f??sr(d.sequence,"input.sequence must have value");return Fa(l,"inputSequence"),wt.format({sourceTXID:r,sourceOutputIndex:sr(d.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:s,transactionVersion:t.version,otherInputs:c??[],allInputs:u,inputIndex:e,outputs:t.outputs,inputSequence:l,subscript:o,lockTime:t.lockTime,scope:i,cache:t.getSignatureHashCache()})}var Yn=class{lock(t){let e;if(typeof t=="string"){let i=co(t);if(i.prefix.length!==1||i.prefix[0]!==0&&i.prefix[0]!==111)throw new Error("only P2PKH is supported");e=i.data}else{if(!Array.isArray(t))throw new Error("P2PKH hash must be a dense byte array");for(let i=0;i<t.length;i++){let r=t[i];if(!Number.isInteger(r)||r<0||r>255)throw new Error("P2PKH hash must be a dense byte array")}e=t}if(e.length!==20)throw new Error("P2PKH hash length must be 20 bytes");return new Le([{op:x.OP_DUP},{op:x.OP_HASH160},{op:e.length,data:e},{op:x.OP_EQUALVERIFY},{op:x.OP_CHECKSIG}])}unlock(t,e="all",i=!1,r,s){return{sign:async(o,c)=>{let u=Ep(e,i),f=kp(o,c,r,s),d=Tp({tx:o,inputIndex:c,signatureScope:u,sourceTXID:f.sourceTXID,sourceSatoshis:f.sourceSatoshis,lockingScript:f.lockingScript,allInputs:f.allInputs}),l=Te(d),p=cf("signDigest"),m=cf("publicKeyFromPrivate"),g=p===void 0&&m===void 0?void 0:Uint8Array.from(t.toArray("be",32)),w=m===void 0?t.toPublicKey().encode(!0):void 0,S=p===void 0?t.sign(l):ge.fromDER(Array.from(af("signDigest",await p.signDigest(g,Uint8Array.from(Te(l)))))),E=new wt(S.r,S.s,u).toChecksigFormat(),A=m===void 0?w:Array.from(Ww(await m.publicKeyFromPrivate(g)));return new Ue([{op:E.length,data:E},{op:A.length,data:A}])},estimateLength:async()=>108}}};function Ww(n){let t=af("publicKeyFromPrivate",n,33);if(t[0]!==2&&t[0]!==3)throw new Error("publicKeyFromPrivate returned an invalid compressed public key");return t}var Io=class{constructor(t){b(this,"value");Op(t),this.value=t}async computeFee(t){let e=this.value;Op(e);let i=o=>o>4294967295?9:o>65535?5:o>=253?3:1,r=4;r+=i(t.inputs.length);for(let o=0;o<t.inputs.length;o++){let c=t.inputs[o];r+=40;let u;if(typeof c.unlockingScript=="object")u=c.unlockingScript.toBinary().length;else if(typeof c.unlockingScriptTemplate=="object")u=await c.unlockingScriptTemplate.estimateLength(t,o);else throw new TypeError("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");if(!Number.isSafeInteger(u)||u<0)throw new RangeError("Unlocking script length must be a non-negative safe integer.");r+=i(u),r+=u}r+=i(t.outputs.length);for(let o of t.outputs){r+=8;let c=o.lockingScript.toBinary().length;if(!Number.isSafeInteger(c)||c<0)throw new RangeError("Locking script length must be a non-negative safe integer.");r+=i(c),r+=c}r+=4;let s=Math.ceil(r/1e3*e);if(!Number.isSafeInteger(s)||s<0||s>21e14)throw new RangeError("Computed transaction fee is outside the valid satoshi range.");return s}};function Op(n){if(!Number.isFinite(n)||n<0||n>21e14)throw new RangeError("Satoshis-per-kilobyte rate must be finite and non-negative.")}var Wa=8*1024*1024,Va=3e4;function Pp(n={}){let t=n.maxResponseBytes??Wa,e=n.timeoutMs??Va;if(!Number.isSafeInteger(t)||t<1)throw new RangeError("maxResponseBytes must be a positive safe integer");if(!Number.isSafeInteger(e)||e<1||e>10*6e4)throw new RangeError("timeoutMs must be an integer from 1 through 600000");return{maxResponseBytes:t,timeoutMs:e}}function Rp(n,t){let e=new AbortController,i=()=>e.abort(n?.reason);n?.aborted===!0?i():n?.addEventListener("abort",i,{once:!0});let r=setTimeout(()=>e.abort(new DOMException("HTTP request timed out","TimeoutError")),t);return{signal:e.signal,dispose(){clearTimeout(r),n?.removeEventListener("abort",i)}}}async function Np(n,t){let e=n,i=n.headers?.get?.("content-length")??null;if(i!==null&&(!/^(0|[1-9]\d*)$/.test(i)||Number(i)>t))throw await n.body?.cancel().catch(()=>{}),new Error("HTTP response exceeds the configured size limit");if(!("body"in e)){let f=await e.text?.()??"";if(Fe(f)>t)throw new Error("HTTP response exceeds the configured size limit");return f}if(n.body==null)return"";let r=n.body.getReader(),s=[],o=0;try{for(;;){let{done:f,value:d}=await r.read();if(f)break;if(o+=d.byteLength,!Number.isSafeInteger(o)||o>t)throw await r.cancel(),new Error("HTTP response exceeds the configured size limit");s.push(d)}}finally{r.releaseLock()}let c=new Uint8Array(o),u=0;for(let f of s)c.set(f,u),u+=f.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(c)}catch(f){throw new Error("HTTP response is not valid UTF-8",{cause:f})}}function Bp(n,t,e,i){return new Promise((r,s)=>{let o;try{o=e.data===null||e.data===void 0?void 0:i(e.data)}catch(S){s(S);return}let{data:c,...u}=e,f=!1,d,l,p=()=>{l!==void 0&&clearTimeout(l),e.signal?.removeEventListener("abort",w)},m=S=>{f||(f=!0,p(),s(S))},g=S=>{f||(f=!0,p(),r(S))},w=()=>{let S=e.signal?.reason instanceof Error?e.signal.reason:new DOMException("HTTP request aborted","AbortError");d?.destroy?.(S),m(S)};d=n.request(t,u,S=>{let C=S.headers?.["content-length"],E=typeof C=="string"?Number(C):void 0;if(typeof C=="string"&&!/^(0|[1-9]\d*)$/.test(C)||E!==void 0&&(!Number.isSafeInteger(E)||E>Wa)){S.destroy?.(),m(new Error("HTTP response exceeds the configured size limit"));return}let A=[],k=0;S.on("data",B=>{if(f)return;let _=typeof B=="string"?Se(B):new Uint8Array(B);if(k+=_.byteLength,!Number.isSafeInteger(k)||k>Wa){S.destroy?.(),d.destroy?.(),m(new Error("HTTP response exceeds the configured size limit"));return}A.push(_)}),S.on("end",()=>{if(!f)try{if(E!==void 0&&E!==k)throw new Error("HTTP response differs from its declared length");if(!Number.isInteger(S.statusCode)||S.statusCode<100||S.statusCode>599)throw new Error("HTTP response returned an invalid status code");let B=new Uint8Array(k),_=0;for(let M of A)B.set(M,_),_+=M.byteLength;let H=new TextDecoder("utf-8",{fatal:!0}).decode(B),O=S.statusCode>=200&&S.statusCode<=299,I=S.headers["content-type"],U=H!==""&&typeof I=="string"&&I.startsWith("application/json")?JSON.parse(H):H;g({status:S.statusCode,statusText:S.statusMessage??"",ok:O,data:U})}catch(B){m(B)}}),S.on("error",m),S.on("aborted",()=>m(new Error("HTTP response was aborted")))}),d.on("error",m),f||(l=setTimeout(()=>{let S=new Error("HTTP request timed out");d.destroy?.(S),m(S)},Va)),d.setTimeout?.(Va,()=>{let S=new Error("HTTP request timed out");d.destroy?.(S),m(S)}),e.signal?.aborted===!0?w():e.signal?.addEventListener("abort",w,{once:!0}),!f&&(o!==void 0&&d.write(o),d.end())})}var Ka=class{constructor(t){b(this,"https");this.https=t}async request(t,e){return await Bp(this.https,t,e,i=>JSON.stringify(i))}};var vo=class{constructor(t,e={}){b(this,"fetch");b(this,"limits");this.fetch=t,this.limits=Pp(e)}async request(t,e){let i=Rp(e.signal,this.limits.timeoutMs),r={method:e.method,headers:e.headers,body:e.data===void 0?null:JSON.stringify(e.data),redirect:"error",signal:i.signal};try{let s=await this.fetch(t,r),o=s,c=o.headers?.get?.("Content-Type"),u;if(!("body"in o)&&typeof o.json=="function"&&(c==null||c.startsWith("application/json"))){if(u=await o.json(),Fe(JSON.stringify(u))>this.limits.maxResponseBytes)throw new Error("HTTP response exceeds the configured size limit")}else{let f=await Np(s,this.limits.maxResponseBytes);u=f!==""&&(c?.startsWith("application/json")??!1)?JSON.parse(f):f}return{ok:s.ok,status:s.status,statusText:s.statusText,data:u}}finally{i.dispose()}}};function pr(){let n={async request(...e){throw new Error("No method available to perform HTTP request")}};if(globalThis.window!==void 0&&typeof globalThis.window.fetch=="function")return new vo(globalThis.window.fetch.bind(globalThis.window));if(typeof globalThis.fetch=="function")return new vo(globalThis.fetch.bind(globalThis));let t=typeof Iu=="function"?Iu:void 0;if(t===void 0)return n;try{let e=t(["node","https"].join(":"));return new Ka(e)}catch{return n}}var Pn=class Pn extends Io{constructor(e=300*1e3){super(100);b(this,"cachedRate",null);b(this,"cacheTimestamp",0);b(this,"cacheValidityMs");if(!Number.isSafeInteger(e)||e<0)throw new RangeError("cacheValidityMs must be a non-negative safe integer");this.cacheValidityMs=e}static getInstance(e=300*1e3){return Pn.instance??(Pn.instance=new Pn(e)),Pn.instance}async fetchFeeRate(){let e=Date.now();if(this.cachedRate!==null&&e-this.cacheTimestamp<this.cacheValidityMs)return this.cachedRate;try{let i=await pr().request(Pn.ARC_POLICY_URL,{method:"GET",headers:{Accept:"application/json"}});if(!i.ok)throw new Error("Fee-policy provider request failed");let r=i.data,s=r?.policy?.miningFee?.satoshis,o=r?.policy?.miningFee?.bytes;if(!Number.isSafeInteger(s)||s<1||s>21e14||!Number.isSafeInteger(o)||o<1||o>1e9)throw new Error("Invalid policy response format");let c=s/o*1e3;if(!Number.isFinite(c)||c<=0||c>1e9)throw new Error("Invalid policy fee rate");return this.cachedRate=c,this.cacheTimestamp=e,c}catch{return this.cachedRate!==null?(console.warn("Failed to fetch live fee rate; using cached value."),this.cachedRate):(console.warn("Failed to fetch live fee rate; using default 100 sat/kb."),100)}}async computeFee(e){let i=await this.fetchFeeRate();return this.value=i,super.computeFee(e)}};b(Pn,"ARC_POLICY_URL","https://arc.gorillapool.io/v1/policy"),b(Pn,"instance",null);var Ao=Pn;function gn(n){return n==="__proto__"||n==="constructor"||n==="prototype"}function _p(n){if(n==null||typeof n!="object"||Array.isArray(n))return!1;let t=Object.getPrototypeOf(n);return t===Object.prototype||t===null}var za=/^[0-9a-f]{64}$/i,Cp=8192,Vw=128,Kw=256;function Ai(n,t){let e=Object.getOwnPropertyDescriptor(n,t);return e==null?{present:!1}:Object.prototype.hasOwnProperty.call(e,"value")?{present:!0,value:e.value}:{present:!0}}function Ef(n,t){return typeof n=="string"&&Fe(n)<=t}function gr(){return{status:"error",code:"ERR_INVALID_RESPONSE",description:"Broadcaster returned a malformed or transaction-mismatched response."}}function Lp(n,t){if(!za.test(t)||!_p(n))return gr();let e=Ai(n,"status").value;if(e==="success"){let u=Ai(n,"txid").value,f=Ai(n,"message").value,d=Ai(n,"competingTxs");if(typeof u!="string"||!za.test(u)||u.toLowerCase()!==t.toLowerCase()||!Ef(f,Cp))return gr();let l={status:"success",txid:t.toLowerCase(),message:f};if(d.present){if(!Array.isArray(d.value)||d.value.length>Kw)return gr();let p=[],m=new Set;for(let g=0;g<d.value.length;g++){let w=Object.getOwnPropertyDescriptor(d.value,g),S=w?.value;if(w==null||!Object.prototype.hasOwnProperty.call(w,"value")||typeof S!="string"||!za.test(S))return gr();let C=S.toLowerCase();if(m.has(C))return gr();m.add(C),p.push(C)}l.competingTxs=p}return l}if(e!=="error")return gr();let i=Ai(n,"code").value,r=Ai(n,"description").value,s=Ai(n,"txid");if(!Ef(i,Vw)||!Ef(r,Cp)||s.present&&(typeof s.value!="string"||!za.test(s.value)||s.value.toLowerCase()!==t.toLowerCase()))return gr();let o={status:"error",code:i,description:r};s.present&&(o.txid=t.toLowerCase());let c=Ai(n,"more");return c.present&&c.value!=null&&typeof c.value=="object"&&(o.more=c.value),o}function Up(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("Invalid offset")}var mn=(n,t)=>Math.floor(n/2**t),Eo=n=>n%2===0?n+1:n-1,kf=(n,t,e)=>mn(n,e)===mn(t,e),Tf=n=>n===0?0:n.toString(2).length;function bn(n,t){return nt(zt(at((n??"")+(t??""),"hex").reverse()).reverse())}function zw(n,t,e,i){let r=i.get(n);if(r==null)return;if(r!==t)throw new Error("Mismatched roots");let s=i.get(`${e}:0`);if(s==null)throw new Error("Mismatched roots");return s}function Mp(n,t,e,i,r,s){if(t==null){if(s)return bn(n,n);throw new Error(`Missing hash for index ${i} at height ${r}`)}return t.duplicate===!0?bn(n,n):e%2===1?bn(t.hash,n):bn(n,t.hash)}var Ei=class n{constructor(t,e,i=!0,r=!0){b(this,"blockHeight");b(this,"path");if(!Array.isArray(e)||e.length===0||e.length>54)throw new Error("Merkle Path must contain between 1 and 54 levels");this.blockHeight=t,this.path=e.map((l,p)=>{if(!Array.isArray(l))throw new TypeError(`Merkle Path level ${p} must be an array`);return l.map(m=>({...m}))});let s=Array.from({length:this.path.length}).fill(0).map(()=>new Set);if(this.path.forEach((l,p)=>{if(l.length===0&&p===0)throw new Error(`Empty level at height: ${p}`);let m=new Set;l.forEach(g=>{if(Up(g.offset),m.has(g.offset))throw new Error(`Duplicate offset: ${g.offset}, at height: ${p}`);if(m.add(g.offset),p===0){if(g.duplicate!==!0)for(let w=1;w<this.path.length;w++)s[w].add(Eo(mn(g.offset,w)))}else if(i&&!s[p].has(g.offset))throw new Error(`Invalid offset: ${g.offset}, at height: ${p}, with legal offsets: ${Array.from(s[p],w=>w.toString()).join(", ")}`)})}),!r)return;let o=this.path.map(l=>new Map(l.map(p=>[p.offset,p]))),c=new Map,u=new Map,f=this.path[0].reduce((l,p)=>Math.max(l,p.offset),0),d;this.path[0].forEach((l,p)=>{let m=this.computeRootCached(l.hash,o,c,u,f);if(p===0&&(d=m),d!==m)throw new Error("Mismatched roots")})}static fromHex(t){return n.fromBinary(at(t,"hex"))}static fromReader(t,e=!0,i=!0){let r=t.readVarIntNumStrict(!1),s=t.readUInt8(),o=Array.from({length:s}).fill(null).map(()=>[]),c,u,f;for(let d=0;d<s;d++){for(f=t.readVarIntNumStrict(!1);f>0;){u=t.readVarIntNumStrict(!1),c=t.readUInt8();let l={offset:u};(c&1)===1?l.duplicate=!0:((c&2)!==0&&(l.txid=!0),l.hash=nt(t.read(32).reverse())),(!Array.isArray(o[d])||o[d].length===0)&&(o[d]=[]),o[d].push(l),f--}o[d].sort((l,p)=>l.offset-p.offset)}return new n(r,o,e,i)}static fromBinary(t,e=!0,i=!0){let r=new bt(t);return n.fromReader(r,e,i)}static fromCoinbaseTxidAndHeight(t,e){return new n(e,[[{offset:0,hash:t,txid:!0}]])}toWriter(t){t.writeVarIntNum(this.blockHeight);let e=this.path.length;t.writeUInt8(e);for(let i=0;i<e;i++){let r=Object.keys(this.path[i]).length;t.writeVarIntNum(r);for(let s of this.path[i]){t.writeVarIntNum(s.offset);let o=0;s?.duplicate===!0&&(o|=1),s?.txid!==void 0&&s.txid!==null&&(o|=2),t.writeUInt8(o),(o&1)===0&&t.write(at(s.hash,"hex").reverse())}}}toBinary(){let t=new fe;return this.toWriter(t),t.toArray()}toBinaryUint8Array(){let t=new ht;return this.toWriter(t),t.toUint8Array()}toHex(){return nt(this.toBinaryUint8Array())}indexOf(t){let e=this.path[0].find(i=>i.hash===t);if(e==null)throw new Error(`Transaction ID ${t} not found in the Merkle Path`);return e.offset}computeRootCached(t,e,i,r,s){if(typeof t!="string"&&(t=this.path[0].find(f=>!!f.hash)?.hash),typeof t!="string")throw new TypeError("Transaction ID is undefined");let o=this.indexOf(t);if(this.path.length===1&&this.path[0].length===1)return t;let c=Math.max(this.path.length,Tf(s)),u=t;for(let f=0;f<c;f++){let d=`${f}:${mn(o,f)}`,l=zw(d,u,c,r);if(l!=null)return l;r.set(d,u);let p=Eo(mn(o,f)),m=this.cachedFindLeaf(f,p,e,i,s);u=Mp(u,m,p,o,f,this.path.length===1&&kf(o,s,f))}return r.set(`${c}:0`,u),u}computeRoot(t){if(typeof t!="string"){let o=this.path[0].find(c=>!!c?.hash);if(o==null)throw new Error("No valid leaf found in the Merkle Path");t=o.hash}if(typeof t!="string")throw new TypeError("Transaction ID is undefined");let e=this.indexOf(t),i=t;if(this.path.length===1&&this.path[0].length===1)return i;let r=this.path[0].reduce((o,c)=>Math.max(o,c.offset),0),s=Math.max(this.path.length,Tf(r));for(let o=0;o<s;o++){let c=Eo(mn(e,o));i=Mp(i,this.findOrComputeLeaf(o,c),c,e,o,this.path.length===1&&kf(e,r,o))}return i}findOrComputeLeaf(t,e){Up(e);let i=t<this.path.length?this.path[t].find(f=>f.offset===e):void 0;if(i!=null)return i;if(t===0)return;let r=t-1,s=e*2;if(!Number.isSafeInteger(s))return;let o=this.findOrComputeLeaf(r,s);if(o?.hash==null||o.hash==="")return;let c=this.findOrComputeLeaf(r,s+1);if(c?.hash==null){if(c?.duplicate===!0)return{offset:e,hash:bn(o.hash,o.hash)};if(this.path.length===1){let f=this.path[0].reduce((d,l)=>Math.max(d,l.offset),0);if(s===mn(f,r))return{offset:e,hash:bn(o.hash,o.hash)}}return}let u;return c.duplicate===!0?u=bn(o.hash,o.hash):u=bn(c.hash,o.hash),i={offset:e,hash:u},i}async verify(t,e){let i=this.blockHeight;if(!Number.isSafeInteger(i)||i<0)throw new Error("Merkle Path block height must be a non-negative safe integer");let r=e?.currentHeight,s=e?.isValidRootForHeight;if(typeof r!="function"||typeof s!="function")throw new TypeError("A valid ChainTracker is required");let o=this.computeRoot(t);if(this.indexOf(t)===0){let u=await r.call(e);if(!Number.isSafeInteger(u)||u<0)throw new Error("ChainTracker current height must be a non-negative safe integer");if(i+100>u)return!1}return await s.call(e,o,i)===!0}combine(t){if(this.blockHeight!==t.blockHeight)throw new Error("You cannot combine paths which do not have the same block height.");let e=this.computeRoot(),i=t.computeRoot();if(e!==i)throw new Error("You cannot combine paths which do not have the same root.");let r=[];for(let s=0;s<this.path.length;s++){r.push([]);for(let o of this.path[s])r[s].push({...o});for(let o of t.path[s]){let c=r[s].find(u=>u.offset===o.offset);c===void 0?r[s].push({...o}):o?.txid!==void 0&&o?.txid!==null&&(c.txid=!0)}}this.path=r,this.trim()}trim(){let t=(o,c)=>{(c.length===0||c.at(-1)!==o)&&c.push(o)},e=(o,c)=>{for(let u=o.length;u>=0;u--){let f=this.path[c].findIndex(d=>d.offset===o[u]);f>=0&&this.path[c].splice(f,1)}},i=o=>{let c=[];for(let u of o)t(mn(u,1),c);return c},r=[],s=[];for(let o of this.path)o.sort((c,u)=>c.offset-u.offset);for(let o=0;o<this.path[0].length;o++){let c=this.path[0][o];if(c.txid===!0)t(mn(c.offset,1),r);else{let u=c.offset%2===1,f=this.path[0][o+(u?-1:1)];(f.txid===void 0||f.txid===null||!f.txid)&&t(f.offset,s)}}e(s,0);for(let o=1;o<this.path.length;o++)s=r,r=i(r),e(s,o)}cachedFindLeaf(t,e,i,r,s){let o=`${t}:${e}`;if(r.has(o))return r.get(o);let c=t<i.length?i[t].get(e):void 0;if(c!=null)return r.set(o,c),c;if(t===0){r.set(o,void 0);return}let u=t-1,f=e*2;if(!Number.isSafeInteger(f))return;let d=this.cachedFindLeaf(u,f,i,r,s);if(d?.hash==null||d.hash===""){r.set(o,void 0);return}let l=this.cachedFindLeaf(u,f+1,i,r,s);if(l?.hash==null){if(l?.duplicate===!0||this.path.length===1&&f===mn(s,u))return c={offset:e,hash:bn(d.hash,d.hash)},r.set(o,c),c;r.set(o,void 0);return}let p=l.duplicate===!0?bn(d.hash,d.hash):bn(l.hash,d.hash);return c={offset:e,hash:p},r.set(o,c),c}extract(t){if(t.length===0)throw new Error("At least one txid must be provided to extract");let e=this.computeRoot(),i=this.path[0].reduce((l,p)=>Math.max(l,p.offset),0),r=Math.max(this.path.length,Tf(i)),s=this.createSourceLeafIndex(),o=new Map,c=this.createTxidToOffsetIndex(),u=this.createNeededLeafLevels(r);for(let l of t)this.collectExtractedLeaves(l,c,u,s,o,i,r);let f=new n(this.blockHeight,this.buildExtractedPath(u));f.trim();let d=f.computeRoot();if(d!==e)throw new Error(`Extracted path root ${d} does not match original root ${e}`);return f}createSourceLeafIndex(){let t=Array.from({length:this.path.length});for(let e=0;e<this.path.length;e++){let i=new Map;for(let r of this.path[e])i.set(r.offset,r);t[e]=i}return t}createTxidToOffsetIndex(){let t=new Map;for(let e of this.path[0])e.hash!=null&&t.set(e.hash,e.offset);return t}createNeededLeafLevels(t){let e=Array.from({length:t});for(let i=0;i<t;i++)e[i]=new Map;return e}collectExtractedLeaves(t,e,i,r,s,o,c){let u=e.get(t);if(u===void 0)throw new Error(`Transaction ID ${t} not found in the Merkle Path`);i[0].set(u,{offset:u,txid:!0,hash:t});let f=Eo(u);if(!i[0].has(f)){let d=this.cachedFindLeaf(0,f,r,s,o);d!=null&&i[0].set(f,d)}for(let d=1;d<c;d++){let l=Eo(mn(u,d));if(i[d].has(l))continue;let p=this.cachedFindLeaf(d,l,r,s,o);p!=null?i[d].set(l,p):kf(u,o,d)&&i[d].set(l,{offset:l,duplicate:!0})}}buildExtractedPath(t){return t.map(e=>Array.from(e.values()).sort((i,r)=>i.offset-r.offset))}};var Xw=32,jw=64;function Dp(n,t,e){if(n==null||typeof n!="object"||Array.isArray(n))throw new TypeError(`${t} must be an accessor-free plain data object.`);let i=Object.getPrototypeOf(n),r=Object.getOwnPropertyDescriptors(n);if(i!==Object.prototype&&i!==null||Object.getOwnPropertySymbols(n).length!==0||Object.keys(r).length>e||Object.values(r).some(s=>s.get!=null||s.set!=null))throw new TypeError(`${t} must be an accessor-free plain data object.`);return r}function Gr(n,t,e){if(n!==void 0){if(typeof n!="string"||Fe(n)>e||Yi(n))throw new TypeError(`${t} must be bounded text without control characters.`);return n}}function Gw(n){if(n===void 0)return;let t=Dp(n,"ARC headers",jw),e=Object.create(null);for(let[i,r]of Object.entries(t)){if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/.test(i))throw new TypeError(`ARC header name is invalid: ${i}`);let s=Gr(r.value,`ARC header ${i}`,8192);if(s===void 0)throw new TypeError(`ARC header ${i} must be a string.`);e[i]=s}return Object.freeze(e)}function Yw(n){let t=n??pr();if(t==null||typeof t!="object"||typeof t.request!="function")throw new TypeError("ARC httpClient must provide request().");return t}function Hp(n,t){if(typeof n=="string")return Object.freeze({apiKey:Gr(n,"ARC API key",16*1024),httpClient:pr(),deploymentId:t()});let e=Dp(n??{},"ARC config",Xw),i=r=>e[r]?.value;return Object.freeze({apiKey:Gr(i("apiKey"),"ARC API key",16*1024),httpClient:Yw(i("httpClient")),deploymentId:Gr(i("deploymentId"),"ARC deployment ID",256)??t(),callbackUrl:Gr(i("callbackUrl"),"ARC callback URL",2048),callbackToken:Gr(i("callbackToken"),"ARC callback token",16*1024),headers:Gw(i("headers"))})}function $p(n){if(typeof n!="string"||n.length===0||Fe(n)>2048||Yi(n))throw new TypeError("ARC URL must be nonempty bounded text without control characters.");return n}function Xa(n,t){for(let e of t){if(!Object.prototype.hasOwnProperty.call(n,e))throw new Error(`Cannot lock missing configuration property ${e}.`);Object.defineProperty(n,e,{configurable:!1,writable:!1})}}function Zw(){return`ts-sdk-${nt(Pe(16))}`}var Jw=new Set(["DOUBLE_SPEND_ATTEMPTED","REJECTED","INVALID","MALFORMED","MINED_IN_STALE_BLOCK"]),Yr=/^[0-9a-f]{64}$/i,Kp=128,zp=8192,Qw=256,ty=32,ey=new Set(["SUCCESS","RECEIVED","SENT_TO_NETWORK","ANNOUNCED_TO_NETWORK","ACCEPTED_BY_NETWORK","SEEN_ON_NETWORK","STORED","MINED","IMMUTABLE"]);function ja(n,t,e=!0){return typeof n=="string"&&(e||n.length!==0)&&Fe(n)<=t&&!Yi(n)}function Pf(n){if(n==null||typeof n!="object"||Array.isArray(n))return;let t=Object.getPrototypeOf(n);if(t!==Object.prototype&&t!==null)return;let e=Object.getOwnPropertyDescriptors(n);if(!(Object.getOwnPropertySymbols(n).length!==0||Object.keys(e).length>ty||Object.values(e).some(i=>i.get!=null||i.set!=null)))return e}function ny(n){if(n===void 0||!Array.isArray(n)||n.length>Qw)return;let t=Object.getOwnPropertyDescriptors(n),e=new Set(["length",...Array.from({length:n.length},(s,o)=>String(o))]);if(Object.getOwnPropertySymbols(n).length!==0||Object.keys(t).length!==e.size||Object.keys(t).some(s=>!e.has(s))||Object.values(t).some(s=>s.get!=null||s.set!=null))return;let i=[],r=new Set;for(let s=0;s<n.length;s++){let o=t[s]?.value;if(typeof o!="string"||!Yr.test(o))return;let c=o.toLowerCase();if(r.has(c))return;r.add(c),i.push(c)}return i}function qp(n){try{return n.toHexEF()}catch(t){if(t.message==="All inputs must have source transactions when serializing to EF format")return n.toHex();throw t}}function mr(n){return{status:"error",code:"ERR_INVALID_RESPONSE",description:n}}function Fp(n,t){let e=Pf(n);if(e===void 0)return mr("ARC returned a malformed response.");let i=p=>e[p]?.value,r=i("txid"),s=i("extraInfo"),o=i("txStatus"),c=i("competingTxs");if(!ja(o,Kp,!1)||s!==void 0&&!ja(s,zp))return mr("ARC returned invalid transaction status metadata.");let u=ny(c);if(c!==void 0&&u===void 0)return mr("ARC returned invalid competing transaction identifiers.");let f=o.toUpperCase(),d=s?.toUpperCase().includes("ORPHAN")||f.includes("ORPHAN");if(Jw.has(f)||d){if(typeof r=="string"&&Yr.test(r)&&r.toLowerCase()!==t.toLowerCase())return{status:"error",code:"ERR_TXID_MISMATCH",description:"ARC returned a failure for another transaction."};let p={status:"error",code:o,description:`${o} ${s??""}`.trim()};return typeof r=="string"&&Yr.test(r)&&(p.txid=t.toLowerCase()),u!=null&&(p.more={competingTxs:u}),p}if(!ey.has(f))return mr("ARC returned an unknown transaction status.");if(typeof r!="string"||!Yr.test(r)||r.toLowerCase()!==t.toLowerCase())return{status:"error",code:"ERR_TXID_MISMATCH",description:"ARC acknowledged a transaction other than the submitted transaction."};let l={status:"success",txid:t,message:`${o} ${s??""}`.trim()};return u!=null&&(l.competingTxs=u),l}function iy(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch{return n}}function Wp(n,t,e){let r={status:"error",code:typeof n=="number"&&Number.isSafeInteger(n)||typeof n=="string"&&ja(n,Kp,!1)?n.toString():"ERR_UNKNOWN",description:"Unknown error"},s=iy(t),o=Pf(s);if(o===void 0)return r;let c=o.detail?.value,u=o.txid?.value;if(typeof u=="string"&&Yr.test(u)){if(e!==void 0&&u.toLowerCase()!==e.toLowerCase())return{status:"error",code:"ERR_TXID_MISMATCH",description:"ARC returned a failure for another transaction."};r.txid=u.toLowerCase()}let f={};return ja(c,zp)&&(r.description=c,f.detail=c),r.txid!==void 0&&(f.txid=r.txid),Object.keys(f).length!==0&&(r.more=f),r}function Vp(){return{status:"error",code:"500",description:"Internal Server Error"}}var Zr,To,Of,ko=class{constructor(t,e){G(this,To);b(this,"URL");b(this,"apiKey");b(this,"deploymentId");b(this,"callbackUrl");b(this,"callbackToken");b(this,"headers");G(this,Zr);this.URL=$p(t);let i=Hp(e,Zw);this.apiKey=i.apiKey,N(this,Zr,i.httpClient),this.deploymentId=i.deploymentId,this.callbackToken=i.callbackToken,this.callbackUrl=i.callbackUrl,this.headers=i.headers,Xa(this,["URL","apiKey","deploymentId","callbackUrl","callbackToken","headers"])}async broadcast(t){let e={method:"POST",headers:a(this,To,Of).call(this),data:{rawTx:qp(t)}};try{let i=await y(this,Zr).request(`${this.URL}/v1/tx`,e);return i.ok?Fp(i.data,t.id("hex")):Wp(i.status,i.data,t.id("hex"))}catch{return Vp()}}async broadcastMany(t){let e=t.map(r=>({rawTx:qp(r)})),i={method:"POST",headers:a(this,To,Of).call(this),data:e};try{let r=await y(this,Zr).request(`${this.URL}/v1/txs`,i);if(!r.ok)return t.map(u=>Wp(r.status,r.data,u.id("hex")));if(!Array.isArray(r.data)||r.data.length!==t.length)return t.map(()=>mr("ARC returned a malformed batch response."));let s=Object.getOwnPropertyDescriptors(r.data),o=new Set(["length",...Array.from({length:r.data.length},(u,f)=>String(f))]);if(Object.getOwnPropertySymbols(r.data).length!==0||Object.keys(s).length!==o.size||Object.keys(s).some(u=>!o.has(u))||Object.values(s).some(u=>u.get!=null||u.set!=null))return t.map(()=>mr("ARC returned a malformed batch response."));let c=new Map;for(let u of t){let f=u.id("hex").toLowerCase();c.set(f,(c.get(f)??0)+1)}return Array.from({length:r.data.length},(u,f)=>{let d=s[f]?.value,l=Pf(d);if(l===void 0)return mr("ARC returned a malformed batch result.");let p=l.txid?.value,m=typeof p=="string"&&Yr.test(p)?p.toLowerCase():"",g=c.get(m)??0;return g<1?{status:"error",code:"ERR_TXID_MISMATCH",description:"ARC batch acknowledged a transaction that was not submitted."}:(g===1?c.delete(m):c.set(m,g-1),Fp(d,m))})}catch{let r=Vp();return t.map(()=>r)}}};Zr=new WeakMap,To=new WeakSet,Of=function(){let t={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(this.apiKey!=null&&this.apiKey!==""&&(t.Authorization=`Bearer ${this.apiKey}`),this.callbackUrl!=null&&this.callbackUrl!==""&&(t["X-CallbackUrl"]=this.callbackUrl),this.callbackToken!=null&&this.callbackToken!==""&&(t["X-CallbackToken"]=this.callbackToken),this.headers!=null)for(let[e,i]of Object.entries(this.headers))t[e]=i;return t};function Xp(n=!1,t={}){return new ko(n?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",t)}var jp=/^[0-9a-f]{64}$/i,Gp=2147483647,ry=256,Yp=64;function sy(n,t,e){if(typeof n!="string"||Fe(n)>e||Yi(n))throw new TypeError(`${t} must be bounded text without control characters.`);return n}function Rf(n,t,e){if(n==null||typeof n!="object"||Array.isArray(n))throw new TypeError(`${t} must be an accessor-free plain data object.`);let i=Object.getPrototypeOf(n),r=Object.getOwnPropertyDescriptors(n);if(i!==Object.prototype&&i!==null||Object.getOwnPropertySymbols(n).length!==0||Object.keys(r).length>e||Object.values(r).some(s=>s.get!=null||s.set!=null))throw new TypeError(`${t} must be an accessor-free plain data object.`);return r}function oy(n){if(n!=="main"&&n!=="test"&&n!=="stn")throw new TypeError("What's On Chain network must be 'main', 'test', or 'stn'.");return n}function ay(n){let t=n??pr();if(t==null||typeof t!="object"||typeof t.request!="function")throw new TypeError("What's On Chain httpClient must provide request().");return t}function cy(n){let t=Rf(n,"What's On Chain config",8);return{apiKey:t.apiKey?.value===void 0?"":sy(t.apiKey.value,"What's On Chain API key",16*1024),httpClient:ay(t.httpClient?.value)}}function uy(n,t){if(typeof n!="string"||!jp.test(n))throw new TypeError("Merkle root must be a 64-character hexadecimal string.");if(!Number.isSafeInteger(t)||t<0||t>Gp)throw new TypeError("Block height must be a nonnegative bounded integer.");return{root:n.toLowerCase(),height:t}}function fy(n){try{let e=Rf(n,"What's On Chain block header",Yp).merkleroot?.value;return typeof e=="string"&&jp.test(e)?e.toLowerCase():void 0}catch{return}}function dy(n){if(!Array.isArray(n)||n.length===0||n.length>ry)return;let t=Object.getOwnPropertyDescriptors(n),e=new Set(["length",...Array.from({length:n.length},(i,r)=>String(r))]);if(!(Object.getOwnPropertySymbols(n).length!==0||Object.keys(t).length!==e.size||Object.keys(t).some(i=>!e.has(i))||Object.values(t).some(i=>i.get!=null||i.set!=null)))try{let r=Rf(t[0]?.value,"What's On Chain height response",Yp).height?.value;return Number.isSafeInteger(r)&&r>=0&&r<=Gp?r:void 0}catch{return}}var Oo=class{constructor(t="main",e={}){b(this,"network");b(this,"apiKey");b(this,"URL");b(this,"httpClient");this.network=oy(t),this.URL=`https://api.whatsonchain.com/v1/bsv/${this.network}`;let i=cy(e);this.httpClient=i.httpClient,this.apiKey=i.apiKey,Xa(this,["network","URL","httpClient","apiKey"])}async isValidRootForHeight(t,e){let i=uy(t,e),r={method:"GET",headers:this.getHttpHeaders()};try{let s=await this.httpClient.request(`${this.URL}/block/${i.height}/header`,r);if(s.ok)return fy(s.data)===i.root;if(s.status===404)return!1;throw new Error("provider request failed")}catch{throw new Error(`Failed to verify merkleroot for height ${i.height}.`)}}async currentHeight(){try{let t={method:"GET",headers:this.getHttpHeaders()},e=await this.httpClient.request(`${this.URL}/block/headers`,t);if(e.ok){let i=dy(e.data);if(i!==void 0)return i}throw new Error("provider response was invalid")}catch{throw new Error("Failed to get current height from What's On Chain.")}}getHttpHeaders(){let t={Accept:"application/json"};return typeof this.apiKey=="string"&&this.apiKey.trim()!==""&&(t.Authorization=this.apiKey),t}};function Zp(){return new Oo}var ze;(function(n){n[n.RAWTX=0]="RAWTX",n[n.RAWTX_AND_BUMP_INDEX=1]="RAWTX_AND_BUMP_INDEX",n[n.TXID_ONLY=2]="TXID_ONLY"})(ze||(ze={}));function Jr(n,t){if(!Number.isSafeInteger(t)||t<0||n.pos+t>n.bin.length)throw new RangeError("Serialized transaction exceeds available BEEF data");n instanceof bt?n.skip(t):n.read(t)}function Nf(n){let t=n.pos;Jr(n,4);let e=n.readVarIntNumStrict(!1),i=new Set;for(let o=0;o<e;o++){i.add(nt(n.readReverse(32))),Jr(n,4);let c=n.readVarIntNumStrict(!1);Jr(n,c+4)}let r=n.readVarIntNumStrict(!1);for(let o=0;o<r;o++){Jr(n,8);let c=n.readVarIntNumStrict(!1);Jr(n,c)}return Jr(n,4),{rawTx:n instanceof bt?n.bin.subarray(t,n.pos):Uint8Array.from(n.bin.slice(t,n.pos)),inputTxids:Array.from(i)}}function ly(n){return Nf(new bt(n)).inputTxids}function hy(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}var Xe=class n{constructor(t,e,i,r=!1){b(this,"_bumpIndex");b(this,"_tx");b(this,"_rawTx");b(this,"_txid");b(this,"inputTxids",[]);b(this,"isValid");if(typeof t=="string")this._txid=t;else if(t instanceof Uint8Array)this._rawTx=r?t:Uint8Array.from(t);else if(Array.isArray(t))this._rawTx=new Uint8Array(t);else if(t instanceof Me)this._tx=t;else throw new TypeError("Invalid transaction data type");this._bumpIndex=e,this.hasProof?this.inputTxids=[]:i!=null?this.inputTxids=Array.from(i):this.updateInputTxids()}get bumpIndex(){return this._bumpIndex}set bumpIndex(t){this._bumpIndex=t,this.updateInputTxids()}get hasProof(){return this._bumpIndex!==void 0}get isTxidOnly(){return this._txid!==void 0&&this._txid!==null&&this._rawTx==null&&this._tx==null}get txid(){if(this._txid!==void 0&&this._txid!==null&&this._txid!=="")return this._txid;if(this._tx!=null)return this._txid=this._tx.id("hex"),this._txid;if(this._rawTx!=null)return this._txid=nt(zt(this._rawTx).reverse()),this._txid;throw new Error("Internal")}get tx(){if(this._tx!=null)return this._tx;if(this._rawTx!=null)return this._tx=Me.fromBinaryView(this._rawTx),this._txid!=null&&Qp(this._tx,this._txid),this._tx}get rawTx(){let t=this.rawTxUint8Array;return t==null?void 0:Array.from(t)}get rawTxUint8Array(){let t=this.getRawTxBytes();return t==null?void 0:Uint8Array.from(t)}getRawTxBytes(){return this._tx!=null?(this._rawTx==null?this._rawTx=this._tx.toUint8Array():this.syncRawTxFromTransaction(),this._rawTx):this._rawTx}syncRawTxFromTransaction(){if(this._tx==null)return!1;let t=Jp(this._tx);if(this._rawTx!=null)return t===this._rawTx?!1:(this._rawTx=t,this._txid=this._tx.id("hex"),this.updateInputTxids(),!0);let e=this._tx.id("hex"),i=this._txid!=null&&this._txid!==e,r=this.inputTxids;return this._txid=e,this.updateInputTxids(),i||!hy(r,this.inputTxids)}static fromTx(t,e){return new n(t,e)}static fromRawTx(t,e){return new n(t,e)}static fromTxid(t,e){return new n(t,e)}updateInputTxids(){if(this.hasProof)this.inputTxids=[];else if(this._tx!=null){let t=new Set;for(let e of this._tx.inputs)e.sourceTXID!==void 0&&e.sourceTXID!==null&&e.sourceTXID!==""&&t.add(e.sourceTXID);this.inputTxids=Array.from(t)}else this._rawTx!=null?this.inputTxids=ly(this._rawTx):this.inputTxids=[]}toWriter(t,e){let i=c=>{t.writeUInt8(c)},r=()=>{if(this._txid==null)throw new Error("Transaction ID (_txid) is undefined");t.writeReverse(at(this._txid,"hex"))},s=()=>{let c=this.getRawTxBytes();if(c==null)throw new Error("a valid serialized Transaction is expected");t.write(c)},o=()=>{this.bumpIndex===void 0?i(ze.RAWTX):(i(ze.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex))};e===4022206466?this.isTxidOnly?(i(ze.TXID_ONLY),r()):this.bumpIndex!==void 0?(i(ze.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex),s()):(i(ze.RAWTX),s()):(s(),o())}static fromReader(t,e){let i,r;if(e===4022206466){let s=t.readUInt8();if(s===ze.TXID_ONLY)r=n.fromTxid(nt(t.readReverse(32)));else{s===ze.RAWTX_AND_BUMP_INDEX&&(i=t.readVarIntNumStrict(!1));let{rawTx:o,inputTxids:c}=Nf(t);r=new n(o,i,c,!0)}}else{let{rawTx:s,inputTxids:o}=Nf(t);i=t.readUInt8()===0?void 0:t.readVarIntNumStrict(!1),r=new n(s,i,o,!0)}return r}};function py(n,t,e,i){if(t.path.length!==e)throw new Error("Mismatched roots");for(let r=0;r<e;r++)gy(n[r],t.path[r],i)}function gy(n,t,e){for(let i of t){let r=n.get(i.offset);if(r==null){n.set(i.offset,i);continue}my(r,i,e)}}function my(n,t,e){if(e&&(n.hash!==t.hash||n.duplicate!==t.duplicate))throw new Error("Mismatched roots");t.txid!=null&&(n.txid=!0)}function t0(n,t,e){for(let i of n.path[0])typeof i.hash=="string"&&e.set(i.hash,t)}var Bn,_n,Cn,Jn,je,Qn,wr,ns,yr,is,rs,ss,xr,Sr,Ln,De,Un,P,Qr,Ga,_f,Cf,Ya,e0,n0,i0,r0,Rn,s0,Nn,o0,a0,Po,c0,Lf,Uf,Mf,u0,Ro,No,Za,br,ts,Df,Ja,f0,Hf,d0,l0,h0,Bo,p0,g0,Qa,m0,b0,$f,w0,y0,x0,S0,I0,v0,A0,es,qf,E0,tc,k0,T0,O0,P0,R0,N0,B0,_0,wn=class wn{constructor(t=4022206466){G(this,P);b(this,"bumps",[]);b(this,"txs",[]);b(this,"version",4022206466);b(this,"atomicTxid");G(this,Bn);G(this,_n);G(this,Cn);G(this,Jn);G(this,je);G(this,Qn);G(this,wr,new Map);G(this,ns);G(this,yr);G(this,is);G(this,rs);G(this,ss);G(this,xr);G(this,Sr);G(this,Ln,!0);G(this,De);G(this,Un);this.version=t}synchronizeNestedTransactionMutations(){let t=!1;for(let e of this.txs)t=e.syncRawTxFromTransaction()||t;t&&(a(this,P,Qr).call(this),N(this,De,void 0),N(this,Un,void 0),N(this,Ln,!0),a(this,P,br).call(this))}isAtomic(t=this.atomicTxid??""){if(this.synchronizeNestedTransactionMutations(),a(this,P,Rn).call(this),t.length===0)return!1;let e=a(this,P,No).call(this);if(e.size!==this.txs.length)return!1;let i=e.get(t);return i==null?!1:a(this,P,Uf).call(this,i,e).size===this.txs.length}findTxid(t){return this.synchronizeNestedTransactionMutations(),a(this,P,Ro).call(this,t)}makeTxidOnly(t){let e=a(this,P,Za).call(this).get(t);if(e===void 0)return;let i=this.txs[e];return i.isTxidOnly||(i=Xe.fromTxid(t),this.txs[e]=i,a(this,P,ts).call(this,i,e),a(this,P,es).call(this,i),a(this,P,Nn).call(this,!0)),i}findBump(t){a(this,P,Rn).call(this);let e=a(this,P,Ja).call(this).get(t);return e===void 0?void 0:this.bumps[e]}findTransactionForSigning(t){let e=this.findTxid(t);if(e?.tx!=null){for(let i of e.tx.inputs)if(i.sourceTransaction==null){let r=a(this,P,Ro).call(this,sr(i.sourceTXID,"sourceTXID must be valid"));r!=null&&(i.sourceTransaction=r.tx)}return e.tx}}findAtomicTransaction(t){let e=this.findTxid(t);if(e?.tx!=null)return a(this,P,d0).call(this,e.tx),e.tx}mergeBump(t){return this.synchronizeNestedTransactionMutations(),a(this,P,Rn).call(this),a(this,P,Nn).call(this,!1),a(this,P,Bo).call(this,t)}mergeProvenTxs(t){if(t.length===0)return[];this.synchronizeNestedTransactionMutations(),a(this,P,Rn).call(this),a(this,P,Nn).call(this,!0);let e=[];for(let s of t)e.push(a(this,P,Qa).call(this,s.rawTx));let i=new Map;for(let s of t){let o=s.merklePath.blockHeight;i.set(o,(i.get(o)??0)+1)}let r=new Map;for(let s=0;s<t.length;s++){let o=t[s].merklePath,c=t[s].merkleRoot,u=i.get(o.blockHeight)===1?`${o.blockHeight}:single:${s}`:`${o.blockHeight}:${c??o.computeRoot()}`,f=r.get(u);f==null?r.set(u,{first:s,paths:[o],validateCombined:c!=null}):(f.paths.push(o),f.validateCombined=f.validateCombined||c!=null)}for(let s of[...r.values()].sort((o,c)=>o.first-c.first))a(this,P,Bo).call(this,a(this,P,h0).call(this,s.paths,s.validateCombined));return e}mergeRawTx(t,e){return this.synchronizeNestedTransactionMutations(),a(this,P,Nn).call(this,!0),a(this,P,Qa).call(this,t,e)}mergeTransaction(t){return this.synchronizeNestedTransactionMutations(),a(this,P,Nn).call(this,!0),a(this,P,$f).call(this,t)}removeExistingTxid(t){let e=a(this,P,Za).call(this).get(t);e!==void 0&&(this.txs.splice(e,1),a(this,P,br).call(this),a(this,P,Nn).call(this,!0))}mergeTxidOnly(t){let e=this.findTxid(t);return e==null&&(e=new Xe(t),this.txs.push(e),a(this,P,ts).call(this,e),a(this,P,es).call(this,e),a(this,P,Nn).call(this,!0)),e}mergeBeefTx(t){let e=this.findTxid(t.txid);if(t.isTxidOnly&&e==null?e=this.mergeTxidOnly(t.txid):t._tx!=null&&(e==null||e.isTxidOnly)?e=this.mergeTransaction(t._tx):t._rawTx!=null&&(e==null||e.isTxidOnly)&&(e=this.mergeRawTx(t._rawTx)),e==null)throw new Error(`Failed to merge BeefTx for txid: ${t.txid}`);return e}mergeBeef(t){let e=wn.fromBinaryStrict(t instanceof wn?t.toBinary():t);this.synchronizeNestedTransactionMutations(),a(this,P,Rn).call(this),a(this,P,Nn).call(this,!0);for(let i of e.bumps)a(this,P,Bo).call(this,i);for(let i of e.txs)a(this,P,w0).call(this,i)}isValid(t){return this.verifyValid(t).valid}async verify(t,e){let i=this.verifyValid(e);if(!i.valid)return!1;for(let r of Object.keys(i.roots))if(await t.isValidRootForHeight(i.roots[r],Number(r))!==!0)return!1;return!0}verifyValid(t){a(this,P,Rn).call(this);let e={valid:!1,roots:{}};if(this.atomicTxid!=null&&!this.isAtomic(this.atomicTxid))return e;let i=this.sortTxs();if(a(this,P,y0).call(this)||i.missingInputs.length>0||i.notValid.length>0||i.txidOnly.length>0&&t!==!0||i.withMissingInputs.length>0)return e;let r={};return!a(this,P,x0).call(this,r,t)||!a(this,P,S0).call(this,r,e)||!a(this,P,I0).call(this)||!a(this,P,v0).call(this,r)||(e.valid=!0),e}toWriter(t){t.writeUInt32LE(this.version),t.writeVarIntNum(this.bumps.length);for(let e of this.bumps)t.write(t instanceof ht?e.toBinaryUint8Array():e.toBinary());t.writeVarIntNum(this.txs.length);for(let e of this.txs)e.toWriter(t,this.version)}toBinary(){return Array.from(a(this,P,Po).call(this))}toUint8Array(){return new Uint8Array(a(this,P,Po).call(this))}toBinaryAtomic(t){return Array.from(a(this,P,Lf).call(this,t))}toUint8ArrayAtomic(t){return new Uint8Array(a(this,P,Lf).call(this,t))}toHex(){let t=a(this,P,Po).call(this);if(y(this,Qn)!=null)return y(this,Qn);let e=nt(t);return N(this,Qn,e),e}static fromReader(t){var f;let e=t.pos,i=t.readUInt32LE(),r,s=e;if(i===16843009&&(r=nt(t.readReverse(32)),s=t.pos,i=t.readUInt32LE()),i!==4022206465&&i!==4022206466)throw new Error(`Serialized BEEF must start with ${4022206465} or ${4022206466} but starts with ${i}`);let o=new wn(i),c=t.readVarIntNumStrict(!1);for(let d=0;d<c;d++){let l=Ei.fromReader(t,!1);o.bumps.push(l)}let u=t.readVarIntNumStrict(!1);for(let d=0;d<u;d++){let l=Xe.fromReader(t,i);o.txs.push(l)}return o.atomicTxid=r,t instanceof bt&&(N(o,je,t.bin.subarray(s,t.pos)),a(f=o,P,Ga).call(f)),o}static fromBinary(t){return wn.fromReader(new bt(Uint8Array.from(t)))}static fromBinaryStrict(t){return wn.fromBinaryView(Uint8Array.from(t))}static fromBinaryView(t){let e=new bt(t),i=wn.fromReader(e);if(!e.eof())throw new Error("Serialized BEEF contains trailing data");return i}static fromString(t,e="hex"){let i=et(t,e);return wn.fromBinaryStrict(i)}sortTxs(){if(this.synchronizeNestedTransactionMutations(),a(this,P,Rn).call(this),y(this,De)!=null&&a(this,P,E0).call(this))return a(this,P,tc).call(this,y(this,De));N(this,De,void 0),N(this,Un,void 0);let t={},e={},i=[],r=[],s=this.partitionTxs(e,t,i,r),{txsMissingInputs:o,missingInputs:c,remaining:u}=a(this,P,k0).call(this,s,e);s=u;let f=a(this,P,T0).call(this,s,t,i);this.txs=o.concat(f).concat(r).concat(i),N(this,Ln,!1),a(this,P,Qr).call(this),a(this,P,br).call(this);let d={missingInputs:Object.keys(c),notValid:f.map(l=>l.txid),valid:Object.keys(t),withMissingInputs:o.map(l=>l.txid),txidOnly:r.map(l=>l.txid)};return N(this,De,d),a(this,P,qf).call(this),a(this,P,tc).call(this,d)}partitionTxs(t,e,i,r){let s=[];for(let o of this.txs)t[o.txid]=o,o.isValid=o.hasProof,o.isValid?(e[o.txid]=!0,i.push(o)):o.isTxidOnly&&o.inputTxids.length===0?(e[o.txid]=!0,r.push(o)):s.push(o);return s}clone(){var e,i;let t=new wn;return t.version=this.version,t.bumps=Array.from(this.bumps),t.txs=Array.from(this.txs),N(t,Bn,void 0),N(t,_n,void 0),N(t,Cn,void 0),N(t,Jn,void 0),N(t,Ln,y(this,Ln)),N(t,De,y(this,De)==null?void 0:a(this,P,tc).call(this,y(this,De))),y(t,De)!=null&&a(e=t,P,qf).call(e),N(t,Qn,y(this,Qn)),N(t,je,y(this,je)),y(t,je)!=null&&a(i=t,P,Ga).call(i),t}trimKnownTxids(t){let e=a(this,P,N0).call(this,new Set(t));e=a(this,P,B0).call(this)||e,e&&a(this,P,Nn).call(this,!0)}getValidTxids(){return this.sortTxs().valid}toLogString(){let t="";t+=`BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}
8
+ ${u}`;super(f);w(this,"txid");w(this,"outputIndex");w(this,"context");w(this,"programCounter");w(this,"stackState");w(this,"altStackState");w(this,"ifStackState");w(this,"stackMem");w(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 pi=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`);w(this,"resource");w(this,"limit");w(this,"attempted");this.resource=e,this.limit=i,this.attempted=r,this.name="ScriptResourceLimitError"}};var f2;function eu(){return f2}var l2=520,og=1e4,ag=500,d2=0x7fffffffn,h2=75e4,p2=32e6,cg=1e3,g2=Math.pow(2,31)-1,m2=BigInt(g2),b2=20,ug=2147483648,nd=4194304,y2=65535,fg=5e8,w2=Object.freeze(new O(-1).toScriptNum()),lg=Object.freeze(Array.from({length:17},(n,t)=>Object.freeze(new O(t).toScriptNum())));function dg(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 tr(n){return new O(n?1:0)}function x2(n,t){return tr(n&&t)}function S2(n,t){return tr(n||t)}function I2(n,t){return n.cmp(t)<0?n:t}function v2(n,t){return n.cmp(t)>0?n:t}function hg(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 pg(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 A2(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 E2(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 mi,Sa,p,Qi,zt,_t,he,ma,gi,ba,gg,mg,bg,yg,id,rd,nu,$s,ya,wg,mt,De,et,ee,Rt,xg,Sg,iu,Ig,vg,Se,wa,sd,Ag,Eg,kg,od,ad,cd,ud,Tg,fd,ld,Og,Pg,Rg,Ng,_g,Cg,Bg,Lg,Mg,Ug,Dg,dd,ru,Hg,hd,Ws,X,pd=class pd{constructor(t){z(this,p);w(this,"sourceTXID");w(this,"sourceOutputIndex");w(this,"sourceSatoshis");w(this,"lockingScript");w(this,"transactionVersion");w(this,"otherInputs");w(this,"allInputs");w(this,"outputs");w(this,"inputIndex");w(this,"unlockingScript");w(this,"inputSequence");w(this,"lockTime");w(this,"context");w(this,"programCounter");w(this,"lastCodeSeparator");w(this,"stack");w(this,"altStack");w(this,"ifStack");w(this,"elseStack");w(this,"memoryLimit");w(this,"hasExplicitMemoryLimit");w(this,"stackMem");w(this,"altStackMem");w(this,"isRelaxedOverride");w(this,"verifyFlags");w(this,"executedOpCount");w(this,"returningFromConditional");z(this,mi);z(this,Sa);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,A(this,Sa,t.sigHashCache==null),A(this,mi,t.sigHashCache??{hashOutputsSingle:new Map}),this.reset()}reset(){g(this,Sa)&&(delete g(this,mi).hashPrevouts,delete g(this,mi).hashSequence,delete g(this,mi).hashOutputsAll,g(this,mi).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,p,Og).call(this);let t=a(this,p,Pg).call(this);if(this.programCounter>=t.chunks.length)return!1;let e=t.chunks[this.programCounter],i=a(this,p,Rg).call(this,e),r=!this.returningFromConditional&&!this.ifStack.includes(!1);if(a(this,p,Ng).call(this,i),r&&i>=0&&i<=x.OP_PUSHDATA4)a(this,p,_g).call(this,e);else if(r||i>=x.OP_IF&&i<=x.OP_ENDIF){let s,o,c,u,f,d,h,l,m,b,y,S,L,T,k,E,_,B,F,C,I,q,W,K,ot,ut;if(a(this,p,Cg).call(this,i,r),a(this,p,Bg).call(this,i,r))return!0;switch(a(this,p,Lg).call(this,i,r),i){case x.OP_VER:{let V=this.transactionVersion;a(this,p,mt).call(this,[V&255,V>>>8&255,V>>>16&255,V>>>24&255]);break}case x.OP_SUBSTR:{(()=>{this.stack.length<3&&a(this,p,X).call(this,"OP_SUBSTR requires at least three items to be on the stack.");let V=a(this,p,wa).call(this,a(this,p,et).call(this)),j=a(this,p,wa).call(this,a(this,p,et).call(this));s=a(this,p,et).call(this);let nt=s.length;(j<0||j>=nt||V<0||V>nt-j)&&a(this,p,X).call(this,`OP_SUBSTR offset (${j}) must be in range [0, ${nt}) and length (${V}) must be in range [0, ${nt-j}]`),a(this,p,mt).call(this,s.slice(j,j+V))})();break}case x.OP_LEFT:{(()=>{this.stack.length<2&&a(this,p,X).call(this,"OP_LEFT requires at least two items to be on the stack.");let V=a(this,p,wa).call(this,a(this,p,et).call(this));s=a(this,p,et).call(this);let j=s.length;(V<0||V>j)&&a(this,p,X).call(this,`OP_LEFT length (${V}) must be in range [0, ${j}]`),a(this,p,mt).call(this,s.slice(0,V))})();break}case x.OP_RIGHT:{(()=>{this.stack.length<2&&a(this,p,X).call(this,"OP_RIGHT requires at least two items to be on the stack.");let V=a(this,p,wa).call(this,a(this,p,et).call(this));s=a(this,p,et).call(this);let j=s.length;(V<0||V>j)&&a(this,p,X).call(this,`OP_RIGHT length (${V}) must be in range [0, ${j}]`),a(this,p,mt).call(this,s.slice(j-V))})();break}case x.OP_LSHIFTNUM:{(()=>{this.stack.length<2&&a(this,p,X).call(this,"OP_LSHIFTNUM requires at least two items to be on the stack.");let V=a(this,p,Se).call(this,a(this,p,et).call(this)).toBigInt();V<0&&a(this,p,X).call(this,"OP_LSHIFTNUM bits to shift must not be negative."),V>0x7fffffffn&&a(this,p,X).call(this,"OP_LSHIFTNUM shift count exceeds INT_MAX.");let j=a(this,p,Se).call(this,a(this,p,et).call(this)).toBigInt(),nt=a(this,p,nu).call(this);nt!==void 0&&j!==0n&&V>=BigInt(nt)*8n&&a(this,p,X).call(this,"script number overflow");let Ot=new O(j<<V).toScriptNum();nt!==void 0&&Ot.length>nt&&a(this,p,X).call(this,"script number overflow"),a(this,p,mt).call(this,Ot)})();break}case x.OP_RSHIFTNUM:{(()=>{this.stack.length<2&&a(this,p,X).call(this,"OP_RSHIFTNUM requires at least two items to be on the stack.");let V=a(this,p,Se).call(this,a(this,p,et).call(this)).toBigInt();V<0&&a(this,p,X).call(this,"OP_RSHIFTNUM bits to shift must not be negative."),V>0x7fffffffn&&a(this,p,X).call(this,"OP_RSHIFTNUM shift count exceeds INT_MAX.");let j=a(this,p,Se).call(this,a(this,p,et).call(this)).toBigInt(),nt;j<0?nt=new O(-(-j>>V)):nt=new O(j>>V),a(this,p,mt).call(this,nt.toScriptNum())})();break}case x.OP_1NEGATE:a(this,p,De).call(this,w2);break;case x.OP_0:a(this,p,De).call(this,lg[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,p,De).call(this,lg[S]);break;case x.OP_NOP:case x.OP_NOP1:break;case x.OP_CHECKLOCKTIMEVERIFY:a(this,p,Mg).call(this);break;case x.OP_CHECKSEQUENCEVERIFY:a(this,p,Ug).call(this);break;case x.OP_NOP9:case x.OP_NOP10:break;case x.OP_VERIF:case x.OP_VERNOTIF:(()=>{if(T=!1,r){if(this.stack.length<1&&a(this,p,X).call(this,"OP_VERIF and OP_VERNOTIF require at least one item on the stack when they are used!"),o=a(this,p,et).call(this),o.length===4){let V=this.transactionVersion;c=[V&255,V>>>8&255,V>>>16&255,V>>>24&255],T=dg(o,c)}i===x.OP_VERNOTIF&&(T=!T)}this.ifStack.push(T),this.elseStack.push(!1)})();break;case x.OP_IF:case x.OP_NOTIF:T=!1,r&&(this.stack.length<1&&a(this,p,X).call(this,"OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),s=a(this,p,et).call(this),a(this,p,_t).call(this,"MINIMALIF")&&a(this,p,gi).call(this)&&s.length>0&&!(s.length===1&&s[0]===1)&&a(this,p,X).call(this,"OP_IF and OP_NOTIF require minimal truth values."),T=a(this,p,Ws).call(this,s),i===x.OP_NOTIF&&(T=!T)),this.ifStack.push(T),this.elseStack.push(!1);break;case x.OP_ELSE:this.ifStack.length===0&&a(this,p,X).call(this,"OP_ELSE requires a preceeding OP_IF."),a(this,p,zt).call(this)&&a(this,p,he).call(this)&&this.elseStack.at(-1)===!0&&a(this,p,X).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,p,X).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,p,X).call(this,"OP_VERIFY requires at least one item to be on the stack."),o=a(this,p,ee).call(this),T=a(this,p,Ws).call(this,o),T||a(this,p,X).call(this,"OP_VERIFY requires the top stack value to be truthy."),a(this,p,et).call(this);break;case x.OP_RETURN:a(this,p,zt).call(this)&&!a(this,p,he).call(this)&&a(this,p,X).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,p,Rt).call(this,1,"OP_TOALTSTACK requires at oeast one item to be on the stack."),a(this,p,Ig).call(this,a(this,p,et).call(this));break;case x.OP_FROMALTSTACK:a(this,p,xg).call(this,1,"OP_FROMALTSTACK requires at least one item to be on the stack."),a(this,p,mt).call(this,a(this,p,vg).call(this));break;case x.OP_2DROP:a(this,p,Rt).call(this,2,"OP_2DROP requires at least two items to be on the stack."),a(this,p,et).call(this),a(this,p,et).call(this);break;case x.OP_2DUP:a(this,p,Rt).call(this,2,"OP_2DUP requires at least two items to be on the stack."),o=a(this,p,ee).call(this,-2),c=a(this,p,ee).call(this,-1),a(this,p,De).call(this,o),a(this,p,De).call(this,c);break;case x.OP_3DUP:a(this,p,Rt).call(this,3,"OP_3DUP requires at least three items to be on the stack."),o=a(this,p,ee).call(this,-3),c=a(this,p,ee).call(this,-2),u=a(this,p,ee).call(this,-1),a(this,p,De).call(this,o),a(this,p,De).call(this,c),a(this,p,De).call(this,u);break;case x.OP_2OVER:a(this,p,Rt).call(this,4,"OP_2OVER requires at least four items to be on the stack."),o=a(this,p,ee).call(this,-4),c=a(this,p,ee).call(this,-3),a(this,p,De).call(this,o),a(this,p,De).call(this,c);break;case x.OP_2ROT:{a(this,p,Rt).call(this,6,"OP_2ROT requires at least six items to be on the stack.");let V=a(this,p,et).call(this),j=a(this,p,et).call(this),nt=a(this,p,et).call(this),Ot=a(this,p,et).call(this),be=a(this,p,et).call(this),Mt=a(this,p,et).call(this);a(this,p,mt).call(this,Ot),a(this,p,mt).call(this,nt),a(this,p,mt).call(this,j),a(this,p,mt).call(this,V),a(this,p,mt).call(this,Mt),a(this,p,mt).call(this,be);break}case x.OP_2SWAP:{a(this,p,Rt).call(this,4,"OP_2SWAP requires at least four items to be on the stack.");let V=a(this,p,et).call(this),j=a(this,p,et).call(this),nt=a(this,p,et).call(this),Ot=a(this,p,et).call(this);a(this,p,mt).call(this,j),a(this,p,mt).call(this,V),a(this,p,mt).call(this,Ot),a(this,p,mt).call(this,nt);break}case x.OP_IFDUP:a(this,p,Rt).call(this,1,"OP_IFDUP requires at least one item to be on the stack."),o=a(this,p,ee).call(this),a(this,p,Ws).call(this,o)&&a(this,p,De).call(this,o);break;case x.OP_DEPTH:a(this,p,mt).call(this,new O(this.stack.length).toScriptNum());break;case x.OP_DROP:a(this,p,Rt).call(this,1,"OP_DROP requires at least one item to be on the stack."),a(this,p,et).call(this);break;case x.OP_DUP:a(this,p,Rt).call(this,1,"OP_DUP requires at least one item to be on the stack."),a(this,p,De).call(this,a(this,p,ee).call(this));break;case x.OP_NIP:a(this,p,Rt).call(this,2,"OP_NIP requires at least two items to be on the stack."),c=a(this,p,et).call(this),a(this,p,et).call(this),a(this,p,mt).call(this,c);break;case x.OP_OVER:a(this,p,Rt).call(this,2,"OP_OVER requires at least two items to be on the stack."),a(this,p,De).call(this,a(this,p,ee).call(this,-2));break;case x.OP_PICK:case x.OP_ROLL:{(()=>{a(this,p,Rt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),l=a(this,p,Se).call(this,a(this,p,et).call(this));let V=l.toBigInt();(V<0n||V>=BigInt(this.stack.length))&&a(this,p,X).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 j=Number(V),nt=this.stack[this.stack.length-1-j];i===x.OP_ROLL?(this.stack.splice(this.stack.length-1-j,1),this.stackMem-=nt.length,a(this,p,mt).call(this,nt)):a(this,p,De).call(this,nt)})();break}case x.OP_ROT:a(this,p,Rt).call(this,3,"OP_ROT requires at least three items to be on the stack."),h=a(this,p,et).call(this),d=a(this,p,et).call(this),f=a(this,p,et).call(this),a(this,p,mt).call(this,d),a(this,p,mt).call(this,h),a(this,p,mt).call(this,f);break;case x.OP_SWAP:a(this,p,Rt).call(this,2,"OP_SWAP requires at least two items to be on the stack."),d=a(this,p,et).call(this),f=a(this,p,et).call(this),a(this,p,mt).call(this,d),a(this,p,mt).call(this,f);break;case x.OP_TUCK:a(this,p,Rt).call(this,2,"OP_TUCK requires at least two items to be on the stack."),o=a(this,p,ee).call(this,-1),a(this,p,ya).call(this,o.length),this.stack.splice(-2,0,o.slice()),this.stackMem+=o.length;break;case x.OP_SIZE:a(this,p,Rt).call(this,1,"OP_SIZE requires at least one item to be on the stack."),a(this,p,mt).call(this,new O(a(this,p,ee).call(this).length).toScriptNum());break;case x.OP_AND:case x.OP_OR:case x.OP_XOR:{(()=>{a(this,p,Rt).call(this,2,`${x[i]} requires at least two items on the stack.`),c=a(this,p,et).call(this),o=a(this,p,et).call(this),o.length!==c.length&&a(this,p,X).call(this,`${x[i]} requires the top two stack items to be the same size.`);let V=Array.from({length:o.length},()=>0);for(let j=0;j<o.length;j++)i===x.OP_AND?V[j]=o[j]&c[j]:i===x.OP_OR?V[j]=o[j]|c[j]:V[j]=o[j]^c[j];a(this,p,mt).call(this,V)})();break}case x.OP_INVERT:{(()=>{a(this,p,Rt).call(this,1,"OP_INVERT requires at least one item to be on the stack."),s=a(this,p,et).call(this);let V=Array.from({length:s.length},()=>0);for(let j=0;j<s.length;j++)V[j]=~s[j]&255;a(this,p,mt).call(this,V)})();break}case x.OP_LSHIFT:case x.OP_RSHIFT:{(()=>{a(this,p,Rt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),b=a(this,p,Se).call(this,a(this,p,et).call(this)),o=a(this,p,et).call(this);let V=b.toBigInt();if(V<0n&&a(this,p,X).call(this,`${x[i]} requires the top item on the stack not to be negative.`),o.length===0){a(this,p,mt).call(this,[]);return}if(V>=BigInt(o.length)*8n){a(this,p,mt).call(this,Array.from({length:o.length},()=>0));return}m=new O(o);let j;if(i===x.OP_LSHIFT){j=m.ushln(V);let Ot=new O(1).ushln(o.length*8).isubn(1);j=j.iand(Ot)}else j=m.ushrn(V);let nt=j.toArray("be",o.length);a(this,p,mt).call(this,nt)})();break}case x.OP_EQUAL:case x.OP_EQUALVERIFY:a(this,p,Rt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),c=a(this,p,et).call(this),o=a(this,p,et).call(this),T=dg(o,c),a(this,p,mt).call(this,T?[1]:[]),i===x.OP_EQUALVERIFY&&(T||a(this,p,X).call(this,"OP_EQUALVERIFY requires the top two stack items to be equal."),a(this,p,et).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,p,Rt).call(this,1,`${x[i]} requires at least one item to be on the stack.`),l=a(this,p,Se).call(this,a(this,p,et).call(this)),i){case x.OP_1ADD:l=l.add(new O(1));break;case x.OP_1SUB:l=l.sub(new O(1));break;case x.OP_2MUL:l=l.mul(new O(2));break;case x.OP_2DIV:l=l.div(new O(2));break;case x.OP_NEGATE:l=l.neg();break;case x.OP_ABS:l.isNeg()&&(l=l.neg());break;case x.OP_NOT:l=new O(l.cmpn(0)===0?1:0);break;case x.OP_0NOTEQUAL:l=new O(l.cmpn(0)===0?0:1);break}a(this,p,mt).call(this,l.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,p,Rt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),c=a(this,p,et).call(this),o=a(this,p,et).call(this),b=a(this,p,Se).call(this,c),m=a(this,p,Se).call(this,o);let V=(()=>{switch(i){case x.OP_MUL:return m.byteLength()+b.byteLength();case x.OP_ADD:case x.OP_SUB:return Math.max(m.byteLength(),b.byteLength())+1;default:return Math.max(m.byteLength(),b.byteLength())}})();a(this,p,ya).call(this,V);let j=(()=>{switch(i){case x.OP_ADD:return m.add(b);case x.OP_SUB:return m.sub(b);case x.OP_MUL:return m.mul(b);case x.OP_DIV:return b.cmpn(0)===0&&a(this,p,X).call(this,"OP_DIV cannot divide by zero!"),m.div(b);case x.OP_MOD:return b.cmpn(0)===0&&a(this,p,X).call(this,"OP_MOD cannot divide by zero!"),m.mod(b);case x.OP_BOOLAND:return x2(m.cmpn(0)!==0,b.cmpn(0)!==0);case x.OP_BOOLOR:return S2(m.cmpn(0)!==0,b.cmpn(0)!==0);case x.OP_NUMEQUAL:case x.OP_NUMEQUALVERIFY:return tr(m.cmp(b)===0);case x.OP_NUMNOTEQUAL:return tr(m.cmp(b)!==0);case x.OP_LESSTHAN:return tr(m.cmp(b)<0);case x.OP_GREATERTHAN:return tr(m.cmp(b)>0);case x.OP_LESSTHANOREQUAL:return tr(m.cmp(b)<=0);case x.OP_GREATERTHANOREQUAL:return tr(m.cmp(b)>=0);case x.OP_MIN:return I2(m,b);case x.OP_MAX:return v2(m,b);default:return new O(0)}})();a(this,p,mt).call(this,j.toScriptNum()),i===x.OP_NUMEQUALVERIFY&&(a(this,p,Ws).call(this,a(this,p,ee).call(this))||a(this,p,X).call(this,"OP_NUMEQUALVERIFY requires the top stack item to be truthy."),a(this,p,et).call(this))})();break}case x.OP_WITHIN:a(this,p,Rt).call(this,3,"OP_WITHIN requires at least three items to be on the stack."),y=a(this,p,Se).call(this,a(this,p,et).call(this)),b=a(this,p,Se).call(this,a(this,p,et).call(this)),m=a(this,p,Se).call(this,a(this,p,et).call(this)),T=m.cmp(b)>=0&&m.cmp(y)<0,a(this,p,mt).call(this,T?[1]:[]);break;case x.OP_RIPEMD160:case x.OP_SHA1:case x.OP_SHA256:case x.OP_HASH160:case x.OP_HASH256:{(()=>{a(this,p,Rt).call(this,1,`${x[i]} requires at least one item to be on the stack.`),s=a(this,p,et).call(this);let V=[];i===x.OP_RIPEMD160?V=Bl(s):i===x.OP_SHA1?V=Ll(s):i===x.OP_SHA256?V=Le(s):i===x.OP_HASH160?V=Qo(s):i===x.OP_HASH256&&(V=ne(s)),a(this,p,mt).call(this,V)})();break}case x.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case x.OP_CHECKSIG:case x.OP_CHECKSIGVERIFY:{a(this,p,Rt).call(this,2,`${x[i]} requires at least two items to be on the stack.`),B=a(this,p,et).call(this),_=a(this,p,et).call(this),(!a(this,p,od).call(this,_)||!a(this,p,fd).call(this,B))&&a(this,p,X).call(this,`${x[i]} requires correct encoding for the public key and signature.`),k=(()=>{if(_.length===0)return!1;try{F=a(this,p,ad).call(this,_);let j=(this.context==="UnlockingScript"?this.unlockingScript:this.lockingScript).chunks.slice(this.lastCodeSeparator===null?0:this.lastCodeSeparator+1);return this.context==="UnlockingScript"&&(j=j.concat(this.lockingScript.chunks)),E=new Ae(j),((F.scope&At.SIGHASH_FORKID)===0||a(this,p,zt).call(this)&&!a(this,p,_t).call(this,"SIGHASH_FORKID"))&&E.findAndDelete(new Ae().writeBin(_)),C=jt.fromDER(B),a(this,p,ld).call(this,F,C,E)}catch{return!1}})(),!k&&a(this,p,_t).call(this,"NULLFAIL")&&a(this,p,gi).call(this)&&_.length>0&&a(this,p,X).call(this,`${x[i]} requires failing signatures to be empty.`),a(this,p,mt).call(this,k?[1]:[]),i===x.OP_CHECKSIGVERIFY&&(k||a(this,p,X).call(this,"OP_CHECKSIGVERIFY requires that a valid signature is provided."),a(this,p,et).call(this));break}case x.OP_CHECKMULTISIG:case x.OP_CHECKMULTISIGVERIFY:{(()=>{I=1,this.stack.length<I&&a(this,p,X).call(this,`${x[i]} requires at least 1 item for nKeys.`);let j=a(this,p,Se).call(this,a(this,p,ee).call(this,-I)).toBigInt(),nt=a(this,p,zt).call(this)&&!a(this,p,he).call(this)?BigInt(b2):m2;(j<0n||j>nt)&&a(this,p,X).call(this,`${x[i]} requires a key count between 0 and ${nt.toString()}.`),K=Number(j);let Ot=K;q=++I,I+=K,this.stack.length<I&&a(this,p,X).call(this,`${x[i]} stack too small for nKeys and keys. Need ${I}, have ${this.stack.length}.`);let Mt=a(this,p,Se).call(this,a(this,p,ee).call(this,-I)).toBigInt();(Mt<0n||Mt>BigInt(K))&&a(this,p,X).call(this,`${x[i]} requires the number of signatures to be no greater than the number of keys.`),ot=Number(Mt);let ln=ot;W=++I,I+=ot,this.stack.length<I&&a(this,p,X).call(this,`${x[i]} stack too small for N, keys, M, sigs, and dummy. Need ${I}, have ${this.stack.length}.`);let Y=(this.context==="UnlockingScript"?this.unlockingScript:this.lockingScript).chunks.slice(this.lastCodeSeparator===null?0:this.lastCodeSeparator+1);E=new Ae(Y);let pt=!1;for(let N=0;N<ot;N++)_=a(this,p,ee).call(this,-W-N),_.length>0&&(pt=!0),((_.at(-1)&At.SIGHASH_FORKID)===0||a(this,p,zt).call(this)&&!a(this,p,_t).call(this,"SIGHASH_FORKID"))&&E.findAndDelete(new Ae().writeBin(_));(()=>{for(k=!0;k&&ot>0;){if(K===0){k=!1;break}if(_=a(this,p,ee).call(this,-W),B=a(this,p,ee).call(this,-q),(!a(this,p,od).call(this,_)||!a(this,p,fd).call(this,B))&&a(this,p,X).call(this,`${x[i]} requires correct encoding for the public key and signature.`),ut=!1,_.length>0)try{F=a(this,p,ad).call(this,_),C=jt.fromDER(B),ut=a(this,p,ld).call(this,F,C,E)}catch{ut=!1}ut&&(W++,ot--),q++,K--,ot>K&&(k=!1)}})(),(()=>{!k&&a(this,p,_t).call(this,"NULLFAIL")&&a(this,p,gi).call(this)&&pt&&a(this,p,X).call(this,`${x[i]} requires failing signatures to be empty.`);let D=1+Ot+1+ln+1-1;for(;D>0;)a(this,p,et).call(this),D--;a(this,p,Rt).call(this,1,`${x[i]} requires an extra item (dummy) to be on the stack.`);let M=a(this,p,et).call(this);a(this,p,mg).call(this)&&M.length>0&&a(this,p,X).call(this,`${x[i]} requires the extra stack item (dummy) to be empty.`),a(this,p,mt).call(this,k?[1]:[]),i===x.OP_CHECKMULTISIGVERIFY&&(k||a(this,p,X).call(this,"OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),a(this,p,et).call(this))})()})();break}case x.OP_CAT:{(()=>{a(this,p,Rt).call(this,2,"OP_CAT requires at least two items to be on the stack."),c=a(this,p,et).call(this),o=a(this,p,et).call(this);let V=o.concat(c);V.length>a(this,p,$s).call(this)&&a(this,p,X).call(this,`It's not currently possible to push data larger than ${a(this,p,$s).call(this)} bytes.`),a(this,p,mt).call(this,V)})();break}case x.OP_SPLIT:{(()=>{a(this,p,Rt).call(this,2,"OP_SPLIT requires at least two items to be on the stack.");let V=a(this,p,et).call(this),j=a(this,p,et).call(this),nt=a(this,p,Se).call(this,V).toBigInt();(nt<0n||nt>BigInt(j.length))&&a(this,p,X).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 Ot=Number(nt);a(this,p,mt).call(this,j.slice(0,Ot)),a(this,p,mt).call(this,j.slice(Ot))})();break}case x.OP_NUM2BIN:{(()=>{a(this,p,Rt).call(this,2,"OP_NUM2BIN requires at least two items to be on the stack.");let V=a(this,p,Se).call(this,a(this,p,et).call(this)).toBigInt(),j=a(this,p,$s).call(this);if((Number.isFinite(j)&&V>BigInt(j)||V<0n)&&a(this,p,X).call(this,`It's not currently possible to push data larger than ${j} bytes or negative size.`),V>d2&&a(this,p,X).call(this,"OP_NUM2BIN size exceeds the node int32 push limit."),this.hasExplicitMemoryLimit&&Number.isFinite(this.memoryLimit)){let Mt=Math.max(0,Math.floor(this.memoryLimit));if(V>BigInt(Mt))throw new pi("element-size",Mt,V)}L=Number(V);let nt=a(this,p,et).call(this);if(nt=Xc(nt),nt.length>L&&a(this,p,X).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."),nt.length===L){a(this,p,mt).call(this,nt);return}let Ot=Array.from({length:L},()=>0),be=0;nt.length>0&&(be=nt.at(-1)&128,nt[nt.length-1]&=127);for(let Mt=0;Mt<nt.length;Mt++)Ot[Mt]=nt[Mt];be!==0&&(Ot[L-1]|=128),a(this,p,mt).call(this,Ot)})();break}case x.OP_BIN2NUM:{(()=>{a(this,p,Rt).call(this,1,"OP_BIN2NUM requires at least one item to be on the stack."),o=a(this,p,et).call(this);let V=Xc(o);pg(V)||a(this,p,X).call(this,"OP_BIN2NUM requires that the resulting number is valid."),a(this,p,mt).call(this,V)})();break}default:a(this,p,X).call(this,`Invalid opcode ${i} (pc=${this.programCounter}).`)}}return a(this,p,Dg).call(this,t),!0}validate(t){let e=eu(),i=a(this,p,dd).call(this),r=t===void 0?void 0:hg(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,p,X).call(this,"The selected script-verification backend rejected the spend."),!0):this.validateJavaScript()}validateJavaScript(){this.reset(),a(this,p,bg).call(this)&&!this.unlockingScript.isPushOnly()&&a(this,p,X).call(this,"Unlocking scripts can only contain push operations, and no other opcodes.");let t=this.lockingScript,e=a(this,p,_t).call(this,"P2SH")&&!a(this,p,he).call(this)&&a(this,p,Hg).call(this,this.lockingScript);e&&!this.unlockingScript.isPushOnly()&&a(this,p,X).call(this,"P2SH unlocking scripts can only contain push operations."),a(this,p,ru).call(this,"UnlockingScript");let i=this.stack.map(r=>r.slice());a(this,p,ru).call(this,"LockingScript"),a(this,p,hd).call(this);try{if(e){i.length===0&&a(this,p,X).call(this,"P2SH evaluation requires a redeem script on the stack.");let r=i.pop();if(r===void 0)return a(this,p,X).call(this,"P2SH evaluation requires a redeem script on the stack."),!1;a(this,p,Sg).call(this,i);let s=Ae.fromBinary(r);this.lockingScript=new qe(s.chunks),a(this,p,ru).call(this,"LockingScript")}}finally{this.lockingScript=t}return a(this,p,yg).call(this)&&this.stack.length!==1&&a(this,p,X).call(this,`The clean stack rule requires exactly one item to be on the stack after script execution, found ${this.stack.length}.`),a(this,p,hd).call(this),!0}async validateWith(t,e){let i=a(this,p,dd).call(this),r=e===void 0?void 0:hg(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 yt;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(ft(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()}};mi=new WeakMap,Sa=new WeakMap,p=new WeakSet,Qi=function(){return this.isRelaxedOverride||this.transactionVersion>1},zt=function(){return this.verifyFlags!==void 0},_t=function(t){return this.verifyFlags?.has(t)===!0},he=function(){return a(this,p,zt).call(this)?a(this,p,_t).call(this,"UTXO_AFTER_GENESIS")||a(this,p,_t).call(this,"UTXO_AFTER_CHRONICLE"):a(this,p,Qi).call(this)},ma=function(){return a(this,p,zt).call(this)?a(this,p,_t).call(this,"UTXO_AFTER_CHRONICLE"):a(this,p,Qi).call(this)},gi=function(){return!(a(this,p,_t).call(this,"CHRONICLE")&&this.transactionVersion>1)},ba=function(){return a(this,p,zt).call(this)?a(this,p,_t).call(this,"MINIMALDATA")&&a(this,p,gi).call(this):!a(this,p,Qi).call(this)},gg=function(){return a(this,p,zt).call(this)?a(this,p,_t).call(this,"LOW_S")&&a(this,p,gi).call(this):!a(this,p,Qi).call(this)},mg=function(){return a(this,p,zt).call(this)?a(this,p,_t).call(this,"NULLDUMMY")&&a(this,p,gi).call(this):!a(this,p,Qi).call(this)},bg=function(){return a(this,p,zt).call(this)?a(this,p,_t).call(this,"SIGPUSHONLY")&&a(this,p,gi).call(this):!a(this,p,Qi).call(this)},yg=function(){return a(this,p,zt).call(this)?a(this,p,_t).call(this,"CLEANSTACK")&&a(this,p,gi).call(this):!a(this,p,Qi).call(this)},id=function(){return a(this,p,zt).call(this)?a(this,p,_t).call(this,"DERSIG")||a(this,p,_t).call(this,"STRICTENC")||a(this,p,_t).call(this,"LOW_S")||a(this,p,_t).call(this,"SIGHASH_FORKID"):!0},rd=function(){return a(this,p,zt).call(this)?a(this,p,_t).call(this,"STRICTENC")||a(this,p,_t).call(this,"SIGHASH_FORKID"):!0},nu=function(){if(a(this,p,zt).call(this))return a(this,p,he).call(this)?a(this,p,ma).call(this)?p2:h2:4},$s=function(){return a(this,p,zt).call(this)&&!a(this,p,he).call(this)?l2:Number.POSITIVE_INFINITY},ya=function(t){if(this.stackMem+t>this.memoryLimit)throw new pi("stack",this.memoryLimit,this.stackMem+t)},wg=function(t){if(this.altStackMem+t>this.memoryLimit)throw new pi("alt-stack",this.memoryLimit,this.altStackMem+t)},mt=function(t){a(this,p,ya).call(this,t.length),this.stack.push(t),this.stackMem+=t.length},De=function(t){a(this,p,ya).call(this,t.length);let e=t.slice();this.stack.push(e),this.stackMem+=e.length},et=function(){this.stack.length===0&&a(this,p,X).call(this,"Attempted to pop from an empty stack.");let t=this.stack.pop();return t===void 0?(a(this,p,X).call(this,"Attempted to pop from an empty stack."),[]):(this.stackMem-=t.length,t)},ee=function(t=-1){return(this.stack.length===0||this.stack.length<Math.abs(t)||t>=0&&t>=this.stack.length)&&a(this,p,X).call(this,`Stack underflow accessing element at index ${t}. Stack length is ${this.stack.length}.`),this.stack[this.stack.length+t]},Rt=function(t,e){this.stack.length<t&&a(this,p,X).call(this,e)},xg=function(t,e){this.altStack.length<t&&a(this,p,X).call(this,e)},Sg=function(t){this.stack=t.map(e=>e.slice()),this.stackMem=this.stack.reduce((e,i)=>e+i.length,0)},iu=function(){this.altStack=[],this.altStackMem=0},Ig=function(t){a(this,p,wg).call(this,t.length),this.altStack.push(t),this.altStackMem+=t.length},vg=function(){this.altStack.length===0&&a(this,p,X).call(this,"Attempted to pop from an empty alt stack.");let t=this.altStack.pop();return t===void 0?(a(this,p,X).call(this,"Attempted to pop from an empty alt stack."),[]):(this.altStackMem-=t.length,t)},Se=function(t){try{return O.fromScriptNum(t,a(this,p,ba).call(this),a(this,p,nu).call(this))}catch(e){let i=e instanceof Error?e.message:String(e);a(this,p,X).call(this,i)}return new O(0)},wa=function(t){let e=a(this,p,nu).call(this);e!==void 0&&t.length>e&&a(this,p,X).call(this,"script number overflow"),a(this,p,ba).call(this)&&!pg(t)&&a(this,p,X).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,p,Se).call(this,t).toBigInt();return i>0x7fffffffn?2147483647:i<-0x80000000n?-2147483648:Number(i)},sd=function(t){try{return O.fromScriptNum(t,a(this,p,ba).call(this),5).toBigInt()}catch(e){a(this,p,X).call(this,e instanceof Error?e.message:String(e))}return 0n},Ag=function(t){let e=t&31;return e>=At.SIGHASH_ALL&&e<=At.SIGHASH_SINGLE},Eg=function(t){if(!a(this,p,rd).call(this))return;a(this,p,Ag).call(this,t.scope)||a(this,p,X).call(this,"The signature hash type is invalid.");let e=(t.scope&At.SIGHASH_CHRONICLE)!==0,i=a(this,p,zt).call(this)?a(this,p,_t).call(this,"CHRONICLE"):a(this,p,ma).call(this);e&&!i&&a(this,p,X).call(this,"The signature hash type is invalid before Chronicle.")},kg=function(t){if(!a(this,p,zt).call(this)||!a(this,p,_t).call(this,"STRICTENC"))return;let e=(t.scope&At.SIGHASH_FORKID)!==0;a(this,p,_t).call(this,"SIGHASH_FORKID")&&!e&&a(this,p,X).call(this,"The signature must use SIGHASH_FORKID."),!a(this,p,_t).call(this,"SIGHASH_FORKID")&&!a(this,p,he).call(this)&&e&&a(this,p,X).call(this,"The signature must not use SIGHASH_FORKID.")},od=function(t){if(t.length===0)return!0;let e=a(this,p,id).call(this);if(e&&!A2(t))return a(this,p,X).call(this,"The signature format is invalid."),!1;try{let i=At.fromChecksigFormat(t);if(a(this,p,Eg).call(this,i),a(this,p,kg).call(this,i),a(this,p,gg).call(this)&&!i.hasLowS())return a(this,p,X).call(this,"The signature must have a low S value."),!1}catch{if(e)return a(this,p,X).call(this,"The signature format is invalid."),!1}return!0},ad=function(t){try{return At.fromChecksigFormat(t)}catch(e){if(a(this,p,id).call(this))throw e;return a(this,p,Tg).call(this,t)}},cd=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},ud=function(t,e,i){if(e.value>=i||t[e.value++]!==2)throw new Error("Invalid DER integer");let r=a(this,p,cd).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 O(s)},Tg=function(t){if(t.length===0)return At.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,p,cd).call(this,i,r),o=Math.min(r.value+s,i.length),c=a(this,p,ud).call(this,i,r,o),u=a(this,p,ud).call(this,i,r,o);return new At(c,u,e)},fd=function(t){if(!a(this,p,rd).call(this))return!0;if(t.length===0)return a(this,p,X).call(this,"Public key is empty."),!1;if(t.length<33)return a(this,p,X).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,p,X).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,p,X).call(this,"The compressed public key must be 33 bytes."),!1}else return a(this,p,X).call(this,"The public key is in an unknown format."),!1;try{jt.fromDER(t)}catch{return a(this,p,X).call(this,"The public key is in an unknown format."),!1}return!0},ld=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,p,zt).call(this)||a(this,p,_t).call(this,"SIGHASH_FORKID"),cache:g(this,mi)},s=At.usesOtdaSingleBug(r)?new O([1,...Array.from({length:31},()=>0)]):new O(ne(At.formatBytes(r)));return Ji(s,t,e)},Og=function(){if(this.stackMem>this.memoryLimit)throw new pi("stack",this.memoryLimit,this.stackMem);if(this.altStackMem>this.memoryLimit)throw new pi("alt-stack",this.memoryLimit,this.altStackMem)},Pg=function(){return this.context==="UnlockingScript"&&this.programCounter>=this.unlockingScript.chunks.length&&(this.ifStack.length>0&&a(this,p,X).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,p,iu).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},Rg=function(t){let e=t.op;return e===void 0?(a(this,p,X).call(this,`Missing opcode in ${this.context} at pc=${this.programCounter}.`),0):(t.invalidLength===!0&&a(this,p,X).call(this,`Malformed push data in ${this.context} at pc=${this.programCounter}.`),Array.isArray(t.data)&&t.data.length>a(this,p,$s).call(this)&&a(this,p,X).call(this,`Data push > ${a(this,p,$s).call(this)} bytes (pc=${this.programCounter}).`),e)},Ng=function(t){a(this,p,zt).call(this)&&!a(this,p,he).call(this)&&!a(this,p,ma).call(this)&&(t===x.OP_2MUL||t===x.OP_2DIV||t===x.OP_VERIF||t===x.OP_VERNOTIF)&&a(this,p,X).call(this,`${x[t]} is disabled until Chronicle.`)},_g=function(t){a(this,p,ba).call(this)&&!E2(t)&&a(this,p,X).call(this,`This data is not minimally-encoded. (PC: ${this.programCounter})`),a(this,p,mt).call(this,Array.isArray(t.data)?t.data:[])},Cg=function(t,e){!e||t<=x.OP_16||(this.executedOpCount++,a(this,p,zt).call(this)&&!a(this,p,he).call(this)&&this.executedOpCount>ag&&a(this,p,X).call(this,`Script executed more than ${ag} opcodes.`))},Bg=function(t,e){return!a(this,p,zt).call(this)||a(this,p,ma).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,p,_t).call(this,"DISCOURAGE_UPGRADABLE_NOPS")&&a(this,p,X).call(this,`${x[t]} is discouraged by verification flags.`),this.programCounter++,!0):((e||!a(this,p,he).call(this))&&(t===x.OP_2MUL||t===x.OP_2DIV)&&a(this,p,X).call(this,`${x[t]} is disabled until Chronicle.`),(e||!a(this,p,he).call(this))&&(t===x.OP_VER||t===x.OP_VERIF||t===x.OP_VERNOTIF)&&a(this,p,X).call(this,`${x[t]} is disabled until Chronicle.`),!e&&a(this,p,he).call(this)&&(t===x.OP_VERIF||t===x.OP_VERNOTIF)?(this.programCounter++,!0):!1)},Lg=function(t,e){let i=t===x.OP_CHECKLOCKTIMEVERIFY&&(!a(this,p,_t).call(this,"CHECKLOCKTIMEVERIFY")||a(this,p,he).call(this)),r=t===x.OP_CHECKSEQUENCEVERIFY&&(!a(this,p,_t).call(this,"CHECKSEQUENCEVERIFY")||a(this,p,he).call(this));e&&a(this,p,_t).call(this,"DISCOURAGE_UPGRADABLE_NOPS")&&(t===x.OP_NOP1||i||r||t===x.OP_NOP9||t===x.OP_NOP10)&&a(this,p,X).call(this,`${x[t]} is discouraged by verification flags.`)},Mg=function(){if(!a(this,p,_t).call(this,"CHECKLOCKTIMEVERIFY")||a(this,p,he).call(this))return;a(this,p,Rt).call(this,1,"OP_CHECKLOCKTIMEVERIFY requires one stack item.");let t=a(this,p,sd).call(this,a(this,p,ee).call(this));t<0n&&a(this,p,X).call(this,"Negative lock time.");let e=t<BigInt(fg),i=this.lockTime<fg;(e!==i||t>BigInt(this.lockTime)||this.inputSequence===4294967295)&&a(this,p,X).call(this,"OP_CHECKLOCKTIMEVERIFY lock time is unsatisfied.")},Ug=function(){if(!a(this,p,_t).call(this,"CHECKSEQUENCEVERIFY")||a(this,p,he).call(this))return;a(this,p,Rt).call(this,1,"OP_CHECKSEQUENCEVERIFY requires at least one item to be on the stack.");let t=a(this,p,sd).call(this,a(this,p,ee).call(this));if(t<0n&&a(this,p,X).call(this,"OP_CHECKSEQUENCEVERIFY requires a non-negative lock time."),(t&BigInt(ug))!==0n)return;let e=BigInt(this.inputSequence>>>0),i=BigInt(nd|y2),r=t&i,s=e&i;(this.transactionVersion>>>0<2||(e&BigInt(ug))!==0n||(r&BigInt(nd))!==(s&BigInt(nd))||r>s)&&a(this,p,X).call(this,"OP_CHECKSEQUENCEVERIFY lock time is unsatisfied.")},Dg=function(t){this.returningFromConditional&&this.ifStack.length===0?this.programCounter=t.chunks.length:this.programCounter++,a(this,p,zt).call(this)&&!a(this,p,he).call(this)&&this.stack.length+this.altStack.length>cg&&a(this,p,X).call(this,`Stack item count has exceeded ${cg}.`)},dd=function(){let t=r=>new qe(r.chunks.map(s=>({op:s.op,data:s.data===void 0?void 0:Array.from(s.data),invalidLength:s.invalidLength}))),e=r=>new Ve(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 pd({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)})},ru=function(t){this.context=t,this.programCounter=0,this.ifStack=[],this.elseStack=[],this.returningFromConditional=!1,a(this,p,iu).call(this),this.lastCodeSeparator=null;let e=t==="UnlockingScript"?this.unlockingScript:this.lockingScript;for(a(this,p,zt).call(this)&&!a(this,p,he).call(this)&&e.toUint8Array().length>og&&a(this,p,X).call(this,`Script size exceeds ${og} bytes.`);this.programCounter<e.chunks.length;)this.step();this.ifStack.length>0&&a(this,p,X).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,p,iu).call(this),this.lastCodeSeparator=null},Hg=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},hd=function(){this.stack.length===0?a(this,p,X).call(this,"The top stack element must be truthy after script evaluation (stack is empty)."):a(this,p,Ws).call(this,a(this,p,ee).call(this))||a(this,p,X).call(this,"The top stack element must be truthy after script evaluation.")},Ws=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},X=function(t){throw new ga({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 xa=pd;var k2=21e14,T2=4294967295;function su(n,t){if(!Number.isSafeInteger(n)||n<0||n>T2)throw new Error(`${t} must be an unsigned 32-bit integer`);return n}function gd(n,t){if(!Number.isSafeInteger(n)||n<0||n>k2)throw new Error(`${t} must be a valid number of satoshis`);return n}function md(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 bd(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 $g(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=At.SIGHASH_FORKID;return n==="all"&&(e|=At.SIGHASH_ALL),n==="none"&&(e|=At.SIGHASH_NONE),n==="single"&&(e|=At.SIGHASH_SINGLE),t&&(e|=At.SIGHASH_ANYONECANPAY),e}function Wg(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=su(r.sourceOutputIndex,"input.sourceOutputIndex"),o=r.sourceTXID===void 0?void 0:md(r.sourceTXID,"input.sourceTXID"),c=r.sourceTransaction===void 0?void 0:md(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:gd(e,"sourceSatoshis"),h=f?.satoshis===void 0?void 0:gd(f.satoshis,"sourceTransaction output satoshis");if(d!==void 0&&h!==void 0&&d!==h)throw new Error("The sourceSatoshis does not match the input sourceTransaction output.");let l=d??h;if(l===void 0)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");let m=i===void 0?void 0:bd(i,"lockingScript"),b=f?.lockingScript===void 0?void 0:bd(f.lockingScript,"sourceTransaction output lockingScript");if(m!==void 0&&b!==void 0&&m.toHex().toLowerCase()!==b.toHex().toLowerCase())throw new Error("The lockingScript does not match the input sourceTransaction output.");let y=m??b;if(y===void 0)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");return{sourceTXID:u,sourceSatoshis:l,lockingScript:y,allInputs:n.inputs,get otherInputs(){return n.inputs.filter((S,L)=>L!==t)}}}function Fg(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];su(d.sourceOutputIndex,"input.sourceOutputIndex"),gd(s,"sourceSatoshis"),md(r,"sourceTXID"),bd(o,"lockingScript"),su(i,"signatureScope");let h=f??Fr(d.sequence,"input.sequence must have value");return su(h,"inputSequence"),At.format({sourceTXID:r,sourceOutputIndex:Fr(d.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:s,transactionVersion:t.version,otherInputs:c??[],allInputs:u,inputIndex:e,outputs:t.outputs,inputSequence:h,subscript:o,lockTime:t.lockTime,scope:i,cache:t.getSignatureHashCache()})}var bi=class{lock(t){let e;if(typeof t=="string"){let i=ua(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 qe([{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=$g(e,i),f=Wg(o,c,r,s),d=Fg({tx:o,inputIndex:c,signatureScope:u,sourceTXID:f.sourceTXID,sourceSatoshis:f.sourceSatoshis,lockingScript:f.lockingScript,allInputs:f.allInputs}),h=Le(d),l=ed("signDigest"),m=ed("publicKeyFromPrivate"),b=l===void 0&&m===void 0?void 0:Uint8Array.from(t.toArray("be",32)),y=m===void 0?t.toPublicKey().encode(!0):void 0,S=l===void 0?t.sign(h):ve.fromDER(Array.from(td("signDigest",await l.signDigest(b,Uint8Array.from(Le(h)))))),T=new At(S.r,S.s,u).toChecksigFormat(),k=m===void 0?y:Array.from(O2(await m.publicKeyFromPrivate(b)));return new Ve([{op:T.length,data:T},{op:k.length,data:k}])},estimateLength:async()=>108}}};function O2(n){let t=td("publicKeyFromPrivate",n,33);if(t[0]!==2&&t[0]!==3)throw new Error("publicKeyFromPrivate returned an invalid compressed public key");return t}var Ia=class{constructor(t){w(this,"value");qg(t),this.value=t}async computeFee(t){let e=this.value;qg(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 qg(n){if(!Number.isFinite(n)||n<0||n>21e14)throw new RangeError("Satoshis-per-kilobyte rate must be finite and non-negative.")}var ou=8*1024*1024,au=3e4;function Vg(n={}){let t=n.maxResponseBytes??ou,e=n.timeoutMs??au;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 Kg(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 zg(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(Qe(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 Xg(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,h,l=()=>{h!==void 0&&clearTimeout(h),e.signal?.removeEventListener("abort",y)},m=S=>{f||(f=!0,l(),s(S))},b=S=>{f||(f=!0,l(),r(S))},y=()=>{let S=e.signal?.reason instanceof Error?e.signal.reason:new DOMException("HTTP request aborted","AbortError");d?.destroy?.(S),m(S)};d=n.request(t,u,S=>{let L=S.headers?.["content-length"],T=typeof L=="string"?Number(L):void 0;if(typeof L=="string"&&!/^(0|[1-9]\d*)$/.test(L)||T!==void 0&&(!Number.isSafeInteger(T)||T>ou)){S.destroy?.(),m(new Error("HTTP response exceeds the configured size limit"));return}let k=[],E=0;S.on("data",_=>{if(f)return;let B=typeof _=="string"?Pe(_):new Uint8Array(_);if(E+=B.byteLength,!Number.isSafeInteger(E)||E>ou){S.destroy?.(),d.destroy?.(),m(new Error("HTTP response exceeds the configured size limit"));return}k.push(B)}),S.on("end",()=>{if(!f)try{if(T!==void 0&&T!==E)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 _=new Uint8Array(E),B=0;for(let W of k)_.set(W,B),B+=W.byteLength;let F=new TextDecoder("utf-8",{fatal:!0}).decode(_),C=S.statusCode>=200&&S.statusCode<=299,I=S.headers["content-type"],q=F!==""&&typeof I=="string"&&I.startsWith("application/json")?JSON.parse(F):F;b({status:S.statusCode,statusText:S.statusMessage??"",ok:C,data:q})}catch(_){m(_)}}),S.on("error",m),S.on("aborted",()=>m(new Error("HTTP response was aborted")))}),d.on("error",m),f||(h=setTimeout(()=>{let S=new Error("HTTP request timed out");d.destroy?.(S),m(S)},au)),d.setTimeout?.(au,()=>{let S=new Error("HTTP request timed out");d.destroy?.(S),m(S)}),e.signal?.aborted===!0?y():e.signal?.addEventListener("abort",y,{once:!0}),!f&&(o!==void 0&&d.write(o),d.end())})}var cu=class{constructor(t){w(this,"https");this.https=t}async request(t,e){return await Xg(this.https,t,e,i=>JSON.stringify(i))}};var va=class{constructor(t,e={}){w(this,"fetch");w(this,"limits");this.fetch=t,this.limits=Vg(e)}async request(t,e){let i=Kg(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(),Qe(JSON.stringify(u))>this.limits.maxResponseBytes)throw new Error("HTTP response exceeds the configured size limit")}else{let f=await zg(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 Zr(){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 va(globalThis.window.fetch.bind(globalThis.window));if(typeof globalThis.fetch=="function")return new va(globalThis.fetch.bind(globalThis));let t=typeof ml=="function"?ml:void 0;if(t===void 0)return n;try{let e=t(["node","https"].join(":"));return new cu(e)}catch{return n}}var Kn=class Kn extends Ia{constructor(e=300*1e3){super(100);w(this,"cachedRate",null);w(this,"cacheTimestamp",0);w(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 Kn.instance??(Kn.instance=new Kn(e)),Kn.instance}async fetchFeeRate(){let e=Date.now();if(this.cachedRate!==null&&e-this.cacheTimestamp<this.cacheValidityMs)return this.cachedRate;try{let i=await Zr().request(Kn.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)}};w(Kn,"ARC_POLICY_URL","https://arc.gorillapool.io/v1/policy"),w(Kn,"instance",null);var Aa=Kn;function Tn(n){return n==="__proto__"||n==="constructor"||n==="prototype"}function jg(n){if(n==null||typeof n!="object"||Array.isArray(n))return!1;let t=Object.getPrototypeOf(n);return t===Object.prototype||t===null}var uu=/^[0-9a-f]{64}$/i,Gg=8192,P2=128,R2=256;function er(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 yd(n,t){return typeof n=="string"&&Qe(n)<=t}function Jr(){return{status:"error",code:"ERR_INVALID_RESPONSE",description:"Broadcaster returned a malformed or transaction-mismatched response."}}function Yg(n,t){if(!uu.test(t)||!jg(n))return Jr();let e=er(n,"status").value;if(e==="success"){let u=er(n,"txid").value,f=er(n,"message").value,d=er(n,"competingTxs");if(typeof u!="string"||!uu.test(u)||u.toLowerCase()!==t.toLowerCase()||!yd(f,Gg))return Jr();let h={status:"success",txid:t.toLowerCase(),message:f};if(d.present){if(!Array.isArray(d.value)||d.value.length>R2)return Jr();let l=[],m=new Set;for(let b=0;b<d.value.length;b++){let y=Object.getOwnPropertyDescriptor(d.value,b),S=y?.value;if(y==null||!Object.prototype.hasOwnProperty.call(y,"value")||typeof S!="string"||!uu.test(S))return Jr();let L=S.toLowerCase();if(m.has(L))return Jr();m.add(L),l.push(L)}h.competingTxs=l}return h}if(e!=="error")return Jr();let i=er(n,"code").value,r=er(n,"description").value,s=er(n,"txid");if(!yd(i,P2)||!yd(r,Gg)||s.present&&(typeof s.value!="string"||!uu.test(s.value)||s.value.toLowerCase()!==t.toLowerCase()))return Jr();let o={status:"error",code:i,description:r};s.present&&(o.txid=t.toLowerCase());let c=er(n,"more");return c.present&&c.value!=null&&typeof c.value=="object"&&(o.more=c.value),o}function Zg(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("Invalid offset")}var On=(n,t)=>Math.floor(n/2**t),Ea=n=>n%2===0?n+1:n-1,wd=(n,t,e)=>On(n,e)===On(t,e),xd=n=>n===0?0:n.toString(2).length;function Pn(n,t){return st(ne(ft((n??"")+(t??""),"hex").reverse()).reverse())}function N2(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 Jg(n,t,e,i,r,s){if(t==null){if(s)return Pn(n,n);throw new Error(`Missing hash for index ${i} at height ${r}`)}return t.duplicate===!0?Pn(n,n):e%2===1?Pn(t.hash,n):Pn(n,t.hash)}var nr=class n{constructor(t,e,i=!0,r=!0){w(this,"blockHeight");w(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((h,l)=>{if(!Array.isArray(h))throw new TypeError(`Merkle Path level ${l} must be an array`);return h.map(m=>({...m}))});let s=Array.from({length:this.path.length}).fill(0).map(()=>new Set);if(this.path.forEach((h,l)=>{if(h.length===0&&l===0)throw new Error(`Empty level at height: ${l}`);let m=new Set;h.forEach(b=>{if(Zg(b.offset),m.has(b.offset))throw new Error(`Duplicate offset: ${b.offset}, at height: ${l}`);if(m.add(b.offset),l===0){if(b.duplicate!==!0)for(let y=1;y<this.path.length;y++)s[y].add(Ea(On(b.offset,y)))}else if(i&&!s[l].has(b.offset))throw new Error(`Invalid offset: ${b.offset}, at height: ${l}, with legal offsets: ${Array.from(s[l],y=>y.toString()).join(", ")}`)})}),!r)return;let o=this.path.map(h=>new Map(h.map(l=>[l.offset,l]))),c=new Map,u=new Map,f=this.path[0].reduce((h,l)=>Math.max(h,l.offset),0),d;this.path[0].forEach((h,l)=>{let m=this.computeRootCached(h.hash,o,c,u,f);if(l===0&&(d=m),d!==m)throw new Error("Mismatched roots")})}static fromHex(t){return n.fromBinary(ft(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 h={offset:u};(c&1)===1?h.duplicate=!0:((c&2)!==0&&(h.txid=!0),h.hash=st(t.read(32).reverse())),(!Array.isArray(o[d])||o[d].length===0)&&(o[d]=[]),o[d].push(h),f--}o[d].sort((h,l)=>h.offset-l.offset)}return new n(r,o,e,i)}static fromBinary(t,e=!0,i=!0){let r=new vt(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(ft(s.hash,"hex").reverse())}}}toBinary(){let t=new we;return this.toWriter(t),t.toArray()}toBinaryUint8Array(){let t=new yt;return this.toWriter(t),t.toUint8Array()}toHex(){return st(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,xd(s)),u=t;for(let f=0;f<c;f++){let d=`${f}:${On(o,f)}`,h=N2(d,u,c,r);if(h!=null)return h;r.set(d,u);let l=Ea(On(o,f)),m=this.cachedFindLeaf(f,l,e,i,s);u=Jg(u,m,l,o,f,this.path.length===1&&wd(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,xd(r));for(let o=0;o<s;o++){let c=Ea(On(e,o));i=Jg(i,this.findOrComputeLeaf(o,c),c,e,o,this.path.length===1&&wd(e,r,o))}return i}findOrComputeLeaf(t,e){Zg(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:Pn(o.hash,o.hash)};if(this.path.length===1){let f=this.path[0].reduce((d,h)=>Math.max(d,h.offset),0);if(s===On(f,r))return{offset:e,hash:Pn(o.hash,o.hash)}}return}let u;return c.duplicate===!0?u=Pn(o.hash,o.hash):u=Pn(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(On(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(On(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 h=this.cachedFindLeaf(u,f+1,i,r,s);if(h?.hash==null){if(h?.duplicate===!0||this.path.length===1&&f===On(s,u))return c={offset:e,hash:Pn(d.hash,d.hash)},r.set(o,c),c;r.set(o,void 0);return}let l=h.duplicate===!0?Pn(d.hash,d.hash):Pn(h.hash,d.hash);return c={offset:e,hash:l},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((h,l)=>Math.max(h,l.offset),0),r=Math.max(this.path.length,xd(i)),s=this.createSourceLeafIndex(),o=new Map,c=this.createTxidToOffsetIndex(),u=this.createNeededLeafLevels(r);for(let h of t)this.collectExtractedLeaves(h,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=Ea(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 h=Ea(On(u,d));if(i[d].has(h))continue;let l=this.cachedFindLeaf(d,h,r,s,o);l!=null?i[d].set(h,l):wd(u,o,d)&&i[d].set(h,{offset:h,duplicate:!0})}}buildExtractedPath(t){return t.map(e=>Array.from(e.values()).sort((i,r)=>i.offset-r.offset))}};var _2=32,C2=64;function Qg(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 Fs(n,t,e){if(n!==void 0){if(typeof n!="string"||Qe(n)>e||Cr(n))throw new TypeError(`${t} must be bounded text without control characters.`);return n}}function B2(n){if(n===void 0)return;let t=Qg(n,"ARC headers",C2),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=Fs(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 L2(n){let t=n??Zr();if(t==null||typeof t!="object"||typeof t.request!="function")throw new TypeError("ARC httpClient must provide request().");return t}function tm(n,t){if(typeof n=="string")return Object.freeze({apiKey:Fs(n,"ARC API key",16*1024),httpClient:Zr(),deploymentId:t()});let e=Qg(n??{},"ARC config",_2),i=r=>e[r]?.value;return Object.freeze({apiKey:Fs(i("apiKey"),"ARC API key",16*1024),httpClient:L2(i("httpClient")),deploymentId:Fs(i("deploymentId"),"ARC deployment ID",256)??t(),callbackUrl:Fs(i("callbackUrl"),"ARC callback URL",2048),callbackToken:Fs(i("callbackToken"),"ARC callback token",16*1024),headers:B2(i("headers"))})}function em(n){if(typeof n!="string"||n.length===0||Qe(n)>2048||Cr(n))throw new TypeError("ARC URL must be nonempty bounded text without control characters.");return n}function fu(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 M2(){return`ts-sdk-${st(Ue(16))}`}var U2=new Set(["DOUBLE_SPEND_ATTEMPTED","REJECTED","INVALID","MALFORMED","MINED_IN_STALE_BLOCK"]),qs=/^[0-9a-f]{64}$/i,om=128,am=8192,D2=256,H2=32,$2=new Set(["SUCCESS","RECEIVED","SENT_TO_NETWORK","ANNOUNCED_TO_NETWORK","ACCEPTED_BY_NETWORK","SEEN_ON_NETWORK","STORED","MINED","IMMUTABLE"]);function lu(n,t,e=!0){return typeof n=="string"&&(e||n.length!==0)&&Qe(n)<=t&&!Cr(n)}function Id(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>H2||Object.values(e).some(i=>i.get!=null||i.set!=null)))return e}function W2(n){if(n===void 0||!Array.isArray(n)||n.length>D2)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"||!qs.test(o))return;let c=o.toLowerCase();if(r.has(c))return;r.add(c),i.push(c)}return i}function nm(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 Qr(n){return{status:"error",code:"ERR_INVALID_RESPONSE",description:n}}function im(n,t){let e=Id(n);if(e===void 0)return Qr("ARC returned a malformed response.");let i=l=>e[l]?.value,r=i("txid"),s=i("extraInfo"),o=i("txStatus"),c=i("competingTxs");if(!lu(o,om,!1)||s!==void 0&&!lu(s,am))return Qr("ARC returned invalid transaction status metadata.");let u=W2(c);if(c!==void 0&&u===void 0)return Qr("ARC returned invalid competing transaction identifiers.");let f=o.toUpperCase(),d=s?.toUpperCase().includes("ORPHAN")||f.includes("ORPHAN");if(U2.has(f)||d){if(typeof r=="string"&&qs.test(r)&&r.toLowerCase()!==t.toLowerCase())return{status:"error",code:"ERR_TXID_MISMATCH",description:"ARC returned a failure for another transaction."};let l={status:"error",code:o,description:`${o} ${s??""}`.trim()};return typeof r=="string"&&qs.test(r)&&(l.txid=t.toLowerCase()),u!=null&&(l.more={competingTxs:u}),l}if(!$2.has(f))return Qr("ARC returned an unknown transaction status.");if(typeof r!="string"||!qs.test(r)||r.toLowerCase()!==t.toLowerCase())return{status:"error",code:"ERR_TXID_MISMATCH",description:"ARC acknowledged a transaction other than the submitted transaction."};let h={status:"success",txid:t,message:`${o} ${s??""}`.trim()};return u!=null&&(h.competingTxs=u),h}function F2(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch{return n}}function rm(n,t,e){let r={status:"error",code:typeof n=="number"&&Number.isSafeInteger(n)||typeof n=="string"&&lu(n,om,!1)?n.toString():"ERR_UNKNOWN",description:"Unknown error"},s=F2(t),o=Id(s);if(o===void 0)return r;let c=o.detail?.value,u=o.txid?.value;if(typeof u=="string"&&qs.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 lu(c,am)&&(r.description=c,f.detail=c),r.txid!==void 0&&(f.txid=r.txid),Object.keys(f).length!==0&&(r.more=f),r}function sm(){return{status:"error",code:"500",description:"Internal Server Error"}}var Vs,Ta,Sd,ka=class{constructor(t,e){z(this,Ta);w(this,"URL");w(this,"apiKey");w(this,"deploymentId");w(this,"callbackUrl");w(this,"callbackToken");w(this,"headers");z(this,Vs);this.URL=em(t);let i=tm(e,M2);this.apiKey=i.apiKey,A(this,Vs,i.httpClient),this.deploymentId=i.deploymentId,this.callbackToken=i.callbackToken,this.callbackUrl=i.callbackUrl,this.headers=i.headers,fu(this,["URL","apiKey","deploymentId","callbackUrl","callbackToken","headers"])}async broadcast(t){let e={method:"POST",headers:a(this,Ta,Sd).call(this),data:{rawTx:nm(t)}};try{let i=await g(this,Vs).request(`${this.URL}/v1/tx`,e);return i.ok?im(i.data,t.id("hex")):rm(i.status,i.data,t.id("hex"))}catch{return sm()}}async broadcastMany(t){let e=t.map(r=>({rawTx:nm(r)})),i={method:"POST",headers:a(this,Ta,Sd).call(this),data:e};try{let r=await g(this,Vs).request(`${this.URL}/v1/txs`,i);if(!r.ok)return t.map(u=>rm(r.status,r.data,u.id("hex")));if(!Array.isArray(r.data)||r.data.length!==t.length)return t.map(()=>Qr("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(()=>Qr("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,h=Id(d);if(h===void 0)return Qr("ARC returned a malformed batch result.");let l=h.txid?.value,m=typeof l=="string"&&qs.test(l)?l.toLowerCase():"",b=c.get(m)??0;return b<1?{status:"error",code:"ERR_TXID_MISMATCH",description:"ARC batch acknowledged a transaction that was not submitted."}:(b===1?c.delete(m):c.set(m,b-1),im(d,m))})}catch{let r=sm();return t.map(()=>r)}}};Vs=new WeakMap,Ta=new WeakSet,Sd=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 cm(n=!1,t={}){return new ka(n?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",t)}var um=/^[0-9a-f]{64}$/i,fm=2147483647,q2=256,lm=64;function V2(n,t,e){if(typeof n!="string"||Qe(n)>e||Cr(n))throw new TypeError(`${t} must be bounded text without control characters.`);return n}function vd(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 K2(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 z2(n){let t=n??Zr();if(t==null||typeof t!="object"||typeof t.request!="function")throw new TypeError("What's On Chain httpClient must provide request().");return t}function X2(n){let t=vd(n,"What's On Chain config",8);return{apiKey:t.apiKey?.value===void 0?"":V2(t.apiKey.value,"What's On Chain API key",16*1024),httpClient:z2(t.httpClient?.value)}}function j2(n,t){if(typeof n!="string"||!um.test(n))throw new TypeError("Merkle root must be a 64-character hexadecimal string.");if(!Number.isSafeInteger(t)||t<0||t>fm)throw new TypeError("Block height must be a nonnegative bounded integer.");return{root:n.toLowerCase(),height:t}}function G2(n){try{let e=vd(n,"What's On Chain block header",lm).merkleroot?.value;return typeof e=="string"&&um.test(e)?e.toLowerCase():void 0}catch{return}}function Y2(n){if(!Array.isArray(n)||n.length===0||n.length>q2)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=vd(t[0]?.value,"What's On Chain height response",lm).height?.value;return Number.isSafeInteger(r)&&r>=0&&r<=fm?r:void 0}catch{return}}var Oa=class{constructor(t="main",e={}){w(this,"network");w(this,"apiKey");w(this,"URL");w(this,"httpClient");this.network=K2(t),this.URL=`https://api.whatsonchain.com/v1/bsv/${this.network}`;let i=X2(e);this.httpClient=i.httpClient,this.apiKey=i.apiKey,fu(this,["network","URL","httpClient","apiKey"])}async isValidRootForHeight(t,e){let i=j2(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 G2(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=Y2(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 dm(){return new Oa}var rn;(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"})(rn||(rn={}));function Ks(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 vt?n.skip(t):n.read(t)}function Ad(n){let t=n.pos;Ks(n,4);let e=n.readVarIntNumStrict(!1),i=new Set;for(let o=0;o<e;o++){i.add(st(n.readReverse(32))),Ks(n,4);let c=n.readVarIntNumStrict(!1);Ks(n,c+4)}let r=n.readVarIntNumStrict(!1);for(let o=0;o<r;o++){Ks(n,8);let c=n.readVarIntNumStrict(!1);Ks(n,c)}return Ks(n,4),{rawTx:n instanceof vt?n.bin.subarray(t,n.pos):Uint8Array.from(n.bin.slice(t,n.pos)),inputTxids:Array.from(i)}}function Z2(n){return Ad(new vt(n)).inputTxids}function J2(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 sn=class n{constructor(t,e,i,r=!1){w(this,"_bumpIndex");w(this,"_tx");w(this,"_rawTx");w(this,"_txid");w(this,"inputTxids",[]);w(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 Ke)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=st(ne(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=Ke.fromBinaryView(this._rawTx),this._txid!=null&&pm(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=hm(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||!J2(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=Z2(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(ft(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(rn.RAWTX):(i(rn.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex))};e===4022206466?this.isTxidOnly?(i(rn.TXID_ONLY),r()):this.bumpIndex!==void 0?(i(rn.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex),s()):(i(rn.RAWTX),s()):(s(),o())}static fromReader(t,e){let i,r;if(e===4022206466){let s=t.readUInt8();if(s===rn.TXID_ONLY)r=n.fromTxid(st(t.readReverse(32)));else{s===rn.RAWTX_AND_BUMP_INDEX&&(i=t.readVarIntNumStrict(!1));let{rawTx:o,inputTxids:c}=Ad(t);r=new n(o,i,c,!0)}}else{let{rawTx:s,inputTxids:o}=Ad(t);i=t.readUInt8()===0?void 0:t.readVarIntNumStrict(!1),r=new n(s,i,o,!0)}return r}};function Q2(n,t,e,i){if(t.path.length!==e)throw new Error("Mismatched roots");for(let r=0;r<e;r++)t4(n[r],t.path[r],i)}function t4(n,t,e){for(let i of t){let r=n.get(i.offset);if(r==null){n.set(i.offset,i);continue}e4(r,i,e)}}function e4(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 gm(n,t,e){for(let i of n.path[0])typeof i.hash=="string"&&e.set(i.hash,t)}var jn,Gn,Yn,wi,on,xi,es,Gs,ns,Ys,Zs,Js,is,rs,Zn,ze,Jn,P,zs,du,kd,Td,hu,mm,bm,ym,wm,zn,xm,Xn,Sm,Im,Pa,vm,Od,Pd,Rd,Am,Ra,Na,pu,ts,Xs,Nd,gu,Em,_d,km,Tm,Om,_a,Pm,Rm,mu,Nm,_m,Cd,Cm,Bm,Lm,Mm,Um,Dm,Hm,js,Bd,$m,bu,Wm,Fm,qm,Vm,Km,zm,Xm,jm,Rn=class Rn{constructor(t=4022206466){z(this,P);w(this,"bumps",[]);w(this,"txs",[]);w(this,"version",4022206466);w(this,"atomicTxid");z(this,jn);z(this,Gn);z(this,Yn);z(this,wi);z(this,on);z(this,xi);z(this,es,new Map);z(this,Gs);z(this,ns);z(this,Ys);z(this,Zs);z(this,Js);z(this,is);z(this,rs);z(this,Zn,!0);z(this,ze);z(this,Jn);this.version=t}synchronizeNestedTransactionMutations(){let t=!1;for(let e of this.txs)t=e.syncRawTxFromTransaction()||t;t&&(a(this,P,zs).call(this),A(this,ze,void 0),A(this,Jn,void 0),A(this,Zn,!0),a(this,P,ts).call(this))}isAtomic(t=this.atomicTxid??""){if(this.synchronizeNestedTransactionMutations(),a(this,P,zn).call(this),t.length===0)return!1;let e=a(this,P,Na).call(this);if(e.size!==this.txs.length)return!1;let i=e.get(t);return i==null?!1:a(this,P,Pd).call(this,i,e).size===this.txs.length}findTxid(t){return this.synchronizeNestedTransactionMutations(),a(this,P,Ra).call(this,t)}makeTxidOnly(t){let e=a(this,P,pu).call(this).get(t);if(e===void 0)return;let i=this.txs[e];return i.isTxidOnly||(i=sn.fromTxid(t),this.txs[e]=i,a(this,P,Xs).call(this,i,e),a(this,P,js).call(this,i),a(this,P,Xn).call(this,!0)),i}findBump(t){a(this,P,zn).call(this);let e=a(this,P,gu).call(this).get(t);return e===void 0?void 0:this.bumps[e]}findTransactionForSigning(t){let e=this.findTxid(t);if(e?.tx!=null){for(let i of e.tx.inputs)if(i.sourceTransaction==null){let r=a(this,P,Ra).call(this,Fr(i.sourceTXID,"sourceTXID must be valid"));r!=null&&(i.sourceTransaction=r.tx)}return e.tx}}findAtomicTransaction(t){let e=this.findTxid(t);if(e?.tx!=null)return a(this,P,km).call(this,e.tx),e.tx}mergeBump(t){return this.synchronizeNestedTransactionMutations(),a(this,P,zn).call(this),a(this,P,Xn).call(this,!1),a(this,P,_a).call(this,t)}mergeProvenTxs(t){if(t.length===0)return[];this.synchronizeNestedTransactionMutations(),a(this,P,zn).call(this),a(this,P,Xn).call(this,!0);let e=[];for(let s of t)e.push(a(this,P,mu).call(this,s.rawTx));let i=new Map;for(let s of t){let o=s.merklePath.blockHeight;i.set(o,(i.get(o)??0)+1)}let r=new Map;for(let s=0;s<t.length;s++){let o=t[s].merklePath,c=t[s].merkleRoot,u=i.get(o.blockHeight)===1?`${o.blockHeight}:single:${s}`:`${o.blockHeight}:${c??o.computeRoot()}`,f=r.get(u);f==null?r.set(u,{first:s,paths:[o],validateCombined:c!=null}):(f.paths.push(o),f.validateCombined=f.validateCombined||c!=null)}for(let s of[...r.values()].sort((o,c)=>o.first-c.first))a(this,P,_a).call(this,a(this,P,Om).call(this,s.paths,s.validateCombined));return e}mergeRawTx(t,e){return this.synchronizeNestedTransactionMutations(),a(this,P,Xn).call(this,!0),a(this,P,mu).call(this,t,e)}mergeTransaction(t){return this.synchronizeNestedTransactionMutations(),a(this,P,Xn).call(this,!0),a(this,P,Cd).call(this,t)}removeExistingTxid(t){let e=a(this,P,pu).call(this).get(t);e!==void 0&&(this.txs.splice(e,1),a(this,P,ts).call(this),a(this,P,Xn).call(this,!0))}mergeTxidOnly(t){let e=this.findTxid(t);return e==null&&(e=new sn(t),this.txs.push(e),a(this,P,Xs).call(this,e),a(this,P,js).call(this,e),a(this,P,Xn).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=Rn.fromBinaryStrict(t instanceof Rn?t.toBinary():t);this.synchronizeNestedTransactionMutations(),a(this,P,zn).call(this),a(this,P,Xn).call(this,!0);for(let i of e.bumps)a(this,P,_a).call(this,i);for(let i of e.txs)a(this,P,Cm).call(this,i)}isValid(t){return this.verifyValid(t).valid}async verify(t,e){let i=this.verifyValid(e);if(!i.valid)return!1;for(let r of Object.keys(i.roots))if(await t.isValidRootForHeight(i.roots[r],Number(r))!==!0)return!1;return!0}verifyValid(t){a(this,P,zn).call(this);let e={valid:!1,roots:{}};if(this.atomicTxid!=null&&!this.isAtomic(this.atomicTxid))return e;let i=this.sortTxs();if(a(this,P,Bm).call(this)||i.missingInputs.length>0||i.notValid.length>0||i.txidOnly.length>0&&t!==!0||i.withMissingInputs.length>0)return e;let r={};return!a(this,P,Lm).call(this,r,t)||!a(this,P,Mm).call(this,r,e)||!a(this,P,Um).call(this)||!a(this,P,Dm).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 yt?e.toBinaryUint8Array():e.toBinary());t.writeVarIntNum(this.txs.length);for(let e of this.txs)e.toWriter(t,this.version)}toBinary(){return Array.from(a(this,P,Pa).call(this))}toUint8Array(){return new Uint8Array(a(this,P,Pa).call(this))}toBinaryAtomic(t){return Array.from(a(this,P,Od).call(this,t))}toUint8ArrayAtomic(t){return new Uint8Array(a(this,P,Od).call(this,t))}toHex(){let t=a(this,P,Pa).call(this);if(g(this,xi)!=null)return g(this,xi);let e=st(t);return A(this,xi,e),e}static fromReader(t){var f;let e=t.pos,i=t.readUInt32LE(),r,s=e;if(i===16843009&&(r=st(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 Rn(i),c=t.readVarIntNumStrict(!1);for(let d=0;d<c;d++){let h=nr.fromReader(t,!1);o.bumps.push(h)}let u=t.readVarIntNumStrict(!1);for(let d=0;d<u;d++){let h=sn.fromReader(t,i);o.txs.push(h)}return o.atomicTxid=r,t instanceof vt&&(A(o,on,t.bin.subarray(s,t.pos)),a(f=o,P,du).call(f)),o}static fromBinary(t){return Rn.fromReader(new vt(Uint8Array.from(t)))}static fromBinaryStrict(t){return Rn.fromBinaryView(Uint8Array.from(t))}static fromBinaryView(t){let e=new vt(t),i=Rn.fromReader(e);if(!e.eof())throw new Error("Serialized BEEF contains trailing data");return i}static fromString(t,e="hex"){let i=it(t,e);return Rn.fromBinaryStrict(i)}sortTxs(){if(this.synchronizeNestedTransactionMutations(),a(this,P,zn).call(this),g(this,ze)!=null&&a(this,P,$m).call(this))return a(this,P,bu).call(this,g(this,ze));A(this,ze,void 0),A(this,Jn,void 0);let t={},e={},i=[],r=[],s=this.partitionTxs(e,t,i,r),{txsMissingInputs:o,missingInputs:c,remaining:u}=a(this,P,Wm).call(this,s,e);s=u;let f=a(this,P,Fm).call(this,s,t,i);this.txs=o.concat(f).concat(r).concat(i),A(this,Zn,!1),a(this,P,zs).call(this),a(this,P,ts).call(this);let d={missingInputs:Object.keys(c),notValid:f.map(h=>h.txid),valid:Object.keys(t),withMissingInputs:o.map(h=>h.txid),txidOnly:r.map(h=>h.txid)};return A(this,ze,d),a(this,P,Bd).call(this),a(this,P,bu).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 Rn;return t.version=this.version,t.bumps=Array.from(this.bumps),t.txs=Array.from(this.txs),A(t,jn,void 0),A(t,Gn,void 0),A(t,Yn,void 0),A(t,wi,void 0),A(t,Zn,g(this,Zn)),A(t,ze,g(this,ze)==null?void 0:a(this,P,bu).call(this,g(this,ze))),g(t,ze)!=null&&a(e=t,P,Bd).call(e),A(t,xi,g(this,xi)),A(t,on,g(this,on)),g(t,on)!=null&&a(i=t,P,du).call(i),t}trimKnownTxids(t){let e=a(this,P,zm).call(this,new Set(t));e=a(this,P,Xm).call(this)||e,e&&a(this,P,Xn).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,39 @@ ${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,P,_0).call(this,t,e)}};Bn=new WeakMap,_n=new WeakMap,Cn=new WeakMap,Jn=new WeakMap,je=new WeakMap,Qn=new WeakMap,wr=new WeakMap,ns=new WeakMap,yr=new WeakMap,is=new WeakMap,rs=new WeakMap,ss=new WeakMap,xr=new WeakMap,Sr=new WeakMap,Ln=new WeakMap,De=new WeakMap,Un=new WeakMap,P=new WeakSet,Qr=function(){N(this,je,void 0),N(this,Qn,void 0),y(this,wr).clear(),N(this,ns,void 0),N(this,yr,void 0),N(this,is,void 0),N(this,rs,void 0),N(this,ss,void 0),N(this,xr,void 0)},Ga=function(){N(this,rs,this.version),N(this,ss,a(this,P,_f).call(this)),N(this,xr,Array.from(this.bumps)),a(this,P,Ya).call(this)},_f=function(){return this.txs.map(t=>({ref:t,bumpIndex:t._bumpIndex,rawTx:t._rawTx,tx:t._rawTx==null?t._tx:void 0,txid:t._rawTx==null&&t._tx==null?t._txid:void 0}))},Cf=function(t){if(t?.length!==this.txs.length)return!1;for(let e=0;e<this.txs.length;e++){let i=this.txs[e],r=t[e];if(r.ref!==i||r.bumpIndex!==i._bumpIndex||r.rawTx!==i._rawTx||r.tx!==(i._rawTx==null?i._tx:void 0)||r.txid!==(i._rawTx==null&&i._tx==null?i._txid:void 0))return!1}return!0},Ya=function(){N(this,Sr,this.bumps.map(t=>({ref:t,blockHeight:t.blockHeight,levels:t.path.map(e=>({ref:e,leaves:e.map(i=>({ref:i,offset:i.offset,hash:i.hash,txid:i.txid,duplicate:i.duplicate}))}))})))},e0=function(t,e){return e.ref===t&&e.offset===t.offset&&e.hash===t.hash&&e.txid===t.txid&&e.duplicate===t.duplicate},n0=function(t,e){return e.ref===t&&e.leaves.length===t.length&&t.every((i,r)=>a(this,P,e0).call(this,i,e.leaves[r]))},i0=function(t,e){return e.ref===t&&e.blockHeight===t.blockHeight&&e.levels.length===t.path.length&&t.path.every((i,r)=>a(this,P,n0).call(this,i,e.levels[r]))},r0=function(){return y(this,Sr)?.length!==this.bumps.length?!1:this.bumps.every((t,e)=>a(this,P,i0).call(this,t,y(this,Sr)[e]))},Rn=function(){if(y(this,Sr)==null){a(this,P,Ya).call(this);return}a(this,P,r0).call(this)||(a(this,P,Qr).call(this),N(this,De,void 0),N(this,Un,void 0),N(this,Ln,!0),a(this,P,Hf).call(this),a(this,P,Ya).call(this))},s0=function(){if(y(this,je)==null||y(this,rs)!==this.version||!a(this,P,Cf).call(this,y(this,ss))||y(this,xr)?.length!==this.bumps.length)return!1;for(let t=0;t<this.bumps.length;t++)if(y(this,xr)[t]!==this.bumps[t])return!1;return!0},Nn=function(t=!0){a(this,P,Qr).call(this),N(this,De,void 0),N(this,Un,void 0),t&&N(this,Ln,!0)},o0=function(){for(let t of this.txs)t.txid},a0=function(){y(this,Ln)&&this.sortTxs()},Po=function(){if(this.synchronizeNestedTransactionMutations(),a(this,P,Rn).call(this),a(this,P,s0).call(this)&&y(this,je)!=null)return y(this,je);a(this,P,Qr).call(this),a(this,P,o0).call(this),a(this,P,a0).call(this);let t=new ht;return this.toWriter(t),N(this,je,t.toUint8Array()),a(this,P,Ga).call(this),y(this,je)},c0=function(t){let e=a(this,P,No).call(this),i=e.get(t);if(i==null)throw new Error(`${t} does not exist in this Beef`);let r=a(this,P,Uf).call(this,i,e),s=a(this,P,u0).call(this,r);return s.sortTxs(),s},Lf=function(t){var u;this.synchronizeNestedTransactionMutations(),a(this,P,Rn).call(this),y(this,is)===this.version&&a(this,P,Cf).call(this,y(this,ns))&&y(this,yr)?.length===this.bumps.length&&this.bumps.every((f,d)=>y(this,yr)?.[d]===f)||y(this,wr).clear();let i=y(this,wr).get(t);if(i!=null)return i;let r=a(u=a(this,P,c0).call(this,t),P,Po).call(u),s=et(t,"hex"),o=new Uint8Array(4+s.length+r.length);new DataView(o.buffer).setUint32(0,16843009,!0);for(let f=0;f<s.length;f++)o[4+f]=s[s.length-1-f];return o.set(r,4+s.length),y(this,wr).set(t,o),N(this,ns,a(this,P,_f).call(this)),N(this,yr,Array.from(this.bumps)),N(this,is,this.version),o},Uf=function(t,e){let i=new Set,r=[t];for(;r.length>0;){let s=r.pop();if(!(s==null||i.has(s))&&(i.add(s),!(a(this,P,Mf).call(this,s)||s.isTxidOnly)))for(let o of s.inputTxids){let c=e.get(o);c!=null&&r.push(c)}}return i},Mf=function(t){let e=t.bumpIndex;return e==null||!Number.isSafeInteger(e)||e<0||e>=this.bumps.length?!1:this.bumps[e]?.path[0]?.some(i=>i.hash===t.txid)??!1},u0=function(t){let e=new wn(this.version),i=new Map;for(let r of this.txs)!t.has(r)||!a(this,P,Mf).call(this,r)||r.bumpIndex==null||i.has(r.bumpIndex)||(i.set(r.bumpIndex,e.bumps.length),e.bumps.push(this.bumps[r.bumpIndex]));for(let r of this.txs){if(!t.has(r))continue;let s=r.bumpIndex==null?void 0:i.get(r.bumpIndex),o;r._rawTx!=null?o=new Xe(r._rawTx,s,Array.from(r.inputTxids)):r._tx!=null?o=Xe.fromTx(r._tx,s):o=Xe.fromTxid(r.txid,s),e.txs.push(o)}return e},Ro=function(t){return a(this,P,No).call(this).get(t)},No=function(){return(y(this,Bn)==null||y(this,_n)==null)&&a(this,P,br).call(this),y(this,Bn)},Za=function(){return(y(this,_n)==null||y(this,Bn)==null)&&a(this,P,br).call(this),y(this,_n)},br=function(){N(this,Bn,new Map),N(this,_n,new Map);for(let t=0;t<this.txs.length;t++){let e=this.txs[t];y(this,Bn).set(e.txid,e),y(this,_n).set(e.txid,t)}},ts=function(t,e=this.txs.length-1){y(this,Bn)?.set(t.txid,t),y(this,_n)?.set(t.txid,e)},Df=function(t){let e=a(this,P,Za).call(this).get(t.txid);e===void 0?(this.txs.push(t),a(this,P,ts).call(this,t)):(this.txs[e]=t,a(this,P,ts).call(this,t,e))},Ja=function(){if(y(this,Jn)==null){N(this,Jn,new Map);for(let t=0;t<this.bumps.length;t++)for(let e of this.bumps[t].path[0])typeof e.hash=="string"&&y(this,Jn).set(e.hash,t)}return y(this,Jn)},f0=function(){if(y(this,Cn)==null){N(this,Cn,new Map);for(let t=0;t<this.bumps.length;t++){let e=this.bumps[t],i=y(this,Cn).get(e.blockHeight)??[];i.push(t),y(this,Cn).set(e.blockHeight,i)}}return y(this,Cn)},Hf=function(){N(this,Cn,void 0),N(this,Jn,void 0)},d0=function(t){let e=new Set,i=[t];for(;i.length>0;){let r=i.pop();if(r==null)continue;let s=r.id("hex");if(e.has(s))continue;e.add(s);let o=this.findBump(s);if(o!=null){r.merklePath=o;continue}for(let c of r.inputs)a(this,P,l0).call(this,c),c.sourceTransaction!=null&&i.push(c.sourceTransaction)}},l0=function(t){if(t.sourceTransaction==null){let e=a(this,P,Ro).call(this,sr(t.sourceTXID,"sourceTXID must be valid"));e!=null&&(t.sourceTransaction=e.tx)}},h0=function(t,e=!1){let i=t[0];if(t.length===1&&!e)return i;let r=i.path.map(o=>new Map(o.map(c=>[c.offset,c])));for(let o=1;o<t.length;o++)py(r,t[o],i.path.length,e);let s=r.map(o=>[...o.values()]);if(e){let o=new Ei(i.blockHeight,s);return o.trim(),o}return i.path=s,i.trim(),i},Bo=function(t){let e=a(this,P,p0).call(this,t),i=this.bumps[e],r=a(this,P,No).call(this);for(let s of i.path[0]){if(typeof s.hash!="string")continue;let o=r.get(s.hash);o!=null&&o.bumpIndex==null&&a(this,P,g0).call(this,o,i,e)}return e},p0=function(t){let e=a(this,P,f0).call(this),i=a(this,P,Ja).call(this),r=e.get(t.blockHeight)??[];if(r.length>0){let o=t.computeRoot();for(let c of r)if(this.bumps[c].computeRoot()===o)return this.bumps[c].combine(t),t0(this.bumps[c],c,i),c}this.bumps.push(t);let s=this.bumps.length-1;return r.push(s),e.set(t.blockHeight,r),t0(t,s,i),s},g0=function(t,e,i){let r=t.txid;for(let s of e.path[0])if(s.hash===r){t.bumpIndex=i,s.txid=!0;break}},Qa=function(t,e){let i=new Xe(t,e);return a(this,P,Df).call(this,i),a(this,P,es).call(this,i),i},m0=function(t){let e=t.merklePath==null?void 0:a(this,P,Bo).call(this,t.merklePath),i=new Xe(t,e);return a(this,P,Df).call(this,i),a(this,P,es).call(this,i),i},b0=function(t,e){for(let i=t.inputs.length-1;i>=0;i--){let r=t.inputs[i].sourceTransaction;r!=null&&e.push(r)}},$f=function(t){t.materializeSourceTXIDs();let e=t.id("hex"),i=new Set,r=[t],s;for(;r.length>0;){let o=r.pop();if(o==null)continue;let c=o.id("hex");if(i.has(c))continue;i.add(c);let u=a(this,P,m0).call(this,o);c===e&&(s=u),u.bumpIndex===void 0&&a(this,P,b0).call(this,o,r)}if(s==null)throw new Error("Failed to merge root transaction");return s},w0=function(t){let e=a(this,P,Ro).call(this,t.txid);if(t.isTxidOnly&&e==null?(e=Xe.fromTxid(t.txid),this.txs.push(e),a(this,P,ts).call(this,e),a(this,P,es).call(this,e)):t._tx!=null&&(e==null||e.isTxidOnly)?e=a(this,P,$f).call(this,t._tx):t._rawTx!=null&&(e==null||e.isTxidOnly)&&(e=a(this,P,Qa).call(this,t._rawTx)),e==null)throw new Error(`Failed to merge BeefTx for txid: ${t.txid}`);return e},y0=function(){let t=new Set;for(let e of this.txs){if(t.has(e.txid))return!0;t.add(e.txid)}return!1},x0=function(t,e){for(let i of this.txs)if(i.isTxidOnly){if(e!==!0)return!1;t[i.txid]=!0}return!0},S0=function(t,e){for(let i of this.bumps)for(let r of i.path[0])if(!(r.txid!==!0||typeof r.hash!="string"||r.hash.length===0)&&(t[r.hash]=!0,!a(this,P,A0).call(this,i,r.hash,e)))return!1;return!0},I0=function(){for(let t of this.txs){if(t.bumpIndex===void 0)continue;if(!Number.isSafeInteger(t.bumpIndex)||t.bumpIndex<0||t.bumpIndex>=this.bumps.length||this.bumps[t.bumpIndex]?.path[0]?.find(i=>i.hash===t.txid)==null)return!1}return!0},v0=function(t){for(let e of this.txs){for(let i of e.inputTxids)if(!t[i])return!1;t[e.txid]=!0}return!0},A0=function(t,e,i){let r=t.computeRoot(e);return(i.roots[t.blockHeight]===void 0||i.roots[t.blockHeight]==="")&&(i.roots[t.blockHeight]=r),i.roots[t.blockHeight]===r},es=function(t){if(t.bumpIndex!==void 0)return!0;let e=t.txid,i=a(this,P,Ja).call(this).get(e);if(i===void 0)return!1;t.bumpIndex=i;let r=this.bumps[i].path[0].find(s=>s.hash===e);return r!=null&&(r.txid=!0),!0},qf=function(){N(this,Un,this.txs.map(t=>({ref:t,txid:t.txid,bumpIndex:t.bumpIndex,isTxidOnly:t.isTxidOnly,inputTxids:[...t.inputTxids]})))},E0=function(){if(y(this,Un)?.length!==this.txs.length)return!1;for(let t=0;t<this.txs.length;t++){let e=this.txs[t],i=y(this,Un)[t];if(i.ref!==e||i.txid!==e.txid||i.bumpIndex!==e.bumpIndex||i.isTxidOnly!==e.isTxidOnly||i.inputTxids.length!==e.inputTxids.length)return!1;for(let r=0;r<e.inputTxids.length;r++)if(i.inputTxids[r]!==e.inputTxids[r])return!1}return!0},tc=function(t){return{missingInputs:[...t.missingInputs],notValid:[...t.notValid],valid:[...t.valid],withMissingInputs:[...t.withMissingInputs],txidOnly:[...t.txidOnly]}},k0=function(t,e){let i={},r=[],s=[];for(let o of t){let c=!1;for(let u of o.inputTxids)e[u]===void 0&&(i[u]=!0,c=!0);c?r.push(o):s.push(o)}return{txsMissingInputs:r,missingInputs:i,remaining:s}},T0=function(t,e,i){let{indegree:r,dependents:s,originalIndex:o,round:c}=a(this,P,O0).call(this,t,e),u=a(this,P,P0).call(this,t,r,s,o,c);return a(this,P,R0).call(this,t,u,c,e,i),t.filter(f=>!u.has(f.txid))},O0=function(t,e){let i=new Set(t.map(u=>u.txid)),r=new Map,s=new Map,o=new Map(t.map((u,f)=>[u.txid,f])),c=new Map;for(let u of t){let f=0;for(let d of u.inputTxids)if(!e[d]&&(f++,i.has(d))){let l=s.get(d)??[];l.push(u),s.set(d,l)}r.set(u.txid,f),c.set(u.txid,0)}return{indegree:r,dependents:s,originalIndex:o,round:c}},P0=function(t,e,i,r,s){let o=t.filter(u=>e.get(u.txid)===0),c=new Set;for(let u of o)if(!c.has(u.txid)){c.add(u.txid);for(let f of i.get(u.txid)??[]){let d=(s.get(u.txid)??0)+((r.get(u.txid)??0)>(r.get(f.txid)??0)?1:0);s.set(f.txid,Math.max(s.get(f.txid)??0,d));let l=(e.get(f.txid)??0)-1;e.set(f.txid,l),l===0&&o.push(f)}}return c},R0=function(t,e,i,r,s){let o=[];for(let c of t){if(!e.has(c.txid))continue;let u=i.get(c.txid)??0,f=o[u]??[];f.push(c),o[u]=f}for(let c of o)for(let u of c??[])r[u.txid]=!0,s.push(u)},N0=function(t){let e=this.txs.length;this.txs=this.txs.filter(r=>!(r.isTxidOnly&&t.has(r.txid)));let i=this.txs.length!==e;return i&&a(this,P,br).call(this),i},B0=function(){let t=new Set;for(let r of this.txs)r.bumpIndex!==void 0&&t.add(r.bumpIndex);if(t.size>=this.bumps.length)return!1;let e=new Map,i=0;for(let r=0;r<this.bumps.length;r++)t.has(r)&&(e.set(r,i),i++);this.bumps=this.bumps.filter((r,s)=>t.has(s));for(let r of this.txs){if(r.bumpIndex===void 0)continue;let s=e.get(r.bumpIndex);if(s===void 0)throw new Error(`Internal error: bumpIndex ${r.bumpIndex} not found in indexMap`);r.bumpIndex=s}return a(this,P,Hf).call(this),!0},_0=function(t,e){let i=r=>nt(zt(at(r,"hex").reverse()).reverse());for(let r of t.path[e-1]){if(typeof r.hash!="string"||(r.offset&1)!==0)continue;let s=t.path[e-1].find(c=>c.offset===r.offset+1);if(s===void 0||typeof s.hash!="string")continue;let o=r.offset>>1;t.path[e].every(c=>c.offset!==o)&&t.path[e].push({offset:o,hash:i(s.hash+r.hash)})}};var Ir=wn,C0=Ir;var cs=256*1024*1024,V0=21e14,by=64,Ff=1e6,us=Array.isArray,rn=Array,Zf=Number,Jf=String,wy=Number.isFinite,yy=Number.isInteger,xy=Number.isSafeInteger,K0=Object.is,Uo=Object.create,Sy=Object.defineProperty,$t=Object.getOwnPropertyDescriptor,L0=Object.getOwnPropertyDescriptors,Qf=Object.getPrototypeOf,Lo=Object.keys,Zt=Reflect.apply,Do=Reflect.ownKeys,Iy=RegExp.prototype.exec,vy=RegExp.prototype.test,Ay=String.prototype.toLowerCase,z0=Uint8Array,td=Uint8Array.prototype,oc=Qf(td),U0=$t(oc,"buffer")?.get,ic=$t(oc,"length")?.get,M0=$t(oc,Symbol.toStringTag)?.get,Ey=td.set,D0=typeof SharedArrayBuffer>"u"?void 0:$t(SharedArrayBuffer.prototype,"byteLength")?.get,ky=WeakMap.prototype.get,Ty=WeakMap.prototype.set,Vf=WeakSet.prototype.add,Oy=WeakSet.prototype.delete,X0=WeakSet.prototype.has,Kf=new WeakSet,Py=me.prototype.toHex,zf,Xf,jf,j0=/^(?:0|[1-9]\d*)$/,Ry=/^([0-9a-f]{64})\.(0|[1-9]\d*)$/i,Ny=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,By=/^(?:[0-9a-f]{2})*$/i,_y=/^[0-9a-f]{64}$/i;function Cy(){let n=[Array.prototype,Map.prototype,Set.prototype,WeakMap.prototype,WeakSet.prototype,Object,Object.prototype,Number,RegExp.prototype,String.prototype,td,oc],t=new rn(n.length);for(let e=0;e<n.length;e++){let i=n[e],r=Do(i),s=new rn(r.length);for(let o=0;o<r.length;o++)s[o]=$t(i,r[o]);t[e]={owner:i,keys:r,descriptors:s}}return t}function Co(n){for(let t=0;t<n.length;t++){let e=n[t];if(Do(e.owner).length!==e.keys.length)throw new Error("Wallet callback modified shared JavaScript intrinsics");for(let i=0;i<e.keys.length;i++){let r=e.descriptors[i],s=$t(e.owner,e.keys[i]);if(s==null||s.configurable!==r.configurable||s.enumerable!==r.enumerable||s.writable!==r.writable||!K0(s.value,r.value)||s.get!==r.get||s.set!==r.set)throw new Error(`Wallet callback modified shared JavaScript intrinsics (${t}:${Jf(e.keys[i])})`)}}}function rc(n,t){return $t(n,t)!==void 0}function Ti(n){return xy(n)}function Mo(n,t){return Zt(vy,n,[t])}function Ar(n){return Zt(Ay,n,[])}function fs(n){return Zt(Py,n,[])}function Ly(){zf??(zf=Me.fromAtomicBEEF),Xf??(Xf=Me.prototype.id),jf??(jf=Me.prototype.toAtomicBEEF)}function Wf(n){if(zf==null)throw new Error("Transaction intrinsics are unavailable");return Zt(zf,Me,[n])}function Uy(n){if(jf==null)throw new Error("Transaction intrinsics are unavailable");return Zt(jf,n,[!0])}function G0(n){if(Xf==null)throw new Error("Transaction intrinsics are unavailable");return Zt(Xf,n,["hex"])}function H0(n,t){return Zt(X0,n.active,[t])}function My(n,t){Zt(Vf,n.active,[t])}function $0(n,t){Zt(Oy,n.active,[t])}function Dy(n,t){return Zt(ky,n.completed,[t])}function ec(n,t,e){Zt(Ty,n.completed,[t,e])}function ki(n,t,e=!1){if(n==null||typeof n!="object"||us(n))throw new Error(`${t} must be a plain data object`);let i=Qf(n);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain data object`);let r=Do(n);for(let s=0;s<r.length;s++){let o=r[s],c=$t(n,o);if(typeof o=="symbol"&&e){if(c==null||!("value"in c))throw new Error(`${t} symbol metadata must be a data property`);continue}if(typeof o!="string"||c==null||!c.enumerable||!("value"in c))throw new Error(`${t} must contain only string-keyed data properties`)}return n}function Y0(n,t,e=cs){if(Qf(n)!==Array.prototype)throw new Error(`${t} must contain only dense data arrays`);let i=$t(n,"length");if(i==null||!("value"in i)||!Ti(i.value)||i.value<0)throw new Error(`${t} must contain only dense data arrays`);let r=i.value;if(r>cs)throw new Error(`${t} exceeds the byte limit`);if(Do(n).length!==r+1)throw new Error(`${t} must contain only dense data arrays`);let o=r>e,c=o?void 0:new rn(r);for(let u=0;u<r;u++){let f=$t(n,Jf(u));if(f==null||!f.enumerable||!("value"in f))throw new Error(`${t} must contain only dense data arrays`);if(!yy(f.value)||f.value<0||f.value>255)return;c!==void 0&&(c[u]=f.value)}if(o)throw new Error(`${t} exceeds the aggregate byte limit`);return c}function Z0(n,t,e=cs){if(U0==null||ic==null||M0==null)return;let i,r,s;try{i=Zt(U0,n,[]),r=Zt(ic,n,[]),s=Zt(M0,n,[])}catch{return}if(s!=="Uint8Array")return;if(D0!=null){let c=!1;try{Zt(D0,i,[]),c=!0}catch{}if(c)throw new Error(`${t} must not use shared byte storage`)}if(r>cs)throw new Error(`${t} exceeds the byte limit`);if(r>e)throw new Error(`${t} exceeds the aggregate byte limit`);let o=new z0(r);try{Zt(Ey,o,[n])}catch{throw new Error(`${t} must contain only intrinsic byte arrays`)}return o}function vr(n,t,e=0,i={nodes:0,active:new WeakSet,completed:new WeakMap,copiedBytes:0},r=!1){if(e>by)throw new Error(`${t} exceeds the depth limit`);if(i.nodes+=1,i.nodes>Ff)throw new Error(`${t} exceeds the node limit`);if(n==null||typeof n=="string"||typeof n=="boolean")return n;if(typeof n=="number"){if(!wy(n)||K0(n,-0))throw new Error(`${t} contains an ambiguous number`);return n}if(typeof n!="object")throw new Error(`${t} contains unsupported data`);if(H0(i,n))throw new Error(`${t} contains a cycle`);let s=Dy(i,n);if(s!==void 0)return s;let o=Z0(n,t,cs-i.copiedBytes);if(o!==void 0)return i.copiedBytes+=o.length,Zt(Vf,Kf,[o]),ec(i,n,o),o;if(us(n)){let l=Y0(n,t,cs-i.copiedBytes);if(l!==void 0)return i.copiedBytes+=l.length,Zt(Vf,Kf,[l]),ec(i,n,l),l;let p=$t(n,"length");if(p==null||!("value"in p)||!Ti(p.value)||p.value<0)throw new Error(`${t} must contain only dense data arrays`);if(p.value>Ff)throw new Error(`${t} exceeds the node limit`)}if(My(i,n),us(n)){let l=L0(n),p=l.length;if(p==null||!("value"in p)||!Ti(p.value)||p.value<0||p.value>Ff)throw new Error(`${t} must contain only dense data arrays`);let m=p.value,g=Do(l);if(g.length!==m+1)throw new Error(`${t} must contain only dense data arrays`);for(let S=0;S<g.length;S++){let C=g[S];if(C!=="length"&&(typeof C!="string"||!Mo(j0,C)||Zf(C)>=m))throw new Error(`${t} must contain only dense data arrays`)}let w=new rn(m);for(let S=0;S<m;S++){let C=Jf(S),E=l[C];if(E==null||!E.enumerable||!("value"in E))throw new Error(`${t} must contain only dense data arrays`);w[S]=vr(E.value,`${t}[${S}]`,e+1,i)}return $0(i,n),ec(i,n,w),w}let c=ki(n,t,r);if(H0(i,c)&&c!==n)throw new Error(`${t} contains a cycle`);let u=Uo(null),f=L0(c),d=Lo(f);for(let l=0;l<d.length;l++){let p=d[l],m=f[p];if(!m.enumerable||!("value"in m))throw new Error(`${t} must contain only string-keyed data properties`);Sy(u,p,{value:vr(m.value,`${t}.${p}`,e+1,i),enumerable:!0,configurable:!0,writable:!0})}return $0(i,n),ec(i,n,u),u}function q0(n,t){if(n!=null&&typeof n=="object"){let r=Zt(X0,Kf,[n]);if(r&&us(n)){let o=$t(n,"length")?.value;if(typeof o!="number"||o===0)throw new Error(`${t} must be a bounded non-empty byte array`);return n}if(r&&ic!=null){let o;try{o=Zt(ic,n,[])}catch{throw new Error(`${t} must be a bounded non-empty byte array`)}if(o===0)throw new Error(`${t} must be a bounded non-empty byte array`);return n}let s=Z0(n,t);if(s!==void 0){if(s.length===0)throw new Error(`${t} must be a bounded non-empty byte array`);return s}}if(!us(n))throw new Error(`${t} must be a bounded non-empty byte array`);let e=Y0(n,t);if(e==null||e.length===0)throw new Error(`${t} must be a bounded non-empty byte array`);let i=new z0(e.length);for(let r=0;r<e.length;r++)i[r]=e[r];return i}function nc(n,t){if(typeof n!="string"||!Mo(_y,n))throw new Error(`${t} must be a 32-byte hexadecimal transaction ID`);return Ar(n)}function sc(n,t){if(typeof n!="string"||!Mo(By,n))throw new Error(`${t} must be an even-length hexadecimal string`);return Ar(n)}function Gf(n,t){if(typeof n!="string")throw new Error(`${t} must be a canonical outpoint`);let e=Zt(Iy,Ry,[n]);if(e==null)throw new Error(`${t} must be a canonical outpoint`);let i=Zf(e[2]);if(!Ti(i)||i>4294967295)throw new Error(`${t} must be a canonical outpoint`);return`${Ar(e[1])}.${i}`}function Yf(n,t){let e=n.inputs[t];if(e==null||!Ti(e.sourceOutputIndex)||e.sourceOutputIndex<0||e.sourceOutputIndex>4294967295)throw new Error("Wallet transaction input is malformed");let i=e.sourceTransaction==null?void 0:G0(e.sourceTransaction);if(e.sourceTXID!==void 0&&i!==void 0&&nc(e.sourceTXID,"Wallet input source TXID")!==nc(i,"Wallet input source transaction ID"))throw new Error("Wallet transaction input source mismatch");return`${nc(e.sourceTXID??i,"Wallet input source TXID")}.${e.sourceOutputIndex}`}function as(n,t){if(typeof n!="number"||!Ti(n)||n<0||n>V0)throw new Error(`${t} must be a valid satoshi amount`);return n}function os(n,t,e){let i=n+t;if(!Ti(i)||i>V0)throw new Error(`${e} exceeds the maximum transaction value`);return i}function F0(n,t){let e=n.inputs[t],i=e?.sourceTransaction?.outputs[e.sourceOutputIndex];if(i==null)throw new Error("Wallet signable transaction omitted an input source output");return as(i.satoshis,`Wallet input ${t} source output`)}function Hy(n,t,e,i){if(t.version!==(n.version??1))throw new Error("Wallet transaction substituted the requested version");if(t.lockTime!==(n.lockTime??0))throw new Error("Wallet transaction substituted the requested lock time");let r=new rn(t.inputs.length),s=Uo(null);for(let A=0;A<t.inputs.length;A++){let k=Yf(t,A);if(rc(s,k))throw new Error("Wallet transaction contains a duplicate input outpoint");r[A]=k,s[k]=!0}let o=[],c=Uo(null);for(let A=0;A<(n.inputs?.length??0);A++){let k=n.inputs[A],B=Gf(k.outpoint,`Requested input ${A} outpoint`);if(rc(c,B))throw new Error("Action requests the same input outpoint more than once");c[B]=!0;let _=-1;for(let O=0;O<r.length;O++)if(r[O]===B){if(_!==-1)throw new Error("Wallet transaction does not contain each requested input exactly once");_=O}if(_===-1)throw new Error("Wallet transaction does not contain each requested input exactly once");if(o[A]=_,(t.inputs[_].sequence??4294967295)!==(k.sequenceNumber??4294967295))throw new Error("Wallet transaction substituted a requested input sequence");let H=t.inputs[_].unlockingScript;if(k.unlockingScript!==void 0&&(H==null?void 0:Ar(fs(H)))!==sc(k.unlockingScript,`Requested input ${A} unlocking script`))throw new Error("Wallet transaction substituted a requested unlocking script")}let u=new rn(t.outputs.length);for(let A=0;A<t.outputs.length;A++){let k=t.outputs[A];u[A]={satoshis:as(k.satoshis,`Wallet output ${A}`),lockingScript:Ar(fs(k.lockingScript))}}let f=new rn(u.length),d=n.options?.randomizeOutputs===!1,l=0,p=(A,k)=>{let B=n.outputs[A],_=sc(B.lockingScript,`Requested output ${A} locking script`),H=as(B.satoshis,`Requested output ${A}`);if(d){let I=u[A],U=I!=null&&(k==null?I.satoshis===H:I.satoshis>=k.minimumSatoshis&&I.satoshis<=k.maximumSatoshis);if(I==null||I.lockingScript!==_||!U)throw new Error("Wallet transaction substituted a requested output position");f[A]=!0,l=os(l,I.satoshis,"Requested output value");return}let O=-1;for(let I=0;I<u.length;I++){let U=u[I];if(!(f[I]===!0||U.lockingScript!==_||!(k==null?U.satoshis===H:U.satoshis>=k.minimumSatoshis&&U.satoshis<=k.maximumSatoshis))){if(k==null){O=I;break}if(O!==-1)throw new Error("Wallet transaction omitted or substituted a requested output");O=I}}if(O===-1)throw new Error("Wallet transaction omitted or substituted a requested output");f[O]=!0,l=os(l,u[O].satoshis,"Requested output value")};for(let A=0;A<(n.outputs?.length??0);A++)e[A]===void 0&&p(A);for(let A=0;A<(n.outputs?.length??0);A++){let k=e[A];k!=null&&p(A,k)}let m=0,g=new rn(t.inputs.length);for(let A=0;A<o.length;A++){let k=o[A];g[k]=!0,m=os(m,i?.[A]??F0(t,k),"Requested input value")}let w=0;for(let A=0;A<t.inputs.length;A++)g[A]!==!0&&(w=os(w,F0(t,A),"Wallet-added input value"));let S=0;for(let A=0;A<u.length;A++)S=os(S,u[A].satoshis,"Wallet output value");let C=os(m,w,"Wallet input value");if(S>C)throw new Error("Wallet signable transaction spends more than its inputs");if(S-l>w)throw new Error("Wallet used a requested input to fund an unrequested output");return o}function W0(n,t){if(n.version!==t.version||n.lockTime!==t.lockTime||n.inputs.length!==t.inputs.length||n.outputs.length!==t.outputs.length)throw new Error("Wallet signed transaction substituted the authorized template");for(let e=0;e<n.inputs.length;e++)if(Yf(n,e)!==Yf(t,e)||(n.inputs[e].sequence??4294967295)!==(t.inputs[e].sequence??4294967295))throw new Error("Wallet signed transaction substituted an authorized input");for(let e=0;e<n.outputs.length;e++)if(n.outputs[e].satoshis!==t.outputs[e].satoshis||fs(n.outputs[e].lockingScript)!==fs(t.outputs[e].lockingScript))throw new Error("Wallet signed transaction substituted an authorized output")}async function $y(n,t,e){try{await n.abortAction({reference:t},e)}catch{}}async function J0(n,t,e={},i,r){Ly();let s=Cy(),o=vr(t,"Create action arguments"),c=vr(o,"Create action arguments"),u=o.inputs??[],f;if(r!==void 0){let I=vr(r,"Trusted requested input satoshis");if(!us(I)||I.length!==u.length)throw new Error("Trusted requested input satoshis must match the requested inputs");let U=new rn(I.length);for(let M=0;M<I.length;M++)U[M]=as(I[M],`Trusted requested input ${M}`);f=U}let d=ki(e,"Bound action options"),l=Lo(d);for(let I=0;I<l.length;I++){let U=l[I];if(U!=="inputSigners"&&U!=="outputSatoshisRanges")throw new Error(`Unknown bound action option "${U}"`)}let p=$t(d,"inputSigners")?.value,m=ki(p??{},"Input signers"),g=Uo(null),w=0,S=Lo(m);for(let I=0;I<S.length;I++){let U=S[I],M=$t(m,U)?.value,F=Gf(U,"Input signer outpoint");if(rc(g,F)||typeof M!="function")throw new Error("Input signers must uniquely identify requested outpoints");g[F]=M,w++}let C=$t(d,"outputSatoshisRanges")?.value,E=ki(C??{},"Output satoshi ranges"),A=new rn(o.outputs?.length??0),k=Lo(E);for(let I=0;I<k.length;I++){let U=k[I],M=$t(E,U)?.value;if(!Mo(j0,U))throw new Error("Output satoshi ranges must identify requested output indexes");let F=Zf(U);if(!Ti(F)||F>=(o.outputs?.length??0))throw new Error("Output satoshi ranges must identify requested output indexes");let it=ki(M,`Output satoshi range ${F}`),ot=Lo(it);for(let tt=0;tt<ot.length;tt++){let St=ot[tt];if(St!=="minimumSatoshis"&&St!=="maximumSatoshis")throw new Error(`Unknown output satoshi range option "${St}"`)}let q=as($t(it,"minimumSatoshis")?.value,`Output satoshi range ${F} minimum`),z=as($t(it,"maximumSatoshis")?.value,`Output satoshi range ${F} maximum`);if(q>z)throw new Error(`Output satoshi range ${F} minimum exceeds its maximum`);A[F]={minimumSatoshis:q,maximumSatoshis:z}}let B=await n.createAction({...c,options:{...c.options,signAndProcess:!1,returnTXIDOnly:!1}},i);Co(s);let _=ki(vr(B,"Wallet createAction result",0,void 0,!0),"Wallet createAction result",!0);Co(s);let H=ki($t(_,"signableTransaction")?.value,"Wallet signable transaction"),O=$t(H,"reference")?.value;if(typeof O!="string"||O.length===0||O.length>4096||!Mo(Ny,O))throw new Error("Wallet signable transaction reference is invalid");try{let I=Wf(q0($t(H,"tx")?.value,"Wallet signable transaction")),U=Hy(o,I,A,f),M=Wf(Uy(I)),F={},it=new rn(I.inputs.length),ot=new rn,q=Uo(null),z=0;for(let ke=0;ke<u.length;ke++){let xe=u[ke],vn=Gf(xe.outpoint,`Requested input ${ke} outpoint`),$=U[ke];if(xe.unlockingScript!==void 0){it[$]=sc(xe.unlockingScript,`Requested input ${ke} unlocking script`),ot[ot.length]=$;continue}let W=$t(g,vn)?.value;if(xe.unlockingScriptLength===void 0||W==null)throw new Error(`Requested input ${ke} has no authorized signer`);let D=await W(I,$);Co(s),W0(M,I);let V=sc(typeof D=="string"?D:fs(D),`Requested input ${ke} signed unlocking script`);F[$]={unlockingScript:V},it[$]=V,ot[ot.length]=$,rc(q,vn)||(q[vn]=!0,z++)}if(z!==w)throw new Error("An input signer does not match a requested signable input");let tt={acceptDelayedBroadcast:o.options?.acceptDelayedBroadcast,returnTXIDOnly:!1,noSend:o.options?.noSend,sendWith:o.options?.sendWith},St=await n.signAction({reference:O,spends:F,options:tt},i);Co(s);let ce=ki(vr(St,"Wallet signAction result",0,void 0,!0),"Wallet signAction result",!0);Co(s);let Bt=Wf(q0($t(ce,"tx")?.value,"Wallet signed transaction"));W0(I,Bt);for(let ke=0;ke<ot.length;ke++){let xe=ot[ke],vn=it[xe],$=Bt.inputs[xe]?.unlockingScript;if($==null||Ar(fs($))!==vn)throw new Error("Wallet signed transaction substituted an authorized unlocking script")}let dn=$t(ce,"txid")?.value;if(dn!==void 0&&nc(dn,"Wallet signed transaction ID")!==Ar(G0(Bt)))throw new Error("Wallet signed transaction ID does not match its transaction data");return Bt}catch(I){throw await $y(n,O,i),I}}var Ho=class extends Error{constructor(e){super(`Transaction evidence: ${e}`);b(this,"code");this.code=e,this.name="TransactionEvidenceError"}};var DS=Object.freeze({candidateBytes:1024*1024,retainedBytes:16*1024*1024,transactions:256,inputs:4096,scriptBytes:256*1024,scriptMemoryBytes:16*1024*1024,candidatesPerTransaction:8,pendingTransactions:32,concurrentTransactions:4,pendingChainCalls:8,consumers:128,cacheEntries:128,cacheAgeMs:6e4,attemptTimeoutMs:5e3,requestTimeoutMs:15e3});function Q0(n){let t=n.tx,e=t.inputs.map(i=>{let r=i.sourceTransaction,s=r?.outputs[i.sourceOutputIndex];if(r===void 0||s===void 0)throw new Ho("invalid-evidence");return[r.id("hex"),i.sourceOutputIndex,s.satoshis,s.lockingScript.toHex()]});return nt(Te(at(JSON.stringify([t.toHex(),e,n.blockHeight,n.consensus,n.verifyFlags,n.memoryLimit]),"utf8")))}var qy=new WeakMap;function tg(n){return qy.get(n)}function eg(n,t){return{supportsMemoryLimit:t.supportsMemoryLimit,shouldVerifyScripts:t.shouldVerifyScripts===void 0?void 0:e=>{n.check();let i=Q0(e),r=t.shouldVerifyScripts(e);if(n.check(),Q0(e)!==i)throw new Ho("invalid-evidence");return r},verifyScripts:async e=>(await n.work.batch(n,[e],t))[0],verifyScriptsBatch:async e=>await n.work.batch(n,e,t)}}var ng=Symbol(),ig=Symbol();function Jp(n){return n[ng]()}function Qp(n,t){n[ig](t)}var Fy=943816,rg=21e14,Wy=1e6;function sn(n,t){if(typeof n!="number"||!Number.isSafeInteger(n)||n<0||n>rg)throw new RangeError(`${t} must be a non-negative safe integer no greater than 21e14.`);return n}function ds(n,t,e){let i=n+t;if(!Number.isSafeInteger(i)||i>rg)throw new RangeError(`${e} exceeds the maximum valid monetary range.`);return i}function Ge(n,t){if(typeof n!="number"||!Number.isInteger(n)||n<0||n>4294967295)throw new RangeError(`${t} must be an unsigned 32-bit integer.`);return n}function Oi(n,t){if(typeof n!="string"||!/^[0-9a-fA-F]{64}$/.test(n))throw new TypeError(`${t} must be a 32-byte hexadecimal transaction ID.`);return n.toLowerCase()}function ed(n,t){if(n===void 0||t===void 0)return n===t;if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}var kr,ti,Ri,Tr,Ni,qo,ls,j,sg,og,Mn,$o,nd,yn,id,ac,rd,ag,cg,ug,fg,dg,lg,hg,Er,pg,sd,gg,mg,bg,wg,cc,yg,xg,Pi,uc,Sg,Ig,vg,Ag,Eg,kg,Tg,Og,Pg,oe=class oe{constructor(t=1,e=[],i=[],r=0,s=new Map,o){G(this,j);b(this,"version");b(this,"inputs");b(this,"outputs");b(this,"lockTime");b(this,"metadata");b(this,"merklePath");G(this,kr);G(this,ti);G(this,Ri);G(this,Tr);G(this,Ni);G(this,qo);G(this,ls);this.version=t,this.inputs=e,this.outputs=i,this.lockTime=r,this.metadata=s,this.merklePath=o}getSignatureHashCache(){return y(this,qo)??{hashOutputsSingle:new Map}}materializeSourceTXIDs(){let t=new Set,e=new Set,i=[{tx:this,expanded:!1}];for(;i.length>0;){let r=i.pop();if(r!=null&&!t.has(r.tx)){if(r.expanded){a(this,j,sg).call(this,r.tx,e,t);continue}a(this,j,og).call(this,r.tx,e,t,i)}}}static fromBEEF(t,e){var r;let{tx:i}=a(r=oe,Mn,$o).call(r,t,e);return i}static fromBEEFView(t,e){var r;let{tx:i}=a(r=oe,Mn,$o).call(r,t,e,!0);return i}static fromAtomicBEEF(t){var s;let{tx:e,txid:i,beef:r}=a(s=oe,Mn,$o).call(s,t);if(i!==r.atomicTxid)throw r.atomicTxid==null?new Error("beef must conform to BRC-95 and must contain the subject txid."):new Error(`Transaction with TXID ${r.atomicTxid} not found in BEEF data.`);if(!r.isAtomic(i))throw new Error("Atomic BEEF contains unrelated transaction data.");return e}static fromAtomicBEEFView(t){var s;let{tx:e,txid:i,beef:r}=a(s=oe,Mn,$o).call(s,t,void 0,!0);if(i!==r.atomicTxid)throw r.atomicTxid==null?new Error("beef must conform to BRC-95 and must contain the subject txid."):new Error(`Transaction with TXID ${r.atomicTxid} not found in BEEF data.`);if(!r.isAtomic(i))throw new Error("Atomic BEEF contains unrelated transaction data.");return e}static fromEF(t){let e=bt.makeReader(t),i=e.readUInt32LE();if(nt(e.read(6))!=="0000000000ef")throw new Error("Invalid EF marker");let r=e.readVarIntNumStrict(!1),s=[];for(let f=0;f<r;f++){let d=nt(e.readReverse(32)),l=e.readUInt32LE();if(l>Wy)throw new RangeError("EF source output index exceeds the allocation limit");let p=e.readVarIntNumStrict(!1),m=e.read(p),g=Ue.fromBinary(m),w=e.readUInt32LE(),S=e.readUInt64LEBn().toNumber(),C=e.readVarIntNumStrict(!1),E=e.read(C),A=Le.fromBinary(E),k=new oe(void 0,[],[],void 0);k.outputs=Array.from({length:l+1}).fill(null),k.outputs[l]={satoshis:S,lockingScript:A},s.push({sourceTransaction:k,sourceTXID:d,sourceOutputIndex:l,unlockingScript:g,sequence:w})}let o=e.readVarIntNumStrict(!1),c=[];for(let f=0;f<o;f++){let d=e.readUInt64LEBn().toNumber(),l=e.readVarIntNumStrict(!1),p=e.read(l),m=Le.fromBinary(p);c.push({satoshis:d,lockingScript:m})}let u=e.readUInt32LE();if(!e.eof())throw new Error("Serialized EF transaction contains trailing data");return new oe(i,s,c,u)}static parseScriptOffsets(t){let e=bt.makeReader(t),i=[],r=[];e.read(4);let s=e.readVarIntNumStrict(!1);for(let c=0;c<s;c++){e.read(36);let u=e.readVarIntNumStrict(!1);i.push({vin:c,offset:e.pos,length:u}),e.read(u+4)}let o=e.readVarIntNumStrict(!1);for(let c=0;c<o;c++){e.read(8);let u=e.readVarIntNumStrict(!1);r.push({vout:c,offset:e.pos,length:u}),e.read(u)}if(e.read(4),!e.eof())throw new Error("Serialized transaction contains trailing data");return{inputs:i,outputs:r}}static fromReader(t){var e;return a(e=oe,Mn,nd).call(e,t,!1)}static fromBinary(t){let e=Uint8Array.from(t);return oe.fromBinaryView(e)}static fromBinaryView(t){var r,s;let e=new bt(t),i=a(r=oe,Mn,nd).call(r,e,!0);if(!e.eof())throw new Error("Serialized transaction contains trailing data");return N(i,Ri,t),a(s=i,j,ac).call(s),i}static fromHex(t){let e=et(t,"hex"),i=oe.fromBinaryView(e);return N(i,Ni,nt(e)),i}static fromHexEF(t){return oe.fromEF(et(t,"hex"))}static fromHexBEEF(t,e){return oe.fromBEEF(at(t,"hex"),e)}addInput(t){if(t.sourceTXID===void 0&&t.sourceTransaction===void 0)throw new TypeError("A reference to an an input transaction is required. If the input transaction itself cannot be referenced, its TXID must still be provided.");Ge(t.sourceOutputIndex,"sourceOutputIndex"),t.sourceTXID!==void 0&&(t.sourceTXID=Oi(t.sourceTXID,"sourceTXID")),t.sequence!==void 0&&Ge(t.sequence,"sequence"),t.sequence??(t.sequence=4294967295),a(this,j,yn).call(this),this.inputs.push(t)}addOutput(t){if(a(this,j,yn).call(this),t.satoshis===void 0&&t.change!==!0)throw new TypeError("either satoshis must be defined or change must be set to true");if(t.satoshis!==void 0&&sn(t.satoshis,"satoshis"),t.lockingScript==null)throw new Error("lockingScript must be defined");this.outputs.push(t)}addP2PKHOutput(t,e){let i=new Yn().lock(t);if(e===void 0)return this.addOutput({lockingScript:i,change:!0});this.addOutput({lockingScript:i,satoshis:e})}updateMetadata(t){this.metadata={...this.metadata,...t}}async fee(t=Ao.getInstance(),e="equal"){var S,C,E,A,k;if(a(this,j,yn).call(this),e!=="equal"&&e!=="random")throw new TypeError('changeDistribution must be either "equal" or "random".');if(typeof t=="number"){let B=t;t={computeFee:async()=>B}}let i=a(this,j,Pi).call(this,!0),r=a(S=i,j,Pi).call(S,!0),s=a(C=i,j,Pi).call(C,!0),o=[...this.inputs],c=this.inputs.map(B=>B.sourceTransaction),u=this.inputs.map(B=>B.unlockingScriptTemplate),f=[...this.outputs],d=[...s.inputs],l=s.inputs.map(B=>B.sourceTransaction),p=s.inputs.map(B=>B.unlockingScriptTemplate),m=[...s.outputs],g=sn(await t.computeFee(s),"Computed transaction fee");if(!a(E=s,j,uc).call(E,i,d,l,p,m))throw new Error("Fee model mutated its transaction snapshot");let w=a(A=r,j,ag).call(A,g);if(w<0)throw new RangeError("Transaction inputs are insufficient for the requested outputs and fee.");if(!a(this,j,uc).call(this,i,o,c,u,f))throw new Error("Transaction changed while computing its fee; no change was applied");if(w===0){this.outputs=f.filter(B=>B.change!==!0),a(this,j,yn).call(this);return}a(k=r,j,cg).call(k,w,e);for(let B=0;B<f.length;B++)f[B].change===!0&&(f[B].satoshis=r.outputs[B].satoshis);a(this,j,yn).call(this)}getFee(){let t=0;for(let i=0;i<this.inputs.length;i++){let r=this.inputs[i];if(typeof r.sourceTransaction!="object")throw new TypeError("Source transactions or sourceSatoshis are required for all inputs to calculate fee");Ge(r.sourceOutputIndex,`Input ${i} sourceOutputIndex`);let s=r.sourceTransaction.outputs[r.sourceOutputIndex];if(s==null)throw new RangeError(`Input ${i} references a source output that does not exist.`);t=ds(t,sn(s.satoshis,`Input ${i} source amount`),"Transaction input total")}let e=0;for(let i=0;i<this.outputs.length;i++)e=ds(e,sn(this.outputs[i].satoshis,`Output ${i} amount`),"Transaction output total");return t-e}async sign(t={}){a(this,j,yn).call(this);for(let f=0;f<this.outputs.length;f++){let d=this.outputs[f];if(d.satoshis===void 0)throw d.change===!0?new Error("There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing."):new Error("One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.");sn(d.satoshis,`Output ${f} amount`)}a(this,j,cc).call(this,this);for(let f=0;f<this.inputs.length;f++){let d=this.inputs[f];if(Ge(d.sourceOutputIndex,`Input ${f} sourceOutputIndex`),Ge(d.sequence??4294967295,`Input ${f} sequence`),d.sourceTXID!==void 0&&Oi(d.sourceTXID,`Input ${f} sourceTXID`),d.sourceTransaction!==void 0){let l=d.sourceTransaction.outputs[d.sourceOutputIndex];if(l==null)throw new RangeError(`Input ${f} references a source output that does not exist.`);if(sn(l.satoshis,`Input ${f} source amount`),d.sourceTXID!==void 0&&(d.sourceTransaction.inputs.length>0||d.sourceTransaction.merklePath!=null)&&Oi(d.sourceTXID,`Input ${f} sourceTXID`)!==d.sourceTransaction.id("hex"))throw new Error(`Input ${f} sourceTXID does not reference its supplied source transaction.`)}}this.materializeSourceTXIDs();let e=a(this,j,Pi).call(this,!0),i=[...this.inputs],r=this.inputs.map(f=>f.sourceTransaction),s=this.inputs.map(f=>f.unlockingScriptTemplate),o=[...this.outputs],c=t.skipExistingSignatures===!0,u;if(u=await Promise.all(e.inputs.map(async(f,d)=>{var w;if(c&&f.unlockingScript!=null)return new Ue([],Uint8Array.from(f.unlockingScript.toUint8Array()),void 0,!1);let l=s[d];if(l===void 0)return;let p=a(w=e,j,Pi).call(w,!0);for(let S=0;S<s.length;S++)p.inputs[S].unlockingScriptTemplate=s[S];N(p,qo,{hashOutputsSingle:new Map});let m=await l.sign(p,d);if(m==null||typeof m.toUint8Array!="function")throw new TypeError(`Input ${d} signing template returned an invalid unlocking script`);let g=m.toUint8Array();if(!(g instanceof Uint8Array))throw new TypeError(`Input ${d} signing template returned an invalid unlocking script`);return new Ue([],Uint8Array.from(g),void 0,!1)})),!a(this,j,uc).call(this,e,i,r,s,o))throw new Error("Transaction changed while signing; no unlocking scripts were applied");for(let f=0,d=this.inputs.length;f<d;f++)s[f]!==void 0&&!(c&&i[f].unlockingScript!=null)&&(this.inputs[f].unlockingScript=u[f]);a(this,j,yn).call(this)}async broadcast(t=Xp()){let e=a(this,j,Pi).call(this),i=e.id("hex");return Lp(await t.broadcast(e),i)}[ng](){return a(this,j,Er).call(this)}[ig](t){N(this,ti,t)}toBinary(){return Array.from(a(this,j,Er).call(this))}toUint8Array(){return Uint8Array.from(a(this,j,Er).call(this))}toEF(){return Array.from(a(this,j,sd).call(this))}toEFUint8Array(){return this.toEFBinary()}toEFBinary(){return Uint8Array.from(a(this,j,sd).call(this))}toHexEF(){return nt(this.toEFBinary())}toHex(){let t=a(this,j,Er).call(this);if(y(this,Ni)!=null)return y(this,Ni);let e=nt(t);return N(this,Ni,e),e}toHexBEEF(){return nt(this.toBEEF())}toHexAtomicBEEF(){return nt(this.toAtomicBEEF())}hash(t){let e=a(this,j,Er).call(this);return y(this,kr)??N(this,kr,zt(e)),t==="hex"?nt(y(this,kr)):Array.from(y(this,kr))}id(t){if(a(this,j,Er).call(this),t==="hex"&&y(this,ti)!=null)return y(this,ti);let e=[...this.hash()];return e.reverse(),t==="hex"?(N(this,ti,nt(e)),y(this,ti)):e}async verifyTransactionFee(t,e,i){if(e===void 0)return;if(t===void 0)throw new Error("Transaction is undefined");let r=oe.fromEF(t.toEF());if(delete r.outputs[0].satoshis,r.outputs[0].change=!0,await r.fee(e),t.getFee()<r.getFee())throw new Error(`Verification failed because the transaction ${i()} has an insufficient fee and has not been mined.`)}async verify(t=Zp(),e,i,r){var o;t!=="scripts only"&&this.materializeSourceTXIDs();let s=t==="scripts only"?void 0:tg(this);return await a(o=a(this,j,Pi).call(this),j,Ig).call(o,t,e,i,r,s)}writeSerializedBEEF(t,e){this.materializeSourceTXIDs(),t.writeUInt32LE(4022206465);let{bumps:i,txs:r}=a(this,j,vg).call(this,e);t.writeVarIntNum(i.length);let s=a(this,j,Tg).call(this,t,i,r);for(let o=0;o<i.length;o++)t.write(s?.[o]??i[o].toBinary());t.writeVarIntNum(r.length);for(let o of r)t.write(o.tx.toUint8Array()),typeof o.pathIndex=="number"?(t.writeUInt8(1),t.writeVarIntNum(o.pathIndex)):t.writeUInt8(0)}toBEEF(t){let e=new fe;return this.writeSerializedBEEF(e,t),e.toArray()}toBEEFUint8Array(t){let e=new ht;return this.writeSerializedBEEF(e,t),e.toArray()}toBEEFBytes(t){let e=new ht;return this.writeSerializedBEEF(e,t),e.toUint8Array()}toAtomicBEEF(t){this.materializeSourceTXIDs();let e=[1,1,1,1],i=this.hash(),r=this.toBEEF(t);return e.concat(i,r)}toAtomicBEEFUint8Array(t){this.materializeSourceTXIDs();let e=new ht,i=[1,1,1,1];e.write(i);let r=this.hash();return e.write(r),this.writeSerializedBEEF(e,t),e.toUint8Array()}async completeWithWallet(t,e,i,r){let s=this.inputs.length,o=this.outputs.length,c=e??`Transaction with ${s} input(s) and ${o} output(s)`,u=this.inputs.some(p=>p.unlockingScriptTemplate!=null),f=await a(this,j,Og).call(this,c,u);f.options=r;let d={};for(let p=0;p<this.inputs.length;p++){let m=this.inputs[p].unlockingScriptTemplate;if(m==null)continue;let g=f.inputs[p].outpoint;d[g]=async(w,S)=>await m.sign(w,S)}let l=await J0(t,f,{inputSigners:d},i,this.inputs.map((p,m)=>{let g=p.sourceTransaction?.outputs[p.sourceOutputIndex];if(g==null)throw new Error(`Input ${m} references a source output that does not exist`);return sn(g.satoshis,`Input ${m} source amount`)}));this.version=l.version,this.inputs=l.inputs,this.outputs=l.outputs,this.lockTime=l.lockTime,this.merklePath=l.merklePath,a(this,j,yn).call(this),this.metadata={...this.metadata,...l.metadata}}preimage(t,e,i){if(t??(t=0),e??(e=wt.SIGHASH_FORKID|wt.SIGHASH_ALL),!Number.isSafeInteger(t)||t<0||t>=this.inputs.length)throw new Error("Invalid input index");Ge(e,"signatureScope");let r=e&240;if(r!==224&&r!==192&&r!==64)throw new Error("FORKID must be set");let s=e&15;if(s<1||s>3)throw new Error("Invalid signature coverage, must be all, none or single");let o=this.inputs[t],c=Ge(o.sourceOutputIndex,"sourceOutputIndex");if(o.sourceTransaction==null)throw new Error("Source transaction is required");let u=Oi(o.sourceTransaction.id("hex"),"sourceTransaction ID");if(o.sourceTXID!==void 0&&Oi(o.sourceTXID,"sourceTXID")!==u)throw new Error("sourceTXID does not match sourceTransaction");let f=o.sourceTransaction.outputs[c];if(f==null)throw new Error(`Source transaction's output at index ${c} is required`);let d=sn(f.satoshis,"Source output amount"),l=Ge(o.sequence??4294967295,"inputSequence"),p=i??f.lockingScript;if(p==null||typeof p.toUint8Array!="function")throw new Error("subscript must be a locking script");return wt.format({sourceTXID:u,sourceOutputIndex:c,sourceSatoshis:d,transactionVersion:this.version,otherInputs:[],allInputs:this.inputs,inputIndex:t,outputs:this.outputs,inputSequence:l,subscript:p,lockTime:this.lockTime,scope:e})}};kr=new WeakMap,ti=new WeakMap,Ri=new WeakMap,Tr=new WeakMap,Ni=new WeakMap,qo=new WeakMap,ls=new WeakMap,j=new WeakSet,sg=function(t,e,i){for(let r of t.inputs)r.sourceTXID==null&&r.sourceTransaction!=null&&(r.sourceTXID=r.sourceTransaction.id("hex"));e.delete(t),i.add(t)},og=function(t,e,i,r){if(e.has(t))throw new Error("Cyclic source transaction graph");e.add(t),r.push({tx:t,expanded:!0});for(let s=t.inputs.length-1;s>=0;s--){let o=t.inputs[s].sourceTransaction;t.inputs[s].sourceTXID==null&&o!=null&&!i.has(o)&&r.push({tx:o,expanded:!1})}},Mn=new WeakSet,$o=function(t,e,i=!1){let r=i&&t instanceof Uint8Array?Ir.fromBinaryView(t):Ir.fromBinaryStrict(t);if(r.txs.length<1)throw new Error("beef must include at least one transaction.");let s=r.txs.at(-1);if(s==null)throw new Error("beef must include at least one transaction.");let o=e??r.atomicTxid??s.txid,c=r.findAtomicTransaction(o);if(c==null)throw e==null?new Error("beef does not contain transaction for atomic txid."):new Error(`Transaction with TXID ${String(o)} not found in BEEF data.`);return{tx:c,beef:r,txid:o}},nd=function(t,e){let i=t.readUInt32LE(),r=t.readVarIntNumStrict(!1),s=[];for(let f=0;f<r;f++){let d=nt(t.readReverse(32)),l=t.readUInt32LE(),p=t.readVarIntNumStrict(!1),m=e&&t instanceof bt?t.readView(p):t.read(p),g=e&&m instanceof Uint8Array?Ue.fromBinaryView(m):Ue.fromBinary(m),w=t.readUInt32LE();s.push({sourceTXID:d,sourceOutputIndex:l,unlockingScript:g,sequence:w})}let o=t.readVarIntNumStrict(!1),c=[];for(let f=0;f<o;f++){let d=t.readUInt64LEBn().toNumber(),l=t.readVarIntNumStrict(!1),p=e&&t instanceof bt?t.readView(l):t.read(l),m=e&&p instanceof Uint8Array?Le.fromBinaryView(p):Le.fromBinary(p);c.push({satoshis:d,lockingScript:m})}let u=t.readUInt32LE();return new oe(i,s,c,u)},yn=function(){N(this,kr,void 0),N(this,ti,void 0),N(this,Ri,void 0),N(this,Tr,void 0),N(this,Ni,void 0),N(this,ls,void 0)},id=function(t){return t.sourceTXID==null?t.sourceTransaction?.id("hex"):void 0},ac=function(){N(this,ls,{version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(t=>{let e=t.sourceTransaction?.outputs[t.sourceOutputIndex];return{ref:t,sourceTXID:t.sourceTXID,sourceTransactionId:a(this,j,id).call(this,t),sourceOutputIndex:t.sourceOutputIndex,sequence:t.sequence,unlockingScript:t.unlockingScript,unlockingScriptBytes:t.unlockingScript==null?void 0:hr(t.unlockingScript),sourceOutput:e,sourceSatoshis:e?.satoshis,sourceLockingScript:e?.lockingScript,sourceLockingScriptBytes:e==null?void 0:hr(e.lockingScript)}}),outputs:this.outputs.map(t=>({ref:t,satoshis:t.satoshis,lockingScript:t.lockingScript,lockingScriptBytes:hr(t.lockingScript)}))})},rd=function(){let t=y(this,ls);if(t?.version!==this.version||t.lockTime!==this.lockTime||t.inputs.length!==this.inputs.length||t.outputs.length!==this.outputs.length)return!1;for(let e=0;e<this.inputs.length;e++){let i=this.inputs[e],r=t.inputs[e],s=i.sourceTransaction?.outputs[i.sourceOutputIndex];if(r.ref!==i||r.sourceTXID!==i.sourceTXID||r.sourceTransactionId!==a(this,j,id).call(this,i)||r.sourceOutputIndex!==i.sourceOutputIndex||r.sequence!==i.sequence||r.unlockingScript!==i.unlockingScript||r.unlockingScriptBytes!==(i.unlockingScript==null?void 0:hr(i.unlockingScript))||r.sourceOutput!==s||r.sourceSatoshis!==s?.satoshis||r.sourceLockingScript!==s?.lockingScript||r.sourceLockingScriptBytes!==(s==null?void 0:hr(s.lockingScript)))return!1}for(let e=0;e<this.outputs.length;e++){let i=this.outputs[e],r=t.outputs[e];if(r.ref!==i||r.satoshis!==i.satoshis||r.lockingScript!==i.lockingScript||r.lockingScriptBytes!==hr(i.lockingScript))return!1}return!0},ag=function(t){let e=0;for(let r=0;r<this.inputs.length;r++){let s=this.inputs[r];if(typeof s.sourceTransaction!="object")throw new TypeError("Source transactions are required for all inputs during fee computation");Ge(s.sourceOutputIndex,`Input ${r} sourceOutputIndex`);let o=s.sourceTransaction.outputs[s.sourceOutputIndex];if(o==null)throw new RangeError(`Input ${r} references a source output that does not exist.`);let c=sn(o.satoshis,`Input ${r} source amount`);e=ds(e,c,"Transaction input total")}let i=0;for(let r=0;r<this.outputs.length;r++){let s=this.outputs[r];if(s.change!==!0){let o=sn(s.satoshis,`Output ${r} amount`);i=ds(i,o,"Transaction output total")}}if(i+t>e)throw new RangeError("Transaction inputs are insufficient for the requested outputs and fee.");return e-i-t},cg=function(t,e){let i=this.outputs.filter(r=>r.change===!0);i.length!==0&&(e==="random"?a(this,j,ug).call(this,t,i):a(this,j,fg).call(this,t,i))},ug=function(t,e){let i=t;for(let r=0;r<e.length-1;r++){let s=a(this,j,dg).call(this,0,i);e[r].satoshis=s,i-=s}e.at(-1).satoshis=i},fg=function(t,e){let i=Math.floor(t/e.length);for(let r of e)r.satoshis=i;e.at(-1).satoshis+=t-i*e.length},dg=function(t,e){let i=Pe(1)[0]%9+1;return Math.floor(t+(e-t)*Math.log10(1+1/i)/Math.log10(10))},lg=function(t){t.writeUInt32LE(this.version),t.writeVarIntNum(this.inputs.length);for(let e of this.inputs){if(e.sourceTXID===void 0){if(e.sourceTransaction==null)throw new Error("sourceTransaction is undefined");t.write(e.sourceTransaction.hash())}else t.writeReverse(at(Oi(e.sourceTXID,"sourceTXID"),"hex"));if(t.writeUInt32LE(Ge(e.sourceOutputIndex,"sourceOutputIndex")),e.unlockingScript==null)throw new Error("unlockingScript is undefined");let i=e.unlockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i),t.writeUInt32LE(Ge(e.sequence??4294967295,"sequence"))}t.writeVarIntNum(this.outputs.length);for(let e of this.outputs){t.writeUInt64LE(e.satoshis??0);let i=e.lockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i)}t.writeUInt32LE(this.lockTime)},hg=function(){let t=new ht;return a(this,j,lg).call(this,t),t.toUint8Array()},Er=function(){return(y(this,Ri)==null||!a(this,j,rd).call(this))&&(a(this,j,yn).call(this),N(this,Ri,a(this,j,hg).call(this)),a(this,j,ac).call(this)),y(this,Ri)},pg=function(t){t.writeUInt32LE(this.version),t.write([0,0,0,0,0,239]),t.writeVarIntNum(this.inputs.length);for(let e of this.inputs){if(e.sourceTransaction===void 0)throw new TypeError("All inputs must have source transactions when serializing to EF format");if(e.sourceTXID===void 0?t.write(e.sourceTransaction.hash()):t.write(at(e.sourceTXID,"hex").reverse()),t.writeUInt32LE(e.sourceOutputIndex),e.unlockingScript==null)throw new Error("unlockingScript is undefined");let i=e.unlockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i),t.writeUInt32LE(e.sequence??4294967295),t.writeUInt64LE(e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0);let r=e.sourceTransaction.outputs[e.sourceOutputIndex].lockingScript.toUint8Array();t.writeVarIntNum(r.length),t.write(r)}t.writeVarIntNum(this.outputs.length);for(let e of this.outputs){t.writeUInt64LE(e.satoshis??0);let i=e.lockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i)}t.writeUInt32LE(this.lockTime)},sd=function(){if(y(this,Tr)==null||!a(this,j,rd).call(this)){a(this,j,yn).call(this);let t=new ht;a(this,j,pg).call(this,t),N(this,Tr,t.toUint8Array()),a(this,j,ac).call(this)}return y(this,Tr)},gg=async function(t,e,i,r,s,o){if(typeof t.merklePath!="object")return!1;if(e)return s.add(t),!0;if(await t.merklePath.verify(r(),i))return o.add(r()),!0;throw new Error(`Invalid merkle path for transaction ${r()}`)},mg=function(t,e){if(t.inputs.length===0)throw new Error(`Verification failed because transaction ${e()} has no inputs.`);if(t.outputs.length===0)throw new Error(`Verification failed because transaction ${e()} has no outputs.`);let i=new Set;for(let r=0;r<t.inputs.length;r++){let s=t.inputs[r],o=Ge(s.sourceOutputIndex,`Input ${r} sourceOutputIndex`);Ge(s.sequence??4294967295,`Input ${r} sequence`);let c=Oi(s.sourceTXID??s.sourceTransaction?.id("hex"),`Input ${r} sourceTXID`);if(/^0{64}$/.test(c)&&o===4294967295)throw new Error(`Verification failed because unmined transaction ${e()} contains a coinbase input.`);let u=`${c}:${o}`;if(i.has(u))throw new Error(`Verification failed because transaction ${e()} spends outpoint ${u} more than once.`);i.add(u)}a(this,j,cc).call(this,t)},bg=function(t,e,i){if(i.scriptsOnly){!i.verifiedTransactions.has(t)&&!i.queuedTransactions.has(t)&&(i.txQueue.push(t),i.queuedTransactions.add(t));return}!i.verifiedTxids.has(e)&&!i.queuedTxids.has(e)&&(i.txQueue.push(t),i.queuedTxids.add(e))},wg=function(t,e,i,r){let s=0,o={hashOutputsSingle:new Map};for(let c=0;c<t.inputs.length;c++){let u=t.inputs[c];if(typeof u.sourceTransaction!="object")throw new TypeError(`Verification failed because the input at index ${c} of transaction ${i()} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`);if(typeof u.unlockingScript!="object")throw new TypeError(`Verification failed because the input at index ${c} of transaction ${i()} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);let f=u.sourceTransaction,d=f.outputs[u.sourceOutputIndex];if(d==null)throw new RangeError(`Verification failed because input ${c} of transaction ${i()} references a source output that does not exist.`);s=ds(s,sn(d.satoshis,`Input ${c} source amount`),"Transaction input total");let l=f.id("hex");if(!r.scriptsOnly&&u.sourceTXID!==void 0&&Oi(u.sourceTXID,`Input ${c} sourceTXID`)!==l)throw new Error(`Verification failed because input ${c} of transaction ${i()} does not reference its supplied source transaction.`);let p=r.scriptsOnly&&u.sourceTXID!==void 0?u.sourceTXID:f.id("hex");if(a(this,j,bg).call(this,f,p,r),u.sourceTXID??(u.sourceTXID=p),!e&&!new xo({sourceTXID:u.sourceTXID,sourceOutputIndex:u.sourceOutputIndex,lockingScript:d.lockingScript,sourceSatoshis:d.satoshis??0,transactionVersion:t.version,otherInputs:[],allInputs:t.inputs,unlockingScript:u.unlockingScript,inputSequence:u.sequence??4294967295,inputIndex:c,outputs:t.outputs,lockTime:t.lockTime,memoryLimit:r.memoryLimit,sigHashCache:o}).validateJavaScript())return{valid:!1,inputTotal:s}}return{valid:!0,inputTotal:s}},cc=function(t){let e=0;for(let i=0;i<t.outputs.length;i++)e=ds(e,sn(t.outputs[i].satoshis,`Output ${i} amount`),"Transaction output total");return e},yg=async function(t,e){if(t.length===0||e===void 0)return;let i=e.verifyScriptsBatch===void 0?await Promise.all(t.map(async o=>await e.verifyScripts(o))):await e.verifyScriptsBatch(t);if(!Array.isArray(i)||i.length!==t.length)throw new Error("Script verifier returned an invalid batch result count");let r=[];for(let o=0;o<i.length;o++){if(!Object.prototype.hasOwnProperty.call(i,o)||typeof i[o]!="boolean")throw new TypeError("Script verifier returned a non-boolean verdict");r.push(i[o])}let s=r.findIndex(o=>!o);if(s>=0)throw new Error(`Script verification failed for transaction ${t[s].tx.id("hex")}`)},xg=function(t,e,i){return i.scriptsOnly?i.verifiedTransactions.has(t):i.verifiedTxids.has(e())},Pi=function(t=!1){let e=new Map,i=[this];e.set(this,new oe(this.version,[],[],this.lockTime));for(let s=0;s<i.length;s++){let o=i[s],c=e.get(o);if(c===void 0)throw new Error("Transaction snapshot is incomplete");c.version=o.version,c.lockTime=o.lockTime,c.merklePath=o.merklePath===void 0?void 0:new Ei(o.merklePath.blockHeight,o.merklePath.path.map(u=>u.map(f=>({...f})))),c.outputs=Array.from(o.outputs,u=>u==null?u:{satoshis:u.satoshis,lockingScript:new Le([],Uint8Array.from(u.lockingScript.toUint8Array()),void 0,!1),change:u.change}),c.inputs=Array.from(o.inputs,u=>{let f;return u.sourceTransaction!==void 0&&(f=e.get(u.sourceTransaction),f===void 0&&(f=new oe(u.sourceTransaction.version,[],[],u.sourceTransaction.lockTime),e.set(u.sourceTransaction,f),i.push(u.sourceTransaction))),{sourceTransaction:f,sourceTXID:u.sourceTXID,sourceOutputIndex:u.sourceOutputIndex,unlockingScript:u.unlockingScript===void 0?void 0:new Ue([],Uint8Array.from(u.unlockingScript.toUint8Array()),void 0,!1),unlockingScriptTemplate:t?u.unlockingScriptTemplate:void 0,sequence:u.sequence}})}let r=e.get(this);if(r===void 0)throw new Error("Transaction snapshot is incomplete");return r},uc=function(t,e,i,r,s){if(this.version!==t.version||this.lockTime!==t.lockTime||this.inputs.length!==t.inputs.length||this.outputs.length!==t.outputs.length)return!1;for(let o=0;o<this.inputs.length;o++){let c=this.inputs[o],u=t.inputs[o];if(c!==e[o]||c.sourceTransaction!==i[o]||c.unlockingScriptTemplate!==r[o]||c.sourceTXID!==u.sourceTXID||c.sourceOutputIndex!==u.sourceOutputIndex||c.sequence!==u.sequence||!ed(c.unlockingScript?.toUint8Array(),u.unlockingScript?.toUint8Array()))return!1;let f=c.sourceTransaction?.outputs[c.sourceOutputIndex],d=u.sourceTransaction?.outputs[u.sourceOutputIndex];if(f==null||d==null){if(f!==d)return!1}else if(!Object.is(f.satoshis,d.satoshis)||!ed(f.lockingScript.toUint8Array(),d.lockingScript.toUint8Array()))return!1}for(let o=0;o<this.outputs.length;o++){let c=this.outputs[o],u=t.outputs[o];if(c!==s[o]||!Object.is(c.satoshis,u.satoshis)||c.change!==u.change||!ed(c.lockingScript.toUint8Array(),u.lockingScript.toUint8Array()))return!1}return!0},Sg=async function(t,e,i){let{feeModel:r,memoryLimit:s,selectedVerifier:o,verifierQueue:c}=i;a(this,j,mg).call(this,t,e),await this.verifyTransactionFee(t,r,e);let u={tx:t,blockHeight:Fy,consensus:!0,...s===void 0?{}:{memoryLimit:s}},f=o!==void 0&&(s===void 0||o.supportsMemoryLimit===!0)&&(o.shouldVerifyScripts?.(u)??!0),d=p=>a(this,j,wg).call(this,t,p,e,i),l=!f&&i.scriptWork!==void 0?i.scriptWork.work.inputs(i.scriptWork,u,d):d(f);return!l.valid||(f&&c.push(u),a(this,j,cc).call(this,t)>l.inputTotal)?!1:(i.scriptsOnly?i.verifiedTransactions.add(t):i.verifiedTxids.add(e()),!0)},Ig=async function(t,e,i,r,s){let o=t==="scripts only",c=r??Da(),u=s!==void 0&&c!==void 0?eg(s,c):c;o||this.materializeSourceTXIDs();let f=new Set,d=new Set,l=[this],p=new Set;o||p.add(this.id("hex"));let m=new Set(l),g=[],w={scriptsOnly:o,memoryLimit:i,txQueue:l,queuedTransactions:m,queuedTxids:p,verifiedTransactions:d,verifiedTxids:f,feeModel:e,selectedVerifier:u,verifierQueue:g,scriptWork:s},S=0;for(;S<l.length;){let C=l[S++],E,A=()=>(E??(E=C.id("hex")),E);if(!a(this,j,xg).call(this,C,A,w)&&!await a(this,j,gg).call(this,C,o,t,A,d,f)&&!await a(this,j,Sg).call(this,C,A,w))return!1}return await a(this,j,yg).call(this,g,u),!0},vg=function(t){let e=[],i=new Map,r=new Map,s=[],o=new Set,c=new Set,u=[{tx:this,expanded:!1}];for(;u.length>0;){let f=u.pop();if(f!=null){if(f.expanded){a(this,j,Ag).call(this,f.tx,o,s,e,i,r);continue}a(this,j,Eg).call(this,f.tx,t,c,u)}}return{bumps:e,txs:s}},Ag=function(t,e,i,r,s,o){let c=t.id("hex");if(e.has(c))return;let u={tx:t};t.merklePath!=null&&(u.pathIndex=a(this,j,kg).call(this,t.merklePath,r,s,o)),e.add(c),i.push(u)},Eg=function(t,e,i,r){let s=t.id("hex");if(!i.has(s)&&(i.add(s),r.push({tx:t,expanded:!0}),t.merklePath==null))for(let o of t.inputs){let c=o.sourceTransaction;if(c!=null)r.push({tx:c,expanded:!1});else if(e===!1)throw new Error("A required source transaction is missing!")}},kg=function(t,e,i,r){let s=i.get(t);if(s!==void 0)return s;let o=`${t.blockHeight}:${t.computeRoot()}`,c=r.get(o);if(c!==void 0)return e[c].combine(t),i.set(t,c),c;let u=e.length;return e.push(t),i.set(t,u),r.set(o,u),u},Tg=function(t,e,i){let r;if(t instanceof ht){r=e.map(o=>o.toBinaryUint8Array());let s=16;for(let o of r)s+=o.length;for(let o of i)s+=o.tx.toUint8Array().length+10;t.reserve(s)}return r},Og=async function(t,e){let i={description:t,inputs:[],outputs:[],lockTime:this.lockTime,version:this.version};this.materializeSourceTXIDs();let r=new Ir;for(let s=0;s<this.inputs.length;s++){let o=this.inputs[s];if(o.sourceTransaction==null)throw new Error("All inputs must have a sourceTransaction when using completeWithWallet");r.mergeTransaction(o.sourceTransaction),i.inputs.push(await a(this,j,Pg).call(this,o,s,e))}return this.inputs.length>0&&(i.inputBEEF=r.toUint8Array()),i.outputs=this.outputs.map(s=>({satoshis:s.satoshis,lockingScript:s.lockingScript.toHex(),outputDescription:"Output from source transaction"})),Array.isArray(this.metadata?.labels)&&(i.labels=this.metadata.labels),i},Pg=async function(t,e,i){let r={outpoint:`${t.sourceTransaction.id("hex")}.${t.sourceOutputIndex}`,inputDescription:"Input from source transaction",sequenceNumber:t.sequence};if(!i){if(t.unlockingScript==null)throw new Error("All inputs must have an unlockingScript when using completeWithWallet");return r.unlockingScript=t.unlockingScript.toHex(),r}if(t.unlockingScriptTemplate!=null)r.unlockingScriptLength=await t.unlockingScriptTemplate.estimateLength(this,e);else if(t.unlockingScript!=null)r.unlockingScript=t.unlockingScript.toHex();else throw new Error(`Input ${e} must have either an unlockingScript or unlockingScriptTemplate`);return r},G(oe,Mn);var Me=oe;var ei=class extends Error{constructor(e,i){super(`The ${e} parameter must be ${i??"valid."}`);b(this,"parameter");b(this,"code");b(this,"isError",!0);this.parameter=e,this.code=6,this.name=this.constructor.name}},ut=ei;var Rg=globalThis.Buffer,od=typeof Rg?.compare=="function"?Rg.compare:void 0,fc=globalThis.SharedArrayBuffer,Vy=16*1024*1024,Bi=class{constructor(){b(this,"cached")}get(t){let e=this.cached;if(!(e==null||!(t instanceof Uint8Array)||t.length!==e.bytes.length||od==null||fc!=null&&t.buffer instanceof fc||od(t,e.bytes)!==0))return e.value}set(t,e){t instanceof Uint8Array&&t.length<=Vy&&od!=null&&!(fc!=null&&t.buffer instanceof fc)&&(this.cached={bytes:new Uint8Array(t),value:e})}};var Dn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ng="0123456789abcdef";function Ye(n){let t="";for(let e=0;e<n.length;e++){let i=n[e];t+=Ng[i>>4]+Ng[i&15]}return t}function hs(n){if(typeof n!="string"||n.length%2!==0||!/^[0-9a-f]*$/iu.test(n))throw new TypeError("Invalid hexadecimal byte string");let t=Array.from({length:n.length/2});for(let e=0;e<t.length;e++)t[e]=Number.parseInt(n.slice(e*2,e*2+2),16);return t}function Bg(n){let t="";for(let e=0;e<n.length;e+=3){let i=n[e],r=e+1<n.length?n[e+1]:0,s=e+2<n.length?n[e+2]:0;t+=Dn[i>>2],t+=Dn[(i&3)<<4|r>>4],t+=e+1<n.length?Dn[(r&15)<<2|s>>6]:"=",t+=e+2<n.length?Dn[s&63]:"="}return t}function dc(n){if(typeof n!="string"||n.length%4!==0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(n))throw new TypeError("Invalid canonical base64 string");if(n.endsWith("==")&&(Dn.indexOf(n[n.length-3])&15)!==0)throw new TypeError("Invalid canonical base64 string");if(n.endsWith("=")&&!n.endsWith("==")&&(Dn.indexOf(n[n.length-2])&3)!==0)throw new TypeError("Invalid canonical base64 string");let t=[];for(let e=0;e<n.length;e+=4){let i=Dn.indexOf(n[e]),r=Dn.indexOf(n[e+1]),s=n[e+2]==="="?0:Dn.indexOf(n[e+2]),o=n[e+3]==="="?0:Dn.indexOf(n[e+3]);t.push(i<<2|r>>4),n[e+2]!=="="&&t.push((r&15)<<4|s>>2),n[e+3]!=="="&&t.push((s&3)<<6|o)}return t}var Hn,_i,ad=class{constructor(t){G(this,Hn);b(this,"bytes");b(this,"pos",0);this.bytes=Uint8Array.from(t)}read(t){let e=a(this,Hn,_i).call(this,t);return this.bytes.slice(e,this.pos)}readView(t){let e=a(this,Hn,_i).call(this,t);return this.bytes.subarray(e,this.pos)}readReverse(t){return this.read(t).reverse()}readUInt8(){return this.bytes[a(this,Hn,_i).call(this,1)]}readUInt16LE(){let t=a(this,Hn,_i).call(this,2);return this.bytes[t]|this.bytes[t+1]<<8}readUInt32LE(){let t=a(this,Hn,_i).call(this,4);return(this.bytes[t]|this.bytes[t+1]<<8|this.bytes[t+2]<<16|this.bytes[t+3]<<24)>>>0}readUInt64LE(){let t=a(this,Hn,_i).call(this,8),e=0n;for(let i=7;i>=0;i--)e=e<<8n|BigInt(this.bytes[t+i]);return Number(e)}readVarInt(){let t=this.readUInt8();if(t<253)return t;if(t===253){let r=this.readUInt16LE();if(r<253)throw new Error("non-canonical varInt");return r}if(t===254){let r=this.readUInt32LE();if(r<=65535)throw new Error("non-canonical varInt");return r}let e=a(this,Hn,_i).call(this,8),i=0n;for(let r=7;r>=0;r--)i=i<<8n|BigInt(this.bytes[e+r]);if(i<=0xffffffffn)throw new Error("non-canonical varInt");if(i>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("varInt is too large");return Number(i)}eof(){return this.pos===this.bytes.length}};Hn=new WeakSet,_i=function(t){let e=this.pos;if(!Number.isSafeInteger(t)||t<0||e+t>this.bytes.length)throw new RangeError("Serialized BEEF exceeds available data");return this.pos+=t,e};var Ky=4294967295;function lc(n,t){return Math.floor(n/2**t)}function zy(n){return n%2===0?n+1:n-1}function Or(n,t){return Ye(zt(hs((n??"")+(t??"")).reverse()).reverse())}function cd(n,t,e,i,r,s){let o=`${t}:${e}`;if(r.has(o))return r.get(o);let c=t<i.length?i[t].get(e):void 0;if(c!==void 0||t===0)return r.set(o,c),c;let u=t-1,f=e*2,d=cd(n,u,f,i,r,s);if(d?.hash==null||d.hash===""){r.set(o,void 0);return}let l=cd(n,u,f+1,i,r,s);if(l?.hash==null){if(l?.duplicate===!0||n.length===1&&f===lc(s,u))return c={offset:e,hash:Or(d.hash,d.hash)},r.set(o,c),c;r.set(o,void 0);return}return c={offset:e,hash:l.duplicate===!0?Or(d.hash,d.hash):Or(l.hash,d.hash)},r.set(o,c),c}function Xy(n,t,e,i,r,s){if(typeof t!="string"&&(t=n[0].find(f=>!!f.hash)?.hash),typeof t!="string")throw new TypeError("Transaction ID is undefined");let o=n[0].find(f=>f.hash===t)?.offset;if(o===void 0)throw new Error("Transaction ID not found in Merkle Path");if(n.length===1&&n[0].length===1)return t;let c=Math.max(n.length,32-Math.clz32(s)),u=t;for(let f=0;f<c;f++){let d=lc(o,f),l=`${f}:${d}`,p=r.get(l);if(p!==void 0){if(p!==u)throw new Error("Mismatched roots");let w=r.get(`${c}:0`);if(w===void 0)throw new Error("Mismatched roots");return w}r.set(l,u);let m=zy(d),g=cd(n,f,m,e,i,s);if(g==null){if(n.length===1&&d===lc(s,f)){u=Or(u,u);continue}throw new Error(`Missing hash for index ${o} at height ${f}`)}g.duplicate===!0?u=Or(u,u):u=m%2===1?Or(g.hash,u):Or(u,g.hash)}return r.set(`${c}:0`,u),u}function jy(n){n.readVarInt();let t=n.readUInt8(),e=Array.from({length:t},()=>[]);for(let u=0;u<t;u++){let f=n.readVarInt();for(let d=0;d<f;d++){let l=n.readVarInt(),p=n.readUInt8();e[u].push((p&1)===1?{offset:l,duplicate:!0}:{offset:l,hash:Ye(n.read(32).reverse())})}e[u].sort((d,l)=>d.offset-l.offset)}if(e.length===0||e.length>32||e[0].length===0)throw new Error("Invalid Merkle Path height");for(let u=0;u<e.length;u++){let f=new Set,d=lc(Ky,u);for(let l of e[u]){if(!Number.isSafeInteger(l.offset)||l.offset<0||l.offset>d)throw new Error("Invalid Merkle Path offset");if(f.has(l.offset))throw new Error("Duplicate Merkle Path offset");f.add(l.offset)}}let i=e.map(u=>new Map(u.map(f=>[f.offset,f]))),r=new Map,s=new Map,o=e[0].reduce((u,f)=>Math.max(u,f.offset),0),c;for(let u of e[0]){let f=Xy(e,u.hash,i,r,s,o);if(c===void 0)c=f;else if(c!==f)throw new Error("Mismatched roots")}return new Set(e[0].flatMap(u=>u.hash===void 0?[]:[u.hash]))}function _g(n){let t=n.pos,e=n.readUInt32LE(),i=n.readVarInt(),r=[],s=new Set;for(let l=0;l<i;l++){let p=Ye(n.readReverse(32));s.add(p);let m=n.readUInt32LE(),g=n.readVarInt(),w=n.readView(g),S=n.readUInt32LE();r.push({sourceTXID:p,sourceOutputIndex:m,unlockingScript:w,sequence:S})}let o=n.readVarInt(),c=[];for(let l=0;l<o;l++){let p=n.readUInt64LE(),m=n.readVarInt();c.push({satoshis:p,lockingScript:n.readView(m)})}let u=n.readUInt32LE(),f=n.bytes.subarray(t,n.pos),d=Ye(zt(f).reverse());return{txid:d,transaction:{txid:d,version:e,inputs:r,outputs:c,lockTime:u},inputTxids:Array.from(s),txidOnly:!1}}function Gy(n,t){if(t===4022206466){let r=n.readUInt8();if(r===ze.TXID_ONLY)return{txid:Ye(n.readReverse(32)),inputTxids:[],txidOnly:!0};let s=r===ze.RAWTX_AND_BUMP_INDEX?n.readVarInt():void 0;return{..._g(n),bumpIndex:s}}let e=_g(n),i=n.readUInt8()===0?void 0:n.readVarInt();return{...e,bumpIndex:i}}function Cg(n){let t=new ad(n),e=t.readUInt32LE(),i;if(e===16843009&&(i=Ye(t.readReverse(32)),e=t.readUInt32LE()),e!==4022206465&&e!==4022206466)throw new Error("Invalid BEEF version");let r=t.readVarInt(),s=[];for(let u=0;u<r;u++)s.push(jy(t));let o=t.readVarInt(),c=[];for(let u=0;u<o;u++)c.push(Gy(t,e));if(!t.eof())throw new Error("Serialized BEEF contains trailing data");return{atomicTxid:i,bumps:s,entries:c}}function ps(n){let{atomicTxid:t,entries:e}=Cg(n),i=new Map;for(let r of e){if(i.has(r.txid))throw new Error("BEEF contains duplicate transactions");i.set(r.txid,r.transaction)}for(let r of e)if(r.transaction!==void 0)for(let s of r.transaction.inputs){let c=i.get(s.sourceTXID)?.outputs[s.sourceOutputIndex];c!==void 0&&(s.sourceSatoshis=c.satoshis)}return{atomicTxid:t,transactions:i}}function Fo(n,t=!1){let{atomicTxid:e,bumps:i,entries:r}=Cg(n);if(e===void 0)throw new Error("Atomic BEEF subject is missing");let s=new Map(r.map(f=>[f.txid,f]));if(s.size!==r.length)throw new Error("Atomic BEEF contains duplicate transactions");let o=s.get(e);if(o?.transaction===void 0)throw new Error("Atomic BEEF subject is missing");let c=new Set,u=[o];for(;u.length>0;){let f=u.pop();if(!(c.has(f)||(c.add(f),(f.bumpIndex===void 0?void 0:i[f.bumpIndex])?.has(f.txid)===!0||f.txidOnly)))for(let p of f.inputTxids){let m=s.get(p);if(m===void 0){if(t)continue;throw new Error("Atomic BEEF omits a required dependency")}u.push(m)}}if(c.size!==r.length)throw new Error("Atomic BEEF contains unrelated transaction data");for(let f of o.transaction.inputs){let l=s.get(f.sourceTXID)?.transaction?.outputs[f.sourceOutputIndex];l!==void 0&&(f.sourceSatoshis=l.satoshis)}return o.transaction}var gs=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,Yy=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;function Zy(n,t){let e=1n;for(;t>0n;)(t&1n)!==0n&&(e=e*n%gs),n=n*n%gs,t>>=1n;return e}function hc(n){if(!/^0[23][0-9a-f]{64}$/iu.test(n))return!1;let t=BigInt(`0x${n.slice(2)}`);if(t>=gs)return!1;let e=(t*t*t+7n)%gs,i=Zy(e,gs+1n>>2n);return i*i%gs===e}function Jy(n,t,e){let i=0n;for(let r=t;r<t+e;r++)i=i<<8n|BigInt(n[r]);return i}function ms(n){if(n.length<8||n.length>72||n[0]!==48||n[1]!==n.length-2)return!1;let t=2;for(let e=0;e<2;e++){if(n[t++]!==2)return!1;let i=n[t++];if(i<1||i>33||t+i>n.length)return!1;let r=n[t];if((r&128)!==0||i>1&&r===0&&(n[t+1]&128)===0)return!1;let s=Jy(n,t,i);if(s===0n||s>=Yy)return!1;t+=i}return t===n.length}var Ci=4294967295,ud=1e5,xn=1e3,Lg=100,Ug=32,Mg=new Bi,Dg=new Bi;function yt(n,t){throw new ut(n,t)}function gt(n,t){if(n==null||typeof n!="object"||Array.isArray(n))return yt(t,"a plain object");let e=Object.getPrototypeOf(n);if(e!==null&&e!==Object.prototype)return yt(t,"a plain object");let i=Reflect.ownKeys(n);if(i.length>ud)return yt(t,`an object with at most ${ud} properties`);for(let r of i){if(typeof r!="string"||gn(r))return yt(t,"an object with safe string keys");let s=Object.getOwnPropertyDescriptor(n,r);if(s==null||!("value"in s))return yt(`${t}.${r}`,"a data property")}return n}function Ne(n,t,e=ud){if(n===void 0)return[];if(!Array.isArray(n))return yt(t,"an array");if(e!==void 0&&n.length>e)return yt(t,`an array of at most ${e} items`);let i=Object.getOwnPropertyDescriptors(n),r=new Set(["length",...Array.from({length:n.length},(s,o)=>String(o))]);if(Object.getOwnPropertySymbols(n).length!==0||Object.keys(i).length!==r.size||Object.keys(i).some(s=>!r.has(s))||Object.values(i).some(s=>s.get!=null||s.set!=null))return yt(t,"an accessor-free dense array without extra properties");for(let s=0;s<n.length;s++)if(!Object.prototype.hasOwnProperty.call(n,s))return yt(t,"a dense array");return n}function $g(n){let t=Ne(n,"sendWith",xn).map((e,i)=>Ui(e,`sendWith[${i}]`,64,64));return new Set(t).size!==t.length?yt("sendWith","unique transaction IDs"):t}function $n(n,t,e,i=268435456){if(n instanceof Uint8Array)return n.length>i?yt(t,`at most ${i} bytes`):e!==void 0&&n.length!==e?yt(t,`exactly ${e} bytes`):n;if(!Array.isArray(n))return yt(t,"an array of bytes");if(n.length>i)return yt(t,`at most ${i} bytes`);for(let r=0;r<n.length;r++)if(!Object.prototype.hasOwnProperty.call(n,r)||!Number.isInteger(n[r])||n[r]<0||n[r]>255)return yt(t,"a dense array of bytes");return e!==void 0&&n.length!==e?yt(t,`exactly ${e} bytes`):n}function ws(n,t,e){return n===void 0?e:typeof n!="boolean"?yt(t,"a boolean"):n}function He(n,t){let e=Ui(n,t,66,66);return hc(e)?e:yt(t,"a valid compressed secp256k1 public key")}function fd(n,t){return n==="self"||n==="anyone"?n:He(n,t)}function dd(n,t="protocolID"){if(!Array.isArray(n)||n.length!==2)return yt(t,"a [securityLevel, protocolName] tuple");let e=ee(n[0],`${t}[0]`,void 0,0,2),i=ae(n[1],`${t}[1]`,5,400);return[e,i]}function Li(n,t=!0){let e=ws(n.privileged,"privileged",!1),i=Rr(n.privilegedReason,"privilegedReason",5,50);e&&i===void 0&&yt("privilegedReason","a value when 'privileged' is true"),t&&ws(n.seekPermission,"seekPermission",!0)}function Pr(n,t="args"){let e=gt(n,t);dd(e.protocolID),ae(e.keyID,"keyID",1,800),e.counterparty!==void 0&&fd(e.counterparty,"counterparty"),Li(e)}function qg(n){let t=yc(n,"outpoint"),[e,i]=t.split(".");return{txid:e,vout:Number(i)}}function ni(n,t="value"){return ws(n,t,!0)}function be(n,t="value"){return ws(n,t,!1)}function Rr(n,t,e,i){if(n!==void 0)return ae(n,t,e,i)}function Qy(n,t,e){if(n===void 0||!Number.isSafeInteger(n)||n<0||n>21e14)throw new ut(t,"a valid number of satoshis");if(e!==void 0&&n<e)throw new ut(t,`at least ${e} satoshis.`);return n}function ee(n,t,e,i,r){if(n===void 0){if(e!==void 0)return e;throw new ut(t,"a valid integer")}if(!Number.isSafeInteger(n))throw new ut(t,"a safe integer");if(n=Number(n),i!==void 0&&n<i)throw new ut(t,`at least ${i} length.`);if(r!==void 0&&n>r)throw new ut(t,`no more than ${r} length.`);return n}function tx(n,t){return ee(n,t,0,0)}function ae(n,t,e,i){if(typeof n!="string")throw new ut(t,"a string");let r=Se(n).length;if(e!==void 0&&r<e)throw new ut(t,`at least ${e} length.`);if(i!==void 0&&r>i)throw new ut(t,`no more than ${i} length.`);return n}function ex(n){if(n!==void 0)return pc(n)}function pc(n){return pd(n,"basket",1,300)}function ld(n){return pd(n,"label",1,300)}function hd(n){return pd(n,"tag",1,300)}function pd(n,t,e,i){if(typeof n!="string")throw new ut(t,"a string");n=n.trim().toLowerCase();let r=Se(n).length;if(e!==void 0&&r<e)throw new ut(t,`at least ${e} length.`);if(i!==void 0&&r>i)throw new ut(t,`no more than ${i} length.`);return n}function Hg(n,t,e,i){if(n!==void 0)return on(n,t,e,i)}function bs(n){throw new ut(n,"valid base64 string")}function nx(n,t){let e=0;for(let i=0;i<n.length;i++){let r=n.codePointAt(i)??0,s=r>=65&&r<=90||r>=97&&r<=122,o=r>=48&&r<=57;s||o||r===43||r===47||((r!==61||i<n.length-2)&&bs(t),e++)}return e}function ix(n,t,e){t>2&&bs(e),t>0&&n.length%4!==0&&bs(e);let i=n.length%4;i!==0&&i!==4-t&&bs(e)}function rx(n,t,e,i){if(e!==void 0&&n<e)throw new ut(t,`at least ${e} bytes`);if(i!==void 0&&n>i)throw new ut(t,`no more than ${i} bytes`)}function on(n,t,e,i){typeof n!="string"&&bs(t),n=n.trim(),n.length===0&&bs(t);let r=nx(n,t);ix(n,r,t);let s=n.length-r,o=Math.floor(s*3/4);return rx(o,t,e,i),n}function sx(n,t,e,i){if(n!==void 0)return Ui(n,t,e,i)}var ox=/^[0-9a-f]+$/,ax=/^[0-9A-Fa-f]+$/;function Ui(n,t,e,i){if(typeof n!="string")throw new ut(t,"a hexadecimal string");if(n=n.trim(),n.length%2===1)throw new ut(t,`even length, not ${n.length}.`);let r=ox.test(n);if(!r&&!ax.test(n))throw new ut(t,"hexadecimal string.");if(e!==void 0&&n.length<e)throw new ut(t,`at least ${e} length.`);if(i!==void 0&&n.length>i)throw new ut(t,`no more than ${i} length.`);return r?n:n.toLowerCase()}function Fg(n,t){let e=Ui(n,t);return ms(hs(e))?e:yt(t,"a canonical DER-encoded ECDSA signature")}function cx(n){if(gt(n,"input"),n.unlockingScript===void 0&&n.unlockingScriptLength===void 0)throw new ut("unlockingScript, unlockingScriptLength","at least one valid value.");let t=sx(n.unlockingScript,"unlockingScript"),e=n.unlockingScriptLength??(t==null?0:t.length/2);if(ee(e,"unlockingScriptLength",void 0,0),t&&e!==t.length/2)throw new ut("unlockingScriptLength","length unlockingScript if both valid.");return{outpoint:qg(n.outpoint),inputDescription:ae(n.inputDescription,"inputDescription",5,2e3),unlockingScript:t,unlockingScriptLength:e,sequenceNumber:ee(n.sequenceNumber,"sequenceNumber",Ci,0,Ci)}}function ux(n){return gt(n,"output"),{lockingScript:Ui(n.lockingScript,"lockingScript"),satoshis:Qy(n.satoshis,"satoshis"),outputDescription:ae(n.outputDescription,"outputDescription",5,2e3),basket:ex(n.basket),customInstructions:Rr(n.customInstructions,"customInstructions"),tags:Ne(n.tags,"tags").map(e=>hd(e))}}function fx(n){n!==void 0&&gt(n,"options");let t=n??{};return t.trustSelf!==void 0&&t.trustSelf!=="known"&&yt("trustSelf","undefined or 'known'"),{signAndProcess:ni(t.signAndProcess,"signAndProcess"),acceptDelayedBroadcast:ni(t.acceptDelayedBroadcast,"acceptDelayedBroadcast"),trustSelf:t.trustSelf,knownTxids:Ne(t.knownTxids,"knownTxids").map(i=>Ui(i,"knownTxids",64,64)),returnTXIDOnly:be(t.returnTXIDOnly,"returnTXIDOnly"),noSend:be(t.noSend,"noSend"),noSendChange:Ne(t.noSendChange,"noSendChange").map(i=>qg(i)),sendWith:$g(t.sendWith),randomizeOutputs:ni(t.randomizeOutputs,"randomizeOutputs")}}function gc(n,t){gt(n,"args");let e={description:ae(n.description,"description",5,2e3),inputBEEF:n.inputBEEF===void 0?void 0:$n(n.inputBEEF,"inputBEEF"),inputs:Ne(n.inputs,"inputs").map(r=>cx(r)),outputs:Ne(n.outputs,"outputs").map(r=>ux(r)),lockTime:ee(n.lockTime,"lockTime",0,0,Ci),version:ee(n.version,"version",1,0,Ci),labels:Ne(n.labels,"labels").map(r=>ld(r)),options:fx(n.options),logger:t,isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!1,isRemixChange:!1,isSignAction:!1,randomVals:void 0,includeAllSourceTransactions:!1,isTestWerrReviewActions:!1};if(e.inputBEEF!==void 0&&Mg.get(e.inputBEEF)!==!0)try{ps(e.inputBEEF),Mg.set(e.inputBEEF,!0)}catch{throw new ut("inputBEEF","a complete, exactly framed BEEF envelope")}let i=new Set;for(let r of e.inputs){let s=`${r.outpoint.txid.toLowerCase()}.${r.outpoint.vout}`;i.has(s)&&yt("inputs","unique input outpoints"),i.add(s)}return e.isTestWerrReviewActions=e.labels.includes(xx),e.isSendWith=e.options.sendWith.length>0,e.isRemixChange=!e.isSendWith&&e.inputs.length===0&&e.outputs.length===0,e.isNewTx=e.isRemixChange||e.inputs.length>0||e.outputs.length>0,e.isNewTx&&e.options.sendWith.length>=xn&&yt("sendWith",`at most ${xn-1} transaction IDs when the new transaction joins the broadcast set`),e.isSignAction=e.isNewTx&&(!e.options.signAndProcess||e.inputs.some(r=>r.unlockingScript===void 0)),e.isDelayed=e.options.acceptDelayedBroadcast,e.isNoSend=e.options.noSend,e}function dx(n){n!==void 0&&gt(n,"options");let t=n??{};return{acceptDelayedBroadcast:ni(t.acceptDelayedBroadcast,"acceptDelayedBroadcast"),returnTXIDOnly:be(t.returnTXIDOnly,"returnTXIDOnly"),noSend:be(t.noSend,"noSend"),sendWith:$g(t.sendWith)}}function mc(n){gt(n,"args");let t=gt(n.spends,"spends"),e=Object.create(null);for(let[r,s]of Object.entries(t)){/^(?:0|[1-9]\d*)$/.test(r)||yt("spends key","a canonical input index");let o=ee(Number(r),"spends key",void 0,0,Ci),c=gt(s,`spends.${r}`);e[o]={unlockingScript:Ui(c.unlockingScript,`spends.${r}.unlockingScript`),sequenceNumber:c.sequenceNumber===void 0?void 0:ee(c.sequenceNumber,`spends.${r}.sequenceNumber`,void 0,0,Ci)}}let i={spends:e,reference:on(n.reference,"reference"),options:dx(n.options),isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!0,isRemixChange:!1,isTestWerrReviewActions:!1};return i.isSendWith=i.options.sendWith.length>0,i.options.sendWith.length>=xn&&yt("sendWith",`at most ${xn-1} transaction IDs when the signed transaction joins the broadcast set`),i.isDelayed=i.options.acceptDelayedBroadcast,i.isNoSend=i.options.noSend,i}function bc(n){return gt(n,"args"),{reference:on(n.reference,"reference")}}function lx(n){return n===void 0?void 0:(gt(n,"paymentRemittance"),{derivationPrefix:on(n.derivationPrefix,"derivationPrefix"),derivationSuffix:on(n.derivationSuffix,"derivationSuffix"),senderIdentityKey:He(n.senderIdentityKey,"senderIdentityKey")})}function hx(n){return n===void 0?void 0:(gt(n,"insertionRemittance"),{basket:pc(n.basket),customInstructions:Rr(n.customInstructions,"customInstructions",0,1e3),tags:Ne(n.tags,"tags").map(e=>hd(e))})}function px(n){if(gt(n,"output"),n.protocol!=="basket insertion"&&n.protocol!=="wallet payment")throw new ut("protocol","'basket insertion' or 'wallet payment'");return n.protocol==="wallet payment"?(n.paymentRemittance===void 0||n.insertionRemittance!==void 0)&&yt("output remittance","only paymentRemittance for wallet payment"):(n.insertionRemittance===void 0||n.paymentRemittance!==void 0)&&yt("output remittance","only insertionRemittance for basket insertion"),{outputIndex:tx(n.outputIndex,"outputIndex"),protocol:n.protocol,paymentRemittance:lx(n.paymentRemittance),insertionRemittance:hx(n.insertionRemittance)}}function ii(n){if(n===void 0)return;n=n.trim().toLowerCase(),ae(n,"originator",1,250);let t=n.lastIndexOf(":"),e=n;if(t!==-1){if(n.indexOf(":")!==t)throw new ut("originator","a canonical DNS hostname with an optional port");let r=n.slice(t+1);if(!/^\d{1,5}$/.test(r)||Number(r)>65535)throw new ut("originator","a canonical DNS hostname with an optional port");e=n.slice(0,t)}ae(e,"originator hostname",1,250);let i=e.split(".");for(let r of i)if(ae(r,"originator part",1,63),!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(r))throw new ut("originator","a canonical DNS hostname with an optional port");return e}function wc(n){gt(n,"args");let t={tx:$n(n.tx,"tx"),outputs:Ne(n.outputs,"outputs").map(e=>px(e)),description:ae(n.description,"description",5,2e3),labels:Ne(n.labels,"labels").map(e=>ld(e)),seekPermission:ni(n.seekPermission,"seekPermission")};if(Dg.get(t.tx)!==!0)try{Fo(t.tx),Dg.set(t.tx,!0)}catch{throw new ut("tx","a complete, exactly framed Atomic BEEF transaction")}if(t.outputs.length<1)throw new ut("outputs","at least one output to internalize from the transaction");return t}function gx(n,t){if(n!==void 0)return yc(n,t)}function yc(n,t){if(typeof n!="string")throw new ut(t,"txid as hex string and numeric output index joined with '.'");let e=/^([0-9A-Fa-f]{64})\.(0|[1-9]\d*)$/.exec(n);if(e===null)throw new ut(t,"a 32-byte txid and canonical numeric output index joined with '.'");let i=Ui(e[1],`${t} txid`,64,64),r=ee(Number(e[2]),`${t} vout`,void 0,0,Ci);return`${i}.${r}`}function xc(n){return gt(n,"args"),{basket:pc(n.basket),output:yc(n.output,"output")}}function Sc(n){return gt(n,"args"),{type:on(n.type,"type",32,32),serialNumber:on(n.serialNumber,"serialNumber",32,32),certifier:He(n.certifier,"certifier")}}function Ic(n){return gt(n,"args"),Li(n,!1),{certifiers:Ne(n.certifiers,"certifiers").map(e=>He(e,"certifiers")),types:Ne(n.types,"types").map(e=>on(e,"types",32,32)),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0,0),privileged:be(n.privileged,"privileged"),privilegedReason:Rr(n.privilegedReason,"privilegedReason",5,50),partial:void 0}}function gd(n){let t=gt(n,"fields");for(let e of Object.keys(t))ae(e,"field name",1,50),ae(t[e],`fields.${e}`);return n}function mx(n,t){return n==="certifier"?n:He(n,t)}function bx(n,t){let e=gt(n,t);for(let i of Object.keys(e))ae(i,`${t} field name`,1,50),on(e[i],`${t} field value`);return n}function vc(n){if(gt(n,"args"),Li(n,!1),n.acquisitionProtocol!=="issuance")throw new Error("Only acquire certificate via issuance requests allowed here.");if(n.serialNumber)throw new ut("serialNumber",'valid when acquisitionProtocol is "direct"');if(n.signature)throw new ut("signature",'valid when acquisitionProtocol is "direct"');if(n.revocationOutpoint)throw new ut("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(n.keyringRevealer)throw new ut("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(n.keyringForSubject!=null)throw new ut("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!n.certifierUrl)throw new ut("certifierUrl",'valid when acquisitionProtocol is "issuance"');return{type:on(n.type,"type",32,32),certifier:He(n.certifier,"certifier"),certifierUrl:wx(n.certifierUrl),fields:gd(n.fields),privileged:be(n.privileged,"privileged"),privilegedReason:Rr(n.privilegedReason,"privilegedReason",5,50),subject:""}}function wx(n){let t=ae(n,"certifierUrl",1,2048);if(t!==t.trim())throw new ut("certifierUrl","an exact HTTPS URL without whitespace");let e;try{e=new URL(t)}catch{throw new ut("certifierUrl","an absolute HTTPS URL")}if(e.protocol!=="https:")throw new ut("certifierUrl","an HTTPS URL");if(e.username!==""||e.password!=="")throw new ut("certifierUrl","a URL without credentials");if(e.search!==""||e.hash!=="")throw new ut("certifierUrl","a URL without a query or fragment");let i=e.hostname.toLowerCase();if(i==="localhost"||i.endsWith(".localhost")||i==="[::1]"||/^\d+(?:\.\d+){0,3}$/.test(i)||i.includes(":"))throw new ut("certifierUrl","a public DNS hostname");let r=i.split(".");if(r.length<2||r.some(s=>!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(s)))throw new ut("certifierUrl","a public DNS hostname");return t.replace(/\/+$/,"")}function Ac(n){if(gt(n,"args"),Li(n,!1),n.acquisitionProtocol!=="direct")throw new Error("Only acquire direct certificate requests allowed here.");if(!n.serialNumber)throw new ut("serialNumber",'valid when acquisitionProtocol is "direct"');if(!n.signature)throw new ut("signature",'valid when acquisitionProtocol is "direct"');if(!n.revocationOutpoint)throw new ut("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!n.keyringRevealer)throw new ut("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(n.keyringForSubject==null)throw new ut("keyringForSubject",'valid when acquisitionProtocol is "direct"');return{type:on(n.type,"type",32,32),serialNumber:on(n.serialNumber,"serialNumber",32,32),certifier:He(n.certifier,"certifier"),revocationOutpoint:yc(n.revocationOutpoint,"revocationOutpoint"),fields:gd(n.fields),signature:Fg(n.signature,"signature"),keyringRevealer:mx(n.keyringRevealer,"keyringRevealer"),keyringForSubject:bx(n.keyringForSubject,"keyringForSubject"),privileged:be(n.privileged,"privileged"),privilegedReason:Rr(n.privilegedReason,"privilegedReason",5,50),subject:""}}function Ec(n){gt(n,"args"),gt(n.certificate,"certificate"),Li(n,!1),n.certificate.fields!==void 0&&gd(n.certificate.fields);let t={type:Hg(n.certificate.type,"certificate.type",32,32),serialNumber:Hg(n.certificate.serialNumber,"certificate.serialNumber",32,32),certifier:n.certificate.certifier===void 0?void 0:He(n.certificate.certifier,"certificate.certifier"),subject:n.certificate.subject===void 0?void 0:He(n.certificate.subject,"certificate.subject"),revocationOutpoint:gx(n.certificate.revocationOutpoint,"certificate.revocationOutpoint"),signature:n.certificate.signature===void 0?void 0:Fg(n.certificate.signature,"certificate.signature"),fieldsToReveal:Ne(n.fieldsToReveal,"fieldsToReveal").map(e=>ae(e,`fieldsToReveal ${e}`,1,50)),verifier:He(n.verifier,"verifier"),privileged:be(n.privileged,"privileged"),privilegedReason:Rr(n.privilegedReason,"privilegedReason",5,50)};return t.fieldsToReveal.length>Lg&&yt("fieldsToReveal",`at most ${Lg} fields`),new Set(t.fieldsToReveal).size!==t.fieldsToReveal.length&&yt("fieldsToReveal","unique field names"),t}function kc(n){return gt(n,"args"),{identityKey:He(n.identityKey,"identityKey"),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0,0),seekPermission:ni(n.seekPermission,"seekPermission")}}function yx(n){let t=gt(n,"attributes"),e=Object.keys(t);(e.length<1||e.length>Ug)&&yt("attributes",`an object containing 1-${Ug} fields`);for(let i of e)ae(i,`field name ${i}`,1,50),ae(t[i],`attributes.${i}`,1,500);return n}function Tc(n){return gt(n,"args"),{attributes:yx(n.attributes),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0,0),seekPermission:ni(n.seekPermission,"seekPermission")}}function Oc(n){gt(n,"args");let t;if(n.tagQueryMode===void 0||n.tagQueryMode==="any")t="any";else if(n.tagQueryMode==="all")t="all";else throw new ut("tagQueryMode","undefined, 'any', or 'all'");return n.include!==void 0&&n.include!=="locking scripts"&&n.include!=="entire transactions"&&yt("include","undefined, 'locking scripts', or 'entire transactions'"),{basket:pc(n.basket),tags:Ne(n.tags,"tags").map(i=>hd(i)),tagQueryMode:t,includeLockingScripts:n.include==="locking scripts",includeTransactions:n.include==="entire transactions",includeCustomInstructions:be(n.includeCustomInstructions,"includeCustomInstructions"),includeTags:be(n.includeTags,"includeTags"),includeLabels:be(n.includeLabels,"includeLabels"),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0),seekPermission:ni(n.seekPermission,"seekPermission"),knownTxids:[]}}function Pc(n){gt(n,"args");let t;if(n.labelQueryMode===void 0||n.labelQueryMode==="any")t="any";else if(n.labelQueryMode==="all")t="all";else throw new ut("labelQueryMode","undefined, 'any', or 'all'");return{labels:Ne(n.labels,"labels").map(i=>ld(i)),labelQueryMode:t,includeLabels:be(n.includeLabels,"includeLabels"),includeInputs:be(n.includeInputs,"includeInputs"),includeInputSourceLockingScripts:be(n.includeInputSourceLockingScripts,"includeInputSourceLockingScripts"),includeInputUnlockingScripts:be(n.includeInputUnlockingScripts,"includeInputUnlockingScripts"),includeOutputs:be(n.includeOutputs,"includeOutputs"),includeOutputLockingScripts:be(n.includeOutputLockingScripts,"includeOutputLockingScripts"),limit:ee(n.limit,"limit",10,1,1e4),offset:ee(n.offset,"offset",0,0),seekPermission:ni(n.seekPermission,"seekPermission")}}function Rc(n){let t=gt(n,"args");if(t.identityKey!==void 0&&t.identityKey!==!0&&yt("identityKey","true or undefined"),t.forSelf!==void 0&&ws(t.forSelf,"forSelf",!1),t.identityKey===!0){t.protocolID!==void 0&&dd(t.protocolID),t.keyID!==void 0&&ae(t.keyID,"keyID",1,800),t.counterparty!==void 0&&fd(t.counterparty,"counterparty"),Li(t);return}Pr(n,"args")}function Nc(n){let t=gt(n,"args");He(t.counterparty,"counterparty"),He(t.verifier,"verifier"),Li(t,!1)}function Bc(n){let t=gt(n,"args");fd(t.counterparty,"counterparty"),He(t.verifier,"verifier"),dd(t.protocolID),ae(t.keyID,"keyID",1,800),Li(t,!1)}function _c(n){let t=gt(n,"args");Pr(n),$n(t.plaintext,"plaintext")}function Cc(n){let t=gt(n,"args");Pr(n),$n(t.ciphertext,"ciphertext")}function Lc(n){let t=gt(n,"args");Pr(n),$n(t.data,"data")}function Uc(n){let t=gt(n,"args");Pr(n),$n(t.data,"data"),$n(t.hmac,"hmac",32)}function Wg(n,t,e){let i=n[t]!==void 0,r=n[e]!==void 0;i===r&&yt(`${t}, ${e}`,"exactly one value"),i&&$n(n[t],t),r&&$n(n[e],e,32)}function Mc(n){let t=gt(n,"args");Pr(n),Wg(t,"data","hashToDirectlySign")}function Dc(n){let t=gt(n,"args");Pr(n),Wg(t,"data","hashToDirectlyVerify");let e=$n(t.signature,"signature",void 0,72);ms(e)||yt("signature","a canonical DER-encoded ECDSA signature"),t.forSelf!==void 0&&ws(t.forSelf,"forSelf",!1)}function Hc(n){let t=gt(n,"args");ee(t.height,"height",void 0,1,Ci)}function Mi(n,t="args"){gt(n,t)}var xx="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";var $c;(function(n){n[n.Silent=0]="Silent",n[n.App=1]="App",n[n.Counterparty=2]="Counterparty"})($c||($c={}));var Sx=Object.prototype.hasOwnProperty,Ix=new Set(["BEEF","atomicBEEF","beef","ciphertext","competingBeef","data","encryptedLinkage","encryptedLinkageProof","hashToDirectlySign","hashToDirectlyVerify","hmac","inputBEEF","payload","plaintext","signature","transaction","tx"]);function qc(n){return n==null||typeof n!="object"||typeof ArrayBuffer>"u"?!1:ArrayBuffer.isView(n)&&Object.prototype.toString.call(n)==="[object Uint8Array]"}function Vg(n){return Number.isInteger(n)&&n>=0&&n<=255}function vx(n){return n!=null&&typeof n=="object"&&typeof ArrayBuffer<"u"&&(ArrayBuffer.isView(n)||Object.prototype.toString.call(n)==="[object ArrayBuffer]")}function Ax(n){for(let t=0;t<n.length;t++)if(!Sx.call(n,t)||!Vg(n[t]))return;return n}function Ex(n){if(!(n==null||typeof n!="object"))try{let t=Object.keys(n);if(t.length===0)return;let e=[];for(let i=0;i<t.length;i++){if(t[i]!==String(i))return;let r=n[t[i]];if(!Vg(r))return;e.push(r)}return e}catch{return}}function md(n){if(qc(n))return n;if(!vx(n))return Array.isArray(n)?Ax(n):Ex(n)}function kx(n,t){let e=this==null?void 0:this[n];return qc(e)?Array.from(e):qc(t)?Array.from(t):t}function ys(n,t){let e=JSON.stringify(n,kx,t);if(e===void 0)throw new TypeError("BRC-100 JSON payload is not serializable");return e}function Tx(n,t,e,i){let r=md(e);r!=null?n[t]=r:i(e)}function Fc(n){let t=new WeakSet,e=[n];for(;e.length>0;){let i=e.pop();if(!(i==null||typeof i!="object"||qc(i))&&!t.has(i)){if(t.add(i),Array.isArray(i)){for(let r of i)e.push(r);continue}for(let[r,s]of Object.entries(i))Ix.has(r)?Tx(i,r,s,o=>e.push(o)):e.push(s)}}return n}var Ox=Number,Px=String,Rx=Uint8Array,Nx=URL,Bx=Array.prototype,_x=Array.isArray,Cx=Date.parse,Lx=Number.MAX_SAFE_INTEGER,Ux=Number.isFinite,Kc=Number.isInteger,Br=Number.isSafeInteger,cm=Object.prototype,Mx=Object.prototype.hasOwnProperty,Di=Object.create,zc=Object.defineProperty,um=Object.freeze,ye=Object.getOwnPropertyDescriptor,Xc=Object.getPrototypeOf,In=Object.keys,Cr=Reflect.ownKeys,Dx=RegExp.prototype.exec,Hx=RegExp.prototype.test,fm=String.prototype.split,$x=String.prototype.toLowerCase,qx=String.prototype.trim,vd=String.prototype.replace,Fx=String.prototype.normalize,Wx=String.prototype.indexOf,Vx=String.prototype.slice,Kx=String.prototype.startsWith,zx=RegExp,Kg=ye(URL.prototype,"protocol")?.get,Ad=Xc(Uint8Array.prototype),zg=ye(Ad,"buffer")?.get,Xg=ye(Ad,"length")?.get,jg=ye(Ad,Symbol.toStringTag)?.get,Xx=Uint8Array.prototype.set,Gg=typeof SharedArrayBuffer>"u"?void 0:ye(SharedArrayBuffer.prototype,"byteLength")?.get,Yg=Map,cn=Set,Zg=WeakMap,jx=WeakSet,Gx=Map.prototype.get,Yx=Map.prototype.set,Zx=Map.prototype.has,Jx=Map.prototype.forEach,Qx=Set.prototype.add,t2=Set.prototype.has,e2=ye(Set.prototype,"size").get,n2=WeakMap.prototype.get,i2=WeakMap.prototype.set,r2=WeakSet.prototype.add,s2=WeakSet.prototype.has,Pt=Reflect.apply;function qt(n){return _x(n)}function Sn(n){return Ox(n)}function Be(n){return Px(n)}function jt(n){return Pt($x,n,[])}function Ed(n,t){return Pt(fm,n,[t])}function Ss(n,t){return Pt(Hx,n,[t])}function _r(n,t){return Pt(Dx,n,[t])}function jc(n,t){return Pt(Mx,n,[t])}function zo(n){if(!(zg==null||Xg==null||jg==null))try{return{buffer:Pt(zg,n,[]),length:Pt(Xg,n,[]),tag:Pt(jg,n,[])}}catch{return}}function xd(n){return zo(n)?.tag==="Uint8Array"}function o2(n){if(Gg==null)return!1;try{return Pt(Gg,n,[]),!0}catch{return!1}}function Nr(n,t){return Pt(Gx,n,[t])}function bd(n,t,e){Pt(Yx,n,[t,e])}function a2(n,t){return Pt(Zx,n,[t])}function c2(n,t){Pt(Jx,n,[t])}function Gt(n,t){Pt(Qx,n,[t])}function un(n,t){return Pt(t2,n,[t])}function Gc(n){return Pt(e2,n,[])}function Jg(n,t){return Pt(n2,n,[t])}function Wo(n,t,e){Pt(i2,n,[t,e])}function wd(n,t){Pt(r2,n,[t])}function Qg(n,t){return Pt(s2,n,[t])}var si=new cn;Gt(si,"completed");Gt(si,"unprocessed");Gt(si,"sending");Gt(si,"unproven");Gt(si,"unsigned");Gt(si,"nosend");Gt(si,"nonfinal");Gt(si,"failed");var Jc=new cn;Gt(Jc,"unproven");Gt(Jc,"sending");Gt(Jc,"failed");var xs=1e6,tm=xs+2,u2=16*1024*1024,f2="0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",em=new Bi,kd=Symbol("createActionSourceEvidence"),Xo=Symbol("byteBudgetExceeded"),Vo=new jx,Yc=um(Di(null));function dm(n){if(!qt(n))return;let t=ye(n,"length");if(t==null||!("value"in t)||!Br(t.value)||t.value<0||t.value>xs)throw new Error("Wallet request arrays must have a bounded own length");let e=t.value;if(Cr(n).length!==e+1)throw new Error("Wallet request arrays must contain only dense data properties");let r=[];r.length=e;for(let s=0;s<e;s++){let o=ye(n,Be(s));if(o==null||!("value"in o))throw new Error("Wallet request arrays must contain only dense data properties");r[s]=o.value}return r}function nm(n){let t=At(n);if(t==null)return;let e=Di(null),i=Cr(t);for(let r=0;r<i.length;r++){let s=i[r];if(typeof s!="string")continue;let o=ye(t,s);o!=null&&"value"in o&&(e[s]=o.value)}return e}function Ze(n,t,e=[]){let i=Di(null);for(let r=0;r<t.length;r++){let s=t[r],o=!1;for(let c=0;c<e.length;c++)if(e[c]===s){o=!0;break}i[s]=o?dm(n[s]):n[s]}return i}function lm(n){let t=At(n);if(t==null)return Yc;let e=ye(t,kd)?.value;if(e!=null)return e;let i=t.inputBEEF,r=t.inputs;if(i===void 0||!qt(r)||r.length===0)return Yc;let s=ri(i,"createAction","request.inputBEEF"),o;try{o=ps(s)}catch{L("createAction","request.inputBEEF","an exactly framed BEEF envelope")}let c=Di(null);for(let u=0;u<r.length;u++){let f=r[u],d=At(f);if(d==null||typeof d.outpoint!="string")continue;let l=_r(/^([0-9a-fA-F]{64})\.(0|[1-9]\d*)$/,d.outpoint);if(l==null)continue;let p=Sn(l[2]);if(p>4294967295)continue;let m=jt(l[1]),g=Nr(o.transactions,m)?.outputs[p];g!==void 0&&(c[`${m}.${p}`]=g.satoshis)}return um(c)}function mt(n,t){let e=At(t);if(e==null)return t;let i=At(e.options);switch(n){case"createAction":{let r={inputs:qt(e.inputs)?(()=>{let s=[];s.length=e.inputs.length;for(let o=0;o<e.inputs.length;o++){let c=e.inputs[o],u=At(c);s[o]=u==null?c:Ze(u,["outpoint","unlockingScript","sequenceNumber"])}return s})():e.inputs,outputs:qt(e.outputs)?(()=>{let s=[];s.length=e.outputs.length;for(let o=0;o<e.outputs.length;o++){let c=e.outputs[o],u=At(c);s[o]=u==null?c:Ze(u,["satoshis","lockingScript"])}return s})():e.outputs,version:e.version,lockTime:e.lockTime,options:i==null?{signAndProcess:void 0,returnTXIDOnly:void 0,sendWith:void 0,randomizeOutputs:void 0,knownTxids:void 0}:Ze(i,["signAndProcess","returnTXIDOnly","sendWith","randomizeOutputs","knownTxids"],["sendWith","knownTxids"])};return zc(r,kd,{value:lm(e),writable:!1,configurable:!1,enumerable:!1}),r}case"signAction":{let r=At(e.spends),s=Di(null);if(r!=null){let o=In(r);for(let c=0;c<o.length;c++){let u=o[c],f=r[u],d=At(f);s[u]=d==null?f:Ze(d,["unlockingScript","sequenceNumber"])}}return{spends:s,options:i==null?{returnTXIDOnly:void 0,sendWith:void 0}:Ze(i,["returnTXIDOnly","sendWith"],["sendWith"])}}case"listActions":return Ze(e,["labels","labelQueryMode","includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts","limit"],["labels"]);case"listOutputs":return Ze(e,["basket","tags","tagQueryMode","include","includeCustomInstructions","includeTags","includeLabels","limit"],["tags"]);case"listCertificates":return Ze(e,["limit","certifiers","types"],["certifiers","types"]);case"discoverByIdentityKey":return Ze(e,["limit","identityKey"]);case"discoverByAttributes":{let r=At(e.attributes);return{limit:e.limit,attributes:r==null?e.attributes:{...r}}}case"revealCounterpartyKeyLinkage":return Ze(e,["verifier","counterparty"]);case"revealSpecificKeyLinkage":return Ze(e,["verifier","counterparty","protocolID","keyID"],["protocolID"]);case"acquireCertificate":return{...Ze(e,["acquisitionProtocol","type","certifier","serialNumber","revocationOutpoint","signature"]),fields:nm(e.fields)};case"proveCertificate":return{fieldsToReveal:dm(e.fieldsToReveal),verifier:e.verifier,certificate:(()=>{let r=At(e.certificate);return r==null?e.certificate:{...Ze(r,["type","serialNumber","subject","certifier","revocationOutpoint","signature"]),fields:nm(r.fields)}})()};default:return t}}function L(n,t,e){throw new Error(`Invalid ${n} result ${t}: expected ${e}`)}function hm(n){let t=ye(n,"length");return t!=null&&"value"in t&&Br(t.value)&&t.value>=0?t.value:void 0}function pm(n,t,e,i=e){if(t>e)return;let r=Cr(n);if(r.length!==t+1)return;for(let o=0;o<r.length;o++){let c=r[o];if(c!=="length"&&(typeof c!="string"||!Kc(Sn(c))||Sn(c)<0||Sn(c)>=t||Be(Sn(c))!==c))return}let s=t<=i?[]:void 0;s!==void 0&&(s.length=t);for(let o=0;o<t;o++){let c=ye(n,Be(o));if(c==null||c.enumerable!==!0||!("value"in c)||!Kc(c.value)||c.value<0||c.value>255)return;s!==void 0&&(s[o]=c.value)}return s??Xo}function d2(n,t,e){let i=Xc(n);if(i!==cm&&i!==null)return;let r=Cr(n);if(r.length===0||r.length>t)return;let s=r.length<=e?[]:void 0;s!==void 0&&(s.length=r.length);for(let o=0;o<r.length;o++){let c=r[o];if(c!==Be(o))return;let u=ye(n,c);if(u==null||u.enumerable!==!0||!("value"in u)||!Kc(u.value)||u.value<0||u.value>255)return;s!==void 0&&(s[o]=u.value)}return s??Xo}function l2(n){switch(n){case"BEEF":case"atomicBEEF":case"beef":case"ciphertext":case"competingBeef":case"data":case"encryptedLinkage":case"encryptedLinkageProof":case"hashToDirectlySign":case"hashToDirectlyVerify":case"hmac":case"inputBEEF":case"payload":case"plaintext":case"signature":case"transaction":case"tx":return!0;default:return!1}}function gm(n,t,e){let i=zo(n);i?.tag!=="Uint8Array"&&L(t,"byte array","an intrinsic Uint8Array");let{buffer:r,length:s}=i;o2(r)&&L(t,"byte array","an unshared Uint8Array"),s>268435456&&L(t,"byte array",`at most ${268435456} bytes`),s>e&&L(t,"byte arrays",`at most ${268435456} total bytes`);let o=new Rx(s);try{Pt(Xx,o,[n])}catch{L(t,"byte array","an intrinsic Uint8Array")}return o}function Td(n,t,e=!1){let i=[],r=new Zg,s=new Zg,o=0,c=0,u=(d,l)=>{if(d==null||typeof d!="object")return typeof d=="function"&&L(t,"value","data without functions"),d;if(!qt(d)&&!xd(d)&&e&&l2(l)){let w=Jg(s,d);if(w!==void 0)return w;let S=d2(d,268435456,268435456-c);if(S===Xo&&L(t,"byte arrays",`at most ${268435456} total bytes`),S!==void 0)return o++,o>xs&&L(t,"object graph","a bounded result"),S.length>268435456-c&&L(t,"byte arrays",`at most ${268435456} total bytes`),c+=S.length,wd(Vo,S),Wo(s,d,S),S}let p=Jg(r,d);if(p!==void 0)return p;if(o++,o>xs&&L(t,"object graph","a bounded result"),xd(d)){let w=gm(d,t,268435456-c);return c+=zo(w).length,wd(Vo,w),Wo(r,d,w),w}if(qt(d)){Xc(d)!==Bx&&L(t,"array prototype","the intrinsic Array.prototype");let S=hm(d);S===void 0&&L(t,"array length","an own integer data property");let C=pm(d,S,268435456,268435456-c);if(C===Xo&&L(t,"byte arrays",`at most ${268435456} total bytes`),C!==void 0)return c+=C.length,wd(Vo,C),Wo(r,d,C),C;S>xs&&L(t,"array length",`at most ${xs} entries`);let E=[];return E.length=S,Wo(r,d,E),i[i.length]={source:d,target:E,array:!0},E}let m=Xc(d);m!==null&&m!==cm&&L(t,"object prototype","Object.prototype or null");let g=m===null?Di(null):{};return Wo(r,d,g),i[i.length]={source:d,target:g,array:!1},g},f=u(n);for(;i.length>0;){let d=i[i.length-1];i.length-=1;let l=Cr(d.source);if(d.array){o+=l.length,o>tm&&L(t,"object graph","a bounded result");let p=d.source,m=d.target.length;l.length!==m+1&&L(t,"array shape","a dense standard array without extra properties");for(let g=0;g<l.length;g++){let w=l[g];if(typeof w!="string"&&L(t,"array key","a string"),gn(w)&&L(t,`array key ${w}`,"a safe array key"),w!=="length"){let C=Sn(w);(!Kc(C)||C<0||C>=m||Be(C)!==w)&&L(t,`array key ${w}`,"a canonical in-range array index")}let S=ye(p,w);(S==null||!("value"in S))&&L(t,`array property ${w}`,"a data property"),w!=="length"&&zc(d.target,w,{value:u(S.value),enumerable:S.enumerable,configurable:!0,writable:!0})}continue}o+=l.length,o>tm&&L(t,"object graph","a bounded result");for(let p=0;p<l.length;p++){let m=l[p];typeof m!="string"&&L(t,"object key","a string"),gn(m)&&L(t,`object key ${m}`,"a safe record key");let g=ye(d.source,m);(g==null||!("value"in g))&&L(t,`object property ${m}`,"a data property"),zc(d.target,m,{value:u(g.value,m),enumerable:g.enumerable,configurable:!0,writable:!0})}}return f}function mm(n,t){return Td(n,t)}function bm(n,t){return Td(n,t,!0)}function qe(n,t,e="value"){(n==null||typeof n!="object"||qt(n))&&L(t,e,"an object");let i=Di(null),r=Cr(n);for(let s=0;s<r.length;s++){let o=r[s];typeof o!="string"&&L(t,`${e} key`,"a string");let c=ye(n,o);(c==null||!("value"in c))&&L(t,`${e}.${o}`,"a data property"),i[o]=c.value}return i}function ri(n,t,e,i,r=268435456){let s;if(n!=null&&typeof n=="object"&&xd(n)){let c=Qg(Vo,n)?n:gm(n,t,268435456);zo(c).length<=r&&(s=c)}else if(qt(n)){let c=hm(n);if(c===void 0&&L(t,e,"an own integer array length"),c>r&&L(t,e,`at most ${r} bytes`),Qg(Vo,n))s=n;else{let u=pm(n,c,r);u===Xo&&L(t,e,`at most ${r} bytes`),s=u}}s==null&&L(t,e,"an array of bytes");let o=qt(s)?s.length:zo(s).length;return o>r&&L(t,e,`at most ${r} bytes`),i!==void 0&&o!==i&&L(t,e,`${i} bytes`),s}function we(n,t,e,i=0,r){typeof n!="string"&&L(t,e,"a string");let s=Se(n).length;return(s<i||r!==void 0&&s>r)&&L(t,e,`${i}${r===void 0?"+":`\u2013${r}`} UTF-8 bytes`),n}function $e(n,t,e,i){let r=we(n,t,e);return Ss(/^(?:[0-9a-fA-F]{2})*$/,r)||L(t,e,"an even-length hex string"),i!==void 0&&r.length!==i*2&&L(t,e,`${i} hexadecimal bytes`),r}function jo(n,t,e){let i=$e(n,t,e,33);hc(i)||L(t,e,"a valid compressed secp256k1 public key")}function ne(n,t,e,i=4294967295){return(!Br(n)||n<0||n>i)&&L(t,e,`an integer from 0 to ${i}`),n}function Od(n,t,e,i,r){return(!Br(n)||n<i||n>r)&&L(t,e,`an integer from ${i} to ${r}`),n}function Wc(n,t,e){n[e]!==!0&&L(t,e,"true")}function wm(n,t,e){typeof n[e]!="boolean"&&L(t,e,"a boolean")}function qn(n,t,e){if(n!==void 0)return qt(n)||L(t,e,"an array"),n.length>1e5&&L(t,e,"at most 100000 entries"),n}function Zc(n,t,e,i,r){let s=qn(n,t,e);if(s!=null)for(let o=0;o<s.length;o++)we(s[o],t,`${e}[${o}]`,i,r)}function h2(n,t,e){let i=we(n,t,e,1,64);Ss(/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/,i)||L(t,e,"an ISO timestamp with a timezone");let r=Cx(i);Ux(r)||L(t,e,"a valid ISO timestamp")}function p2(n,t,e,i){let r=we(n,t,e,1,i);try{let s=new Nx(r);if(Kg==null)throw new Error;let o=Pt(Kg,s,[]);if(o!=="https:"&&o!=="http:")throw new Error}catch{L(t,e,"an absolute HTTP(S) URL")}}function g2(n,t){let e=qn(n,t,"sendWithResults");if(e!=null){e.length>xn+1&&L(t,"sendWithResults",`at most ${xn+1} transaction results`);for(let i=0;i<e.length;i++){let r=e[i],s=`sendWithResults[${i}]`,o=qe(r,t,s);$e(o.txid,t,`${s}.txid`,32),un(Jc,o.status)||L(t,`${s}.status`,"a supported status")}}}function ym(n,t,e,i){let r=n.inputs[t];r==null&&L(e,i,"a transaction input");let s=jt($e(r.sourceTXID,e,`${i}.sourceTXID`,32)),o=ne(r.sourceOutputIndex,e,`${i}.sourceOutputIndex`);return`${s}.${o}`}function im(n,t,e,i,r){let s=At(e);if(s==null){Sd(n,t,i,r);return}let o=s.version===void 0?1:ne(s.version,t,"request.version"),c=s.lockTime===void 0?0:ne(s.lockTime,t,"request.lockTime");n.version!==o&&L(t,"tx.version","the requested transaction version"),n.lockTime!==c&&L(t,"tx.lockTime","the requested transaction lock time");let u=new Yg;for(let w=0;w<n.inputs.length;w++){let S=ym(n,w,t,`tx.inputs[${w}]`);a2(u,S)&&L(t,`tx.inputs[${w}]`,"a unique transaction input outpoint"),bd(u,S,w)}let f=s.inputs===void 0?[]:qn(s.inputs,t,"request.inputs"),d=new cn;for(let w=0;w<f.length;w++){let S=f[w],C=`request.inputs[${w}]`,E=qe(S,t,C),A=Is(E.outpoint,t,`${C}.outpoint`),k=`${A.txid}.${A.outputIndex}`;un(d,k)&&L(t,`${C}.outpoint`,"a unique requested input"),Gt(d,k);let B=Nr(u,k);B===void 0&&L(t,"tx.inputs","every requested input exactly once");let _=n.inputs[B],H=E.sequenceNumber===void 0?4294967295:ne(E.sequenceNumber,t,`${C}.sequenceNumber`);if((_.sequence??4294967295)!==H&&L(t,`tx.inputs[${B}].sequence`,"the requested input sequence"),E.unlockingScript!==void 0){let O=jt($e(E.unlockingScript,t,`${C}.unlockingScript`));jt(Ye(_.unlockingScript))!==O&&L(t,`tx.inputs[${B}].unlockingScript`,"the requested unlocking script")}}let l=s.outputs===void 0?[]:qn(s.outputs,t,"request.outputs"),m=At(s.options)?.randomizeOutputs===!1,g=new Yg;for(let w=0;w<n.outputs.length;w++){let S=n.outputs[w],C=ne(S.satoshis,t,`tx.outputs[${w}].satoshis`,21e14);if(l.length>0){let E=`${C}:${jt(Ye(S.lockingScript))}`;bd(g,E,(Nr(g,E)??0)+1)}}for(let w=0;w<l.length;w++){let S=l[w],C=`request.outputs[${w}]`,E=qe(S,t,C),A=ne(E.satoshis,t,`${C}.satoshis`,21e14),k=jt($e(E.lockingScript,t,`${C}.lockingScript`));if(m){let H=n.outputs[w];(H==null||H.satoshis!==A||jt(Ye(H.lockingScript))!==k)&&L(t,`tx.outputs[${w}]`,"the requested output at the requested position");continue}let B=`${A}:${k}`,_=Nr(g,B)??0;_===0&&L(t,"tx.outputs","every requested output with its requested amount and script"),bd(g,B,_-1)}Sd(n,t,i,r)}function Sd(n,t,e=Yc,i=!1){let r=0,s=!1,o=new cn;for(let u=0;u<n.inputs.length;u++){let f=n.inputs[u],d=ym(n,u,t,`tx.inputs[${u}]`);un(o,d)&&L(t,`tx.inputs[${u}]`,"a unique transaction input outpoint"),Gt(o,d);let l=f.sourceSatoshis??e[d];if(l===void 0){i||L(t,`tx.inputs[${u}].sourceSatoshis`,"source transaction evidence for every completed transaction input"),s=!0;continue}r+=ne(l,t,`tx.inputs[${u}].sourceSatoshis`,21e14),(!Br(r)||r>21e14)&&L(t,"tx.inputs","a valid total input value")}let c=0;for(let u=0;u<n.outputs.length;u++){let f=n.outputs[u];c+=ne(f.satoshis,t,`tx.outputs[${u}].satoshis`,21e14),(!Br(c)||c>21e14)&&L(t,"tx.outputs","a valid total output value")}!s&&c>r&&L(t,"tx.outputs","a total value no greater than the transaction inputs")}function m2(n,t,e){let i=At(At(e)?.spends);if(i==null)return;let r=In(i);for(let s=0;s<r.length;s++){let o=r[s],c=i[o],u=`request.spends.${o}`;Ss(/^(?:0|[1-9]\d*)$/,o)||L(t,u,"a canonical input index");let f=Sn(o),d=n.inputs[f];(!Br(f)||d==null)&&L(t,`tx.inputs[${o}]`,"the requested input index");let l=qe(c,t,u),p=jt($e(l.unlockingScript,t,`${u}.unlockingScript`));jt(Ye(d.unlockingScript))!==p&&L(t,`tx.inputs[${f}]`,"the requested unlocking script"),l.sequenceNumber!==void 0&&d.sequence!==ne(l.sequenceNumber,t,`${u}.sequenceNumber`)&&L(t,`tx.inputs[${f}].sequence`,"the requested input sequence")}}function b2(n,t,e){let i=t==="createAction"?lm(e):Yc,r=n.txid===void 0?void 0:$e(n.txid,t,"txid",32),s=n.tx===void 0?void 0:rm(n.tx,t,"tx",r),o=s?.txid;r!==void 0&&o!==void 0&&!an(r,o)&&L(t,"tx","a BEEF transaction matching txid");let c=qn(n.noSendChange,t,"noSendChange");if(c!=null)for(let g=0;g<c.length;g++)Is(c[g],t,`noSendChange[${g}]`);g2(n.sendWithResults,t);let u;if(n.signableTransaction!==void 0){t!=="createAction"&&L(t,"signableTransaction","an absent field"),(n.txid!==void 0||n.tx!==void 0)&&L(t,"signableTransaction","exclusive of txid and tx");let g=qe(n.signableTransaction,t,"signableTransaction");u=rm(g.tx,t,"signableTransaction.tx"),Pd(g.reference,t,"signableTransaction.reference")}let f=At(e);if(f!==void 0&&t==="createAction"){let g=f.inputs===void 0?[]:qn(f.inputs,t,"request.inputs"),w=f.outputs===void 0?[]:qn(f.outputs,t,"request.outputs"),S=At(f.options),C=qt(S?.sendWith)?S.sendWith:[],E=g.length>0||w.length>0||C.length===0,A=!1;for(let B=0;B<g.length;B++)if(At(g[B])?.unlockingScript===void 0){A=!0;break}let k=E&&(S?.signAndProcess===!1||A);E&&k&&u===void 0&&L(t,"signableTransaction","the requested deferred-signing transaction"),E&&!k&&r===void 0&&L(t,"txid","the requested completed transaction"),E&&!k&&u!==void 0&&L(t,"signableTransaction","absent for a completed transaction request")}f!==void 0&&t==="signAction"&&r===void 0&&L(t,"txid","the completed signed transaction"),t==="createAction"?(s!==void 0&&im(s,t,e,i,!1),u!==void 0&&im(u,t,e,i,!0)):s!==void 0&&(m2(s,t,e),Sd(s,t));let d=u?.txid,l=r??d;if(c!=null){l===void 0&&L(t,"noSendChange","associated with a transaction");for(let g=0;g<c.length;g++){let w=c[g];an(Ed(Be(w),".")[0],l)||L(t,`noSendChange[${g}]`,"an outpoint of the returned transaction")}}let p=At(At(e)?.options),m=new cn;if(l!==void 0&&Gt(m,jt(l)),qt(p?.sendWith))for(let g=0;g<p.sendWith.length;g++)Gt(m,jt(Be(p.sendWith[g])));if(qt(n.sendWithResults)){let g=new cn;for(let w=0;w<n.sendWithResults.length;w++){let S=n.sendWithResults[w],C=`sendWithResults[${w}].txid`,E=jt(Be(qe(S,t,`sendWithResults[${w}]`).txid));un(g,E)&&L(t,C,"a unique transaction"),Gt(g,E),Gc(m)>0&&!un(m,E)&&L(t,C,"a submitted or returned transaction")}}n.tx!==void 0&&n.txid===void 0&&L(t,"txid","present with tx"),At(e)!==void 0&&n.txid!==void 0&&n.tx===void 0&&At(At(e)?.options)?.returnTXIDOnly!==!0&&L(t,"tx","transaction evidence unless returnTXIDOnly was explicitly requested"),t==="signAction"&&n.noSendChange!==void 0&&L(t,"noSendChange","an absent field"),n.txid===void 0&&n.signableTransaction===void 0&&(!qt(n.sendWithResults)||n.sendWithResults.length===0)&&L(t,"outcome","a transaction, signable transaction, or batch-send result")}function rm(n,t,e,i){let r=ri(n,t,e),s=i===void 0?em.get(r):void 0;if(s!=null)return s;try{let o=Fo(r);return i===void 0&&em.set(r,o),o}catch{}try{return Fo(r,!0)}catch{}try{let o=ps(r),c=i===void 0?void 0:jt(i),u;c2(o.transactions,(l,p)=>{l!==void 0&&(u=p)});let f=(c!==void 0&&Nr(o.transactions,c)!==void 0?c:void 0)??o.atomicTxid??u,d=f===void 0?void 0:Nr(o.transactions,jt(f));if(d===void 0)throw new Error("BEEF subject transaction is missing");return d}catch{L(t,e,"a complete, exactly framed BEEF transaction")}}function w2(n,t,e){let i=ri(n,t,e);try{return ps(i)}catch{L(t,e,"a complete, exactly framed BEEF envelope")}}function Is(n,t,e){let i=we(n,t,e),r=_r(/^([0-9a-fA-F]{64})\.(0|[1-9]\d*)$/,i);return(r==null||Sn(r[2])>4294967295)&&L(t,e,"a canonical transaction outpoint"),{txid:jt(r[1]),outputIndex:Sn(r[2])}}function Pd(n,t,e){let i=we(n,t,e,1);return Ss(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,i)||L(t,e,"a canonical base64 string"),i}function Vc(n){return n<253?1:n<=65535?3:n<=4294967295?5:9}function Ko(n,t,e,i=!1){let r=qe(n,t,e),s=In(r);for(let o=0;o<s.length;o++){let c=s[o],u=r[c],f=Se(c).length;(f<1||f>50||gn(c))&&L(t,`${e} key`,"a safe 1\u201350 byte field name"),i?Pd(u,t,`${e}.${c}`):we(u,t,`${e}.${c}`)}return r}function Id(n,t,e){let i=qe(n,t,e);try{let r=0,s=["type","serialNumber"];for(let g=0;g<s.length;g++){let w=s[g],S=Pd(i[w],t,`${e}.${w}`),C=dc(S);if(C.length!==32||Bg(C)!==S)throw new Error;r+=C.length}let o=["subject","certifier"];for(let g=0;g<o.length;g++){let w=o[g];jo(i[w],t,`${e}.${w}`),r+=33}let c=we(i.revocationOutpoint,t,`${e}.revocationOutpoint`),u=Ed(c,"."),f=u[1]??"0";if(u.length>2||!Ss(/^[0-9a-fA-F]{64}$/,u[0])||!Ss(/^(?:0|[1-9]\d*)$/,f)||Sn(f)>4294967295)throw new Error;r+=32+Vc(Sn(f));let d=Ko(i.fields,t,`${e}.fields`),l=In(d);for(let g=1;g<l.length;g++){let w=l[g],S=g;for(;S>0&&l[S-1]>w;)l[S]=l[S-1],S--;l[S]=w}r+=Vc(l.length);for(let g=0;g<l.length;g++){let w=l[g],S=Se(w),C=Se(d[w]);r+=Vc(S.length)+S.length+Vc(C.length)+C.length}let p=$e(i.signature,t,`${e}.signature`),m=hs(p);if(!ms(m))throw new Error;if(r+=m.length,r>u2)throw new Error}catch{L(t,e,"a canonical signed wallet certificate")}return i}function At(n){if(n==null||typeof n!="object"||qt(n))return;let t=n,e=Di(null),i=Cr(t);for(let r=0;r<i.length;r++){let s=i[r],o=ye(t,s);if(s===kd){if(o==null||!("value"in o))throw new Error("Wallet result request records must contain only data properties");zc(e,s,{value:o.value,enumerable:!1,configurable:!1,writable:!1});continue}if(typeof s!="string"||gn(s))throw new Error("Wallet result request records must contain only safe string keys");if(o==null||!("value"in o))throw new Error("Wallet result request records must contain only data properties");e[s]=o.value}return e}function an(n,t){return typeof n=="string"&&typeof t=="string"&&jt(n)===jt(t)}function Qc(n){let t=Pt(vd,n,[/\s+/g," "]);return Pt(qx,t,[])}function sm(n){let t=Pt(Fx,n,["NFD"]);return jt(Pt(vd,t,[/\p{Mn}/gu,""]))}function xm(n,t){return Pt(Wx,n,[t])!==-1}function Sm(n,t){let e=Ed(Qc(t)," "),i=Pt(fm,n,[/\r\n?|\n|\u2028|\u2029/]),r=0;for(;r<i.length;){let s=0,o=0;for(;o<e.length;){let c=Pt(vd,e[o],[/[.*+?^${}()|[\]\\]/g,String.raw`\$&`]),u=new zx(c,"gi");u.lastIndex=s;let f=_r(u,i[r]);if(f==null)break;s=f.index+f[0].length,o++}if(o===e.length)return!0;r++}return!1}var y2=" a about above after again against all am an and any are aren't as at be because been before being below between both but by can't cannot could couldn't did didn't do does doesn't doing don't down during each few for from further had hadn't has hasn't have haven't having he he'd he'll he's her here here's hers herself him himself his how how's i i'd i'll i'm i've if in into is isn't it it's its itself let's me more most mustn't my myself no nor not of off on once only or other ought our ours ourselves out over own same shan't she she'd she'll she's should shouldn't so some such than that that's the their theirs them themselves then there there's these they they'd they'll they're they've this those through to too under until up very was wasn't we we'd we'll we're we've were weren't what what's when when's where where's which while who who's whom why why's with won't would wouldn't you you'd you'll you're you've your yours yourself yourselves ";function Im(n){let t=[],e=/(?:[^\p{Dash}\p{Pattern_Syntax}\p{Quotation_Mark}\p{Terminal_Punctuation}\p{White_Space}]|')+/gu,i=_r(e,n);for(;i!=null;)xm(y2,` ${i[0]} `)||(t[t.length]=i[0]),i=_r(e,n);return t}function x2(n,t){let e=0;for(;e<n.length;)if(n[e++]===t)return!0;return!1}function S2(n,t,e,i){let r=Pt(Kx,e,["-"])&&e.length>1;if(i!==void 0){let u=xm(t,i);if(r?u:!u)return-1;if(r)return 0}let s=Im(i??(r?Pt(Vx,e,[1]):e)),o=!1,c=0;for(;c<s.length;){let u=x2(n,s[c++]);if(r&&u)return-1;o=o||u}return o&&!r?1:0}function I2(n,t){let e=sm(n),i=sm(t),r=Im(e),s=/-?"([^"]*)"|[^\s"]+/g,o=!1,c=_r(s,i);for(;c!=null;){let u=S2(r,e,c[0],c[1]);if(u===-1)return!1;u===1&&(o=!0),c=_r(s,i)}return o}function v2(n){return n!=="profilePhoto"&&n!=="icon"}function A2(n,t){if(typeof t!="string")return!1;let e=Qc(t);if(e.length<2)return!1;let i=In(n),r="",s=0;for(;s<i.length;){let o=i[s++];if(!v2(o))continue;let c=n[o];r=r.length>0?`${r} ${c}`:c}return e.length===2?Sm(r,e):I2(r,e)}function E2(n,t,e){return typeof t!="string"?!1:n==="userName"?t===Qc(e):Sm(t,e)}function k2(n,t,e,i){let r=At(i);if(r==null)return;if(jc(r,"any")){A2(e,r.any)||L(n,`${t}.decryptedFields`,"a match for the requested any attribute");return}let s=In(r),o=0,c=0;for(;c<s.length;){let u=s[c++],f=r[u];typeof f!="string"&&L(n,`request.attributes.${u}`,"a string"),Qc(f).length!==0&&(o++,(!jc(e,u)||!E2(u,e[u],f))&&L(n,`${t}.decryptedFields.${u}`,"the requested public attribute"))}o===0&&L(n,`${t}.decryptedFields`,"a usable requested attribute")}function T2(n,t,e,i){let r=Is(n,e,i),s=Is(t,e,`request.${i}`);return r.txid===s.txid&&r.outputIndex===s.outputIndex}function O2(n,t){let e=At(n),i=At(t);if(e==null||i==null)return!1;let r=In(e),s=In(i);if(r.length!==s.length)return!1;for(let o=0;o<s.length;o++){let c=s[o];if(!jc(e,c)||e[c]!==i[c])return!1}return!0}function P2(n,t){let e=At(n),i=At(t);if(e==null||i==null)return!1;let r=In(e),s=In(i);if(r.length!==s.length)return!1;let o=0;for(;o<s.length;){if(!jc(e,s[o]))return!1;o++}return!0}function om(n,t,e,i,r=!0){let s=At(t);if(s==null)return;let o=["type","serialNumber"];for(let u=0;u<o.length;u++){let f=o[u];s[f]!==void 0&&n[f]!==s[f]&&L(e,`${i}.${f}`,`the requested certificate ${f}`)}let c=["subject","certifier","signature"];for(let u=0;u<c.length;u++){let f=c[u];s[f]!==void 0&&!an(n[f],s[f])&&L(e,`${i}.${f}`,`the requested certificate ${f}`)}s.revocationOutpoint!==void 0&&!T2(n.revocationOutpoint,s.revocationOutpoint,e,`${i}.revocationOutpoint`)&&L(e,`${i}.revocationOutpoint`,"the requested certificate revocation outpoint"),s.fields!==void 0&&!(r?O2(n.fields,s.fields):P2(n.fields,s.fields))&&L(e,`${i}.fields`,"the requested certificate fields")}function R2(n,t,e){let i=Rd(n,t,"totalCertificates","certificates",e),r=At(e),s;if(t==="listCertificates"&&qt(r?.certifiers)){s=new cn;for(let c=0;c<r.certifiers.length;c++)Gt(s,jt(Be(r.certifiers[c])))}let o;if(t==="listCertificates"&&qt(r?.types)){o=new cn;for(let c=0;c<r.types.length;c++)Gt(o,Be(r.types[c]))}for(let c=0;c<i.length;c++){let u=i[c],f=`certificates[${c}]`,d=Id(u,t,f);if(s!=null&&Gc(s)>0&&(un(s,jt(Be(d.certifier)))||L(t,`${f}.certifier`,"one of the requested certifiers")),o!=null&&Gc(o)>0&&(un(o,Be(d.type))||L(t,`${f}.type`,"one of the requested types")),t==="discoverByIdentityKey"&&r?.identityKey!==void 0&&!an(d.subject,r.identityKey)&&L(t,`${f}.subject`,"the requested identity key"),d.keyring!==void 0&&Ko(d.keyring,t,`${f}.keyring`,!0),d.verifier!==void 0&&jo(d.verifier,t,`${f}.verifier`),t==="discoverByIdentityKey"||t==="discoverByAttributes"){let l=`${f}.certifierInfo`,p=qe(d.certifierInfo,t,l);we(p.name,t,`${l}.name`,1,100),p2(p.iconUrl,t,`${l}.iconUrl`,500),we(p.description,t,`${l}.description`,5,50),Od(p.trust,t,`${l}.trust`,1,10),Ko(d.publiclyRevealedKeyring,t,`${f}.publiclyRevealedKeyring`,!0);let m=Ko(d.decryptedFields,t,`${f}.decryptedFields`);t==="discoverByAttributes"&&k2(t,f,m,r?.attributes)}}}function Rd(n,t,e,i,r){let s=ne(n[e],t,e,Lx),o=qn(n[i],t,i);o==null&&L(t,i,"an array"),o.length>s&&L(t,e,`at least ${o.length}`);let c=At(r);if(c!=null){let u=c.limit===void 0?10:ne(c.limit,t,"limit",1e4);o.length>u&&L(t,i,`at most the requested limit of ${u}`)}return o}function yd(n,t,e){we(n,t,e,n===""?0:5,2e3)}function N2(n,t,e){let i=Rd(n,t,"totalActions","actions",e),r=At(e),s=[];if(qt(r?.labels))for(let c=0;c<r.labels.length;c++)s[c]=Be(r.labels[c]);let o=r?.labelQueryMode==="all"?"all":"any";for(let c=0;c<i.length;c++){let u=i[c],f=`actions[${c}]`,d=qe(u,t,f);if($e(d.txid,t,`${f}.txid`,32),Od(d.satoshis,t,`${f}.satoshis`,-21e14,21e14),un(si,d.status)||L(t,`${f}.status`,"a supported action status"),typeof d.isOutgoing!="boolean"&&L(t,`${f}.isOutgoing`,"a boolean"),yd(d.description,t,`${f}.description`),Zc(d.labels,t,`${f}.labels`,1,300),r?.includeLabels===!0&&d.labels===void 0&&L(t,`${f}.labels`,"the explicitly requested labels"),s.length>0&&qt(d.labels)){let m=new cn;for(let w=0;w<d.labels.length;w++)Gt(m,d.labels[w]);let g=o==="all";for(let w=0;w<s.length;w++){let S=un(m,s[w]);if(o==="all"&&!S){g=!1;break}if(o==="any"&&S){g=!0;break}}g||L(t,`${f}.labels`,"the requested label query")}ne(d.version,t,`${f}.version`),ne(d.lockTime,t,`${f}.lockTime`);let l=qn(d.inputs,t,`${f}.inputs`);if((r?.includeInputs===!0||r?.includeInputSourceLockingScripts===!0||r?.includeInputUnlockingScripts===!0)&&l===void 0&&L(t,`${f}.inputs`,"the explicitly requested inputs"),l!=null)for(let m=0;m<l.length;m++){let g=l[m],w=`${f}.inputs[${m}]`,S=qe(g,t,w);Is(S.sourceOutpoint,t,`${w}.sourceOutpoint`),ne(S.sourceSatoshis,t,`${w}.sourceSatoshis`,21e14),S.sourceLockingScript!==void 0&&$e(S.sourceLockingScript,t,`${w}.sourceLockingScript`),S.unlockingScript!==void 0&&$e(S.unlockingScript,t,`${w}.unlockingScript`),r?.includeInputSourceLockingScripts===!0&&S.sourceLockingScript===void 0&&L(t,`${w}.sourceLockingScript`,"the explicitly requested source locking script"),r?.includeInputUnlockingScripts===!0&&S.unlockingScript===void 0&&L(t,`${w}.unlockingScript`,"the explicitly requested unlocking script"),yd(S.inputDescription,t,`${w}.inputDescription`),ne(S.sequenceNumber,t,`${w}.sequenceNumber`)}let p=qn(d.outputs,t,`${f}.outputs`);if((r?.includeOutputs===!0||r?.includeOutputLockingScripts===!0)&&p===void 0&&L(t,`${f}.outputs`,"the explicitly requested outputs"),p!=null)for(let m=0;m<p.length;m++){let g=p[m],w=`${f}.outputs[${m}]`,S=qe(g,t,w);ne(S.satoshis,t,`${w}.satoshis`,21e14),S.lockingScript!==void 0&&$e(S.lockingScript,t,`${w}.lockingScript`),r?.includeOutputLockingScripts===!0&&S.lockingScript===void 0&&L(t,`${w}.lockingScript`,"the explicitly requested output locking script"),wm(S,t,"spendable"),S.customInstructions!==void 0&&we(S.customInstructions,t,`${w}.customInstructions`),Zc(S.tags,t,`${w}.tags`,1,300),ne(S.outputIndex,t,`${w}.outputIndex`),yd(S.outputDescription,t,`${w}.outputDescription`),we(S.basket,t,`${w}.basket`,0,300)}}}function B2(n,t,e){let i=Rd(n,t,"totalOutputs","outputs",e),r=n.BEEF===void 0?void 0:w2(n.BEEF,t,"BEEF"),s=At(e),o=[];if(qt(s?.tags))for(let f=0;f<s.tags.length;f++)o[f]=Be(s.tags[f]);let c=s?.tagQueryMode==="all"?"all":"any";i.length>0&&s?.include==="entire transactions"&&r==null&&L(t,"BEEF","the requested complete output transactions");let u=new cn;for(let f=0;f<i.length;f++){let d=i[f],l=`outputs[${f}]`,p=qe(d,t,l),m=Is(p.outpoint,t,`${l}.outpoint`),g=`${m.txid}.${m.outputIndex}`;un(u,g)&&L(t,`${l}.outpoint`,"a unique output in the result page"),Gt(u,g);let w=ne(p.satoshis,t,`${l}.satoshis`,21e14);typeof p.spendable!="boolean"&&L(t,`${l}.spendable`,"a boolean");let S=p.lockingScript===void 0?void 0:$e(p.lockingScript,t,`${l}.lockingScript`);if(s?.include==="locking scripts"&&S===void 0&&L(t,`${l}.lockingScript`,"the requested locking script"),r!=null){let E=Nr(r.transactions,m.txid)?.outputs[m.outputIndex];E==null&&L(t,`${l}.outpoint`,"an output contained in BEEF"),E.satoshis!==w&&L(t,`${l}.satoshis`,"the amount committed by BEEF"),S!==void 0&&jt(Ye(E.lockingScript))!==jt(S)&&L(t,`${l}.lockingScript`,"the script committed by BEEF")}if(p.customInstructions!==void 0&&we(p.customInstructions,t,`${l}.customInstructions`),Zc(p.tags,t,`${l}.tags`,1,300),Zc(p.labels,t,`${l}.labels`,1,300),s?.includeTags===!0&&p.tags===void 0&&L(t,`${l}.tags`,"the explicitly requested output tags"),s?.includeLabels===!0&&p.labels===void 0&&L(t,`${l}.labels`,"the explicitly requested transaction labels"),o.length>0&&qt(p.tags)){let C=new cn;for(let A=0;A<p.tags.length;A++)Gt(C,p.tags[A]);let E=c==="all";for(let A=0;A<o.length;A++){let k=un(C,o[A]);if(c==="all"&&!k){E=!1;break}if(c==="any"&&k){E=!0;break}}E||L(t,`${l}.tags`,"the requested tag query")}}}function am(n,t){let e=["prover","verifier","counterparty"];for(let i=0;i<e.length;i++){let r=e[i];jo(n[r],t,r)}ri(n.encryptedLinkage,t,"encryptedLinkage"),ri(n.encryptedLinkageProof,t,"encryptedLinkageProof")}function Ft(n,t,e){let i=Td(t,n),r=qe(i,n),s=At(e);switch(n){case"createAction":case"signAction":b2(r,n,e);break;case"abortAction":wm(r,n,"aborted");break;case"internalizeAction":Wc(r,n,"accepted");break;case"relinquishOutput":case"relinquishCertificate":Wc(r,n,"relinquished");break;case"verifyHmac":case"verifySignature":Wc(r,n,"valid");break;case"isAuthenticated":case"waitForAuthentication":Wc(r,n,"authenticated");break;case"getPublicKey":jo(r.publicKey,n,"publicKey");break;case"encrypt":ri(r.ciphertext,n,"ciphertext");break;case"decrypt":ri(r.plaintext,n,"plaintext");break;case"createHmac":ri(r.hmac,n,"hmac",32);break;case"createSignature":{let o=ri(r.signature,n,"signature",void 0,72);ms(o)||L(n,"signature","a canonical DER-encoded ECDSA signature");break}case"revealCounterpartyKeyLinkage":am(r,n),h2(r.revelationTime,n,"revelationTime"),s?.verifier!==void 0&&!an(r.verifier,s?.verifier)&&L(n,"verifier","the requested verifier"),s?.counterparty!==void 0&&!an(r.counterparty,s?.counterparty)&&L(n,"counterparty","the requested counterparty");break;case"revealSpecificKeyLinkage":am(r,n),(!qt(r.protocolID)||r.protocolID.length!==2)&&L(n,"protocolID","a [securityLevel, protocolName] tuple"),ne(r.protocolID[0],n,"protocolID[0]",2),we(r.protocolID[1],n,"protocolID[1]",5,400),we(r.keyID,n,"keyID",1,800),ne(r.proofType,n,"proofType",255),s?.verifier!==void 0&&!an(r.verifier,s?.verifier)&&L(n,"verifier","the requested verifier"),s?.counterparty==="self"?an(r.counterparty,r.prover)||L(n,"counterparty","the prover's identity key for counterparty self"):s?.counterparty==="anyone"?an(r.counterparty,f2)||L(n,"counterparty","the canonical anyone public key"):typeof s?.counterparty=="string"&&!an(r.counterparty,s.counterparty)&&L(n,"counterparty","the requested counterparty"),qt(s?.protocolID)&&(r.protocolID[0]!==s.protocolID[0]||r.protocolID[1]!==s.protocolID[1])&&L(n,"protocolID","the requested protocol"),s?.keyID!==void 0&&r.keyID!==s?.keyID&&L(n,"keyID","the requested key ID");break;case"listActions":N2(r,n,e);break;case"listOutputs":B2(r,n,e);break;case"listCertificates":case"discoverByIdentityKey":case"discoverByAttributes":R2(r,n,e);break;case"getHeight":Od(r.height,n,"height",1,4294967295);break;case"getHeaderForHeight":$e(r.header,n,"header",80);break;case"getNetwork":r.network!=="mainnet"&&r.network!=="testnet"&&L(n,"network","mainnet or testnet");break;case"getVersion":we(r.version,n,"version",7,30);break;case"acquireCertificate":Id(r,n,"certificate"),s?.type!==void 0&&r.type!==s?.type&&L(n,"certificate.type","the requested certificate type"),s?.certifier!==void 0&&!an(r.certifier,s?.certifier)&&L(n,"certificate.certifier","the requested certifier"),om(r,s,n,"certificate",s?.acquisitionProtocol!=="issuance");break;case"proveCertificate":{let o=Ko(r.keyringForVerifier,n,"keyringForVerifier",!0),c=qt(s?.fieldsToReveal)?s.fieldsToReveal:[],u=new cn;for(let l=0;l<c.length;l++)Gt(u,Be(c[l]));let f=In(o),d=f.length===Gc(u);for(let l=0;d&&l<f.length;l++)d=un(u,f[l]);d||L(n,"keyringForVerifier","exactly the requested certificate fields")}if(r.certificate!==void 0){let o=Id(r.certificate,n,"certificate");om(o,s?.certificate,n,"certificate")}r.verifier!==void 0&&jo(r.verifier,n,"verifier"),r.verifier!==void 0&&s?.verifier!==void 0&&!an(r.verifier,s?.verifier)&&L(n,"verifier","the requested verifier");break}return i}var Nd;(function(n){n[n.createAction=1]="createAction",n[n.signAction=2]="signAction",n[n.abortAction=3]="abortAction",n[n.listActions=4]="listActions",n[n.internalizeAction=5]="internalizeAction",n[n.listOutputs=6]="listOutputs",n[n.relinquishOutput=7]="relinquishOutput",n[n.getPublicKey=8]="getPublicKey",n[n.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",n[n.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",n[n.encrypt=11]="encrypt",n[n.decrypt=12]="decrypt",n[n.createHmac=13]="createHmac",n[n.verifyHmac=14]="verifyHmac",n[n.createSignature=15]="createSignature",n[n.verifySignature=16]="verifySignature",n[n.acquireCertificate=17]="acquireCertificate",n[n.listCertificates=18]="listCertificates",n[n.proveCertificate=19]="proveCertificate",n[n.relinquishCertificate=20]="relinquishCertificate",n[n.discoverByIdentityKey=21]="discoverByIdentityKey",n[n.discoverByAttributes=22]="discoverByAttributes",n[n.isAuthenticated=23]="isAuthenticated",n[n.waitForAuthentication=24]="waitForAuthentication",n[n.getHeight=25]="getHeight",n[n.getHeaderForHeight=26]="getHeaderForHeight",n[n.getNetwork=27]="getNetwork",n[n.getVersion=28]="getVersion"})(Nd||(Nd={}));var vs=Nd;function xt(n,t){switch(n){case"createAction":gc(t);return;case"signAction":mc(t);return;case"abortAction":bc(t);return;case"listActions":Pc(t);return;case"internalizeAction":wc(t);return;case"listOutputs":Oc(t);return;case"relinquishOutput":xc(t);return;case"getPublicKey":Rc(t);return;case"revealCounterpartyKeyLinkage":Nc(t);return;case"revealSpecificKeyLinkage":Bc(t);return;case"encrypt":_c(t);return;case"decrypt":Cc(t);return;case"createHmac":Lc(t);return;case"verifyHmac":Uc(t);return;case"createSignature":Mc(t);return;case"verifySignature":Dc(t);return;case"acquireCertificate":{let e=t;if(e?.acquisitionProtocol==="direct")Ac(e);else if(e?.acquisitionProtocol==="issuance")vc(e);else throw new ei("acquisitionProtocol","direct or issuance");return}case"listCertificates":Ic(t);return;case"proveCertificate":Ec(t);return;case"relinquishCertificate":Sc(t);return;case"discoverByIdentityKey":kc(t);return;case"discoverByAttributes":Tc(t);return;case"getHeaderForHeight":Hc(t);return;case"isAuthenticated":case"waitForAuthentication":case"getHeight":case"getNetwork":case"getVersion":Mi(t)}}var As=class{constructor(){b(this,"CWI");if(typeof window!="object")throw new TypeError("The window.CWI substrate requires a global window object.");if(typeof window.CWI!="object")throw new TypeError("The window.CWI interface does not appear to be bound to the window object.");let t=window.CWI;this.CWI=new Proxy(t,{get(e,i,r){let s=Reflect.get(e,i,r);return typeof i!="string"||!Object.prototype.hasOwnProperty.call(vs,i)||typeof s!="function"?s:(o,...c)=>(xt(i,o),Reflect.apply(s,e,[o,...c]))}})}async validatedResult(t,e,i){return Ft(t,await e,i)}async createAction(t,e){let i=mt("createAction",t);return await this.validatedResult("createAction",this.CWI.createAction(t,e),i)}async signAction(t,e){let i=mt("signAction",t);return await this.validatedResult("signAction",this.CWI.signAction(t,e),i)}async abortAction(t,e){return await this.validatedResult("abortAction",this.CWI.abortAction(t,e))}async listActions(t,e){let i=mt("listActions",t);return await this.validatedResult("listActions",this.CWI.listActions(t,e),i)}async internalizeAction(t,e){return await this.validatedResult("internalizeAction",this.CWI.internalizeAction(t,e))}async listOutputs(t,e){let i=mt("listOutputs",t);return await this.validatedResult("listOutputs",this.CWI.listOutputs(t,e),i)}async relinquishOutput(t,e){return await this.validatedResult("relinquishOutput",this.CWI.relinquishOutput(t,e))}async getPublicKey(t,e){return await this.validatedResult("getPublicKey",this.CWI.getPublicKey(t,e))}async revealCounterpartyKeyLinkage(t,e){let i=mt("revealCounterpartyKeyLinkage",t);return await this.validatedResult("revealCounterpartyKeyLinkage",this.CWI.revealCounterpartyKeyLinkage(t,e),i)}async revealSpecificKeyLinkage(t,e){let i=mt("revealSpecificKeyLinkage",t);return await this.validatedResult("revealSpecificKeyLinkage",this.CWI.revealSpecificKeyLinkage(t,e),i)}async encrypt(t,e){return await this.validatedResult("encrypt",this.CWI.encrypt(t,e))}async decrypt(t,e){return await this.validatedResult("decrypt",this.CWI.decrypt(t,e))}async createHmac(t,e){return await this.validatedResult("createHmac",this.CWI.createHmac(t,e))}async verifyHmac(t,e){return await this.validatedResult("verifyHmac",this.CWI.verifyHmac(t,e))}async createSignature(t,e){return await this.validatedResult("createSignature",this.CWI.createSignature(t,e))}async verifySignature(t,e){return await this.validatedResult("verifySignature",this.CWI.verifySignature(t,e))}async acquireCertificate(t,e){let i=mt("acquireCertificate",t);return await this.validatedResult("acquireCertificate",this.CWI.acquireCertificate(t,e),i)}async listCertificates(t,e){let i=mt("listCertificates",t);return await this.validatedResult("listCertificates",this.CWI.listCertificates(t,e),i)}async proveCertificate(t,e){let i=mt("proveCertificate",t);return await this.validatedResult("proveCertificate",this.CWI.proveCertificate(t,e),i)}async relinquishCertificate(t,e){return await this.validatedResult("relinquishCertificate",this.CWI.relinquishCertificate(t,e))}async discoverByIdentityKey(t,e){let i=mt("discoverByIdentityKey",t);return await this.validatedResult("discoverByIdentityKey",this.CWI.discoverByIdentityKey(t,e),i)}async discoverByAttributes(t,e){let i=mt("discoverByAttributes",t);return await this.validatedResult("discoverByAttributes",this.CWI.discoverByAttributes(t,e),i)}async isAuthenticated(t,e){return await this.validatedResult("isAuthenticated",this.CWI.isAuthenticated(t,e))}async waitForAuthentication(t,e){return await this.validatedResult("waitForAuthentication",this.CWI.waitForAuthentication(t,e))}async getHeight(t,e){return await this.validatedResult("getHeight",this.CWI.getHeight(t,e))}async getHeaderForHeight(t,e){return await this.validatedResult("getHeaderForHeight",this.CWI.getHeaderForHeight(t,e))}async getNetwork(t,e){return await this.validatedResult("getNetwork",this.CWI.getNetwork(t,e))}async getVersion(t,e){return await this.validatedResult("getVersion",this.CWI.getVersion(t,e))}};var oi=class extends Error{constructor(e,i=1,r){super(e);b(this,"code");b(this,"isError",!0);this.code=i,this.name=this.constructor.name,r!=null&&r!==""?this.stack=r:Error.captureStackTrace(this,this.constructor)}static unknownToJson(e){let i;return e.isError===!0&&String(e.name).startsWith("WERR_")?(i={name:e.name,message:e.message,isError:!0},i.name==="WERR_REVIEW_ACTIONS"?(i.reviewActionResults=e.reviewActionResults,i.sendWithResults=e.sendWithResults,i.txid=e.txid,i.tx=e.tx,i.noSendChange=e.noSendChange,i.code=5):i.name==="WERR_INVALID_PARAMETER"?(i.parameter=e.parameter,i.code=6):i.name==="WERR_INSUFFICIENT_FUNDS"&&(i.totalSatoshisNeeded=e.totalSatoshisNeeded,i.moreSatoshisNeeded=e.moreSatoshisNeeded,i.code=7)):e instanceof Error?i={name:e.constructor.name,message:e.message,isError:!0}:i={name:"WERR_UNKNOWN",message:String(e),isError:!0},ys(i)}},fn;(function(n){n[n.unknownError=1]="unknownError",n[n.unsupportedAction=2]="unsupportedAction",n[n.invalidHmac=3]="invalidHmac",n[n.invalidSignature=4]="invalidSignature",n[n.reviewActions=5]="reviewActions",n[n.invalidParameter=6]="invalidParameter",n[n.insufficientFunds=7]="insufficientFunds",n[n.abortRefused=8]="abortRefused"})(fn||(fn={}));var Es=class{async invokeRaw(t,e,i){throw new Error("This substrate must implement invoke() or invokeRaw().")}async invoke(t,e){xt(t,e);let i=mt(t,e);return await this.invokeRaw(t,e,i)}async createAction(t){return await this.invoke("createAction",t)}async signAction(t){return await this.invoke("signAction",t)}async abortAction(t){return await this.invoke("abortAction",t)}async listActions(t){return await this.invoke("listActions",t)}async internalizeAction(t){return await this.invoke("internalizeAction",t)}async listOutputs(t){return await this.invoke("listOutputs",t)}async relinquishOutput(t){return await this.invoke("relinquishOutput",t)}async getPublicKey(t){return await this.invoke("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.invoke("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.invoke("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.invoke("encrypt",t)}async decrypt(t){return await this.invoke("decrypt",t)}async createHmac(t){return await this.invoke("createHmac",t)}async verifyHmac(t){return await this.invoke("verifyHmac",t)}async createSignature(t){return await this.invoke("createSignature",t)}async verifySignature(t){return await this.invoke("verifySignature",t)}async acquireCertificate(t){return await this.invoke("acquireCertificate",t)}async listCertificates(t){return await this.invoke("listCertificates",t)}async proveCertificate(t){return await this.invoke("proveCertificate",t)}async relinquishCertificate(t){return await this.invoke("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.invoke("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.invoke("discoverByAttributes",t)}async isAuthenticated(t){return await this.invoke("isAuthenticated",t)}async waitForAuthentication(t){return await this.invoke("waitForAuthentication",t)}async getHeight(t){return await this.invoke("getHeight",t)}async getHeaderForHeight(t){return await this.invoke("getHeaderForHeight",t)}async getNetwork(t){return await this.invoke("getNetwork",t)}async getVersion(t){return await this.invoke("getVersion",t)}};var _2=1024,vm=3600*1e3;function C2(n,t){if(typeof n!="object"||n===null)return!1;let e=n;return e.type!=="CWI"||e.isInvocation!==!1||e.id!==t?!1:e.status==="success"?!0:e.status==="error"&&typeof e.description=="string"&&at(e.description,"utf8").length<=4096&&typeof e.code=="number"&&Number.isSafeInteger(e.code)&&e.code>=1&&e.code<=255}var Fn=class extends Es{constructor(e="*",i){super();b(this,"domain");b(this,"responseTimeout");b(this,"pendingInvocations",0);if(typeof globalThis.window!="object")throw new TypeError("The XDM substrate requires a global window object.");if(typeof globalThis.window.postMessage!="function")throw new TypeError("The window object does not seem to support postMessage calls.");if(i!==void 0&&(!Number.isSafeInteger(i)||i<1||i>vm))throw new TypeError(`XDM responseTimeout must be an integer from 1 to ${vm}.`);this.domain=e,this.responseTimeout=i}async invokeRaw(e,i,r){if(this.pendingInvocations>=_2)throw new Error("XDM wallet pending invocation limit reached.");let s=ve(Pe(12));return this.pendingInvocations++,await new Promise((o,c)=>{let u,f=!1,d=!0,l=()=>{if(d&&(d=!1,this.pendingInvocations--,u!==void 0&&clearTimeout(u),f&&typeof window.removeEventListener=="function"))try{window.removeEventListener("message",p)}catch{}},p=m=>{if(!(!m.isTrusted||m.source!==window.parent||this.domain!=="*"&&m.origin!==this.domain||!C2(m.data,s)))if(l(),m.data.status==="error"){let g=m.data.code>=fn.unsupportedAction&&m.data.code<=fn.abortRefused,w=g?m.data.description:"Wallet operation failed",S=new oi(w,g?m.data.code:fn.unknownError);c(S)}else try{o(Ft(e,m.data.result,r))}catch(g){c(g)}};try{window.addEventListener("message",p),f=!0,this.responseTimeout!==void 0&&(u=setTimeout(()=>{l(),c(new Error("XDM wallet response timed out."))},this.responseTimeout)),window.parent.postMessage({type:"CWI",isInvocation:!0,id:s,call:e,args:i},this.domain)}catch(m){l(),c(m)}})}};var eu=16*1024*1024,nu=1e5,iu=1024*1024,Am=72;function Em(n,t,e){let i;try{i=dc(n)}catch{throw new Error(`Invalid certificate ${t}: expected canonical base64`)}return Tm(i,t,e),i}function L2(n){if(n==null||typeof n!="object"||Array.isArray(n))throw new Error("Certificate fields must be a plain object");let t=Object.getPrototypeOf(n);if(t!==Object.prototype&&t!==null)throw new Error("Certificate fields must be a plain object");let e=Reflect.ownKeys(n);if(e.length>nu)throw new Error(`Certificate field count exceeds the maximum of ${nu}`);let i=Object.create(null);for(let r of e){if(typeof r!="string")throw new Error("Certificate fields cannot contain symbol keys");let s=Object.getOwnPropertyDescriptor(n,r);if(s==null||!Object.hasOwn(s,"value")||typeof s.value!="string")throw new Error(`Certificate field ${r} must be an own string data property`);let o=at(r,"utf8");if(Bd(r,o.length),at(s.value,"utf8").length>iu)throw new Error(`Certificate field ${r} exceeds the maximum of ${iu} bytes`);i[r]=s.value}return i}function km(n){let t=n instanceof Uint8Array?Array.from(n):n;if(!Array.isArray(t)||t.length>eu)throw new Error(`Certificate binary must be a byte array of at most ${eu} bytes`);let e=Array.from({length:t.length});for(let i=0;i<t.length;i++){let r=Object.getOwnPropertyDescriptor(t,i);if(r==null||!Object.hasOwn(r,"value")||!Number.isInteger(r.value)||r.value<0||r.value>255)throw new Error("Certificate binary must be a dense byte array");e[i]=r.value}return e}function U2(n,t){if(n.length!==t.length)return!1;let e=0;for(let i=0;i<n.length;i++)e|=n[i]^t[i];return e===0}function Bd(n,t){if(t<1||t>50)throw new Error(`Invalid certificate field name length: expected 1\u201350 bytes, received ${t}`);if(gn(n))throw new Error(`Unsafe certificate field name: ${n}`)}function Tm(n,t,e){if(n.length!==e)throw new Error(`Invalid certificate ${t} length: expected ${e} bytes, received ${n.length}`)}function tu(n,t){Tm(n,t,33);try{Ht.fromDER(n)}catch{throw new Error(`Invalid certificate ${t}: expected a compressed secp256k1 public key`)}}var Lr=class n{constructor(t,e,i,r,s,o,c){b(this,"type");b(this,"serialNumber");b(this,"subject");b(this,"certifier");b(this,"revocationOutpoint");b(this,"fields");b(this,"signature");this.type=t,this.serialNumber=e,this.subject=i,this.certifier=r,this.revocationOutpoint=s,this.fields=o,this.signature=c}toBinary(t=!0){let e=new fe,i=Em(this.type,"type",32);e.write(i);let r=Em(this.serialNumber,"serial number",32);if(e.write(r),!/^(02|03)[0-9a-fA-F]{64}$/.test(this.subject))throw new Error("Invalid certificate subject: expected compressed public key hex");let s=at(this.subject,"hex");if(tu(s,"subject"),e.write(s),!/^(02|03)[0-9a-fA-F]{64}$/.test(this.certifier))throw new Error("Invalid certificate certifier: expected compressed public key hex");let o=at(this.certifier,"hex");if(tu(o,"certifier"),e.write(o),typeof this.revocationOutpoint!="string")throw new Error("Invalid certificate revocation outpoint");let c=this.revocationOutpoint.split("."),[u,f="0"]=c;if(c.length>2||!/^[0-9a-fA-F]{64}$/.test(u)||!/^(?:0|[1-9]\d*)$/.test(f)||Number(f)>4294967295)throw new Error(`Invalid certificate revocation outpoint: ${this.revocationOutpoint}`);let d=at(u,"hex");if(d.length!==32)throw new Error(`Invalid certificate revocation txid length: ${d.length}`);e.write(d),e.writeVarIntNum(Number(f));let l=L2(this.fields),p=Object.keys(l).sort((g,w)=>g.localeCompare(w));e.writeVarIntNum(p.length);for(let g of p){let w=l[g],S=at(g,"utf8");Bd(g,S.length),e.writeVarIntNum(S.length),e.write(S);let C=at(w,"utf8");e.writeVarIntNum(C.length),e.write(C)}if(t&&(this.signature??"").length>0){if(typeof this.signature!="string"||this.signature.length>Am*2||!/^(?:[0-9a-fA-F]{2})+$/.test(this.signature))throw new Error("Invalid certificate signature encoding");let g=at(this.signature,"hex");ge.fromDER(g),e.write(g)}let m=e.toArray();if(m.length>eu)throw new Error(`Certificate binary exceeds the maximum of ${eu} bytes`);return m}static fromBinary(t){let e=new bt(km(t)),i=e.read(32),r=ve(i),s=e.read(32),o=ve(s),c=e.read(33);tu(Array.from(c),"subject");let u=nt(c),f=e.read(33);tu(Array.from(f),"certifier");let d=nt(f),l=e.read(32),p=nt(l),m=e.readVarIntNumStrict(!1),g=`${p}.${m}`,w=e.readVarIntNumStrict(!1);if(w>nu)throw new Error(`Certificate field count exceeds the maximum of ${nu}`);if(w>Math.floor(e.remaining()/3))throw new Error("Certificate field count exceeds the available data");let S=new Map;for(let E=0;E<w;E++){let A=e.readVarIntNumStrict(!1);if(A<1||A>50)throw new Error(`Invalid certificate field name length: received ${A}`);let k=e.read(A),B=Rt(k);if(Bd(B,A),S.has(B))throw new Error(`Duplicate certificate field name: ${B}`);let _=e.readVarIntNumStrict(!1);if(_>iu)throw new Error(`Certificate field ${B} exceeds the maximum of ${iu} bytes`);let H=e.read(_),O=Rt(H);S.set(B,O)}let C;if(!e.eof()){if(e.remaining()>Am)throw new Error("Certificate signature exceeds the DER size limit");let E=e.read();C=ge.fromDER(Array.from(E)).toString("hex")}return new n(r,o,u,d,g,Object.fromEntries(S),C)}async verify(){try{let t=this.toBinary(!1);return Ht.fromString(this.certifier).deriveChild(new T(1),`2-certificate signature-${this.type} ${this.serialNumber}`).verify(t,ge.fromDER(at(this.signature??"","hex")))}catch{return!1}}async sign(t){if(this.signature!=null&&this.signature.length>0)throw new Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await t.getPublicKey({identityKey:!0})).publicKey;let e=this.toBinary(!1),{signature:i}=await t.createSignature({data:e,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});if(!U2(e,this.toBinary(!1)))throw new Error("Certificate changed while its signature was being created");let r=km(i),s=ge.fromDER(r);this.signature=s.toString("hex")}static getCertificateFieldEncryptionDetails(t,e){return{protocolID:[2,"certificate field encryption"],keyID:e?`${e} ${t}`:t}}static fromObject(t){return new n(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,t.signature)}};var M2=1e5,D2={1:"completed",2:"unprocessed",3:"sending",4:"unproven",5:"unsigned",6:"nosend",7:"nonfinal",8:"failed"},v,Nt,Om,Pm,Rm,Nm,Bm,_m,Cm,Lm,ks,ru,Dt,ai,Ur,su,ou,au,_d,Um,Mm,Dm,Hm,ci,Mr,Cd,Hi,Go,Yo,Je,ui,Zo,Jo,$i,$m,Ee,Dr,qi,cu=class cu{constructor(t){G(this,v);b(this,"wire");this.wire=t}async createAction(t,e){xt("createAction",t);let i=mt("createAction",t),r=new ht(void 0,Math.max(256,Math.ceil((t.inputBEEF?.length??0)+(t.inputs??[]).reduce((o,c)=>o+(c.unlockingScript?.length??0)/2,0)+(t.outputs??[]).reduce((o,c)=>o+c.lockingScript.length/2,0)+4096)));if(a(this,v,Ur).call(this,r,t.description),t.inputBEEF==null?r.writeVarIntNum(-1):(r.writeVarIntNum(t.inputBEEF.length),r.write(t.inputBEEF)),t.inputs==null)r.writeVarIntNum(-1);else{r.writeVarIntNum(t.inputs.length);for(let o of t.inputs)a(this,v,Um).call(this,r,o)}if(t.outputs==null)r.writeVarIntNum(-1);else{r.writeVarIntNum(t.outputs.length);for(let o of t.outputs)a(this,v,Mm).call(this,r,o)}a(this,v,ai).call(this,r,t.lockTime),a(this,v,ai).call(this,r,t.version),a(this,v,ou).call(this,r,t.labels),a(this,v,Dm).call(this,r,t.options);let s=await a(this,v,Nt).call(this,"createAction",e,r.toUint8ArrayZeroCopy());return Ft("createAction",a(this,v,Om).call(this,s),i)}async signAction(t,e){xt("signAction",t);let i=mt("signAction",t),r=new ht,s=Object.keys(t.spends);r.writeVarIntNum(s.length);for(let l of s){r.writeVarIntNum(Number(l));let p=t.spends[Number(l)],m=et(p.unlockingScript,"hex");r.writeVarIntNum(m.length),r.write(m),a(this,v,ai).call(this,r,p.sequenceNumber)}let o=et(t.reference,"base64");r.writeVarIntNum(o.length),r.write(o),a(this,v,Hm).call(this,r,t.options);let c=await a(this,v,Nt).call(this,"signAction",e,r.toUint8ArrayZeroCopy()),u=new bt(c),f={};a(this,v,ui).call(this,u,"signAction txid present")&&(f.txid=nt(u.read(32))),a(this,v,ui).call(this,u,"signAction tx present")&&(f.tx=u.readView(u.readVarIntNumStrict(!1)));let d=a(this,v,_d).call(this,u);return d!=null&&(f.sendWithResults=d),a(this,v,Hi).call(this,u,"signAction"),Ft("signAction",f,i)}async abortAction(t,e){xt("abortAction",t);try{let i=await a(this,v,Nt).call(this,"abortAction",e,et(t.reference,"base64"));return a(this,v,qi).call(this,i,"abortAction"),{aborted:!0}}catch(i){if(i instanceof oi&&i.code===fn.abortRefused)return{aborted:!1};throw i}}async listActions(t,e){xt("listActions",t);let i=new ht;i.writeVarIntNum(t.labels.length);for(let u of t.labels)a(this,v,Ur).call(this,i,u);t.labelQueryMode==="any"?i.writeInt8(1):t.labelQueryMode==="all"?i.writeInt8(2):i.writeInt8(-1);for(let u of[t.includeLabels,t.includeInputs,t.includeInputSourceLockingScripts,t.includeInputUnlockingScripts,t.includeOutputs,t.includeOutputLockingScripts])a(this,v,Dt).call(this,i,u);a(this,v,ai).call(this,i,t.limit),a(this,v,ai).call(this,i,t.offset),a(this,v,Dt).call(this,i,t.seekPermission);let r=await a(this,v,Nt).call(this,"listActions",e,i.toUint8Array()),s=new bt(r),o=a(this,v,Ee).call(this,s.readVarIntNumStrict(!1),"listActions totalActions",0,4294967295),c=[];for(;!s.eof();)a(this,v,Yo).call(this,c.length,t.limit,"listActions"),c.push(a(this,v,Nm).call(this,s));return a(this,v,Go).call(this,c.length,o,"listActions"),{totalActions:o,actions:c}}async internalizeAction(t,e){xt("internalizeAction",t);let i=new ht(void 0,Math.max(256,t.tx.length+4096));i.writeVarIntNum(t.tx.length),i.write(t.tx),i.writeVarIntNum(t.outputs.length);for(let o of t.outputs)a(this,v,Cm).call(this,i,o);a(this,v,ou).call(this,i,typeof t.labels=="object"?t.labels:void 0);let r=et(t.description);i.writeVarIntNum(r.length),i.write(r),a(this,v,Dt).call(this,i,t.seekPermission);let s=await a(this,v,Nt).call(this,"internalizeAction",e,i.toUint8ArrayZeroCopy());return a(this,v,qi).call(this,s,"internalizeAction"),{accepted:!0}}async listOutputs(t,e){xt("listOutputs",t);let i=mt("listOutputs",t),r=new ht;if(a(this,v,Ur).call(this,r,t.basket),typeof t.tags=="object"){r.writeVarIntNum(t.tags.length);for(let l of t.tags)a(this,v,Ur).call(this,r,l)}else r.writeVarIntNum(0);t.tagQueryMode==="all"?r.writeInt8(1):t.tagQueryMode==="any"?r.writeInt8(2):r.writeInt8(-1),t.include==="locking scripts"?r.writeInt8(1):t.include==="entire transactions"?r.writeInt8(2):r.writeInt8(-1),a(this,v,Dt).call(this,r,t.includeCustomInstructions),a(this,v,Dt).call(this,r,t.includeTags),a(this,v,Dt).call(this,r,t.includeLabels),a(this,v,ai).call(this,r,t.limit),a(this,v,ai).call(this,r,t.offset),a(this,v,Dt).call(this,r,t.seekPermission);let s=await a(this,v,Nt).call(this,"listOutputs",e,r.toUint8Array()),o=new bt(s),c=a(this,v,Ee).call(this,o.readVarIntNumStrict(!1),"listOutputs totalOutputs",0,4294967295),u=o.readVarIntNumStrict(),f=u>=0?o.readView(u):void 0,d=[];for(;!o.eof();)a(this,v,Yo).call(this,d.length,t.limit,"listOutputs"),d.push(a(this,v,Lm).call(this,o));return a(this,v,Go).call(this,d.length,c,"listOutputs"),Ft("listOutputs",{totalOutputs:c,BEEF:f,outputs:d},i)}async relinquishOutput(t,e){xt("relinquishOutput",t);let i=new ht,r=et(t.basket,"utf8");i.writeVarIntNum(r.length),i.write(r),i.write(a(this,v,ks).call(this,t.output));let s=await a(this,v,Nt).call(this,"relinquishOutput",e,i.toUint8Array());return a(this,v,qi).call(this,s,"relinquishOutput"),{relinquished:!0}}async getPublicKey(t,e){xt("getPublicKey",t);let i=new ht;i.writeUInt8(t.identityKey?1:0),t.identityKey?i.write(a(this,v,Mr).call(this,t.privileged,t.privilegedReason)):(t.protocolID??(t.protocolID=[$c.Silent,"default"]),t.keyID??(t.keyID=""),i.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),typeof t.forSelf=="boolean"?i.writeInt8(t.forSelf?1:0):i.writeInt8(-1)),a(this,v,Dt).call(this,i,t.seekPermission);let r=await a(this,v,Nt).call(this,"getPublicKey",e,i.toUint8Array());return a(this,v,Dr).call(this,r,33,"getPublicKey"),Ht.fromDER(Array.from(r)),{publicKey:nt(r)}}async revealCounterpartyKeyLinkage(t,e){xt("revealCounterpartyKeyLinkage",t);let i=mt("revealCounterpartyKeyLinkage",t),r=new ht;r.write(a(this,v,Mr).call(this,t.privileged,t.privilegedReason)),r.write(et(t.counterparty,"hex")),r.write(et(t.verifier,"hex"));let s=await a(this,v,Nt).call(this,"revealCounterpartyKeyLinkage",e,r.toUint8Array()),o=new bt(s),c=a(this,v,$i).call(this,o,"revealCounterpartyKeyLinkage prover"),u=a(this,v,$i).call(this,o,"revealCounterpartyKeyLinkage verifier"),f=a(this,v,$i).call(this,o,"revealCounterpartyKeyLinkage counterparty"),d=o.readVarIntNumStrict(!1),l=Rt(o.read(d)),p=o.readVarIntNumStrict(!1),m=o.read(p),g=o.readVarIntNumStrict(!1),w=o.read(g);return a(this,v,Hi).call(this,o,"revealCounterpartyKeyLinkage"),Ft("revealCounterpartyKeyLinkage",{prover:c,verifier:u,counterparty:f,revelationTime:l,encryptedLinkage:Array.from(m),encryptedLinkageProof:Array.from(w)},i)}async revealSpecificKeyLinkage(t,e){xt("revealSpecificKeyLinkage",t);let i=mt("revealSpecificKeyLinkage",t),r=new ht;r.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),r.write(et(t.verifier,"hex"));let s=await a(this,v,Nt).call(this,"revealSpecificKeyLinkage",e,r.toUint8Array()),o=new bt(s),c=a(this,v,$i).call(this,o,"revealSpecificKeyLinkage prover"),u=a(this,v,$i).call(this,o,"revealSpecificKeyLinkage verifier"),f=a(this,v,$i).call(this,o,"revealSpecificKeyLinkage counterparty"),d=a(this,v,$m).call(this,o,"revealSpecificKeyLinkage"),l=o.readVarIntNumStrict(!1),p=Rt(o.read(l)),m=o.readVarIntNumStrict(!1),g=Rt(o.read(m)),w=o.readVarIntNumStrict(!1),S=o.read(w),C=o.readVarIntNumStrict(!1),E=o.read(C),A=o.readUInt8();return a(this,v,Hi).call(this,o,"revealSpecificKeyLinkage"),Ft("revealSpecificKeyLinkage",{prover:c,verifier:u,counterparty:f,protocolID:[d,p],keyID:g,encryptedLinkage:Array.from(S),encryptedLinkageProof:Array.from(E),proofType:A},i)}async encrypt(t,e){xt("encrypt",t);let i=new ht;return i.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.plaintext.length),i.write(t.plaintext),a(this,v,Dt).call(this,i,t.seekPermission),{ciphertext:Array.from(await a(this,v,Nt).call(this,"encrypt",e,i.toUint8Array()))}}async decrypt(t,e){xt("decrypt",t);let i=new ht;return i.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.ciphertext.length),i.write(t.ciphertext),a(this,v,Dt).call(this,i,t.seekPermission),{plaintext:Array.from(await a(this,v,Nt).call(this,"decrypt",e,i.toUint8Array()))}}async createHmac(t,e){xt("createHmac",t);let i=new ht;i.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.data.length),i.write(t.data),a(this,v,Dt).call(this,i,t.seekPermission);let r=await a(this,v,Nt).call(this,"createHmac",e,i.toUint8Array());return a(this,v,Dr).call(this,r,32,"createHmac"),{hmac:Array.from(r)}}async verifyHmac(t,e){xt("verifyHmac",t);let i=new ht;i.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.write(t.hmac),i.writeVarIntNum(t.data.length),i.write(t.data),a(this,v,Dt).call(this,i,t.seekPermission);let r=await a(this,v,Nt).call(this,"verifyHmac",e,i.toUint8Array());return a(this,v,qi).call(this,r,"verifyHmac"),{valid:!0}}async createSignature(t,e){xt("createSignature",t);let i=new ht;return i.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),typeof t.data=="object"?(i.writeUInt8(1),i.writeVarIntNum(t.data.length),i.write(t.data)):(t.hashToDirectlySign??(t.hashToDirectlySign=[]),i.writeUInt8(2),i.write(t.hashToDirectlySign)),a(this,v,Dt).call(this,i,t.seekPermission),Ft("createSignature",{signature:Array.from(await a(this,v,Nt).call(this,"createSignature",e,i.toUint8Array()))},t)}async verifySignature(t,e){xt("verifySignature",t);let i=new ht;i.write(a(this,v,ci).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),typeof t.forSelf=="boolean"?i.writeInt8(t.forSelf?1:0):i.writeInt8(-1),i.writeVarIntNum(t.signature.length),i.write(t.signature),typeof t.data=="object"?(i.writeUInt8(1),i.writeVarIntNum(t.data.length),i.write(t.data)):(i.writeUInt8(2),i.write(t.hashToDirectlyVerify??[])),a(this,v,Dt).call(this,i,t.seekPermission);let r=await a(this,v,Nt).call(this,"verifySignature",e,i.toUint8Array());return a(this,v,qi).call(this,r,"verifySignature"),{valid:!0}}async acquireCertificate(t,e){xt("acquireCertificate",t);let i=mt("acquireCertificate",t),r=new ht;r.write(et(t.type,"base64")),r.write(et(t.certifier,"hex"));let s=Object.entries(t.fields);r.writeVarIntNum(s.length);for(let[u,f]of s){let d=et(u,"utf8"),l=et(f,"utf8");r.writeVarIntNum(d.length),r.write(d),r.writeVarIntNum(l.length),r.write(l)}if(r.write(a(this,v,Mr).call(this,t.privileged,t.privilegedReason)),r.writeUInt8(t.acquisitionProtocol==="direct"?1:2),t.acquisitionProtocol==="direct"){r.write(et(t.serialNumber,"base64")),r.write(a(this,v,ks).call(this,t.revocationOutpoint??""));let u=et(t.signature,"hex");r.writeVarIntNum(u.length),r.write(u);let f=t.keyringRevealer==="certifier"?[11]:et(t.keyringRevealer,"hex");r.write(f);let d=Object.keys(t.keyringForSubject??{});r.writeVarIntNum(d.length);for(let l of d){let p=et(l,"utf8");r.writeVarIntNum(p.length),r.write(p);let m=et(t.keyringForSubject?.[l],"base64");r.writeVarIntNum(m.length),r.write(m)}}else{let u=et(t.certifierUrl,"utf8");r.writeVarIntNum(u.length),r.write(u)}let o=await a(this,v,Nt).call(this,"acquireCertificate",e,r.toUint8Array()),c=Lr.fromBinary(o);return Ft("acquireCertificate",{...c,signature:c.signature},i)}async listCertificates(t,e){xt("listCertificates",t);let i=mt("listCertificates",t),r=new ht;r.writeVarIntNum(t.certifiers.length);for(let f of t.certifiers)r.write(et(f,"hex"));r.writeVarIntNum(t.types.length);for(let f of t.types)r.write(et(f,"base64"));typeof t.limit=="number"?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),typeof t.offset=="number"?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),r.write(a(this,v,Mr).call(this,t.privileged,t.privilegedReason));let s=await a(this,v,Nt).call(this,"listCertificates",e,r.toUint8Array()),o=new bt(s),c=a(this,v,Ee).call(this,o.readVarIntNumStrict(!1),"listCertificates totalCertificates",0,4294967295),u=[];for(;!o.eof();){a(this,v,Yo).call(this,u.length,t.limit,"listCertificates");let f=o.readVarIntNumStrict(!1),d=o.read(f),l=Lr.fromBinary(d),p={};if(a(this,v,ui).call(this,o,"listCertificates keyring present")){let w=o.readVarIntNumStrict(!1);a(this,v,Je).call(this,o,w,"listCertificates keyring");for(let S=0;S<w;S++){let C=o.readVarIntNumStrict(!1),E=a(this,v,Zo).call(this,o,C,"listCertificates keyring"),A=o.readVarIntNumStrict(!1);a(this,v,Jo).call(this,p,E,ve(o.read(A)),"listCertificates keyring")}}let m=o.readVarIntNumStrict(!1),g;if(m>0){if(m!==33)throw new Error(`Invalid listCertificates verifier length: expected 33 bytes, received ${m}`);g=a(this,v,$i).call(this,o,"listCertificates verifier")}u.push({...l,signature:l.signature,keyring:p,verifier:g})}return a(this,v,Go).call(this,u.length,c,"listCertificates"),Ft("listCertificates",{totalCertificates:c,certificates:u},i)}async proveCertificate(t,e){xt("proveCertificate",t);let i=mt("proveCertificate",t),r=new ht,s=et(t.certificate.type,"base64");r.write(s);let o=et(t.certificate.subject,"hex");r.write(o);let c=et(t.certificate.serialNumber,"base64");r.write(c);let u=et(t.certificate.certifier,"hex");r.write(u);let f=a(this,v,ks).call(this,t.certificate.revocationOutpoint??"");r.write(f);let d=et(t.certificate.signature,"hex");r.writeVarIntNum(d.length),r.write(d);let l=Object.entries(t.certificate.fields??{});r.writeVarIntNum(l.length);for(let[S,C]of l){let E=et(S,"utf8"),A=et(C,"utf8");r.writeVarIntNum(E.length),r.write(E),r.writeVarIntNum(A.length),r.write(A)}r.writeVarIntNum(t.fieldsToReveal.length);for(let S of t.fieldsToReveal){let C=et(S,"utf8");r.writeVarIntNum(C.length),r.write(C)}r.write(et(t.verifier,"hex")),r.write(a(this,v,Mr).call(this,t.privileged,t.privilegedReason));let p=await a(this,v,Nt).call(this,"proveCertificate",e,r.toUint8Array()),m=new bt(p),g=m.readVarIntNumStrict(!1);a(this,v,Je).call(this,m,g,"proveCertificate keyring");let w={};for(let S=0;S<g;S++){let C=m.readVarIntNumStrict(!1),E=a(this,v,Zo).call(this,m,C,"proveCertificate keyring"),A=m.readVarIntNumStrict(!1);a(this,v,Jo).call(this,w,E,ve(m.read(A)),"proveCertificate keyring")}return a(this,v,Hi).call(this,m,"proveCertificate"),Ft("proveCertificate",{keyringForVerifier:w},i)}async relinquishCertificate(t,e){xt("relinquishCertificate",t);let i=new ht,r=et(t.type,"base64");i.write(r);let s=et(t.serialNumber,"base64");i.write(s);let o=et(t.certifier,"hex");i.write(o);let c=await a(this,v,Nt).call(this,"relinquishCertificate",e,i.toUint8Array());return a(this,v,qi).call(this,c,"relinquishCertificate"),{relinquished:!0}}async discoverByIdentityKey(t,e){xt("discoverByIdentityKey",t);let i=mt("discoverByIdentityKey",t),r=new ht;r.write(et(t.identityKey,"hex")),typeof t.limit=="number"?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),typeof t.offset=="number"?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),a(this,v,Dt).call(this,r,t.seekPermission);let s=await a(this,v,Nt).call(this,"discoverByIdentityKey",e,r.toUint8Array());return Ft("discoverByIdentityKey",a(this,v,Cd).call(this,s,t.limit),i)}async discoverByAttributes(t,e){xt("discoverByAttributes",t);let i=mt("discoverByAttributes",t),r=new ht,s=Object.keys(t.attributes);r.writeVarIntNum(s.length);for(let c of s){let u=et(c,"utf8"),f=et(t.attributes[c],"utf8");r.writeVarIntNum(u.length),r.write(u),r.writeVarIntNum(f.length),r.write(f)}typeof t.limit=="number"?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),typeof t.offset=="number"?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),a(this,v,Dt).call(this,r,t.seekPermission);let o=await a(this,v,Nt).call(this,"discoverByAttributes",e,r.toUint8Array());return Ft("discoverByAttributes",a(this,v,Cd).call(this,o,t.limit),i)}async isAuthenticated(t,e){xt("isAuthenticated",t);let i=await a(this,v,Nt).call(this,"isAuthenticated",e);if(a(this,v,Dr).call(this,i,1,"isAuthenticated"),i[0]!==0&&i[0]!==1)throw new Error("Wallet returned an invalid authentication verdict");return{authenticated:i[0]===1}}async waitForAuthentication(t,e){xt("waitForAuthentication",t);let i=await a(this,v,Nt).call(this,"waitForAuthentication",e);return a(this,v,qi).call(this,i,"waitForAuthentication"),{authenticated:!0}}async getHeight(t,e){xt("getHeight",t);let i=await a(this,v,Nt).call(this,"getHeight",e),r=new bt(i),s=r.readVarIntNumStrict(!1);if(a(this,v,Hi).call(this,r,"getHeight"),s<1||s>4294967295)throw new Error("Wallet returned an invalid height");return{height:s}}async getHeaderForHeight(t,e){if(xt("getHeaderForHeight",t),!Number.isInteger(t.height)||t.height<1||t.height>4294967295)throw new Error("getHeaderForHeight requires a height from 1 to 4294967295");let i=new ht;i.writeVarIntNum(t.height);let r=await a(this,v,Nt).call(this,"getHeaderForHeight",e,i.toUint8Array());return a(this,v,Dr).call(this,r,80,"getHeaderForHeight"),{header:nt(r)}}async getNetwork(t,e){xt("getNetwork",t);let i=await a(this,v,Nt).call(this,"getNetwork",e);if(a(this,v,Dr).call(this,i,1,"getNetwork"),i[0]!==0&&i[0]!==1)throw new Error("Wallet returned an invalid network");return{network:i[0]===0?"mainnet":"testnet"}}async getVersion(t,e){xt("getVersion",t);let i=await a(this,v,Nt).call(this,"getVersion",e);if(i.length<7||i.length>30)throw new Error("Wallet returned an invalid version");return{version:Rt(i)}}};v=new WeakSet,Nt=async function(t,e="",i=[]){let r=e===""?"":ii(e),s=et(r,"utf8"),o=new ht(void 0,2+s.length+i.length);o.writeUInt8(vs[t]),o.writeUInt8(s.length),o.write(s),i.length>0&&o.write(i);let c=o.toUint8ArrayZeroCopy();if(c.length>268435456)throw new Error("Wallet Wire request exceeds the maximum permitted size");let u;if(this.wire.transmitToWalletUint8Array===void 0){let l=await this.wire.transmitToWallet(Array.from(c));if(!Array.isArray(l)||l.length>268435456)throw new Error("Wallet Wire response exceeds the maximum permitted size");for(let p=0;p<l.length;p++)if(!Object.prototype.hasOwnProperty.call(l,p)||!Number.isInteger(l[p])||l[p]<0||l[p]>255)throw new Error("Wallet Wire response must be a dense byte array");u=Uint8Array.from(l)}else{let l=await this.wire.transmitToWalletUint8Array(c);if(!(l instanceof Uint8Array)||l.length>268435456)throw new Error("Wallet Wire response exceeds the maximum permitted size");u=l}let f=new bt(u),d=f.readUInt8();if(d===0)return f.readView();{let l=f.readVarIntNumStrict(!1),p=f.read(l),m=Rt(p),g=f.readVarIntNumStrict(!1),w=f.read(g),S=Rt(w);throw a(this,v,Hi).call(this,f,t),new oi(m,d,S)}},Om=function(t){let e=new bt(t),i={};a(this,v,ui).call(this,e,"createAction txid present")&&(i.txid=nt(e.read(32))),a(this,v,ui).call(this,e,"createAction tx present")&&(i.tx=e.readView(e.readVarIntNumStrict(!1)));let r=e.readVarIntNumStrict();if(r>=0){a(this,v,Je).call(this,e,r,"createAction noSendChange",33),i.noSendChange=[];for(let o=0;o<r;o++)i.noSendChange.push(a(this,v,ru).call(this,e))}let s=a(this,v,_d).call(this,e);if(s!=null&&(i.sendWithResults=s),a(this,v,ui).call(this,e,"createAction signableTransaction present")){let o=e.readView(e.readVarIntNumStrict(!1)),c=e.read(e.readVarIntNumStrict(!1));i.signableTransaction={tx:o,reference:ve(c)}}return a(this,v,Hi).call(this,e,"createAction"),i},Pm=function(t){let e=D2[t];if(e==null)throw new Error(`Unknown status code: ${t}`);return e},Rm=function(t){let e;return t.remaining()>=9&&t.bin[t.pos]===255&&t.bin[t.pos+8]>=128?(t.skip(1),e=t.readInt64LEBn().toNumber()):e=t.readVarIntNumStrict(!1),a(this,v,Ee).call(this,e,"listActions satoshis",-21e14,21e14)},Nm=function(t){let e=nt(t.read(32)),i=a(this,v,Rm).call(this,t),r=a(this,v,Pm).call(this,t.readInt8()),s=a(this,v,ui).call(this,t,"listActions isOutgoing"),o=Rt(t.read(t.readVarIntNumStrict(!1))),c={txid:e,satoshis:i,status:r,isOutgoing:s,description:o,version:0,lockTime:0},u=t.readVarIntNumStrict();if(u>=0){a(this,v,Je).call(this,t,u,"listActions labels"),c.labels=[];for(let l=0;l<u;l++)c.labels.push(Rt(t.read(t.readVarIntNumStrict(!1))))}c.version=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"listActions version",0,4294967295),c.lockTime=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"listActions lockTime",0,4294967295);let f=t.readVarIntNumStrict();if(f>=0){a(this,v,Je).call(this,t,f,"listActions inputs"),c.inputs=[];for(let l=0;l<f;l++)c.inputs.push(a(this,v,Bm).call(this,t))}let d=t.readVarIntNumStrict();if(d>=0){a(this,v,Je).call(this,t,d,"listActions outputs"),c.outputs=[];for(let l=0;l<d;l++)c.outputs.push(a(this,v,_m).call(this,t))}return c},Bm=function(t){let e=a(this,v,ru).call(this,t),i=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"listActions input sourceSatoshis",0,21e14),r=t.readVarIntNumStrict(),s=r>=0?nt(t.read(r)):void 0,o=t.readVarIntNumStrict(),c=o>=0?nt(t.read(o)):void 0,u=Rt(t.read(t.readVarIntNumStrict(!1))),f=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"listActions input sequenceNumber",0,4294967295);return{sourceOutpoint:e,sourceSatoshis:i,sourceLockingScript:s,unlockingScript:c,inputDescription:u,sequenceNumber:f}},_m=function(t){let e=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"listActions output outputIndex",0,4294967295),i=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"listActions output satoshis",0,21e14),r=t.readVarIntNumStrict(),s=r>=0?nt(t.read(r)):void 0,o=a(this,v,ui).call(this,t,"listOutputs spendable"),c=Rt(t.read(t.readVarIntNumStrict(!1))),u=t.readVarIntNumStrict(),f=u>=0?Rt(t.read(u)):void 0,d=t.readVarIntNumStrict(),l=[];if(d>=0){a(this,v,Je).call(this,t,d,"listActions output tags");for(let g=0;g<d;g++)l.push(Rt(t.read(t.readVarIntNumStrict(!1))))}let p=t.readVarIntNumStrict(),m=p>=0?Rt(t.read(p)):void 0;return{outputIndex:e,satoshis:i,lockingScript:s,spendable:o,outputDescription:c,basket:f,tags:l,customInstructions:m}},Cm=function(t,e){if(t.writeVarIntNum(e.outputIndex),e.protocol==="wallet payment"){if(e.paymentRemittance==null)throw new Error("Payment remittance is required for wallet payment");t.writeUInt8(1),t.write(et(e.paymentRemittance.senderIdentityKey,"hex"));let i=et(e.paymentRemittance.derivationPrefix,"base64");t.writeVarIntNum(i.length),t.write(i);let r=et(e.paymentRemittance.derivationSuffix,"base64");t.writeVarIntNum(r.length),t.write(r)}else{t.writeUInt8(2);let i=et(e.insertionRemittance?.basket,"utf8");t.writeVarIntNum(i.length),t.write(i),a(this,v,su).call(this,t,e.insertionRemittance?.customInstructions);let r=e.insertionRemittance?.tags;if(typeof r=="object"){t.writeVarIntNum(r.length);for(let s of r){let o=et(s,"utf8");t.writeVarIntNum(o.length),t.write(o)}}else t.writeVarIntNum(0)}},Lm=function(t){let e=a(this,v,ru).call(this,t),i=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"listOutputs satoshis",0,21e14),r={spendable:!0,outpoint:e,satoshis:i},s=t.readVarIntNumStrict();s>=0&&(r.lockingScript=nt(t.read(s)));let o=t.readVarIntNumStrict();o>=0&&(r.customInstructions=Rt(t.read(o)));let c=t.readVarIntNumStrict();if(c!==-1){a(this,v,Je).call(this,t,c,"listOutputs tags");let f=[];for(let d=0;d<c;d++)f.push(Rt(t.read(t.readVarIntNumStrict(!1))));r.tags=f}let u=t.readVarIntNumStrict();if(u!==-1){a(this,v,Je).call(this,t,u,"listOutputs labels");let f=[];for(let d=0;d<u;d++)f.push(Rt(t.read(t.readVarIntNumStrict(!1))));r.labels=f}return r},ks=function(t){let e=new ht;if(typeof t!="string")throw new Error("Invalid outpoint: expected a string");let i=t.split(".");if(i.length!==2||!/^(?:0|[1-9]\d*)$/.test(i[1]))throw new Error(`Invalid outpoint: ${t}`);let r=et(i[0],"hex");if(r.length!==32)throw new Error("Invalid outpoint txid length");return e.write(r),e.writeVarIntNum(a(this,v,Ee).call(this,Number(i[1]),"outpoint index",0,4294967295)),e.toUint8Array()},ru=function(t){let e=nt(t.read(32)),i=a(this,v,Ee).call(this,t.readVarIntNumStrict(!1),"outpoint index",0,4294967295);return`${e}.${i}`},Dt=function(t,e){t.writeInt8(cu.OPTIONAL_BOOLEAN_WIRE_VALUES.get(e))},ai=function(t,e){typeof e=="number"?t.writeVarIntNum(e):t.writeVarIntNum(-1)},Ur=function(t,e){let i=et(e??"","utf8");t.writeVarIntNum(i.length),t.write(i)},su=function(t,e){if(e!=null&&e!==""){let i=et(e,"utf8");t.writeVarIntNum(i.length),t.write(i)}else t.writeVarIntNum(-1)},ou=function(t,e){if(e==null)t.writeVarIntNum(-1);else{t.writeVarIntNum(e.length);for(let i of e){let r=et(i,"utf8");t.writeVarIntNum(r.length),t.write(r)}}},au=function(t,e){if(e==null)t.writeVarIntNum(-1);else{t.writeVarIntNum(e.length);for(let i of e)t.write(et(i,"hex"))}},_d=function(t){let e=t.readVarIntNumStrict();if(e<0)return;a(this,v,Je).call(this,t,e,"sendWithResults",33,1001);let i=[];for(let r=0;r<e;r++){let s=nt(t.read(32)),o=t.readInt8(),c="unproven";if(o===2)c="sending";else if(o===3)c="failed";else if(o!==1)throw new Error(`Unknown sendWith result status code: ${o}`);i.push({txid:s,status:c})}return i},Um=function(t,e){if(t.write(a(this,v,ks).call(this,e.outpoint)),e.unlockingScript!=null&&e.unlockingScript!==""){let i=et(e.unlockingScript,"hex");t.writeVarIntNum(i.length),t.write(i)}else t.writeVarIntNum(-1),t.writeVarIntNum(e.unlockingScriptLength??0);a(this,v,Ur).call(this,t,e.inputDescription),a(this,v,ai).call(this,t,e.sequenceNumber)},Mm=function(t,e){let i=et(e.lockingScript,"hex");t.writeVarIntNum(i.length),t.write(i),t.writeVarIntNum(e.satoshis),a(this,v,Ur).call(this,t,e.outputDescription),a(this,v,su).call(this,t,e.basket),a(this,v,su).call(this,t,e.customInstructions),a(this,v,ou).call(this,t,e.tags)},Dm=function(t,e){if(e==null){t.writeInt8(0);return}if(t.writeInt8(1),a(this,v,Dt).call(this,t,e.signAndProcess),a(this,v,Dt).call(this,t,e.acceptDelayedBroadcast),t.writeInt8(e.trustSelf==="known"?1:-1),a(this,v,au).call(this,t,e.knownTxids),a(this,v,Dt).call(this,t,e.returnTXIDOnly),a(this,v,Dt).call(this,t,e.noSend),e.noSendChange==null)t.writeVarIntNum(-1);else{t.writeVarIntNum(e.noSendChange.length);for(let i of e.noSendChange)t.write(a(this,v,ks).call(this,i))}a(this,v,au).call(this,t,e.sendWith),a(this,v,Dt).call(this,t,e.randomizeOutputs)},Hm=function(t,e){if(e==null){t.writeInt8(0);return}t.writeInt8(1),a(this,v,Dt).call(this,t,e.acceptDelayedBroadcast),a(this,v,Dt).call(this,t,e.returnTXIDOnly),a(this,v,Dt).call(this,t,e.noSend),a(this,v,au).call(this,t,e.sendWith)},ci=function(t,e,i,r,s){let o=new ht;o.writeUInt8(t[0]);let c=et(t[1],"utf8");o.writeVarIntNum(c.length),o.write(c);let u=et(e,"utf8");return o.writeVarIntNum(u.length),o.write(u),typeof i!="string"?o.writeUInt8(0):i==="self"?o.writeUInt8(11):i==="anyone"?o.writeUInt8(12):o.write(et(i,"hex")),o.write(a(this,v,Mr).call(this,r,s)),o.toUint8Array()},Mr=function(t,e){let i=new ht;if(typeof t=="boolean"?i.writeInt8(t?1:0):i.writeInt8(-1),typeof e=="string"){let r=et(e,"utf8");i.writeInt8(r.length),i.write(r)}else i.writeInt8(-1);return i.toUint8Array()},Cd=function(t,e){let i=new bt(t),r=a(this,v,Ee).call(this,i.readVarIntNumStrict(!1),"discovery totalCertificates",0,4294967295),s=[];for(;!i.eof();){a(this,v,Yo).call(this,s.length,e,"discover");let o=i.readVarIntNumStrict(!1),c=i.read(o),u=Lr.fromBinary(c),f=i.readVarIntNumStrict(!1),d=Rt(i.read(f)),l=i.readVarIntNumStrict(!1),p=Rt(i.read(l)),m=i.readVarIntNumStrict(!1),g=Rt(i.read(m)),w=a(this,v,Ee).call(this,i.readUInt8(),"discovery trust",1,10),S={},C=i.readVarIntNumStrict(!1);a(this,v,Je).call(this,i,C,"discovery public keyring");for(let k=0;k<C;k++){let B=i.readVarIntNumStrict(!1),_=a(this,v,Zo).call(this,i,B,"discovery public keyring"),H=i.readVarIntNumStrict(!1);a(this,v,Jo).call(this,S,_,ve(i.read(H)),"discovery public keyring")}let E={},A=i.readVarIntNumStrict(!1);a(this,v,Je).call(this,i,A,"discovery decrypted fields");for(let k=0;k<A;k++){let B=i.readVarIntNumStrict(!1),_=a(this,v,Zo).call(this,i,B,"discovery decrypted fields"),H=i.readVarIntNumStrict(!1);a(this,v,Jo).call(this,E,_,Rt(i.read(H)),"discovery decrypted fields")}s.push({...u,signature:u.signature,certifierInfo:{iconUrl:p,name:d,description:g,trust:w},publiclyRevealedKeyring:S,decryptedFields:E})}return a(this,v,Go).call(this,s.length,r,"discover"),{totalCertificates:r,certificates:s}},Hi=function(t,e){if(!t.eof())throw new Error(`Wallet Wire ${e} response contains trailing data`)},Go=function(t,e,i){if(t>e)throw new Error(`Wallet Wire ${i} response returned ${t} records but declared a total of ${e}`)},Yo=function(t,e,i){let r=e??10;if(t>=r)throw new Error(`Wallet Wire ${i} response exceeds the requested page limit of ${r}`)},Je=function(t,e,i,r=1,s=M2){if(!Number.isSafeInteger(e)||e<0||e>s)throw new Error(`Wallet Wire ${i} exceeds the maximum collection size of ${s}`);if(e>Math.floor(t.remaining()/r))throw new Error(`Wallet Wire ${i} count exceeds the remaining response data`);return e},ui=function(t,e){let i=t.readInt8();if(i!==0&&i!==1)throw new Error(`Invalid ${e} flag: expected 0 or 1, received ${i}`);return i===1},Zo=function(t,e,i){if(e<1||e>50)throw new Error(`Invalid ${i} key length: expected 1\u201350 bytes, received ${e}`);let r=Rt(t.read(e));if(gn(r))throw new Error(`Unsafe ${i} key: ${r}`);return r},Jo=function(t,e,i,r){if(Object.prototype.hasOwnProperty.call(t,e))throw new Error(`Duplicate ${r} key: ${e}`);t[e]=i},$i=function(t,e){let i=t.read(33);return Ht.fromDER(Array.from(i)),nt(i)},$m=function(t,e){let i=t.readUInt8();if(i!==0&&i!==1&&i!==2)throw new Error(`Invalid ${e} security level: ${i}`);return i},Ee=function(t,e,i,r){if(!Number.isSafeInteger(t)||t<i||t>r)throw new Error(`Invalid ${e}: expected an integer from ${i} to ${r}, received ${String(t)}`);return t},Dr=function(t,e,i){if(t.length!==e)throw new Error(`Wallet Wire ${i} response has an invalid length`)},qi=function(t,e){a(this,v,Dr).call(this,t,0,e)},b(cu,"OPTIONAL_BOOLEAN_WIRE_VALUES",new Map([[!0,1],[!1,0],[void 0,-1]]));var Ts=cu;function qm(n,t="http"){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(n))try{return new URL(n).origin}catch{}try{return new URL(`${t}://${n}`).origin}catch{throw new Error(`Invalid originator value: ${n}`)}}function Os(n){if(typeof n!="string"||n.length<1||n.length>2048||n!==n.trim())throw new TypeError("Wallet HTTP baseUrl must be an exact HTTP(S) origin.");let t;try{t=new URL(n)}catch{throw new TypeError("Wallet HTTP baseUrl must be an exact HTTP(S) origin.")}if(t.protocol!=="https:"&&t.protocol!=="http:"||t.username!==""||t.password!==""||t.pathname!=="/"||t.search!==""||t.hash!==""||t.origin==="null")throw new TypeError("Wallet HTTP baseUrl must be an HTTP(S) origin without credentials, path, query, or fragment.");if(t.protocol==="http:"&&!H2(t.hostname))throw new TypeError("Wallet HTTP baseUrl may use cleartext HTTP only for a loopback host.");return t.origin}function H2(n){let t=n.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="[::1]"}var Ps=class{constructor(t,e="http://localhost:3301",i){b(this,"baseUrl");b(this,"httpClient");b(this,"originator");let r=ii(t);this.baseUrl=Os(e),this.httpClient=i??globalThis.fetch.bind(globalThis),this.originator=r}async transmitToWallet(t){return Array.from(await this.transmitToWalletUint8Array(Uint8Array.from(t)))}async transmitToWalletUint8Array(t){if(!(t instanceof Uint8Array)||t.length>268435456)throw new Error("HTTPWalletWire request exceeds the maximum permitted size");let e=new bt(t),i=e.readUInt8(),r=vs[i];if(r===void 0||r==="")throw new Error(`Invalid call code: ${i}`);let s=e.readUInt8();if(s>250)throw new Error(`Invalid originator length: expected at most 250 bytes, received ${s}`);let o;if(s>0){let d=e.read(s);o=ii(Rt(d))}if(this.originator!==void 0&&o!==this.originator)throw new Error("Wallet Wire frame originator does not match the configured originator");let c=e.readView(),u=Os(this.baseUrl),f=await this.httpClient(`${u}/${r}`,{method:"POST",redirect:"error",headers:{"Content-Type":"application/octet-stream",Origin:o??""},body:c});return await this.readResponse(f)}async readResponse(t){if(t.ok===!1)throw new Error(`HTTPWalletWire request failed with HTTP status ${String(t.status)}`);let e=t.headers?.get("content-length");if(e!=null){if(!/^\d+$/.test(e))throw new Error("HTTPWalletWire response has an invalid Content-Length");let u=Number(e);if(!Number.isSafeInteger(u)||u>268435456)throw new Error("HTTPWalletWire response exceeds the maximum permitted size")}if(t.body==null){let u=await t.arrayBuffer();if(u.byteLength>268435456)throw new Error("HTTPWalletWire response exceeds the maximum permitted size");return new Uint8Array(u)}let i=t.body.getReader(),r=[],s=0;for(;;){let{value:u,done:f}=await i.read();if(f)break;if(u!=null){if(s+=u.byteLength,s>268435456)throw await i.cancel().catch(()=>{}),new Error("HTTPWalletWire response exceeds the maximum permitted size");r.push(u)}}let o=new Uint8Array(s),c=0;for(let u of r)o.set(u,c),c+=u.byteLength;return o}};var uu=class extends Error{constructor(e,i,r,s,o){super("Undelayed createAction or signAction results require review.");b(this,"reviewActionResults");b(this,"sendWithResults");b(this,"txid");b(this,"tx");b(this,"noSendChange");b(this,"code");b(this,"isError",!0);this.reviewActionResults=e,this.sendWithResults=i,this.txid=r,this.tx=s,this.noSendChange=o,this.code=5,this.name=this.constructor.name}};var Ld=class extends Error{constructor(e,i){super(`Insufficient funds in the available inputs to cover the cost of the required outputs and the transaction fee (${i} more satoshis are needed, for a total of ${e}), plus whatever would be required in order to pay the fee to unlock and spend the outputs used to provide the additional satoshis.`);b(this,"totalSatoshisNeeded");b(this,"moreSatoshisNeeded");b(this,"code");b(this,"isError",!0);this.totalSatoshisNeeded=e,this.moreSatoshisNeeded=i,this.code=7,this.name=this.constructor.name}},Fm=Ld;var Ud=256*1024*1024,$2=256*1024*1024;async function q2(n){let t=n.headers?.get("content-length");if(t!=null){if(!/^\d+$/.test(t))throw new Error("HTTPWalletJSON response has an invalid Content-Length");let i=Number(t);if(!Number.isSafeInteger(i)||i>Ud)throw new Error("HTTPWalletJSON response exceeds the maximum permitted size")}let e;if(n.body!=null&&typeof n.body.getReader=="function"){let i=n.body.getReader(),r=[],s=0;for(;;){let{value:c,done:u}=await i.read();if(u)break;if(c!=null){if(s+=c.byteLength,s>Ud)throw await i.cancel().catch(()=>{}),new Error("HTTPWalletJSON response exceeds the maximum permitted size");r.push(c)}}e=new Uint8Array(s);let o=0;for(let c of r)e.set(c,o),o+=c.byteLength}else if(typeof n.arrayBuffer=="function"){let i=await n.arrayBuffer();if(i.byteLength>Ud)throw new Error("HTTPWalletJSON response exceeds the maximum permitted size");e=new Uint8Array(i)}return e!==void 0?JSON.parse(Rt(e)):await n.json()}function Md(n,t,e=0,i=4096){if(typeof n!="string")throw new Error(`Invalid wallet error ${t}`);let r=at(n,"utf8").length;if(r<e||r>i)throw new Error(`Invalid wallet error ${t}`);return n}function Wm(n,t){if(!Number.isSafeInteger(n)||n<0||n>21e14)throw new Error(`Invalid wallet error ${t}`);return n}function F2(n,t){if(!Array.isArray(n))throw new Error("Invalid wallet error reviewActionResults");if(n.length>xn+1)throw new Error("Invalid wallet error reviewActionResults");let e=new Set(["success","doubleSpend","serviceError","invalidTx"]),i=new Set;for(let[r,s]of n.entries()){if(s==null||typeof s!="object"||Array.isArray(s))throw new Error(`Invalid wallet error reviewActionResults[${r}]`);let o=s;if(typeof o.txid!="string"||!/^[0-9a-fA-F]{64}$/.test(o.txid))throw new Error(`Invalid wallet error reviewActionResults[${r}].txid`);let c=o.txid.toLowerCase();if(i.has(c)||!t.has(c))throw new Error(`Invalid wallet error reviewActionResults[${r}].txid`);if(i.add(c),!e.has(o.status))throw new Error(`Invalid wallet error reviewActionResults[${r}].status`);if(o.status!=="doubleSpend"&&(o.competingTxs!==void 0||o.competingBeef!==void 0))throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs`);let u;if(o.competingTxs!==void 0){if(!Array.isArray(o.competingTxs)||o.competingTxs.length>xn)throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs`);u=[];let f=new Set;for(let[d,l]of o.competingTxs.entries()){if(typeof l!="string"||!/^[0-9a-fA-F]{64}$/.test(l))throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs[${d}]`);let p=l.toLowerCase();if(p===c||f.has(p))throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs`);f.add(p),u.push(p)}}if(o.competingBeef!==void 0){if(u==null||u.length===0)throw new Error(`Invalid wallet error reviewActionResults[${r}].competingBeef`);let f=md(o.competingBeef);if(f==null)throw new Error(`Invalid wallet error reviewActionResults[${r}].competingBeef`);try{let d=C0.fromBinaryStrict(f);for(let l of u)if(d.findTxid(l)==null)throw new Error}catch{throw new Error(`Invalid wallet error reviewActionResults[${r}].competingBeef`)}}}}function W2(n,t,e){if(n.isError!==!0||!Number.isSafeInteger(n.code))throw new Error("Invalid wallet error envelope");switch(n.message!==void 0&&Md(n.message,"message"),n.code){case 5:{if(t!=="createAction"&&t!=="signAction")throw new Error(`Invalid ${t} wallet error code`);if(!Array.isArray(n.sendWithResults))throw new Error("Invalid wallet error sendWithResults");let i={...e,options:{...e.options,returnTXIDOnly:!0}};Ft(t,{txid:n.txid,tx:n.tx,noSendChange:n.noSendChange,sendWithResults:n.sendWithResults},i);let r=new Set;typeof n.txid=="string"&&r.add(n.txid.toLowerCase());let s=e.options;if(Array.isArray(s?.sendWith))for(let o of s.sendWith)r.add(String(o).toLowerCase());return F2(n.reviewActionResults,r),new uu(n.reviewActionResults,n.sendWithResults,n.txid,n.tx,n.noSendChange)}case 6:{let i=Md(n.parameter,"parameter",1,200),r=Md(n.message,"message"),s=new ei(i);return s.message=r,s}case 7:{let i=Wm(n.totalSatoshisNeeded,"totalSatoshisNeeded"),r=Wm(n.moreSatoshisNeeded,"moreSatoshisNeeded");if(r>i)throw new Error("Invalid wallet error moreSatoshisNeeded");return new Fm(i,r)}default:return}}var Fi=class{constructor(t,e="http://localhost:3321",i=globalThis.fetch.bind(globalThis)){b(this,"baseUrl");b(this,"httpClient");b(this,"originator");b(this,"api");this.baseUrl=Os(e),this.originator=ii(t),this.httpClient=i;let r=typeof window<"u"&&typeof document<"u"&&window.origin!=="file://";this.api=async(s,o)=>{xt(s,o);let c=mt(s,o),u=Os(this.baseUrl);if(!r&&!this.originator)throw new Error('HTTPWalletJSON: originator is required when using the HTTP substrate in Node.js. Pass an originator (e.g. "example.com") to the constructor.');let f=r?void 0:qm(this.originator,"http"),d=ys(o);if(et(d,"utf8").length>$2)throw new Error("HTTPWalletJSON request exceeds the maximum permitted size");let l=await this.httpClient(`${u}/${s}`,{method:"POST",redirect:"error",headers:{Accept:"application/json","Content-Type":"application/json",...f?{Origin:f,Originator:f}:{}},body:d}),p=bm(await q2(l),`HTTPWalletJSON ${s} raw response`),m=mm(Fc(p),`HTTPWalletJSON ${s} response`);if(m==null||typeof m!="object"||Array.isArray(m))throw new Error(`Invalid HTTPWalletJSON ${s} response: expected an object`);if(!l.ok){if(l.status===400&&Object.prototype.hasOwnProperty.call(m,"isError")){let g=W2(m,s,c);if(g!==void 0)throw g}throw new Error(`HTTPWalletJSON ${s} failed with HTTP status ${l.status}`)}return Ft(s,m,c)}}async createAction(t){return await this.api("createAction",t)}async signAction(t){return await this.api("signAction",t)}async abortAction(t){return await this.api("abortAction",t)}async listActions(t){return await this.api("listActions",t)}async internalizeAction(t){return await this.api("internalizeAction",t)}async listOutputs(t){return await this.api("listOutputs",t)}async relinquishOutput(t){return await this.api("relinquishOutput",t)}async getPublicKey(t){return await this.api("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.api("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.api("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.api("encrypt",t)}async decrypt(t){return await this.api("decrypt",t)}async createHmac(t){return await this.api("createHmac",t)}async verifyHmac(t){return await this.api("verifyHmac",t)}async createSignature(t){return await this.api("createSignature",t)}async verifySignature(t){return await this.api("verifySignature",t)}async acquireCertificate(t){return await this.api("acquireCertificate",t)}async listCertificates(t){return await this.api("listCertificates",t)}async proveCertificate(t){return await this.api("proveCertificate",t)}async relinquishCertificate(t){return await this.api("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.api("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.api("discoverByAttributes",t)}async isAuthenticated(t){return await this.api("isAuthenticated",t)}async waitForAuthentication(t){return await this.api("waitForAuthentication",t)}async getHeight(t){return await this.api("getHeight",t)}async getHeaderForHeight(t){return await this.api("getHeaderForHeight",t)}async getNetwork(t){return await this.api("getNetwork",t)}async getVersion(t){return await this.api("getVersion",t)}};var V2=1024,Vm=3600*1e3,Km=256*1024*1024,Hr=class extends Es{constructor(e="*",i){super();b(this,"domain");b(this,"responseTimeout");b(this,"pendingInvocations",0);if(typeof globalThis.window!="object")throw new TypeError("The XDM substrate requires a global window object.");if(!Object.prototype.hasOwnProperty.call(globalThis.window,"ReactNativeWebView"))throw new Error("The window object does not have a ReactNativeWebView property.");if(typeof globalThis.window.ReactNativeWebView.postMessage!="function")throw new TypeError("The window.ReactNativeWebView property does not seem to support postMessage calls.");if(i!==void 0&&(!Number.isSafeInteger(i)||i<1||i>Vm))throw new TypeError(`ReactNativeWebView responseTimeout must be an integer from 1 to ${Vm}.`);this.domain=z2(e),this.responseTimeout=i}async invokeRaw(e,i,r){if(this.pendingInvocations>=V2)throw new Error("React Native wallet pending invocation limit reached.");let s=ve(Pe(12));return this.pendingInvocations++,await new Promise((o,c)=>{let u,f=!1,d=!0,l=()=>{if(d&&(d=!1,this.pendingInvocations--,u!==void 0&&clearTimeout(u),f&&typeof globalThis.window.removeEventListener=="function"))try{globalThis.window.removeEventListener("message",p)}catch{}},p=m=>{if(!K2(m,this.domain)||typeof m.data!="string")return;if(et(m.data,"utf8").length>Km){l(),c(new Error("React Native wallet response exceeds the maximum permitted size."));return}let g;try{g=JSON.parse(m.data)}catch{return}if(!(g?.type!=="CWI"||g.id!==s||g.isInvocation!==!1||g.status!=="success"&&g.status!=="error")){if(this.domain!=="*"&&m.origin!=null&&m.origin!==""&&m.origin!==this.domain){l(),c(new Error(`React Native wallet response origin ${m.origin} did not match ${this.domain}.`));return}if(l(),g.status==="error")if(typeof g.description!="string"||at(g.description,"utf8").length>4096||!Number.isSafeInteger(g.code)||g.code<1||g.code>255)c(new Error("Invalid React Native wallet error response."));else{let w=g.code>=fn.unsupportedAction&&g.code<=fn.abortRefused,S=w?g.description:"Wallet operation failed";c(new oi(S,w?g.code:fn.unknownError))}else try{let w=Fc(g.result);o(Ft(e,w,r))}catch(w){c(w)}}};try{globalThis.window.addEventListener("message",p),f=!0,this.responseTimeout!==void 0&&(u=setTimeout(()=>{l(),c(new Error("React Native wallet response timed out."))},this.responseTimeout));let m=ys({type:"CWI",isInvocation:!0,id:s,call:e,args:i});if(et(m,"utf8").length>Km)throw new Error("React Native wallet request exceeds the maximum permitted size.");globalThis.window.ReactNativeWebView.postMessage(m)}catch(m){l(),c(m)}})}};function K2(n,t){let e=globalThis.window,i=n.source;return i==null||i===e?!0:i===e.parent&&(n.origin===e.origin||n.origin===t)}function z2(n){if(n==="*")return n;try{if(/^[a-z][a-z\d+.-]*:\/\//i.test(n)&&!/^https?:\/\//i.test(n))throw new TypeError("Only HTTP(S) origins are supported.");let t=/^https?:\/\//i.test(n)?n:`https://${n}`,e=new URL(t).origin;if(e==="null")throw new TypeError("The origin could not be normalized.");return e}catch{throw new TypeError("ReactNativeWebView domain must be an HTTP(S) origin or domain name.")}}var Rs=1e3,zm=200,Wi=class{constructor(t="auto",e){b(this,"substrate");b(this,"originator");let i=ii(e);t==="Cicada"&&(t=new Ts(new Ps(i))),t==="window.CWI"&&(t=new As),t==="XDM"&&(t=new Fn),t==="json-api"&&(t=new Fi(i)),t==="react-native"&&(t=new Hr),t==="secure-json-api"&&(t=new Fi(i,"https://localhost:2121")),this.substrate=t,this.originator=i}async validatedResult(t,e,i){return Ft(t,await e,i)}async connectToSubstrate(){if(typeof this.substrate=="object")return;let t=async(o,c,u)=>{try{let f=o(),d,l;try{d=await Promise.race([f.getVersion({},this.originator),new Promise((p,m)=>{l=setTimeout(()=>m(new Error("Timed out.")),c)})])}finally{clearTimeout(l)}return Ft("getVersion",d),{success:!0,sub:u?.()??f}}catch{return{success:!1}}},e=[t(()=>new As,Rs),t(()=>new Ts(new Ps(this.originator)),Rs),t(()=>new Fi(this.originator,"https://localhost:2121"),Rs),t(()=>new Fi(this.originator),Rs),t(()=>new Hr("*",Rs),Rs,()=>new Hr)],r=(await Promise.allSettled(e)).filter(o=>o.status==="fulfilled"&&o.value.success&&o.value.sub!==void 0).map(o=>o.value.sub);if(r.length>0){this.substrate=r[0];return}let s=await t(()=>new Fn("*",zm),zm,()=>new Fn);if(s.success&&s.sub!==void 0)this.substrate=s.sub;else throw new Error("No wallet available over any communication substrate. Install a BSV wallet today!")}async createAction(t){gc(t);let e=mt("createAction",t);return await this.connectToSubstrate(),await this.validatedResult("createAction",this.substrate.createAction(t,this.originator),e)}async signAction(t){mc(t);let e=mt("signAction",t);return await this.connectToSubstrate(),await this.validatedResult("signAction",this.substrate.signAction(t,this.originator),e)}async abortAction(t){return bc(t),await this.connectToSubstrate(),await this.validatedResult("abortAction",this.substrate.abortAction(t,this.originator))}async listActions(t){Pc(t);let e=mt("listActions",t);return await this.connectToSubstrate(),await this.validatedResult("listActions",this.substrate.listActions(t,this.originator),e)}async internalizeAction(t){return wc(t),await this.connectToSubstrate(),await this.validatedResult("internalizeAction",this.substrate.internalizeAction(t,this.originator))}async listOutputs(t){Oc(t);let e=mt("listOutputs",t);return await this.connectToSubstrate(),await this.validatedResult("listOutputs",this.substrate.listOutputs(t,this.originator),e)}async relinquishOutput(t){return xc(t),await this.connectToSubstrate(),await this.validatedResult("relinquishOutput",this.substrate.relinquishOutput(t,this.originator))}async getPublicKey(t){return Rc(t),await this.connectToSubstrate(),await this.validatedResult("getPublicKey",this.substrate.getPublicKey(t,this.originator))}async revealCounterpartyKeyLinkage(t){Nc(t);let e=mt("revealCounterpartyKeyLinkage",t);return await this.connectToSubstrate(),await this.validatedResult("revealCounterpartyKeyLinkage",this.substrate.revealCounterpartyKeyLinkage(t,this.originator),e)}async revealSpecificKeyLinkage(t){Bc(t);let e=mt("revealSpecificKeyLinkage",t);return await this.connectToSubstrate(),await this.validatedResult("revealSpecificKeyLinkage",this.substrate.revealSpecificKeyLinkage(t,this.originator),e)}async encrypt(t){return _c(t),await this.connectToSubstrate(),await this.validatedResult("encrypt",this.substrate.encrypt(t,this.originator))}async decrypt(t){return Cc(t),await this.connectToSubstrate(),await this.validatedResult("decrypt",this.substrate.decrypt(t,this.originator))}async createHmac(t){return Lc(t),await this.connectToSubstrate(),await this.validatedResult("createHmac",this.substrate.createHmac(t,this.originator))}async verifyHmac(t){return Uc(t),await this.connectToSubstrate(),await this.validatedResult("verifyHmac",this.substrate.verifyHmac(t,this.originator))}async createSignature(t){return Mc(t),await this.connectToSubstrate(),await this.validatedResult("createSignature",this.substrate.createSignature(t,this.originator))}async verifySignature(t){return Dc(t),await this.connectToSubstrate(),await this.validatedResult("verifySignature",this.substrate.verifySignature(t,this.originator))}async acquireCertificate(t){if(t.acquisitionProtocol==="direct")Ac(t);else if(t.acquisitionProtocol==="issuance")vc(t);else throw new ei("acquisitionProtocol",`valid. ${String(t.acquisitionProtocol)} is unrecognized.`);let e=mt("acquireCertificate",t);return await this.connectToSubstrate(),await this.validatedResult("acquireCertificate",this.substrate.acquireCertificate(t,this.originator),e)}async listCertificates(t){Ic(t);let e=mt("listCertificates",t);return await this.connectToSubstrate(),await this.validatedResult("listCertificates",this.substrate.listCertificates(t,this.originator),e)}async proveCertificate(t){Ec(t);let e=mt("proveCertificate",t);return await this.connectToSubstrate(),await this.validatedResult("proveCertificate",this.substrate.proveCertificate(t,this.originator),e)}async relinquishCertificate(t){return Sc(t),await this.connectToSubstrate(),await this.validatedResult("relinquishCertificate",this.substrate.relinquishCertificate(t,this.originator))}async discoverByIdentityKey(t){kc(t);let e=mt("discoverByIdentityKey",t);return await this.connectToSubstrate(),await this.validatedResult("discoverByIdentityKey",this.substrate.discoverByIdentityKey(t,this.originator),e)}async discoverByAttributes(t){Tc(t);let e=mt("discoverByAttributes",t);return await this.connectToSubstrate(),await this.validatedResult("discoverByAttributes",this.substrate.discoverByAttributes(t,this.originator),e)}async isAuthenticated(t={}){return Mi(t),await this.connectToSubstrate(),await this.validatedResult("isAuthenticated",this.substrate.isAuthenticated(t,this.originator))}async waitForAuthentication(t={}){return Mi(t),await this.connectToSubstrate(),await this.validatedResult("waitForAuthentication",this.substrate.waitForAuthentication(t,this.originator))}async getHeight(t={}){return Mi(t),await this.connectToSubstrate(),await this.validatedResult("getHeight",this.substrate.getHeight(t,this.originator))}async getHeaderForHeight(t){return Hc(t),await this.connectToSubstrate(),await this.validatedResult("getHeaderForHeight",this.substrate.getHeaderForHeight(t,this.originator))}async getNetwork(t={}){return Mi(t),await this.connectToSubstrate(),await this.validatedResult("getNetwork",this.substrate.getNetwork(t,this.originator))}async getVersion(t={}){return Mi(t),await this.connectToSubstrate(),await this.validatedResult("getVersion",this.substrate.getVersion(t,this.originator))}};var Ns="com.bwalletx.extension",Dd="space.bwallet.mobile",Qo=[Ns,Dd],Vi=300;function Ki(n=Vi){return typeof window>"u"?Promise.resolve(null):new Promise(t=>{let e=!1,i,r=c=>{e||(e=!0,i!==void 0&&clearTimeout(i),window.removeEventListener("brc100:announceWallet",s),t(c))},s=c=>{let u=c.detail,f=u?.info?.rdns??"";u?.wallet&&Qo.includes(f)&&r({wallet:u.wallet,method:f===Ns?"extension":"in-app",rdns:f})},o=()=>{let c=window.CWI;return c&&r({wallet:c,method:"in-app",rdns:null}),!!c};if(window.addEventListener("brc100:announceWallet",s),window.dispatchEvent(new Event("brc100:requestWallet")),!(e||o())){if(X2()){Y2(Math.max(n,1200)).then(c=>r(c?{wallet:c,method:"in-app",rdns:null}:null));return}i=setTimeout(()=>{i=void 0,o()||r(null)},n)}})}async function jm(n=Vi){return(await Ki(n))?.wallet??null}var X2=()=>{try{return window.parent!==window}catch{return!0}},j2=["https://web.bwalletx.com","https://desktop.bwalletx.com","https://bwalletx.com","https://www.bwallet.space","https://bwallet.space","capacitor://localhost","https://localhost","tauri://localhost","https://tauri.localhost","chrome-extension://bombmmcjghjdlbmcclnhjodgcelnehgl"],G2=()=>{try{let n=window.location.ancestorOrigins;if(n&&n.length>0)return n[0]??null;if(!document.referrer)return null;let t=new URL(document.referrer);return`${t.protocol}//${t.host}`}catch{return null}};async function Y2(n=1200,t=j2){let e=G2();if(!e||!t.includes(e))return null;try{let i=new Wi(new Fn(e));return await Promise.race([i.isAuthenticated({}).then(()=>!0,()=>!1),new Promise(s=>setTimeout(()=>s(!1),n))])?i:null}catch{return null}}var Xm=0;function Hd(){typeof window>"u"||Date.now()-Xm<2e4||(Xm=Date.now(),Ki(0).then(n=>{n&&n.method==="extension"&&n.wallet.isAuthenticated({}).catch(()=>{})}))}function fu(n){let t=()=>Hd(),e=["pointerenter","focus","touchstart"];for(let i of e)n.addEventListener(i,t,{passive:!0});return()=>e.forEach(i=>n.removeEventListener(i,t))}function ta(n,t){let e=Promise.resolve();return i=>(e=e.then(()=>n(i)).catch(r=>t?.(r)),e)}var Zm="1",Z2="bwallet-pair-v1",J2="www.bwallet.space";var Jm="relay.bwallet.space",du=120,Bs=new TextEncoder,Q2=new TextDecoder,Qm=n=>{let t="";for(let e=0;e<n.length;e+=32768)t+=String.fromCharCode(...n.subarray(e,e+32768));return t},$d=n=>btoa(Qm(n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),t4=n=>{let t=n.replace(/-/g,"+").replace(/_/g,"/"),e=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(e,i=>i.charCodeAt(0))},Gm=n=>btoa(Qm(n)),Ym=n=>Uint8Array.from(atob(n),t=>t.charCodeAt(0)),tb=()=>$d(crypto.getRandomValues(new Uint8Array(16)));function eb(n){let t=new URLSearchParams({v:n.v,r:n.r,c:n.c,k:n.k,o:n.o,e:String(n.e)});return`https://${J2}/pair?${t}`}var qd=()=>$d(crypto.getRandomValues(new Uint8Array(16))),e4="bwallet-pair-wallet-claim-v1",n4=n=>Array.from(n,t=>t.toString(16).padStart(2,"0")).join("");async function nb(n,t){let e=await crypto.subtle.digest("SHA-256",Bs.encode(`${e4}|${n}|${t}`));return $d(new Uint8Array(e))}async function ib(n){return n4(new Uint8Array(await crypto.subtle.digest("SHA-256",Bs.encode(n))))}var Fd=(n,t,e,i,r,s)=>{let o=/^(localhost|127\.0\.0\.1)(:\d+)?$/.test(n),c=new URLSearchParams({role:e});return i&&c.set("e",String(i)),r&&c.set("claim",r),s&&e==="site"&&c.set("wc",s),`${o?"ws":"wss"}://${n}/v1/c/${t}?${c}`};async function Wd(n,t,e){let i=n.deriveSharedSecret(Ht.fromString(t)),r=new Uint8Array(i.encode(!0)),s=await crypto.subtle.importKey("raw",r,"HKDF",!1,["deriveBits"]),o=new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:t4(e),info:Bs.encode(Z2)},s,256)),c=await crypto.subtle.importKey("raw",o,"AES-GCM",!1,["encrypt","decrypt"]),u=new Uint8Array(await crypto.subtle.digest("SHA-256",o)),f=String((u[0]<<8|u[1])%1e4).padStart(4,"0");return{key:c,code:f}}var ea=class{constructor(t,e){b(this,"key",t);b(this,"me",e);b(this,"sent",0);b(this,"lastSeen",0)}async seal(t){let e=++this.sent,i=crypto.getRandomValues(new Uint8Array(12)),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:i,additionalData:Bs.encode(`${this.me}|${e}`)},this.key,Bs.encode(JSON.stringify(t))));return{s:e,n:Gm(i),d:Gm(r)}}async open(t){if(!Number.isInteger(t.s)||t.s<=this.lastSeen)return null;let e=this.me==="site"?"wallet":"site";try{let i=await crypto.subtle.decrypt({name:"AES-GCM",iv:Ym(t.n),additionalData:Bs.encode(`${e}|${t.s}`)},this.key,Ym(t.d));return this.lastSeen=t.s,JSON.parse(Q2.decode(i))}catch{return null}}get counters(){return{sent:this.sent,lastSeen:this.lastSeen}}restore(t){this.sent=t.sent,this.lastSeen=t.lastSeen}},Vd=n=>!!n&&typeof n=="object"&&"d"in n&&"n"in n&&"s"in n;var Kd="bwalletx.connect.pairing.v1",rb=1;function hu(){let n=new Map;return{getItem:t=>n.get(t)??null,setItem:(t,e)=>{n.set(t,e)},removeItem:t=>{n.delete(t)}}}function zd(){try{if(typeof localStorage<"u")return localStorage}catch{}return hu()}function sb(){return n=>{if(typeof WebSocket>"u")throw new Error("No WebSocket here. Pass options.socket.");return new WebSocket(n)}}function i4(n){if(!n)return null;try{let t=JSON.parse(n),e=i=>Number.isInteger(i)&&i>=0;return t.v!==1||typeof t.c!="string"||!/^[A-Za-z0-9_-]{22}$/.test(t.c)||typeof t.r!="string"||!/^[a-z0-9.-]+(:\d+)?$/i.test(t.r)||typeof t.s!="string"||!/^[0-9a-f]{64}$/i.test(t.s)||typeof t.k!="string"||!/^0[23][0-9a-f]{64}$/i.test(t.k)||!e(t.sent)||!e(t.lastSeen)||!e(t.pairedAt)||t.sc!==void 0&&(typeof t.sc!="string"||!/^[A-Za-z0-9_-]{22,64}$/.test(t.sc))?null:t}catch{return null}}var lu=class{constructor(t,e,i,r,s,o){b(this,"p",t);b(this,"sealer",e);b(this,"storage",i);b(this,"key",r);b(this,"socket",s);b(this,"timeoutMs",o);b(this,"ws",null);b(this,"opening",null);b(this,"waiting",new Map);b(this,"forgotten",!1)}adopt(t){this.ws=t,this.wire(t)}wire(t){t.onmessage=ta(e=>this.onFrame(String(e.data))),t.onerror=null,t.onclose=()=>{this.ws===t&&(this.ws=null),this.failAll(new Error("The connection to bWalletX closed"))}}persist(){this.forgotten||(this.p={...this.p,...this.sealer.counters},Promise.resolve(this.storage.setItem(this.key,JSON.stringify(this.p))).catch(()=>{}))}failAll(t){for(let e of this.waiting.values())clearTimeout(e.timer),e.reject(t);this.waiting.clear()}async ensure(){if(this.forgotten)throw new Error("This pairing was removed. Pair again.");this.ws&&this.ws.readyState===rb||(this.opening??(this.opening=this.reopen().finally(()=>this.opening=null)),await this.opening)}reopen(){this.p.sc||(this.p={...this.p,sc:qd()},this.persist());let t=Math.floor(Date.now()/1e3)+du-10,e=this.socket(Fd(this.p.r,this.p.c,"site",t,this.p.sc));return new Promise((i,r)=>{e.onopen=()=>{this.ws=e,this.wire(e),i()},e.onerror=()=>r(new Error("Could not reach the bWalletX pairing service")),e.onclose=()=>r(new Error("Could not reach the bWalletX pairing service"))})}async onFrame(t){let e;try{e=JSON.parse(t)}catch{return}if(e.t==="relay"&&e.error)return this.failAll(new Error(`bWalletX pairing service: ${e.error}`));if(!Vd(e))return;let r=await this.sealer.open(e);if(r)if(this.persist(),r.t==="res"){let s=this.waiting.get(r.id);if(!s)return;clearTimeout(s.timer),this.waiting.delete(r.id),r.error?s.reject(Object.assign(new Error(r.error.message),{code:r.error.code})):s.resolve(r.result)}else r.t==="close"&&(this.drop(),this.failAll(new Error("bWalletX disconnected this site. Pair again.")))}async call(t,e){await this.ensure();let i=this.ws,r=`${t}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,s=new Promise((o,c)=>{let u=setTimeout(()=>{this.waiting.delete(r)&&c(new Error("No answer from bWalletX. Open it, unlocked, and approve."))},this.timeoutMs);this.waiting.set(r,{resolve:o,reject:c,timer:u})});return i.send(JSON.stringify(await this.sealer.seal({t:"req",id:r,action:t,params:e}))),this.persist(),s}close(){let t=this.ws;this.ws=null,t?.close()}drop(){this.forgotten=!0,Promise.resolve(this.storage.removeItem(this.key)).catch(()=>{}),this.close()}async forget(){if(!this.forgotten){try{this.ws&&this.ws.readyState===rb&&this.ws.send(JSON.stringify(await this.sealer.seal({t:"close",reason:"site unpaired"})))}catch{}this.drop()}}wallet(){return new Proxy({},{get:(t,e)=>{if(e==="close")return()=>this.close();if(e==="forget")return()=>this.forget();if(!(typeof e!="string"||e==="then"||e==="toJSON"))return i=>this.call(e,i??{})}})}};function _s(n){let t=n.storage===void 0?zd():n.storage??hu(),e=n.storageKey??Kd,i=n.socket??sb(),r=n.relay??Jm,s=n.origin??(typeof location<"u"?location.origin:"");if(!s)return Promise.reject(new Error("pairBwalletX needs options.origin outside a browser"));let o=dr.fromRandom(),c=tb(),u=Math.floor(Date.now()/1e3)+du,f=qd(),d=o.toPublicKey().toString();return nb(c,d).then(ib).then(l=>new Promise((p,m)=>{if(n.signal?.aborted)return m(new Error("cancelled"));let g;try{g=i(Fd(r,c,"site",u,f,l))}catch(k){return m(k)}let w=null,S="",C=!1,E=k=>{C||(C=!0,clearTimeout(A),g.close(),m(k))},A=setTimeout(()=>E(new Error("The pairing code expired. Show a new one.")),du*1e3);n.signal?.addEventListener("abort",()=>E(new Error("cancelled"))),g.onerror=()=>E(new Error("Could not reach the bWalletX pairing service")),g.onclose=()=>E(new Error("The connection to bWalletX closed before pairing finished")),g.onmessage=ta(async k=>{if(C)return;let B;try{B=JSON.parse(String(k.data))}catch{return}if(B.t==="hello"&&!w){S=B.k;let H=await Wd(o,S,c);w=new ea(H.key,"site"),n.onCode(H.code);return}if(!w||!Vd(B))return;let _=await w.open(B);if(_)if(_.t==="ready"){C=!0,clearTimeout(A);let H={v:1,c,r,s:o.toHex(),k:S,...w.counters,pairedAt:Date.now(),sc:f};await Promise.resolve(t.setItem(e,JSON.stringify(H))).catch(()=>{});let O=new lu(H,w,t,e,i,n.callTimeoutMs??12e4);O.adopt(g),p(O.wallet())}else _.t==="close"&&E(new Error("Pairing was declined in bWalletX"))}),n.onLink(eb({v:Zm,r,c,k:d,o:s,e:u}))}))}async function Cs(n={}){let t=n.storage===void 0?zd():n.storage??hu(),e=n.storageKey??Kd,i=i4(await Promise.resolve(t.getItem(e)).catch(()=>null));if(!i)return null;let{key:r}=await Wd(dr.fromHex(i.s),i.k,i.c),s=new ea(r,"site");return s.restore({sent:i.sent,lastSeen:i.lastSeen}),new lu(i,s,t,e,n.socket??sb(),n.callTimeoutMs??12e4).wallet()}async function ob(n={}){let t=n.storage===void 0?zd():n.storage??hu();await Promise.resolve(t.removeItem(n.storageKey??Kd)).catch(()=>{})}var jd=[2,"bwallet sign in"];async function na(n={}){let t=i=>{try{n.onStatus?.(i)}catch{}};if(n.wallet)return t("opening"),{wallet:n.wallet,method:"wallet"};t("finding");let e=await Ki(n.discoverMs??Vi);if(e)return t("opening"),{wallet:e.wallet,method:e.method};if(n.reusePairing!==!1){let i=await Cs(n.pairing??{});if(i)return t("opening"),{wallet:i,method:"pairing"}}if(!n.pairing)throw Object.assign(new Error("bWalletX was not found in this browser"),{code:"NOT_FOUND"});return t("pairing"),{wallet:await _s(n.pairing),method:"pairing"}}async function pu(n){let{wallet:t,method:e}=await na(n);e!=="pairing"&&await t.waitForAuthentication({}).catch(()=>{});let{publicKey:i}=await Xd("identity",()=>t.getPublicKey({identityKey:!0}));try{n.onStatus?.("signing")}catch{}let r=await Xd("challenge",()=>n.challenge(i)),{signature:s}=await Xd("signature",()=>t.createSignature({protocolID:r.protocolID??jd,keyID:r.keyID,counterparty:"anyone",data:Array.from(new TextEncoder().encode(r.message))}));return{identityKey:i,signature:Array.from(s),nonce:r.nonce,method:e,wallet:t}}async function Xd(n,t){try{return await t()}catch(e){let i=e instanceof Error?e:new Error(String(e));throw i.stage||Object.assign(i,{stage:n}),i}}var ab=1,gu=[2,"bwalletx access"];var cb=50,ub={not_installed:424,user_rejected:403,wrong_account:409,insufficient_tokens:403,identity_level_too_low:403,kyc_required:403,indexer_unavailable:503,expired:401,replay:401,invalid_signature:401,bad_request:400},kt=class extends Error{constructor(e,i,r={}){super(i??e);b(this,"code");b(this,"have");b(this,"need");this.name="AccessError",this.code=e,this.have=r.have,this.need=r.need}toJSON(){let e={error:this.code,message:this.message};return this.have!==void 0&&(e.have=this.have),this.need!==void 0&&(e.need=this.need),e}},Gd={401:{name:"Identity",color:"#22c55e",video:"assets/protocol/401.mp4",poster:"assets/protocol/401.jpg"},402:{name:"Payment",color:"#3b82f6",video:"assets/protocol/402.mp4",poster:"assets/protocol/402.jpg"},403:{name:"Access",color:"#ef4444",video:"assets/protocol/403.mp4",poster:"assets/protocol/403.jpg"}};function fb(n,t,e="latest"){return`https://unpkg.com/@bwalletx/connect@${e}/${Gd[n][t]}`}function ia(n){if(n===null)return"null";if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="number"){if(!Number.isFinite(n))throw new Error("canonicalJson: non-finite number");return JSON.stringify(n)}if(Array.isArray(n))return`[${n.map(t=>ia(t)).join(",")}]`;if(typeof n=="object"){let t=n;return`{${Object.keys(t).filter(i=>t[i]!==void 0).sort().map(i=>`${JSON.stringify(i)}:${ia(t[i])}`).join(",")}}`}throw new Error(`canonicalJson: unsupported ${typeof n}`)}function Yd(n){return Array.from(new TextEncoder().encode(n))}var r4=/^bsv21:[0-9a-f]{64}_\d{1,6}$/,s4=/^[1-9]\d{0,38}$/;function o4(n){if(!n||typeof n!="object")throw new kt("bad_request","require must be an object");let t=n,e={};if(t.token!==void 0){let i=t.token;if(!i||typeof i!="object"||typeof i.id!="string")throw new kt("bad_request","require.token.id is required");let r=i.id.trim().toLowerCase();if(!r4.test(r))throw new kt("bad_request","require.token.id must be 'bsv21:<txid>_<vout>'");let s=i.min!==void 0,o=i.minBps!==void 0;if(s===o)throw new kt("bad_request","require.token needs exactly one of min or minBps");if(e.token={id:r},s){if(typeof i.min!="string"||!s4.test(i.min))throw new kt("bad_request","require.token.min must be a positive integer string (raw units)");e.token.min=i.min}else{if(!Number.isInteger(i.minBps)||i.minBps<1||i.minBps>1e4)throw new kt("bad_request","require.token.minBps must be an integer 1..10000");e.token.minBps=i.minBps}}if(t.identityLevel!==void 0){if(!Number.isInteger(t.identityLevel)||t.identityLevel<1||t.identityLevel>10)throw new kt("bad_request","require.identityLevel must be an integer 1..10");e.identityLevel=t.identityLevel}if(t.kyc!==void 0){if(typeof t.kyc!="boolean")throw new kt("bad_request","require.kyc must be a boolean");t.kyc&&(e.kyc=!0)}if(!e.token&&!e.identityLevel&&!e.kyc)throw new kt("bad_request","require is empty");return e}function db(n){if(typeof n!="string"||n.length>4096)throw new kt("bad_request","challenge must be a string");let t;try{t=JSON.parse(n)}catch{throw new kt("bad_request","challenge is not JSON")}if(!t||typeof t!="object"||t.v!==1)throw new kt("bad_request","unsupported challenge version");if(t.kind!=="401"&&t.kind!=="402"&&t.kind!=="403")throw new kt("bad_request","bad kind");if(typeof t.origin!="string"||typeof t.nonce!="string"||!/^[A-Za-z0-9_-]{16,64}$/.test(t.nonce))throw new kt("bad_request","bad origin or nonce");if(!Number.isInteger(t.iat)||!Number.isInteger(t.exp)||t.exp<=t.iat)throw new kt("bad_request","bad iat/exp");if(t.sub!==void 0&&(typeof t.sub!="string"||!/^0[23][0-9a-f]{64}$/.test(t.sub)))throw new kt("bad_request","bad sub");if(t.require=o4(t.require),ia(t)!==n)throw new kt("bad_request","challenge is not canonical");return t}function lb(n,t={}){switch(n){case"not_installed":return"No bWalletX (or other BRC-100 wallet) was found.";case"user_rejected":return"The request was declined in the wallet.";case"wrong_account":return"The wallet is signed in to a different account than this site expects.";case"insufficient_tokens":return`Not enough tokens: holding ${t.have??0}, need ${t.need??"?"}.`;case"identity_level_too_low":return`Identity level ${t.have??0} is below the required level ${t.need??"?"}.`;case"kyc_required":return"A verified identity (KYC) is required.";case"indexer_unavailable":return"Holdings could not be checked right now. Try again shortly.";case"expired":return"The request expired. Try again.";case"replay":return"That request was already used. Try again.";case"invalid_signature":return"The wallet signature did not verify.";case"bad_request":return"The request was malformed."}}var a4=[0,"onesat"],c4=[0,"p 1sat"];function mu(n){if(n instanceof kt)return n;let t=n,e=String(t?.message??n??"");return t?.code==="NOT_FOUND"?new kt("not_installed",e):/reject|denied|declin|cancel|user/i.test(e)||t?.code==="ERR_USER_REJECTED"||t?.status===4001?new kt("user_rejected",e):new kt("bad_request",e||"access failed")}function Zd(n){let t=n;if(t&&typeof t.error=="string")throw new kt(t.error,t.message,{have:t.have,need:t.need})}function u4(n){let t=/^76a914([0-9a-f]{40})88ac$/i.exec(n.slice(-50));return t?t[1].toLowerCase():null}async function Jd(n,t,e,i="bsv21"){let r=e.replace(/^bsv21:/,""),s=await n.listOutputs({basket:i,include:"locking scripts",includeCustomInstructions:!0,limit:1e4}),o=new Map,c=Yd(t);for(let u of s.outputs){if(o.size>=cb)break;let f={};try{f=JSON.parse(u.customInstructions??"{}")}catch{continue}if(f.id!==r||!f.keyID)continue;let d=u.lockingScript?u4(u.lockingScript):null,l=f.counterparty??"self";for(let p of f.protocolID?[f.protocolID]:[a4,c4]){let{publicKey:m}=await n.getPublicKey({protocolID:p,keyID:f.keyID,counterparty:l}),g=yi.toHex(Ta.hash160(Ht.fromString(m).encode(!0)));if(d&&g!==d)continue;let w=o.get(m);if(w){w.outpoints.push(u.outpoint.replace(".","_"));break}let{signature:S}=await n.createSignature({protocolID:p,keyID:f.keyID,counterparty:l,data:c});o.set(m,{pubkey:m,signature:Array.from(S),outpoints:[u.outpoint.replace(".","_")]});break}}return[...o.values()]}async function bu(n){let t;try{({wallet:t}=await na({wallet:n.wallet,pairing:n.pairing,discoverMs:n.discoverMs}))}catch(e){throw e?.code==="NOT_FOUND"?new kt("not_installed"):mu(e)}try{let{publicKey:e}=await t.getPublicKey({identityKey:!0}),{challenge:i}=await n.challenge(e),r=db(i);if(r.sub&&r.sub!==e.toLowerCase())throw new kt("wrong_account");if(Date.now()/1e3>=r.exp)throw new kt("expired");let{signature:s}=await t.createSignature({protocolID:gu,keyID:r.nonce,counterparty:"anyone",data:Yd(i)}),o={v:1,challenge:i,identityKey:e,signature:Array.from(s)};r.require.token&&(o.holdings=await Jd(t,i,r.require.token.id,n.tokenBasket));let c;return n.verify&&(c=await n.verify(o),Zd(c)),{response:o,verified:c,wallet:t}}catch(e){throw mu(e)}}var el="bwalletx-signin",nl="https://bwalletx.com/get",ra="https://web.bwalletx.com",hb={signin:"Sign in with",continue:"Continue with",connect:"Connect"};function il(n="signin",t="bWalletX"){return`${hb[n]??hb.signin} ${t}`}var f4=0;function rl(n=20){let t=++f4;return`<svg viewBox="23 8 74 100" width="${Math.round(n*.74)}" height="${n}" aria-hidden="true" focusable="false"><defs><linearGradient id="bwxg${t}" gradientUnits="userSpaceOnUse" x1="0" y1="12" x2="0" y2="105"><stop offset="0" stop-color="#FFE58A"/><stop offset=".55" stop-color="#FFD24D"/><stop offset="1" stop-color="#C98F00"/></linearGradient><mask id="bwxh${t}"><rect width="140" height="140" fill="#fff"/><circle cx="60" cy="72" r="15" fill="#000"/></mask></defs><g fill="url(#bwxg${t})" mask="url(#bwxh${t})"><polygon points="45,12 45,76 27,76 27,30"/><circle cx="60" cy="72" r="33"/></g></svg>`}var sl=`
24
+ `}return t}addComputedLeaves(){for(let t of this.bumps)for(let e=1;e<t.path.length;e++)a(this,P,jm).call(this,t,e)}};jn=new WeakMap,Gn=new WeakMap,Yn=new WeakMap,wi=new WeakMap,on=new WeakMap,xi=new WeakMap,es=new WeakMap,Gs=new WeakMap,ns=new WeakMap,Ys=new WeakMap,Zs=new WeakMap,Js=new WeakMap,is=new WeakMap,rs=new WeakMap,Zn=new WeakMap,ze=new WeakMap,Jn=new WeakMap,P=new WeakSet,zs=function(){A(this,on,void 0),A(this,xi,void 0),g(this,es).clear(),A(this,Gs,void 0),A(this,ns,void 0),A(this,Ys,void 0),A(this,Zs,void 0),A(this,Js,void 0),A(this,is,void 0)},du=function(){A(this,Zs,this.version),A(this,Js,a(this,P,kd).call(this)),A(this,is,Array.from(this.bumps)),a(this,P,hu).call(this)},kd=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}))},Td=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},hu=function(){A(this,rs,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}))}))})))},mm=function(t,e){return e.ref===t&&e.offset===t.offset&&e.hash===t.hash&&e.txid===t.txid&&e.duplicate===t.duplicate},bm=function(t,e){return e.ref===t&&e.leaves.length===t.length&&t.every((i,r)=>a(this,P,mm).call(this,i,e.leaves[r]))},ym=function(t,e){return e.ref===t&&e.blockHeight===t.blockHeight&&e.levels.length===t.path.length&&t.path.every((i,r)=>a(this,P,bm).call(this,i,e.levels[r]))},wm=function(){return g(this,rs)?.length!==this.bumps.length?!1:this.bumps.every((t,e)=>a(this,P,ym).call(this,t,g(this,rs)[e]))},zn=function(){if(g(this,rs)==null){a(this,P,hu).call(this);return}a(this,P,wm).call(this)||(a(this,P,zs).call(this),A(this,ze,void 0),A(this,Jn,void 0),A(this,Zn,!0),a(this,P,_d).call(this),a(this,P,hu).call(this))},xm=function(){if(g(this,on)==null||g(this,Zs)!==this.version||!a(this,P,Td).call(this,g(this,Js))||g(this,is)?.length!==this.bumps.length)return!1;for(let t=0;t<this.bumps.length;t++)if(g(this,is)[t]!==this.bumps[t])return!1;return!0},Xn=function(t=!0){a(this,P,zs).call(this),A(this,ze,void 0),A(this,Jn,void 0),t&&A(this,Zn,!0)},Sm=function(){for(let t of this.txs)t.txid},Im=function(){g(this,Zn)&&this.sortTxs()},Pa=function(){if(this.synchronizeNestedTransactionMutations(),a(this,P,zn).call(this),a(this,P,xm).call(this)&&g(this,on)!=null)return g(this,on);a(this,P,zs).call(this),a(this,P,Sm).call(this),a(this,P,Im).call(this);let t=new yt;return this.toWriter(t),A(this,on,t.toUint8Array()),a(this,P,du).call(this),g(this,on)},vm=function(t){let e=a(this,P,Na).call(this),i=e.get(t);if(i==null)throw new Error(`${t} does not exist in this Beef`);let r=a(this,P,Pd).call(this,i,e),s=a(this,P,Am).call(this,r);return s.sortTxs(),s},Od=function(t){var u;this.synchronizeNestedTransactionMutations(),a(this,P,zn).call(this),g(this,Ys)===this.version&&a(this,P,Td).call(this,g(this,Gs))&&g(this,ns)?.length===this.bumps.length&&this.bumps.every((f,d)=>g(this,ns)?.[d]===f)||g(this,es).clear();let i=g(this,es).get(t);if(i!=null)return i;let r=a(u=a(this,P,vm).call(this,t),P,Pa).call(u),s=it(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),g(this,es).set(t,o),A(this,Gs,a(this,P,kd).call(this)),A(this,ns,Array.from(this.bumps)),A(this,Ys,this.version),o},Pd=function(t,e){let i=new Set,r=[t];for(;r.length>0;){let s=r.pop();if(!(s==null||i.has(s))&&(i.add(s),!(a(this,P,Rd).call(this,s)||s.isTxidOnly)))for(let o of s.inputTxids){let c=e.get(o);c!=null&&r.push(c)}}return i},Rd=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},Am=function(t){let e=new Rn(this.version),i=new Map;for(let r of this.txs)!t.has(r)||!a(this,P,Rd).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 sn(r._rawTx,s,Array.from(r.inputTxids)):r._tx!=null?o=sn.fromTx(r._tx,s):o=sn.fromTxid(r.txid,s),e.txs.push(o)}return e},Ra=function(t){return a(this,P,Na).call(this).get(t)},Na=function(){return(g(this,jn)==null||g(this,Gn)==null)&&a(this,P,ts).call(this),g(this,jn)},pu=function(){return(g(this,Gn)==null||g(this,jn)==null)&&a(this,P,ts).call(this),g(this,Gn)},ts=function(){A(this,jn,new Map),A(this,Gn,new Map);for(let t=0;t<this.txs.length;t++){let e=this.txs[t];g(this,jn).set(e.txid,e),g(this,Gn).set(e.txid,t)}},Xs=function(t,e=this.txs.length-1){g(this,jn)?.set(t.txid,t),g(this,Gn)?.set(t.txid,e)},Nd=function(t){let e=a(this,P,pu).call(this).get(t.txid);e===void 0?(this.txs.push(t),a(this,P,Xs).call(this,t)):(this.txs[e]=t,a(this,P,Xs).call(this,t,e))},gu=function(){if(g(this,wi)==null){A(this,wi,new Map);for(let t=0;t<this.bumps.length;t++)for(let e of this.bumps[t].path[0])typeof e.hash=="string"&&g(this,wi).set(e.hash,t)}return g(this,wi)},Em=function(){if(g(this,Yn)==null){A(this,Yn,new Map);for(let t=0;t<this.bumps.length;t++){let e=this.bumps[t],i=g(this,Yn).get(e.blockHeight)??[];i.push(t),g(this,Yn).set(e.blockHeight,i)}}return g(this,Yn)},_d=function(){A(this,Yn,void 0),A(this,wi,void 0)},km=function(t){let e=new Set,i=[t];for(;i.length>0;){let r=i.pop();if(r==null)continue;let s=r.id("hex");if(e.has(s))continue;e.add(s);let o=this.findBump(s);if(o!=null){r.merklePath=o;continue}for(let c of r.inputs)a(this,P,Tm).call(this,c),c.sourceTransaction!=null&&i.push(c.sourceTransaction)}},Tm=function(t){if(t.sourceTransaction==null){let e=a(this,P,Ra).call(this,Fr(t.sourceTXID,"sourceTXID must be valid"));e!=null&&(t.sourceTransaction=e.tx)}},Om=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++)Q2(r,t[o],i.path.length,e);let s=r.map(o=>[...o.values()]);if(e){let o=new nr(i.blockHeight,s);return o.trim(),o}return i.path=s,i.trim(),i},_a=function(t){let e=a(this,P,Pm).call(this,t),i=this.bumps[e],r=a(this,P,Na).call(this);for(let s of i.path[0]){if(typeof s.hash!="string")continue;let o=r.get(s.hash);o!=null&&o.bumpIndex==null&&a(this,P,Rm).call(this,o,i,e)}return e},Pm=function(t){let e=a(this,P,Em).call(this),i=a(this,P,gu).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),gm(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),gm(t,s,i),s},Rm=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}},mu=function(t,e){let i=new sn(t,e);return a(this,P,Nd).call(this,i),a(this,P,js).call(this,i),i},Nm=function(t){let e=t.merklePath==null?void 0:a(this,P,_a).call(this,t.merklePath),i=new sn(t,e);return a(this,P,Nd).call(this,i),a(this,P,js).call(this,i),i},_m=function(t,e){for(let i=t.inputs.length-1;i>=0;i--){let r=t.inputs[i].sourceTransaction;r!=null&&e.push(r)}},Cd=function(t){t.materializeSourceTXIDs();let e=t.id("hex"),i=new Set,r=[t],s;for(;r.length>0;){let o=r.pop();if(o==null)continue;let c=o.id("hex");if(i.has(c))continue;i.add(c);let u=a(this,P,Nm).call(this,o);c===e&&(s=u),u.bumpIndex===void 0&&a(this,P,_m).call(this,o,r)}if(s==null)throw new Error("Failed to merge root transaction");return s},Cm=function(t){let e=a(this,P,Ra).call(this,t.txid);if(t.isTxidOnly&&e==null?(e=sn.fromTxid(t.txid),this.txs.push(e),a(this,P,Xs).call(this,e),a(this,P,js).call(this,e)):t._tx!=null&&(e==null||e.isTxidOnly)?e=a(this,P,Cd).call(this,t._tx):t._rawTx!=null&&(e==null||e.isTxidOnly)&&(e=a(this,P,mu).call(this,t._rawTx)),e==null)throw new Error(`Failed to merge BeefTx for txid: ${t.txid}`);return e},Bm=function(){let t=new Set;for(let e of this.txs){if(t.has(e.txid))return!0;t.add(e.txid)}return!1},Lm=function(t,e){for(let i of this.txs)if(i.isTxidOnly){if(e!==!0)return!1;t[i.txid]=!0}return!0},Mm=function(t,e){for(let i of this.bumps)for(let r of i.path[0])if(!(r.txid!==!0||typeof r.hash!="string"||r.hash.length===0)&&(t[r.hash]=!0,!a(this,P,Hm).call(this,i,r.hash,e)))return!1;return!0},Um=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},Dm=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},Hm=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},js=function(t){if(t.bumpIndex!==void 0)return!0;let e=t.txid,i=a(this,P,gu).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},Bd=function(){A(this,Jn,this.txs.map(t=>({ref:t,txid:t.txid,bumpIndex:t.bumpIndex,isTxidOnly:t.isTxidOnly,inputTxids:[...t.inputTxids]})))},$m=function(){if(g(this,Jn)?.length!==this.txs.length)return!1;for(let t=0;t<this.txs.length;t++){let e=this.txs[t],i=g(this,Jn)[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},bu=function(t){return{missingInputs:[...t.missingInputs],notValid:[...t.notValid],valid:[...t.valid],withMissingInputs:[...t.withMissingInputs],txidOnly:[...t.txidOnly]}},Wm=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}},Fm=function(t,e,i){let{indegree:r,dependents:s,originalIndex:o,round:c}=a(this,P,qm).call(this,t,e),u=a(this,P,Vm).call(this,t,r,s,o,c);return a(this,P,Km).call(this,t,u,c,e,i),t.filter(f=>!u.has(f.txid))},qm=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 h=s.get(d)??[];h.push(u),s.set(d,h)}r.set(u.txid,f),c.set(u.txid,0)}return{indegree:r,dependents:s,originalIndex:o,round:c}},Vm=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 h=(e.get(f.txid)??0)-1;e.set(f.txid,h),h===0&&o.push(f)}}return c},Km=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)},zm=function(t){let e=this.txs.length;this.txs=this.txs.filter(r=>!(r.isTxidOnly&&t.has(r.txid)));let i=this.txs.length!==e;return i&&a(this,P,ts).call(this),i},Xm=function(){let t=new Set;for(let r of this.txs)r.bumpIndex!==void 0&&t.add(r.bumpIndex);if(t.size>=this.bumps.length)return!1;let e=new Map,i=0;for(let r=0;r<this.bumps.length;r++)t.has(r)&&(e.set(r,i),i++);this.bumps=this.bumps.filter((r,s)=>t.has(s));for(let r of this.txs){if(r.bumpIndex===void 0)continue;let s=e.get(r.bumpIndex);if(s===void 0)throw new Error(`Internal error: bumpIndex ${r.bumpIndex} not found in indexMap`);r.bumpIndex=s}return a(this,P,_d).call(this),!0},jm=function(t,e){let i=r=>st(ne(ft(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 ss=Rn,Gm=ss;var eo=256*1024*1024,sb=21e14,n4=64,Ld=1e6,no=Array.isArray,pn=Array,Vd=Number,Kd=String,i4=Number.isFinite,r4=Number.isInteger,s4=Number.isSafeInteger,ob=Object.is,Ma=Object.create,o4=Object.defineProperty,Gt=Object.getOwnPropertyDescriptor,Ym=Object.getOwnPropertyDescriptors,zd=Object.getPrototypeOf,La=Object.keys,ce=Reflect.apply,Da=Reflect.ownKeys,a4=RegExp.prototype.exec,c4=RegExp.prototype.test,u4=String.prototype.toLowerCase,ab=Uint8Array,Xd=Uint8Array.prototype,vu=zd(Xd),Zm=Gt(vu,"buffer")?.get,xu=Gt(vu,"length")?.get,Jm=Gt(vu,Symbol.toStringTag)?.get,f4=Xd.set,Qm=typeof SharedArrayBuffer>"u"?void 0:Gt(SharedArrayBuffer.prototype,"byteLength")?.get,l4=WeakMap.prototype.get,d4=WeakMap.prototype.set,Ud=WeakSet.prototype.add,h4=WeakSet.prototype.delete,cb=WeakSet.prototype.has,Dd=new WeakSet,p4=Ae.prototype.toHex,Hd,$d,Wd,ub=/^(?:0|[1-9]\d*)$/,g4=/^([0-9a-f]{64})\.(0|[1-9]\d*)$/i,m4=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,b4=/^(?:[0-9a-f]{2})*$/i,y4=/^[0-9a-f]{64}$/i;function w4(){let n=[Array.prototype,Map.prototype,Set.prototype,WeakMap.prototype,WeakSet.prototype,Object,Object.prototype,Number,RegExp.prototype,String.prototype,Xd,vu],t=new pn(n.length);for(let e=0;e<n.length;e++){let i=n[e],r=Da(i),s=new pn(r.length);for(let o=0;o<r.length;o++)s[o]=Gt(i,r[o]);t[e]={owner:i,keys:r,descriptors:s}}return t}function Ba(n){for(let t=0;t<n.length;t++){let e=n[t];if(Da(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=Gt(e.owner,e.keys[i]);if(s==null||s.configurable!==r.configurable||s.enumerable!==r.enumerable||s.writable!==r.writable||!ob(s.value,r.value)||s.get!==r.get||s.set!==r.set)throw new Error(`Wallet callback modified shared JavaScript intrinsics (${t}:${Kd(e.keys[i])})`)}}}function Su(n,t){return Gt(n,t)!==void 0}function rr(n){return s4(n)}function Ua(n,t){return ce(c4,n,[t])}function as(n){return ce(u4,n,[])}function io(n){return ce(p4,n,[])}function x4(){Hd??(Hd=Ke.fromAtomicBEEF),$d??($d=Ke.prototype.id),Wd??(Wd=Ke.prototype.toAtomicBEEF)}function Md(n){if(Hd==null)throw new Error("Transaction intrinsics are unavailable");return ce(Hd,Ke,[n])}function S4(n){if(Wd==null)throw new Error("Transaction intrinsics are unavailable");return ce(Wd,n,[!0])}function fb(n){if($d==null)throw new Error("Transaction intrinsics are unavailable");return ce($d,n,["hex"])}function tb(n,t){return ce(cb,n.active,[t])}function I4(n,t){ce(Ud,n.active,[t])}function eb(n,t){ce(h4,n.active,[t])}function v4(n,t){return ce(l4,n.completed,[t])}function yu(n,t,e){ce(d4,n.completed,[t,e])}function ir(n,t,e=!1){if(n==null||typeof n!="object"||no(n))throw new Error(`${t} must be a plain data object`);let i=zd(n);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain data object`);let r=Da(n);for(let s=0;s<r.length;s++){let o=r[s],c=Gt(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 lb(n,t,e=eo){if(zd(n)!==Array.prototype)throw new Error(`${t} must contain only dense data arrays`);let i=Gt(n,"length");if(i==null||!("value"in i)||!rr(i.value)||i.value<0)throw new Error(`${t} must contain only dense data arrays`);let r=i.value;if(r>eo)throw new Error(`${t} exceeds the byte limit`);if(Da(n).length!==r+1)throw new Error(`${t} must contain only dense data arrays`);let o=r>e,c=o?void 0:new pn(r);for(let u=0;u<r;u++){let f=Gt(n,Kd(u));if(f==null||!f.enumerable||!("value"in f))throw new Error(`${t} must contain only dense data arrays`);if(!r4(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 db(n,t,e=eo){if(Zm==null||xu==null||Jm==null)return;let i,r,s;try{i=ce(Zm,n,[]),r=ce(xu,n,[]),s=ce(Jm,n,[])}catch{return}if(s!=="Uint8Array")return;if(Qm!=null){let c=!1;try{ce(Qm,i,[]),c=!0}catch{}if(c)throw new Error(`${t} must not use shared byte storage`)}if(r>eo)throw new Error(`${t} exceeds the byte limit`);if(r>e)throw new Error(`${t} exceeds the aggregate byte limit`);let o=new ab(r);try{ce(f4,o,[n])}catch{throw new Error(`${t} must contain only intrinsic byte arrays`)}return o}function os(n,t,e=0,i={nodes:0,active:new WeakSet,completed:new WeakMap,copiedBytes:0},r=!1){if(e>n4)throw new Error(`${t} exceeds the depth limit`);if(i.nodes+=1,i.nodes>Ld)throw new Error(`${t} exceeds the node limit`);if(n==null||typeof n=="string"||typeof n=="boolean")return n;if(typeof n=="number"){if(!i4(n)||ob(n,-0))throw new Error(`${t} contains an ambiguous number`);return n}if(typeof n!="object")throw new Error(`${t} contains unsupported data`);if(tb(i,n))throw new Error(`${t} contains a cycle`);let s=v4(i,n);if(s!==void 0)return s;let o=db(n,t,eo-i.copiedBytes);if(o!==void 0)return i.copiedBytes+=o.length,ce(Ud,Dd,[o]),yu(i,n,o),o;if(no(n)){let h=lb(n,t,eo-i.copiedBytes);if(h!==void 0)return i.copiedBytes+=h.length,ce(Ud,Dd,[h]),yu(i,n,h),h;let l=Gt(n,"length");if(l==null||!("value"in l)||!rr(l.value)||l.value<0)throw new Error(`${t} must contain only dense data arrays`);if(l.value>Ld)throw new Error(`${t} exceeds the node limit`)}if(I4(i,n),no(n)){let h=Ym(n),l=h.length;if(l==null||!("value"in l)||!rr(l.value)||l.value<0||l.value>Ld)throw new Error(`${t} must contain only dense data arrays`);let m=l.value,b=Da(h);if(b.length!==m+1)throw new Error(`${t} must contain only dense data arrays`);for(let S=0;S<b.length;S++){let L=b[S];if(L!=="length"&&(typeof L!="string"||!Ua(ub,L)||Vd(L)>=m))throw new Error(`${t} must contain only dense data arrays`)}let y=new pn(m);for(let S=0;S<m;S++){let L=Kd(S),T=h[L];if(T==null||!T.enumerable||!("value"in T))throw new Error(`${t} must contain only dense data arrays`);y[S]=os(T.value,`${t}[${S}]`,e+1,i)}return eb(i,n),yu(i,n,y),y}let c=ir(n,t,r);if(tb(i,c)&&c!==n)throw new Error(`${t} contains a cycle`);let u=Ma(null),f=Ym(c),d=La(f);for(let h=0;h<d.length;h++){let l=d[h],m=f[l];if(!m.enumerable||!("value"in m))throw new Error(`${t} must contain only string-keyed data properties`);o4(u,l,{value:os(m.value,`${t}.${l}`,e+1,i),enumerable:!0,configurable:!0,writable:!0})}return eb(i,n),yu(i,n,u),u}function nb(n,t){if(n!=null&&typeof n=="object"){let r=ce(cb,Dd,[n]);if(r&&no(n)){let o=Gt(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&&xu!=null){let o;try{o=ce(xu,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=db(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(!no(n))throw new Error(`${t} must be a bounded non-empty byte array`);let e=lb(n,t);if(e==null||e.length===0)throw new Error(`${t} must be a bounded non-empty byte array`);let i=new ab(e.length);for(let r=0;r<e.length;r++)i[r]=e[r];return i}function wu(n,t){if(typeof n!="string"||!Ua(y4,n))throw new Error(`${t} must be a 32-byte hexadecimal transaction ID`);return as(n)}function Iu(n,t){if(typeof n!="string"||!Ua(b4,n))throw new Error(`${t} must be an even-length hexadecimal string`);return as(n)}function Fd(n,t){if(typeof n!="string")throw new Error(`${t} must be a canonical outpoint`);let e=ce(a4,g4,[n]);if(e==null)throw new Error(`${t} must be a canonical outpoint`);let i=Vd(e[2]);if(!rr(i)||i>4294967295)throw new Error(`${t} must be a canonical outpoint`);return`${as(e[1])}.${i}`}function qd(n,t){let e=n.inputs[t];if(e==null||!rr(e.sourceOutputIndex)||e.sourceOutputIndex<0||e.sourceOutputIndex>4294967295)throw new Error("Wallet transaction input is malformed");let i=e.sourceTransaction==null?void 0:fb(e.sourceTransaction);if(e.sourceTXID!==void 0&&i!==void 0&&wu(e.sourceTXID,"Wallet input source TXID")!==wu(i,"Wallet input source transaction ID"))throw new Error("Wallet transaction input source mismatch");return`${wu(e.sourceTXID??i,"Wallet input source TXID")}.${e.sourceOutputIndex}`}function to(n,t){if(typeof n!="number"||!rr(n)||n<0||n>sb)throw new Error(`${t} must be a valid satoshi amount`);return n}function Qs(n,t,e){let i=n+t;if(!rr(i)||i>sb)throw new Error(`${e} exceeds the maximum transaction value`);return i}function ib(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 to(i.satoshis,`Wallet input ${t} source output`)}function A4(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 pn(t.inputs.length),s=Ma(null);for(let k=0;k<t.inputs.length;k++){let E=qd(t,k);if(Su(s,E))throw new Error("Wallet transaction contains a duplicate input outpoint");r[k]=E,s[E]=!0}let o=[],c=Ma(null);for(let k=0;k<(n.inputs?.length??0);k++){let E=n.inputs[k],_=Fd(E.outpoint,`Requested input ${k} outpoint`);if(Su(c,_))throw new Error("Action requests the same input outpoint more than once");c[_]=!0;let B=-1;for(let C=0;C<r.length;C++)if(r[C]===_){if(B!==-1)throw new Error("Wallet transaction does not contain each requested input exactly once");B=C}if(B===-1)throw new Error("Wallet transaction does not contain each requested input exactly once");if(o[k]=B,(t.inputs[B].sequence??4294967295)!==(E.sequenceNumber??4294967295))throw new Error("Wallet transaction substituted a requested input sequence");let F=t.inputs[B].unlockingScript;if(E.unlockingScript!==void 0&&(F==null?void 0:as(io(F)))!==Iu(E.unlockingScript,`Requested input ${k} unlocking script`))throw new Error("Wallet transaction substituted a requested unlocking script")}let u=new pn(t.outputs.length);for(let k=0;k<t.outputs.length;k++){let E=t.outputs[k];u[k]={satoshis:to(E.satoshis,`Wallet output ${k}`),lockingScript:as(io(E.lockingScript))}}let f=new pn(u.length),d=n.options?.randomizeOutputs===!1,h=0,l=(k,E)=>{let _=n.outputs[k],B=Iu(_.lockingScript,`Requested output ${k} locking script`),F=to(_.satoshis,`Requested output ${k}`);if(d){let I=u[k],q=I!=null&&(E==null?I.satoshis===F:I.satoshis>=E.minimumSatoshis&&I.satoshis<=E.maximumSatoshis);if(I==null||I.lockingScript!==B||!q)throw new Error("Wallet transaction substituted a requested output position");f[k]=!0,h=Qs(h,I.satoshis,"Requested output value");return}let C=-1;for(let I=0;I<u.length;I++){let q=u[I];if(!(f[I]===!0||q.lockingScript!==B||!(E==null?q.satoshis===F:q.satoshis>=E.minimumSatoshis&&q.satoshis<=E.maximumSatoshis))){if(E==null){C=I;break}if(C!==-1)throw new Error("Wallet transaction omitted or substituted a requested output");C=I}}if(C===-1)throw new Error("Wallet transaction omitted or substituted a requested output");f[C]=!0,h=Qs(h,u[C].satoshis,"Requested output value")};for(let k=0;k<(n.outputs?.length??0);k++)e[k]===void 0&&l(k);for(let k=0;k<(n.outputs?.length??0);k++){let E=e[k];E!=null&&l(k,E)}let m=0,b=new pn(t.inputs.length);for(let k=0;k<o.length;k++){let E=o[k];b[E]=!0,m=Qs(m,i?.[k]??ib(t,E),"Requested input value")}let y=0;for(let k=0;k<t.inputs.length;k++)b[k]!==!0&&(y=Qs(y,ib(t,k),"Wallet-added input value"));let S=0;for(let k=0;k<u.length;k++)S=Qs(S,u[k].satoshis,"Wallet output value");let L=Qs(m,y,"Wallet input value");if(S>L)throw new Error("Wallet signable transaction spends more than its inputs");if(S-h>y)throw new Error("Wallet used a requested input to fund an unrequested output");return o}function rb(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(qd(n,e)!==qd(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||io(n.outputs[e].lockingScript)!==io(t.outputs[e].lockingScript))throw new Error("Wallet signed transaction substituted an authorized output")}async function E4(n,t,e){try{await n.abortAction({reference:t},e)}catch{}}async function hb(n,t,e={},i,r){x4();let s=w4(),o=os(t,"Create action arguments"),c=os(o,"Create action arguments"),u=o.inputs??[],f;if(r!==void 0){let I=os(r,"Trusted requested input satoshis");if(!no(I)||I.length!==u.length)throw new Error("Trusted requested input satoshis must match the requested inputs");let q=new pn(I.length);for(let W=0;W<I.length;W++)q[W]=to(I[W],`Trusted requested input ${W}`);f=q}let d=ir(e,"Bound action options"),h=La(d);for(let I=0;I<h.length;I++){let q=h[I];if(q!=="inputSigners"&&q!=="outputSatoshisRanges")throw new Error(`Unknown bound action option "${q}"`)}let l=Gt(d,"inputSigners")?.value,m=ir(l??{},"Input signers"),b=Ma(null),y=0,S=La(m);for(let I=0;I<S.length;I++){let q=S[I],W=Gt(m,q)?.value,K=Fd(q,"Input signer outpoint");if(Su(b,K)||typeof W!="function")throw new Error("Input signers must uniquely identify requested outpoints");b[K]=W,y++}let L=Gt(d,"outputSatoshisRanges")?.value,T=ir(L??{},"Output satoshi ranges"),k=new pn(o.outputs?.length??0),E=La(T);for(let I=0;I<E.length;I++){let q=E[I],W=Gt(T,q)?.value;if(!Ua(ub,q))throw new Error("Output satoshi ranges must identify requested output indexes");let K=Vd(q);if(!rr(K)||K>=(o.outputs?.length??0))throw new Error("Output satoshi ranges must identify requested output indexes");let ot=ir(W,`Output satoshi range ${K}`),ut=La(ot);for(let nt=0;nt<ut.length;nt++){let Ot=ut[nt];if(Ot!=="minimumSatoshis"&&Ot!=="maximumSatoshis")throw new Error(`Unknown output satoshi range option "${Ot}"`)}let V=to(Gt(ot,"minimumSatoshis")?.value,`Output satoshi range ${K} minimum`),j=to(Gt(ot,"maximumSatoshis")?.value,`Output satoshi range ${K} maximum`);if(V>j)throw new Error(`Output satoshi range ${K} minimum exceeds its maximum`);k[K]={minimumSatoshis:V,maximumSatoshis:j}}let _=await n.createAction({...c,options:{...c.options,signAndProcess:!1,returnTXIDOnly:!1}},i);Ba(s);let B=ir(os(_,"Wallet createAction result",0,void 0,!0),"Wallet createAction result",!0);Ba(s);let F=ir(Gt(B,"signableTransaction")?.value,"Wallet signable transaction"),C=Gt(F,"reference")?.value;if(typeof C!="string"||C.length===0||C.length>4096||!Ua(m4,C))throw new Error("Wallet signable transaction reference is invalid");try{let I=Md(nb(Gt(F,"tx")?.value,"Wallet signable transaction")),q=A4(o,I,k,f),W=Md(S4(I)),K={},ot=new pn(I.inputs.length),ut=new pn,V=Ma(null),j=0;for(let Oe=0;Oe<u.length;Oe++){let Y=u[Oe],pt=Fd(Y.outpoint,`Requested input ${Oe} outpoint`),N=q[Oe];if(Y.unlockingScript!==void 0){ot[N]=Iu(Y.unlockingScript,`Requested input ${Oe} unlocking script`),ut[ut.length]=N;continue}let D=Gt(b,pt)?.value;if(Y.unlockingScriptLength===void 0||D==null)throw new Error(`Requested input ${Oe} has no authorized signer`);let M=await D(I,N);Ba(s),rb(W,I);let H=Iu(typeof M=="string"?M:io(M),`Requested input ${Oe} signed unlocking script`);K[N]={unlockingScript:H},ot[N]=H,ut[ut.length]=N,Su(V,pt)||(V[pt]=!0,j++)}if(j!==y)throw new Error("An input signer does not match a requested signable input");let nt={acceptDelayedBroadcast:o.options?.acceptDelayedBroadcast,returnTXIDOnly:!1,noSend:o.options?.noSend,sendWith:o.options?.sendWith},Ot=await n.signAction({reference:C,spends:K,options:nt},i);Ba(s);let be=ir(os(Ot,"Wallet signAction result",0,void 0,!0),"Wallet signAction result",!0);Ba(s);let Mt=Md(nb(Gt(be,"tx")?.value,"Wallet signed transaction"));rb(I,Mt);for(let Oe=0;Oe<ut.length;Oe++){let Y=ut[Oe],pt=ot[Y],N=Mt.inputs[Y]?.unlockingScript;if(N==null||as(io(N))!==pt)throw new Error("Wallet signed transaction substituted an authorized unlocking script")}let ln=Gt(be,"txid")?.value;if(ln!==void 0&&wu(ln,"Wallet signed transaction ID")!==as(fb(Mt)))throw new Error("Wallet signed transaction ID does not match its transaction data");return Mt}catch(I){throw await E4(n,C,i),I}}var Ha=class extends Error{constructor(e){super(`Transaction evidence: ${e}`);w(this,"code");this.code=e,this.name="TransactionEvidenceError"}};var N5=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 pb(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 Ha("invalid-evidence");return[r.id("hex"),i.sourceOutputIndex,s.satoshis,s.lockingScript.toHex()]});return st(Le(ft(JSON.stringify([t.toHex(),e,n.blockHeight,n.consensus,n.verifyFlags,n.memoryLimit]),"utf8")))}var k4=new WeakMap;function gb(n){return k4.get(n)}function mb(n,t){return{supportsMemoryLimit:t.supportsMemoryLimit,shouldVerifyScripts:t.shouldVerifyScripts===void 0?void 0:e=>{n.check();let i=pb(e),r=t.shouldVerifyScripts(e);if(n.check(),pb(e)!==i)throw new Ha("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 bb=Symbol(),yb=Symbol();function hm(n){return n[bb]()}function pm(n,t){n[yb](t)}var T4=943816,wb=21e14,O4=1e6;function gn(n,t){if(typeof n!="number"||!Number.isSafeInteger(n)||n<0||n>wb)throw new RangeError(`${t} must be a non-negative safe integer no greater than 21e14.`);return n}function ro(n,t,e){let i=n+t;if(!Number.isSafeInteger(i)||i>wb)throw new RangeError(`${e} exceeds the maximum valid monetary range.`);return i}function an(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 sr(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 jd(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 us,Si,ar,fs,cr,Wa,so,G,xb,Sb,Qn,$a,Gd,Nn,Yd,Au,Zd,Ib,vb,Ab,Eb,kb,Tb,Ob,cs,Pb,Jd,Rb,Nb,_b,Cb,Eu,Bb,Lb,or,ku,Mb,Ub,Db,Hb,$b,Wb,Fb,qb,Vb,pe=class pe{constructor(t=1,e=[],i=[],r=0,s=new Map,o){z(this,G);w(this,"version");w(this,"inputs");w(this,"outputs");w(this,"lockTime");w(this,"metadata");w(this,"merklePath");z(this,us);z(this,Si);z(this,ar);z(this,fs);z(this,cr);z(this,Wa);z(this,so);this.version=t,this.inputs=e,this.outputs=i,this.lockTime=r,this.metadata=s,this.merklePath=o}getSignatureHashCache(){return g(this,Wa)??{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,G,xb).call(this,r.tx,e,t);continue}a(this,G,Sb).call(this,r.tx,e,t,i)}}}static fromBEEF(t,e){var r;let{tx:i}=a(r=pe,Qn,$a).call(r,t,e);return i}static fromBEEFView(t,e){var r;let{tx:i}=a(r=pe,Qn,$a).call(r,t,e,!0);return i}static fromAtomicBEEF(t){var s;let{tx:e,txid:i,beef:r}=a(s=pe,Qn,$a).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=pe,Qn,$a).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=vt.makeReader(t),i=e.readUInt32LE();if(st(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=st(e.readReverse(32)),h=e.readUInt32LE();if(h>O4)throw new RangeError("EF source output index exceeds the allocation limit");let l=e.readVarIntNumStrict(!1),m=e.read(l),b=Ve.fromBinary(m),y=e.readUInt32LE(),S=e.readUInt64LEBn().toNumber(),L=e.readVarIntNumStrict(!1),T=e.read(L),k=qe.fromBinary(T),E=new pe(void 0,[],[],void 0);E.outputs=Array.from({length:h+1}).fill(null),E.outputs[h]={satoshis:S,lockingScript:k},s.push({sourceTransaction:E,sourceTXID:d,sourceOutputIndex:h,unlockingScript:b,sequence:y})}let o=e.readVarIntNumStrict(!1),c=[];for(let f=0;f<o;f++){let d=e.readUInt64LEBn().toNumber(),h=e.readVarIntNumStrict(!1),l=e.read(h),m=qe.fromBinary(l);c.push({satoshis:d,lockingScript:m})}let u=e.readUInt32LE();if(!e.eof())throw new Error("Serialized EF transaction contains trailing data");return new pe(i,s,c,u)}static parseScriptOffsets(t){let e=vt.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=pe,Qn,Gd).call(e,t,!1)}static fromBinary(t){let e=Uint8Array.from(t);return pe.fromBinaryView(e)}static fromBinaryView(t){var r,s;let e=new vt(t),i=a(r=pe,Qn,Gd).call(r,e,!0);if(!e.eof())throw new Error("Serialized transaction contains trailing data");return A(i,ar,t),a(s=i,G,Au).call(s),i}static fromHex(t){let e=it(t,"hex"),i=pe.fromBinaryView(e);return A(i,cr,st(e)),i}static fromHexEF(t){return pe.fromEF(it(t,"hex"))}static fromHexBEEF(t,e){return pe.fromBEEF(ft(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.");an(t.sourceOutputIndex,"sourceOutputIndex"),t.sourceTXID!==void 0&&(t.sourceTXID=sr(t.sourceTXID,"sourceTXID")),t.sequence!==void 0&&an(t.sequence,"sequence"),t.sequence??(t.sequence=4294967295),a(this,G,Nn).call(this),this.inputs.push(t)}addOutput(t){if(a(this,G,Nn).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&&gn(t.satoshis,"satoshis"),t.lockingScript==null)throw new Error("lockingScript must be defined");this.outputs.push(t)}addP2PKHOutput(t,e){let i=new bi().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=Aa.getInstance(),e="equal"){var S,L,T,k,E;if(a(this,G,Nn).call(this),e!=="equal"&&e!=="random")throw new TypeError('changeDistribution must be either "equal" or "random".');if(typeof t=="number"){let _=t;t={computeFee:async()=>_}}let i=a(this,G,or).call(this,!0),r=a(S=i,G,or).call(S,!0),s=a(L=i,G,or).call(L,!0),o=[...this.inputs],c=this.inputs.map(_=>_.sourceTransaction),u=this.inputs.map(_=>_.unlockingScriptTemplate),f=[...this.outputs],d=[...s.inputs],h=s.inputs.map(_=>_.sourceTransaction),l=s.inputs.map(_=>_.unlockingScriptTemplate),m=[...s.outputs],b=gn(await t.computeFee(s),"Computed transaction fee");if(!a(T=s,G,ku).call(T,i,d,h,l,m))throw new Error("Fee model mutated its transaction snapshot");let y=a(k=r,G,Ib).call(k,b);if(y<0)throw new RangeError("Transaction inputs are insufficient for the requested outputs and fee.");if(!a(this,G,ku).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(_=>_.change!==!0),a(this,G,Nn).call(this);return}a(E=r,G,vb).call(E,y,e);for(let _=0;_<f.length;_++)f[_].change===!0&&(f[_].satoshis=r.outputs[_].satoshis);a(this,G,Nn).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");an(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=ro(t,gn(s.satoshis,`Input ${i} source amount`),"Transaction input total")}let e=0;for(let i=0;i<this.outputs.length;i++)e=ro(e,gn(this.outputs[i].satoshis,`Output ${i} amount`),"Transaction output total");return t-e}async sign(t={}){a(this,G,Nn).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.");gn(d.satoshis,`Output ${f} amount`)}a(this,G,Eu).call(this,this);for(let f=0;f<this.inputs.length;f++){let d=this.inputs[f];if(an(d.sourceOutputIndex,`Input ${f} sourceOutputIndex`),an(d.sequence??4294967295,`Input ${f} sequence`),d.sourceTXID!==void 0&&sr(d.sourceTXID,`Input ${f} sourceTXID`),d.sourceTransaction!==void 0){let h=d.sourceTransaction.outputs[d.sourceOutputIndex];if(h==null)throw new RangeError(`Input ${f} references a source output that does not exist.`);if(gn(h.satoshis,`Input ${f} source amount`),d.sourceTXID!==void 0&&(d.sourceTransaction.inputs.length>0||d.sourceTransaction.merklePath!=null)&&sr(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,G,or).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 y;if(c&&f.unlockingScript!=null)return new Ve([],Uint8Array.from(f.unlockingScript.toUint8Array()),void 0,!1);let h=s[d];if(h===void 0)return;let l=a(y=e,G,or).call(y,!0);for(let S=0;S<s.length;S++)l.inputs[S].unlockingScriptTemplate=s[S];A(l,Wa,{hashOutputsSingle:new Map});let m=await h.sign(l,d);if(m==null||typeof m.toUint8Array!="function")throw new TypeError(`Input ${d} signing template returned an invalid unlocking script`);let b=m.toUint8Array();if(!(b instanceof Uint8Array))throw new TypeError(`Input ${d} signing template returned an invalid unlocking script`);return new Ve([],Uint8Array.from(b),void 0,!1)})),!a(this,G,ku).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,G,Nn).call(this)}async broadcast(t=cm()){let e=a(this,G,or).call(this),i=e.id("hex");return Yg(await t.broadcast(e),i)}[bb](){return a(this,G,cs).call(this)}[yb](t){A(this,Si,t)}toBinary(){return Array.from(a(this,G,cs).call(this))}toUint8Array(){return Uint8Array.from(a(this,G,cs).call(this))}toEF(){return Array.from(a(this,G,Jd).call(this))}toEFUint8Array(){return this.toEFBinary()}toEFBinary(){return Uint8Array.from(a(this,G,Jd).call(this))}toHexEF(){return st(this.toEFBinary())}toHex(){let t=a(this,G,cs).call(this);if(g(this,cr)!=null)return g(this,cr);let e=st(t);return A(this,cr,e),e}toHexBEEF(){return st(this.toBEEF())}toHexAtomicBEEF(){return st(this.toAtomicBEEF())}hash(t){let e=a(this,G,cs).call(this);return g(this,us)??A(this,us,ne(e)),t==="hex"?st(g(this,us)):Array.from(g(this,us))}id(t){if(a(this,G,cs).call(this),t==="hex"&&g(this,Si)!=null)return g(this,Si);let e=[...this.hash()];return e.reverse(),t==="hex"?(A(this,Si,st(e)),g(this,Si)):e}async verifyTransactionFee(t,e,i){if(e===void 0)return;if(t===void 0)throw new Error("Transaction is undefined");let r=pe.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=dm(),e,i,r){var o;t!=="scripts only"&&this.materializeSourceTXIDs();let s=t==="scripts only"?void 0:gb(this);return await a(o=a(this,G,or).call(this),G,Ub).call(o,t,e,i,r,s)}writeSerializedBEEF(t,e){this.materializeSourceTXIDs(),t.writeUInt32LE(4022206465);let{bumps:i,txs:r}=a(this,G,Db).call(this,e);t.writeVarIntNum(i.length);let s=a(this,G,Fb).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 we;return this.writeSerializedBEEF(e,t),e.toArray()}toBEEFUint8Array(t){let e=new yt;return this.writeSerializedBEEF(e,t),e.toArray()}toBEEFBytes(t){let e=new yt;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 yt,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(l=>l.unlockingScriptTemplate!=null),f=await a(this,G,qb).call(this,c,u);f.options=r;let d={};for(let l=0;l<this.inputs.length;l++){let m=this.inputs[l].unlockingScriptTemplate;if(m==null)continue;let b=f.inputs[l].outpoint;d[b]=async(y,S)=>await m.sign(y,S)}let h=await hb(t,f,{inputSigners:d},i,this.inputs.map((l,m)=>{let b=l.sourceTransaction?.outputs[l.sourceOutputIndex];if(b==null)throw new Error(`Input ${m} references a source output that does not exist`);return gn(b.satoshis,`Input ${m} source amount`)}));this.version=h.version,this.inputs=h.inputs,this.outputs=h.outputs,this.lockTime=h.lockTime,this.merklePath=h.merklePath,a(this,G,Nn).call(this),this.metadata={...this.metadata,...h.metadata}}preimage(t,e,i){if(t??(t=0),e??(e=At.SIGHASH_FORKID|At.SIGHASH_ALL),!Number.isSafeInteger(t)||t<0||t>=this.inputs.length)throw new Error("Invalid input index");an(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=an(o.sourceOutputIndex,"sourceOutputIndex");if(o.sourceTransaction==null)throw new Error("Source transaction is required");let u=sr(o.sourceTransaction.id("hex"),"sourceTransaction ID");if(o.sourceTXID!==void 0&&sr(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=gn(f.satoshis,"Source output amount"),h=an(o.sequence??4294967295,"inputSequence"),l=i??f.lockingScript;if(l==null||typeof l.toUint8Array!="function")throw new Error("subscript must be a locking script");return At.format({sourceTXID:u,sourceOutputIndex:c,sourceSatoshis:d,transactionVersion:this.version,otherInputs:[],allInputs:this.inputs,inputIndex:t,outputs:this.outputs,inputSequence:h,subscript:l,lockTime:this.lockTime,scope:e})}};us=new WeakMap,Si=new WeakMap,ar=new WeakMap,fs=new WeakMap,cr=new WeakMap,Wa=new WeakMap,so=new WeakMap,G=new WeakSet,xb=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)},Sb=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})}},Qn=new WeakSet,$a=function(t,e,i=!1){let r=i&&t instanceof Uint8Array?ss.fromBinaryView(t):ss.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}},Gd=function(t,e){let i=t.readUInt32LE(),r=t.readVarIntNumStrict(!1),s=[];for(let f=0;f<r;f++){let d=st(t.readReverse(32)),h=t.readUInt32LE(),l=t.readVarIntNumStrict(!1),m=e&&t instanceof vt?t.readView(l):t.read(l),b=e&&m instanceof Uint8Array?Ve.fromBinaryView(m):Ve.fromBinary(m),y=t.readUInt32LE();s.push({sourceTXID:d,sourceOutputIndex:h,unlockingScript:b,sequence:y})}let o=t.readVarIntNumStrict(!1),c=[];for(let f=0;f<o;f++){let d=t.readUInt64LEBn().toNumber(),h=t.readVarIntNumStrict(!1),l=e&&t instanceof vt?t.readView(h):t.read(h),m=e&&l instanceof Uint8Array?qe.fromBinaryView(l):qe.fromBinary(l);c.push({satoshis:d,lockingScript:m})}let u=t.readUInt32LE();return new pe(i,s,c,u)},Nn=function(){A(this,us,void 0),A(this,Si,void 0),A(this,ar,void 0),A(this,fs,void 0),A(this,cr,void 0),A(this,so,void 0)},Yd=function(t){return t.sourceTXID==null?t.sourceTransaction?.id("hex"):void 0},Au=function(){A(this,so,{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,G,Yd).call(this,t),sourceOutputIndex:t.sourceOutputIndex,sequence:t.sequence,unlockingScript:t.unlockingScript,unlockingScriptBytes:t.unlockingScript==null?void 0:Yr(t.unlockingScript),sourceOutput:e,sourceSatoshis:e?.satoshis,sourceLockingScript:e?.lockingScript,sourceLockingScriptBytes:e==null?void 0:Yr(e.lockingScript)}}),outputs:this.outputs.map(t=>({ref:t,satoshis:t.satoshis,lockingScript:t.lockingScript,lockingScriptBytes:Yr(t.lockingScript)}))})},Zd=function(){let t=g(this,so);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,G,Yd).call(this,i)||r.sourceOutputIndex!==i.sourceOutputIndex||r.sequence!==i.sequence||r.unlockingScript!==i.unlockingScript||r.unlockingScriptBytes!==(i.unlockingScript==null?void 0:Yr(i.unlockingScript))||r.sourceOutput!==s||r.sourceSatoshis!==s?.satoshis||r.sourceLockingScript!==s?.lockingScript||r.sourceLockingScriptBytes!==(s==null?void 0:Yr(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!==Yr(i.lockingScript))return!1}return!0},Ib=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");an(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=gn(o.satoshis,`Input ${r} source amount`);e=ro(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=gn(s.satoshis,`Output ${r} amount`);i=ro(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},vb=function(t,e){let i=this.outputs.filter(r=>r.change===!0);i.length!==0&&(e==="random"?a(this,G,Ab).call(this,t,i):a(this,G,Eb).call(this,t,i))},Ab=function(t,e){let i=t;for(let r=0;r<e.length-1;r++){let s=a(this,G,kb).call(this,0,i);e[r].satoshis=s,i-=s}e.at(-1).satoshis=i},Eb=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},kb=function(t,e){let i=Ue(1)[0]%9+1;return Math.floor(t+(e-t)*Math.log10(1+1/i)/Math.log10(10))},Tb=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(ft(sr(e.sourceTXID,"sourceTXID"),"hex"));if(t.writeUInt32LE(an(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(an(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)},Ob=function(){let t=new yt;return a(this,G,Tb).call(this,t),t.toUint8Array()},cs=function(){return(g(this,ar)==null||!a(this,G,Zd).call(this))&&(a(this,G,Nn).call(this),A(this,ar,a(this,G,Ob).call(this)),a(this,G,Au).call(this)),g(this,ar)},Pb=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(ft(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)},Jd=function(){if(g(this,fs)==null||!a(this,G,Zd).call(this)){a(this,G,Nn).call(this);let t=new yt;a(this,G,Pb).call(this,t),A(this,fs,t.toUint8Array()),a(this,G,Au).call(this)}return g(this,fs)},Rb=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()}`)},Nb=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=an(s.sourceOutputIndex,`Input ${r} sourceOutputIndex`);an(s.sequence??4294967295,`Input ${r} sequence`);let c=sr(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,G,Eu).call(this,t)},_b=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))},Cb=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=ro(s,gn(d.satoshis,`Input ${c} source amount`),"Transaction input total");let h=f.id("hex");if(!r.scriptsOnly&&u.sourceTXID!==void 0&&sr(u.sourceTXID,`Input ${c} sourceTXID`)!==h)throw new Error(`Verification failed because input ${c} of transaction ${i()} does not reference its supplied source transaction.`);let l=r.scriptsOnly&&u.sourceTXID!==void 0?u.sourceTXID:f.id("hex");if(a(this,G,_b).call(this,f,l,r),u.sourceTXID??(u.sourceTXID=l),!e&&!new xa({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}},Eu=function(t){let e=0;for(let i=0;i<t.outputs.length;i++)e=ro(e,gn(t.outputs[i].satoshis,`Output ${i} amount`),"Transaction output total");return e},Bb=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")}`)},Lb=function(t,e,i){return i.scriptsOnly?i.verifiedTransactions.has(t):i.verifiedTxids.has(e())},or=function(t=!1){let e=new Map,i=[this];e.set(this,new pe(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 nr(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 qe([],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 pe(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 Ve([],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},ku=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||!jd(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)||!jd(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||!jd(c.lockingScript.toUint8Array(),u.lockingScript.toUint8Array()))return!1}return!0},Mb=async function(t,e,i){let{feeModel:r,memoryLimit:s,selectedVerifier:o,verifierQueue:c}=i;a(this,G,Nb).call(this,t,e),await this.verifyTransactionFee(t,r,e);let u={tx:t,blockHeight:T4,consensus:!0,...s===void 0?{}:{memoryLimit:s}},f=o!==void 0&&(s===void 0||o.supportsMemoryLimit===!0)&&(o.shouldVerifyScripts?.(u)??!0),d=l=>a(this,G,Cb).call(this,t,l,e,i),h=!f&&i.scriptWork!==void 0?i.scriptWork.work.inputs(i.scriptWork,u,d):d(f);return!h.valid||(f&&c.push(u),a(this,G,Eu).call(this,t)>h.inputTotal)?!1:(i.scriptsOnly?i.verifiedTransactions.add(t):i.verifiedTxids.add(e()),!0)},Ub=async function(t,e,i,r,s){let o=t==="scripts only",c=r??eu(),u=s!==void 0&&c!==void 0?mb(s,c):c;o||this.materializeSourceTXIDs();let f=new Set,d=new Set,h=[this],l=new Set;o||l.add(this.id("hex"));let m=new Set(h),b=[],y={scriptsOnly:o,memoryLimit:i,txQueue:h,queuedTransactions:m,queuedTxids:l,verifiedTransactions:d,verifiedTxids:f,feeModel:e,selectedVerifier:u,verifierQueue:b,scriptWork:s},S=0;for(;S<h.length;){let L=h[S++],T,k=()=>(T??(T=L.id("hex")),T);if(!a(this,G,Lb).call(this,L,k,y)&&!await a(this,G,Rb).call(this,L,o,t,k,d,f)&&!await a(this,G,Mb).call(this,L,k,y))return!1}return await a(this,G,Bb).call(this,b,u),!0},Db=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,G,Hb).call(this,f.tx,o,s,e,i,r);continue}a(this,G,$b).call(this,f.tx,t,c,u)}}return{bumps:e,txs:s}},Hb=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,G,Wb).call(this,t.merklePath,r,s,o)),e.add(c),i.push(u)},$b=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!")}},Wb=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},Fb=function(t,e,i){let r;if(t instanceof yt){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},qb=async function(t,e){let i={description:t,inputs:[],outputs:[],lockTime:this.lockTime,version:this.version};this.materializeSourceTXIDs();let r=new ss;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,G,Vb).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},Vb=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},z(pe,Qn);var Ke=pe;var Ii=class extends Error{constructor(e,i){super(`The ${e} parameter must be ${i??"valid."}`);w(this,"parameter");w(this,"code");w(this,"isError",!0);this.parameter=e,this.code=6,this.name=this.constructor.name}},ht=Ii;var Kb=globalThis.Buffer,Qd=typeof Kb?.compare=="function"?Kb.compare:void 0,Tu=globalThis.SharedArrayBuffer,P4=16*1024*1024,ur=class{constructor(){w(this,"cached")}get(t){let e=this.cached;if(!(e==null||!(t instanceof Uint8Array)||t.length!==e.bytes.length||Qd==null||Tu!=null&&t.buffer instanceof Tu||Qd(t,e.bytes)!==0))return e.value}set(t,e){t instanceof Uint8Array&&t.length<=P4&&Qd!=null&&!(Tu!=null&&t.buffer instanceof Tu)&&(this.cached={bytes:new Uint8Array(t),value:e})}};var ti="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",zb="0123456789abcdef";function cn(n){let t="";for(let e=0;e<n.length;e++){let i=n[e];t+=zb[i>>4]+zb[i&15]}return t}function oo(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 Xb(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+=ti[i>>2],t+=ti[(i&3)<<4|r>>4],t+=e+1<n.length?ti[(r&15)<<2|s>>6]:"=",t+=e+2<n.length?ti[s&63]:"="}return t}function Ou(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("==")&&(ti.indexOf(n[n.length-3])&15)!==0)throw new TypeError("Invalid canonical base64 string");if(n.endsWith("=")&&!n.endsWith("==")&&(ti.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=ti.indexOf(n[e]),r=ti.indexOf(n[e+1]),s=n[e+2]==="="?0:ti.indexOf(n[e+2]),o=n[e+3]==="="?0:ti.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 ei,fr,th=class{constructor(t){z(this,ei);w(this,"bytes");w(this,"pos",0);this.bytes=Uint8Array.from(t)}read(t){let e=a(this,ei,fr).call(this,t);return this.bytes.slice(e,this.pos)}readView(t){let e=a(this,ei,fr).call(this,t);return this.bytes.subarray(e,this.pos)}readReverse(t){return this.read(t).reverse()}readUInt8(){return this.bytes[a(this,ei,fr).call(this,1)]}readUInt16LE(){let t=a(this,ei,fr).call(this,2);return this.bytes[t]|this.bytes[t+1]<<8}readUInt32LE(){let t=a(this,ei,fr).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,ei,fr).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,ei,fr).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}};ei=new WeakSet,fr=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 R4=4294967295;function Pu(n,t){return Math.floor(n/2**t)}function N4(n){return n%2===0?n+1:n-1}function ls(n,t){return cn(ne(oo((n??"")+(t??"")).reverse()).reverse())}function eh(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=eh(n,u,f,i,r,s);if(d?.hash==null||d.hash===""){r.set(o,void 0);return}let h=eh(n,u,f+1,i,r,s);if(h?.hash==null){if(h?.duplicate===!0||n.length===1&&f===Pu(s,u))return c={offset:e,hash:ls(d.hash,d.hash)},r.set(o,c),c;r.set(o,void 0);return}return c={offset:e,hash:h.duplicate===!0?ls(d.hash,d.hash):ls(h.hash,d.hash)},r.set(o,c),c}function _4(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=Pu(o,f),h=`${f}:${d}`,l=r.get(h);if(l!==void 0){if(l!==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(h,u);let m=N4(d),b=eh(n,f,m,e,i,s);if(b==null){if(n.length===1&&d===Pu(s,f)){u=ls(u,u);continue}throw new Error(`Missing hash for index ${o} at height ${f}`)}b.duplicate===!0?u=ls(u,u):u=m%2===1?ls(b.hash,u):ls(u,b.hash)}return r.set(`${c}:0`,u),u}function C4(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 h=n.readVarInt(),l=n.readUInt8();e[u].push((l&1)===1?{offset:h,duplicate:!0}:{offset:h,hash:cn(n.read(32).reverse())})}e[u].sort((d,h)=>d.offset-h.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=Pu(R4,u);for(let h of e[u]){if(!Number.isSafeInteger(h.offset)||h.offset<0||h.offset>d)throw new Error("Invalid Merkle Path offset");if(f.has(h.offset))throw new Error("Duplicate Merkle Path offset");f.add(h.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=_4(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 jb(n){let t=n.pos,e=n.readUInt32LE(),i=n.readVarInt(),r=[],s=new Set;for(let h=0;h<i;h++){let l=cn(n.readReverse(32));s.add(l);let m=n.readUInt32LE(),b=n.readVarInt(),y=n.readView(b),S=n.readUInt32LE();r.push({sourceTXID:l,sourceOutputIndex:m,unlockingScript:y,sequence:S})}let o=n.readVarInt(),c=[];for(let h=0;h<o;h++){let l=n.readUInt64LE(),m=n.readVarInt();c.push({satoshis:l,lockingScript:n.readView(m)})}let u=n.readUInt32LE(),f=n.bytes.subarray(t,n.pos),d=cn(ne(f).reverse());return{txid:d,transaction:{txid:d,version:e,inputs:r,outputs:c,lockTime:u},inputTxids:Array.from(s),txidOnly:!1}}function B4(n,t){if(t===4022206466){let r=n.readUInt8();if(r===rn.TXID_ONLY)return{txid:cn(n.readReverse(32)),inputTxids:[],txidOnly:!0};let s=r===rn.RAWTX_AND_BUMP_INDEX?n.readVarInt():void 0;return{...jb(n),bumpIndex:s}}let e=jb(n),i=n.readUInt8()===0?void 0:n.readVarInt();return{...e,bumpIndex:i}}function Gb(n){let t=new th(n),e=t.readUInt32LE(),i;if(e===16843009&&(i=cn(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(C4(t));let o=t.readVarInt(),c=[];for(let u=0;u<o;u++)c.push(B4(t,e));if(!t.eof())throw new Error("Serialized BEEF contains trailing data");return{atomicTxid:i,bumps:s,entries:c}}function ao(n){let{atomicTxid:t,entries:e}=Gb(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 Fa(n,t=!1){let{atomicTxid:e,bumps:i,entries:r}=Gb(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 l of f.inputTxids){let m=s.get(l);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 h=s.get(f.sourceTXID)?.transaction?.outputs[f.sourceOutputIndex];h!==void 0&&(f.sourceSatoshis=h.satoshis)}return o.transaction}var co=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,L4=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;function M4(n,t){let e=1n;for(;t>0n;)(t&1n)!==0n&&(e=e*n%co),n=n*n%co,t>>=1n;return e}function Ru(n){if(!/^0[23][0-9a-f]{64}$/iu.test(n))return!1;let t=BigInt(`0x${n.slice(2)}`);if(t>=co)return!1;let e=(t*t*t+7n)%co,i=M4(e,co+1n>>2n);return i*i%co===e}function U4(n,t,e){let i=0n;for(let r=t;r<t+e;r++)i=i<<8n|BigInt(n[r]);return i}function uo(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=U4(n,t,i);if(s===0n||s>=L4)return!1;t+=i}return t===n.length}var lr=4294967295,nh=1e5,_n=1e3,Yb=100,Zb=32,Jb=new ur,Qb=new ur;function kt(n,t){throw new ht(n,t)}function xt(n,t){if(n==null||typeof n!="object"||Array.isArray(n))return kt(t,"a plain object");let e=Object.getPrototypeOf(n);if(e!==null&&e!==Object.prototype)return kt(t,"a plain object");let i=Reflect.ownKeys(n);if(i.length>nh)return kt(t,`an object with at most ${nh} properties`);for(let r of i){if(typeof r!="string"||Tn(r))return kt(t,"an object with safe string keys");let s=Object.getOwnPropertyDescriptor(n,r);if(s==null||!("value"in s))return kt(`${t}.${r}`,"a data property")}return n}function He(n,t,e=nh){if(n===void 0)return[];if(!Array.isArray(n))return kt(t,"an array");if(e!==void 0&&n.length>e)return kt(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 kt(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 kt(t,"a dense array");return n}function ey(n){let t=He(n,"sendWith",_n).map((e,i)=>hr(e,`sendWith[${i}]`,64,64));return new Set(t).size!==t.length?kt("sendWith","unique transaction IDs"):t}function ni(n,t,e,i=268435456){if(n instanceof Uint8Array)return n.length>i?kt(t,`at most ${i} bytes`):e!==void 0&&n.length!==e?kt(t,`exactly ${e} bytes`):n;if(!Array.isArray(n))return kt(t,"an array of bytes");if(n.length>i)return kt(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 kt(t,"a dense array of bytes");return e!==void 0&&n.length!==e?kt(t,`exactly ${e} bytes`):n}function lo(n,t,e){return n===void 0?e:typeof n!="boolean"?kt(t,"a boolean"):n}function Xe(n,t){let e=hr(n,t,66,66);return Ru(e)?e:kt(t,"a valid compressed secp256k1 public key")}function ih(n,t){return n==="self"||n==="anyone"?n:Xe(n,t)}function rh(n,t="protocolID"){if(!Array.isArray(n)||n.length!==2)return kt(t,"a [securityLevel, protocolName] tuple");let e=le(n[0],`${t}[0]`,void 0,0,2),i=ge(n[1],`${t}[1]`,5,400);return[e,i]}function dr(n,t=!0){let e=lo(n.privileged,"privileged",!1),i=hs(n.privilegedReason,"privilegedReason",5,50);e&&i===void 0&&kt("privilegedReason","a value when 'privileged' is true"),t&&lo(n.seekPermission,"seekPermission",!0)}function ds(n,t="args"){let e=xt(n,t);rh(e.protocolID),ge(e.keyID,"keyID",1,800),e.counterparty!==void 0&&ih(e.counterparty,"counterparty"),dr(e)}function ny(n){let t=Mu(n,"outpoint"),[e,i]=t.split(".");return{txid:e,vout:Number(i)}}function vi(n,t="value"){return lo(n,t,!0)}function Ee(n,t="value"){return lo(n,t,!1)}function hs(n,t,e,i){if(n!==void 0)return ge(n,t,e,i)}function D4(n,t,e){if(n===void 0||!Number.isSafeInteger(n)||n<0||n>21e14)throw new ht(t,"a valid number of satoshis");if(e!==void 0&&n<e)throw new ht(t,`at least ${e} satoshis.`);return n}function le(n,t,e,i,r){if(n===void 0){if(e!==void 0)return e;throw new ht(t,"a valid integer")}if(!Number.isSafeInteger(n))throw new ht(t,"a safe integer");if(n=Number(n),i!==void 0&&n<i)throw new ht(t,`at least ${i} length.`);if(r!==void 0&&n>r)throw new ht(t,`no more than ${r} length.`);return n}function H4(n,t){return le(n,t,0,0)}function ge(n,t,e,i){if(typeof n!="string")throw new ht(t,"a string");let r=Pe(n).length;if(e!==void 0&&r<e)throw new ht(t,`at least ${e} length.`);if(i!==void 0&&r>i)throw new ht(t,`no more than ${i} length.`);return n}function $4(n){if(n!==void 0)return Nu(n)}function Nu(n){return ah(n,"basket",1,300)}function sh(n){return ah(n,"label",1,300)}function oh(n){return ah(n,"tag",1,300)}function ah(n,t,e,i){if(typeof n!="string")throw new ht(t,"a string");n=n.trim().toLowerCase();let r=Pe(n).length;if(e!==void 0&&r<e)throw new ht(t,`at least ${e} length.`);if(i!==void 0&&r>i)throw new ht(t,`no more than ${i} length.`);return n}function ty(n,t,e,i){if(n!==void 0)return mn(n,t,e,i)}function fo(n){throw new ht(n,"valid base64 string")}function W4(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)&&fo(t),e++)}return e}function F4(n,t,e){t>2&&fo(e),t>0&&n.length%4!==0&&fo(e);let i=n.length%4;i!==0&&i!==4-t&&fo(e)}function q4(n,t,e,i){if(e!==void 0&&n<e)throw new ht(t,`at least ${e} bytes`);if(i!==void 0&&n>i)throw new ht(t,`no more than ${i} bytes`)}function mn(n,t,e,i){typeof n!="string"&&fo(t),n=n.trim(),n.length===0&&fo(t);let r=W4(n,t);F4(n,r,t);let s=n.length-r,o=Math.floor(s*3/4);return q4(o,t,e,i),n}function V4(n,t,e,i){if(n!==void 0)return hr(n,t,e,i)}var K4=/^[0-9a-f]+$/,z4=/^[0-9A-Fa-f]+$/;function hr(n,t,e,i){if(typeof n!="string")throw new ht(t,"a hexadecimal string");if(n=n.trim(),n.length%2===1)throw new ht(t,`even length, not ${n.length}.`);let r=K4.test(n);if(!r&&!z4.test(n))throw new ht(t,"hexadecimal string.");if(e!==void 0&&n.length<e)throw new ht(t,`at least ${e} length.`);if(i!==void 0&&n.length>i)throw new ht(t,`no more than ${i} length.`);return r?n:n.toLowerCase()}function iy(n,t){let e=hr(n,t);return uo(oo(e))?e:kt(t,"a canonical DER-encoded ECDSA signature")}function X4(n){if(xt(n,"input"),n.unlockingScript===void 0&&n.unlockingScriptLength===void 0)throw new ht("unlockingScript, unlockingScriptLength","at least one valid value.");let t=V4(n.unlockingScript,"unlockingScript"),e=n.unlockingScriptLength??(t==null?0:t.length/2);if(le(e,"unlockingScriptLength",void 0,0),t&&e!==t.length/2)throw new ht("unlockingScriptLength","length unlockingScript if both valid.");return{outpoint:ny(n.outpoint),inputDescription:ge(n.inputDescription,"inputDescription",5,2e3),unlockingScript:t,unlockingScriptLength:e,sequenceNumber:le(n.sequenceNumber,"sequenceNumber",lr,0,lr)}}function j4(n){return xt(n,"output"),{lockingScript:hr(n.lockingScript,"lockingScript"),satoshis:D4(n.satoshis,"satoshis"),outputDescription:ge(n.outputDescription,"outputDescription",5,2e3),basket:$4(n.basket),customInstructions:hs(n.customInstructions,"customInstructions"),tags:He(n.tags,"tags").map(e=>oh(e))}}function G4(n){n!==void 0&&xt(n,"options");let t=n??{};return t.trustSelf!==void 0&&t.trustSelf!=="known"&&kt("trustSelf","undefined or 'known'"),{signAndProcess:vi(t.signAndProcess,"signAndProcess"),acceptDelayedBroadcast:vi(t.acceptDelayedBroadcast,"acceptDelayedBroadcast"),trustSelf:t.trustSelf,knownTxids:He(t.knownTxids,"knownTxids").map(i=>hr(i,"knownTxids",64,64)),returnTXIDOnly:Ee(t.returnTXIDOnly,"returnTXIDOnly"),noSend:Ee(t.noSend,"noSend"),noSendChange:He(t.noSendChange,"noSendChange").map(i=>ny(i)),sendWith:ey(t.sendWith),randomizeOutputs:vi(t.randomizeOutputs,"randomizeOutputs")}}function _u(n,t){xt(n,"args");let e={description:ge(n.description,"description",5,2e3),inputBEEF:n.inputBEEF===void 0?void 0:ni(n.inputBEEF,"inputBEEF"),inputs:He(n.inputs,"inputs").map(r=>X4(r)),outputs:He(n.outputs,"outputs").map(r=>j4(r)),lockTime:le(n.lockTime,"lockTime",0,0,lr),version:le(n.version,"version",1,0,lr),labels:He(n.labels,"labels").map(r=>sh(r)),options:G4(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&&Jb.get(e.inputBEEF)!==!0)try{ao(e.inputBEEF),Jb.set(e.inputBEEF,!0)}catch{throw new ht("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)&&kt("inputs","unique input outpoints"),i.add(s)}return e.isTestWerrReviewActions=e.labels.includes(s8),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>=_n&&kt("sendWith",`at most ${_n-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 Y4(n){n!==void 0&&xt(n,"options");let t=n??{};return{acceptDelayedBroadcast:vi(t.acceptDelayedBroadcast,"acceptDelayedBroadcast"),returnTXIDOnly:Ee(t.returnTXIDOnly,"returnTXIDOnly"),noSend:Ee(t.noSend,"noSend"),sendWith:ey(t.sendWith)}}function Cu(n){xt(n,"args");let t=xt(n.spends,"spends"),e=Object.create(null);for(let[r,s]of Object.entries(t)){/^(?:0|[1-9]\d*)$/.test(r)||kt("spends key","a canonical input index");let o=le(Number(r),"spends key",void 0,0,lr),c=xt(s,`spends.${r}`);e[o]={unlockingScript:hr(c.unlockingScript,`spends.${r}.unlockingScript`),sequenceNumber:c.sequenceNumber===void 0?void 0:le(c.sequenceNumber,`spends.${r}.sequenceNumber`,void 0,0,lr)}}let i={spends:e,reference:mn(n.reference,"reference"),options:Y4(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>=_n&&kt("sendWith",`at most ${_n-1} transaction IDs when the signed transaction joins the broadcast set`),i.isDelayed=i.options.acceptDelayedBroadcast,i.isNoSend=i.options.noSend,i}function Bu(n){return xt(n,"args"),{reference:mn(n.reference,"reference")}}function Z4(n){return n===void 0?void 0:(xt(n,"paymentRemittance"),{derivationPrefix:mn(n.derivationPrefix,"derivationPrefix"),derivationSuffix:mn(n.derivationSuffix,"derivationSuffix"),senderIdentityKey:Xe(n.senderIdentityKey,"senderIdentityKey")})}function J4(n){return n===void 0?void 0:(xt(n,"insertionRemittance"),{basket:Nu(n.basket),customInstructions:hs(n.customInstructions,"customInstructions",0,1e3),tags:He(n.tags,"tags").map(e=>oh(e))})}function Q4(n){if(xt(n,"output"),n.protocol!=="basket insertion"&&n.protocol!=="wallet payment")throw new ht("protocol","'basket insertion' or 'wallet payment'");return n.protocol==="wallet payment"?(n.paymentRemittance===void 0||n.insertionRemittance!==void 0)&&kt("output remittance","only paymentRemittance for wallet payment"):(n.insertionRemittance===void 0||n.paymentRemittance!==void 0)&&kt("output remittance","only insertionRemittance for basket insertion"),{outputIndex:H4(n.outputIndex,"outputIndex"),protocol:n.protocol,paymentRemittance:Z4(n.paymentRemittance),insertionRemittance:J4(n.insertionRemittance)}}function Ai(n){if(n===void 0)return;n=n.trim().toLowerCase(),ge(n,"originator",1,250);let t=n.lastIndexOf(":"),e=n;if(t!==-1){if(n.indexOf(":")!==t)throw new ht("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 ht("originator","a canonical DNS hostname with an optional port");e=n.slice(0,t)}ge(e,"originator hostname",1,250);let i=e.split(".");for(let r of i)if(ge(r,"originator part",1,63),!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(r))throw new ht("originator","a canonical DNS hostname with an optional port");return e}function Lu(n){xt(n,"args");let t={tx:ni(n.tx,"tx"),outputs:He(n.outputs,"outputs").map(e=>Q4(e)),description:ge(n.description,"description",5,2e3),labels:He(n.labels,"labels").map(e=>sh(e)),seekPermission:vi(n.seekPermission,"seekPermission")};if(Qb.get(t.tx)!==!0)try{Fa(t.tx),Qb.set(t.tx,!0)}catch{throw new ht("tx","a complete, exactly framed Atomic BEEF transaction")}if(t.outputs.length<1)throw new ht("outputs","at least one output to internalize from the transaction");return t}function t8(n,t){if(n!==void 0)return Mu(n,t)}function Mu(n,t){if(typeof n!="string")throw new ht(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 ht(t,"a 32-byte txid and canonical numeric output index joined with '.'");let i=hr(e[1],`${t} txid`,64,64),r=le(Number(e[2]),`${t} vout`,void 0,0,lr);return`${i}.${r}`}function Uu(n){return xt(n,"args"),{basket:Nu(n.basket),output:Mu(n.output,"output")}}function Du(n){return xt(n,"args"),{type:mn(n.type,"type",32,32),serialNumber:mn(n.serialNumber,"serialNumber",32,32),certifier:Xe(n.certifier,"certifier")}}function Hu(n){return xt(n,"args"),dr(n,!1),{certifiers:He(n.certifiers,"certifiers").map(e=>Xe(e,"certifiers")),types:He(n.types,"types").map(e=>mn(e,"types",32,32)),limit:le(n.limit,"limit",10,1,1e4),offset:le(n.offset,"offset",0,0),privileged:Ee(n.privileged,"privileged"),privilegedReason:hs(n.privilegedReason,"privilegedReason",5,50),partial:void 0}}function ch(n){let t=xt(n,"fields");for(let e of Object.keys(t))ge(e,"field name",1,50),ge(t[e],`fields.${e}`);return n}function e8(n,t){return n==="certifier"?n:Xe(n,t)}function n8(n,t){let e=xt(n,t);for(let i of Object.keys(e))ge(i,`${t} field name`,1,50),mn(e[i],`${t} field value`);return n}function $u(n){if(xt(n,"args"),dr(n,!1),n.acquisitionProtocol!=="issuance")throw new Error("Only acquire certificate via issuance requests allowed here.");if(n.serialNumber)throw new ht("serialNumber",'valid when acquisitionProtocol is "direct"');if(n.signature)throw new ht("signature",'valid when acquisitionProtocol is "direct"');if(n.revocationOutpoint)throw new ht("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(n.keyringRevealer)throw new ht("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(n.keyringForSubject!=null)throw new ht("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!n.certifierUrl)throw new ht("certifierUrl",'valid when acquisitionProtocol is "issuance"');return{type:mn(n.type,"type",32,32),certifier:Xe(n.certifier,"certifier"),certifierUrl:i8(n.certifierUrl),fields:ch(n.fields),privileged:Ee(n.privileged,"privileged"),privilegedReason:hs(n.privilegedReason,"privilegedReason",5,50),subject:""}}function i8(n){let t=ge(n,"certifierUrl",1,2048);if(t!==t.trim())throw new ht("certifierUrl","an exact HTTPS URL without whitespace");let e;try{e=new URL(t)}catch{throw new ht("certifierUrl","an absolute HTTPS URL")}if(e.protocol!=="https:")throw new ht("certifierUrl","an HTTPS URL");if(e.username!==""||e.password!=="")throw new ht("certifierUrl","a URL without credentials");if(e.search!==""||e.hash!=="")throw new ht("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 ht("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 ht("certifierUrl","a public DNS hostname");return t.replace(/\/+$/,"")}function Wu(n){if(xt(n,"args"),dr(n,!1),n.acquisitionProtocol!=="direct")throw new Error("Only acquire direct certificate requests allowed here.");if(!n.serialNumber)throw new ht("serialNumber",'valid when acquisitionProtocol is "direct"');if(!n.signature)throw new ht("signature",'valid when acquisitionProtocol is "direct"');if(!n.revocationOutpoint)throw new ht("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!n.keyringRevealer)throw new ht("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(n.keyringForSubject==null)throw new ht("keyringForSubject",'valid when acquisitionProtocol is "direct"');return{type:mn(n.type,"type",32,32),serialNumber:mn(n.serialNumber,"serialNumber",32,32),certifier:Xe(n.certifier,"certifier"),revocationOutpoint:Mu(n.revocationOutpoint,"revocationOutpoint"),fields:ch(n.fields),signature:iy(n.signature,"signature"),keyringRevealer:e8(n.keyringRevealer,"keyringRevealer"),keyringForSubject:n8(n.keyringForSubject,"keyringForSubject"),privileged:Ee(n.privileged,"privileged"),privilegedReason:hs(n.privilegedReason,"privilegedReason",5,50),subject:""}}function Fu(n){xt(n,"args"),xt(n.certificate,"certificate"),dr(n,!1),n.certificate.fields!==void 0&&ch(n.certificate.fields);let t={type:ty(n.certificate.type,"certificate.type",32,32),serialNumber:ty(n.certificate.serialNumber,"certificate.serialNumber",32,32),certifier:n.certificate.certifier===void 0?void 0:Xe(n.certificate.certifier,"certificate.certifier"),subject:n.certificate.subject===void 0?void 0:Xe(n.certificate.subject,"certificate.subject"),revocationOutpoint:t8(n.certificate.revocationOutpoint,"certificate.revocationOutpoint"),signature:n.certificate.signature===void 0?void 0:iy(n.certificate.signature,"certificate.signature"),fieldsToReveal:He(n.fieldsToReveal,"fieldsToReveal").map(e=>ge(e,`fieldsToReveal ${e}`,1,50)),verifier:Xe(n.verifier,"verifier"),privileged:Ee(n.privileged,"privileged"),privilegedReason:hs(n.privilegedReason,"privilegedReason",5,50)};return t.fieldsToReveal.length>Yb&&kt("fieldsToReveal",`at most ${Yb} fields`),new Set(t.fieldsToReveal).size!==t.fieldsToReveal.length&&kt("fieldsToReveal","unique field names"),t}function qu(n){return xt(n,"args"),{identityKey:Xe(n.identityKey,"identityKey"),limit:le(n.limit,"limit",10,1,1e4),offset:le(n.offset,"offset",0,0),seekPermission:vi(n.seekPermission,"seekPermission")}}function r8(n){let t=xt(n,"attributes"),e=Object.keys(t);(e.length<1||e.length>Zb)&&kt("attributes",`an object containing 1-${Zb} fields`);for(let i of e)ge(i,`field name ${i}`,1,50),ge(t[i],`attributes.${i}`,1,500);return n}function Vu(n){return xt(n,"args"),{attributes:r8(n.attributes),limit:le(n.limit,"limit",10,1,1e4),offset:le(n.offset,"offset",0,0),seekPermission:vi(n.seekPermission,"seekPermission")}}function Ku(n){xt(n,"args");let t;if(n.tagQueryMode===void 0||n.tagQueryMode==="any")t="any";else if(n.tagQueryMode==="all")t="all";else throw new ht("tagQueryMode","undefined, 'any', or 'all'");return n.include!==void 0&&n.include!=="locking scripts"&&n.include!=="entire transactions"&&kt("include","undefined, 'locking scripts', or 'entire transactions'"),{basket:Nu(n.basket),tags:He(n.tags,"tags").map(i=>oh(i)),tagQueryMode:t,includeLockingScripts:n.include==="locking scripts",includeTransactions:n.include==="entire transactions",includeCustomInstructions:Ee(n.includeCustomInstructions,"includeCustomInstructions"),includeTags:Ee(n.includeTags,"includeTags"),includeLabels:Ee(n.includeLabels,"includeLabels"),limit:le(n.limit,"limit",10,1,1e4),offset:le(n.offset,"offset",0),seekPermission:vi(n.seekPermission,"seekPermission"),knownTxids:[]}}function zu(n){xt(n,"args");let t;if(n.labelQueryMode===void 0||n.labelQueryMode==="any")t="any";else if(n.labelQueryMode==="all")t="all";else throw new ht("labelQueryMode","undefined, 'any', or 'all'");return{labels:He(n.labels,"labels").map(i=>sh(i)),labelQueryMode:t,includeLabels:Ee(n.includeLabels,"includeLabels"),includeInputs:Ee(n.includeInputs,"includeInputs"),includeInputSourceLockingScripts:Ee(n.includeInputSourceLockingScripts,"includeInputSourceLockingScripts"),includeInputUnlockingScripts:Ee(n.includeInputUnlockingScripts,"includeInputUnlockingScripts"),includeOutputs:Ee(n.includeOutputs,"includeOutputs"),includeOutputLockingScripts:Ee(n.includeOutputLockingScripts,"includeOutputLockingScripts"),limit:le(n.limit,"limit",10,1,1e4),offset:le(n.offset,"offset",0,0),seekPermission:vi(n.seekPermission,"seekPermission")}}function Xu(n){let t=xt(n,"args");if(t.identityKey!==void 0&&t.identityKey!==!0&&kt("identityKey","true or undefined"),t.forSelf!==void 0&&lo(t.forSelf,"forSelf",!1),t.identityKey===!0){t.protocolID!==void 0&&rh(t.protocolID),t.keyID!==void 0&&ge(t.keyID,"keyID",1,800),t.counterparty!==void 0&&ih(t.counterparty,"counterparty"),dr(t);return}ds(n,"args")}function ju(n){let t=xt(n,"args");Xe(t.counterparty,"counterparty"),Xe(t.verifier,"verifier"),dr(t,!1)}function Gu(n){let t=xt(n,"args");ih(t.counterparty,"counterparty"),Xe(t.verifier,"verifier"),rh(t.protocolID),ge(t.keyID,"keyID",1,800),dr(t,!1)}function Yu(n){let t=xt(n,"args");ds(n),ni(t.plaintext,"plaintext")}function Zu(n){let t=xt(n,"args");ds(n),ni(t.ciphertext,"ciphertext")}function Ju(n){let t=xt(n,"args");ds(n),ni(t.data,"data")}function Qu(n){let t=xt(n,"args");ds(n),ni(t.data,"data"),ni(t.hmac,"hmac",32)}function ry(n,t,e){let i=n[t]!==void 0,r=n[e]!==void 0;i===r&&kt(`${t}, ${e}`,"exactly one value"),i&&ni(n[t],t),r&&ni(n[e],e,32)}function tf(n){let t=xt(n,"args");ds(n),ry(t,"data","hashToDirectlySign")}function ef(n){let t=xt(n,"args");ds(n),ry(t,"data","hashToDirectlyVerify");let e=ni(t.signature,"signature",void 0,72);uo(e)||kt("signature","a canonical DER-encoded ECDSA signature"),t.forSelf!==void 0&&lo(t.forSelf,"forSelf",!1)}function nf(n){let t=xt(n,"args");le(t.height,"height",void 0,1,lr)}function pr(n,t="args"){xt(n,t)}var s8="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";var rf;(function(n){n[n.Silent=0]="Silent",n[n.App=1]="App",n[n.Counterparty=2]="Counterparty"})(rf||(rf={}));var o8=Object.prototype.hasOwnProperty,a8=new Set(["BEEF","atomicBEEF","beef","ciphertext","competingBeef","data","encryptedLinkage","encryptedLinkageProof","hashToDirectlySign","hashToDirectlyVerify","hmac","inputBEEF","payload","plaintext","signature","transaction","tx"]);function sf(n){return n==null||typeof n!="object"||typeof ArrayBuffer>"u"?!1:ArrayBuffer.isView(n)&&Object.prototype.toString.call(n)==="[object Uint8Array]"}function sy(n){return Number.isInteger(n)&&n>=0&&n<=255}function c8(n){return n!=null&&typeof n=="object"&&typeof ArrayBuffer<"u"&&(ArrayBuffer.isView(n)||Object.prototype.toString.call(n)==="[object ArrayBuffer]")}function u8(n){for(let t=0;t<n.length;t++)if(!o8.call(n,t)||!sy(n[t]))return;return n}function f8(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(!sy(r))return;e.push(r)}return e}catch{return}}function uh(n){if(sf(n))return n;if(!c8(n))return Array.isArray(n)?u8(n):f8(n)}function l8(n,t){let e=this==null?void 0:this[n];return sf(e)?Array.from(e):sf(t)?Array.from(t):t}function ho(n,t){let e=JSON.stringify(n,l8,t);if(e===void 0)throw new TypeError("BRC-100 JSON payload is not serializable");return e}function d8(n,t,e,i){let r=uh(e);r!=null?n[t]=r:i(e)}function of(n){let t=new WeakSet,e=[n];for(;e.length>0;){let i=e.pop();if(!(i==null||typeof i!="object"||sf(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))a8.has(r)?d8(i,r,s,o=>e.push(o)):e.push(s)}}return n}var h8=Number,p8=String,g8=Uint8Array,m8=URL,b8=Array.prototype,y8=Array.isArray,w8=Date.parse,x8=Number.MAX_SAFE_INTEGER,S8=Number.isFinite,uf=Number.isInteger,gs=Number.isSafeInteger,vy=Object.prototype,I8=Object.prototype.hasOwnProperty,gr=Object.create,ff=Object.defineProperty,Ay=Object.freeze,Te=Object.getOwnPropertyDescriptor,lf=Object.getPrototypeOf,Bn=Object.keys,bs=Reflect.ownKeys,v8=RegExp.prototype.exec,A8=RegExp.prototype.test,Ey=String.prototype.split,E8=String.prototype.toLowerCase,k8=String.prototype.trim,mh=String.prototype.replace,T8=String.prototype.normalize,O8=String.prototype.indexOf,P8=String.prototype.slice,R8=String.prototype.startsWith,N8=RegExp,oy=Te(URL.prototype,"protocol")?.get,bh=lf(Uint8Array.prototype),ay=Te(bh,"buffer")?.get,cy=Te(bh,"length")?.get,uy=Te(bh,Symbol.toStringTag)?.get,_8=Uint8Array.prototype.set,fy=typeof SharedArrayBuffer>"u"?void 0:Te(SharedArrayBuffer.prototype,"byteLength")?.get,ly=Map,yn=Set,dy=WeakMap,C8=WeakSet,B8=Map.prototype.get,L8=Map.prototype.set,M8=Map.prototype.has,U8=Map.prototype.forEach,D8=Set.prototype.add,H8=Set.prototype.has,$8=Te(Set.prototype,"size").get,W8=WeakMap.prototype.get,F8=WeakMap.prototype.set,q8=WeakSet.prototype.add,V8=WeakSet.prototype.has,Ut=Reflect.apply;function Yt(n){return y8(n)}function Cn(n){return h8(n)}function $e(n){return p8(n)}function re(n){return Ut(E8,n,[])}function yh(n,t){return Ut(Ey,n,[t])}function go(n,t){return Ut(A8,n,[t])}function ms(n,t){return Ut(v8,n,[t])}function df(n,t){return Ut(I8,n,[t])}function za(n){if(!(ay==null||cy==null||uy==null))try{return{buffer:Ut(ay,n,[]),length:Ut(cy,n,[]),tag:Ut(uy,n,[])}}catch{return}}function hh(n){return za(n)?.tag==="Uint8Array"}function K8(n){if(fy==null)return!1;try{return Ut(fy,n,[]),!0}catch{return!1}}function ps(n,t){return Ut(B8,n,[t])}function fh(n,t,e){Ut(L8,n,[t,e])}function z8(n,t){return Ut(M8,n,[t])}function X8(n,t){Ut(U8,n,[t])}function se(n,t){Ut(D8,n,[t])}function wn(n,t){return Ut(H8,n,[t])}function hf(n){return Ut($8,n,[])}function hy(n,t){return Ut(W8,n,[t])}function qa(n,t,e){Ut(F8,n,[t,e])}function lh(n,t){Ut(q8,n,[t])}function py(n,t){return Ut(V8,n,[t])}var ki=new yn;se(ki,"completed");se(ki,"unprocessed");se(ki,"sending");se(ki,"unproven");se(ki,"unsigned");se(ki,"nosend");se(ki,"nonfinal");se(ki,"failed");var mf=new yn;se(mf,"unproven");se(mf,"sending");se(mf,"failed");var po=1e6,gy=po+2,j8=16*1024*1024,G8="0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",my=new ur,wh=Symbol("createActionSourceEvidence"),Xa=Symbol("byteBudgetExceeded"),Va=new C8,pf=Ay(gr(null));function ky(n){if(!Yt(n))return;let t=Te(n,"length");if(t==null||!("value"in t)||!gs(t.value)||t.value<0||t.value>po)throw new Error("Wallet request arrays must have a bounded own length");let e=t.value;if(bs(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=Te(n,$e(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 by(n){let t=Nt(n);if(t==null)return;let e=gr(null),i=bs(t);for(let r=0;r<i.length;r++){let s=i[r];if(typeof s!="string")continue;let o=Te(t,s);o!=null&&"value"in o&&(e[s]=o.value)}return e}function un(n,t,e=[]){let i=gr(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?ky(n[s]):n[s]}return i}function Ty(n){let t=Nt(n);if(t==null)return pf;let e=Te(t,wh)?.value;if(e!=null)return e;let i=t.inputBEEF,r=t.inputs;if(i===void 0||!Yt(r)||r.length===0)return pf;let s=Ei(i,"createAction","request.inputBEEF"),o;try{o=ao(s)}catch{$("createAction","request.inputBEEF","an exactly framed BEEF envelope")}let c=gr(null);for(let u=0;u<r.length;u++){let f=r[u],d=Nt(f);if(d==null||typeof d.outpoint!="string")continue;let h=ms(/^([0-9a-fA-F]{64})\.(0|[1-9]\d*)$/,d.outpoint);if(h==null)continue;let l=Cn(h[2]);if(l>4294967295)continue;let m=re(h[1]),b=ps(o.transactions,m)?.outputs[l];b!==void 0&&(c[`${m}.${l}`]=b.satoshis)}return Ay(c)}function St(n,t){let e=Nt(t);if(e==null)return t;let i=Nt(e.options);switch(n){case"createAction":{let r={inputs:Yt(e.inputs)?(()=>{let s=[];s.length=e.inputs.length;for(let o=0;o<e.inputs.length;o++){let c=e.inputs[o],u=Nt(c);s[o]=u==null?c:un(u,["outpoint","unlockingScript","sequenceNumber"])}return s})():e.inputs,outputs:Yt(e.outputs)?(()=>{let s=[];s.length=e.outputs.length;for(let o=0;o<e.outputs.length;o++){let c=e.outputs[o],u=Nt(c);s[o]=u==null?c:un(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}:un(i,["signAndProcess","returnTXIDOnly","sendWith","randomizeOutputs","knownTxids"],["sendWith","knownTxids"])};return ff(r,wh,{value:Ty(e),writable:!1,configurable:!1,enumerable:!1}),r}case"signAction":{let r=Nt(e.spends),s=gr(null);if(r!=null){let o=Bn(r);for(let c=0;c<o.length;c++){let u=o[c],f=r[u],d=Nt(f);s[u]=d==null?f:un(d,["unlockingScript","sequenceNumber"])}}return{spends:s,options:i==null?{returnTXIDOnly:void 0,sendWith:void 0}:un(i,["returnTXIDOnly","sendWith"],["sendWith"])}}case"listActions":return un(e,["labels","labelQueryMode","includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts","limit"],["labels"]);case"listOutputs":return un(e,["basket","tags","tagQueryMode","include","includeCustomInstructions","includeTags","includeLabels","limit"],["tags"]);case"listCertificates":return un(e,["limit","certifiers","types"],["certifiers","types"]);case"discoverByIdentityKey":return un(e,["limit","identityKey"]);case"discoverByAttributes":{let r=Nt(e.attributes);return{limit:e.limit,attributes:r==null?e.attributes:{...r}}}case"revealCounterpartyKeyLinkage":return un(e,["verifier","counterparty"]);case"revealSpecificKeyLinkage":return un(e,["verifier","counterparty","protocolID","keyID"],["protocolID"]);case"acquireCertificate":return{...un(e,["acquisitionProtocol","type","certifier","serialNumber","revocationOutpoint","signature"]),fields:by(e.fields)};case"proveCertificate":return{fieldsToReveal:ky(e.fieldsToReveal),verifier:e.verifier,certificate:(()=>{let r=Nt(e.certificate);return r==null?e.certificate:{...un(r,["type","serialNumber","subject","certifier","revocationOutpoint","signature"]),fields:by(r.fields)}})()};default:return t}}function $(n,t,e){throw new Error(`Invalid ${n} result ${t}: expected ${e}`)}function Oy(n){let t=Te(n,"length");return t!=null&&"value"in t&&gs(t.value)&&t.value>=0?t.value:void 0}function Py(n,t,e,i=e){if(t>e)return;let r=bs(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"||!uf(Cn(c))||Cn(c)<0||Cn(c)>=t||$e(Cn(c))!==c))return}let s=t<=i?[]:void 0;s!==void 0&&(s.length=t);for(let o=0;o<t;o++){let c=Te(n,$e(o));if(c==null||c.enumerable!==!0||!("value"in c)||!uf(c.value)||c.value<0||c.value>255)return;s!==void 0&&(s[o]=c.value)}return s??Xa}function Y8(n,t,e){let i=lf(n);if(i!==vy&&i!==null)return;let r=bs(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!==$e(o))return;let u=Te(n,c);if(u==null||u.enumerable!==!0||!("value"in u)||!uf(u.value)||u.value<0||u.value>255)return;s!==void 0&&(s[o]=u.value)}return s??Xa}function Z8(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 Ry(n,t,e){let i=za(n);i?.tag!=="Uint8Array"&&$(t,"byte array","an intrinsic Uint8Array");let{buffer:r,length:s}=i;K8(r)&&$(t,"byte array","an unshared Uint8Array"),s>268435456&&$(t,"byte array",`at most ${268435456} bytes`),s>e&&$(t,"byte arrays",`at most ${268435456} total bytes`);let o=new g8(s);try{Ut(_8,o,[n])}catch{$(t,"byte array","an intrinsic Uint8Array")}return o}function xh(n,t,e=!1){let i=[],r=new dy,s=new dy,o=0,c=0,u=(d,h)=>{if(d==null||typeof d!="object")return typeof d=="function"&&$(t,"value","data without functions"),d;if(!Yt(d)&&!hh(d)&&e&&Z8(h)){let y=hy(s,d);if(y!==void 0)return y;let S=Y8(d,268435456,268435456-c);if(S===Xa&&$(t,"byte arrays",`at most ${268435456} total bytes`),S!==void 0)return o++,o>po&&$(t,"object graph","a bounded result"),S.length>268435456-c&&$(t,"byte arrays",`at most ${268435456} total bytes`),c+=S.length,lh(Va,S),qa(s,d,S),S}let l=hy(r,d);if(l!==void 0)return l;if(o++,o>po&&$(t,"object graph","a bounded result"),hh(d)){let y=Ry(d,t,268435456-c);return c+=za(y).length,lh(Va,y),qa(r,d,y),y}if(Yt(d)){lf(d)!==b8&&$(t,"array prototype","the intrinsic Array.prototype");let S=Oy(d);S===void 0&&$(t,"array length","an own integer data property");let L=Py(d,S,268435456,268435456-c);if(L===Xa&&$(t,"byte arrays",`at most ${268435456} total bytes`),L!==void 0)return c+=L.length,lh(Va,L),qa(r,d,L),L;S>po&&$(t,"array length",`at most ${po} entries`);let T=[];return T.length=S,qa(r,d,T),i[i.length]={source:d,target:T,array:!0},T}let m=lf(d);m!==null&&m!==vy&&$(t,"object prototype","Object.prototype or null");let b=m===null?gr(null):{};return qa(r,d,b),i[i.length]={source:d,target:b,array:!1},b},f=u(n);for(;i.length>0;){let d=i[i.length-1];i.length-=1;let h=bs(d.source);if(d.array){o+=h.length,o>gy&&$(t,"object graph","a bounded result");let l=d.source,m=d.target.length;h.length!==m+1&&$(t,"array shape","a dense standard array without extra properties");for(let b=0;b<h.length;b++){let y=h[b];if(typeof y!="string"&&$(t,"array key","a string"),Tn(y)&&$(t,`array key ${y}`,"a safe array key"),y!=="length"){let L=Cn(y);(!uf(L)||L<0||L>=m||$e(L)!==y)&&$(t,`array key ${y}`,"a canonical in-range array index")}let S=Te(l,y);(S==null||!("value"in S))&&$(t,`array property ${y}`,"a data property"),y!=="length"&&ff(d.target,y,{value:u(S.value),enumerable:S.enumerable,configurable:!0,writable:!0})}continue}o+=h.length,o>gy&&$(t,"object graph","a bounded result");for(let l=0;l<h.length;l++){let m=h[l];typeof m!="string"&&$(t,"object key","a string"),Tn(m)&&$(t,`object key ${m}`,"a safe record key");let b=Te(d.source,m);(b==null||!("value"in b))&&$(t,`object property ${m}`,"a data property"),ff(d.target,m,{value:u(b.value,m),enumerable:b.enumerable,configurable:!0,writable:!0})}}return f}function Ny(n,t){return xh(n,t)}function _y(n,t){return xh(n,t,!0)}function Ge(n,t,e="value"){(n==null||typeof n!="object"||Yt(n))&&$(t,e,"an object");let i=gr(null),r=bs(n);for(let s=0;s<r.length;s++){let o=r[s];typeof o!="string"&&$(t,`${e} key`,"a string");let c=Te(n,o);(c==null||!("value"in c))&&$(t,`${e}.${o}`,"a data property"),i[o]=c.value}return i}function Ei(n,t,e,i,r=268435456){let s;if(n!=null&&typeof n=="object"&&hh(n)){let c=py(Va,n)?n:Ry(n,t,268435456);za(c).length<=r&&(s=c)}else if(Yt(n)){let c=Oy(n);if(c===void 0&&$(t,e,"an own integer array length"),c>r&&$(t,e,`at most ${r} bytes`),py(Va,n))s=n;else{let u=Py(n,c,r);u===Xa&&$(t,e,`at most ${r} bytes`),s=u}}s==null&&$(t,e,"an array of bytes");let o=Yt(s)?s.length:za(s).length;return o>r&&$(t,e,`at most ${r} bytes`),i!==void 0&&o!==i&&$(t,e,`${i} bytes`),s}function ke(n,t,e,i=0,r){typeof n!="string"&&$(t,e,"a string");let s=Pe(n).length;return(s<i||r!==void 0&&s>r)&&$(t,e,`${i}${r===void 0?"+":`\u2013${r}`} UTF-8 bytes`),n}function je(n,t,e,i){let r=ke(n,t,e);return go(/^(?:[0-9a-fA-F]{2})*$/,r)||$(t,e,"an even-length hex string"),i!==void 0&&r.length!==i*2&&$(t,e,`${i} hexadecimal bytes`),r}function ja(n,t,e){let i=je(n,t,e,33);Ru(i)||$(t,e,"a valid compressed secp256k1 public key")}function de(n,t,e,i=4294967295){return(!gs(n)||n<0||n>i)&&$(t,e,`an integer from 0 to ${i}`),n}function Sh(n,t,e,i,r){return(!gs(n)||n<i||n>r)&&$(t,e,`an integer from ${i} to ${r}`),n}function af(n,t,e){n[e]!==!0&&$(t,e,"true")}function Cy(n,t,e){typeof n[e]!="boolean"&&$(t,e,"a boolean")}function ii(n,t,e){if(n!==void 0)return Yt(n)||$(t,e,"an array"),n.length>1e5&&$(t,e,"at most 100000 entries"),n}function gf(n,t,e,i,r){let s=ii(n,t,e);if(s!=null)for(let o=0;o<s.length;o++)ke(s[o],t,`${e}[${o}]`,i,r)}function J8(n,t,e){let i=ke(n,t,e,1,64);go(/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/,i)||$(t,e,"an ISO timestamp with a timezone");let r=w8(i);S8(r)||$(t,e,"a valid ISO timestamp")}function Q8(n,t,e,i){let r=ke(n,t,e,1,i);try{let s=new m8(r);if(oy==null)throw new Error;let o=Ut(oy,s,[]);if(o!=="https:"&&o!=="http:")throw new Error}catch{$(t,e,"an absolute HTTP(S) URL")}}function t6(n,t){let e=ii(n,t,"sendWithResults");if(e!=null){e.length>_n+1&&$(t,"sendWithResults",`at most ${_n+1} transaction results`);for(let i=0;i<e.length;i++){let r=e[i],s=`sendWithResults[${i}]`,o=Ge(r,t,s);je(o.txid,t,`${s}.txid`,32),wn(mf,o.status)||$(t,`${s}.status`,"a supported status")}}}function By(n,t,e,i){let r=n.inputs[t];r==null&&$(e,i,"a transaction input");let s=re(je(r.sourceTXID,e,`${i}.sourceTXID`,32)),o=de(r.sourceOutputIndex,e,`${i}.sourceOutputIndex`);return`${s}.${o}`}function yy(n,t,e,i,r){let s=Nt(e);if(s==null){ph(n,t,i,r);return}let o=s.version===void 0?1:de(s.version,t,"request.version"),c=s.lockTime===void 0?0:de(s.lockTime,t,"request.lockTime");n.version!==o&&$(t,"tx.version","the requested transaction version"),n.lockTime!==c&&$(t,"tx.lockTime","the requested transaction lock time");let u=new ly;for(let y=0;y<n.inputs.length;y++){let S=By(n,y,t,`tx.inputs[${y}]`);z8(u,S)&&$(t,`tx.inputs[${y}]`,"a unique transaction input outpoint"),fh(u,S,y)}let f=s.inputs===void 0?[]:ii(s.inputs,t,"request.inputs"),d=new yn;for(let y=0;y<f.length;y++){let S=f[y],L=`request.inputs[${y}]`,T=Ge(S,t,L),k=mo(T.outpoint,t,`${L}.outpoint`),E=`${k.txid}.${k.outputIndex}`;wn(d,E)&&$(t,`${L}.outpoint`,"a unique requested input"),se(d,E);let _=ps(u,E);_===void 0&&$(t,"tx.inputs","every requested input exactly once");let B=n.inputs[_],F=T.sequenceNumber===void 0?4294967295:de(T.sequenceNumber,t,`${L}.sequenceNumber`);if((B.sequence??4294967295)!==F&&$(t,`tx.inputs[${_}].sequence`,"the requested input sequence"),T.unlockingScript!==void 0){let C=re(je(T.unlockingScript,t,`${L}.unlockingScript`));re(cn(B.unlockingScript))!==C&&$(t,`tx.inputs[${_}].unlockingScript`,"the requested unlocking script")}}let h=s.outputs===void 0?[]:ii(s.outputs,t,"request.outputs"),m=Nt(s.options)?.randomizeOutputs===!1,b=new ly;for(let y=0;y<n.outputs.length;y++){let S=n.outputs[y],L=de(S.satoshis,t,`tx.outputs[${y}].satoshis`,21e14);if(h.length>0){let T=`${L}:${re(cn(S.lockingScript))}`;fh(b,T,(ps(b,T)??0)+1)}}for(let y=0;y<h.length;y++){let S=h[y],L=`request.outputs[${y}]`,T=Ge(S,t,L),k=de(T.satoshis,t,`${L}.satoshis`,21e14),E=re(je(T.lockingScript,t,`${L}.lockingScript`));if(m){let F=n.outputs[y];(F==null||F.satoshis!==k||re(cn(F.lockingScript))!==E)&&$(t,`tx.outputs[${y}]`,"the requested output at the requested position");continue}let _=`${k}:${E}`,B=ps(b,_)??0;B===0&&$(t,"tx.outputs","every requested output with its requested amount and script"),fh(b,_,B-1)}ph(n,t,i,r)}function ph(n,t,e=pf,i=!1){let r=0,s=!1,o=new yn;for(let u=0;u<n.inputs.length;u++){let f=n.inputs[u],d=By(n,u,t,`tx.inputs[${u}]`);wn(o,d)&&$(t,`tx.inputs[${u}]`,"a unique transaction input outpoint"),se(o,d);let h=f.sourceSatoshis??e[d];if(h===void 0){i||$(t,`tx.inputs[${u}].sourceSatoshis`,"source transaction evidence for every completed transaction input"),s=!0;continue}r+=de(h,t,`tx.inputs[${u}].sourceSatoshis`,21e14),(!gs(r)||r>21e14)&&$(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+=de(f.satoshis,t,`tx.outputs[${u}].satoshis`,21e14),(!gs(c)||c>21e14)&&$(t,"tx.outputs","a valid total output value")}!s&&c>r&&$(t,"tx.outputs","a total value no greater than the transaction inputs")}function e6(n,t,e){let i=Nt(Nt(e)?.spends);if(i==null)return;let r=Bn(i);for(let s=0;s<r.length;s++){let o=r[s],c=i[o],u=`request.spends.${o}`;go(/^(?:0|[1-9]\d*)$/,o)||$(t,u,"a canonical input index");let f=Cn(o),d=n.inputs[f];(!gs(f)||d==null)&&$(t,`tx.inputs[${o}]`,"the requested input index");let h=Ge(c,t,u),l=re(je(h.unlockingScript,t,`${u}.unlockingScript`));re(cn(d.unlockingScript))!==l&&$(t,`tx.inputs[${f}]`,"the requested unlocking script"),h.sequenceNumber!==void 0&&d.sequence!==de(h.sequenceNumber,t,`${u}.sequenceNumber`)&&$(t,`tx.inputs[${f}].sequence`,"the requested input sequence")}}function n6(n,t,e){let i=t==="createAction"?Ty(e):pf,r=n.txid===void 0?void 0:je(n.txid,t,"txid",32),s=n.tx===void 0?void 0:wy(n.tx,t,"tx",r),o=s?.txid;r!==void 0&&o!==void 0&&!bn(r,o)&&$(t,"tx","a BEEF transaction matching txid");let c=ii(n.noSendChange,t,"noSendChange");if(c!=null)for(let b=0;b<c.length;b++)mo(c[b],t,`noSendChange[${b}]`);t6(n.sendWithResults,t);let u;if(n.signableTransaction!==void 0){t!=="createAction"&&$(t,"signableTransaction","an absent field"),(n.txid!==void 0||n.tx!==void 0)&&$(t,"signableTransaction","exclusive of txid and tx");let b=Ge(n.signableTransaction,t,"signableTransaction");u=wy(b.tx,t,"signableTransaction.tx"),Ih(b.reference,t,"signableTransaction.reference")}let f=Nt(e);if(f!==void 0&&t==="createAction"){let b=f.inputs===void 0?[]:ii(f.inputs,t,"request.inputs"),y=f.outputs===void 0?[]:ii(f.outputs,t,"request.outputs"),S=Nt(f.options),L=Yt(S?.sendWith)?S.sendWith:[],T=b.length>0||y.length>0||L.length===0,k=!1;for(let _=0;_<b.length;_++)if(Nt(b[_])?.unlockingScript===void 0){k=!0;break}let E=T&&(S?.signAndProcess===!1||k);T&&E&&u===void 0&&$(t,"signableTransaction","the requested deferred-signing transaction"),T&&!E&&r===void 0&&$(t,"txid","the requested completed transaction"),T&&!E&&u!==void 0&&$(t,"signableTransaction","absent for a completed transaction request")}f!==void 0&&t==="signAction"&&r===void 0&&$(t,"txid","the completed signed transaction"),t==="createAction"?(s!==void 0&&yy(s,t,e,i,!1),u!==void 0&&yy(u,t,e,i,!0)):s!==void 0&&(e6(s,t,e),ph(s,t));let d=u?.txid,h=r??d;if(c!=null){h===void 0&&$(t,"noSendChange","associated with a transaction");for(let b=0;b<c.length;b++){let y=c[b];bn(yh($e(y),".")[0],h)||$(t,`noSendChange[${b}]`,"an outpoint of the returned transaction")}}let l=Nt(Nt(e)?.options),m=new yn;if(h!==void 0&&se(m,re(h)),Yt(l?.sendWith))for(let b=0;b<l.sendWith.length;b++)se(m,re($e(l.sendWith[b])));if(Yt(n.sendWithResults)){let b=new yn;for(let y=0;y<n.sendWithResults.length;y++){let S=n.sendWithResults[y],L=`sendWithResults[${y}].txid`,T=re($e(Ge(S,t,`sendWithResults[${y}]`).txid));wn(b,T)&&$(t,L,"a unique transaction"),se(b,T),hf(m)>0&&!wn(m,T)&&$(t,L,"a submitted or returned transaction")}}n.tx!==void 0&&n.txid===void 0&&$(t,"txid","present with tx"),Nt(e)!==void 0&&n.txid!==void 0&&n.tx===void 0&&Nt(Nt(e)?.options)?.returnTXIDOnly!==!0&&$(t,"tx","transaction evidence unless returnTXIDOnly was explicitly requested"),t==="signAction"&&n.noSendChange!==void 0&&$(t,"noSendChange","an absent field"),n.txid===void 0&&n.signableTransaction===void 0&&(!Yt(n.sendWithResults)||n.sendWithResults.length===0)&&$(t,"outcome","a transaction, signable transaction, or batch-send result")}function wy(n,t,e,i){let r=Ei(n,t,e),s=i===void 0?my.get(r):void 0;if(s!=null)return s;try{let o=Fa(r);return i===void 0&&my.set(r,o),o}catch{}try{return Fa(r,!0)}catch{}try{let o=ao(r),c=i===void 0?void 0:re(i),u;X8(o.transactions,(h,l)=>{h!==void 0&&(u=l)});let f=(c!==void 0&&ps(o.transactions,c)!==void 0?c:void 0)??o.atomicTxid??u,d=f===void 0?void 0:ps(o.transactions,re(f));if(d===void 0)throw new Error("BEEF subject transaction is missing");return d}catch{$(t,e,"a complete, exactly framed BEEF transaction")}}function i6(n,t,e){let i=Ei(n,t,e);try{return ao(i)}catch{$(t,e,"a complete, exactly framed BEEF envelope")}}function mo(n,t,e){let i=ke(n,t,e),r=ms(/^([0-9a-fA-F]{64})\.(0|[1-9]\d*)$/,i);return(r==null||Cn(r[2])>4294967295)&&$(t,e,"a canonical transaction outpoint"),{txid:re(r[1]),outputIndex:Cn(r[2])}}function Ih(n,t,e){let i=ke(n,t,e,1);return go(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,i)||$(t,e,"a canonical base64 string"),i}function cf(n){return n<253?1:n<=65535?3:n<=4294967295?5:9}function Ka(n,t,e,i=!1){let r=Ge(n,t,e),s=Bn(r);for(let o=0;o<s.length;o++){let c=s[o],u=r[c],f=Pe(c).length;(f<1||f>50||Tn(c))&&$(t,`${e} key`,"a safe 1\u201350 byte field name"),i?Ih(u,t,`${e}.${c}`):ke(u,t,`${e}.${c}`)}return r}function gh(n,t,e){let i=Ge(n,t,e);try{let r=0,s=["type","serialNumber"];for(let b=0;b<s.length;b++){let y=s[b],S=Ih(i[y],t,`${e}.${y}`),L=Ou(S);if(L.length!==32||Xb(L)!==S)throw new Error;r+=L.length}let o=["subject","certifier"];for(let b=0;b<o.length;b++){let y=o[b];ja(i[y],t,`${e}.${y}`),r+=33}let c=ke(i.revocationOutpoint,t,`${e}.revocationOutpoint`),u=yh(c,"."),f=u[1]??"0";if(u.length>2||!go(/^[0-9a-fA-F]{64}$/,u[0])||!go(/^(?:0|[1-9]\d*)$/,f)||Cn(f)>4294967295)throw new Error;r+=32+cf(Cn(f));let d=Ka(i.fields,t,`${e}.fields`),h=Bn(d);for(let b=1;b<h.length;b++){let y=h[b],S=b;for(;S>0&&h[S-1]>y;)h[S]=h[S-1],S--;h[S]=y}r+=cf(h.length);for(let b=0;b<h.length;b++){let y=h[b],S=Pe(y),L=Pe(d[y]);r+=cf(S.length)+S.length+cf(L.length)+L.length}let l=je(i.signature,t,`${e}.signature`),m=oo(l);if(!uo(m))throw new Error;if(r+=m.length,r>j8)throw new Error}catch{$(t,e,"a canonical signed wallet certificate")}return i}function Nt(n){if(n==null||typeof n!="object"||Yt(n))return;let t=n,e=gr(null),i=bs(t);for(let r=0;r<i.length;r++){let s=i[r],o=Te(t,s);if(s===wh){if(o==null||!("value"in o))throw new Error("Wallet result request records must contain only data properties");ff(e,s,{value:o.value,enumerable:!1,configurable:!1,writable:!1});continue}if(typeof s!="string"||Tn(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 bn(n,t){return typeof n=="string"&&typeof t=="string"&&re(n)===re(t)}function bf(n){let t=Ut(mh,n,[/\s+/g," "]);return Ut(k8,t,[])}function xy(n){let t=Ut(T8,n,["NFD"]);return re(Ut(mh,t,[/\p{Mn}/gu,""]))}function Ly(n,t){return Ut(O8,n,[t])!==-1}function My(n,t){let e=yh(bf(t)," "),i=Ut(Ey,n,[/\r\n?|\n|\u2028|\u2029/]),r=0;for(;r<i.length;){let s=0,o=0;for(;o<e.length;){let c=Ut(mh,e[o],[/[.*+?^${}()|[\]\\]/g,String.raw`\$&`]),u=new N8(c,"gi");u.lastIndex=s;let f=ms(u,i[r]);if(f==null)break;s=f.index+f[0].length,o++}if(o===e.length)return!0;r++}return!1}var r6=" 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 Uy(n){let t=[],e=/(?:[^\p{Dash}\p{Pattern_Syntax}\p{Quotation_Mark}\p{Terminal_Punctuation}\p{White_Space}]|')+/gu,i=ms(e,n);for(;i!=null;)Ly(r6,` ${i[0]} `)||(t[t.length]=i[0]),i=ms(e,n);return t}function s6(n,t){let e=0;for(;e<n.length;)if(n[e++]===t)return!0;return!1}function o6(n,t,e,i){let r=Ut(R8,e,["-"])&&e.length>1;if(i!==void 0){let u=Ly(t,i);if(r?u:!u)return-1;if(r)return 0}let s=Uy(i??(r?Ut(P8,e,[1]):e)),o=!1,c=0;for(;c<s.length;){let u=s6(n,s[c++]);if(r&&u)return-1;o=o||u}return o&&!r?1:0}function a6(n,t){let e=xy(n),i=xy(t),r=Uy(e),s=/-?"([^"]*)"|[^\s"]+/g,o=!1,c=ms(s,i);for(;c!=null;){let u=o6(r,e,c[0],c[1]);if(u===-1)return!1;u===1&&(o=!0),c=ms(s,i)}return o}function c6(n){return n!=="profilePhoto"&&n!=="icon"}function u6(n,t){if(typeof t!="string")return!1;let e=bf(t);if(e.length<2)return!1;let i=Bn(n),r="",s=0;for(;s<i.length;){let o=i[s++];if(!c6(o))continue;let c=n[o];r=r.length>0?`${r} ${c}`:c}return e.length===2?My(r,e):a6(r,e)}function f6(n,t,e){return typeof t!="string"?!1:n==="userName"?t===bf(e):My(t,e)}function l6(n,t,e,i){let r=Nt(i);if(r==null)return;if(df(r,"any")){u6(e,r.any)||$(n,`${t}.decryptedFields`,"a match for the requested any attribute");return}let s=Bn(r),o=0,c=0;for(;c<s.length;){let u=s[c++],f=r[u];typeof f!="string"&&$(n,`request.attributes.${u}`,"a string"),bf(f).length!==0&&(o++,(!df(e,u)||!f6(u,e[u],f))&&$(n,`${t}.decryptedFields.${u}`,"the requested public attribute"))}o===0&&$(n,`${t}.decryptedFields`,"a usable requested attribute")}function d6(n,t,e,i){let r=mo(n,e,i),s=mo(t,e,`request.${i}`);return r.txid===s.txid&&r.outputIndex===s.outputIndex}function h6(n,t){let e=Nt(n),i=Nt(t);if(e==null||i==null)return!1;let r=Bn(e),s=Bn(i);if(r.length!==s.length)return!1;for(let o=0;o<s.length;o++){let c=s[o];if(!df(e,c)||e[c]!==i[c])return!1}return!0}function p6(n,t){let e=Nt(n),i=Nt(t);if(e==null||i==null)return!1;let r=Bn(e),s=Bn(i);if(r.length!==s.length)return!1;let o=0;for(;o<s.length;){if(!df(e,s[o]))return!1;o++}return!0}function Sy(n,t,e,i,r=!0){let s=Nt(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]&&$(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&&!bn(n[f],s[f])&&$(e,`${i}.${f}`,`the requested certificate ${f}`)}s.revocationOutpoint!==void 0&&!d6(n.revocationOutpoint,s.revocationOutpoint,e,`${i}.revocationOutpoint`)&&$(e,`${i}.revocationOutpoint`,"the requested certificate revocation outpoint"),s.fields!==void 0&&!(r?h6(n.fields,s.fields):p6(n.fields,s.fields))&&$(e,`${i}.fields`,"the requested certificate fields")}function g6(n,t,e){let i=vh(n,t,"totalCertificates","certificates",e),r=Nt(e),s;if(t==="listCertificates"&&Yt(r?.certifiers)){s=new yn;for(let c=0;c<r.certifiers.length;c++)se(s,re($e(r.certifiers[c])))}let o;if(t==="listCertificates"&&Yt(r?.types)){o=new yn;for(let c=0;c<r.types.length;c++)se(o,$e(r.types[c]))}for(let c=0;c<i.length;c++){let u=i[c],f=`certificates[${c}]`,d=gh(u,t,f);if(s!=null&&hf(s)>0&&(wn(s,re($e(d.certifier)))||$(t,`${f}.certifier`,"one of the requested certifiers")),o!=null&&hf(o)>0&&(wn(o,$e(d.type))||$(t,`${f}.type`,"one of the requested types")),t==="discoverByIdentityKey"&&r?.identityKey!==void 0&&!bn(d.subject,r.identityKey)&&$(t,`${f}.subject`,"the requested identity key"),d.keyring!==void 0&&Ka(d.keyring,t,`${f}.keyring`,!0),d.verifier!==void 0&&ja(d.verifier,t,`${f}.verifier`),t==="discoverByIdentityKey"||t==="discoverByAttributes"){let h=`${f}.certifierInfo`,l=Ge(d.certifierInfo,t,h);ke(l.name,t,`${h}.name`,1,100),Q8(l.iconUrl,t,`${h}.iconUrl`,500),ke(l.description,t,`${h}.description`,5,50),Sh(l.trust,t,`${h}.trust`,1,10),Ka(d.publiclyRevealedKeyring,t,`${f}.publiclyRevealedKeyring`,!0);let m=Ka(d.decryptedFields,t,`${f}.decryptedFields`);t==="discoverByAttributes"&&l6(t,f,m,r?.attributes)}}}function vh(n,t,e,i,r){let s=de(n[e],t,e,x8),o=ii(n[i],t,i);o==null&&$(t,i,"an array"),o.length>s&&$(t,e,`at least ${o.length}`);let c=Nt(r);if(c!=null){let u=c.limit===void 0?10:de(c.limit,t,"limit",1e4);o.length>u&&$(t,i,`at most the requested limit of ${u}`)}return o}function dh(n,t,e){ke(n,t,e,n===""?0:5,2e3)}function m6(n,t,e){let i=vh(n,t,"totalActions","actions",e),r=Nt(e),s=[];if(Yt(r?.labels))for(let c=0;c<r.labels.length;c++)s[c]=$e(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=Ge(u,t,f);if(je(d.txid,t,`${f}.txid`,32),Sh(d.satoshis,t,`${f}.satoshis`,-21e14,21e14),wn(ki,d.status)||$(t,`${f}.status`,"a supported action status"),typeof d.isOutgoing!="boolean"&&$(t,`${f}.isOutgoing`,"a boolean"),dh(d.description,t,`${f}.description`),gf(d.labels,t,`${f}.labels`,1,300),r?.includeLabels===!0&&d.labels===void 0&&$(t,`${f}.labels`,"the explicitly requested labels"),s.length>0&&Yt(d.labels)){let m=new yn;for(let y=0;y<d.labels.length;y++)se(m,d.labels[y]);let b=o==="all";for(let y=0;y<s.length;y++){let S=wn(m,s[y]);if(o==="all"&&!S){b=!1;break}if(o==="any"&&S){b=!0;break}}b||$(t,`${f}.labels`,"the requested label query")}de(d.version,t,`${f}.version`),de(d.lockTime,t,`${f}.lockTime`);let h=ii(d.inputs,t,`${f}.inputs`);if((r?.includeInputs===!0||r?.includeInputSourceLockingScripts===!0||r?.includeInputUnlockingScripts===!0)&&h===void 0&&$(t,`${f}.inputs`,"the explicitly requested inputs"),h!=null)for(let m=0;m<h.length;m++){let b=h[m],y=`${f}.inputs[${m}]`,S=Ge(b,t,y);mo(S.sourceOutpoint,t,`${y}.sourceOutpoint`),de(S.sourceSatoshis,t,`${y}.sourceSatoshis`,21e14),S.sourceLockingScript!==void 0&&je(S.sourceLockingScript,t,`${y}.sourceLockingScript`),S.unlockingScript!==void 0&&je(S.unlockingScript,t,`${y}.unlockingScript`),r?.includeInputSourceLockingScripts===!0&&S.sourceLockingScript===void 0&&$(t,`${y}.sourceLockingScript`,"the explicitly requested source locking script"),r?.includeInputUnlockingScripts===!0&&S.unlockingScript===void 0&&$(t,`${y}.unlockingScript`,"the explicitly requested unlocking script"),dh(S.inputDescription,t,`${y}.inputDescription`),de(S.sequenceNumber,t,`${y}.sequenceNumber`)}let l=ii(d.outputs,t,`${f}.outputs`);if((r?.includeOutputs===!0||r?.includeOutputLockingScripts===!0)&&l===void 0&&$(t,`${f}.outputs`,"the explicitly requested outputs"),l!=null)for(let m=0;m<l.length;m++){let b=l[m],y=`${f}.outputs[${m}]`,S=Ge(b,t,y);de(S.satoshis,t,`${y}.satoshis`,21e14),S.lockingScript!==void 0&&je(S.lockingScript,t,`${y}.lockingScript`),r?.includeOutputLockingScripts===!0&&S.lockingScript===void 0&&$(t,`${y}.lockingScript`,"the explicitly requested output locking script"),Cy(S,t,"spendable"),S.customInstructions!==void 0&&ke(S.customInstructions,t,`${y}.customInstructions`),gf(S.tags,t,`${y}.tags`,1,300),de(S.outputIndex,t,`${y}.outputIndex`),dh(S.outputDescription,t,`${y}.outputDescription`),ke(S.basket,t,`${y}.basket`,0,300)}}}function b6(n,t,e){let i=vh(n,t,"totalOutputs","outputs",e),r=n.BEEF===void 0?void 0:i6(n.BEEF,t,"BEEF"),s=Nt(e),o=[];if(Yt(s?.tags))for(let f=0;f<s.tags.length;f++)o[f]=$e(s.tags[f]);let c=s?.tagQueryMode==="all"?"all":"any";i.length>0&&s?.include==="entire transactions"&&r==null&&$(t,"BEEF","the requested complete output transactions");let u=new yn;for(let f=0;f<i.length;f++){let d=i[f],h=`outputs[${f}]`,l=Ge(d,t,h),m=mo(l.outpoint,t,`${h}.outpoint`),b=`${m.txid}.${m.outputIndex}`;wn(u,b)&&$(t,`${h}.outpoint`,"a unique output in the result page"),se(u,b);let y=de(l.satoshis,t,`${h}.satoshis`,21e14);typeof l.spendable!="boolean"&&$(t,`${h}.spendable`,"a boolean");let S=l.lockingScript===void 0?void 0:je(l.lockingScript,t,`${h}.lockingScript`);if(s?.include==="locking scripts"&&S===void 0&&$(t,`${h}.lockingScript`,"the requested locking script"),r!=null){let T=ps(r.transactions,m.txid)?.outputs[m.outputIndex];T==null&&$(t,`${h}.outpoint`,"an output contained in BEEF"),T.satoshis!==y&&$(t,`${h}.satoshis`,"the amount committed by BEEF"),S!==void 0&&re(cn(T.lockingScript))!==re(S)&&$(t,`${h}.lockingScript`,"the script committed by BEEF")}if(l.customInstructions!==void 0&&ke(l.customInstructions,t,`${h}.customInstructions`),gf(l.tags,t,`${h}.tags`,1,300),gf(l.labels,t,`${h}.labels`,1,300),s?.includeTags===!0&&l.tags===void 0&&$(t,`${h}.tags`,"the explicitly requested output tags"),s?.includeLabels===!0&&l.labels===void 0&&$(t,`${h}.labels`,"the explicitly requested transaction labels"),o.length>0&&Yt(l.tags)){let L=new yn;for(let k=0;k<l.tags.length;k++)se(L,l.tags[k]);let T=c==="all";for(let k=0;k<o.length;k++){let E=wn(L,o[k]);if(c==="all"&&!E){T=!1;break}if(c==="any"&&E){T=!0;break}}T||$(t,`${h}.tags`,"the requested tag query")}}}function Iy(n,t){let e=["prover","verifier","counterparty"];for(let i=0;i<e.length;i++){let r=e[i];ja(n[r],t,r)}Ei(n.encryptedLinkage,t,"encryptedLinkage"),Ei(n.encryptedLinkageProof,t,"encryptedLinkageProof")}function Zt(n,t,e){let i=xh(t,n),r=Ge(i,n),s=Nt(e);switch(n){case"createAction":case"signAction":n6(r,n,e);break;case"abortAction":Cy(r,n,"aborted");break;case"internalizeAction":af(r,n,"accepted");break;case"relinquishOutput":case"relinquishCertificate":af(r,n,"relinquished");break;case"verifyHmac":case"verifySignature":af(r,n,"valid");break;case"isAuthenticated":case"waitForAuthentication":af(r,n,"authenticated");break;case"getPublicKey":ja(r.publicKey,n,"publicKey");break;case"encrypt":Ei(r.ciphertext,n,"ciphertext");break;case"decrypt":Ei(r.plaintext,n,"plaintext");break;case"createHmac":Ei(r.hmac,n,"hmac",32);break;case"createSignature":{let o=Ei(r.signature,n,"signature",void 0,72);uo(o)||$(n,"signature","a canonical DER-encoded ECDSA signature");break}case"revealCounterpartyKeyLinkage":Iy(r,n),J8(r.revelationTime,n,"revelationTime"),s?.verifier!==void 0&&!bn(r.verifier,s?.verifier)&&$(n,"verifier","the requested verifier"),s?.counterparty!==void 0&&!bn(r.counterparty,s?.counterparty)&&$(n,"counterparty","the requested counterparty");break;case"revealSpecificKeyLinkage":Iy(r,n),(!Yt(r.protocolID)||r.protocolID.length!==2)&&$(n,"protocolID","a [securityLevel, protocolName] tuple"),de(r.protocolID[0],n,"protocolID[0]",2),ke(r.protocolID[1],n,"protocolID[1]",5,400),ke(r.keyID,n,"keyID",1,800),de(r.proofType,n,"proofType",255),s?.verifier!==void 0&&!bn(r.verifier,s?.verifier)&&$(n,"verifier","the requested verifier"),s?.counterparty==="self"?bn(r.counterparty,r.prover)||$(n,"counterparty","the prover's identity key for counterparty self"):s?.counterparty==="anyone"?bn(r.counterparty,G8)||$(n,"counterparty","the canonical anyone public key"):typeof s?.counterparty=="string"&&!bn(r.counterparty,s.counterparty)&&$(n,"counterparty","the requested counterparty"),Yt(s?.protocolID)&&(r.protocolID[0]!==s.protocolID[0]||r.protocolID[1]!==s.protocolID[1])&&$(n,"protocolID","the requested protocol"),s?.keyID!==void 0&&r.keyID!==s?.keyID&&$(n,"keyID","the requested key ID");break;case"listActions":m6(r,n,e);break;case"listOutputs":b6(r,n,e);break;case"listCertificates":case"discoverByIdentityKey":case"discoverByAttributes":g6(r,n,e);break;case"getHeight":Sh(r.height,n,"height",1,4294967295);break;case"getHeaderForHeight":je(r.header,n,"header",80);break;case"getNetwork":r.network!=="mainnet"&&r.network!=="testnet"&&$(n,"network","mainnet or testnet");break;case"getVersion":ke(r.version,n,"version",7,30);break;case"acquireCertificate":gh(r,n,"certificate"),s?.type!==void 0&&r.type!==s?.type&&$(n,"certificate.type","the requested certificate type"),s?.certifier!==void 0&&!bn(r.certifier,s?.certifier)&&$(n,"certificate.certifier","the requested certifier"),Sy(r,s,n,"certificate",s?.acquisitionProtocol!=="issuance");break;case"proveCertificate":{let o=Ka(r.keyringForVerifier,n,"keyringForVerifier",!0),c=Yt(s?.fieldsToReveal)?s.fieldsToReveal:[],u=new yn;for(let h=0;h<c.length;h++)se(u,$e(c[h]));let f=Bn(o),d=f.length===hf(u);for(let h=0;d&&h<f.length;h++)d=wn(u,f[h]);d||$(n,"keyringForVerifier","exactly the requested certificate fields")}if(r.certificate!==void 0){let o=gh(r.certificate,n,"certificate");Sy(o,s?.certificate,n,"certificate")}r.verifier!==void 0&&ja(r.verifier,n,"verifier"),r.verifier!==void 0&&s?.verifier!==void 0&&!bn(r.verifier,s?.verifier)&&$(n,"verifier","the requested verifier");break}return i}var Ah;(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"})(Ah||(Ah={}));var bo=Ah;function Tt(n,t){switch(n){case"createAction":_u(t);return;case"signAction":Cu(t);return;case"abortAction":Bu(t);return;case"listActions":zu(t);return;case"internalizeAction":Lu(t);return;case"listOutputs":Ku(t);return;case"relinquishOutput":Uu(t);return;case"getPublicKey":Xu(t);return;case"revealCounterpartyKeyLinkage":ju(t);return;case"revealSpecificKeyLinkage":Gu(t);return;case"encrypt":Yu(t);return;case"decrypt":Zu(t);return;case"createHmac":Ju(t);return;case"verifyHmac":Qu(t);return;case"createSignature":tf(t);return;case"verifySignature":ef(t);return;case"acquireCertificate":{let e=t;if(e?.acquisitionProtocol==="direct")Wu(e);else if(e?.acquisitionProtocol==="issuance")$u(e);else throw new Ii("acquisitionProtocol","direct or issuance");return}case"listCertificates":Hu(t);return;case"proveCertificate":Fu(t);return;case"relinquishCertificate":Du(t);return;case"discoverByIdentityKey":qu(t);return;case"discoverByAttributes":Vu(t);return;case"getHeaderForHeight":nf(t);return;case"isAuthenticated":case"waitForAuthentication":case"getHeight":case"getNetwork":case"getVersion":pr(t)}}var yo=class{constructor(){w(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(bo,i)||typeof s!="function"?s:(o,...c)=>(Tt(i,o),Reflect.apply(s,e,[o,...c]))}})}async validatedResult(t,e,i){return Zt(t,await e,i)}async createAction(t,e){let i=St("createAction",t);return await this.validatedResult("createAction",this.CWI.createAction(t,e),i)}async signAction(t,e){let i=St("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=St("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=St("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=St("revealCounterpartyKeyLinkage",t);return await this.validatedResult("revealCounterpartyKeyLinkage",this.CWI.revealCounterpartyKeyLinkage(t,e),i)}async revealSpecificKeyLinkage(t,e){let i=St("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=St("acquireCertificate",t);return await this.validatedResult("acquireCertificate",this.CWI.acquireCertificate(t,e),i)}async listCertificates(t,e){let i=St("listCertificates",t);return await this.validatedResult("listCertificates",this.CWI.listCertificates(t,e),i)}async proveCertificate(t,e){let i=St("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=St("discoverByIdentityKey",t);return await this.validatedResult("discoverByIdentityKey",this.CWI.discoverByIdentityKey(t,e),i)}async discoverByAttributes(t,e){let i=St("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 Ti=class extends Error{constructor(e,i=1,r){super(e);w(this,"code");w(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},ho(i)}},xn;(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"})(xn||(xn={}));var wo=class{async invokeRaw(t,e,i){throw new Error("This substrate must implement invoke() or invokeRaw().")}async invoke(t,e){Tt(t,e);let i=St(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 y6=1024,Dy=3600*1e3;function w6(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"&&ft(e.description,"utf8").length<=4096&&typeof e.code=="number"&&Number.isSafeInteger(e.code)&&e.code>=1&&e.code<=255}var ri=class extends wo{constructor(e="*",i){super();w(this,"domain");w(this,"responseTimeout");w(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>Dy))throw new TypeError(`XDM responseTimeout must be an integer from 1 to ${Dy}.`);this.domain=e,this.responseTimeout=i}async invokeRaw(e,i,r){if(this.pendingInvocations>=y6)throw new Error("XDM wallet pending invocation limit reached.");let s=Ne(Ue(12));return this.pendingInvocations++,await new Promise((o,c)=>{let u,f=!1,d=!0,h=()=>{if(d&&(d=!1,this.pendingInvocations--,u!==void 0&&clearTimeout(u),f&&typeof window.removeEventListener=="function"))try{window.removeEventListener("message",l)}catch{}},l=m=>{if(!(!m.isTrusted||m.source!==window.parent||this.domain!=="*"&&m.origin!==this.domain||!w6(m.data,s)))if(h(),m.data.status==="error"){let b=m.data.code>=xn.unsupportedAction&&m.data.code<=xn.abortRefused,y=b?m.data.description:"Wallet operation failed",S=new Ti(y,b?m.data.code:xn.unknownError);c(S)}else try{o(Zt(e,m.data.result,r))}catch(b){c(b)}};try{window.addEventListener("message",l),f=!0,this.responseTimeout!==void 0&&(u=setTimeout(()=>{h(),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){h(),c(m)}})}};var wf=16*1024*1024,xf=1e5,Sf=1024*1024,Hy=72;function $y(n,t,e){let i;try{i=Ou(n)}catch{throw new Error(`Invalid certificate ${t}: expected canonical base64`)}return Fy(i,t,e),i}function x6(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>xf)throw new Error(`Certificate field count exceeds the maximum of ${xf}`);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=ft(r,"utf8");if(Eh(r,o.length),ft(s.value,"utf8").length>Sf)throw new Error(`Certificate field ${r} exceeds the maximum of ${Sf} bytes`);i[r]=s.value}return i}function Wy(n){let t=n instanceof Uint8Array?Array.from(n):n;if(!Array.isArray(t)||t.length>wf)throw new Error(`Certificate binary must be a byte array of at most ${wf} 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 S6(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 Eh(n,t){if(t<1||t>50)throw new Error(`Invalid certificate field name length: expected 1\u201350 bytes, received ${t}`);if(Tn(n))throw new Error(`Unsafe certificate field name: ${n}`)}function Fy(n,t,e){if(n.length!==e)throw new Error(`Invalid certificate ${t} length: expected ${e} bytes, received ${n.length}`)}function yf(n,t){Fy(n,t,33);try{jt.fromDER(n)}catch{throw new Error(`Invalid certificate ${t}: expected a compressed secp256k1 public key`)}}var ys=class n{constructor(t,e,i,r,s,o,c){w(this,"type");w(this,"serialNumber");w(this,"subject");w(this,"certifier");w(this,"revocationOutpoint");w(this,"fields");w(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 we,i=$y(this.type,"type",32);e.write(i);let r=$y(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=ft(this.subject,"hex");if(yf(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=ft(this.certifier,"hex");if(yf(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=ft(u,"hex");if(d.length!==32)throw new Error(`Invalid certificate revocation txid length: ${d.length}`);e.write(d),e.writeVarIntNum(Number(f));let h=x6(this.fields),l=Object.keys(h).sort((b,y)=>b.localeCompare(y));e.writeVarIntNum(l.length);for(let b of l){let y=h[b],S=ft(b,"utf8");Eh(b,S.length),e.writeVarIntNum(S.length),e.write(S);let L=ft(y,"utf8");e.writeVarIntNum(L.length),e.write(L)}if(t&&(this.signature??"").length>0){if(typeof this.signature!="string"||this.signature.length>Hy*2||!/^(?:[0-9a-fA-F]{2})+$/.test(this.signature))throw new Error("Invalid certificate signature encoding");let b=ft(this.signature,"hex");ve.fromDER(b),e.write(b)}let m=e.toArray();if(m.length>wf)throw new Error(`Certificate binary exceeds the maximum of ${wf} bytes`);return m}static fromBinary(t){let e=new vt(Wy(t)),i=e.read(32),r=Ne(i),s=e.read(32),o=Ne(s),c=e.read(33);yf(Array.from(c),"subject");let u=st(c),f=e.read(33);yf(Array.from(f),"certifier");let d=st(f),h=e.read(32),l=st(h),m=e.readVarIntNumStrict(!1),b=`${l}.${m}`,y=e.readVarIntNumStrict(!1);if(y>xf)throw new Error(`Certificate field count exceeds the maximum of ${xf}`);if(y>Math.floor(e.remaining()/3))throw new Error("Certificate field count exceeds the available data");let S=new Map;for(let T=0;T<y;T++){let k=e.readVarIntNumStrict(!1);if(k<1||k>50)throw new Error(`Invalid certificate field name length: received ${k}`);let E=e.read(k),_=Dt(E);if(Eh(_,k),S.has(_))throw new Error(`Duplicate certificate field name: ${_}`);let B=e.readVarIntNumStrict(!1);if(B>Sf)throw new Error(`Certificate field ${_} exceeds the maximum of ${Sf} bytes`);let F=e.read(B),C=Dt(F);S.set(_,C)}let L;if(!e.eof()){if(e.remaining()>Hy)throw new Error("Certificate signature exceeds the DER size limit");let T=e.read();L=ve.fromDER(Array.from(T)).toString("hex")}return new n(r,o,u,d,b,Object.fromEntries(S),L)}async verify(){try{let t=this.toBinary(!1);return jt.fromString(this.certifier).deriveChild(new O(1),`2-certificate signature-${this.type} ${this.serialNumber}`).verify(t,ve.fromDER(ft(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(!S6(e,this.toBinary(!1)))throw new Error("Certificate changed while its signature was being created");let r=Wy(i),s=ve.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 I6=1e5,v6={1:"completed",2:"unprocessed",3:"sending",4:"unproven",5:"unsigned",6:"nosend",7:"nonfinal",8:"failed"},v,Ht,qy,Vy,Ky,zy,Xy,jy,Gy,Yy,xo,If,Xt,Oi,ws,vf,Af,Ef,kh,Zy,Jy,Qy,tw,Pi,xs,Th,mr,Ga,Ya,fn,Ri,Za,Ja,br,ew,Ce,Ss,yr,kf=class kf{constructor(t){z(this,v);w(this,"wire");this.wire=t}async createAction(t,e){Tt("createAction",t);let i=St("createAction",t),r=new yt(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,ws).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,Zy).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,Jy).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,Af).call(this,r,t.labels),a(this,v,Qy).call(this,r,t.options);let s=await a(this,v,Ht).call(this,"createAction",e,r.toUint8ArrayZeroCopy());return Zt("createAction",a(this,v,qy).call(this,s),i)}async signAction(t,e){Tt("signAction",t);let i=St("signAction",t),r=new yt,s=Object.keys(t.spends);r.writeVarIntNum(s.length);for(let h of s){r.writeVarIntNum(Number(h));let l=t.spends[Number(h)],m=it(l.unlockingScript,"hex");r.writeVarIntNum(m.length),r.write(m),a(this,v,Oi).call(this,r,l.sequenceNumber)}let o=it(t.reference,"base64");r.writeVarIntNum(o.length),r.write(o),a(this,v,tw).call(this,r,t.options);let c=await a(this,v,Ht).call(this,"signAction",e,r.toUint8ArrayZeroCopy()),u=new vt(c),f={};a(this,v,Ri).call(this,u,"signAction txid present")&&(f.txid=st(u.read(32))),a(this,v,Ri).call(this,u,"signAction tx present")&&(f.tx=u.readView(u.readVarIntNumStrict(!1)));let d=a(this,v,kh).call(this,u);return d!=null&&(f.sendWithResults=d),a(this,v,mr).call(this,u,"signAction"),Zt("signAction",f,i)}async abortAction(t,e){Tt("abortAction",t);try{let i=await a(this,v,Ht).call(this,"abortAction",e,it(t.reference,"base64"));return a(this,v,yr).call(this,i,"abortAction"),{aborted:!0}}catch(i){if(i instanceof Ti&&i.code===xn.abortRefused)return{aborted:!1};throw i}}async listActions(t,e){Tt("listActions",t);let i=new yt;i.writeVarIntNum(t.labels.length);for(let u of t.labels)a(this,v,ws).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,Xt).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,Xt).call(this,i,t.seekPermission);let r=await a(this,v,Ht).call(this,"listActions",e,i.toUint8Array()),s=new vt(r),o=a(this,v,Ce).call(this,s.readVarIntNumStrict(!1),"listActions totalActions",0,4294967295),c=[];for(;!s.eof();)a(this,v,Ya).call(this,c.length,t.limit,"listActions"),c.push(a(this,v,zy).call(this,s));return a(this,v,Ga).call(this,c.length,o,"listActions"),{totalActions:o,actions:c}}async internalizeAction(t,e){Tt("internalizeAction",t);let i=new yt(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,Gy).call(this,i,o);a(this,v,Af).call(this,i,typeof t.labels=="object"?t.labels:void 0);let r=it(t.description);i.writeVarIntNum(r.length),i.write(r),a(this,v,Xt).call(this,i,t.seekPermission);let s=await a(this,v,Ht).call(this,"internalizeAction",e,i.toUint8ArrayZeroCopy());return a(this,v,yr).call(this,s,"internalizeAction"),{accepted:!0}}async listOutputs(t,e){Tt("listOutputs",t);let i=St("listOutputs",t),r=new yt;if(a(this,v,ws).call(this,r,t.basket),typeof t.tags=="object"){r.writeVarIntNum(t.tags.length);for(let h of t.tags)a(this,v,ws).call(this,r,h)}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,Xt).call(this,r,t.includeCustomInstructions),a(this,v,Xt).call(this,r,t.includeTags),a(this,v,Xt).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,Xt).call(this,r,t.seekPermission);let s=await a(this,v,Ht).call(this,"listOutputs",e,r.toUint8Array()),o=new vt(s),c=a(this,v,Ce).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,Ya).call(this,d.length,t.limit,"listOutputs"),d.push(a(this,v,Yy).call(this,o));return a(this,v,Ga).call(this,d.length,c,"listOutputs"),Zt("listOutputs",{totalOutputs:c,BEEF:f,outputs:d},i)}async relinquishOutput(t,e){Tt("relinquishOutput",t);let i=new yt,r=it(t.basket,"utf8");i.writeVarIntNum(r.length),i.write(r),i.write(a(this,v,xo).call(this,t.output));let s=await a(this,v,Ht).call(this,"relinquishOutput",e,i.toUint8Array());return a(this,v,yr).call(this,s,"relinquishOutput"),{relinquished:!0}}async getPublicKey(t,e){Tt("getPublicKey",t);let i=new yt;i.writeUInt8(t.identityKey?1:0),t.identityKey?i.write(a(this,v,xs).call(this,t.privileged,t.privilegedReason)):(t.protocolID??(t.protocolID=[rf.Silent,"default"]),t.keyID??(t.keyID=""),i.write(a(this,v,Pi).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,Xt).call(this,i,t.seekPermission);let r=await a(this,v,Ht).call(this,"getPublicKey",e,i.toUint8Array());return a(this,v,Ss).call(this,r,33,"getPublicKey"),jt.fromDER(Array.from(r)),{publicKey:st(r)}}async revealCounterpartyKeyLinkage(t,e){Tt("revealCounterpartyKeyLinkage",t);let i=St("revealCounterpartyKeyLinkage",t),r=new yt;r.write(a(this,v,xs).call(this,t.privileged,t.privilegedReason)),r.write(it(t.counterparty,"hex")),r.write(it(t.verifier,"hex"));let s=await a(this,v,Ht).call(this,"revealCounterpartyKeyLinkage",e,r.toUint8Array()),o=new vt(s),c=a(this,v,br).call(this,o,"revealCounterpartyKeyLinkage prover"),u=a(this,v,br).call(this,o,"revealCounterpartyKeyLinkage verifier"),f=a(this,v,br).call(this,o,"revealCounterpartyKeyLinkage counterparty"),d=o.readVarIntNumStrict(!1),h=Dt(o.read(d)),l=o.readVarIntNumStrict(!1),m=o.read(l),b=o.readVarIntNumStrict(!1),y=o.read(b);return a(this,v,mr).call(this,o,"revealCounterpartyKeyLinkage"),Zt("revealCounterpartyKeyLinkage",{prover:c,verifier:u,counterparty:f,revelationTime:h,encryptedLinkage:Array.from(m),encryptedLinkageProof:Array.from(y)},i)}async revealSpecificKeyLinkage(t,e){Tt("revealSpecificKeyLinkage",t);let i=St("revealSpecificKeyLinkage",t),r=new yt;r.write(a(this,v,Pi).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),r.write(it(t.verifier,"hex"));let s=await a(this,v,Ht).call(this,"revealSpecificKeyLinkage",e,r.toUint8Array()),o=new vt(s),c=a(this,v,br).call(this,o,"revealSpecificKeyLinkage prover"),u=a(this,v,br).call(this,o,"revealSpecificKeyLinkage verifier"),f=a(this,v,br).call(this,o,"revealSpecificKeyLinkage counterparty"),d=a(this,v,ew).call(this,o,"revealSpecificKeyLinkage"),h=o.readVarIntNumStrict(!1),l=Dt(o.read(h)),m=o.readVarIntNumStrict(!1),b=Dt(o.read(m)),y=o.readVarIntNumStrict(!1),S=o.read(y),L=o.readVarIntNumStrict(!1),T=o.read(L),k=o.readUInt8();return a(this,v,mr).call(this,o,"revealSpecificKeyLinkage"),Zt("revealSpecificKeyLinkage",{prover:c,verifier:u,counterparty:f,protocolID:[d,l],keyID:b,encryptedLinkage:Array.from(S),encryptedLinkageProof:Array.from(T),proofType:k},i)}async encrypt(t,e){Tt("encrypt",t);let i=new yt;return i.write(a(this,v,Pi).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.plaintext.length),i.write(t.plaintext),a(this,v,Xt).call(this,i,t.seekPermission),{ciphertext:Array.from(await a(this,v,Ht).call(this,"encrypt",e,i.toUint8Array()))}}async decrypt(t,e){Tt("decrypt",t);let i=new yt;return i.write(a(this,v,Pi).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.ciphertext.length),i.write(t.ciphertext),a(this,v,Xt).call(this,i,t.seekPermission),{plaintext:Array.from(await a(this,v,Ht).call(this,"decrypt",e,i.toUint8Array()))}}async createHmac(t,e){Tt("createHmac",t);let i=new yt;i.write(a(this,v,Pi).call(this,t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.data.length),i.write(t.data),a(this,v,Xt).call(this,i,t.seekPermission);let r=await a(this,v,Ht).call(this,"createHmac",e,i.toUint8Array());return a(this,v,Ss).call(this,r,32,"createHmac"),{hmac:Array.from(r)}}async verifyHmac(t,e){Tt("verifyHmac",t);let i=new yt;i.write(a(this,v,Pi).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,Xt).call(this,i,t.seekPermission);let r=await a(this,v,Ht).call(this,"verifyHmac",e,i.toUint8Array());return a(this,v,yr).call(this,r,"verifyHmac"),{valid:!0}}async createSignature(t,e){Tt("createSignature",t);let i=new yt;return i.write(a(this,v,Pi).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,Xt).call(this,i,t.seekPermission),Zt("createSignature",{signature:Array.from(await a(this,v,Ht).call(this,"createSignature",e,i.toUint8Array()))},t)}async verifySignature(t,e){Tt("verifySignature",t);let i=new yt;i.write(a(this,v,Pi).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,Xt).call(this,i,t.seekPermission);let r=await a(this,v,Ht).call(this,"verifySignature",e,i.toUint8Array());return a(this,v,yr).call(this,r,"verifySignature"),{valid:!0}}async acquireCertificate(t,e){Tt("acquireCertificate",t);let i=St("acquireCertificate",t),r=new yt;r.write(it(t.type,"base64")),r.write(it(t.certifier,"hex"));let s=Object.entries(t.fields);r.writeVarIntNum(s.length);for(let[u,f]of s){let d=it(u,"utf8"),h=it(f,"utf8");r.writeVarIntNum(d.length),r.write(d),r.writeVarIntNum(h.length),r.write(h)}if(r.write(a(this,v,xs).call(this,t.privileged,t.privilegedReason)),r.writeUInt8(t.acquisitionProtocol==="direct"?1:2),t.acquisitionProtocol==="direct"){r.write(it(t.serialNumber,"base64")),r.write(a(this,v,xo).call(this,t.revocationOutpoint??""));let u=it(t.signature,"hex");r.writeVarIntNum(u.length),r.write(u);let f=t.keyringRevealer==="certifier"?[11]:it(t.keyringRevealer,"hex");r.write(f);let d=Object.keys(t.keyringForSubject??{});r.writeVarIntNum(d.length);for(let h of d){let l=it(h,"utf8");r.writeVarIntNum(l.length),r.write(l);let m=it(t.keyringForSubject?.[h],"base64");r.writeVarIntNum(m.length),r.write(m)}}else{let u=it(t.certifierUrl,"utf8");r.writeVarIntNum(u.length),r.write(u)}let o=await a(this,v,Ht).call(this,"acquireCertificate",e,r.toUint8Array()),c=ys.fromBinary(o);return Zt("acquireCertificate",{...c,signature:c.signature},i)}async listCertificates(t,e){Tt("listCertificates",t);let i=St("listCertificates",t),r=new yt;r.writeVarIntNum(t.certifiers.length);for(let f of t.certifiers)r.write(it(f,"hex"));r.writeVarIntNum(t.types.length);for(let f of t.types)r.write(it(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,xs).call(this,t.privileged,t.privilegedReason));let s=await a(this,v,Ht).call(this,"listCertificates",e,r.toUint8Array()),o=new vt(s),c=a(this,v,Ce).call(this,o.readVarIntNumStrict(!1),"listCertificates totalCertificates",0,4294967295),u=[];for(;!o.eof();){a(this,v,Ya).call(this,u.length,t.limit,"listCertificates");let f=o.readVarIntNumStrict(!1),d=o.read(f),h=ys.fromBinary(d),l={};if(a(this,v,Ri).call(this,o,"listCertificates keyring present")){let y=o.readVarIntNumStrict(!1);a(this,v,fn).call(this,o,y,"listCertificates keyring");for(let S=0;S<y;S++){let L=o.readVarIntNumStrict(!1),T=a(this,v,Za).call(this,o,L,"listCertificates keyring"),k=o.readVarIntNumStrict(!1);a(this,v,Ja).call(this,l,T,Ne(o.read(k)),"listCertificates keyring")}}let m=o.readVarIntNumStrict(!1),b;if(m>0){if(m!==33)throw new Error(`Invalid listCertificates verifier length: expected 33 bytes, received ${m}`);b=a(this,v,br).call(this,o,"listCertificates verifier")}u.push({...h,signature:h.signature,keyring:l,verifier:b})}return a(this,v,Ga).call(this,u.length,c,"listCertificates"),Zt("listCertificates",{totalCertificates:c,certificates:u},i)}async proveCertificate(t,e){Tt("proveCertificate",t);let i=St("proveCertificate",t),r=new yt,s=it(t.certificate.type,"base64");r.write(s);let o=it(t.certificate.subject,"hex");r.write(o);let c=it(t.certificate.serialNumber,"base64");r.write(c);let u=it(t.certificate.certifier,"hex");r.write(u);let f=a(this,v,xo).call(this,t.certificate.revocationOutpoint??"");r.write(f);let d=it(t.certificate.signature,"hex");r.writeVarIntNum(d.length),r.write(d);let h=Object.entries(t.certificate.fields??{});r.writeVarIntNum(h.length);for(let[S,L]of h){let T=it(S,"utf8"),k=it(L,"utf8");r.writeVarIntNum(T.length),r.write(T),r.writeVarIntNum(k.length),r.write(k)}r.writeVarIntNum(t.fieldsToReveal.length);for(let S of t.fieldsToReveal){let L=it(S,"utf8");r.writeVarIntNum(L.length),r.write(L)}r.write(it(t.verifier,"hex")),r.write(a(this,v,xs).call(this,t.privileged,t.privilegedReason));let l=await a(this,v,Ht).call(this,"proveCertificate",e,r.toUint8Array()),m=new vt(l),b=m.readVarIntNumStrict(!1);a(this,v,fn).call(this,m,b,"proveCertificate keyring");let y={};for(let S=0;S<b;S++){let L=m.readVarIntNumStrict(!1),T=a(this,v,Za).call(this,m,L,"proveCertificate keyring"),k=m.readVarIntNumStrict(!1);a(this,v,Ja).call(this,y,T,Ne(m.read(k)),"proveCertificate keyring")}return a(this,v,mr).call(this,m,"proveCertificate"),Zt("proveCertificate",{keyringForVerifier:y},i)}async relinquishCertificate(t,e){Tt("relinquishCertificate",t);let i=new yt,r=it(t.type,"base64");i.write(r);let s=it(t.serialNumber,"base64");i.write(s);let o=it(t.certifier,"hex");i.write(o);let c=await a(this,v,Ht).call(this,"relinquishCertificate",e,i.toUint8Array());return a(this,v,yr).call(this,c,"relinquishCertificate"),{relinquished:!0}}async discoverByIdentityKey(t,e){Tt("discoverByIdentityKey",t);let i=St("discoverByIdentityKey",t),r=new yt;r.write(it(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,Xt).call(this,r,t.seekPermission);let s=await a(this,v,Ht).call(this,"discoverByIdentityKey",e,r.toUint8Array());return Zt("discoverByIdentityKey",a(this,v,Th).call(this,s,t.limit),i)}async discoverByAttributes(t,e){Tt("discoverByAttributes",t);let i=St("discoverByAttributes",t),r=new yt,s=Object.keys(t.attributes);r.writeVarIntNum(s.length);for(let c of s){let u=it(c,"utf8"),f=it(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,Xt).call(this,r,t.seekPermission);let o=await a(this,v,Ht).call(this,"discoverByAttributes",e,r.toUint8Array());return Zt("discoverByAttributes",a(this,v,Th).call(this,o,t.limit),i)}async isAuthenticated(t,e){Tt("isAuthenticated",t);let i=await a(this,v,Ht).call(this,"isAuthenticated",e);if(a(this,v,Ss).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){Tt("waitForAuthentication",t);let i=await a(this,v,Ht).call(this,"waitForAuthentication",e);return a(this,v,yr).call(this,i,"waitForAuthentication"),{authenticated:!0}}async getHeight(t,e){Tt("getHeight",t);let i=await a(this,v,Ht).call(this,"getHeight",e),r=new vt(i),s=r.readVarIntNumStrict(!1);if(a(this,v,mr).call(this,r,"getHeight"),s<1||s>4294967295)throw new Error("Wallet returned an invalid height");return{height:s}}async getHeaderForHeight(t,e){if(Tt("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 yt;i.writeVarIntNum(t.height);let r=await a(this,v,Ht).call(this,"getHeaderForHeight",e,i.toUint8Array());return a(this,v,Ss).call(this,r,80,"getHeaderForHeight"),{header:st(r)}}async getNetwork(t,e){Tt("getNetwork",t);let i=await a(this,v,Ht).call(this,"getNetwork",e);if(a(this,v,Ss).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){Tt("getVersion",t);let i=await a(this,v,Ht).call(this,"getVersion",e);if(i.length<7||i.length>30)throw new Error("Wallet returned an invalid version");return{version:Dt(i)}}};v=new WeakSet,Ht=async function(t,e="",i=[]){let r=e===""?"":Ai(e),s=it(r,"utf8"),o=new yt(void 0,2+s.length+i.length);o.writeUInt8(bo[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 h=await this.wire.transmitToWallet(Array.from(c));if(!Array.isArray(h)||h.length>268435456)throw new Error("Wallet Wire response exceeds the maximum permitted size");for(let l=0;l<h.length;l++)if(!Object.prototype.hasOwnProperty.call(h,l)||!Number.isInteger(h[l])||h[l]<0||h[l]>255)throw new Error("Wallet Wire response must be a dense byte array");u=Uint8Array.from(h)}else{let h=await this.wire.transmitToWalletUint8Array(c);if(!(h instanceof Uint8Array)||h.length>268435456)throw new Error("Wallet Wire response exceeds the maximum permitted size");u=h}let f=new vt(u),d=f.readUInt8();if(d===0)return f.readView();{let h=f.readVarIntNumStrict(!1),l=f.read(h),m=Dt(l),b=f.readVarIntNumStrict(!1),y=f.read(b),S=Dt(y);throw a(this,v,mr).call(this,f,t),new Ti(m,d,S)}},qy=function(t){let e=new vt(t),i={};a(this,v,Ri).call(this,e,"createAction txid present")&&(i.txid=st(e.read(32))),a(this,v,Ri).call(this,e,"createAction tx present")&&(i.tx=e.readView(e.readVarIntNumStrict(!1)));let r=e.readVarIntNumStrict();if(r>=0){a(this,v,fn).call(this,e,r,"createAction noSendChange",33),i.noSendChange=[];for(let o=0;o<r;o++)i.noSendChange.push(a(this,v,If).call(this,e))}let s=a(this,v,kh).call(this,e);if(s!=null&&(i.sendWithResults=s),a(this,v,Ri).call(this,e,"createAction signableTransaction present")){let o=e.readView(e.readVarIntNumStrict(!1)),c=e.read(e.readVarIntNumStrict(!1));i.signableTransaction={tx:o,reference:Ne(c)}}return a(this,v,mr).call(this,e,"createAction"),i},Vy=function(t){let e=v6[t];if(e==null)throw new Error(`Unknown status code: ${t}`);return e},Ky=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,Ce).call(this,e,"listActions satoshis",-21e14,21e14)},zy=function(t){let e=st(t.read(32)),i=a(this,v,Ky).call(this,t),r=a(this,v,Vy).call(this,t.readInt8()),s=a(this,v,Ri).call(this,t,"listActions isOutgoing"),o=Dt(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,fn).call(this,t,u,"listActions labels"),c.labels=[];for(let h=0;h<u;h++)c.labels.push(Dt(t.read(t.readVarIntNumStrict(!1))))}c.version=a(this,v,Ce).call(this,t.readVarIntNumStrict(!1),"listActions version",0,4294967295),c.lockTime=a(this,v,Ce).call(this,t.readVarIntNumStrict(!1),"listActions lockTime",0,4294967295);let f=t.readVarIntNumStrict();if(f>=0){a(this,v,fn).call(this,t,f,"listActions inputs"),c.inputs=[];for(let h=0;h<f;h++)c.inputs.push(a(this,v,Xy).call(this,t))}let d=t.readVarIntNumStrict();if(d>=0){a(this,v,fn).call(this,t,d,"listActions outputs"),c.outputs=[];for(let h=0;h<d;h++)c.outputs.push(a(this,v,jy).call(this,t))}return c},Xy=function(t){let e=a(this,v,If).call(this,t),i=a(this,v,Ce).call(this,t.readVarIntNumStrict(!1),"listActions input sourceSatoshis",0,21e14),r=t.readVarIntNumStrict(),s=r>=0?st(t.read(r)):void 0,o=t.readVarIntNumStrict(),c=o>=0?st(t.read(o)):void 0,u=Dt(t.read(t.readVarIntNumStrict(!1))),f=a(this,v,Ce).call(this,t.readVarIntNumStrict(!1),"listActions input sequenceNumber",0,4294967295);return{sourceOutpoint:e,sourceSatoshis:i,sourceLockingScript:s,unlockingScript:c,inputDescription:u,sequenceNumber:f}},jy=function(t){let e=a(this,v,Ce).call(this,t.readVarIntNumStrict(!1),"listActions output outputIndex",0,4294967295),i=a(this,v,Ce).call(this,t.readVarIntNumStrict(!1),"listActions output satoshis",0,21e14),r=t.readVarIntNumStrict(),s=r>=0?st(t.read(r)):void 0,o=a(this,v,Ri).call(this,t,"listOutputs spendable"),c=Dt(t.read(t.readVarIntNumStrict(!1))),u=t.readVarIntNumStrict(),f=u>=0?Dt(t.read(u)):void 0,d=t.readVarIntNumStrict(),h=[];if(d>=0){a(this,v,fn).call(this,t,d,"listActions output tags");for(let b=0;b<d;b++)h.push(Dt(t.read(t.readVarIntNumStrict(!1))))}let l=t.readVarIntNumStrict(),m=l>=0?Dt(t.read(l)):void 0;return{outputIndex:e,satoshis:i,lockingScript:s,spendable:o,outputDescription:c,basket:f,tags:h,customInstructions:m}},Gy=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(it(e.paymentRemittance.senderIdentityKey,"hex"));let i=it(e.paymentRemittance.derivationPrefix,"base64");t.writeVarIntNum(i.length),t.write(i);let r=it(e.paymentRemittance.derivationSuffix,"base64");t.writeVarIntNum(r.length),t.write(r)}else{t.writeUInt8(2);let i=it(e.insertionRemittance?.basket,"utf8");t.writeVarIntNum(i.length),t.write(i),a(this,v,vf).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=it(s,"utf8");t.writeVarIntNum(o.length),t.write(o)}}else t.writeVarIntNum(0)}},Yy=function(t){let e=a(this,v,If).call(this,t),i=a(this,v,Ce).call(this,t.readVarIntNumStrict(!1),"listOutputs satoshis",0,21e14),r={spendable:!0,outpoint:e,satoshis:i},s=t.readVarIntNumStrict();s>=0&&(r.lockingScript=st(t.read(s)));let o=t.readVarIntNumStrict();o>=0&&(r.customInstructions=Dt(t.read(o)));let c=t.readVarIntNumStrict();if(c!==-1){a(this,v,fn).call(this,t,c,"listOutputs tags");let f=[];for(let d=0;d<c;d++)f.push(Dt(t.read(t.readVarIntNumStrict(!1))));r.tags=f}let u=t.readVarIntNumStrict();if(u!==-1){a(this,v,fn).call(this,t,u,"listOutputs labels");let f=[];for(let d=0;d<u;d++)f.push(Dt(t.read(t.readVarIntNumStrict(!1))));r.labels=f}return r},xo=function(t){let e=new yt;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=it(i[0],"hex");if(r.length!==32)throw new Error("Invalid outpoint txid length");return e.write(r),e.writeVarIntNum(a(this,v,Ce).call(this,Number(i[1]),"outpoint index",0,4294967295)),e.toUint8Array()},If=function(t){let e=st(t.read(32)),i=a(this,v,Ce).call(this,t.readVarIntNumStrict(!1),"outpoint index",0,4294967295);return`${e}.${i}`},Xt=function(t,e){t.writeInt8(kf.OPTIONAL_BOOLEAN_WIRE_VALUES.get(e))},Oi=function(t,e){typeof e=="number"?t.writeVarIntNum(e):t.writeVarIntNum(-1)},ws=function(t,e){let i=it(e??"","utf8");t.writeVarIntNum(i.length),t.write(i)},vf=function(t,e){if(e!=null&&e!==""){let i=it(e,"utf8");t.writeVarIntNum(i.length),t.write(i)}else t.writeVarIntNum(-1)},Af=function(t,e){if(e==null)t.writeVarIntNum(-1);else{t.writeVarIntNum(e.length);for(let i of e){let r=it(i,"utf8");t.writeVarIntNum(r.length),t.write(r)}}},Ef=function(t,e){if(e==null)t.writeVarIntNum(-1);else{t.writeVarIntNum(e.length);for(let i of e)t.write(it(i,"hex"))}},kh=function(t){let e=t.readVarIntNumStrict();if(e<0)return;a(this,v,fn).call(this,t,e,"sendWithResults",33,1001);let i=[];for(let r=0;r<e;r++){let s=st(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},Zy=function(t,e){if(t.write(a(this,v,xo).call(this,e.outpoint)),e.unlockingScript!=null&&e.unlockingScript!==""){let i=it(e.unlockingScript,"hex");t.writeVarIntNum(i.length),t.write(i)}else t.writeVarIntNum(-1),t.writeVarIntNum(e.unlockingScriptLength??0);a(this,v,ws).call(this,t,e.inputDescription),a(this,v,Oi).call(this,t,e.sequenceNumber)},Jy=function(t,e){let i=it(e.lockingScript,"hex");t.writeVarIntNum(i.length),t.write(i),t.writeVarIntNum(e.satoshis),a(this,v,ws).call(this,t,e.outputDescription),a(this,v,vf).call(this,t,e.basket),a(this,v,vf).call(this,t,e.customInstructions),a(this,v,Af).call(this,t,e.tags)},Qy=function(t,e){if(e==null){t.writeInt8(0);return}if(t.writeInt8(1),a(this,v,Xt).call(this,t,e.signAndProcess),a(this,v,Xt).call(this,t,e.acceptDelayedBroadcast),t.writeInt8(e.trustSelf==="known"?1:-1),a(this,v,Ef).call(this,t,e.knownTxids),a(this,v,Xt).call(this,t,e.returnTXIDOnly),a(this,v,Xt).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,xo).call(this,i))}a(this,v,Ef).call(this,t,e.sendWith),a(this,v,Xt).call(this,t,e.randomizeOutputs)},tw=function(t,e){if(e==null){t.writeInt8(0);return}t.writeInt8(1),a(this,v,Xt).call(this,t,e.acceptDelayedBroadcast),a(this,v,Xt).call(this,t,e.returnTXIDOnly),a(this,v,Xt).call(this,t,e.noSend),a(this,v,Ef).call(this,t,e.sendWith)},Pi=function(t,e,i,r,s){let o=new yt;o.writeUInt8(t[0]);let c=it(t[1],"utf8");o.writeVarIntNum(c.length),o.write(c);let u=it(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(it(i,"hex")),o.write(a(this,v,xs).call(this,r,s)),o.toUint8Array()},xs=function(t,e){let i=new yt;if(typeof t=="boolean"?i.writeInt8(t?1:0):i.writeInt8(-1),typeof e=="string"){let r=it(e,"utf8");i.writeInt8(r.length),i.write(r)}else i.writeInt8(-1);return i.toUint8Array()},Th=function(t,e){let i=new vt(t),r=a(this,v,Ce).call(this,i.readVarIntNumStrict(!1),"discovery totalCertificates",0,4294967295),s=[];for(;!i.eof();){a(this,v,Ya).call(this,s.length,e,"discover");let o=i.readVarIntNumStrict(!1),c=i.read(o),u=ys.fromBinary(c),f=i.readVarIntNumStrict(!1),d=Dt(i.read(f)),h=i.readVarIntNumStrict(!1),l=Dt(i.read(h)),m=i.readVarIntNumStrict(!1),b=Dt(i.read(m)),y=a(this,v,Ce).call(this,i.readUInt8(),"discovery trust",1,10),S={},L=i.readVarIntNumStrict(!1);a(this,v,fn).call(this,i,L,"discovery public keyring");for(let E=0;E<L;E++){let _=i.readVarIntNumStrict(!1),B=a(this,v,Za).call(this,i,_,"discovery public keyring"),F=i.readVarIntNumStrict(!1);a(this,v,Ja).call(this,S,B,Ne(i.read(F)),"discovery public keyring")}let T={},k=i.readVarIntNumStrict(!1);a(this,v,fn).call(this,i,k,"discovery decrypted fields");for(let E=0;E<k;E++){let _=i.readVarIntNumStrict(!1),B=a(this,v,Za).call(this,i,_,"discovery decrypted fields"),F=i.readVarIntNumStrict(!1);a(this,v,Ja).call(this,T,B,Dt(i.read(F)),"discovery decrypted fields")}s.push({...u,signature:u.signature,certifierInfo:{iconUrl:l,name:d,description:b,trust:y},publiclyRevealedKeyring:S,decryptedFields:T})}return a(this,v,Ga).call(this,s.length,r,"discover"),{totalCertificates:r,certificates:s}},mr=function(t,e){if(!t.eof())throw new Error(`Wallet Wire ${e} response contains trailing data`)},Ga=function(t,e,i){if(t>e)throw new Error(`Wallet Wire ${i} response returned ${t} records but declared a total of ${e}`)},Ya=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}`)},fn=function(t,e,i,r=1,s=I6){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},Ri=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},Za=function(t,e,i){if(e<1||e>50)throw new Error(`Invalid ${i} key length: expected 1\u201350 bytes, received ${e}`);let r=Dt(t.read(e));if(Tn(r))throw new Error(`Unsafe ${i} key: ${r}`);return r},Ja=function(t,e,i,r){if(Object.prototype.hasOwnProperty.call(t,e))throw new Error(`Duplicate ${r} key: ${e}`);t[e]=i},br=function(t,e){let i=t.read(33);return jt.fromDER(Array.from(i)),st(i)},ew=function(t,e){let i=t.readUInt8();if(i!==0&&i!==1&&i!==2)throw new Error(`Invalid ${e} security level: ${i}`);return i},Ce=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},Ss=function(t,e,i){if(t.length!==e)throw new Error(`Wallet Wire ${i} response has an invalid length`)},yr=function(t,e){a(this,v,Ss).call(this,t,0,e)},w(kf,"OPTIONAL_BOOLEAN_WIRE_VALUES",new Map([[!0,1],[!1,0],[void 0,-1]]));var So=kf;function nw(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 Io(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:"&&!A6(t.hostname))throw new TypeError("Wallet HTTP baseUrl may use cleartext HTTP only for a loopback host.");return t.origin}function A6(n){let t=n.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="[::1]"}var vo=class{constructor(t,e="http://localhost:3301",i){w(this,"baseUrl");w(this,"httpClient");w(this,"originator");let r=Ai(t);this.baseUrl=Io(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 vt(t),i=e.readUInt8(),r=bo[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=Ai(Dt(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=Io(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 Tf=class extends Error{constructor(e,i,r,s,o){super("Undelayed createAction or signAction results require review.");w(this,"reviewActionResults");w(this,"sendWithResults");w(this,"txid");w(this,"tx");w(this,"noSendChange");w(this,"code");w(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 Oh=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.`);w(this,"totalSatoshisNeeded");w(this,"moreSatoshisNeeded");w(this,"code");w(this,"isError",!0);this.totalSatoshisNeeded=e,this.moreSatoshisNeeded=i,this.code=7,this.name=this.constructor.name}},iw=Oh;var Ph=256*1024*1024,E6=256*1024*1024;async function k6(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>Ph)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>Ph)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>Ph)throw new Error("HTTPWalletJSON response exceeds the maximum permitted size");e=new Uint8Array(i)}return e!==void 0?JSON.parse(Dt(e)):await n.json()}function Rh(n,t,e=0,i=4096){if(typeof n!="string")throw new Error(`Invalid wallet error ${t}`);let r=ft(n,"utf8").length;if(r<e||r>i)throw new Error(`Invalid wallet error ${t}`);return n}function rw(n,t){if(!Number.isSafeInteger(n)||n<0||n>21e14)throw new Error(`Invalid wallet error ${t}`);return n}function T6(n,t){if(!Array.isArray(n))throw new Error("Invalid wallet error reviewActionResults");if(n.length>_n+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>_n)throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs`);u=[];let f=new Set;for(let[d,h]of o.competingTxs.entries()){if(typeof h!="string"||!/^[0-9a-fA-F]{64}$/.test(h))throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs[${d}]`);let l=h.toLowerCase();if(l===c||f.has(l))throw new Error(`Invalid wallet error reviewActionResults[${r}].competingTxs`);f.add(l),u.push(l)}}if(o.competingBeef!==void 0){if(u==null||u.length===0)throw new Error(`Invalid wallet error reviewActionResults[${r}].competingBeef`);let f=uh(o.competingBeef);if(f==null)throw new Error(`Invalid wallet error reviewActionResults[${r}].competingBeef`);try{let d=Gm.fromBinaryStrict(f);for(let h of u)if(d.findTxid(h)==null)throw new Error}catch{throw new Error(`Invalid wallet error reviewActionResults[${r}].competingBeef`)}}}}function O6(n,t,e){if(n.isError!==!0||!Number.isSafeInteger(n.code))throw new Error("Invalid wallet error envelope");switch(n.message!==void 0&&Rh(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}};Zt(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 T6(n.reviewActionResults,r),new Tf(n.reviewActionResults,n.sendWithResults,n.txid,n.tx,n.noSendChange)}case 6:{let i=Rh(n.parameter,"parameter",1,200),r=Rh(n.message,"message"),s=new Ii(i);return s.message=r,s}case 7:{let i=rw(n.totalSatoshisNeeded,"totalSatoshisNeeded"),r=rw(n.moreSatoshisNeeded,"moreSatoshisNeeded");if(r>i)throw new Error("Invalid wallet error moreSatoshisNeeded");return new iw(i,r)}default:return}}var wr=class{constructor(t,e="http://localhost:3321",i=globalThis.fetch.bind(globalThis)){w(this,"baseUrl");w(this,"httpClient");w(this,"originator");w(this,"api");this.baseUrl=Io(e),this.originator=Ai(t),this.httpClient=i;let r=typeof window<"u"&&typeof document<"u"&&window.origin!=="file://";this.api=async(s,o)=>{Tt(s,o);let c=St(s,o),u=Io(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:nw(this.originator,"http"),d=ho(o);if(it(d,"utf8").length>E6)throw new Error("HTTPWalletJSON request exceeds the maximum permitted size");let h=await this.httpClient(`${u}/${s}`,{method:"POST",redirect:"error",headers:{Accept:"application/json","Content-Type":"application/json",...f?{Origin:f,Originator:f}:{}},body:d}),l=_y(await k6(h),`HTTPWalletJSON ${s} raw response`),m=Ny(of(l),`HTTPWalletJSON ${s} response`);if(m==null||typeof m!="object"||Array.isArray(m))throw new Error(`Invalid HTTPWalletJSON ${s} response: expected an object`);if(!h.ok){if(h.status===400&&Object.prototype.hasOwnProperty.call(m,"isError")){let b=O6(m,s,c);if(b!==void 0)throw b}throw new Error(`HTTPWalletJSON ${s} failed with HTTP status ${h.status}`)}return Zt(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 P6=1024,sw=3600*1e3,ow=256*1024*1024,Is=class extends wo{constructor(e="*",i){super();w(this,"domain");w(this,"responseTimeout");w(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>sw))throw new TypeError(`ReactNativeWebView responseTimeout must be an integer from 1 to ${sw}.`);this.domain=N6(e),this.responseTimeout=i}async invokeRaw(e,i,r){if(this.pendingInvocations>=P6)throw new Error("React Native wallet pending invocation limit reached.");let s=Ne(Ue(12));return this.pendingInvocations++,await new Promise((o,c)=>{let u,f=!1,d=!0,h=()=>{if(d&&(d=!1,this.pendingInvocations--,u!==void 0&&clearTimeout(u),f&&typeof globalThis.window.removeEventListener=="function"))try{globalThis.window.removeEventListener("message",l)}catch{}},l=m=>{if(!R6(m,this.domain)||typeof m.data!="string")return;if(it(m.data,"utf8").length>ow){h(),c(new Error("React Native wallet response exceeds the maximum permitted size."));return}let b;try{b=JSON.parse(m.data)}catch{return}if(!(b?.type!=="CWI"||b.id!==s||b.isInvocation!==!1||b.status!=="success"&&b.status!=="error")){if(this.domain!=="*"&&m.origin!=null&&m.origin!==""&&m.origin!==this.domain){h(),c(new Error(`React Native wallet response origin ${m.origin} did not match ${this.domain}.`));return}if(h(),b.status==="error")if(typeof b.description!="string"||ft(b.description,"utf8").length>4096||!Number.isSafeInteger(b.code)||b.code<1||b.code>255)c(new Error("Invalid React Native wallet error response."));else{let y=b.code>=xn.unsupportedAction&&b.code<=xn.abortRefused,S=y?b.description:"Wallet operation failed";c(new Ti(S,y?b.code:xn.unknownError))}else try{let y=of(b.result);o(Zt(e,y,r))}catch(y){c(y)}}};try{globalThis.window.addEventListener("message",l),f=!0,this.responseTimeout!==void 0&&(u=setTimeout(()=>{h(),c(new Error("React Native wallet response timed out."))},this.responseTimeout));let m=ho({type:"CWI",isInvocation:!0,id:s,call:e,args:i});if(it(m,"utf8").length>ow)throw new Error("React Native wallet request exceeds the maximum permitted size.");globalThis.window.ReactNativeWebView.postMessage(m)}catch(m){h(),c(m)}})}};function R6(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 N6(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 Ao=1e3,aw=200,si=class{constructor(t="auto",e){w(this,"substrate");w(this,"originator");let i=Ai(e);t==="Cicada"&&(t=new So(new vo(i))),t==="window.CWI"&&(t=new yo),t==="XDM"&&(t=new ri),t==="json-api"&&(t=new wr(i)),t==="react-native"&&(t=new Is),t==="secure-json-api"&&(t=new wr(i,"https://localhost:2121")),this.substrate=t,this.originator=i}async validatedResult(t,e,i){return Zt(t,await e,i)}async connectToSubstrate(){if(typeof this.substrate=="object")return;let t=async(o,c,u)=>{try{let f=o(),d,h;try{d=await Promise.race([f.getVersion({},this.originator),new Promise((l,m)=>{h=setTimeout(()=>m(new Error("Timed out.")),c)})])}finally{clearTimeout(h)}return Zt("getVersion",d),{success:!0,sub:u?.()??f}}catch{return{success:!1}}},e=[t(()=>new yo,Ao),t(()=>new So(new vo(this.originator)),Ao),t(()=>new wr(this.originator,"https://localhost:2121"),Ao),t(()=>new wr(this.originator),Ao),t(()=>new Is("*",Ao),Ao,()=>new Is)],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 ri("*",aw),aw,()=>new ri);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){_u(t);let e=St("createAction",t);return await this.connectToSubstrate(),await this.validatedResult("createAction",this.substrate.createAction(t,this.originator),e)}async signAction(t){Cu(t);let e=St("signAction",t);return await this.connectToSubstrate(),await this.validatedResult("signAction",this.substrate.signAction(t,this.originator),e)}async abortAction(t){return Bu(t),await this.connectToSubstrate(),await this.validatedResult("abortAction",this.substrate.abortAction(t,this.originator))}async listActions(t){zu(t);let e=St("listActions",t);return await this.connectToSubstrate(),await this.validatedResult("listActions",this.substrate.listActions(t,this.originator),e)}async internalizeAction(t){return Lu(t),await this.connectToSubstrate(),await this.validatedResult("internalizeAction",this.substrate.internalizeAction(t,this.originator))}async listOutputs(t){Ku(t);let e=St("listOutputs",t);return await this.connectToSubstrate(),await this.validatedResult("listOutputs",this.substrate.listOutputs(t,this.originator),e)}async relinquishOutput(t){return Uu(t),await this.connectToSubstrate(),await this.validatedResult("relinquishOutput",this.substrate.relinquishOutput(t,this.originator))}async getPublicKey(t){return Xu(t),await this.connectToSubstrate(),await this.validatedResult("getPublicKey",this.substrate.getPublicKey(t,this.originator))}async revealCounterpartyKeyLinkage(t){ju(t);let e=St("revealCounterpartyKeyLinkage",t);return await this.connectToSubstrate(),await this.validatedResult("revealCounterpartyKeyLinkage",this.substrate.revealCounterpartyKeyLinkage(t,this.originator),e)}async revealSpecificKeyLinkage(t){Gu(t);let e=St("revealSpecificKeyLinkage",t);return await this.connectToSubstrate(),await this.validatedResult("revealSpecificKeyLinkage",this.substrate.revealSpecificKeyLinkage(t,this.originator),e)}async encrypt(t){return Yu(t),await this.connectToSubstrate(),await this.validatedResult("encrypt",this.substrate.encrypt(t,this.originator))}async decrypt(t){return Zu(t),await this.connectToSubstrate(),await this.validatedResult("decrypt",this.substrate.decrypt(t,this.originator))}async createHmac(t){return Ju(t),await this.connectToSubstrate(),await this.validatedResult("createHmac",this.substrate.createHmac(t,this.originator))}async verifyHmac(t){return Qu(t),await this.connectToSubstrate(),await this.validatedResult("verifyHmac",this.substrate.verifyHmac(t,this.originator))}async createSignature(t){return tf(t),await this.connectToSubstrate(),await this.validatedResult("createSignature",this.substrate.createSignature(t,this.originator))}async verifySignature(t){return ef(t),await this.connectToSubstrate(),await this.validatedResult("verifySignature",this.substrate.verifySignature(t,this.originator))}async acquireCertificate(t){if(t.acquisitionProtocol==="direct")Wu(t);else if(t.acquisitionProtocol==="issuance")$u(t);else throw new Ii("acquisitionProtocol",`valid. ${String(t.acquisitionProtocol)} is unrecognized.`);let e=St("acquireCertificate",t);return await this.connectToSubstrate(),await this.validatedResult("acquireCertificate",this.substrate.acquireCertificate(t,this.originator),e)}async listCertificates(t){Hu(t);let e=St("listCertificates",t);return await this.connectToSubstrate(),await this.validatedResult("listCertificates",this.substrate.listCertificates(t,this.originator),e)}async proveCertificate(t){Fu(t);let e=St("proveCertificate",t);return await this.connectToSubstrate(),await this.validatedResult("proveCertificate",this.substrate.proveCertificate(t,this.originator),e)}async relinquishCertificate(t){return Du(t),await this.connectToSubstrate(),await this.validatedResult("relinquishCertificate",this.substrate.relinquishCertificate(t,this.originator))}async discoverByIdentityKey(t){qu(t);let e=St("discoverByIdentityKey",t);return await this.connectToSubstrate(),await this.validatedResult("discoverByIdentityKey",this.substrate.discoverByIdentityKey(t,this.originator),e)}async discoverByAttributes(t){Vu(t);let e=St("discoverByAttributes",t);return await this.connectToSubstrate(),await this.validatedResult("discoverByAttributes",this.substrate.discoverByAttributes(t,this.originator),e)}async isAuthenticated(t={}){return pr(t),await this.connectToSubstrate(),await this.validatedResult("isAuthenticated",this.substrate.isAuthenticated(t,this.originator))}async waitForAuthentication(t={}){return pr(t),await this.connectToSubstrate(),await this.validatedResult("waitForAuthentication",this.substrate.waitForAuthentication(t,this.originator))}async getHeight(t={}){return pr(t),await this.connectToSubstrate(),await this.validatedResult("getHeight",this.substrate.getHeight(t,this.originator))}async getHeaderForHeight(t){return nf(t),await this.connectToSubstrate(),await this.validatedResult("getHeaderForHeight",this.substrate.getHeaderForHeight(t,this.originator))}async getNetwork(t={}){return pr(t),await this.connectToSubstrate(),await this.validatedResult("getNetwork",this.substrate.getNetwork(t,this.originator))}async getVersion(t={}){return pr(t),await this.connectToSubstrate(),await this.validatedResult("getVersion",this.substrate.getVersion(t,this.originator))}};var Ln="com.bwalletx.extension",Mn="space.bwallet.mobile",Qa=[Ln,Mn],xr=300;function oi(n=xr){return typeof window>"u"?Promise.resolve(null):new Promise(t=>{let e=!1,i,r=o=>{e||(e=!0,i!==void 0&&clearTimeout(i),window.removeEventListener("brc100:announceWallet",s),t(o))},s=o=>{let c=o.detail,u=c?.info?.rdns??"";c?.wallet&&Qa.includes(u)&&r({wallet:c.wallet,method:u===Ln?"extension":"in-app",rdns:u})};if(window.addEventListener("brc100:announceWallet",s),window.dispatchEvent(new Event("brc100:requestWallet")),!e){if(tc()){Nh(Math.max(n,1200)).then(o=>r(o?{wallet:o,method:"in-app",rdns:null}:null));return}i=setTimeout(()=>{i=void 0,r(null)},n)}})}async function uw(n=xr){return(await oi(n))?.wallet??null}var tc=()=>{try{return window.parent!==window}catch{return!0}},_6=["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"],C6=()=>{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 Nh(n=1200,t=_6){let e=C6();if(!e||!t.includes(e))return null;try{let i=new si(new ri(e));return await Promise.race([i.isAuthenticated({}).then(()=>!0,()=>!1),new Promise(s=>setTimeout(()=>s(!1),n))])?i:null}catch{return null}}var cw=0;function _h(){typeof window>"u"||Date.now()-cw<2e4||(cw=Date.now(),oi(0).then(n=>{n&&n.method==="extension"&&n.wallet.isAuthenticated({}).catch(()=>{})}))}function Of(n){let t=()=>_h(),e=["pointerenter","focus","touchstart"];for(let i of e)n.addEventListener(i,t,{passive:!0});return()=>e.forEach(i=>n.removeEventListener(i,t))}function ec(n,t){let e=Promise.resolve();return i=>(e=e.then(()=>n(i)).catch(r=>t?.(r)),e)}var dw="1",B6="bwallet-pair-v1",L6="www.bwallet.space";var hw="relay.bwallet.space",Pf=120,Eo=new TextEncoder,M6=new TextDecoder,pw=n=>{let t="";for(let e=0;e<n.length;e+=32768)t+=String.fromCharCode(...n.subarray(e,e+32768));return t},Ch=n=>btoa(pw(n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),U6=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))},fw=n=>btoa(pw(n)),lw=n=>Uint8Array.from(atob(n),t=>t.charCodeAt(0)),gw=()=>Ch(crypto.getRandomValues(new Uint8Array(16)));function mw(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://${L6}/pair?${t}`}var Bh=()=>Ch(crypto.getRandomValues(new Uint8Array(16))),D6="bwallet-pair-wallet-claim-v1",H6=n=>Array.from(n,t=>t.toString(16).padStart(2,"0")).join("");async function bw(n,t){let e=await crypto.subtle.digest("SHA-256",Eo.encode(`${D6}|${n}|${t}`));return Ch(new Uint8Array(e))}async function yw(n){return H6(new Uint8Array(await crypto.subtle.digest("SHA-256",Eo.encode(n))))}var Lh=(n,t,e,i,r,s)=>{let o=/^(localhost|127\.0\.0\.1)(:\d+)?$/.test(n),c=new URLSearchParams({role:e});return i&&c.set("e",String(i)),r&&c.set("claim",r),s&&e==="site"&&c.set("wc",s),`${o?"ws":"wss"}://${n}/v1/c/${t}?${c}`};async function Mh(n,t,e){let i=n.deriveSharedSecret(jt.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:U6(e),info:Eo.encode(B6)},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 nc=class{constructor(t,e){w(this,"key",t);w(this,"me",e);w(this,"sent",0);w(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:Eo.encode(`${this.me}|${e}`)},this.key,Eo.encode(JSON.stringify(t))));return{s:e,n:fw(i),d:fw(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:lw(t.n),additionalData:Eo.encode(`${e}|${t.s}`)},this.key,lw(t.d));return this.lastSeen=t.s,JSON.parse(M6.decode(i))}catch{return null}}get counters(){return{sent:this.sent,lastSeen:this.lastSeen}}restore(t){this.sent=t.sent,this.lastSeen=t.lastSeen}},Uh=n=>!!n&&typeof n=="object"&&"d"in n&&"n"in n&&"s"in n;var Dh="bwalletx.connect.pairing.v1",ww=1;function Nf(){let n=new Map;return{getItem:t=>n.get(t)??null,setItem:(t,e)=>{n.set(t,e)},removeItem:t=>{n.delete(t)}}}function Hh(){try{if(typeof localStorage<"u")return localStorage}catch{}return Nf()}function xw(){return n=>{if(typeof WebSocket>"u")throw new Error("No WebSocket here. Pass options.socket.");return new WebSocket(n)}}function $6(n){if(!n)return null;try{let t=JSON.parse(n),e=i=>Number.isInteger(i)&&i>=0;return t.v!==1||typeof t.c!="string"||!/^[A-Za-z0-9_-]{22}$/.test(t.c)||typeof t.r!="string"||!/^[a-z0-9.-]+(:\d+)?$/i.test(t.r)||typeof t.s!="string"||!/^[0-9a-f]{64}$/i.test(t.s)||typeof t.k!="string"||!/^0[23][0-9a-f]{64}$/i.test(t.k)||!e(t.sent)||!e(t.lastSeen)||!e(t.pairedAt)||t.sc!==void 0&&(typeof t.sc!="string"||!/^[A-Za-z0-9_-]{22,64}$/.test(t.sc))?null:t}catch{return null}}var Rf=class{constructor(t,e,i,r,s,o){w(this,"p",t);w(this,"sealer",e);w(this,"storage",i);w(this,"key",r);w(this,"socket",s);w(this,"timeoutMs",o);w(this,"ws",null);w(this,"opening",null);w(this,"waiting",new Map);w(this,"forgotten",!1)}adopt(t){this.ws=t,this.wire(t)}wire(t){t.onmessage=ec(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===ww||(this.opening??(this.opening=this.reopen().finally(()=>this.opening=null)),await this.opening)}reopen(){this.p.sc||(this.p={...this.p,sc:Bh()},this.persist());let t=Math.floor(Date.now()/1e3)+Pf-10,e=this.socket(Lh(this.p.r,this.p.c,"site",t,this.p.sc));return new Promise((i,r)=>{e.onopen=()=>{this.ws=e,this.wire(e),i()},e.onerror=()=>r(new Error("Could not reach the bWalletX pairing service")),e.onclose=()=>r(new Error("Could not reach the bWalletX pairing service"))})}async onFrame(t){let e;try{e=JSON.parse(t)}catch{return}if(e.t==="relay"&&e.error)return this.failAll(new Error(`bWalletX pairing service: ${e.error}`));if(!Uh(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===ww&&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 ko(n){let t=n.storage===void 0?Hh():n.storage??Nf(),e=n.storageKey??Dh,i=n.socket??xw(),r=n.relay??hw,s=n.origin??(typeof location<"u"?location.origin:"");if(!s)return Promise.reject(new Error("pairBwalletX needs options.origin outside a browser"));let o=jr.fromRandom(),c=gw(),u=Math.floor(Date.now()/1e3)+Pf,f=Bh(),d=o.toPublicKey().toString();return bw(c,d).then(yw).then(h=>new Promise((l,m)=>{if(n.signal?.aborted)return m(new Error("cancelled"));let b;try{b=i(Lh(r,c,"site",u,f,h))}catch(E){return m(E)}let y=null,S="",L=!1,T=E=>{L||(L=!0,clearTimeout(k),b.close(),m(E))},k=setTimeout(()=>T(new Error("The pairing code expired. Show a new one.")),Pf*1e3);n.signal?.addEventListener("abort",()=>T(new Error("cancelled"))),b.onerror=()=>T(new Error("Could not reach the bWalletX pairing service")),b.onclose=()=>T(new Error("The connection to bWalletX closed before pairing finished")),b.onmessage=ec(async E=>{if(L)return;let _;try{_=JSON.parse(String(E.data))}catch{return}if(_.t==="hello"&&!y){S=_.k;let F=await Mh(o,S,c);y=new nc(F.key,"site"),n.onCode(F.code);return}if(!y||!Uh(_))return;let B=await y.open(_);if(B)if(B.t==="ready"){L=!0,clearTimeout(k);let F={v:1,c,r,s:o.toHex(),k:S,...y.counters,pairedAt:Date.now(),sc:f};await Promise.resolve(t.setItem(e,JSON.stringify(F))).catch(()=>{});let C=new Rf(F,y,t,e,i,n.callTimeoutMs??12e4);C.adopt(b),l(C.wallet())}else B.t==="close"&&T(new Error("Pairing was declined in bWalletX"))}),n.onLink(mw({v:dw,r,c,k:d,o:s,e:u}))}))}async function To(n={}){let t=n.storage===void 0?Hh():n.storage??Nf(),e=n.storageKey??Dh,i=$6(await Promise.resolve(t.getItem(e)).catch(()=>null));if(!i)return null;let{key:r}=await Mh(jr.fromHex(i.s),i.k,i.c),s=new nc(r,"site");return s.restore({sent:i.sent,lastSeen:i.lastSeen}),new Rf(i,s,t,e,n.socket??xw(),n.callTimeoutMs??12e4).wallet()}async function _f(n={}){let t=n.storage===void 0?Hh():n.storage??Nf();await Promise.resolve(t.removeItem(n.storageKey??Dh)).catch(()=>{})}var $h=[2,"bwallet sign in"];async function vs(n={}){let t=i=>{try{n.onStatus?.(i)}catch{}};if(n.wallet)return t("opening"),{wallet:n.wallet,method:"wallet"};t("finding");let e=await oi(n.discoverMs??xr);if(e)return t("opening"),{wallet:e.wallet,method:e.method};if(n.reusePairing!==!1){let i=await To(n.pairing??{});if(i)return t("opening"),{wallet:i,method:"pairing"}}if(!n.pairing)throw Object.assign(new Error("bWalletX was not found in this browser"),{code:"NOT_FOUND"});return t("pairing"),{wallet:await ko(n.pairing),method:"pairing"}}async function As(n){let t=!1;try{t=!!(await n.isAuthenticated({}))?.authenticated}catch{}t||await Promise.resolve().then(()=>n.waitForAuthentication({})).catch(()=>{})}function Wh(n){let t=n instanceof Error?n.message:String(n??"");return/identityKey/i.test(t)}async function Cf(n){let{wallet:t,method:e}=await vs(n);e!=="pairing"&&!n.skipWaitForAuthentication&&await As(t);let i=()=>{try{n.onStatus?.("signing")}catch{}},r=f=>t.createSignature({protocolID:f.protocolID??$h,keyID:f.keyID,counterparty:"anyone",data:Array.from(new TextEncoder().encode(f.message))}),s=async()=>{let{publicKey:f}=await Sr("identity",()=>t.getPublicKey({identityKey:!0}));i();let d=await Sr("challenge",()=>n.challenge(f)),{signature:h}=await Sr("signature",()=>r(d));return{identityKey:f,signature:Array.from(h),nonce:d.nonce,method:e,wallet:t}};if(n.challengeNeedsIdentityKey&&!n.identityKey)return s();let o;try{o=await Sr("challenge",()=>n.challenge(n.identityKey))}catch(f){if(!n.identityKey&&Wh(f))return s();throw f}i();let[{publicKey:c},{signature:u}]=await Promise.all([n.identityKey?Promise.resolve({publicKey:n.identityKey}):Sr("identity",()=>t.getPublicKey({identityKey:!0})),Sr("signature",()=>r(o))]);return{identityKey:c,signature:Array.from(u),nonce:o.nonce,method:e,wallet:t}}async function Es(n){let t=!n.identityKey&&!!n.identityKeyHint,e=await Cf({...n,identityKey:n.identityKey??n.identityKeyHint});try{return{result:e,verified:await Sr("verify",()=>n.verify(e))}}catch(i){let r=i?.status;if(!t||r!==401)throw i;let s=await Cf({...n,wallet:e.wallet,identityKey:void 0,skipWaitForAuthentication:!0});return{result:s,verified:await Sr("verify",()=>n.verify(s))}}}async function Sr(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}}async function Fh(n,t,e={}){if(e.identity===!1)return{wallet:n,payer:n,identityKey:null,optionId:t.id,kind:t.kind};await As(n);let{publicKey:i}=await n.getPublicKey({identityKey:!0});return{wallet:n,payer:n,identityKey:i,optionId:t.id,kind:t.kind}}function Ni(n,t){let e={id:t.id,name:t.name,icon:t.icon,rdns:t.rdns,kind:"brc100",isBwalletX:t.isBwalletX??!1,substrate:t.substrate,wallet:n,connect:i=>Fh(n,e,i)};return e}function qh(n){let t={id:"bwalletx-pairing",name:"bWalletX on your phone",kind:"pairing",isBwalletX:!0,substrate:"pairing",async connect(e){let i=typeof n=="function"?n():n,r=await To(i)??await ko(i);return Fh(r,t,e)}};return t}function Sw(n){let t={id:"handcash",name:"HandCash",icon:n.icon,kind:"handcash",isBwalletX:!1,substrate:"adapter",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 W6={[Ln]:"bWalletX","space.bwallet.mobile":"bWalletX"};async function Bf(n,t){try{let e=new si(n);return await Promise.race([e.isAuthenticated({}).then(()=>!0),new Promise(r=>setTimeout(()=>r(!1),t))])?e:null}catch{return null}}function Vh(n,t){return t.some(e=>e.wallet===n||e.rdns===Mn)}async function ks(n={}){let t=[],e=n.ms??300;if(typeof window<"u"){let r=new Map,s=d=>{let h=d.detail;if(!h?.wallet)return;let l=h.info?.rdns??h.info?.uuid??`wallet-${r.size}`;if(r.has(l))return;let m=Qa.includes(l),b=l===Ln?"extension":l===Mn?"in-app":"injected";r.set(l,Ni(h.wallet,{id:l,rdns:l,name:W6[l]??h.info?.name??l,icon:h.info?.icon,isBwalletX:m,substrate:b}))};window.addEventListener("brc100:announceWallet",s),window.dispatchEvent(new Event("brc100:requestWallet"));let o=n.probeLocal?Promise.all([Bf("json-api",e),Bf("Cicada",e)]):Promise.resolve([null,null]);if(await new Promise(d=>setTimeout(d,r.size>0||window.CWI?Math.min(e,50):e)),window.removeEventListener("brc100:announceWallet",s),t.push(...r.values()),![...r.values()].some(d=>d.isBwalletX)&&tc()){let d=await Nh(Math.max(e,1200));d&&t.push(Ni(d,{id:"bwalletx-xdm",name:"bWalletX",isBwalletX:!0,substrate:"xdm"}))}let c=window.CWI;c&&!Vh(c,[...r.values()])&&t.push(Ni(c,{id:"window.CWI",name:r.size?"Another browser wallet":"Browser wallet",isBwalletX:!1,substrate:"window.CWI"}));let[u,f]=await o;u&&t.push(Ni(u,{id:"localhost:3321",name:"Desktop wallet (localhost:3321)",substrate:"json-api"})),f&&t.push(Ni(f,{id:"localhost:3301",name:"Desktop wallet (localhost:3301)",substrate:"cicada"}))}n.pairing&&t.push(qh(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 Ir="desktop";function Iw(n=1500){let t={id:Ir,name:"Desktop wallet",kind:"brc100",isBwalletX:!1,substrate:"json-api",async connect(e){let[i,r]=await Promise.all([Bf("json-api",n),Bf("Cicada",n)]),s=i??r;if(!s)throw Object.assign(new Error("No desktop wallet answered on this computer"),{code:"NOT_FOUND"});return t.wallet=s,t.substrate=i?"json-api":"cicada",Fh(s,t,e)}};return t}function Lf(n,t=!1){let e=n.filter(o=>!ic(o)),i=e.filter(o=>o.kind==="brc100"),r=e.filter(o=>o.kind==="handcash"||o.kind==="custom"),s=e.length!==n.length;if(t)return i[0]??e.find(o=>o.kind!=="pairing")??e[0]??null;if(!n.length)return null;if(n.length===1)return s?void 0:n[0];if(i.length===1&&r.length===0&&!s)return i[0];if(i.length===0&&r.length===0)return e[0]??void 0}function ic(n){return n.substrate==="json-api"||n.substrate==="cicada"||n.id==="localhost:3321"||n.id==="localhost:3301"||n.id===Ir}var Kh="https://pay.bwallet.space/api/paymail/lookup?key=",zh="https://chat.bwalletx.com/api/bavatar/";function Xh(n){return n.length>12?`${n.slice(0,6)}\u2026${n.slice(-4)}`:n}function sc(n){return n.paymail&&/@bwalletx\.com$/i.test(n.paymail)?"$"+n.paymail.split("@")[0]:n.handle?n.handle:n.paymail?n.paymail:n.identityKey?Xh(n.identityKey):""}function Mf(n){return n&&/^0[23][0-9a-fA-F]{64}$/.test(n)?`${zh}${n.toLowerCase()}.png`:null}var vw=new Map;function Uf(n,t=Kh){if(t==="off"||typeof fetch>"u")return Promise.resolve(null);let e=`${t}|${n}`,i=vw.get(e);return i||(i=fetch(t+encodeURIComponent(n)).then(r=>r.ok?r.json():null).then(r=>r&&typeof r.paymail=="string"?r.paymail:null).catch(()=>null),vw.set(e,i)),i}function oc(n){let t=n?.code;if(t==="ERR_PERMISSION_DENIED"||t===4001)return!0;let e=n instanceof Error?n.message:String(n??"");return/denied|reject|cancel|declin|refused|not now|user closed/i.test(e)}function Df(n){if(oc(n))return"Sign-in cancelled";if(n?.name==="MetanetUnreachableError")return n.message;if(n?.code==="NOT_FOUND")return"bWalletX was not found in this browser";let e=n instanceof Error?n.message:String(n??"");return/lock/i.test(e)?"Your wallet is locked. Unlock it and try again":/timeout|timed out|expired/i.test(e)?"The wallet did not answer in time":/origin/i.test(e)?"This page is not on the site\u2019s configured origin":"Sign-in failed"}async function Aw(n){try{return await navigator.clipboard.writeText(n),!0}catch{return!1}}var rc="bwx:identityKey";function vr(){try{let n=globalThis.localStorage?.getItem(rc)??"";return/^0[23][0-9a-f]{64}$/i.test(n)?n:void 0}catch{return}}function Ts(n){try{n?globalThis.localStorage?.setItem(rc,n):globalThis.localStorage?.removeItem(rc)}catch{}}function Os(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}}var Sn="metanet",Ar=Sn,kw="http://localhost:3321",ac="Use Metanet Desktop or another BRC-100 wallet",Po="Metanet Desktop must be running on this computer",cc="Signs in with Metanet Desktop on this computer.",$f="Not you? Use another wallet",jh="We couldn\u2019t reach Metanet Desktop. Open it, then try again.",Gh=4e3,Yh=2e3,Oo=class extends Error{constructor(){super(jh);w(this,"code","NOT_FOUND");this.name="MetanetUnreachableError"}};function Zh(n=typeof window>"u"?void 0:window){if(!n)return!1;try{return n.top!==n.self}catch{return!0}}function In(n={}){let t=n.window??(typeof window>"u"?void 0:window);if(!t)return!1;let e=n.navigator??(typeof navigator>"u"?void 0:navigator),i=n.matchMedia??(typeof matchMedia>"u"?void 0:r=>matchMedia(r));return!Os({navigator:e,matchMedia:i})&&!Zh(t)}function Tw(n){if(n.make)return n.make();let t=n.originator??(typeof location<"u"&&location.host?location.host:void 0);return new si("json-api",t)}async function Ow(n){return Promise.resolve().then(()=>n.getVersion({})).then(t=>typeof t?.version=="string",()=>!1)}async function Jh(n={}){let t;try{t=Tw(n)}catch{throw new Oo}let e,i=await Promise.race([Ow(t),new Promise(r=>e=setTimeout(()=>r(!1),n.timeoutMs??Gh))]);if(clearTimeout(e),!i)throw new Oo;return t}function _i(n={}){let t={id:Ar,name:ac,kind:"brc100",isBwalletX:!1,substrate:"json-api",async connect(){let e=await Jh(n);t.wallet=e,await As(e);let{publicKey:i}=await e.getPublicKey({identityKey:!0});return{wallet:e,payer:e,identityKey:i,optionId:t.id,kind:"brc100"}}};return t}var Wf="bwx:known-keys",Qh=/^0[23][0-9a-f]{64}$/,F6=8;function Ff(){try{let n=JSON.parse(globalThis.localStorage?.getItem(Wf)||"[]");return Array.isArray(n)?n.filter(t=>typeof t=="string"&&Qh.test(t)):[]}catch{return[]}}function uc(n){if(!n)return!1;let t=n.toLowerCase();return Qh.test(t)?Ff().includes(t)||vr()?.toLowerCase()===t:!1}function Ps(n){let t=(n??"").toLowerCase();if(Qh.test(t))try{let e=[t,...Ff().filter(i=>i!==t)].slice(0,F6);globalThis.localStorage?.setItem(Wf,JSON.stringify(e))}catch{}}var Hf=!1;function qf(){return Hf}function tp(){return Hf?!1:(Hf=!0,!0)}function Pw(){Hf=!1}async function Vf(n={}){if(!In())return{ok:!1,stop:"not-here"};if(!tp())return{ok:!1,stop:"used"};let t=async()=>{let r;try{r=Tw(n)}catch{return{ok:!1,stop:"unreachable"}}if(!await Ow(r))return{ok:!1,stop:"unreachable"};if(!await Promise.resolve().then(()=>r.isAuthenticated({})).then(c=>c?.authenticated===!0,()=>!1))return{ok:!1,stop:"locked"};let o=await Promise.resolve().then(()=>r.getPublicKey({identityKey:!0})).then(c=>c.publicKey,()=>null);return o?uc(o)?{ok:!0,wallet:r,identityKey:o}:{ok:!1,stop:"unknown-key"}:{ok:!1,stop:"unreachable"}},e,i=await Promise.race([t().catch(()=>({ok:!1,stop:"unreachable"})),new Promise(r=>e=setTimeout(()=>r({ok:!1,stop:"slow"}),n.windowMs??Yh))]);return clearTimeout(e),i}var Ew=!1,q6=()=>{try{return globalThis.process?.env?.NODE_ENV==="production"}catch{return!1}};function Kf(n){return!n.verifyUrl||n.logoutUrl||Ew||q6()||typeof console>"u"?!1:(Ew=!0,console.warn(`@bwalletx/connect: ${n.where} has a verify URL but no logout URL. Set it: "Not you? Use another wallet" and Disconnect must be able to end a session the verify route created.`),!0)}var Ci="bwalletx";function Un(n){return n.substrate?n.substrate:n.kind==="pairing"?"pairing":n.isBwalletX&&n.kind==="brc100"?n.rdns===Mn?"in-app":n.id==="bwalletx-xdm"?"xdm":"extension":n.kind==="handcash"||n.kind==="custom"?"adapter":n.rdns===Ln?"extension":n.rdns===Mn?"in-app":n.id==="window.CWI"?"window.CWI":n.id==="localhost:3321"||n.id===Ir?"json-api":n.id==="localhost:3301"?"cicada":"injected"}function Dn(n){return n.isBwalletX?Ci:n.rdns??n.id}var V6=["extension","in-app","xdm"];function Bi(n){return n.isBwalletX&&n.kind==="brc100"&&!!n.wallet&&V6.includes(Un(n))}function Ro(n){return n.some(Bi)}function No(n){return n.filter(t=>!t.isBwalletX&&t.kind==="brc100"&&!!t.wallet)}function zf(n){let t=e=>Bi(e)?0:e.isBwalletX?1:e.kind==="brc100"?2:e.kind==="custom"?3:4;return n.map((e,i)=>({o:e,i})).sort((e,i)=>t(e.o)-t(i.o)||e.i-i.i).map(e=>e.o)}function Xf(n,t={}){if(t.walletId){let i=n.find(r=>r.id===t.walletId);if(i)return{option:i,reason:"requested"}}if(t.chooser)return{option:null,reason:n.length||t.picker!==!1?"chooser":"none"};if(t.fastPath===!1){let i=Lf([...n],t.picker===!1);return i===void 0?{option:null,reason:"chooser"}:i===null?{option:null,reason:"none"}:{option:i,reason:"legacy"}}if(t.remembered&&!t.preferBwalletX){let i=Bo(n,t.remembered);if(i)return{option:i,reason:"remembered"}}let e=n.find(Bi);if(e)return{option:e,reason:"bwalletx"};if(t.picker===!1){let i=n.find(r=>r.isBwalletX);return i?{option:i,reason:"bwalletx-phone"}:{option:null,reason:"none"}}return n.length?{option:null,reason:"chooser"}:{option:null,reason:"none"}}function Er(n){let t=n;return t?.code==="NOT_FOUND"?"not-found":t?.name==="AbortError"||t?.message==="cancelled"?"cancelled":oc(n)?"rejected":"error"}function ai(n,t,e,i=Date.now()){return{walletType:n?Dn(n):null,substrate:n?Un(n):null,outcome:t,ms:Math.max(0,Math.round(i-e))}}function kr(n,t){if(n)try{n(Object.freeze({walletType:t.walletType,substrate:t.substrate,outcome:t.outcome,ms:t.ms}))}catch{}}var fc="bwx:wallet",K6=["extension","in-app","xdm","injected","window.CWI","json-api","cicada","pairing","adapter"],Rw=/^[A-Za-z0-9._:-]{1,64}$/,Nw=/^(0[23][0-9a-f]{64}|04[0-9a-f]{128}|[13][1-9A-HJ-NP-Za-km-z]{25,34})$/i;function jf(n){let t=Dn(n);return Un(n)!=="window.CWI"&&Rw.test(t)&&!Nw.test(t)}function _o(n,t){return n.isBwalletX||t==="chooser"||t==="requested"||t==="remembered"}function ci(n){try{if(!n)return void globalThis.localStorage?.removeItem(fc);if(!jf(n))return;let t={type:Dn(n),substrate:Un(n),v:1};globalThis.localStorage?.setItem(fc,JSON.stringify(t))}catch{}}function Li(){try{let n=globalThis.localStorage?.getItem(fc);if(!n)return null;let t=JSON.parse(n);return typeof t.type!="string"||!Rw.test(t.type)||Nw.test(t.type)||!K6.includes(t.substrate)||t.substrate==="window.CWI"?null:{type:t.type,substrate:t.substrate}}catch{return null}}function Rs(){ci(null)}function Co(n){return!!n&&n!==Ci}function lc(n){return Co(n)&&n!==Sn&&n!==Ir}function Gf(n){return n.type===Sn||n.type===Ir||n.substrate==="json-api"||n.substrate==="cicada"}function Bo(n,t){return Gf(t)?null:t.type===Ci?(t.substrate==="pairing"?n.find(e=>e.kind==="pairing"):n.find(Bi))??null:n.find(e=>!e.isBwalletX&&!ic(e)&&jf(e)&&Dn(e)===t.type)??null}var ep=["extension","in-app","xdm","injected"];function _w(n){let t=n.remembered;return!t||n.enabled===!1?{action:"none",remembered:t,needsBwalletX:!1}:t.type===Sn?{action:n.metanetHere??In()?"silent-metanet":"none",remembered:t,needsBwalletX:!1}:Gf(t)?{action:"none",remembered:t,needsBwalletX:!1}:{action:n.signedIn&&ep.includes(t.substrate)?"attach":"wait-for-tap",remembered:t,needsBwalletX:Co(t.type)}}async function Cw(n,t={}){if(!ep.includes(n.substrate))return null;let e=await ks({ms:t.ms}),i=Bo(e,n);return i&&i.kind==="brc100"&&i.wallet&&ep.includes(Un(i))?i:null}var Hw=O1(Uw(),1);var z6=`
25
+ .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}
26
+ .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)}
27
+ .bwx-box h2{margin:0 0 6px;font-size:18px;color:#e8c766}
28
+ .bwx-box p{margin:0 0 14px;color:#bdb6a3;font-size:14px}
29
+ .bwx-qr{background:#fff;border-radius:12px;padding:12px;display:flex;justify-content:center}
30
+ .bwx-qr svg{width:100%;height:auto;max-width:260px}
31
+ .bwx-code{margin:14px 0 0;text-align:center;font-size:28px;letter-spacing:.3em;color:#e8c766;font-variant-numeric:tabular-nums}
32
+ .bwx-row{display:flex;gap:8px;margin-top:14px}
33
+ .bwx-btn{flex:1;border:1px solid #3a3220;background:#15130e;color:#f4f1e8;border-radius:10px;padding:10px 12px;font:inherit;cursor:pointer}
34
+ .bwx-btn:hover{border-color:#e8c766}
35
+ a.bwx-btn{display:block;text-align:center;text-decoration:none;box-sizing:border-box}
36
+ .bwx-primary{background:linear-gradient(180deg,#fcd34d,#f59e0b);color:#000;border:0;font-weight:700;min-height:48px;padding:13px 12px}
37
+ .bwx-stack{display:flex;flex-direction:column;gap:8px}
38
+ .bwx-list{display:flex;flex-direction:column;gap:8px}
39
+ .bwx-opt{display:flex;align-items:center;gap:10px;text-align:left}
40
+ .bwx-opt img{width:24px;height:24px;border-radius:6px}
41
+ .bwx-tag{margin-left:auto;font-size:11px;color:#8d866f;white-space:nowrap}
42
+ .bwx-opt{min-height:48px;box-sizing:border-box}
43
+ a.bwx-btn.bwx-opt{display:flex;text-align:left}
44
+ .bwx-btn:focus{outline:none}
45
+ .bwx-btn:focus-visible{outline:2px solid #e8c766;outline-offset:2px}
46
+ .bwx-mk{display:inline-flex;align-items:center;justify-content:center;flex:none;width:28px;height:28px;border-radius:50%;background:#000}
47
+ .bwx-ico{display:inline-grid;place-items:center;flex:none;width:28px;height:28px;border-radius:8px;background:#2a2518;color:#e8c766;font-weight:700;font-size:13px}
48
+ .bwx-opt img{width:28px;height:28px;border-radius:8px;flex:none}
49
+ .bwx-txt{display:flex;flex-direction:column;min-width:0;gap:1px}
50
+ .bwx-txt b{font-weight:600}
51
+ .bwx-txt small{font-size:12px;color:#8d866f;font-weight:400}
52
+ .bwx-primary .bwx-txt small{color:rgba(0,0,0,.68)}
53
+ .bwx-primary .bwx-tag{color:rgba(0,0,0,.6)}
54
+ .bwx-sep{font-size:12px;color:#8d866f;margin:6px 2px 0}
55
+ .bwx-foot{font-size:12px;color:#8d866f;margin:12px 0 0}
56
+ `;function np(){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=z6;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 wt(n,t,e){let i=document.createElement(n);return t&&(i.className=t),e!=null&&(i.textContent=e),i}function ip(n){let t=(0,Hw.default)(0,"M");return t.addData(n),t.make(),t.createSvgTag({cellSize:4,margin:2,scalable:!0})}function Lo(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=np();let o=n.mode==="app"||(n.mode??"auto")==="auto"&&Os(),c=wt("h2","",n.title??"Connect bWalletX"),u=wt("button","bwx-btn","Cancel");if(u.onclick=()=>{n.onCancel?.(),t.abort()},i=wt("div","bwx-code",""),i.setAttribute("aria-live","polite"),o){let m=wt("p","","Open bWalletX, approve, then come back to this page."),b=wt("div","bwx-stack"),y=wt("a","bwx-btn bwx-primary","Open bWalletX");y.href=s,y.rel="noopener";let S=wt("button","bwx-btn","Use web.bwalletx.com instead");S.onclick=()=>{navigator.clipboard?.writeText(s).catch(()=>{}),window.open(hc,"_blank","noopener"),m.textContent="Link copied. In web.bwalletx.com tap Connect and paste it, then come back here."},b.append(y,S,u),e.box.append(c,m,i,b);return}let f=wt("p","","Scan with bWalletX on your phone, or paste the link into web.bwalletx.com."),d=wt("div","bwx-qr");d.innerHTML=ip(s);let h=wt("div","bwx-row"),l=wt("button","bwx-btn","Copy link");l.onclick=()=>{navigator.clipboard?.writeText(s).then(()=>l.textContent="Copied")},h.append(l,u),e.box.append(c,f,d,i,h)},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 $w(n,t={}){return typeof document>"u"?Promise.resolve(null):new Promise(e=>{let i=np(),r=c=>{i.close(),e(c)};i.box.append(wt("h2","",t.title??"Choose a wallet")),n.length||i.box.append(wt("p","","No wallet found. Get bWalletX at bwalletx.com."));let s=wt("div","bwx-list");for(let c of n){let u=wt("button","bwx-btn bwx-opt");if(c.icon){let f=wt("img");f.src=c.icon,f.alt="",u.append(f)}u.append(wt("span","",c.name)),c.kind==="handcash"&&u.append(wt("span","bwx-tag","until BRC-100")),u.onclick=()=>r(c),s.append(u)}let o=wt("button","bwx-btn","Cancel");o.onclick=()=>r(null),i.root.onclick=c=>c.target===i.root&&r(null),i.box.append(s,wt("div","bwx-row")),i.box.lastChild.append(o)})}function Dw(n,t,e,i){let r=wt("button",`bwx-btn bwx-opt${t?" bwx-primary":""}`);if(r.type="button",r.dataset.wallet=n.id,n.isBwalletX){let o=wt("span","bwx-mk");o.innerHTML=Tr(18),r.append(o)}else if(n.icon){let o=wt("img");o.src=n.icon,o.alt="",r.append(o)}else r.append(wt("span","bwx-ico",(n.name.trim().charAt(0)||"W").toUpperCase()));let s=wt("span","bwx-txt");return s.append(wt("b","",n.name)),e&&s.append(wt("small","",e)),r.append(s),i&&r.append(wt("span","bwx-tag",i)),r}function Yf(n,t={}){return typeof document>"u"?Promise.resolve(null):new Promise(e=>{let i=np();i.root.dataset.bwxChooser="";let r=m=>{document.removeEventListener("keydown",s,!0),i.close(),e(m)},s=m=>{m.key==="Escape"&&(m.preventDefault(),r(null))};document.addEventListener("keydown",s,!0),i.box.append(wt("h2","",t.title??"Choose a wallet"));let o=wt("div","bwx-list"),c=Ro(n);if(!c){let m=wt("a","bwx-btn bwx-opt bwx-primary");m.href=t.getUrl??dc,m.target="_blank",m.rel="noopener",m.dataset.wallet="get-bwalletx";let b=wt("span","bwx-mk");b.innerHTML=Tr(18);let y=wt("span","bwx-txt");y.append(wt("b","","Get bWalletX"),wt("small","","Free. Every feature on this site")),m.append(b,y),o.append(m)}let u=zf(n),f=Os(),d=!1;for(let m of u){!c&&!d&&(o.append(wt("p","bwx-sep","Or use")),d=!0);let b=Bi(m)?"Recommended":m.kind==="pairing"?f?"Open the bWalletX app":"Scan a QR with your phone":void 0,y=m.kind==="handcash"?"until BRC-100":!m.isBwalletX&&m.kind==="brc100"?"Fewer features":void 0,S=Dw(m,Bi(m),b,y);S.onclick=()=>r(m),o.append(S)}if(t.desktop!==!1&&In()&&!n.some(m=>m.substrate==="json-api"||m.substrate==="cicada")){!c&&!d&&o.append(wt("p","bwx-sep","Or use"));let m=_i(),b=Dw(m,!1,Po);b.title="Connects to Metanet Desktop on this computer, never to a browser extension.",b.onclick=()=>r(m),o.append(b)}i.box.append(o),(No(n).length||!c)&&i.box.append(wt("p","bwx-foot","Some features need bWalletX."));let h=wt("div","bwx-row"),l=wt("button","bwx-btn","Cancel");l.type="button",l.onclick=()=>r(null),h.append(l),i.box.append(h),i.root.onclick=m=>m.target===i.root&&r(null),o.querySelector("a,button")?.focus()})}var Ww=1,Zf=[2,"bwalletx access"];var Fw=50,qw={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},Ct=class extends Error{constructor(e,i,r={}){super(i??e);w(this,"code");w(this,"have");w(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}},rp={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 Vw(n,t,e="latest"){return`https://unpkg.com/@bwalletx/connect@${e}/${rp[n][t]}`}function pc(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=>pc(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)}:${pc(t[i])}`).join(",")}}`}throw new Error(`canonicalJson: unsupported ${typeof n}`)}function sp(n){return Array.from(new TextEncoder().encode(n))}var X6=/^bsv21:[0-9a-f]{64}_\d{1,6}$/,j6=/^[1-9]\d{0,38}$/;function G6(n){if(!n||typeof n!="object")throw new Ct("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 Ct("bad_request","require.token.id is required");let r=i.id.trim().toLowerCase();if(!X6.test(r))throw new Ct("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 Ct("bad_request","require.token needs exactly one of min or minBps");if(e.token={id:r},s){if(typeof i.min!="string"||!j6.test(i.min))throw new Ct("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 Ct("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 Ct("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 Ct("bad_request","require.kyc must be a boolean");t.kyc&&(e.kyc=!0)}if(!e.token&&!e.identityLevel&&!e.kyc)throw new Ct("bad_request","require is empty");return e}function Kw(n){if(typeof n!="string"||n.length>4096)throw new Ct("bad_request","challenge must be a string");let t;try{t=JSON.parse(n)}catch{throw new Ct("bad_request","challenge is not JSON")}if(!t||typeof t!="object"||t.v!==1)throw new Ct("bad_request","unsupported challenge version");if(t.kind!=="401"&&t.kind!=="402"&&t.kind!=="403")throw new Ct("bad_request","bad kind");if(typeof t.origin!="string"||typeof t.nonce!="string"||!/^[A-Za-z0-9_-]{16,64}$/.test(t.nonce))throw new Ct("bad_request","bad origin or nonce");if(!Number.isInteger(t.iat)||!Number.isInteger(t.exp)||t.exp<=t.iat)throw new Ct("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 Ct("bad_request","bad sub");if(t.require=G6(t.require),pc(t)!==n)throw new Ct("bad_request","challenge is not canonical");return t}function zw(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 Y6=[0,"onesat"],Z6=[0,"p 1sat"];function Jf(n){if(n instanceof Ct)return n;let t=n,e=String(t?.message??n??"");return t?.code==="NOT_FOUND"?new Ct("not_installed",e):/reject|denied|declin|cancel|user/i.test(e)||t?.code==="ERR_USER_REJECTED"||t?.status===4001?new Ct("user_rejected",e):new Ct("bad_request",e||"access failed")}function op(n){let t=n;if(t&&typeof t.error=="string")throw new Ct(t.error,t.message,{have:t.have,need:t.need})}function J6(n){let t=/^76a914([0-9a-f]{40})88ac$/i.exec(n.slice(-50));return t?t[1].toLowerCase():null}async function ap(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=sp(t);for(let u of s.outputs){if(o.size>=Fw)break;let f={};try{f=JSON.parse(u.customInstructions??"{}")}catch{continue}if(f.id!==r||!f.keyID)continue;let d=u.lockingScript?J6(u.lockingScript):null,h=f.counterparty??"self";for(let l of f.protocolID?[f.protocolID]:[Y6,Z6]){let{publicKey:m}=await n.getPublicKey({protocolID:l,keyID:f.keyID,counterparty:h}),b=Yi.toHex(Vc.hash160(jt.fromString(m).encode(!0)));if(d&&b!==d)continue;let y=o.get(m);if(y){y.outpoints.push(u.outpoint.replace(".","_"));break}let{signature:S}=await n.createSignature({protocolID:l,keyID:f.keyID,counterparty:h,data:c});o.set(m,{pubkey:m,signature:Array.from(S),outpoints:[u.outpoint.replace(".","_")]});break}}return[...o.values()]}async function Qf(n){let t;try{({wallet:t}=await vs({wallet:n.wallet,pairing:n.pairing,discoverMs:n.discoverMs}))}catch(e){throw e?.code==="NOT_FOUND"?new Ct("not_installed"):Jf(e)}try{let{publicKey:e}=await t.getPublicKey({identityKey:!0}),{challenge:i}=await n.challenge(e),r=Kw(i);if(r.sub&&r.sub!==e.toLowerCase())throw new Ct("wrong_account");if(Date.now()/1e3>=r.exp)throw new Ct("expired");let{signature:s}=await t.createSignature({protocolID:Zf,keyID:r.nonce,counterparty:"anyone",data:sp(i)}),o={v:1,challenge:i,identityKey:e,signature:Array.from(s)};r.require.token&&(o.holdings=await ap(t,i,r.require.token.id,n.tokenBasket));let c;return n.verify&&(c=await n.verify(o),op(c)),{response:o,verified:c,wallet:t}}catch(e){throw Jf(e)}}async function jw(n){let t=Date.now(),{list:e}=n,i=null,r="none";try{if(n.metanet){if(!In())throw Object.assign(new Error("Metanet Desktop runs on a computer, outside any frame."),{code:"NOT_SUPPORTED"});return i=_i(typeof n.metanet=="object"?n.metanet:{}),r="requested",await Xw(n,i,r,t)}let s=Xf(e,{walletId:n.walletId,chooser:n.chooser,picker:n.picker,fastPath:n.fastPath,remembered:n.remembered,preferBwalletX:n.preferBwalletX});if(i=s.option,r=s.reason,!i&&s.reason==="chooser"&&(i=await n.pick(e)),!i){if(s.reason==="none"||!e.length)throw Object.assign(new Error("No wallet found. Get bWalletX at bwalletx.com."),{code:"NOT_FOUND"});return kr(n.onAttempt,ai(null,"cancelled",t)),null}return await Xw(n,i,r,t)}catch(s){throw kr(n.onAttempt,ai(i,Er(s),t)),s}}async function Xw(n,t,e,i){let r=!!(n.challengeUrl&&n.verifyUrl)&&t.kind!=="handcash",s=await t.connect(r?{identity:!1}:void 0),o=s.handle??null,c=s.paymail??null,u=s.identityKey,f=!1;if(s.wallet&&r){let{result:d,verified:h}=await Es({wallet:s.wallet,identityKey:s.identityKey??void 0,skipWaitForAuthentication:t.id===Ar,identityKeyHint:vr(),challengeNeedsIdentityKey:n.challengeNeedsIdentityKey,challenge:l=>n.post(n.challengeUrl,l?{identityKey:l}:{}),verify:l=>n.post(n.verifyUrl,{identityKey:l.identityKey,nonce:l.nonce,signature:l.signature})});Ts(d.identityKey),u=d.identityKey,o=h.handle??o,c=h.paymail??c,f=!0}else s.wallet&&!u&&(u=(await s.wallet.getPublicKey({identityKey:!0})).publicKey);return n.remember&&_o(t,e)&&ci(t),n.remember&&f&&Ps(u),kr(n.onAttempt,ai(t,f?"signed-in":"connected",i)),{connected:s,identityKey:u,handle:o,paymail:c,signedIn:f,walletType:Dn(t),substrate:Un(t),reason:e}}async function tl(n={}){let t=await Vf(n);if(!t.ok||n.isAbandoned?.())return null;let e=Date.now(),i=_i(n);i.wallet=t.wallet;let r={wallet:t.wallet,payer:t.wallet,identityKey:t.identityKey,optionId:Ar,kind:"brc100"},s=(o,c=null,u=null)=>(ci(i),o&&Ps(t.identityKey),kr(n.onAttempt,ai(i,o?"signed-in":"connected",e)),{connected:r,identityKey:t.identityKey,handle:c,paymail:u,signedIn:o,walletType:Dn(i),substrate:"json-api",reason:"remembered"});if(n.sessionKey!==void 0&&n.sessionKey!==null)return n.sessionKey.toLowerCase()===t.identityKey.toLowerCase()?s(!0):null;if(!n.challengeUrl||!n.verifyUrl||!n.post)return s(!1);if(!uc(t.identityKey))return null;try{n.onSignIn?.();let o=n.post,{result:c,verified:u}=await Es({wallet:t.wallet,identityKey:t.identityKey,skipWaitForAuthentication:!0,challenge:f=>o(n.challengeUrl,f?{identityKey:f}:{}),verify:f=>o(n.verifyUrl,{identityKey:f.identityKey,nonce:f.nonce,signature:f.signature})});return n.isAbandoned?.()?(await Promise.resolve(n.logout?.()).catch(()=>{}),null):(Ts(c.identityKey),s(!0,u.handle??null,u.paymail??null))}catch(o){return kr(n.onAttempt,ai(i,Er(o),e)),null}}var lp="bwalletx-signin",dc="https://bwalletx.com/get",hc="https://web.bwalletx.com",Gw={signin:"Sign in with",continue:"Continue with",connect:"Connect",get:"Get",play:"Play with"};function dp(n="signin",t="bWalletX"){return`${Gw[n]??Gw.signin} ${t}`}var Q6=0;function Tr(n=20){let t=++Q6;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 Mo=`
25
57
  :host{display:inline-block;vertical-align:middle;font-family:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
26
58
  :host([full-width]){display:block;width:100%}
27
59
  :host([hidden]){display:none}
@@ -67,29 +99,69 @@ button[aria-busy=true]{cursor:wait}
67
99
  .nf a:focus-visible{outline:2px solid #b45309;outline-offset:2px;border-radius:2px}
68
100
  :host([theme=dark]) .nf,:host-context(.dark) .nf{color:#a1a1aa}
69
101
  .sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
70
- `;function pb(n){let t="";for(let e of n)t+=String.fromCharCode(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ol(n){let t=u=>pb(crypto.getRandomValues(new Uint8Array(u))),e=t(32),i=t(16),r=t(16),s=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))),o=new URL(n.authorizeUrl,typeof location<"u"?location.href:void 0),c=(u,f)=>{f&&o.searchParams.set(u,f)};c("response_type","code"),c("client_id",n.clientId),c("redirect_uri",n.redirectUri),c("scope",n.scope||"openid profile"),c("state",i),c("nonce",r),c("code_challenge",pb(s)),c("code_challenge_method","S256");try{sessionStorage.setItem("bwalletx:oauth",JSON.stringify({verifier:e,state:i,nonce:r}))}catch{}return o.toString()}async function Qd(n,t){let e=await fetch(n,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),i=await e.json().catch(()=>({}));if(!e.ok)throw new Error(i.error??`HTTP ${e.status}`);return i}async function d4(n,t){let e=await fetch(n,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify(t)});return e.json().catch(()=>({error:"bad_request",message:`HTTP ${e.status}`}))}var l4=["size","theme","label","brand","subtitle","loading","disabled","full-width","aria-label","get-url","web-url"];function h4(){var n,t,e,i,Qt,wu,zi,tl,gb,f;return f=class extends HTMLElement{constructor(){super();G(this,i);G(this,n);G(this,t,!1);G(this,e,!1);N(this,n,this.attachShadow({mode:"open"}))}static get observedAttributes(){return l4}connectedCallback(){a(this,i,wu).call(this)}attributeChangedCallback(){this.isConnected&&a(this,i,wu).call(this)}get button(){return y(this,n).querySelector("button")}get notFound(){return y(this,t)}focus(p){this.button?.focus(p)}},n=new WeakMap,t=new WeakMap,e=new WeakMap,i=new WeakSet,Qt=function(p){return this.getAttribute(p)},wu=function(){let p=a(this,i,Qt).call(this,"size")??"lg",m=a(this,i,Qt).call(this,"brand")==="bWallet"?"bWallet":"bWalletX",g=il(a(this,i,Qt).call(this,"label")??"signin",m),w=a(this,i,Qt).call(this,"subtitle"),C=w===null||w===""||w==="on"?w==="on"?"also works with bWallet":m==="bWalletX"&&(p==="lg"||p==="md")?"also works with bWallet":null:w==="off"?null:w,E=this.hasAttribute("loading")||y(this,e),A=this.hasAttribute("disabled"),k=p==="icon"?24:p==="sm"?15:p==="md"?17:20,B=a(this,i,Qt).call(this,"aria-label")??(C&&p!=="icon"?`${g}, ${C}`:g),_=a(this,i,Qt).call(this,"get-url")??nl,H=a(this,i,Qt).call(this,"web-url")??ra,O=F=>F.replace(/[&<>"]/g,it=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[it]),I=p==="icon"?"":`<span class="txt" part="text"><b part="label">${O(g)}</b>${C?`<small part="subtitle">${O(C)}</small>`:""}</span>`,U=E?'<span class="spin" aria-hidden="true"></span>':rl(k),M=y(this,t)?`<p class="nf" part="not-found" role="status">bWalletX wasn't found in this browser. <a href="${O(_)}" target="_blank" rel="noopener">Get ${m}</a> or <a href="${O(H)}" target="_blank" rel="noopener">use the web wallet</a>.</p>`:"";y(this,n).innerHTML=`<style>${sl}</style><button type="button" part="button" aria-label="${O(B)}" title="${O(C?`${g} (${C})`:g)}"${A?" disabled":""}${E?' aria-busy="true"':""}><span class="mark" part="mark">${U}</span>${I}</button>${E?'<span class="sr" role="status">Connecting to bWalletX\u2026</span>':""}${M}`,this.button.addEventListener("click",()=>{a(this,i,gb).call(this)}),fu(this.button)},zi=function(p,m,g=!1){return this.dispatchEvent(new CustomEvent(p,{detail:m,bubbles:!0,composed:!0,cancelable:g}))},tl=function(p){N(this,e,p),a(this,i,wu).call(this)},gb=async function(){if(this.hasAttribute("disabled")||this.hasAttribute("loading")||y(this,e)||!a(this,i,zi).call(this,"bwalletx-signin",{element:this},!0))return;let p=a(this,i,Qt).call(this,"href"),m=a(this,i,Qt).call(this,"authorize-url");if(m){location.assign(await ol({authorizeUrl:m,clientId:a(this,i,Qt).call(this,"client-id"),redirectUri:a(this,i,Qt).call(this,"redirect-uri"),scope:a(this,i,Qt).call(this,"scope")}));return}if(p){location.assign(p);return}let g=a(this,i,Qt).call(this,"challenge-url");if(g){N(this,t,!1),a(this,i,tl).call(this,!0);try{let w=Number(a(this,i,Qt).call(this,"discover-ms"))||Vi,S=await Ki(w);if(!S){N(this,t,!0),a(this,i,zi).call(this,"bwalletx-not-found"),a(this,i,Qt).call(this,"require-token")&&a(this,i,zi).call(this,"bwalletx-access-denied",{code:"not_installed",message:"No wallet found"});return}let C=a(this,i,Qt).call(this,"require-token");if(C){let B=a(this,i,Qt).call(this,"verify-url"),_=a(this,i,Qt).call(this,"min"),H=a(this,i,Qt).call(this,"min-bps"),O={token:{id:C,...H?{minBps:Number(H)}:{min:_??"1"}}};try{let I=await bu({wallet:S.wallet,challenge:U=>Qd(g,{identityKey:U,require:O}),verify:B?U=>d4(B,U):void 0});a(this,i,zi).call(this,"bwalletx-access-granted",{identityKey:I.response.identityKey,response:I.verified})}catch(I){let U=I instanceof kt?I:new kt("bad_request",String(I));a(this,i,zi).call(this,"bwalletx-access-denied",{code:U.code,message:U.message,have:U.have,need:U.need})}return}let E=await pu({wallet:S.wallet,challenge:B=>Qd(g,{identityKey:B})}),A=a(this,i,Qt).call(this,"verify-url"),k=A?await Qd(A,{identityKey:E.identityKey,nonce:E.nonce,signature:E.signature}):null;a(this,i,zi).call(this,"bwalletx-signed-in",{identityKey:E.identityKey,method:S.method,nonce:E.nonce,signature:E.signature,response:k})}catch(w){a(this,i,zi).call(this,"bwalletx-error",{error:w})}finally{a(this,i,tl).call(this,!1)}}},f}function yu(n=el){if(typeof window>"u"||typeof customElements>"u")return;let t=customElements.get(n);if(t)return t;let e=h4();return customElements.define(n,e),e}var p4=`
102
+ /* pending: one plain line under the button */
103
+ .note{margin:8px 0 0;width:0;min-width:100%;font-size:12px;line-height:1.4;color:#71717a;text-align:center;overflow-wrap:break-word}
104
+ :host([theme=dark]) .note,:host-context(.dark) .note{color:#a1a1aa}
105
+ /* "Other wallets" (0.5.6): one small link under the button */
106
+ .ow{margin:8px 0 0;width:0;min-width:100%;font-size:12px;line-height:1.4;color:#71717a;text-align:center}
107
+ :host([theme=dark]) .ow,:host-context(.dark) .ow{color:#a1a1aa}
108
+ .sw{margin:8px 0 0;width:0;min-width:100%;font-size:12px;line-height:1.4;color:#a16207;text-align:center}
109
+ :host([theme=dark]) .sw,:host-context(.dark) .sw{color:#fcd34d}
110
+ .mn{margin:8px 0 0;width:0;min-width:100%;font-size:12px;line-height:1.4;color:#71717a;text-align:center}
111
+ .mn small{display:block;font-size:11px;opacity:.85}
112
+ :host([theme=dark]) .mn,:host-context(.dark) .mn{color:#a1a1aa}
113
+ .lnk{all:unset;cursor:pointer;color:inherit;font-weight:600;text-decoration:underline;text-underline-offset:2px}
114
+ .lnk:focus-visible{outline:2px solid #b45309;outline-offset:2px;border-radius:2px}
115
+ /* error: one line plus Retry */
116
+ .err{margin:0 0 8px;width:0;min-width:100%;font-size:13px;font-weight:600;line-height:1.4;color:#b91c1c;text-align:center;overflow-wrap:anywhere}
117
+ :host([theme=dark]) .err,:host-context(.dark) .err{color:#fca5a5}
118
+ /* signed in: the badge */
119
+ button.chip{display:inline-flex;align-items:center;justify-content:flex-start;gap:10px;width:auto;max-width:100%;padding:5px 14px 5px 5px;border-radius:999px;
120
+ background:#0b0b0c;color:#ffd24d;border:1px solid rgba(255,210,77,.55);box-shadow:none;font-size:15px}
121
+ button.chip:hover{background:#151517;border-color:#ffd24d}
122
+ button.chip:active{background:#000;transform:none}
123
+ button.chip:focus-visible{outline:2px solid #ffd24d;outline-offset:3px}
124
+ :host([theme=light]) button.chip{background:#fff;color:#09090b;border-color:#f59e0b}
125
+ :host([theme=light]) button.chip:hover{background:#fffbeb}
126
+ :host([full-width]) button.chip{width:100%}
127
+ .av{position:relative;flex:none;display:inline-grid;place-items:center;width:30px;height:30px;border-radius:50%;overflow:hidden;
128
+ background:radial-gradient(circle at 30% 30%,#ffe27a,#f5b800 55%,#b88600);color:#000;font-weight:800;font-size:14px}
129
+ .av img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
130
+ .name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;max-width:min(52vw,260px)}
131
+ .dot{flex:none;width:8px;height:8px;border-radius:50%;background:#ffd24d;box-shadow:0 0 0 3px rgba(255,210,77,.22)}
132
+ :host([size=sm]) button.chip{font-size:13px;padding:3px 12px 3px 3px;gap:8px}
133
+ :host([size=sm]) .av{width:26px;height:26px}
134
+ :host([size=icon]) button.chip{width:48px;height:48px;padding:0;justify-content:center}
135
+ :host([size=icon]) .name,:host([size=icon]) .dot{display:none}
136
+ :host([size=icon]) .av{width:40px;height:40px}
137
+ `,rl=`
138
+ :host{all:initial}
139
+ .menu{position:fixed;z-index:2147483600;box-sizing:border-box;min-width:200px;padding:6px;border-radius:14px;background:#0b0b0c;color:#ffd24d;
140
+ border:1px solid rgba(255,210,77,.55);box-shadow:0 12px 32px rgba(0,0,0,.45);font:600 14px/1.3 Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
141
+ .who{padding:8px 10px 10px;font-size:12px;font-weight:500;color:#e7d9a8;overflow-wrap:anywhere;border-bottom:1px solid rgba(255,210,77,.3);margin-bottom:4px}
142
+ .item{all:unset;box-sizing:border-box;display:block;width:100%;padding:11px 10px;border-radius:10px;cursor:pointer;color:#ffd24d}
143
+ .item:hover,.item:focus-visible{background:#ffd24d;color:#000;outline:none}
144
+ .tip{position:fixed;z-index:2147483600;box-sizing:border-box;padding:8px 12px;border-radius:10px;background:#0b0b0c;color:#e7d9a8;
145
+ border:1px solid rgba(255,210,77,.4);box-shadow:0 8px 24px rgba(0,0,0,.35);font:500 12px/1.4 Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
146
+ `,sl="Sign in: shares only your public identity key, moves no money",yc="Approve in bWalletX\u2026",wc="Approve in your wallet\u2026",ol="Some features need bWalletX",hp="Continue with your wallet";function tS(n){return`<svg viewBox="0 0 24 24" width="${n}" height="${n}" aria-hidden="true" focusable="false" fill="none" stroke="#FFD24D" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 7V5a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2"/><path d="M3 6v12a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-3"/></svg>`}function Yw(n){let t="";for(let e of n)t+=String.fromCharCode(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function pp(n){let t=u=>Yw(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",Yw(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 el(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 Object.assign(new Error(i.error??`HTTP ${e.status}`),{status:e.status});return i}async function eS(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 nS=["size","theme","label","brand","subtitle","loading","disabled","full-width","aria-label","get-url","web-url","state","identity-key","paymail","handle","avatar-url","error","other-wallets","challenge-url","wallet-type","switch-note","remember","metanet"],iS=["signed-out","restoring","pending","signed-in","error"];function rS(){var n,t,e,i,r,s,o,c,u,f,d,h,l,Ye,gc,gt,Zw,Mi,nl,Ui,E,Jw,il,cp,Ze,Qw,Or,up,t1,e1,mc,n1,fp,Ns,i1,bc,Mt;return Mt=class extends HTMLElement{constructor(){super();z(this,l);z(this,n);z(this,t,!1);z(this,e,!1);z(this,i,"signed-out");z(this,r,null);z(this,s,"");z(this,o,!1);z(this,c,yc);z(this,u,null);z(this,f,null);z(this,d,!1);z(this,h,0);z(this,E,null);A(this,n,this.attachShadow({mode:"open"}))}static get observedAttributes(){return nS}connectedCallback(){!g(this,l,Ye)&&g(this,l,gc)&&Kf({verifyUrl:a(this,l,gt).call(this,"verify-url"),logoutUrl:a(this,l,gt).call(this,"logout-url"),where:"<bwalletx-signin>"}),a(this,l,Ui).call(this),a(this,l,Zw).call(this).then(()=>a(this,l,e1).call(this))}disconnectedCallback(){g(this,f)?.close(!1),a(this,l,il).call(this)}attributeChangedCallback(){this.isConnected&&a(this,l,Ui).call(this)}get button(){return g(this,n).querySelector("button")}get notFound(){return g(this,t)}get state(){let Y=a(this,l,gt).call(this,"state");return Y&&iS.includes(Y)?Y:g(this,i)}get account(){if(!g(this,l,Ye))return g(this,r);let Y=a(this,l,gt).call(this,"identity-key");return Y?{identityKey:Y,paymail:a(this,l,gt).call(this,"paymail"),handle:a(this,l,gt).call(this,"handle"),avatarUrl:a(this,l,gt).call(this,"avatar-url")}:null}get menuOpen(){return!!g(this,f)}focus(Y){this.button?.focus(Y)}async signOut(){if(g(this,f)?.close(!1),!a(this,l,Ze).call(this,"bwalletx-disconnect",{element:this,account:this.account},!0)||g(this,l,Ye))return;let Y=a(this,l,gt).call(this,"logout-url");Y&&await fetch(Y,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:"{}"}).catch(()=>{}),g(this,l,Or)&&Rs(),A(this,u,null),A(this,r,null),a(this,l,Mi).call(this,"signed-out"),a(this,l,Ze).call(this,"bwalletx-signed-out"),this.button?.focus()}otherWallets(){return a(this,l,bc).call(this,"chooser")}switchToBwalletX(){return a(this,l,bc).call(this,"bwalletx")}useMetanet(){return a(this,l,bc).call(this,"metanet")}notYou(){a(this,l,Ze).call(this,"bwalletx-not-you",{element:this},!0)&&(Ic(this,h)._++,g(this,l,Or)&&Rs(),A(this,u,null),g(this,d)&&!g(this,l,Ye)&&(A(this,d,!1),A(this,e,!1),g(this,i)==="pending"&&A(this,i,"signed-out")),a(this,l,Ui).call(this))}},n=new WeakMap,t=new WeakMap,e=new WeakMap,i=new WeakMap,r=new WeakMap,s=new WeakMap,o=new WeakMap,c=new WeakMap,u=new WeakMap,f=new WeakMap,d=new WeakMap,h=new WeakMap,l=new WeakSet,Ye=function(){return this.hasAttribute("state")},gc=function(){return!this.hasAttribute("stateless")},gt=function(Y){return this.getAttribute(Y)},Zw=async function(){let Y=a(this,l,gt).call(this,"session-url");if(!(g(this,o)||!Y||g(this,l,Ye)||!g(this,l,gc))){A(this,o,!0),a(this,l,Mi).call(this,"restoring");try{let N=await(await fetch(Y,{credentials:"include",headers:{accept:"application/json"}})).json().catch(()=>({}));if(g(this,i)!=="restoring")return;N.identityKey?a(this,l,nl).call(this,{identityKey:N.identityKey,handle:N.handle??null,paymail:N.paymail??null}):a(this,l,Mi).call(this,"signed-out")}catch{g(this,i)==="restoring"&&a(this,l,Mi).call(this,"signed-out")}}},Mi=function(Y){A(this,i,Y),Y!=="signed-in"&&g(this,f)?.close(!1),a(this,l,Ui).call(this)},nl=function(Y){A(this,r,Y),A(this,s,""),a(this,l,Mi).call(this,"signed-in");let pt=a(this,l,gt).call(this,"lookup-url");!Y.paymail&&pt!=="off"&&Uf(Y.identityKey,pt??void 0).then(N=>{N&&g(this,r)?.identityKey===Y.identityKey&&!g(this,r).paymail&&(A(this,r,{...g(this,r),paymail:N}),a(this,l,Ui).call(this))})},Ui=function(){let Y=a(this,l,gt).call(this,"size")??"lg",pt=a(this,l,gt).call(this,"brand")==="bWallet"?"bWallet":"bWalletX",N=$i=>$i.replace(/[&<>"]/g,xc=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[xc]),D=this.state,M=this.account;if(D==="signed-in"&&M){a(this,l,il).call(this);let $i=sc(M),xc=M.avatarUrl??Mf(M.identityKey),x1=($i.replace(/^\$/,"").charAt(0)||"b").toUpperCase();g(this,n).innerHTML=`<style>${Mo}</style><button type="button" class="chip" part="button chip" aria-haspopup="menu" aria-expanded="${g(this,f)?"true":"false"}" aria-label="Signed in with bWalletX as ${N($i)}. Account menu" title="Signed in as ${N($i)}"><span class="av" part="avatar" aria-hidden="true">${N(x1)}${xc?`<img alt="" src="${N(xc)}" referrerpolicy="no-referrer">`:""}</span><span class="name" part="label">${N($i)}</span><span class="dot" part="dot" aria-hidden="true"></span></button>`;let gl=g(this,n).querySelector("img");gl&&gl.addEventListener("error",()=>gl.remove(),{once:!0});let Lp=this.button;Lp.addEventListener("click",()=>g(this,f)?g(this,f).close(!0):a(this,l,cp).call(this)),Lp.addEventListener("keydown",Sc=>{(Sc.key==="ArrowDown"||Sc.key==="Enter"||Sc.key===" ")&&!g(this,f)&&(Sc.preventDefault(),a(this,l,cp).call(this))});return}let H=D==="pending",U=D==="restoring",Z=D==="error",rt=g(this,l,Ye)?yc:g(this,c),tt=D==="signed-out"&&lc(a(this,l,mc).call(this)),bt=H?rt:Z?"Retry":tt?hp:dp(a(this,l,gt).call(this,"label")??"signin",pt),Et=a(this,l,gt).call(this,"subtitle"),$t=H||Z||tt?null:Et===null||Et===""||Et==="on"?Et==="on"?"also works with bWallet":pt==="bWalletX"&&(Y==="lg"||Y==="md")?"also works with bWallet":null:Et==="off"?null:Et,Wt=this.hasAttribute("loading")||g(this,e)||H||U,ui=this.hasAttribute("disabled"),vn=Y==="icon"?24:Y==="sm"?15:Y==="md"?17:20,Be=H?rt:a(this,l,gt).call(this,"aria-label")??($t&&Y!=="icon"?`${bt}, ${$t}`:bt),oe=a(this,l,gt).call(this,"get-url")??dc,It=a(this,l,gt).call(this,"web-url")??hc,Jt=Z?(g(this,l,Ye)?a(this,l,gt).call(this,"error"):g(this,s))||"Sign-in failed":"",qt=Y==="icon"?"":`<span class="txt" part="text"><b part="label">${N(bt)}</b>${$t?`<small part="subtitle">${N($t)}</small>`:""}</span>`,Pr=Wt?'<span class="spin" aria-hidden="true"></span>':tt?tS(vn-4):Tr(vn),_s=a(this,l,gt).call(this,"other-wallets")==="off",Hi='<button type="button" class="lnk" data-act="other" part="other-wallets-link">Other wallets</button>',Je=g(this,t)?`<p class="nf" part="not-found" role="status">bWalletX wasn't found in this browser. <a href="${N(oe)}" target="_blank" rel="noopener">Get ${pt}</a> or <a href="${N(It)}" target="_blank" rel="noopener">use the web wallet</a>.${_s?"":` ${Hi}`}</p>`:"",Hn=!g(this,t)&&!H&&!U&&a(this,l,Qw).call(this,Y)?`<p class="ow" part="other-wallets">${Hi}</p>`:"",g1=!H&&!U&&a(this,l,n1).call(this,Y)?`<p class="sw" part="switch-note">${N(ol)} \xB7 <button type="button" class="lnk" data-act="switch" part="switch-link">Switch</button></p>`:"",m1=Z?`<p class="err" part="error" role="alert">${N(Jt)}</p>`:"",Np=a(this,l,up).call(this,Y),_p=Np&&(H?a(this,l,t1).call(this):!U&&a(this,l,mc).call(this)===Sn),Cp=`<button type="button" class="lnk" data-act="not-you" part="not-you-link">${N($f)}</button>`,b1=Np?H?_p?`<p class="mn" part="metanet">${N(cc)} ${Cp}</p>`:"":U?"":`<p class="mn" part="metanet"><button type="button" class="lnk" data-act="metanet" part="metanet-link" title="Connects to Metanet Desktop on this computer, never to a browser extension.">${N(ac)}</button><small>${N(Po)}</small>${_p?`<small>${N(cc)} ${Cp}</small>`:""}</p>`:"",Bp=Y==="sm"||Y==="icon",y1=H&&!Bp?`<p class="note" part="note">${N(sl)}</p>`:"",w1=H?`<span class="sr" role="status">${N(rt)}</span>`:Wt?'<span class="sr" role="status">Connecting to bWalletX\u2026</span>':"";g(this,n).innerHTML=`<style>${Mo}</style>${m1}<button type="button" part="button" aria-label="${N(Be)}" title="${N($t?`${bt} (${$t})`:bt)}"${ui?" disabled":""}${Wt?' aria-busy="true"':""}><span class="mark" part="mark">${Pr}</span>${qt}</button>${w1}${y1}${g1}${b1}${Hn}${Je}`,this.button.addEventListener("click",()=>{a(this,l,bc).call(this)});for(let $i of Array.from(g(this,n).querySelectorAll("[data-act=other]")))$i.addEventListener("click",()=>{this.otherWallets()});g(this,n).querySelector("[data-act=switch]")?.addEventListener("click",()=>{this.switchToBwalletX()}),g(this,n).querySelector("[data-act=metanet]")?.addEventListener("click",()=>{this.useMetanet()}),g(this,n).querySelector("[data-act=not-you]")?.addEventListener("click",()=>this.notYou()),Of(this.button),H&&Bp?a(this,l,Jw).call(this,sl):a(this,l,il).call(this)},E=new WeakMap,Jw=function(Y){let pt=this.button;if(!pt||typeof document>"u")return;if(!g(this,E)){let U=document.createElement("div");U.setAttribute("data-bwalletx-tip","");let Z=U.attachShadow({mode:"open"});Z.innerHTML=`<style>${rl}</style><div class="tip" role="note"></div>`,document.body.appendChild(U),A(this,E,U)}let N=g(this,E).shadowRoot.querySelector(".tip");N.textContent=Y;let D=pt.getBoundingClientRect(),M=window.innerWidth||document.documentElement.clientWidth||360,H=Math.min(280,M-32);N.style.width=`${H}px`,N.style.left=`${Math.max(16,Math.min(D.right-H,M-H-16))}px`,N.style.top=`${D.bottom+8}px`},il=function(){g(this,E)?.remove(),A(this,E,null)},cp=function(){let Y=this.account,pt=this.button;if(!Y||!pt||typeof document>"u")return;let N=sc(Y),D=document.createElement("div");D.setAttribute("data-bwalletx-menu","");let M=D.attachShadow({mode:"open"}),H=document.createElement("style");H.textContent=rl;let U=document.createElement("div");U.className="menu",U.setAttribute("role","menu"),U.setAttribute("aria-label","bWalletX account");let Z=document.createElement("div");Z.className="who",Z.textContent=`Signed in as ${Y.paymail||N}`;let rt=(It,Jt)=>{let qt=document.createElement("button");return qt.type="button",qt.className="item",qt.setAttribute("role","menuitem"),qt.tabIndex=-1,qt.textContent=It,qt.addEventListener("click",()=>Jt(qt)),qt},tt=Y.paymail?"paymail":"key",bt=rt(`Copy ${tt}`,It=>{Aw(Y.paymail||Y.identityKey).then(Jt=>{It.textContent=Jt?"Copied":`Copy ${tt}`,setTimeout(()=>oe(!0),Jt?600:0)})}),Et=rt("Disconnect",()=>{oe(!1),this.signOut()}),dt=[bt,Et];if(U.append(Z),Co(a(this,l,mc).call(this))){let It=rt("Switch to bWalletX",()=>{oe(!1),this.switchToBwalletX()}),Jt=document.createElement("div");Jt.className="who",Jt.textContent=ol,U.append(Jt,It),dt.unshift(It)}U.append(bt,Et),M.append(H,U),document.body.appendChild(D);let $t=()=>{let It=pt.getBoundingClientRect(),Jt=window.innerWidth||document.documentElement.clientWidth||360,qt=window.innerHeight||document.documentElement.clientHeight||640,Pr=Math.min(260,Jt-32);U.style.width=`${Pr}px`;let _s=Math.max(16,Math.min(It.right-Pr,Jt-Pr-16));U.style.left=`${_s}px`;let Hi=U.offsetHeight||150,Je=It.bottom+8;U.style.top=`${Je+Hi>qt&&It.top-8-Hi>0?It.top-8-Hi:Je}px`};$t();let Wt=It=>dt[(It+dt.length)%dt.length].focus(),ui=It=>{let Jt=dt.indexOf(M.activeElement);It.key==="Escape"?(It.preventDefault(),oe(!0)):It.key==="ArrowDown"?(It.preventDefault(),Wt(Jt+1)):It.key==="ArrowUp"?(It.preventDefault(),Wt(Jt-1)):It.key==="Home"?(It.preventDefault(),Wt(0)):It.key==="End"?(It.preventDefault(),Wt(dt.length-1)):It.key==="Tab"&&oe(!1)},vn=It=>{let Jt=It.composedPath?.()??[];!Jt.includes(D)&&!Jt.includes(this)&&oe(!1)},Be=()=>oe(!1);U.addEventListener("keydown",ui),document.addEventListener("pointerdown",vn,!0),window.addEventListener("resize",Be),window.addEventListener("scroll",$t,!0);let oe=(It=!1)=>{g(this,f)?.host===D&&(A(this,f,null),U.removeEventListener("keydown",ui),document.removeEventListener("pointerdown",vn,!0),window.removeEventListener("resize",Be),window.removeEventListener("scroll",$t,!0),D.remove(),this.button?.setAttribute("aria-expanded","false"),It&&this.button?.focus())};A(this,f,{host:D,close:oe}),pt.setAttribute("aria-expanded","true"),Wt(0)},Ze=function(Y,pt,N=!1){return this.dispatchEvent(new CustomEvent(Y,{detail:pt,bubbles:!0,composed:!0,cancelable:N}))},Qw=function(Y){let pt=a(this,l,gt).call(this,"other-wallets");return pt==="off"?!1:pt==="on"?!0:(Y==="lg"||Y==="md")&&(g(this,l,Ye)||!!a(this,l,gt).call(this,"challenge-url"))},Or=function(){return a(this,l,gt).call(this,"remember")!=="off"},up=function(Y){let pt=a(this,l,gt).call(this,"metanet");return pt==="off"||!In()?!1:pt==="on"?!0:(Y==="lg"||Y==="md")&&(g(this,l,Ye)||!!a(this,l,gt).call(this,"challenge-url"))},t1=function(){return g(this,l,Ye)?a(this,l,gt).call(this,"wallet-type")===Sn:g(this,d)},e1=async function(){if(g(this,l,Ye)||!g(this,l,gc)||!g(this,l,Or)||a(this,l,gt).call(this,"require-token")||!a(this,l,up).call(this,a(this,l,gt).call(this,"size")??"lg"))return;let Y=a(this,l,gt).call(this,"challenge-url"),pt=a(this,l,gt).call(this,"verify-url");if(!Y||!pt||g(this,i)!=="signed-out"||g(this,e)||qf()||Li()?.type!==Sn||!In())return;let N=++Ic(this,h)._,D=()=>N===g(this,h),M=Date.now(),H=await tl({challengeUrl:Y,verifyUrl:pt,post:(U,Z)=>el(U,Z),isAbandoned:()=>!D(),logout:async()=>{let U=a(this,l,gt).call(this,"logout-url");U&&await fetch(U,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:"{}"}).catch(()=>{})},onSignIn:()=>{!D()||g(this,i)!=="signed-out"||g(this,e)||(A(this,d,!0),A(this,e,!0),A(this,c,wc),a(this,l,Mi).call(this,"pending"))},onAttempt:U=>a(this,l,Ze).call(this,"bwalletx-attempt",U)});if(D()){if(A(this,d,!1),A(this,e,!1),!H){g(this,i)==="pending"&&a(this,l,Mi).call(this,"signed-out");return}A(this,u,H.walletType),a(this,l,nl).call(this,{identityKey:H.identityKey,handle:H.handle,paymail:H.paymail}),a(this,l,Ze).call(this,"bwalletx-signed-in",{identityKey:H.identityKey,method:"wallet",nonce:null,signature:null,response:{handle:H.handle,paymail:H.paymail},silent:!0,ms:Date.now()-M})}},mc=function(){return g(this,l,Ye)?a(this,l,gt).call(this,"wallet-type"):g(this,u)??(g(this,l,Or)?Li()?.type??null:null)},n1=function(Y){let pt=a(this,l,gt).call(this,"switch-note");return pt==="off"||!lc(a(this,l,mc).call(this))?!1:pt==="on"||Y==="lg"||Y==="md"},fp=function(Y,pt,N){A(this,u,Dn(Y)),g(this,l,Or)&&_o(Y,pt)&&ci(Y),g(this,l,Or)&&Ps(N)},Ns=function(Y,pt,N){a(this,l,Ze).call(this,"bwalletx-attempt",ai(Y,pt,N))},i1=async function(Y,pt,N){if(Y==="metanet")return{option:_i(),reason:"requested"};let D=Y==="signin"&&g(this,l,Or)?Li():null;if(D&&D.type!==Sn&&!(D.type===Ci&&D.substrate!=="pairing")){let U=Bo(await ks({ms:pt,pairing:()=>N}),D);if(U)return{option:U,reason:"remembered"}}if(Y!=="chooser"){let U=await oi(pt);if(U){let Z=U.rdns===Ln?"extension":U.rdns===Mn?"in-app":"xdm";return{option:Ni(U.wallet,{id:U.rdns??"bwalletx-xdm",rdns:U.rdns??void 0,name:"bWalletX",isBwalletX:!0,substrate:Z}),reason:"bwalletx"}}}let M=await ks({ms:50,pairing:()=>N});if(Y!=="chooser"&&!Ro(M)&&!No(M).length)return"not-found";let H=await Yf(M,{getUrl:a(this,l,gt).call(this,"get-url")??void 0});return H?{option:H,reason:"chooser"}:null},bc=async function(Y="signin"){if(this.hasAttribute("disabled")||this.hasAttribute("loading")||g(this,e)||this.state==="pending"||!a(this,l,Ze).call(this,"bwalletx-signin",{element:this,mode:Y},!0))return;if(Y==="signin"){let tt=a(this,l,gt).call(this,"href"),bt=a(this,l,gt).call(this,"authorize-url");if(bt){location.assign(await pp({authorizeUrl:bt,clientId:a(this,l,gt).call(this,"client-id"),redirectUri:a(this,l,gt).call(this,"redirect-uri"),scope:a(this,l,gt).call(this,"scope")}));return}if(tt){location.assign(tt);return}}let pt=a(this,l,gt).call(this,"challenge-url");if(!pt)return;let N=g(this,l,gc)&&!g(this,l,Ye),D=g(this,i)==="signed-in"?"signed-in":"signed-out",M=Date.now(),H=Lo(),U=null,Z=++Ic(this,h)._,rt=()=>Z===g(this,h);A(this,t,!1),A(this,e,!0),A(this,d,Y==="metanet"),A(this,c,Y==="metanet"?wc:yc),N?a(this,l,Mi).call(this,"pending"):a(this,l,Ui).call(this);try{let tt=Number(a(this,l,gt).call(this,"discover-ms"))||xr,bt=await a(this,l,i1).call(this,Y,tt,H);if(bt==="not-found"){A(this,t,!0),N&&A(this,i,"signed-out"),a(this,l,Ns).call(this,null,"not-found",M),a(this,l,Ze).call(this,"bwalletx-not-found"),a(this,l,gt).call(this,"require-token")&&a(this,l,Ze).call(this,"bwalletx-access-denied",{code:"not_installed",message:"No wallet found"});return}if(!bt){N&&A(this,i,D),a(this,l,Ns).call(this,null,"cancelled",M);return}U=bt.option;let Et=bt.reason;U.isBwalletX||(A(this,c,wc),N&&a(this,l,Ui).call(this));let dt=await U.connect({identity:!1});if(!rt())return;let $t=dt.wallet;if(!$t)throw Object.assign(new Error("This wallet cannot sign in here"),{code:"NOT_SUPPORTED"});let Wt=Un(U),ui=Wt==="extension"?"extension":Wt==="in-app"||Wt==="xdm"?"in-app":Wt==="pairing"?"pairing":"wallet",vn=a(this,l,gt).call(this,"require-token");if(vn){N&&A(this,i,"signed-out");let qt=a(this,l,gt).call(this,"verify-url"),Pr=a(this,l,gt).call(this,"min"),_s=a(this,l,gt).call(this,"min-bps"),Hi={token:{id:vn,..._s?{minBps:Number(_s)}:{min:Pr??"1"}}};try{let Je=await Qf({wallet:$t,challenge:Hn=>el(pt,{identityKey:Hn,require:Hi}),verify:qt?Hn=>eS(qt,Hn):void 0});a(this,l,fp).call(this,U,Et,qt?Je.response.identityKey:null),a(this,l,Ns).call(this,U,"signed-in",M),a(this,l,Ze).call(this,"bwalletx-access-granted",{identityKey:Je.response.identityKey,response:Je.verified})}catch(Je){let Hn=Je instanceof Ct?Je:new Ct("bad_request",String(Je));a(this,l,Ns).call(this,U,Er(Je),M),a(this,l,Ze).call(this,"bwalletx-access-denied",{code:Hn.code,message:Hn.message,have:Hn.have,need:Hn.need})}return}let Be=a(this,l,gt).call(this,"verify-url"),{result:oe,verified:It}=await Es({wallet:$t,identityKey:dt.identityKey??void 0,skipWaitForAuthentication:U.id===Ar,identityKeyHint:Be?vr():void 0,challenge:qt=>el(pt,qt?{identityKey:qt}:{}),verify:async qt=>Be?await el(Be,{identityKey:qt.identityKey,nonce:qt.nonce,signature:qt.signature}):{}});if(!rt()){let qt=a(this,l,gt).call(this,"logout-url");Be&&qt&&await fetch(qt,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:"{}"}).catch(()=>{});return}Be&&Ts(oe.identityKey);let Jt=Be?It:null;a(this,l,fp).call(this,U,Et,Be?oe.identityKey:null),N&&a(this,l,nl).call(this,{identityKey:oe.identityKey,handle:Jt?.handle??null,paymail:Jt?.paymail??null}),a(this,l,Ns).call(this,U,"signed-in",M),a(this,l,Ze).call(this,"bwalletx-signed-in",{identityKey:oe.identityKey,method:ui,nonce:oe.nonce,signature:oe.signature,response:Jt})}catch(tt){let bt=Er(tt);if(a(this,l,Ns).call(this,U,bt,M),!rt())return;let Et=bt==="cancelled"&&U?.kind==="pairing";N&&(Et?A(this,i,D):(A(this,s,Df(tt)),A(this,i,"error"))),Et||a(this,l,Ze).call(this,"bwalletx-error",{error:tt})}finally{try{H.close()}catch{}rt()&&(A(this,e,!1),A(this,d,!1),a(this,l,Ui).call(this))}},Mt}function al(n=lp){if(typeof window>"u"||typeof customElements>"u")return;let t=customElements.get(n);if(t)return t;let e=rS();return customElements.define(n,e),e}var bp="bwalletx-button",fl="bwx:connected";function yp(){let n=dl();return n&&!Li()&&r1("extension"),n}function r1(n){ci({id:"bwalletx",name:"bWalletX",kind:n==="pairing"?"pairing":"brc100",isBwalletX:!0,substrate:n,connect:async()=>{throw new Error("unused")}})}function dl(){try{let n=globalThis.localStorage?.getItem(fl)!=null;return n&&globalThis.localStorage?.removeItem(fl),n}catch{return!1}}var sS="https://pay.bwallet.space/api/paymail/lookup?key=",oS='[data-bwx-connect], .nav-connect, .nav-acct, a[href^="https://bwalletx.com/get"], a[href^="https://www.bwalletx.com/get"]';function wp(n,t=!1){return/iPhone|iPad|iPod/i.test(n)||t&&/Macintosh/.test(n)?"https://bwalletx.com/iphone":/Android/i.test(n)?"https://bwalletx.com/android":/Chrome\//.test(n)&&!/Edg\/|OPR\//.test(n)?"https://bwalletx.com/extension":"https://bwalletx.com/get"}function ll(n){return n.connected?"connected":n.found===null?n.phone?"available":"checking":n.found||n.phone?"available":"none"}function xp(n,t){return t&&/@bwalletx\.com$/i.test(t)?"$"+t.split("@")[0]:t||n.slice(0,6)+"\u2026"+n.slice(-4)}var aS=`
147
+ a.b,button.b{all:unset;box-sizing:border-box}
148
+ .chip{background:#0b0b0c;color:#ffd24d;border:1px solid rgba(255,210,77,.45);box-shadow:none}
149
+ .chip:hover{background:#151517;border-color:#ffd24d}
150
+ .chip .dot{width:8px;height:8px;border-radius:50%;background:#34d399;flex:none}
151
+ .txt b{overflow:hidden;text-overflow:ellipsis;max-width:min(40vw,220px)}
152
+ :host(:not([size])) button,:host(:not([size])) a.btn,:host([size=sm]) a.btn{padding:6px 12px 6px 6px;border-radius:8px;font-size:13px;gap:8px;min-height:36px}
153
+ :host(:not([size])) .mark,:host([size=sm]) a.btn .mark{width:22px;height:22px}
154
+ a.btn{all:unset;box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;gap:12px;cursor:pointer;
155
+ padding:16px 20px;border-radius:12px;font-size:16px;font-weight:700;line-height:1.2;background:linear-gradient(180deg,#fcd34d,#f59e0b);color:#000;
156
+ box-shadow:0 10px 15px -3px rgba(245,158,11,.2),0 4px 6px -4px rgba(245,158,11,.2)}
157
+ a.btn:hover{background:linear-gradient(180deg,#fde68a,#fbbf24)}
158
+ a.btn:focus-visible{outline:2px solid #b45309;outline-offset:3px}
159
+ :host([size=md]) a.btn{padding:10px 16px;border-radius:10px;font-size:15px;gap:10px}
160
+ `,cl=new Set;function cS(){var n,t,e,i,r,s,s1,o1,gp,Di,mp,ul,l;return l=class extends HTMLElement{constructor(){super();z(this,s);z(this,n);z(this,t,"checking");z(this,e,null);z(this,i,null);z(this,r,!1);A(this,n,this.attachShadow({mode:"open"}))}get state(){return g(this,t)}get identityKey(){return g(this,e)}connectedCallback(){if(cl.size&&![...cl].includes(this)){A(this,r,!0),this.hidden=!0,console.warn("[bwalletx] A second <bwalletx-button> is on this page; it is hidden. Use one per page.");return}cl.add(this),a(this,s,o1).call(this),yp();let y=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent);a(this,s,Di).call(this,ll({connected:!1,found:null,phone:y}));let S=Number(this.getAttribute("discover-ms"))||800;oi(S).then(L=>{this.isConnected&&g(this,t)!=="connected"&&g(this,t)!=="connecting"&&a(this,s,Di).call(this,ll({connected:!1,found:!!L,phone:y}))}).catch(()=>{g(this,t)==="checking"&&a(this,s,Di).call(this,"none")}),a(this,s,s1).call(this)}disconnectedCallback(){g(this,r)||cl.delete(this)}async connect(){if(g(this,t)==="connecting"||g(this,t)==="connected")return;let y=Lo({title:"Connect bWalletX"});a(this,s,Di).call(this,"connecting");try{let{wallet:S,method:L}=await vs({pairing:y}),{publicKey:T}=await S.getPublicKey({identityKey:!0});r1(L==="pairing"?"pairing":L==="in-app"?"in-app":"extension"),a(this,s,mp).call(this,T)}catch(S){S?.code==="NOT_FOUND"?a(this,s,Di).call(this,"none"):(a(this,s,Di).call(this,"available"),S?.name!=="AbortError"&&console.warn("[bwalletx] connect:",S))}finally{try{y.close()}catch{}}}disconnect(){try{_f()}catch{}try{window.postMessage({type:"bwallet:disconnect"},location.origin)}catch{}A(this,e,null),A(this,i,null),dl(),Li()?.type===Ci&&Rs(),a(this,s,Di).call(this,"available"),a(this,s,gp).call(this,"bwalletx-disconnected")}},n=new WeakMap,t=new WeakMap,e=new WeakMap,i=new WeakMap,r=new WeakMap,s=new WeakSet,s1=async function(){let y=this.getAttribute("session-url");if(y)try{let L=await(await fetch(y,{credentials:"include",headers:{accept:"application/json"}})).json().catch(()=>({}));L.identityKey&&this.isConnected&&g(this,t)!=="connected"&&g(this,t)!=="connecting"&&(a(this,s,mp).call(this,L.identityKey),L.paymail&&(A(this,i,L.paymail),a(this,s,ul).call(this)))}catch{}},o1=function(){let y=this.closest("header, nav")??document;for(let S of Array.from(y.querySelectorAll(oS)))S===this||S.contains(this)||(S.hidden=!0,S.style.setProperty("display","none","important"),console.warn("[bwalletx] Hid a second wallet control next to <bwalletx-button>:",S,". Use only <bwalletx-button>; don't add your own Get or Connect links."))},gp=function(y,S){this.dispatchEvent(new CustomEvent(y,{detail:S,bubbles:!0,composed:!0}))},Di=function(y){A(this,t,y),this.setAttribute("state",y),a(this,s,ul).call(this)},mp=function(y){A(this,e,y),a(this,s,Di).call(this,"connected"),a(this,s,gp).call(this,"bwalletx-connected",{identityKey:y});let S=this.getAttribute("lookup-url");S!=="off"&&fetch((S??sS)+encodeURIComponent(y)).then(L=>L.ok?L.json():null).then(L=>{L&&typeof L.paymail=="string"&&g(this,e)===y&&(A(this,i,L.paymail),a(this,s,ul).call(this))}).catch(()=>{})},ul=function(){let y=B=>B.replace(/[&<>"]/g,F=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[F]),S=this.getAttribute("size")??"sm",T=`<span class="mark" part="mark">${Tr(S==="lg"?20:S==="md"?17:15)}</span>`,k=`<style>${Mo}${aS}</style>`,E=g(this,t);if(E==="none"){let B=this.getAttribute("get-url")??wp(navigator.userAgent,(navigator.maxTouchPoints??0)>1);g(this,n).innerHTML=`${k}<a class="btn" part="button" href="${y(B)}" target="_blank" rel="noopener">${T}<span class="txt" part="text"><b part="label">Get bWalletX</b></span></a>`;return}if(E==="connected"&&g(this,e)){let B=xp(g(this,e),g(this,i));g(this,n).innerHTML=`${k}<button type="button" class="chip" part="button chip" title="Connected to bWalletX. Click to disconnect." aria-label="Connected as ${y(B)}. Disconnect">${T}<span class="txt" part="text"><b part="label">${y(B)}</b></span><span class="dot" aria-hidden="true"></span></button>`,g(this,n).querySelector("button").onclick=()=>this.disconnect();return}let _=E==="connecting"||E==="checking";g(this,n).innerHTML=`${k}<button type="button" part="button"${_?' aria-busy="true"':""}>${_?'<span class="mark" part="mark"><span class="spin" aria-hidden="true"></span></span>':T}<span class="txt" part="text"><b part="label">${E==="connecting"?"Connecting\u2026":"Connect bWalletX"}</b></span></button>`,g(this,n).querySelector("button").onclick=()=>{this.connect()}},l}function hl(n=bp){typeof customElements>"u"||customElements.get(n)||customElements.define(n,cS())}var uS=`
71
161
  .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
162
  .bwx-signin:hover{background:linear-gradient(180deg,#fde68a,#fbbf24)}
73
163
  .bwx-signin:focus-visible{outline:2px solid #ffd24d;outline-offset:3px}
74
164
  .bwx-signin:disabled{opacity:.6;cursor:wait}
75
165
  .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)}`,al="https://bwalletx.com/logo.svg";function mb(n,t={}){let e=typeof n=="string"?document.querySelector(n):n;if(!e)throw new Error(`renderButton: no element ${String(n)}`);if(!document.getElementById("bwx-signin-css")){let u=document.createElement("style");u.id="bwx-signin-css",u.textContent=p4,document.head.appendChild(u)}let i=document.createElement("button");i.type="button",i.className="bwx-signin";let r=document.createElement("span");r.className="bwx-mark";let s=document.createElement("img");s.src=al,s.alt="",s.width=15,s.height=20,r.appendChild(s);let o=document.createElement("span");o.className="bwx-label",o.textContent="Sign in with bWalletX";let c=t.subtitle===void 0?"also works with bWallet":t.subtitle;if(c){let u=document.createElement("small");u.textContent=c,o.appendChild(u)}return i.append(r,o),t.onClick&&i.addEventListener("click",()=>t.onClick(i)),e.replaceChildren(i),i}var cl=[2,"3241645161d8"],he=class extends Error{constructor(e,i,r=!1,s){super(i);b(this,"code",e);b(this,"maybeSent",r);b(this,"cause",s);this.name="PaymentError"}},yb=n=>typeof n.pay=="function"&&typeof n.createAction!="function",ul=n=>/^0[23][0-9a-fA-F]{64}$/.test(n),fl=n=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n);function bb(n){let t=new Uint8Array(n);return globalThis.crypto.getRandomValues(t),yi.toBase64(Array.from(t))}function g4(n){let t=yi.toArray(n,"utf8"),e=t.length,i=e<76?[e]:e<=255?[76,e]:[77,e&255,e>>8];return yi.toHex([0,106,...i,...t])}var dl=(n,t)=>n.length>t?n.slice(0,t-1)+"\u2026":n,wb=n=>dl(n.length<5?`${n} payment`.trim():n,50);async function m4(n){if(typeof n.usdPerBsv=="number")return n.usdPerBsv;try{if(typeof n.usdPerBsv=="function")return await n.usdPerBsv();let t=await(n.fetch??fetch)("https://api.whatsonchain.com/v1/bsv/main/exchangerate"),e=await t.json();if(!t.ok||!(Number(e.rate)>0))throw new Error(`status ${t.status}`);return Number(e.rate)}catch(t){throw new he("RATE_FAILED",`Could not get the BSV/USD rate: ${t.message}`,!1,t)}}async function ll(n,t={}){if(n.sats!=null){if(!Number.isSafeInteger(n.sats)||n.sats<=0)throw new he("BAD_REQUEST","sats must be a positive integer");return n.sats}if(n.usd!=null){if(!(n.usd>0))throw new he("BAD_REQUEST","usd must be positive");return Math.max(1,Math.ceil(n.usd/await m4(t)*1e8))}throw new he("BAD_REQUEST","Give sats or usd")}async function hl(n,t,e=fetch){let[i,r]=n.split("@"),s=(l,p)=>new he("RESOLVE_FAILED",`Could not resolve ${n}: ${l}`,!1,p),o;try{o=(await(await e(`https://${r}/.well-known/bsvalias`)).json()).capabilities}catch(l){throw s("no bsvalias document (or CORS blocked it; resolve on your server and pass resolvePaymail)",l)}let c=l=>l.replace("{alias}",encodeURIComponent(i)).replace("{domain.tld}",r),u=o?.["2a40af698840"];if(!u)throw s("it does not offer P2P payment destinations");let f;try{let l=await e(c(u),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({satoshis:t})});if(!l.ok)throw new Error(`status ${l.status}`);f=await l.json()}catch(l){throw s(l.message,l)}if(!f.outputs?.length)throw s("no outputs returned");let d=o["5f1323cddf31"];return{outputs:f.outputs.map(l=>({script:l.script,satoshis:l.satoshis})),reference:f.reference,submit:d?async l=>{await e(c(d),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hex:l,reference:f.reference,metadata:{}})})}:void 0}}async function xb(n,t,e,i){try{return await n.createAction({description:wb(t),outputs:e.map(r=>({lockingScript:r.script,satoshis:r.satoshis,outputDescription:wb(r.description??"payment")})),labels:i?.length?i:void 0,options:{randomizeOutputs:!1}})}catch(r){let s=r?.message??String(r),o=/denied|reject|cancel|abort|user/i.test(s)||r?.code===4001;throw new he(o?"WALLET_REJECTED":"WALLET_ERROR",o?"The payment was declined in the wallet.":`The wallet could not make the payment: ${s}`,!o,r)}}async function pl(n,t,e={}){let i=(t.to??"").trim();if(!i)throw new he("BAD_REQUEST","Give a recipient (to)");if(t.memo&&t.memo.length>1e3)throw new he("BAD_REQUEST","memo is too long");let r=await ll(t,e);if(yb(n))return n.pay({...t,to:i,sats:r});let s,o,c;if(ul(i)){let d=bb(8),l=bb(8),p,m;try{({publicKey:p}=await n.getPublicKey({protocolID:cl,keyID:`${d} ${l}`,counterparty:i.toLowerCase()})),{publicKey:m}=await n.getPublicKey({identityKey:!0})}catch(g){throw new he("WALLET_ERROR",`The wallet could not derive the payment key: ${g.message}`,!1,g)}s=[{script:new Yn().lock(Ht.fromString(p).toHash()).toHex(),satoshis:r,description:"payment"}],o={senderIdentityKey:m,derivationPrefix:d,derivationSuffix:l,outputIndex:0}}else if(fl(i)){let d=await(e.resolvePaymail??((l,p)=>hl(l,p,e.fetch??fetch)))(i,r);s=d.outputs,c=d.submit}else try{s=[{script:new Yn().lock(i).toHex(),satoshis:r,description:"payment"}]}catch{throw new he("BAD_REQUEST",`Not a paymail, address or identity key: ${i}`)}t.memo&&t.memoOnChain&&(s=[...s,{script:g4(t.memo),satoshis:0,description:"memo"}]);let u=await xb(n,t.memo||`Pay ${dl(i,30)}`,s,t.labels);if(!u.txid)throw new he("WALLET_ERROR","The wallet did not return a txid",!0);let f=u.tx?Array.from(u.tx):void 0;return c&&f&&await c(Me.fromAtomicBEEF(f).toHex()).catch(()=>{}),{txid:u.txid,tx:f,sats:r,outputs:s,remittance:o}}function Sb(n,t,e={}){return pl(n,{memo:"Tip",...t,labels:[...t.labels??[],"tip"]},e)}async function Ib(n,t){if(yb(n))throw new he("NOT_SUPPORTED","This wallet cannot buy tokens. Use a BRC-100 wallet such as bWalletX.");let e=await t.quote({token:t.token,amount:t.amount});if(!e?.outputs?.length)throw new he("BAD_REQUEST","The quote returned no outputs");let i=e.outputs.reduce((o,c)=>o+c.satoshis,0),r=await xb(n,e.description??`Buy ${dl(t.token,30)}`,e.outputs,[...t.labels??[],"token-buy"]);if(!r.txid)throw new he("WALLET_ERROR","The wallet did not return a txid",!0);let s={txid:r.txid,tx:r.tx?Array.from(r.tx):void 0,sats:i,outputs:e.outputs};return await e.onPaid?.(s),s}async function Ab(n,t){await n.waitForAuthentication({}).catch(()=>{});let{publicKey:e}=await n.getPublicKey({identityKey:!0});return{wallet:n,payer:n,identityKey:e,optionId:t.id,kind:t.kind}}function Ls(n,t){let e={id:t.id,name:t.name,icon:t.icon,rdns:t.rdns,kind:"brc100",isBwalletX:t.isBwalletX??!1,connect:()=>Ab(n,e)};return e}function gl(n){let t={id:"bwalletx-pairing",name:"bWalletX on your phone",kind:"pairing",isBwalletX:!0,async connect(){let e=typeof n=="function"?n():n,i=await Cs(e)??await _s(e);return Ab(i,t)}};return t}function Eb(n){let t={id:"handcash",name:"HandCash",icon:n.icon,kind:"handcash",isBwalletX:!1,async connect(){let e=await n.login();return{wallet:null,payer:n.pay?{pay:n.pay}:null,identityKey:e.identityKey??null,handle:e.handle,paymail:e.paymail??`${e.handle.replace(/^\$/,"")}@handcash.io`,optionId:t.id,kind:"handcash",transitional:!0}}};return t}var b4={[Ns]:"bWalletX","space.bwallet.mobile":"bWalletX"};async function vb(n,t){try{let e=new Wi(n);return await Promise.race([e.isAuthenticated({}).then(()=>!0),new Promise(r=>setTimeout(()=>r(!1),t))])?e:null}catch{return null}}async function kb(n={}){let t=[],e=n.ms??300;if(typeof window<"u"){let r=new Map,s=d=>{let l=d.detail;if(!l?.wallet)return;let p=l.info?.rdns??l.info?.uuid??`wallet-${r.size}`;if(r.has(p))return;let m=Qo.includes(p);r.set(p,Ls(l.wallet,{id:p,rdns:p,name:b4[p]??l.info?.name??p,icon:l.info?.icon,isBwalletX:m}))};window.addEventListener("brc100:announceWallet",s),window.dispatchEvent(new Event("brc100:requestWallet"));let o=n.probeLocal?Promise.all([vb("json-api",e),vb("Cicada",e)]):Promise.resolve([null,null]);await new Promise(d=>setTimeout(d,r.size>0||window.CWI?Math.min(e,50):e)),window.removeEventListener("brc100:announceWallet",s),t.push(...r.values());let c=window.CWI;c&&![...r.values()].some(d=>d.rdns==="space.bwallet.mobile")&&t.push(Ls(c,{id:"window.CWI",name:"This app\u2019s wallet",isBwalletX:!1}));let[u,f]=await o;u&&t.push(Ls(u,{id:"localhost:3321",name:"Desktop wallet (localhost:3321)"})),f&&t.push(Ls(f,{id:"localhost:3301",name:"Desktop wallet (localhost:3301)"}))}n.pairing&&t.push(gl(n.pairing)),t.push(...n.extra??[]);let i=r=>r.isBwalletX?0:r.kind==="handcash"?2:1;return t.map((r,s)=>({w:r,i:s})).sort((r,s)=>i(r.w)-i(s.w)||r.i-s.i).map(r=>r.w)}var Nb=Wb(Rb(),1);var w4=`
77
- .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
- .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
- .bwx-box h2{margin:0 0 6px;font-size:18px;color:#e8c766}
80
- .bwx-box p{margin:0 0 14px;color:#bdb6a3;font-size:14px}
81
- .bwx-qr{background:#fff;border-radius:12px;padding:12px;display:flex;justify-content:center}
82
- .bwx-qr svg{width:100%;height:auto;max-width:260px}
83
- .bwx-code{margin:14px 0 0;text-align:center;font-size:28px;letter-spacing:.3em;color:#e8c766;font-variant-numeric:tabular-nums}
84
- .bwx-row{display:flex;gap:8px;margin-top:14px}
85
- .bwx-btn{flex:1;border:1px solid #3a3220;background:#15130e;color:#f4f1e8;border-radius:10px;padding:10px 12px;font:inherit;cursor:pointer}
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}
90
- .bwx-list{display:flex;flex-direction:column;gap:8px}
91
- .bwx-opt{display:flex;align-items:center;gap:10px;text-align:left}
92
- .bwx-opt img{width:24px;height:24px;border-radius:6px}
93
- .bwx-tag{margin-left:auto;font-size:11px;color:#8d866f}
94
- `;function Bb(){let n=document.createElement("div");n.className="bwx-ov",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true");let t=document.createElement("style");t.textContent=w4;let e=document.createElement("div");return e.className="bwx-box",n.append(t,e),document.body.appendChild(n),{root:n,box:e,close:()=>n.remove()}}function ie(n,t,e){let i=document.createElement(n);return t&&(i.className=t),e!=null&&(i.textContent=e),i}function ml(n){let t=(0,Nb.default)(0,"M");return t.addData(n),t.make(),t.createSvgTag({cellSize:4,margin:2,scalable:!0})}function bl(n=globalThis){let t=n.navigator;if(!t)return!1;let e=t.userAgent??"";if(/Android|iPhone|iPad|iPod|Mobile|Silk|Kindle/i.test(e)||/Macintosh/.test(e)&&(t.maxTouchPoints??0)>1)return!0;try{return!!n.matchMedia?.("(pointer: coarse)").matches&&!n.matchMedia?.("(hover: hover)").matches}catch{return!1}}function _b(n={}){let t=new AbortController,e=null,i=null,r=()=>{e?.close(),e=null};return t.signal.addEventListener("abort",r),{signal:t.signal,close:r,onLink(s){if(typeof document>"u")return;r(),e=Bb();let o=n.mode==="app"||(n.mode??"auto")==="auto"&&bl(),c=ie("h2","",n.title??"Connect bWalletX"),u=ie("button","bwx-btn","Cancel");if(u.onclick=()=>{n.onCancel?.(),t.abort()},i=ie("div","bwx-code",""),i.setAttribute("aria-live","polite"),o){let m=ie("p","","Open bWalletX, approve, then come back to this page."),g=ie("div","bwx-stack"),w=ie("a","bwx-btn bwx-primary","Open bWalletX");w.href=s,w.rel="noopener";let S=ie("button","bwx-btn","Use web.bwalletx.com instead");S.onclick=()=>{navigator.clipboard?.writeText(s).catch(()=>{}),window.open(ra,"_blank","noopener"),m.textContent="Link copied. In web.bwalletx.com tap Connect and paste it, then come back here."},g.append(w,S,u),e.box.append(c,m,i,g);return}let f=ie("p","","Scan with bWalletX on your phone, or paste the link into web.bwalletx.com."),d=ie("div","bwx-qr");d.innerHTML=ml(s);let l=ie("div","bwx-row"),p=ie("button","bwx-btn","Copy link");p.onclick=()=>{navigator.clipboard?.writeText(s).then(()=>p.textContent="Copied")},l.append(p,u),e.box.append(c,f,d,i,l)},onCode(s){if(i){i.textContent=s;let o=e?.box.querySelector("p");o&&(o.textContent="Check bWalletX shows the same code, then tap Connect.")}}}}function Cb(n,t={}){return typeof document>"u"?Promise.resolve(null):new Promise(e=>{let i=Bb(),r=c=>{i.close(),e(c)};i.box.append(ie("h2","",t.title??"Choose a wallet")),n.length||i.box.append(ie("p","","No wallet found. Get bWalletX at bwalletx.com."));let s=ie("div","bwx-list");for(let c of n){let u=ie("button","bwx-btn bwx-opt");if(c.icon){let f=ie("img");f.src=c.icon,f.alt="",u.append(f)}u.append(ie("span","",c.name)),c.kind==="handcash"&&u.append(ie("span","bwx-tag","until BRC-100")),u.onclick=()=>r(c),s.append(u)}let o=ie("button","bwx-btn","Cancel");o.onclick=()=>r(null),i.root.onclick=c=>c.target===i.root&&r(null),i.box.append(s,ie("div","bwx-row")),i.box.lastChild.append(o)})}var xu="bwalletx-theme",y4=/^[a-z0-9-]{1,32}$/;function Lb(n){if(typeof document>"u")return;let t=(n??"").trim().toLowerCase(),e=document.head.querySelector(`meta[name="${xu}"]`);if(!t||!y4.test(t)){e?.remove();return}e||(e=document.createElement("meta"),e.name=xu,document.head.appendChild(e)),e.content!==t&&(e.content=t)}yu();return Vb(x4);})();
166
+ .bwx-signin small{display:block;font-size:11px;font-weight:500;color:rgba(0,0,0,.6)}`,Sp="https://bwalletx.com/logo.svg";function a1(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=uS,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=Sp,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 Ip=[2,"3241645161d8"],vp="Your wallet doesn't have enough to cover this payment and its small network fee. Add a little and try again.";function Ap(n){let t=n;if(!t)return!1;if(t.name==="WERR_INSUFFICIENT_FUNDS"||t.code==="WERR_INSUFFICIENT_FUNDS"||t.code==="ERR_INSUFFICIENT_FUNDS"||t.isError===!0&&t.code===7)return!0;let e=typeof t.message=="string"?t.message:String(n);return/insufficient (funds|balance)|not enough (funds|coins|satoshis|sats)|more satoshis are needed/i.test(e)}var me=class extends Error{constructor(e,i,r=!1,s){super(i);w(this,"code",e);w(this,"maybeSent",r);w(this,"cause",s);this.name="PaymentError"}},f1=n=>typeof n.pay=="function"&&typeof n.createAction!="function",Ep=n=>/^0[23][0-9a-fA-F]{64}$/.test(n),kp=n=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n);function c1(n){let t=new Uint8Array(n);return globalThis.crypto.getRandomValues(t),Yi.toBase64(Array.from(t))}function fS(n){let t=Yi.toArray(n,"utf8"),e=t.length,i=e<76?[e]:e<=255?[76,e]:[77,e&255,e>>8];return Yi.toHex([0,106,...i,...t])}var Tp=(n,t)=>n.length>t?n.slice(0,t-1)+"\u2026":n,u1=n=>Tp(n.length<5?`${n} payment`.trim():n,50);async function lS(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 me("RATE_FAILED",`Could not get the BSV/USD rate: ${t.message}`,!1,t)}}async function Op(n,t={}){if(n.sats!=null){if(!Number.isSafeInteger(n.sats)||n.sats<=0)throw new me("BAD_REQUEST","sats must be a positive integer");return n.sats}if(n.usd!=null){if(!(n.usd>0))throw new me("BAD_REQUEST","usd must be positive");return Math.max(1,Math.ceil(n.usd/await lS(t)*1e8))}throw new me("BAD_REQUEST","Give sats or usd")}async function Pp(n,t,e=fetch){let[i,r]=n.split("@"),s=(h,l)=>new me("RESOLVE_FAILED",`Could not resolve ${n}: ${h}`,!1,l),o;try{o=(await(await e(`https://${r}/.well-known/bsvalias`)).json()).capabilities}catch(h){throw s("no bsvalias document (or CORS blocked it; resolve on your server and pass resolvePaymail)",h)}let c=h=>h.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 h=await e(c(u),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({satoshis:t})});if(!h.ok)throw new Error(`status ${h.status}`);f=await h.json()}catch(h){throw s(h.message,h)}if(!f.outputs?.length)throw s("no outputs returned");let d=o["5f1323cddf31"];return{outputs:f.outputs.map(h=>({script:h.script,satoshis:h.satoshis})),reference:f.reference,submit:d?async h=>{await e(c(d),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hex:h,reference:f.reference,metadata:{}})})}:void 0}}async function l1(n,t,e,i){try{return await n.createAction({description:u1(t),outputs:e.map(r=>({lockingScript:r.script,satoshis:r.satoshis,outputDescription:u1(r.description??"payment")})),labels:i?.length?i:void 0,options:{randomizeOutputs:!1}})}catch(r){if(Ap(r))throw new me("INSUFFICIENT_FUNDS",vp,!1,r);let s=r?.message??String(r),o=/denied|reject|cancel|abort|user/i.test(s)||r?.code===4001;throw new me(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 Rp(n,t,e={}){let i=(t.to??"").trim();if(!i)throw new me("BAD_REQUEST","Give a recipient (to)");if(t.memo&&t.memo.length>1e3)throw new me("BAD_REQUEST","memo is too long");let r=await Op(t,e);if(f1(n))return n.pay({...t,to:i,sats:r});let s,o,c;if(Ep(i)){let d=c1(8),h=c1(8),l,m;try{({publicKey:l}=await n.getPublicKey({protocolID:Ip,keyID:`${d} ${h}`,counterparty:i.toLowerCase()})),{publicKey:m}=await n.getPublicKey({identityKey:!0})}catch(b){throw new me("WALLET_ERROR",`The wallet could not derive the payment key: ${b.message}`,!1,b)}s=[{script:new bi().lock(jt.fromString(l).toHash()).toHex(),satoshis:r,description:"payment"}],o={senderIdentityKey:m,derivationPrefix:d,derivationSuffix:h,outputIndex:0}}else if(kp(i)){let d=await(e.resolvePaymail??((h,l)=>Pp(h,l,e.fetch??fetch)))(i,r);s=d.outputs,c=d.submit}else try{s=[{script:new bi().lock(i).toHex(),satoshis:r,description:"payment"}]}catch{throw new me("BAD_REQUEST",`Not a paymail, address or identity key: ${i}`)}t.memo&&t.memoOnChain&&(s=[...s,{script:fS(t.memo),satoshis:0,description:"memo"}]);let u=await l1(n,t.memo||`Pay ${Tp(i,30)}`,s,t.labels);if(!u.txid)throw new me("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(Ke.fromAtomicBEEF(f).toHex()).catch(()=>{}),{txid:u.txid,tx:f,sats:r,outputs:s,remittance:o}}function d1(n,t,e={}){return Rp(n,{memo:"Tip",...t,labels:[...t.labels??[],"tip"]},e)}async function h1(n,t){if(f1(n))throw new me("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 me("BAD_REQUEST","The quote returned no outputs");let i=e.outputs.reduce((o,c)=>o+c.satoshis,0),r=await l1(n,e.description??`Buy ${Tp(t.token,30)}`,e.outputs,[...t.labels??[],"token-buy"]);if(!r.txid)throw new me("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}var pl="bwalletx-theme",dS=/^[a-z0-9-]{1,32}$/;function p1(n){if(typeof document>"u")return;let t=(n??"").trim().toLowerCase(),e=document.head.querySelector(`meta[name="${pl}"]`);if(!t||!dS.test(t)){e?.remove();return}e||(e=document.createElement("meta"),e.name=pl,document.head.appendChild(e)),e.content!==t&&(e.content=t)}al();hl();return P1(hS);})();
95
167
  //# sourceMappingURL=bwalletx-connect.global.js.map