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=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>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>>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;_=0?T.getAt(I):0}}let W=0;for(let _=0;_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"u"?w*4:m;let b="";b+='";for(let E=0;E';b+=""}return b+="",b+="
",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 ",_+=''+D(x.text)+"":"",_+=b.text?''+D(b.text)+"":"",_+='',_+='"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"u"?w*4:m;let x=u.getModuleCount()*w+m*2,E="";return E+="",E};let D=function(w){let m="";for(let b=0;b":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=E?te[ae]:_[ae];de+=` `}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>>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<=0;)a^=n<5&&(c+=3+p-5)}for(let l=0;l=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"u")throw"bad rs block @ typeNumber:"+o+"/errorCorrectionLevel:"+s;let a=i.length/3,c=[];for(let f=0;f>>7-r%8&1)==1},n.put=function(r,o){for(let s=0;s>>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>>8&255)*192+(f&255),i.put(f,13),c+=2}if(c>>8)},t.writeBytes=function(n,r,o){r=r||0,o=o||n.length;for(let s=0;s0&&(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=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<>>=8-l,d=0,l=0;d=h<0&&u.writeByte(d)},p},a=function(f){let u=1<({}));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;rtypeof 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>>t}function bn(e,t){return 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=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 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= 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&&to)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(r1024)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)||et)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)&&ruo;){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>=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>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;ca.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<=0;u--){if(u!==c-1)for(let p=0;p>BigInt(u*o)&i),d=a[0];for(let p=1;p=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{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),e1&&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=p||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``}};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>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{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;r8)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>i&t,!(i0&&(o[a]=s<{let r=n.length,o=new Uint8Array(Math.floor(r*e/8)),s=0,i=0,a=0;for(let c=0;c=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;s127)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{Tt("decode",s);let i=s.length,a=new Uint8Array(i);for(let c=0;c({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=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=e)throw new Error(`invalid integer: ${y}`);d=d*e+y,p*=e}c=5;let h=d;for(let g=0;g0;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=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;n126)throw new Error(`${e}: printable ASCII expected`)}}function qc(e){let t=e.length,n=new Uint8Array(t);for(let r=0;r=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>r&1)===1&&(n^=ws[r]);return n}function ys(e,t,n=1){let r=e.length,o=1;for(let i=0;i126)throw new Error(`Invalid prefix (${e})`);o=kn(o)^a>>5}o=kn(o);for(let i=0;i>>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=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=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)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=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{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{for(let o=r,s=0;oAs(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;rnew 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<{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>>i-r<>>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>>i-r<>>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{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(;othis.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<>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.chunkPos8)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;i32)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<>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{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=s&&o[i]==="0";i--);let a=o.slice(0,s),c=o.slice(s,i+1);return a||(a="0"),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{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<{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{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.leftByteso.leftBytes)throw o.err(`array: length=${a} elements of size=${t.size} exceed ${o.leftBytes} bytes left`);for(let c=0;c{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{}){if(!Array.isArray(e))throw new TypeError(`"${t}" expected array, got type=${typeof e}`);for(let r=0;re%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.r4294967295)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{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=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{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{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>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;cUe(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;on&&(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{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{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.length0&&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;r999))return{type:"tr_ns",pubkeys:n}},decode:e=>{if(e.type!=="tr_ns")return;let t=[];for(let n=0;nn.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;ne.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{if(r+a>e.length)throw new Error("Unexpected end of script");let c=0;for(let f=0;fe.length))throw new Error("Unexpected end of script")}return t===0?e:(te===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"),n4294967295))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{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{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{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;tIe.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;tthis.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=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;sln.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({"&":"&","<":"<",">":">",'"':""","'":"'"})[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`${e.tier}${t?"":` ${n}`}`}function hn(e,t=0,n=""){return`${$(n)}`}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?`${se.owedRatings.length}`:"";il.innerHTML='BrowseList an item'+(se?`Trades${e}Wallet${$(se.user.name)}`:'Sign in')}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=>`${$(a)}`).join("");Le.innerHTML=`

Trade with your neighbors.

No price tags. Make one honest offer in Bitcoin. The first offer the seller will take gets it, with no haggling.

List an item

Loading\u2026

${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(""):'

Nothing here yet.

Be the first in your neighborhood. Listing takes a minute.

List an item
'}function ri(e){return`
${hn(e.id,0,e.title)}

${$(e.title)}

${$(ti[e.mode])}${e.mode!=="ship"&&e.city?" \xB7 "+$(e.city):""}

${e.seller?`

${$(e.seller.name)} ${jn(e.seller.trust,!0)}

`:""}
`}function cl(){return`

How the market works

One offer, no haggling

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.

Paid in Bitcoin

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.

Every trade is rated

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.

Trust pays

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.

Local first

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.

Say thanks

Got more than you hoped for? After rating, a slider lets the buyer send the seller any extra amount, up to the full trade.

Open rating data: every rating. Open source code, free to copy.

`}async function fl(e){let t=await Z(`/listings/${e}`),n=t.listing,r=Array.from({length:n.photos},(c,f)=>``).join(""),o="";t.tradeId?o=`Go to your trade`:t.mine?o=`

Your item

${n.status==="open"?"Waiting for an offer.":"Status: "+$(n.status)}

Private minimum: ${t.floorSats?Me(t.floorSats):"none (the first offer takes it)"}. Offers below it: ${t.declinedOffers||0}.

${n.status==="open"?'':""}
`:t.myOffer?o=`

Your offer: ${Me(t.myOffer.sats)}

${t.myOffer.status==="won"?"Your offer took it.":"It was below what the seller will take. Each person gets one offer per item."}

`:n.status==="open"?o=`

Make your one offer

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.

`:o='

Someone\u2019s offer already took this item.

';let s=n.mode==="ship"?`

Ships. ${$(n.boxLabel)}. After you pay, you add your address and the seller prints a label.

`:n.mode==="consign"?`

At a nook, on consignment. Pick it up at the ${$(n.city)} nook after you pay. Your payment is split between the seller and the nook in one transaction.

`:`

Local pickup in ${$(n.city)}. After you pay, you and the seller set a time and a public place to meet.

`;Le.innerHTML=`

\u2190 Browse

${hn(n.id,0,n.title)}
${n.photos>1?`
${r}
`:""}

${$(n.category)} \xB7 ${$(n.condition)}

${$(n.title)}

${$(n.description).replace(/\n/g,"
")}

${s} ${$(t.seller.name)} ${jn(t.seller.trust)} ${o}
`,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=`

\u2190 Browse

List an item

No price tag. Buyers make one offer each, and the first one that meets your private minimum takes it.

Photos (1 to 4)
How will it trade?
`;let n=[],r=J("#pv"),o=()=>{r.innerHTML=n.map((i,a)=>`
`).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=`

Sign in with a passkey

Your face, fingerprint or screen lock is your key. No passwords, no email, nothing to remember.

${e?"":'

This browser doesn\u2019t support passkeys. Try a recent Chrome, Safari, Edge or Firefox.

'}

I\u2019m new here

I\u2019ve been here before

Use the passkey you made on Tradenook.

`;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=`

Your wallet

Every trade is paid in Bitcoin. While we test, the market runs on Bitcoin signet: test coins with no value.

Create a wallet for me

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.

Use my own wallet

Paste a receiving address from a wallet you already use. For testing, it must be a signet address starting with tb1.

`;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=`

Your wallet

Test mode: Bitcoin signet. These coins have no value.

Balance

Checking\u2026

Need test coins? Get free ones from a signet faucet.

Receive

${ni("bitcoin:"+e.walletAddress)}

${$(e.walletAddress)}

${t?`

Send

Your passkey unlocks the wallet for each payment.

`:'

This is your own wallet. Send from the wallet app you use.

'}
Change wallet

Switch to a new address. Trades waiting for payment move to the new address too.${t?" Move your coins out first.":""}

`,Aa(e.walletAddress).then(r=>{J("#bal").innerHTML=`${Me(r.confirmed)}${r.pending?` + ${Me(r.pending)} arriving`:""}`}).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=`

Your trades

${e.length?``:'

No trades yet.

Find something you like and make an offer.

Browse
'}`}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"?"":`
    ${f.map((O,D)=>`
  1. ${{awaiting_payment:"Pay",paid:"Paid",shipped:"Shipped",received:"Received",complete:"Rated"}[O]}
  2. `).join("")}
`,d="";if(n.status==="cancelled")d='

This trade was cancelled before payment.

';else if(n.status==="awaiting_payment")if(o){let O=n.mode==="ship"?`
Ship to (only the seller sees this)
`:"";d=`

Pay ${Me(n.sats)}

${n.nookSats?`

This is a consignment trade, so one payment goes to two places: ${Me(n.sellerSats)} to the seller (${n.sellerPct}%) and ${Me(n.nookSats)} to the nook.

`:`

Paid straight to ${$(t.seller.name)}\u2019s wallet.

`} ${O} ${se.user.walletKind==="mine"?'':""}
Pay from another wallet ${c.map(D=>`

${Me(D.sats)} \u2192 ${$(D.address)}

`).join("")}
${ni(`bitcoin:${n.sellerAddress}?amount=${(n.sellerSats/1e8).toFixed(8)}`,3)}
`}else d=`

Waiting for ${$(t.buyer.name)} to pay ${Me(n.sats)}

You\u2019ll get ${Me(n.sellerSats)} at ${$(n.sellerAddress)}.

`;else if(n.status==="paid"||n.status==="shipped"){let O=`

Payment: ${$(n.txid.slice(0,16))}\u2026

`;if(n.mode==="ship")!o&&n.status==="paid"?d=`

Pack and ship

Box: ${$(t.box)}.

Print the shipping label
${O}
`:o?d=`

${n.status==="shipped"?"On its way":"Paid. The seller is packing it."}

${n.tracking?`

Tracking: ${$(n.tracking)}

`:""}${O}
`:d=`

Shipped

Tracking: ${$(n.tracking||"none given")}. Waiting for ${$(t.buyer.name)} to confirm it arrived.

${O}
`;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?`

Paid. ${D}

Once it\u2019s in your hands and it\u2019s as described, tap below.

${O}
`:`

Paid. ${n.mode==="consign"?"The nook will hand it over.":"Meet the buyer to hand it over."}

${$(t.buyer.name)} confirms when they have it, then you both rate.

${O}
`}}else(n.status==="received"||n.status==="rating"||n.status==="complete")&&(i?d=`

${n.status==="complete"?"Trade complete":`Waiting for ${$(s.name)}\u2019s rating`}

You gave ${zr(i.honest)} for honesty.

${a?`

${$(s.name)} gave you ${zr(a.honest)}.

`:""}
`:d=`

Rate ${$(s.name)}

Ratings are public and every trade needs one from both sides.

How honest were they?${Oa("honest")}
${o?"Was the item as described?":"Did they do what they said (pay, show up, be fair)?"}${Oa("described")}
`,o&&i&&!n.thanksTxid&&(d+=`

Got more than you hoped for?

Send ${$(t.seller.name)} any extra amount, up to the full trade. It\u2019s optional, and it goes straight to them.

0 sats

${se.user.walletKind==="mine"?'':`

${$(n.sellerAddress)}

`}
`),n.thanksTxid&&(d+=`

${o?"You":$(t.buyer.name)} sent ${Me(n.thanksSats)} extra. Thank you!

`));Le.innerHTML=`

\u2190 Your trades

${hn(r.id,0,r.title)}

${$(ti[n.mode])} \xB7 ${$(La[n.status]||n.status)}

${$(r.title)}

${o?"You\u2019re buying from":"You\u2019re selling to"} ${$(s.name)} ${jn(s.trust)}

${Me(n.sats)} ${Ia(n.sats)}

${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`
${[5,4,3,2,1].map(t=>``).join("")}
`}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="

Only the seller of a shipped item can print its label.

";return}let r="";try{r=localStorage.getItem("tn_return")||""}catch{}let o=`${location.origin}/market/#/trade/${n.id}`;Le.innerHTML=`

\u2190 Back to the trade

Shipping label

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 ${$(t.box)}.

  1. Wrap the item and fill gaps so nothing moves.
  2. Use the standard box size above, so every Tradenook package stacks the same.
  3. Tape every seam, then stick this label on the biggest side.
  4. Mark it shipped on the trade page, with the tracking number if you have one.
FROM
${$(r||t.seller.name)}
SHIP TO
${$(n.shipTo)}
TRADENOOK TRADE${$(n.id)}Box ${$(t.listing.box)} \xB7 ${$(t.listing.title.slice(0,40))}
${ni(o,3)}
`;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=`

Hi, ${$(e.name)}

${se.owedRatings.length?`

You have a trade to rate. Rate it before your next offer. Rate it now

`:""}

Your trust

${jn(t)}

Consignment split at a nook: you keep ${t.sellerPct}%.

${r}

See your public profile

Profile

Your items

${n.length?n.map(ri).join(""):'

Nothing listed yet. List an item

'}

`;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=`

\u2190 Browse

${$(t.user.name)}

${jn(t.user.trust)}

${t.user.city?$(t.user.city)+" \xB7 ":""}Joined ${$a(t.user.created)} \xB7 ${t.completedTrades} completed trade${t.completedTrades===1?"":"s"}

Every rating

${t.ratings.length?`
${t.ratings.map(o=>`

${zr(o.honest)} honesty \xB7 ${zr(o.described)} ${o.role==="buyer"?"as described":"did what they said"}

${o.note?`

\u201C${$(o.note)}\u201D

`:""}

From ${$(o.from_name||"a neighbor")}, as the ${o.role}, ${$a(o.created)}

`).join("")}
`:'

No ratings yet.

'}

Open items

${r.length?r.map(ri).join(""):'

Nothing open right now.

'}
`}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='

Not found

Browse the market

'}}catch(o){if(o instanceof Ut&&o.status===401){se=null,Wr(),_t();return}Le.innerHTML=`

That didn\u2019t load.

${$(o.message)}

Back to browsing
`}window.scrollTo(0,0)}window.addEventListener("hashchange",dt);Lt().catch(()=>Wr()).finally(dt); /*! Bundled license information: @noble/curves/utils.js: @noble/curves/abstract/modular.js: @noble/curves/abstract/curve.js: @noble/curves/abstract/der.js: @noble/curves/abstract/weierstrass.js: @noble/curves/secp256k1.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @scure/base/index.js: (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *) */