Tradenook / website · tradenook.ai / market / app.js
| 1 | var Ca=Object.defineProperty;var Na=(e,t,n)=>t in e?Ca(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var k=(e,t,n)=>Na(e,typeof t!="symbol"?t+"":t,n);var zt=function(e,t){let o=e,s=wn[t],i=null,a=0,c=null,f=[],u={},l=function(w,m){a=o*4+17,i=(function(b){let x=new Array(b);for(let E=0;E<b;E+=1){x[E]=new Array(b);for(let A=0;A<b;A+=1)x[E][A]=null}return x})(a),d(0,0),d(a-7,0),d(0,a-7),g(),h(),S(w,m),o>=7&&y(w),c==null&&(c=O(o,s,f)),P(c,m)},d=function(w,m){for(let b=-1;b<=7;b+=1)if(!(w+b<=-1||a<=w+b))for(let x=-1;x<=7;x+=1)m+x<=-1||a<=m+x||(0<=b&&b<=6&&(x==0||x==6)||0<=x&&x<=6&&(b==0||b==6)||2<=b&&b<=4&&2<=x&&x<=4?i[w+b][m+x]=!0:i[w+b][m+x]=!1)},p=function(){let w=0,m=0;for(let b=0;b<8;b+=1){l(!0,b);let x=ht.getLostPoint(u);(b==0||w>x)&&(w=x,m=b)}return m},h=function(){for(let w=8;w<a-8;w+=1)i[w][6]==null&&(i[w][6]=w%2==0);for(let w=8;w<a-8;w+=1)i[6][w]==null&&(i[6][w]=w%2==0)},g=function(){let w=ht.getPatternPosition(o);for(let m=0;m<w.length;m+=1)for(let b=0;b<w.length;b+=1){let x=w[m],E=w[b];if(i[x][E]==null)for(let A=-2;A<=2;A+=1)for(let M=-2;M<=2;M+=1)A==-2||A==2||M==-2||M==2||A==0&&M==0?i[x+A][E+M]=!0:i[x+A][E+M]=!1}},y=function(w){let m=ht.getBCHTypeNumber(o);for(let b=0;b<18;b+=1){let x=!w&&(m>>b&1)==1;i[Math.floor(b/3)][b%3+a-8-3]=x}for(let b=0;b<18;b+=1){let x=!w&&(m>>b&1)==1;i[b%3+a-8-3][Math.floor(b/3)]=x}},S=function(w,m){let b=s<<3|m,x=ht.getBCHTypeInfo(b);for(let E=0;E<15;E+=1){let A=!w&&(x>>E&1)==1;E<6?i[E][8]=A:E<8?i[E+1][8]=A:i[a-15+E][8]=A}for(let E=0;E<15;E+=1){let A=!w&&(x>>E&1)==1;E<8?i[8][a-E-1]=A:E<9?i[8][15-E-1+1]=A:i[8][15-E-1]=A}i[a-8][8]=!w},P=function(w,m){let b=-1,x=a-1,E=7,A=0,M=ht.getMaskFunction(m);for(let W=a-1;W>0;W-=2)for(W==6&&(W-=1);;){for(let G=0;G<2;G+=1)if(i[x][W-G]==null){let ae=!1;A<w.length&&(ae=(w[A]>>>E&1)==1),M(x,W-G)&&(ae=!ae),i[x][W-G]=ae,E-=1,E==-1&&(A+=1,E=7)}if(x+=b,x<0||a<=x){x-=b,b=-b;break}}},N=function(w,m){let b=0,x=0,E=0,A=new Array(m.length),M=new Array(m.length);for(let _=0;_<m.length;_+=1){let te=m[_].dataCount,de=m[_].totalCount-te;x=Math.max(x,te),E=Math.max(E,de),A[_]=new Array(te);for(let B=0;B<A[_].length;B+=1)A[_][B]=255&w.getBuffer()[B+b];b+=te;let U=ht.getErrorCorrectPolynomial(de),T=yn(A[_],U.getLength()-1).mod(U);M[_]=new Array(U.getLength()-1);for(let B=0;B<M[_].length;B+=1){let I=B+T.getLength()-M[_].length;M[_][B]=I>=0?T.getAt(I):0}}let W=0;for(let _=0;_<m.length;_+=1)W+=m[_].totalCount;let G=new Array(W),ae=0;for(let _=0;_<x;_+=1)for(let te=0;te<m.length;te+=1)_<A[te].length&&(G[ae]=A[te][_],ae+=1);for(let _=0;_<E;_+=1)for(let te=0;te<m.length;te+=1)_<M[te].length&&(G[ae]=M[te][_],ae+=1);return G},O=function(w,m,b){let x=ii.getRSBlocks(w,m),E=si();for(let M=0;M<b.length;M+=1){let W=b[M];E.put(W.getMode(),4),E.put(W.getLength(),ht.getLengthInBits(W.getMode(),w)),W.write(E)}let A=0;for(let M=0;M<x.length;M+=1)A+=x[M].dataCount;if(E.getLengthInBits()>A*8)throw"code length overflow. ("+E.getLengthInBits()+">"+A*8+")";for(E.getLengthInBits()+4<=A*8&&E.put(0,4);E.getLengthInBits()%8!=0;)E.putBit(!1);for(;!(E.getLengthInBits()>=A*8||(E.put(236,8),E.getLengthInBits()>=A*8));)E.put(17,8);return N(E,x)};u.addData=function(w,m){m=m||"Byte";let b=null;switch(m){case"Numeric":b=Ha(w);break;case"Alphanumeric":b=Da(w);break;case"Byte":b=Fa(w);break;case"Kanji":b=ja(w);break;default:throw"mode:"+m}f.push(b),c=null},u.isDark=function(w,m){if(w<0||a<=w||m<0||a<=m)throw w+","+m;return i[w][m]},u.getModuleCount=function(){return a},u.make=function(){if(o<1){let w=1;for(;w<40;w++){let m=ii.getRSBlocks(w,s),b=si();for(let E=0;E<f.length;E++){let A=f[E];b.put(A.getMode(),4),b.put(A.getLength(),ht.getLengthInBits(A.getMode(),w)),A.write(b)}let x=0;for(let E=0;E<m.length;E++)x+=m[E].dataCount;if(b.getLengthInBits()<=x*8)break}o=w}l(!1,p())},u.createTableTag=function(w,m){w=w||2,m=typeof m>"u"?w*4:m;let b="";b+='<table style="',b+=" border-width: 0px; border-style: none;",b+=" border-collapse: collapse;",b+=" padding: 0px; margin: "+m+"px;",b+='">',b+="<tbody>";for(let x=0;x<u.getModuleCount();x+=1){b+="<tr>";for(let E=0;E<u.getModuleCount();E+=1)b+='<td style="',b+=" border-width: 0px; border-style: none;",b+=" border-collapse: collapse;",b+=" padding: 0px; margin: 0px;",b+=" width: "+w+"px;",b+=" height: "+w+"px;",b+=" background-color: ",b+=u.isDark(x,E)?"#000000":"#ffffff",b+=";",b+='"/>';b+="</tr>"}return b+="</tbody>",b+="</table>",b},u.createSvgTag=function(w,m,b,x){let E={};typeof arguments[0]=="object"&&(E=arguments[0],w=E.cellSize,m=E.margin,b=E.alt,x=E.title),w=w||2,m=typeof m>"u"?w*4:m,b=typeof b=="string"?{text:b}:b||{},b.text=b.text||null,b.id=b.text?b.id||"qrcode-description":null,x=typeof x=="string"?{text:x}:x||{},x.text=x.text||null,x.id=x.text?x.id||"qrcode-title":null;let A=u.getModuleCount()*w+m*2,M,W,G,ae,_="",te;for(te="l"+w+",0 0,"+w+" -"+w+",0 0,-"+w+"z ",_+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"',_+=E.scalable?"":' width="'+A+'px" height="'+A+'px"',_+=' viewBox="0 0 '+A+" "+A+'" ',_+=' preserveAspectRatio="xMinYMin meet"',_+=x.text||b.text?' role="img" aria-labelledby="'+D([x.id,b.id].join(" ").trim())+'"':"",_+=">",_+=x.text?'<title id="'+D(x.id)+'">'+D(x.text)+"</title>":"",_+=b.text?'<description id="'+D(b.id)+'">'+D(b.text)+"</description>":"",_+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>',_+='<path d="',G=0;G<u.getModuleCount();G+=1)for(ae=G*w+m,M=0;M<u.getModuleCount();M+=1)u.isDark(G,M)&&(W=M*w+m,_+="M"+W+","+ae+te);return _+='" stroke="transparent" fill="black"/>',_+="</svg>",_},u.createDataURL=function(w,m){w=w||2,m=typeof m>"u"?w*4:m;let b=u.getModuleCount()*w+m*2,x=m,E=b-m;return qa(b,b,function(A,M){if(x<=A&&A<E&&x<=M&&M<E){let W=Math.floor((A-x)/w),G=Math.floor((M-x)/w);return u.isDark(G,W)?0:1}else return 1})},u.createImgTag=function(w,m,b){w=w||2,m=typeof m>"u"?w*4:m;let x=u.getModuleCount()*w+m*2,E="";return E+="<img",E+=' src="',E+=u.createDataURL(w,m),E+='"',E+=' width="',E+=x,E+='"',E+=' height="',E+=x,E+='"',b&&(E+=' alt="',E+=D(b),E+='"'),E+="/>",E};let D=function(w){let m="";for(let b=0;b<w.length;b+=1){let x=w.charAt(b);switch(x){case"<":m+="<";break;case">":m+=">";break;case"&":m+="&";break;case'"':m+=""";break;default:m+=x;break}}return m},L=function(w){w=typeof w>"u"?2:w;let b=u.getModuleCount()*1+w*2,x=w,E=b-w,A,M,W,G,ae,_={"\u2588\u2588":"\u2588","\u2588 ":"\u2580"," \u2588":"\u2584"," ":" "},te={"\u2588\u2588":"\u2580","\u2588 ":"\u2580"," \u2588":" "," ":" "},de="";for(A=0;A<b;A+=2){for(W=Math.floor((A-x)/1),G=Math.floor((A+1-x)/1),M=0;M<b;M+=1)ae="\u2588",x<=M&&M<E&&x<=A&&A<E&&u.isDark(W,Math.floor((M-x)/1))&&(ae=" "),x<=M&&M<E&&x<=A+1&&A+1<E&&u.isDark(G,Math.floor((M-x)/1))?ae+=" ":ae+="\u2588",de+=w<1&&A+1>=E?te[ae]:_[ae];de+=` |
| 2 | `}return b%2&&w>0?de.substring(0,de.length-b-1)+Array(b+1).join("\u2580"):de.substring(0,de.length-1)};return u.createASCII=function(w,m){if(w=w||1,w<2)return L(m);w-=1,m=typeof m>"u"?w*2:m;let b=u.getModuleCount()*w+m*2,x=m,E=b-m,A,M,W,G,ae=Array(w+1).join("\u2588\u2588"),_=Array(w+1).join(" "),te="",de="";for(A=0;A<b;A+=1){for(W=Math.floor((A-x)/w),de="",M=0;M<b;M+=1)G=1,x<=M&&M<E&&x<=A&&A<E&&u.isDark(W,Math.floor((M-x)/w))&&(G=0),de+=G?ae:_;for(W=0;W<w;W+=1)te+=de+` |
| 3 | `}return te.substring(0,te.length-1)},u.renderTo2dContext=function(w,m){m=m||2;let b=u.getModuleCount();for(let x=0;x<b;x++)for(let E=0;E<b;E++)w.fillStyle=u.isDark(x,E)?"black":"white",w.fillRect(E*m,x*m,m,m)},u};zt.stringToBytes=function(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);t.push(r&255)}return t};zt.createStringToBytes=function(e,t){let n=(function(){let o=za(e),s=function(){let c=o.read();if(c==-1)throw"eof";return c},i=0,a={};for(;;){let c=o.read();if(c==-1)break;let f=s(),u=s(),l=s(),d=String.fromCharCode(c<<8|f),p=u<<8|l;a[d]=p,i+=1}if(i!=t)throw i+" != "+t;return a})(),r=63;return function(o){let s=[];for(let i=0;i<o.length;i+=1){let a=o.charCodeAt(i);if(a<128)s.push(a);else{let c=n[o.charAt(i)];typeof c=="number"?(c&255)==c?s.push(c):(s.push(c>>>8),s.push(c&255)):s.push(r)}}return s}};var Oe={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},wn={L:1,M:0,Q:3,H:2},pt={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},ht=(function(){let 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]],t=1335,n=7973,r=21522,o={},s=function(i){let a=0;for(;i!=0;)a+=1,i>>>=1;return a};return o.getBCHTypeInfo=function(i){let a=i<<10;for(;s(a)-s(t)>=0;)a^=t<<s(a)-s(t);return(i<<10|a)^r},o.getBCHTypeNumber=function(i){let a=i<<12;for(;s(a)-s(n)>=0;)a^=n<<s(a)-s(n);return i<<12|a},o.getPatternPosition=function(i){return e[i-1]},o.getMaskFunction=function(i){switch(i){case pt.PATTERN000:return function(a,c){return(a+c)%2==0};case pt.PATTERN001:return function(a,c){return a%2==0};case pt.PATTERN010:return function(a,c){return c%3==0};case pt.PATTERN011:return function(a,c){return(a+c)%3==0};case pt.PATTERN100:return function(a,c){return(Math.floor(a/2)+Math.floor(c/3))%2==0};case pt.PATTERN101:return function(a,c){return a*c%2+a*c%3==0};case pt.PATTERN110:return function(a,c){return(a*c%2+a*c%3)%2==0};case pt.PATTERN111:return function(a,c){return(a*c%3+(a+c)%2)%2==0};default:throw"bad maskPattern:"+i}},o.getErrorCorrectPolynomial=function(i){let a=yn([1],0);for(let c=0;c<i;c+=1)a=a.multiply(yn([1,gt.gexp(c)],0));return a},o.getLengthInBits=function(i,a){if(1<=a&&a<10)switch(i){case Oe.MODE_NUMBER:return 10;case Oe.MODE_ALPHA_NUM:return 9;case Oe.MODE_8BIT_BYTE:return 8;case Oe.MODE_KANJI:return 8;default:throw"mode:"+i}else if(a<27)switch(i){case Oe.MODE_NUMBER:return 12;case Oe.MODE_ALPHA_NUM:return 11;case Oe.MODE_8BIT_BYTE:return 16;case Oe.MODE_KANJI:return 10;default:throw"mode:"+i}else if(a<41)switch(i){case Oe.MODE_NUMBER:return 14;case Oe.MODE_ALPHA_NUM:return 13;case Oe.MODE_8BIT_BYTE:return 16;case Oe.MODE_KANJI:return 12;default:throw"mode:"+i}else throw"type:"+a},o.getLostPoint=function(i){let a=i.getModuleCount(),c=0;for(let l=0;l<a;l+=1)for(let d=0;d<a;d+=1){let p=0,h=i.isDark(l,d);for(let g=-1;g<=1;g+=1)if(!(l+g<0||a<=l+g))for(let y=-1;y<=1;y+=1)d+y<0||a<=d+y||g==0&&y==0||h==i.isDark(l+g,d+y)&&(p+=1);p>5&&(c+=3+p-5)}for(let l=0;l<a-1;l+=1)for(let d=0;d<a-1;d+=1){let p=0;i.isDark(l,d)&&(p+=1),i.isDark(l+1,d)&&(p+=1),i.isDark(l,d+1)&&(p+=1),i.isDark(l+1,d+1)&&(p+=1),(p==0||p==4)&&(c+=3)}for(let l=0;l<a;l+=1)for(let d=0;d<a-6;d+=1)i.isDark(l,d)&&!i.isDark(l,d+1)&&i.isDark(l,d+2)&&i.isDark(l,d+3)&&i.isDark(l,d+4)&&!i.isDark(l,d+5)&&i.isDark(l,d+6)&&(c+=40);for(let l=0;l<a;l+=1)for(let d=0;d<a-6;d+=1)i.isDark(d,l)&&!i.isDark(d+1,l)&&i.isDark(d+2,l)&&i.isDark(d+3,l)&&i.isDark(d+4,l)&&!i.isDark(d+5,l)&&i.isDark(d+6,l)&&(c+=40);let f=0;for(let l=0;l<a;l+=1)for(let d=0;d<a;d+=1)i.isDark(d,l)&&(f+=1);let u=Math.abs(100*f/a/a-50)/5;return c+=u*10,c},o})(),gt=(function(){let e=new Array(256),t=new Array(256);for(let r=0;r<8;r+=1)e[r]=1<<r;for(let r=8;r<256;r+=1)e[r]=e[r-4]^e[r-5]^e[r-6]^e[r-8];for(let r=0;r<255;r+=1)t[e[r]]=r;let n={};return n.glog=function(r){if(r<1)throw"glog("+r+")";return t[r]},n.gexp=function(r){for(;r<0;)r+=255;for(;r>=256;)r-=255;return e[r]},n})(),yn=function(e,t){if(typeof e.length>"u")throw e.length+"/"+t;let n=(function(){let o=0;for(;o<e.length&&e[o]==0;)o+=1;let s=new Array(e.length-o+t);for(let i=0;i<e.length-o;i+=1)s[i]=e[i+o];return s})(),r={};return r.getAt=function(o){return n[o]},r.getLength=function(){return n.length},r.multiply=function(o){let s=new Array(r.getLength()+o.getLength()-1);for(let i=0;i<r.getLength();i+=1)for(let a=0;a<o.getLength();a+=1)s[i+a]^=gt.gexp(gt.glog(r.getAt(i))+gt.glog(o.getAt(a)));return yn(s,0)},r.mod=function(o){if(r.getLength()-o.getLength()<0)return r;let s=gt.glog(r.getAt(0))-gt.glog(o.getAt(0)),i=new Array(r.getLength());for(let a=0;a<r.getLength();a+=1)i[a]=r.getAt(a);for(let a=0;a<o.getLength();a+=1)i[a]^=gt.gexp(gt.glog(o.getAt(a))+s);return yn(i,0).mod(o)},r},ii=(function(){let 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]],t=function(o,s){let i={};return i.totalCount=o,i.dataCount=s,i},n={},r=function(o,s){switch(s){case wn.L:return e[(o-1)*4+0];case wn.M:return e[(o-1)*4+1];case wn.Q:return e[(o-1)*4+2];case wn.H:return e[(o-1)*4+3];default:return}};return n.getRSBlocks=function(o,s){let i=r(o,s);if(typeof i>"u")throw"bad rs block @ typeNumber:"+o+"/errorCorrectionLevel:"+s;let a=i.length/3,c=[];for(let f=0;f<a;f+=1){let u=i[f*3+0],l=i[f*3+1],d=i[f*3+2];for(let p=0;p<u;p+=1)c.push(t(l,d))}return c},n})(),si=function(){let e=[],t=0,n={};return n.getBuffer=function(){return e},n.getAt=function(r){let o=Math.floor(r/8);return(e[o]>>>7-r%8&1)==1},n.put=function(r,o){for(let s=0;s<o;s+=1)n.putBit((r>>>o-s-1&1)==1)},n.getLengthInBits=function(){return t},n.putBit=function(r){let o=Math.floor(t/8);e.length<=o&&e.push(0),r&&(e[o]|=128>>>t%8),t+=1},n},Ha=function(e){let t=Oe.MODE_NUMBER,n=e,r={};r.getMode=function(){return t},r.getLength=function(i){return n.length},r.write=function(i){let a=n,c=0;for(;c+2<a.length;)i.put(o(a.substring(c,c+3)),10),c+=3;c<a.length&&(a.length-c==1?i.put(o(a.substring(c,c+1)),4):a.length-c==2&&i.put(o(a.substring(c,c+2)),7))};let o=function(i){let a=0;for(let c=0;c<i.length;c+=1)a=a*10+s(i.charAt(c));return a},s=function(i){if("0"<=i&&i<="9")return i.charCodeAt(0)-48;throw"illegal char :"+i};return r},Da=function(e){let t=Oe.MODE_ALPHA_NUM,n=e,r={};r.getMode=function(){return t},r.getLength=function(s){return n.length},r.write=function(s){let i=n,a=0;for(;a+1<i.length;)s.put(o(i.charAt(a))*45+o(i.charAt(a+1)),11),a+=2;a<i.length&&s.put(o(i.charAt(a)),6)};let o=function(s){if("0"<=s&&s<="9")return s.charCodeAt(0)-48;if("A"<=s&&s<="Z")return s.charCodeAt(0)-65+10;switch(s){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 :"+s}};return r},Fa=function(e){let t=Oe.MODE_8BIT_BYTE,n=e,r=zt.stringToBytes(e),o={};return o.getMode=function(){return t},o.getLength=function(s){return r.length},o.write=function(s){for(let i=0;i<r.length;i+=1)s.put(r[i],8)},o},ja=function(e){let t=Oe.MODE_KANJI,n=e,r=zt.stringToBytes;(function(i,a){let c=r(i);if(c.length!=2||(c[0]<<8|c[1])!=a)throw"sjis not supported."})("\u53CB",38726);let o=r(e),s={};return s.getMode=function(){return t},s.getLength=function(i){return~~(o.length/2)},s.write=function(i){let a=o,c=0;for(;c+1<a.length;){let f=(255&a[c])<<8|255&a[c+1];if(33088<=f&&f<=40956)f-=33088;else if(57408<=f&&f<=60351)f-=49472;else throw"illegal char at "+(c+1)+"/"+f;f=(f>>>8&255)*192+(f&255),i.put(f,13),c+=2}if(c<a.length)throw"illegal char at "+(c+1)},s},ai=function(){let e=[],t={};return t.writeByte=function(n){e.push(n&255)},t.writeShort=function(n){t.writeByte(n),t.writeByte(n>>>8)},t.writeBytes=function(n,r,o){r=r||0,o=o||n.length;for(let s=0;s<o;s+=1)t.writeByte(n[s+r])},t.writeString=function(n){for(let r=0;r<n.length;r+=1)t.writeByte(n.charCodeAt(r))},t.toByteArray=function(){return e},t.toString=function(){let n="";n+="[";for(let r=0;r<e.length;r+=1)r>0&&(n+=","),n+=e[r];return n+="]",n},t},Ka=function(){let e=0,t=0,n=0,r="",o={},s=function(a){r+=String.fromCharCode(i(a&63))},i=function(a){if(a<0)throw"n:"+a;if(a<26)return 65+a;if(a<52)return 97+(a-26);if(a<62)return 48+(a-52);if(a==62)return 43;if(a==63)return 47;throw"n:"+a};return o.writeByte=function(a){for(e=e<<8|a&255,t+=8,n+=1;t>=6;)s(e>>>t-6),t-=6},o.flush=function(){if(t>0&&(s(e<<6-t),e=0,t=0),n%3!=0){let a=3-n%3;for(let c=0;c<a;c+=1)r+="="}},o.toString=function(){return r},o},za=function(e){let t=e,n=0,r=0,o=0,s={};s.read=function(){for(;o<8;){if(n>=t.length){if(o==0)return-1;throw"unexpected end of file./"+o}let c=t.charAt(n);if(n+=1,c=="=")return o=0,-1;if(c.match(/^\s$/))continue;r=r<<6|i(c.charCodeAt(0)),o+=6}let a=r>>>o-8&255;return o-=8,a};let i=function(a){if(65<=a&&a<=90)return a-65;if(97<=a&&a<=122)return a-97+26;if(48<=a&&a<=57)return a-48+52;if(a==43)return 62;if(a==47)return 63;throw"c:"+a};return s},Wa=function(e,t){let n=e,r=t,o=new Array(e*t),s={};s.setPixel=function(f,u,l){o[u*n+f]=l},s.write=function(f){f.writeString("GIF87a"),f.writeShort(n),f.writeShort(r),f.writeByte(128),f.writeByte(0),f.writeByte(0),f.writeByte(0),f.writeByte(0),f.writeByte(0),f.writeByte(255),f.writeByte(255),f.writeByte(255),f.writeString(","),f.writeShort(0),f.writeShort(0),f.writeShort(n),f.writeShort(r),f.writeByte(0);let u=2,l=a(u);f.writeByte(u);let d=0;for(;l.length-d>255;)f.writeByte(255),f.writeBytes(l,d,255),d+=255;f.writeByte(l.length-d),f.writeBytes(l,d,l.length-d),f.writeByte(0),f.writeString(";")};let i=function(f){let u=f,l=0,d=0,p={};return p.write=function(h,g){if(h>>>g)throw"length over";for(;l+g>=8;)u.writeByte(255&(h<<l|d)),g-=8-l,h>>>=8-l,d=0,l=0;d=h<<l|d,l=l+g},p.flush=function(){l>0&&u.writeByte(d)},p},a=function(f){let u=1<<f,l=(1<<f)+1,d=f+1,p=c();for(let P=0;P<u;P+=1)p.add(String.fromCharCode(P));p.add(String.fromCharCode(u)),p.add(String.fromCharCode(l));let h=ai(),g=i(h);g.write(u,d);let y=0,S=String.fromCharCode(o[y]);for(y+=1;y<o.length;){let P=String.fromCharCode(o[y]);y+=1,p.contains(S+P)?S=S+P:(g.write(p.indexOf(S),d),p.size()<4095&&(p.size()==1<<d&&(d+=1),p.add(S+P)),S=P)}return g.write(p.indexOf(S),d),g.write(l,d),g.flush(),h.toByteArray()},c=function(){let f={},u=0,l={};return l.add=function(d){if(l.contains(d))throw"dup key:"+d;f[d]=u,u+=1},l.size=function(){return u},l.indexOf=function(d){return f[d]},l.contains=function(d){return typeof f[d]<"u"},l};return s},qa=function(e,t,n){let r=Wa(e,t);for(let a=0;a<t;a+=1)for(let c=0;c<e;c+=1)r.setPixel(c,a,n(c,a));let o=ai();r.write(o);let s=Ka(),i=o.toByteArray();for(let a=0;a<i.length;a+=1)s.writeByte(i[a]);return s.flush(),"data:image/gif;base64,"+s},ci=zt,ml=zt.stringToBytes;var Ut=class extends Error{constructor(n,r){super(r);k(this,"status",n)}};async function Z(e,t){let n={credentials:"same-origin"};t!==void 0&&(n.method="POST",n.headers={"content-type":"application/json"},n.body=JSON.stringify(t));let r;try{r=await fetch("/api"+e,n)}catch{throw new Ut(0,"You seem to be offline. Check your connection and try again.")}let o=await r.json().catch(()=>({}));if(!r.ok)throw new Ut(r.status,o.error||"Something went wrong. Please try again.");return o}var ze=e=>{let t=e instanceof Uint8Array?e:new Uint8Array(e),n="";for(let r of t)n+=String.fromCharCode(r);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")},wt=e=>{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((e.length+3)%4)),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n};var fi=()=>typeof window.PublicKeyCredential=="function"&&!!navigator.credentials;async function li(e){let t=await navigator.credentials.create({publicKey:{challenge:wt(e.challenge),rp:e.rp,user:{id:wt(e.user.id),name:e.user.name,displayName:e.user.displayName},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-8},{type:"public-key",alg:-257}],authenticatorSelection:{residentKey:"required",requireResidentKey:!0,userVerification:"required"},attestation:"none",timeout:12e4,extensions:{prf:{}}}});if(!t)throw new Error("Passkey creation was cancelled.");let n=t.response;return{id:t.id,clientDataJSON:ze(n.clientDataJSON),attestationObject:ze(n.attestationObject)}}async function Kn(e,t,n){let r={};n&&(r.prf={eval:{first:n}});let o=await navigator.credentials.get({publicKey:{challenge:wt(e.challenge),rpId:e.rpId,userVerification:"required",timeout:12e4,allowCredentials:t?[{type:"public-key",id:wt(t)}]:[],extensions:r}});if(!o)throw new Error("Sign-in was cancelled.");let s=o.response,i=o.getClientExtensionResults();return{body:{id:o.id,clientDataJSON:ze(s.clientDataJSON),authenticatorData:ze(s.authenticatorData),signature:ze(s.signature),userHandle:s.userHandle?ze(s.userHandle):""},prf:i.prf?.results?.first?new Uint8Array(i.prf.results.first):null}}var Va=e=>e/2**32|0,Ya=e=>e>>>0;function ui(e,t,n,r){let o=Va(n),s=Ya(n);e.setUint32(t,r?s:o,r),e.setUint32(t+4,r?o:s,r)}function zn(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var qr=e=>e?`"${e}" `:"";function le(e,t=""){if(typeof e!="number")throw new TypeError(qr(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(qr(t)+"expected integer >= 0, got "+e);return e}function Ze(e,t,n=""){if(zn(e)&&(t===void 0||e.length===t))return e;t!==void 0&&le(t,"length");let r=zn(e),o=t!==void 0?` of length ${t}`:"",s=r?`length=${e.length}`:`type=${typeof e}`,i=qr(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}function Wn(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(le(e.outputLen),le(e.blockLen),e.outputLen<1||e.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Ga=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},di=(e,t)=>{Ga(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function Wt(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function qn(e,t){Ze(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function yt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Vn(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function We(e,t){return e<<32-t|e>>>t}function bn(e,t){return e<<t|e>>>32-t>>>0}var hi=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Za=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Yn(e){if(Ze(e),hi)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Za[e[n]];return t}function pi(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Vr(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(hi)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let t=e.length,n=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){let i=pi(e.charCodeAt(s)),a=pi(e.charCodeAt(s+1));if(i===void 0||a===void 0){let c=e[s]+e[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function Gn(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];Ze(o),t+=o.length}let n=new Uint8Array(t);for(let r=0,o=0;r<e.length;r++){let s=e[r];n.set(s,o),o+=s.length}return n}function Xa(e,t,n="opts"){return di(e,"defaults"),t!==void 0&&di(t,n),Object.assign(Object.create(null),e,t)}function Zn(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=Xa({},t,"info");let n=(o,s)=>e(s).update(o).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>e(o),Object.assign(n,t),Object.freeze(n)}function mn(e=32){le(e,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var gi=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Yr(e,t,n){return e&t^~e&n}function Gr(e,t,n){return e&t^e&n^t&n}var qt=class{constructor(t,n,r,o){k(this,"blockLen");k(this,"outputLen");k(this,"canXOF",!1);k(this,"padOffset");k(this,"isLE");k(this,"buffer");k(this,"view");k(this,"finished",!1);k(this,"length",0);k(this,"pos",0);k(this,"destroyed",!1);this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Vn(this.buffer)}update(t){Wt(this),Ze(t);let{view:n,buffer:r,blockLen:o}=this,s=t.length,i=!1;for(let a=0;a<s;){let c=Math.min(o-this.pos,s-a);if(c===o){let f=Vn(t);for(;o<=s-a;a+=o)this.process(f,a);i=!0;continue}r.set(a===0&&c===s?t:t.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(n,0),this.pos=0,i=!0)}return this.length+=t.length,i&&this.roundClean(),this}digestInto(t){Wt(this),qn(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:s}=this,{pos:i}=this;n[i++]=128,n.fill(0,i),this.padOffset>o-i&&(this.process(r,0),n.fill(0)),ui(r,o-8,this.length*8,s),this.process(r,0),this.roundClean();let a=t===n?r:Vn(t),c=this.outputLen,f=c/4,u=this.get();if(c%4||f>u.length)throw new Error("invalid outputLen");for(let l=0;l<f;l++)a.setUint32(4*l,u[l],s)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:o,destroyed:s,pos:i}=this;return t.destroyed=s,t.finished=o,t.length=r,t.pos=i,i&&t.buffer.set(n),t}clone(){return this._cloneInto()}},wi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Qa=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]),bt=new Uint32Array(64),Zr=class extends qt{constructor(n,r){super(64,n,8,!1);k(this,"A",0);k(this,"B",0);k(this,"C",0);k(this,"D",0);k(this,"E",0);k(this,"F",0);k(this,"G",0);k(this,"H",0);this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:n,B:r,C:o,D:s,E:i,F:a,G:c,H:f}=this;return[n,r,o,s,i,a,c,f]}set(n,r,o,s,i,a,c,f){this.A=n|0,this.B=r|0,this.C=o|0,this.D=s|0,this.E=i|0,this.F=a|0,this.G=c|0,this.H=f|0}_cloneInto(n){return(n||(n=new this.constructor)).set(...this.get()),this._cloneIntoMeta(n)}process(n,r){for(let d=0;d<16;d++,r+=4)bt[d]=n.getUint32(r,!1);for(let d=16;d<64;d++){let p=bt[d-15],h=bt[d-2],g=We(p,7)^We(p,18)^p>>>3,y=We(h,17)^We(h,19)^h>>>10;bt[d]=y+bt[d-7]+g+bt[d-16]|0}let{A:o,B:s,C:i,D:a,E:c,F:f,G:u,H:l}=this;for(let d=0;d<64;d++){let p=We(c,6)^We(c,11)^We(c,25),h=l+p+Yr(c,f,u)+Qa[d]+bt[d]|0,y=(We(o,2)^We(o,13)^We(o,22))+Gr(o,s,i)|0;l=u,u=f,f=c,c=a+h|0,a=i,i=s,s=o,o=h+y|0}o=o+this.A|0,s=s+this.B|0,i=i+this.C|0,a=a+this.D|0,c=c+this.E|0,f=f+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(o,s,i,a,c,f,u,l)}roundClean(){yt(bt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),yt(this.buffer)}},Xr=class extends Zr{constructor(){super(32,wi)}};var Vt=Zn(()=>new Xr,gi(1));function Qn(e,t,n=()=>{}){if(!Array.isArray(e))throw new TypeError(`"${t}" expected array, got type=${typeof e}`);for(let r=0;r<e.length;r++)n(e[r],`${t}[${r}]`);return e}var q=(e,t,n)=>Ze(e,t,n),Qr=le;function bi(e,t=""){if(typeof e!="string"){let n=t&&`"${t}" `;throw new TypeError(n+"expected string, got type="+typeof e)}return e}function mt(e,t="object"){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`);return e}function Rt(e,t){if(typeof e!="function")throw new TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}var Jr=Yn,Fe=(...e)=>Gn(...e),Jn=e=>Vr(e),Yt=zn,er=e=>mn(e),Xn=BigInt(0),yi=BigInt(1),Ja=e=>e?`"${e}" `:"";function Xe(e,t=""){if(typeof e!="boolean")throw new TypeError(Ja(t)+"expected boolean, got type="+typeof e);return e}function tr(e){if(typeof e=="bigint"){if(!xt(e))throw new RangeError("positive bigint expected, got "+e)}else Qr(e);return e}function Mt(e,t=""){if(typeof e!="number"){let n=t&&`"${t}" `;throw new TypeError(n+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let n=t&&`"${t}" `;throw new RangeError(n+"expected safe integer, got "+e)}}function xn(e){let t=tr(e).toString(16);return t.length&1?"0"+t:t}function mi(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?Xn:BigInt("0x"+e)}function Pe(e){return mi(Yn(e))}function eo(e){return mi(Yn(no(Ze(e)).reverse()))}function Gt(e,t){if(le(t),t===0)throw new Error("zero output length is invalid");e=tr(e);let n=t*2,r=e.toString(16);if(r.length>n)throw new RangeError("number is too large");return Vr(r.padStart(n,"0"))}function to(e,t){return Gt(e,t).reverse()}function no(e){return Uint8Array.from(q(e))}function xi(e){if(typeof e!="string")throw new TypeError("ascii string expected, got "+typeof e);return Uint8Array.from(e,(t,n)=>{let r=t.charCodeAt(0);if(t.length!==1||r>127)throw new RangeError(`string contains non-ASCII character "${e[n]}" with code ${r} at position ${n}`);return r})}function xt(e){return typeof e=="bigint"&&Xn<=e}function ro(e,t,n){return xt(e)&&xt(t)&&xt(n)&&t<=e&&e<n}function oo(e,t,n,r){if(!ro(t,n,r))throw new RangeError("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Zt(e){if(e<Xn)throw new Error("expected non-negative bigint, got "+e);return e===Xn?0:e.toString(2).length}var En=e=>(Mt(e,"n"),(yi<<BigInt(e))-yi);function Ei(e,t,n){if(le(e,"hashLen"),le(t,"qByteLen"),typeof n!="function")throw new TypeError("hmacFn must be a function");let r=y=>new Uint8Array(y),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=r(e),f=r(e),u=0,l=()=>{c.fill(1),f.fill(0),u=0},d=(...y)=>n(f,Fe(c,...y)),p=(y=o)=>{f=d(s,y),c=d(),y.length!==0&&(f=d(i,y),c=d())},h=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,S=[];for(;y<t;){c=d();let P=c.slice();S.push(P),y+=c.length}return Fe(...S)};return(y,S)=>{l(),p(y);let P;for(;(P=S(h()))===void 0;)p();return l(),P}}function qe(e,t={},n={},r="object"){mt(e,r),mt(t,"fields"),mt(n,"optFields");function o(i,a,c){let f=r==="object"?`param "${String(i)}"`:`"${r}.${String(i)}"`,u=e[i];if(!Object.hasOwn(e,i)&&(c?u!==void 0:a!=="function"))throw new TypeError(`${f} is invalid: expected own property`);if(c&&u===void 0)return;let l=typeof u;if(l!==a||u===null)throw new TypeError(`${f} is invalid: expected ${a}, got ${l}`)}let s=(i,a)=>Object.entries(i).forEach(([c,f])=>o(c,f,a));s(t,!1),s(n,!0)}var Ee=BigInt(0),oe=BigInt(1),Et=BigInt(2),Bi=BigInt(3),io=BigInt(4),vi=BigInt(5),ec=BigInt(7),Pi=BigInt(8),tc=BigInt(9),nc=BigInt(15),Ai=BigInt(16),rc=BigInt("0x10000000000000000");function Ce(e,t){if(t<=Ee)throw new Error("mod: expected positive modulus, got "+t);let n=e%t;return n>=Ee?n:t+n}function $i(e,t,n){if(n<=oe)throw new Error("pow: expected modulus > 1, got "+n);if(typeof t!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof t);if(t<Ee)throw new Error("invalid exponent, negatives unsupported");if(t===Ee)return oe;if(t===oe)return e;let r=e%n;if(r<Ee&&(r+=n),t<rc){let a=oe;for(;t>Ee;)t&oe&&(a=a*r%n),r=r*r%n,t>>=oe;return a}let o=[];for(;t>Ee;)o.push(Number(t&nc)),t>>=io;let s=new Array(16);s[0]=oe,s[1]=r;for(let a=2;a<16;a++)s[a]=s[a-1]*r%n;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%n,i=i*i%n,i=i*i%n,i=i*i%n;let c=o[a];c!==0&&(i=i*s[c]%n)}return i}function Ne(e,t,n){if(n<=oe)throw new Error("pow2: expected modulus > 1, got "+n);if(t<Ee)throw new Error("pow2: expected non-negative exponent, got "+t);let r=e;for(;t-- >Ee;)r*=r,r%=n;return r}function Si(e,t){if(e===Ee)throw new Error("invert: expected non-zero number");if(t<=oe)throw new Error("invert: expected modulus > 1, got "+t);let n=Ce(e,t),r=t,o=Ee,s=oe;for(;n!==Ee;){let a=r/n,c=r-n*a,f=o-s*a;r=n,n=c,o=s,s=f}if(r!==oe)throw new Error("invert: does not exist");return Ce(o,t)}function Oi(e,t){if(t<=oe)throw new Error("invertCt: expected prime modulus > 1, got "+t);let n=Ce(e,t);if(n===Ee)throw new Error("invertCt: expected non-zero number");let r=$i(n,t-Et,t);if(Ce(n*r,t)!==oe)throw new Error("invertCt: does not exist");return r}function so(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function ao(e,t){if((e&oe)===Ee)throw new Error(t+": expected odd modulus, got "+e)}function Ii(e,t){let n=e,r=(n.ORDER+oe)/io,o=n.pow(t,r);return so(n,o,t),o}function oc(e,t){let n=e,r=(n.ORDER-vi)/Pi,o=n.mul(t,Et),s=n.pow(o,r),i=n.mul(t,s),a=n.mul(n.mul(i,Et),s),c=n.mul(i,n.sub(a,n.ONE));return so(n,c,t),c}function ic(e){let t=Qt(e),n=Li(e),r=n(t,t.neg(t.ONE)),o=n(t,r),s=n(t,t.neg(r)),i=(e+ec)/Ai;return((a,c)=>{let f=a,u=f.pow(c,i),l=f.mul(u,r),d=f.mul(u,o),p=f.mul(u,s),h=f.eql(f.sqr(l),c),g=f.eql(f.sqr(d),c);u=f.cmov(u,l,h),l=f.cmov(p,d,g);let y=f.eql(f.sqr(l),c),S=f.cmov(u,l,y);return so(f,S,c),S})}function Li(e){if(e<Bi)throw new Error("sqrt is not defined for small field");ao(e,"tonelliShanks");let t=e-oe,n=0;for(;t%Et===Ee;)t/=Et,n++;let r=Et,o=Qt(e);for(;Ti(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Ii;let s=o.pow(r,t),i=(t+oe)/Et;return function(c,f){let u=c;if(u.is0(f))return f;if(Ti(u,f)!==1)throw new Error("Cannot find square root");let l=n,d=u.mul(u.ONE,s),p=u.pow(f,t),h=u.pow(f,i);for(;!u.eql(p,u.ONE);){if(u.is0(p))throw new Error("Cannot find square root: probably non-prime P");let g=1,y=u.sqr(p);for(;!u.eql(y,u.ONE);)if(g++,y=u.sqr(y),g===l)throw new Error("Cannot find square root");let S=oe<<BigInt(l-g-1),P=u.pow(d,S);l=g,d=u.sqr(P),p=u.mul(p,d),h=u.mul(h,P)}return h}}function sc(e){return ao(e,"Fp.sqrt"),e%io===Bi?Ii:e%Pi===vi?oc:e%Ai===tc?ic(e):Li(e)}var ac=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Xt(e){if(mt(e,"field"),typeof e.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof e.ORDER);Mt(e.BYTES,"BYTES"),Mt(e.BITS,"BITS");for(let t of ac)Rt(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=oe)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function co(e,t,n=!1){Xt(e),Qn(t,"nums"),Xe(n,"passZero");let r=e,o=new Array(t.length).fill(n?r.ZERO:void 0),s=t.reduce((a,c,f)=>r.is0(c)?a:(o[f]=a,r.mul(a,c)),r.ONE),i=r.inv(s);return t.reduceRight((a,c,f)=>r.is0(c)?a:(o[f]=r.mul(a,o[f]),r.mul(a,c)),i),o}function Ti(e,t){Xt(e);let n=e;ao(n.ORDER,"FpLegendre");let r=(n.ORDER-oe)/Et,o=n.pow(t,r),s=n.eql(o,n.ONE),i=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function cc(e,t){if(t!==void 0&&Qr(t),e<=Ee)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);let n=Zt(e);if(t!==void 0&&t<n)throw new Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${n})`);let r=t!==void 0?t:n,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}var ki=new WeakMap,nr=class{constructor(t,n={}){k(this,"ORDER");k(this,"BITS");k(this,"BYTES");k(this,"isLE");k(this,"ZERO",Ee);k(this,"ONE",oe);k(this,"_lengths");k(this,"_mod");if(t<=oe)throw new Error("invalid field: expected ORDER > 1, got "+t);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:!0}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:s}=cc(t,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(t){return Ce(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return Ee<=t&&t<this.ORDER}is0(t){return t===Ee}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&oe)===oe}neg(t){return Ce(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){return Ce(t*t,this.ORDER)}add(t,n){return Ce(t+n,this.ORDER)}sub(t,n){return Ce(t-n,this.ORDER)}mul(t,n){return Ce(t*n,this.ORDER)}pow(t,n){return $i(t,n,this.ORDER)}div(t,n){return Ce(t*Si(n,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return Si(t,this.ORDER)}sqrt(t){let n=ki.get(this);return n||ki.set(this,n=sc(this.ORDER)),n(this,t)}toBytes(t){return this.isLE?to(t,this.BYTES):Gt(t,this.BYTES)}fromBytes(t,n=!1){q(t);let{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(r){if(t.length<1||!r.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+t.length);let f=new Uint8Array(o);f.set(t,s?0:f.length-t.length),t=f}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?eo(t):Pe(t);if(a&&(c=Ce(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return co(this,t,!0)}cmov(t,n,r){return Xe(r,"condition"),r?n:t}};function Qt(e,t={}){return Object.freeze(nr.prototype),new nr(e,t)}function _i(e){if(typeof e!="bigint")throw new Error("field order must be bigint");if(e<=oe)throw new Error("field order must be greater than 1");let t=Zt(e-oe);return Math.ceil(t/8)}function rr(e){let t=_i(e);return t+Math.ceil(t/2)}function Sn(e,t,n=!1){q(e);let r=e.length,o=_i(t),s=Math.max(rr(t),16);if(r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);let i=n?eo(e):Pe(e),a=Ce(i,t-oe)+oe;return n?to(a,o):Gt(a,o)}var uo=BigInt(0),Tn=BigInt(1),fc=BigInt(4),fo=16,Ui=128,lc=5,Ri=2**31;function Jt(e){let t=e;if(typeof t!="function")throw new TypeError('"Point" expected constructor, got type='+typeof e);Rt(t.fromAffine,"Point.fromAffine"),Rt(t.fromBytes,"Point.fromBytes"),Rt(t.fromHex,"Point.fromHex"),mt(t.BASE,"Point.BASE"),mt(t.ZERO,"Point.ZERO"),Xt(t.Fp),Xt(t.Fn)}function Ci(e,t){Jt(e),Ni(t,e);let n=co(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function uc(e,t,n=1){if(!Number.isSafeInteger(e)||e<n||e>t)throw new Error("invalid window size, expected ["+n+".."+t+"], got W="+e)}function dc(e,t){let n=e*(4*t+128);if(n>Ri)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+Ri/2**20+" MiB")}function po(e,t){if(e!==void 0){Rt(e,"randomBytes");try{let n=e(t);if(!Yt(n)||n.length!==t)return}catch{return}return e}}function Ni(e,t){Qn(e,"points"),e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function pc(e,t,n){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,o)=>{if(!(n===void 0?t.isValid(r):xt(r)&&r<n))throw new Error("invalid scalar at index "+o)})}var Hi=new WeakMap;function lo(e){return Hi.get(e)||1}function hc(e,t){let n=e.double(),r=[e];for(let o=1;o<t;o++)r.push(r[o-1].add(n));return r}function gc(e,t){let n=2**t,r=n/2,o=BigInt(n-1),s=[];for(;e>uo;){let i=0;e&Tn&&(i=Number(e&o),i>=r&&(i-=n),e-=BigInt(i)),s.push(i),e>>=Tn}return s}function wc(e,t,n){let r=2**t,o=r/2,s=BigInt(r-1),i=BigInt(t),a=[];for(let c=0;c<n;c++){let f=Number(e&s);e>>=i,f>o&&(f-=r,e+=Tn),a.push(f)}if(e!==uo)throw new Error("invalid wnaf");return a}function yc(e,t,n){let r=0;for(let s of n)r=Math.max(r,s.length);let o=e;for(let s=r-1;s>=0;s--){s!==r-1&&(o=o.double());for(let i=0;i<n.length;i++){let a=n[i][s];if(a){let c=t[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var or=class{constructor(t,n){k(this,"Point");k(this,"BASE");k(this,"ZERO");k(this,"randomBytes");k(this,"wnafPrecomputes",new WeakMap);k(this,"baseCanBeBlinded");k(this,"bits");Jt(t),this.randomBytes=po(n,fo),this.Point=t,this.BASE=t.BASE,this.ZERO=t.ZERO,this.bits=t.Fn.BITS}buildWnafTable(t,n,r){let o=Math.ceil(r/n)+1,s=2**(n-1),i=[],a=t;for(let c=0;c<o;c++){let f=a;for(let u=0;u<s;u++)i.push(f),f=f.add(a);a=i[i.length-1].double()}return{W:n,bits:r,windows:o,comp:i}}wnafCachedCT(t,n){let{W:r,windows:o,comp:s}=t,i=2**(r-1),a=wc(n,r,o),c=this.ZERO,f=this.BASE;for(let u=0;u<o;u++){let l=a[u],d=u*i,p=Math.abs(l)-1,h=s[d];for(let y=1;y<i;y++)h=y===p?s[d+y]:h;let g=h.negate();l===0?f=f.add(s[d]):c=c.add(l<0?g:h)}return{p:c,f}}getWnafPrecomputes(t,n,r,o){let s=this.wnafPrecomputes.get(n),i=s?.find(a=>a.W===t&&a.bits===r);return i||(i=this.buildWnafTable(n,t,r),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(n,s)),s.push(i)),i}assertPoint(t){if(!(t instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof t)}validateMulInput(t,n){if(this.assertPoint(t),!ro(n,Tn,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(t,n,r,o){let s=lo(t);return s===1?this.fixedWindowCT(t,n,r):this.wnafCachedCT(this.getWnafPrecomputes(s,t,r,o),n)}mulCT(t,n,r){return this.validateMulInput(t,n),this.runCT(t,n,this.bits,r)}mulCTBlinded(t,n,r){if(this.validateMulInput(t,n),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+Ui,s=this.randomBytes(fo);if(!Yt(s)||s.length!==fo)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let i=n+Pe(s)*this.Point.Fn.ORDER;return this.runCT(t,i,o,r)}fixedWindowCT(t,n,r){let o=lc,s=1<<o,i=En(o),a=new Array(s);a[0]=this.ZERO;for(let u=1;u<s;u++)a[u]=a[u-1].add(t);let c=Math.ceil(r/o),f=this.ZERO;for(let u=c-1;u>=0;u--){if(u!==c-1)for(let p=0;p<o;p++)f=f.double();let l=Number(n>>BigInt(u*o)&i),d=a[0];for(let p=1;p<s;p++)d=p===l?a[p]:d;f=f.add(d)}return{p:f,f}}shouldBlind(t,n){return this.randomBytes===void 0?!1:n===Tn?!0:t!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(t,n,r,o){return this.shouldBlind(t,r)?this.mulCTBlinded(t,n,o):this.mulCT(t,n,o)}mulUnsafe(t,n,r){if(this.assertPoint(t),!xt(n))throw new Error("invalid scalar");let o=lo(t);if(o===1||n>=this.Point.Fn.ORDER)return ir(this.Point,[t],[n],!0);let s=this.getWnafPrecomputes(o,t,this.bits,r);return this.wnafCachedCT(s,n).p}setWindowSize(t,n){this.assertPoint(t),uc(n,this.bits);let r=Math.ceil((this.bits+Ui)/n)+1;dc(r*2**(n-1),this.Point.Fp.BYTES),Hi.set(t,n),this.wnafPrecomputes.delete(t)}hasWindowSize(t){return lo(t)!==1}};function ir(e,t,n,r=!1){if(Jt(e),Ni(t,e),Xe(r,"allowOversized"),pc(n,e.Fn,r?e.Fn.ORDER**fc:void 0),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=t.map(i=>hc(i,4)),s=n.map(i=>gc(i,4));return yc(e.ZERO,o,s)}function Mi(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Xt(t),t}else return Qt(e,{isLE:n})}function Di(e,t,n={},r){if(e!=="weierstrass"&&e!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);qe(n);for(let c of["p","n","h"]){let f=t[c];if(!(xt(f)&&f!==uo))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Mi(t.p,n.Fp,r),s=Mi(t.n,n.Fn,r),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function sr(e,t){return function(r){let o=e(r);return{secretKey:o,publicKey:t(o)}}}var ar=class{constructor(t,n){k(this,"oHash");k(this,"iHash");k(this,"blockLen");k(this,"outputLen");k(this,"canXOF",!1);k(this,"finished",!1);k(this,"destroyed",!1);if(Wn(t),Ze(n,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?t.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),yt(o)}update(t){return Wt(this),this.iHash.update(t),this}digestInto(t){Wt(this),qn(t,this),this.finished=!0;let n=t.subarray(0,this.outputLen);this.iHash.digestInto(n),this.oHash.update(n),this.oHash.digestInto(n),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.canXOF=c,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Fi=(()=>{let e=((t,n,r)=>new ar(t,n).update(r).digest());return e.create=(t,n)=>new ar(t,n),e})();var bc=BigInt(0),ho=class extends Error{constructor(t=""){super(t)}},ot={Err:ho,_tlv:{encode:(e,t)=>{let{Err:n}=ot;if(Mt(e,"tag"),e<0||e>255)throw new n("tlv.encode: wrong tag");if(bi(t,"data"),t.length&1)throw new n("tlv.encode: unpadded data");let r=t.length/2,o=xn(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let s=r>127?xn(o.length/2|128):"";return xn(e)+s+o+t},decode(e,t){let{Err:n}=ot;t=q(t,void 0,"DER data");let r=0;if(e<0||e>255)throw new n("tlv.decode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");let o=t[r++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");let f=t.subarray(r,r+c);if(f.length!==c)throw new n("tlv.decode: length bytes not complete");if(f[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(let u of f)i=i<<8|u;if(r+=c,i<128)throw new n("tlv.decode(long): not minimal encoding")}let a=t.subarray(r,r+i);if(a.length!==i)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+i)}}},_int:{encode(e){let{Err:t}=ot;if(tr(e),e<bc)throw new t("integer: negative integers are not allowed");let n=xn(e);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){let{Err:t}=ot;if(e.length<1)throw new t("invalid signature integer: empty");if(e[0]&128)throw new t("invalid signature integer: negative");if(e.length>1&&e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Pe(e)}},toSig(e,t){let{Err:n,_int:r,_tlv:o}=ot;if(t!==void 0&&(Mt(t,"maxScalarBytes"),t<1))throw new n("invalid signature: maxScalarBytes must be positive");let s=q(e,void 0,"signature"),{v:i,l:a}=o.decode(48,s);if(a.length)throw new n("invalid signature: left bytes after parsing");let{v:c,l:f}=o.decode(2,i),{v:u,l}=o.decode(2,f);if(l.length)throw new n("invalid signature: left bytes after parsing");if(t!==void 0&&(c.length>t||u.length>t))throw new n("invalid signature: integer too large");return{r:r.decode(c),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:n}=ot;qe(e,{r:"bigint",s:"bigint"},{},"sig");let r=t.encode(2,n.encode(e.r)),o=t.encode(2,n.encode(e.s)),s=r+o;return t.encode(48,s)}},cr=(Object.freeze(ot._tlv),Object.freeze(ot._int),Object.freeze(ot));var ji=(e,t)=>(e+(e>=0?t:-t)/Ki)/t;function mc(e,t,n){oo("scalar",e,it,n);let[[r,o],[s,i]]=t,a=ji(i*e,n),c=ji(-o*e,n),f=e-a*r-c*s,u=-a*o-c*i,l=f<it,d=u<it;l&&(f=-f),d&&(u=-u);let p=En(Math.ceil(Zt(n)/2))+Ct;if(f<it||f>=p||u<it||u>=p)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:l,k1:f,k2neg:d,k2:u}}function yo(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function go(e,t){qe(e);let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return Xe(n.lowS,"lowS"),Xe(n.prehash,"prehash"),n.format!==void 0&&yo(n.format),n}var it=BigInt(0),Ct=BigInt(1),Ki=BigInt(2),wo=BigInt(3),xc=BigInt(4);function zi(e,t={}){let n=Di("weierstrass",e,t),r=n.Fp,o=n.Fn,s=n.CURVE,{h:i,n:a}=s;qe(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:f,clearCofactor:u,isTorsionFree:l,fromBytes:d,toBytes:p}=t,h=t.randomBytes===void 0?er:t.randomBytes;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let g=c?{beta:c.beta,basises:c.basises.map(v=>[...v])}:void 0,y=qi(r,o);function S(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function P(v,T,B){if(T.is0()){if(!f)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:I,y:H}=T.toAffine(),F=r.toBytes(I);if(Xe(B,"isCompressed"),B){S();let C=!r.isOdd(H);return Fe(Wi(C),F)}else return Fe(Uint8Array.of(4),F,r.toBytes(H))}function N(v){q(v,void 0,"Point");let{publicKey:T,publicKeyUncompressed:B}=y,I=v.length,H=v[0],F=v.subarray(1);if(f&&I===1&&H===0)return{x:r.ZERO,y:r.ZERO};if(I===T&&(H===2||H===3)){let C=r.fromBytes(F);if(!r.isValid(C))throw new Error("bad point: is not on curve, wrong x");let K=m(C),j;try{j=r.sqrt(K)}catch(ce){let ye=ce instanceof Error?": "+ce.message:"";throw new Error("bad point: is not on curve, sqrt error"+ye)}S();let ne=r.isOdd(j);return(H&1)===1!==ne&&(j=r.neg(j)),{x:C,y:j}}else if(I===B&&H===4){let C=r.BYTES,K=r.fromBytes(F.subarray(0,C)),j=r.fromBytes(F.subarray(C,C*2));if(!b(K,j))throw new Error("bad point: is not on curve");return{x:K,y:j}}else throw new Error(`bad point: got length ${I}, expected compressed=${T} or uncompressed=${B}`)}let O=p===void 0?P:p,D=d===void 0?N:d,L=r.mul(s.b,wo),w=r.is0(s.a)?v=>r.ZERO:v=>r.mul(s.a,v);function m(v){let T=r.sqr(v),B=r.mul(T,v);return r.add(r.add(B,r.mul(v,s.a)),s.b)}function b(v,T){let B=r.sqr(T),I=m(v);return r.eql(B,I)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let x=r.mul(r.pow(s.a,wo),xc),E=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(x,E)))throw new Error("bad curve params: a or b");function A(v,T,B=!1){if(!r.isValid(T)||B&&r.is0(T))throw new Error(`bad point coordinate ${v}`);return typeof T=="object"&&T!==null?r.create(T):T}function M(v){if(!(v instanceof _))throw new Error("Weierstrass Point expected")}function W(v){if(!g||!g.basises)throw new Error("no endo");return mc(v,g.basises,o.ORDER)}function G(v,T,B,I){if(!o.isValid(I))throw new RangeError("invalid scalar: out of range");if(g){let{k1neg:H,k1:F,k2neg:C,k2:K}=W(I),j=new _(r.mul(B.X,g.beta),B.Y,B.Z);v.push(H?B.negate():B,C?j.negate():j),T.push(F,K)}else v.push(B),T.push(I)}let ae=new WeakSet,U=class U{constructor(T,B,I){k(this,"X");k(this,"Y");k(this,"Z");this.X=A("x",T),this.Y=A("y",B,!0),this.Z=A("z",I),Object.freeze(this)}static CURVE(){return s}static fromAffine(T){let{x:B,y:I}=T||{};if(!T||!r.isValid(B)||!r.isValid(I))throw new Error("invalid affine point");if(T instanceof U)throw new Error("projective point not allowed");return r.is0(B)&&r.is0(I)?U.ZERO:new U(B,I,r.ONE)}static fromBytes(T){let B=U.fromAffine(D(q(T,void 0,"point")));return B.assertValidity(),B}static fromHex(T){return U.fromBytes(Jn(T))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(T=6,B=!0){return de.setWindowSize(this,T),B||this.multiply(wo),this}assertValidity(){let T=this;if(T.is0()){if(f&&r.is0(T.X)&&r.eql(T.Y,r.ONE)&&r.is0(T.Z))return;throw new Error("bad point: ZERO")}if(ae.has(T))return;let{x:B,y:I}=T.toAffine();if(!r.isValid(B)||!r.isValid(I))throw new Error("bad point: x or y not field elements");if(!b(B,I))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");ae.add(T)}hasEvenY(){let{y:T}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(T)}equals(T){M(T);let{X:B,Y:I,Z:H}=this,{X:F,Y:C,Z:K}=T,j=r.eql(r.mul(B,K),r.mul(F,H)),ne=r.eql(r.mul(I,K),r.mul(C,H));return j&&ne}negate(){return new U(this.X,r.neg(this.Y),this.Z)}double(){let{X:T,Y:B,Z:I}=this,H=r.ZERO,F=r.ZERO,C=r.ZERO,K=r.mul(T,T),j=r.mul(B,B),ne=r.mul(I,I),V=r.mul(T,B);return V=r.add(V,V),C=r.mul(T,I),C=r.add(C,C),H=w(C),F=r.mul(L,ne),F=r.add(H,F),H=r.sub(j,F),F=r.add(j,F),F=r.mul(H,F),H=r.mul(V,H),C=r.mul(L,C),ne=w(ne),V=r.sub(K,ne),V=w(V),V=r.add(V,C),C=r.add(K,K),K=r.add(C,K),K=r.add(K,ne),K=r.mul(K,V),F=r.add(F,K),ne=r.mul(B,I),ne=r.add(ne,ne),K=r.mul(ne,V),H=r.sub(H,K),C=r.mul(ne,j),C=r.add(C,C),C=r.add(C,C),new U(H,F,C)}add(T){M(T);let{X:B,Y:I,Z:H}=this,{X:F,Y:C,Z:K}=T,j=r.ZERO,ne=r.ZERO,V=r.ZERO,ce=r.mul(B,F),ye=r.mul(I,C),ve=r.mul(H,K),_e=r.add(B,I),fe=r.add(F,C);_e=r.mul(_e,fe),fe=r.add(ce,ye),_e=r.sub(_e,fe),fe=r.add(B,H);let Re=r.add(F,K);return fe=r.mul(fe,Re),Re=r.add(ce,ve),fe=r.sub(fe,Re),Re=r.add(I,H),j=r.add(C,K),Re=r.mul(Re,j),j=r.add(ye,ve),Re=r.sub(Re,j),V=w(fe),j=r.mul(L,ve),V=r.add(j,V),j=r.sub(ye,V),V=r.add(ye,V),ne=r.mul(j,V),ye=r.add(ce,ce),ye=r.add(ye,ce),ve=w(ve),fe=r.mul(L,fe),ye=r.add(ye,ve),ve=r.sub(ce,ve),ve=w(ve),fe=r.add(fe,ve),ce=r.mul(ye,fe),ne=r.add(ne,ce),ce=r.mul(Re,fe),j=r.mul(_e,j),j=r.sub(j,ce),ce=r.mul(_e,ye),V=r.mul(Re,V),V=r.add(V,ce),new U(j,ne,V)}subtract(T){return M(T),this.add(T.negate())}is0(){return this.equals(U.ZERO)}multiply(T){if(!o.isValidNot0(T))throw new RangeError("invalid scalar: out of range");let{p:B,f:I}=de.mulSecret(this,T,i,te);return te([B,I])[0]}multiplyUnsafe(T){let B=this,I=T;if(!o.isValid(I))throw new RangeError("invalid scalar: out of range");if(I===it||B.is0())return U.ZERO;if(I===Ct)return B;if(de.hasWindowSize(this))return de.mulUnsafe(B,I,te);let H=[],F=[];return G(H,F,B,I),ir(U,H,F)}mulAddUnsafe(T,B,I){M(B);let H=[],F=[];return G(H,F,this,T),G(H,F,B,I),ir(U,H,F)}toAffine(T){let B=this,I=T;if(I!=null&&!r.isValid(I))throw new RangeError('"invertedZ" expected valid field element');let{X:H,Y:F,Z:C}=B;if(r.eql(C,r.ONE))return{x:H,y:F};let K=B.is0();I==null&&(I=K?r.ONE:r.inv(C));let j=r.mul(H,I),ne=r.mul(F,I),V=r.mul(C,I);if(K)return{x:r.ZERO,y:r.ZERO};if(!r.eql(V,r.ONE))throw new Error("invZ was invalid");return{x:j,y:ne}}isTorsionFree(){return i===Ct?!0:l?l(U,this):de.mulUnsafe(this,a).is0()}clearCofactor(){return i===Ct?this:u?u(U,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Ct?this.is0():this.clearCofactor().is0()}toBytes(T=!0){return Xe(T,"isCompressed"),this.assertValidity(),O(U,this,T)}toHex(T=!0){return Jr(this.toBytes(T))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};k(U,"BASE",new U(s.Gx,s.Gy,r.ONE)),k(U,"ZERO",new U(r.ZERO,r.ONE,r.ZERO)),k(U,"Fp",r),k(U,"Fn",o);let _=U,te=v=>Ci(_,v),de=new or(_,h);return de.bits>=6&&_.BASE.precompute(6),Object.freeze(_.prototype),Object.freeze(_),_}function Wi(e){return Uint8Array.of(e?2:3)}function qi(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Ec(e,t={}){Jt(e);let{Fn:n}=e,r=t.randomBytes===void 0?er:t.randomBytes,o=Object.assign(qi(e.Fp,n),{seed:Math.max(rr(n.ORDER),16)});function s(p){try{let h=n.fromBytes(p);return n.isValidNot0(h)}catch{return!1}}function i(p,h){let{publicKey:g,publicKeyUncompressed:y}=o;try{let S=p.length;return h===!0&&S!==g||h===!1&&S!==y?!1:!e.fromBytes(p).is0()}catch{return!1}}function a(p){return p=p===void 0?r(o.seed):p,Sn(q(p,o.seed,"seed"),n.ORDER)}function c(p,h=!0){return e.BASE.multiply(n.fromBytes(p)).toBytes(h)}function f(p){let{secretKey:h,publicKey:g,publicKeyUncompressed:y}=o,S=n._lengths;if(!Yt(p))return;let P=q(p,void 0,"key").length,N=P===g||P===y,O=P===h||!!S?.includes(P);if(!(N&&O))return N}function u(p,h,g=!0){if(f(p)===!0)throw new Error("first arg must be private key");if(f(h)===!1)throw new Error("second arg must be public key");let y=n.fromBytes(p),S=e.fromBytes(h);if(S.is0())throw new Error("invalid public key: point at infinity");return S.multiply(y).toBytes(g)}let l={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=sr(a,c);return Object.freeze(l),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:e,utils:l,lengths:o})}function Vi(e,t,n={}){Jt(e);let r=t;Wn(r),qe(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},n),s=o.randomBytes===void 0?er:o.randomBytes,i=o.hmac===void 0?(U,v)=>Fi(r,U,v):o.hmac,{Fp:a,Fn:c}=e,{ORDER:f,BITS:u}=c,l=rr(f),d=po(s,l),{keygen:p,getPublicKey:h,getSharedSecret:g,utils:y,lengths:S}=Ec(e,o),P={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},N=f*Ki+Ct<a.ORDER;function O(U){let v=f>>Ct;return U>v}function D(U,v){if(!c.isValidNot0(v))throw new Error(`invalid signature ${U}: out of range 1..Point.Fn.ORDER`);return v}function L(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function w(U,v,T){return L(),(U===T?0:2)|Number(a.isOdd(v))}function m(){if(N)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function b(U,v){yo(v);let T=S.signature,B=v==="compact"?T:v==="recovered"?T+1:void 0;return q(U,B)}class x{constructor(v,T,B){k(this,"r");k(this,"s");k(this,"recovery");if(this.r=D("r",v),this.s=D("s",T),B!=null){if(m(),![0,1,2,3].includes(B))throw new Error("invalid recovery id");this.recovery=B}Object.freeze(this)}static fromBytes(v,T=P.format){b(v,T);let B;if(T==="der"){if(v.length>2*c.BYTES+16)throw new cr.Err("invalid signature: DER signature too long");let{r:C,s:K}=cr.toSig(q(v),c.BYTES+1);return new x(C,K)}T==="recovered"&&(B=v[0],T="compact",v=v.subarray(1));let I=S.signature/2,H=v.subarray(0,I),F=v.subarray(I,I*2);return new x(c.fromBytes(H),c.fromBytes(F),B)}static fromHex(v,T){return this.fromBytes(Jn(v),T)}assertRecovery(){let{recovery:v}=this;if(v==null)throw new Error("invalid recovery id: must be present");return v}addRecoveryBit(v){return new x(this.r,this.s,v)}recoverPublicKey(v){let{r:T,s:B}=this,I=this.assertRecovery(),H=I===2||I===3?T+f:T;if(!a.isValid(H))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let F=a.toBytes(H),C=e.fromBytes(Fe(Wi((I&1)===0),F)),K=c.inv(H),j=A(q(v,void 0,"msgHash")),ne=c.create(-j*K),V=c.create(B*K),ce=e.BASE.mulAddUnsafe(ne,C,V);if(ce.is0())throw new Error("invalid recovery: point at infinify");return ce.assertValidity(),ce}hasHighS(){return O(this.s)}toBytes(v=P.format){if(yo(v),v==="der")return Jn(cr.hexFromSig(this));let{r:T,s:B}=this,I=c.toBytes(T),H=c.toBytes(B);return v==="recovered"?(m(),Fe(Uint8Array.of(this.assertRecovery()),I,H)):Fe(I,H)}toHex(v){return Jr(this.toBytes(v))}}Object.freeze(x.prototype),Object.freeze(x);let E=o.bits2int===void 0?function(v){if(v.length>8192)throw new Error("input is too large");let T=Pe(v),B=v.length*8-u;return B>0?T>>BigInt(B):T}:o.bits2int,A=o.bits2int_modN===void 0?function(v){return c.create(E(v))}:o.bits2int_modN,M=En(u);function W(U){return oo("num < 2^"+u,U,it,M),c.toBytes(U)}function G(U,v){return q(U,void 0,"message"),v?q(r(U),void 0,"prehashed message"):U}function ae(U,v,T){let{lowS:B,prehash:I,extraEntropy:H}=go(T,P);U=G(U,I);let F=A(U),C=c.fromBytes(v);if(!c.isValidNot0(C))throw new Error("invalid private key");let K=[W(C),W(F)];if(H!=null&&H!==!1){let ce=H===!0?s(S.secretKey):H;K.push(q(ce,void 0,"extraEntropy"))}let j=Fe(...K),ne=F;function V(ce){let ye=E(ce);if(!c.isValidNot0(ye))return;let ve=e.BASE.multiply(ye).toAffine(),_e=c.create(ve.x);if(_e===it)return;let fe;if(d!==void 0){let gn=Pe(Sn(d(l),f)),Ua=c.inv(c.mul(gn,ye)),Ra=c.mul(gn,ne),Ma=c.mul(gn,C);fe=c.create(Ua*c.create(Ra+Ma*_e))}else{let gn=Oi(ye,f);fe=c.create(gn*c.create(ne+_e*C))}if(fe===it)return;let Re=w(ve.x,ve.y,_e),oi=fe;return B&&O(fe)&&(oi=c.neg(fe),Re^=1),new x(_e,oi,N?void 0:Re)}return{seed:j,k2sig:V}}function _(U,v,T={}){let{seed:B,k2sig:I}=ae(U,v,T);return Ei(r.outputLen,c.BYTES,i)(B,I).toBytes(T.format)}function te(U,v,T,B={}){let{lowS:I,prehash:H,format:F}=go(B,P);if(T=q(T,void 0,"publicKey"),v=G(v,H),!Yt(U)){let C=U instanceof x?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+C)}b(U,F);try{let C=x.fromBytes(U,F),K=e.fromBytes(T);if(K.is0()||I&&C.hasHighS())return!1;let{r:j,s:ne}=C,V=A(v),ce=c.inv(ne),ye=c.create(V*ce),ve=c.create(j*ce),_e=e.BASE.mulAddUnsafe(ye,K,ve);if(_e.is0())return!1;let fe=_e.toAffine();return!(c.create(fe.x)!==j||F==="recovered"&&C.recovery!==w(fe.x,fe.y,j))}catch{return!1}}function de(U,v,T={}){let{prehash:B}=go(T,P);return v=G(v,B),x.fromBytes(U,"recovered").recoverPublicKey(v).toBytes()}return Object.freeze({keygen:p,getPublicKey:h,getSharedSecret:g,utils:y,lengths:S,Point:e,sign:_,verify:te,recoverPublicKey:de,Signature:x,hash:r})}var lr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Sc={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Tc=BigInt(0),Yi=BigInt(2);function kc(e){let t=lr.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=e*e*e%t,u=f*f*e%t,l=Ne(u,n,t)*u%t,d=Ne(l,n,t)*u%t,p=Ne(d,Yi,t)*f%t,h=Ne(p,o,t)*p%t,g=Ne(h,s,t)*h%t,y=Ne(g,a,t)*g%t,S=Ne(y,c,t)*y%t,P=Ne(S,a,t)*g%t,N=Ne(P,n,t)*u%t,O=Ne(N,i,t)*h%t,D=Ne(O,r,t)*f%t,L=Ne(D,Yi,t);if(!tn.eql(tn.sqr(L),e))throw new Error("Cannot find square root");return L}var tn=Qt(lr.p,{sqrt:kc}),Nt=zi(lr,{Fp:tn,endo:Sc}),Ve=Vi(Nt,Vt),Gi=Object.create(null);function fr(e,...t){let n=Gi[e];if(n===void 0){let r=Vt(xi(e));n=Fe(r,r),Gi[e]=n}return Vt(Fe(n,...t))}var Xi=e=>e.toBytes(!0).slice(1),Qi=({x:e})=>tn.toBytes(e),ur=e=>!tn.isOdd(e);function Ji(e){let{Fn:t,BASE:n}=Nt,r=t.fromBytes(q(e,32,"secretKey")),s=n.multiply(r).toAffine();return{scalar:ur(s.y)?r:t.neg(r),bytes:Qi(s)}}function es(e){let t=tn;if(!t.isValidNot0(e))throw new Error("invalid x: Fail if x \u2265 p");let n=t.sqr(e),r=t.add(t.mulN(n,e),BigInt(7)),o=t.sqrt(r);ur(o)||(o=t.neg(o));let s=Nt.fromAffine({x:e,y:o});return s.assertValidity(),s}var en=Pe;function ts(...e){return Nt.Fn.create(en(fr("BIP0340/challenge",...e)))}function Zi(e){return Ji(e).bytes}function Bc(e,t,n=mn(32)){let{Fn:r,BASE:o}=Nt,s=no(q(e,void 0,"message")),{bytes:i,scalar:a}=Ji(t),c=q(n,32,"auxRand"),f=r.toBytes(a^en(fr("BIP0340/aux",c))),u=fr("BIP0340/nonce",f,i,s),l=r.create(en(u));if(l===Tc)throw new Error("sign failed: k is zero");let p=o.multiply(l).toAffine(),h=ur(p.y)?l:r.neg(l),g=Qi(p),y=ts(g,i,s),S=new Uint8Array(64);if(S.set(g,0),S.set(r.toBytes(r.create(h+y*a)),32),!ns(S,s,i))throw new Error("sign: Invalid signature produced");return S}function ns(e,t,n){let{Fp:r,Fn:o,BASE:s}=Nt,i=q(e,64,"signature"),a=q(t,void 0,"message"),c=q(n,32,"publicKey");try{let f=es(en(c)),u=i.subarray(0,32),l=en(u);if(!r.isValidNot0(l))return!1;let d=en(i.subarray(32,64));if(!o.isValidNot0(d))return!1;let p=ts(u,Xi(f),a),h=s.mulAddUnsafe(d,f,o.neg(p)),{x:g,y}=h.toAffine();return!(h.is0()||!ur(y)||!r.eql(g,l))}catch{return!1}}var St=(()=>{let n=r=>(r=r===void 0?mn(48):r,Sn(q(r,48,"seed"),lr.n));return Object.freeze({keygen:sr(n,Zi),getPublicKey:Zi,sign:Bc,verify:ns,Point:Nt,utils:Object.freeze({randomSecretKey:n,taggedHash:fr,lift_x:es,pointToBytes:Xi}),lengths:Object.freeze({secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48})})})();var vc=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),os=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),Pc=os.map(e=>(9*e+5)%16),is=(()=>{let n=[[os],[Pc]];for(let r=0;r<4;r++)for(let o of n)o.push(o[r].map(s=>vc[s]));return n})(),ss=is[0],as=is[1],cs=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>Uint8Array.from(e)),Ac=ss.map((e,t)=>e.map(n=>cs[t][n])),$c=as.map((e,t)=>e.map(n=>cs[t][n])),Oc=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Ic=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function rs(e,t,n,r){return e===0?t^n^r:e===1?t&n|~t&r:e===2?(t|~n)^r:e===3?t&r|n&~r:t^(n|~r)}var dr=new Uint32Array(16),bo=class extends qt{constructor(){super(64,20,8,!0);k(this,"h0",1732584193);k(this,"h1",-271733879);k(this,"h2",-1732584194);k(this,"h3",271733878);k(this,"h4",-1009589776)}get(){let{h0:n,h1:r,h2:o,h3:s,h4:i}=this;return[n,r,o,s,i]}set(n,r,o,s,i){this.h0=n|0,this.h1=r|0,this.h2=o|0,this.h3=s|0,this.h4=i|0}_cloneInto(n){return(n||(n=new this.constructor)).set(...this.get()),this._cloneIntoMeta(n)}process(n,r){for(let h=0;h<16;h++,r+=4)dr[h]=n.getUint32(r,!0);let o=this.h0|0,s=o,i=this.h1|0,a=i,c=this.h2|0,f=c,u=this.h3|0,l=u,d=this.h4|0,p=d;for(let h=0;h<5;h++){let g=4-h,y=Oc[h],S=Ic[h],P=ss[h],N=as[h],O=Ac[h],D=$c[h];for(let L=0;L<16;L++){let w=bn(o+rs(h,i,c,u)+dr[P[L]]+y,O[L])+d|0;o=d,d=u,u=bn(c,10)|0,c=i,i=w}for(let L=0;L<16;L++){let w=bn(s+rs(g,a,f,l)+dr[N[L]]+S,D[L])+p|0;s=p,p=l,l=bn(f,10)|0,f=a,a=w}}this.set(this.h1+c+l|0,this.h2+u+p|0,this.h3+d+s|0,this.h4+o+a|0,this.h0+i+f|0)}roundClean(){yt(dr)}destroy(){this.destroyed=!0,yt(this.buffer),this.set(0,0,0,0,0)}},fs=Zn(()=>new bo);var Ht=e=>Object.freeze(e());function ms(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Qe(e){if(!ms(e))throw new TypeError("Uint8Array expected")}function Lc(e,t){return Array.isArray(t)?t.length===0?!0:e?t.every(n=>typeof n=="string"):t.every(n=>Number.isSafeInteger(n)):!1}function hr(e){if(typeof e!="function")throw new TypeError("function expected");return!0}function Tt(e,t){if(typeof t!="string")throw new TypeError(`${e}: string expected`);return!0}function pr(e,t="number"){if(typeof e!="number")throw new TypeError(`${t}: expected number, got ${typeof e}`);if(!Number.isSafeInteger(e))throw new RangeError(`${t}: expected safe integer, got ${e}`)}function ls(e,t){if(!Lc(!1,t))throw new TypeError(`${e}: array of numbers expected`)}function xs(...e){let t=s=>s,n=(s,i)=>a=>s(i(a)),r=e.map(s=>s.encode).reduceRight(n,t),o=e.map(s=>s.decode).reduce(n,t);return{encode:r,decode:o}}function _c(e){return hr(e),{encode:t=>t,decode:t=>e(t)}}var Uc=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function us(e,t=e.length){let n=new Array(t);for(let r=0;r<t;r++)n[r]=e[r];return n}var ds=(()=>{try{let e=new TextDecoder;return e.decode(Uint8Array.of(65,48,43,127))==="A0+\x7F"?e:void 0}catch{return}})(),mo=8192;function Rc(e){let t=e.length;if(ds!==void 0&&t>=12)return ds.decode(e);if(t<=mo)return String.fromCharCode.apply(null,e);let n="";for(let r=0;r<t;r+=mo)n+=String.fromCharCode.apply(null,e.subarray(r,r+mo));return n}function Es(e){if(pr(e),e<=0||e>8)throw new RangeError("radix2: bits should be in (0..8]");let t=Uc[e]-1;return{encode:n=>{Qe(n);let r=n.length,o=new Uint8Array(Math.ceil(r*8/e)),s=0,i=0,a=0;for(let c=0;c<r;)for(c+2<r?(s=s<<24|n[c]<<16|n[c+1]<<8|n[c+2],i+=24,c+=3):(s=(s<<8|n[c])&65535,i+=8,c++);i-=e,o[a++]=s>>i&t,!(i<e););return i>0&&(o[a]=s<<e-i&t),o},decode:n=>{let r=n.length,o=new Uint8Array(Math.floor(r*e/8)),s=0,i=0,a=0;for(let c=0;c<r;c++)for(s=(s<<e|n[c])&65535,i+=e;i>=8;i-=8)o[a++]=s>>i-8&255;if(s=s<<8-i&255,i>=e)throw new Error("Excess padding");if(s>0)throw new Error(`Non-zero padding: ${s}`);return o}}}function Eo(e,t){let n=e.length;if(n>128)throw new Error("alphabet: max 128 letters");let r=new Uint8Array(n),o=new Int8Array(128).fill(-1);for(let s=0;s<n;s++){let i=e.charCodeAt(s);if(e.codePointAt(s)!==i||i>127)throw new Error("alphabet: single-char ASCII letters only");r[s]=i,o[i]=s}if(t!==void 0)for(let s of Object.keys(t)){let i=s.charCodeAt(0),a=o[t[s].charCodeAt(0)];if(s.length!==1||i>127||a===void 0||a===-1)throw new Error(`alphabet: invalid alias ${s}`);o[i]=a}return{encode:s=>{let i=new Uint8Array(s.length);for(let a=0;a<s.length;a++){let c=s[a],f=r[c];if(f===void 0)throw new Error(`alphabet.encode: invalid digit ${c}`);i[a]=f}return Rc(i)},decode:s=>{Tt("decode",s);let i=s.length,a=new Uint8Array(i);for(let c=0;c<i;c++){let f=s.charCodeAt(c),u=f<128?o[f]:-1;if(u===-1)throw new Error(`Unknown letter "${s[c]}". Allowed: ${e}`);a[c]=u}return a}}}function ps(e){return hr(e),function(...t){try{return e.apply(null,t)}catch{}}}function Mc(e,t){if(pr(e),e<=0)throw new RangeError(`checksum length must be positive: ${e}`);hr(t);let n=t;return{encode(r){Qe(r);let o=n(r).slice(0,e),s=new Uint8Array(r.length+e);return s.set(r),s.set(o,r.length),s},decode(r){Qe(r);let o=r.slice(0,-e),s=r.slice(-e),i=n(o).slice(0,e);for(let a=0;a<e;a++)if(i[a]!==s[a])throw new Error("Invalid checksum");return o}}}var Cc=656356768;var hs=65536,Nc=2048,Hc=4096,Dc=(e,t)=>({encode:n=>{Qe(n);let r=n.length;if(r===0)return new Uint8Array(0);if(r>=hs)throw new Error("invalid length");let o=0;for(;o<r-1&&n[o]===0;)o++;let s=Math.ceil(r/2),i=new Uint16Array(s),a=r&1;a&&(i[0]=n[0]);for(let h=a,g=a;h<r;h+=2,g++)i[g]=n[h]<<8|n[h+1];let c=[],f=0;for(;f<s;){let h=0;for(let g=f;g<s;g++){let y=h*65536+i[g],S=Math.floor(y/t);h=y-S*t,i[g]=S,S===0&&g===f&&f++}c.push(h)}let u=c.length-1,l=u*5;for(let h=c[u];l++,!(h<e);h=Math.floor(h/e));let d=new Uint8Array(o+l),p=d.length-1;for(let h=0;h<u;h++){let g=c[h];for(let y=0;y<5;y++)d[p--]=g%e,g=Math.floor(g/e)}for(let h=c[u];p>=o;h=Math.floor(h/e))d[p--]=h%e;return d},decode:n=>{Qe(n);let r=n.length;if(r===0)return new Uint8Array(0);if(r>=hs)throw new Error("invalid length");let o=0;for(;o<r-1&&n[o]===0;)o++;let s=new Uint16Array(Math.ceil(r*6/16)+1),i=0,a=0,c=r%5||5;for(;a<r;){let d=0,p=1;for(let g=a+c;a<g;a++){let y=n[a];if(y>=e)throw new Error(`invalid integer: ${y}`);d=d*e+y,p*=e}c=5;let h=d;for(let g=0;g<i;g++){let y=s[g]*p+h;h=Math.floor(y/65536),s[g]=y-h*65536}for(;h>0;h=Math.floor(h/65536))s[i++]=h%65536}let f=i===0?1:i*2-(s[i-1]<256?1:0),u=new Uint8Array(o+f),l=u.length-1;for(let d=0;d<i;d++){let p=s[d];u[l--]=p&255,l>=o&&(u[l--]=p>>8)}return u}}),Fc=(e,t)=>{let n=Eo(t);return{encode(r){if(Qe(r),r.length>Nc)throw new Error("invalid length");return n.encode(e.encode(r))},decode(r){if(Tt("baseN.decode",r),r.length>Hc)throw new Error("invalid length");return e.decode(n.decode(r))}}},jc=Dc(58,Cc);var Kc=e=>Fc(jc,e),zc=Ht(()=>Kc("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"));var Ss=e=>{hr(e);let t=e;return xs(Mc(4,n=>t(t(n))),zc)};var xo=Eo("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Wc=/^[\x21-\x60\x7b-\x7e]+$/;function gs(e,t){for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r<33||r>126)throw new Error(`${e}: printable ASCII expected`)}}function qc(e){let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++){let o=e[r];if(o<0||o>=32)throw new Error(`alphabet.encode: invalid digit ${o}`);n[r]=o}return n}var ws=[996825010,642813549,513874426,1027748829,705979059];function kn(e){let t=e>>25,n=(e&33554431)<<5;for(let r=0;r<ws.length;r++)(t>>r&1)===1&&(n^=ws[r]);return n}function ys(e,t,n=1){let r=e.length,o=1;for(let i=0;i<r;i++){let a=e.charCodeAt(i);if(a<33||a>126)throw new Error(`Invalid prefix (${e})`);o=kn(o)^a>>5}o=kn(o);for(let i=0;i<r;i++)o=kn(o)^e.charCodeAt(i)&31;for(let i of t)o=kn(o)^i;for(let i=0;i<6;i++)o=kn(o);o^=n;let s=new Uint8Array(6);for(let i=0;i<6;i++)s[i]=o>>>5*(5-i)&31;return xo.encode(s)}function Ts(e){let t=e==="bech32"?1:734539939,n=Es(5),r=l=>{Qe(l);let d=l.length,p=new Array(Math.ceil(d*8/5)),h=0,g=0,y=0;for(let S=0;S<d;S++)for(h=h<<8|l[S],g+=8;g>=5;g-=5)p[y++]=h>>g-5&31;return g>0&&(p[y]=h<<5-g&31),p},o=l=>{ls("radix2.decode",l);let d=l.length,p=new Uint8Array(d);for(let h=0;h<d;h++){let g=l[h];if(g<0||g>=32)throw new Error(`convertRadix2: invalid word=${g}`);p[h]=g}return n.decode(p)},s=ps(o);function i(l,d,p=90){Tt("bech32.encode prefix",l),p!==!1&&pr(p,"limit"),ms(d)&&(d=us(d)),ls("bech32.encode",d);let h=l.length;if(h===0)throw new TypeError(`Invalid prefix length ${h}`);let g=h+7+d.length;if(p!==!1&&g>p)throw new TypeError(`Length ${g} exceeds limit ${p}`);gs("bech32.encode prefix",l);let y=l.toLowerCase(),S=ys(y,d,t);return`${y}1${xo.encode(qc(d))}${S}`}function a(l,d=90){Tt("bech32.decode input",l),d!==!1&&pr(d,"limit");let p=l.length;if(p<8||d!==!1&&p>d)throw new TypeError(`invalid string length ${p}, expected (8..${d})`);let h=l.toLowerCase();if(l!==h&&!Wc.test(l))throw gs("bech32.decode input",l),new Error("mixed-case string not allowed");let g=h.lastIndexOf("1");if(g===0||g===-1)throw new Error('invalid separator "1"');let y=h.slice(0,g),S=h.slice(g+1);if(S.length<6)throw new Error("invalid data length");let P=xo.decode(S),N=us(P,P.length-6),O=ys(y,N,t);if(!S.endsWith(O))throw new Error(`Invalid checksum in ${l}`);return{prefix:y,words:N}}let c=ps(a);function f(l,d=90){let{prefix:p,words:h}=a(l,d);return{prefix:p,words:h,bytes:o(h)}}function u(l,d){return i(l,r(d))}return{encode:i,decode:a,encodeFromBytes:u,decodeToBytes:f,decodeUnsafe:c,fromWords:o,fromWordsUnsafe:s,toWords:r}}var gr=Ht(()=>Ts("bech32")),So=Ht(()=>Ts("bech32m"));var Vc=e=>{try{return encodeURI(e)!==null}catch{return!1}},ks=typeof"".isWellFormed=="function"?e=>e.isWellFormed():Vc,nn=e=>new TypeError(`invalid utf8 at byte ${e}`),bs=Ht(()=>({encode(e){Qe(e);let t="";for(let n=0;n<e.length;){let r=e[n++];if(r<128){t+=String.fromCharCode(r);continue}if(r<194||n>=e.length)throw nn(n-1);let o=e[n++];if((o&192)!==128)throw nn(n-1);let s=(r&31)<<6|o&63;if(r>=224){if(n>=e.length)throw nn(n-1);let i=e[n++];if((i&192)!==128||r===224&&o<160||r===237&&o>=160)throw nn(n-1);if(s=(r&15)<<12|(o&63)<<6|i&63,r>=240){if(n>=e.length)throw nn(n-1);let a=e[n++];if(r>244||(a&192)!==128||r===240&&o<144||r===244&&o>=144)throw nn(n-1);s=(r&7)<<18|(o&63)<<12|(i&63)<<6|a&63}}s<65536?t+=String.fromCharCode(s):(s-=65536,t+=String.fromCharCode((s>>10)+55296,(s&1023)+56320))}return t},decode(e){if(Tt("utf8",e),!ks(e))throw new TypeError("utf8 expected well-formed string");let t=new Uint8Array(e.length*3),n=0;for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);if(o<128){t[n++]=o;continue}if(o>=55296&&o<=57343){let s=e.charCodeAt(++r);o=65536+(o-55296<<10)+s-56320}o>=65536?(t[n++]=o>>18|240,t[n++]=o>>12&63|128):o>=2048?t[n++]=o>>12|224:t[n++]=o>>6|192,o>=2048&&(t[n++]=o>>6&63|128),t[n++]=o&63|128}return t.subarray(0,n)}})),Bs=Ht(()=>{let e,t,n={encode(r){return Qe(r),(t||(t=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}))).decode(r)},decode(r){if(Tt("utf8",r),!ks(r))throw new TypeError("utf8 expected well-formed string");return(e||(e=new TextEncoder)).encode(r)}};return{encode:typeof TextDecoder=="function"?n.encode:bs.encode,decode:typeof TextEncoder=="function"?n.decode:bs.decode}}),Yc=Ht(()=>xs(Es(4),Eo("0123456789abcdef",{A:"a",B:"b",C:"c",D:"d",E:"e",F:"f"}),_c(e=>{if(Tt("hex",e),e.length%2!==0)throw new TypeError(`hex.decode: odd-length string (${e.length})`);return e})));var Gc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Zc={encode(e){return Qe(e),e.toHex()},decode(e){return Tt("hex",e),Uint8Array.fromHex(e)}},X=Ht(()=>Gc?Zc:Yc);var pe=Uint8Array.of(),Ps=Uint8Array.of(0),Xc=new Set(["__proto__","constructor","prototype"]),To=(e,t)=>{if(typeof e!="string")throw new Error(`${t} should be string, got ${typeof e}`);if(e.includes(".."))throw new TypeError(`${t} ${e} cannot contain path parent ..`);if(e.includes("/"))throw new TypeError(`${t} ${e} cannot contain path separator /`);if(Xc.has(e))throw new Error(`${t} ${e} is reserved`)};function Bn(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function As(e){if(e.length===1){let n=e[0];return(r,o=0)=>{let s=r.indexOf(n,o);return s===-1?void 0:s}}let t=new Uint32Array(e.length);for(let n=1,r=0;n<e.length;n++){for(;r&&e[n]!==e[r];)r=t[r-1];e[n]===e[r]&&(t[n]=++r)}return(n,r=0)=>{for(let o=r,s=0;o<n.length;o++){for(;s&&n[o]!==e[s];)s=t[s-1];if(n[o]===e[s]&&++s===e.length)return o-e.length+1}}}var Qc=(e,t,n=0)=>As(e)(t,n);function $s(e,t){let n=be(e),r=be(t);return n||r?n&&r&&Bn(e,t):e===t}function be(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Jc(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];if(!be(o))throw new Error("Uint8Array expected");t+=o.length}let n=new Uint8Array(t);for(let r=0,o=0;r<e.length;r++){let s=e[r];n.set(s,o),o+=s.length}return n}var Po=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),Dt=BigInt(0),ko=BigInt(1),yr=BigInt(2),rn=BigInt(8),vs=BigInt(10),ef=BigInt(255);function kt(e){return Object.prototype.toString.call(e)==="[object Object]"}function ie(e){return Number.isSafeInteger(e)}var tf=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),vn=Object.freeze({equalBytes:Bn,isBytes:be,isCoder:He,checkBounds:Is,concatBytes:Jc,createView:Po,isPlainObject:kt}),Os=e=>{if(e!==null&&typeof e!="string"&&!He(e)&&!be(e)&&!ie(e))throw new TypeError(`lengthCoder: expected null | number | Uint8Array | CoderType, got ${e} (${typeof e})`);if(typeof e=="number"&&e<0)throw new Error(`lengthCoder: wrong length=${e}`);if(be(e)&&!e.length)throw new Error("lengthCoder: empty terminator");return{encodeStream(t,n){if(e===null)return;if(He(e))return e.encodeStream(t,n);let r;if(typeof e=="number"?r=e:typeof e=="string"&&(r=st.resolve(t.stack,e)),typeof r=="bigint"&&(r=Number(r)),!ie(r)||r<0||r!==n)throw t.err(`Wrong length: ${r} len=${e} exp=${n} (${typeof n})`)},decodeStream(t){let n;if(He(e)?n=e.decodeStream(t):typeof e=="number"?n=e:typeof e=="string"&&(n=st.resolve(t.stack,e)),typeof n=="bigint")n=Number(n);else if(typeof n!="number")throw t.err(`Wrong length: ${n}`);if(!ie(n)||n<0)throw t.err(`Wrong length: ${n}`);return n}}},Te=Object.freeze({BITS:32,FULL_MASK:-1>>>0,len:e=>{if(!ie(e)||e<0)throw new Error(`wrong len=${e}`);return Math.ceil(e/32)},create:e=>new Uint32Array(Te.len(e)),clean:e=>e.fill(0),debug:e=>Array.from(e).map(t=>(t>>>0).toString(2).padStart(32,"0")),checkLen:(e,t)=>{if(Te.len(t)!==e.length)throw new Error(`wrong length=${e.length}. Expected: ${Te.len(t)}`)},chunkLen:(e,t,n)=>{if(!ie(e)||e<0)throw new Error(`wrong bsLen=${e}`);if(!ie(t)||t<0)throw new Error(`wrong pos=${t}`);if(!ie(n)||n<0)throw new Error(`wrong len=${n}`);if(t>e-n)throw new Error(`wrong range=${t}/${n} of ${e}`)},set:(e,t,n,r=!0)=>!ie(t)||t<0||t>=e.length||!r&&(e[t]&n)!==0?!1:(e[t]|=n,!0),pos:(e,t)=>({chunk:Math.floor((e+t)/32),mask:1<<32-(e+t)%32-1}),indices:(e,t,n=!1)=>{Te.checkLen(e,t);let{FULL_MASK:r,BITS:o}=Te,s=o-t%o,i=s?r>>>s<<s:r,a=[];for(let c=0;c<e.length;c++){let f=e[c];if(n&&(f=~f),c===e.length-1&&(f&=i),f!==0)for(let u=0;u<o;u++){let l=1<<o-u-1;f&l&&a.push(c*o+u)}}return a},range:e=>{let t=[],n;for(let r of e)n===void 0||r!==n.pos+n.length?t.push(n={pos:r,length:1}):n.length+=1;return t},rangeDebug:(e,t,n=!1)=>`[${Te.range(Te.indices(e,t,n)).map(r=>`(${r.pos}/${r.length})`).join(", ")}]`,setRange:(e,t,n,r,o=!0)=>{if(Te.chunkLen(t,n,r),r===0)return!0;let{FULL_MASK:s,BITS:i}=Te,a=n%i?Math.floor(n/i):void 0,c=n+r,f=c%i?Math.floor(c/i):void 0,u=(p,h)=>p>=0&&p<e.length&&(e[p]&h)===0;if(!o)if(a!==void 0&&a===f){if(!u(a,s>>>i-r<<i-r-n))return!1}else{if(a!==void 0&&!u(a,s>>>n%i))return!1;let p=a!==void 0?a+1:n/i,h=f!==void 0?f:c/i;for(let g=p;g<h;g++)if(!u(g,s))return!1;if(f!==void 0&&a!==f&&!u(f,s<<i-c%i))return!1}if(a!==void 0&&a===f)return Te.set(e,a,s>>>i-r<<i-r-n,o);if(a!==void 0&&!Te.set(e,a,s>>>n%i,o))return!1;let l=a!==void 0?a+1:n/i,d=f!==void 0?f:c/i;for(let p=l;p<d;p++)if(!Te.set(e,p,s,o))return!1;return!(f!==void 0&&a!==f&&!Te.set(e,f,s<<i-c%i,o))}}),st=Object.freeze({pushObj:(e,t,n)=>{e.push({obj:t}),n(),e.pop()},path:e=>{let t=[];for(let n of e)n.field!==void 0&&t.push(n.field===""?'""':`${n.field}`);return t.join("/")},err:(e,t,n)=>{let r=`${e}(${st.path(t)}): ${typeof n=="string"?n:n.message}`,o=n instanceof TypeError?new TypeError(r):n instanceof RangeError?new RangeError(r):new Error(r);if(n instanceof Error&&n.stack){let s=`${n.name}: ${n.message}`,i=`${o.name}: ${o.message}`;o.stack=n.stack.startsWith(s)?`${i}${n.stack.slice(s.length)}`:n.stack}return o},resolve:(e,t)=>{let n=t.split("/"),r=e.map(i=>i.obj),o=0;for(;o<n.length&&n[o]==="..";o++)r.pop();let s=r.pop();for(;o<n.length;o++){if(!s||s[n[o]]===void 0)return;s=s[n[o]]}return s}}),Bo=class e{constructor(t,n={},r=[],o=void 0,s=0){k(this,"pos",0);k(this,"data");k(this,"opts");k(this,"stack");k(this,"parent");k(this,"parentOffset");k(this,"bitBuf",0);k(this,"bitPos",0);k(this,"bs");k(this,"view");if(!be(t))throw new TypeError(`Reader: expected Uint8Array, got ${typeof t}`);if(!kt(n))throw new TypeError(`ReaderOpts: expected plain object, got ${n}`);if(n.allowUnreadBytes!==void 0&&typeof n.allowUnreadBytes!="boolean")throw new TypeError(`ReaderOpts.allowUnreadBytes: expected boolean, got ${typeof n.allowUnreadBytes}`);if(n.allowMultipleReads!==void 0&&typeof n.allowMultipleReads!="boolean")throw new TypeError(`ReaderOpts.allowMultipleReads: expected boolean, got ${typeof n.allowMultipleReads}`);this.data=t,this.opts=n,this.stack=r,this.parent=o,this.parentOffset=s,this.view=Po(t)}_enablePointers(){if(this.parent)return this.parent._enablePointers();this.bs||(this.bs=Te.create(this.data.length),Te.setRange(this.bs,this.data.length,0,this.pos,this.opts.allowMultipleReads))}markBytesBS(t,n){return this.parent?this.parent.markBytesBS(this.parentOffset+t,n):!n||!this.bs?!0:Te.setRange(this.bs,this.data.length,t,n,!1)}markBytes(t){let n=this.pos,r=this.markBytesBS(n,t);if(!this.opts.allowMultipleReads&&!r)throw this.err(`multiple read pos=${n} len=${t}`);return this.pos+=t,r}pushObj(t,n){return st.pushObj(this.stack,t,n)}enterField(t){let n=this.stack[this.stack.length-1];if(n===void 0||n.field!==void 0)throw this.err(`enterField: invalid stack state, field=${t}`);n.field=t}exitField(){this.stack[this.stack.length-1].field=void 0}readView(t,n){if(!ie(t)||t<0)throw this.err(`readView: wrong length=${t}`);if(this.pos+t>this.data.length)throw this.err("readView: Unexpected end of buffer");let r=n(this.view,this.pos);return this.markBytes(t),r}absBytes(t){if(!ie(t)||t<0||t>this.data.length)throw new Error("Unexpected end of buffer");return this.data.subarray(t)}finish(){if(!this.opts.allowUnreadBytes){if(this.bitPos)throw this.err(`${this.bitPos} bits left after unpack: ${X.encode(this.data.subarray(this.pos))}`);if(this.bs&&!this.parent){let t=Te.indices(this.bs,this.data.length,!0);if(t.length){let n=Te.range(t).map(({pos:r,length:o})=>`(${r}/${o})[${X.encode(this.data.subarray(r,r+o))}]`).join(", ");throw this.err(`unread byte ranges: ${n} (total=${this.data.length})`)}else return}if(!this.isEnd())throw this.err(`${this.leftBytes} bytes ${this.bitPos} bits left after unpack: ${X.encode(this.data.subarray(this.pos))}`)}}err(t){return st.err("Reader",this.stack,t)}offsetReader(t){if(!ie(t)||t<0||t>this.data.length)throw this.err("offsetReader: Unexpected end of buffer");return new e(this.absBytes(t),this.opts,this.stack,this,t)}bytes(t,n=!1){if(this.bitPos)throw this.err("readBytes: bitPos not empty");if(!ie(t)||t<0)throw this.err(`readBytes: wrong length=${t}`);if(this.pos+t>this.data.length)throw this.err("readBytes: Unexpected end of buffer");let r=this.data.subarray(this.pos,this.pos+t);return n||this.markBytes(t),r}byte(t=!1){if(this.bitPos)throw this.err("readByte: bitPos not empty");if(this.pos+1>this.data.length)throw this.err("readByte: Unexpected end of buffer");let n=this.data[this.pos];return t||this.markBytes(1),n}get leftBytes(){return this.data.length-this.pos}get totalBytes(){return this.data.length}isEnd(){return this.pos>=this.data.length&&!this.bitPos}progress(){return this.pos*8-this.bitPos}bits(t){if(!ie(t)||t<0)throw this.err(`BitReader: wrong length=${t}`);if(t>32)throw this.err("BitReader: cannot read more than 32 bits in single call");let n=0;for(;t;){this.bitPos||(this.bitBuf=this.byte(),this.bitPos=8);let r=Math.min(t,this.bitPos);this.bitPos-=r,n=n<<r|this.bitBuf>>this.bitPos&2**r-1,this.bitBuf&=2**this.bitPos-1,t-=r}return n>>>0}find(t,n=this.pos){if(!be(t))throw this.err(`find: needle is not bytes! ${t}`);if(this.bitPos)throw this.err("find: bitPos not empty");if(!t.length)throw this.err("find: needle is empty");if(!ie(n)||n<0)throw this.err(`find: wrong pos=${n}`);return Qc(t,this.data,n)}},vo=class{constructor(t=[]){k(this,"pos",0);k(this,"stack");k(this,"buffers",[]);k(this,"chunks",[]);k(this,"chunk");k(this,"chunkView");k(this,"chunkPos",0);k(this,"run");k(this,"nextChunkSize",0);k(this,"ptrs",[]);k(this,"bitBuf",0);k(this,"bitPos",0);k(this,"finished",!1);this.stack=t}carve(t){if(this.chunk===void 0||this.chunk.length-this.chunkPos<t){let r=Math.max(t,this.nextChunkSize,64);this.nextChunkSize=Math.min(r*8,4096),this.chunk=new Uint8Array(r),this.chunkView=void 0,this.chunkPos=0,this.run=void 0,this.chunks.push(this.chunk)}let n=this.chunkPos;return this.run===void 0?(this.run={chunk:this.chunk,start:n,end:n+t},this.buffers.push(this.run)):this.run.end+=t,this.chunkPos=n+t,this.pos+=t,n}pushObj(t,n){return st.pushObj(this.stack,t,n)}enterField(t){let n=this.stack[this.stack.length-1];if(n===void 0||n.field!==void 0)throw this.err(`enterField: invalid stack state, field=${t}`);n.field=t}exitField(){this.stack[this.stack.length-1].field=void 0}writeView(t,n){if(this.finished)throw this.err("buffer: finished");if(!ie(t)||t<0||t>8)throw new Error(`wrong writeView length=${t}`);if(this.bitPos)throw this.err("writeBytes: ends with non-empty bit buffer");let r=this.carve(t);this.chunkView===void 0&&(this.chunkView=Po(this.chunk)),n(this.chunkView,r)}err(t){return st.err("Writer",this.stack,t)}bytes(t){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeBytes: ends with non-empty bit buffer");if(!be(t))throw this.err(`writeBytes: expected Uint8Array, got ${typeof t}`);this.buffers.push(t),this.run=void 0,this.pos+=t.length}byte(t){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeByte: ends with non-empty bit buffer");if(!ie(t)||t<0||t>255)throw this.err(`writeByte: wrong value=${t}`);let n=this.carve(1);this.chunk[n]=t}finish(t=!0){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("buffer: ends with non-empty bit buffer");let n=this.buffers,r=0;for(let i=0;i<n.length;i++){let a=n[i];r+=be(a)?a.length:a.end-a.start}for(let i=0;i<this.ptrs.length;i++)r+=this.ptrs[i].buffer.length;let o=new Uint8Array(r),s=0;for(let i=0;i<n.length;i++){let a=n[i];be(a)?(o.set(a,s),s+=a.length):(o.set(a.chunk.subarray(a.start,a.end),s),s+=a.end-a.start)}for(let i=0;i<this.ptrs.length;i++)o.set(this.ptrs[i].buffer,s),s+=this.ptrs[i].buffer.length;for(let i=this.pos,a=0;a<this.ptrs.length;a++){let c=this.ptrs[a];o.set(c.ptr.encode(i),c.pos),i+=c.buffer.length}if(t){for(let i of this.chunks)i.fill(0);this.chunks=[],this.chunk=void 0,this.chunkView=void 0,this.chunkPos=0,this.run=void 0,this.buffers=[];for(let i of this.ptrs)i.buffer.fill(0);this.ptrs=[],this.finished=!0,this.bitBuf=0}return o}bits(t,n){if(this.finished)throw this.err("buffer: finished");if(!ie(n)||n<0)throw this.err(`writeBits: wrong length=${n}`);if(n>32)throw this.err("writeBits: cannot write more than 32 bits in single call");if(!ie(t)||t<0)throw this.err(`writeBits: wrong value=${t}`);if(t>=2**n)throw this.err(`writeBits: value (${t}) >= 2**bits (${n})`);for(;n;){let r=Math.min(n,8-this.bitPos);if(this.bitBuf=this.bitBuf<<r|t>>n-r,this.bitPos+=r,n-=r,t&=2**n-1,this.bitPos===8){this.bitPos=0;let o=this.carve(1);this.chunk[o]=this.bitBuf}}}},wr=e=>Uint8Array.from(e).reverse();function nf(e,t,n,r){if(!e.length)return;let o=t?wr(e):e,s=()=>{throw r("bigint: non-minimal encoding")};if(!n){o[0]===0&&s();return}o[0]===0&&(o.length===1||(o[1]&128)===0)&&s(),o.length>1&&o[0]===255&&(o[1]&128)!==0&&s()}function Is(e,t,n){if(n){if(t<=Dt)throw new Error(`checkBounds: signed bits must be positive, got ${t}`);let r=yr**(t-ko);if(e<-r||e>=r)throw new Error(`value out of signed bounds. Expected ${-r} <= ${e} < ${r}`)}else{let r=yr**t;if(Dt>e||e>=r)throw new Error(`value out of unsigned bounds. Expected 0 <= ${e} < ${r}`)}}function Ls(e){let t=e;return{encodeStream:t.encodeStream,decodeStream:t.decodeStream,size:t.size,encode:n=>{let r=new vo;return t.encodeStream(r,n),r.finish()},decode:(n,r={})=>{if(!be(n))throw new TypeError(`decode: expected Uint8Array, got ${typeof n}`);let o=new Bo(n,r),s=t.decodeStream(o);return o.finish(),s}}}function me(e,t){if(!He(e))throw new TypeError(`validate: invalid inner value ${e}`);if(typeof t!="function")throw new TypeError("validate: fn should be function");return Ls({size:e.size,encodeStream:(n,r)=>{let o;try{o=t(r)}catch(s){throw n.err(s)}e.encodeStream(n,o)},decodeStream:n=>{let r=e.decodeStream(n);try{return t(r)}catch(o){throw n.err(o)}}})}var Ae=e=>{let t=e;if(!kt(t))throw new TypeError(`wrap: invalid inner value ${t}`);if(typeof t.encodeStream!="function")throw new TypeError("wrap: encodeStream should be function");if(typeof t.decodeStream!="function")throw new TypeError("wrap: decodeStream should be function");if(t.size!==void 0&&(!ie(t.size)||t.size<0))throw new TypeError(`wrap: invalid size ${t.size}`);if(t.validate!==void 0&&typeof t.validate!="function")throw new TypeError("wrap: validate should be function");let n=Ls(t);return t.validate!==void 0?me(n,t.validate):n},br=e=>kt(e)&&typeof e.decode=="function"&&typeof e.encode=="function";function He(e){return kt(e)&&br(e)&&typeof e.encodeStream=="function"&&typeof e.decodeStream=="function"&&(e.size===void 0||ie(e.size)&&e.size>=0)}function rf(){return{encode:e=>{if(!Array.isArray(e))throw new Error("array expected");let t={},n=new Set;for(let r of e){if(!Array.isArray(r)||r.length!==2)throw new Error("array of two elements expected");let o=r[0],s=r[1];if(To(o,"dict: key"),n.has(o))throw new Error(`key(${o}) appears twice in struct`);n.add(o),t[o]=s}return t},decode:e=>{if(!kt(e))throw new Error(`expected plain object, got ${e}`);for(let t in e)To(t,"dict: key");return Object.entries(e)}}}var of=Object.freeze({encode:e=>{if(typeof e!="bigint")throw new Error(`expected bigint, got ${typeof e}`);if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`element bigger than MAX_SAFE_INTEGER=${e}`);if(e<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`element smaller than MIN_SAFE_INTEGER=${e}`);return Number(e)},decode:e=>{if(!ie(e))throw new Error("element is not a safe integer");return BigInt(e)}});function sf(e){if(!kt(e))throw new Error("plain object expected");return{encode:t=>{if(!ie(t)||!(t in e))throw new Error(`wrong value ${t}`);return e[t]},decode:t=>{if(typeof t!="string")throw new Error(`wrong value ${typeof t}`);let n=e[t];if(!tf(e,t)||!ie(n))throw new Error(`wrong value ${t}`);return n}}}function af(e,t=!1){if(!ie(e)||e<0)throw new Error(`decimal/precision: wrong value ${e}`);if(typeof t!="boolean")throw new Error(`decimal/round: expected boolean, got ${typeof t}`);let n=vs**BigInt(e);return{encode:r=>{if(typeof r!="bigint")throw new Error(`expected bigint, got ${typeof r}`);let o=(r<Dt?-r:r).toString(10),s=o.length-e;s<0&&(o=o.padStart(o.length-s,"0"),s=0);let i=o.length-1;for(;i>=s&&o[i]==="0";i--);let a=o.slice(0,s),c=o.slice(s,i+1);return a||(a="0"),r<Dt&&(a="-"+a),c?`${a}.${c}`:a},decode:r=>{if(typeof r!="string")throw new Error(`expected string, got ${typeof r}`);let o=!1;if(r.startsWith("-")&&(o=!0,r=r.slice(1)),!/^(0|[1-9]\d*)(\.\d+)?$/.test(r))throw new Error(`wrong string value=${r}`);let s=r.indexOf(".");s=s===-1?r.length:s;let i=r.slice(0,s),a=r.slice(s+1).replace(/0+$/,""),c=BigInt(i)*n;if(!t&&a.length>e)throw new Error(`fractional part cannot be represented with this precision (num=${r}, prec=${e})`);let f=Math.min(a.length,e),u=BigInt(a.slice(0,f))*vs**BigInt(e-f),l=c+u;if(o&&l===Dt)throw new Error("negative zero is not allowed");return o?-l:l}}}function cf(e){if(!Array.isArray(e))throw new Error(`expected array, got ${typeof e}`);for(let t of e)if(!br(t))throw new Error(`wrong base coder ${t}`);return{encode:t=>{for(let n of e){let r;try{r=n.encode(t)}catch{continue}if(r!==void 0)return r}throw new Error(`match/encode: cannot find match in ${t}`)},decode:t=>{for(let n of e){let r;try{r=n.decode(t)}catch{continue}if(r!==void 0)return r}throw new Error(`match/decode: cannot find match in ${t}`)}}}var _s=e=>{if(!br(e))throw new Error("BaseCoder expected");return{encode:t=>e.decode(t),decode:t=>e.encode(t)}},on=Object.freeze({dict:rf,numberBigint:of,tsEnum:sf,decimal:af,match:cf,reverse:_s});var Ao=(e,t=!1,n=!1,r=!0,o=!1)=>{if(!ie(e)||e<=0)throw new Error(`bigint/size: wrong value ${e}`);if(typeof t!="boolean")throw new Error(`bigint/le: expected boolean, got ${typeof t}`);if(typeof n!="boolean")throw new Error(`bigint/signed: expected boolean, got ${typeof n}`);if(typeof r!="boolean")throw new Error(`bigint/sized: expected boolean, got ${typeof r}`);if(typeof o!="boolean")throw new Error(`bigint/minimal: expected boolean, got ${typeof o}`);let s=BigInt(e),i=yr**(rn*s-ko);return Ae({size:r?e:void 0,encodeStream:(a,c)=>{let f=c===Dt;n&&c<0&&(c=c|i);let u=new Uint8Array(e);for(let l=e-1;l>=0;l--)u[l]=Number(c&ef),c>>=rn;if(!r){let l=0;if(n){for(;l<u.length-1;l++){let d=u[l+1];if(!(u[l]===0&&(d&128)===0)&&!(u[l]===255&&(d&128)!==0))break}u=f?u.subarray(u.length):u.subarray(l)}else{for(;l<u.length&&u[l]===0;l++);u=u.subarray(l)}}a.bytes(t?u.reverse():u)},decodeStream:a=>{let c=a.bytes(r?e:Math.min(e,a.leftBytes));!r&&o&&nf(c,t,n,l=>a.err(l));let f=Dt;if(t)for(let l=c.length-1;l>=0;l--)f=f<<rn|BigInt(c[l]);else for(let l=0;l<c.length;l++)f=f<<rn|BigInt(c[l]);let u=r||!c.length?i:yr**(rn*BigInt(c.length)-ko);return n&&f&u&&(f=(f^u)-u),f},validate:a=>{if(typeof a!="bigint")throw new Error(`bigint: invalid value: ${a}`);return Is(a,rn*s,!!n),a}})},Us=Object.freeze(Ao(32,!0));var sn=Object.freeze(Ao(8,!0));var Rs=Object.freeze(Ao(8,!0,!0));var ff=(e,t)=>Ae({size:e,encodeStream:(n,r)=>n.writeView(e,(o,s)=>t.write(o,s,r)),decodeStream:n=>n.readView(e,t.read),validate:n=>{if(typeof n!="number")throw new TypeError(`viewCoder: expected number, got ${typeof n}`);return t.validate&&t.validate(n),n}}),Pn=(e,t,n)=>{let r=e*8,o=2**(r-1),s=c=>{if(!ie(c))throw new TypeError(`sintView: value is not safe integer: ${c}`);if(c<-o||c>=o)throw new RangeError(`sintView: value out of bounds. Expected ${-o} <= ${c} < ${o}`)},i=2**r,a=c=>{if(!ie(c))throw new TypeError(`uintView: value is not safe integer: ${c}`);if(0>c||c>=i)throw new RangeError(`uintView: value out of bounds. Expected 0 <= ${c} < ${i}`)};return ff(e,{write:n.write,read:n.read,validate:t?s:a})},Q=Object.freeze(Pn(4,!1,{read:(e,t)=>e.getUint32(t,!0),write:(e,t,n)=>e.setUint32(t,n,!0)})),An=Object.freeze(Pn(4,!1,{read:(e,t)=>e.getUint32(t,!1),write:(e,t,n)=>e.setUint32(t,n,!1)})),at=Object.freeze(Pn(4,!0,{read:(e,t)=>e.getInt32(t,!0),write:(e,t,n)=>e.setInt32(t,n,!0)}));var $o=Object.freeze(Pn(2,!1,{read:(e,t)=>e.getUint16(t,!0),write:(e,t,n)=>e.setUint16(t,n,!0)}));var De=Object.freeze(Pn(1,!1,{read:(e,t)=>e.getUint8(t),write:(e,t,n)=>e.setUint8(t,n)}));var re=(e,t=!1)=>{if(typeof t!="boolean")throw new TypeError(`bytes/le: expected boolean, got ${typeof t}`);let n=Os(e),r=be(e),o=r?Uint8Array.from(e):void 0,s=o&&o.length?As(o):void 0;return Ae({size:typeof e=="number"?e:void 0,encodeStream:(i,a)=>{r||n.encodeStream(i,a.length),i.bytes(t?wr(a):a),o&&i.bytes(o)},decodeStream:i=>{let a;if(o){let c=i.find(o);if(c===void 0)throw i.err("bytes: cannot find terminator");a=i.bytes(c-i.pos),i.bytes(o.length)}else a=i.bytes(e===null?i.leftBytes:n.decodeStream(i));return t?wr(a):a},validate:i=>{if(!be(i))throw new TypeError(`bytes: invalid value ${i}`);if(s){let a=t?wr(i):i;if(s(a)!==void 0)throw new Error("bytes: value contains terminator")}return i}})};function Ms(e,t){if(!He(t))throw new TypeError(`prefix: invalid inner value ${t}`);return Bt(re(e),_s(t))}var Oo=(e,t=!1)=>me(Bt(re(e,t),Bs),n=>{if(typeof n!="string")throw new Error(`expected string, got ${typeof n}`);return n});function Bt(e,t){if(!He(e))throw new TypeError(`apply: invalid inner value ${e}`);if(!br(t))throw new TypeError(`apply: invalid base value ${t}`);return Ae({size:e.size,encodeStream:(n,r)=>{let o;try{o=t.decode(r)}catch(s){throw n.err(""+s)}return e.encodeStream(n,o)},decodeStream:n=>{let r=e.decodeStream(n);try{return t.encode(r)}catch(o){throw n.err(""+o)}}})}var Cs=(e,t=!1)=>{if(!be(e))throw new TypeError(`flag/flagValue: expected Uint8Array, got ${typeof e}`);if(e.length===0)throw new Error("flag/flagValue: empty marker");if(typeof t!="boolean")throw new TypeError(`flag/xor: expected boolean, got ${typeof t}`);let n=Uint8Array.from(e);return Ae({size:void 0,encodeStream:(r,o)=>{!!o!==t&&r.bytes(n)},decodeStream:r=>{let o=r.leftBytes>=n.length;return o&&(o=Bn(r.bytes(n.length,!0),n),o&&r.bytes(n.length)),o!==t},validate:r=>{if(r!==void 0&&typeof r!="boolean")throw new Error(`flag: expected boolean value or undefined, got ${typeof r}`);return r}})};function lf(e,t,n){let r=t!==null&&typeof t=="object"&&!be(t),o=n!==null&&typeof n=="object"&&!be(n),s=typeof t=="number"&&typeof n=="number"&&Number.isNaN(t)&&Number.isNaN(n);if((!r||!o)&&!$s(t,n)&&!s)throw e.err(`default: invalid value ${t} !== ${n}`)}function Ns(e,t,n){if(typeof e!="string"&&!He(e))throw new TypeError(`flagged: wrong path=${e}`);if(!He(t))throw new TypeError(`flagged: invalid inner value ${t}`);let r=n!==void 0;return Ae({encodeStream:(o,s)=>{if(typeof e=="string")st.resolve(o.stack,e)?t.encodeStream(o,s):r&&t.encodeStream(o,n);else{let i=s!==void 0;e.encodeStream(o,i),i?t.encodeStream(o,s):r&&t.encodeStream(o,n)}},decodeStream:o=>{let s=!1;if(typeof e=="string"?s=!!st.resolve(o.stack,e):s=e.decodeStream(o),s)return t.decodeStream(o);r&&lf(o,t.decodeStream(o),n)}})}function Io(e,t,n=!0){if(!He(e))throw new TypeError(`magic: invalid inner value ${e}`);if(typeof n!="boolean")throw new TypeError(`magic: expected boolean, got ${typeof n}`);return Ae({size:e.size,encodeStream:(r,o)=>e.encodeStream(r,t),decodeStream:r=>{let o=e.decodeStream(r),s=o!==null&&typeof o=="object"&&!be(o),i=t!==null&&typeof t=="object"&&!be(t);if(n&&(!s||!i)&&!$s(o,t))throw r.err(`magic: invalid value: ${o} !== ${t}`)},validate:r=>{if(r!==void 0)throw new Error(`magic: wrong value=${typeof r}`);return r}})}function uf(e){let t=0;for(let n of e){if(n.size===void 0)return;if(!ie(n.size))throw new Error(`sizeof: wrong element size=${n.size}`);t+=n.size}return t}function he(e){if(!kt(e))throw new TypeError(`struct: expected plain object, got ${e}`);let t=[];for(let n in e){if(To(n,"struct: field"),!He(e[n]))throw new TypeError(`struct: field ${n} is not CoderType`);t.push(e[n])}return Ae({size:uf(t),encodeStream:(n,r)=>{let o=n;o.pushObj(r,()=>{for(let s in e)o.enterField(s),e[s].encodeStream(n,r[s]),o.exitField()})},decodeStream:n=>{let r={},o=n;return o.pushObj(r,()=>{for(let s in e)o.enterField(s),r[s]=e[s].decodeStream(n),o.exitField()}),r},validate:n=>{if(typeof n!="object"||n===null)throw new Error(`struct: invalid value ${n}`);return n}})}function Ue(e,t){if(!He(t))throw new TypeError(`array: invalid inner value ${t}`);let n=be(e)?Uint8Array.from(e):void 0,r=Os(typeof e=="string"?`../${e}`:n||e);if(e===null&&t.size===0)throw new Error("array: null length cannot use zero-size inner");if((He(e)||typeof e=="string")&&t.size===0)throw new Error("array: dynamic length cannot use zero-size inner");return Ae({size:typeof e=="number"&&t.size!==void 0?e*t.size:void 0,encodeStream:(o,s)=>{let i=o;i.pushObj(s,()=>{n||r.encodeStream(o,s.length);for(let a=0;a<s.length;a++){i.enterField(a);let c=s[a],f=i.pos;if(t.encodeStream(o,c),n&&n.length<=i.pos-f){let u=i.finish(!1).subarray(f,i.pos);if(Bn(u.subarray(0,n.length),n))throw i.err(`array: inner element encoding same as separator. elm=${c} data=${u}`)}i.exitField()}}),n&&o.bytes(n)},decodeStream:o=>{let s=[],i=o;return i.pushObj(s,()=>{if(e===null)for(let a=0;!o.isEnd();a++){i.enterField(a);let c=i.progress();if(s.push(t.decodeStream(o)),i.progress()===c)throw o.err("array: inner decoder did not consume input");if(i.exitField(),t.size&&o.leftBytes<t.size)break}else if(n)for(let a=0;;a++){if(Bn(o.bytes(n.length,!0),n)){o.bytes(n.length);break}i.enterField(a);let c=i.progress();if(s.push(t.decodeStream(o)),i.progress()===c)throw o.err("array: inner decoder did not consume input");i.exitField()}else{i.enterField("arrayLen");let a=r.decodeStream(o);if(i.exitField(),t.size&&a*t.size>o.leftBytes)throw o.err(`array: length=${a} elements of size=${t.size} exceed ${o.leftBytes} bytes left`);for(let c=0;c<a;c++)i.enterField(c),s.push(t.decodeStream(o)),i.exitField()}}),s},validate:o=>{if(!Array.isArray(o))throw new Error(`array: invalid value ${o}`);return o}})}function Lo(e,t="value"){if(typeof e!="bigint")throw new TypeError(`"${t}" expected bigint, got type=${typeof e}`);if(e<js)throw new RangeError(`"${t}" expected non-negative bigint, got ${e}`);return e}function Je(e,t,n=()=>{}){if(!Array.isArray(e))throw new TypeError(`"${t}" expected array, got type=${typeof e}`);for(let r=0;r<e.length;r++)n(e[r],`${t}[${r}]`);return e}function _o(e,t=""){if(typeof e!="string"){let n=t&&`"${t}" `;throw new TypeError(n+"expected string, got type="+typeof e)}return e}function ge(e,t={},n={},r="object"){return qe(e,t,n)}var $n=Ve.Point,Hs=$n.Fn,Fs=$n.Fn.ORDER,js=BigInt(0),Ks=BigInt(2),zs=e=>e%Ks===js,ee=vn.isBytes,et=vn.concatBytes,Y=vn.equalBytes,je=Vt,an=e=>fs(je(e)),ct=(...e)=>je(je(et(...e)));var On=e=>St.getPublicKey(e),xr=(e,t)=>Ve.getPublicKey(e,t),df=Fs/Ks,Ds=e=>e.r<df;function Ws(e,t,n=!1){q(e,32,"hash");let r=Ve.Signature.fromBytes(Ve.sign(e,t,{prehash:!1}));if(n&&!Ds(r)){let o=new Uint8Array(32),s=0;for(;!Ds(r);)if(o.set(Q.encode(s++)),r=Ve.Signature.fromBytes(Ve.sign(e,t,{prehash:!1,extraEntropy:o})),s>4294967295)throw new Error("lowR counter overflow: report the error")}return r.toBytes("der")}var Uo=(e,t,n)=>St.sign(e,t,n),cn=(e,...t)=>St.utils.taggedHash(e,...t),xe=Object.freeze({ecdsa:0,schnorr:1});function ft(e,t){let n=e.length;if(t===xe.ecdsa){if(n===32)throw new RangeError("Expected non-Schnorr key");return $n.fromBytes(e),e}else if(t===xe.schnorr){if(n!==32)throw new RangeError("Expected 32-byte Schnorr key");return St.utils.lift_x(Pe(e)),e}else throw new TypeError("Unknown key type")}function qs(e,t){let r=St.utils.taggedHash("TapTweak",e,t),o=Pe(r);if(o>=Fs)throw new Error("tweak higher than curve order");return o}function Vs(e,t=Uint8Array.of()){let n=St.utils;q(e,32,"privKey");let r=Pe(e),o=$n.BASE.multiply(r),s=zs(o.y)?r:Hs.neg(r),i=n.pointToBytes(o),a=qs(i,t);return Gt(Hs.add(s,a),32)}function Er(e,t){let n=St.utils;q(e,32,"pubKey");let r=qs(e,t),s=n.lift_x(Pe(e)).add($n.BASE.multiply(r)),i=zs(s.y)?0:1;return[n.pointToBytes(s),i]}var vt=Object.freeze({bech32:"bc",pubKeyHash:0,scriptHash:5,wif:128}),Ro=Object.freeze({bech32:"tb",pubKeyHash:111,scriptHash:196,wif:239});function fn(e,t){if(!ee(e)||!ee(t))throw new TypeError(`cmp: wrong type a=${typeof e} b=${typeof t}`);let n=Math.min(e.length,t.length);for(let r=0;r<n;r++)if(e[r]!=t[r])return Math.sign(e[r]-t[r]);return Math.sign(e.length-t.length)}function Sr(e){let t=Object.create(null);for(let n in e){if(t[e[n]]!==void 0)throw new Error("duplicate key");t[e[n]]=n}return t}var In=BigInt(0),Gs=BigInt(1),pf=BigInt(2),Tr=BigInt(8),Zs=BigInt(255),hf=BigInt(252),Se=Object.freeze({OP_0:0,PUSHDATA1:76,PUSHDATA2:77,PUSHDATA4:78,"1NEGATE":79,RESERVED:80,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,NOP:97,VER:98,IF:99,NOTIF:100,VERIF:101,VERNOTIF:102,ELSE:103,ENDIF:104,VERIFY:105,RETURN:106,TOALTSTACK:107,FROMALTSTACK:108,"2DROP":109,"2DUP":110,"3DUP":111,"2OVER":112,"2ROT":113,"2SWAP":114,IFDUP:115,DEPTH:116,DROP:117,DUP:118,NIP:119,OVER:120,PICK:121,ROLL:122,ROT:123,SWAP:124,TUCK:125,CAT:126,SUBSTR:127,LEFT:128,RIGHT:129,SIZE:130,INVERT:131,AND:132,OR:133,XOR:134,EQUAL:135,EQUALVERIFY:136,RESERVED1:137,RESERVED2:138,"1ADD":139,"1SUB":140,"2MUL":141,"2DIV":142,NEGATE:143,ABS:144,NOT:145,"0NOTEQUAL":146,ADD:147,SUB:148,MUL:149,DIV:150,MOD:151,LSHIFT:152,RSHIFT:153,BOOLAND:154,BOOLOR:155,NUMEQUAL:156,NUMEQUALVERIFY:157,NUMNOTEQUAL:158,LESSTHAN:159,GREATERTHAN:160,LESSTHANOREQUAL:161,GREATERTHANOREQUAL:162,MIN:163,MAX:164,WITHIN:165,RIPEMD160:166,SHA1:167,SHA256:168,HASH160:169,HASH256:170,CODESEPARATOR:171,CHECKSIG:172,CHECKSIGVERIFY:173,CHECKMULTISIG:174,CHECKMULTISIGVERIFY:175,NOP1:176,CHECKLOCKTIMEVERIFY:177,CHECKSEQUENCEVERIFY:178,NOP4:179,NOP5:180,NOP6:181,NOP7:182,NOP8:183,NOP9:184,NOP10:185,CHECKSIGADD:186,INVALID:255}),gf=Object.freeze(Sr(Se));function Xs(e=6,t=!1){return Ae({encodeStream:(n,r)=>{if(r===In)return;let o=r<0,s=BigInt(r),i=[];for(let a=o?-s:s;a;a>>=Tr)i.push(Number(a&Zs));i[i.length-1]>=128?i.push(o?128:0):o&&(i[i.length-1]|=128),n.bytes(new Uint8Array(i))},decodeStream:n=>{let r=n.leftBytes;if(r>e)throw new Error(`ScriptNum: number (${r}) bigger than limit=${e}`);if(r===0)return In;let o=n.bytes(r);if(t&&(o[r-1]&127)===0&&(r<=1||(o[r-2]&128)===0))throw new Error("Non-minimally encoded ScriptNum");let s=In;for(let i=0;i<r;++i)s|=BigInt(o[i])<<Tr*BigInt(i);return o[r-1]>=128&&(s&=pf**BigInt(r*8)-Gs>>Gs,s=-s),s}})}function Qs(e,t=4,n=!0){if(typeof e=="number")return e;if(ee(e))try{let r=Xs(t,n).decode(e);return r>Number.MAX_SAFE_INTEGER||r<-Number.MAX_SAFE_INTEGER?void 0:Number(r)}catch{return}}var Mo=(e,t)=>{if(Se.OP_0<e&&e<=Se.PUSHDATA4){if(e<Se.PUSHDATA1)return e;if(e===Se.PUSHDATA1)return t(1);if(e===Se.PUSHDATA2)return t(2);if(e===Se.PUSHDATA4)return t(4);throw new Error("Should be not possible")}},we=Object.freeze(Ae({encodeStream:(e,t)=>{Je(t,"value");for(let n of t){if(typeof n=="string"){let o=Se[n];if(typeof o!="number")throw new Error(`Unknown opcode=${n}`);e.byte(o);continue}else if(typeof n=="number"){if(n===0){e.byte(0);continue}else if(n===-1){e.byte(Se["1NEGATE"]);continue}else if(1<=n&&n<=16){e.byte(Se.OP_1-1+n);continue}}typeof n=="number"&&(n=Xs().encode(BigInt(n))),q(n,void 0,"value");let r=n.length;r<Se.PUSHDATA1?e.byte(r):r<=255?(e.byte(Se.PUSHDATA1),e.byte(r)):r<=65535?(e.byte(Se.PUSHDATA2),e.bytes($o.encode(r))):(e.byte(Se.PUSHDATA4),e.bytes(Q.encode(r))),e.bytes(n)}},decodeStream:e=>{let t=[];for(;!e.isEnd();){let n=e.byte(),r=Mo(n,o=>o===1?De.decodeStream(e):o===2?$o.decodeStream(e):Q.decodeStream(e));if(r!==void 0)t.push(e.bytes(r));else if(n===0)t.push(0);else if(Se.OP_1<=n&&n<=Se.OP_16)t.push(n-(Se.OP_1-1));else{let o=gf[n];if(o===void 0)throw new Error(`Unknown opcode=${n.toString(16)}`);t.push(o)}}return t}})),Br=(()=>{let e={253:[253,2,BigInt(253),BigInt(65535)],254:[254,4,BigInt(65536),BigInt(4294967295)],255:[255,8,BigInt(4294967296),BigInt("0xffffffffffffffff")]},t=Object.values(e);return Object.freeze(Ae({encodeStream:(n,r)=>{if(typeof r=="number"&&(r=BigInt(r)),In<=r&&r<=hf)return n.byte(Number(r));for(let[o,s,i,a]of t)if(!(i>r||r>a)){n.byte(o);for(let c=0;c<s;c++)n.byte(Number(r>>Tr*BigInt(c)&Zs));return}throw n.err(`VarInt too big: ${r}`)},decodeStream:n=>{let r=n.byte();if(r<=252)return BigInt(r);let[o,s,i]=e[r],a=In;for(let c=0;c<s;c++)a|=BigInt(n.byte())<<Tr*BigInt(c);if(a<i)throw n.err(`Wrong CompactSize(${8*s})`);return a}}))})(),Ie=Object.freeze(Bt(Br,on.numberBigint)),vr=Object.freeze(re(Br)),lt=vr,Js=Object.freeze(Ue(Ie,vr)),Pr=Js,kr=e=>Ue(Br,e),Ar=Object.freeze(he({txid:re(32,!0),index:Q,finalScriptSig:vr,sequence:Q})),ut=Object.freeze(he({amount:sn,script:vr})),wf=he({version:at,segwitFlag:Cs(new Uint8Array([0,1])),inputs:kr(Ar),outputs:kr(ut),witnesses:Ns("segwitFlag",Ue("inputs/length",Js)),lockTime:Q});function yf(e){if(e.segwitFlag&&e.witnesses&&e.witnesses.every(t=>!t.length))throw new Error("Segwit flag with only empty witness fields");return e}var Pt=Object.freeze(me(wf,yf)),Ln=Object.freeze(he({version:at,inputs:kr(Ar),outputs:kr(ut),lockTime:Q}));var ea=(e,t)=>{if(e===!0)return"ignore";if(e===!1)return"strip";if(e==="ignore"||e==="strip"||e==="strict")return e;throw new Error(`PSBT: invalid ${t} policy=${e}`)},sa=BigInt(0),ta=BigInt(1),No=me(re(null),e=>ft(e,xe.ecdsa)),ke=me(re(33),e=>ft(e,xe.ecdsa)),_n=me(re(32),e=>ft(e,xe.schnorr)),na=me(re(null),e=>{if(e.length!==64&&e.length!==65)throw new Error("Schnorr signature should be 64 or 65 bytes long");return e}),bf=Pr,Un=he({fingerprint:An,path:Ue(null,Q)}),aa=he({hashes:Ue(Ie,re(32)),der:Un}),mf=me(he({version:An,depth:De,parentFingerprint:An,childNumber:An,chainCode:re(32),publicKey:ke}),e=>{if(e.depth===0&&e.parentFingerprint!==0)throw new Error("GlobalXPUB: depth=0 requires parentFingerprint=0");if(e.depth===0&&e.childNumber!==0)throw new Error("GlobalXPUB: depth=0 requires childNumber=0");return e}),xf=he({pubKey:_n,leafHash:re(32)}),Ef=he({version:De,internalKey:re(32),merklePath:Ue(null,re(32))}),ln=Object.freeze(me(Ef,e=>{if(e.merklePath.length>128)throw new Error("TaprootControlBlock: merklePath should be of length 0..128 (inclusive)");return e})),Sf=me(Ue(null,he({depth:De,version:De,script:lt})),e=>{if(e.length<1)throw new Error("tapTree: expected at least one tuple");let t=Array(e[0].depth).fill(0),n=e[0].depth;for(let o=1;o<e.length;o++){let{depth:s}=e[o];s>n&&(n=s);let i=t.length-1;for(;i>=0&&t[i]===1;)i--;if(i<0)throw new Error("tapTree: tuples must be in DFS order");let a=t.slice(0,i);if(a.push(1),s<a.length)throw new Error("tapTree: tuples must be in DFS order");for(;a.length<s;)a.push(0);t=a}let r=sa;for(let o=0;o<e.length;o++)r+=ta<<BigInt(n-e[o].depth);if(r!==ta<<BigInt(n))throw new Error("tapTree: tuples must describe a complete binary tree");return e}),ue=re(null),Do=(()=>{let e=he({identifier:re(Ie),subtype:Ie,data:ue});return me(ue,t=>{try{e.decode(t)}catch(n){let r=n instanceof Error?n.message:String(n);throw new Error(`Proprietary key: expected BIP174 identifier and subtype, got ${r}`)}return t})})(),ra=re(20),At=re(32),ca=re(64),Tf=re(66),fa=Ue(null,ke),oa=Bt(ue,{decode:e=>{let t=e;return Gn(ke.encode(t.participantPubkey),ke.encode(t.aggregatePubkey),t.leafHash===void 0?pe:At.encode(t.leafHash))},encode:e=>{let t=e;if(t.length!==66&&t.length!==98)throw new Error(`MuSig2 key: expected 66 or 98 bytes, got ${t.length}`);let n={participantPubkey:ke.decode(t.subarray(0,33)),aggregatePubkey:ke.decode(t.subarray(33,66))};return t.length===98&&(n.leafHash=At.decode(t.subarray(66))),n}}),kf=he({scanKey:ke,spendKey:ke}),Bf=he({name:re(De),proof:ue}),R=(e,t,n,r,o,s)=>Object.freeze([e,t&&typeof t=="object"?Object.freeze(t):t,n&&typeof n=="object"?Object.freeze(n):n,Object.freeze([...r]),Object.freeze([...o]),s]),Or=Object.freeze({unsignedTx:R(0,!1,Ln,[0],[0],!1),xpub:R(1,mf,Un,[],[0,2],!1),txVersion:R(2,!1,Q,[2],[2],!1),fallbackLocktime:R(3,!1,Q,[],[2],!1),inputCount:R(4,!1,Ie,[2],[2],!1),outputCount:R(5,!1,Ie,[2],[2],!1),txModifiable:R(6,!1,De,[],[2],!1),spEcdhShare:R(7,ke,ke,[],[2],!1),spDleq:R(8,ke,ca,[],[2],!1),genericSignedMessage:R(9,!1,ue,[],[0,2],!1),version:R(251,!1,Q,[],[0,2],!1),proprietary:R(252,Do,ue,[],[0,2],!1)}),Ft=Object.freeze({nonWitnessUtxo:R(0,!1,Pt,[],[0,2],!1),witnessUtxo:R(1,!1,ut,[],[0,2],!1),partialSig:R(2,No,ue,[],[0,2],!1),sighashType:R(3,!1,Q,[],[0,2],!1),redeemScript:R(4,!1,ue,[],[0,2],!1),witnessScript:R(5,!1,ue,[],[0,2],!1),bip32Derivation:R(6,No,Un,[],[0,2],!1),finalScriptSig:R(7,!1,ue,[],[0,2],!1),finalScriptWitness:R(8,!1,bf,[],[0,2],!1),porCommitment:R(9,!1,ue,[],[0,2],!1),ripemd160:R(10,ra,ue,[],[0,2],!1),sha256:R(11,At,ue,[],[0,2],!1),hash160:R(12,ra,ue,[],[0,2],!1),hash256:R(13,At,ue,[],[0,2],!1),txid:R(14,!1,re(32,!0),[2],[2],!0),index:R(15,!1,Q,[2],[2],!0),sequence:R(16,!1,Q,[],[2],!0),requiredTimeLocktime:R(17,!1,Q,[],[2],!1),requiredHeightLocktime:R(18,!1,Q,[],[2],!1),tapKeySig:R(19,!1,na,[],[0,2],!1),tapScriptSig:R(20,xf,na,[],[0,2],!1),tapLeafScript:R(21,ln,ue,[],[0,2],!1),tapBip32Derivation:R(22,_n,aa,[],[0,2],!1),tapInternalKey:R(23,!1,_n,[],[0,2],!1),tapMerkleRoot:R(24,!1,At,[],[0,2],!1),p2cKeyTweak:R(25,ke,At,[],[0,2],!1),musig2ParticipantPubkeys:R(26,ke,fa,[],[0,2],!1),musig2PubNonce:R(27,oa,Tf,[],[0,2],!1),musig2PartialSig:R(28,oa,At,[],[0,2],!1),spEcdhShare:R(29,ke,ke,[],[2],!1),spDleq:R(30,ke,ca,[],[2],!1),spSpendBip32Derivation:R(31,ke,Un,[],[2],!1),spTweak:R(32,!1,At,[],[2],!1),proprietary:R(252,Do,ue,[],[0,2],!1)}),la=Object.freeze(["txid","sequence","index","witnessUtxo","nonWitnessUtxo","requiredTimeLocktime","requiredHeightLocktime","finalScriptSig","finalScriptWitness","unknown"]),ua=Object.freeze(["partialSig","finalScriptSig","finalScriptWitness","tapKeySig","tapScriptSig"]);var un=Object.freeze({redeemScript:R(0,!1,ue,[],[0,2],!1),witnessScript:R(1,!1,ue,[],[0,2],!1),bip32Derivation:R(2,No,Un,[],[0,2],!1),amount:R(3,!1,Rs,[2],[2],!0),script:R(4,!1,ue,[2],[2],!0),tapInternalKey:R(5,!1,_n,[],[0,2],!1),tapTree:R(6,!1,Sf,[],[0,2],!1),tapBip32Derivation:R(7,_n,aa,[],[0,2],!1),musig2ParticipantPubkeys:R(8,ke,fa,[],[0,2],!1),spV0Info:R(9,!1,kf,[],[2],!1),spV0Label:R(10,!1,Q,[],[2],!1),dnssecProof:R(53,!1,Bf,[],[0,2],!1),proprietary:R(252,Do,ue,[],[0,2],!1)}),da=Object.freeze([]),ia=Ue(Ps,he({key:Ms(Ie,he({type:Ie,key:re(null)})),value:re(Ie)}));function Ho(e){let[t,n,r,o,s,i]=e;return{type:t,kc:n,vc:r,reqInc:o,allowInc:s,silentIgnore:i}}var $r=he({type:Ie,key:re(null)});function Fo(e){let t={};for(let n in e){let[r,o,s]=e[n];t[r]=[n,o,s]}return Ae({encodeStream:(n,r)=>{let o=r,s=[],i={},a=(c,f)=>{let u=f,l=X.encode($r.encode(c));if(i[l])throw new Error(`PSBT: duplicate key=${l}`);i[l]=!0,s.push({key:c,value:u})};for(let c in e){let f=o[c];if(f===void 0)continue;let[u,l,d]=e[c];if(!l)a({type:u,key:pe},d.encode(f));else{let p=f.map(([h,g])=>[l.encode(h),d.encode(g)]);p.sort((h,g)=>fn(h[0],g[0]));for(let[h,g]of p)a({key:h,type:u},g)}}if(o.unknown){o.unknown.sort((c,f)=>fn(c[0].key,f[0].key));for(let[c,f]of o.unknown)a(c,f)}ia.encodeStream(n,s)},decodeStream:n=>{let r=ia.decodeStream(n),o={},s={},i={};for(let a of r){let c=X.encode($r.encode(a.key));if(i[c])throw new Error(`PSBT: duplicate key=${c}`);i[c]=!0;let f="unknown",u=a.key.key,l=a.value;if(t[a.key.type]){let[d,p,h]=t[a.key.type];if(f=d,!p&&u.length)throw new Error(`PSBT: Non-empty key for ${f} (key=${X.encode(u)} value=${X.encode(l)}`);if(u=p?p.decode(u):void 0,l=h.decode(l),!p){if(o[f])throw new Error(`PSBT: Same keys: ${f} (key=${u} value=${l})`);o[f]=l,s[f]=!0;continue}}else u={type:a.key.type,key:a.key.key};if(s[f])throw new Error(`PSBT: Key type with empty key and no key=${f} val=${l}`);o[f]||(o[f]=[]),o[f].push([u,l])}return o}})}var Ir=Object.freeze(me(Fo(Ft),e=>{if(e.finalScriptWitness&&!e.finalScriptWitness.length)throw new Error("validateInput: empty finalScriptWitness");if(e.partialSig&&!e.partialSig.length)throw new Error("Empty partialSig");if(e.partialSig)for(let[t]of e.partialSig)ft(t,xe.ecdsa);if(e.bip32Derivation)for(let[t]of e.bip32Derivation)ft(t,xe.ecdsa);if(e.requiredTimeLocktime!==void 0&&e.requiredTimeLocktime<5e8)throw new Error(`validateInput: wrong timeLocktime=${e.requiredTimeLocktime}`);if(e.requiredHeightLocktime!==void 0&&(e.requiredHeightLocktime<=0||e.requiredHeightLocktime>=5e8))throw new Error(`validateInput: wrong heighLocktime=${e.requiredHeightLocktime}`);if(e.tapLeafScript)for(let[t,n]of e.tapLeafScript){if((t.version&254)!==n[n.length-1])throw new Error("validateInput: tapLeafScript version mimatch");if(n[n.length-1]&1)throw new Error("validateInput: tapLeafScript version has parity bit!")}return e})),Lr=Object.freeze(me(Fo(un),e=>{if(e.amount!==void 0&&e.amount<sa)throw new Error(`validateOutput: wrong amount=${e.amount}`);if(e.bip32Derivation)for(let[t]of e.bip32Derivation)ft(t,xe.ecdsa);return e})),pa=me(Fo(Or),e=>{if((e.version||0)===0){if(!e.unsignedTx)throw new Error("PSBTv0: missing unsignedTx");for(let n of e.unsignedTx.inputs)if(n.finalScriptSig&&n.finalScriptSig.length)throw new Error("PSBTv0: input scriptSig found in unsignedTx")}for(let[n,r]of e.xpub||[])if(n.depth!==r.path.length)throw new Error(`PSBT_GLOBAL_XPUB: xpub depth=${n.depth} must match derivation path length=${r.path.length}`);return e}),vf=Object.freeze(he({magic:Io(Oo(new Uint8Array([255])),"psbt"),global:pa,inputs:Ue("global/unsignedTx/inputs/length",Ir),outputs:Ue(null,Lr)})),Pf=Object.freeze(he({magic:Io(Oo(new Uint8Array([255])),"psbt"),global:pa,inputs:Ue("global/inputCount",Ir),outputs:Ue("global/outputCount",Lr)}));function Co(e,t,n){let r=n;for(let o in r){if(o==="unknown"||!t[o])continue;let{allowInc:s}=Ho(t[o]);if(!s.includes(e))throw new Error(`PSBTv${e}: field ${o} is not allowed`)}for(let o in t){let{reqInc:s}=Ho(t[o]);if(s.includes(e)&&r[o]===void 0)throw new Error(`PSBTv${e}: missing required field ${o}`)}}function jo(e,t,n){le(e,"version"),ge(t,{},{},"info"),ge(n,{},{},"lst");let r=n,o={};for(let s in r){let i=s;if(i!=="unknown"){if(!t[i])continue;let{allowInc:a,silentIgnore:c}=Ho(t[i]);if(!a.includes(e)){if(c)continue;throw new Error(`Failed to serialize in PSBTv${e}: ${i} but versions allows inclusion=${a}`)}}o[i]=r[i]}return o}function ha(e){let t=e&&e.global&&e.global.version||0;Co(t,Or,e.global);for(let i of e.inputs)Co(t,Ft,i);for(let i of e.outputs)Co(t,un,i);let n=t?e.global.inputCount:e.global.unsignedTx.inputs.length;if(e.inputs.length!==n)throw new Error(`Wrong number of input maps=${e.inputs.length}, expected=${n}`);let r=t?e.global.outputCount:e.global.unsignedTx.outputs.length;if(e.outputs.length<r)throw new Error("Not outputs inputs");if(t===0&&n===0&&Object.keys(e.outputs[0]||{}).length===0&&(r>0&&e.outputs.length===r+1||r===0&&e.outputs.length===2&&Object.keys(e.outputs[1]).length===0))return e;let s=e.outputs.slice(r);if(s.length>1||s.length&&(t!==0||Object.keys(s[0]).length))throw new Error(`Unexpected outputs left in tx=${s}`);return e}function _r(e,t,n,r,o="strip",s="strip"){ge(e,{},{},"psbtEnum"),ge(t,{},{},"val"),n!==void 0&&ge(n,{},{},"cur"),r!==void 0&&Je(r,"allowedFields");let i=t,a=n,c=r,f=ea(o,"unknown"),u=ea(s,"proprietary");for(let[d,p]of[["unknown",f],["proprietary",u]])if(p==="strict"&&(i[d]?.length||a?.[d]?.length))throw new Error(`PSBT: ${d} PSBT field is not allowed in strict mode`);let l={...a,...i};for(let d in e){let p=d;if(d==="proprietary"&&u!=="ignore")continue;let[h,g,y]=e[p],S=c&&!c.includes(d);if(i[d]===void 0&&d in i){if(S)throw new Error(`Cannot remove signed field=${d}`);delete l[d]}else if(g){let P=a&&a[d]?a[d]:[],N=i[p];if(N){if(!Array.isArray(N))throw new Error(`keyMap(${d}): KV pairs should be [k, v][]`);N=N.map(L=>{if(L.length!==2)throw new Error(`keyMap(${d}): KV pairs should be [k, v][]`);return[typeof L[0]=="string"?g.decode(X.decode(L[0])):L[0],typeof L[1]=="string"?y.decode(X.decode(L[1])):L[1]]});let O={},D=(L,w,m)=>{if(O[L]===void 0){O[L]=[w,m];return}let b=X.encode(y.encode(O[L][1])),x=X.encode(y.encode(m));if(b!==x)throw new Error(`keyMap(${p}): same key=${L} oldVal=${b} newVal=${x}`)};for(let[L,w]of P){let m=X.encode(g.encode(L));D(m,L,w)}for(let[L,w]of N){let m=X.encode(g.encode(L));if(w===void 0){if(S)throw new Error(`Cannot remove signed field=${p}/${L}`);delete O[m]}else{if(S&&O[m]===void 0)throw new Error(`Cannot add signed field=${p}/${m}`);D(m,L,w)}}l[p]=Object.values(O)}}else if(typeof l[d]=="string"&&(l[d]=y.decode(X.decode(l[d]))),S&&d in i){if(!a||a[d]===void 0)throw new Error(`Cannot add signed field=${d}`);let P=a[d];if(typeof P=="string"&&(P=y.decode(X.decode(P))),!Y(y.encode(l[d]),y.encode(P)))throw new Error(`Cannot change signed field=${d}`)}}if(f==="ignore"&&i.unknown){let d={};for(let[p,h]of a?.unknown||[])d[X.encode($r.encode(p))]=[p,h];for(let[p,h]of i.unknown){let g=X.encode($r.encode(p));if(d[g]===void 0){d[g]=[p,h];continue}let y=X.encode(ue.encode(d[g][1])),S=X.encode(ue.encode(h));if(y!==S)throw new Error(`keyMap(unknown): same key=${g} oldVal=${y} newVal=${S}`)}l.unknown=Object.values(d)}for(let d in l)if(!e[d]){if(f==="ignore"&&d==="unknown")continue;delete l[d]}return f!=="ignore"&&delete l.unknown,u!=="ignore"&&delete l.proprietary,l}function Ur(e,t,n,r="strip",o="strip"){ge(e,{},{},"psbtEnum"),ge(t,{},{},"current"),ge(n,{},{},"other");let s=t,i=n;for(let a in e){let c=a,[f,u,l]=e[c];if(u||s[c]===void 0||i[c]===void 0)continue;let d=s[c],p=i[c];if(typeof d=="string"&&(d=l.decode(X.decode(d))),typeof p=="string"&&(p=l.decode(X.decode(p))),!Y(l.encode(d),l.encode(p)))throw new Error(`Cannot combine conflicting field=${a}`)}return _r(e,i,s,void 0,r,o)}var Ko=Object.freeze(me(vf,ha)),zo=Object.freeze(me(Pf,ha));var Mr=Uint8Array.from([78,115]),Of={encode(e){if(!(e.length!==2||e[0]!==1||!ee(e[1])||!Y(e[1],Mr)))return{type:"p2a",script:we.encode(e)}},decode:e=>{if(e.type==="p2a")return[1,Uint8Array.from(Mr)]}};function tt(e,t){try{return ft(e,t),!0}catch{return!1}}var If={encode(e){if(!(e.length!==2||!ee(e[0])||!tt(e[0],xe.ecdsa)||e[1]!=="CHECKSIG"))return{type:"pk",pubkey:e[0]}},decode:e=>{if(e.type==="pk")return[e.pubkey,"CHECKSIG"]}},Lf={encode(e){if(!(e.length!==5||e[0]!=="DUP"||e[1]!=="HASH160"||!ee(e[2]))&&e[2].length===20&&!(e[3]!=="EQUALVERIFY"||e[4]!=="CHECKSIG"))return{type:"pkh",hash:e[2]}},decode:e=>e.type==="pkh"?["DUP","HASH160",e.hash,"EQUALVERIFY","CHECKSIG"]:void 0},_f={encode(e){if(!(e.length!==3||e[0]!=="HASH160"||!ee(e[1])||e[2]!=="EQUAL")&&e[1].length===20)return{type:"sh",hash:e[1]}},decode:e=>e.type==="sh"?["HASH160",e.hash,"EQUAL"]:void 0},Uf={encode(e){if(!(e.length!==2||e[0]!==0||!ee(e[1]))&&e[1].length===32)return{type:"wsh",hash:e[1]}},decode:e=>e.type==="wsh"?[0,e.hash]:void 0},Rf={encode(e){if(!(e.length!==2||e[0]!==0||!ee(e[1]))&&e[1].length===20)return{type:"wpkh",hash:e[1]}},decode:e=>e.type==="wpkh"?[0,e.hash]:void 0},Mf={encode(e){let t=e.length-1;if(e[t]!=="CHECKMULTISIG")return;let n=e[0],r=e[t-1];if(typeof n!="number"||typeof r!="number")return;let o=e.slice(1,-2);if(r===o.length){for(let s of o)if(!ee(s)||!tt(s,xe.ecdsa))return;if(!(!Number.isSafeInteger(n)||n<1||n>r))return{type:"ms",m:n,pubkeys:o}}},decode:e=>e.type==="ms"?[e.m,...e.pubkeys,e.pubkeys.length,"CHECKMULTISIG"]:void 0},Cf={encode(e){if(!(e.length!==2||e[0]!==1||!ee(e[1])||e[1].length!==32)&&tt(e[1],xe.schnorr))return{type:"tr",pubkey:e[1]}},decode:e=>e.type==="tr"?[1,e.pubkey]:void 0},Nf={encode(e){let t=e.length-1;if(e[t]!=="CHECKSIG")return;let n=[];for(let r=0;r<t;r++){let o=e[r];if(r&1){if(o!=="CHECKSIGVERIFY"||r===t-1)return;continue}if(!ee(o)||!tt(o,xe.schnorr))return;n.push(o)}if(!(!n.length||n.length>999))return{type:"tr_ns",pubkeys:n}},decode:e=>{if(e.type!=="tr_ns")return;let t=[];for(let n=0;n<e.pubkeys.length-1;n++)t.push(e.pubkeys[n],"CHECKSIGVERIFY");return t.push(e.pubkeys[e.pubkeys.length-1],"CHECKSIG"),t}},Hf={encode(e){let t=e.length-1;if(e[t]!=="NUMEQUAL"||e[1]!=="CHECKSIG")return;let n=[],r=Qs(e[t-1]);if(typeof r=="number"){for(let o=0;o<t-1;o++){let s=e[o];if(o&1){if(s!==(o===1?"CHECKSIG":"CHECKSIGADD"))return;continue}if(!ee(s)||!tt(s,xe.schnorr))return;n.push(s)}if(!(!Number.isSafeInteger(r)||r<1||r>n.length||n.length>999))return{type:"tr_ms",pubkeys:n,m:r}}},decode:e=>{if(e.type!=="tr_ms")return;let t=[e.pubkeys[0],"CHECKSIG"];for(let n=1;n<e.pubkeys.length;n++)t.push(e.pubkeys[n],"CHECKSIGADD");return t.push(e.m,"NUMEQUAL"),t}},Df={encode(e){return{type:"unknown",script:we.encode(e)}},decode:e=>e.type==="unknown"?we.decode(e.script):void 0},Ff=[Of,If,Lf,_f,Uf,Rf,Mf,Cf,Nf,Hf,Df],jf=Bt(we,on.match(Ff)),Ye=Object.freeze(me(jf,e=>{if(e.type==="pk"&&!tt(e.pubkey,xe.ecdsa))throw new Error("OutScript/pk: wrong key");if((e.type==="pkh"||e.type==="sh"||e.type==="wpkh")&&(!ee(e.hash)||e.hash.length!==20))throw new Error(`OutScript/${e.type}: wrong hash`);if(e.type==="wsh"&&(!ee(e.hash)||e.hash.length!==32))throw new Error("OutScript/wsh: wrong hash");if(e.type==="tr"&&(!ee(e.pubkey)||!tt(e.pubkey,xe.schnorr)))throw new Error("OutScript/tr: wrong taproot public key");if((e.type==="ms"||e.type==="tr_ns"||e.type==="tr_ms")&&!Array.isArray(e.pubkeys))throw new Error("OutScript/multisig: wrong pubkeys array");if(e.type==="ms"){let t=e.pubkeys.length;for(let n of e.pubkeys)if(!tt(n,xe.ecdsa))throw new Error("OutScript/multisig: wrong pubkey");if(le(e.m,"m"),e.m<=0||t>16||e.m>t)throw new Error("OutScript/multisig: invalid params")}if(e.type==="tr_ns"||e.type==="tr_ms"){if(e.pubkeys.length>999)throw new Error(`OutScript/${e.type}: invalid params`);for(let n of e.pubkeys)if(!tt(n,xe.schnorr))throw new Error(`OutScript/${e.type}: wrong pubkey`)}if(e.type==="tr_ms"){let t=e.pubkeys.length;if(le(e.m,"m"),e.m<=0||e.m>t)throw new Error("OutScript/tr_ms: invalid params")}return e})),nt=Object.freeze(Ae({encodeStream:(e,t)=>Ye.encodeStream(e,t),decodeStream:e=>{let t=e.bytes(e.leftBytes),n=Ye.decode(t);if(n&&(n.type==="p2a"||n.type==="wpkh"||n.type==="wsh"||n.type==="tr")&&!Y(t,Ye.encode(n)))throw new Error("OutScript: non-canonical witness program");return n}}));function ga(e,t){if(!Y(e.hash,je(t)))throw new Error("checkScript: wsh wrong witnessScript hash");let n=Ye.decode(t);if(n.type==="tr"||n.type==="tr_ns"||n.type==="tr_ms")throw new Error(`checkScript: P2${n.type} cannot be wrapped in P2SH`);if(n.type==="wpkh"||n.type==="wsh"||n.type==="sh")throw new Error(`checkScript: P2${n.type} cannot be wrapped in P2WSH`)}function Wo(e,t,n){let r=!1,o;if(e){let s=nt.decode(e);if(s.type==="tr_ns"||s.type==="tr_ms"||s.type==="ms"||s.type=="pk")throw new Error(`checkScript: non-wrapped ${s.type}`);if(t){if(s.type!=="sh")throw new Error("checkScript: redeemScript without P2SH");if(!Y(s.hash,an(t)))throw new Error("checkScript: sh wrong redeemScript hash");if(o=nt.decode(t),o?.type==="tr"||o?.type==="tr_ns"||o?.type==="tr_ms")throw new Error(`checkScript: P2${o.type} cannot be wrapped in P2SH`);if(o?.type==="sh")throw new Error("checkScript: P2SH cannot be wrapped in P2SH")}s.type==="wsh"&&(r=!0,n&&ga(s,n))}if(t&&(o===void 0&&(o=nt.decode(t)),o?.type==="wsh"&&(r=!0,n&&ga(o,n))),n&&!r)throw new Error("checkScript: witnessScript without P2WSH")}var Cr=(e,t=vt)=>{if(!tt(e,xe.ecdsa))throw new Error("P2WPKH: invalid publicKey");if(e.length===65)throw new Error("P2WPKH: uncompressed public key");let n=an(e);return{type:"wpkh",script:Ye.encode({type:"wpkh",hash:n}),address:jt(t).encode({type:"wpkh",hash:n}),hash:n}};var ya=192,Kf=e=>{if(e===void 0)return ya;if(le(e,"leafVersion"),e>254||e===80||e&1)throw new Error(`P2TR: invalid leafVersion=${e}`);return e},Rn=(e,t=ya)=>cn("TapLeaf",new Uint8Array([Kf(t)]),lt.encode(e));var ba=Ss(je);function ma(e,t){if(t.length<2||t.length>40)throw new Error("Witness: invalid length");if(e>16)throw new Error("Witness: invalid version");if(e===0&&!(t.length===20||t.length===32))throw new Error("Witness: invalid length for version")}function Rr(e,t,n=vt){ma(e,t);let r=e===0?gr:So;return r.encode(n.bech32,[e].concat(r.toWords(t)))}function wa(e,t){return ba.encode(et(Uint8Array.from(t),e))}function jt(e=vt){return ge(e,{},{},"network"),{encode(t){ge(t,{},{},"from");let{type:n}=t;if(_o(n,"from.type"),n==="wpkh")return Rr(0,t.hash,e);if(n==="wsh")return Rr(0,t.hash,e);if(n==="tr")return Rr(1,t.pubkey,e);if(n==="p2a")return Rr(1,Mr,e);if(n==="pkh")return wa(t.hash,[e.pubKeyHash]);if(n==="sh")return wa(t.hash,[e.scriptHash]);throw new Error(`Unknown address type=${n}`)},decode(t){if(_o(t,"address"),t.length<14||t.length>74)throw new Error("Invalid address length");if(e.bech32&&t.toLowerCase().startsWith(`${e.bech32}1`)){let r;try{if(r=gr.decode(t),r.words[0]!==0)throw new Error(`bech32: wrong version=${r.words[0]}`)}catch{if(r=So.decode(t),r.words[0]===0)throw new Error(`bech32m: wrong version=${r.words[0]}`)}if(r.prefix!==e.bech32)throw new Error(`wrong bech32 prefix=${r.prefix}`);let[o,...s]=r.words,i=gr.fromWords(s);if(ma(o,i),o===0&&i.length===32)return{type:"wsh",hash:i};if(o===0&&i.length===20)return{type:"wpkh",hash:i};if(o===1&&i.length===32)return{type:"tr",pubkey:i};if(o===1&&Y(i,Mr))return{type:"p2a",script:we.encode([1,i])};throw new Error("Unknown witness program")}let n=ba.decode(t);if(n.length!==21)throw new Error("Invalid base58 address");if(n[0]===e.pubKeyHash)return{type:"pkh",hash:n.slice(1)};if(n[0]===e.scriptHash)return{type:"sh",hash:n.slice(1)};throw new Error(`Invalid address prefix=${n[0]}`)}}}var qo=BigInt(0),zf=BigInt(1),Wf=BigInt("0xffffffffffffffff"),Vo=new Uint8Array(32),qf={amount:Wf,script:pe},Vf=e=>Math.ceil(e/4),Yf=e=>{let t=0,n=[];for(let r=0;r<e.length;){let o=r,s=e[r++];if(s===Se.CODESEPARATOR){t<o&&n.push(e.subarray(t,o)),t=r;continue}let i=Mo(s,a=>{if(r+a>e.length)throw new Error("Unexpected end of script");let c=0;for(let f=0;f<a;f++)c|=e[r+f]<<8*f;return r+=a,c});if(i!==void 0&&(r+=i,r>e.length))throw new Error("Unexpected end of script")}return t===0?e:(t<e.length&&n.push(e.subarray(t)),n.length?et(...n):pe)};var Gf=2,$t=0,Fr=4294967295;var Ot=(e,t)=>e===void 0?t:e;function rt(e){if(Array.isArray(e))return e.map(t=>rt(t));if(ee(e))return Uint8Array.from(e);if(["number","bigint","boolean","string","undefined"].includes(typeof e))return e;if(e===null)return e;if(typeof e=="object")return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,rt(n)]));throw new Error(`cloneDeep: unknown type=${typeof e}`)}var z=Object.freeze({DEFAULT:0,ALL:1,NONE:2,SINGLE:3,ANYONECANPAY:128}),Zf=Object.freeze({DEFAULT:z.DEFAULT,ALL:z.ALL,NONE:z.NONE,SINGLE:z.SINGLE,ALL_ANYONECANPAY:z.ALL|z.ANYONECANPAY,NONE_ANYONECANPAY:z.NONE|z.ANYONECANPAY,SINGLE_ANYONECANPAY:z.SINGLE|z.ANYONECANPAY}),Xf=Object.freeze(Sr(Zf));function Qf(e,t,n,r=pe){return Y(n,t)&&(e=Vs(e,r),t=On(e)),{privKey:e,pubKey:t}}function Kt(e){if(e.script===void 0||e.amount===void 0)throw new Error("Transaction/output: script and amount required");return{script:e.script,amount:e.amount}}function Mn(e){if(ge(e,{},{},"i"),e.txid===void 0||e.index===void 0)throw new Error("Transaction/input: txid and index required");let t={txid:e.txid,index:e.index,sequence:Ot(e.sequence,Fr),finalScriptSig:Ot(e.finalScriptSig,pe)};return Ar.encode(t),t}var Ke=(e,t,n,r=!1)=>{let o={...e};for(let[s,i]of[["unknown",t],["proprietary",n]]){let a=o[s];if(a!==void 0&&Je(a,`${s} PSBT field`),!a?.length){delete o[s];continue}if(i==="strict")throw new Error(`PSBT: ${s} PSBT field is not allowed in strict mode`);if(i==="strip"){if(r)throw new Error(`PSBT: ${s} PSBT field cannot be supplied when policy is strip`);delete o[s]}}return o},dn=(e,t)=>{if(e===void 0||!(e&-8))return e;if(t==="strict")throw new Error("PSBT: unknown txModifiable bits in strict mode");return t==="strip"?e&7:e};function xa(e,t="strip",n="strip"){let r=e,o=Ke(r,t,n);o.unknown?r.unknown=o.unknown:delete r.unknown,o.proprietary?r.proprietary=o.proprietary:delete r.proprietary;for(let s in r){let i=s;n==="ignore"&&i==="proprietary"&&r.proprietary?.length||la.includes(i)||delete r[i]}}var Yo=he({txid:re(32,!0),index:Q});function Jf(e){if(typeof e!="number"||typeof Xf[e]!="string")throw new Error(`Invalid SigHash=${e}`);return e}function Nr(e){let t=e&31;return{isAny:!!(e&z.ANYONECANPAY),isNone:t===z.NONE,isSingle:t===z.SINGLE}}var Ea=e=>({sigInputs:e&z.ANYONECANPAY,sigOutputs:e===z.DEFAULT?z.ALL:e&3}),Sa=(e,t,n,r="strip")=>{let o=n===void 0?void 0:n?"ignore":"strip";if(t!==void 0&&t!=="ignore"&&t!=="strip"&&t!=="strict")throw new Error(`Transaction options wrong value: ${e}=${t}`);if(t!==void 0&&o!==void 0&&t!==o)throw new Error(`Transaction options: conflicting ${e} options`);return t||o||r};function el(e){e!==void 0&&ge(e,{},{},"opts");let t={...e,version:Ot(e.version,Gf),lockTime:Ot(e.lockTime,0),PSBTVersion:Ot(e.PSBTVersion,0)};if(typeof t.allowUnknowInput<"u"&&(t.allowUnknownInputs=t.allowUnknowInput),typeof t.allowUnknowOutput<"u"&&(t.allowUnknownOutputs=t.allowUnknowOutput),t.allowMissingTxModifiable===void 0&&(t.allowMissingTxModifiable=!0),typeof t.lockTime!="number")throw new Error("Transaction lock time should be number");if(Q.encode(t.lockTime),t.PSBTVersion!==0&&t.PSBTVersion!==2)throw new Error(`Unknown PSBT version ${t.PSBTVersion}`);for(let n of["allowUnknownVersion","allowUnknownOutputs","allowUnknownInputs","disableScriptCheck","bip174jsCompat","allowLegacyWitnessUtxo","strictPrevoutValidation","lowR","allowUnknown","allowMissingTxModifiable"]){let r=t[n];if(r!==void 0&&typeof r!="boolean")throw new Error(`Transation options wrong type: ${n}=${r} (${typeof r})`)}if(t.unknown=Sa("unknown",t.unknown,t.allowUnknown),t.proprietary=Sa("proprietary",t.proprietary,void 0,t.unknown),t.allowUnknownVersion?typeof t.version!="number":![-1,0,1,2,3].includes(t.version))throw new Error(`Unknown version: ${t.version}`);if(at.encode(t.version),t.customScripts!==void 0){let n=t.customScripts;if(!Array.isArray(n))throw new Error(`wrong custom scripts type (expected array): customScripts=${n} (${typeof n})`);for(let r of n){if(typeof r.encode!="function"||typeof r.decode!="function")throw new Error(`wrong script=${r} (${typeof r})`);if(r.finalizeTaproot!==void 0&&typeof r.finalizeTaproot!="function")throw new Error(`wrong script=${r} (${typeof r})`)}}return Object.freeze(t)}function tl(e,t){let n=nt.decode(t),r=e.tapInternalKey!==void 0||e.tapMerkleRoot!==void 0||!!e.tapLeafScript?.length;if(n.type!=="tr"){if(r)throw new Error("validateInput: Taproot metadata without P2TR previous output");return}let o=(s,i,a)=>{let[c,f]=Er(s,i);if(!Y(c,n.pubkey))throw new Error("validateInput: Taproot commitment does not match previous output");if(a!==void 0&&f!==a)throw new Error("validateInput: Taproot control-block parity does not match previous output")};if(e.tapLeafScript)for(let[s,i]of e.tapLeafScript){let a=i[i.length-1],c=i.subarray(0,-1),f=Rn(c,a);for(let u of s.merklePath)f=fn(u,f)===-1?cn("TapBranch",u,f):cn("TapBranch",f,u);if(o(s.internalKey,f,s.version&1),e.tapInternalKey&&!Y(e.tapInternalKey,s.internalKey))throw new Error("validateInput: tapInternalKey does not match Taproot control block");if(e.tapMerkleRoot&&!Y(e.tapMerkleRoot,f))throw new Error("validateInput: tapMerkleRoot does not match Taproot control block")}e.tapInternalKey&&(e.tapMerkleRoot||!e.tapLeafScript?.length)&&o(e.tapInternalKey,e.tapMerkleRoot||pe)}var Hr=5e8;function Xo(e){let t=e.requiredHeightLocktime;if(t!==void 0&&(le(t,"requiredHeightLocktime"),t===0||t>=Hr))throw new RangeError(`requiredHeightLocktime must be between 1 and ${Hr-1}, got ${t}`);let n=e.requiredTimeLocktime;if(n!==void 0&&(le(n,"requiredTimeLocktime"),n<Hr||n>4294967295))throw new RangeError(`requiredTimeLocktime must be between ${Hr} and 4294967295, got ${n}`)}function Dr(e,t=$t){let n=$t,r=$t,o=!1,s=!0,i=!0;for(let a of e){Xo(a);let c=a.requiredHeightLocktime!==void 0,f=a.requiredTimeLocktime!==void 0;!c&&!f||(o=!0,c?n=Math.max(n,a.requiredHeightLocktime):s=!1,f?r=Math.max(r,a.requiredTimeLocktime):i=!1)}if(!o)return t;if(s)return n;if(i)return r;throw new Error("PSBTv2: incompatible height-based and time-based locktime requirements")}function Nn(e,t=!1){ge(e,{},{},"i");let n=e;Xo(n);let r;if(n.nonWitnessUtxo&&n.index!==void 0){let o=n.nonWitnessUtxo.outputs.length-1;if(n.index>o)throw new Error(`validateInput: index(${n.index}) not in nonWitnessUtxo`);if(r=n.nonWitnessUtxo.outputs[n.index],n.witnessUtxo&&(!Y(n.witnessUtxo.script,r.script)||n.witnessUtxo.amount!==r.amount))throw new Error("validateInput: witnessUtxo different from nonWitnessUtxo");if(n.txid){if(n.nonWitnessUtxo.outputs.length-1<n.index)throw new Error("nonWitnessUtxo: incorect output index");let i=pn.fromRaw(Pt.encode(n.nonWitnessUtxo),{allowUnknownOutputs:!0,disableScriptCheck:!0,allowUnknownInputs:!0,allowUnknownVersion:!0}),a=X.encode(n.txid);if(i.id!==a)throw new Error(`nonWitnessUtxo: wrong txid, exp=${a} got=${i.id}`)}}else n.witnessUtxo&&(r=n.witnessUtxo);return r&&!t&&(Wo(r.script,n.redeemScript,n.witnessScript),tl(n,r.script)),n}var Ta=e=>{let t=e,n=[],r=(o,s,i=!1)=>{let a=o;if(!a.length)return;let c=s&&a.length===64?z.DEFAULT:a[a.length-1];n.push({sighash:c,taproot:s,scriptPath:i})};for(let[,o]of t.partialSig||[])r(o,!1);t.tapKeySig&&r(t.tapKeySig,!0);for(let[,o]of t.tapScriptSig||[])r(o,!0,!0);return n},Cn={self:["txid","index","sequence","nonWitnessUtxo","witnessUtxo","sighashType"],ecdsa:["redeemScript","witnessScript"],tapscript:["tapLeafScript"],cross:["txid","index"],prevout:["nonWitnessUtxo","witnessUtxo"]};function Hn(e){ge(e,{},{},"input");let t=e;if(t.nonWitnessUtxo){if(t.index===void 0)throw new Error("Unknown input index");if(!Number.isSafeInteger(t.index)||t.index<0||t.index>=t.nonWitnessUtxo.outputs.length)throw new Error(`Wrong input index=${t.index}`);return t.nonWitnessUtxo.outputs[t.index]}else if("witnessUtxo"in t){let n=t.witnessUtxo;if(ge(n,{},{},"input.witnessUtxo"),Lo(n.amount,"input.witnessUtxo.amount"),!ee(n.script))throw new TypeError('"input.witnessUtxo.script" expected Uint8Array, got type='+typeof n.script);return n}else throw new Error("Cannot find previous output info")}function Go(e,t,n,r=!1,o="strip",s="strip"){ge(e,{},{},"i"),t!==void 0&&ge(t,{},{},"cur"),n!==void 0&&Je(n,"allowedFields");let i=e,a=t,c=n,{nonWitnessUtxo:f,txid:u}=i;typeof f=="string"&&(f=X.decode(f)),ee(f)&&(f=Pt.decode(f)),!("nonWitnessUtxo"in i)&&f===void 0&&(f=a?.nonWitnessUtxo),typeof u=="string"&&(u=X.decode(u)),u===void 0&&(u=a?.txid);let l={...a,...i,nonWitnessUtxo:f,txid:u};return!("nonWitnessUtxo"in i)&&l.nonWitnessUtxo===void 0&&delete l.nonWitnessUtxo,l.sequence===void 0&&(l.sequence=Fr),l.tapMerkleRoot===null&&delete l.tapMerkleRoot,l=_r(Ft,l,a,c,o,s),Array.isArray(l.tapLeafScript)&&!l.tapLeafScript.length&&delete l.tapLeafScript,Xo(l),Ir.encode(l),Nn(l,r)}function Zo(e,t=!1){let n=e,r="legacy",o=z.ALL,s=Hn(n),i=nt.decode(s.script),a=i.type,c=i,f=[i],u=s.script;if(i.type==="tr")return o=z.DEFAULT,{txType:"taproot",type:"tr",last:i,lastScript:s.script,defaultSighash:o,sighash:n.sighashType||o};{if((i.type==="wpkh"||i.type==="wsh")&&(r="segwit"),i.type==="sh"){if(!n.redeemScript)throw new Error("inputType: sh without redeemScript");let p=nt.decode(n.redeemScript);(p.type==="wpkh"||p.type==="wsh")&&(r="segwit"),f.push(p),c=p,u=n.redeemScript,a+=`-${p.type}`}if(c.type==="wsh"){if(!n.witnessScript)throw new Error("inputType: wsh without witnessScript");let p=Ye.decode(n.witnessScript);p.type==="wsh"&&(r="segwit"),f.push(p),c=p,u=n.witnessScript,a+=`-${p.type}`}let l=f[f.length-1];if(l.type==="sh"||l.type==="wsh")throw new Error("inputType: sh/wsh cannot be terminal type");let d={type:a,txType:r,last:l,lastScript:u,defaultSighash:o,sighash:n.sighashType||o};if(r==="legacy"&&!t&&!n.nonWitnessUtxo)throw new Error("Transaction/sign: legacy input without nonWitnessUtxo, can result in attack that forces paying higher fees. Pass allowLegacyWitnessUtxo=true, if you sure");return d}}var pn=class e{constructor(t={}){k(this,"global",{});k(this,"inputs",[]);k(this,"outputs",[]);k(this,"opts");let n=this.opts=el(t);this.global.fallbackLocktime=n.lockTime,this.global.txVersion=n.version,n.PSBTVersion===2&&(this.global.txModifiable=3)}isPSBTv2(){return(this.global.version??this.opts.PSBTVersion)===2}requireTxModifiable(t,n){if(this.isPSBTv2()&&!(this.txModifiablePolicy()&t))throw new Error(`PSBTv2: ${n} are not modifiable`)}txModifiablePolicy(t=this.opts.allowMissingTxModifiable,n=this.opts.unknown){return this.isPSBTv2()?this.global.txModifiable!==void 0?dn(this.global.txModifiable,n):t?3:0:3}modifiable(t=this.opts.allowMissingTxModifiable,n=this.opts.unknown){let r=this.txModifiablePolicy(t,n),o=!1,s=!1;for(let i=0;i<this.inputs.length;i++){let a=Ta(this.inputs[i]);!a.length&&this.inputStatus(i)==="finalized"&&(o=!0);for(let{sighash:c}of a){let{isAny:f,isNone:u,isSingle:l}=Nr(c);f||(r&=-2),u||(r&=-3),l&&(s=!0)}}return s&&(r|=4),o&&this.global.txModifiable===void 0&&(r&=-4),r}get txModifiable(){return this.modifiable()}static fromRaw(t,n={}){let r=Pt.decode(t),o=new e({...n,version:r.version,lockTime:r.lockTime});for(let s of r.outputs)o.addOutput(s);if(o.outputs=r.outputs,o.inputs=r.inputs,r.witnesses)for(let s=0;s<r.witnesses.length;s++)o.inputs[s].finalScriptWitness=r.witnesses[s];return o}static fromPSBT(t,n={}){let r;try{r=Ko.decode(t)}catch(g){try{r=zo.decode(t)}catch{throw g}}let o=r.global.version||0;if(o!==0&&o!==2)throw new Error(`Wrong PSBT version=${o}`);let s=r.global.unsignedTx,i=o===0?s?.version:r.global.txVersion,a=o===0?s?.lockTime:r.global.fallbackLocktime,c=new e({...n,version:i,lockTime:a,PSBTVersion:o}),f=o===0?s?.inputs.length:r.global.inputCount;c.inputs=r.inputs.slice(0,f).map((g,y)=>{let S={...r.global.unsignedTx?.inputs[y],...g};return g.finalScriptSig?.length||delete S.finalScriptSig,Nn(S,c.opts.disableScriptCheck)});let u=o===0?s?.outputs.length:r.global.outputCount,d=o===0&&f===0&&Object.keys(r.outputs[0]||{}).length===0&&(u>0&&r.outputs.length===u+1||u===0&&r.outputs.length===2&&Object.keys(r.outputs[1]).length===0)?1:0;c.outputs=r.outputs.slice(d,d+u).map((g,y)=>({...g,...r.global.unsignedTx?.outputs[y]}));let p=c.opts.unknown,h=c.opts.proprietary;return c.global=Ke({...r.global,txVersion:i},p,h),c.inputs=c.inputs.map(g=>Ke(g,p,h)),c.outputs=c.outputs.map(g=>Ke(g,p,h)),c.global.txModifiable!==void 0&&(c.global.txModifiable=dn(c.global.txModifiable,p)),Dr(c.inputs,c.global.fallbackLocktime??$t),o===0&&(c.global.fallbackLocktime=Ot(a,$t)),c}toPSBT(t=this.global.version||this.opts.PSBTVersion){if(t!==void 0&&le(t,"PSBTVersion"),t!==0&&t!==2)throw new Error(`Wrong PSBT version=${t}`);let n=this.inputs.map(i=>Ke(jo(t,Ft,Nn(i,this.opts.disableScriptCheck)),this.opts.unknown,this.opts.proprietary));for(let i of n)i.partialSig&&!i.partialSig.length&&delete i.partialSig,i.finalScriptSig&&!i.finalScriptSig.length&&delete i.finalScriptSig,i.finalScriptWitness&&!i.finalScriptWitness.length&&delete i.finalScriptWitness;let r=this.outputs.map(i=>Ke(jo(t,un,i),this.opts.unknown,this.opts.proprietary)),o=Ke({...this.global},this.opts.unknown,this.opts.proprietary);o.txModifiable!==void 0&&(o.txModifiable=dn(o.txModifiable,this.opts.unknown)),t===0?(o.unsignedTx=Ln.decode(Ln.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(i=>Mn(i)).map(i=>({...i,finalScriptSig:pe})),outputs:this.outputs.map(i=>Kt(i))})),delete o.fallbackLocktime,delete o.txVersion,delete o.inputCount,delete o.outputCount,delete o.version,delete o.txModifiable):(delete o.unsignedTx,o.version=t,o.txVersion=this.version,o.inputCount=this.inputs.length,o.outputCount=this.outputs.length,(!this.isPSBTv2()||o.txModifiable===void 0&&this.opts.allowMissingTxModifiable)&&(o.txModifiable=this.txModifiable)),this.opts.bip174jsCompat&&t===0&&!r.length&&r.push({});let s={global:o,inputs:n,outputs:r};return t===0?Ko.encode(s):zo.encode(s)}get lockTime(){return Dr(this.inputs,this.global.fallbackLocktime??$t)}get version(){if(this.global.txVersion===void 0)throw new Error("No global.txVersion");return this.global.txVersion}inputStatus(t){this.checkInputIdx(t);let n=this.inputs[t];return n.finalScriptSig&&n.finalScriptSig.length||n.finalScriptWitness&&n.finalScriptWitness.length?"finalized":n.tapKeySig||n.tapScriptSig&&n.tapScriptSig.length||n.partialSig&&n.partialSig.length?"signed":"unsigned"}cleanFinalInput(t){xa(t,this.opts.unknown,this.opts.proprietary),this.global.txModifiable!==void 0&&(this.global.txModifiable=dn(this.global.txModifiable,this.opts.unknown))}inputSighash(t){this.checkInputIdx(t);let n=this.inputs[t].sighashType,r=n===void 0?z.DEFAULT:n;return Ea(r)}signatures(){let t=[];for(let n=0;n<this.inputs.length;n++){let r=Ta(this.inputs[n]);for(let a of r)t.push({idx:n,...a});if(r.length||this.inputStatus(n)!=="finalized")continue;let o=!0;try{o=nt.decode(Hn(this.inputs[n]).script).type==="tr"}catch{}let s=this.inputs[n].sighashType,i=s===void 0?z.DEFAULT:s;t.push({idx:n,sighash:i,taproot:o,scriptPath:o})}return t}signedInputKeys(t,n=this.signatures()){let r=new Set,o=s=>{for(let i of s)r.add(i)};for(let s of n){let{isAny:i,isNone:a,isSingle:c}=Nr(s.sighash);s.idx===t?(o(Cn.self),s.taproot?s.scriptPath&&o(Cn.tapscript):o(Cn.ecdsa)):i||(o(Cn.cross),(s.taproot||!a&&!c)&&r.add("sequence"),s.taproot&&o(Cn.prevout))}return[...r]}signStatus(t=this.signatures()){let n=!0,r=!0,o=[],s=[];for(let{idx:i,sighash:a}of t){let{sigInputs:c,sigOutputs:f}=Ea(a);if(c===z.ANYONECANPAY?o.includes(i)||o.push(i):n=!1,f===z.ALL)r=!1;else if(f===z.SINGLE)s.includes(i)||s.push(i);else if(f!==z.NONE)throw new Error(`Wrong signature hash output type: ${f}`)}return{addInput:n,addOutput:r,inputs:o,outputs:s}}get isFinal(){for(let t=0;t<this.inputs.length;t++)if(this.inputStatus(t)!=="finalized")return!1;return!0}get hasWitnesses(){for(let t of this.inputs)if(t.finalScriptWitness&&t.finalScriptWitness.length)return!0;return!1}get weight(){if(!this.isFinal)throw new Error("Transaction is not finalized");let t=s=>Ie.encode(s).length+s,n=this.hasWitnesses,r=32,o=this.outputs.map(Kt);r+=4*Ie.encode(this.outputs.length).length;for(let s of o)r+=32+4*t(s.script.length);n&&(r+=2),r+=4*Ie.encode(this.inputs.length).length;for(let s of this.inputs)if(r+=160+4*t((s.finalScriptSig||pe).length),n){let i=s.finalScriptWitness||[];r+=Ie.encode(i.length).length;for(let a of i)r+=t(a.length)}return r}get vsize(){return Vf(this.weight)}toBytes(t=!1,n=!1){return Pt.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(Mn).map(r=>({...r,finalScriptSig:t&&r.finalScriptSig||pe})),outputs:this.outputs.map(Kt),witnesses:this.inputs.map(r=>r.finalScriptWitness||[]),segwitFlag:n&&this.hasWitnesses})}get unsignedTx(){return this.toBytes(!1,!1)}get hex(){return X.encode(this.toBytes(!0,this.hasWitnesses))}get hash(){return X.encode(ct(this.toBytes(!0)))}get id(){return X.encode(ct(this.toBytes(!0)).reverse())}checkInputIdx(t){if(le(t,"idx"),t>=this.inputs.length)throw new Error(`Wrong input index=${t}`)}validatePrevoutsForSigning(){if(this.opts.strictPrevoutValidation)for(let t=0;t<this.inputs.length;t++){let n=this.inputs[t];if(!n.nonWitnessUtxo)throw new Error(`Transaction/sign: strictPrevoutValidation requires nonWitnessUtxo for input=${t}`);if(n.txid===void 0||n.index===void 0)throw new Error(`Transaction/sign: strictPrevoutValidation requires an outpoint for input=${t}`);Nn(n,this.opts.disableScriptCheck)}}getInput(t){return this.checkInputIdx(t),rt(this.inputs[t])}get inputsLength(){return this.inputs.length}addInput(t,n=!1){ge(t,{},{},"input"),Ke(t,this.opts.unknown,this.opts.proprietary,!0),this.requireTxModifiable(1,"inputs");let r=n?void 0:this.signatures(),o=r&&this.signStatus(r);if(o&&!o.addInput)throw new Error("Tx has signed inputs, cannot add new one");let s=rt(Go(t,void 0,void 0,this.opts.disableScriptCheck,this.opts.unknown,this.opts.proprietary)),i=Dr([...this.inputs,s],this.global.fallbackLocktime??$t);if(r?.length&&i!==this.lockTime)throw new Error("Tx has signed inputs, cannot change lockTime");return this.inputs.push(s),this.inputs.length-1}updateInput(t,n,r=!1){this.checkInputIdx(t),Ke(n,this.opts.unknown,this.opts.proprietary,!0);let o,s=r?void 0:this.signatures();if(s?.length)if(this.inputStatus(t)==="finalized")o=ua.filter(l=>this.inputs[t][l]!==void 0);else{let l=new Set(this.signedInputKeys(t,s));l.size&&(o=Object.keys(Ft).filter(d=>!l.has(d)))}let i=rt(Go(n,this.inputs[t],o,this.opts.disableScriptCheck,this.opts.unknown,this.opts.proprietary)),a=this.inputs.slice();a[t]=i;let c=Dr(a,this.global.fallbackLocktime??$t);if(s?.length&&c!==this.lockTime)throw new Error("Tx has signed inputs, cannot change lockTime");let f=this.inputs[t];(f.index!==i.index||Ot(f.sequence,Fr)!==Ot(i.sequence,Fr)||(f.txid===void 0?i.txid!==void 0:i.txid===void 0||!Y(f.txid,i.txid))||c!==this.lockTime)&&this.requireTxModifiable(1,"inputs"),this.inputs[t]=i}checkOutputIdx(t){if(le(t,"idx"),t>=this.outputs.length)throw new Error(`Wrong output index=${t}`)}getOutput(t){return this.checkOutputIdx(t),rt(this.outputs[t])}getOutputAddress(t,n=vt){let r=this.getOutput(t);if(r.script)return jt(n).encode(nt.decode(r.script))}get outputsLength(){return this.outputs.length}normalizeOutput(t,n,r){ge(t,{},{},"o");let{amount:o,script:s}=t;o===void 0&&(o=n?.amount),o=Lo(o,"o.amount"),typeof s=="string"&&(s=X.decode(s)),s===void 0&&(s=n?.script);let i={...n,...t,amount:o,script:s};if(i.amount===void 0&&delete i.amount,i=_r(un,i,n,r,this.opts.unknown,this.opts.proprietary),Lr.encode(i),i.script&&!this.opts.allowUnknownOutputs&&nt.decode(i.script).type==="unknown")throw new Error("Transaction/output: unknown output script type, there is a chance that input is unspendable. Pass allowUnknownOutputs=true, if you sure");return this.opts.disableScriptCheck||Wo(i.script,i.redeemScript,i.witnessScript),i}addOutput(t,n=!1){Ke(t,this.opts.unknown,this.opts.proprietary,!0),this.requireTxModifiable(2,"outputs");let r=n?void 0:this.signStatus();if(r&&(!r.addOutput||r.outputs.includes(this.outputs.length)))throw new Error("Tx has signed outputs, cannot add new one");return this.outputs.push(rt(this.normalizeOutput(t))),this.outputs.length-1}updateOutput(t,n,r=!1){this.checkOutputIdx(t),Ke(n,this.opts.unknown,this.opts.proprietary,!0);let o;if(!r){let c=this.signStatus();(!c.addOutput||c.outputs.includes(t))&&(o=da)}let s=this.outputs[t],i=rt(this.normalizeOutput(n,s,o));(s.amount!==i.amount||(s.script===void 0?i.script!==void 0:i.script===void 0||!Y(s.script,i.script)))&&this.requireTxModifiable(2,"outputs"),this.outputs[t]=i}addOutputAddress(t,n,r=vt){return this.addOutput({script:Ye.encode(jt(r).decode(t)),amount:n})}get fee(){let t=qo;for(let r of this.inputs){let o=Hn(r);if(!o)throw new Error("Empty input amount");t+=o.amount}let n=this.outputs.map(Kt);for(let r of n)t-=r.amount;return t}preimageLegacy(t,n,r){let{isAny:o,isNone:s,isSingle:i}=Nr(r);if(t<0||!Number.isSafeInteger(t))throw new Error(`Invalid input idx=${t}`);if(i&&t>=this.outputs.length||t>=this.inputs.length)return Us.encode(zf);n=Yf(n);let a=this.inputs.map(Mn).map((u,l)=>({...u,finalScriptSig:l===t?n:pe}));o?a=[a[t]]:(s||i)&&(a=a.map((u,l)=>({...u,sequence:l===t?u.sequence:0})));let c=this.outputs.map(Kt);s?c=[]:i&&(c=c.slice(0,t).fill(qf).concat([c[t]]));let f=Pt.encode({lockTime:this.lockTime,version:this.version,segwitFlag:!1,inputs:a,outputs:c});return ct(f,at.encode(r))}preimageWitnessV0(t,n,r,o){if(le(t,"idx"),t>=this.inputs.length)throw new Error(`Invalid input idx=${t}`);let{isAny:s,isNone:i,isSingle:a}=Nr(r),c=Vo,f=Vo,u=Vo,l=this.inputs.map(Mn),d=this.outputs.map(Kt);s||(c=ct(...l.map(Yo.encode))),!s&&!a&&!i&&(f=ct(...l.map(h=>Q.encode(h.sequence)))),!a&&!i?u=ct(...d.map(ut.encode)):a&&t<d.length&&(u=ct(ut.encode(d[t])));let p=l[t];return ct(at.encode(this.version),c,f,re(32,!0).encode(p.txid),Q.encode(p.index),lt.encode(n),sn.encode(o),Q.encode(p.sequence),u,Q.encode(this.lockTime),Q.encode(r))}preimageWitnessV1(t,n,r,o,s=-1,i,a=192,c){if(le(t,"idx"),t>=this.inputs.length)throw new Error(`Invalid input idx=${t}`);if(Je(o,"amount"),Je(n,"prevOutScript"),this.inputs.length!==o.length)throw new Error(`Invalid amounts array=${o}`);if(this.inputs.length!==n.length)throw new Error(`Invalid prevOutScript array=${n}`);let f=[De.encode(0),De.encode(r),at.encode(this.version),Q.encode(this.lockTime)],u=r===z.DEFAULT?z.ALL:r&3,l=r&z.ANYONECANPAY,d=this.inputs.map(Mn),p=this.outputs.map(Kt);if(u===z.SINGLE&&t>=p.length)throw new Error(`Input with sighash SINGLE, but there is no output with corresponding index=${t}`);l!==z.ANYONECANPAY&&f.push(...[d.map(Yo.encode),o.map(sn.encode),n.map(lt.encode),d.map(g=>Q.encode(g.sequence))].map(g=>je(et(...g)))),u===z.ALL&&f.push(je(et(...p.map(ut.encode))));let h=(c?1:0)|(i?2:0);if(f.push(new Uint8Array([h])),l===z.ANYONECANPAY){let g=d[t];f.push(Yo.encode(g),sn.encode(o[t]),lt.encode(n[t]),Q.encode(g.sequence))}else f.push(Q.encode(t));return h&1&&f.push(je(lt.encode(c||pe))),u===z.SINGLE&&f.push(je(ut.encode(p[t]))),i&&f.push(Rn(i,a),De.encode(0),at.encode(s)),cn("TapSighash",...f)}signIdx(t,n,r,o){if(!ee(t)&&(!t||typeof t!="object"||typeof t.deriveChild!="function"))throw new TypeError('"privateKey" expected Uint8Array or HDKey, got type='+typeof t);this.checkInputIdx(n),this.validatePrevoutsForSigning();let s=Nn(this.inputs[n],this.opts.disableScriptCheck),i=Zo(s,this.opts.allowLegacyWitnessUtxo),a=l=>{if(i.txType==="taproot"){let h=On(l);if(s.tapInternalKey&&Y(h,s.tapInternalKey))return!0;if(!s.tapLeafScript)return!1;for(let[g,y]of s.tapLeafScript)for(let S of we.decode(y.subarray(0,-1)))if(ee(S)&&Y(S,h))return!0;return!1}let d=xr(l),p=an(d);for(let h of we.decode(i.lastScript))if(ee(h)&&(Y(h,d)||Y(h,p)))return!0;return!1};if(!ee(t)){let l=t,d=(g,y,S)=>{if(!y||!y.length)throw new Error(`${g}: empty`);let P=y.filter(N=>N.fingerprint==l.fingerprint).map(N=>{let O=l;for(let D of N.path)O=O.deriveChild(D);if(!Y(S(O),N.pubKey))throw new Error(`${g}: wrong pubKey`);if(!O.privateKey)throw new Error(`${g}: no privateKey`);return O});if(!P.length)throw new Error(`${g}: no items with fingerprint=${l.fingerprint}`);return P},p=i.txType==="taproot"?d("tapBip32Derivation",s.tapBip32Derivation?.map(([g,{der:y}])=>({pubKey:g,fingerprint:y.fingerprint,path:y.path})),g=>g.publicKey.slice(1)):d("bip32Derivation",s.bip32Derivation?.map(([g,y])=>({pubKey:g,fingerprint:y.fingerprint,path:y.path})),g=>g.publicKey),h=!1;for(let g of p)a(g.privateKey)&&this.signIdx(g.privateKey,n,r,o)&&(h=!0);if(h)return!0;throw i.txType==="taproot"?new Error("No taproot scripts signed"):new Error(`Input script doesn't have pubKey: ${i.lastScript}`)}r?r.forEach(Jf):r=[i.defaultSighash];let c=i.sighash;if(!r.includes(c))throw new Error(`Input with not allowed sigHash=${c}. Allowed: ${r.join(", ")}`);let{sigOutputs:f}=this.inputSighash(n);if(f===z.SINGLE&&n>=this.outputs.length)throw new Error(`Input with sighash SINGLE, but there is no output with corresponding index=${n}`);let u=Hn(s);if(i.txType==="taproot"){let l=this.inputs.map(Hn),d=l.map(S=>S.script),p=l.map(S=>S.amount),h=!1,g=On(t),y=s.tapMerkleRoot||pe;if(s.tapInternalKey){let{pubKey:S,privKey:P}=Qf(t,g,s.tapInternalKey,y),[N,O]=Er(s.tapInternalKey,y);if(Y(N,S)){let D=this.preimageWitnessV1(n,d,c,p),L=et(Uo(D,P,o),c!==z.DEFAULT?new Uint8Array([c]):pe);this.updateInput(n,{tapKeySig:L},!0),h=!0}}if(s.tapLeafScript){s.tapScriptSig=s.tapScriptSig||[];for(let[S,P]of s.tapLeafScript){let N=P.subarray(0,-1),O=we.decode(N),D=P[P.length-1],L=Rn(N,D);if(O.findIndex(x=>ee(x)&&Y(x,g))===-1)continue;let m=this.preimageWitnessV1(n,d,c,p,void 0,N,D),b=et(Uo(m,t,o),c!==z.DEFAULT?new Uint8Array([c]):pe);this.updateInput(n,{tapScriptSig:[[{pubKey:g,leafHash:L},b]]},!0),h=!0}}if(!h)throw new Error("No taproot scripts signed");return!0}else{let l=xr(t),d=!1,p=an(l);for(let y of we.decode(i.lastScript))ee(y)&&(Y(y,l)||Y(y,p))&&(d=!0);if(!d)throw new Error(`Input script doesn't have pubKey: ${i.lastScript}`);let h;if(i.txType==="legacy")h=this.preimageLegacy(n,i.lastScript,c);else if(i.txType==="segwit"){let y=i.lastScript;i.last.type==="wpkh"&&(y=Ye.encode({type:"pkh",hash:i.last.hash})),h=this.preimageWitnessV0(n,y,c,u.amount)}else throw new Error(`Transaction/sign: unknown tx type: ${i.txType}`);let g=Ws(h,t,this.opts.lowR);this.updateInput(n,{partialSig:[[l,et(g,new Uint8Array([c]))]]},!0)}return!0}sign(t,n,r){this.validatePrevoutsForSigning();let o=0;for(let s=0;s<this.inputs.length;s++)try{this.signIdx(t,s,n,r)&&o++}catch{}if(!o)throw new Error("No inputs signed");return o}finalizeIdx(t){if(this.checkInputIdx(t),this.fee<qo)throw new Error("Outputs spends more than inputs amount");let n=this.inputs[t];Ke(n,this.opts.unknown,this.opts.proprietary),dn(this.global.txModifiable,this.opts.unknown);let r=Zo(n,this.opts.allowLegacyWitnessUtxo);if(r.txType==="taproot"){if(n.tapKeySig)n.finalScriptWitness=[n.tapKeySig];else if(n.tapLeafScript&&n.tapScriptSig){let c=n.tapLeafScript.slice().sort((d,p)=>ln.encode(d[0]).length-ln.encode(p[0]).length),f,u=Number.POSITIVE_INFINITY,l=!1;for(let[d,p]of c){let h=p.slice(0,-1),g=p[p.length-1],y=Ye.decode(h),S=Rn(h,g),P=n.tapScriptSig.filter(L=>Y(L[0].leafHash,S)),N=[],O;if(y.type==="tr_ms"){let L=y.m,w=y.pubkeys,m=0;for(let b of w){let x=P.findIndex(E=>Y(E[0].pubKey,b));if(m===L||x===-1){N.push(pe);continue}N.push(P[x][1]),m++}if(m!==L)continue}else if(y.type==="tr_ns"){for(let L of y.pubkeys){let w=P.findIndex(m=>Y(m[0].pubKey,L));w!==-1&&N.push(P[w][1])}if(N.length!==y.pubkeys.length)continue}else if(y.type==="unknown"&&this.opts.allowUnknownInputs){let L=we.decode(h);if(N=P.map(([{pubKey:w},m])=>{let b=L.findIndex(x=>ee(x)&&Y(x,w));if(b===-1)throw new Error("finalize/taproot: cannot find position of pubkey in script");return{signature:m,pos:b}}).sort((w,m)=>w.pos-m.pos).map(w=>w.signature),!N.length)continue}else{let L=this.opts.customScripts,w=!1;if(L)for(let m of L){if(!m.finalizeTaproot)continue;let b=we.decode(h),x=m.encode(b);if(x===void 0)continue;w=!0;let E=m.finalizeTaproot(h,x,P);if(E){O=E.concat(ln.encode(d));break}}if(!O&&!w&&P.length&&(l=!0),!O)continue}O||(O=N.reverse().concat([h,ln.encode(d)]));let D=Pr.encode(O).length;D>=u||(f=O,u=D)}if(!f&&l)throw new Error("Finalize: Unknown tapLeafScript");if(!f)throw new Error("finalize/taproot: empty witness");n.finalScriptWitness=f}else throw new Error("finalize/taproot: unknown input");delete n.finalScriptSig,this.cleanFinalInput(n);return}if(!n.partialSig||!n.partialSig.length)throw new Error("Not enough partial sign");let o=pe,s=[];if(r.last.type==="ms"){let c=r.last.m,f=r.last.pubkeys,u=[];for(let l of f){let d=n.partialSig.find(p=>Y(l,p[0]));d&&u.push(d[1])}if(u=u.slice(0,c),u.length!==c)throw new Error(`Multisig: wrong signatures count, m=${c} n=${f.length} signatures=${u.length}`);o=we.encode([0,...u])}else if(r.last.type==="pk")o=we.encode([n.partialSig[0][1]]);else if(r.last.type==="pkh")o=we.encode([n.partialSig[0][1],n.partialSig[0][0]]);else if(r.last.type==="wpkh")o=pe,s=[n.partialSig[0][1],n.partialSig[0][0]];else if(r.last.type==="unknown"&&!this.opts.allowUnknownInputs)throw new Error("Unknown inputs not allowed");let i,a;if(r.type.includes("wsh-")&&(o.length&&r.lastScript.length&&(s=we.decode(o).map(c=>{if(c===0)return pe;if(ee(c))return c;throw new Error(`Wrong witness op=${c}`)})),s=s.concat(r.lastScript)),r.txType==="segwit"&&(a=s),r.type.startsWith("sh-wsh-")?i=we.encode([we.encode([0,je(r.lastScript)])]):r.type.startsWith("sh-")?i=we.encode([...we.decode(o),r.lastScript]):r.type.startsWith("wsh-")||r.txType!=="segwit"&&(i=o),!i&&!a)throw new Error("Unknown error finalizing input");i&&(n.finalScriptSig=i),a&&(n.finalScriptWitness=a),this.cleanFinalInput(n)}finalize(){for(let t=0;t<this.inputs.length;t++)this.finalizeIdx(t)}extract(){if(!this.isFinal)throw new Error("Transaction has unfinalized inputs");if(!this.outputs.length)throw new Error("Transaction has no outputs");if(this.fee<qo)throw new Error("Outputs spends more than inputs amount");return this.toBytes(!0,!0)}combine(t){if(!(t instanceof e))throw new TypeError('"other" expected Transaction, got type='+typeof t);let n=this.opts,r=Math.max(this.opts.PSBTVersion||0,t.opts.PSBTVersion||0);if(this.opts.version!==t.opts.version)throw new Error(`Transaction/combine: different version this=${this.opts.version} other=${t.opts.version}`);let o=this.isPSBTv2(),s=t.isPSBTv2();if(!o||!s){let y=this.lockTime,S=t.lockTime;if(y!==S)throw new Error(`Transaction/combine: different lockTime this=${y} other=${S}`)}for(let y of["inputs","outputs"])if(this[y].length!==t[y].length)throw new Error(`Transaction/combine: different ${y} length this=${this[y].length} other=${t[y].length}`);let i=this.unsignedTx;if(!Y(i,t.unsignedTx))throw new Error("Transaction/combine: different unsigned tx");let a;if(o&&s){let y=N=>N.global.txModifiable!==void 0?dn(N.global.txModifiable,n.unknown):n.allowMissingTxModifiable?N.modifiable(!0,n.unknown):0,S=y(this),P=y(t);if((S&-8)!==(P&-8))throw new Error("Transaction/combine: conflicting unknown txModifiable flags");a=S&-8|S&P&3|(S|P)&4,a===0&&this.global.txModifiable===void 0&&t.global.txModifiable===void 0&&!n.allowMissingTxModifiable&&(a=void 0)}else o?a=this.modifiable(n.allowMissingTxModifiable,n.unknown):s&&(a=t.modifiable(n.allowMissingTxModifiable,n.unknown));let c={...this.global},f={...t.global};o!==s&&(o||delete c.fallbackLocktime,s||delete f.fallbackLocktime,o||delete c.version,s||delete f.version);let u=c.fallbackLocktime!==void 0?c.fallbackLocktime:f.fallbackLocktime;delete c.txModifiable,delete f.txModifiable,delete c.fallbackLocktime,delete f.fallbackLocktime;let l=Ur(Or,c,f,n.unknown,n.proprietary);u!==void 0&&(l.fallbackLocktime=u),r&&(l.version=r),a===void 0?delete l.txModifiable:l.txModifiable=a;let d=!1,p=this.inputs.map((y,S)=>{let P=this.inputStatus(S)==="finalized",N=t.inputStatus(S)==="finalized";if((!o&&P||!s&&N)&&(d=!0),P&&N)for(let D of["finalScriptSig","finalScriptWitness"]){let L=!!this.inputs[S][D]?.length,w=!!t.inputs[S][D]?.length;if(L!==w)throw new Error(`Transaction/combine: different finalized field=${D} input=${S}`)}let O=Ur(Ft,y,t.inputs[S],n.unknown,n.proprietary);return(P||N)&&xa(O,n.unknown,n.proprietary),rt(Go(O,void 0,void 0,n.disableScriptCheck,n.unknown,n.proprietary))});d&&l.txModifiable!==void 0&&(l.txModifiable&=-4);let h=new e({...n,PSBTVersion:r}),g=this.outputs.map((y,S)=>{let P=Ur(un,y,t.outputs[S],n.unknown,n.proprietary);return rt(h.normalizeOutput(P))});if(h.global=l,h.inputs=p,h.outputs=g,(!o||!s)&&h.isPSBTv2()&&(h.global.txModifiable=h.txModifiable),!Y(h.unsignedTx,i))throw new Error("Transaction/combine: combined unsigned tx differs");return this.global=h.global,this.inputs=h.inputs,this.outputs=h.outputs,this}clone(){return e.fromPSBT(this.toPSBT(),this.opts)}};var Dn=Ro,ka="tn_wallet_device_key",It=null,Fn=e=>Cr(Ve.getPublicKey(e,!0),Dn).address;var Qo=()=>{It=null};async function Ba(e,t){let n=await crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:t,info:new TextEncoder().encode("tradenook wallet v1")},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function va(e,t){let n=ze(crypto.getRandomValues(new Uint8Array(32))),r=await Kn({challenge:n,rpId:location.hostname},t,e);return{prf:r.prf?new Uint8Array(r.prf):null,credId:r.body.id}}async function Pa(){let e=Ve.utils.randomSecretKey(),t=crypto.getRandomValues(new Uint8Array(32)),{prf:n,credId:r}=await va(t);if(n){let o=await Ba(n,t),s=crypto.getRandomValues(new Uint8Array(12)),i=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:s},o,e)),a=new Uint8Array(s.length+i.length);return a.set(s),a.set(i,s.length),await Z("/vault",{cred:r,blob:ze(a),salt:ze(t)}),It=e,{address:Fn(e),where:"passkey"}}try{localStorage.setItem(ka,ze(e))}catch{}return It=e,{address:Fn(e),where:"device"}}async function rl(e){if(It&&Fn(It)===e)return It;let t=null;try{t=localStorage.getItem(ka)}catch{}if(t){let c=wt(t);if(Fn(c)===e)return It=c,c}let n=await Z("/vault"),r=wt(n.salt),{prf:o}=await va(r,n.cred);if(!o)throw new Error("This browser couldn\u2019t open your wallet with your passkey. Try Chrome, Safari or Edge on the device where you made it.");let s=wt(n.blob),i=await Ba(o,r),a;try{a=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:s.slice(0,12)},i,s.slice(12)))}catch{throw new Error("That passkey didn\u2019t open this wallet. Use the passkey you made it with.")}if(Fn(a)!==e)throw new Error("That wallet doesn\u2019t match your account address.");return It=a,a}async function Aa(e){return Z(`/chain/balance/${e}`)}async function jr(e,t){let n=await rl(e),r=Ve.getPublicKey(n,!0),o=Cr(r,Dn).script,s=await Z(`/chain/utxo/${e}`),{rate:i}=await Z("/chain/fees"),a=t.reduce((h,g)=>h+g.sats,0);s.sort((h,g)=>g.value-h.value);let c=[],f=0,u=0;for(let h of s)if(c.push(h),f+=h.value,u=Math.ceil((11+68*c.length+31*(t.length+1))*i),f>=a+u)break;if(f<a+u)throw new Error(`Not enough test coins. You need ${(a+u).toLocaleString("en-US")} sats including the network fee, and have ${f.toLocaleString("en-US")}.`);let l=new pn;for(let h of c)l.addInput({txid:h.txid,index:h.vout,witnessUtxo:{script:o,amount:BigInt(h.value)}});for(let h of t)l.addOutputAddress(h.address,BigInt(h.sats),Dn);let d=f-a-u;return d>546&&l.addOutputAddress(e,BigInt(d),Dn),l.sign(n),l.finalize(),(await Z("/chain/tx",{hex:l.hex})).txid}function Jo(e){try{return jt(Dn).decode(e),e.toLowerCase().startsWith("tb1")}catch{return!1}}var Le=document.getElementById("app"),il=document.getElementById("mnav"),se=null,Kr=null,$=e=>String(e??"").replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]),Me=e=>`${Math.round(e).toLocaleString("en-US")} sats`,Ia=e=>`${(e/1e8).toFixed(8).replace(/0+$/,"").replace(/\.$/,"")} test BTC`,$a=e=>new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"}),Ge=e=>{location.hash=e},J=(e,t=Le)=>t.querySelector(e),ti={local:"Local pickup",ship:"Ships (small item)",consign:"At a nook"},La={awaiting_payment:"Waiting for payment",paid:"Paid",shipped:"Shipped",received:"Received, needs ratings",rating:"Waiting for the other rating",complete:"Complete",cancelled:"Cancelled"},zr=e=>"\u2605\u2605\u2605\u2605\u2605".slice(0,Math.round(e))+"\u2606\u2606\u2606\u2606\u2606".slice(0,5-Math.round(e));function jn(e,t=!1){let n=e.count?`${e.score.toFixed(1)} honesty \xB7 ${e.count} rating${e.count===1?"":"s"}`:"New, no ratings yet";return`<span class="tier tier-${e.tier.toLowerCase()}">${e.tier}</span>${t?"":` <span class="mut">${n}</span>`}`}function hn(e,t=0,n=""){return`<img src="/api/photo/${$(e)}/${t}" alt="${$(n)}" loading="lazy">`}function ni(e,t=4){let n=ci(0,"M");return n.addData(e),n.make(),n.createSvgTag({cellSize:t,margin:2,scalable:!0})}function $e(e,t="err"){let n=document.getElementById("flash");n.textContent=e,n.className="flash show "+t,clearTimeout(n._t),n._t=setTimeout(()=>n.className="flash",6e3)}async function Be(e,t){let n=e?.textContent;e&&(e.disabled=!0,e.textContent="Working\u2026");try{await t()}catch(r){let o=r instanceof Error?r.message:String(r);$e(/NotAllowedError|cancel|timed out/i.test(o)?"The passkey step was cancelled. Try again when you\u2019re ready.":o)}finally{e&&e.isConnected&&(e.disabled=!1,e.textContent=n)}}function sl(e,t,n){Le.querySelectorAll(e).forEach(r=>r.addEventListener(t,o=>n(o,r)))}async function Lt(){try{se=await Z("/me")}catch(e){if(e instanceof Ut&&e.status===401)se=null;else throw e}Wr()}function Wr(){let e=se?.owedRatings.length?`<span class="dot-n">${se.owedRatings.length}</span>`:"";il.innerHTML='<a href="#/">Browse</a><a href="#/sell">List an item</a>'+(se?`<a href="#/trades">Trades${e}</a><a href="#/wallet">Wallet</a><a href="#/me">${$(se.user.name)}</a>`:'<a href="#/signin" class="pill-s">Sign in</a>')}function _t(){return se?!1:(sessionStorage.setItem("tn_after",location.hash),Ge("#/signin"),!0)}function _a(){return!se||se.user.walletAddress?!1:(sessionStorage.setItem("tn_after",location.hash),Ge("#/wallet"),$e("Set up your wallet first. It\u2019s where you pay and get paid.","ok"),!0)}async function al(e){let t=e.get("q")||"",n=e.get("mode")||"",r=e.get("category")||"",o=Kr.categories.map(a=>`<option${a===r?" selected":""}>${$(a)}</option>`).join("");Le.innerHTML=` |
| 4 | <section class="mhead"><div> |
| 5 | <h1>Trade with your neighbors.</h1> |
| 6 | <p class="lede">No price tags. Make one honest offer in Bitcoin. The first offer the seller will take gets it, with no haggling.</p> |
| 7 | </div><a class="pill" href="#/sell">List an item</a></section> |
| 8 | <form class="filters" id="f"> |
| 9 | <input name="q" type="search" placeholder="Search items or towns" value="${$(t)}" aria-label="Search"> |
| 10 | <select name="mode" aria-label="How it trades"><option value="">Any way</option>${Object.entries(ti).map(([a,c])=>`<option value="${a}"${a===n?" selected":""}>${c}</option>`).join("")}</select> |
| 11 | <select name="category" aria-label="Category"><option value="">All kinds</option>${o}</select> |
| 12 | <button class="pill">Search</button> |
| 13 | </form> |
| 14 | <div id="grid" class="grid"><p class="mut">Loading\u2026</p></div> |
| 15 | ${cl()}`,J("#f").addEventListener("submit",a=>{a.preventDefault();let c=new FormData(a.target),f=new URLSearchParams;for(let[u,l]of c)l&&f.set(u,String(l));Ge("#/?"+f.toString())});let s=new URLSearchParams({q:t,mode:n,category:r}),{listings:i}=await Z("/listings?"+s.toString());J("#grid").innerHTML=i.length?i.map(ri).join(""):'<div class="empty"><h3>Nothing here yet.</h3><p>Be the first in your neighborhood. Listing takes a minute.</p><a class="pill" href="#/sell">List an item</a></div>'}function ri(e){return`<a class="card" href="#/item/${$(e.id)}"><div class="ph">${hn(e.id,0,e.title)}</div><div class="cb"> |
| 16 | <h3>${$(e.title)}</h3> |
| 17 | <p class="mut">${$(ti[e.mode])}${e.mode!=="ship"&&e.city?" \xB7 "+$(e.city):""}</p> |
| 18 | ${e.seller?`<p class="sl">${$(e.seller.name)} ${jn(e.seller.trust,!0)}</p>`:""} |
| 19 | </div></a>`}function cl(){return`<section class="rules"><h2>How the market works</h2><div class="rgrid"> |
| 20 | <div><h3>One offer, no haggling</h3><p>Nothing has a price tag. You offer what it\u2019s worth to you, once. The first offer that meets the seller\u2019s private minimum takes the item.</p></div> |
| 21 | <div><h3>Paid in Bitcoin</h3><p>Every trade is paid in Bitcoin, straight to the seller\u2019s wallet. We check the payment on the network. While we test, it uses test coins with no value.</p></div> |
| 22 | <div><h3>Every trade is rated</h3><p>Both people rate each other for honesty after every trade, and every rating is public. You rate your last trade before you make your next offer.</p></div> |
| 23 | <div><h3>Trust pays</h3><p>Ratings build your tier: Explorer, Builder, then Guide. At a nook, consignment starts at a 50-50 split and the seller\u2019s share rises to 55% and then 60% as their tier goes up.</p></div> |
| 24 | <div><h3>Local first</h3><p>Meet a neighbor, or leave it at a nook on consignment. Small items can ship, in one of three standard boxes with a printed label.</p></div> |
| 25 | <div><h3>Say thanks</h3><p>Got more than you hoped for? After rating, a slider lets the buyer send the seller any extra amount, up to the full trade.</p></div> |
| 26 | </div><p class="mut small">Open rating data: <a href="/api/ratings.json">every rating</a>. Open source code, free to copy.</p></section>`}async function fl(e){let t=await Z(`/listings/${e}`),n=t.listing,r=Array.from({length:n.photos},(c,f)=>`<button class="th" data-i="${f}" aria-label="Photo ${f+1}">${hn(n.id,f)}</button>`).join(""),o="";t.tradeId?o=`<a class="pill" href="#/trade/${$(t.tradeId)}">Go to your trade</a>`:t.mine?o=`<div class="box"><h3>Your item</h3> |
| 27 | <p>${n.status==="open"?"Waiting for an offer.":"Status: "+$(n.status)}</p> |
| 28 | <p class="mut">Private minimum: ${t.floorSats?Me(t.floorSats):"none (the first offer takes it)"}. Offers below it: ${t.declinedOffers||0}.</p> |
| 29 | ${n.status==="open"?'<button class="pill ghost" id="wd">Take it down</button>':""}</div>`:t.myOffer?o=`<div class="box"><h3>Your offer: ${Me(t.myOffer.sats)}</h3><p>${t.myOffer.status==="won"?"Your offer took it.":"It was below what the seller will take. Each person gets one offer per item."}</p></div>`:n.status==="open"?o=`<form class="box" id="offer"><h3>Make your one offer</h3> |
| 30 | <p class="mut">Offer what it\u2019s worth to you, in sats (1 test BTC = 100,000,000 sats). If it meets the seller\u2019s private minimum, it\u2019s yours right away. You get one offer, and there\u2019s no haggling.</p> |
| 31 | <label class="fld"><span>Your offer (sats)</span><input name="sats" inputmode="numeric" pattern="[0-9,]*" required placeholder="50,000"></label> |
| 32 | <p class="mut small" id="oc"></p> |
| 33 | <button class="pill">Make my offer</button></form>`:o='<div class="box"><p>Someone\u2019s offer already took this item.</p></div>';let s=n.mode==="ship"?`<p><b>Ships.</b> ${$(n.boxLabel)}. After you pay, you add your address and the seller prints a label.</p>`:n.mode==="consign"?`<p><b>At a nook, on consignment.</b> Pick it up at the ${$(n.city)} nook after you pay. Your payment is split between the seller and the nook in one transaction.</p>`:`<p><b>Local pickup</b> in ${$(n.city)}. After you pay, you and the seller set a time and a public place to meet.</p>`;Le.innerHTML=`<p class="crumbs"><a href="#/">\u2190 Browse</a></p> |
| 34 | <div class="item"> |
| 35 | <div class="gal"><div class="big" id="big">${hn(n.id,0,n.title)}</div>${n.photos>1?`<div class="ths">${r}</div>`:""}</div> |
| 36 | <div class="info"> |
| 37 | <p class="kick">${$(n.category)} \xB7 ${$(n.condition)}</p> |
| 38 | <h1>${$(n.title)}</h1> |
| 39 | <p class="desc">${$(n.description).replace(/\n/g,"<br>")}</p> |
| 40 | ${s} |
| 41 | <a class="seller" href="#/u/${$(t.seller.id)}"><b>${$(t.seller.name)}</b> ${jn(t.seller.trust)}</a> |
| 42 | ${o} |
| 43 | </div> |
| 44 | </div>`,sl(".th","click",(c,f)=>{J("#big").innerHTML=hn(n.id,Number(f.dataset.i),n.title)});let i=J("#wd");i&&i.addEventListener("click",()=>Be(i,async()=>{await Z(`/listings/${n.id}/withdraw`,{}),$e("Taken down.","ok"),dt()}));let a=J("#offer");if(a){let c=a.querySelector("input");c.addEventListener("input",()=>{let f=Number(c.value.replace(/[^0-9]/g,""));J("#oc").textContent=f?Ia(f):""}),a.addEventListener("submit",f=>{if(f.preventDefault(),_t()||_a())return;let u=Number(c.value.replace(/[^0-9]/g,"")),l=a.querySelector("button");Be(l,async()=>{let d=await Z(`/listings/${n.id}/offer`,{sats:u});d.won?($e("Your offer took it! Next, pay the seller.","ok"),Ge("#/trade/"+d.tradeId)):($e(d.message||"Not accepted."),dt())})})}}function ll(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{let s=Math.min(1,1200/Math.max(r.width,r.height)),i=document.createElement("canvas");i.width=Math.round(r.width*s),i.height=Math.round(r.height*s),i.getContext("2d").drawImage(r,0,0,i.width,i.height);let a=.82,c=i.toDataURL("image/jpeg",a);for(;c.length>56e4&&a>.4;)a-=.1,c=i.toDataURL("image/jpeg",a);URL.revokeObjectURL(r.src),t(c)},r.onerror=()=>n(new Error("We couldn\u2019t read that photo. Try a JPEG or PNG.")),r.src=URL.createObjectURL(e)})}async function ul(){if(_t()||_a())return;let e=Kr,t=se.trust.sellerPct;Le.innerHTML=`<p class="crumbs"><a href="#/">\u2190 Browse</a></p> |
| 45 | <h1>List an item</h1> |
| 46 | <p class="lede">No price tag. Buyers make one offer each, and the first one that meets your private minimum takes it.</p> |
| 47 | <form id="sell" class="form"> |
| 48 | <div class="fld"><span>Photos (1 to 4)</span><div class="photos" id="pv"></div><input type="file" id="pf" accept="image/*" multiple></div> |
| 49 | <label class="fld"><span>What is it?</span><input name="title" maxlength="80" required placeholder="Brass desk lamp"></label> |
| 50 | <label class="fld"><span>Describe it honestly, flaws included</span><textarea name="description" rows="4" maxlength="2000" required placeholder="Works well. Small dent on the base. Bulb included."></textarea></label> |
| 51 | <div class="row2"> |
| 52 | <label class="fld"><span>Kind</span><select name="category" required><option value="">Pick one</option>${e.categories.map(i=>`<option>${$(i)}</option>`).join("")}</select></label> |
| 53 | <label class="fld"><span>Condition</span><select name="condition" required><option value="">Pick one</option>${e.conditions.map(i=>`<option>${$(i)}</option>`).join("")}</select></label> |
| 54 | </div> |
| 55 | <fieldset class="fld modes"><legend>How will it trade?</legend> |
| 56 | <label><input type="radio" name="mode" value="local" checked><b>Local pickup</b><span>Meet the buyer in a public place.</span></label> |
| 57 | <label><input type="radio" name="mode" value="consign"><b>Consign at a nook</b><span>Leave it at your local nook. You keep ${t}% of the offer and the nook keeps ${100-t}%. Your share rises as your trust tier goes up.</span></label> |
| 58 | <label><input type="radio" name="mode" value="ship"><b>Ship it (small items only)</b><span>Fits one of our three standard boxes. You print the label here.</span></label> |
| 59 | </fieldset> |
| 60 | <label class="fld" id="boxf" hidden><span>Which box does it fit?</span><select name="box">${Object.entries(e.boxes).map(([i,a])=>`<option value="${i}">${$(a)}</option>`).join("")}</select></label> |
| 61 | <label class="fld" id="cityf"><span>Town or neighborhood</span><input name="city" maxlength="60" value="${$(se.user.city)}" placeholder="Ballard, Seattle"></label> |
| 62 | <label class="fld"><span>Private minimum in sats (optional, never shown)</span><input name="floorSats" inputmode="numeric" placeholder="Leave blank to take the first offer"></label> |
| 63 | <button class="pill">List it</button> |
| 64 | </form>`;let n=[],r=J("#pv"),o=()=>{r.innerHTML=n.map((i,a)=>`<div class="pp"><img src="${i}" alt=""><button type="button" data-i="${a}" aria-label="Remove photo">\xD7</button></div>`).join(""),r.querySelectorAll("button").forEach(i=>i.addEventListener("click",()=>{n.splice(Number(i.dataset.i),1),o()}))};J("#pf").addEventListener("change",async i=>{let a=Array.from(i.target.files||[]);for(let c of a){if(n.length>=4)break;try{n.push(await ll(c))}catch(f){$e(f.message)}}i.target.value="",o()});let s=J("#sell");s.addEventListener("change",()=>{let i=s.elements.namedItem("mode").value;J("#boxf").hidden=i!=="ship",J("#cityf").hidden=i==="ship"}),s.addEventListener("submit",i=>{i.preventDefault();let a=Object.fromEntries(new FormData(s));Be(s.querySelector("button.pill"),async()=>{let c=await Z("/listings",{...a,floorSats:a.floorSats?Number(a.floorSats.replace(/[^0-9]/g,"")):"",photos:n});$e("Listed! Neighbors can make offers now.","ok"),Ge("#/item/"+c.id)})})}async function dl(){if(se){Ge("#/me");return}let e=fi();Le.innerHTML=`<div class="auth"> |
| 65 | <h1>Sign in with a passkey</h1> |
| 66 | <p class="lede">Your face, fingerprint or screen lock is your key. No passwords, no email, nothing to remember.</p> |
| 67 | ${e?"":'<p class="warn">This browser doesn\u2019t support passkeys. Try a recent Chrome, Safari, Edge or Firefox.</p>'} |
| 68 | <div class="two"> |
| 69 | <div class="box"><h3>I\u2019m new here</h3> |
| 70 | <form id="reg"><label class="fld"><span>Name neighbors will see</span><input name="name" maxlength="40" required placeholder="Sam R."></label><button class="pill">Create my passkey</button></form></div> |
| 71 | <div class="box"><h3>I\u2019ve been here before</h3><p class="mut">Use the passkey you made on Tradenook.</p><button class="pill" id="login">Sign in</button></div> |
| 72 | </div></div>`;let t=()=>{let r=sessionStorage.getItem("tn_after");sessionStorage.removeItem("tn_after"),Ge(r&&r!=="#/signin"?r:"#/")};J("#reg").addEventListener("submit",r=>{r.preventDefault();let o=new FormData(r.target).get("name").trim();Be(r.target.querySelector("button"),async()=>{let s=await Z("/auth/register/start",{name:o}),i=await li(s.options);await Z("/auth/register/finish",{cid:s.cid,...i}),await Lt(),$e(`Welcome, ${o}! Next, set up your wallet.`,"ok"),Ge("#/wallet")})});let n=J("#login");n.addEventListener("click",()=>Be(n,async()=>{let r=await Z("/auth/login/start",{}),o=await Kn(r.options);await Z("/auth/login/finish",{cid:r.cid,...o.body}),await Lt(),$e("Signed in.","ok"),t()}))}async function ei(){if(_t())return;let e=se.user;if(!e.walletAddress){Le.innerHTML=`<h1>Your wallet</h1> |
| 73 | <p class="lede">Every trade is paid in Bitcoin. While we test, the market runs on Bitcoin signet: test coins with no value.</p> |
| 74 | <div class="two"> |
| 75 | <div class="box"><h3>Create a wallet for me</h3><p>We make a wallet right here in your browser and lock its backup with your passkey. We store only the locked box and can never open it. No recovery words to write down.</p><button class="pill" id="mk">Create my wallet</button></div> |
| 76 | <form class="box" id="own"><h3>Use my own wallet</h3><p>Paste a receiving address from a wallet you already use. For testing, it must be a signet address starting with tb1.</p><label class="fld"><span>Your address</span><input name="address" required placeholder="tb1q\u2026" autocomplete="off" spellcheck="false"></label><button class="pill ghost">Use this address</button></form> |
| 77 | </div>`;let r=J("#mk");r.addEventListener("click",()=>Be(r,async()=>{let o=await Pa();await Z("/wallet",{kind:"mine",address:o.address}),await Lt(),$e(o.where==="passkey"?"Your wallet is ready and locked with your passkey.":"Your wallet is ready. This browser can\u2019t lock it with a passkey, so it lives on this device only.","ok");let s=sessionStorage.getItem("tn_after");sessionStorage.removeItem("tn_after"),s?Ge(s):dt()})),J("#own").addEventListener("submit",o=>{o.preventDefault();let s=new FormData(o.target).get("address").trim();Be(o.target.querySelector("button"),async()=>{if(!Jo(s))throw new Error("That address doesn\u2019t check out. Use a signet address starting with tb1.");await Z("/wallet",{kind:"own",address:s}),await Lt(),$e("Saved. Buyers will pay this address.","ok");let i=sessionStorage.getItem("tn_after");sessionStorage.removeItem("tn_after"),i?Ge(i):dt()})});return}let t=e.walletKind==="mine";Le.innerHTML=`<h1>Your wallet</h1> |
| 78 | <p class="warn">Test mode: Bitcoin signet. These coins have no value.</p> |
| 79 | <div class="two"> |
| 80 | <div class="box"><h3>Balance</h3><p class="bal" id="bal">Checking\u2026</p> |
| 81 | <p class="mut small">Need test coins? Get free ones from a <a href="https://signetfaucet.com" target="_blank" rel="noopener">signet faucet</a>.</p></div> |
| 82 | <div class="box"><h3>Receive</h3><div class="qr">${ni("bitcoin:"+e.walletAddress)}</div><p class="addr">${$(e.walletAddress)}</p><button class="pill ghost" id="cp">Copy address</button></div> |
| 83 | </div> |
| 84 | ${t?`<form class="box" id="send"><h3>Send</h3><p class="mut">Your passkey unlocks the wallet for each payment.</p> |
| 85 | <div class="row2"><label class="fld"><span>To address</span><input name="to" required placeholder="tb1q\u2026" spellcheck="false"></label> |
| 86 | <label class="fld"><span>Amount (sats)</span><input name="sats" inputmode="numeric" required></label></div><button class="pill">Send</button></form>`:'<div class="box"><p>This is your own wallet. Send from the wallet app you use.</p></div>'} |
| 87 | <details class="box"><summary>Change wallet</summary><p class="mut">Switch to a new address. Trades waiting for payment move to the new address too.${t?" Move your coins out first.":""}</p><button class="pill ghost" id="chg">Set up a different wallet</button></details>`,Aa(e.walletAddress).then(r=>{J("#bal").innerHTML=`${Me(r.confirmed)}${r.pending?`<span class="mut small"> + ${Me(r.pending)} arriving</span>`:""}`}).catch(()=>{J("#bal").textContent="Couldn\u2019t reach the network."}),J("#cp").addEventListener("click",()=>{navigator.clipboard?.writeText(e.walletAddress),$e("Address copied.","ok")}),J("#chg").addEventListener("click",()=>{se.user.walletAddress="",Qo(),ei()});let n=J("#send");n&&n.addEventListener("submit",r=>{r.preventDefault();let o=new FormData(n),s=String(o.get("to")).trim(),i=Number(String(o.get("sats")).replace(/[^0-9]/g,""));Be(n.querySelector("button"),async()=>{if(!Jo(s))throw new Error("That address doesn\u2019t check out.");let a=await jr(e.walletAddress,[{address:s,sats:i}]);$e("Sent. Transaction "+a.slice(0,12)+"\u2026","ok"),ei()})})}async function pl(){if(_t())return;let{trades:e}=await Z("/trades");Le.innerHTML=`<h1>Your trades</h1>${e.length?`<div class="list">${e.map(t=>`<a class="li" href="#/trade/${$(t.id)}"><div class="lph">${hn(t.listingId,0)}</div><div><b>${$(t.title)}</b><p class="mut">${t.role==="buyer"?"You\u2019re buying":"You\u2019re selling"} \xB7 ${Me(t.sats)}</p></div><span class="st st-${$(t.status)}">${$(La[t.status]||t.status)}</span></a>`).join("")}</div>`:'<div class="empty"><h3>No trades yet.</h3><p>Find something you like and make an offer.</p><a class="pill" href="#/">Browse</a></div>'}`}async function hl(e){if(_t())return;let t=await Z(`/trades/${e}`),n=t.trade,r=t.listing,o=n.role==="buyer",s=o?t.seller:t.buyer,i=t.ratings.find(O=>O.from_id===se.user.id),a=t.ratings.find(O=>O.from_id!==se.user.id),c=[{address:n.sellerAddress,sats:n.sellerSats},...n.nookSats>0?[{address:n.nookAddress,sats:n.nookSats}]:[]],f=["awaiting_payment","paid",...n.mode==="ship"?["shipped"]:[],"received","complete"],u=n.status==="rating"?f.indexOf("received"):f.indexOf(n.status),l=n.status==="cancelled"?"":`<ol class="steps">${f.map((O,D)=>`<li class="${D<u||n.status==="complete"?"done":D===u?"now":""}">${{awaiting_payment:"Pay",paid:"Paid",shipped:"Shipped",received:"Received",complete:"Rated"}[O]}</li>`).join("")}</ol>`,d="";if(n.status==="cancelled")d='<div class="box"><p>This trade was cancelled before payment.</p></div>';else if(n.status==="awaiting_payment")if(o){let O=n.mode==="ship"?`<form class="fld" id="shipto"><span>Ship to (only the seller sees this)</span><textarea name="shipTo" rows="4" required placeholder="Name Street City, State ZIP">${$(n.shipTo)}</textarea><button class="pill ghost">${n.shipTo?"Update address":"Save address"}</button></form>`:"";d=`<div class="box"><h3>Pay ${Me(n.sats)}</h3> |
| 88 | ${n.nookSats?`<p>This is a consignment trade, so one payment goes to two places: <b>${Me(n.sellerSats)}</b> to the seller (${n.sellerPct}%) and <b>${Me(n.nookSats)}</b> to the nook.</p>`:`<p>Paid straight to ${$(t.seller.name)}\u2019s wallet.</p>`} |
| 89 | ${O} |
| 90 | ${se.user.walletKind==="mine"?'<button class="pill" id="paynow">Pay from my wallet</button>':""} |
| 91 | <details><summary>Pay from another wallet</summary> |
| 92 | ${c.map(D=>`<p class="addr">${Me(D.sats)} \u2192 ${$(D.address)}</p>`).join("")} |
| 93 | <div class="qr sm">${ni(`bitcoin:${n.sellerAddress}?amount=${(n.sellerSats/1e8).toFixed(8)}`,3)}</div> |
| 94 | <form id="txf"><label class="fld"><span>Transaction ID after you pay</span><input name="txid" required pattern="[0-9a-fA-F]{64}" spellcheck="false"></label><button class="pill ghost">I paid</button></form> |
| 95 | </details> |
| 96 | <button class="link" id="cancel">Cancel this trade</button></div>`}else d=`<div class="box"><h3>Waiting for ${$(t.buyer.name)} to pay ${Me(n.sats)}</h3><p class="mut">You\u2019ll get ${Me(n.sellerSats)} at ${$(n.sellerAddress)}.</p><button class="link" id="cancel">Cancel this trade</button></div>`;else if(n.status==="paid"||n.status==="shipped"){let O=`<p class="mut small">Payment: <a href="https://mempool.space/signet/tx/${$(n.txid)}" target="_blank" rel="noopener">${$(n.txid.slice(0,16))}\u2026</a></p>`;if(n.mode==="ship")!o&&n.status==="paid"?d=`<div class="box"><h3>Pack and ship</h3><p>Box: <b>${$(t.box)}</b>.</p><a class="pill" href="#/label/${$(n.id)}">Print the shipping label</a> |
| 97 | <form id="shipped"><label class="fld"><span>Carrier tracking number (optional)</span><input name="tracking" maxlength="60"></label><button class="pill ghost">Mark as shipped</button></form>${O}</div>`:o?d=`<div class="box"><h3>${n.status==="shipped"?"On its way":"Paid. The seller is packing it."}</h3>${n.tracking?`<p>Tracking: ${$(n.tracking)}</p>`:""}<button class="pill" id="recv">It arrived</button>${O}</div>`:d=`<div class="box"><h3>Shipped</h3><p>Tracking: ${$(n.tracking||"none given")}. Waiting for ${$(t.buyer.name)} to confirm it arrived.</p>${O}</div>`;else{let D=n.mode==="consign"?`Pick it up at the ${$(r.city)} nook.`:`Set a time and a public place in ${$(r.city)} to meet.`;d=o?`<div class="box"><h3>Paid. ${D}</h3><p>Once it\u2019s in your hands and it\u2019s as described, tap below.</p><button class="pill" id="recv">I have it</button>${O}</div>`:`<div class="box"><h3>Paid. ${n.mode==="consign"?"The nook will hand it over.":"Meet the buyer to hand it over."}</h3><p class="mut">${$(t.buyer.name)} confirms when they have it, then you both rate.</p>${O}</div>`}}else(n.status==="received"||n.status==="rating"||n.status==="complete")&&(i?d=`<div class="box"><h3>${n.status==="complete"?"Trade complete":`Waiting for ${$(s.name)}\u2019s rating`}</h3><p>You gave ${zr(i.honest)} for honesty.</p>${a?`<p>${$(s.name)} gave you ${zr(a.honest)}.</p>`:""}</div>`:d=`<form class="box" id="rate"><h3>Rate ${$(s.name)}</h3><p class="mut">Ratings are public and every trade needs one from both sides.</p> |
| 98 | <div class="fld"><span>How honest were they?</span>${Oa("honest")}</div> |
| 99 | <div class="fld"><span>${o?"Was the item as described?":"Did they do what they said (pay, show up, be fair)?"}</span>${Oa("described")}</div> |
| 100 | <label class="fld"><span>A few words (optional, public)</span><textarea name="note" rows="2" maxlength="500"></textarea></label><button class="pill">Post my rating</button></form>`,o&&i&&!n.thanksTxid&&(d+=`<form class="box" id="thanks"><h3>Got more than you hoped for?</h3><p class="mut">Send ${$(t.seller.name)} any extra amount, up to the full trade. It\u2019s optional, and it goes straight to them.</p> |
| 101 | <input type="range" name="pct" min="0" max="100" value="0" step="1" aria-label="Extra amount"><p class="bal" id="tv">0 sats</p> |
| 102 | ${se.user.walletKind==="mine"?'<button class="pill" id="thx">Send extra</button>':`<p class="addr">${$(n.sellerAddress)}</p><label class="fld"><span>Transaction ID after you send</span><input name="txid" pattern="[0-9a-fA-F]{64}"></label><button class="pill" id="thx">I sent it</button>`}</form>`),n.thanksTxid&&(d+=`<div class="box"><p>${o?"You":$(t.buyer.name)} sent ${Me(n.thanksSats)} extra. Thank you!</p></div>`));Le.innerHTML=`<p class="crumbs"><a href="#/trades">\u2190 Your trades</a></p> |
| 103 | <div class="trade"><div class="tph">${hn(r.id,0,r.title)}</div><div> |
| 104 | <p class="kick">${$(ti[n.mode])} \xB7 ${$(La[n.status]||n.status)}</p> |
| 105 | <h1>${$(r.title)}</h1> |
| 106 | <p>${o?"You\u2019re buying from":"You\u2019re selling to"} <a href="#/u/${$(s.id)}">${$(s.name)}</a> ${jn(s.trust)}</p> |
| 107 | <p class="big">${Me(n.sats)} <span class="mut small">${Ia(n.sats)}</span></p> |
| 108 | </div></div>${l}${d}`;let p=(O,D,L)=>async()=>{await Z(`/trades/${n.id}/${O}`,D),$e(L,"ok"),await Lt(),dt()},h=O=>J("#"+O);h("cancel")&&h("cancel").addEventListener("click",()=>Be(h("cancel"),p("cancel",{},"Trade cancelled. The item is open for offers again."))),h("paynow")&&h("paynow").addEventListener("click",()=>Be(h("paynow"),async()=>{if(n.mode==="ship"&&!n.shipTo)throw new Error("Add your shipping address first.");let O=await jr(se.user.walletAddress,c);await new Promise(D=>setTimeout(D,1500)),await Z(`/trades/${n.id}/paid`,{txid:O}),$e("Paid! The seller has been told.","ok"),dt()}));let g=J("#shipto");g&&g.addEventListener("submit",O=>{O.preventDefault(),Be(g.querySelector("button"),p("ship-to",{shipTo:new FormData(g).get("shipTo")},"Address saved."))});let y=J("#txf");y&&y.addEventListener("submit",O=>{O.preventDefault(),Be(y.querySelector("button"),p("paid",{txid:String(new FormData(y).get("txid")).trim()},"Payment found. Thank you!"))});let S=J("#shipped");S&&S.addEventListener("submit",O=>{O.preventDefault(),Be(S.querySelector("button"),p("shipped",{tracking:new FormData(S).get("tracking")},"Marked as shipped."))}),h("recv")&&h("recv").addEventListener("click",()=>Be(h("recv"),p("received",{},"Great. Now rate the trade.")));let P=J("#rate");P&&P.addEventListener("submit",O=>{O.preventDefault();let D=new FormData(P);Be(P.querySelector("button.pill"),p("rate",{honest:Number(D.get("honest")),described:Number(D.get("described")),note:D.get("note")},"Rating posted. Thank you!"))});let N=J("#thanks");if(N){let O=N.querySelector("input[type=range]"),D=()=>Math.floor(n.sats*Number(O.value)/100);O.addEventListener("input",()=>{J("#tv").textContent=`${Me(D())} (${O.value}% of the trade)`}),N.addEventListener("submit",L=>{L.preventDefault(),Be(h("thx"),async()=>{let w=D();if(w<1)throw new Error("Slide to choose an amount first.");let m=String(new FormData(N).get("txid")||"").trim();se.user.walletKind==="mine"&&(m=await jr(se.user.walletAddress,[{address:n.sellerAddress,sats:w}]),await new Promise(b=>setTimeout(b,1500))),await Z(`/trades/${n.id}/thanks`,{sats:w,txid:m}),$e("Sent. That\u2019s kind of you.","ok"),dt()})})}}function Oa(e){return`<div class="stars">${[5,4,3,2,1].map(t=>`<input type="radio" id="${e}${t}" name="${e}" value="${t}" required><label for="${e}${t}" title="${t} star${t>1?"s":""}">\u2605</label>`).join("")}</div>`}async function gl(e){if(_t())return;let t=await Z(`/trades/${e}`),n=t.trade;if(n.role!=="seller"||n.mode!=="ship"){Le.innerHTML="<p>Only the seller of a shipped item can print its label.</p>";return}let r="";try{r=localStorage.getItem("tn_return")||""}catch{}let o=`${location.origin}/market/#/trade/${n.id}`;Le.innerHTML=`<div class="noprint"><p class="crumbs"><a href="#/trade/${$(n.id)}">\u2190 Back to the trade</a></p> |
| 109 | <h1>Shipping label</h1> |
| 110 | <p class="lede">Print on a 4 \xD7 6 in label or plain paper, tape it to the box, and buy postage at your carrier. Pack it in the <b>${$(t.box)}</b>.</p> |
| 111 | <ol class="pack"><li>Wrap the item and fill gaps so nothing moves.</li><li>Use the standard box size above, so every Tradenook package stacks the same.</li><li>Tape every seam, then stick this label on the biggest side.</li><li>Mark it shipped on the trade page, with the tracking number if you have one.</li></ol> |
| 112 | <label class="fld"><span>Your return address (saved only on this device)</span><textarea id="from" rows="3" placeholder="Your name Street City, State ZIP">${$(r)}</textarea></label> |
| 113 | <button class="pill" id="pr">Print label</button></div> |
| 114 | <div class="label" id="lbl"> |
| 115 | <div class="lf"><small>FROM</small><pre id="lfrom">${$(r||t.seller.name)}</pre></div> |
| 116 | <div class="lt"><small>SHIP TO</small><pre>${$(n.shipTo)}</pre></div> |
| 117 | <div class="lb"><div><small>TRADENOOK TRADE</small><b>${$(n.id)}</b><small>Box ${$(t.listing.box)} \xB7 ${$(t.listing.title.slice(0,40))}</small></div><div class="lq">${ni(o,3)}</div></div> |
| 118 | </div>`;let s=J("#from");s.addEventListener("input",()=>{J("#lfrom").textContent=s.value||t.seller.name;try{localStorage.setItem("tn_return",s.value)}catch{}}),J("#pr").addEventListener("click",()=>window.print())}async function wl(){if(_t())return;await Lt();let e=se.user,t=se.trust,{listings:n}=await Z(`/listings?seller=${e.id}`),r=t.tier==="Explorer"?"Builder needs 5 ratings averaging 4.3 or better.":t.tier==="Builder"?"Guide needs 20 ratings averaging 4.6 or better.":"You\u2019re at the top tier.";Le.innerHTML=`<h1>Hi, ${$(e.name)}</h1> |
| 119 | ${se.owedRatings.length?`<p class="warn">You have a trade to rate. Rate it before your next offer. <a href="#/trade/${$(se.owedRatings[0])}">Rate it now</a></p>`:""} |
| 120 | <div class="two"> |
| 121 | <div class="box"><h3>Your trust</h3><p class="bigtier">${jn(t)}</p><p>Consignment split at a nook: <b>you keep ${t.sellerPct}%</b>.</p><p class="mut small">${r}</p><a href="#/u/${$(e.id)}">See your public profile</a></div> |
| 122 | <form class="box" id="prof"><h3>Profile</h3><label class="fld"><span>Name</span><input name="name" value="${$(e.name)}" maxlength="40" required></label><label class="fld"><span>Town or neighborhood</span><input name="city" value="${$(e.city)}" maxlength="60"></label><button class="pill ghost">Save</button></form> |
| 123 | </div> |
| 124 | <h2>Your items</h2> |
| 125 | <div class="grid">${n.length?n.map(ri).join(""):'<p class="mut">Nothing listed yet. <a href="#/sell">List an item</a></p>'}</div> |
| 126 | <p><button class="pill ghost" id="out">Sign out</button></p>`;let o=J("#prof");o.addEventListener("submit",i=>{i.preventDefault(),Be(o.querySelector("button"),async()=>{await Z("/me",Object.fromEntries(new FormData(o))),await Lt(),$e("Saved.","ok")})});let s=J("#out");s.addEventListener("click",()=>Be(s,async()=>{await Z("/auth/logout",{}),Qo(),se=null,Wr(),Ge("#/")}))}async function yl(e){let t=await Z(`/users/${e}`),{listings:n}=await Z(`/listings?seller=${e}`),r=n.filter(o=>o.status==="open");Le.innerHTML=`<p class="crumbs"><a href="#/">\u2190 Browse</a></p> |
| 127 | <h1>${$(t.user.name)}</h1> |
| 128 | <p>${jn(t.user.trust)}</p> |
| 129 | <p class="mut">${t.user.city?$(t.user.city)+" \xB7 ":""}Joined ${$a(t.user.created)} \xB7 ${t.completedTrades} completed trade${t.completedTrades===1?"":"s"}</p> |
| 130 | <h2>Every rating</h2> |
| 131 | ${t.ratings.length?`<div class="ratings">${t.ratings.map(o=>`<div class="rt"><p><span class="stars-s">${zr(o.honest)}</span> honesty \xB7 ${zr(o.described)} ${o.role==="buyer"?"as described":"did what they said"}</p>${o.note?`<p>\u201C${$(o.note)}\u201D</p>`:""}<p class="mut small">From <a href="#/u/${$(o.from_id)}">${$(o.from_name||"a neighbor")}</a>, as the ${o.role}, ${$a(o.created)}</p></div>`).join("")}</div>`:'<p class="mut">No ratings yet.</p>'} |
| 132 | <h2>Open items</h2><div class="grid">${r.length?r.map(ri).join(""):'<p class="mut">Nothing open right now.</p>'}</div>`}async function dt(){let e=location.hash.replace(/^#/,"")||"/",[t,n]=e.split("?"),r=t.split("/").filter(Boolean);document.body.classList.toggle("printing-label",r[0]==="label");try{switch(Kr||(Kr=await Z("/config")),r[0]){case void 0:await al(new URLSearchParams(n));break;case"item":await fl(r[1]);break;case"sell":await ul();break;case"signin":await dl();break;case"wallet":await ei();break;case"trades":await pl();break;case"trade":await hl(r[1]);break;case"label":await gl(r[1]);break;case"me":await wl();break;case"u":await yl(r[1]);break;default:Le.innerHTML='<h1>Not found</h1><p><a href="#/">Browse the market</a></p>'}}catch(o){if(o instanceof Ut&&o.status===401){se=null,Wr(),_t();return}Le.innerHTML=`<div class="empty"><h3>That didn\u2019t load.</h3><p>${$(o.message)}</p><a class="pill" href="#/">Back to browsing</a></div>`}window.scrollTo(0,0)}window.addEventListener("hashchange",dt);Lt().catch(()=>Wr()).finally(dt); |
| 133 | /*! Bundled license information: |
| 134 | |
| 135 | @noble/curves/utils.js: |
| 136 | @noble/curves/abstract/modular.js: |
| 137 | @noble/curves/abstract/curve.js: |
| 138 | @noble/curves/abstract/der.js: |
| 139 | @noble/curves/abstract/weierstrass.js: |
| 140 | @noble/curves/secp256k1.js: |
| 141 | (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) |
| 142 | |
| 143 | @scure/base/index.js: |
| 144 | (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *) |
| 145 | */ |