From 4359351bf01aef67b236251e58885189cc0ed321 Mon Sep 17 00:00:00 2001 From: teahubxyz Date: Thu, 15 Oct 2026 16:10:49 -0700 Subject: [PATCH] lineage: Orgchain v1.14.1 (a belt counts only on its seat's sat) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H4upF5LVwmPDDqrhdUfnXh --- .../lineage/orgchain/assets/index-CT5G0hes.js | 2065 ----------------- .../lineage/orgchain/assets/index-CpxUP_85.js | 2065 +++++++++++++++++ ventures/lineage/orgchain/index.html | 2 +- 3 files changed, 2066 insertions(+), 2066 deletions(-) delete mode 100644 ventures/lineage/orgchain/assets/index-CT5G0hes.js create mode 100644 ventures/lineage/orgchain/assets/index-CpxUP_85.js diff --git a/ventures/lineage/orgchain/assets/index-CT5G0hes.js b/ventures/lineage/orgchain/assets/index-CT5G0hes.js deleted file mode 100644 index 809352d..0000000 --- a/ventures/lineage/orgchain/assets/index-CT5G0hes.js +++ /dev/null @@ -1,2065 +0,0 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();const Io=5e9,Du=2**52,Xl=(e,t)=>[[Du+e*Io,Du+e*Io+t]];function Jl(e,t,n){const r=[];for(const[s,o]of e){const i=o-s;if(t>=i){t-=i;continue}const a=Math.min(n,i-t);if(a&&r.push([s+t,s+t+a]),n-=a,t=0,!n)break}return r}function Ql(e,t){var n;return(n=Jl(e,t,1)[0])==null?void 0:n[0]}function tn(e,t){let n=0;for(const[r,s]of e){if(t>=r&&ti.ranges);let o=0;return e.vout.map(i=>{const a=Jl(s,o,Number(i.value));return o+=Number(i.value),a})}function $a(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function P0(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function tf(e,...t){if(!(e instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new TypeError(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function U0(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");$a(e.outputLen),$a(e.blockLen)}function N0(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function L0(e,t){tf(e);const n=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),Pt=(e,t)=>e<<32-t|e>>>t,R0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!R0)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function j0(e){if(typeof e!="string")throw new TypeError(`utf8ToBytes expected string, got ${typeof e}`);return new TextEncoder().encode(e)}function nf(e){if(typeof e=="string"&&(e=j0(e)),!(e instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof e})`);return e}let K0=class{clone(){return this._cloneInto()}};function rf(e){const t=r=>e().update(nf(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function D0(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const s=BigInt(32),o=BigInt(4294967295),i=Number(n>>s&o),a=Number(n&o),c=r?4:0,u=r?0:4;e.setUint32(t+c,i,r),e.setUint32(t+u,a,r)}let M0=class extends K0{constructor(t,n,r,s){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Vi(this.buffer)}update(t){Zi.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=nf(t);const o=t.length;for(let i=0;is-i&&(this.process(r,0),i=0);for(let l=i;lf.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;le&t^~e&n,V0=(e,t,n)=>e&t^e&n^t&n,q0=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),dn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),hn=new Uint32Array(64);let sf=class extends M0{constructor(){super(64,32,8,!1),this.A=dn[0]|0,this.B=dn[1]|0,this.C=dn[2]|0,this.D=dn[3]|0,this.E=dn[4]|0,this.F=dn[5]|0,this.G=dn[6]|0,this.H=dn[7]|0}get(){const{A:t,B:n,C:r,D:s,E:o,F:i,G:a,H:c}=this;return[t,n,r,s,o,i,a,c]}set(t,n,r,s,o,i,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,n){for(let l=0;l<16;l++,n+=4)hn[l]=t.getUint32(n,!1);for(let l=16;l<64;l++){const d=hn[l-15],p=hn[l-2],g=Pt(d,7)^Pt(d,18)^d>>>3,h=Pt(p,17)^Pt(p,19)^p>>>10;hn[l]=h+hn[l-7]+g+hn[l-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){const d=Pt(a,6)^Pt(a,11)^Pt(a,25),p=f+d+Z0(a,c,u)+q0[l]+hn[l]|0,h=(Pt(r,2)^Pt(r,13)^Pt(r,22))+V0(r,s,o)|0;f=u,u=c,c=a,a=i+p|0,i=o,o=s,s=r,r=p+h|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,s,o,i,a,c,u,f)}roundClean(){hn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},z0=class extends sf{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}};const Ea=rf(()=>new sf);rf(()=>new z0);function F0(e,t){if(e.length>t)throw new TypeError(`Data is larger than array size: ${e.length} > ${t}`)}function W0(e){if(e.match(/[^a-fA-f0-9]/)!==null)throw new TypeError("Invalid characters in hex string: "+e);if(e.length%2!==0)throw new Error(`Length of hex string is invalid: ${e.length}`)}function G0(e){if(e>Number.MAX_SAFE_INTEGER)throw new TypeError("Number exceeds safe bounds!")}const{getRandomValues:Y0}=crypto??globalThis.crypto??window.crypto;function X0(e=32){if(typeof Y0=="function")return crypto.getRandomValues(new Uint8Array(e));throw new Error("Crypto module missing getRandomValues!")}function J0(e,t,n="be"){t===void 0&&(t=e.length),F0(e,t);const r=new Uint8Array(t).fill(0),s=n==="be"?0:t-e.length;return r.set(e,s),r}function of(e){let t,n=0;const r=e.reduce((o,i)=>o+i.length,0),s=new Uint8Array(r);for(t=0;t0||(i.length^a)>0?"":"1";c in o||u>0;)f=o[c],f=f>0?f*256+u:u,u=f/s|0,o[c]=f%s,c++;for(;c-- >0;)i+=r[o[c]];return n&&i.length%4>0?i+"=".repeat(4-i.length%4):i}function ng(e,t){const n=af(t),r=n.length,s=[],o=[];e=e.replace("=","");let i,a=0,c,u;for(i=0;i0||(o.length^i)>0||o.push(0);a in s||c>0;)u=s[a],u=u>0?u*r+c:c,c=u>>8,s[a]=u%256,a++}for(;a-- >0;)o.push(s[a]);return new Uint8Array(o)}function cf(e){return Ea(Ea(e))}function rg(e){const t=cf(e);return of([e,t.slice(0,4)])}function sg(e){const t=e.slice(0,-4),n=e.slice(-4);if(cf(t).slice(0,4).toString()!==n.toString())throw new Error("Invalid checksum!");return t}const Mu={encode:tg,decode:ng},uf={encode:e=>{const t=rg(e);return Mu.encode(t,"base58")},decode:e=>{const t=Mu.decode(e,"base58");return sg(t)}},lf="qpzry9x8gf2tvdw0s3jn54khce6mua7l",og=[996825010,642813549,513874426,1027748829,705979059],Co=[{version:0,name:"bech32",const:1},{version:1,name:"bech32m",const:734539939}];function ff(e){let t=1;for(let n=0;n>25;t=(t&33554431)<<5^e[n];for(let s=0;s<5;++s)(r>>s&1)!==0&&(t^=og[s])}return t}function df(e){const t=[];let n;for(n=0;n>5);for(t.push(0),n=0;n>5*(5-i)&31);return o}function hf(e,t,n,r=!0){const s=[];let o=0,i=0;const a=(1<>t>0)throw new Error("Failed to perform base conversion. Invalid value: "+String(u));for(o=(o<=n;)i-=n,s.push(o>>i&a)}if(r)i>0&&s.push(o<=t||(o<0)throw new Error("Failed to perform base conversion. Invalid Size!");return s}function cg(e,t,n){const r=t.concat(ag(e,t,n));let s=e+"1";for(let o=0;oo.version===t[0])??Co[0];if(!ig(r,t,s))throw new Error("Checksum verification failed!");return[r,t.slice(0,t.length-6)]}function ug(e){let t,n,r=!1,s=!1;for(t=0;t126)return!1;n>=97&&n<=122&&(r=!0),n>=65&&n<=90&&(s=!0)}return!(r&&s)}function lg(e){const t=e.lastIndexOf("1");return!(t<1||t+7>e.length||e.length>90)}function fg(e,t="bc",n=0){const r=[n,...hf([...e],8,5)],s=Co.find(i=>i.version===n)??Co[0],o=cg(t,r,s);return gf(o),o}function gf(e){e=e.toLowerCase();const t=e.split("1",1)[0],[n,r]=pf(e),s=hf(r.slice(1),5,8,!1),o=s.length;switch(!0){case t!==n:throw new Error("Returned hrp string is invalid.");case(s===null||o<2||o>40):throw new Error("Decoded string is invalid or out of spec.");case r[0]>16:throw new Error("Returned version bit is out of range.");default:return Uint8Array.from(s)}}function dg(e){e=e.toLowerCase();const[t,n]=pf(e);return n[0]}const mf={encode:fg,decode:gf,version:dg},yf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",wf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",hg=new TextEncoder;function bf(e,t=!1,n=!0){typeof e=="string"&&(e=hg.encode(e));const r=t?wf:yf;let s="",o=0,i=0;for(let a=0;a=6;)o-=6,s+=r[i>>o&63];if(o>0)for(i<<=6-o,s+=r[i&63];o<6;)s+=n?"=":"",o+=2;return s}function xf(e,t=!1){const n=t||e.includes("-")||e.includes("_")?wf.split(""):yf.split("");e=e.replace(/=+$/,"");const r=e.split("");let s=0,o=0;const i=[];for(let a=0;a=8&&(s-=8,i.push(o>>>s&255))}return new Uint8Array(i)}const vf={encode:bf,decode:xf},kf={encode:e=>bf(e,!0,!1),decode:e=>xf(e,!0)},pg=BigInt(0),gg=BigInt(255),$f=BigInt(256);function mg(e){if(e<=0xffn)return 1;if(e<=0xffffn)return 2;if(e<=0xffffffffn)return 4;if(e<=0xffffffffffffffffn)return 8;if(e<=0xffffffffffffffffffffffffffffffffn)return 16;if(e<=0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn)return 32;throw new TypeError("Must specify a fixed buffer size for bigints greater than 32 bytes.")}function yg(e,t,n="be"){t===void 0&&(t=mg(e));const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(;e>pg;){const a=e&gg,c=Number(a);r?o.setUint8(i++,c):o.setUint8(i--,c),e=(e-a)/$f}return new Uint8Array(s)}function wg(e){let t=BigInt(0);for(let n=e.length-1;n>=0;n--)t=t*$f+BigInt(e[n]);return BigInt(t)}function bg(e){const t=e.split("").map(Number);if(t.length%8!==0)throw new Error(`Binary array is invalid length: ${e.length}`);const n=new Uint8Array(t.length/8);for(let r=0,s=0;r255)throw new Error(`Invalid byte value: ${r}. Byte values must be between 0 and 255.`);for(let s=7;s>=0;s--,n++)t[n]=r>>s&1}return t.join("")}function vg(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=4294967295)return 4;throw new TypeError("Numbers larger than 4 bytes must specify a fixed size!")}function kg(e,t,n="be"){t===void 0&&(t=vg(e));const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(;e>0;){const a=e&255;r?o.setUint8(i++,e):o.setUint8(i--,e),e=(e-a)/256}return new Uint8Array(s)}function $g(e){let t=0;for(let n=e.length-1;n>=0;n--)t=t*256+e[n],G0(t);return t}const Eg=new TextEncoder,Sg=new TextDecoder;function pc(e){return Eg.encode(e)}function qi(e){return Sg.decode(e)}function _g(e,t){W0(e);const n=e.length/2;if(t===void 0&&(t=n),n>t)throw new TypeError(`Hex string is larger than array size: ${n} > ${t}`);return t}function Ag(e,t,n="le"){t=_g(e,t);const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(let a=0;atypeof r=="bigint"?`${r}n`:r);return pc(t)}function Og(e,t,n){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Uint8Array)return J0(e,t,n);if(typeof e=="string")return Ag(e,t,n);if(typeof e=="bigint")return yg(e,t,n);if(typeof e=="number")return kg(e,t,n);if(typeof e=="boolean")return Uint8Array.of(e?1:0);throw TypeError("Unsupported format:"+typeof e)}var re;let B=(re=class extends Uint8Array{static random(t=32){const n=X0(t);return new re(n,t)}constructor(t,n,r){const s=Og(t,n,r);super(s)}get arr(){return[...this]}get num(){return this.toNum()}get big(){return this.toBig()}get str(){return this.toStr()}get hex(){return this.toHex()}get raw(){return new Uint8Array(this)}get bin(){return this.toBin()}get b58chk(){return this.tob58chk()}get base64(){return this.toBase64()}get b64url(){return this.toB64url()}get digest(){return this.toHash()}get id(){return this.toHash().hex}get stream(){return new as(this)}toNum(t="be"){const n=t==="be"?this.reverse():this;return $g(n)}toBin(){return xg(this)}toBig(t="be"){const n=t==="be"?this.reverse():this;return wg(n)}toHash(){const t=Ea(this);return new re(t)}toJson(){const t=qi(this);return JSON.parse(t)}toBech32(t,n=0){return mf.encode(this,t,n)}toStr(){return qi(this)}toHex(){return Bg(this)}toBytes(){return new Uint8Array(this)}tob58chk(){return uf.encode(this)}toBase64(){return vf.encode(this)}toB64url(){return kf.encode(this)}prepend(t){return re.join([re.bytes(t),this])}append(t){return re.join([this,re.bytes(t)])}slice(t,n){const r=new Uint8Array(this).slice(t,n);return new re(r)}subarray(t,n){const r=new Uint8Array(this).subarray(t,n);return new re(r)}reverse(){const t=new Uint8Array(this).reverse();return new re(t)}write(t,n){const r=re.bytes(t);this.set(r,n)}prefixSize(t){const n=re.varInt(this.length,t);return re.join([n,this])}static from(t){return new re(Uint8Array.from(t))}static of(...t){return new re(Uint8Array.of(...t))}static join(t){const n=t.map(s=>re.bytes(s)),r=of(n);return new re(r)}static varInt(t,n){if(t<253)return re.num(t,1);if(t<65536)return re.of(253,...re.num(t,2,n));if(t<4294967296)return re.of(254,...re.num(t,4,n));if(BigInt(t)<0x10000000000000000n)return re.of(255,...re.num(t,8,n));throw new Error(`Value is too large: ${t}`)}},re.num=Ig,re.big=Pg,re.bin=Cg,re.raw=Ug,re.str=Ng,re.hex=Lg,re.bytes=Hg,re.json=Rg,re.base64=jg,re.b64url=Kg,re.bech32=Dg,re.b58chk=Mg,re.encode=pc,re.decode=qi,re);function Ig(e,t,n){return new B(e,t,n)}function Cg(e,t,n){return new B(bg(e),t,n)}function Pg(e,t,n){return new B(e,t,n)}function Ug(e,t,n){return new B(e,t,n)}function Ng(e,t,n){return new B(pc(e),t,n)}function Lg(e,t,n){return new B(e,t,n)}function Hg(e,t,n){return new B(e,t,n)}function Rg(e){return new B(Tg(e))}function jg(e){return new B(vf.decode(e))}function Kg(e){return new B(kf.decode(e))}function Dg(e){return new B(mf.decode(e))}function Mg(e){return new B(uf.decode(e))}let as=class{constructor(t){this.data=B.bytes(t),this.size=this.data.length}peek(t){if(t>this.size)throw new Error(`Size greater than stream: ${t} > ${this.size}`);return new B(this.data.slice(0,t))}read(t){t=t??this.readSize();const n=this.peek(t);return this.data=this.data.slice(t),this.size=this.data.length,n}readSize(t){const n=this.read(1).num;switch(!0){case(n>=0&&n<253):return n;case n===253:return this.read(2).toNum(t);case n===254:return this.read(4).toNum(t);case n===255:return this.read(8).toNum(t);default:throw new Error(`Varint is out of range: ${n}`)}}};function Ft(e,t){const n=B.bytes(e);if(n.length!==t)throw new Error(`Invalid input size: ${n.hex} !== ${t}`)}function Je(e,t){if(t)throw new Error(e);return!1}function Eo(e,...t){const n=B.str(e).digest.raw,r=t.map(s=>B.bytes(s));return B.join([n,n,B.join(r)]).digest}const Ef={OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_SUCCESS80:80,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_SUCCESS98:98,OP_IF:99,OP_NOTIF:100,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_SUCCESS126:126,OP_SUCCESS127:127,OP_SUCCESS128:128,OP_SUCCESS129:129,OP_SIZE:130,OP_SUCCESS131:131,OP_SUCCESS132:132,OP_SUCCESS133:133,OP_SUCCESS134:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_SUCCESS137:137,OP_SUCCESS138:138,OP_1ADD:139,OP_1SUB:140,OP_SUCCESS141:141,OP_SUCCESS142:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_SUCCESS149:149,OP_SUCCESS150:150,OP_SUCCESS151:151,OP_SUCCESS152:152,OP_SUCCESS153:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_CHECKLOCKTIMEVERIFY:177,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_CHECKSIGADD:186,OP_SUCCESS187:187,OP_SUCCESS188:188,OP_SUCCESS189:189,OP_SUCCESS190:190,OP_SUCCESS191:191,OP_SUCCESS192:192,OP_SUCCESS193:193,OP_SUCCESS194:194,OP_SUCCESS195:195,OP_SUCCESS196:196,OP_SUCCESS197:197,OP_SUCCESS198:198,OP_SUCCESS199:199,OP_SUCCESS200:200,OP_SUCCESS201:201,OP_SUCCESS202:202,OP_SUCCESS203:203,OP_SUCCESS204:204,OP_SUCCESS205:205,OP_SUCCESS206:206,OP_SUCCESS207:207,OP_SUCCESS208:208,OP_SUCCESS209:209,OP_SUCCESS210:210,OP_SUCCESS211:211,OP_SUCCESS212:212,OP_SUCCESS213:213,OP_SUCCESS214:214,OP_SUCCESS215:215,OP_SUCCESS216:216,OP_SUCCESS217:217,OP_SUCCESS218:218,OP_SUCCESS219:219,OP_SUCCESS220:220,OP_SUCCESS221:221,OP_SUCCESS222:222,OP_SUCCESS223:223,OP_SUCCESS224:224,OP_SUCCESS225:225,OP_SUCCESS226:226,OP_SUCCESS227:227,OP_SUCCESS228:228,OP_SUCCESS229:229,OP_SUCCESS230:230,OP_SUCCESS231:231,OP_SUCCESS232:232,OP_SUCCESS233:233,OP_SUCCESS234:234,OP_SUCCESS235:235,OP_SUCCESS236:236,OP_SUCCESS237:237,OP_SUCCESS238:238,OP_SUCCESS239:239,OP_SUCCESS240:240,OP_SUCCESS241:241,OP_SUCCESS242:242,OP_SUCCESS243:243,OP_SUCCESS244:244,OP_SUCCESS245:245,OP_SUCCESS246:246,OP_SUCCESS247:247,OP_SUCCESS248:248,OP_SUCCESS249:249,OP_SUCCESS250:250,OP_SUCCESS251:251,OP_SUCCESS252:252,OP_SUCCESS253:253,OP_SUCCESS254:254};function Zg(e){if(e>186&&e<255)return"OP_SUCCESS"+String(e);for(const[t,n]of Object.entries(Ef))if(n===e)return t;throw new Error("OPCODE not found:"+String(e))}function Vg(e){for(const[t,n]of Object.entries(Ef))if(t===e)return Number(n);throw new Error("OPCODE not found:"+e)}function qg(e){switch(!0){case e===0:return"opcode";case(e>=1&&e<=75):return"varint";case e===76:return"pushdata1";case e===77:return"pushdata2";case e===78:return"pushdata4";case e<=254:return"opcode";default:throw new Error(`Invalid word range: ${e}`)}}function zg(e){const r=[];switch(!0){case typeof e!="number":return!1;case e===0:return!0;case r.includes(e):return!1;case(750?B.join(t):new Uint8Array}function Fg(e){let t=new Uint8Array;if(typeof e=="string"){if(e.startsWith("OP_"))return B.num(Vg(e),1);fn(e)?t=B.hex(e):t=B.str(e)}else t=B.bytes(e);if(t.length===1)return t[0]!==0&&t[0]<=16?(t[0]+=80,t):(t[0]>128&&t[0]<=255&&(t=new Uint8Array([t[0],0])),B.join([Zu(t.length),t]));if(t.length>Po){const n=Wg(t);return _f(n)}else return B.join([Zu(t.length),t])}function Zu(e){const t=B.num(76,1),n=B.num(77,1);switch(!0){case e<=75:return B.num(e);case(e>75&&e<256):return B.join([t,B.num(e,1,"le")]);case(e>=256&&e<=Po):return B.join([n,B.num(e,2,"le")]);default:throw new Error("Invalid word size:"+e.toString())}}function Wg(e){const t=[],n=new as(e);for(;n.size>Po;)t.push(n.read(Po));return t.push(n.read(n.size)),t}function gc(e,t=!1){let n=B.bytes(e);if(t){const s=n.stream.readSize("le");if(n=n.slice(1),n.length!==s)throw new Error(`Varint does not match stream size: ${s} !== ${n.length}`)}return Gg(n)}function Gg(e){const t=new as(e),n=[],r=t.size;let s,o,i,a=0;for(;a0&&!t.includes(e.length))throw new TypeError(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function tm(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Sa(e.outputLen),Sa(e.blockLen)}function nm(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function rm(e,t){Af(e);const n=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),Ut=(e,t)=>e<<32-t|e>>>t,om=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!om)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function im(e){if(typeof e!="string")throw new TypeError(`utf8ToBytes expected string, got ${typeof e}`);return new TextEncoder().encode(e)}function mc(e){if(typeof e=="string"&&(e=im(e)),!(e instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof e})`);return e}function am(...e){if(!e.every(r=>r instanceof Uint8Array))throw new Error("Uint8Array list expected");if(e.length===1)return e[0];const t=e.reduce((r,s)=>r+s.length,0),n=new Uint8Array(t);for(let r=0,s=0;re().update(mc(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function cm(e=32){if(zi&&typeof zi.getRandomValues=="function")return zi.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function um(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const s=BigInt(32),o=BigInt(4294967295),i=Number(n>>s&o),a=Number(n&o),c=r?4:0,u=r?0:4;e.setUint32(t+c,i,r),e.setUint32(t+u,a,r)}let lm=class extends Bf{constructor(t,n,r,s){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Fi(this.buffer)}update(t){Jn.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=mc(t);const o=t.length;for(let i=0;is-i&&(this.process(r,0),i=0);for(let l=i;lf.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;le&t^~e&n,dm=(e,t,n)=>e&t^e&n^t&n,hm=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),pn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),gn=new Uint32Array(64);let Of=class extends lm{constructor(){super(64,32,8,!1),this.A=pn[0]|0,this.B=pn[1]|0,this.C=pn[2]|0,this.D=pn[3]|0,this.E=pn[4]|0,this.F=pn[5]|0,this.G=pn[6]|0,this.H=pn[7]|0}get(){const{A:t,B:n,C:r,D:s,E:o,F:i,G:a,H:c}=this;return[t,n,r,s,o,i,a,c]}set(t,n,r,s,o,i,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,n){for(let l=0;l<16;l++,n+=4)gn[l]=t.getUint32(n,!1);for(let l=16;l<64;l++){const d=gn[l-15],p=gn[l-2],g=Ut(d,7)^Ut(d,18)^d>>>3,h=Ut(p,17)^Ut(p,19)^p>>>10;gn[l]=h+gn[l-7]+g+gn[l-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){const d=Ut(a,6)^Ut(a,11)^Ut(a,25),p=f+d+fm(a,c,u)+hm[l]+gn[l]|0,h=(Ut(r,2)^Ut(r,13)^Ut(r,22))+dm(r,s,o)|0;f=u,u=c,c=a,a=i+p|0,i=o,o=s,s=r,r=p+h|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,s,o,i,a,c,u,f)}roundClean(){gn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},pm=class extends Of{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}};const If=Tf(()=>new Of);Tf(()=>new pm);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const gm=BigInt(0),yc=BigInt(1),mm=BigInt(2),gi=e=>e instanceof Uint8Array,ym=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Zr(e){if(!gi(e))throw new Error("Uint8Array expected");let t="";for(let n=0;nVr(e.toString(16).padStart(t*2,"0")),Pf=(e,t)=>Lr(e,t).reverse(),wm=e=>Vr(Cf(e));function gt(e,t,n){let r;if(typeof t=="string")try{r=Vr(t)}catch(o){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${o}`)}else if(gi(t))r=Uint8Array.from(t);else throw new Error(`${e} must be hex string or Uint8Array`);const s=r.length;if(typeof n=="number"&&s!==n)throw new Error(`${e} expected ${n} bytes, got ${s}`);return r}function kt(...e){const t=new Uint8Array(e.reduce((r,s)=>r+s.length,0));let n=0;return e.forEach(r=>{if(!gi(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}function bm(e,t){if(e.length!==t.length)return!1;for(let n=0;n0n;e>>=yc,t+=1);return t}const vm=(e,t)=>e>>BigInt(t)&1n,km=(e,t,n)=>e|(n?yc:gm)<(mm<new Uint8Array(e),Vu=e=>Uint8Array.from(e);function Uf(e,t,n){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=Wi(e),s=Wi(e),o=0;const i=()=>{r.fill(1),s.fill(0),o=0},a=(...l)=>n(s,r,...l),c=(l=Wi())=>{s=a(Vu([0]),l),r=a(),l.length!==0&&(s=a(Vu([1]),l),r=a())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const d=[];for(;l{i(),c(l);let p;for(;!(p=d(u()));)c();return i(),p}}const $m={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function cs(e,t,n={}){const r=(s,o,i)=>{const a=$m[o];if(typeof a!="function")throw new Error(`Invalid validator "${o}", expected function`);const c=e[s];if(!(i&&c===void 0)&&!a(c,e))throw new Error(`Invalid param ${String(s)}=${c} (${typeof c}), expected ${o}`)};for(const[s,o]of Object.entries(t))r(s,o,!1);for(const[s,o]of Object.entries(n))r(s,o,!0);return e}var Em=Object.freeze({__proto__:null,bitGet:vm,bitLen:xm,bitMask:xc,bitSet:km,bytesToHex:Zr,bytesToNumberBE:In,bytesToNumberLE:bc,concatBytes:kt,createHmacDrbg:Uf,ensureBytes:gt,equalBytes:bm,hexToBytes:Vr,hexToNumber:wc,numberToBytesBE:Lr,numberToBytesLE:Pf,numberToHexUnpadded:Cf,numberToVarBytesBE:wm,utf8ToBytes:mi,validateObject:cs});/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const qe=BigInt(0),He=BigInt(1),Gn=BigInt(2),Sm=BigInt(3),_a=BigInt(4),qu=BigInt(5),zu=BigInt(8);BigInt(9);BigInt(16);function Qe(e,t){const n=e%t;return n>=qe?n:t+n}function _m(e,t,n){if(n<=qe||t 0");if(n===He)return qe;let r=He;for(;t>qe;)t&He&&(r=r*e%n),e=e*e%n,t>>=He;return r}function pt(e,t,n){let r=e;for(;t-- >qe;)r*=r,r%=n;return r}function Aa(e,t){if(e===qe||t<=qe)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let n=Qe(e,t),r=t,s=qe,o=He;for(;n!==qe;){const a=r/n,c=r%n,u=s-o*a;r=n,n=c,s=o,o=u}if(r!==He)throw new Error("invert: does not exist");return Qe(s,t)}function Am(e){const t=(e-He)/Gn;let n,r,s;for(n=e-He,r=0;n%Gn===qe;n/=Gn,r++);for(s=Gn;s(r[s]="function",r),t);return cs(e,n)}function Om(e,t,n){if(n 0");if(n===qe)return e.ONE;if(n===He)return t;let r=e.ONE,s=t;for(;n>qe;)n&He&&(r=e.mul(r,s)),s=e.sqr(s),n>>=He;return r}function Im(e,t){const n=new Array(t.length),r=t.reduce((o,i,a)=>e.is0(i)?o:(n[a]=o,e.mul(o,i)),e.ONE),s=e.inv(r);return t.reduceRight((o,i,a)=>e.is0(i)?o:(n[a]=e.mul(o,n[a]),e.mul(o,i)),s),n}function vc(e,t){const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Lf(e,t,n=!1,r={}){if(e<=qe)throw new Error(`Expected Fp ORDER > 0, got ${e}`);const{nBitLength:s,nByteLength:o}=vc(e,t);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");const i=Bm(e),a=Object.freeze({ORDER:e,BITS:s,BYTES:o,MASK:xc(s),ZERO:qe,ONE:He,create:c=>Qe(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return qe<=c&&cc===qe,isOdd:c=>(c&He)===He,neg:c=>Qe(-c,e),eql:(c,u)=>c===u,sqr:c=>Qe(c*c,e),add:(c,u)=>Qe(c+u,e),sub:(c,u)=>Qe(c-u,e),mul:(c,u)=>Qe(c*u,e),pow:(c,u)=>Om(a,c,u),div:(c,u)=>Qe(c*Aa(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Aa(c,e),sqrt:r.sqrt||(c=>i(a,c)),invertBatch:c=>Im(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>n?Pf(c,o):Lr(c,o),fromBytes:c=>{if(c.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${c.length}`);return n?bc(c):In(c)}});return Object.freeze(a)}function Cm(e,t,n=!1){e=gt("privateHash",e);const r=e.length,s=vc(t).nByteLength+8;if(s<24||r1024)throw new Error(`hashToPrivateScalar: expected ${s}-1024 bytes of input, got ${r}`);const o=n?bc(e):In(e);return Qe(o,t-He)+He}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Pm=BigInt(0),Gi=BigInt(1);function Um(e,t){const n=(s,o)=>{const i=o.negate();return s?i:o},r=s=>{const o=Math.ceil(t/s)+1,i=2**(s-1);return{windows:o,windowSize:i}};return{constTimeNegate:n,unsafeLadder(s,o){let i=e.ZERO,a=s;for(;o>Pm;)o&Gi&&(i=i.add(a)),a=a.double(),o>>=Gi;return i},precomputeWindow(s,o){const{windows:i,windowSize:a}=r(o),c=[];let u=s,f=u;for(let l=0;l>=p,y>c&&(y-=d,i+=Gi);const m=h,x=h+Math.abs(y)-1,w=g%2!==0,P=y<0;y===0?f=f.add(n(w,o[m])):u=u.add(n(P,o[x]))}return{p:u,f}},wNAFCached(s,o,i,a){const c=s._WINDOW_SIZE||1;let u=o.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&o.set(s,a(u))),this.wNAF(c,u,i)}}}function Hf(e){return Nf(e.Fp),cs(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...vc(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Nm(e){const t=Hf(e);cs(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:n,Fp:r,a:s}=t;if(n){if(!r.eql(s,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof n!="object"||typeof n.beta!="bigint"||typeof n.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}const{bytesToNumberBE:Lm,hexToBytes:Hm}=Em,Qn={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){const{Err:t}=Qn;if(e.length<2||e[0]!==2)throw new t("Invalid signature integer tag");const n=e[1],r=e.subarray(2,n+2);if(!n||r.length!==n)throw new t("Invalid signature integer: wrong length");if(r[0]===0&&r[1]<=127)throw new t("Invalid signature integer: trailing length");return{d:Lm(r),l:e.subarray(n+2)}},toSig(e){const{Err:t}=Qn,n=typeof e=="string"?Hm(e):e;if(!(n instanceof Uint8Array))throw new Error("ui8a expected");let r=n.length;if(r<2||n[0]!=48)throw new t("Invalid signature tag");if(n[1]!==r-2)throw new t("Invalid signature: incorrect length");const{d:s,l:o}=Qn._parseInt(n.subarray(2)),{d:i,l:a}=Qn._parseInt(o);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:s,s:i}},hexFromSig(e){const t=u=>Number.parseInt(u[0],16)>=8?"00"+u:u,n=u=>{const f=u.toString(16);return f.length&1?`0${f}`:f},r=t(n(e.s)),s=t(n(e.r)),o=r.length/2,i=s.length/2,a=n(o),c=n(i);return`30${n(i+o+4)}02${c}${s}02${a}${r}`}},$t=BigInt(0),je=BigInt(1),Xt=BigInt(2),Uo=BigInt(3),Fu=BigInt(4);function Rm(e){const t=Nm(e),{Fp:n}=t,r=t.toBytes||((g,h,y)=>{const m=h.toAffine();return kt(Uint8Array.from([4]),n.toBytes(m.x),n.toBytes(m.y))}),s=t.fromBytes||(g=>{const h=g.subarray(1),y=n.fromBytes(h.subarray(0,n.BYTES)),m=n.fromBytes(h.subarray(n.BYTES,2*n.BYTES));return{x:y,y:m}});function o(g){const{a:h,b:y}=t,m=n.sqr(g),x=n.mul(m,g);return n.add(n.add(x,n.mul(g,h)),y)}function i(g){return typeof g=="bigint"&&$tn.eql(w,n.ZERO);return x(y)&&x(m)?l.ZERO:new l(y,m,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){const y=n.invertBatch(h.map(m=>m.pz));return h.map((m,x)=>m.toAffine(y[x])).map(l.fromAffine)}static fromHex(h){const y=l.fromAffine(s(gt("pointHex",h)));return y.assertValidity(),y}static fromPrivateKey(h){return l.BASE.multiply(c(h))}_setWindowSize(h){this._WINDOW_SIZE=h,u.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint)return;throw new Error("bad point: ZERO")}const{x:h,y}=this.toAffine();if(!n.isValid(h)||!n.isValid(y))throw new Error("bad point: x or y not FE");const m=n.sqr(y),x=o(h);if(!n.eql(m,x))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:h}=this.toAffine();if(n.isOdd)return!n.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){f(h);const{px:y,py:m,pz:x}=this,{px:w,py:P,pz:b}=h,$=n.eql(n.mul(y,b),n.mul(w,x)),T=n.eql(n.mul(m,b),n.mul(P,x));return $&&T}negate(){return new l(this.px,n.neg(this.py),this.pz)}double(){const{a:h,b:y}=t,m=n.mul(y,Uo),{px:x,py:w,pz:P}=this;let b=n.ZERO,$=n.ZERO,T=n.ZERO,U=n.mul(x,x),O=n.mul(w,w),L=n.mul(P,P),_=n.mul(x,w);return _=n.add(_,_),T=n.mul(x,P),T=n.add(T,T),b=n.mul(h,T),$=n.mul(m,L),$=n.add(b,$),b=n.sub(O,$),$=n.add(O,$),$=n.mul(b,$),b=n.mul(_,b),T=n.mul(m,T),L=n.mul(h,L),_=n.sub(U,L),_=n.mul(h,_),_=n.add(_,T),T=n.add(U,U),U=n.add(T,U),U=n.add(U,L),U=n.mul(U,_),$=n.add($,U),L=n.mul(w,P),L=n.add(L,L),U=n.mul(L,_),b=n.sub(b,U),T=n.mul(L,O),T=n.add(T,T),T=n.add(T,T),new l(b,$,T)}add(h){f(h);const{px:y,py:m,pz:x}=this,{px:w,py:P,pz:b}=h;let $=n.ZERO,T=n.ZERO,U=n.ZERO;const O=t.a,L=n.mul(t.b,Uo);let _=n.mul(y,w),C=n.mul(m,P),k=n.mul(x,b),S=n.add(y,m),v=n.add(w,P);S=n.mul(S,v),v=n.add(_,C),S=n.sub(S,v),v=n.add(y,x);let A=n.add(w,b);return v=n.mul(v,A),A=n.add(_,k),v=n.sub(v,A),A=n.add(m,x),$=n.add(P,b),A=n.mul(A,$),$=n.add(C,k),A=n.sub(A,$),U=n.mul(O,v),$=n.mul(L,k),U=n.add($,U),$=n.sub(C,U),U=n.add(C,U),T=n.mul($,U),C=n.add(_,_),C=n.add(C,_),k=n.mul(O,k),v=n.mul(L,v),C=n.add(C,k),k=n.sub(_,k),k=n.mul(O,k),v=n.add(v,k),_=n.mul(C,v),T=n.add(T,_),_=n.mul(A,v),$=n.mul(S,$),$=n.sub($,_),_=n.mul(S,C),U=n.mul(A,U),U=n.add(U,_),new l($,T,U)}subtract(h){return this.add(h.negate())}is0(){return this.equals(l.ZERO)}wNAF(h){return p.wNAFCached(this,u,h,y=>{const m=n.invertBatch(y.map(x=>x.pz));return y.map((x,w)=>x.toAffine(m[w])).map(l.fromAffine)})}multiplyUnsafe(h){const y=l.ZERO;if(h===$t)return y;if(a(h),h===je)return this;const{endo:m}=t;if(!m)return p.unsafeLadder(this,h);let{k1neg:x,k1:w,k2neg:P,k2:b}=m.splitScalar(h),$=y,T=y,U=this;for(;w>$t||b>$t;)w&je&&($=$.add(U)),b&je&&(T=T.add(U)),U=U.double(),w>>=je,b>>=je;return x&&($=$.negate()),P&&(T=T.negate()),T=new l(n.mul(T.px,m.beta),T.py,T.pz),$.add(T)}multiply(h){a(h);let y=h,m,x;const{endo:w}=t;if(w){const{k1neg:P,k1:b,k2neg:$,k2:T}=w.splitScalar(y);let{p:U,f:O}=this.wNAF(b),{p:L,f:_}=this.wNAF(T);U=p.constTimeNegate(P,U),L=p.constTimeNegate($,L),L=new l(n.mul(L.px,w.beta),L.py,L.pz),m=U.add(L),x=O.add(_)}else{const{p:P,f:b}=this.wNAF(y);m=P,x=b}return l.normalizeZ([m,x])[0]}multiplyAndAddUnsafe(h,y,m){const x=l.BASE,w=(b,$)=>$===$t||$===je||!b.equals(x)?b.multiplyUnsafe($):b.multiply($),P=w(this,y).add(w(h,m));return P.is0()?void 0:P}toAffine(h){const{px:y,py:m,pz:x}=this,w=this.is0();h==null&&(h=w?n.ONE:n.inv(x));const P=n.mul(y,h),b=n.mul(m,h),$=n.mul(x,h);if(w)return{x:n.ZERO,y:n.ZERO};if(!n.eql($,n.ONE))throw new Error("invZ was invalid");return{x:P,y:b}}isTorsionFree(){const{h,isTorsionFree:y}=t;if(h===je)return!0;if(y)return y(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h,clearCofactor:y}=t;return h===je?this:y?y(l,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return this.assertValidity(),r(l,this,h)}toHex(h=!0){return Zr(this.toRawBytes(h))}}l.BASE=new l(t.Gx,t.Gy,n.ONE),l.ZERO=new l(n.ZERO,n.ONE,n.ZERO);const d=t.nBitLength,p=Um(l,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:i}}function jm(e){const t=Hf(e);return cs(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Km(e){const t=jm(e),{Fp:n,n:r}=t,s=n.BYTES+1,o=2*n.BYTES+1;function i(v){return $tZr(Lr(v,t.nByteLength));function g(v){const A=r>>je;return v>A}function h(v){return g(v)?a(-v):v}const y=(v,A,N)=>In(v.slice(A,N));class m{constructor(A,N,K){this.r=A,this.s=N,this.recovery=K,this.assertValidity()}static fromCompact(A){const N=t.nByteLength;return A=gt("compactSignature",A,N*2),new m(y(A,0,N),y(A,N,2*N))}static fromDER(A){const{r:N,s:K}=Qn.toSig(gt("DER",A));return new m(N,K)}assertValidity(){if(!d(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!d(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(A){return new m(this.r,this.s,A)}recoverPublicKey(A){const{r:N,s:K,recovery:H}=this,D=T(gt("msgHash",A));if(H==null||![0,1,2,3].includes(H))throw new Error("recovery id invalid");const q=H===2||H===3?N+t.n:N;if(q>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const G=(H&1)===0?"02":"03",fe=u.fromHex(G+p(q)),ce=c(q),ne=a(-D*ce),ge=a(K*ce),me=u.BASE.multiplyAndAddUnsafe(fe,ne,ge);if(!me)throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new m(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Vr(this.toDERHex())}toDERHex(){return Qn.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Vr(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const x={isValidPrivateKey(v){try{return f(v),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{const v=t.randomBytes(n.BYTES+8),A=Cm(v,r);return Lr(A,t.nByteLength)},precompute(v=8,A=u.BASE){return A._setWindowSize(v),A.multiply(BigInt(3)),A}};function w(v,A=!0){return u.fromPrivateKey(v).toRawBytes(A)}function P(v){const A=v instanceof Uint8Array,N=typeof v=="string",K=(A||N)&&v.length;return A?K===s||K===o:N?K===2*s||K===2*o:v instanceof u}function b(v,A,N=!0){if(P(v))throw new Error("first arg must be private key");if(!P(A))throw new Error("second arg must be public key");return u.fromHex(A).multiply(f(v)).toRawBytes(N)}const $=t.bits2int||function(v){const A=In(v),N=v.length*8-t.nBitLength;return N>0?A>>BigInt(N):A},T=t.bits2int_modN||function(v){return a($(v))},U=xc(t.nBitLength);function O(v){if(typeof v!="bigint")throw new Error("bigint expected");if(!($t<=v&&vpe in N))throw new Error("sign() legacy options not supported");const{hash:K,randomBytes:H}=t;let{lowS:D,prehash:q,extraEntropy:G}=N;D==null&&(D=!0),v=gt("msgHash",v),q&&(v=gt("prehashed msgHash",K(v)));const fe=T(v),ce=f(A),ne=[O(ce),O(fe)];if(G!=null){const pe=G===!0?H(n.BYTES):G;ne.push(gt("extraEntropy",pe,n.BYTES))}const ge=kt(...ne),me=fe;function Le(pe){const _e=$(pe);if(!d(_e))return;const Gt=c(_e),ht=u.BASE.multiply(_e).toAffine(),We=a(ht.x);if(We===$t)return;const Yt=a(Gt*a(me+We*ce));if(Yt===$t)return;let hs=(ht.x===We?0:2)|Number(ht.y&je),Ku=Yt;return D&&g(Yt)&&(Ku=h(Yt),hs^=1),new m(We,Ku,hs)}return{seed:ge,k2sig:Le}}const _={lowS:t.lowS,prehash:!1},C={lowS:t.lowS,prehash:!1};function k(v,A,N=_){const{seed:K,k2sig:H}=L(v,A,N);return Uf(t.hash.outputLen,t.nByteLength,t.hmac)(K,H)}u.BASE._setWindowSize(8);function S(v,A,N,K=C){var ht;const H=v;if(A=gt("msgHash",A),N=gt("publicKey",N),"strict"in K)throw new Error("options.strict was renamed to lowS");const{lowS:D,prehash:q}=K;let G,fe;try{if(typeof H=="string"||H instanceof Uint8Array)try{G=m.fromDER(H)}catch(We){if(!(We instanceof Qn.Err))throw We;G=m.fromCompact(H)}else if(typeof H=="object"&&typeof H.r=="bigint"&&typeof H.s=="bigint"){const{r:We,s:Yt}=H;G=new m(We,Yt)}else throw new Error("PARSE");fe=u.fromHex(N)}catch(We){if(We.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(D&&G.hasHighS())return!1;q&&(A=t.hash(A));const{r:ce,s:ne}=G,ge=T(A),me=c(ne),Le=a(ge*me),pe=a(ce*me),_e=(ht=u.BASE.multiplyAndAddUnsafe(fe,Le,pe))==null?void 0:ht.toAffine();return _e?a(_e.x)===ce:!1}return{CURVE:t,getPublicKey:w,getSharedSecret:b,sign:k,verify:S,ProjectivePoint:u,Signature:m,utils:x}}function Dm(e,t){const n=e.ORDER;let r=$t;for(let d=n-je;d%Xt===$t;d/=Xt)r+=je;const s=r,o=(n-je)/Xt**s,i=(o-je)/Xt,a=Xt**s-je,c=Xt**(s-je),u=e.pow(t,o),f=e.pow(t,(o+je)/Xt);let l=(d,p)=>{let g=u,h=e.pow(p,a),y=e.sqr(h);y=e.mul(y,p);let m=e.mul(d,y);m=e.pow(m,i),m=e.mul(m,h),h=e.mul(m,p),y=e.mul(m,d);let x=e.mul(y,h);m=e.pow(x,c);let w=e.eql(m,e.ONE);h=e.mul(y,f),m=e.mul(x,g),y=e.cmov(h,y,w),x=e.cmov(m,x,w);for(let P=s;P>1;P--){let b=Xt**(P-Xt),$=e.pow(x,b);const T=e.eql($,e.ONE);h=e.mul(y,g),g=e.mul(g,g),$=e.mul(x,g),y=e.cmov(h,y,T),x=e.cmov($,x,T)}return{isValid:w,value:y}};if(e.ORDER%Fu===Uo){const d=(e.ORDER-Uo)/Fu,p=e.sqrt(e.neg(t));l=(g,h)=>{let y=e.sqr(h);const m=e.mul(g,h);y=e.mul(y,m);let x=e.pow(y,d);x=e.mul(x,m);const w=e.mul(x,p),P=e.mul(e.sqr(x),h),b=e.eql(P,g);let $=e.cmov(w,x,b);return{isValid:b,value:$}}}return l}function Mm(e,t){if(Nf(e),!e.isValid(t.A)||!e.isValid(t.B)||!e.isValid(t.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");const n=Dm(e,t.Z);if(!e.isOdd)throw new Error("Fp.isOdd is not implemented!");return r=>{let s,o,i,a,c,u,f,l;s=e.sqr(r),s=e.mul(s,t.Z),o=e.sqr(s),o=e.add(o,s),i=e.add(o,e.ONE),i=e.mul(i,t.B),a=e.cmov(t.Z,e.neg(o),!e.eql(o,e.ZERO)),a=e.mul(a,t.A),o=e.sqr(i),u=e.sqr(a),c=e.mul(u,t.A),o=e.add(o,c),o=e.mul(o,i),u=e.mul(u,a),c=e.mul(u,t.B),o=e.add(o,c),f=e.mul(s,i);const{isValid:d,value:p}=n(o,u);l=e.mul(s,r),l=e.mul(l,p),f=e.cmov(f,i,d),l=e.cmov(l,p,d);const g=e.isOdd(r)===e.isOdd(l);return l=e.cmov(e.neg(l),l,g),f=e.div(f,a),{x:f,y:l}}}function Zm(e){if(e instanceof Uint8Array)return e;if(typeof e=="string")return mi(e);throw new Error("DST must be Uint8Array or string")}const Vm=In;function An(e,t){if(e<0||e>=1<<8*t)throw new Error(`bad I2OSP call: value=${e} length=${t}`);const n=Array.from({length:t}).fill(0);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return new Uint8Array(n)}function qm(e,t){const n=new Uint8Array(e.length);for(let r=0;r255&&(t=r(kt(mi("H2C-OVERSIZE-DST-"),t)));const{outputLen:s,blockLen:o}=r,i=Math.ceil(n/s);if(i>255)throw new Error("Invalid xmd length");const a=kt(t,An(t.length,1)),c=An(0,o),u=An(n,2),f=new Array(i),l=r(kt(c,e,u,An(0,1),a));f[0]=r(kt(l,An(1,1),a));for(let p=1;p<=i;p++){const g=[qm(l,f[p-1]),An(p+1,1),a];f[p]=r(kt(...g))}return kt(...f).slice(0,n)}function Fm(e,t,n,r,s){if(_s(e),_s(t),kc(n),t.length>255){const o=Math.ceil(2*r/8);t=s.create({dkLen:o}).update(mi("H2C-OVERSIZE-DST-")).update(t).digest()}if(n>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return s.create({dkLen:n}).update(e).update(An(n,2)).update(t).update(An(t.length,1)).digest()}function Wu(e,t,n){cs(n,{DST:"string",p:"bigint",m:"isSafeInteger",k:"isSafeInteger",hash:"hash"});const{p:r,k:s,m:o,hash:i,expand:a,DST:c}=n;_s(e),kc(t);const u=Zm(c),f=r.toString(2).length,l=Math.ceil((f+s)/8),d=t*o*l;let p;if(a==="xmd")p=zm(e,u,d,i);else if(a==="xof")p=Fm(e,u,d,s,i);else if(a===void 0)p=e;else throw new Error('expand must be "xmd", "xof" or undefined');const g=new Array(t);for(let h=0;hArray.from(r).reverse());return(r,s)=>{const[o,i,a,c]=n.map(u=>u.reduce((f,l)=>e.add(e.mul(f,r),l)));return r=e.div(o,i),s=e.mul(s,e.div(a,c)),{x:r,y:s}}}function Gm(e,t,n){if(typeof t!="function")throw new Error("mapToCurve() must be defined");return{hashToCurve(r,s){const o=Wu(r,2,{...n,DST:n.DST,...s}),i=e.fromAffine(t(o[0])),a=e.fromAffine(t(o[1])),c=i.add(a).clearCofactor();return c.assertValidity(),c},encodeToCurve(r,s){const o=Wu(r,1,{...n,DST:n.encodeDST,...s}),i=e.fromAffine(t(o[0])).clearCofactor();return i.assertValidity(),i}}}let Rf=class extends Bf{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Jn.hash(t);const r=mc(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new TypeError("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?t.create().update(r).digest():r);for(let i=0;inew Rf(e,t).update(n).digest();jf.create=(e,t)=>new Rf(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ym(e){return{hash:e,hmac:(t,...n)=>jf(e,t,am(...n)),randomBytes:cm}}function Xm(e,t){const n=r=>Km({...e,...Ym(r)});return Object.freeze({...n(t),create:n})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Kf=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Gu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Jm=BigInt(1),Ba=BigInt(2),Yu=(e,t)=>(e+t/Ba)/t;function Qm(e){const t=Kf,n=BigInt(3),r=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,f=u*u*e%t,l=pt(f,n,t)*f%t,d=pt(l,n,t)*f%t,p=pt(d,Ba,t)*u%t,g=pt(p,s,t)*p%t,h=pt(g,o,t)*g%t,y=pt(h,a,t)*h%t,m=pt(y,c,t)*y%t,x=pt(m,a,t)*h%t,w=pt(x,n,t)*f%t,P=pt(w,i,t)*g%t,b=pt(P,r,t)*u%t,$=pt(b,Ba,t);if(!Pn.eql(Pn.sqr($),e))throw new Error("Cannot find square root");return $}const Pn=Lf(Kf,void 0,void 0,{sqrt:Qm}),an=Xm({a:BigInt(0),b:BigInt(7),Fp:Pn,n:Gu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Gu,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Jm*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=n,i=BigInt("0x100000000000000000000000000000000"),a=Yu(o*e,t),c=Yu(-r*e,t);let u=Qe(e-a*n-c*s,t),f=Qe(-a*r-c*o,t);const l=u>i,d=f>i;if(l&&(u=t-u),d&&(f=t-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:l,k1:u,k2neg:d,k2:f}}}},If);BigInt(0);an.ProjectivePoint;an.utils.randomPrivateKey;const ey=Wm(Pn,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),ty=Mm(Pn,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:Pn.create(BigInt("-11"))});Gm(an.ProjectivePoint,e=>{const{x:t,y:n}=ty(Pn.create(e[0]));return ey(t,n)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:Pn.ORDER,m:1,k:128,expand:"xmd",hash:If});function Ta(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function ny(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function Df(e,...t){if(!(e instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new TypeError(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function ry(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ta(e.outputLen),Ta(e.blockLen)}function sy(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function oy(e,t){Df(e);const n=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),Nt=(e,t)=>e<<32-t|e>>>t,ay=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ay)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function cy(e){if(typeof e!="string")throw new TypeError(`utf8ToBytes expected string, got ${typeof e}`);return new TextEncoder().encode(e)}function Mf(e){if(typeof e=="string"&&(e=cy(e)),!(e instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof e})`);return e}let uy=class{clone(){return this._cloneInto()}};function Zf(e){const t=r=>e().update(Mf(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function ly(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const s=BigInt(32),o=BigInt(4294967295),i=Number(n>>s&o),a=Number(n&o),c=r?4:0,u=r?0:4;e.setUint32(t+c,i,r),e.setUint32(t+u,a,r)}let fy=class extends uy{constructor(t,n,r,s){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Xi(this.buffer)}update(t){Yi.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=Mf(t);const o=t.length;for(let i=0;is-i&&(this.process(r,0),i=0);for(let l=i;lf.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;le&t^~e&n,hy=(e,t,n)=>e&t^e&n^t&n,py=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),mn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),yn=new Uint32Array(64);let Vf=class extends fy{constructor(){super(64,32,8,!1),this.A=mn[0]|0,this.B=mn[1]|0,this.C=mn[2]|0,this.D=mn[3]|0,this.E=mn[4]|0,this.F=mn[5]|0,this.G=mn[6]|0,this.H=mn[7]|0}get(){const{A:t,B:n,C:r,D:s,E:o,F:i,G:a,H:c}=this;return[t,n,r,s,o,i,a,c]}set(t,n,r,s,o,i,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,n){for(let l=0;l<16;l++,n+=4)yn[l]=t.getUint32(n,!1);for(let l=16;l<64;l++){const d=yn[l-15],p=yn[l-2],g=Nt(d,7)^Nt(d,18)^d>>>3,h=Nt(p,17)^Nt(p,19)^p>>>10;yn[l]=h+yn[l-7]+g+yn[l-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){const d=Nt(a,6)^Nt(a,11)^Nt(a,25),p=f+d+dy(a,c,u)+py[l]+yn[l]|0,h=(Nt(r,2)^Nt(r,13)^Nt(r,22))+hy(r,s,o)|0;f=u,u=c,c=a,a=i+p|0,i=o,o=s,s=r,r=p+h|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,s,o,i,a,c,u,f)}roundClean(){yn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},gy=class extends Vf{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}};const Oa=Zf(()=>new Vf);Zf(()=>new gy);function my(e,t){if(e.length>t)throw new TypeError(`Data is larger than array size: ${e.length} > ${t}`)}function yy(e){if(e.match(/[^a-fA-f0-9]/)!==null)throw new TypeError("Invalid characters in hex string: "+e);if(e.length%2!==0)throw new Error(`Length of hex string is invalid: ${e.length}`)}function wy(e){if(e>Number.MAX_SAFE_INTEGER)throw new TypeError("Number exceeds safe bounds!")}const{getRandomValues:by}=crypto??globalThis.crypto??window.crypto;function xy(e=32){if(typeof by=="function")return crypto.getRandomValues(new Uint8Array(e));throw new Error("Crypto module missing getRandomValues!")}function vy(e,t,n="be"){t===void 0&&(t=e.length),my(e,t);const r=new Uint8Array(t).fill(0),s=n==="be"?0:t-e.length;return r.set(e,s),r}function qf(e){let t,n=0;const r=e.reduce((o,i)=>o+i.length,0),s=new Uint8Array(r);for(t=0;t0||(i.length^a)>0?"":"1";c in o||u>0;)f=o[c],f=f>0?f*256+u:u,u=f/s|0,o[c]=f%s,c++;for(;c-- >0;)i+=r[o[c]];return n&&i.length%4>0?i+"=".repeat(4-i.length%4):i}function Sy(e,t){const n=zf(t),r=n.length,s=[],o=[];e=e.replace("=","");let i,a=0,c,u;for(i=0;i0||(o.length^i)>0||o.push(0);a in s||c>0;)u=s[a],u=u>0?u*r+c:c,c=u>>8,s[a]=u%256,a++}for(;a-- >0;)o.push(s[a]);return new Uint8Array(o)}function Ff(e){return Oa(Oa(e))}function _y(e){const t=Ff(e);return qf([e,t.slice(0,4)])}function Ay(e){const t=e.slice(0,-4),n=e.slice(-4);if(Ff(t).slice(0,4).toString()!==n.toString())throw new Error("Invalid checksum!");return t}const Xu={encode:Ey,decode:Sy},Wf={encode:e=>{const t=_y(e);return Xu.encode(t,"base58")},decode:e=>{const t=Xu.decode(e,"base58");return Ay(t)}},Gf="qpzry9x8gf2tvdw0s3jn54khce6mua7l",By=[996825010,642813549,513874426,1027748829,705979059],No=[{version:0,name:"bech32",const:1},{version:1,name:"bech32m",const:734539939}];function Yf(e){let t=1;for(let n=0;n>25;t=(t&33554431)<<5^e[n];for(let s=0;s<5;++s)(r>>s&1)!==0&&(t^=By[s])}return t}function Xf(e){const t=[];let n;for(n=0;n>5);for(t.push(0),n=0;n>5*(5-i)&31);return o}function Jf(e,t,n,r=!0){const s=[];let o=0,i=0;const a=(1<>t>0)throw new Error("Failed to perform base conversion. Invalid value: "+String(u));for(o=(o<=n;)i-=n,s.push(o>>i&a)}if(r)i>0&&s.push(o<=t||(o<0)throw new Error("Failed to perform base conversion. Invalid Size!");return s}function Iy(e,t,n){const r=t.concat(Oy(e,t,n));let s=e+"1";for(let o=0;oo.version===t[0])??No[0];if(!Ty(r,t,s))throw new Error("Checksum verification failed!");return[r,t.slice(0,t.length-6)]}function Cy(e){let t,n,r=!1,s=!1;for(t=0;t126)return!1;n>=97&&n<=122&&(r=!0),n>=65&&n<=90&&(s=!0)}return!(r&&s)}function Py(e){const t=e.lastIndexOf("1");return!(t<1||t+7>e.length||e.length>90)}function Uy(e,t="bc",n=0){const r=[n,...Jf([...e],8,5)],s=No.find(i=>i.version===n)??No[0],o=Iy(t,r,s);return ed(o),o}function ed(e){e=e.toLowerCase();const t=e.split("1",1)[0],[n,r]=Qf(e),s=Jf(r.slice(1),5,8,!1),o=s.length;switch(!0){case t!==n:throw new Error("Returned hrp string is invalid.");case(s===null||o<2||o>40):throw new Error("Decoded string is invalid or out of spec.");case r[0]>16:throw new Error("Returned version bit is out of range.");default:return Uint8Array.from(s)}}function Ny(e){e=e.toLowerCase();const[t,n]=Qf(e);return n[0]}const td={encode:Uy,decode:ed,version:Ny},nd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",rd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Ly=new TextEncoder;function sd(e,t=!1,n=!0){typeof e=="string"&&(e=Ly.encode(e));const r=t?rd:nd;let s="",o=0,i=0;for(let a=0;a=6;)o-=6,s+=r[i>>o&63];if(o>0)for(i<<=6-o,s+=r[i&63];o<6;)s+=n?"=":"",o+=2;return s}function od(e,t=!1){const n=t||e.includes("-")||e.includes("_")?rd.split(""):nd.split("");e=e.replace(/=+$/,"");const r=e.split("");let s=0,o=0;const i=[];for(let a=0;a=8&&(s-=8,i.push(o>>>s&255))}return new Uint8Array(i)}const id={encode:sd,decode:od},ad={encode:e=>sd(e,!0,!1),decode:e=>od(e,!0)},Hy=BigInt(0),Ry=BigInt(255),cd=BigInt(256);function jy(e){if(e<=0xffn)return 1;if(e<=0xffffn)return 2;if(e<=0xffffffffn)return 4;if(e<=0xffffffffffffffffn)return 8;if(e<=0xffffffffffffffffffffffffffffffffn)return 16;if(e<=0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn)return 32;throw new TypeError("Must specify a fixed buffer size for bigints greater than 32 bytes.")}function Ky(e,t,n="be"){t===void 0&&(t=jy(e));const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(;e>Hy;){const a=e&Ry,c=Number(a);r?o.setUint8(i++,c):o.setUint8(i--,c),e=(e-a)/cd}return new Uint8Array(s)}function Dy(e){let t=BigInt(0);for(let n=e.length-1;n>=0;n--)t=t*cd+BigInt(e[n]);return BigInt(t)}function My(e){const t=e.split("").map(Number);if(t.length%8!==0)throw new Error(`Binary array is invalid length: ${e.length}`);const n=new Uint8Array(t.length/8);for(let r=0,s=0;r255)throw new Error(`Invalid byte value: ${r}. Byte values must be between 0 and 255.`);for(let s=7;s>=0;s--,n++)t[n]=r>>s&1}return t.join("")}function Vy(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=4294967295)return 4;throw new TypeError("Numbers larger than 4 bytes must specify a fixed size!")}function qy(e,t,n="be"){t===void 0&&(t=Vy(e));const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(;e>0;){const a=e&255;r?o.setUint8(i++,e):o.setUint8(i--,e),e=(e-a)/256}return new Uint8Array(s)}function zy(e){let t=0;for(let n=e.length-1;n>=0;n--)t=t*256+e[n],wy(t);return t}const Fy=new TextEncoder,Wy=new TextDecoder;function $c(e){return Fy.encode(e)}function Ji(e){return Wy.decode(e)}function Gy(e,t){yy(e);const n=e.length/2;if(t===void 0&&(t=n),n>t)throw new TypeError(`Hex string is larger than array size: ${n} > ${t}`);return t}function Yy(e,t,n="le"){t=Gy(e,t);const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(let a=0;atypeof r=="bigint"?`${r}n`:r);return $c(t)}function Qy(e,t,n){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Uint8Array)return vy(e,t,n);if(typeof e=="string")return Yy(e,t,n);if(typeof e=="bigint")return Ky(e,t,n);if(typeof e=="number")return qy(e,t,n);if(typeof e=="boolean")return Uint8Array.of(e?1:0);throw TypeError("Unsupported format:"+typeof e)}const ie=class ie extends Uint8Array{static random(t=32){const n=xy(t);return new ie(n,t)}constructor(t,n,r){const s=Qy(t,n,r);super(s)}get arr(){return[...this]}get num(){return this.toNum()}get big(){return this.toBig()}get str(){return this.toStr()}get hex(){return this.toHex()}get raw(){return new Uint8Array(this)}get bin(){return this.toBin()}get b58chk(){return this.tob58chk()}get base64(){return this.toBase64()}get b64url(){return this.toB64url()}get digest(){return this.toHash()}get id(){return this.toHash().hex}get stream(){return new dw(this)}toNum(t="be"){const n=t==="be"?this.reverse():this;return zy(n)}toBin(){return Zy(this)}toBig(t="be"){const n=t==="be"?this.reverse():this;return Dy(n)}toHash(){const t=Oa(this);return new ie(t)}toJson(){const t=Ji(this);return JSON.parse(t)}toBech32(t,n=0){return td.encode(this,t,n)}toStr(){return Ji(this)}toHex(){return Xy(this)}toBytes(){return new Uint8Array(this)}tob58chk(){return Wf.encode(this)}toBase64(){return id.encode(this)}toB64url(){return ad.encode(this)}prepend(t){return ie.join([ie.bytes(t),this])}append(t){return ie.join([this,ie.bytes(t)])}slice(t,n){const r=new Uint8Array(this).slice(t,n);return new ie(r)}subarray(t,n){const r=new Uint8Array(this).subarray(t,n);return new ie(r)}reverse(){const t=new Uint8Array(this).reverse();return new ie(t)}write(t,n){const r=ie.bytes(t);this.set(r,n)}prefixSize(t){const n=ie.varInt(this.length,t);return ie.join([n,this])}static from(t){return new ie(Uint8Array.from(t))}static of(...t){return new ie(Uint8Array.of(...t))}static join(t){const n=t.map(s=>ie.bytes(s)),r=qf(n);return new ie(r)}static varInt(t,n){if(t<253)return ie.num(t,1);if(t<65536)return ie.of(253,...ie.num(t,2,n));if(t<4294967296)return ie.of(254,...ie.num(t,4,n));if(BigInt(t)<0x10000000000000000n)return ie.of(255,...ie.num(t,8,n));throw new Error(`Value is too large: ${t}`)}};ie.num=ew,ie.big=nw,ie.bin=tw,ie.raw=rw,ie.str=sw,ie.hex=ow,ie.bytes=iw,ie.json=aw,ie.base64=cw,ie.b64url=uw,ie.bech32=lw,ie.b58chk=fw,ie.encode=$c,ie.decode=Ji;let ee=ie;function ew(e,t,n){return new ee(e,t,n)}function tw(e,t,n){return new ee(My(e),t,n)}function nw(e,t,n){return new ee(e,t,n)}function rw(e,t,n){return new ee(e,t,n)}function sw(e,t,n){return new ee($c(e),t,n)}function ow(e,t,n){return new ee(e,t,n)}function iw(e,t,n){return new ee(e,t,n)}function aw(e){return new ee(Jy(e))}function cw(e){return new ee(id.decode(e))}function uw(e){return new ee(ad.decode(e))}function lw(e){return new ee(td.decode(e))}function fw(e){return new ee(Wf.decode(e))}class dw{constructor(t){this.data=ee.bytes(t),this.size=this.data.length}peek(t){if(t>this.size)throw new Error(`Size greater than stream: ${t} > ${this.size}`);return new ee(this.data.slice(0,t))}read(t){t=t??this.readSize();const n=this.peek(t);return this.data=this.data.slice(t),this.size=this.data.length,n}readSize(t){const n=this.read(1).num;switch(!0){case(n>=0&&n<253):return n;case n===253:return this.read(2).toNum(t);case n===254:return this.read(4).toNum(t);case n===255:return this.read(8).toNum(t);default:throw new Error(`Varint is out of range: ${n}`)}}}const Lo=an.CURVE,Ec=Lo.n,hw=Lo.p,pw={x:Lo.Gx,y:Lo.Gy},gw=BigInt(0);BigInt(1);BigInt(2);BigInt(3);BigInt(4);const Ia={N:Ec,P:hw,G:pw,_0n:gw},ps=Lf(Ec,32,!0),ud=e=>Qe(e,Ec);function Sc(e,t=!1){if(t)throw new Error(e);return!1}function ld(e){return ee.random(e)}function mw(e){const t=ee.bytes(e).big;return ee.big(ud(t),32)}var yw=Object.freeze({__proto__:null,fail:Sc,mod_bytes:mw,random:ld});const{N:ww,_0n:bw}=Ia;function xw(e,t,n){const r=ee.bytes(e);return r.length!==t?Sc(`Invalid byte size: ${r.hex} !== ${t}`,n):!0}function vw(e,t){return typeof e=="bigint"&&bwthis.big}lt(t){return new Be(t).big0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function Sw(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ca(e.outputLen),Ca(e.blockLen)}function _w(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Aw(e,t){fd(e);const n=t.outputLen;if(e.lengthe instanceof Uint8Array,Qi=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),Lt=(e,t)=>e<<32-t|e>>>t,Ow=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Ow)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Iw(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function _c(e){if(typeof e=="string"&&(e=Iw(e)),!Tw(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}let dd=class{clone(){return this._cloneInto()}};function vr(e){const t=r=>e().update(_c(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Cw(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const s=BigInt(32),o=BigInt(4294967295),i=Number(n>>s&o),a=Number(n&o),c=r?4:0,u=r?0:4;e.setUint32(t+c,i,r),e.setUint32(t+u,a,r)}class Ac extends dd{constructor(t,n,r,s){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Qi(this.buffer)}update(t){er.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=_c(t);const o=t.length;for(let i=0;is-i&&(this.process(r,0),i=0);for(let l=i;lf.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;le&t^~e&n,Uw=(e,t,n)=>e&t^e&n^t&n,Nw=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),wn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),bn=new Uint32Array(64);let hd=class extends Ac{constructor(){super(64,32,8,!1),this.A=wn[0]|0,this.B=wn[1]|0,this.C=wn[2]|0,this.D=wn[3]|0,this.E=wn[4]|0,this.F=wn[5]|0,this.G=wn[6]|0,this.H=wn[7]|0}get(){const{A:t,B:n,C:r,D:s,E:o,F:i,G:a,H:c}=this;return[t,n,r,s,o,i,a,c]}set(t,n,r,s,o,i,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,n){for(let l=0;l<16;l++,n+=4)bn[l]=t.getUint32(n,!1);for(let l=16;l<64;l++){const d=bn[l-15],p=bn[l-2],g=Lt(d,7)^Lt(d,18)^d>>>3,h=Lt(p,17)^Lt(p,19)^p>>>10;bn[l]=h+bn[l-7]+g+bn[l-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){const d=Lt(a,6)^Lt(a,11)^Lt(a,25),p=f+d+Pw(a,c,u)+Nw[l]+bn[l]|0,h=(Lt(r,2)^Lt(r,13)^Lt(r,22))+Uw(r,s,o)|0;f=u,u=c,c=a,a=i+p|0,i=o,o=s,s=r,r=p+h|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,s,o,i,a,c,u,f)}roundClean(){bn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};class Lw extends hd{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const Ho=vr(()=>new hd);vr(()=>new Lw);const oo=BigInt(2**32-1),Pa=BigInt(32);function pd(e,t=!1){return t?{h:Number(e&oo),l:Number(e>>Pa&oo)}:{h:Number(e>>Pa&oo)|0,l:Number(e&oo)|0}}function Hw(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let s=0;sBigInt(e>>>0)<>>0),jw=(e,t,n)=>e>>>n,Kw=(e,t,n)=>e<<32-n|t>>>n,Dw=(e,t,n)=>e>>>n|t<<32-n,Mw=(e,t,n)=>e<<32-n|t>>>n,Zw=(e,t,n)=>e<<64-n|t>>>n-32,Vw=(e,t,n)=>e>>>n-32|t<<64-n,qw=(e,t)=>t,zw=(e,t)=>e,Fw=(e,t,n)=>e<>>32-n,Ww=(e,t,n)=>t<>>32-n,Gw=(e,t,n)=>t<>>64-n,Yw=(e,t,n)=>e<>>64-n;function Xw(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}const Jw=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Qw=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,eb=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),tb=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,nb=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),rb=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,sb={fromBig:pd,split:Hw,toBig:Rw,shrSH:jw,shrSL:Kw,rotrSH:Dw,rotrSL:Mw,rotrBH:Zw,rotrBL:Vw,rotr32H:qw,rotr32L:zw,rotlSH:Fw,rotlSL:Ww,rotlBH:Gw,rotlBL:Yw,add:Xw,add3L:Jw,add3H:Qw,add4L:eb,add4H:tb,add5H:rb,add5L:nb};var oe=sb;const[ob,ib]=oe.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),xn=new Uint32Array(80),vn=new Uint32Array(80);let yi=class extends Ac{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:t,Al:n,Bh:r,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:p,Gl:g,Hh:h,Hl:y}=this;return[t,n,r,s,o,i,a,c,u,f,l,d,p,g,h,y]}set(t,n,r,s,o,i,a,c,u,f,l,d,p,g,h,y){this.Ah=t|0,this.Al=n|0,this.Bh=r|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=p|0,this.Gl=g|0,this.Hh=h|0,this.Hl=y|0}process(t,n){for(let w=0;w<16;w++,n+=4)xn[w]=t.getUint32(n),vn[w]=t.getUint32(n+=4);for(let w=16;w<80;w++){const P=xn[w-15]|0,b=vn[w-15]|0,$=oe.rotrSH(P,b,1)^oe.rotrSH(P,b,8)^oe.shrSH(P,b,7),T=oe.rotrSL(P,b,1)^oe.rotrSL(P,b,8)^oe.shrSL(P,b,7),U=xn[w-2]|0,O=vn[w-2]|0,L=oe.rotrSH(U,O,19)^oe.rotrBH(U,O,61)^oe.shrSH(U,O,6),_=oe.rotrSL(U,O,19)^oe.rotrBL(U,O,61)^oe.shrSL(U,O,6),C=oe.add4L(T,_,vn[w-7],vn[w-16]),k=oe.add4H(C,$,L,xn[w-7],xn[w-16]);xn[w]=k|0,vn[w]=C|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:p,Fl:g,Gh:h,Gl:y,Hh:m,Hl:x}=this;for(let w=0;w<80;w++){const P=oe.rotrSH(l,d,14)^oe.rotrSH(l,d,18)^oe.rotrBH(l,d,41),b=oe.rotrSL(l,d,14)^oe.rotrSL(l,d,18)^oe.rotrBL(l,d,41),$=l&p^~l&h,T=d&g^~d&y,U=oe.add5L(x,b,T,ib[w],vn[w]),O=oe.add5H(U,m,P,$,ob[w],xn[w]),L=U|0,_=oe.rotrSH(r,s,28)^oe.rotrBH(r,s,34)^oe.rotrBH(r,s,39),C=oe.rotrSL(r,s,28)^oe.rotrBL(r,s,34)^oe.rotrBL(r,s,39),k=r&o^r&a^o&a,S=s&i^s&c^i&c;m=h|0,x=y|0,h=p|0,y=g|0,p=l|0,g=d|0,{h:l,l:d}=oe.add(u|0,f|0,O|0,L|0),u=a|0,f=c|0,a=o|0,c=i|0,o=r|0,i=s|0;const v=oe.add3L(L,C,S);r=oe.add3H(v,O,_,k),s=v|0}({h:r,l:s}=oe.add(this.Ah|0,this.Al|0,r|0,s|0)),{h:o,l:i}=oe.add(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=oe.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=oe.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=oe.add(this.Eh|0,this.El|0,l|0,d|0),{h:p,l:g}=oe.add(this.Fh|0,this.Fl|0,p|0,g|0),{h,l:y}=oe.add(this.Gh|0,this.Gl|0,h|0,y|0),{h:m,l:x}=oe.add(this.Hh|0,this.Hl|0,m|0,x|0),this.set(r,s,o,i,a,c,u,f,l,d,p,g,h,y,m,x)}roundClean(){xn.fill(0),vn.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class ab extends yi{constructor(){super(),this.Ah=-1942145080,this.Al=424955298,this.Bh=1944164710,this.Bl=-1982016298,this.Ch=502970286,this.Cl=855612546,this.Dh=1738396948,this.Dl=1479516111,this.Eh=258812777,this.El=2077511080,this.Fh=2011393907,this.Fl=79989058,this.Gh=1067287976,this.Gl=1780299464,this.Hh=286451373,this.Hl=-1848208735,this.outputLen=28}}class cb extends yi{constructor(){super(),this.Ah=573645204,this.Al=-64227540,this.Bh=-1621794909,this.Bl=-934517566,this.Ch=596883563,this.Cl=1867755857,this.Dh=-1774684391,this.Dl=1497426621,this.Eh=-1775747358,this.El=-1467023389,this.Fh=-1101128155,this.Fl=1401305490,this.Gh=721525244,this.Gl=746961066,this.Hh=246885852,this.Hl=-2117784414,this.outputLen=32}}class ub extends yi{constructor(){super(),this.Ah=-876896931,this.Al=-1056596264,this.Bh=1654270250,this.Bl=914150663,this.Ch=-1856437926,this.Cl=812702999,this.Dh=355462360,this.Dl=-150054599,this.Eh=1731405415,this.El=-4191439,this.Fh=-1900787065,this.Fl=1750603025,this.Gh=-619958771,this.Gl=1694076839,this.Hh=1203062813,this.Hl=-1090891868,this.outputLen=48}}const lb=vr(()=>new yi);vr(()=>new ab);vr(()=>new cb);vr(()=>new ub);const fb=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),gd=Uint8Array.from({length:16},(e,t)=>t),db=gd.map(e=>(9*e+5)%16);let Bc=[gd],Tc=[db];for(let e=0;e<4;e++)for(let t of[Bc,Tc])t.push(t[e].map(n=>fb[n]));const md=[[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=>new Uint8Array(e)),hb=Bc.map((e,t)=>e.map(n=>md[t][n])),pb=Tc.map((e,t)=>e.map(n=>md[t][n])),gb=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),mb=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),io=(e,t)=>e<>>32-t;function Qu(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)}const ao=new Uint32Array(16);let yb=class extends Ac{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:n,h2:r,h3:s,h4:o}=this;return[t,n,r,s,o]}set(t,n,r,s,o){this.h0=t|0,this.h1=n|0,this.h2=r|0,this.h3=s|0,this.h4=o|0}process(t,n){for(let p=0;p<16;p++,n+=4)ao[p]=t.getUint32(n,!0);let r=this.h0|0,s=r,o=this.h1|0,i=o,a=this.h2|0,c=a,u=this.h3|0,f=u,l=this.h4|0,d=l;for(let p=0;p<5;p++){const g=4-p,h=gb[p],y=mb[p],m=Bc[p],x=Tc[p],w=hb[p],P=pb[p];for(let b=0;b<16;b++){const $=io(r+Qu(p,o,a,u)+ao[m[b]]+h,w[b])+l|0;r=l,l=u,u=io(a,10)|0,a=o,o=$}for(let b=0;b<16;b++){const $=io(s+Qu(g,i,c,f)+ao[x[b]]+y,P[b])+d|0;s=d,d=f,f=io(c,10)|0,c=i,i=$}}this.set(this.h1+a+f|0,this.h2+u+d|0,this.h3+l+s|0,this.h4+r+i|0,this.h0+o+c|0)}roundClean(){ao.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}};const wb=vr(()=>new yb);let yd=class extends dd{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,er.hash(t);const r=_c(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?t.create().update(r).digest():r);for(let i=0;inew yd(e,t).update(n).digest();wd.create=(e,t)=>new yd(e,t);function bb(e){const t=ee.bytes(e);return ee.raw(Ho(t))}function qr(e){const t=ee.bytes(e);return ee.raw(Ho(Ho(t)))}function Oc(e){const t=ee.bytes(e);return ee.raw(wb(Ho(t)))}function xb(e,t){const n=ee.bytes(e),r=ee.bytes(t);return ee.raw(wd(lb,n,r))}function vb(e){const t=ee.str(e).digest;return ee.join([t,t])}function kb(e=32){return Ic(ld(e))}function Ic(e){return nt.mod(e).buff}function bd(e,t=!1){const n=nt.mod(e).point;return t?n.x:n.buff}function xd(e,t){const n=xr.from_x(t),r=nt.mod(e);return n.mul(r).buff}function $b(e,t,n="ecdh/code"){const r=vb(n),s=Ic(e),o=bd(s),i=ee.bytes(t),a=xd(s,i),c=[o.hex,i.hex];return c.sort(),xb(a,ee.join([r,...c]))}function Eb(e){const t=ee.bytes(e);switch(!0){case t.length===32:return!0;case(t.length===33&&t[0]===2):return!0;case(t.length===33&&t[0]===3):return!1;default:throw new TypeError(`Invalid public key: ${t.hex}`)}}function Sb(e){const t=ee.bytes(e);switch(t.length){case 32:return t;case 33:return t.slice(1,33);default:throw new Error(`Invalid key length: ${t.length}`)}}var _b=Object.freeze({__proto__:null,genSecretKey:kb,getPublicKey:bd,getSecretKey:Ic,getSharedCode:$b,getSharedKey:xd,is_even_pub:Eb,xonly_pub:Sb});ee.random(32);const vd={secp:an},Ua={..._b,...yw};function wi(e){const t=B.bytes(e);return Ft(t,33),Oc(t)}function kd(e){const t=Ce.fmt.toBytes(e,!1);return Oc(t)}function $d(e){const t=Ce.fmt.toBytes(e,!1);return bb(t)}function Ed(e,t="main"){const n=t==="main"?["1"]:["m","n"];for(const r of n)if(e.startsWith(r))return!0;return!1}function Sd(e,t="main"){const n=B.bytes(e),r=t==="main"?B.num(0):B.num(111);return Ft(e,20),n.prepend(r).tob58chk()}function Ab(e,t="main"){if(!Ed(e,t))throw new TypeError("Invalid p2pkh address!");return B.b58chk(e).slice(1)}function Bb(e){const t=B.bytes(e);return Ft(t,20),["OP_DUP","OP_HASH160",t.hex,"OP_EQUALVERIFY","OP_CHECKSIG"]}function Tb(e,t){const n=wi(e);return Sd(n,t)}const _d={check:Ed,encode:Sd,decode:Ab,hash:wi,scriptPubKey:Bb,fromPubKey:Tb};function Ad(e,t="main"){const n=t==="main"?["3"]:["2"];for(const r of n)if(e.startsWith(r))return!0;return!1}function Bd(e,t="main"){const n=t==="main"?B.num(5):B.num(196),r=B.bytes(e);return Ft(r,20),r.prepend(n).tob58chk()}function Ob(e,t="main"){if(!Ad(e,t))throw new TypeError(`Invalid p2sh address for network ${t}:`+e);return B.b58chk(e).slice(1)}function Ib(e){return["OP_HASH160",B.bytes(e).hex,"OP_EQUAL"]}function Cb(e,t){const n=kd(e);return Bd(n,t)}const Td={check:Ad,encode:Bd,decode:Ob,hash:kd,scriptPubKey:Ib,fromScript:Cb},Cc={main:"bc",testnet:"tb",signet:"tb",regtest:"bcrt"},Pb=["bc1q","tb1q","bcrt1q"];function Od(e){for(const t of Pb)if(e.startsWith(t))return!0;return!1}function Id(e,t="main"){const n=Cc[t],r=B.bytes(e);return Ft(r,20),r.toBech32(n,0)}function Ub(e){if(!Od(e))throw new TypeError("Invalid segwit address!");return B.bech32(e)}function Nb(e){const t=B.bytes(e);return Ft(t,20),["OP_0",t.hex]}function Lb(e,t){const n=wi(e);return Id(n,t)}const Cd={check:Od,encode:Id,decode:Ub,hash:wi,scriptPubKey:Nb,fromPubKey:Lb},Hb=["bc1q","tb1q","bcrt1q"];function Pd(e){for(const t of Hb)if(e.startsWith(t))return!0;return!1}function Ud(e,t="main"){const n=Cc[t],r=B.bytes(e);return Ft(r,32),r.toBech32(n,0)}function Rb(e){if(!Pd(e))throw new TypeError("Invalid segwit address!");return B.bech32(e)}function jb(e){const t=B.bytes(e);return Ft(t,32),["OP_0",t.hex]}function Kb(e,t){const n=$d(e);return Ud(n,t)}const Nd={check:Pd,encode:Ud,decode:Rb,hash:$d,scriptPubKey:jb,fromScript:Kb};function cr(e){const t=B.bytes(e);return t.length>32?t.slice(1,33):t}const Db=["bc1p","tb1p","bcrt1p"];function Ld(e){for(const t of Db)if(e.startsWith(t))return!0;return!1}function Hd(e,t="main"){const n=Cc[t],r=B.bytes(e);return Ft(r,32),r.toBech32(n,1)}function Mb(e){if(!Ld(e))throw new TypeError("Invalid taproot address!");return B.bech32(e)}function Zb(e){const t=B.bytes(e);return Ft(t,32),["OP_1",t.hex]}function Vb(e,t){const n=cr(e);return Hd(n,t)}const Rd={check:Ld,encode:Hd,decode:Mb,scriptPubKey:Zb,fromPubKey:Vb},qb={version:2,vin:[],vout:[],locktime:0},zb={scriptSig:[],sequence:4294967293,witness:[]},Fb={value:0n,scriptPubKey:[]};function Pc(e){const t={...qb,...e};return t.vin=t.vin.map(n=>({...zb,...n})),t.vout=t.vout.map(n=>({...Fb,...n})),t}function zr(e,t){const{version:n,vin:r,vout:s,locktime:o}=Pc(e),i=t!==!0&&Wb(r),a=[Uc(n)];i&&a.push(B.hex("0001")),a.push(Gb(r)),a.push(Yb(s));for(const c of r)i&&a.push(Jb(c.witness));return a.push(Nc(o)),B.join(a)}function Wb(e){for(const t of e){const{witness:n}=t;if(typeof n=="string"||n instanceof Uint8Array||Array.isArray(n)&&n.length>0)return!0}return!1}function Uc(e){return B.num(e,4).reverse()}function Vs(e){return B.hex(e,32).reverse()}function qs(e){return B.num(e,4).reverse()}function zs(e){if(typeof e=="string")return B.hex(e,4).reverse();if(typeof e=="number")return B.num(e,4).reverse();throw new Error("Unrecognized format: "+String(e))}function Gb(e){const t=[B.varInt(e.length,"le")];for(const n of e){const{txid:r,vout:s,scriptSig:o,sequence:i}=n;t.push(Vs(r)),t.push(qs(s)),t.push(br(o,!0)),t.push(zs(i))}return B.join(t)}function Un(e){if(typeof e=="number"){if(e%1!==0)throw new Error("Value must be an integer:"+String(e));return B.num(e,8).reverse()}return B.big(e,8).reverse()}function Yb(e){const t=[B.varInt(e.length,"le")];for(const n of e)t.push(Xb(n));return B.join(t)}function Xb(e){const{value:t,scriptPubKey:n}=e,r=[];return r.push(Un(t)),r.push(br(n,!0)),B.join(r)}function Jb(e=[]){const t=[];if(Array.isArray(e)){const n=B.varInt(e.length);t.push(n);for(const r of e)t.push(Qb(r));return B.join(t)}else return B.bytes(e)}function Qb(e){return e1(e)?new B(0):br(e,!0)}function e1(e){if(Array.isArray(e))return e.length===0;if(typeof e=="string"&&e==="")return!0;const t=B.bytes(e);return t.length===1&&t[0]===0}function Nc(e){if(typeof e=="string")return B.hex(e,4);if(typeof e=="number")return B.num(e,4).reverse();throw new Error("Unrecognized format: "+String(e))}function Lc(e){typeof e=="string"&&(e=B.hex(e).raw);const t=new as(e),n=t1(t),r=n1(t),s=r1(t),o=o1(t);if(r)for(const a of s)a.witness=a1(t);const i=c1(t);return{version:n,vin:s,vout:o,locktime:i}}function t1(e){return e.read(4).reverse().toNum()}function n1(e){const[t,n]=[...e.peek(2)];if(t===0){if(e.read(2),n===1)return!0;throw new Error(`Invalid witness flag: ${n}`)}return!1}function r1(e){const t=[],n=e.readSize("le");for(let r=0;r0?e.read(n).hex:null}function Kd(e,t){const n=jd(e);return n!==null?n:[]}function c1(e){return e.read(4).reverse().toNum()}function u1(e){if(Sf(e))return Lc(e);if(typeof e=="object"&&!(e instanceof Uint8Array))return zr(e),Pc(e);throw new Error("Invalid format: "+typeof e)}function l1(e){if(Sf(e))return Lc(e),B.bytes(e);if(typeof e=="object")return zr(e);throw new Error("Invalid format: "+typeof e)}const Hc={toBytes:l1,toJson:u1},f1=[["p2pkh",/^76a914(?\w{40})88ac$/],["p2sh",/^a914(?\w{40})87$/],["p2w-pkh",/^0014(?\w{40})$/],["p2w-sh",/^0020(?\w{64})$/],["p2tr",/^5120(?\w{64})$/]],d1=[192,194,196,198,200,202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,238,240,242,244,246,248,250,252,254,102,126,128,132,150,152,186,188,190];function h1(e){let t=e.at(-1);return fn(t)&&(t=B.hex(t)),e.length>1&&t instanceof Uint8Array&&t[0]===80?(e.pop(),B.raw(t)):null}function p1(e){let t=e.at(-1);return fn(t)&&(t=B.hex(t)),e.length>1&&t instanceof Uint8Array&&t.length>32&&d1.includes(t[0]&254)?(e.pop(),B.raw(t)):null}function g1(e){if(e.length>1){const t=e.at(-1);try{const n=Ce.fmt.toBytes(t);return e.pop(),n}catch{return null}}return null}function m1(e){const t=[];for(const n of e)if(fn(n)||n instanceof Uint8Array||typeof n=="number")t.push(B.bytes(n));else throw new Error("unrecognized value: "+String(n));return t}function y1(e=[]){const t=[...e],n=h1(t),r=p1(t),s=g1(t),o=m1(t);return{annex:n,cblock:r,script:s,params:o}}function w1(e){const t=Ce.fmt.toBytes(e,!1).hex;for(const[n,r]of f1){const s=n,{groups:o}=r.exec(t)??{},{hash:i}=o??{};if(fn(i))return{type:s,data:B.hex(i)}}return{type:"raw",data:B.hex(t)}}function b1(e){const t=Hc.toJson(e),n=zr(t,!0);return qr(n).reverse().hex}function x1(e){const t=Hc.toJson(e),n=zr(t,!0).length,r=zr(t,!1).length,s=n*3+r,o=s%4>0?1:0,i=Math.floor(s/4)+o;return{size:r,bsize:n,vsize:i,weight:s}}const X={create:Pc,encode:zr,decode:Lc,fmt:Hc,util:{getTxSize:x1,getTxid:b1,readScriptPubKey:w1,readWitness:y1}},v1=[["1","p2pkh","main",20,"base58"],["3","p2sh","main",20,"base58"],["m","p2pkh","testnet",20,"base58"],["n","p2pkh","testnet",20,"base58"],["2","p2sh","testnet",20,"base58"],["bc1q","p2w-pkh","main",20,"bech32"],["tb1q","p2w-pkh","testnet",20,"bech32"],["bcrt1q","p2w-pkh","regtest",20,"bech32"],["bc1q","p2w-sh","main",32,"bech32"],["tb1q","p2w-sh","testnet",32,"bech32"],["bcrt1q","p2w-sh","regtest",32,"bech32"],["bc1p","p2tr","main",32,"bech32m"],["tb1p","p2tr","testnet",32,"bech32m"],["bcrt1p","p2tr","regtest",32,"bech32m"]];function k1(e,t){switch(t){case"base58":return B.b58chk(e).slice(1);case"bech32":return B.bech32(e);case"bech32m":return B.bech32(e);default:throw new Error("Invalid address format: "+t)}}function $1(e){for(const t of v1){const[n,r,s,o,i]=t;if(e.startsWith(n)&&k1(e,i).length===o)return t}throw new Error("Invalid address: "+e)}function Dd(e){switch(e){case"p2pkh":return _d;case"p2sh":return Td;case"p2w-pkh":return Cd;case"p2w-sh":return Nd;case"p2tr":return Rd;default:throw new Error("Invalid address type: "+e)}}function Md(e){const[t,n,r]=$1(e),s=Dd(n),o=s.decode(e,r),i=s.scriptPubKey(o);return{prefix:t,type:n,network:r,data:o,script:i}}function E1(e,t){const{type:n,data:r}=X.util.readScriptPubKey(e);return Dd(n).encode(r,t)}function S1(e){const{script:t}=Md(e);return Ce.fmt.toAsm(t,!1)}const As={p2pkh:_d,p2sh:Td,p2wpkh:Cd,p2wsh:Nd,p2tr:Rd,decode:Md,fromScriptPubKey:E1,toScriptPubKey:S1},_1=[1,2,3];function Rc(e,t,n={}){const{sigflag:r=1}=n,s=(r&128)===128,o=r%128;if(!_1.includes(o))throw new Error("Invalid hash type: "+String(r));const i=X.fmt.toJson(e),{version:a,vin:c,vout:u,locktime:f}=i,{txid:l,vout:d,prevout:p,sequence:g}=c[t],{value:h}=p??{};if(h===void 0)throw new Error("Prevout value is empty!");let y=n.script;if(y===void 0&&n.pubkey!==void 0&&(y=`76a914${Oc(n.pubkey).hex}88ac`),y===void 0)throw new Error("No pubkey / script has been set!");if(Ce.fmt.toAsm(y).includes("OP_CODESEPARATOR"))throw new Error("This library does not currently support the use of OP_CODESEPARATOR in segwit scripts.");const m=[Uc(a),A1(c,s),B1(c,o,s),Vs(l),qs(d),Ce.encode(y,!0),Un(h),zs(g),T1(u,t,o),Nc(f),B.num(r,4).reverse()];return qr(B.join(m))}function A1(e,t){if(t===!0)return B.num(0,32);const n=[];for(const{txid:r,vout:s}of e)n.push(Vs(r)),n.push(qs(s));return qr(B.join(n))}function B1(e,t,n){if(n||t!==1)return B.num(0,32);const r=[];for(const{sequence:s}of e)r.push(zs(s));return qr(B.join(r))}function T1(e,t,n){const r=[];if(n===1){for(const{value:s,scriptPubKey:o}of e)r.push(Un(s)),r.push(Ce.encode(o,!0));return qr(B.join(r))}if(n===3&&t1&&c[1].length===33)u=B.bytes(c[1]);else return Je("No pubkey provided!",s);const f=Ce.fmt.toParam(c[0]),l=f.slice(0,-1),d=f.slice(-1)[0],p=Rc(r,t,{...n,sigflag:d});return vd.secp.verify(l,p,u)?!0:Je("Invalid signature!",s)}const C1={hash:Rc,sign:O1,verify:I1},P1=[0,1,2,3,129,130,131];function jc(e,t,n={}){const{extension:r,sigflag:s=0,extflag:o=0,key_version:i=0,separator_pos:a=4294967295}=n,c=X.fmt.toJson(e),{version:u,vin:f,vout:l,locktime:d}=c;if(t>=f.length)throw new Error("Index out of bounds: "+String(t));if(!P1.includes(s))throw new Error("Invalid hash type: "+String(s));if(o<0||o>127)throw new Error("Extention flag out of range: "+String(o));const{txid:p,vout:g,sequence:h,witness:y=[]}=f[t],m=(s&128)===128,x=K1(y),w=x!==void 0?1:0,b=(o+(r!==void 0?1:0))*2+w,$=B.str("TapSighash").digest,T=[$,$,B.num(0,1),B.num(s,1),Uc(u),Nc(d)];if(!m){const U=f.map(O=>el(O));T.push(U1(f),L1(U),H1(U),N1(f))}if(((s&3)<2||(s&3)>3)&&T.push(R1(l)),T.push(B.num(b,1)),m){const{value:U,scriptPubKey:O}=el(f[t]);T.push(Vs(p),qs(g),Un(U),Ce.encode(O,!0),zs(h))}else T.push(B.num(t,4).reverse());return x!==void 0&&T.push(x),(s&3)===3&&T.push(j1(l[t])),r!==void 0&&T.push(B.bytes(r),B.num(i),B.num(a,4,"le")),B.join(T).digest}function U1(e){const t=[];for(const{txid:n,vout:r}of e)t.push(Vs(n)),t.push(qs(r));return B.join(t).digest}function N1(e){const t=[];for(const{sequence:n}of e)t.push(zs(n));return B.join(t).digest}function L1(e){const t=[];for(const{value:n}of e)t.push(Un(n));return B.join(t).digest}function H1(e){const t=[];for(const{scriptPubKey:n}of e)t.push(br(n,!0));return B.join(t).digest}function R1(e){const t=[];for(const{value:n,scriptPubKey:r}of e)t.push(Un(n)),t.push(Ce.encode(r,!0));return B.join(t).digest}function j1(e){return B.join([Un(e.value),Ce.encode(e.scriptPubKey,!0)]).digest}function K1(e){if(e===void 0||e.length<2)return;let t=e.at(-1);if(typeof t=="string"&&(t=B.hex(t)),t instanceof Uint8Array&&t[0]===80)return B.raw(t).prefixSize("be").digest}function el(e){if(e.prevout===void 0)throw new Error("Prevout data missing for input: "+String(e.txid));return e.prevout}const D1=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,M1=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;function Z1(e,t,n,r={}){const{sigflag:s=0}=r,o=jc(t,n,r),i=V1(e,o);return s===0?B.raw(i):B.join([i,s])}function V1(e,t,n=B.random(32)){const r=B.bytes(t),s=new nt(e),o=s.point,i=o.hasEvenY?s.big:s.negated.big,a=Eo("BIP0340/aux",B.bytes(n)),c=i^a.big,u=Eo("BIP0340/nonce",c,o.x.raw,r),f=new nt(u),l=f.point,d=l.hasEvenY?f.big:f.negated.big,p=new nt(Eo("BIP0340/challenge",l.x.raw,o.x.raw,r)),g=new nt(d+p.big*i);return B.join([l.x.raw,g.raw])}function q1(e,t,n,r=!1){const s=xr.from_x(cr(n)),o=B.bytes(t),i=B.bytes(e).stream;i.size<64&&Je("Signature length is too small: "+String(i.size),r);const a=i.read(32);a.big>D1&&Je("Signature r value greater than field size!",r);const c=i.read(32);c.big>M1&&Je("Signature s value greater than curve order!",r);const u=new nt(Eo("BIP0340/challenge",a.raw,s.x.raw,o)),f=new nt(c).point,l=s.mul(u.big),d=f.sub(l);return d.hasOddY&&Je("Signature R value has odd Y coordinate!",r),d.x.big===0n&&Je("Signature R value is infinite!",r),d.x.big===a.big}const z1=192;function bi(e){const t=B.str(e).digest;return B.join([t,t])}function Kc(e,t=z1){return B.join([bi("TapLeaf"),G1(t),B.bytes(e)]).digest.hex}function F1(e,t){return Kc(Ce.fmt.toBytes(e),t)}function Dc(e,t){return t0){const[p,g,h]=Ro(r,i);c=h,a=Hr(e,p,n)}else i!==void 0?a=Hr(e,i,n):a=Hr(e,void 0,n);const u=n?Ua.getPublicKey(a)[0]:a[0],l=[B.num(s+Wd(u)),o];c.length>0&&c.forEach(p=>l.push(B.hex(p)));const d=B.join(l);if(i!==void 0&&!Mc(a,i,d,t))throw new Error("Path checking failed! Unable to generate path.");return[cr(a).hex,d.hex]}function Mc(e,t,n,r={}){const{isPrivate:s=!1,throws:o=!1}=r,{parity:i,paths:a,intkey:c}=Fd(n),u=s?Ua.getPublicKey(e,!0):cr(e),f=B.join([i,u]);if(f.length!==33)return Je("Invalid tapkey: "+f.hex,o);let l=B.bytes(t).hex;for(const p of a)l=Dc(l,p);const d=Hr(c,l);return B.raw(d).hex===B.raw(f).hex}function Fd(e){const t=new as(B.bytes(e)),n=t.read(1).num,r=t.read(32),[s,o]=n%2===0?[n,2]:[n-1,3],i=[];for(;t.size>=32;)i.push(t.read(32).hex);if(t.size!==0)throw new Error("Non-empty buffer on control block: "+String(t));return{intkey:r,paths:i,parity:o,version:s}}function Wd(e=2){if(e===0||e===1)return e;if(e===2||e==="02")return 0;if(e===3||e==="03")return 1;throw new Error("Invalid parity bit: "+String(e))}function rx(e,t,n={}){const r=X.fmt.toJson(e),{throws:s=!1}=n,{prevout:o,witness:i=[]}=r.vin[t],a=X.util.readWitness(i),{cblock:c,script:u,params:f}=a;let l;if(f.length<1)return Je("Invalid witness data: "+String(i),s);const{scriptPubKey:d}=o??{};if(d===void 0)return Je("Prevout scriptPubKey is empty!",s);const{type:p,data:g}=X.util.readScriptPubKey(d);if(p!=="p2tr")return Je("Prevout script is not a valid taproot output:"+g.hex,s);if(g.length!==32)return Je("Invalid tapkey length: "+String(g.length),s);if(c!==null&&u!==null){const w=c[0]&254,P=Kc(u,w);if(n.extension=P,!Mc(g,P,c,{throws:s}))return Je("cblock verification failed!",s)}n.pubkey!==void 0?l=B.bytes(n.pubkey):f.length>1&&f[1].length===32?l=B.bytes(f[1]):l=B.bytes(g);const h=Ce.fmt.toParam(f[0]),y=new as(h),m=y.read(64).raw;if(y.size===1&&(n.sigflag=y.read(1).num,n.sigflag===0))return Je("0x00 is not a valid appended sigflag!",s);const x=jc(r,t,n);return q1(m,x,l,s)?!0:Je("Invalid signature!",s)}const sx={hash:jc,sign:Z1,verify:rx},ur={segwit:C1,taproot:sx},ox={getTag:bi,getLeaf:Kc,getBranch:Dc,getRoot:W1},ix={readCtrlBlock:Fd,readParityBit:Wd},ax={getPubKey:Y1,getSecKey:X1,getTweak:Zd,tweakSecKey:Vd,tweakPubKey:qd},Fs={getPubKey:nx,getSecKey:tx,encodeScript:F1,checkPath:Mc,tree:ox,tweak:ax,util:ix,SCRIPT_PUBKEY:Q1};var ye;(function(e){e.assertEqual=s=>s;function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{const o={};for(const i of s)o[i]=i;return o},e.getValidEnumValues=s=>{const o=e.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(const a of o)i[a]=s[a];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},e.find=(s,o)=>{for(const i of s)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(ye||(ye={}));var Na;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Na||(Na={}));const z=ye.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Bn=e=>{switch(typeof e){case"undefined":return z.undefined;case"string":return z.string;case"number":return isNaN(e)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(e)?z.array:e===null?z.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?z.promise:typeof Map<"u"&&e instanceof Map?z.map:typeof Set<"u"&&e instanceof Set?z.set:typeof Date<"u"&&e instanceof Date?z.date:z.object;default:return z.unknown}},M=ye.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),cx=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Bt extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(const i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;cn.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Bt.create=e=>new Bt(e);const Bs=(e,t)=>{let n;switch(e.code){case M.invalid_type:e.received===z.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case M.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ye.jsonStringifyReplacer)}`;break;case M.unrecognized_keys:n=`Unrecognized key(s) in object: ${ye.joinValues(e.keys,", ")}`;break;case M.invalid_union:n="Invalid input";break;case M.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ye.joinValues(e.options)}`;break;case M.invalid_enum_value:n=`Invalid enum value. Expected ${ye.joinValues(e.options)}, received '${e.received}'`;break;case M.invalid_arguments:n="Invalid function arguments";break;case M.invalid_return_type:n="Invalid function return type";break;case M.invalid_date:n="Invalid date";break;case M.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:ye.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case M.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case M.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case M.custom:n="Invalid input";break;case M.invalid_intersection_types:n="Intersection results could not be merged";break;case M.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case M.not_finite:n="Number must be finite";break;default:n=t.defaultError,ye.assertNever(e)}return{message:n}};let Gd=Bs;function ux(e){Gd=e}function jo(){return Gd}const Ko=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],i={...s,path:o};let a="";const c=r.filter(u=>!!u).slice().reverse();for(const u of c)a=u(i,{data:t,defaultError:a}).message;return{...s,path:o,message:s.message||a}},lx=[];function F(e,t){const n=Ko({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,jo(),Bs].filter(r=>!!r)});e.common.issues.push(n)}class et{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const s of n){if(s.status==="aborted")return te;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const s of n)r.push({key:await s.key,value:await s.value});return et.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const s of n){const{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return te;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}}const te=Object.freeze({status:"aborted"}),Yd=e=>({status:"dirty",value:e}),it=e=>({status:"valid",value:e}),La=e=>e.status==="aborted",Ha=e=>e.status==="dirty",Do=e=>e.status==="valid",Mo=e=>typeof Promise<"u"&&e instanceof Promise;var J;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(J||(J={}));class Dt{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const tl=(e,t)=>{if(Do(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Bt(e.common.issues);return this._error=n,this._error}}};function se(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(i,a)=>i.code!=="invalid_type"?{message:a.defaultError}:typeof a.data>"u"?{message:r??a.defaultError}:{message:n??a.defaultError},description:s}}class ae{constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return Bn(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Bn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new et,ctx:{common:t.parent.common,data:t.data,parsedType:Bn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Mo(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const s={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Bn(t)},o=this._parseSync({data:t,path:s.path,parent:s});return tl(s,o)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Bn(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(Mo(s)?s:Promise.resolve(s));return tl(r,o)}refine(t,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{const i=t(s),a=()=>o.addIssue({code:M.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new Ot({schema:this,typeName:Q.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return sn.create(this,this._def)}nullable(){return dr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Tt.create(this,this._def)}promise(){return Wr.create(this,this._def)}or(t){return Cs.create([this,t],this._def)}and(t){return Ps.create(this,t,this._def)}transform(t){return new Ot({...se(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Rs({...se(this._def),innerType:this,defaultValue:n,typeName:Q.ZodDefault})}brand(){return new Jd({typeName:Q.ZodBranded,type:this,...se(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new zo({...se(this._def),innerType:this,catchValue:n,typeName:Q.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Ws.create(this,t)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const fx=/^c[^\s-]{8,}$/i,dx=/^[a-z][a-z0-9]*$/,hx=/[0-9A-HJKMNP-TV-Z]{26}/,px=/^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i,gx=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/,mx=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u"),yx=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,wx=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,bx=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):e.precision===0?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function xx(e,t){return!!((t==="v4"||!t)&&yx.test(e)||(t==="v6"||!t)&&wx.test(e))}class St extends ae{constructor(){super(...arguments),this._regex=(t,n,r)=>this.refinement(s=>t.test(s),{validation:n,code:M.invalid_string,...J.errToObj(r)}),this.nonempty=t=>this.min(1,J.errToObj(t)),this.trim=()=>new St({...this._def,checks:[...this._def.checks,{kind:"trim"}]}),this.toLowerCase=()=>new St({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]}),this.toUpperCase=()=>new St({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==z.string){const o=this._getOrReturnCtx(t);return F(o,{code:M.invalid_type,expected:z.string,received:o.parsedType}),te}const r=new et;let s;for(const o of this._def.checks)if(o.kind==="min")t.data.lengtho.value&&(s=this._getOrReturnCtx(t,s),F(s,{code:M.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){const i=t.data.length>o.value,a=t.data.length"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...J.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...J.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...J.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...J.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...J.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...J.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...J.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...J.errToObj(n)})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new St({checks:[],typeName:Q.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...se(e)})};function vx(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=parseInt(e.toFixed(s).replace(".","")),i=parseInt(t.toFixed(s).replace(".",""));return o%i/Math.pow(10,s)}class Nn extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==z.number){const o=this._getOrReturnCtx(t);return F(o,{code:M.invalid_type,expected:z.number,received:o.parsedType}),te}let r;const s=new et;for(const o of this._def.checks)o.kind==="int"?ye.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),F(r,{code:M.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),F(r,{code:M.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?vx(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),F(r,{code:M.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),F(r,{code:M.not_finite,message:o.message}),s.dirty()):ye.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,J.toString(n))}gt(t,n){return this.setLimit("min",t,!1,J.toString(n))}lte(t,n){return this.setLimit("max",t,!0,J.toString(n))}lt(t,n){return this.setLimit("max",t,!1,J.toString(n))}setLimit(t,n,r,s){return new Nn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:J.toString(s)}]})}_addCheck(t){return new Nn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:J.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:J.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:J.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:J.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:J.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:J.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:J.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:J.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:J.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&ye.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.valuenew Nn({checks:[],typeName:Q.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...se(e)});class Ln extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==z.bigint){const o=this._getOrReturnCtx(t);return F(o,{code:M.invalid_type,expected:z.bigint,received:o.parsedType}),te}let r;const s=new et;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),F(r,{code:M.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),F(r,{code:M.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):ye.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,J.toString(n))}gt(t,n){return this.setLimit("min",t,!1,J.toString(n))}lte(t,n){return this.setLimit("max",t,!0,J.toString(n))}lt(t,n){return this.setLimit("max",t,!1,J.toString(n))}setLimit(t,n,r,s){return new Ln({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:J.toString(s)}]})}_addCheck(t){return new Ln({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:J.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:J.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:J.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:J.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:J.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new Ln({checks:[],typeName:Q.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...se(e)})};class Ts extends ae{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==z.boolean){const r=this._getOrReturnCtx(t);return F(r,{code:M.invalid_type,expected:z.boolean,received:r.parsedType}),te}return it(t.data)}}Ts.create=e=>new Ts({typeName:Q.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...se(e)});class lr extends ae{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==z.date){const o=this._getOrReturnCtx(t);return F(o,{code:M.invalid_type,expected:z.date,received:o.parsedType}),te}if(isNaN(t.data.getTime())){const o=this._getOrReturnCtx(t);return F(o,{code:M.invalid_date}),te}const r=new et;let s;for(const o of this._def.checks)o.kind==="min"?t.data.getTime()o.value&&(s=this._getOrReturnCtx(t,s),F(s,{code:M.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):ye.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new lr({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:J.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:J.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew lr({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Q.ZodDate,...se(e)});class Zo extends ae{_parse(t){if(this._getType(t)!==z.symbol){const r=this._getOrReturnCtx(t);return F(r,{code:M.invalid_type,expected:z.symbol,received:r.parsedType}),te}return it(t.data)}}Zo.create=e=>new Zo({typeName:Q.ZodSymbol,...se(e)});class Os extends ae{_parse(t){if(this._getType(t)!==z.undefined){const r=this._getOrReturnCtx(t);return F(r,{code:M.invalid_type,expected:z.undefined,received:r.parsedType}),te}return it(t.data)}}Os.create=e=>new Os({typeName:Q.ZodUndefined,...se(e)});class Is extends ae{_parse(t){if(this._getType(t)!==z.null){const r=this._getOrReturnCtx(t);return F(r,{code:M.invalid_type,expected:z.null,received:r.parsedType}),te}return it(t.data)}}Is.create=e=>new Is({typeName:Q.ZodNull,...se(e)});class Fr extends ae{constructor(){super(...arguments),this._any=!0}_parse(t){return it(t.data)}}Fr.create=e=>new Fr({typeName:Q.ZodAny,...se(e)});class or extends ae{constructor(){super(...arguments),this._unknown=!0}_parse(t){return it(t.data)}}or.create=e=>new or({typeName:Q.ZodUnknown,...se(e)});class cn extends ae{_parse(t){const n=this._getOrReturnCtx(t);return F(n,{code:M.invalid_type,expected:z.never,received:n.parsedType}),te}}cn.create=e=>new cn({typeName:Q.ZodNever,...se(e)});class Vo extends ae{_parse(t){if(this._getType(t)!==z.undefined){const r=this._getOrReturnCtx(t);return F(r,{code:M.invalid_type,expected:z.void,received:r.parsedType}),te}return it(t.data)}}Vo.create=e=>new Vo({typeName:Q.ZodVoid,...se(e)});class Tt extends ae{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==z.array)return F(n,{code:M.invalid_type,expected:z.array,received:n.parsedType}),te;if(s.exactLength!==null){const i=n.data.length>s.exactLength.value,a=n.data.lengths.maxLength.value&&(F(n,{code:M.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new Dt(n,i,n.path,a)))).then(i=>et.mergeArray(r,i));const o=[...n.data].map((i,a)=>s.type._parseSync(new Dt(n,i,n.path,a)));return et.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new Tt({...this._def,minLength:{value:t,message:J.toString(n)}})}max(t,n){return new Tt({...this._def,maxLength:{value:t,message:J.toString(n)}})}length(t,n){return new Tt({...this._def,exactLength:{value:t,message:J.toString(n)}})}nonempty(t){return this.min(1,t)}}Tt.create=(e,t)=>new Tt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...se(t)});function Ur(e){if(e instanceof Ue){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=sn.create(Ur(r))}return new Ue({...e._def,shape:()=>t})}else return e instanceof Tt?new Tt({...e._def,type:Ur(e.element)}):e instanceof sn?sn.create(Ur(e.unwrap())):e instanceof dr?dr.create(Ur(e.unwrap())):e instanceof Mt?Mt.create(e.items.map(t=>Ur(t))):e}class Ue extends ae{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=ye.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==z.object){const u=this._getOrReturnCtx(t);return F(u,{code:M.invalid_type,expected:z.object,received:u.parsedType}),te}const{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof cn&&this._def.unknownKeys==="strip"))for(const u in s.data)i.includes(u)||a.push(u);const c=[];for(const u of i){const f=o[u],l=s.data[u];c.push({key:{status:"valid",value:u},value:f._parse(new Dt(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof cn){const u=this._def.unknownKeys;if(u==="passthrough")for(const f of a)c.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(u==="strict")a.length>0&&(F(s,{code:M.unrecognized_keys,keys:a}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const f of a){const l=s.data[f];c.push({key:{status:"valid",value:f},value:u._parse(new Dt(s,l,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const f of c){const l=await f.key;u.push({key:l,value:await f.value,alwaysSet:f.alwaysSet})}return u}).then(u=>et.mergeObjectSync(r,u)):et.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return new Ue({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,o,i,a;const c=(i=(o=(s=this._def).errorMap)===null||o===void 0?void 0:o.call(s,n,r).message)!==null&&i!==void 0?i:r.defaultError;return n.code==="unrecognized_keys"?{message:(a=J.errToObj(t).message)!==null&&a!==void 0?a:c}:{message:c}}}:{}})}strip(){return new Ue({...this._def,unknownKeys:"strip"})}passthrough(){return new Ue({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ue({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ue({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Q.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Ue({...this._def,catchall:t})}pick(t){const n={};return ye.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}omit(t){const n={};return ye.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}deepPartial(){return Ur(this)}partial(t){const n={};return ye.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}),new Ue({...this._def,shape:()=>n})}required(t){const n={};return ye.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof sn;)o=o._def.innerType;n[r]=o}}),new Ue({...this._def,shape:()=>n})}keyof(){return Xd(ye.objectKeys(this.shape))}}Ue.create=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strip",catchall:cn.create(),typeName:Q.ZodObject,...se(t)});Ue.strictCreate=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strict",catchall:cn.create(),typeName:Q.ZodObject,...se(t)});Ue.lazycreate=(e,t)=>new Ue({shape:e,unknownKeys:"strip",catchall:cn.create(),typeName:Q.ZodObject,...se(t)});class Cs extends ae{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(const a of o)if(a.result.status==="valid")return a.result;for(const a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;const i=o.map(a=>new Bt(a.ctx.common.issues));return F(n,{code:M.invalid_union,unionErrors:i}),te}if(n.common.async)return Promise.all(r.map(async o=>{const i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o;const i=[];for(const c of r){const u={...n,common:{...n.common,issues:[]},parent:null},f=c._parseSync({data:n.data,path:n.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!o&&(o={result:f,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(c=>new Bt(c));return F(n,{code:M.invalid_union,unionErrors:a}),te}}get options(){return this._def.options}}Cs.create=(e,t)=>new Cs({options:e,typeName:Q.ZodUnion,...se(t)});const So=e=>e instanceof Ns?So(e.schema):e instanceof Ot?So(e.innerType()):e instanceof Ls?[e.value]:e instanceof Hn?e.options:e instanceof Hs?Object.keys(e.enum):e instanceof Rs?So(e._def.innerType):e instanceof Os?[void 0]:e instanceof Is?[null]:null;class xi extends ae{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==z.object)return F(n,{code:M.invalid_type,expected:z.object,received:n.parsedType}),te;const r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(F(n,{code:M.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),te)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const s=new Map;for(const o of n){const i=So(o.shape[t]);if(!i)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const a of i){if(s.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);s.set(a,o)}}return new xi({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...se(r)})}}function Ra(e,t){const n=Bn(e),r=Bn(t);if(e===t)return{valid:!0,data:e};if(n===z.object&&r===z.object){const s=ye.objectKeys(t),o=ye.objectKeys(e).filter(a=>s.indexOf(a)!==-1),i={...e,...t};for(const a of o){const c=Ra(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===z.array&&r===z.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let o=0;o{if(La(o)||La(i))return te;const a=Ra(o.value,i.value);return a.valid?((Ha(o)||Ha(i))&&n.dirty(),{status:n.value,value:a.data}):(F(r,{code:M.invalid_intersection_types}),te)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Ps.create=(e,t,n)=>new Ps({left:e,right:t,typeName:Q.ZodIntersection,...se(n)});class Mt extends ae{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==z.array)return F(r,{code:M.invalid_type,expected:z.array,received:r.parsedType}),te;if(r.data.lengththis._def.items.length&&(F(r,{code:M.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const o=[...r.data].map((i,a)=>{const c=this._def.items[a]||this._def.rest;return c?c._parse(new Dt(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>et.mergeArray(n,i)):et.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new Mt({...this._def,rest:t})}}Mt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Mt({items:e,typeName:Q.ZodTuple,rest:null,...se(t)})};class Us extends ae{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==z.object)return F(r,{code:M.invalid_type,expected:z.object,received:r.parsedType}),te;const s=[],o=this._def.keyType,i=this._def.valueType;for(const a in r.data)s.push({key:o._parse(new Dt(r,a,r.path,a)),value:i._parse(new Dt(r,r.data[a],r.path,a))});return r.common.async?et.mergeObjectAsync(n,s):et.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof ae?new Us({keyType:t,valueType:n,typeName:Q.ZodRecord,...se(r)}):new Us({keyType:St.create(),valueType:t,typeName:Q.ZodRecord,...se(n)})}}class qo extends ae{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==z.map)return F(r,{code:M.invalid_type,expected:z.map,received:r.parsedType}),te;const s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,c],u)=>({key:s._parse(new Dt(r,a,r.path,[u,"key"])),value:o._parse(new Dt(r,c,r.path,[u,"value"]))}));if(r.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const c of i){const u=await c.key,f=await c.value;if(u.status==="aborted"||f.status==="aborted")return te;(u.status==="dirty"||f.status==="dirty")&&n.dirty(),a.set(u.value,f.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const c of i){const u=c.key,f=c.value;if(u.status==="aborted"||f.status==="aborted")return te;(u.status==="dirty"||f.status==="dirty")&&n.dirty(),a.set(u.value,f.value)}return{status:n.value,value:a}}}}qo.create=(e,t,n)=>new qo({valueType:t,keyType:e,typeName:Q.ZodMap,...se(n)});class fr extends ae{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==z.set)return F(r,{code:M.invalid_type,expected:z.set,received:r.parsedType}),te;const s=this._def;s.minSize!==null&&r.data.sizes.maxSize.value&&(F(r,{code:M.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const o=this._def.valueType;function i(c){const u=new Set;for(const f of c){if(f.status==="aborted")return te;f.status==="dirty"&&n.dirty(),u.add(f.value)}return{status:n.value,value:u}}const a=[...r.data.values()].map((c,u)=>o._parse(new Dt(r,c,r.path,u)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(t,n){return new fr({...this._def,minSize:{value:t,message:J.toString(n)}})}max(t,n){return new fr({...this._def,maxSize:{value:t,message:J.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}fr.create=(e,t)=>new fr({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...se(t)});class Rr extends ae{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==z.function)return F(n,{code:M.invalid_type,expected:z.function,received:n.parsedType}),te;function r(a,c){return Ko({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,jo(),Bs].filter(u=>!!u),issueData:{code:M.invalid_arguments,argumentsError:c}})}function s(a,c){return Ko({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,jo(),Bs].filter(u=>!!u),issueData:{code:M.invalid_return_type,returnTypeError:c}})}const o={errorMap:n.common.contextualErrorMap},i=n.data;return this._def.returns instanceof Wr?it(async(...a)=>{const c=new Bt([]),u=await this._def.args.parseAsync(a,o).catch(d=>{throw c.addIssue(r(a,d)),c}),f=await i(...u);return await this._def.returns._def.type.parseAsync(f,o).catch(d=>{throw c.addIssue(s(f,d)),c})}):it((...a)=>{const c=this._def.args.safeParse(a,o);if(!c.success)throw new Bt([r(a,c.error)]);const u=i(...c.data),f=this._def.returns.safeParse(u,o);if(!f.success)throw new Bt([s(u,f.error)]);return f.data})}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Rr({...this._def,args:Mt.create(t).rest(or.create())})}returns(t){return new Rr({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Rr({args:t||Mt.create([]).rest(or.create()),returns:n||or.create(),typeName:Q.ZodFunction,...se(r)})}}class Ns extends ae{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Ns.create=(e,t)=>new Ns({getter:e,typeName:Q.ZodLazy,...se(t)});class Ls extends ae{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return F(n,{received:n.data,code:M.invalid_literal,expected:this._def.value}),te}return{status:"valid",value:t.data}}get value(){return this._def.value}}Ls.create=(e,t)=>new Ls({value:e,typeName:Q.ZodLiteral,...se(t)});function Xd(e,t){return new Hn({values:e,typeName:Q.ZodEnum,...se(t)})}class Hn extends ae{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return F(n,{expected:ye.joinValues(r),received:n.parsedType,code:M.invalid_type}),te}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return F(n,{received:n.data,code:M.invalid_enum_value,options:r}),te}return it(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t){return Hn.create(t)}exclude(t){return Hn.create(this.options.filter(n=>!t.includes(n)))}}Hn.create=Xd;class Hs extends ae{_parse(t){const n=ye.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==z.string&&r.parsedType!==z.number){const s=ye.objectValues(n);return F(r,{expected:ye.joinValues(s),received:r.parsedType,code:M.invalid_type}),te}if(n.indexOf(t.data)===-1){const s=ye.objectValues(n);return F(r,{received:r.data,code:M.invalid_enum_value,options:s}),te}return it(t.data)}get enum(){return this._def.values}}Hs.create=(e,t)=>new Hs({values:e,typeName:Q.ZodNativeEnum,...se(t)});class Wr extends ae{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==z.promise&&n.common.async===!1)return F(n,{code:M.invalid_type,expected:z.promise,received:n.parsedType}),te;const r=n.parsedType===z.promise?n.data:Promise.resolve(n.data);return it(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Wr.create=(e,t)=>new Wr({type:e,typeName:Q.ZodPromise,...se(t)});class Ot extends ae{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null;if(s.type==="preprocess"){const i=s.transform(r.data);return r.common.async?Promise.resolve(i).then(a=>this._def.schema._parseAsync({data:a,path:r.path,parent:r})):this._def.schema._parseSync({data:i,path:r.path,parent:r})}const o={addIssue:i=>{F(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="refinement"){const i=a=>{const c=s.refinement(a,o);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?te:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?te:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Do(i))return i;const a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>Do(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):i);ye.assertNever(s)}}Ot.create=(e,t,n)=>new Ot({schema:e,typeName:Q.ZodEffects,effect:t,...se(n)});Ot.createWithPreprocess=(e,t,n)=>new Ot({schema:t,effect:{type:"preprocess",transform:e},typeName:Q.ZodEffects,...se(n)});class sn extends ae{_parse(t){return this._getType(t)===z.undefined?it(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}sn.create=(e,t)=>new sn({innerType:e,typeName:Q.ZodOptional,...se(t)});class dr extends ae{_parse(t){return this._getType(t)===z.null?it(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}dr.create=(e,t)=>new dr({innerType:e,typeName:Q.ZodNullable,...se(t)});class Rs extends ae{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===z.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Rs.create=(e,t)=>new Rs({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...se(t)});class zo extends ae{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Mo(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Bt(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Bt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}zo.create=(e,t)=>new zo({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...se(t)});class Fo extends ae{_parse(t){if(this._getType(t)!==z.nan){const r=this._getOrReturnCtx(t);return F(r,{code:M.invalid_type,expected:z.nan,received:r.parsedType}),te}return{status:"valid",value:t.data}}}Fo.create=e=>new Fo({typeName:Q.ZodNaN,...se(e)});const kx=Symbol("zod_brand");class Jd extends ae{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Ws extends ae{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?te:o.status==="dirty"?(n.dirty(),Yd(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?te:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new Ws({in:t,out:n,typeName:Q.ZodPipeline})}}const Qd=(e,t={},n)=>e?Fr.create().superRefine((r,s)=>{var o,i;if(!e(r)){const a=typeof t=="function"?t(r):typeof t=="string"?{message:t}:t,c=(i=(o=a.fatal)!==null&&o!==void 0?o:n)!==null&&i!==void 0?i:!0,u=typeof a=="string"?{message:a}:a;s.addIssue({code:"custom",...u,fatal:c})}}):Fr.create(),$x={object:Ue.lazycreate};var Q;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline"})(Q||(Q={}));const Ex=(e,t={message:`Input not instance of ${e.name}`})=>Qd(n=>n instanceof e,t),eh=St.create,th=Nn.create,Sx=Fo.create,_x=Ln.create,nh=Ts.create,Ax=lr.create,Bx=Zo.create,Tx=Os.create,Ox=Is.create,Ix=Fr.create,Cx=or.create,Px=cn.create,Ux=Vo.create,Nx=Tt.create,Lx=Ue.create,Hx=Ue.strictCreate,Rx=Cs.create,jx=xi.create,Kx=Ps.create,Dx=Mt.create,Mx=Us.create,Zx=qo.create,Vx=fr.create,qx=Rr.create,zx=Ns.create,Fx=Ls.create,Wx=Hn.create,Gx=Hs.create,Yx=Wr.create,nl=Ot.create,Xx=sn.create,Jx=dr.create,Qx=Ot.createWithPreprocess,e2=Ws.create,t2=()=>eh().optional(),n2=()=>th().optional(),r2=()=>nh().optional(),s2={string:(e=>St.create({...e,coerce:!0})),number:(e=>Nn.create({...e,coerce:!0})),boolean:(e=>Ts.create({...e,coerce:!0})),bigint:(e=>Ln.create({...e,coerce:!0})),date:(e=>lr.create({...e,coerce:!0}))},o2=te;var st=Object.freeze({__proto__:null,defaultErrorMap:Bs,setErrorMap:ux,getErrorMap:jo,makeIssue:Ko,EMPTY_PATH:lx,addIssueToContext:F,ParseStatus:et,INVALID:te,DIRTY:Yd,OK:it,isAborted:La,isDirty:Ha,isValid:Do,isAsync:Mo,get util(){return ye},get objectUtil(){return Na},ZodParsedType:z,getParsedType:Bn,ZodType:ae,ZodString:St,ZodNumber:Nn,ZodBigInt:Ln,ZodBoolean:Ts,ZodDate:lr,ZodSymbol:Zo,ZodUndefined:Os,ZodNull:Is,ZodAny:Fr,ZodUnknown:or,ZodNever:cn,ZodVoid:Vo,ZodArray:Tt,ZodObject:Ue,ZodUnion:Cs,ZodDiscriminatedUnion:xi,ZodIntersection:Ps,ZodTuple:Mt,ZodRecord:Us,ZodMap:qo,ZodSet:fr,ZodFunction:Rr,ZodLazy:Ns,ZodLiteral:Ls,ZodEnum:Hn,ZodNativeEnum:Hs,ZodPromise:Wr,ZodEffects:Ot,ZodTransformer:Ot,ZodOptional:sn,ZodNullable:dr,ZodDefault:Rs,ZodCatch:zo,ZodNaN:Fo,BRAND:kx,ZodBranded:Jd,ZodPipeline:Ws,custom:Qd,Schema:ae,ZodSchema:ae,late:$x,get ZodFirstPartyTypeKind(){return Q},coerce:s2,any:Ix,array:Nx,bigint:_x,boolean:nh,date:Ax,discriminatedUnion:jx,effect:nl,enum:Wx,function:qx,instanceof:Ex,intersection:Kx,lazy:zx,literal:Fx,map:Zx,nan:Sx,nativeEnum:Gx,never:Px,null:Ox,nullable:Jx,number:th,object:Lx,oboolean:r2,onumber:n2,optional:Xx,ostring:t2,pipeline:e2,preprocess:Qx,promise:Yx,record:Mx,set:Vx,strictObject:Hx,string:eh,symbol:Bx,transformer:nl,tuple:Dx,undefined:Tx,union:Rx,unknown:Cx,void:Ux,NEVER:o2,ZodIssueCode:M,quotelessJson:cx,ZodError:Bt});const rh=st.string().regex(/^[a-fA-F0-9]$/),i2=st.string().regex(/^[a-fA-F0-9]{64}$/),Gr=st.number().min(0).max(4294967295),a2=st.bigint(),sh=st.instanceof(Uint8Array),c2=st.union([rh,Gr,st.string(),sh]).array(),Zc=st.union([c2,rh,sh]),u2=st.array(Zc),oh=st.object({value:st.union([Gr,a2]),scriptPubKey:Zc}),l2=st.object({txid:i2,vout:Gr,scriptSig:Zc,sequence:Gr,prevout:oh.optional(),witness:u2});st.object({version:Gr,vin:st.array(l2),vout:st.array(oh),locktime:Gr});const ja=2048,f2=new TextEncoder;function ih(e){const t=[],n=(s,o)=>{if(o<24)t.push(s*32+o);else if(o<=255)t.push(s*32+24,o);else if(o<=65535)t.push(s*32+25,o>>>8,o&255);else if(o<=4294967295){const i=new Uint8Array(4);new DataView(i.buffer).setUint32(0,o),t.push(s*32+26,...i)}else{t.push(s*32+27);const i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,BigInt(o)),t.push(...i)}},r=(s,o=0)=>{if(o>64)throw new Error("Metadata nesting exceeds 64 levels.");if(s===null)t.push(246);else if(typeof s=="boolean")t.push(s?245:244);else if(typeof s=="number"&&Number.isFinite(s))if(Number.isSafeInteger(s)&&!Object.is(s,-0))n(s>=0?0:1,s>=0?s:-1-s);else{const i=new Uint8Array(8);new DataView(i.buffer).setFloat64(0,s),t.push(251,...i)}else if(typeof s=="string"){const i=f2.encode(s);n(3,i.length);for(const a of i)t.push(a)}else if(Array.isArray(s))n(4,s.length),s.forEach(i=>r(i,o+1));else if(typeof s=="object"&&Object.getPrototypeOf(s)===Object.prototype){const i=Object.entries(s);n(5,i.length);for(const[a,c]of i)r(a,o+1),r(c,o+1)}else throw new Error("Metadata must contain only JSON values.");if(t.length>ja)throw new Error(`Metadata must be at most ${ja} CBOR bytes.`)};return r(e),Uint8Array.from(t)}function d2(e){if(e=new Uint8Array(e),!e.length||e.length>ja)throw new Error("Invalid CBOR metadata size.");let t=0;const n=o=>{if(t+o>e.length)throw new Error("Truncated CBOR metadata.");const i=e.slice(t,t+o);return t+=o,i},r=(o=0)=>{if(o>64)throw new Error("Metadata nesting exceeds 64 levels.");const i=n(1)[0],a=i>>5,c=i&31;if(a===7){if(c===20)return!1;if(c===21)return!0;if(c===22)return null;if(c===27){const f=new DataView(n(8).buffer).getFloat64(0);if(Number.isFinite(f))return f}throw new Error("Unsupported CBOR value.")}let u=c;if(c>=24&&c<=27){u=0;for(const f of n(2**(c-24)))u=u*256+f}else if(c>=28)throw new Error("Unsupported CBOR length.");if(!Number.isSafeInteger(u))throw new Error("CBOR integer exceeds JSON precision.");if(a===0)return u;if(a===1)return-1-u;if(a===3)return new TextDecoder("utf-8",{fatal:!0}).decode(n(u));if((a===4||a===5)&&u>e.length)throw new Error("Invalid CBOR collection length.");if(a===4)return Array.from({length:u},()=>r(o+1));if(a===5){const f={};for(let l=0;l({txid:e,vout:t,sequence:4294967295,prevout:{value:n,scriptPubKey:r}}),de=(e,t)=>({value:e,scriptPubKey:t}),rl=16*1024,Rt=1e3,W=500,Wo="text/plain;charset=utf-8",h2=["text/plain","application/json","text/html","image/svg+xml","image/png","image/jpeg","image/webp"],ah=new TextEncoder,ks=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""),Yn=e=>Uint8Array.from(e.match(/../g)??[],t=>parseInt(t,16)),Go=e=>ks(ah.encode(e));function Vc(e){const t=typeof e=="string"?{contentType:Wo,bytes:ah.encode(e)}:e;if(!t||![...h2,Wo].includes(t.contentType))throw new Error("Unsupported MIME type.");if(!(t.bytes instanceof Uint8Array)||!t.bytes.length)throw new Error("Enter non-empty inscription bytes.");if(t.bytes.length>rl)throw new Error(`Body must be at most ${rl} bytes.`);return{contentType:t.contentType,bytes:new Uint8Array(t.bytes)}}function Yo(e){const t=/^([0-9a-f]{64})i(0|[1-9][0-9]*)$/.exec(e);if(!t||Number(t[2])>4294967295)throw new Error("Invalid parent inscription id.");let n=Number(t[2]),r="";for(;n;)r+=(n%256).toString(16).padStart(2,"0"),n=Math.floor(n/256);return t[1].match(/../g).reverse().join("")+r}function sl(e){if(typeof e!="string"||!/^[0-9a-f]{64,72}$/.test(e)||e.length%2)throw new Error("Invalid parent tag.");const t=[...Yn(e.slice(64))].reduce((r,s,o)=>r+s*256**o,0),n=`${e.slice(0,64).match(/../g).reverse().join("")}i${t}`;if(Yo(n)!==e)throw new Error("Non-canonical parent tag.");return n}function qc(e,t,n=null,r=void 0,s={}){const{contentType:o,bytes:i}=Vc(t),{delegate:a=null,pointer:c,metaprotocol:u=null}=s,f=u==null||u===""?null:new TextEncoder().encode(String(u));if(f&&f.length>520)throw new Error("Metaprotocol identifier must be 520 bytes or less.");const l=r===void 0?void 0:ih(r),d=[];for(let g=0;g{const h=g.length/2;return(h<=75?h.toString(16).padStart(2,"0"):h<=255?"4c"+h.toString(16).padStart(2,"0"):"4d"+(h%256).toString(16).padStart(2,"0")+Math.floor(h/256).toString(16).padStart(2,"0"))+g};return p(e)+"ac0063"+p(Go("ord"))+p("01")+p(Go(o))+(a?p("0b")+p(Yo(a)):"")+(c===void 0?"":p("02")+p(uh(c)))+(n?p("03")+p(Yo(n)):"")+(l===void 0?"":Array.from({length:Math.ceil(l.length/520)},(g,h)=>p("05")+p(ks(l.slice(h*520,(h+1)*520)))).join(""))+(f?p("07")+p(ks(f)):"")+"00"+d.map(p).join("")+"68"}const ch=e=>Fs.tree.getLeaf(Ce.encode(e,!0));function zc(e){if(!Array.isArray(e)||e.length!==3)throw new Error("Unsupported script-path witness.");const t=Ce.decode(e[1]);let n=7,r=null,s=null,o;t[n]==="0b"&&(s=sl(t[n+1]),n+=2),t[n]==="02"&&(o=g2(t[n+1]==="OP_0"?"":t[n+1]),n+=2),t[n]==="03"&&(r=sl(t[n+1]),n+=2);const i=[];for(;t[n]==="05";){const g=t[n+1];if(typeof g!="string"||!/^(?:[0-9a-f]{2}){1,520}$/.test(g))throw new Error("Invalid metadata push.");i.push(g),n+=2}const a=i.length?d2(Yn(i.join(""))):void 0;let c=null;if(t[n]==="07"){const g=t[n+1];if(typeof g!="string"||!/^(?:[0-9a-f]{2}){1,520}$/.test(g))throw new Error("Invalid metaprotocol field.");c=new TextDecoder().decode(Yn(g)),n+=2}if(t[n]!=="OP_0")throw new Error("Unsupported ord tag or missing body separator.");const u=t.slice(n+1,-1);if(!u.length||u.some(g=>typeof g!="string"||!/^(?:[0-9a-f]{2})+$/.test(g)))throw new Error("Invalid body envelope.");const f=new TextDecoder().decode(Yn(t[6])),l=Vc({contentType:f,bytes:Yn(u.join(""))}),d=qc(t[0],l,r,a,{delegate:s,pointer:o,metaprotocol:c}),p=a===void 0&&!r&&f===Wo&&l.bytes.length<=280&&Ce.encode([t[0],"OP_CHECKSIG","OP_0","OP_IF",Go("ord"),"01",Go(Wo),"OP_0",ks(l.bytes),"OP_ENDIF"],!1).hex;if(d!==e[1]&&p!==e[1])throw new Error("Unsupported ord envelope.");if(!/^[0-9a-f]{64}$/.test(t[0]))throw new Error("Invalid inscription signing key.");return{...l,parent:r,delegate:s,pointer:o,metaprotocol:c,metadata:a,metadataBytes:i.length?Yn(i.join("")):void 0,text:new TextDecoder().decode(l.bytes),pubkey:t[0]}}class p2{constructor(t,n){this.chain=t,this.wallet=n}prepare(t,n=null,r=void 0,s={}){const o=Vc(t);if(r!==void 0&&ih(r),s.delegate&&Yo(s.delegate),s.pointer!==void 0&&uh(s.pointer),s.metaprotocol!==void 0&&s.metaprotocol!==null&&s.metaprotocol!==""&&new TextEncoder().encode(String(s.metaprotocol)).length>520)throw new Error("Metaprotocol identifier must be 520 bytes or less.");if(n&&s.reinscribe)throw new Error("Choose parent or reinscription, not both.");const i=this.chain.coins(this.wallet.script),a=n?i.find(f=>{var l;return(l=f.inscriptions)==null?void 0:l.some(d=>d.id===n)}):null;if(n&&!a)throw new Error("Parent must be an owned, unspent inscription.");const c=s.reinscribe?i.find(f=>{var l;return(l=f.inscriptions)==null?void 0:l.some(d=>d.id===s.reinscribe)}):null;if(s.reinscribe&&!c)throw new Error("Reinscription must spend an owned sat.");const u=i.find(f=>!f.inscription&&f.value>=Rt+2*W+330);if(!u)throw new Error("Mine a block first to get spendable fake BTC.");return{...o,coin:u,parent:a,reinscribe:c,totalFee:W*2,postage:Rt}}inscribe(t,n=null,r=void 0,s={}){const{coin:o,parent:i,reinscribe:a,...c}=this.prepare(t,n,r,s),u=i??a,f=a==null?void 0:a.inscriptions.find(P=>P.id===s.reinscribe),l=f?this.chain.satLocation(f.sat).offset:s.pointer??(i?i.value:void 0),d=qc(this.wallet.pubkey,c,n,r,{...s,pointer:l}),p=ch(d),[g,h]=Fs.getPubKey(this.wallet.pubkey,{target:p}),y=X.create({vin:[Fe(o.txid,o.vout,o.value,o.scriptPubKey)],vout:[de(Rt+W,["OP_1",g]),de(o.value-Rt-2*W,this.wallet.script)]});y.vin[0].witness=[this.wallet.sign(y)];const m=X.util.getTxid(y),x=X.create({vin:[...u?[Fe(u.txid,u.vout,u.value,u.scriptPubKey)]:[],Fe(m,0,Rt+W,["OP_1",g])],vout:[...u?[de(u.value,this.wallet.script)]:[],de(Rt,this.wallet.script)]}),w=u?1:0;return x.vin[w].witness=[this.wallet.sign(x,p,w),Ce.encode(d,!1).hex,h],u&&(x.vin[0].witness=[this.wallet.sign(x)]),this.chain.submitPackage([X.encode(y).hex,X.encode(x).hex]),`${X.util.getTxid(x)}i0`}list(){return this.chain.coins(this.wallet.script).flatMap(t=>t.inscriptions??[])}}function uh(e){let t;try{t=BigInt(e)}catch{throw new Error("Invalid pointer.")}if(t<0n||t>0xffffffffffffffffn||typeof e=="number"&&!Number.isSafeInteger(e))throw new Error("Invalid pointer.");let n="";for(;t;)n+=Number(t&255n).toString(16).padStart(2,"0"),t>>=8n;return n}function g2(e){if(typeof e!="string"||!/^(?:[0-9a-f]{2}){0,8}$/.test(e))throw new Error("Invalid pointer tag.");return[...Yn(e)].reduce((t,n,r)=>t+(BigInt(n)<this.utxos.set(`${r.txid}:${r.vout}`,{txid:r.txid,vout:r.vout,value:r.value,ranges:Xl(s,r.value)}));const n=(r,s,o)=>{var m;const i=X.decode(r),a=X.util.getTxid(i),c=i.vin[0].txid==="0".repeat(64),u=c?[]:i.vin.map(x=>this.utxos.get(`${x.txid}:${x.vout}`)),f=ef(i,u,s,c);i.vin.forEach(x=>this.utxos.delete(`${x.txid}:${x.vout}`)),i.vout.forEach((x,w)=>this.utxos.set(`${a}:${w}`,{txid:a,vout:w,value:Number(x.value),ranges:f[w]}));const l=(m=i.vin.find(x=>{var w;return((w=x.witness)==null?void 0:w.length)===3}))==null?void 0:m.witness;if(!l)return;const d=zc(l),p=BigInt(d.pointer??0),g=i.vout.reduce((x,w)=>x+Number(w.value),0),h=Ql(f.flat(),px.sat===h).length,status:s===null?"pending":"confirmed",height:s,block:o,metadata:y??null,hasMetadata:y!==void 0,parent:d.parent,protocol:d.metaprotocol??(y&&!Array.isArray(y)&&typeof y=="object"&&Object.hasOwn(y,"protocol")&&typeof y.protocol=="string"?y.protocol:null)})};for(const r of t.blocks)for(const s of r.raws)n(s,r.height,r.hash);for(const r of t.mempool)n(r,null,null);for(const r of this.events){r.location=null;for(const s of this.utxos.values()){const o=tn(s.ranges,r.sat);if(o!==null){r.location={txid:s.txid,vout:s.vout,offset:o};break}}r.delegatedBy=this.events.filter(s=>s.delegate===r.id).map(s=>s.id),r.inscriptions=this.events.filter(s=>s.sat===r.sat).map(s=>s.id)}}forProtocol(t){return this.events.filter(n=>n.protocol===t)}get protocols(){return[...new Set(this.events.filter(t=>t.protocol!==null).map(t=>t.protocol))].sort()}get stats(){return{events:this.events.length,withMetadata:this.events.filter(t=>t.hasMetadata).length,confirmed:this.events.filter(t=>t.status==="confirmed").length,pending:this.events.filter(t=>t.status==="pending").length,protocols:this.protocols}}}const Tr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Gs(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function jt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Ve(e,...t){if(!Gs(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Ys(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");jt(e.outputLen),jt(e.blockLen)}function Yr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function lh(e,t){Ve(e);const n=t.outputLen;if(e.length>>t}function co(e,t){return e<>>32-t>>>0}const y2=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function w2(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function b2(e){for(let t=0;te:b2,fh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",x2=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ie(e){if(Ve(e),fh)return e.toHex();let t="";for(let n=0;n=Jt._0&&e<=Jt._9)return e-Jt._0;if(e>=Jt.A&&e<=Jt.F)return e-(Jt.A-10);if(e>=Jt.a&&e<=Jt.f)return e-(Jt.a-10)}function bt(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(fh)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let s=0,o=0;se().update(Xr(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function kr(e=32){if(Tr&&typeof Tr.getRandomValues=="function")return Tr.getRandomValues(new Uint8Array(e));if(Tr&&typeof Tr.randomBytes=="function")return Uint8Array.from(Tr.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function k2(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const s=BigInt(32),o=BigInt(4294967295),i=Number(n>>s&o),a=Number(n&o),c=r?4:0,u=r?0:4;e.setUint32(t+c,i,r),e.setUint32(t+u,a,r)}function $2(e,t,n){return e&t^~e&n}function E2(e,t,n){return e&t^e&n^t&n}class Wc extends Fc{constructor(t,n,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(t),this.view=ir(this.buffer)}update(t){Yr(this),t=Xr(t),Ve(t);const{view:n,buffer:r,blockLen:s}=this,o=t.length;for(let i=0;is-i&&(this.process(r,0),i=0);for(let l=i;lf.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l>cl&uo)}:{h:Number(e>>cl&uo)|0,l:Number(e&uo)|0}}function dh(e,t=!1){const n=e.length;let r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;oe>>>n,ll=(e,t,n)=>e<<32-n|t>>>n,Or=(e,t,n)=>e>>>n|t<<32-n,Ir=(e,t,n)=>e<<32-n|t>>>n,lo=(e,t,n)=>e<<64-n|t>>>n-32,fo=(e,t,n)=>e>>>n-32|t<<64-n,_2=(e,t,n)=>e<>>32-n,A2=(e,t,n)=>t<>>32-n,B2=(e,t,n)=>t<>>64-n,T2=(e,t,n)=>e<>>64-n;function Qt(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}const O2=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),I2=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,C2=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),P2=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,U2=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),N2=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,L2=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),$n=new Uint32Array(64);class H2 extends Wc{constructor(t=32){super(64,t,8,!1),this.A=kn[0]|0,this.B=kn[1]|0,this.C=kn[2]|0,this.D=kn[3]|0,this.E=kn[4]|0,this.F=kn[5]|0,this.G=kn[6]|0,this.H=kn[7]|0}get(){const{A:t,B:n,C:r,D:s,E:o,F:i,G:a,H:c}=this;return[t,n,r,s,o,i,a,c]}set(t,n,r,s,o,i,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,n){for(let l=0;l<16;l++,n+=4)$n[l]=t.getUint32(n,!1);for(let l=16;l<64;l++){const d=$n[l-15],p=$n[l-2],g=Ht(d,7)^Ht(d,18)^d>>>3,h=Ht(p,17)^Ht(p,19)^p>>>10;$n[l]=h+$n[l-7]+g+$n[l-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){const d=Ht(a,6)^Ht(a,11)^Ht(a,25),p=f+d+$2(a,c,u)+L2[l]+$n[l]|0,h=(Ht(r,2)^Ht(r,13)^Ht(r,22))+E2(r,s,o)|0;f=u,u=c,c=a,a=i+p|0,i=o,o=s,s=r,r=p+h|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,s,o,i,a,c,u,f)}roundClean(){wt($n)}destroy(){this.set(0,0,0,0,0,0,0,0),wt(this.buffer)}}const hh=dh(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),R2=hh[0],j2=hh[1],En=new Uint32Array(80),Sn=new Uint32Array(80);class K2 extends Wc{constructor(t=64){super(128,t,16,!1),this.Ah=Xe[0]|0,this.Al=Xe[1]|0,this.Bh=Xe[2]|0,this.Bl=Xe[3]|0,this.Ch=Xe[4]|0,this.Cl=Xe[5]|0,this.Dh=Xe[6]|0,this.Dl=Xe[7]|0,this.Eh=Xe[8]|0,this.El=Xe[9]|0,this.Fh=Xe[10]|0,this.Fl=Xe[11]|0,this.Gh=Xe[12]|0,this.Gl=Xe[13]|0,this.Hh=Xe[14]|0,this.Hl=Xe[15]|0}get(){const{Ah:t,Al:n,Bh:r,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:p,Gl:g,Hh:h,Hl:y}=this;return[t,n,r,s,o,i,a,c,u,f,l,d,p,g,h,y]}set(t,n,r,s,o,i,a,c,u,f,l,d,p,g,h,y){this.Ah=t|0,this.Al=n|0,this.Bh=r|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=p|0,this.Gl=g|0,this.Hh=h|0,this.Hl=y|0}process(t,n){for(let w=0;w<16;w++,n+=4)En[w]=t.getUint32(n),Sn[w]=t.getUint32(n+=4);for(let w=16;w<80;w++){const P=En[w-15]|0,b=Sn[w-15]|0,$=Or(P,b,1)^Or(P,b,8)^ul(P,b,7),T=Ir(P,b,1)^Ir(P,b,8)^ll(P,b,7),U=En[w-2]|0,O=Sn[w-2]|0,L=Or(U,O,19)^lo(U,O,61)^ul(U,O,6),_=Ir(U,O,19)^fo(U,O,61)^ll(U,O,6),C=C2(T,_,Sn[w-7],Sn[w-16]),k=P2(C,$,L,En[w-7],En[w-16]);En[w]=k|0,Sn[w]=C|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:p,Fl:g,Gh:h,Gl:y,Hh:m,Hl:x}=this;for(let w=0;w<80;w++){const P=Or(l,d,14)^Or(l,d,18)^lo(l,d,41),b=Ir(l,d,14)^Ir(l,d,18)^fo(l,d,41),$=l&p^~l&h,T=d&g^~d&y,U=U2(x,b,T,j2[w],Sn[w]),O=N2(U,m,P,$,R2[w],En[w]),L=U|0,_=Or(r,s,28)^lo(r,s,34)^lo(r,s,39),C=Ir(r,s,28)^fo(r,s,34)^fo(r,s,39),k=r&o^r&a^o&a,S=s&i^s&c^i&c;m=h|0,x=y|0,h=p|0,y=g|0,p=l|0,g=d|0,{h:l,l:d}=Qt(u|0,f|0,O|0,L|0),u=a|0,f=c|0,a=o|0,c=i|0,o=r|0,i=s|0;const v=O2(L,C,S);r=I2(v,O,_,k),s=v|0}({h:r,l:s}=Qt(this.Ah|0,this.Al|0,r|0,s|0)),{h:o,l:i}=Qt(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=Qt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=Qt(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=Qt(this.Eh|0,this.El|0,l|0,d|0),{h:p,l:g}=Qt(this.Fh|0,this.Fl|0,p|0,g|0),{h,l:y}=Qt(this.Gh|0,this.Gl|0,h|0,y|0),{h:m,l:x}=Qt(this.Hh|0,this.Hl|0,m|0,x|0),this.set(r,s,o,i,a,c,u,f,l,d,p,g,h,y,m,x)}roundClean(){wt(En,Sn)}destroy(){wt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Ae=vi(()=>new H2),js=vi(()=>new K2);class ph extends Fc{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Ys(t);const r=Xr(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?t.create().update(r).digest():r);for(let i=0;inew ph(e,t).update(n).digest();Rn.create=(e,t)=>new ph(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Gc=BigInt(0),Ka=BigInt(1);function hr(e,t=""){if(typeof e!="boolean"){const n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function _t(e,t,n=""){const r=Gs(e),s=e==null?void 0:e.length,o=t!==void 0;if(!r||o&&s!==t){const i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function ho(e){const t=e.toString(16);return t.length&1?"0"+t:t}function gh(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Gc:BigInt("0x"+e)}function $r(e){return gh(Ie(e))}function pr(e){return Ve(e),gh(Ie(Uint8Array.from(e).reverse()))}function ki(e,t){return bt(e.toString(16).padStart(t*2,"0"))}function Yc(e,t){return ki(e,t).reverse()}function be(e,t,n){let r;if(typeof t=="string")try{r=bt(t)}catch(o){throw new Error(e+" must be hex string or Uint8Array, cause: "+o)}else if(Gs(t))r=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const s=r.length;if(typeof n=="number"&&s!==n)throw new Error(e+" of length "+n+" expected, got "+s);return r}function fl(e){return Uint8Array.from(e)}const ea=e=>typeof e=="bigint"&&Gc<=e;function Da(e,t,n){return ea(e)&&ea(t)&&ea(n)&&t<=e&&eGc;e>>=Ka,t+=1);return t}const Xs=e=>(Ka<new Uint8Array(p),s=p=>Uint8Array.of(p);let o=r(e),i=r(e),a=0;const c=()=>{o.fill(1),i.fill(0),a=0},u=(...p)=>n(i,o,...p),f=(p=r(0))=>{i=u(s(0),p),o=u(),p.length!==0&&(i=u(s(1),p),o=u())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0;const g=[];for(;p{c(),f(p);let h;for(;!(h=g(l()));)f();return c(),h}}function us(e,t,n={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function r(s,o,i){const a=e[s];if(i&&a===void 0)return;const c=typeof a;if(c!==o||a===null)throw new Error(`param "${s}" is invalid: expected ${o}, got ${c}`)}Object.entries(t).forEach(([s,o])=>r(s,o,!1)),Object.entries(n).forEach(([s,o])=>r(s,o,!0))}function Xo(e){const t=new WeakMap;return(n,...r)=>{const s=t.get(n);if(s!==void 0)return s;const o=e(n,...r);return t.set(n,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ut=BigInt(0),Ye=BigInt(1),tr=BigInt(2),yh=BigInt(3),wh=BigInt(4),bh=BigInt(5),M2=BigInt(7),xh=BigInt(8),Z2=BigInt(9),vh=BigInt(16);function Te(e,t){const n=e%t;return n>=ut?n:t+n}function Pe(e,t,n){let r=e;for(;t-- >ut;)r*=r,r%=n;return r}function dl(e,t){if(e===ut)throw new Error("invert: expected non-zero number");if(t<=ut)throw new Error("invert: expected positive modulus, got "+t);let n=Te(e,t),r=t,s=ut,o=Ye;for(;n!==ut;){const a=r/n,c=r%n,u=s-o*a;r=n,n=c,s=o,o=u}if(r!==Ye)throw new Error("invert: does not exist");return Te(s,t)}function Xc(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function kh(e,t){const n=(e.ORDER+Ye)/wh,r=e.pow(t,n);return Xc(e,r,t),r}function V2(e,t){const n=(e.ORDER-bh)/xh,r=e.mul(t,tr),s=e.pow(r,n),o=e.mul(t,s),i=e.mul(e.mul(o,tr),s),a=e.mul(o,e.sub(i,e.ONE));return Xc(e,a,t),a}function q2(e){const t=Er(e),n=$h(e),r=n(t,t.neg(t.ONE)),s=n(t,r),o=n(t,t.neg(r)),i=(e+M2)/vh;return(a,c)=>{let u=a.pow(c,i),f=a.mul(u,r);const l=a.mul(u,s),d=a.mul(u,o),p=a.eql(a.sqr(f),c),g=a.eql(a.sqr(l),c);u=a.cmov(u,f,p),f=a.cmov(d,l,g);const h=a.eql(a.sqr(f),c),y=a.cmov(u,f,h);return Xc(a,y,c),y}}function $h(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return kh;let o=s.pow(r,t);const i=(t+Ye)/tr;return function(c,u){if(c.is0(u))return u;if(hl(c,u)!==1)throw new Error("Cannot find square root");let f=n,l=c.mul(c.ONE,o),d=c.pow(u,t),p=c.pow(u,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let g=1,h=c.sqr(d);for(;!c.eql(h,c.ONE);)if(g++,h=c.sqr(h),g===f)throw new Error("Cannot find square root");const y=Ye<(Te(e,t)&Ye)===Ye,W2=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function G2(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=W2.reduce((r,s)=>(r[s]="function",r),t);return us(e,n),e}function Y2(e,t,n){if(nut;)n&Ye&&(r=e.mul(r,s)),s=e.sqr(s),n>>=Ye;return r}function Eh(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),s=t.reduce((i,a,c)=>e.is0(a)?i:(r[c]=i,e.mul(i,a)),e.ONE),o=e.inv(s);return t.reduceRight((i,a,c)=>e.is0(a)?i:(r[c]=e.mul(i,r[c]),e.mul(i,a)),o),r}function hl(e,t){const n=(e.ORDER-Ye)/tr,r=e.pow(t,n),s=e.eql(r,e.ONE),o=e.eql(r,e.ZERO),i=e.eql(r,e.neg(e.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function Sh(e,t){t!==void 0&&jt(t);const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Er(e,t,n=!1,r={}){if(e<=ut)throw new Error("invalid field: expected ORDER > 0, got "+e);let s,o,i=!1,a;if(typeof t=="object"&&t!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const d=t;d.BITS&&(s=d.BITS),d.sqrt&&(o=d.sqrt),typeof d.isLE=="boolean"&&(n=d.isLE),typeof d.modFromBytes=="boolean"&&(i=d.modFromBytes),a=d.allowedLengths}else typeof t=="number"&&(s=t),r.sqrt&&(o=r.sqrt);const{nBitLength:c,nByteLength:u}=Sh(e,s);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let f;const l=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:u,MASK:Xs(c),ZERO:ut,ONE:Ye,allowedLengths:a,create:d=>Te(d,e),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return ut<=d&&dd===ut,isValidNot0:d=>!l.is0(d)&&l.isValid(d),isOdd:d=>(d&Ye)===Ye,neg:d=>Te(-d,e),eql:(d,p)=>d===p,sqr:d=>Te(d*d,e),add:(d,p)=>Te(d+p,e),sub:(d,p)=>Te(d-p,e),mul:(d,p)=>Te(d*p,e),pow:(d,p)=>Y2(l,d,p),div:(d,p)=>Te(d*dl(p,e),e),sqrN:d=>d*d,addN:(d,p)=>d+p,subN:(d,p)=>d-p,mulN:(d,p)=>d*p,inv:d=>dl(d,e),sqrt:o||(d=>(f||(f=z2(e)),f(l,d))),toBytes:d=>n?Yc(d,u):ki(d,u),fromBytes:(d,p=!0)=>{if(a){if(!a.includes(d.length)||d.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);const h=new Uint8Array(u);h.set(d,n?0:h.length-d.length),d=h}if(d.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+d.length);let g=n?pr(d):$r(d);if(i&&(g=Te(g,e)),!p&&!l.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:d=>Eh(l,d),cmov:(d,p,g)=>g?p:d});return Object.freeze(l)}function _h(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Ah(e){const t=_h(e);return t+Math.ceil(t/2)}function Bh(e,t,n=!1){const r=e.length,s=_h(t),o=Ah(t);if(r<16||r1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);const i=n?pr(e):$r(e),a=Te(i,t-Ye)+Ye;return n?Yc(a,s):ki(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Jr=BigInt(0),nr=BigInt(1);function Jo(e,t){const n=t.negate();return e?n:t}function rr(e,t){const n=Eh(e.Fp,t.map(r=>r.Z));return t.map((r,s)=>e.fromAffine(r.toAffine(n[s])))}function Th(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function ta(e,t){Th(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1),s=2**e,o=Xs(e),i=BigInt(e);return{windows:n,windowSize:r,mask:o,maxNumber:s,shiftBy:i}}function pl(e,t,n){const{windowSize:r,mask:s,maxNumber:o,shiftBy:i}=n;let a=Number(e&s),c=e>>i;a>r&&(a-=o,c+=nr);const u=t*r,f=u+Math.abs(a)-1,l=a===0,d=a<0,p=t%2!==0;return{nextN:c,offset:f,isZero:l,isNeg:d,isNegF:p,offsetF:u}}function X2(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function J2(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,r)=>{if(!t.isValid(n))throw new Error("invalid scalar at index "+r)})}const na=new WeakMap,Oh=new WeakMap;function ra(e){return Oh.get(e)||1}function gl(e){if(e!==Jr)throw new Error("invalid wNAF")}class Ih{constructor(t,n){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=n}_unsafeLadder(t,n,r=this.ZERO){let s=t;for(;n>Jr;)n&nr&&(r=r.add(s)),s=s.double(),n>>=nr;return r}precomputeWindow(t,n){const{windows:r,windowSize:s}=ta(n,this.bits),o=[];let i=t,a=i;for(let c=0;cJr||r>Jr;)n&nr&&(o=o.add(s)),r&nr&&(i=i.add(s)),s=s.double(),n>>=nr,r>>=nr;return{p1:o,p2:i}}function Ch(e,t,n,r){X2(n,e),J2(r,t);const s=n.length,o=r.length;if(s!==o)throw new Error("arrays of points and scalars must have equal length");const i=e.ZERO,a=mh(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Xs(c),f=new Array(Number(u)+1).fill(i),l=Math.floor((t.BITS-1)/c)*c;let d=i;for(let p=l;p>=0;p-=c){f.fill(i);for(let h=0;h>BigInt(p)&u);f[m]=f[m].add(n[h])}let g=i;for(let h=f.length-1,y=i;h>0;h--)y=y.add(f[h]),g=g.add(y);if(d=d.add(g),p!==0)for(let h=0;hJr))throw new Error(`CURVE.${c} must be positive bigint`)}const s=ml(t.p,n.Fp,r),o=ml(t.n,n.Fn,r),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(const c of a)if(!s.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:s,Fn:o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const yl=(e,t)=>(e+(e>=0?t:-t)/Uh)/t;function ev(e,t,n){const[[r,s],[o,i]]=t,a=yl(i*e,n),c=yl(-s*e,n);let u=e-a*r-c*o,f=-a*s-c*i;const l=u=p||f=p)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:l,k1:u,k2neg:d,k2:f}}function Ma(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function sa(e,t){const n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return hr(n.lowS,"lowS"),hr(n.prehash,"prehash"),n.format!==void 0&&Ma(n.format),n}class tv extends Error{constructor(t=""){super(t)}}const en={Err:tv,_tlv:{encode:(e,t)=>{const{Err:n}=en;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length&1)throw new n("tlv.encode: unpadded data");const r=t.length/2,s=ho(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const o=r>127?ho(s.length/2|128):"";return ho(e)+o+s+t},decode(e,t){const{Err:n}=en;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const s=t[r++],o=!!(s&128);let i=0;if(!o)i=s;else{const c=s&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");const u=t.subarray(r,r+c);if(u.length!==c)throw new n("tlv.decode: length bytes not complete");if(u[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const f of u)i=i<<8|f;if(r+=c,i<128)throw new n("tlv.decode(long): not minimal encoding")}const 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){const{Err:t}=en;if(e{const{X:S,Y:v,Z:A}=C;if(r.eql(A,r.ONE))return{x:S,y:v};const N=C.is0();k==null&&(k=N?r.ONE:r.inv(A));const K=r.mul(S,k),H=r.mul(v,k),D=r.mul(A,k);if(N)return{x:r.ZERO,y:r.ZERO};if(!r.eql(D,r.ONE))throw new Error("invZ was invalid");return{x:K,y:H}}),T=Xo(C=>{if(C.is0()){if(t.allowInfinityPoint&&!r.is0(C.Y))return;throw new Error("bad point: ZERO")}const{x:k,y:S}=C.toAffine();if(!r.isValid(k)||!r.isValid(S))throw new Error("bad point: x or y not field elements");if(!y(k,S))throw new Error("bad point: equation left != right");if(!C.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function U(C,k,S,v,A){return S=new O(r.mul(S.X,C),S.Y,S.Z),k=Jo(v,k),S=Jo(A,S),k.add(S)}class O{constructor(k,S,v){this.X=w("x",k),this.Y=w("y",S,!0),this.Z=w("z",v),Object.freeze(this)}static CURVE(){return o}static fromAffine(k){const{x:S,y:v}=k||{};if(!k||!r.isValid(S)||!r.isValid(v))throw new Error("invalid affine point");if(k instanceof O)throw new Error("projective point not allowed");return r.is0(S)&&r.is0(v)?O.ZERO:new O(S,v,r.ONE)}static fromBytes(k){const S=O.fromAffine(g(_t(k,void 0,"point")));return S.assertValidity(),S}static fromHex(k){return O.fromBytes(be("pointHex",k))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(k=8,S=!0){return _.createCache(this,k),S||this.multiply(po),this}assertValidity(){T(this)}hasEvenY(){const{y:k}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(k)}equals(k){P(k);const{X:S,Y:v,Z:A}=this,{X:N,Y:K,Z:H}=k,D=r.eql(r.mul(S,H),r.mul(N,A)),q=r.eql(r.mul(v,H),r.mul(K,A));return D&&q}negate(){return new O(this.X,r.neg(this.Y),this.Z)}double(){const{a:k,b:S}=o,v=r.mul(S,po),{X:A,Y:N,Z:K}=this;let H=r.ZERO,D=r.ZERO,q=r.ZERO,G=r.mul(A,A),fe=r.mul(N,N),ce=r.mul(K,K),ne=r.mul(A,N);return ne=r.add(ne,ne),q=r.mul(A,K),q=r.add(q,q),H=r.mul(k,q),D=r.mul(v,ce),D=r.add(H,D),H=r.sub(fe,D),D=r.add(fe,D),D=r.mul(H,D),H=r.mul(ne,H),q=r.mul(v,q),ce=r.mul(k,ce),ne=r.sub(G,ce),ne=r.mul(k,ne),ne=r.add(ne,q),q=r.add(G,G),G=r.add(q,G),G=r.add(G,ce),G=r.mul(G,ne),D=r.add(D,G),ce=r.mul(N,K),ce=r.add(ce,ce),G=r.mul(ce,ne),H=r.sub(H,G),q=r.mul(ce,fe),q=r.add(q,q),q=r.add(q,q),new O(H,D,q)}add(k){P(k);const{X:S,Y:v,Z:A}=this,{X:N,Y:K,Z:H}=k;let D=r.ZERO,q=r.ZERO,G=r.ZERO;const fe=o.a,ce=r.mul(o.b,po);let ne=r.mul(S,N),ge=r.mul(v,K),me=r.mul(A,H),Le=r.add(S,v),pe=r.add(N,K);Le=r.mul(Le,pe),pe=r.add(ne,ge),Le=r.sub(Le,pe),pe=r.add(S,A);let _e=r.add(N,H);return pe=r.mul(pe,_e),_e=r.add(ne,me),pe=r.sub(pe,_e),_e=r.add(v,A),D=r.add(K,H),_e=r.mul(_e,D),D=r.add(ge,me),_e=r.sub(_e,D),G=r.mul(fe,pe),D=r.mul(ce,me),G=r.add(D,G),D=r.sub(ge,G),G=r.add(ge,G),q=r.mul(D,G),ge=r.add(ne,ne),ge=r.add(ge,ne),me=r.mul(fe,me),pe=r.mul(ce,pe),ge=r.add(ge,me),me=r.sub(ne,me),me=r.mul(fe,me),pe=r.add(pe,me),ne=r.mul(ge,pe),q=r.add(q,ne),ne=r.mul(_e,pe),D=r.mul(Le,D),D=r.sub(D,ne),ne=r.mul(Le,ge),G=r.mul(_e,G),G=r.add(G,ne),new O(D,q,G)}subtract(k){return this.add(k.negate())}is0(){return this.equals(O.ZERO)}multiply(k){const{endo:S}=t;if(!s.isValidNot0(k))throw new Error("invalid scalar: out of range");let v,A;const N=K=>_.cached(this,K,H=>rr(O,H));if(S){const{k1neg:K,k1:H,k2neg:D,k2:q}=b(k),{p:G,f:fe}=N(H),{p:ce,f:ne}=N(q);A=fe.add(ne),v=U(S.beta,G,ce,K,D)}else{const{p:K,f:H}=N(k);v=K,A=H}return rr(O,[v,A])[0]}multiplyUnsafe(k){const{endo:S}=t,v=this;if(!s.isValid(k))throw new Error("invalid scalar: out of range");if(k===nn||v.is0())return O.ZERO;if(k===jr)return v;if(_.hasCache(this))return this.multiply(k);if(S){const{k1neg:A,k1:N,k2neg:K,k2:H}=b(k),{p1:D,p2:q}=Q2(O,v,N,H);return U(S.beta,D,q,A,K)}else return _.unsafe(v,k)}multiplyAndAddUnsafe(k,S,v){const A=this.multiplyUnsafe(S).add(k.multiplyUnsafe(v));return A.is0()?void 0:A}toAffine(k){return $(this,k)}isTorsionFree(){const{isTorsionFree:k}=t;return i===jr?!0:k?k(O,this):_.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:k}=t;return i===jr?this:k?k(O,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(k=!0){return hr(k,"isCompressed"),this.assertValidity(),p(O,this,k)}toHex(k=!0){return Ie(this.toBytes(k))}toString(){return``}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(k=!0){return this.toBytes(k)}_setWindowSize(k){this.precompute(k)}static normalizeZ(k){return rr(O,k)}static msm(k,S){return Ch(O,s,k,S)}static fromPrivateKey(k){return O.BASE.multiply(sr(s,k))}}O.BASE=new O(o.Gx,o.Gy,r.ONE),O.ZERO=new O(r.ZERO,r.ONE,r.ZERO),O.Fp=r,O.Fn=s;const L=s.BITS,_=new Ih(O,t.endo?Math.ceil(L/2):L);return O.BASE.precompute(8),O}function Nh(e){return Uint8Array.of(e?2:3)}function Lh(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function sv(e,t={}){const{Fn:n}=e,r=t.randomBytes||kr,s=Object.assign(Lh(e.Fp,n),{seed:Ah(n.ORDER)});function o(p){try{return!!sr(n,p)}catch{return!1}}function i(p,g){const{publicKey:h,publicKeyUncompressed:y}=s;try{const m=p.length;return g===!0&&m!==h||g===!1&&m!==y?!1:!!e.fromBytes(p)}catch{return!1}}function a(p=r(s.seed)){return Bh(_t(p,s.seed,"seed"),n.ORDER)}function c(p,g=!0){return e.BASE.multiply(sr(n,p)).toBytes(g)}function u(p){const g=a(p);return{secretKey:g,publicKey:c(g)}}function f(p){if(typeof p=="bigint")return!1;if(p instanceof e)return!0;const{secretKey:g,publicKey:h,publicKeyUncompressed:y}=s;if(n.allowedLengths||g===h)return;const m=be("key",p).length;return m===h||m===y}function l(p,g,h=!0){if(f(p)===!0)throw new Error("first arg must be private key");if(f(g)===!1)throw new Error("second arg must be public key");const y=sr(n,p);return e.fromHex(g).multiply(y).toBytes(h)}return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:u,Point:e,utils:{isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:p=>sr(n,p),precompute(p=8,g=e.BASE){return g.precompute(p,!1)}},lengths:s})}function ov(e,t,n={}){Ys(t),us(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||kr,s=n.hmac||((S,...v)=>Rn(t,S,ue(...v))),{Fp:o,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:f,getSharedSecret:l,utils:d,lengths:p}=sv(e,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},h="compact";function y(S){const v=a>>jr;return S>v}function m(S,v){if(!i.isValidNot0(v))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return v}function x(S,v){Ma(v);const A=p.signature,N=v==="compact"?A:v==="recovered"?A+1:void 0;return _t(S,N,`${v} signature`)}class w{constructor(v,A,N){this.r=m("r",v),this.s=m("s",A),N!=null&&(this.recovery=N),Object.freeze(this)}static fromBytes(v,A=h){x(v,A);let N;if(A==="der"){const{r:q,s:G}=en.toSig(_t(v));return new w(q,G)}A==="recovered"&&(N=v[0],A="compact",v=v.subarray(1));const K=i.BYTES,H=v.subarray(0,K),D=v.subarray(K,K*2);return new w(i.fromBytes(H),i.fromBytes(D),N)}static fromHex(v,A){return this.fromBytes(bt(v),A)}addRecoveryBit(v){return new w(this.r,this.s,v)}recoverPublicKey(v){const A=o.ORDER,{r:N,s:K,recovery:H}=this;if(H==null||![0,1,2,3].includes(H))throw new Error("recovery id invalid");if(a*Uh1)throw new Error("recovery id is ambiguous for h>1 curve");const q=H===2||H===3?N+a:N;if(!o.isValid(q))throw new Error("recovery id 2 or 3 invalid");const G=o.toBytes(q),fe=e.fromBytes(ue(Nh((H&1)===0),G)),ce=i.inv(q),ne=b(be("msgHash",v)),ge=i.create(-ne*ce),me=i.create(K*ce),Le=e.BASE.multiplyUnsafe(ge).add(fe.multiplyUnsafe(me));if(Le.is0())throw new Error("point at infinify");return Le.assertValidity(),Le}hasHighS(){return y(this.s)}toBytes(v=h){if(Ma(v),v==="der")return bt(en.hexFromSig(this));const A=i.toBytes(this.r),N=i.toBytes(this.s);if(v==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ue(Uint8Array.of(this.recovery),A,N)}return ue(A,N)}toHex(v){return Ie(this.toBytes(v))}assertValidity(){}static fromCompact(v){return w.fromBytes(be("sig",v),"compact")}static fromDER(v){return w.fromBytes(be("sig",v),"der")}normalizeS(){return this.hasHighS()?new w(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ie(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ie(this.toBytes("compact"))}}const P=n.bits2int||function(v){if(v.length>8192)throw new Error("input is too large");const A=$r(v),N=v.length*8-c;return N>0?A>>BigInt(N):A},b=n.bits2int_modN||function(v){return i.create(P(v))},$=Xs(c);function T(S){return Ks("num < 2^"+c,S,nn,$),i.toBytes(S)}function U(S,v){return _t(S,void 0,"message"),v?_t(t(S),void 0,"prehashed message"):S}function O(S,v,A){if(["recovered","canonical"].some(ge=>ge in A))throw new Error("sign() legacy options not supported");const{lowS:N,prehash:K,extraEntropy:H}=sa(A,g);S=U(S,K);const D=b(S),q=sr(i,v),G=[T(q),T(D)];if(H!=null&&H!==!1){const ge=H===!0?r(p.secretKey):H;G.push(be("extraEntropy",ge))}const fe=ue(...G),ce=D;function ne(ge){const me=P(ge);if(!i.isValidNot0(me))return;const Le=i.inv(me),pe=e.BASE.multiply(me).toAffine(),_e=i.create(pe.x);if(_e===nn)return;const Gt=i.create(Le*i.create(ce+_e*q));if(Gt===nn)return;let ht=(pe.x===_e?0:2)|Number(pe.y&jr),We=Gt;return N&&y(Gt)&&(We=i.neg(Gt),ht^=1),new w(_e,We,ht)}return{seed:fe,k2sig:ne}}function L(S,v,A={}){S=be("message",S);const{seed:N,k2sig:K}=O(S,v,A);return D2(t.outputLen,i.BYTES,s)(N,K)}function _(S){let v;const A=typeof S=="string"||Gs(S),N=!A&&S!==null&&typeof S=="object"&&typeof S.r=="bigint"&&typeof S.s=="bigint";if(!A&&!N)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(N)v=new w(S.r,S.s);else if(A){try{v=w.fromBytes(be("sig",S),"der")}catch(K){if(!(K instanceof en.Err))throw K}if(!v)try{v=w.fromBytes(be("sig",S),"compact")}catch{return!1}}return v||!1}function C(S,v,A,N={}){const{lowS:K,prehash:H,format:D}=sa(N,g);if(A=be("publicKey",A),v=U(be("message",v),H),"strict"in N)throw new Error("options.strict was renamed to lowS");const q=D===void 0?_(S):w.fromBytes(be("sig",S),D);if(q===!1)return!1;try{const G=e.fromBytes(A);if(K&&q.hasHighS())return!1;const{r:fe,s:ce}=q,ne=b(v),ge=i.inv(ce),me=i.create(ne*ge),Le=i.create(fe*ge),pe=e.BASE.multiplyUnsafe(me).add(G.multiplyUnsafe(Le));return pe.is0()?!1:i.create(pe.x)===fe}catch{return!1}}function k(S,v,A={}){const{prehash:N}=sa(A,g);return v=U(v,N),w.fromBytes(S,"recovered").recoverPublicKey(v).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:l,utils:d,lengths:p,Point:e,sign:L,verify:C,recoverPublicKey:k,Signature:w,hash:t})}function iv(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0;const s=Er(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),o={Fp:n,Fn:s,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:o}}function av(e){const{CURVE:t,curveOpts:n}=iv(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function cv(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Sh(n.Fn.ORDER,n.Fn.BITS))})}function uv(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:s}=av(e),o=rv(t,n),i=ov(o,r,s);return cv(e,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function lv(e,t){const n=r=>uv({...e,hash:r});return{...n(t),create:n}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Qr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},fv={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},dv=BigInt(0),wl=BigInt(1),Za=BigInt(2);function hv(e){const t=Qr.p,n=BigInt(3),r=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,f=u*u*e%t,l=Pe(f,n,t)*f%t,d=Pe(l,n,t)*f%t,p=Pe(d,Za,t)*u%t,g=Pe(p,s,t)*p%t,h=Pe(g,o,t)*g%t,y=Pe(h,a,t)*h%t,m=Pe(y,c,t)*y%t,x=Pe(m,a,t)*h%t,w=Pe(x,n,t)*f%t,P=Pe(w,i,t)*g%t,b=Pe(P,r,t)*u%t,$=Pe(b,Za,t);if(!Qo.eql(Qo.sqr($),e))throw new Error("Cannot find square root");return $}const Qo=Er(Qr.p,{sqrt:hv}),Oe=lv({...Qr,Fp:Qo,lowS:!0,endo:fv},Ae),bl={};function ei(e,...t){let n=bl[e];if(n===void 0){const r=Ae(Ke(e));n=ue(r,r),bl[e]=n}return Ae(ue(n,...t))}const Jc=e=>e.toBytes(!0).slice(1),ls=Oe.Point,Qc=e=>e%Za===dv;function Va(e){const{Fn:t,BASE:n}=ls,r=sr(t,e),s=n.multiply(r);return{scalar:Qc(s.y)?r:t.neg(r),bytes:Jc(s)}}function Hh(e){const t=Qo;if(!t.isValidNot0(e))throw new Error("invalid x: Fail if x ≥ p");const n=t.create(e*e),r=t.create(n*e+BigInt(7));let s=t.sqrt(r);Qc(s)||(s=t.neg(s));const o=ls.fromAffine({x:e,y:s});return o.assertValidity(),o}const $s=$r;function Rh(...e){return ls.Fn.create($s(ei("BIP0340/challenge",...e)))}function xl(e){return Va(e).bytes}function pv(e,t,n=kr(32)){const{Fn:r}=ls,s=be("message",e),{bytes:o,scalar:i}=Va(t),a=be("auxRand",n,32),c=r.toBytes(i^$s(ei("BIP0340/aux",a))),u=ei("BIP0340/nonce",c,o,s),{bytes:f,scalar:l}=Va(u),d=Rh(f,o,s),p=new Uint8Array(64);if(p.set(f,0),p.set(r.toBytes(r.create(l+d*i)),32),!jh(p,s,o))throw new Error("sign: Invalid signature produced");return p}function jh(e,t,n){const{Fn:r,BASE:s}=ls,o=be("signature",e,64),i=be("message",t),a=be("publicKey",n,32);try{const c=Hh($s(a)),u=$s(o.subarray(0,32));if(!Da(u,wl,Qr.p))return!1;const f=$s(o.subarray(32,64));if(!Da(f,wl,Qr.n))return!1;const l=Rh(r.toBytes(u),Jc(c),i),d=s.multiplyUnsafe(f).add(c.multiplyUnsafe(r.neg(l))),{x:p,y:g}=d.toAffine();return!(d.is0()||!Qc(g)||p!==u)}catch{return!1}}const jn=(()=>{const n=(s=kr(48))=>Bh(s,Qr.n);Oe.utils.randomSecretKey;function r(s){const o=n(s);return{secretKey:o,publicKey:xl(o)}}return{keygen:r,getPublicKey:xl,sign:pv,verify:jh,Point:ls,utils:{randomSecretKey:n,randomPrivateKey:n,taggedHash:ei,lift_x:Hh,pointToBytes:Jc,numberToBytesBE:ki,bytesToNumberBE:$r,mod:Te},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})(),gv=BigInt(0),gs=BigInt(1),mv=BigInt(2),yv=BigInt(7),wv=BigInt(256),bv=BigInt(113),Kh=[],Dh=[],Mh=[];for(let e=0,t=gs,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Kh.push(2*(5*r+n)),Dh.push((e+1)*(e+2)/2%64);let s=gv;for(let o=0;o<7;o++)t=(t<>yv)*bv)%wv,t&mv&&(s^=gs<<(gs<n>32?B2(e,t,n):_2(e,t,n),kl=(e,t,n)=>n>32?T2(e,t,n):A2(e,t,n);function kv(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let i=0;i<10;i++)n[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,u=n[c],f=n[c+1],l=vl(u,f,1)^n[a],d=kl(u,f,1)^n[a+1];for(let p=0;p<50;p+=10)e[i+p]^=l,e[i+p+1]^=d}let s=e[2],o=e[3];for(let i=0;i<24;i++){const a=Dh[i],c=vl(s,o,a),u=kl(s,o,a),f=Kh[i];s=e[f],o=e[f+1],e[f]=c,e[f+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)n[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~n[(a+2)%10]&n[(a+4)%10]}e[0]^=xv[r],e[1]^=vv[r]}wt(n)}class eu extends Fc{constructor(t,n,r,s=!1,o=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,jt(r),!(0=r&&this.keccak();const i=Math.min(r-this.posOut,o-s);t.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return jt(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(lh(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,wt(this.state)}_cloneInto(t){const{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return t||(t=new eu(n,r,s,i,o)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=o,t.suffix=r,t.outputLen=s,t.enableXOF=i,t.destroyed=this.destroyed,t}}const $v=(e,t,n)=>vi(()=>new eu(t,e,n)),tu=$v(1,136,256/8),Ev=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Vh=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),Sv=Vh.map(e=>(9*e+5)%16),qh=(()=>{const n=[[Vh],[Sv]];for(let r=0;r<4;r++)for(let s of n)s.push(s[r].map(o=>Ev[o]));return n})(),zh=qh[0],Fh=qh[1],Wh=[[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)),_v=zh.map((e,t)=>e.map(n=>Wh[t][n])),Av=Fh.map((e,t)=>e.map(n=>Wh[t][n])),Bv=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Tv=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function $l(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)}const go=new Uint32Array(16);class Ov extends Wc{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:n,h2:r,h3:s,h4:o}=this;return[t,n,r,s,o]}set(t,n,r,s,o){this.h0=t|0,this.h1=n|0,this.h2=r|0,this.h3=s|0,this.h4=o|0}process(t,n){for(let p=0;p<16;p++,n+=4)go[p]=t.getUint32(n,!0);let r=this.h0|0,s=r,o=this.h1|0,i=o,a=this.h2|0,c=a,u=this.h3|0,f=u,l=this.h4|0,d=l;for(let p=0;p<5;p++){const g=4-p,h=Bv[p],y=Tv[p],m=zh[p],x=Fh[p],w=_v[p],P=Av[p];for(let b=0;b<16;b++){const $=co(r+$l(p,o,a,u)+go[m[b]]+h,w[b])+l|0;r=l,l=u,u=co(a,10)|0,a=o,o=$}for(let b=0;b<16;b++){const $=co(s+$l(g,i,c,f)+go[x[b]]+y,P[b])+d|0;s=d,d=f,f=co(c,10)|0,c=i,i=$}}this.set(this.h1+a+f|0,this.h2+u+d|0,this.h3+l+s|0,this.h4+r+i|0,this.h0+o+c|0)}roundClean(){wt(go)}destroy(){this.destroyed=!0,wt(this.buffer),this.set(0,0,0,0,0)}}const nu=vi(()=>new Ov);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function es(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Iv(e,...t){if(!es(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Gh(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 Yh(e){if(typeof e!="function")throw new Error("function expected");return!0}function gr(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function fs(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function ti(e){if(!Array.isArray(e))throw new Error("array expected")}function ni(e,t){if(!Gh(!0,t))throw new Error(`${e}: array of strings expected`)}function ru(e,t){if(!Gh(!1,t))throw new Error(`${e}: array of numbers expected`)}function Js(...e){const t=o=>o,n=(o,i)=>a=>o(i(a)),r=e.map(o=>o.encode).reduceRight(n,t),s=e.map(o=>o.decode).reduce(n,t);return{encode:r,decode:s}}function $i(e){const t=typeof e=="string"?e.split(""):e,n=t.length;ni("alphabet",t);const r=new Map(t.map((s,o)=>[s,o]));return{encode:s=>(ti(s),s.map(o=>{if(!Number.isSafeInteger(o)||o<0||o>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${e}`);return t[o]})),decode:s=>(ti(s),s.map(o=>{gr("alphabet.decode",o);const i=r.get(o);if(i===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${e}`);return i}))}}function Ei(e=""){return gr("join",e),{encode:t=>(ni("join.decode",t),t.join(e)),decode:t=>(gr("join.decode",t),t.split(e))}}function Xh(e,t="="){return fs(e),gr("padding",t),{encode(n){for(ni("padding.encode",n);n.length*e%8;)n.push(t);return n},decode(n){ni("padding.decode",n);let r=n.length;if(r*e%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===t;r--)if((r-1)*e%8===0)throw new Error("padding: invalid, string has too much padding");return n.slice(0,r)}}}function qa(e,t,n){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: invalid to=${n}, base cannot be less than 2`);if(ti(e),!e.length)return[];let r=0;const s=[],o=Array.from(e,a=>{if(fs(a),a<0||a>=t)throw new Error(`invalid integer: ${a}`);return a}),i=o.length;for(;;){let a=0,c=!0;for(let u=r;ut===0?e:Jh(t,e%t),ri=(e,t)=>e+(t-Jh(e,t)),_o=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function si(e,t,n,r){if(ti(e),t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(ri(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${ri(t,n)}`);let s=0,o=0;const i=_o[t],a=_o[n]-1,c=[];for(const u of e){if(fs(u),u>=i)throw new Error(`convertRadix2: invalid data word=${u} from=${t}`);if(s=s<32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${t}`);for(o+=t;o>=n;o-=n)c.push((s>>o-n&a)>>>0);const f=_o[o];if(f===void 0)throw new Error("invalid carry");s&=f-1}if(s=s<=t)throw new Error("Excess padding");if(!r&&s>0)throw new Error(`Non-zero padding: ${s}`);return r&&o>0&&c.push(s>>>0),c}function Qh(e){fs(e);const t=2**8;return{encode:n=>{if(!es(n))throw new Error("radix.encode input should be Uint8Array");return qa(Array.from(n),t,e)},decode:n=>(ru("radix.decode",n),Uint8Array.from(qa(n,e,t)))}}function su(e,t=!1){if(fs(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(ri(8,e)>32||ri(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!es(n))throw new Error("radix2.encode input should be Uint8Array");return si(Array.from(n),8,e,!t)},decode:n=>(ru("radix2.decode",n),Uint8Array.from(si(n,e,8,t)))}}function El(e){return Yh(e),function(...t){try{return e.apply(null,t)}catch{}}}function ep(e,t){return fs(e),Yh(t),{encode(n){if(!es(n))throw new Error("checksum.encode: input should be Uint8Array");const r=t(n).slice(0,e),s=new Uint8Array(n.length+e);return s.set(n),s.set(r,n.length),s},decode(n){if(!es(n))throw new Error("checksum.decode: input should be Uint8Array");const r=n.slice(0,-e),s=n.slice(-e),o=t(r).slice(0,e);for(let i=0;i{gr("base64",e);const n=/^[A-Za-z0-9=+/]+$/,r="base64";if(e.length>0&&!n.test(e))throw new Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},yt=Cv?{encode(e){return Iv(e),e.toBase64()},decode(e){return Pv(e)}}:Js(su(6),$i("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Xh(6),Ei("")),Uv=e=>Js(Qh(58),$i(e),Ei("")),Nv=Uv("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),tp=e=>Js(ep(4,t=>e(e(t))),Nv),za=Js($i("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Ei("")),Sl=[996825010,642813549,513874426,1027748829,705979059];function ms(e){const t=e>>25;let n=(e&33554431)<<5;for(let r=0;r>r&1)===1&&(n^=Sl[r]);return n}function _l(e,t,n=1){const r=e.length;let s=1;for(let o=0;o126)throw new Error(`Invalid prefix (${e})`);s=ms(s)^i>>5}s=ms(s);for(let o=0;op)throw new TypeError(`Length ${h} exceeds limit ${p}`);const y=l.toLowerCase(),m=_l(y,d,t);return`${y}1${za.encode(d)}${m}`}function a(l,d=90){gr("bech32.decode input",l);const p=l.length;if(p<8||d!==!1&&p>d)throw new TypeError(`invalid string length: ${p} (${l}). Expected (8..${d})`);const g=l.toLowerCase();if(l!==g&&l!==l.toUpperCase())throw new Error("String must be lowercase or uppercase");const h=g.lastIndexOf("1");if(h===0||h===-1)throw new Error('Letter "1" must be present between prefix and data only');const y=g.slice(0,h),m=g.slice(h+1);if(m.length<6)throw new Error("Data must be at least 6 characters long");const x=za.decode(m).slice(0,-6),w=_l(y,x,t);if(!m.endsWith(w))throw new Error(`Invalid checksum in ${l}: expected "${w}"`);return{prefix:y,words:x}}const c=El(a);function u(l){const{prefix:d,words:p}=a(l,!1);return{prefix:d,words:p,bytes:r(p)}}function f(l,d){return i(l,s(d))}return{encode:i,decode:a,encodeFromBytes:f,decodeToBytes:u,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:o,toWords:s}}const mr=np("bech32"),Lv=np("bech32m");/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */const yo=Oe.ProjectivePoint,oa=tp(Ae);function Al(e){Ve(e);const t=e.length===0?"0":Ie(e);return BigInt("0x"+t)}function Hv(e){if(typeof e!="bigint")throw new Error("bigint expected");return bt(e.toString(16).padStart(64,"0"))}const Rv=Ke("Bitcoin seed"),ia={private:76066276,public:76067358},aa=2147483648,jv=e=>nu(Ae(e)),Kv=e=>ir(e).getUint32(0,!1),wo=e=>{if(!Number.isSafeInteger(e)||e<0||e>2**32-1)throw new Error("invalid number, should be from 0 to 2**32-1, got "+e);const t=new Uint8Array(4);return ir(t).setUint32(0,e,!1),t};class Xn{get fingerprint(){if(!this.pubHash)throw new Error("No publicKey set!");return Kv(this.pubHash)}get identifier(){return this.pubHash}get pubKeyHash(){return this.pubHash}get privateKey(){return this.privKeyBytes||null}get publicKey(){return this.pubKey||null}get privateExtendedKey(){const t=this.privateKey;if(!t)throw new Error("No private key");return oa.encode(this.serialize(this.versions.private,ue(new Uint8Array([0]),t)))}get publicExtendedKey(){if(!this.pubKey)throw new Error("No public key");return oa.encode(this.serialize(this.versions.public,this.pubKey))}static fromMasterSeed(t,n=ia){if(Ve(t),8*t.length<128||8*t.length>512)throw new Error("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got "+t.length);const r=Rn(js,Rv,t);return new Xn({versions:n,chainCode:r.slice(32),privateKey:r.slice(0,32)})}static fromExtendedKey(t,n=ia){const r=oa.decode(t),s=ir(r),o=s.getUint32(0,!1),i={versions:n,depth:r[4],parentFingerprint:s.getUint32(5,!1),index:s.getUint32(9,!1),chainCode:r.slice(13,45)},a=r.slice(45),c=a[0]===0;if(o!==n[c?"private":"public"])throw new Error("Version mismatch");return c?new Xn({...i,privateKey:a.slice(1)}):new Xn({...i,publicKey:a})}static fromJSON(t){return Xn.fromExtendedKey(t.xpriv)}constructor(t){if(this.depth=0,this.index=0,this.chainCode=null,this.parentFingerprint=0,!t||typeof t!="object")throw new Error("HDKey.constructor must not be called directly");if(this.versions=t.versions||ia,this.depth=t.depth||0,this.chainCode=t.chainCode||null,this.index=t.index||0,this.parentFingerprint=t.parentFingerprint||0,!this.depth&&(this.parentFingerprint||this.index))throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");if(t.publicKey&&t.privateKey)throw new Error("HDKey: publicKey and privateKey at same time.");if(t.privateKey){if(!Oe.utils.isValidPrivateKey(t.privateKey))throw new Error("Invalid private key");this.privKey=typeof t.privateKey=="bigint"?t.privateKey:Al(t.privateKey),this.privKeyBytes=Hv(this.privKey),this.pubKey=Oe.getPublicKey(t.privateKey,!0)}else if(t.publicKey)this.pubKey=yo.fromHex(t.publicKey).toRawBytes(!0);else throw new Error("HDKey: no public or private key provided");this.pubHash=jv(this.pubKey)}derive(t){if(!/^[mM]'?/.test(t))throw new Error('Path must start with "m" or "M"');if(/^[mM]'?$/.test(t))return this;const n=t.replace(/^[mM]'?\//,"").split("/");let r=this;for(const s of n){const o=/^(\d+)('?)$/.exec(s),i=o&&o[1];if(!o||o.length!==3||typeof i!="string")throw new Error("invalid child index: "+s);let a=+i;if(!Number.isSafeInteger(a)||a>=aa)throw new Error("Invalid index");o[2]==="'"&&(a+=aa),r=r.deriveChild(a)}return r}deriveChild(t){if(!this.pubKey||!this.chainCode)throw new Error("No publicKey or chainCode set");let n=wo(t);if(t>=aa){const a=this.privateKey;if(!a)throw new Error("Could not derive hardened child key");n=ue(new Uint8Array([0]),a,n)}else n=ue(this.pubKey,n);const r=Rn(js,this.chainCode,n),s=Al(r.slice(0,32)),o=r.slice(32);if(!Oe.utils.isValidPrivateKey(s))throw new Error("Tweak bigger than curve order");const i={versions:this.versions,chainCode:o,depth:this.depth+1,parentFingerprint:this.fingerprint,index:t};try{if(this.privateKey){const a=Te(this.privKey+s,Oe.CURVE.n);if(!Oe.utils.isValidPrivateKey(a))throw new Error("The tweak was out of range or the resulted private key is invalid");i.privateKey=a}else{const a=yo.fromHex(this.pubKey).add(yo.fromPrivateKey(s));if(a.equals(yo.ZERO))throw new Error("The tweak was equal to negative P, which made the result key invalid");i.publicKey=a.toRawBytes(!0)}return new Xn(i)}catch{return this.deriveChild(t+1)}}sign(t){if(!this.privateKey)throw new Error("No privateKey set!");return Ve(t,32),Oe.sign(t,this.privKey).toCompactRawBytes()}verify(t,n){if(Ve(t,32),Ve(n,64),!this.publicKey)throw new Error("No publicKey set!");let r;try{r=Oe.Signature.fromCompact(n)}catch{return!1}return Oe.verify(r,t,this.publicKey)}wipePrivateData(){return this.privKey=void 0,this.privKeyBytes&&(this.privKeyBytes.fill(0),this.privKeyBytes=void 0),this}toJSON(){return{xpriv:this.privateExtendedKey,xpub:this.publicExtendedKey}}serialize(t,n){if(!this.chainCode)throw new Error("No chainCode set");return Ve(n,33),ue(wo(t),new Uint8Array([this.depth]),wo(this.parentFingerprint),wo(this.index),this.chainCode,n)}}function Dv(e,t,n,r){Ys(e);const s=v2({dkLen:32,asyncTick:10},r),{c:o,dkLen:i,asyncTick:a}=s;if(jt(o),jt(i),jt(a),o<1)throw new Error("iterations (c) should be >= 1");const c=al(t),u=al(n),f=new Uint8Array(i),l=Rn.create(e,c),d=l._cloneInto().update(u);return{c:o,dkLen:i,asyncTick:a,DK:f,PRF:l,PRFSalt:d}}function Mv(e,t,n,r,s){return e.destroy(),t.destroy(),r&&r.destroy(),wt(s),n}function Zv(e,t,n,r){const{c:s,dkLen:o,DK:i,PRF:a,PRFSalt:c}=Dv(e,t,n,r);let u;const f=new Uint8Array(4),l=ir(f),d=new Uint8Array(a.outputLen);for(let p=1,g=0;ge[0]==="あいこくしん";function rp(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function sp(e){const t=rp(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}function op(e){Ve(e,16,20,24,28,32)}function qv(e,t=128){if(jt(t),t%32!==0||t>256)throw new TypeError("Invalid entropy");return ap(kr(t/8),e)}const zv=e=>{const t=8-e.length/4;return new Uint8Array([Ae(e)[0]>>t<{if(typeof t!="string")throw new Error("wordlist: non-string element: "+t)}),mo.chain(mo.checksum(1,zv),mo.radix2(11,!0),mo.alphabet(e))}function Fv(e,t){const{words:n}=sp(e),r=ip(t).decode(n);return op(r),r}function ap(e,t){return op(e),ip(t).encode(e).join(Vv(t)?" ":" ")}function Wv(e,t){try{Fv(e,t)}catch{return!1}return!0}const Gv=e=>rp("mnemonic"+e);function Yv(e,t=""){return Zv(js,sp(e).nfkd,Gv(t),{c:2048,dkLen:64})}const ou=`abandon -ability -able -about -above -absent -absorb -abstract -absurd -abuse -access -accident -account -accuse -achieve -acid -acoustic -acquire -across -act -action -actor -actress -actual -adapt -add -addict -address -adjust -admit -adult -advance -advice -aerobic -affair -afford -afraid -again -age -agent -agree -ahead -aim -air -airport -aisle -alarm -album -alcohol -alert -alien -all -alley -allow -almost -alone -alpha -already -also -alter -always -amateur -amazing -among -amount -amused -analyst -anchor -ancient -anger -angle -angry -animal -ankle -announce -annual -another -answer -antenna -antique -anxiety -any -apart -apology -appear -apple -approve -april -arch -arctic -area -arena -argue -arm -armed -armor -army -around -arrange -arrest -arrive -arrow -art -artefact -artist -artwork -ask -aspect -assault -asset -assist -assume -asthma -athlete -atom -attack -attend -attitude -attract -auction -audit -august -aunt -author -auto -autumn -average -avocado -avoid -awake -aware -away -awesome -awful -awkward -axis -baby -bachelor -bacon -badge -bag -balance -balcony -ball -bamboo -banana -banner -bar -barely -bargain -barrel -base -basic -basket -battle -beach -bean -beauty -because -become -beef -before -begin -behave -behind -believe -below -belt -bench -benefit -best -betray -better -between -beyond -bicycle -bid -bike -bind -biology -bird -birth -bitter -black -blade -blame -blanket -blast -bleak -bless -blind -blood -blossom -blouse -blue -blur -blush -board -boat -body -boil -bomb -bone -bonus -book -boost -border -boring -borrow -boss -bottom -bounce -box -boy -bracket -brain -brand -brass -brave -bread -breeze -brick -bridge -brief -bright -bring -brisk -broccoli -broken -bronze -broom -brother -brown -brush -bubble -buddy -budget -buffalo -build -bulb -bulk -bullet -bundle -bunker -burden -burger -burst -bus -business -busy -butter -buyer -buzz -cabbage -cabin -cable -cactus -cage -cake -call -calm -camera -camp -can -canal -cancel -candy -cannon -canoe -canvas -canyon -capable -capital -captain -car -carbon -card -cargo -carpet -carry -cart -case -cash -casino -castle -casual -cat -catalog -catch -category -cattle -caught -cause -caution -cave -ceiling -celery -cement -census -century -cereal -certain -chair -chalk -champion -change -chaos -chapter -charge -chase -chat -cheap -check -cheese -chef -cherry -chest -chicken -chief -child -chimney -choice -choose -chronic -chuckle -chunk -churn -cigar -cinnamon -circle -citizen -city -civil -claim -clap -clarify -claw -clay -clean -clerk -clever -click -client -cliff -climb -clinic -clip -clock -clog -close -cloth -cloud -clown -club -clump -cluster -clutch -coach -coast -coconut -code -coffee -coil -coin -collect -color -column -combine -come -comfort -comic -common -company -concert -conduct -confirm -congress -connect -consider -control -convince -cook -cool -copper -copy -coral -core -corn -correct -cost -cotton -couch -country -couple -course -cousin -cover -coyote -crack -cradle -craft -cram -crane -crash -crater -crawl -crazy -cream -credit -creek -crew -cricket -crime -crisp -critic -crop -cross -crouch -crowd -crucial -cruel -cruise -crumble -crunch -crush -cry -crystal -cube -culture -cup -cupboard -curious -current -curtain -curve -cushion -custom -cute -cycle -dad -damage -damp -dance -danger -daring -dash -daughter -dawn -day -deal -debate -debris -decade -december -decide -decline -decorate -decrease -deer -defense -define -defy -degree -delay -deliver -demand -demise -denial -dentist -deny -depart -depend -deposit -depth -deputy -derive -describe -desert -design -desk -despair -destroy -detail -detect -develop -device -devote -diagram -dial -diamond -diary -dice -diesel -diet -differ -digital -dignity -dilemma -dinner -dinosaur -direct -dirt -disagree -discover -disease -dish -dismiss -disorder -display -distance -divert -divide -divorce -dizzy -doctor -document -dog -doll -dolphin -domain -donate -donkey -donor -door -dose -double -dove -draft -dragon -drama -drastic -draw -dream -dress -drift -drill -drink -drip -drive -drop -drum -dry -duck -dumb -dune -during -dust -dutch -duty -dwarf -dynamic -eager -eagle -early -earn -earth -easily -east -easy -echo -ecology -economy -edge -edit -educate -effort -egg -eight -either -elbow -elder -electric -elegant -element -elephant -elevator -elite -else -embark -embody -embrace -emerge -emotion -employ -empower -empty -enable -enact -end -endless -endorse -enemy -energy -enforce -engage -engine -enhance -enjoy -enlist -enough -enrich -enroll -ensure -enter -entire -entry -envelope -episode -equal -equip -era -erase -erode -erosion -error -erupt -escape -essay -essence -estate -eternal -ethics -evidence -evil -evoke -evolve -exact -example -excess -exchange -excite -exclude -excuse -execute -exercise -exhaust -exhibit -exile -exist -exit -exotic -expand -expect -expire -explain -expose -express -extend -extra -eye -eyebrow -fabric -face -faculty -fade -faint -faith -fall -false -fame -family -famous -fan -fancy -fantasy -farm -fashion -fat -fatal -father -fatigue -fault -favorite -feature -february -federal -fee -feed -feel -female -fence -festival -fetch -fever -few -fiber -fiction -field -figure -file -film -filter -final -find -fine -finger -finish -fire -firm -first -fiscal -fish -fit -fitness -fix -flag -flame -flash -flat -flavor -flee -flight -flip -float -flock -floor -flower -fluid -flush -fly -foam -focus -fog -foil -fold -follow -food -foot -force -forest -forget -fork -fortune -forum -forward -fossil -foster -found -fox -fragile -frame -frequent -fresh -friend -fringe -frog -front -frost -frown -frozen -fruit -fuel -fun -funny -furnace -fury -future -gadget -gain -galaxy -gallery -game -gap -garage -garbage -garden -garlic -garment -gas -gasp -gate -gather -gauge -gaze -general -genius -genre -gentle -genuine -gesture -ghost -giant -gift -giggle -ginger -giraffe -girl -give -glad -glance -glare -glass -glide -glimpse -globe -gloom -glory -glove -glow -glue -goat -goddess -gold -good -goose -gorilla -gospel -gossip -govern -gown -grab -grace -grain -grant -grape -grass -gravity -great -green -grid -grief -grit -grocery -group -grow -grunt -guard -guess -guide -guilt -guitar -gun -gym -habit -hair -half -hammer -hamster -hand -happy -harbor -hard -harsh -harvest -hat -have -hawk -hazard -head -health -heart -heavy -hedgehog -height -hello -helmet -help -hen -hero -hidden -high -hill -hint -hip -hire -history -hobby -hockey -hold -hole -holiday -hollow -home -honey -hood -hope -horn -horror -horse -hospital -host -hotel -hour -hover -hub -huge -human -humble -humor -hundred -hungry -hunt -hurdle -hurry -hurt -husband -hybrid -ice -icon -idea -identify -idle -ignore -ill -illegal -illness -image -imitate -immense -immune -impact -impose -improve -impulse -inch -include -income -increase -index -indicate -indoor -industry -infant -inflict -inform -inhale -inherit -initial -inject -injury -inmate -inner -innocent -input -inquiry -insane -insect -inside -inspire -install -intact -interest -into -invest -invite -involve -iron -island -isolate -issue -item -ivory -jacket -jaguar -jar -jazz -jealous -jeans -jelly -jewel -job -join -joke -journey -joy -judge -juice -jump -jungle -junior -junk -just -kangaroo -keen -keep -ketchup -key -kick -kid -kidney -kind -kingdom -kiss -kit -kitchen -kite -kitten -kiwi -knee -knife -knock -know -lab -label -labor -ladder -lady -lake -lamp -language -laptop -large -later -latin -laugh -laundry -lava -law -lawn -lawsuit -layer -lazy -leader -leaf -learn -leave -lecture -left -leg -legal -legend -leisure -lemon -lend -length -lens -leopard -lesson -letter -level -liar -liberty -library -license -life -lift -light -like -limb -limit -link -lion -liquid -list -little -live -lizard -load -loan -lobster -local -lock -logic -lonely -long -loop -lottery -loud -lounge -love -loyal -lucky -luggage -lumber -lunar -lunch -luxury -lyrics -machine -mad -magic -magnet -maid -mail -main -major -make -mammal -man -manage -mandate -mango -mansion -manual -maple -marble -march -margin -marine -market -marriage -mask -mass -master -match -material -math -matrix -matter -maximum -maze -meadow -mean -measure -meat -mechanic -medal -media -melody -melt -member -memory -mention -menu -mercy -merge -merit -merry -mesh -message -metal -method -middle -midnight -milk -million -mimic -mind -minimum -minor -minute -miracle -mirror -misery -miss -mistake -mix -mixed -mixture -mobile -model -modify -mom -moment -monitor -monkey -monster -month -moon -moral -more -morning -mosquito -mother -motion -motor -mountain -mouse -move -movie -much -muffin -mule -multiply -muscle -museum -mushroom -music -must -mutual -myself -mystery -myth -naive -name -napkin -narrow -nasty -nation -nature -near -neck -need -negative -neglect -neither -nephew -nerve -nest -net -network -neutral -never -news -next -nice -night -noble -noise -nominee -noodle -normal -north -nose -notable -note -nothing -notice -novel -now -nuclear -number -nurse -nut -oak -obey -object -oblige -obscure -observe -obtain -obvious -occur -ocean -october -odor -off -offer -office -often -oil -okay -old -olive -olympic -omit -once -one -onion -online -only -open -opera -opinion -oppose -option -orange -orbit -orchard -order -ordinary -organ -orient -original -orphan -ostrich -other -outdoor -outer -output -outside -oval -oven -over -own -owner -oxygen -oyster -ozone -pact -paddle -page -pair -palace -palm -panda -panel -panic -panther -paper -parade -parent -park -parrot -party -pass -patch -path -patient -patrol -pattern -pause -pave -payment -peace -peanut -pear -peasant -pelican -pen -penalty -pencil -people -pepper -perfect -permit -person -pet -phone -photo -phrase -physical -piano -picnic -picture -piece -pig -pigeon -pill -pilot -pink -pioneer -pipe -pistol -pitch -pizza -place -planet -plastic -plate -play -please -pledge -pluck -plug -plunge -poem -poet -point -polar -pole -police -pond -pony -pool -popular -portion -position -possible -post -potato -pottery -poverty -powder -power -practice -praise -predict -prefer -prepare -present -pretty -prevent -price -pride -primary -print -priority -prison -private -prize -problem -process -produce -profit -program -project -promote -proof -property -prosper -protect -proud -provide -public -pudding -pull -pulp -pulse -pumpkin -punch -pupil -puppy -purchase -purity -purpose -purse -push -put -puzzle -pyramid -quality -quantum -quarter -question -quick -quit -quiz -quote -rabbit -raccoon -race -rack -radar -radio -rail -rain -raise -rally -ramp -ranch -random -range -rapid -rare -rate -rather -raven -raw -razor -ready -real -reason -rebel -rebuild -recall -receive -recipe -record -recycle -reduce -reflect -reform -refuse -region -regret -regular -reject -relax -release -relief -rely -remain -remember -remind -remove -render -renew -rent -reopen -repair -repeat -replace -report -require -rescue -resemble -resist -resource -response -result -retire -retreat -return -reunion -reveal -review -reward -rhythm -rib -ribbon -rice -rich -ride -ridge -rifle -right -rigid -ring -riot -ripple -risk -ritual -rival -river -road -roast -robot -robust -rocket -romance -roof -rookie -room -rose -rotate -rough -round -route -royal -rubber -rude -rug -rule -run -runway -rural -sad -saddle -sadness -safe -sail -salad -salmon -salon -salt -salute -same -sample -sand -satisfy -satoshi -sauce -sausage -save -say -scale -scan -scare -scatter -scene -scheme -school -science -scissors -scorpion -scout -scrap -screen -script -scrub -sea -search -season -seat -second -secret -section -security -seed -seek -segment -select -sell -seminar -senior -sense -sentence -series -service -session -settle -setup -seven -shadow -shaft -shallow -share -shed -shell -sheriff -shield -shift -shine -ship -shiver -shock -shoe -shoot -shop -short -shoulder -shove -shrimp -shrug -shuffle -shy -sibling -sick -side -siege -sight -sign -silent -silk -silly -silver -similar -simple -since -sing -siren -sister -situate -six -size -skate -sketch -ski -skill -skin -skirt -skull -slab -slam -sleep -slender -slice -slide -slight -slim -slogan -slot -slow -slush -small -smart -smile -smoke -smooth -snack -snake -snap -sniff -snow -soap -soccer -social -sock -soda -soft -solar -soldier -solid -solution -solve -someone -song -soon -sorry -sort -soul -sound -soup -source -south -space -spare -spatial -spawn -speak -special -speed -spell -spend -sphere -spice -spider -spike -spin -spirit -split -spoil -sponsor -spoon -sport -spot -spray -spread -spring -spy -square -squeeze -squirrel -stable -stadium -staff -stage -stairs -stamp -stand -start -state -stay -steak -steel -stem -step -stereo -stick -still -sting -stock -stomach -stone -stool -story -stove -strategy -street -strike -strong -struggle -student -stuff -stumble -style -subject -submit -subway -success -such -sudden -suffer -sugar -suggest -suit -summer -sun -sunny -sunset -super -supply -supreme -sure -surface -surge -surprise -surround -survey -suspect -sustain -swallow -swamp -swap -swarm -swear -sweet -swift -swim -swing -switch -sword -symbol -symptom -syrup -system -table -tackle -tag -tail -talent -talk -tank -tape -target -task -taste -tattoo -taxi -teach -team -tell -ten -tenant -tennis -tent -term -test -text -thank -that -theme -then -theory -there -they -thing -this -thought -three -thrive -throw -thumb -thunder -ticket -tide -tiger -tilt -timber -time -tiny -tip -tired -tissue -title -toast -tobacco -today -toddler -toe -together -toilet -token -tomato -tomorrow -tone -tongue -tonight -tool -tooth -top -topic -topple -torch -tornado -tortoise -toss -total -tourist -toward -tower -town -toy -track -trade -traffic -tragic -train -transfer -trap -trash -travel -tray -treat -tree -trend -trial -tribe -trick -trigger -trim -trip -trophy -trouble -truck -true -truly -trumpet -trust -truth -try -tube -tuition -tumble -tuna -tunnel -turkey -turn -turtle -twelve -twenty -twice -twin -twist -two -type -typical -ugly -umbrella -unable -unaware -uncle -uncover -under -undo -unfair -unfold -unhappy -uniform -unique -unit -universe -unknown -unlock -until -unusual -unveil -update -upgrade -uphold -upon -upper -upset -urban -urge -usage -use -used -useful -useless -usual -utility -vacant -vacuum -vague -valid -valley -valve -van -vanish -vapor -various -vast -vault -vehicle -velvet -vendor -venture -venue -verb -verify -version -very -vessel -veteran -viable -vibrant -vicious -victory -video -view -village -vintage -violin -virtual -virus -visa -visit -visual -vital -vivid -vocal -voice -void -volcano -volume -vote -voyage -wage -wagon -wait -walk -wall -walnut -want -warfare -warm -warrior -wash -wasp -waste -water -wave -way -wealth -weapon -wear -weasel -weather -web -wedding -weekend -weird -welcome -west -wet -whale -what -wheat -wheel -when -where -whip -whisper -wide -width -wife -wild -will -win -window -wine -wing -wink -winner -winter -wire -wisdom -wise -wish -witness -wolf -woman -wonder -wood -wool -word -work -world -worry -worth -wrap -wreck -wrestle -wrist -write -wrong -yard -year -yellow -you -young -youth -zebra -zero -zone -zoo`.split(` -`),rt={orgSeed:e=>`m/83696968'/39'/0'/24'/${e}'`,wallet:(e,t=1)=>`m/86'/${t}'/${e}'/0/0`,segwit:(e,t=1)=>`m/84'/${t}'/${e}'/0/0`,nostr:e=>`m/44'/1237'/${e}'/0/0`,ethereum:e=>`m/44'/60'/${e}'/0/0`},Xv=2**31-1,ca=new Map,ua=new Map,Bl=()=>qv(ou,256);function cp(e,t=0){if(typeof e!="string"||!Wv(e,ou)||t&&e.split(" ").length!==t)throw new Error("Invalid lab mnemonic.");return e}function qn(e,t){if(!Number.isSafeInteger(e)||e<0||e>Xv)throw new Error(`Invalid ${t}.`);return e}const la=new Map;function iu(e){return la.has(e)||la.set(e,Yv(cp(e))),la.get(e)}function zn(e){return ca.has(e)||ca.set(e,Xn.fromMasterSeed(iu(e))),ca.get(e)}function Jv(e,t){const n=e.derive(t).privateKey;if(!n)throw new Error("BIP-85 path produced no private key.");return Rn(js,Ke("bip-entropy-from-k"),n)}function Qv(e,t){const n=`${e}|${qn(t,"child index")}`;return ua.has(n)||ua.set(n,ap(Jv(zn(e),rt.orgSeed(t)).slice(0,32),ou)),ua.get(n)}function Fa(e,t=0,n=1){return Ie(zn(e).derive(rt.wallet(qn(t,"account"),n)).privateKey)}function au(e,t=0,n=1){return Ie(zn(e).derive(rt.segwit(qn(t,"account"),n)).privateKey)}function up(e,t=0,n=1){return Ie(zn(e).derive(rt.segwit(qn(t,"account"),n)).publicKey)}function Si(e,t=0){return Ie(zn(e).derive(rt.nostr(qn(t,"account"))).privateKey)}function lp(e){const t=e.toLowerCase(),n=Ie(tu(Ke(t)));return`0x${[...t].map((r,s)=>parseInt(n[s],16)>=8?r.toUpperCase():r).join("")}`}const fp=e=>lp(Ie(tu(Oe.ProjectivePoint.fromHex(e).toRawBytes(!1).slice(1)).slice(-20)));function dp(e,t=0){return Ie(zn(e).derive(rt.ethereum(qn(t,"account"))).privateKey)}const fa=new Map;function ek(e,t=0){const n=`${e}|${t}`;return fa.has(n)||fa.set(n,fp(zn(e).derive(rt.ethereum(qn(t,"account"))).publicKey)),fa.get(n)}function tk(e,t=0){const n=jn.getPublicKey(zn(e).derive(rt.nostr(qn(t,"account"))).privateKey);return{pubkey:Ie(n),npub:mr.encode("npub",mr.toWords(n))}}const It=["taproot","segwit","nostr","ethereum"],_i=(e,t)=>["lineage/v0 keyring",`node: ${e}`,...It.map(n=>`${n}: ${t[n]}`)].join(` -`),nk=["bc","tb","bcrt"],hp=new Uint8Array(32),ct=e=>{const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),t},Ds=e=>ue(e.length<253?Uint8Array.of(e.length):Uint8Array.of(253,e.length&255,e.length>>8),e),vs=e=>Ae(Ae(e)),pp=(e,...t)=>{const n=Ae(Ke(e));return Ae(ue(n,n,...t))},rk=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]);function Ms(e){if(typeof e!="string"||e!==e.toLowerCase())return null;for(const[t,n]of[[mr,0],[Lv,1]])try{const{prefix:r,words:s}=t.decode(e,90);if(s[0]===n&&nk.includes(r))return{network:r,version:n,program:Uint8Array.from(t.fromWords(s.slice(1)))}}catch{}return null}const cu=e=>(e==null?void 0:e.version)===1&&e.program.length===32,uu=e=>(e==null?void 0:e.version)===0&&e.program.length===20,gp=({version:e,program:t})=>ue(Uint8Array.of(e?80+e:0,t.length),t),sk=e=>pp("BIP0322-signed-message",Ke(e)),oi=new Uint8Array(8),Tl=ue(oi,Ds(Uint8Array.of(106)));function ok(e,t){const n=gp(e),r=ue(Uint8Array.of(0,32),sk(t));return vs(ue(ct(0),Uint8Array.of(1),new Uint8Array(32),ct(4294967295),Ds(r),ct(0),Uint8Array.of(1),oi,Ds(n),ct(0)))}function ii(e,t,n=0){const r=gp(e),s=ue(ok(e,t),ct(0));if(e.version===0){const o=ue(Uint8Array.of(25,118,169,20),e.program,Uint8Array.of(136,172));return vs(ue(ct(0),vs(s),vs(ct(0)),s,o,oi,ct(0),vs(Tl),ct(0),ct(1)))}return pp("TapSighash",Uint8Array.of(0,n),ct(0),ct(0),Ae(s),Ae(oi),Ae(Ds(r)),Ae(ct(0)),Ae(Tl),Uint8Array.of(0),ct(0))}const Ol=e=>yt.encode(ue(Uint8Array.of(e.length),...e.map(Ds)));function ik(e){try{const t=yt.decode(e);let n=0;const r=()=>{if(n>=t.length)throw new Error("short");const o=t[n++];if(o<253)return o;if(o>253||n+2>t.length)throw new Error("size");return n+=2,t[n-2]|t[n-1]<<8},s=Array.from({length:r()},()=>{const o=r();if(n+o>t.length)throw new Error("short");return n+=o,t.slice(n-o,n)});return n===t.length?s:null}catch{return null}}function Il(e,t,n){const r=Ms(e);if(cu(r))return Ol([jn.sign(ii(r,t),n,hp)]);if(!uu(r))throw new Error("BIP-322 here signs for Taproot and P2WPKH addresses only.");const s=Oe.sign(ii(r,t),n).toDERRawBytes();return Ol([ue(s,Uint8Array.of(1)),Oe.getPublicKey(n,!0)])}function Cl(e,t,n){const r=Ms(e),s=typeof n=="string"?ik(n):null;if(!r||!s)return!1;try{if(cu(r)){const[o]=s;return s.length!==1||!(o.length===64||o.length===65&&o[64]===1)?!1:jn.verify(o.slice(0,64),ii(r,t,o.length===65?1:0),r.program)}if(uu(r)){const[o,i]=s;return s.length!==2||i.length!==33||o.at(-1)!==1||!rk(nu(Ae(i)),r.program)?!1:Oe.verify(Oe.Signature.fromDER(o.slice(0,-1)),ii(r,t),i)}}catch{}return!1}const mp=e=>{const t=Ke(e);return tu(ue(Ke(`Ethereum Signed Message: -${t.length}`),t))},yp=e=>typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e)&&lp(e.slice(2))===e;function ak(e,t){const n=Oe.sign(mp(e),t);return`0x${Ie(n.toCompactRawBytes())}${(27+n.recovery).toString(16)}`}function ck(e,t,n){if(!yp(e)||typeof n!="string"||!/^0x[0-9a-f]{130}$/.test(n))return!1;try{const r=bt(n.slice(2)),s=r[64]-27;if(s!==0&&s!==1)return!1;const o=Oe.Signature.fromCompact(r.slice(0,64)).addRecoveryBit(s).recoverPublicKey(mp(t));return fp(o.toRawBytes(!1))===e}catch{return!1}}const wp=(e,t)=>Ae(Ke(JSON.stringify([0,e,0,1,[],t])));function lu(e){try{const{prefix:t,words:n}=mr.decode(e,90),r=mr.fromWords(n);return t==="npub"&&r.length===32&&e===e.toLowerCase()?Ie(Uint8Array.from(r)):null}catch{return null}}const uk=(e,t)=>Ie(jn.sign(wp(Ie(jn.getPublicKey(t)),e),t,hp));function lk(e,t,n){const r=lu(e);try{return!!r&&typeof n=="string"&&/^[0-9a-f]{128}$/.test(n)&&jn.verify(n,wp(r,t),r)}catch{return!1}}const fk={taproot:Il,segwit:Il,nostr:(e,t,n)=>uk(t,n),ethereum:(e,t,n)=>ak(t,n)},dk={taproot:Cl,segwit:Cl,nostr:lk,ethereum:ck};function bp(e){const t=Ms(e.taproot),n=Ms(e.segwit);return cu(t)?uu(n)?t.network!==n.network?"its Taproot and SegWit addresses must be on one network":lu(e.nostr)?yp(e.ethereum)?"":"ethereum must be an EIP-55 address":"nostr must be an npub":"segwit must be a P2WPKH address":"taproot must be a Taproot address"}function hk(e,t,n){const r=bp(t);if(r)throw new Error(`${r[0].toUpperCase()}${r.slice(1)}.`);const s=_i(e,t);return{...Object.fromEntries(It.map(o=>[o,t[o]])),proof:Object.fromEntries(It.map(o=>[o,fk[o](t[o],s,n[o])]))}}const ys=new Map;function pk(e,t){const n=t.proof&&typeof t.proof=="object"&&!Array.isArray(t.proof)?t.proof:{},r=JSON.stringify([e,...It.map(s=>[t[s]??null,n[s]??null])]);if(!ys.has(r)){ys.size>=1e3&&ys.clear();let s=bp(t);if(!s){const o=_i(e,t),i=It.find(a=>!dk[a](t[a],o,n[a]));i&&(s=`the ${i} key did not sign this keyring`)}ys.set(r,s)}return ys.get(r)}const Pl=e=>It.map(t=>`${t}:${t==="nostr"?lu(e[t]):t==="ethereum"?e[t].toLowerCase():Ie(Ms(e[t]).program)}`),Ai="lineage/v0",gk=["white","green","black"],Ul=["sole","llc","series-llc","series","corp"],mk={sole:"sole proprietor",llc:"LLC","series-llc":"series LLC",series:"series",corp:"corporation"},Nl=/^[A-Z]{2}(-[A-Z0-9]{1,3})?$/,yk=/^[0-9a-f]{64}$/,on=e=>e.kind==="agent"&&e.root!==e.id,bo="names are 1-40 lowercase letters, digits or hyphens (they become domains)",wk=/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/,ws=e=>typeof e=="string"&&wk.test(e),Nr=(e,t)=>typeof e=="string"?e.trim().slice(0,t):"";function Qs(e){return String(e??"").toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/,"")}const Sr=e=>e.events.filter(t=>t.protocol===Ai);function Zt(e,{upTo:t=1/0,pending:n=!1}={}){var p,g;const r=new Map,s=[],o=[],i=new Map,a=new Map,c=new Map,u=h=>h.status==="active",f=h=>_r(r,h),l=h=>{if(h.keyring&&!h.keyring.retired)for(const y of Pl(h.keyring.keys))a.delete(y)},d=(h,y,m,x)=>{h.keyring&&!h.keyring.retired&&(l(h),h.keyring.retired={cause:y,by:m,beat:x})};for(const h of e){const y=h.status==="confirmed";if(y?h.height>t:!n)continue;const m=h.metadata&&typeof h.metadata=="object"&&!Array.isArray(h.metadata)?h.metadata:{},x={id:h.id,op:typeof m.op=="string"?m.op.slice(0,20):"?",beat:y?h.height:null,pending:!y,meta:m,parent:h.parent??null,ok:!0,why:"",node:null,root:null,also:[]},w=x.parent?r.get(x.parent):null,P=x.beat??"cued",b=_=>{x.ok=!1,x.why=_},$=_=>w?u(w)?"":`the ${_} is ${w.status}`:`the ${_} is not in this lineage`;let T="",U=[];const O=(w==null?void 0:w.root)??null;switch(x.op){case"found":if(x.parent)b("a holding has no parent");else if(!ws(m.name))b(bo);else if(s.some(_=>u(_)&&_.name===m.name))b(`an active holding is already named ${m.name}`);else{const _=Ll(h,m.name,null,"holding");r.set(_.id,_),s.push(_),x.node=_.id}break;case"birth":{const _=m.kind==="agent"?"agent":"org";if(T=$("parent"))b(T);else if(on(w))b("agents give birth only once they graduate");else if(!ws(m.name))b(bo);else if(f(w).some(C=>u(C)&&C.name===m.name))b(`${w.name} already has an active ${m.name}`);else{const C=Ll(h,m.name,w,_);C.index=w.children.filter(k=>r.get(k).kind===_).length,w.children.push(C.id),r.set(C.id,C),x.node=C.id}break}case"award":{const _=r.get(m.to);(T=$("issuer"))?b(T):on(w)?b("agents award belts only once they graduate"):!_||_.id===w.id?b("the recipient must be another node in this lineage"):u(_)?!ws(m.skill)||!gk.includes(m.belt)?b("an award needs a skill name and a belt (white, green or black)"):(_.badges=_.badges.filter(C=>C.skill!==m.skill),_.badges.push({skill:m.skill,belt:m.belt,by:w.id,beat:P,id:h.id}),x.node=_.id):b(`the recipient is ${_.status}`);break}case"decide":(T=$("decider"))?b(T):Nr(m.title,140)?(w.decisions.push({title:Nr(m.title,140),why:Nr(m.why,400),beat:P,id:h.id}),x.node=w.id):b("a decision needs a title");break;case"make":(T=$("maker"))?b(T):ws(m.name)?w.made.some(_=>i.get(_).name===m.name)?b(`there is already a ${m.name} by ${w.name}`):(i.set(h.id,{id:h.id,name:m.name,note:Nr(m.note,280),maker:w.id,beat:P}),w.made.push(h.id),x.node=w.id):b(bo);break;case"graduate":{const _=r.get(m.of);if(T=$("parent"))b(T);else if(!_||_.parent!==w.id)b("only its parent can graduate a child");else if(!u(_))b(`the child is ${_.status}`);else if(_.edge==="adopted")b("already graduated");else if(_.joining)b(`${_.name} is joining ${r.get(_.joining.to).name}`);else{const C=_.root,k=v=>{v.root=_.id;for(const A of f(v))A.root===C&&k(A)};_.edge="adopted",_.graduated=P,_.rooted=h.id,x.node=_.id,x.rekeys=!0,k(_),s.push(_);const S=v=>{d(v,"graduate",_.id,P);for(const A of f(v))A.edge==="derived"&&S(A)};S(_)}break}case"close":if(!w)b(x.parent?"that node is not in this lineage":"a close spends the node it closes");else if(!u(w))b(`already ${w.status}`);else{const _=C=>{C.status="closed",C.closed=P,d(C,"close",w.id,P);for(const k of f(C))k.edge==="derived"&&u(k)&&(x.also.push(k.id),_(k))};_(w),x.node=w.id}break;case"charter":{const _=m.form==="series",C=_?r.get(m.of):w,k=w&&(w.kind==="holding"||w.kind==="agent");(T=$(_?"master":"node"))?b(T):Ul.includes(m.form)?!_&&m.of!==void 0&&m.of!==w.id?b("a node charters itself; only a series is chartered by its master"):_&&(!C||!xp(r,C,w))?b("a series must descend from its master"):_&&!u(C)?b(`the series is ${C.status}`):_&&C.kind!=="org"?b("only orgs become series"):_&&((p=w.charter)==null?void 0:p.form)!=="series-llc"?b(`${w.name} is not chartered as a series LLC`):_&&m.jurisdiction!==void 0?b("a series takes its master's jurisdiction"):m.form==="sole"&&!k?b("a sole proprietor is a person: a holding or an agent"):m.form!=="sole"&&!_&&on(w)?b("an agent graduates before it incorporates"):m.form!=="sole"&&!_&&!Nl.test(m.jurisdiction??"")||m.form==="sole"&&m.jurisdiction!==void 0&&!Nl.test(m.jurisdiction)?b("a jurisdiction is an ISO code such as US-WY"):m.provider!==void 0&&!ws(m.provider)?b(`a provider's name follows the name rule: ${bo}`):m.filing!==void 0&&!yk.test(m.filing)?b("a filing is the SHA-256 of the filed documents, in hex"):(C.charter={id:h.id,beat:P,form:m.form,jurisdiction:_?null:m.jurisdiction??null,legal:Nr(m.legal,120)||null,provider:m.provider??null,filing:m.filing??null,master:_?w.id:null},x.node=C.id):b(`a charter's form is ${Ul.join(", ")}`);break}case"keyring":{if(T=$("node"))b(T);else if(T=pk(w.id,m))b(T);else{const _=Object.fromEntries(It.map(S=>[S,m[S]])),C=Pl(_),k=C.findIndex(S=>a.has(S)&&a.get(S)!==w.id);if(k>=0)b(`its ${It[k]} key is already bound to ${r.get(a.get(C[k])).name}`);else{l(w),w.keyring={id:h.id,beat:P,keys:_,retired:null};for(const S of C)a.set(S,w.id);x.node=w.id}}break}case"join":case"adopt":{const _=x.op==="join",C=_?w:r.get(m.of),k=_?r.get(m.to)??null:w;if(T=$(_?"node":"parent"))b(T);else if(T=Vt(r,C,k))b(T);else{const S=`${k.id}>${C.id}`,v=_?c.get(S):((g=C.joining)==null?void 0:g.to)===k.id?C.joining:null;if(x.node=C.id,U=[C.root,k.root],!v&&_)C.joining={to:k.id,id:h.id,beat:P};else if(!v)c.set(S,{id:h.id});else{c.delete(S),C.joining=null;const A=C.root,N=H=>{H.root=k.root;for(const D of f(H))D.root===A&&N(D)};C.moves.push({from:C.parent,index:C.index,to:k.id,beat:P,join:_?h.id:v.id,adopt:_?v.id:h.id}),C.root===C.id&&s.splice(s.indexOf(C),1),C.kind==="holding"&&(C.kind="org"),C.index=k.children.filter(H=>r.get(H).kind===C.kind).length,C.parent=k.id,C.edge="derived",k.children.push(C.id),N(C);const K=H=>{d(H,"move",k.id,P);for(const D of f(H))D.edge==="derived"&&K(D)};K(C),x.rekeys=!0}}break}default:b("not a lineage/v0 op")}const L=x.node?r.get(x.node).root:null;x.root=O??L,x.roots=[...new Set([x.root,L,...U].filter(Boolean))],o.push(x)}return{nodes:r,roots:s,log:o,items:i,bound:a}}function Ll(e,t,n,r){return{id:e.id,name:t,kind:r,parent:(n==null?void 0:n.id)??null,root:n?n.root:e.id,edge:n?"derived":null,status:"active",index:null,born:e.status==="confirmed"?e.height:"cued",children:[],badges:[],decisions:[],made:[],keyring:null,charter:null,graduated:null,rooted:null,closed:null,joining:null,moves:[]}}function xp(e,t,n){for(let r=e.get(t.parent);r;r=e.get(r.parent))if(r.id===n.id)return!0;return!1}const _r=(e,t)=>[...new Set(t.children)].map(n=>e.get(n)).filter(n=>n.parent===t.id);function Vt(e,t,n){return t?t.kind==="agent"?"an agent changes hands only with the org it sits in":t.status!=="active"?`${t.name} is ${t.status}`:n===void 0?"":n?n.status!=="active"?`the new parent is ${n.status}`:on(n)?"agents adopt only once they graduate":n.id===t.id||xp(e,n,t)?`${t.name} cannot join itself or anything below it`:n.id===t.parent?`${t.name} is already ${n.name}'s`:_r(e,n).some(r=>r.status==="active"&&r.name===t.name)?`${n.name} already has an active ${t.name}`:"":"the new parent must be a node in this lineage":"that node is not in this lineage"}function Es(e,t){var s;const n=t==null?void 0:t.charter;if(!n)return null;if(t.status!=="active")return{ok:!1,why:`${t.name} is closed`};if(n.form==="sole"&&t.kind==="org")return{ok:!1,why:`${t.name} joined another holding, and a sole proprietor is a person`};if(n.form!=="series")return{ok:!0,why:""};const r=e.nodes.get(n.master);return r.status!=="active"?{ok:!1,why:`${r.name} is closed`}:((s=r.charter)==null?void 0:s.form)!=="series-llc"?{ok:!1,why:`${r.name} no longer holds series`}:t.root!==r.root?{ok:!1,why:`${t.name} is no longer in ${r.name}'s holding`}:{ok:!0,why:""}}function bk(e,t){const n=[],r=e.nodes.get(t),s=(o,i,a,c=null)=>{const u=!!c&&(o.parent!==c.parent||o.index!==c.index),f=u||o.root!==t;if(n.push({type:"node",node:o,guide:i,path:o.id===t?"●":`${c?c.index:o.index}'`,away:f,moved:u}),f)return;const l={agent:[],org:[]};for(const p of o.children){const g=e.nodes.get(p),h=l[g.kind==="agent"?"agent":"org"];h.push([g,{parent:o.id,index:h.length}])}const d=[["agents",l.agent],["orgs",l.org]].filter(([,p])=>p.length);d.forEach(([p,g],h)=>{const y=h===d.length-1,m=a+(y?" ":"│ ");n.push({type:"group",label:p,guide:a+(y?"└─ ":"├─ ")}),g.forEach(([x,w],P)=>{const b=P===g.length-1;s(x,m+(b?"└─ ":"├─ "),m+(b?" ":"│ "),w)})})};return r&&s(r,"",""),n}function xk(e,t){const n={orgs:0,agents:0,belts:0,decisions:0,closed:0};for(const r of e.nodes.values())r.root===t&&(r.id!==t&&(n[r.kind==="agent"?"agents":"orgs"]++,r.status==="closed"&&n.closed++),n.belts+=r.badges.length,n.decisions+=r.decisions.length);return n}function ts(e,t){const n=[];for(let r=e.nodes.get(t);r;r=r.id===r.root?null:e.nodes.get(r.parent))n.unshift(r.name);return n.join(" / ")}function vp(e,t){var s;const n=e.meta,r=o=>{var i;return((i=t.nodes.get(o))==null?void 0:i.name)??(typeof o=="string"?`${o.slice(0,8)}…`:"?")};if(!e.ok)return`${e.op}: ${e.why}`;switch(e.op){case"found":return`found ${n.name}`;case"birth":return`birth ${n.name}${n.kind==="agent"?" (agent)":""} ← ${r(e.parent)}`;case"award":return`award ${n.skill} · ${n.belt} → ${r(n.to)}, from ${r(e.parent)}`;case"decide":return`decide “${Nr(n.title,140)}” · ${r(e.parent)}`;case"make":return`make ${n.name} · ${r(e.parent)}`;case"keyring":return`keyring · ${r(e.parent)}`;case"charter":return n.form==="series"?`charter ${r(n.of)} as a series of ${r(e.parent)}`:`charter ${r(e.parent)} · ${mk[n.form]}${n.jurisdiction?` (${n.jurisdiction})`:""}`;case"graduate":return`graduate ${r(n.of)} from ${r(e.parent)}`;case"close":return`close ${r(e.parent)}${e.also.length?` and ${e.also.length} derived`:""}`;case"join":case"adopt":{const o=e.op==="join"?e.parent:n.of,i=e.op==="join"?n.to:e.parent,a=(s=t.nodes.get(o))==null?void 0:s.moves.find(c=>c.join===e.id||c.adopt===e.id);return`${e.op==="join"?`join ${r(o)} to ${r(i)}`:`adopt ${r(o)} into ${r(i)}`}${a?a.from?`, from ${r(a.from)}`:", a holding till now":e.op==="join"?`, for ${r(i)} to adopt`:`, once ${r(o)} joins`}`}default:return e.op}}const Tn=Ie,vk=ue,Wa=bt,kk=$r,On="super-testnet-local-v0";class Kn{constructor(t){if(!/^[0-9a-f]{64}$/.test(t)||!Oe.utils.isValidPrivateKey(t))throw new Error("Invalid test wallet key. Load a Super Testnet v0 backup.");this.kind="test-wallet",this.secret=t,this.pubkey=Tn(jn.getPublicKey(t)),this.address=As.p2tr.fromPubKey(this.pubkey,"regtest"),this.script=["OP_1",this.pubkey]}static create(){return new Kn(Tn(Oe.utils.randomPrivateKey()))}static load(t){if((t==null?void 0:t.network)!==On||(t==null?void 0:t.version)!==1||(t==null?void 0:t.kind)!=="test-wallet")throw new Error("Only Super Testnet v0 test-wallet backups are accepted.");return new Kn(t.secret)}backup(){return{kind:"test-wallet",version:1,network:On,secret:this.secret}}sign(t,n,r=0){return ur.taproot.sign(this.secret,t,r,n?{extension:n}:{}).hex}}const xo=50*1e8,vo="0".repeat(64),Hl=e=>Tn(Ae(new TextEncoder().encode(JSON.stringify(e)))),Cr=(e,t)=>`${e}:${t}`,De=e=>Ce.encode(e,!1).hex,le=(e,t)=>{if(!e)throw new Error(t)},Rl=/^5120[0-9a-f]{64}$/,ko=/^0014[0-9a-f]{40}$/,kp=64,xt=64,$k=e=>Tn(nu(Ae(Wa(e))));function Ek(e,t){const[n,r]=e.vin[t].witness;return Oe.verify(n.slice(0,-2),ur.segwit.hash(e,t,{pubkey:r,sigflag:1}),r,{lowS:!0,format:"der"})}const da=(e,...t)=>{const n=Ae(new TextEncoder().encode(e));return Ae(vk(n,n,...t))},Sk=e=>e<253?Uint8Array.of(e):Uint8Array.of(253,e&255,e>>8);function _k(e,t){const[n,r,s]=e.vin[t].witness,o=Wa(s),i=Wa(r);if(o.length<33||(o.length-33)%32||i.length>65535||!/^20[0-9a-f]{64}ac/.test(r))return!1;const a=da("TapLeaf",Uint8Array.of(o[0]&254),Sk(i.length),i);let c=a;for(let l=33;l=Oe.CURVE.n)return!1;const f=Oe.ProjectivePoint.fromHex(`02${Tn(o.slice(1,33))}`).add(Oe.ProjectivePoint.BASE.multiply(u)).toAffine();return`5120${f.x.toString(16).padStart(64,"0")}`!==De(e.vin[t].prevout.scriptPubKey)||Number(f.y&1n)!==(o[0]&1)?!1:jn.verify(n,ur.taproot.hash(e,t,{extension:Tn(a)}),r.slice(2,66))}class Bi{constructor(t){if(this.blocks=[],this.mempool=[],this.utxos=new Map,this.transactions=new Map,this.imports=[],t){le(t.network===On&&t.version===1,"Unsupported local chain version/network."),le(Array.isArray(t.blocks)&&Array.isArray(t.mempool)&&Array.isArray(t.imports??[]),"Invalid chain snapshot.");for(const n of t.imports??[])this.importCoin(n);for(const n of t.blocks)this.acceptBlock(structuredClone(n));this.submitPackage(t.mempool)}}snapshot(){return{network:On,version:1,blocks:structuredClone(this.blocks),mempool:[...this.mempool],...this.imports.length?{imports:structuredClone(this.imports)}:{}}}importCoin({txid:t,vout:n,value:r,script:s}){le(/^[0-9a-f]{64}$/.test(t)&&Number.isSafeInteger(n)&&n>=0&&Number.isSafeInteger(r)&&r>=330&&r<=xo&&(Rl.test(s)||ko.test(s)),"Invalid imported coin."),le(!this.utxos.has(Cr(t,n))&&!this.transactions.has(t)&&!this.imported(t,n),"That coin is already in this chain."),this.utxos.set(Cr(t,n),{txid:t,vout:n,value:r,scriptPubKey:s,height:0,ranges:Xl(this.imports.length,r),inscriptions:[]}),this.imports.push({txid:t,vout:n,value:r,script:s})}imported(t,n){const r=this.imports.find(s=>s.txid===t&&s.vout===n);return r?{value:r.value,scriptPubKey:r.script}:null}coins(t){return[...this.utxos.values()].filter(n=>De(n.scriptPubKey)===De(t))}satLocation(t){for(const n of this.utxos.values()){const r=tn(n.ranges,t);if(r!==null)return{txid:n.txid,vout:n.vout,offset:r}}return null}balance(t){return this.coins(t).reduce((n,r)=>n+r.value,0)}apply(t,n,r=!1){var y,m,x,w,P;le(typeof t=="string"&&t.length<4e4&&/^(?:[a-f0-9]{2})+$/.test(t),"Invalid raw transaction.");const s=X.decode(t),o=X.util.getTxid(s);le(!this.transactions.has(o),"Duplicate transaction."),le(s.version===2&&s.locktime===0,"Unsupported transaction version or locktime.");const i=!r&&s.vin.some(b=>{var $;return(($=b.witness)==null?void 0:$.length)===3}),a=r?1:i?3:xt,c=r?kp:i?2:xt;le(s.vin.length>=1&&s.vin.length<=a&&s.vout.length>=1&&s.vout.length<=c,"Unsupported transaction shape.");let u=0;for(const b of s.vout){const $=Number(b.value);le(Number.isSafeInteger($)&&$>=330&&$<=xo,"Invalid output amount.");const T=De(b.scriptPubKey);le(Rl.test(T)||ko.test(T),"Only Taproot and P2WPKH outputs are supported."),u+=$}let f,l=[];const d=s.vin.findIndex(b=>{var $;return(($=b.witness)==null?void 0:$.length)===3}),p=s.vin[d<0?0:d];if(r)le(p.txid===vo&&p.vout===4294967295&&u===xo,"Invalid local coinbase."),le(De(p.scriptSig)===Ce.encode([new TextEncoder().encode(`${On}:${n}`)],!1).hex,"Wrong coinbase height."),le(!((y=p.witness)!=null&&y.length),"Unexpected coinbase witness.");else{l=s.vin.map($=>this.utxos.get(Cr($.txid,$.vout))),le(l.every(Boolean),"Input is missing or already spent."),le(new Set(s.vin.map($=>Cr($.txid,$.vout))).size===s.vin.length,"Duplicate input."),s.vin.forEach(($,T)=>{var O,L,_;le($.sequence==="ffffffff"&&De($.scriptSig)==="","Unsupported input flags."),$.prevout={value:l[T].value,scriptPubKey:l[T].scriptPubKey};const U=De(l[T].scriptPubKey);if(ko.test(U)){const[C,k]=$.witness??[];le(T!==d&&((O=$.witness)==null?void 0:O.length)===2,"Unsupported witness."),le(/^30[0-9a-f]{12,140}01$/.test(C)&&/^0[23][0-9a-f]{64}$/.test(k)&&$k(k)===U.slice(4),"P2WPKH spends need a SIGHASH_ALL signature by the key they pay.");return}le(((L=$.witness)==null?void 0:L.length)===1||T===d&&((_=$.witness)==null?void 0:_.length)===3,"Unsupported witness."),le(/^[0-9a-f]{128}$/.test($.witness[0])||!i&&/^[0-9a-f]{128}83$/.test($.witness[0]),"Only default 64-byte Schnorr signatures, or SIGHASH_SINGLE|ANYONECANPAY outside reveals, are accepted.")}),le(l.reduce(($,T)=>$+T.value,0)-u===W,"v0 requires a fixed 500 sat fee per transaction.");let b={};if(p.witness.length===3){const $=zc(p.witness),T=d;if(s.vin.length===3){const[U,O]=l,L=$.pointer===void 0?null:Number($.pointer);le(d===2&&$.parent&&((m=O.inscriptions)==null?void 0:m.some(_=>_.id===$.parent))&&De(O.scriptPubKey)===`5120${$.pubkey}`,"An inscription on a held sat needs its parent spent, from the inscriber's key."),le(s.vout.length===2&&[U,O].every((_,C)=>Number(s.vout[C].value)===_.value&&De(s.vout[C].scriptPubKey)===De(_.scriptPubKey)),"An inscription on a held sat returns both coins unchanged."),le(L!==null&&Ltn(U.ranges,_.sat)===L)),"An inscription on a held sat must point at an inscribed sat.")}else if(le(Number(s.vout[T].value)===Rt,"Invalid reveal postage."),le(De(s.vout[T].scriptPubKey)===`5120${$.pubkey}`,"Reveal must return to its signing wallet."),$.parent){const U=d===0?1:0,O=l[U];le((w=O==null?void 0:O.inscriptions)==null?void 0:w.some(L=>L.id===$.parent),"Referenced parent inscription must actually be spent."),le(s.vout.length===2&&Number(s.vout[U].value)===O.value&&De(O.scriptPubKey)===`5120${$.pubkey}`&&De(s.vout[U].scriptPubKey)===De(O.scriptPubKey),"Parent must be owned and preserved in the same wallet.")}else s.vin.length===2&&(le(d===1&&((P=l[0].inscriptions)==null?void 0:P.length)&&$.pointer!==void 0,"Reinscription spend requires correct tag and owned sat."),le(Number(s.vout[0].value)===l[0].value&&De(s.vout[0].scriptPubKey)===De(l[0].scriptPubKey)&&De(l[0].scriptPubKey)===`5120${$.pubkey}`,"Reinscription sat must be returned to owner."));b={pubkey:$.pubkey},f={id:`${o}i0`,txid:o,commitTxid:p.txid,text:$.text,bytes:Array.from($.bytes),contentType:$.contentType,parent:$.parent,delegate:$.delegate,pointer:$.pointer,metaprotocol:$.metaprotocol,metadata:$.metadata,height:n,value:Rt}}s.vin.forEach(($,T)=>{let U=!1;try{U=ko.test(De(l[T].scriptPubKey))?Ek(s,T):T===d?_k(s,T)||ur.taproot.verify(s,T,b):ur.taproot.verify(s,T,{})}catch{}le(U,"Invalid signature or Taproot commitment.")})}const g=ef(s,l,n,r),h=l.flatMap(b=>b.inscriptions??[]);if(f){const b=BigInt(f.pointer??0),$=b{var U;return((U=T.inscription)==null?void 0:U.sat)===f.sat}).length,h.push(f)}return le(h.every(b=>g.some($=>tn($,b.sat)!==null)),"Local lab protects inscription sats from fee loss."),r||s.vin.forEach(b=>this.utxos.delete(Cr(b.txid,b.vout))),s.vout.forEach((b,$)=>{const T=h.filter(U=>tn(g[$],U.sat)!==null);this.utxos.set(Cr(o,$),{txid:o,vout:$,value:Number(b.value),scriptPubKey:b.scriptPubKey,height:n,ranges:g[$],inscriptions:T,...T.length?{inscription:T[0]}:{}})}),this.transactions.set(o,{txid:o,raw:t,height:n,coinbase:r,tx:s,...f?{inscription:f}:{}}),o}submitPackage(t){le(Array.isArray(t)&&this.mempool.length+t.length<=1e3,"Invalid package or mempool full; mine a block first.");const n=new Map(this.utxos),r=new Map(this.transactions);try{t.forEach(s=>this.apply(s,null))}catch(s){throw this.utxos=n,this.transactions=r,s}this.mempool.push(...t)}acceptBlock(t){var i;le(t.height===this.blocks.length+1&&t.previous===(((i=this.blocks.at(-1))==null?void 0:i.hash)??vo),"Invalid block ancestry."),le(Number.isSafeInteger(t.time)&&t.time>0&&Array.isArray(t.raws)&&t.raws.length>0&&t.raws.length<=1001,"Invalid block.");const{hash:n,...r}=t;le(Hl(r)===n,"Invalid local block hash.");const s=new Map(this.utxos),o=new Map(this.transactions);try{t.raws.forEach((a,c)=>this.apply(a,t.height,c===0))}catch(a){throw this.utxos=s,this.transactions=o,a}this.blocks.push(t)}mine(t){return this.mineTo([de(xo,t)])}mineTo(t){var a;const n=new Bi({...this.snapshot(),mempool:[]}),r=this.blocks.length+1,s=X.create({vin:[{txid:vo,vout:4294967295,scriptSig:[new TextEncoder().encode(`${On}:${r}`)]}],vout:t}),o={height:r,previous:((a=this.blocks.at(-1))==null?void 0:a.hash)??vo,time:Date.now(),raws:[X.encode(s).hex,...this.mempool]},i={...o,hash:Hl(o)};return n.acceptBlock(i),Object.assign(this,n),i}}const $p="lineage-claim",Ga=330,ai=e=>Ce.encode(e,!1).hex,jl=e=>({txid:e.txid,vout:e.vout,value:e.value,script:ai(e.scriptPubKey)}),ha=/^[0-9a-f]{64}$/,Ak=/^5120[0-9a-f]{64}$/;function Ct(e,t){var n;for(const r of e.utxos.values())if((n=r.inscriptions)!=null&&n.some(s=>s.id===t))return r;return null}function Ep(e){return X.create({vin:[Fe(e.holder.txid,e.holder.vout,e.holder.value,e.holder.script),Fe(e.payer.txid,e.payer.vout,e.payer.value,e.payer.script)],vout:[de(e.holder.value,["OP_1",e.to]),de(e.payer.value-W,["OP_1",e.to])]})}function Bk(e,t,n,r=Date.now()){if((n==null?void 0:n.kind)!=="test-wallet")throw new Error("Claims are signed by local test wallets.");const s=Ct(e,t);if(!s)throw new Error("That inscription is not in an unspent output.");if(ai(s.scriptPubKey)===ai(n.script))throw new Error("The recipient already holds that inscription.");const o=e.coins(n.script).find(c=>{var u;return!((u=c.inscriptions)!=null&&u.length)&&c.value>=W+Ga});if(!o)throw new Error("The recipient needs a plain coin for the 500-sat fee. Mine a block to it first.");const i={kind:$p,version:1,inscription:t,carried:s.inscriptions.map(c=>c.id),holder:jl(s),payer:jl(o),to:n.pubkey,at:r},a=Ep(i);return i.txid=X.util.getTxid(a),i.sig=n.sign(a,void 0,1),i}function Tk(e,t,n){const r=Ik(t);if((n==null?void 0:n.kind)!=="test-wallet")throw new Error("Countersigning needs a local test wallet.");if(ai(n.script)!==r.holder.script)throw new Error("Only the current holder can countersign.");if(Ok(e,r)!=="open")throw new Error("This claim is stale: an input it spends was already spent.");const s=Ep(r);return s.vin[1].witness=[r.sig],s.vin[0].witness=[n.sign(s,void 0,0)],e.submitPackage([X.encode(s).hex]),X.util.getTxid(s)}function Ok(e,t){return e.utxos.has(`${t.holder.txid}:${t.holder.vout}`)&&e.utxos.has(`${t.payer.txid}:${t.payer.vout}`)?"open":"stale"}function Ik(e){const t=n=>n&&ha.test(n.txid)&&Number.isSafeInteger(n.vout)&&n.vout>=0&&Number.isSafeInteger(n.value)&&n.value>=Ga&&Ak.test(n.script);if((e==null?void 0:e.kind)!==$p||e.version!==1||!/^[0-9a-f]{64}i\d+$/.test(e.inscription)||!Array.isArray(e.carried)||!t(e.holder)||!t(e.payer)||e.payer.value255*s)throw new Error("Length should be <= 255*HashLen");const o=Math.ceil(r/s);n===void 0&&(n=Kl);const i=new Uint8Array(o*s),a=Rn.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let f=0;fPk(e,Ck(e,t,n),r,s);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _n=BigInt(0),Me=BigInt(1),ga=BigInt(2),Nk=BigInt(8);function Lk(e,t,n,r){const s=e.sqr(n),o=e.sqr(r),i=e.add(e.mul(t.a,s),o),a=e.add(e.ONE,e.mul(t.d,e.mul(s,o)));return e.eql(i,a)}function Hk(e,t={}){const n=Ph("edwards",e,t,t.FpFnLE),{Fp:r,Fn:s}=n;let o=n.CURVE;const{h:i}=o;us(t,{},{uvRatio:"function"});const a=ga<r.create(y),u=t.uvRatio||((y,m)=>{try{return{isValid:!0,value:r.sqrt(r.div(y,m))}}catch{return{isValid:!1,value:_n}}});if(!Lk(r,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function f(y,m,x=!1){const w=x?Me:_n;return Ks("coordinate "+y,m,w,a),m}function l(y){if(!(y instanceof g))throw new Error("ExtendedPoint expected")}const d=Xo((y,m)=>{const{X:x,Y:w,Z:P}=y,b=y.is0();m==null&&(m=b?Nk:r.inv(P));const $=c(x*m),T=c(w*m),U=r.mul(P,m);if(b)return{x:_n,y:Me};if(U!==Me)throw new Error("invZ was invalid");return{x:$,y:T}}),p=Xo(y=>{const{a:m,d:x}=o;if(y.is0())throw new Error("bad point: ZERO");const{X:w,Y:P,Z:b,T:$}=y,T=c(w*w),U=c(P*P),O=c(b*b),L=c(O*O),_=c(T*m),C=c(O*c(_+U)),k=c(L+c(x*c(T*U)));if(C!==k)throw new Error("bad point: equation left != right (1)");const S=c(w*P),v=c(b*$);if(S!==v)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(m,x,w,P){this.X=f("x",m),this.Y=f("y",x),this.Z=f("z",w,!0),this.T=f("t",P),Object.freeze(this)}static CURVE(){return o}static fromAffine(m){if(m instanceof g)throw new Error("extended point not allowed");const{x,y:w}=m||{};return f("x",x),f("y",w),new g(x,w,Me,c(x*w))}static fromBytes(m,x=!1){const w=r.BYTES,{a:P,d:b}=o;m=fl(_t(m,w,"point")),hr(x,"zip215");const $=fl(m),T=m[w-1];$[w-1]=T&-129;const U=pr($),O=x?a:r.ORDER;Ks("point.y",U,_n,O);const L=c(U*U),_=c(L-Me),C=c(b*L-P);let{isValid:k,value:S}=u(_,C);if(!k)throw new Error("bad point: invalid y coordinate");const v=(S&Me)===Me,A=(T&128)!==0;if(!x&&S===_n&&A)throw new Error("bad point: x=0 and x_0=1");return A!==v&&(S=c(-S)),g.fromAffine({x:S,y:U})}static fromHex(m,x=!1){return g.fromBytes(be("point",m),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,x=!0){return h.createCache(this,m),x||this.multiply(ga),this}assertValidity(){p(this)}equals(m){l(m);const{X:x,Y:w,Z:P}=this,{X:b,Y:$,Z:T}=m,U=c(x*T),O=c(b*P),L=c(w*T),_=c($*P);return U===O&&L===_}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:m}=o,{X:x,Y:w,Z:P}=this,b=c(x*x),$=c(w*w),T=c(ga*c(P*P)),U=c(m*b),O=x+w,L=c(c(O*O)-b-$),_=U+$,C=_-T,k=U-$,S=c(L*C),v=c(_*k),A=c(L*k),N=c(C*_);return new g(S,v,N,A)}add(m){l(m);const{a:x,d:w}=o,{X:P,Y:b,Z:$,T}=this,{X:U,Y:O,Z:L,T:_}=m,C=c(P*U),k=c(b*O),S=c(T*w*_),v=c($*L),A=c((P+b)*(U+O)-C-k),N=v-S,K=v+S,H=c(k-x*C),D=c(A*N),q=c(K*H),G=c(A*H),fe=c(N*K);return new g(D,q,fe,G)}subtract(m){return this.add(m.negate())}multiply(m){if(!s.isValidNot0(m))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:x,f:w}=h.cached(this,m,P=>rr(g,P));return rr(g,[x,w])[0]}multiplyUnsafe(m,x=g.ZERO){if(!s.isValid(m))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return m===_n?g.ZERO:this.is0()||m===Me?this:h.unsafe(this,m,w=>rr(g,w),x)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return h.unsafe(this,o.n).is0()}toAffine(m){return d(this,m)}clearCofactor(){return i===Me?this:this.multiplyUnsafe(i)}toBytes(){const{x:m,y:x}=this.toAffine(),w=r.toBytes(x);return w[w.length-1]|=m&Me?128:0,w}toHex(){return Ie(this.toBytes())}toString(){return``}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(m){return rr(g,m)}static msm(m,x){return Ch(g,s,m,x)}_setWindowSize(m){this.precompute(m)}toRawBytes(){return this.toBytes()}}g.BASE=new g(o.Gx,o.Gy,Me,c(o.Gx*o.Gy)),g.ZERO=new g(_n,Me,Me,_n),g.Fp=r,g.Fn=s;const h=new Ih(g,s.BITS);return g.BASE.precompute(8),g}function Rk(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');us(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:s,Fp:o,Fn:i}=e,a=n.randomBytes||kr,c=n.adjustScalarBytes||(O=>O),u=n.domain||((O,L,_)=>{if(hr(_,"phflag"),L.length||_)throw new Error("Contexts/pre-hash are not supported");return O});function f(O){return i.create(pr(O))}function l(O){const L=w.secretKey;O=be("private key",O,L);const _=be("hashed private key",t(O),2*L),C=c(_.slice(0,L)),k=_.slice(L,2*L),S=f(C);return{head:C,prefix:k,scalar:S}}function d(O){const{head:L,prefix:_,scalar:C}=l(O),k=s.multiply(C),S=k.toBytes();return{head:L,prefix:_,scalar:C,point:k,pointBytes:S}}function p(O){return d(O).pointBytes}function g(O=Uint8Array.of(),...L){const _=ue(...L);return f(t(u(_,be("context",O),!!r)))}function h(O,L,_={}){O=be("message",O),r&&(O=r(O));const{prefix:C,scalar:k,pointBytes:S}=d(L),v=g(_.context,C,O),A=s.multiply(v).toBytes(),N=g(_.context,A,S,O),K=i.create(v+N*k);if(!i.isValid(K))throw new Error("sign failed: invalid s");const H=ue(A,i.toBytes(K));return _t(H,w.signature,"result")}const y={zip215:!0};function m(O,L,_,C=y){const{context:k,zip215:S}=C,v=w.signature;O=be("signature",O,v),L=be("message",L),_=be("publicKey",_,w.publicKey),S!==void 0&&hr(S,"zip215"),r&&(L=r(L));const A=v/2,N=O.subarray(0,A),K=pr(O.subarray(A,v));let H,D,q;try{H=e.fromBytes(_,S),D=e.fromBytes(N,S),q=s.multiplyUnsafe(K)}catch{return!1}if(!S&&H.isSmallOrder())return!1;const G=g(k,D.toBytes(),H.toBytes(),L);return D.add(H.multiplyUnsafe(G)).subtract(q).clearCofactor().is0()}const x=o.BYTES,w={secretKey:x,publicKey:x,signature:2*x,seed:x};function P(O=a(w.seed)){return _t(O,w.seed,"seed")}function b(O){const L=U.randomSecretKey(O);return{secretKey:L,publicKey:p(L)}}function $(O){return Gs(O)&&O.length===i.BYTES}function T(O,L){try{return!!e.fromBytes(O,L)}catch{return!1}}const U={getExtendedPublicKey:d,randomSecretKey:P,isValidSecretKey:$,isValidPublicKey:T,toMontgomery(O){const{y:L}=e.fromBytes(O),_=w.publicKey,C=_===32;if(!C&&_!==57)throw new Error("only defined for 25519 and 448");const k=C?o.div(Me+L,Me-L):o.div(L-Me,L+Me);return o.toBytes(k)},toMontgomerySecret(O){const L=w.secretKey;_t(O,L);const _=t(O.subarray(0,L));return c(_).subarray(0,L)},randomPrivateKey:P,precompute(O=8,L=e.BASE){return L.precompute(O,!1)}};return Object.freeze({keygen:b,getPublicKey:p,sign:h,verify:m,utils:U,Point:e,lengths:w})}function jk(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp,r=Er(t.n,e.nBitLength,!0),s={Fp:n,Fn:r,uvRatio:e.uvRatio},o={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:s,hash:e.hash,eddsaOpts:o}}function Kk(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function Dk(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:s}=jk(e),o=Hk(t,n),i=Rk(o,r,s);return Kk(e,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const bs=BigInt(0),Pr=BigInt(1),$o=BigInt(2);function Mk(e){return us(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function Zk(e){const t=Mk(e),{P:n,type:r,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=t,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=i||kr,u=a?255:448,f=a?32:56,l=BigInt(a?9:5),d=BigInt(a?121665:39081),p=a?$o**BigInt(254):$o**BigInt(447),g=a?BigInt(8)*$o**BigInt(251)-Pr:BigInt(4)*$o**BigInt(445)-Pr,h=p+g+Pr,y=k=>Te(k,n),m=x(l);function x(k){return Yc(y(k),f)}function w(k){const S=be("u coordinate",k,f);return a&&(S[31]&=127),y(pr(S))}function P(k){return pr(s(be("scalar",k,f)))}function b(k,S){const v=U(w(S),P(k));if(v===bs)throw new Error("invalid private or public key received");return x(v)}function $(k){return b(k,m)}function T(k,S,v){const A=y(k*(S-v));return S=y(S-A),v=y(v+A),{x_2:S,x_3:v}}function U(k,S){Ks("u",k,bs,n),Ks("scalar",S,p,h);const v=S,A=k;let N=Pr,K=bs,H=k,D=Pr,q=bs;for(let fe=BigInt(u-1);fe>=bs;fe--){const ce=v>>fe⪻q^=ce,{x_2:N,x_3:H}=T(q,N,H),{x_2:K,x_3:D}=T(q,K,D),q=ce;const ne=N+K,ge=y(ne*ne),me=N-K,Le=y(me*me),pe=ge-Le,_e=H+D,Gt=H-D,ht=y(Gt*ne),We=y(_e*me),Yt=ht+We,hs=ht-We;H=y(Yt*Yt),D=y(A*y(hs*hs)),N=y(ge*Le),K=y(pe*(ge+y(d*pe)))}({x_2:N,x_3:H}=T(q,N,H)),{x_2:K,x_3:D}=T(q,K,D);const G=o(K);return y(N*G)}const O={secretKey:f,publicKey:f,seed:f},L=(k=c(f))=>(Ve(k,O.seed),k);function _(k){const S=L(k);return{secretKey:S,publicKey:$(S)}}return{keygen:_,getSharedSecret:(k,S)=>b(k,S),getPublicKey:k=>$(k),scalarMult:b,scalarMultBase:$,utils:{randomSecretKey:L,randomPrivateKey:L},GuBytes:m.slice(),lengths:O}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Vk=BigInt(1),Dl=BigInt(2),qk=BigInt(3),zk=BigInt(5),Fk=BigInt(8),fu=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Sp={p:fu,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Fk,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function _p(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),o=fu,a=e*e%o*e%o,c=Pe(a,Dl,o)*a%o,u=Pe(c,Vk,o)*e%o,f=Pe(u,zk,o)*u%o,l=Pe(f,t,o)*f%o,d=Pe(l,n,o)*l%o,p=Pe(d,r,o)*d%o,g=Pe(p,s,o)*p%o,h=Pe(g,s,o)*p%o,y=Pe(h,t,o)*f%o;return{pow_p_5_8:Pe(y,Dl,o)*e%o,b2:a}}function Ap(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Ml=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Wk(e,t){const n=fu,r=Te(t*t*t,n),s=Te(r*r*t,n),o=_p(e*s).pow_p_5_8;let i=Te(e*r*o,n);const a=Te(t*i*i,n),c=i,u=Te(i*Ml,n),f=a===e,l=a===Te(-e,n),d=a===Te(-e*Ml,n);return f&&(i=c),(l||d)&&(i=u),F2(i,n)&&(i=Te(-i,n)),{isValid:f||l,value:i}}const Bp=Er(Sp.p,{isLE:!0}),Gk={...Sp,Fp:Bp,hash:js,adjustScalarBytes:Ap,uvRatio:Wk},Ti=Dk(Gk),Tp=(()=>{const e=Bp.ORDER;return Zk({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:n,b2:r}=_p(t);return Te(Pe(n,qk,e)*r,e)},adjustScalarBytes:Ap})})(),Yk=Ke("lineage/v0"),Kt=(e,t)=>Uk(Ae,e,Yk,Ke(t),32),Oi=e=>{const t=Uint8Array.from(e);return t[0]&=248,t[31]&=127,t[31]|=64,t},Op=e=>{const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t},vt=e=>ue(Op(e.length),e),du=e=>ue(vt(Ke("ssh-ed25519")),vt(e)),Ya=(e,t)=>`ssh-ed25519 ${yt.encode(du(e))}${t?` ${t}`:""}`,Xa=e=>`SHA256:${yt.encode(Ae(du(e))).replace(/=+$/,"")}`;function Xk(e){const t=bt(e),n=r=>Ti.getPublicKey(Kt(t,r));return{ssh:n("ssh"),git:n("git"),dkim:n("dkim"),wg:Tp.getPublicKey(Oi(Kt(t,"wg")))}}function Jk(e){const t=n=>Ti.getPublicKey(Kt(e,n));return{"ssh-ca":t("node/ssh-ca"),mtls:t("node/mtls"),noise:Tp.getPublicKey(Oi(Kt(e,"node/noise")))}}function Qk(e,t,n,r){return[["ssh",Xa(e.ssh),Ya(e.ssh,t)],["git",Xa(e.git),`${t} namespaces="git" ${Ya(e.git,t)}`],["dkim",`${n}._domainkey.${r}`,`${n}._domainkey.${r}. IN TXT "v=DKIM1; k=ed25519; p=${yt.encode(e.dkim)}"`],["wg",yt.encode(e.wg),`[Peer] -# ${t} -PublicKey = ${yt.encode(e.wg)}`]]}function e$(e,t){return[["ssh-ca",Xa(e["ssh-ca"]),Ya(e["ssh-ca"],`lineage-ca@${t}`)],["mtls",yt.encode(e.mtls),null],["noise",`mkey:${Ie(e.noise)}`,null]]}const t$=bt("302e020100300506032b657004220420");function Ip(e,t,n){const r=Ae(e).slice(0,4);let s=ue(r,r,vt(Ke("ssh-ed25519")),vt(t),vt(ue(e,t)),vt(Ke(n)));s=ue(s,new Uint8Array((8-s.length%8)%8).map((i,a)=>a+1));const o=ue(Ke("openssh-key-v1\0"),vt(Ke("none")),vt(Ke("none")),vt(new Uint8Array(0)),Op(1),vt(du(t)),vt(s));return`-----BEGIN OPENSSH PRIVATE KEY----- -${yt.encode(o).match(/.{1,70}/g).join(` -`)} ------END OPENSSH PRIVATE KEY----- -`}const n$=(e,t)=>`-----BEGIN ${e}----- -${yt.encode(t).match(/.{1,64}/g).join(` -`)} ------END ${e}----- -`;function r$(e,t){const n=bt(e),r=s=>{const o=Kt(n,s);return Ip(o,Ti.getPublicKey(o),t)};return[["ssh","OpenSSH private key",r("ssh")],["git","OpenSSH private key",r("git")],["dkim","Ed25519 private key (base64)",yt.encode(Kt(n,"dkim"))],["wg","Interface entry",`[Interface] -PrivateKey = ${yt.encode(Oi(Kt(n,"wg")))}`]]}function s$(e,t){const n=Kt(e,"node/ssh-ca");return[["ssh-ca","OpenSSH private key",Ip(n,Ti.getPublicKey(n),`lineage-ca@${t}`)],["mtls","Private key (PKCS#8 PEM)",n$("PRIVATE KEY",ue(t$,Kt(e,"node/mtls")))],["noise","noise_private.key",`privkey:${Ie(Oi(Kt(e,"node/noise")))}`]]}const o$=["bip86","tapkey","wallet"],hu=()=>({scheme:"bip86",roots:{},adopted:{}}),i$=e=>Fs.getPubKey(e)[0];function Cp(e,t,n){return e.scheme==="wallet"?Fa(t,n):Fs.getSecKey(e.scheme==="tapkey"?Si(t,n):Fa(t,n))[0]}const Pp=(e,t)=>e.scheme==="tapkey"?rt.nostr(t):rt.wallet(t),a$=(e,t)=>new Kn(Cp(e,t,0)),Se=e=>Ce.encode(e,!1).hex;function un(e,t,n){if(!n)return null;const r=i=>i?{mnemonic:i,account:0,origin:`${n.name} root`,steps:[]}:null;if(n.kind==="holding")return r(e.roots[n.id]);if(n.edge==="adopted")return r(e.adopted[n.rooted]??e.adopted[n.id]);const s=t.nodes.get(n.parent);if(n.kind==="agent"){const i=un(e,t,s);return i&&{...i,account:n.index+1}}const o=un(e,t,s);return o&&{mnemonic:Qv(o.mnemonic,n.index),account:0,origin:o.origin,steps:[...o.steps,`${n.index}'`]}}const ma=new Map;function $e(e,t,n){const r=un(e,t,n);if(!r)return null;const s=`${e.scheme}|${r.mnemonic}|${r.account}`;if(!ma.has(s)){const{npub:u,pubkey:f}=tk(r.mnemonic,r.account);ma.set(s,{wallet:new Kn(Cp(e,r.mnemonic,r.account)),npub:u,pubkey:f})}const{wallet:o,npub:i,pubkey:a}=ma.get(s),c=[r.origin,...r.steps].join(" › ");return{wallet:o,npub:i,pubkey:a,scheme:e.scheme,account:r.account,from:c,path:`${c} · ${Pp(e,r.account)}`}}function pu(e,t,n){const r=un(e,t,n);if(!r)return null;const s=$e(e,t,n),o=up(r.mnemonic,r.account);return{taproot:{address:s.wallet.address,path:Pp(e,r.account)},segwit:{address:As.p2wpkh.fromPubKey(o,"regtest"),path:rt.segwit(r.account)},tapkey:{address:As.p2tr.fromPubKey(i$(s.pubkey),"regtest"),path:rt.nostr(r.account)},npub:{address:s.npub,path:rt.nostr(r.account)},ethereum:{address:ek(r.mnemonic,r.account),path:rt.ethereum(r.account)}}}function c$(e,t,n){const r=un(e,t,n);if(!r)return null;const s=$e(e,t,n),o=pu(e,t,n),{mnemonic:i,account:a}=r;return{keys:{taproot:o.taproot.address,segwit:o.segwit.address,nostr:o.npub.address,ethereum:o.ethereum.address},secrets:{taproot:s.wallet.secret,segwit:au(i,a),nostr:Si(i,a),ethereum:dp(i,a)}}}function Ii(e,t,n){const r=Ct(e.chain,n);if(!r)return null;const s=Se(r.scriptPubKey),o=t.nodes.get(n),i=$e(e.keys,t,o),a=o&&$e(e.keys,t,t.nodes.get(o.parent));return i&&Se(i.wallet.script)===s?{wallet:i.wallet,who:"own"}:e.wallet&&Se(e.wallet.script)===s?{wallet:e.wallet,who:"lab"}:a&&Se(a.wallet.script)===s?{wallet:a.wallet,who:"parent"}:{wallet:null,who:"other",script:s}}function Fn(e,t){const n=e.nodes.get(t),r=[n];for(const s of _r(e.nodes,n))s.status==="active"&&s.edge==="derived"&&r.push(...Fn(e,s.id));return r}function Ja(e,t){const n=[];for(let r=t;r;r=e.nodes.get(r.parent))n.push(r.name);return n.join(".")}function u$(e,t,n){const r=un(e,t,n);if(!r)return null;if(n.kind!=="agent")return e$(Jk(iu(r.mnemonic)),Ja(t,n));const s=Ja(t,t.nodes.get(n.parent));return Qk(Xk(Si(r.mnemonic,r.account)),`${n.name}@${s}`,n.name,s)}const l$=tp(Ae),xs=(e,t=239)=>l$.encode(ue(Uint8Array.of(t),bt(e),Uint8Array.of(1))),f$=e=>mr.encode("nsec",mr.toWords(bt(e))),d$="0123456789()[],'/*abcdefgh@:$%{}IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ",h$=[0xf5dee51989n,0xa9fdca3312n,0x1bab10e32dn,0x3706b1677an,0x644d626ffdn];function ya(e){const t=(i,a)=>{const c=i>>35n;return i=(i&0x7ffffffffn)<<5n^BigInt(a),h$.forEach((u,f)=>{c>>BigInt(f)&1n&&(i^=u)}),i};let n=1n,r=0,s=0;for(const i of e){const a=d$.indexOf(i);if(a<0)throw new Error("Invalid descriptor character.");n=t(n,a&31),r=r*3+(a>>5),++s===3&&(n=t(n,r),r=0,s=0)}s&&(n=t(n,r));for(let i=0;i<8;i++)n=t(n,0);n^=1n;let o="";for(let i=0;i<8;i++)o+="qpzry9x8gf2tvdw0s3jn54khce6mua7l"[Number(n>>BigInt(5*(7-i))&31n)];return`${e}#${o}`}function p$(e,t,n){const r=un(e,t,n);if(!r)return null;const s=Si(r.mnemonic,r.account),o=Fa(r.mnemonic,r.account),i={bip86:`tr(${xs(o)})`,tapkey:`tr(${xs(s)})`,wallet:`rawtr(${xs(o)})`}[e.scheme],a=n.kind==="agent",c=Ja(t,a?t.nodes.get(n.parent):n);return{seed:a&&n.edge!=="adopted"?null:{from:[r.origin,...r.steps].join(" › "),mnemonic:r.mnemonic},account:[["nsec","NIP-06",f$(s)],["taproot","descriptor",ya(i)],["segwit","descriptor",ya(`wpkh(${xs(au(r.mnemonic,r.account))})`)],["tapkey","descriptor",ya(`tr(${xs(s)})`)],["ethereum","private key",`0x${dp(r.mnemonic,r.account)}`]],leaves:a?r$(s,`${n.name}@${c}`):s$(iu(r.mnemonic),c)}}const Kr=1e8,Ge=50*Kr,we=330,Up=e=>(e/Kr).toFixed(8).replace(/\.?0+$/,""),Y=e=>`${Up(e)} tBTC`;function gu(e){if(e<1e6)return Y(e);const t=Math.round(e/1e6)*1e6;return`${t===e?"":"≈"}${Y(t)}`}function Ci(e){const t=/^\s*(\d{0,7})(?:\.(\d{0,8}))?\s*$/.exec(String(e??""));return!t||!(t[1]||t[2])?null:Number(t[1]||0)*Kr+Number((t[2]??"").padEnd(8,"0"))}class mu{constructor(t,n,r){this.secret=t,this.pubkey=n,this.path=r,this.address=As.p2wpkh.fromPubKey(n,"regtest"),this.script=As.toScriptPubKey(this.address)}sign(t,n){return[ur.segwit.sign(this.secret,t,n,{pubkey:this.pubkey}).hex,this.pubkey]}}const wa=new Map;function xe(e,t,n){const r=un(e,t,n);if(!r)return null;const s=`${r.mnemonic}|${r.account}`;return wa.has(s)||wa.set(s,new mu(au(r.mnemonic,r.account),up(r.mnemonic,r.account),rt.segwit(r.account))),wa.get(s)}function g$(e,t,n){var s;const r=n?t.nodes.get(n):null;return r&&r.root===r.id&&r.status==="active"?((s=xe(e,t,r))==null?void 0:s.script)??null:null}const Dr=(e,t)=>{var n,r;return((r=(n=e.mining)==null?void 0:n.rigs)==null?void 0:r[t])??1};function Np(e,t,n){if((e.asks??[]).some(o=>o.lot===n.id&&!o.taken&&e.chain.utxos.has(`${o.holder.txid}:${o.holder.vout}`)))return!0;const r=Ct(e.chain,n.id),s=$e(e.keys,t,n);return!!r&&!!s&&Se(r.scriptPubKey)!==Se(s.wallet.script)}function yu(e,t){var n;return((n=e.mining)==null?void 0:n.rule)==="none"?[]:t.roots.filter(r=>r.status==="active"&&Dr(e,r.id)>0&&xe(e.keys,t,r)&&!Np(e,t,r)).slice(0,kp)}function Lp(e,t,n){var i,a;if(((i=e.mining)==null?void 0:i.rule)==="none")return null;if(((a=e.mining)==null?void 0:a.rule)==="last"){const c=n?t.nodes.get(n):null,u=c&&!Np(e,t,c)?g$(e.keys,t,n):null;return u?[{script:u,value:Ge}]:null}const r=yu(e,t),s=r.reduce((c,u)=>c+Dr(e,u.id),0);let o=Ge;return r.length?r.map((c,u)=>{const f=u===r.length-1?o:Math.floor(Ge*Dr(e,c.id)/s);return o-=f,{script:xe(e.keys,t,c).script,value:f}}):null}function yr(e,t,n=xt){const r=t+W,s=u=>u===r||u-r>=we&&u-r<=Ge,o=[...e].sort((u,f)=>u.value-f.value),i=o.find(u=>s(u.value));if(i||n<2)return i?[i]:null;let a=null;for(let u=0;ue.reduce((t,n)=>t+n.value,0);function bu(e,t=xt){let n=0,r=-W;for(const s of e.map(o=>o.value).sort((o,i)=>i-o).slice(0,t)){r+=s;const o=r<=Ge?r:r-Ge>=we?Ge:r-we;o>=we&&r-o<=Ge&&(n=Math.max(n,o))}return n}function xu(e,t,n,r=xt,s="send"){const o=wu(t),i=n+W,a=bu(t,r),c=`${s[0].toUpperCase()}${s.slice(1)}`;if(od.value).sort((d,p)=>p-d),f=u.slice(0,r).map((d,p)=>u.slice(0,p+1).reduce((g,h)=>g+h,0)),l=Math.min(...[...u,...u.flatMap((d,p)=>u.slice(p+1).map(g=>d+g)),...f].filter(d=>d>=i));return Number.isFinite(l)&&l-inew Set((e.offers??[]).flatMap(t=>t.payers.map(n=>`${n.txid}:${n.vout}`))),Hp=(e,t)=>e.chain.coins(t.script).filter(n=>{var r;return!((r=n.inscriptions)!=null&&r.length)}),Rp=(e,t,n=xt)=>!!yr(e,t,n),jp=(e,t,n)=>Rp(Hp(e,t),n);function ku(e,t,n,r,s="This node",o="send"){const i=Hp(e,t),a=vu(e),c=yr(i.filter(d=>!a.has(`${d.txid}:${d.vout}`)),r)??yr(i,r);if(!c)throw new Error(xu(s,i,r,xt,o));const u=wu(c)-r-W,f=X.create({vin:c.map(d=>Fe(d.txid,d.vout,d.value,d.scriptPubKey)),vout:[de(r,n),...u?[de(u,t.script)]:[]]});c.forEach((d,p)=>{f.vin[p].witness=t instanceof mu?t.sign(f,p):[t.sign(f,void 0,p)]});const l=X.encode(f).hex;return e.chain.submitPackage([l]),X.util.getTxid(l)}function Kp(e,t,n,r,s){const o=t.nodes.get(n),i=t.nodes.get(r);if(!o||!i)throw new Error("Pick who sends and who receives.");if(o.id===i.id)throw new Error(`${o.name} cannot send to itself.`);for(const u of[o,i])if(u.status!=="active")throw new Error(`${u.name} is ${u.status}.`);const a=xe(e.keys,t,o),c=xe(e.keys,t,i);if(!a||!c)throw new Error("A holding that predates lab keys has no SegWit addresses.");if(!Number.isSafeInteger(s)||sGe)throw new Error("Send at most 50 test BTC at a time: no output on this chain is bigger than one block reward.");return ku(e,a,c.script,s,o.name)}function m$(e,t,n){if(!t||!n||Se(t.script)===Se(n.script))return 0;let r=0;for(const s of e.chain.coins(t.script)){if(s.value-W{var u;return r||!((u=c.inscriptions)!=null&&u.length)}).sort((c,u)=>u.value-c.value);let o=[],i=0;const a=()=>{const c=o.reduce((u,f)=>u+f.value,0);if(o.length&&c-W>=we){const u=X.create({vin:o.map(f=>Fe(f.txid,f.vout,f.value,f.scriptPubKey)),vout:[de(c-W,n)]});o.forEach((f,l)=>{u.vin[l].witness=r?t.sign(u,l):[t.sign(u,void 0,l)]}),e.chain.submitPackage([X.encode(u).hex]),i++}o=[]};for(const c of s)(o.length===xt||o.reduce((u,f)=>u+f.value,0)+c.value-W>Ge)&&a(),o.push(c);return a(),i}const Dp=(e,t)=>[t,...t.log.flatMap((n,r)=>n.ok&&n.rekeys?[Zt(e.slice(0,r),{pending:!0})]:[])];function Mp(e,t){const n=new Map;for(const r of e)for(const s of r.nodes.values()){const o=t(r,s);o&&!n.has(o)&&n.set(o,s.id)}return n}const y$=(e,t,n)=>Mp(Dp(t,n),(r,s)=>{const o=xe(e,r,s);return o&&Se(o.script)}),ba=new Map,w$=(e,t,n)=>Mp(Dp(t,n),(r,s)=>{const o=un(e,r,s),i=o&&`${e.scheme}|${o.mnemonic}|${o.account}`;return i&&!ba.has(i)&&ba.set(i,Se($e(e,r,s).wallet.script)),i?ba.get(i):null}),$u=(e,t)=>e.coins(t.script).filter(n=>{var r;return!((r=n.inscriptions)!=null&&r.length)}).reduce((n,r)=>n+r.value,0),Vl=new WeakMap,xa=new WeakMap;function ql(e,t){let n=Vl.get(t);if(!n){n=new Map;for(const r of t.nodes.values()){const s=$e(e,t,r),o=s&&Se(s.wallet.script);o&&!n.has(o)&&n.set(o,{node:r.id,wallet:s.wallet})}Vl.set(t,n)}return n}function Pi(e,t,n,r){const s=ql(e,n).get(r);if(s)return s;xa.has(n)||xa.set(n,n.log.flatMap((o,i)=>o.ok&&o.rekeys?[{i,state:null}]:[]));for(const o of xa.get(n)){o.state??(o.state=Zt(t.slice(0,o.i),{pending:!0}));const i=ql(e,o.state).get(r);if(i)return i}return null}function b$(e,t,n=new Map,r=new Map){var a,c;const s=[],o=u=>t.get(Se(u))??null,i=u=>u.reduce((f,l)=>f+l.value,0);for(const{txid:u,tx:f,height:l,coinbase:d}of e.transactions.values()){const p=f.vout.map(b=>({script:Se(b.scriptPubKey),node:o(b.scriptPubKey),value:Number(b.value)}));if(d){p.forEach((b,$)=>{b.node&&s.push({kind:"mine",key:`${u}:${$}`,txid:u,beat:l,from:null,to:b.node,amount:b.value,fee:0,change:0})});continue}const g=f.vin.map(b=>{var T,U;const $=((T=e.transactions.get(b.txid))==null?void 0:T.tx.vout[b.vout])??((U=e.imported)==null?void 0:U.call(e,b.txid,b.vout));return $?{node:o($.scriptPubKey),tank:n.get(Se($.scriptPubKey))??null,value:Number($.value)}:null}),h=r.get(u);if(h!=null&&h.prep)continue;if(h!=null&&h.ask){s.push({kind:"deal",key:u,txid:u,beat:l,from:h.buyer,to:h.seller,amount:h.price,item:h.item,fee:2*W,change:0,ask:!0});continue}if(h&&g.length>1&&g[0]&&g.slice(((a=h.holders)==null?void 0:a.length)??1).every(b=>(b==null?void 0:b.node)===h.buyer)){s.push({kind:"deal",key:u,txid:u,beat:l,from:h.buyer,to:h.seller,amount:h.price,item:h.item,fee:i(g)-i(p),change:i(p.filter(b=>b.node===h.buyer))});continue}if(g.every(b=>b&&!b.node)){const b=p.filter(T=>T.node),$=g[0].tank&&g.every(T=>T.tank===g[0].tank)?g[0].tank:null;b.length&&$?s.push({kind:"pay",key:u,txid:u,beat:l,from:$,to:b[0].node,amount:b[0].value,fee:i(g)-i(p),change:0}):b.length&&s.push({kind:"fund",key:u,txid:u,beat:l,from:null,to:b[0].node,amount:b[0].value,fee:i(g)-i(p),change:i(p.filter(T=>!T.node))});continue}const y=(c=g[0])==null?void 0:c.node;if(!y||!g.every(b=>(b==null?void 0:b.node)===y))continue;const m=p.filter(b=>b.node!==y),x=p.filter(b=>b.node===y),w=i(g)-i(p),P={key:u,txid:u,beat:l,from:y,fee:w};m.length&&m.every(b=>n.get(b.script)===y)?s.push({...P,kind:"gas",to:y,amount:i(m),change:i(x)}):m.length?s.push({...P,kind:"pay",to:m[0].node,amount:m[0].value,change:i(x)}):s.push({...P,kind:"move",to:y,amount:i(x),change:0})}return s}function Qa(e,t,n=1/0){const r=new Map;for(const{txid:o,tx:i,height:a,coinbase:c}of e.transactions.values())if(!(a===null?n!==1/0:a>n)){if(!c)for(const u of i.vin)r.delete(`${u.txid}:${u.vout}`);i.vout.forEach((u,f)=>{const l=t.get(Se(u.scriptPubKey));l&&r.set(`${o}:${f}`,{node:l,value:Number(u.value)})})}const s=new Map;for(const{node:o,value:i}of r.values())s.set(o,(s.get(o)??0)+i);return s}const ec="lineage-offer",tc="lineage-ask",Et=600,ci=xt-1,ui=/^[0-9a-f]{64}$/,Dn=/^[0-9a-f]{64}i0$/,li=/^5120[0-9a-f]{64}$/,nc=/^0014[0-9a-f]{40}$/,x$=/^[0-9a-f]{128}83$/,v$="0".repeat(64),rc=e=>({txid:e.txid,vout:e.vout,value:e.value,script:Se(e.scriptPubKey)}),sc=(e,t)=>!e.utxos.has(`${t.txid}:${t.vout}`),Zs=e=>{const t=Sr(new Vn(e.chain));return{events:t,state:Zt(t,{pending:!0})}},Eu=e=>`${e[0].toUpperCase()}${e.slice(1)}`,Ss=e=>e.reduce((t,n)=>t+n.value,0),k$=e=>Fe(e.txid,e.vout,e.value,e.scriptPubKey);function Ui(e,t,n){var s,o;const r=n?(s=xe(e.keys,t,n))==null?void 0:s.script:(o=e.wallet)==null?void 0:o.script;return r?Se(r):null}function Zp(e){return X.create({vin:[...e.holders,...e.payers].map(t=>Fe(t.txid,t.vout,t.value,t.script)),vout:[de(Ss(e.holders),e.to),...e.price?[de(e.price,e.pay)]:[],...e.change?[de(e.change,e.back)]:[]]})}function Mn(e,t,n,r){const s=Ct(e.chain,r),o=s&&Pi(e.keys,t,n,Se(s.scriptPubKey));return o?{coin:s,node:n.nodes.get(o.node),wallet:o.wallet}:null}function Zn(e,t,n,r){const s=n.items.get(r)??null,o=s?null:n.nodes.get(r)??null;if(!s&&!o)return null;const i=Mn(e,t,n,r),a=s?(i==null?void 0:i.node)??null:o.root===o.id?null:n.nodes.get(o.parent)??null;return{id:r,name:(s??o).name,item:s,node:o,holder:i,seller:a}}function wr(e,t,n,r){var u;if(!(r!=null&&r.holder))return{nodes:[],coins:[],layout:[]};if(r.item)return{nodes:[],coins:[r.holder.coin],layout:[]};const s=Fn(n,r.node.id),o=new Set(s.map(f=>f.id)),i=new Map,a=[],c=f=>{f&&!i.has(`${f.txid}:${f.vout}`)&&i.set(`${f.txid}:${f.vout}`,f)};for(const f of s)c(Ct(e.chain,f.id));for(const f of n.items.keys()){const l=Mn(e,t,n,f);l&&o.has(l.node.id)&&(c(l.coin),a.push([f,l.node.id]))}return{nodes:s,coins:[...i.values()],layout:((u=Ni(e,n,r.id))==null?void 0:u.layout)??a}}function Su(e,t,n,r,s=wr(e,t,n,r)){var f;if(!r.holder)return`no node in this lab holds ${r.name}`;const o=r.holder.coin.inscriptions.map(l=>n.nodes.get(l.id)).find(Boolean);if(o&&o.id!==r.id)return`${r.name} goes with ${o.name}'s tree while it changes hands`;if(r.item)return"";const i=Vt(n.nodes,r.node);if(i)return i;if(r.holder.node.id!==r.node.id)return`${r.name} is held by ${r.holder.node.name}`;const a=new Set(s.nodes.map(l=>l.id)),c=l=>{const d=Ni(e,n,l);return d?Y(d.price):""};for(const l of s.nodes.slice(1)){if(c(l.id))return`${l.name} is listed on its own at ${c(l.id)}. Withdraw its ask first`;const d=Mn(e,t,n,l.id);if(!d||!a.has(d.node.id))return`${l.name} is held by ${(d==null?void 0:d.node.name)??"no node in this lab"}`}for(const[l]of s.layout)if(c(l))return`${n.items.get(l).name} is listed on its own at ${c(l)}. Withdraw its ask first`;for(const l of s.nodes){const d=(f=$e(e.keys,n,l))==null?void 0:f.wallet,p=d&&e.chain.coins(d.script).flatMap(g=>g.inscriptions??[]).map(g=>n.nodes.get(g.id)).find(g=>g&&!a.has(g.id));if(p)return`${l.name} holds ${p.name}, which it bought, and adopts it first`}const u=s.coins.reduce((l,d)=>l+new Set(d.inscriptions.map(p=>tn(d.ranges,p.sat))).size,0);return u>ci?`${r.name}'s tree holds ${u} inscribed sats, and one deal carries ${ci} at most`:""}function Vp(e,t,n,r){var a;const s=n.nodes.get(r),o=(s==null?void 0:s.status)==="active"?Mn(e,t,n,r):null;if(!o)return null;for(let c=s;c;c=c.edge==="derived"?n.nodes.get(c.parent):null)if(c.id===o.node.id)return null;const i=s.edge==="derived"?n.nodes.get(s.parent):null;return i&&((a=Mn(e,t,n,i.id))==null?void 0:a.node.id)===o.node.id?null:o.node}function qp(e,t,n,r,s=Date.now()){const{events:o,state:i}=Zs(e),a=Zn(e,o,i,t),c=i.nodes.get(n);if(!a)throw new Error("Pick an item, an org or a holding to make an offer on.");if(!c)throw new Error("Pick who makes the offer.");if(!Number.isSafeInteger(r)||r<0||r>0&&rGe)throw new Error("Offer at most 50 test BTC: no output on this chain is bigger than one block reward.");const u=wr(e,o,i,a),f=Su(e,o,i,a,u)||(a.node?Vt(i.nodes,a.node,c):"");if(f)throw new Error(`${Eu(f)}.`);const l=a.seller;if((l==null?void 0:l.id)===c.id)throw new Error(`${c.name} already holds ${a.name}.`);for(const b of[c,l])if(b&&b.status!=="active")throw new Error(`${b.name} is ${b.status}.`);const d=xe(e.keys,i,c),p=Ui(e,i,l),g=$e(e.keys,i,c);if(!d||!p||!g)throw new Error("A holding that predates lab keys cannot trade.");if((e.offers??[]).some(b=>b.item===t&&b.buyer===c.id&&Ao(e,i,b,o)==="open"))throw new Error(`${c.name} already has an open offer on ${a.name}. Withdraw it first.`);const h=e.chain.coins(d.script),y=vu(e),m=xt-u.coins.length,x=yr(h.filter(b=>!y.has(`${b.txid}:${b.vout}`)),r,m)??yr(h,r,m);if(!x)throw new Error(xu(c.name,h,r,m,"offer"));const w={kind:ec,version:1,item:t,buyer:c.id,seller:(l==null?void 0:l.id)??null,price:r,holders:u.coins.map(b=>({...rc(b),ids:b.inscriptions.map($=>$.id)})),layout:u.layout,payers:x.map(rc),to:Se(g.wallet.script),pay:p,back:Se(d.script),change:Ss(x)-r-W,at:s},P=Zp(w);return w.txid=X.util.getTxid(P),w.witnesses=x.map((b,$)=>d.sign(P,w.holders.length+$)),(e.offers??(e.offers=[])).push(w),w}function _u(e,t,n,r=null){var d,p,g;const s=t.nodes.get(n.item),o=(s==null?void 0:s.name)??((d=t.items.get(n.item))==null?void 0:d.name)??"the item",i=h=>{var y,m;return((y=t.nodes.get(h))==null?void 0:y.name)??((m=t.items.get(h))==null?void 0:m.name)??null},a=h=>h?Se(h.script):"",c=n.holders.find(h=>sc(e.chain,h));if(c===n.holders[0])return s?`${o}'s inscription has moved since`:`${o} has moved since`;if(c){const h=(p=c.ids)==null?void 0:p.find(y=>i(y));return`${h?t.nodes.has(h)?`${i(h)}'s inscription`:i(h):`something in ${o}'s tree`} has moved since`}if(n.payers.some(h=>sc(e.chain,h)))return`${i(n.buyer)??"the buyer"} has spent a coin the offer promised`;for(const h of[n.buyer,n.seller]){const y=h&&t.nodes.get(h);if(h&&(y==null?void 0:y.status)!=="active")return`${(y==null?void 0:y.name)??"a node"} is ${(y==null?void 0:y.status)??"gone"}`}const u=t.nodes.get(n.buyer),f=n.seller?t.nodes.get(n.seller):null;if(s&&f&&s.parent!==f.id)return`${o} is no longer ${f.name}'s`;if(s&&!f&&s.root!==s.id)return`${o} is no longer a holding`;const l=s?Vt(t.nodes,s,u):"";if(l)return l;if(a((g=$e(e.keys,t,u))==null?void 0:g.wallet)!==n.to||a(xe(e.keys,t,u))!==n.back)return`${u.name} has new keys since`;if(n.price&&Ui(e,t,f)!==n.pay)return f?`${f.name} has new keys since`:"the lab wallet has changed since";if(s){const h=r??Sr(new Vn(e.chain)),y=wr(e,h,t,Zn(e,h,t,n.item)).coins,m=new Set(n.holders.map(x=>`${x.txid}:${x.vout}`));if(y.length!==m.size||y.some(x=>!m.has(`${x.txid}:${x.vout}`)))return`${o}'s tree has changed since`}return""}const Ao=(e,t,n,r=null)=>e.chain.transactions.has(n.txid)?"done":_u(e,t,n,r)?"stale":"open";function $$(e,t,n=null){var f;const r=(e.offers??[]).find(l=>l.txid===t);if(!r)throw new Error("That offer is gone.");if(e.chain.transactions.has(r.txid))throw new Error("That offer was already accepted.");const{events:s,state:o}=Zs(e),i=_u(e,o,r,s);if(i)throw new Error(`This offer is stale: ${i}.`);const a=Zn(e,s,o,r.item);if(!a||(((f=a.seller)==null?void 0:f.id)??null)!==r.seller||Su(e,s,o,a))throw new Error("Only the holder can accept.");n==null||n(o,a);const c=Zp(r),u=r.holders.length;return r.witnesses.forEach((l,d)=>{c.vin[u+d].witness=l}),r.holders.forEach((l,d)=>{c.vin[d].witness=[Pi(e.keys,s,o,l.script).wallet.sign(c,void 0,d)]}),e.chain.submitPackage([X.encode(c).hex]),r}function E$(e,t){const n=(e.offers??[]).find(r=>r.txid===t);if(!n)throw new Error("That offer is gone.");if(e.chain.transactions.has(n.txid))throw new Error("That offer was accepted: it is on the chain now.");return e.offers=e.offers.filter(r=>r!==n),n}const Ar=e=>`${e.holder.txid}:${e.holder.vout}`,S$=e=>X.create({vin:[Fe(v$,0,Et,e.pay),Fe(e.holder.txid,e.holder.vout,e.holder.value,e.holder.script)],vout:[de(Et+e.holder.value,e.holder.script),de(e.price,e.pay)]});function _$(e,t,n,r=Date.now(),s=null){var y;let{events:o,state:i}=Zs(e),a=Zn(e,o,i,t);if(!a)throw new Error("Pick an item, an org or a holding to sell.");if(!Number.isSafeInteger(n)||nGe-W)throw new Error(`Ask at most ${Y(Ge-W)}: the buyer funds the price and its fee in one output.`);const c=wr(e,o,i,a),u=Su(e,o,i,a,c);if(u)throw new Error(`${Eu(u)}.`);const f=a.seller,l=Ui(e,i,f);if(f&&f.status!=="active")throw new Error(`${f.name} is ${f.status}.`);if(!l||!((y=a.holder.wallet)!=null&&y.secret))throw new Error("A holding that predates lab keys cannot trade.");const d=Ni(e,i,t);if(d)throw new Error(`${a.name} is already listed at ${Y(d.price)}. Withdraw that ask first.`);s==null||s(i,a,c),{events:o,state:i}=Zs(e),a=Zn(e,o,i,t);const[p,...g]=wr(e,o,i,a).coins;if(!p||g.length)throw new Error(`${a.name}'s tree is not in one coin at its key.`);const h={kind:tc,version:1,lot:t,seller:(f==null?void 0:f.id)??null,price:n,holder:{...rc(p),ids:p.inscriptions.map(m=>m.id)},layout:c.layout,pay:l,at:r,taken:null};return h.sig=ur.taproot.sign(a.holder.wallet.secret,S$(h),1,{sigflag:131}).hex,(e.asks??(e.asks=[])).push(h),h}function Au(e,t,n){var i;const r=t.nodes.get(n.lot),s=(r==null?void 0:r.name)??((i=t.items.get(n.lot))==null?void 0:i.name)??"the item",o=n.seller?t.nodes.get(n.seller):null;return sc(e.chain,n.holder)?r?`${s}'s inscription has moved since`:`${s} has moved since`:n.seller&&(o==null?void 0:o.status)!=="active"?`${(o==null?void 0:o.name)??"the seller"} is ${(o==null?void 0:o.status)??"gone"}`:Ui(e,t,o)!==n.pay?o?`${o.name} has new keys since`:"the lab wallet has changed since":r&&o&&r.parent!==o.id?`${s} is no longer ${o.name}'s`:r&&!o&&r.root!==r.id?`${s} is no longer a holding`:r?Vt(t.nodes,r):""}const Bu=(e,t,n)=>n.taken&&e.chain.transactions.has(n.taken.txid)?"done":Au(e,t,n)?"stale":"open",Ni=(e,t,n)=>(e.asks??[]).find(r=>r.lot===n&&Bu(e,t,r)==="open")??null;function A$(e,t,n,r=Date.now()){const s=(e.asks??[]).find(T=>Ar(T)===t);if(!s)throw new Error("That ask is gone.");if(s.taken)throw new Error("That ask was already taken.");const{state:o}=Zs(e),i=Au(e,o,s),a=o.nodes.get(n);if(i)throw new Error(`This ask is stale: ${i}.`);if(!a)throw new Error("Pick who takes the ask.");if(a.status!=="active")throw new Error(`${a.name} is ${a.status}.`);if(a.id===s.seller)throw new Error(`${a.name} is the seller.`);const c=o.nodes.get(s.lot),u=c?Vt(o.nodes,c,a):"";if(u)throw new Error(`${Eu(u)}.`);const f=xe(e.keys,o,a),l=$e(e.keys,o,a);if(!f||!l)throw new Error("A holding that predates lab keys cannot trade.");const d=e.chain.coins(f.script),p=vu(e),g=Et+s.price+W,h=yr(d.filter(T=>!p.has(`${T.txid}:${T.vout}`)),g)??yr(d,g);if(!h)throw Ss(d){x.vin[U].witness=f.sign(x,U)});const w=X.encode(x).hex,P=X.util.getTxid(w),b=X.create({vin:[Fe(P,0,Et,m),Fe(s.holder.txid,s.holder.vout,s.holder.value,s.holder.script),Fe(P,1,s.price+W,m)],vout:[de(Et+s.holder.value,l.wallet.script),de(s.price,s.pay)]});b.vin[1].witness=[s.sig],b.vin[0].witness=f.sign(b,0),b.vin[2].witness=f.sign(b,2);const $=X.encode(b).hex;return e.chain.submitPackage([w,$]),s.taken={txid:X.util.getTxid($),prep:P,buyer:a.id,at:r},s}function zl(e,t){const n=(e.asks??[]).find(r=>Ar(r)===t);if(!n)throw new Error("That ask is gone.");if(n.taken)throw new Error("That ask was taken: it is on the chain now.");return e.asks=e.asks.filter(r=>r!==n),n}function B$(e){const t=(e.asks??[]).filter(n=>n.taken).flatMap(n=>[[n.taken.txid,{ask:!0,buyer:n.taken.buyer,seller:n.seller,price:n.price,item:n.lot,ids:n.holder.ids??[n.lot]}],[n.taken.prep,{prep:!0}]]);return new Map([...(e.offers??[]).map(n=>[n.txid,n]),...t])}const oc=(e,t)=>e&&ui.test(e.txid)&&Number.isSafeInteger(e.vout)&&e.vout>=0&&Number.isSafeInteger(e.value)&&e.value>=we&&e.value<=Ge&&t.test(e.script),zp=e=>e===void 0||Array.isArray(e)&&e.length<=1024&&e.every(t=>Dn.test(t)),Fp=e=>e===void 0||Array.isArray(e)&&e.length<=ci&&e.every(t=>Array.isArray(t)&&t.length===2&&Dn.test(t[0])&&Dn.test(t[1])),Wp=(e,t)=>e===null?li.test(t):Dn.test(e)&&nc.test(t);function T$(e){const t=r=>Number.isSafeInteger(r)&&(r===0||r>=we&&r<=Ge),n=Array.isArray(e==null?void 0:e.holders)?e.holders:e!=null&&e.holder?[e.holder]:[];if((e==null?void 0:e.kind)!==ec||e.version!==1||!Dn.test(e.item)||!Dn.test(e.buyer)||!Wp(e.seller,e.pay)||e.buyer===e.seller||!t(e.price)||!t(e.change)||!n.length||n.length>ci||!n.every(r=>oc(r,li)&&zp(r.ids))||!Array.isArray(e.payers)||!e.payers.length||n.length+e.payers.length>xt||!e.payers.every(r=>oc(r,nc))||!li.test(e.to)||!nc.test(e.back)||!Fp(e.layout)||!ui.test(e.txid)||!Array.isArray(e.witnesses)||e.witnesses.length!==e.payers.length||!e.witnesses.every(r=>Array.isArray(r)&&r.length===2&&/^30[0-9a-f]{12,140}01$/.test(r[0])&&/^0[23][0-9a-f]{64}$/.test(r[1]))||!Number.isSafeInteger(e.at))throw new Error("Invalid offer.");return{kind:ec,version:1,item:e.item,buyer:e.buyer,seller:e.seller,price:e.price,holders:n.map(r=>({txid:r.txid,vout:r.vout,value:r.value,script:r.script,...r.ids?{ids:[...r.ids]}:{}})),layout:(e.layout??[]).map(r=>[...r]),payers:e.payers.map(r=>({...r})),to:e.to,pay:e.pay,back:e.back,change:e.change,at:e.at,txid:e.txid,witnesses:e.witnesses.map(r=>[...r])}}function O$(e){const t=e==null?void 0:e.taken;if((e==null?void 0:e.kind)!==tc||e.version!==1||!Dn.test(e.lot)||!Wp(e.seller,e.pay)||!Number.isSafeInteger(e.price)||e.priceGe-W||!oc(e.holder,li)||!zp(e.holder.ids)||!Fp(e.layout)||typeof e.sig!="string"||!x$.test(e.sig)||!Number.isSafeInteger(e.at)||!(t===null||t&&ui.test(t.txid)&&ui.test(t.prep)&&Dn.test(t.buyer)&&Number.isSafeInteger(t.at)))throw new Error("Invalid ask.");return{kind:tc,version:1,lot:e.lot,seller:e.seller,price:e.price,holder:{txid:e.holder.txid,vout:e.holder.vout,value:e.holder.value,script:e.holder.script,...e.holder.ids?{ids:[...e.holder.ids]}:{}},layout:(e.layout??[]).map(n=>[...n]),pay:e.pay,at:e.at,sig:e.sig,taken:t?{txid:t.txid,prep:t.prep,buyer:t.buyer,at:t.at}:null}}const Li="orgchain:lab:v1",I$=["each",10,30,60,"manual"];function eo(e={tempo:"each",nextAt:null}){const{tempo:t,nextAt:n}=e??{},r=typeof t=="number";if(!I$.includes(t)||!(n===null||r&&Number.isSafeInteger(n)&&n>0))throw new Error("Invalid clock.");return{tempo:t,nextAt:n}}function Gp(e){const t=hu();for(const n of["roots","adopted"])for(const[r,s]of Object.entries((e==null?void 0:e[n])??{})){if(!/^[0-9a-f]{64}i0$/.test(r))throw new Error("Invalid lab keys.");t[n][r]=cp(s,24)}if(t.scheme=(e==null?void 0:e.scheme)??(Object.keys(t.roots).length?"wallet":"bip86"),!o$.includes(t.scheme))throw new Error("Invalid lab keys.");return t}const C$=["split","last","none"];function to(e){const t=(e==null?void 0:e.rule)??"split",n={};if(!C$.includes(t))throw new Error("Invalid mining rule.");for(const[r,s]of Object.entries((e==null?void 0:e.rigs)??{})){if(!/^[0-9a-f]{64}i0$/.test(r)||!Number.isSafeInteger(s)||s<0||s>9)throw new Error("Invalid hashrate.");s!==1&&(n[r]=s)}return{rule:t,rigs:n}}function Yp(e=[]){if(!Array.isArray(e)||e.length>1e3)throw new Error("Invalid offers.");const t=e.map(T$);if(new Set(t.map(n=>n.txid)).size!==t.length)throw new Error("Invalid offers.");return t}function Xp(e=[]){if(!Array.isArray(e)||e.length>1e3)throw new Error("Invalid asks.");const t=e.map(O$);if(new Set(t.map(Ar)).size!==t.length)throw new Error("Invalid asks.");return t}const no=()=>({wallet:null,chain:new Bi,clock:eo(),keys:hu(),mining:to(),offers:[],asks:[]});function Jp(e){if(!e)return no();const t=JSON.parse(e);if((t==null?void 0:t.kind)!=="orgchain-lab"||t.network!==On||t.version!==1)throw new Error("That is not an Orgchain v1 lab.");return{wallet:t.wallet?Kn.load(t.wallet):null,chain:new Bi(t.chain),clock:eo(t.clock),keys:Gp(t.keys),mining:to(t.mining),offers:Yp(t.offers),asks:Xp(t.asks)}}const Qp=e=>{var t;return JSON.stringify({kind:"orgchain-lab",network:On,version:1,wallet:((t=e.wallet)==null?void 0:t.backup())??null,chain:e.chain.snapshot(),clock:eo(e.clock),keys:Gp(e.keys),mining:to(e.mining),offers:Yp(e.offers),asks:Xp(e.asks)})};function P$(e,t,n){var r;e.mining=to({...e.mining,rigs:{...(r=e.mining)==null?void 0:r.rigs,[t]:n}})}function U$(e,t){e.mining=to({...e.mining,rule:t})}const Tu=()=>Jp(localStorage.getItem(Li));function N$(e){try{localStorage.setItem(Li,Qp(e))}catch{throw new Error("Browser storage is full or unavailable, so nothing was saved. Save a backup, then reset.")}}async function L$(e,{locks:t=(s=>(s=globalThis.navigator)==null?void 0:s.locks)(),read:n=Tu,save:r=N$}={}){if(!t)throw new Error("Orgchain needs Web Locks: open it over HTTPS or on localhost.");return t.request(Li,async()=>{const o=n(),i=await e(o);return i!==!1&&r(o),{lab:o,result:i}})}function at(e,t=null){e.wallet||(e.wallet=Kn.create());const n=t!=null&&t.length?e.chain.mineTo(t.map(r=>de(r.value,r.script))):e.chain.mine(e.wallet.script);return e.clock=eo({tempo:e.clock.tempo,nextAt:null}),n}function Wt(e,t=Date.now()){const{tempo:n,nextAt:r}=e.clock;typeof n=="number"&&e.chain.mempool.length&&r===null&&(e.clock={tempo:n,nextAt:t+n*1e3})}function H$(e,t,n=Date.now(),r=null){e.clock=eo({tempo:t,nextAt:null}),t==="each"&&e.chain.mempool.length?at(e,r):Wt(e,n)}function R$(e,t=Date.now(),n=null){const{tempo:r,nextAt:s}=e.clock;return typeof r!="number"||!e.chain.mempool.length?!1:s===null?(Wt(e,t),!0):tFe(e.txid,e.vout,e.value,e.scriptPubKey);function j$(e,{inscriber:t,holder:n,parent:r,on:s,value:o,metadata:i,metaprotocol:a}){const c=Ct(e,s),u=Ct(e,r);if(!c||!u)throw new Error("Both inscriptions must be unspent.");if(c===u)throw new Error("A belt goes on another node's sat.");const f=e.coins(t.script).find(w=>{var P;return!((P=w.inscriptions)!=null&&P.length)&&w.value>=ic+330});if(!f)throw new Error("The issuer needs a plain coin for the two fees.");const l=tn(c.ranges,c.inscriptions.find(w=>w.id===s).sat),d=qc(t.pubkey,o,r,i,{pointer:l,metaprotocol:a}),p=ch(d),[g,h]=Fs.getPubKey(t.pubkey,{target:p}),y=X.create({vin:[va(f)],vout:[de(W,["OP_1",g]),de(f.value-ic,t.script)]});y.vin[0].witness=[t.sign(y)];const m=X.util.getTxid(y),x=X.create({vin:[va(c),va(u),Fe(m,0,W,["OP_1",g])],vout:[de(c.value,c.scriptPubKey),de(u.value,u.scriptPubKey)]});return x.vin[2].witness=[t.sign(x,p,2),Ce.encode(d,!1).hex,h],x.vin[1].witness=[t.sign(x,void 0,1)],x.vin[0].witness=[n.sign(x,void 0,0)],e.submitPackage([X.encode(y).hex,X.encode(x).hex]),`${X.util.getTxid(x)}i0`}const e0={reinscription:"♻️",vindicated:"❤️‍🔥"};function K$(e,t,n){const r=i=>{var u;const a=(u=e.transactions.get(i.id.slice(0,-2)))==null?void 0:u.tx;return(a?a.vin.findIndex(f=>{var l;return((l=f.witness)==null?void 0:l.length)===3}):0)>0||i.pointer!==void 0},s=t.events.find(i=>i.sat===n.sat),o=s&&s.id!==n.id;return[...o?["reinscription"]:[],...r(n)||o&&!r(s)?["vindicated"]:[]]}const Fl={found:["name"],birth:["name","kind"],award:["to","skill","belt"],decide:["title","why"],make:["name","note"],keyring:It,charter:["form","of","jurisdiction","legal","provider","filing"],graduate:["of"],close:[],join:["to"],adopt:["of"]},t0={found:e=>`found ${e.name}`,birth:e=>`birth ${e.name}`,award:e=>`award ${e.skill} ${e.belt}`,decide:e=>`decide ${e.title}`,make:e=>`make ${e.name}`,keyring:(e,t)=>_i(t,e),charter:e=>`charter ${e.form}${e.jurisdiction?` ${e.jurisdiction}`:""}`,graduate:()=>"graduate",close:()=>"close",join:()=>"join",adopt:()=>"adopt"};function D$(e,t={}){if(!Object.hasOwn(Fl,e))throw new Error("Unknown verb.");const n={op:e};for(const s of Fl[e]){const o=t[s];typeof o=="string"&&o.trim()&&(n[s]=o.trim())}const r=e==="keyring"&&t.proof&&typeof t.proof=="object"?t.proof:null;return r&&(n.proof=Object.fromEntries(It.filter(s=>typeof r[s]=="string").map(s=>[s,r[s]]))),n}function n0(e,t){const n=Re(e),r=n.nodes.get(t),s=r&&c$(e.keys,n,r);if(!s)throw new Error(`${(r==null?void 0:r.name)??"That node"} predates lab keys, so it has no keys to list.`);return hk(t,s.keys,s.secrets)}function Ou(e,t,n,r={}){if(t==="keyring"){for(let s=e.nodes.get(n);s;s=s.edge==="derived"?e.nodes.get(s.parent):null)if(s.graduated==="cued")return`${s.name}'s graduation is cued, and it changes ${s.id===n?"its":`${e.nodes.get(n).name}'s`} keys. Publish the keyring once it lands`}if(t==="graduate"&&e.nodes.has(r.of)){const s=new Set(Fn(e,r.of).map(i=>i.id)),o=e.log.find(i=>i.pending&&i.ok&&i.op==="keyring"&&s.has(i.node));if(o)return`${e.nodes.get(o.node).name}'s keyring is cued. Graduate ${e.nodes.get(r.of).name} once it lands, so the graduation retires it`}return""}const Re=e=>Zt(Sr(new Vn(e.chain)),{pending:!0}),Hi=e=>{const t=Sr(new Vn(e.chain));return{events:t,state:Zt(t,{pending:!0})}};function fi(e,t,n,r){const s=D$(t,r),o=Sr(new Vn(e.chain)),i={id:"check",status:"pending",height:null,metadata:s,parent:n??null,protocol:Ai},{ok:a,why:c}=Zt([...o,i],{pending:!0}).log.at(-1);if(!a)throw new Error(`${c[0].toUpperCase()}${c.slice(1)}.`);return s}const ac=Rt+2*W+330,r0=1e5,Ri=1e4,rn=(e,t=0)=>(e==="award"?ic:Rt+2*W+(e==="birth"||e==="join"?1:e==="graduate"?Math.max(0,t-1):0)*W)+330,M$=(e,t=0)=>rn(e,t)-330,ln=(e,t,n)=>e.chain.coins(t.script).find(r=>{var s;return!((s=r.inscriptions)!=null&&s.length)&&r.value>=n}),ns=e=>Fe(e.txid,e.vout,e.value,e.scriptPubKey),ji=(e,t)=>(t.forEach((n,r)=>{e.vin[r].witness=[n.sign(e,void 0,r)]}),X.encode(e).hex);function ro(e){e.keys??(e.keys=hu()),e.wallet||(e.wallet=Kn.create()),ln(e,e.wallet,r0+W+330)||at(e)}function s0(e,t,n=ac,r=r0){if(t===e.wallet||ln(e,t,n))return;const s=ln(e,e.wallet,r+W+330),o=X.create({vin:[ns(s)],vout:[de(r,t.script),de(s.value-r-W,e.wallet.script)]});e.chain.submitPackage([ji(o,[e.wallet])])}function ar(e,t,n,r,s){if(r===e.wallet||ln(e,r,s))return;const o=n&&xe(e.keys,t,n);if(!o)return s0(e,r,s);ku(e,o,r.script,Math.max(Ri,s),n.name)}function Iu(e,t,n,r,s){if(r===e.wallet||ln(e,r,s))return!0;const o=n&&xe(e.keys,t,n);return!o||jp(e,o,Math.max(Ri,s))}function Cu(e,t,n,r,s={}){var f,l;const o=r?t.nodes.get(r):null,i=o&&((f=Ii(e,t,r))==null?void 0:f.wallet);if(n==="found"||!i)return"";const a=n==="graduate"?t.nodes.get(s.of):null,c=a&&$e(e.keys,t,a)?Fn(t,a.id).length:0;if(!Iu(e,t,o,i,rn(n,c))){const d=t.nodes.get(o.parent);return`${o.name} has no test BTC for gas. ${d?`${d.name} can send some`:((l=e.mining)==null?void 0:l.rule)==="none"?"Fund it from the lab wallet":"It earns some each beat it mines"}`}const u=c?xe(e.keys,t,a):null;return u&&!Rp(e.chain.coins(u.script).filter(d=>d.value-W>=we).map(d=>({value:d.value-W})),Ri)?`${a.name} needs test BTC of its own to claim its new root. Send it some first`:""}function Wl(e,t,n,r,s=n){const o=Ct(e.chain,t),i=ln(e,s,W+330),a=X.create({vin:[ns(o),ns(i)],vout:[de(o.value,r.script),de(i.value-W,s.script)]});e.chain.submitPackage([ji(a,[n,s])])}function di(e,t,n,r,s){return new p2(e.chain,t).inscribe(t0[n](s,r),r??null,s,{metaprotocol:Ai})}const Wn=(e,t)=>{var r;const n=Re(e);return Lp(e,n,((r=n.nodes.get(t))==null?void 0:r.root)??null)},Ki=(e,t)=>Lp(e,Re(e),t);function Pu(e){var r,s,o;const t=Re(e),n=new Map;for(const i of t.nodes.values())for(const a of[xe(e.keys,t,i),(r=$e(e.keys,t,i))==null?void 0:r.wallet])a&&n.set(Se(a.script),i.root);for(const i of[...e.chain.mempool].reverse()){const a=e.chain.transactions.get(X.util.getTxid(i));if(a!=null&&a.inscription){const c=(s=t.log.find(u=>u.id===a.inscription.id))==null?void 0:s.root;if(c)return c;continue}for(const c of(a==null?void 0:a.tx.vin)??[]){const u=((o=e.chain.transactions.get(c.txid))==null?void 0:o.tx.vout[c.vout])??e.chain.imported(c.txid,c.vout),f=u&&n.get(Se(u.scriptPubKey));if(f)return f}}return null}function rs(e,t,n){var s;const r=Ii(e,t,n);if(!(r!=null&&r.wallet))throw new Error(`No key in this lab holds ${((s=t.nodes.get(n))==null?void 0:s.name)??"that node"}'s inscription.`);return r.wallet}function o0(e,t,n,r){var l,d;if(t==="found"){const p=Bl(),g=a$(e.keys,p);s0(e,g,ac,ac);const h=di(e,g,t,null,r);return e.keys.roots[h]=p,h}const s=Re(e),o=rs(e,s,n),i=s.nodes.get(n),a=t==="graduate"?s.nodes.get(r.of):null,c=a&&$e(e.keys,s,a)?Fn(s,a.id).map(p=>[p.id,rs(e,s,p.id)]):[],u=t==="award"?(l=Ii(e,s,r.to))==null?void 0:l.wallet:null;if(t==="award"&&!u)throw new Error(`No key in this lab holds ${((d=s.nodes.get(r.to))==null?void 0:d.name)??"the recipient"}'s inscription, so it can't take a belt.`);ar(e,s,i,o,rn(t,c.length));const f=t==="award"?j$(e.chain,{inscriber:o,holder:u,parent:n,on:r.to,value:t0.award(r),metadata:r,metaprotocol:Ai}):di(e,o,t,n,r);if(t==="birth"){const p=Re(e),g=$e(e.keys,p,p.nodes.get(f));g&&Wl(e,f,o,g.wallet)}if(c.length){e.keys.adopted[f]=Bl();const p=Re(e);for(const[g,h]of c){const y=$e(e.keys,p,p.nodes.get(g)).wallet;if(m$(e,xe(e.keys,s,s.nodes.get(g)),xe(e.keys,p,p.nodes.get(g))),g!==a.id){Wl(e,g,h,y,o);continue}ar(e,p,p.nodes.get(g),y,W+330),Tk(e.chain,Bk(e.chain,g,y),h)}}return f}function Z$(e,t,n,r,s=Date.now()){if(t==="join"||t==="adopt")throw new Error("An org or a holding changes hands through Sell and Buy, and its buyer adopts it.");const o=qt(e,Re(e),t,n??null,r??{});if(o)throw new Error(`${o}.`);const i=Ou(Re(e),t,n??null,r??{});if(i)throw new Error(`${i}.`);const a=fi(e,t,n,t==="keyring"?n0(e,n):r),c=Cu(e,Re(e),t,n??null,a);if(c)throw new Error(`${c}.`);ro(e);const u=o0(e,t,n??null,a);return e.clock.tempo==="each"?at(e,Wn(e,n??u)):Wt(e,s),u}function V$(e,t,n,r,s=Date.now()){const o=qt(e,Re(e),"send",t)||qt(e,Re(e),"send",n);if(o)throw new Error(`${o}.`);const i=Kp(e,Re(e),t,n,r);return e.clock.tempo==="each"?at(e,Wn(e,t)):Wt(e,s),i}function q$(e,t,n,r,s=Date.now()){const o=qt(e,Re(e),"offer",n);if(o)throw new Error(`${o}.`);return qp(e,t,n,r,s)}function z$(e,t,n=Date.now()){const r=$$(e,t,(s,o)=>{o.node&&i0(e,s,o)});return e.clock.tempo==="each"?at(e,Wn(e,r.seller??r.item)):Wt(e,n),r}const F$=(e,t)=>E$(e,t);function qt(e,t,n,r,s={},o=Sr(new Vn(e.chain))){const i=u=>{const f=Ni(e,t,u.id),l=f?null:Vp(e,o,t,u.id);return f?`${u.name} is listed for sale at ${Y(f.price)}. Withdraw its ask first`:l?`${u.name} was sold to ${l.name}, which adopts it next`:""},a=u=>{const f=[];for(let l=u?t.nodes.get(u):null;l;l=l.edge==="derived"?t.nodes.get(l.parent):null)f.unshift(l);return f},c=t.nodes.get(n==="graduate"?s.of:n==="close"?r:null);for(const u of[...a(r),...n==="award"?a(s.to):[],...c?Fn(t,c.id):[]]){const f=i(u);if(f)return f}return""}function i0(e,t,n){var o,i,a;const r=n.seller?(o=xe(e.keys,t,n.seller))==null?void 0:o.script:(i=e.wallet)==null?void 0:i.script,s=c=>[c,..._r(t.nodes,c).filter(u=>u.edge==="derived").flatMap(s)];if(r)for(const c of s(n.node)){const u=(a=$e(e.keys,t,c))==null?void 0:a.wallet,f=xe(e.keys,t,c);u&&Zl(e,u,r),f&&Zl(e,f,r)}}function W$(e,t,n){const{events:r,state:s}=Hi(e),o=Zn(e,r,s,t),{coins:i}=wr(e,r,s,o);if(i.length<2)return;const a=$e(e.keys,s,o.node).wallet,c=ln(e,n,W+we);if(!c)throw new Error(`There is no test BTC for the fee that bundles ${o.name}'s tree.`);const u=i.map(l=>Pi(e.keys,r,s,Se(l.scriptPubKey)).wallet),f=X.create({vin:[...i,c].map(ns),vout:[de(i.reduce((l,d)=>l+d.value,0),a.script),de(c.value-W,n.script)]});e.chain.submitPackage([ji(f,[...u,n])])}function a0(e,t,n,r,s,o,i){var g;const a=new Set(Fn(t,s.id).map(h=>h.id)),c=new Map(o),u=h=>{const y=t.nodes.get(a.has(h)?h:c.get(h));return $e(e.keys,t,y&&a.has(y.id)?y:s).wallet.script},f=[];for(const{id:h,offset:y}of n.inscriptions.map(m=>({id:m.id,offset:tn(n.ranges,m.sat)})).sort((m,x)=>m.offset-x.offset))((g=f.at(-1))==null?void 0:g.offset)===y?f.at(-1).ids.push(h):f.push({offset:y,ids:[h]});const l=f.map((h,y)=>{var m;return[(((m=f[y+1])==null?void 0:m.offset)??n.value)-(y?h.offset:0),u(h.ids.find(x=>t.nodes.has(x))??h.ids[0])]});if(l.some(([h])=>hde(h,y)),de(d.value-W,i.script)]});e.chain.submitPackage([ji(p,[r,i])])}function c0(e,t,n,r=[]){const{events:s,state:o}=Hi(e),i=o.nodes.get(t),a=o.nodes.get(n),c=Mn(e,s,o,t);if(!i||!a||(c==null?void 0:c.node.id)!==a.id)throw new Error(`${(a==null?void 0:a.name)??"That node"} does not hold ${(i==null?void 0:i.name)??"that org"}.`);const u=rs(e,o,a.id),f=c.wallet,l=fi(e,"adopt",a.id,{of:i.id});if(!Iu(e,o,a,u,rn("adopt")+rn("join")))throw new Error(`${a.name} has no test BTC for gas.`);ar(e,o,a,u,rn("adopt")),di(e,u,"adopt",a.id,l);const d=fi(e,"join",i.id,{to:a.id});ar(e,o,a,f,rn("join")),di(e,f,"join",i.id,d);const p=Re(e);ar(e,p,p.nodes.get(a.id),f,W+we),a0(e,p,Ct(e.chain,i.id),f,p.nodes.get(i.id),r,f)}function G$(e,t,n,r){const s=t.nodes.get(r),o=t.nodes.get(n.lot),i=s&&xe(e.keys,t,s);if(!o||!i)return"";const a=Vt(t.nodes,o,s);if(a)return`${a[0].toUpperCase()}${a.slice(1)}`;const c=rs(e,t,s.id),u=rn("adopt")+rn("join"),f=n.price+Et+2*W+(ln(e,c,u)?0:Ri+W),l=e.chain.balance(i.script);return l{if(!p.node)return;const h=p.seller?rs(e,d,p.seller.id):e.wallet,y=g.coins.length>1;if(y&&p.seller&&!Iu(e,d,p.seller,h,W+we))throw new Error(`${p.seller.name} has no test BTC for the fee that bundles ${p.name}'s tree.`);i0(e,d,p),y&&(p.seller&&ar(e,Re(e),p.seller,h,W+we),W$(e,p.id,h))});return e.chain.mempool.length>c&&(e.clock.tempo==="each"?at(e,Wn(e,u.seller??u.lot)):Wt(e,r)),u}function Y$(e,t,n=Date.now()){var u;const r=(e.asks??[]).find(f=>Ar(f)===t);if(!r||r.taken||!(((u=e.chain.utxos.get(t))==null?void 0:u.inscriptions.length)>1))return zl(e,t);r.seller||ro(e);const{events:s,state:o}=Hi(e),i=e.chain.utxos.get(t),a=r.seller?o.nodes.get(r.seller):null,c=a?rs(e,o,a.id):e.wallet;return a&&ar(e,o,a,c,W+we),a0(e,o,i,Pi(e.keys,s,o,Se(i.scriptPubKey)).wallet,o.nodes.get(r.lot),r.layout??[],c),zl(e,t),e.clock.tempo==="each"?at(e,Wn(e,r.seller??r.lot)):Wt(e,n),r}function X$(e,t,n,r=Date.now()){const s=Re(e),o=(e.asks??[]).find(a=>Ar(a)===t),i=qt(e,s,"take",n)||(o&&!o.taken?G$(e,s,o,n):"");if(i)throw new Error(`${i}.`);return A$(e,t,n,r),s.nodes.has(o.lot)&&c0(e,o.lot,n,o.layout??[]),e.clock.tempo==="each"?at(e,Wn(e,n)):Wt(e,r),o}function J$(e,t,n,r=Date.now()){var i;const s=qt(e,Re(e),"adopt",n);if(s)throw new Error(`${s}.`);const o=[...(e.offers??[]).filter(a=>a.item===t&&a.buyer===n&&e.chain.transactions.has(a.txid)).map(a=>[a.at,a.layout]),...(e.asks??[]).filter(a=>{var c;return a.lot===t&&((c=a.taken)==null?void 0:c.buyer)===n}).map(a=>[a.taken.at,a.layout])].sort((a,c)=>a[0]-c[0]);c0(e,t,n,((i=o.at(-1))==null?void 0:i[1])??[]),e.clock.tempo==="each"?at(e,Wn(e,n)):Wt(e,r)}function Q$(e,t,n,r=Date.now()){const s=Re(e),o=s.nodes.get(t);if(!o||o.root!==o.id)throw new Error("Pick a holding to fund.");if(o.status!=="active")throw new Error(`${o.name} is closed.`);const i=qt(e,s,"fund",o.id);if(i)throw new Error(`${i}.`);const a=xe(e.keys,s,o);if(!a)throw new Error("A holding that predates lab keys has no SegWit address to fund.");if(!Number.isSafeInteger(n)||nGe)throw new Error("Fund at most 50 test BTC at a time: no output on this chain is bigger than one block reward.");ro(e),jp(e,e.wallet,n)||at(e);const c=ku(e,e.wallet,a.script,n,"The lab wallet","fund");return e.clock.tempo==="each"?at(e,Wn(e,t)):Wt(e,r),c}const cc="yolopreneur",eE=[[["found",null,{name:"yolopreneur"}]],[["birth","yolopreneur",{name:"well-known",kind:"org"}],["birth","yolopreneur",{name:"time",kind:"org"}],["keyring","yolopreneur",{}],["charter","yolopreneur",{form:"series-llc",jurisdiction:"US-WY",legal:"Yolopreneur Holdings LLC",provider:"doola"}]],[["send","yolopreneur",{to:"time",amount:40}],["send","yolopreneur",{to:"well-known",amount:10}],["birth","well-known",{name:"mailr",kind:"org"}],["birth","well-known",{name:"lineage",kind:"org"}],["birth","time",{name:"luna",kind:"agent"}],["birth","time",{name:"sol",kind:"agent"}],["birth","time",{name:"astra",kind:"agent"}],["charter","yolopreneur",{form:"series",of:"well-known"}],["charter","yolopreneur",{form:"series",of:"time"}]],[["send","well-known",{to:"lineage",amount:2}],["birth","time",{name:"docscope",kind:"org"}],["birth","time",{name:"dollhouse",kind:"org"}],["birth","time",{name:"doodleloop",kind:"org"}],["birth","time",{name:"hearthframe",kind:"org"}],["charter","yolopreneur",{form:"series",of:"lineage"}]],[["send","time",{to:"sol",amount:1}],["send","time",{to:"luna",amount:.5}],["award","time",{to:"sol",skill:"launch",belt:"green"}],["award","time",{to:"luna",skill:"post",belt:"white"}],["decide","yolopreneur",{title:"Every venture gets a page",why:".yolopreneur.lol, served from one pages branch."}],["make","sol",{name:"launch-kit",note:"The page, the post and the checklist every venture launches with."}],["keyring","sol",{}],["keyring","lineage",{}]],[["graduate","well-known",{of:"lineage"}],["decide","lineage",{title:"Lineage gets its own org",why:"Its own repo on Teahub now, lineage.llc later: adopted, not derived."}],["charter","lineage",{form:"llc",jurisdiction:"US-WY",legal:"Lineage LLC",provider:"doola"}],["offer","lineage",{item:"launch-kit",price:.1}],["sell","well-known",{lot:"mailr",price:1}]]];function tE(e){ro(e),e.chain.mempool.length&&at(e);const t={},n={};for(const r of eE){for(const[s,o,i]of r){if(s==="send"){Kp(e,Re(e),t[o],t[i.to],i.amount*Kr);continue}if(s==="offer"){qp(e,n[i.item],t[o],i.price*Kr);continue}if(s==="sell"){u0(e,t[i.lot]??n[i.lot],i.price*Kr);continue}const a=s==="keyring"?n0(e,t[o]):Object.fromEntries(Object.entries(i).map(([f,l])=>[f,f==="to"||f==="of"?t[l]:l])),c=o?t[o]:null,u=o0(e,s,c,fi(e,s,c,a));(s==="found"||s==="birth")&&(t[i.name]=u),s==="make"&&(n[i.name]=u)}at(e,Ki(e,t[cc]))}return t[cc]}const R=e=>document.getElementById(e);function E(e,t={},...n){const r=document.createElement(e);for(const[s,o]of Object.entries(t))o==null||o===!1||(s==="class"?r.className=o:s==="text"?r.textContent=o:s.startsWith("on")?r.addEventListener(s.slice(2),o):r.setAttribute(s,o===!0?"":String(o)));for(const s of n.flat(1/0))s!=null&&s!==!1&&s!==""&&r.append(s instanceof Node?s:String(s));return r}const Cn=(e,t)=>`${e} ${t}${e===1?"":"s"}`,mt=e=>e==="cued"?"cued":`beat ${e}`,nE=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}),Gl=e=>JSON.stringify(e,(t,n)=>typeof n=="bigint"?String(n):n,2),I={holding:null,node:null,event:null,tx:null,beat:null,verb:"birth",busy:!1,replay:null,closing:null,reveal:null};let Z=no(),ss=new Vn(Z.chain),Ze=[],j=Zt([]),Ee=j,ze={owner:new Map,ledger:[],now:new Map,view:new Map},At=new Map;const lt=()=>Z.chain.blocks.length,uc=()=>Ze.filter(e=>e.status==="pending").length,lc=e=>ze.ledger.filter(t=>t.beat===null&&t.kind===e).length,Bo=[["pay","cued send"],["deal","cued deal"],["fund","cued deposit"]],rE=()=>uc()+Bo.reduce((e,[t])=>e+lc(t),0),Ne=e=>{var t,n;return((t=j.items.get(e))==null?void 0:t.name)??((n=j.nodes.get(e))==null?void 0:n.name)??"an item"},To=()=>Z.offers??[],Uu=()=>Z.asks??[];let ot=new Map,dt=new Map,ft=new Map,fc=new Map;const sE=e=>{var t,n;return((t=ot.get(e))==null?void 0:t.layout)??((n=[...To().filter(r=>r.item===e&&Z.chain.transactions.has(r.txid)).map(r=>[r.at,r.layout]),...Uu().filter(r=>r.lot===e&&r.taken).map(r=>[r.taken.at,r.layout])].sort((r,s)=>r[0]-s[0]).at(-1))==null?void 0:n[1])??[]},l0=e=>e?ke(e):"its owner, the lab wallet",Oo=e=>ze.view.get(e)??0,f0=e=>ze.now.get(e)??0,V=(e,t=j)=>e?t.nodes.get(e)??null:null,oE=e=>{var t;return!!e&&(e.root===I.holding||((t=V(e.parent))==null?void 0:t.root)===I.holding||e.moves.some(n=>{var r;return((r=V(n.from))==null?void 0:r.root)===I.holding}))},Nu=e=>Object.assign(I,{event:null,tx:null,closing:null,reveal:null},e),Br=e=>{Nu(e),Di()};function he(e,t=!1){const n=R("say");n.textContent=e,n.classList.toggle("bad",t)}function d0(){try{Z=Tu()}catch(e){Z=no(),he(`This browser's saved lab could not be read (${e.message}) Load a backup, or reset to start over.`,!0)}Lu()}function Lu(){var t,n,r;ss=new Vn(Z.chain),Ze=Sr(ss),j=Zt(Ze,{pending:!0}),I.beat!==null&&I.beat>=lt()&&(I.beat=null),V(I.holding)&&V(I.holding).root!==I.holding&&(I.holding=V(I.holding).root),V(I.holding)||(I.holding=((t=j.roots.filter(s=>s.kind==="holding").at(-1)??j.roots.at(-1))==null?void 0:t.id)??null),oE(V(I.node))||(I.node=I.holding),I.event&&!j.log.some(s=>s.id===I.event)&&(I.event=null),Ee=I.beat===null?j:Zt(Ze,{upTo:I.beat});const e=y$(Z.keys,Ze,j);fc=B$(Z),ze={owner:e,ledger:b$(Z.chain,e,w$(Z.keys,Ze,j),fc),now:Qa(Z.chain,e)},At=new Map([...j.items.keys()].map(s=>{var o;return[s,((o=Mn(Z,Ze,j,s))==null?void 0:o.node.id)??null]})),ot=new Map(Uu().filter(s=>Bu(Z,j,s)==="open").map(s=>[s.lot,s])),dt=new Map([...j.nodes.values()].filter(s=>s.kind!=="agent"&&s.status==="active").map(s=>{var o;return[s.id,(o=Vp(Z,Ze,j,s.id))==null?void 0:o.id]}).filter(([,s])=>s)),ft=new Map;for(const s of Z.chain.utxos.values()){const o=((n=s.inscriptions)==null?void 0:n.length)>1?(r=s.inscriptions.find(i=>j.nodes.has(i.id)))==null?void 0:r.id:null;if(o)for(const i of s.inscriptions)i.id!==o&&ft.set(i.id,o)}for(const s of new Set(ft.values()))for(const[o,i]of sE(s))ft.has(o)&&At.set(o,i);ze.view=I.beat===null?ze.now:Qa(Z.chain,e,I.beat),I.tx&&!ze.ledger.some(s=>s.key===I.tx)&&(I.tx=null),Di()}function hi(e){I.beat=e>=lt()?null:Math.max(0,e),Ee=I.beat===null?j:Zt(Ze,{upTo:I.beat}),ze.view=I.beat===null?ze.now:Qa(Z.chain,ze.owner,I.beat),Di()}async function tt(e,t){if(I.busy)return!1;I.busy=!0,document.body.classList.add("busy");try{return Z=(await L$(e,t)).lab,!0}catch(n){return he((n==null?void 0:n.message)||String(n),!0),!1}finally{I.busy=!1,document.body.classList.remove("busy"),Lu()}}async function zt(e,t,n,r){let s=null;if(!await tt(i=>{s=Z$(i,e,t,n)}))return!1;const o=ss.events.find(i=>i.id===s);return he(r(s,(o==null?void 0:o.status)==="confirmed"?`at beat ${o.height}`:"cued for the next beat")),Di(),!0}async function h0(e){const t=[uc(),...Bo.map(([a])=>lc(a))],n=lt();if(!await tt(e)||lt()===n)return;const r=[uc(),...Bo.map(([a])=>lc(a))],s=["cued act",...Bo.map(([,a])=>a)],o=t.map((a,c)=>[a-r[c],s[c]]).filter(([a])=>a>0).map(([a,c])=>Cn(a,c)),i=iE(ze.ledger.filter(a=>a.kind==="mine"&&a.beat===lt()));he(`Beat ${lt()}: ${o.length?`${o.join(" and ")} landed, and ${i}`:i}.`)}function iE(e){if(!e.length)return"the lab wallet earned 50 tBTC";const t=e.map(r=>{var s;return((s=V(r.to))==null?void 0:s.name)??"?"}),n=e.map(r=>gu(r.amount));return e.length===1?`${t[0]} earned ${Y(e[0].amount)}`:n.every(r=>r===n[0])?`${t.slice(0,-1).join(", ")} and ${t.at(-1)} earned ${n[0]} each`:e.map((r,s)=>`${t[s]}${s?"":" earned"} ${n[s]}`).join(", ")}function aE(){var t;if(((t=Z.mining)==null?void 0:t.rule)==="last")return"the holding that acts";const e=yu(Z,j);return e.length?e.length===1?e[0].name:`${e.length} holdings, split by hashrate`:"the lab wallet"}function Di(){p0(),lE(),fE(),ds(),_0(),ju()}function p0(){const e=rE(),{tempo:t}=Z.clock;for(const r of document.querySelectorAll("[data-tempo]"))r.setAttribute("aria-pressed",String(String(t)===r.dataset.tempo));R("clock-beat").textContent=String(lt()),R("clock-cued").textContent=e?`${e} cued · ${cE()}`:"nothing cued";const n=aE();R("clock-pays").textContent=`beats pay ${n}`,R("beat-now").title=`Beat now: ${e?"land what is cued, and ":""}pay ${n} 50 test BTC`}function cE(){const{tempo:e,nextAt:t}=Z.clock;return e==="manual"?"waiting for Beat now":typeof e=="number"&&t?`next beat in ${Math.max(0,Math.ceil((t-Date.now())/1e3))}s`:"landing on the next beat"}const uE={split:"Every active holding mines: each beat's 50 tBTC splits by hashrate, set on each holding (0 sits out).",last:"The holding behind the latest act or send takes the whole beat; with nothing cued, Beat now pays the one you're working in. At a timed tempo it's a race for the next beat.",none:"Mainnet has no mining to join: beats pay the lab wallet, standing in for the world's miners. Fund a holding from it, the way you'd fund a seed from a wallet you already have."};function lE(){var a,c;const e=((a=Z.mining)==null?void 0:a.rule)??"split",t=e==="split",n=t?yu(Z,j):[],r=n.reduce((u,f)=>u+Dr(Z,f.id),0);R("holdings-list").replaceChildren(...j.roots.map(u=>{var m;const f=xk(j,u.id),l=u.id===I.holding,d=u.status==="active",p=n.some(x=>x.id===u.id)?Dr(Z,u.id)/r:0,g=[...j.nodes.values()].reduce((x,w)=>x+(w.root===u.id?f0(w.id):0),0),y=[u.graduated!==null&&`from ${((m=V(u.parent))==null?void 0:m.name)??"?"}${u.graduated==="cued"?", cued":` at beat ${u.graduated}`}`||mt(u.born),Cn(f.orgs,"org"),Cn(f.agents,"agent"),Cn(f.belts,"belt"),g>0&&gu(g),t&&d&&(p?`${Math.round(p*100)}% of each beat`:"not mining"),!d&&"closed"].filter(Boolean);return E("li",{},E("button",{type:"button",class:`hold${l?" on":""}${d?"":" gone"}`,"aria-pressed":String(l),onclick:()=>Br({holding:u.id,node:u.id})},E("span",{class:"hn",text:u.name})," ",E("span",{class:"hm",text:y.join(" · ")})),t&&d&&xe(Z.keys,j,u)&&kE(u,Dr(Z,u.id)))}));for(const u of document.querySelectorAll("[data-rule]"))u.setAttribute("aria-pressed",String(e===u.dataset.rule));R("mining-note").textContent=uE[e];const s=j.roots.filter(u=>u.status==="active"&&xe(Z.keys,j,u)&&!ot.has(u.id)&&!dt.has(u.id)),o=R("fund-to"),i=o.value;R("f-fund").hidden=e!=="none"||!s.length||I.beat!==null,o.replaceChildren(...s.map(u=>E("option",{value:u.id,text:u.name}))),o.value=s.some(u=>u.id===i)?i:s.some(u=>u.id===I.holding)?I.holding:((c=s[0])==null?void 0:c.id)??"",R("fund-has").textContent=Y(Z.wallet?$u(Z.chain,Z.wallet):0),R("holdings-empty").hidden=j.roots.length>0,R("holdings-sub").textContent=j.roots.length?String(j.roots.length):"",R("sample").disabled=j.roots.some(u=>u.name===cc&&u.status==="active")}function fE(){var r;const e=R("tree-rows"),t=V(I.holding);if(R("tree-sub").textContent=t?`${t.name} · ${I.beat===null?"now":`beat ${I.beat} of ${lt()}`}`:"",!t)return e.replaceChildren(E("p",{class:"wait",text:"No holding yet. Found one, or load the yolopreneur sample."}));if(!Ee.nodes.has(t.id))return e.replaceChildren(E("p",{class:"wait",text:`${t.name} is founded at ${mt(t.born)}. Move the slider forward.`}));const n=e.contains(document.activeElement)?document.activeElement.dataset.id:null;e.replaceChildren(...bk(Ee,t.id).map(s=>s.type==="group"?E("div",{class:"row grp"},E("span",{class:"g","aria-hidden":"true",text:s.guide}),E("span",{class:"gl",text:s.label})):dE(s))),n&&((r=e.querySelector(`[data-id="${n}"]`))==null||r.focus())}function dE({node:e,guide:t,path:n,away:r,moved:s}){const o=e.id===I.node,i=s&&V(e.parent,Ee),a=["row",o&&"on",e.status==="closed"&&"gone",e.born==="cued"&&"cue",s&&"moved"].filter(Boolean).join(" ");return E("div",{class:a},E("button",{type:"button",class:"sel","data-id":e.id,"aria-pressed":String(o),onclick:()=>Br({node:e.id}),title:s?`${e.name} changed hands: it's ${(i==null?void 0:i.name)??"?"}'s now`:r?`${e.name} graduated into a holding of its own`:null},E("span",{class:"g","aria-hidden":"true",text:t}),E("span",{class:"p",text:`${n} `}),E("span",{class:"l",text:e.name})," ",E("span",{class:"v"},s?E("span",{class:"mk",text:`to ${(i==null?void 0:i.name)??"?"}`}):hE(e))))}function hE(e){var n;return[e.kind==="agent"&&E("span",{class:"mk",text:"agent"}),I.beat===null&&ot.has(e.id)&&E("span",{class:"mk ok",title:`${Y(ot.get(e.id).price)}, asked by ${l0(ot.get(e.id).seller)}`,text:"for sale"}),I.beat===null&&dt.has(e.id)&&E("span",{class:"mk",title:`bought by ${ke(dt.get(e.id))}, which adopts it next`,text:"sold"}),e.edge==="adopted"&&E("span",{class:"mk ok",text:"graduated"}),e.charter&&E("span",{class:`mk form${(n=Es(Ee,e))!=null&&n.ok?"":" lapsed"}`,title:Ru(e),text:gE[e.charter.form]}),e.status==="closed"&&E("span",{class:"mk bad",text:"closed"}),e.born==="cued"&&E("span",{class:"mk",text:"cued"}),...e.badges.map(g0),Oo(e.id)>0&&E("span",{class:"mk sats",title:`${Y(Oo(e.id))} at its SegWit address`,text:gu(Oo(e.id))})].filter(Boolean).flatMap((r,s)=>s?[" ",r]:[r])}const g0=e=>E("span",{class:`belt ${e.belt}`,title:`${e.skill}: ${e.belt} belt`},e.skill,E("span",{class:"sr",text:` (${e.belt} belt)`}));function pE(e,t){const n=Ct(Z.chain,e.id);if(!n||n!==Ct(Z.chain,t.id))return!1;const r=s=>tn(n.ranges,n.inscriptions.find(o=>o.id===s).sat);return r(e.id)===r(t.id)}const dc=e=>{const t=ss.events.find(n=>n.id===e);return t?K$(Z.chain,ss,t):[]},Hu=e=>`${e0[e]} ${e}`,gE={sole:"sole",llc:"llc","series-llc":"series llc",series:"series",corp:"corp"},mE={sole:"Sole proprietor",llc:"LLC","series-llc":"Series LLC",series:"Series",corp:"Corporation"},yE={sole:"a sole proprietor",llc:"an LLC","series-llc":"a series LLC",corp:"a corporation"};function Ru(e,t=Ee){var o;const n=e.charter,r=n.master&&V(n.master,t),s=n.form==="series"?(o=r==null?void 0:r.charter)==null?void 0:o.jurisdiction:n.jurisdiction;return[n.form==="series"?`Series of ${(r==null?void 0:r.name)??"?"}`:mE[n.form],s,n.legal,n.provider&&`via ${n.provider}`,`since ${mt(n.beat)}`].filter(Boolean).join(" · ")}function Mi(e){var t;for(let n=V(e.parent);n&&n.root===e.root;n=V(n.parent))if(n.status==="active"&&((t=n.charter)==null?void 0:t.form)==="series-llc")return n;return null}function wE(e){var r;const t=e.kind==="org"&&Mi(e),n=e.kind==="org"&&e.edge==="derived";return[(e.kind==="holding"||e.kind==="agent")&&["sole","Sole proprietor","a person trading under their own name"],t&&["series",`Series of ${t.name}`,`a cell of ${t.name}'s LLC, chartered by ${t.name}`],!on(e)&&["llc","LLC",n?`a company of its own, owned through ${(r=V(e.parent))==null?void 0:r.name} while it is derived`:"a company of its own"],!on(e)&&["series-llc","Series LLC","an LLC that can hold series, one for each venture"],!on(e)&&["corp","Corporation","a company with shares"]].filter(Boolean)}function m0(e){return wE(e).map(([t,n,r])=>{const s=t==="series"?Mi(e):e,o=Cu(Z,j,"charter",s.id);return{form:t,label:n,hint:o?`${o}.`:r,off:!!o}})}const bE=e=>{var n;const t=m0(e);return t.some(r=>!r.off)?"":((n=t[0])==null?void 0:n.hint.replace(/\.$/,""))??"No legal form fits"},pi=()=>{var e;return((e=document.querySelector("#charter-forms input:checked"))==null?void 0:e.value)??null};function xE(e){var i;const t=R("charter-forms"),n=m0(e),r=n.map(a=>`${a.form}=${a.label}=${a.off}`).join("|");if(t.dataset.sig!==r){const a=pi(),c=n.filter(f=>!f.off),u=c.some(f=>f.form===a)?a:(i=c[0])==null?void 0:i.form;t.dataset.sig=r,t.replaceChildren(E("legend",{class:"lab",text:"Form"}),...n.map(f=>E("label",{class:f.off?"off":null},E("input",{type:"radio",name:"form",value:f.form,checked:f.form===u,disabled:f.off}),` ${f.label} `,E("span",{text:f.hint}))))}const s=pi()==="series",o=Es(j,e);R("charter-where").hidden=s,R("charter-now").textContent=e.charter?`Now: ${Ru(e,j)}${o.ok?"":`, lapsed: ${o.why}`}.`:"It has no legal form yet."}const y0=(e,t)=>{for(let n=V(e.parent);n;n=V(n.parent))if(n.id===t.id)return!0;return!1},vE=e=>{for(let t=e;t;t=t.edge==="derived"?V(t.parent):null)if(ot.has(t.id)||dt.has(t.id))return!0;return!1},w0=e=>[...j.nodes.values()].filter(t=>t.id!==e.id&&t.status==="active"&&!vE(t)).map(t=>[t,(t.root===e.root?0:4)+(y0(t,e)?0:2)+(t.kind==="agent"?0:1)]).sort((t,n)=>t[1]-n[1]).map(([t])=>t),os=e=>_r(j.nodes,e).reduce((t,n)=>n.edge==="derived"&&n.status==="active"?t+1+os(n):t,0);function kE(e,t){const n=async r=>{await tt(s=>P$(s,e.id,r))&&he(r?`${e.name} mines at hashrate ${r}.`:`${e.name} sits out of mining.`)};return E("span",{class:"rig"},E("span",{class:"rl",text:"hashrate"}),E("span",{class:"rn"},E("button",{type:"button",class:"rb","aria-label":`Lower ${e.name}'s hashrate`,disabled:t<=0,onclick:()=>n(t-1)},"−"),E("b",{text:String(t)}),E("button",{type:"button",class:"rb","aria-label":`Raise ${e.name}'s hashrate`,disabled:t>=9,onclick:()=>n(t+1)},"+")))}const b0=e=>[...j.nodes.values()].filter(t=>t.id!==e.id&&t.status==="active").map(t=>[t,(t.root===e.root?0:4)+(y0(t,e)?0:2)+(t.kind==="agent"?0:1)]).sort((t,n)=>t[1]-n[1]).map(([t])=>t);function $E(e){const t=xe(Z.keys,j,e);return t?bu(Z.chain.coins(t.script))!ft.has(r.id)).map(r=>[r,V(At.get(r.id))]).filter(([,r])=>r&&r.id!==e.id&&r.status==="active"),n=[...j.nodes.values()].filter(r=>r.kind!=="agent"&&!ft.has(r.id)&&!dt.has(r.id)&&!Vt(j.nodes,r,e)).map(r=>[r,r]);return[...t,...n].sort((r,s)=>(r[1].root===e.root?0:1)-(s[1].root===e.root?0:1)).map(([r])=>r)}const hc=e=>os(e)?`, with ${os(e)} below it`:"",EE=e=>(j.items.has(e.id)?`${e.name} · held by ${ke(At.get(e.id))}`:`${e.name} · ${e.root===e.id?"a holding":`an org of ${ke(e.parent)}`}${hc(e)}`)+(ot.has(e.id)?` · asks ${Y(ot.get(e.id).price)}`:"");function SE(e){const t=xe(Z.keys,j,e);return t?v0(e).length?Z.chain.coins(t.script).some(n=>n.value>=W+we||n.value===W)?"":x0(e,"to pay with"):"Nothing to buy yet. Items come from Make, and orgs and holdings change hands from other trees":"This holding predates lab keys, so it has no SegWit address to pay from"}const k0=e=>[...[...j.items.values()].filter(t=>At.get(t.id)===e.id&&!ft.has(t.id)),..._r(j.nodes,e).filter(t=>t.kind==="org"&&t.edge==="derived"&&!dt.has(t.id)&&!ft.has(t.id)&&!Vt(j.nodes,t)),...e.root===e.id&&e.kind!=="agent"&&!dt.has(e.id)&&!Vt(j.nodes,e)?[e]:[]],$0=e=>k0(e).filter(t=>!ot.has(t.id));function _E(e){return xe(Z.keys,j,e)?$0(e).length?"":k0(e).length?`Everything ${e.name} can sell is listed. Its asks are in Inspect, to withdraw`:`${e.name} has nothing to sell yet: no item, and no org of its own free to change hands`:"This holding predates lab keys, so it has no SegWit address to be paid at"}function AE(e){const t=R("offer-item").value,n=ot.get(t),r=j.items.has(t)?null:V(t),s=!!r&&r.root===r.id,o=r?s?`${r.name}'s owner`:ke(r.parent):ke(At.get(t)),i=r?os(r):0,a=r?i?`${r.name}'s tree, ${Cn(i+1,"node")} and the items they hold,`:`${r.name}'s inscription and its items`:"the item";R("offer-ask").hidden=!n,R("offer-go").classList.toggle("primary",!n),n&&(R("offer-ask-line").textContent=`${n.seller?ke(n.seller):`${r.name}'s owner`} asks ${Y(n.price)} for ${Ne(t)}${s?", whole":""}. Taking it costs the price, two ${W}-sat fees and a ${Et}-sat coin of ${e.name}'s that leads the deal${r?`, and gas to adopt ${r.name} at once`:""}.`,R("offer-take").textContent=`Take it for ${Y(n.price)}`),R("offer-note").textContent=`${n?"Or offer less. ":""}${e.name}'s SegWit key signs the whole deal now: ${a} to its Taproot key, the price to ${s?"the lab wallet":o}, the ${W}-sat fee from its balance. Nothing reaches the chain until ${o} accepts. ${r?`Accepting takes the money in ${r.name}'s tree home to ${s?"the lab wallet":o} first, and its items go with it; then ${e.name} adopts it. Each act in ${r.name}'s tree moves an inscription, which voids the offer.`:"Until then the offer stands, unless it's withdrawn or a coin it promised moves."}`}function BE(e){const t=V(R("sell-lot").value),n=(t==null?void 0:t.id)===e.id,r=t?os(t):0,s=E0(t);R("sell-note").textContent=t?`Cash-free: ${n?"its owner, the lab wallet,":e.name} takes home the money in ${t.name}'s tree first, every gas tank included, and its items go with it. ${s>1?`Its ${s} inscriptions become one coin at ${t.name}'s key, since an ask signs one input, and ${r?"all of its tree is":"it is"} frozen while it's listed.`:`${t.name} is frozen while it's listed.`} ${n?`${t.name}'s root key`:"Its own key"} signs that input alone, SIGHASH_SINGLE|ANYONECANPAY, for the price to ${n?"the lab wallet":`${e.name}'s SegWit address`}. Whoever takes it adopts it${n?" as an org":""}, and ${r?"its tree takes":"it takes"} new keys from its buyer's seed.`:`The key that holds it signs its input alone, SIGHASH_SINGLE|ANYONECANPAY: that input, for the price to ${e.name}'s SegWit address, and nothing else. Any node can complete the deal around it, so nothing reaches the chain until one does.`}function TE(e){const t=V(R("award-to").value);R("award-note").textContent=t?`${e.name}'s key signs as the belt's parent, and ${t.name}'s co-signs, accepting it. The belt is inscribed on ${t.name}'s own sat, so it goes wherever ${t.name} goes and never sells apart from it; ord marks it ${Hu("reinscription")}.`:""}const E0=e=>e?wr(Z,Ze,j,Zn(Z,Ze,j,e.id)).coins.reduce((t,n)=>t+n.inscriptions.length,0):1;function S0(e,t=j){const n=pu(Z.keys,t,e);return n&&{taproot:n.taproot.address,segwit:n.segwit.address,nostr:n.npub.address,ethereum:n.ethereum.address}}function OE(e){const t=S0(e),n=e.keyring;if(!t)return"This holding predates lab keys, so it has no keys to list";const r=Ou(j,"keyring",e.id);return r||(!n||n.retired||It.some(s=>n.keys[s]!==t[s])?"":n.beat==="cued"?`${e.name}'s keyring is cued for the next beat`:`${e.name}'s keyring already lists these keys, since beat ${n.beat}`)}function IE(e){const t=V(e.parent),n=e.status==="closed"?`${e.name} is closed`:"",r=n?"":qt(Z,j,"act",e.id,{},Ze),s=(o,i=e.id,a={})=>Cu(Z,j,o,i,a);return{birth:n||r||(on(e)?"Agents give birth only once they graduate":s("birth")),award:n||r||(on(e)?"Agents award belts only once they graduate":w0(e).length?s("award"):"There is nobody else to award yet"),charter:n||r||bE(e),decide:n||r||s("decide"),make:n||r||s("make"),keyring:n||r||OE(e)||s("keyring"),send:n||r||$E(e),offer:n||r||SE(e),sell:n||r||_E(e),graduate:n||(t?e.edge==="adopted"?`${e.name} has already graduated`:t.status!=="active"?`${t.name} is closed`:qt(Z,j,"graduate",t.id,{of:e.id},Ze)||Ou(j,"graduate",t.id,{of:e.id})||s("graduate",t.id,{of:e.id}):"A holding has no parent to graduate from"),close:n||r||s("close")}}function ds(){const e=V(I.node),t=I.beat!==null;if(R("act-none").hidden=!!e,R("act-past").hidden=!e||!t,R("act-on").hidden=!e||t,R("act-sub").textContent=(e==null?void 0:e.name)??"",R("past-beat").textContent=String(I.beat??""),!e||t)return;const n=IE(e),r=V(e.parent);for(const h of document.querySelectorAll("[data-verb]"))h.setAttribute("aria-pressed",String(h.dataset.verb===I.verb)),h.classList.toggle("off",!!n[h.dataset.verb]);for(const h of document.querySelectorAll("form[data-form]"))h.hidden=h.dataset.form!==I.verb||!!n[I.verb];R("act-why").textContent=n[I.verb]?`${n[I.verb]}.`:"";for(const h of document.querySelectorAll("#act-on [data-name]"))h.textContent=e.name;for(const h of document.querySelectorAll("#act-on [data-parent]"))h.textContent=(r==null?void 0:r.name)??"";const s=h=>h.map(y=>`${y.value}=${y.textContent}`).join("|"),o=[[R("award-to"),w0(e).map(h=>[h.id,`${ts(j,h.id)}${h.kind==="agent"?" (agent)":""}`])],[R("send-to"),b0(e).map(h=>[h.id,`${ts(j,h.id)}${h.kind==="agent"?" (agent)":""}`])],[R("offer-item"),v0(e).map(h=>[h.id,EE(h)])],[R("sell-lot"),$0(e).map(h=>[h.id,j.items.has(h.id)?`${h.name} · an item`:h.id===e.id?`${h.name} · the whole holding${hc(h)}`:`${h.name} · org ${h.index}'${hc(h)}`])]];for(const[h,y]of o){const m=h.value,x=y.map(([w,P])=>E("option",{value:w,text:P}));s(x)!==s([...h.options])&&(h.replaceChildren(...x),x.some(w=>w.value===m)&&(h.value=m))}for(const h of["send-has","offer-has"])R(h).textContent=Y(f0(e.id));R("graduate-go").textContent=`Graduate ${e.name}`,I.verb==="charter"&&!n.charter&&xE(e),I.verb==="award"&&!n.award&&TE(e),I.verb==="offer"&&!n.offer&&AE(e),I.verb==="sell"&&!n.sell&&BE(e);const i=I.verb==="keyring"&&!n.keyring&&S0(e);i&&R("keyring-keys").replaceChildren(...[["Taproot",i.taproot],["SegWit",i.segwit],["nostr",i.nostr],["Ethereum",i.ethereum]].map(is));const a=I.verb==="sell"&&V(R("sell-lot").value),c=I.verb==="graduate"?r:I.verb==="charter"&&pi()==="series"?Mi(e):a||e,u=c&&$e(Z.keys,j,c),f=I.verb==="send"||I.verb==="offer",l=u&&(f?`${u.from} · ${xe(Z.keys,j,c).path}`:u.path);R("act-key").textContent=!c||n[I.verb]?"":u?`Signs as ${c.name}: ${l}`:"Signs with the lab wallet: this holding predates lab keys.";const d=I.verb==="graduate"&&$e(Z.keys,j,e)?Fn(j,e.id).length:0;R("act-gas").textContent=!c||n[I.verb]||!u?"":I.verb==="send"?`Fee: ${W} sats, from ${e.name}'s balance.`:I.verb==="offer"?`Fee: ${W} sats, from ${e.name}'s balance, paid only if the holder accepts.`:I.verb==="sell"?E0(a||null)>1?`Bundling its tree costs one ${W}-sat fee, from ${a.id===e.id?"the lab wallet":`${e.name}'s tank`}; whoever takes the ask pays the deal's fees.`:"No fee to list: whoever takes the ask pays the fees.":`Gas: ${M$(I.verb,d).toLocaleString("en-US")} sats from ${c.name}'s tank (${Y($u(Z.chain,u.wallet))}), which tops up from its balance.${d?` ${e.name} pays ${W} more, from its own money, to claim its new root.`:""}`;const p=os(e),g=I.closing===e.id;R("close-note").textContent=p?`Closing ${e.name} spends it for the last time, and its ${Cn(p,"derived descendant")} close with it. Graduated children hold their own roots and stay open.`:`Closing ${e.name} spends its inscription for the last time. Nothing can act through it afterwards.`,R("close-go").textContent=g?`Yes, close ${e.name}`:`Close ${e.name}`,R("close-keep").hidden=!g}function _0(){const e=R("inspect-body"),t=I.event?j.log.find(o=>o.id===I.event):null;if(t)return R("inspect-sub").textContent="event",e.replaceChildren(...FE(t));const n=I.tx?ze.ledger.find(o=>o.key===I.tx):null;if(n)return R("inspect-sub").textContent="money",e.replaceChildren(...WE(n));const r=V(I.node);if(R("inspect-sub").textContent=(r==null?void 0:r.kind)??"",!r)return e.replaceChildren(E("p",{class:"note pad",text:"Select a node in the tree, or an event in the timeline."}));const s=V(I.node,Ee);if(!s)return e.replaceChildren(E("p",{class:"note pad",text:`${r.name} is not born yet at beat ${I.beat}.`}));e.replaceChildren(...CE(s))}const is=([e,t,n])=>E("div",{class:"f"},E("dt",{text:e}),E("dd",{},t,n&&E("span",{class:"fn",text:n})));function CE(e){var r;const t=V(e.parent,Ee),n=[["Born",e.born==="cued"?"cued for the next beat":`beat ${e.born}`],t&&["Parent",`${t.name} · ${e.kind} ${e.index}'`],t&&["Edge",e.edge==="adopted"?`adopted at ${mt(e.graduated)}: it holds its own root`:`derived: ${t.name} holds its seed`],e.moves.length>0&&["Changed hands",e.moves.map(s=>{var o,i;return`${s.from?`from ${((o=V(s.from,Ee))==null?void 0:o.name)??"?"}`:"whole, from its owner,"} to ${((i=V(s.to,Ee))==null?void 0:i.name)??"?"}, ${mt(s.beat)}`}).join("; "),"Each time, it took the next index under its new parent, and keys derived there, with its tree."],I.beat===null&&(ot.has(e.id)||dt.has(e.id)||ft.has(e.id))&&UE(e),t&&e.root===e.id&&["Holding",E("span",{},"its own, since it graduated",e.id!==I.holding&&E("button",{type:"button",class:"btn sm open",onclick:()=>{Br({holding:e.id,node:e.id}),LE()}},`Open ${e.name}`))],e.closed!==null&&["Closed",mt(e.closed)],["Charter",e.charter?Ru(e):"none yet",e.charter?Es(Ee,e).ok?e.charter.filing?`Filing SHA-256 ${e.charter.filing.slice(0,16)}…`:"":`Lapsed: ${Es(Ee,e).why}.`:"Charter gives it a legal form: sole proprietor, LLC, series LLC, series or corporation."],((r=e.charter)==null?void 0:r.form)==="series-llc"&&["Series",[...Ee.nodes.values()].filter(s=>{var o;return((o=s.charter)==null?void 0:o.master)===e.id}).map(s=>`${s.name}${Es(Ee,s).ok?"":" (lapsed)"}`).join(", ")||"none yet"],["Children",_r(Ee.nodes,e).map(s=>s.name).join(", ")||"none yet"],xe(Z.keys,Ee,e)&&["Balance",Y(Oo(e.id)),`Test BTC at its SegWit address${I.beat===null?"":`, as of beat ${I.beat}`}.`],I.beat===null&&$e(Z.keys,j,e)&&["Gas tank",Y($u(Z.chain,$e(Z.keys,j,e).wallet)),"Plain coins at its Taproot key. Its acts burn their fees from here, and the tank tops up from its balance, 0.0001 tBTC at a time."],["Inscription",e.id,dc(e.id).length?`ord charms: ${dc(e.id).map(Hu).join(", ")}`:""]].filter(Boolean);return[E("div",{class:"ih"},E("p",{class:"eyebrow",text:ts(Ee,e.id)}),E("h3",{class:"it",text:e.name}),E("div",{class:"chips"},E("span",{class:"chip",text:e.kind}),E("span",{class:`chip ${e.status==="active"?"ok":"bad"}`,text:e.status}),e.edge==="adopted"&&E("span",{class:"chip ok",text:"graduated"}),e.born==="cued"&&E("span",{class:"chip",text:"cued"}))),E("div",{class:"ib"},E("dl",{class:"fl"},n.map(is)),e.badges.length>0&&E("div",{},E("p",{class:"lab"},"Belts",E("span",{text:` · soulbound to ${e.name}`})),E("ul",{class:"list"},e.badges.map(s=>{var o,i;return E("li",{},g0(s),E("span",{class:"when",text:` from ${((o=V(s.by))==null?void 0:o.name)??"?"}, ${mt(s.beat)}${I.beat!==null?"":pE(s,e)?` · ${e0.reinscription} on ${e.name}'s own sat`:` · kept by ${((i=V(s.by))==null?void 0:i.name)??"its issuer"}, from before belts rode their seats`}`}))}))),e.decisions.length>0&&E("div",{},E("p",{class:"lab",text:"Decisions"}),E("ul",{class:"list"},e.decisions.map(s=>E("li",{},E("b",{text:s.title}),s.why&&` · ${s.why}`,E("span",{class:"when",text:` (${mt(s.beat)})`}))))),PE(e),HE(e),ME(e))]}function PE(e){const t=(l,d)=>d.length>0&&E("div",{},E("p",{class:"lab",text:l}),E("ul",{class:"list items"},d)),n=(l,d)=>E("li",{},E("b",{text:l.name}),l.note&&` · ${l.note}`,E("span",{class:"when",text:` (${d})`}));if(I.beat!==null)return t("Made",e.made.map(l=>Ee.items.get(l)).filter(Boolean).map(l=>n(l,mt(l.beat))));const r=l=>`made${l.maker===e.id?"":` by ${ke(l.maker)}`}${l.beat==="cued"?", cued":` at beat ${l.beat}`}`,s=[...j.items.values()].filter(l=>At.get(l.id)===e.id).map(l=>{const d=n(l,`${r(l)}${ft.has(l.id)?`, in one coin with ${Ne(ft.get(l.id))}'s tree`:""}`),p=To().filter(g=>g.item===l.id&&g.seller===e.id&&Ao(Z,j,g,Ze)==="open");return p.length&&d.append(E("ul",{class:"bids"},p.map(g=>E("li",{},E("span",{text:`${ke(g.buyer)} offers ${g.price?Y(g.price):"nothing, a free claim"}`}),e.status==="active"&&E("button",{type:"button",class:"btn sm","aria-label":`Accept ${ke(g.buyer)}'s offer for ${l.name}`,onclick:()=>Yl(g)},"Accept"))))),d}),o=e.made.map(l=>j.items.get(l)).filter(l=>l&&At.get(l.id)!==e.id).map(l=>n(l,At.get(l.id)?`now held by ${ke(At.get(l.id))}`:"held outside this lab")),i=To().filter(l=>l.buyer===e.id&&Ao(Z,j,l,Ze)!=="done").map(l=>{const d=_u(Z,j,l,Ze);return E("li",{},E("b",{text:l.price?Y(l.price):"nothing"}),` for ${Ne(l.item)}`,E("span",{class:"when",text:d?` (stale: ${d})`:` (open until ${l.seller?ke(l.seller):`${Ne(l.item)}'s owner`} accepts)`}),E("button",{type:"button",class:"btn sm","aria-label":`Withdraw the offer for ${Ne(l.item)}`,onclick:()=>NE(l)},"Withdraw"))}),a=l=>l.seller===e.id||l.seller===null&&(l.item??l.lot)===e.id,c=To().filter(l=>a(l)&&j.nodes.has(l.item)&&Ao(Z,j,l,Ze)==="open").map(l=>E("li",{},E("b",{text:Ne(l.item)}),E("span",{class:"when",text:` ${ke(l.buyer)} offers ${l.price?Y(l.price):"nothing, a free claim"}`}),e.status==="active"&&E("button",{type:"button",class:"btn sm","aria-label":`Accept ${ke(l.buyer)}'s offer for ${Ne(l.item)}`,onclick:()=>Yl(l)},"Accept"))),u=Uu().filter(l=>a(l)&&Bu(Z,j,l)!=="done").map(l=>{const d=Au(Z,j,l);return E("li",{},E("b",{text:Y(l.price)}),` for ${Ne(l.lot)}`,E("span",{class:"when",text:d?` (stale: ${d})`:" (open: any node can take it)"}),E("button",{type:"button",class:"btn sm","aria-label":`Withdraw the ask for ${Ne(l.lot)}`,onclick:()=>A0(l)},"Withdraw"))}),f=[...dt].filter(([,l])=>l===e.id).map(([l])=>E("li",{},E("b",{text:Ne(l)}),E("span",{class:"when",text:V(l).root===l?" bought whole":` bought from ${ke(V(l).parent)}`}),E("button",{type:"button",class:"btn sm","aria-label":`Adopt ${Ne(l)}`,onclick:()=>B0(l,e.id)},"Adopt")));return[t("Items",s),t("Made, held elsewhere",o),t(e.root===e.id?"Offers on it or its orgs":"Offers on its orgs",c),t("Asks",u),t("Offers made",i),t("Bought, to adopt",f)]}const ke=e=>{const t=V(e);return t?t.root===I.holding?t.name:ts(j,e):"?"};async function Yl(e){const t=Ne(e.item),n=ke(e.buyer),r=e.seller?ke(e.seller):`${t}'s owner`,s=j.nodes.has(e.item);if(!await tt(i=>{z$(i,e.txid)}))return;const o=ze.ledger.find(i=>i.txid===e.txid);he(`${r} accepted: ${t} goes to ${n}${e.price?` for ${Y(e.price)}`:", free"}, ${o!=null&&o.beat?`at beat ${o.beat}`:"cued for the next beat"}.${s?` The money in its tree went ${e.seller?`home to ${r}`:"to the lab wallet"} first, its items went with it, and ${n} adopts it next.`:""}`)}function UE(e){var o;const t=ot.get(e.id),n=V(dt.get(e.id)),r=V(ft.get(e.id)),s=[...ft.values()].includes(e.id);return!t&&!n?["Changing hands",`with ${(r==null?void 0:r.name)??"?"}'s tree`,ot.has(r==null?void 0:r.id)?`${r.name} is listed for sale: its tree is one coin at its key, frozen until the ask is taken or withdrawn.`:`${ke(dt.get(r==null?void 0:r.id))} bought ${(r==null?void 0:r.name)??"?"}'s tree, and adopts it next.`]:t?["For sale",E("span",{},`${Y(t.price)}, asked by ${l0(t.seller)}`,E("button",{type:"button",class:"btn sm open",onclick:()=>A0(t)},"Withdraw")),s?`Its tree is one coin at its key, ${Cn(((o=t.holder.ids)==null?void 0:o.length)??2,"inscription")}, and its own key signed that input, SIGHASH_SINGLE|ANYONECANPAY: any node can take it. All of the tree is frozen until then.`:"Its own key signed its input, SIGHASH_SINGLE|ANYONECANPAY: any node can take it. It's frozen until then."]:["Sold",E("span",{},`to ${ke(n.id)}, which adopts it next`,E("button",{type:"button",class:"btn sm open",onclick:()=>B0(e.id,n.id)},`Adopt into ${n.name}`)),`${n.name}'s key holds its ${s?"tree, in one coin,":"inscription"} now.`]}async function A0(e){var s;const t=Ne(e.lot),n=e.seller?ke(e.seller):`${t}'s owner`,r=(((s=e.holder.ids)==null?void 0:s.length)??1)>1;await tt(o=>{Y$(o,Ar(e))})&&he(`${n} withdrew its ask for ${t}.${r?" Its tree split back, each inscription to its own key.":""}`)}async function B0(e,t){const n=Ne(e),r=ke(t);if(!await tt(o=>{J$(o,e,t)}))return;const s=j.log.findLast(o=>o.op==="join"&&o.node===e);he(`${r} adopted ${n}, ${s!=null&&s.pending?"cued for the next beat":`at beat ${s==null?void 0:s.beat}`}: its keys derive from ${r}'s seed now.`)}async function NE(e){const t=Ne(e.item),n=ke(e.buyer);await tt(r=>{F$(r,e.txid)})&&he(`${n} withdrew its offer for ${t}.`)}function LE(){const e=document.querySelector(".tree-blk").getBoundingClientRect().top+scrollY-document.querySelector(".clock").offsetHeight-12;e(n.to===e.id||n.from===e.id)&&(I.beat===null||n.beat!==null&&n.beat<=I.beat)).slice(-6).reverse();return t.length>0&&E("div",{},E("p",{class:"lab",text:"Money"}),E("ul",{class:"list"},t.map(n=>E("li",{},E("b",{text:RE(n,e.id)}),E("span",{class:"when",text:` (${mt(n.beat??"cued")})`})))))}function RE(e,t){const n=r=>{var s;return r?((s=V(r))==null?void 0:s.name)??"?":"the lab wallet"};if(e.kind==="mine")return`+${Y(e.amount)}, a beat's reward`;if(e.kind==="move")return`${Y(e.amount)} moved to its new key, after a ${e.fee}-sat fee`;if(e.kind==="gas")return`−${Y(e.amount)} into its gas tank, and a ${e.fee}-sat fee`;if(e.kind==="fund")return`+${Y(e.amount)} from the lab wallet`;if(e.kind==="deal"){const r=Ne(e.item);return e.to===t?e.amount?`+${Y(e.amount)} from ${n(e.from)} for ${r}`:`${r} to ${n(e.from)}, free`:e.amount?`−${Y(e.amount)} to ${n(e.to)} for ${r}, and a ${e.fee}-sat fee`:`${r} from ${n(e.to)}, free but for a ${e.fee}-sat fee`}return e.to===t?`+${Y(e.amount)} from ${n(e.from)}`:`−${Y(e.amount)} to ${n(e.to)}, and a ${e.fee}-sat fee`}function T0(e){const t=n=>{const r=V(n);return n?r?r.root===I.holding?r.name:ts(j,n):"?":"lab wallet"};return e.kind==="mine"?`${Y(e.amount)} → ${t(e.to)}`:e.kind==="move"?`${Y(e.amount)} → ${t(e.to)}'s new key`:e.kind==="gas"?`${Y(e.amount)} → ${t(e.to)}'s gas tank`:e.kind==="fund"?`${Y(e.amount)} lab wallet → ${t(e.to)}`:e.kind==="deal"?`${Ne(e.item)} ${t(e.to)} → ${t(e.from)}, ${e.amount?`for ${Y(e.amount)}`:"free"}`:`${Y(e.amount)} ${t(e.from)} → ${t(e.to)}`}const jE={own:"its own key",lab:"the lab wallet",parent:"its parent's key (its handoff is cued)",other:"a key outside this lab"},KE={ssh:"shell access, certified by the CA",git:"commit signing",dkim:"mail signing",wg:"WireGuard peer key","ssh-ca":"SSH certificate authority",mtls:"TLS identity between nodes",noise:"Headscale noise key"};function DE(e){var s;const t=Ii(Z,j,e.id),n=V(ft.get(e.id)),r=(s=Mn(Z,Ze,j,e.id))==null?void 0:s.node;return t?n?`${ke(r==null?void 0:r.id)}'s key, in one coin with ${n.name}'s tree while it changes hands`:dt.has(e.id)?`${ke(dt.get(e.id))}'s key: it bought ${e.name}, and adopts it next`:jE[t.who]:"nobody: its inscription has been spent"}function ME(e){const t=$e(Z.keys,Ee,e),n=["Held now by",DE(e)];if(!t)return E("div",{class:"keys"},E("p",{class:"lab",text:"Keys"}),E("dl",{class:"fl"},[["Signs with","the lab wallet: this holding predates lab keys, so it has no addresses, leaves or secrets of its own"],n].map(is)));const r=e.kind==="agent",s=pu(Z.keys,Ee,e),o=u$(Z.keys,Ee,e),i=o.map(([,,l])=>l).filter(Boolean),a="Reset the lab for standard BIP-86 keys.",c=r?"Holds this seat's inscription, and inscriptions sent to it land here.":"Holds this org's inscription and signs its acts. Inscriptions sent to it land here.",u={bip86:`BIP-86 at ${s.taproot.path}. ${c}`,tapkey:`Its npub's key with the BIP-86 tweak, the way v1.2 keyed this lab. ${c} ${a}`,wallet:`An untweaked key at ${s.taproot.path}, the way v1.1 keyed this lab. ${c} ${a}`}[t.scheme],f=[["Taproot",s.taproot.address,u],["SegWit",s.segwit.address,`BIP-84 at ${s.segwit.path}. Its money: ${e.kind==="holding"?"the beats it earns land here, and ":""}sends come and go here.`],["Tapkey",s.tapkey.address,"Its npub as a Taproot address (its nostr key with the BIP-86 tweak), so the npub alone finds it. Nostr secrets get pasted into clients, so treat it as an inbox."],["npub",s.npub.address,`NIP-06 at ${s.npub.path}. Its nostr name; the leaves below hang off it.`],["Ethereum",s.ethereum.address,r&&e.edge!=="adopted"?`BIP-44 at ${s.ethereum.path}: account ${t.account} of its org's seed, the way Ledger Live numbers Ethereum accounts.`:`BIP-44 at ${s.ethereum.path}. Its legal-control key, the one that holds the entity NFT, as on the lineage key tree page.`],["From",`${t.from} · account ${t.account}`],n,ZE(e)];return E("div",{class:"keys"},E("p",{class:"lab",text:"Keys"}),E("dl",{class:"fl"},f.map(is)),e.keyring&&Mr(`${e.keyring.retired?"Retired keyring":"Keyring"} · what each key signed`,_i(e.id,e.keyring.keys)),E("p",{class:"lab"},"Leaves",E("span",{text:` · HKDF-SHA256 from its ${r?"nostr secret":"seed"}`})),E("ul",{class:"list leaves"},o.map(([l,d])=>E("li",{},E("b",{text:l}),E("span",{class:"when",text:` ${KE[l]}`}),E("code",{text:d})))),Mr(r?"Public lines to paste":"CA key for TrustedUserCAKeys",i.join(` - -`)),qE(e,t))}function ZE(e){var r,s;const t=e.keyring,n=(t==null?void 0:t.retired)&&(t.retired.by===e.id?"It":((r=V(t.retired.by,Ee))==null?void 0:r.name)??"Its parent");return t?t.retired?["Keyring",`retired at ${mt(t.retired.beat)}`,t.retired.cause==="close"?`${n} closed, which freed the keys it listed.`:t.retired.cause==="move"?`Its tree changed hands to ${((s=V(t.retired.by,Ee))==null?void 0:s.name)??"?"}, so its keys changed with its new parent's seed. Keyring publishes a new one.`:n==="It"?"It graduated, so its keys changed with its new root. Keyring publishes a new one.":`${n} graduated, so ${e.name}'s keys changed with ${n}'s new root. Keyring publishes a new one.`]:["Keyring",`published at ${mt(t.beat)}`,"Each key signed it: Taproot and SegWit by BIP-322, the npub as a nostr event, Ethereum by EIP-191."]:["Keyring","none yet","Keyring publishes one: an inscription that lists these keys, each key signing it."]}function Mr(e,t,n=t){const r=E("pre",{text:n}),s=E("button",{type:"button",class:"cp","aria-label":`Copy ${e}`,onclick:()=>VE(t,s,r)},"Copy");return E("div",{class:"code"},E("div",{class:"code-h cph"},E("span",{text:e}),s),r)}async function VE(e,t,n){const r=s=>{t.textContent=s,setTimeout(()=>{t.textContent="Copy"},1400)};try{await navigator.clipboard.writeText(e),r("Copied")}catch{getSelection().selectAllChildren(n),r("Selected")}}function qE(e,t){var a;const n=I.reveal===e.id,r=n&&p$(Z.keys,Ee,e),s=V(e.parent,Ee),o=()=>{var c;I.reveal=n?null:e.id,_0(),(c=R("reveal"))==null||c.focus()},i=(a=r==null?void 0:r.seed)==null?void 0:a.mnemonic.split(" ");return E("div",{class:"secret"},E("div",{class:"hz"},E("span",{class:"hz-l",text:"Secret · stays in this tab"}),E("button",{type:"button",class:"btn sm",id:"reveal","aria-expanded":String(n),onclick:o},n?"Hide":"Reveal")),r&&E("div",{class:"sb"},r.seed?Mr(`Seed · ${r.seed.from}`,r.seed.mnemonic,i.map((c,u)=>`${String(u+1).padStart(2,"0")} ${c}`).reduce((c,u,f)=>(f%3?c[c.length-1].push(u):c.push([u]),c),[]).map(c=>c.join(" ")).join(` -`)):E("p",{class:"note",text:`A seat has no seed of its own: these are account ${t.account} of ${(s==null?void 0:s.name)??"its org"}'s seed.`}),r.account.map(([c,u,f])=>Mr(`${c} · ${u}`,f)),r.leaves.map(([c,u,f])=>Mr(`${c} · ${u}`,f))))}function zE(e){var i,a,c;const t=(a=(i=Z.chain.transactions.get(e.id.slice(0,-2)))==null?void 0:i.tx.vin.find(u=>{var f;return((f=u.witness)==null?void 0:f.length)===3}))==null?void 0:a.witness;if(!t)return"?";const n=zc(t).pubkey,r=V(e.parent),s=e.op==="found"?V(e.node):null,o=[[s&&$e(Z.keys,j,s),`${s==null?void 0:s.name}'s root`],[r&&$e(Z.keys,j,r),`${r==null?void 0:r.name}'s key`],[(r==null?void 0:r.edge)==="adopted"&&$e(Z.keys,j,{...r,edge:"derived"}),`${r==null?void 0:r.name}'s derived key, from before it graduated`]];for(const[u,f]of o)if(u&&u.wallet.pubkey===n)return f;return((c=Z.wallet)==null?void 0:c.pubkey)===n?"the lab wallet":`a key outside this lab (${n.slice(0,12)}…)`}function FE(e){var o,i,a;const t=ss.events.find(c=>c.id===e.id),n=(i=(o=Z.chain.transactions.get(e.id.slice(0,-2)))==null?void 0:o.inscription)==null?void 0:i.text,r=[["When",e.pending?"cued for the next beat":`beat ${e.beat}`],["Authorized by",e.parent?`${((a=V(e.parent))==null?void 0:a.name)??"an unknown inscription"}, whose inscription this event spent`:"nothing: a founding has no parent"],["Signed by",zE(e)],["Inscription",e.id],n&&["Body",n],(t==null?void 0:t.block)&&["Block",t.block]].filter(Boolean),s=t&&{id:t.id,status:t.status,height:t.height,block:t.block,parent:t.parent??null,metaprotocol:t.metaprotocol??null,contentType:t.contentType,sat:t.sat,location:t.location};return[E("div",{class:"ih"},E("p",{class:"eyebrow",text:`${e.op} · ${e.pending?"cued":`beat ${e.beat}`}`}),E("h3",{class:"it",text:vp(e,j)}),E("div",{class:"chips"},E("span",{class:"chip",text:(t==null?void 0:t.protocol)??"?"}),E("span",{class:`chip ${e.ok?"ok":"bad"}`,text:e.ok?"applied":"rejected"}),...dc(e.id).map(c=>E("span",{class:"chip",title:`ord charm: ${c}`,text:Hu(c)}))),!e.ok&&E("p",{class:"idesc",text:"The reducer rejected this event. It stays on the chain, but it does not change the tree."})),E("div",{class:"ib"},E("dl",{class:"fl"},r.map(is)),E("div",{class:"code"},E("p",{class:"code-h",text:"Metadata · CBOR, tag 5"}),E("pre",{text:Gl(e.meta)})),s&&E("div",{class:"code"},E("p",{class:"code-h",text:"Raw index entry"}),E("pre",{text:Gl(s)})))]}function WE(e){var c;const t=u=>{var f;return((f=V(u))==null?void 0:f.name)??"a key outside this lab"},n=Z.chain.transactions.get(e.txid),r=e.kind==="deal",s=e.kind==="fund",o=fc.get(e.txid),i=o!=null&&o.holders?o.holders.reduce((u,f)=>{var l;return u+(((l=f.ids)==null?void 0:l.length)??1)},0):((c=o==null?void 0:o.ids)==null?void 0:c.length)??1,a=[["When",e.beat===null?"cued for the next beat":`beat ${e.beat}`],r&&(j.nodes.has(e.item)?[e.to?"Org":"Holding",i>1?`${Ne(e.item)} and its tree: ${Cn(i,"inscription")} in one coin, from its key to ${t(e.from)}'s Taproot key. It sold cash-free, and ${t(e.from)} adopts it.`:`${Ne(e.item)}: its inscription, from its own key to ${t(e.from)}'s Taproot key. It sold cash-free, and ${t(e.from)} adopts it.`]:["Item",`${Ne(e.item)}, an inscription: from ${t(e.to)}'s Taproot key to ${t(e.from)}'s`]),["From",e.kind==="mine"?"its share of the beat's block reward (the coinbase)":s?"the lab wallet, standing in for a wallet you already have":`${t(e.from)}'s SegWit address${e.kind==="move"?", from before it graduated":""}`],["To",e.kind==="gas"?`${t(e.to)}'s gas tank, at its Taproot key`:r&&!e.amount?"nobody: a free claim pays no price":e.to===null?"the lab wallet, which plays the owner of every holding":`${t(e.to)}'s ${e.kind==="move"?"new ":""}SegWit address`],[r?"Price":"Amount",r&&!e.amount?"nothing":Y(e.amount)],e.kind!=="mine"&&["Fee",`${e.fee} sats${e.ask?` over two transactions (the buyer's split, then the deal), and a ${Et}-sat coin of the buyer's that leads the deal and pads the lot's coin now`:""}, retired: this toy chain pays no fees to miners`],e.change>0&&["Change",`${Y(e.change)} back to ${s?"the lab wallet":t(e.from)}`],["Signed by",e.kind==="mine"?"nobody: a coinbase spends nothing":s?"the lab wallet's Taproot key":r&&e.ask?`the lot's Taproot key (SIGHASH_SINGLE|ANYONECANPAY) when ${e.to?t(e.to):"its owner"} listed it, then ${t(e.from)}'s SegWit key (SIGHASH_ALL) when it took it`:r&&j.nodes.has(e.item)?`${t(e.from)}'s SegWit key (SIGHASH_ALL) when it made the offer, then the Taproot keys that held ${i>1?"its tree":"it"}, when ${e.to?t(e.to):"its owner"} accepted`:r?`${t(e.from)}'s SegWit key (SIGHASH_ALL) when it made the offer, then ${t(e.to)}'s Taproot key when it accepted`:`${t(e.from)}'s SegWit key (BIP-143, SIGHASH_ALL)`],["Transaction",e.txid]].filter(Boolean);return[E("div",{class:"ih"},E("p",{class:"eyebrow",text:`${e.kind} · ${e.beat===null?"cued":`beat ${e.beat}`}`}),E("h3",{class:"it",text:T0(e)}),E("div",{class:"chips"},E("span",{class:"chip",text:"test BTC"}),E("span",{class:`chip${e.beat===null?"":" ok"}`,text:e.beat===null?"cued":"confirmed"}))),E("div",{class:"ib"},E("dl",{class:"fl"},a.map(is)),n&&Mr("Raw transaction",n.raw))]}function ju(){const e=lt(),t=R("beat"),n=V(I.holding);t.max=String(e),t.value=String(I.beat??e),t.disabled=e===0,R("beat-label").textContent=I.beat===null?`Now · beat ${e}`:`Beat ${I.beat} of ${e}`,R("replay").textContent=I.replay?"Stop":"Replay",R("replay").disabled=!n||e===0,R("to-now").disabled=I.beat===null,R("timeline-sub").textContent=(n==null?void 0:n.name)??"";const r=new Map,s=new Map([...Z.chain.transactions.keys()].map((a,c)=>[a,c])),o=(a,c)=>r.set(a,[...r.get(a)??[],c]);for(const a of j.log)a.roots.some(c=>{var u;return((u=V(c))==null?void 0:u.root)===I.holding})&&o(a.pending?"cued":a.beat,{e:a,at:s.get(a.id.slice(0,-2))??0});for(const a of ze.ledger)[a.to,a.from].some(c=>{var u;return c&&((u=V(c))==null?void 0:u.root)===I.holding})&&o(a.beat??"cued",{m:a,at:s.get(a.txid)??0});const i=[...r.keys()].sort((a,c)=>a==="cued"?-1:c==="cued"?1:c-a);if(!i.length)return R("timeline-list").replaceChildren(E("li",{class:"wait",text:n?"Nothing yet.":"Found a holding to start its timeline."}));R("timeline-list").replaceChildren(...i.map(a=>{const c=a==="cued"?null:Z.chain.blocks[a-1],u=I.beat!==null&&(a==="cued"||a>I.beat),f=I.beat!==null&&a===I.beat;return E("li",{class:`beat${u?" later":""}${f?" now":""}`},E("p",{class:"bh"},E("span",{class:"bn",text:a==="cued"?"Cued":`Beat ${a}`}),E("span",{class:"bt",text:c?nE(c.time):Z.clock.tempo==="manual"?"waiting for Beat now":"landing on the next beat"})),E("ol",{class:"evs"},r.get(a).sort((l,d)=>l.at-d.at).map(({e:l,m:d})=>d?YE(d):GE(l))))}))}function GE(e){const[t,...n]=vp(e,j).split(" ");return E("li",{},E("button",{type:"button",class:`ev${e.ok?"":" bad"}${e.id===I.event?" on":""}`,"aria-pressed":String(e.id===I.event),onclick:()=>Br({event:e.id,node:e.node??I.node})},E("span",{class:"op",text:e.ok?t:`✕ ${t.replace(/:$/,"")}`})," ",E("span",{class:"es",text:n.join(" ")})))}const YE=e=>E("li",{},E("button",{type:"button",class:`ev money${e.kind==="gas"?" gas":""}${e.kind==="deal"?" deal":""}${e.key===I.tx?" on":""}`,"aria-pressed":String(e.key===I.tx),onclick:()=>{var t;return Br({tx:e.key,node:((t=V(e.to))==null?void 0:t.root)===I.holding?e.to:I.node})}},E("span",{class:"op",text:e.kind})," ",E("span",{class:"es",text:T0(e)})));R("f-found").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=Qs(t.elements.name.value);if(!n)return he("Name the holding: lowercase letters, digits and hyphens.",!0);await zt("found",null,{name:n},(r,s)=>(Nu({holding:r,node:r}),`${n} is founded, ${s}.`))&&t.reset()});R("sample").addEventListener("click",async()=>{let e=null;he("Rehearsing the yolopreneur tree over six beats…"),await tt(t=>{e=tE(t)})&&(Br({holding:e,node:e}),he("Loaded the yolopreneur sample: six beats of history, ending on both sides of a deal: lineage's offer for sol's launch-kit, and well-known's ask for mailr. Press Replay to watch it grow."))});R("f-birth").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=V(I.node),r=Qs(t.elements.name.value),s=t.elements.kind.value;if(!r)return he("Name the child: lowercase letters, digits and hyphens.",!0);await zt("birth",n.id,{name:r,kind:s},(o,i)=>`${r} is born to ${n.name}, ${i}.`)&&(t.elements.name.value="")});R("f-award").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=V(I.node),r=t.elements.to.value,s=Qs(t.elements.skill.value),o=t.elements.belt.value;if(!s)return he("Name the skill, for example launch.",!0);await zt("award",n.id,{to:r,skill:s,belt:o},(i,a)=>{var c;return`${(c=V(r))==null?void 0:c.name} holds a ${o} belt in ${s}, ${a}, on its own sat.`})&&(t.elements.skill.value="")});R("f-decide").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=V(I.node),r=t.elements.title.value.trim(),s=t.elements.why.value.trim();if(!r)return he("A decision needs a title.",!0);await zt("decide",n.id,{title:r,why:s},(o,i)=>`${n.name} decided “${r}”, ${i}.`)&&t.reset()});R("f-send").addEventListener("submit",async e=>{var a;e.preventDefault();const t=e.currentTarget,n=V(I.node),r=t.elements.to.value,s=Ci(t.elements.amount.value);if(s===null)return he("Write an amount in test BTC, for example 1.5 (at most eight decimals).",!0);let o=null;if(!await tt(c=>{o=V$(c,n.id,r,s)}))return;const i=ze.ledger.find(c=>c.txid===o);he(`${n.name} sent ${Y(s)} to ${((a=V(r))==null?void 0:a.root)===n.root?V(r).name:ts(j,r)}, ${i!=null&&i.beat?`at beat ${i.beat}`:"cued for the next beat"}.`),t.elements.amount.value=""});R("f-make").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=V(I.node),r=Qs(t.elements.name.value),s=t.elements.note.value.trim();if(!r)return he("Name the item: lowercase letters, digits and hyphens.",!0);await zt("make",n.id,{name:r,note:s},(o,i)=>`${n.name} made ${r}, ${i}.`)&&t.reset()});R("f-charter").addEventListener("change",e=>{e.target.name==="form"&&ds()});R("charter-file").addEventListener("change",async e=>{var r;const t=(r=e.target.files)==null?void 0:r[0];if(!t)return;const n=new Uint8Array(await crypto.subtle.digest("SHA-256",await t.arrayBuffer()));R("charter-filing").value=[...n].map(s=>s.toString(16).padStart(2,"0")).join(""),e.target.value="",he(`Hashed ${t.name} in this tab: only its SHA-256 would go on chain.`)});R("f-charter").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=V(I.node),r=pi();if(!r)return he("Pick a legal form.",!0);if(r==="series"){const a=Mi(n);await zt("charter",a.id,{form:"series",of:n.id},(c,u)=>`${n.name} is a series of ${a.name}, ${u}.`);return}const s=a=>t.querySelector(`[name="${a}"]`).value.trim(),o={form:r,jurisdiction:s("jurisdiction").toUpperCase(),legal:s("legal"),provider:Qs(s("provider")),filing:s("filing").toLowerCase()},i=(a,c)=>`${n.name} is chartered as ${yE[r]}${o.jurisdiction?` in ${o.jurisdiction}`:""}, ${c}.`;if(await zt("charter",n.id,o,i))for(const a of["legal","filing"])t.querySelector(`[name="${a}"]`).value=""});R("f-keyring").addEventListener("submit",async e=>{e.preventDefault();const t=V(I.node);await zt("keyring",t.id,{},(n,r)=>`${t.name} published its keyring, ${r}: four keys, each signing the same statement.`)});R("f-offer").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=V(I.node),r=R("offer-item").value,s=Ci(t.elements.price.value);if(s===null)return he("Write a price in test BTC, for example 0.1, or 0 for a free claim.",!0);const o=V(r),i=Ne(r),a=j.items.has(r)?ke(At.get(r)):(o==null?void 0:o.root)===(o==null?void 0:o.id)?`${i}'s owner`:ke(o==null?void 0:o.parent);await tt(c=>{q$(c,r,n.id,s)})&&(he(`${n.name} offers ${s?Y(s):"nothing"} for ${i}. The offer stands until ${a} accepts it.`),t.elements.price.value="")});R("offer-take").addEventListener("click",async()=>{const e=V(I.node),t=R("offer-item").value,n=ot.get(t),r=j.nodes.has(t);if(!n)return;const s=Ne(t),o=ke(n.seller);if(!await tt(c=>{X$(c,Ar(n),e.id)}))return;const i=ze.ledger.findLast(c=>c.kind==="deal"&&c.item===t),a=i!=null&&i.beat?`at beat ${i.beat}`:"cued for the next beat";if(!r)return he(`${e.name} took ${s} from ${o} for ${Y(n.price)}, ${a}.`);Br({holding:e.root,node:t}),he(`${e.name} bought ${s}${n.seller?` from ${o}`:" whole"} for ${Y(n.price)} and adopted it, ${a}: its keys derive from ${e.name}'s seed now.`)});R("f-sell").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=V(I.node),r=R("sell-lot").value,s=Ci(t.elements.price.value),o=j.nodes.has(r);if(s===null)return he("Write a price in test BTC, for example 1.",!0);const i=Ne(r);await tt(a=>{u0(a,r,s)})&&(he(r===n.id?`${n.name}'s owner lists it whole at ${Y(s)}: any node can take it. The money in its tree went to the lab wallet first, its items go with it, and it's frozen until the ask is taken or withdrawn.`:`${n.name} lists ${i} at ${Y(s)}: any node can take it.${o?` The money in its tree went home to ${n.name} first, its items go with it, and it's frozen until the ask is taken or withdrawn.`:""}`),t.elements.price.value="")});for(const e of["offer-item","sell-lot","award-to"])R(e).addEventListener("change",()=>ds());R("send-max").addEventListener("click",()=>{const e=V(I.node),t=e&&xe(Z.keys,j,e);t&&(R("send-amount").value=Up(bu(Z.chain.coins(t.script))))});R("f-graduate").addEventListener("submit",async e=>{e.preventDefault();const t=V(I.node),n=V(t.parent);await zt("graduate",n.id,{of:t.id},(r,s)=>(Nu({node:t.id}),`${t.name} graduates from ${n.name}, ${s}. It's a holding of its own now.`))});R("f-close").addEventListener("submit",async e=>{e.preventDefault();const t=V(I.node);if(I.closing!==t.id)return I.closing=t.id,ds(),R("close-go").focus();I.closing=null,await zt("close",t.id,{},(n,r)=>`${t.name} is closed, ${r}.`)});R("close-keep").addEventListener("click",()=>{I.closing=null,ds(),R("close-go").focus()});for(const e of document.querySelectorAll("[data-verb]"))e.addEventListener("click",()=>{I.verb=e.dataset.verb,I.closing=null,ds()});for(const e of document.querySelectorAll("[data-rule]"))e.addEventListener("click",async()=>{const t=e.dataset.rule;await tt(n=>U$(n,t))&&he({split:"Each beat splits across the holdings that mine, by hashrate.",last:"Each beat goes whole to the holding that acts.",none:"Mainnet: no holding mines. Beats pay the lab wallet, and you fund holdings from it."}[t])});R("f-fund").addEventListener("submit",async e=>{var i;e.preventDefault();const t=e.currentTarget,n=t.elements.to.value,r=Ci(t.elements.amount.value);if(r===null)return he("Write an amount in test BTC, for example 5 (at most eight decimals).",!0);let s=null;if(!await tt(a=>{s=Q$(a,n,r)}))return;const o=ze.ledger.find(a=>a.txid===s);he(`The lab wallet funded ${(i=V(n))==null?void 0:i.name} with ${Y(r)}, ${o!=null&&o.beat?`at beat ${o.beat}`:"cued for the next beat"}.`),t.elements.amount.value=""});for(const e of document.querySelectorAll("[data-tempo]"))e.addEventListener("click",async()=>{const t=e.dataset.tempo,n=/^\d+$/.test(t)?Number(t):t;await tt(r=>H$(r,n,Date.now(),Ki(r,Pu(r)??I.holding)))&&he(t==="each"?"Each act is its own beat.":t==="manual"?"Acts are cued until you press Beat now.":`Acts are cued and land together on the next beat, at most ${t} seconds after the first.`)});R("beat-now").addEventListener("click",()=>h0(e=>{at(e,Ki(e,Pu(e)??I.holding))}));setInterval(()=>{p0();const{tempo:e,nextAt:t}=Z.clock;I.busy||document.hidden||typeof e!="number"||!Z.chain.mempool.length||t&&Date.now()R$(n,Date.now(),Ki(n,Pu(n)??I.holding)))},1e3);addEventListener("storage",e=>{(e.key===Li||e.key===null)&&d0()});function so(){I.replay&&(clearInterval(I.replay),I.replay=null,ju())}function XE(){const e=V(I.holding);if(!(!e||!lt())){if(hi(typeof e.born=="number"?e.born:lt()),I.beat===null)return he("Nothing to replay yet: this holding has one beat of history.");I.replay=setInterval(()=>{(I.beat===null||I.beat+1>=lt())&&so(),hi(I.beat===null?lt():I.beat+1)},800),ju()}}R("beat").addEventListener("input",e=>{so(),hi(Number(e.target.value))});R("replay").addEventListener("click",()=>I.replay?so():XE());for(const e of["to-now","past-now"])R(e).addEventListener("click",()=>{so(),hi(lt())});const ka=["system","light","dark"],O0=()=>{R("theme").textContent=`Theme: ${document.documentElement.dataset.theme??"system"}`};R("theme").addEventListener("click",()=>{const e=ka[(ka.indexOf(document.documentElement.dataset.theme??"system")+1)%ka.length];e==="system"?delete document.documentElement.dataset.theme:document.documentElement.dataset.theme=e;try{e==="system"?localStorage.removeItem("orgchain-theme"):localStorage.setItem("orgchain-theme",e)}catch{}O0()});function I0(e,t,n){const r=R("confirm");r.replaceChildren(E("span",{text:e}),E("button",{type:"button",class:"btn sm danger",text:t,onclick:()=>{r.hidden=!0,n()}}),E("button",{type:"button",class:"btn sm",text:"Cancel",onclick:()=>{r.hidden=!0}})),r.hidden=!1,r.querySelector("button").focus()}const JE={read:()=>{try{return Tu()}catch{return no()}}};async function C0(e,t){so(),await tt(n=>{Object.assign(n,e())},JE)&&(Object.assign(I,{holding:null,node:null,event:null,tx:null,beat:null,closing:null}),Lu(),he(t))}R("save").addEventListener("click",()=>{const e=E("a",{href:URL.createObjectURL(new Blob([Qp(Z)],{type:"application/json"})),download:`orgchain-lab-${new Date().toISOString().slice(0,10)}.json`});document.body.append(e),e.click(),e.remove(),setTimeout(()=>URL.revokeObjectURL(e.href),5e3),he("Saved a backup of this lab, test wallet included. Load it in any browser to carry on.")});R("load").addEventListener("click",()=>R("load-file").click());R("load-file").addEventListener("change",async e=>{var r;const t=(r=e.target.files)==null?void 0:r[0];if(e.target.value="",!t)return;let n;try{n=Jp(await t.text())}catch(s){return he(`${t.name} is not an Orgchain lab: ${s.message}`,!0)}I0(`Replace this browser's lab with ${t.name}?`,"Replace",()=>C0(()=>n,`Loaded ${t.name}.`))});R("reset").addEventListener("click",()=>I0("Erase this browser's lab: every holding, the chain and the test wallet?","Erase",()=>C0(no,"Erased. This is a fresh lab.")));O0();d0(); diff --git a/ventures/lineage/orgchain/assets/index-CpxUP_85.js b/ventures/lineage/orgchain/assets/index-CpxUP_85.js new file mode 100644 index 0000000..ac1282a --- /dev/null +++ b/ventures/lineage/orgchain/assets/index-CpxUP_85.js @@ -0,0 +1,2065 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();const Io=5e9,Ml=2**52,Xu=(e,t)=>[[Ml+e*Io,Ml+e*Io+t]];function Ju(e,t,n){const r=[];for(const[s,o]of e){const i=o-s;if(t>=i){t-=i;continue}const a=Math.min(n,i-t);if(a&&r.push([s+t,s+t+a]),n-=a,t=0,!n)break}return r}function Qu(e,t){var n;return(n=Ju(e,t,1)[0])==null?void 0:n[0]}function Bn(e,t){let n=0;for(const[r,s]of e){if(t>=r&&ti.ranges);let o=0;return e.vout.map(i=>{const a=Ju(s,o,Number(i.value));return o+=Number(i.value),a})}function $a(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function P0(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function tf(e,...t){if(!(e instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new TypeError(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function U0(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");$a(e.outputLen),$a(e.blockLen)}function N0(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function L0(e,t){tf(e);const n=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),Ct=(e,t)=>e<<32-t|e>>>t,R0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!R0)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function j0(e){if(typeof e!="string")throw new TypeError(`utf8ToBytes expected string, got ${typeof e}`);return new TextEncoder().encode(e)}function nf(e){if(typeof e=="string"&&(e=j0(e)),!(e instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof e})`);return e}let K0=class{clone(){return this._cloneInto()}};function rf(e){const t=r=>e().update(nf(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function M0(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const s=BigInt(32),o=BigInt(4294967295),i=Number(n>>s&o),a=Number(n&o),c=r?4:0,l=r?0:4;e.setUint32(t+c,i,r),e.setUint32(t+l,a,r)}let D0=class extends K0{constructor(t,n,r,s){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Vi(this.buffer)}update(t){Zi.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=nf(t);const o=t.length;for(let i=0;is-i&&(this.process(r,0),i=0);for(let u=i;uf.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;ue&t^~e&n,V0=(e,t,n)=>e&t^e&n^t&n,q0=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),fn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),dn=new Uint32Array(64);let sf=class extends D0{constructor(){super(64,32,8,!1),this.A=fn[0]|0,this.B=fn[1]|0,this.C=fn[2]|0,this.D=fn[3]|0,this.E=fn[4]|0,this.F=fn[5]|0,this.G=fn[6]|0,this.H=fn[7]|0}get(){const{A:t,B:n,C:r,D:s,E:o,F:i,G:a,H:c}=this;return[t,n,r,s,o,i,a,c]}set(t,n,r,s,o,i,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,n){for(let u=0;u<16;u++,n+=4)dn[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const d=dn[u-15],h=dn[u-2],g=Ct(d,7)^Ct(d,18)^d>>>3,p=Ct(h,17)^Ct(h,19)^h>>>10;dn[u]=p+dn[u-7]+g+dn[u-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){const d=Ct(a,6)^Ct(a,11)^Ct(a,25),h=f+d+Z0(a,c,l)+q0[u]+dn[u]|0,p=(Ct(r,2)^Ct(r,13)^Ct(r,22))+V0(r,s,o)|0;f=l,l=c,c=a,a=i+h|0,i=o,o=s,s=r,r=h+p|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,f=f+this.H|0,this.set(r,s,o,i,a,c,l,f)}roundClean(){dn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},z0=class extends sf{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}};const Ea=rf(()=>new sf);rf(()=>new z0);function F0(e,t){if(e.length>t)throw new TypeError(`Data is larger than array size: ${e.length} > ${t}`)}function W0(e){if(e.match(/[^a-fA-f0-9]/)!==null)throw new TypeError("Invalid characters in hex string: "+e);if(e.length%2!==0)throw new Error(`Length of hex string is invalid: ${e.length}`)}function G0(e){if(e>Number.MAX_SAFE_INTEGER)throw new TypeError("Number exceeds safe bounds!")}const{getRandomValues:Y0}=crypto??globalThis.crypto??window.crypto;function X0(e=32){if(typeof Y0=="function")return crypto.getRandomValues(new Uint8Array(e));throw new Error("Crypto module missing getRandomValues!")}function J0(e,t,n="be"){t===void 0&&(t=e.length),F0(e,t);const r=new Uint8Array(t).fill(0),s=n==="be"?0:t-e.length;return r.set(e,s),r}function of(e){let t,n=0;const r=e.reduce((o,i)=>o+i.length,0),s=new Uint8Array(r);for(t=0;t0||(i.length^a)>0?"":"1";c in o||l>0;)f=o[c],f=f>0?f*256+l:l,l=f/s|0,o[c]=f%s,c++;for(;c-- >0;)i+=r[o[c]];return n&&i.length%4>0?i+"=".repeat(4-i.length%4):i}function ng(e,t){const n=af(t),r=n.length,s=[],o=[];e=e.replace("=","");let i,a=0,c,l;for(i=0;i0||(o.length^i)>0||o.push(0);a in s||c>0;)l=s[a],l=l>0?l*r+c:c,c=l>>8,s[a]=l%256,a++}for(;a-- >0;)o.push(s[a]);return new Uint8Array(o)}function cf(e){return Ea(Ea(e))}function rg(e){const t=cf(e);return of([e,t.slice(0,4)])}function sg(e){const t=e.slice(0,-4),n=e.slice(-4);if(cf(t).slice(0,4).toString()!==n.toString())throw new Error("Invalid checksum!");return t}const Dl={encode:tg,decode:ng},lf={encode:e=>{const t=rg(e);return Dl.encode(t,"base58")},decode:e=>{const t=Dl.decode(e,"base58");return sg(t)}},uf="qpzry9x8gf2tvdw0s3jn54khce6mua7l",og=[996825010,642813549,513874426,1027748829,705979059],Co=[{version:0,name:"bech32",const:1},{version:1,name:"bech32m",const:734539939}];function ff(e){let t=1;for(let n=0;n>25;t=(t&33554431)<<5^e[n];for(let s=0;s<5;++s)(r>>s&1)!==0&&(t^=og[s])}return t}function df(e){const t=[];let n;for(n=0;n>5);for(t.push(0),n=0;n>5*(5-i)&31);return o}function hf(e,t,n,r=!0){const s=[];let o=0,i=0;const a=(1<>t>0)throw new Error("Failed to perform base conversion. Invalid value: "+String(l));for(o=(o<=n;)i-=n,s.push(o>>i&a)}if(r)i>0&&s.push(o<=t||(o<0)throw new Error("Failed to perform base conversion. Invalid Size!");return s}function cg(e,t,n){const r=t.concat(ag(e,t,n));let s=e+"1";for(let o=0;oo.version===t[0])??Co[0];if(!ig(r,t,s))throw new Error("Checksum verification failed!");return[r,t.slice(0,t.length-6)]}function lg(e){let t,n,r=!1,s=!1;for(t=0;t126)return!1;n>=97&&n<=122&&(r=!0),n>=65&&n<=90&&(s=!0)}return!(r&&s)}function ug(e){const t=e.lastIndexOf("1");return!(t<1||t+7>e.length||e.length>90)}function fg(e,t="bc",n=0){const r=[n,...hf([...e],8,5)],s=Co.find(i=>i.version===n)??Co[0],o=cg(t,r,s);return gf(o),o}function gf(e){e=e.toLowerCase();const t=e.split("1",1)[0],[n,r]=pf(e),s=hf(r.slice(1),5,8,!1),o=s.length;switch(!0){case t!==n:throw new Error("Returned hrp string is invalid.");case(s===null||o<2||o>40):throw new Error("Decoded string is invalid or out of spec.");case r[0]>16:throw new Error("Returned version bit is out of range.");default:return Uint8Array.from(s)}}function dg(e){e=e.toLowerCase();const[t,n]=pf(e);return n[0]}const mf={encode:fg,decode:gf,version:dg},yf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",wf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",hg=new TextEncoder;function bf(e,t=!1,n=!0){typeof e=="string"&&(e=hg.encode(e));const r=t?wf:yf;let s="",o=0,i=0;for(let a=0;a=6;)o-=6,s+=r[i>>o&63];if(o>0)for(i<<=6-o,s+=r[i&63];o<6;)s+=n?"=":"",o+=2;return s}function xf(e,t=!1){const n=t||e.includes("-")||e.includes("_")?wf.split(""):yf.split("");e=e.replace(/=+$/,"");const r=e.split("");let s=0,o=0;const i=[];for(let a=0;a=8&&(s-=8,i.push(o>>>s&255))}return new Uint8Array(i)}const vf={encode:bf,decode:xf},kf={encode:e=>bf(e,!0,!1),decode:e=>xf(e,!0)},pg=BigInt(0),gg=BigInt(255),$f=BigInt(256);function mg(e){if(e<=0xffn)return 1;if(e<=0xffffn)return 2;if(e<=0xffffffffn)return 4;if(e<=0xffffffffffffffffn)return 8;if(e<=0xffffffffffffffffffffffffffffffffn)return 16;if(e<=0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn)return 32;throw new TypeError("Must specify a fixed buffer size for bigints greater than 32 bytes.")}function yg(e,t,n="be"){t===void 0&&(t=mg(e));const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(;e>pg;){const a=e&gg,c=Number(a);r?o.setUint8(i++,c):o.setUint8(i--,c),e=(e-a)/$f}return new Uint8Array(s)}function wg(e){let t=BigInt(0);for(let n=e.length-1;n>=0;n--)t=t*$f+BigInt(e[n]);return BigInt(t)}function bg(e){const t=e.split("").map(Number);if(t.length%8!==0)throw new Error(`Binary array is invalid length: ${e.length}`);const n=new Uint8Array(t.length/8);for(let r=0,s=0;r255)throw new Error(`Invalid byte value: ${r}. Byte values must be between 0 and 255.`);for(let s=7;s>=0;s--,n++)t[n]=r>>s&1}return t.join("")}function vg(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=4294967295)return 4;throw new TypeError("Numbers larger than 4 bytes must specify a fixed size!")}function kg(e,t,n="be"){t===void 0&&(t=vg(e));const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(;e>0;){const a=e&255;r?o.setUint8(i++,e):o.setUint8(i--,e),e=(e-a)/256}return new Uint8Array(s)}function $g(e){let t=0;for(let n=e.length-1;n>=0;n--)t=t*256+e[n],G0(t);return t}const Eg=new TextEncoder,Sg=new TextDecoder;function pc(e){return Eg.encode(e)}function qi(e){return Sg.decode(e)}function _g(e,t){W0(e);const n=e.length/2;if(t===void 0&&(t=n),n>t)throw new TypeError(`Hex string is larger than array size: ${n} > ${t}`);return t}function Ag(e,t,n="le"){t=_g(e,t);const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(let a=0;atypeof r=="bigint"?`${r}n`:r);return pc(t)}function Og(e,t,n){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Uint8Array)return J0(e,t,n);if(typeof e=="string")return Ag(e,t,n);if(typeof e=="bigint")return yg(e,t,n);if(typeof e=="number")return kg(e,t,n);if(typeof e=="boolean")return Uint8Array.of(e?1:0);throw TypeError("Unsupported format:"+typeof e)}var re;let T=(re=class extends Uint8Array{static random(t=32){const n=X0(t);return new re(n,t)}constructor(t,n,r){const s=Og(t,n,r);super(s)}get arr(){return[...this]}get num(){return this.toNum()}get big(){return this.toBig()}get str(){return this.toStr()}get hex(){return this.toHex()}get raw(){return new Uint8Array(this)}get bin(){return this.toBin()}get b58chk(){return this.tob58chk()}get base64(){return this.toBase64()}get b64url(){return this.toB64url()}get digest(){return this.toHash()}get id(){return this.toHash().hex}get stream(){return new as(this)}toNum(t="be"){const n=t==="be"?this.reverse():this;return $g(n)}toBin(){return xg(this)}toBig(t="be"){const n=t==="be"?this.reverse():this;return wg(n)}toHash(){const t=Ea(this);return new re(t)}toJson(){const t=qi(this);return JSON.parse(t)}toBech32(t,n=0){return mf.encode(this,t,n)}toStr(){return qi(this)}toHex(){return Bg(this)}toBytes(){return new Uint8Array(this)}tob58chk(){return lf.encode(this)}toBase64(){return vf.encode(this)}toB64url(){return kf.encode(this)}prepend(t){return re.join([re.bytes(t),this])}append(t){return re.join([this,re.bytes(t)])}slice(t,n){const r=new Uint8Array(this).slice(t,n);return new re(r)}subarray(t,n){const r=new Uint8Array(this).subarray(t,n);return new re(r)}reverse(){const t=new Uint8Array(this).reverse();return new re(t)}write(t,n){const r=re.bytes(t);this.set(r,n)}prefixSize(t){const n=re.varInt(this.length,t);return re.join([n,this])}static from(t){return new re(Uint8Array.from(t))}static of(...t){return new re(Uint8Array.of(...t))}static join(t){const n=t.map(s=>re.bytes(s)),r=of(n);return new re(r)}static varInt(t,n){if(t<253)return re.num(t,1);if(t<65536)return re.of(253,...re.num(t,2,n));if(t<4294967296)return re.of(254,...re.num(t,4,n));if(BigInt(t)<0x10000000000000000n)return re.of(255,...re.num(t,8,n));throw new Error(`Value is too large: ${t}`)}},re.num=Ig,re.big=Pg,re.bin=Cg,re.raw=Ug,re.str=Ng,re.hex=Lg,re.bytes=Hg,re.json=Rg,re.base64=jg,re.b64url=Kg,re.bech32=Mg,re.b58chk=Dg,re.encode=pc,re.decode=qi,re);function Ig(e,t,n){return new T(e,t,n)}function Cg(e,t,n){return new T(bg(e),t,n)}function Pg(e,t,n){return new T(e,t,n)}function Ug(e,t,n){return new T(e,t,n)}function Ng(e,t,n){return new T(pc(e),t,n)}function Lg(e,t,n){return new T(e,t,n)}function Hg(e,t,n){return new T(e,t,n)}function Rg(e){return new T(Tg(e))}function jg(e){return new T(vf.decode(e))}function Kg(e){return new T(kf.decode(e))}function Mg(e){return new T(mf.decode(e))}function Dg(e){return new T(lf.decode(e))}let as=class{constructor(t){this.data=T.bytes(t),this.size=this.data.length}peek(t){if(t>this.size)throw new Error(`Size greater than stream: ${t} > ${this.size}`);return new T(this.data.slice(0,t))}read(t){t=t??this.readSize();const n=this.peek(t);return this.data=this.data.slice(t),this.size=this.data.length,n}readSize(t){const n=this.read(1).num;switch(!0){case(n>=0&&n<253):return n;case n===253:return this.read(2).toNum(t);case n===254:return this.read(4).toNum(t);case n===255:return this.read(8).toNum(t);default:throw new Error(`Varint is out of range: ${n}`)}}};function zt(e,t){const n=T.bytes(e);if(n.length!==t)throw new Error(`Invalid input size: ${n.hex} !== ${t}`)}function Je(e,t){if(t)throw new Error(e);return!1}function Eo(e,...t){const n=T.str(e).digest.raw,r=t.map(s=>T.bytes(s));return T.join([n,n,T.join(r)]).digest}const Ef={OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_SUCCESS80:80,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_SUCCESS98:98,OP_IF:99,OP_NOTIF:100,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_SUCCESS126:126,OP_SUCCESS127:127,OP_SUCCESS128:128,OP_SUCCESS129:129,OP_SIZE:130,OP_SUCCESS131:131,OP_SUCCESS132:132,OP_SUCCESS133:133,OP_SUCCESS134:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_SUCCESS137:137,OP_SUCCESS138:138,OP_1ADD:139,OP_1SUB:140,OP_SUCCESS141:141,OP_SUCCESS142:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_SUCCESS149:149,OP_SUCCESS150:150,OP_SUCCESS151:151,OP_SUCCESS152:152,OP_SUCCESS153:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_CHECKLOCKTIMEVERIFY:177,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_CHECKSIGADD:186,OP_SUCCESS187:187,OP_SUCCESS188:188,OP_SUCCESS189:189,OP_SUCCESS190:190,OP_SUCCESS191:191,OP_SUCCESS192:192,OP_SUCCESS193:193,OP_SUCCESS194:194,OP_SUCCESS195:195,OP_SUCCESS196:196,OP_SUCCESS197:197,OP_SUCCESS198:198,OP_SUCCESS199:199,OP_SUCCESS200:200,OP_SUCCESS201:201,OP_SUCCESS202:202,OP_SUCCESS203:203,OP_SUCCESS204:204,OP_SUCCESS205:205,OP_SUCCESS206:206,OP_SUCCESS207:207,OP_SUCCESS208:208,OP_SUCCESS209:209,OP_SUCCESS210:210,OP_SUCCESS211:211,OP_SUCCESS212:212,OP_SUCCESS213:213,OP_SUCCESS214:214,OP_SUCCESS215:215,OP_SUCCESS216:216,OP_SUCCESS217:217,OP_SUCCESS218:218,OP_SUCCESS219:219,OP_SUCCESS220:220,OP_SUCCESS221:221,OP_SUCCESS222:222,OP_SUCCESS223:223,OP_SUCCESS224:224,OP_SUCCESS225:225,OP_SUCCESS226:226,OP_SUCCESS227:227,OP_SUCCESS228:228,OP_SUCCESS229:229,OP_SUCCESS230:230,OP_SUCCESS231:231,OP_SUCCESS232:232,OP_SUCCESS233:233,OP_SUCCESS234:234,OP_SUCCESS235:235,OP_SUCCESS236:236,OP_SUCCESS237:237,OP_SUCCESS238:238,OP_SUCCESS239:239,OP_SUCCESS240:240,OP_SUCCESS241:241,OP_SUCCESS242:242,OP_SUCCESS243:243,OP_SUCCESS244:244,OP_SUCCESS245:245,OP_SUCCESS246:246,OP_SUCCESS247:247,OP_SUCCESS248:248,OP_SUCCESS249:249,OP_SUCCESS250:250,OP_SUCCESS251:251,OP_SUCCESS252:252,OP_SUCCESS253:253,OP_SUCCESS254:254};function Zg(e){if(e>186&&e<255)return"OP_SUCCESS"+String(e);for(const[t,n]of Object.entries(Ef))if(n===e)return t;throw new Error("OPCODE not found:"+String(e))}function Vg(e){for(const[t,n]of Object.entries(Ef))if(t===e)return Number(n);throw new Error("OPCODE not found:"+e)}function qg(e){switch(!0){case e===0:return"opcode";case(e>=1&&e<=75):return"varint";case e===76:return"pushdata1";case e===77:return"pushdata2";case e===78:return"pushdata4";case e<=254:return"opcode";default:throw new Error(`Invalid word range: ${e}`)}}function zg(e){const r=[];switch(!0){case typeof e!="number":return!1;case e===0:return!0;case r.includes(e):return!1;case(750?T.join(t):new Uint8Array}function Fg(e){let t=new Uint8Array;if(typeof e=="string"){if(e.startsWith("OP_"))return T.num(Vg(e),1);un(e)?t=T.hex(e):t=T.str(e)}else t=T.bytes(e);if(t.length===1)return t[0]!==0&&t[0]<=16?(t[0]+=80,t):(t[0]>128&&t[0]<=255&&(t=new Uint8Array([t[0],0])),T.join([Zl(t.length),t]));if(t.length>Po){const n=Wg(t);return _f(n)}else return T.join([Zl(t.length),t])}function Zl(e){const t=T.num(76,1),n=T.num(77,1);switch(!0){case e<=75:return T.num(e);case(e>75&&e<256):return T.join([t,T.num(e,1,"le")]);case(e>=256&&e<=Po):return T.join([n,T.num(e,2,"le")]);default:throw new Error("Invalid word size:"+e.toString())}}function Wg(e){const t=[],n=new as(e);for(;n.size>Po;)t.push(n.read(Po));return t.push(n.read(n.size)),t}function gc(e,t=!1){let n=T.bytes(e);if(t){const s=n.stream.readSize("le");if(n=n.slice(1),n.length!==s)throw new Error(`Varint does not match stream size: ${s} !== ${n.length}`)}return Gg(n)}function Gg(e){const t=new as(e),n=[],r=t.size;let s,o,i,a=0;for(;a0&&!t.includes(e.length))throw new TypeError(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function tm(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Sa(e.outputLen),Sa(e.blockLen)}function nm(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function rm(e,t){Af(e);const n=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),Pt=(e,t)=>e<<32-t|e>>>t,om=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!om)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function im(e){if(typeof e!="string")throw new TypeError(`utf8ToBytes expected string, got ${typeof e}`);return new TextEncoder().encode(e)}function mc(e){if(typeof e=="string"&&(e=im(e)),!(e instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof e})`);return e}function am(...e){if(!e.every(r=>r instanceof Uint8Array))throw new Error("Uint8Array list expected");if(e.length===1)return e[0];const t=e.reduce((r,s)=>r+s.length,0),n=new Uint8Array(t);for(let r=0,s=0;re().update(mc(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function cm(e=32){if(zi&&typeof zi.getRandomValues=="function")return zi.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function lm(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const s=BigInt(32),o=BigInt(4294967295),i=Number(n>>s&o),a=Number(n&o),c=r?4:0,l=r?0:4;e.setUint32(t+c,i,r),e.setUint32(t+l,a,r)}let um=class extends Bf{constructor(t,n,r,s){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Fi(this.buffer)}update(t){Jn.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=mc(t);const o=t.length;for(let i=0;is-i&&(this.process(r,0),i=0);for(let u=i;uf.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;ue&t^~e&n,dm=(e,t,n)=>e&t^e&n^t&n,hm=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),hn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),pn=new Uint32Array(64);let Of=class extends um{constructor(){super(64,32,8,!1),this.A=hn[0]|0,this.B=hn[1]|0,this.C=hn[2]|0,this.D=hn[3]|0,this.E=hn[4]|0,this.F=hn[5]|0,this.G=hn[6]|0,this.H=hn[7]|0}get(){const{A:t,B:n,C:r,D:s,E:o,F:i,G:a,H:c}=this;return[t,n,r,s,o,i,a,c]}set(t,n,r,s,o,i,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,n){for(let u=0;u<16;u++,n+=4)pn[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const d=pn[u-15],h=pn[u-2],g=Pt(d,7)^Pt(d,18)^d>>>3,p=Pt(h,17)^Pt(h,19)^h>>>10;pn[u]=p+pn[u-7]+g+pn[u-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){const d=Pt(a,6)^Pt(a,11)^Pt(a,25),h=f+d+fm(a,c,l)+hm[u]+pn[u]|0,p=(Pt(r,2)^Pt(r,13)^Pt(r,22))+dm(r,s,o)|0;f=l,l=c,c=a,a=i+h|0,i=o,o=s,s=r,r=h+p|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,f=f+this.H|0,this.set(r,s,o,i,a,c,l,f)}roundClean(){pn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},pm=class extends Of{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}};const If=Tf(()=>new Of);Tf(()=>new pm);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const gm=BigInt(0),yc=BigInt(1),mm=BigInt(2),gi=e=>e instanceof Uint8Array,ym=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Zr(e){if(!gi(e))throw new Error("Uint8Array expected");let t="";for(let n=0;nVr(e.toString(16).padStart(t*2,"0")),Pf=(e,t)=>Lr(e,t).reverse(),wm=e=>Vr(Cf(e));function mt(e,t,n){let r;if(typeof t=="string")try{r=Vr(t)}catch(o){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${o}`)}else if(gi(t))r=Uint8Array.from(t);else throw new Error(`${e} must be hex string or Uint8Array`);const s=r.length;if(typeof n=="number"&&s!==n)throw new Error(`${e} expected ${n} bytes, got ${s}`);return r}function kt(...e){const t=new Uint8Array(e.reduce((r,s)=>r+s.length,0));let n=0;return e.forEach(r=>{if(!gi(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}function bm(e,t){if(e.length!==t.length)return!1;for(let n=0;n0n;e>>=yc,t+=1);return t}const vm=(e,t)=>e>>BigInt(t)&1n,km=(e,t,n)=>e|(n?yc:gm)<(mm<new Uint8Array(e),Vl=e=>Uint8Array.from(e);function Uf(e,t,n){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=Wi(e),s=Wi(e),o=0;const i=()=>{r.fill(1),s.fill(0),o=0},a=(...u)=>n(s,r,...u),c=(u=Wi())=>{s=a(Vl([0]),u),r=a(),u.length!==0&&(s=a(Vl([1]),u),r=a())},l=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const d=[];for(;u{i(),c(u);let h;for(;!(h=d(l()));)c();return i(),h}}const $m={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function cs(e,t,n={}){const r=(s,o,i)=>{const a=$m[o];if(typeof a!="function")throw new Error(`Invalid validator "${o}", expected function`);const c=e[s];if(!(i&&c===void 0)&&!a(c,e))throw new Error(`Invalid param ${String(s)}=${c} (${typeof c}), expected ${o}`)};for(const[s,o]of Object.entries(t))r(s,o,!1);for(const[s,o]of Object.entries(n))r(s,o,!0);return e}var Em=Object.freeze({__proto__:null,bitGet:vm,bitLen:xm,bitMask:xc,bitSet:km,bytesToHex:Zr,bytesToNumberBE:In,bytesToNumberLE:bc,concatBytes:kt,createHmacDrbg:Uf,ensureBytes:mt,equalBytes:bm,hexToBytes:Vr,hexToNumber:wc,numberToBytesBE:Lr,numberToBytesLE:Pf,numberToHexUnpadded:Cf,numberToVarBytesBE:wm,utf8ToBytes:mi,validateObject:cs});/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const qe=BigInt(0),He=BigInt(1),Gn=BigInt(2),Sm=BigInt(3),_a=BigInt(4),ql=BigInt(5),zl=BigInt(8);BigInt(9);BigInt(16);function Qe(e,t){const n=e%t;return n>=qe?n:t+n}function _m(e,t,n){if(n<=qe||t 0");if(n===He)return qe;let r=He;for(;t>qe;)t&He&&(r=r*e%n),e=e*e%n,t>>=He;return r}function gt(e,t,n){let r=e;for(;t-- >qe;)r*=r,r%=n;return r}function Aa(e,t){if(e===qe||t<=qe)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let n=Qe(e,t),r=t,s=qe,o=He;for(;n!==qe;){const a=r/n,c=r%n,l=s-o*a;r=n,n=c,s=o,o=l}if(r!==He)throw new Error("invert: does not exist");return Qe(s,t)}function Am(e){const t=(e-He)/Gn;let n,r,s;for(n=e-He,r=0;n%Gn===qe;n/=Gn,r++);for(s=Gn;s(r[s]="function",r),t);return cs(e,n)}function Om(e,t,n){if(n 0");if(n===qe)return e.ONE;if(n===He)return t;let r=e.ONE,s=t;for(;n>qe;)n&He&&(r=e.mul(r,s)),s=e.sqr(s),n>>=He;return r}function Im(e,t){const n=new Array(t.length),r=t.reduce((o,i,a)=>e.is0(i)?o:(n[a]=o,e.mul(o,i)),e.ONE),s=e.inv(r);return t.reduceRight((o,i,a)=>e.is0(i)?o:(n[a]=e.mul(o,n[a]),e.mul(o,i)),s),n}function vc(e,t){const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Lf(e,t,n=!1,r={}){if(e<=qe)throw new Error(`Expected Fp ORDER > 0, got ${e}`);const{nBitLength:s,nByteLength:o}=vc(e,t);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");const i=Bm(e),a=Object.freeze({ORDER:e,BITS:s,BYTES:o,MASK:xc(s),ZERO:qe,ONE:He,create:c=>Qe(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return qe<=c&&cc===qe,isOdd:c=>(c&He)===He,neg:c=>Qe(-c,e),eql:(c,l)=>c===l,sqr:c=>Qe(c*c,e),add:(c,l)=>Qe(c+l,e),sub:(c,l)=>Qe(c-l,e),mul:(c,l)=>Qe(c*l,e),pow:(c,l)=>Om(a,c,l),div:(c,l)=>Qe(c*Aa(l,e),e),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Aa(c,e),sqrt:r.sqrt||(c=>i(a,c)),invertBatch:c=>Im(a,c),cmov:(c,l,f)=>f?l:c,toBytes:c=>n?Pf(c,o):Lr(c,o),fromBytes:c=>{if(c.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${c.length}`);return n?bc(c):In(c)}});return Object.freeze(a)}function Cm(e,t,n=!1){e=mt("privateHash",e);const r=e.length,s=vc(t).nByteLength+8;if(s<24||r1024)throw new Error(`hashToPrivateScalar: expected ${s}-1024 bytes of input, got ${r}`);const o=n?bc(e):In(e);return Qe(o,t-He)+He}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Pm=BigInt(0),Gi=BigInt(1);function Um(e,t){const n=(s,o)=>{const i=o.negate();return s?i:o},r=s=>{const o=Math.ceil(t/s)+1,i=2**(s-1);return{windows:o,windowSize:i}};return{constTimeNegate:n,unsafeLadder(s,o){let i=e.ZERO,a=s;for(;o>Pm;)o&Gi&&(i=i.add(a)),a=a.double(),o>>=Gi;return i},precomputeWindow(s,o){const{windows:i,windowSize:a}=r(o),c=[];let l=s,f=l;for(let u=0;u>=h,m>c&&(m-=d,i+=Gi);const w=p,y=p+Math.abs(m)-1,b=g%2!==0,_=m<0;m===0?f=f.add(n(b,o[w])):l=l.add(n(_,o[y]))}return{p:l,f}},wNAFCached(s,o,i,a){const c=s._WINDOW_SIZE||1;let l=o.get(s);return l||(l=this.precomputeWindow(s,c),c!==1&&o.set(s,a(l))),this.wNAF(c,l,i)}}}function Hf(e){return Nf(e.Fp),cs(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...vc(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Nm(e){const t=Hf(e);cs(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:n,Fp:r,a:s}=t;if(n){if(!r.eql(s,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof n!="object"||typeof n.beta!="bigint"||typeof n.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}const{bytesToNumberBE:Lm,hexToBytes:Hm}=Em,Qn={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){const{Err:t}=Qn;if(e.length<2||e[0]!==2)throw new t("Invalid signature integer tag");const n=e[1],r=e.subarray(2,n+2);if(!n||r.length!==n)throw new t("Invalid signature integer: wrong length");if(r[0]===0&&r[1]<=127)throw new t("Invalid signature integer: trailing length");return{d:Lm(r),l:e.subarray(n+2)}},toSig(e){const{Err:t}=Qn,n=typeof e=="string"?Hm(e):e;if(!(n instanceof Uint8Array))throw new Error("ui8a expected");let r=n.length;if(r<2||n[0]!=48)throw new t("Invalid signature tag");if(n[1]!==r-2)throw new t("Invalid signature: incorrect length");const{d:s,l:o}=Qn._parseInt(n.subarray(2)),{d:i,l:a}=Qn._parseInt(o);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:s,s:i}},hexFromSig(e){const t=l=>Number.parseInt(l[0],16)>=8?"00"+l:l,n=l=>{const f=l.toString(16);return f.length&1?`0${f}`:f},r=t(n(e.s)),s=t(n(e.r)),o=r.length/2,i=s.length/2,a=n(o),c=n(i);return`30${n(i+o+4)}02${c}${s}02${a}${r}`}},$t=BigInt(0),je=BigInt(1),Yt=BigInt(2),Uo=BigInt(3),Fl=BigInt(4);function Rm(e){const t=Nm(e),{Fp:n}=t,r=t.toBytes||((g,p,m)=>{const w=p.toAffine();return kt(Uint8Array.from([4]),n.toBytes(w.x),n.toBytes(w.y))}),s=t.fromBytes||(g=>{const p=g.subarray(1),m=n.fromBytes(p.subarray(0,n.BYTES)),w=n.fromBytes(p.subarray(n.BYTES,2*n.BYTES));return{x:m,y:w}});function o(g){const{a:p,b:m}=t,w=n.sqr(g),y=n.mul(w,g);return n.add(n.add(y,n.mul(g,p)),m)}function i(g){return typeof g=="bigint"&&$tn.eql(b,n.ZERO);return y(m)&&y(w)?u.ZERO:new u(m,w,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(p){const m=n.invertBatch(p.map(w=>w.pz));return p.map((w,y)=>w.toAffine(m[y])).map(u.fromAffine)}static fromHex(p){const m=u.fromAffine(s(mt("pointHex",p)));return m.assertValidity(),m}static fromPrivateKey(p){return u.BASE.multiply(c(p))}_setWindowSize(p){this._WINDOW_SIZE=p,l.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint)return;throw new Error("bad point: ZERO")}const{x:p,y:m}=this.toAffine();if(!n.isValid(p)||!n.isValid(m))throw new Error("bad point: x or y not FE");const w=n.sqr(m),y=o(p);if(!n.eql(w,y))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:p}=this.toAffine();if(n.isOdd)return!n.isOdd(p);throw new Error("Field doesn't support isOdd")}equals(p){f(p);const{px:m,py:w,pz:y}=this,{px:b,py:_,pz:$}=p,x=n.eql(n.mul(m,$),n.mul(b,y)),C=n.eql(n.mul(w,$),n.mul(_,y));return x&&C}negate(){return new u(this.px,n.neg(this.py),this.pz)}double(){const{a:p,b:m}=t,w=n.mul(m,Uo),{px:y,py:b,pz:_}=this;let $=n.ZERO,x=n.ZERO,C=n.ZERO,P=n.mul(y,y),O=n.mul(b,b),N=n.mul(_,_),R=n.mul(y,b);return R=n.add(R,R),C=n.mul(y,_),C=n.add(C,C),$=n.mul(p,C),x=n.mul(w,N),x=n.add($,x),$=n.sub(O,x),x=n.add(O,x),x=n.mul($,x),$=n.mul(R,$),C=n.mul(w,C),N=n.mul(p,N),R=n.sub(P,N),R=n.mul(p,R),R=n.add(R,C),C=n.add(P,P),P=n.add(C,P),P=n.add(P,N),P=n.mul(P,R),x=n.add(x,P),N=n.mul(b,_),N=n.add(N,N),P=n.mul(N,R),$=n.sub($,P),C=n.mul(N,O),C=n.add(C,C),C=n.add(C,C),new u($,x,C)}add(p){f(p);const{px:m,py:w,pz:y}=this,{px:b,py:_,pz:$}=p;let x=n.ZERO,C=n.ZERO,P=n.ZERO;const O=t.a,N=n.mul(t.b,Uo);let R=n.mul(m,b),B=n.mul(w,_),k=n.mul(y,$),E=n.add(m,w),v=n.add(b,_);E=n.mul(E,v),v=n.add(R,B),E=n.sub(E,v),v=n.add(m,y);let A=n.add(b,$);return v=n.mul(v,A),A=n.add(R,k),v=n.sub(v,A),A=n.add(w,y),x=n.add(_,$),A=n.mul(A,x),x=n.add(B,k),A=n.sub(A,x),P=n.mul(O,v),x=n.mul(N,k),P=n.add(x,P),x=n.sub(B,P),P=n.add(B,P),C=n.mul(x,P),B=n.add(R,R),B=n.add(B,R),k=n.mul(O,k),v=n.mul(N,v),B=n.add(B,k),k=n.sub(R,k),k=n.mul(O,k),v=n.add(v,k),R=n.mul(B,v),C=n.add(C,R),R=n.mul(A,v),x=n.mul(E,x),x=n.sub(x,R),R=n.mul(E,B),P=n.mul(A,P),P=n.add(P,R),new u(x,C,P)}subtract(p){return this.add(p.negate())}is0(){return this.equals(u.ZERO)}wNAF(p){return h.wNAFCached(this,l,p,m=>{const w=n.invertBatch(m.map(y=>y.pz));return m.map((y,b)=>y.toAffine(w[b])).map(u.fromAffine)})}multiplyUnsafe(p){const m=u.ZERO;if(p===$t)return m;if(a(p),p===je)return this;const{endo:w}=t;if(!w)return h.unsafeLadder(this,p);let{k1neg:y,k1:b,k2neg:_,k2:$}=w.splitScalar(p),x=m,C=m,P=this;for(;b>$t||$>$t;)b&je&&(x=x.add(P)),$&je&&(C=C.add(P)),P=P.double(),b>>=je,$>>=je;return y&&(x=x.negate()),_&&(C=C.negate()),C=new u(n.mul(C.px,w.beta),C.py,C.pz),x.add(C)}multiply(p){a(p);let m=p,w,y;const{endo:b}=t;if(b){const{k1neg:_,k1:$,k2neg:x,k2:C}=b.splitScalar(m);let{p:P,f:O}=this.wNAF($),{p:N,f:R}=this.wNAF(C);P=h.constTimeNegate(_,P),N=h.constTimeNegate(x,N),N=new u(n.mul(N.px,b.beta),N.py,N.pz),w=P.add(N),y=O.add(R)}else{const{p:_,f:$}=this.wNAF(m);w=_,y=$}return u.normalizeZ([w,y])[0]}multiplyAndAddUnsafe(p,m,w){const y=u.BASE,b=($,x)=>x===$t||x===je||!$.equals(y)?$.multiplyUnsafe(x):$.multiply(x),_=b(this,m).add(b(p,w));return _.is0()?void 0:_}toAffine(p){const{px:m,py:w,pz:y}=this,b=this.is0();p==null&&(p=b?n.ONE:n.inv(y));const _=n.mul(m,p),$=n.mul(w,p),x=n.mul(y,p);if(b)return{x:n.ZERO,y:n.ZERO};if(!n.eql(x,n.ONE))throw new Error("invZ was invalid");return{x:_,y:$}}isTorsionFree(){const{h:p,isTorsionFree:m}=t;if(p===je)return!0;if(m)return m(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:p,clearCofactor:m}=t;return p===je?this:m?m(u,this):this.multiplyUnsafe(t.h)}toRawBytes(p=!0){return this.assertValidity(),r(u,this,p)}toHex(p=!0){return Zr(this.toRawBytes(p))}}u.BASE=new u(t.Gx,t.Gy,n.ONE),u.ZERO=new u(n.ZERO,n.ONE,n.ZERO);const d=t.nBitLength,h=Um(u,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:i}}function jm(e){const t=Hf(e);return cs(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Km(e){const t=jm(e),{Fp:n,n:r}=t,s=n.BYTES+1,o=2*n.BYTES+1;function i(v){return $tZr(Lr(v,t.nByteLength));function g(v){const A=r>>je;return v>A}function p(v){return g(v)?a(-v):v}const m=(v,A,U)=>In(v.slice(A,U));class w{constructor(A,U,K){this.r=A,this.s=U,this.recovery=K,this.assertValidity()}static fromCompact(A){const U=t.nByteLength;return A=mt("compactSignature",A,U*2),new w(m(A,0,U),m(A,U,2*U))}static fromDER(A){const{r:U,s:K}=Qn.toSig(mt("DER",A));return new w(U,K)}assertValidity(){if(!d(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!d(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(A){return new w(this.r,this.s,A)}recoverPublicKey(A){const{r:U,s:K,recovery:H}=this,M=C(mt("msgHash",A));if(H==null||![0,1,2,3].includes(H))throw new Error("recovery id invalid");const V=H===2||H===3?U+t.n:U;if(V>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const G=(H&1)===0?"02":"03",fe=l.fromHex(G+h(V)),ce=c(V),ne=a(-M*ce),ge=a(K*ce),me=l.BASE.multiplyAndAddUnsafe(fe,ne,ge);if(!me)throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Vr(this.toDERHex())}toDERHex(){return Qn.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Vr(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}const y={isValidPrivateKey(v){try{return f(v),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{const v=t.randomBytes(n.BYTES+8),A=Cm(v,r);return Lr(A,t.nByteLength)},precompute(v=8,A=l.BASE){return A._setWindowSize(v),A.multiply(BigInt(3)),A}};function b(v,A=!0){return l.fromPrivateKey(v).toRawBytes(A)}function _(v){const A=v instanceof Uint8Array,U=typeof v=="string",K=(A||U)&&v.length;return A?K===s||K===o:U?K===2*s||K===2*o:v instanceof l}function $(v,A,U=!0){if(_(v))throw new Error("first arg must be private key");if(!_(A))throw new Error("second arg must be public key");return l.fromHex(A).multiply(f(v)).toRawBytes(U)}const x=t.bits2int||function(v){const A=In(v),U=v.length*8-t.nBitLength;return U>0?A>>BigInt(U):A},C=t.bits2int_modN||function(v){return a(x(v))},P=xc(t.nBitLength);function O(v){if(typeof v!="bigint")throw new Error("bigint expected");if(!($t<=v&&vpe in U))throw new Error("sign() legacy options not supported");const{hash:K,randomBytes:H}=t;let{lowS:M,prehash:V,extraEntropy:G}=U;M==null&&(M=!0),v=mt("msgHash",v),V&&(v=mt("prehashed msgHash",K(v)));const fe=C(v),ce=f(A),ne=[O(ce),O(fe)];if(G!=null){const pe=G===!0?H(n.BYTES):G;ne.push(mt("extraEntropy",pe,n.BYTES))}const ge=kt(...ne),me=fe;function Le(pe){const _e=x(pe);if(!d(_e))return;const Wt=c(_e),pt=l.BASE.multiply(_e).toAffine(),We=a(pt.x);if(We===$t)return;const Gt=a(Wt*a(me+We*ce));if(Gt===$t)return;let hs=(pt.x===We?0:2)|Number(pt.y&je),Kl=Gt;return M&&g(Gt)&&(Kl=p(Gt),hs^=1),new w(We,Kl,hs)}return{seed:ge,k2sig:Le}}const R={lowS:t.lowS,prehash:!1},B={lowS:t.lowS,prehash:!1};function k(v,A,U=R){const{seed:K,k2sig:H}=N(v,A,U);return Uf(t.hash.outputLen,t.nByteLength,t.hmac)(K,H)}l.BASE._setWindowSize(8);function E(v,A,U,K=B){var pt;const H=v;if(A=mt("msgHash",A),U=mt("publicKey",U),"strict"in K)throw new Error("options.strict was renamed to lowS");const{lowS:M,prehash:V}=K;let G,fe;try{if(typeof H=="string"||H instanceof Uint8Array)try{G=w.fromDER(H)}catch(We){if(!(We instanceof Qn.Err))throw We;G=w.fromCompact(H)}else if(typeof H=="object"&&typeof H.r=="bigint"&&typeof H.s=="bigint"){const{r:We,s:Gt}=H;G=new w(We,Gt)}else throw new Error("PARSE");fe=l.fromHex(U)}catch(We){if(We.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(M&&G.hasHighS())return!1;V&&(A=t.hash(A));const{r:ce,s:ne}=G,ge=C(A),me=c(ne),Le=a(ge*me),pe=a(ce*me),_e=(pt=l.BASE.multiplyAndAddUnsafe(fe,Le,pe))==null?void 0:pt.toAffine();return _e?a(_e.x)===ce:!1}return{CURVE:t,getPublicKey:b,getSharedSecret:$,sign:k,verify:E,ProjectivePoint:l,Signature:w,utils:y}}function Mm(e,t){const n=e.ORDER;let r=$t;for(let d=n-je;d%Yt===$t;d/=Yt)r+=je;const s=r,o=(n-je)/Yt**s,i=(o-je)/Yt,a=Yt**s-je,c=Yt**(s-je),l=e.pow(t,o),f=e.pow(t,(o+je)/Yt);let u=(d,h)=>{let g=l,p=e.pow(h,a),m=e.sqr(p);m=e.mul(m,h);let w=e.mul(d,m);w=e.pow(w,i),w=e.mul(w,p),p=e.mul(w,h),m=e.mul(w,d);let y=e.mul(m,p);w=e.pow(y,c);let b=e.eql(w,e.ONE);p=e.mul(m,f),w=e.mul(y,g),m=e.cmov(p,m,b),y=e.cmov(w,y,b);for(let _=s;_>1;_--){let $=Yt**(_-Yt),x=e.pow(y,$);const C=e.eql(x,e.ONE);p=e.mul(m,g),g=e.mul(g,g),x=e.mul(y,g),m=e.cmov(p,m,C),y=e.cmov(x,y,C)}return{isValid:b,value:m}};if(e.ORDER%Fl===Uo){const d=(e.ORDER-Uo)/Fl,h=e.sqrt(e.neg(t));u=(g,p)=>{let m=e.sqr(p);const w=e.mul(g,p);m=e.mul(m,w);let y=e.pow(m,d);y=e.mul(y,w);const b=e.mul(y,h),_=e.mul(e.sqr(y),p),$=e.eql(_,g);let x=e.cmov(b,y,$);return{isValid:$,value:x}}}return u}function Dm(e,t){if(Nf(e),!e.isValid(t.A)||!e.isValid(t.B)||!e.isValid(t.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");const n=Mm(e,t.Z);if(!e.isOdd)throw new Error("Fp.isOdd is not implemented!");return r=>{let s,o,i,a,c,l,f,u;s=e.sqr(r),s=e.mul(s,t.Z),o=e.sqr(s),o=e.add(o,s),i=e.add(o,e.ONE),i=e.mul(i,t.B),a=e.cmov(t.Z,e.neg(o),!e.eql(o,e.ZERO)),a=e.mul(a,t.A),o=e.sqr(i),l=e.sqr(a),c=e.mul(l,t.A),o=e.add(o,c),o=e.mul(o,i),l=e.mul(l,a),c=e.mul(l,t.B),o=e.add(o,c),f=e.mul(s,i);const{isValid:d,value:h}=n(o,l);u=e.mul(s,r),u=e.mul(u,h),f=e.cmov(f,i,d),u=e.cmov(u,h,d);const g=e.isOdd(r)===e.isOdd(u);return u=e.cmov(e.neg(u),u,g),f=e.div(f,a),{x:f,y:u}}}function Zm(e){if(e instanceof Uint8Array)return e;if(typeof e=="string")return mi(e);throw new Error("DST must be Uint8Array or string")}const Vm=In;function _n(e,t){if(e<0||e>=1<<8*t)throw new Error(`bad I2OSP call: value=${e} length=${t}`);const n=Array.from({length:t}).fill(0);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return new Uint8Array(n)}function qm(e,t){const n=new Uint8Array(e.length);for(let r=0;r255&&(t=r(kt(mi("H2C-OVERSIZE-DST-"),t)));const{outputLen:s,blockLen:o}=r,i=Math.ceil(n/s);if(i>255)throw new Error("Invalid xmd length");const a=kt(t,_n(t.length,1)),c=_n(0,o),l=_n(n,2),f=new Array(i),u=r(kt(c,e,l,_n(0,1),a));f[0]=r(kt(u,_n(1,1),a));for(let h=1;h<=i;h++){const g=[qm(u,f[h-1]),_n(h+1,1),a];f[h]=r(kt(...g))}return kt(...f).slice(0,n)}function Fm(e,t,n,r,s){if(_s(e),_s(t),kc(n),t.length>255){const o=Math.ceil(2*r/8);t=s.create({dkLen:o}).update(mi("H2C-OVERSIZE-DST-")).update(t).digest()}if(n>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return s.create({dkLen:n}).update(e).update(_n(n,2)).update(t).update(_n(t.length,1)).digest()}function Wl(e,t,n){cs(n,{DST:"string",p:"bigint",m:"isSafeInteger",k:"isSafeInteger",hash:"hash"});const{p:r,k:s,m:o,hash:i,expand:a,DST:c}=n;_s(e),kc(t);const l=Zm(c),f=r.toString(2).length,u=Math.ceil((f+s)/8),d=t*o*u;let h;if(a==="xmd")h=zm(e,l,d,i);else if(a==="xof")h=Fm(e,l,d,s,i);else if(a===void 0)h=e;else throw new Error('expand must be "xmd", "xof" or undefined');const g=new Array(t);for(let p=0;pArray.from(r).reverse());return(r,s)=>{const[o,i,a,c]=n.map(l=>l.reduce((f,u)=>e.add(e.mul(f,r),u)));return r=e.div(o,i),s=e.mul(s,e.div(a,c)),{x:r,y:s}}}function Gm(e,t,n){if(typeof t!="function")throw new Error("mapToCurve() must be defined");return{hashToCurve(r,s){const o=Wl(r,2,{...n,DST:n.DST,...s}),i=e.fromAffine(t(o[0])),a=e.fromAffine(t(o[1])),c=i.add(a).clearCofactor();return c.assertValidity(),c},encodeToCurve(r,s){const o=Wl(r,1,{...n,DST:n.encodeDST,...s}),i=e.fromAffine(t(o[0])).clearCofactor();return i.assertValidity(),i}}}let Rf=class extends Bf{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Jn.hash(t);const r=mc(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new TypeError("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?t.create().update(r).digest():r);for(let i=0;inew Rf(e,t).update(n).digest();jf.create=(e,t)=>new Rf(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ym(e){return{hash:e,hmac:(t,...n)=>jf(e,t,am(...n)),randomBytes:cm}}function Xm(e,t){const n=r=>Km({...e,...Ym(r)});return Object.freeze({...n(t),create:n})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Kf=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Gl=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Jm=BigInt(1),Ba=BigInt(2),Yl=(e,t)=>(e+t/Ba)/t;function Qm(e){const t=Kf,n=BigInt(3),r=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,f=l*l*e%t,u=gt(f,n,t)*f%t,d=gt(u,n,t)*f%t,h=gt(d,Ba,t)*l%t,g=gt(h,s,t)*h%t,p=gt(g,o,t)*g%t,m=gt(p,a,t)*p%t,w=gt(m,c,t)*m%t,y=gt(w,a,t)*p%t,b=gt(y,n,t)*f%t,_=gt(b,i,t)*g%t,$=gt(_,r,t)*l%t,x=gt($,Ba,t);if(!Pn.eql(Pn.sqr(x),e))throw new Error("Cannot find square root");return x}const Pn=Lf(Kf,void 0,void 0,{sqrt:Qm}),sn=Xm({a:BigInt(0),b:BigInt(7),Fp:Pn,n:Gl,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Gl,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Jm*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=n,i=BigInt("0x100000000000000000000000000000000"),a=Yl(o*e,t),c=Yl(-r*e,t);let l=Qe(e-a*n-c*s,t),f=Qe(-a*r-c*o,t);const u=l>i,d=f>i;if(u&&(l=t-l),d&&(f=t-f),l>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:u,k1:l,k2neg:d,k2:f}}}},If);BigInt(0);sn.ProjectivePoint;sn.utils.randomPrivateKey;const ey=Wm(Pn,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),ty=Dm(Pn,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:Pn.create(BigInt("-11"))});Gm(sn.ProjectivePoint,e=>{const{x:t,y:n}=ty(Pn.create(e[0]));return ey(t,n)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:Pn.ORDER,m:1,k:128,expand:"xmd",hash:If});function Ta(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function ny(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function Mf(e,...t){if(!(e instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new TypeError(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function ry(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ta(e.outputLen),Ta(e.blockLen)}function sy(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function oy(e,t){Mf(e);const n=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),Ut=(e,t)=>e<<32-t|e>>>t,ay=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ay)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function cy(e){if(typeof e!="string")throw new TypeError(`utf8ToBytes expected string, got ${typeof e}`);return new TextEncoder().encode(e)}function Df(e){if(typeof e=="string"&&(e=cy(e)),!(e instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof e})`);return e}let ly=class{clone(){return this._cloneInto()}};function Zf(e){const t=r=>e().update(Df(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function uy(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const s=BigInt(32),o=BigInt(4294967295),i=Number(n>>s&o),a=Number(n&o),c=r?4:0,l=r?0:4;e.setUint32(t+c,i,r),e.setUint32(t+l,a,r)}let fy=class extends ly{constructor(t,n,r,s){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Xi(this.buffer)}update(t){Yi.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=Df(t);const o=t.length;for(let i=0;is-i&&(this.process(r,0),i=0);for(let u=i;uf.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;ue&t^~e&n,hy=(e,t,n)=>e&t^e&n^t&n,py=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),gn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),mn=new Uint32Array(64);let Vf=class extends fy{constructor(){super(64,32,8,!1),this.A=gn[0]|0,this.B=gn[1]|0,this.C=gn[2]|0,this.D=gn[3]|0,this.E=gn[4]|0,this.F=gn[5]|0,this.G=gn[6]|0,this.H=gn[7]|0}get(){const{A:t,B:n,C:r,D:s,E:o,F:i,G:a,H:c}=this;return[t,n,r,s,o,i,a,c]}set(t,n,r,s,o,i,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,n){for(let u=0;u<16;u++,n+=4)mn[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const d=mn[u-15],h=mn[u-2],g=Ut(d,7)^Ut(d,18)^d>>>3,p=Ut(h,17)^Ut(h,19)^h>>>10;mn[u]=p+mn[u-7]+g+mn[u-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){const d=Ut(a,6)^Ut(a,11)^Ut(a,25),h=f+d+dy(a,c,l)+py[u]+mn[u]|0,p=(Ut(r,2)^Ut(r,13)^Ut(r,22))+hy(r,s,o)|0;f=l,l=c,c=a,a=i+h|0,i=o,o=s,s=r,r=h+p|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,f=f+this.H|0,this.set(r,s,o,i,a,c,l,f)}roundClean(){mn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},gy=class extends Vf{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}};const Oa=Zf(()=>new Vf);Zf(()=>new gy);function my(e,t){if(e.length>t)throw new TypeError(`Data is larger than array size: ${e.length} > ${t}`)}function yy(e){if(e.match(/[^a-fA-f0-9]/)!==null)throw new TypeError("Invalid characters in hex string: "+e);if(e.length%2!==0)throw new Error(`Length of hex string is invalid: ${e.length}`)}function wy(e){if(e>Number.MAX_SAFE_INTEGER)throw new TypeError("Number exceeds safe bounds!")}const{getRandomValues:by}=crypto??globalThis.crypto??window.crypto;function xy(e=32){if(typeof by=="function")return crypto.getRandomValues(new Uint8Array(e));throw new Error("Crypto module missing getRandomValues!")}function vy(e,t,n="be"){t===void 0&&(t=e.length),my(e,t);const r=new Uint8Array(t).fill(0),s=n==="be"?0:t-e.length;return r.set(e,s),r}function qf(e){let t,n=0;const r=e.reduce((o,i)=>o+i.length,0),s=new Uint8Array(r);for(t=0;t0||(i.length^a)>0?"":"1";c in o||l>0;)f=o[c],f=f>0?f*256+l:l,l=f/s|0,o[c]=f%s,c++;for(;c-- >0;)i+=r[o[c]];return n&&i.length%4>0?i+"=".repeat(4-i.length%4):i}function Sy(e,t){const n=zf(t),r=n.length,s=[],o=[];e=e.replace("=","");let i,a=0,c,l;for(i=0;i0||(o.length^i)>0||o.push(0);a in s||c>0;)l=s[a],l=l>0?l*r+c:c,c=l>>8,s[a]=l%256,a++}for(;a-- >0;)o.push(s[a]);return new Uint8Array(o)}function Ff(e){return Oa(Oa(e))}function _y(e){const t=Ff(e);return qf([e,t.slice(0,4)])}function Ay(e){const t=e.slice(0,-4),n=e.slice(-4);if(Ff(t).slice(0,4).toString()!==n.toString())throw new Error("Invalid checksum!");return t}const Xl={encode:Ey,decode:Sy},Wf={encode:e=>{const t=_y(e);return Xl.encode(t,"base58")},decode:e=>{const t=Xl.decode(e,"base58");return Ay(t)}},Gf="qpzry9x8gf2tvdw0s3jn54khce6mua7l",By=[996825010,642813549,513874426,1027748829,705979059],No=[{version:0,name:"bech32",const:1},{version:1,name:"bech32m",const:734539939}];function Yf(e){let t=1;for(let n=0;n>25;t=(t&33554431)<<5^e[n];for(let s=0;s<5;++s)(r>>s&1)!==0&&(t^=By[s])}return t}function Xf(e){const t=[];let n;for(n=0;n>5);for(t.push(0),n=0;n>5*(5-i)&31);return o}function Jf(e,t,n,r=!0){const s=[];let o=0,i=0;const a=(1<>t>0)throw new Error("Failed to perform base conversion. Invalid value: "+String(l));for(o=(o<=n;)i-=n,s.push(o>>i&a)}if(r)i>0&&s.push(o<=t||(o<0)throw new Error("Failed to perform base conversion. Invalid Size!");return s}function Iy(e,t,n){const r=t.concat(Oy(e,t,n));let s=e+"1";for(let o=0;oo.version===t[0])??No[0];if(!Ty(r,t,s))throw new Error("Checksum verification failed!");return[r,t.slice(0,t.length-6)]}function Cy(e){let t,n,r=!1,s=!1;for(t=0;t126)return!1;n>=97&&n<=122&&(r=!0),n>=65&&n<=90&&(s=!0)}return!(r&&s)}function Py(e){const t=e.lastIndexOf("1");return!(t<1||t+7>e.length||e.length>90)}function Uy(e,t="bc",n=0){const r=[n,...Jf([...e],8,5)],s=No.find(i=>i.version===n)??No[0],o=Iy(t,r,s);return ed(o),o}function ed(e){e=e.toLowerCase();const t=e.split("1",1)[0],[n,r]=Qf(e),s=Jf(r.slice(1),5,8,!1),o=s.length;switch(!0){case t!==n:throw new Error("Returned hrp string is invalid.");case(s===null||o<2||o>40):throw new Error("Decoded string is invalid or out of spec.");case r[0]>16:throw new Error("Returned version bit is out of range.");default:return Uint8Array.from(s)}}function Ny(e){e=e.toLowerCase();const[t,n]=Qf(e);return n[0]}const td={encode:Uy,decode:ed,version:Ny},nd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",rd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Ly=new TextEncoder;function sd(e,t=!1,n=!0){typeof e=="string"&&(e=Ly.encode(e));const r=t?rd:nd;let s="",o=0,i=0;for(let a=0;a=6;)o-=6,s+=r[i>>o&63];if(o>0)for(i<<=6-o,s+=r[i&63];o<6;)s+=n?"=":"",o+=2;return s}function od(e,t=!1){const n=t||e.includes("-")||e.includes("_")?rd.split(""):nd.split("");e=e.replace(/=+$/,"");const r=e.split("");let s=0,o=0;const i=[];for(let a=0;a=8&&(s-=8,i.push(o>>>s&255))}return new Uint8Array(i)}const id={encode:sd,decode:od},ad={encode:e=>sd(e,!0,!1),decode:e=>od(e,!0)},Hy=BigInt(0),Ry=BigInt(255),cd=BigInt(256);function jy(e){if(e<=0xffn)return 1;if(e<=0xffffn)return 2;if(e<=0xffffffffn)return 4;if(e<=0xffffffffffffffffn)return 8;if(e<=0xffffffffffffffffffffffffffffffffn)return 16;if(e<=0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn)return 32;throw new TypeError("Must specify a fixed buffer size for bigints greater than 32 bytes.")}function Ky(e,t,n="be"){t===void 0&&(t=jy(e));const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(;e>Hy;){const a=e&Ry,c=Number(a);r?o.setUint8(i++,c):o.setUint8(i--,c),e=(e-a)/cd}return new Uint8Array(s)}function My(e){let t=BigInt(0);for(let n=e.length-1;n>=0;n--)t=t*cd+BigInt(e[n]);return BigInt(t)}function Dy(e){const t=e.split("").map(Number);if(t.length%8!==0)throw new Error(`Binary array is invalid length: ${e.length}`);const n=new Uint8Array(t.length/8);for(let r=0,s=0;r255)throw new Error(`Invalid byte value: ${r}. Byte values must be between 0 and 255.`);for(let s=7;s>=0;s--,n++)t[n]=r>>s&1}return t.join("")}function Vy(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=4294967295)return 4;throw new TypeError("Numbers larger than 4 bytes must specify a fixed size!")}function qy(e,t,n="be"){t===void 0&&(t=Vy(e));const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(;e>0;){const a=e&255;r?o.setUint8(i++,e):o.setUint8(i--,e),e=(e-a)/256}return new Uint8Array(s)}function zy(e){let t=0;for(let n=e.length-1;n>=0;n--)t=t*256+e[n],wy(t);return t}const Fy=new TextEncoder,Wy=new TextDecoder;function $c(e){return Fy.encode(e)}function Ji(e){return Wy.decode(e)}function Gy(e,t){yy(e);const n=e.length/2;if(t===void 0&&(t=n),n>t)throw new TypeError(`Hex string is larger than array size: ${n} > ${t}`);return t}function Yy(e,t,n="le"){t=Gy(e,t);const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(let a=0;atypeof r=="bigint"?`${r}n`:r);return $c(t)}function Qy(e,t,n){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Uint8Array)return vy(e,t,n);if(typeof e=="string")return Yy(e,t,n);if(typeof e=="bigint")return Ky(e,t,n);if(typeof e=="number")return qy(e,t,n);if(typeof e=="boolean")return Uint8Array.of(e?1:0);throw TypeError("Unsupported format:"+typeof e)}const ie=class ie extends Uint8Array{static random(t=32){const n=xy(t);return new ie(n,t)}constructor(t,n,r){const s=Qy(t,n,r);super(s)}get arr(){return[...this]}get num(){return this.toNum()}get big(){return this.toBig()}get str(){return this.toStr()}get hex(){return this.toHex()}get raw(){return new Uint8Array(this)}get bin(){return this.toBin()}get b58chk(){return this.tob58chk()}get base64(){return this.toBase64()}get b64url(){return this.toB64url()}get digest(){return this.toHash()}get id(){return this.toHash().hex}get stream(){return new dw(this)}toNum(t="be"){const n=t==="be"?this.reverse():this;return zy(n)}toBin(){return Zy(this)}toBig(t="be"){const n=t==="be"?this.reverse():this;return My(n)}toHash(){const t=Oa(this);return new ie(t)}toJson(){const t=Ji(this);return JSON.parse(t)}toBech32(t,n=0){return td.encode(this,t,n)}toStr(){return Ji(this)}toHex(){return Xy(this)}toBytes(){return new Uint8Array(this)}tob58chk(){return Wf.encode(this)}toBase64(){return id.encode(this)}toB64url(){return ad.encode(this)}prepend(t){return ie.join([ie.bytes(t),this])}append(t){return ie.join([this,ie.bytes(t)])}slice(t,n){const r=new Uint8Array(this).slice(t,n);return new ie(r)}subarray(t,n){const r=new Uint8Array(this).subarray(t,n);return new ie(r)}reverse(){const t=new Uint8Array(this).reverse();return new ie(t)}write(t,n){const r=ie.bytes(t);this.set(r,n)}prefixSize(t){const n=ie.varInt(this.length,t);return ie.join([n,this])}static from(t){return new ie(Uint8Array.from(t))}static of(...t){return new ie(Uint8Array.of(...t))}static join(t){const n=t.map(s=>ie.bytes(s)),r=qf(n);return new ie(r)}static varInt(t,n){if(t<253)return ie.num(t,1);if(t<65536)return ie.of(253,...ie.num(t,2,n));if(t<4294967296)return ie.of(254,...ie.num(t,4,n));if(BigInt(t)<0x10000000000000000n)return ie.of(255,...ie.num(t,8,n));throw new Error(`Value is too large: ${t}`)}};ie.num=ew,ie.big=nw,ie.bin=tw,ie.raw=rw,ie.str=sw,ie.hex=ow,ie.bytes=iw,ie.json=aw,ie.base64=cw,ie.b64url=lw,ie.bech32=uw,ie.b58chk=fw,ie.encode=$c,ie.decode=Ji;let ee=ie;function ew(e,t,n){return new ee(e,t,n)}function tw(e,t,n){return new ee(Dy(e),t,n)}function nw(e,t,n){return new ee(e,t,n)}function rw(e,t,n){return new ee(e,t,n)}function sw(e,t,n){return new ee($c(e),t,n)}function ow(e,t,n){return new ee(e,t,n)}function iw(e,t,n){return new ee(e,t,n)}function aw(e){return new ee(Jy(e))}function cw(e){return new ee(id.decode(e))}function lw(e){return new ee(ad.decode(e))}function uw(e){return new ee(td.decode(e))}function fw(e){return new ee(Wf.decode(e))}class dw{constructor(t){this.data=ee.bytes(t),this.size=this.data.length}peek(t){if(t>this.size)throw new Error(`Size greater than stream: ${t} > ${this.size}`);return new ee(this.data.slice(0,t))}read(t){t=t??this.readSize();const n=this.peek(t);return this.data=this.data.slice(t),this.size=this.data.length,n}readSize(t){const n=this.read(1).num;switch(!0){case(n>=0&&n<253):return n;case n===253:return this.read(2).toNum(t);case n===254:return this.read(4).toNum(t);case n===255:return this.read(8).toNum(t);default:throw new Error(`Varint is out of range: ${n}`)}}}const Lo=sn.CURVE,Ec=Lo.n,hw=Lo.p,pw={x:Lo.Gx,y:Lo.Gy},gw=BigInt(0);BigInt(1);BigInt(2);BigInt(3);BigInt(4);const Ia={N:Ec,P:hw,G:pw,_0n:gw},ps=Lf(Ec,32,!0),ld=e=>Qe(e,Ec);function Sc(e,t=!1){if(t)throw new Error(e);return!1}function ud(e){return ee.random(e)}function mw(e){const t=ee.bytes(e).big;return ee.big(ld(t),32)}var yw=Object.freeze({__proto__:null,fail:Sc,mod_bytes:mw,random:ud});const{N:ww,_0n:bw}=Ia;function xw(e,t,n){const r=ee.bytes(e);return r.length!==t?Sc(`Invalid byte size: ${r.hex} !== ${t}`,n):!0}function vw(e,t){return typeof e=="bigint"&&bwthis.big}lt(t){return new Be(t).big0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function Sw(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ca(e.outputLen),Ca(e.blockLen)}function _w(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Aw(e,t){fd(e);const n=t.outputLen;if(e.lengthe instanceof Uint8Array,Qi=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),Nt=(e,t)=>e<<32-t|e>>>t,Ow=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Ow)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Iw(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function _c(e){if(typeof e=="string"&&(e=Iw(e)),!Tw(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}let dd=class{clone(){return this._cloneInto()}};function vr(e){const t=r=>e().update(_c(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Cw(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const s=BigInt(32),o=BigInt(4294967295),i=Number(n>>s&o),a=Number(n&o),c=r?4:0,l=r?0:4;e.setUint32(t+c,i,r),e.setUint32(t+l,a,r)}class Ac extends dd{constructor(t,n,r,s){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Qi(this.buffer)}update(t){er.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=_c(t);const o=t.length;for(let i=0;is-i&&(this.process(r,0),i=0);for(let u=i;uf.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;ue&t^~e&n,Uw=(e,t,n)=>e&t^e&n^t&n,Nw=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),yn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),wn=new Uint32Array(64);let hd=class extends Ac{constructor(){super(64,32,8,!1),this.A=yn[0]|0,this.B=yn[1]|0,this.C=yn[2]|0,this.D=yn[3]|0,this.E=yn[4]|0,this.F=yn[5]|0,this.G=yn[6]|0,this.H=yn[7]|0}get(){const{A:t,B:n,C:r,D:s,E:o,F:i,G:a,H:c}=this;return[t,n,r,s,o,i,a,c]}set(t,n,r,s,o,i,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,n){for(let u=0;u<16;u++,n+=4)wn[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const d=wn[u-15],h=wn[u-2],g=Nt(d,7)^Nt(d,18)^d>>>3,p=Nt(h,17)^Nt(h,19)^h>>>10;wn[u]=p+wn[u-7]+g+wn[u-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){const d=Nt(a,6)^Nt(a,11)^Nt(a,25),h=f+d+Pw(a,c,l)+Nw[u]+wn[u]|0,p=(Nt(r,2)^Nt(r,13)^Nt(r,22))+Uw(r,s,o)|0;f=l,l=c,c=a,a=i+h|0,i=o,o=s,s=r,r=h+p|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,f=f+this.H|0,this.set(r,s,o,i,a,c,l,f)}roundClean(){wn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};class Lw extends hd{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const Ho=vr(()=>new hd);vr(()=>new Lw);const oo=BigInt(2**32-1),Pa=BigInt(32);function pd(e,t=!1){return t?{h:Number(e&oo),l:Number(e>>Pa&oo)}:{h:Number(e>>Pa&oo)|0,l:Number(e&oo)|0}}function Hw(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let s=0;sBigInt(e>>>0)<>>0),jw=(e,t,n)=>e>>>n,Kw=(e,t,n)=>e<<32-n|t>>>n,Mw=(e,t,n)=>e>>>n|t<<32-n,Dw=(e,t,n)=>e<<32-n|t>>>n,Zw=(e,t,n)=>e<<64-n|t>>>n-32,Vw=(e,t,n)=>e>>>n-32|t<<64-n,qw=(e,t)=>t,zw=(e,t)=>e,Fw=(e,t,n)=>e<>>32-n,Ww=(e,t,n)=>t<>>32-n,Gw=(e,t,n)=>t<>>64-n,Yw=(e,t,n)=>e<>>64-n;function Xw(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}const Jw=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Qw=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,eb=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),tb=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,nb=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),rb=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,sb={fromBig:pd,split:Hw,toBig:Rw,shrSH:jw,shrSL:Kw,rotrSH:Mw,rotrSL:Dw,rotrBH:Zw,rotrBL:Vw,rotr32H:qw,rotr32L:zw,rotlSH:Fw,rotlSL:Ww,rotlBH:Gw,rotlBL:Yw,add:Xw,add3L:Jw,add3H:Qw,add4L:eb,add4H:tb,add5H:rb,add5L:nb};var oe=sb;const[ob,ib]=oe.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),bn=new Uint32Array(80),xn=new Uint32Array(80);let yi=class extends Ac{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:t,Al:n,Bh:r,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:f,Fh:u,Fl:d,Gh:h,Gl:g,Hh:p,Hl:m}=this;return[t,n,r,s,o,i,a,c,l,f,u,d,h,g,p,m]}set(t,n,r,s,o,i,a,c,l,f,u,d,h,g,p,m){this.Ah=t|0,this.Al=n|0,this.Bh=r|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=f|0,this.Fh=u|0,this.Fl=d|0,this.Gh=h|0,this.Gl=g|0,this.Hh=p|0,this.Hl=m|0}process(t,n){for(let b=0;b<16;b++,n+=4)bn[b]=t.getUint32(n),xn[b]=t.getUint32(n+=4);for(let b=16;b<80;b++){const _=bn[b-15]|0,$=xn[b-15]|0,x=oe.rotrSH(_,$,1)^oe.rotrSH(_,$,8)^oe.shrSH(_,$,7),C=oe.rotrSL(_,$,1)^oe.rotrSL(_,$,8)^oe.shrSL(_,$,7),P=bn[b-2]|0,O=xn[b-2]|0,N=oe.rotrSH(P,O,19)^oe.rotrBH(P,O,61)^oe.shrSH(P,O,6),R=oe.rotrSL(P,O,19)^oe.rotrBL(P,O,61)^oe.shrSL(P,O,6),B=oe.add4L(C,R,xn[b-7],xn[b-16]),k=oe.add4H(B,x,N,bn[b-7],bn[b-16]);bn[b]=k|0,xn[b]=B|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:f,Eh:u,El:d,Fh:h,Fl:g,Gh:p,Gl:m,Hh:w,Hl:y}=this;for(let b=0;b<80;b++){const _=oe.rotrSH(u,d,14)^oe.rotrSH(u,d,18)^oe.rotrBH(u,d,41),$=oe.rotrSL(u,d,14)^oe.rotrSL(u,d,18)^oe.rotrBL(u,d,41),x=u&h^~u&p,C=d&g^~d&m,P=oe.add5L(y,$,C,ib[b],xn[b]),O=oe.add5H(P,w,_,x,ob[b],bn[b]),N=P|0,R=oe.rotrSH(r,s,28)^oe.rotrBH(r,s,34)^oe.rotrBH(r,s,39),B=oe.rotrSL(r,s,28)^oe.rotrBL(r,s,34)^oe.rotrBL(r,s,39),k=r&o^r&a^o&a,E=s&i^s&c^i&c;w=p|0,y=m|0,p=h|0,m=g|0,h=u|0,g=d|0,{h:u,l:d}=oe.add(l|0,f|0,O|0,N|0),l=a|0,f=c|0,a=o|0,c=i|0,o=r|0,i=s|0;const v=oe.add3L(N,B,E);r=oe.add3H(v,O,R,k),s=v|0}({h:r,l:s}=oe.add(this.Ah|0,this.Al|0,r|0,s|0)),{h:o,l:i}=oe.add(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=oe.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:f}=oe.add(this.Dh|0,this.Dl|0,l|0,f|0),{h:u,l:d}=oe.add(this.Eh|0,this.El|0,u|0,d|0),{h,l:g}=oe.add(this.Fh|0,this.Fl|0,h|0,g|0),{h:p,l:m}=oe.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:w,l:y}=oe.add(this.Hh|0,this.Hl|0,w|0,y|0),this.set(r,s,o,i,a,c,l,f,u,d,h,g,p,m,w,y)}roundClean(){bn.fill(0),xn.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class ab extends yi{constructor(){super(),this.Ah=-1942145080,this.Al=424955298,this.Bh=1944164710,this.Bl=-1982016298,this.Ch=502970286,this.Cl=855612546,this.Dh=1738396948,this.Dl=1479516111,this.Eh=258812777,this.El=2077511080,this.Fh=2011393907,this.Fl=79989058,this.Gh=1067287976,this.Gl=1780299464,this.Hh=286451373,this.Hl=-1848208735,this.outputLen=28}}class cb extends yi{constructor(){super(),this.Ah=573645204,this.Al=-64227540,this.Bh=-1621794909,this.Bl=-934517566,this.Ch=596883563,this.Cl=1867755857,this.Dh=-1774684391,this.Dl=1497426621,this.Eh=-1775747358,this.El=-1467023389,this.Fh=-1101128155,this.Fl=1401305490,this.Gh=721525244,this.Gl=746961066,this.Hh=246885852,this.Hl=-2117784414,this.outputLen=32}}class lb extends yi{constructor(){super(),this.Ah=-876896931,this.Al=-1056596264,this.Bh=1654270250,this.Bl=914150663,this.Ch=-1856437926,this.Cl=812702999,this.Dh=355462360,this.Dl=-150054599,this.Eh=1731405415,this.El=-4191439,this.Fh=-1900787065,this.Fl=1750603025,this.Gh=-619958771,this.Gl=1694076839,this.Hh=1203062813,this.Hl=-1090891868,this.outputLen=48}}const ub=vr(()=>new yi);vr(()=>new ab);vr(()=>new cb);vr(()=>new lb);const fb=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),gd=Uint8Array.from({length:16},(e,t)=>t),db=gd.map(e=>(9*e+5)%16);let Bc=[gd],Tc=[db];for(let e=0;e<4;e++)for(let t of[Bc,Tc])t.push(t[e].map(n=>fb[n]));const md=[[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=>new Uint8Array(e)),hb=Bc.map((e,t)=>e.map(n=>md[t][n])),pb=Tc.map((e,t)=>e.map(n=>md[t][n])),gb=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),mb=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),io=(e,t)=>e<>>32-t;function Ql(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)}const ao=new Uint32Array(16);let yb=class extends Ac{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:n,h2:r,h3:s,h4:o}=this;return[t,n,r,s,o]}set(t,n,r,s,o){this.h0=t|0,this.h1=n|0,this.h2=r|0,this.h3=s|0,this.h4=o|0}process(t,n){for(let h=0;h<16;h++,n+=4)ao[h]=t.getUint32(n,!0);let r=this.h0|0,s=r,o=this.h1|0,i=o,a=this.h2|0,c=a,l=this.h3|0,f=l,u=this.h4|0,d=u;for(let h=0;h<5;h++){const g=4-h,p=gb[h],m=mb[h],w=Bc[h],y=Tc[h],b=hb[h],_=pb[h];for(let $=0;$<16;$++){const x=io(r+Ql(h,o,a,l)+ao[w[$]]+p,b[$])+u|0;r=u,u=l,l=io(a,10)|0,a=o,o=x}for(let $=0;$<16;$++){const x=io(s+Ql(g,i,c,f)+ao[y[$]]+m,_[$])+d|0;s=d,d=f,f=io(c,10)|0,c=i,i=x}}this.set(this.h1+a+f|0,this.h2+l+d|0,this.h3+u+s|0,this.h4+r+i|0,this.h0+o+c|0)}roundClean(){ao.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}};const wb=vr(()=>new yb);let yd=class extends dd{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,er.hash(t);const r=_c(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?t.create().update(r).digest():r);for(let i=0;inew yd(e,t).update(n).digest();wd.create=(e,t)=>new yd(e,t);function bb(e){const t=ee.bytes(e);return ee.raw(Ho(t))}function qr(e){const t=ee.bytes(e);return ee.raw(Ho(Ho(t)))}function Oc(e){const t=ee.bytes(e);return ee.raw(wb(Ho(t)))}function xb(e,t){const n=ee.bytes(e),r=ee.bytes(t);return ee.raw(wd(ub,n,r))}function vb(e){const t=ee.str(e).digest;return ee.join([t,t])}function kb(e=32){return Ic(ud(e))}function Ic(e){return nt.mod(e).buff}function bd(e,t=!1){const n=nt.mod(e).point;return t?n.x:n.buff}function xd(e,t){const n=xr.from_x(t),r=nt.mod(e);return n.mul(r).buff}function $b(e,t,n="ecdh/code"){const r=vb(n),s=Ic(e),o=bd(s),i=ee.bytes(t),a=xd(s,i),c=[o.hex,i.hex];return c.sort(),xb(a,ee.join([r,...c]))}function Eb(e){const t=ee.bytes(e);switch(!0){case t.length===32:return!0;case(t.length===33&&t[0]===2):return!0;case(t.length===33&&t[0]===3):return!1;default:throw new TypeError(`Invalid public key: ${t.hex}`)}}function Sb(e){const t=ee.bytes(e);switch(t.length){case 32:return t;case 33:return t.slice(1,33);default:throw new Error(`Invalid key length: ${t.length}`)}}var _b=Object.freeze({__proto__:null,genSecretKey:kb,getPublicKey:bd,getSecretKey:Ic,getSharedCode:$b,getSharedKey:xd,is_even_pub:Eb,xonly_pub:Sb});ee.random(32);const vd={secp:sn},Ua={..._b,...yw};function wi(e){const t=T.bytes(e);return zt(t,33),Oc(t)}function kd(e){const t=Ce.fmt.toBytes(e,!1);return Oc(t)}function $d(e){const t=Ce.fmt.toBytes(e,!1);return bb(t)}function Ed(e,t="main"){const n=t==="main"?["1"]:["m","n"];for(const r of n)if(e.startsWith(r))return!0;return!1}function Sd(e,t="main"){const n=T.bytes(e),r=t==="main"?T.num(0):T.num(111);return zt(e,20),n.prepend(r).tob58chk()}function Ab(e,t="main"){if(!Ed(e,t))throw new TypeError("Invalid p2pkh address!");return T.b58chk(e).slice(1)}function Bb(e){const t=T.bytes(e);return zt(t,20),["OP_DUP","OP_HASH160",t.hex,"OP_EQUALVERIFY","OP_CHECKSIG"]}function Tb(e,t){const n=wi(e);return Sd(n,t)}const _d={check:Ed,encode:Sd,decode:Ab,hash:wi,scriptPubKey:Bb,fromPubKey:Tb};function Ad(e,t="main"){const n=t==="main"?["3"]:["2"];for(const r of n)if(e.startsWith(r))return!0;return!1}function Bd(e,t="main"){const n=t==="main"?T.num(5):T.num(196),r=T.bytes(e);return zt(r,20),r.prepend(n).tob58chk()}function Ob(e,t="main"){if(!Ad(e,t))throw new TypeError(`Invalid p2sh address for network ${t}:`+e);return T.b58chk(e).slice(1)}function Ib(e){return["OP_HASH160",T.bytes(e).hex,"OP_EQUAL"]}function Cb(e,t){const n=kd(e);return Bd(n,t)}const Td={check:Ad,encode:Bd,decode:Ob,hash:kd,scriptPubKey:Ib,fromScript:Cb},Cc={main:"bc",testnet:"tb",signet:"tb",regtest:"bcrt"},Pb=["bc1q","tb1q","bcrt1q"];function Od(e){for(const t of Pb)if(e.startsWith(t))return!0;return!1}function Id(e,t="main"){const n=Cc[t],r=T.bytes(e);return zt(r,20),r.toBech32(n,0)}function Ub(e){if(!Od(e))throw new TypeError("Invalid segwit address!");return T.bech32(e)}function Nb(e){const t=T.bytes(e);return zt(t,20),["OP_0",t.hex]}function Lb(e,t){const n=wi(e);return Id(n,t)}const Cd={check:Od,encode:Id,decode:Ub,hash:wi,scriptPubKey:Nb,fromPubKey:Lb},Hb=["bc1q","tb1q","bcrt1q"];function Pd(e){for(const t of Hb)if(e.startsWith(t))return!0;return!1}function Ud(e,t="main"){const n=Cc[t],r=T.bytes(e);return zt(r,32),r.toBech32(n,0)}function Rb(e){if(!Pd(e))throw new TypeError("Invalid segwit address!");return T.bech32(e)}function jb(e){const t=T.bytes(e);return zt(t,32),["OP_0",t.hex]}function Kb(e,t){const n=$d(e);return Ud(n,t)}const Nd={check:Pd,encode:Ud,decode:Rb,hash:$d,scriptPubKey:jb,fromScript:Kb};function cr(e){const t=T.bytes(e);return t.length>32?t.slice(1,33):t}const Mb=["bc1p","tb1p","bcrt1p"];function Ld(e){for(const t of Mb)if(e.startsWith(t))return!0;return!1}function Hd(e,t="main"){const n=Cc[t],r=T.bytes(e);return zt(r,32),r.toBech32(n,1)}function Db(e){if(!Ld(e))throw new TypeError("Invalid taproot address!");return T.bech32(e)}function Zb(e){const t=T.bytes(e);return zt(t,32),["OP_1",t.hex]}function Vb(e,t){const n=cr(e);return Hd(n,t)}const Rd={check:Ld,encode:Hd,decode:Db,scriptPubKey:Zb,fromPubKey:Vb},qb={version:2,vin:[],vout:[],locktime:0},zb={scriptSig:[],sequence:4294967293,witness:[]},Fb={value:0n,scriptPubKey:[]};function Pc(e){const t={...qb,...e};return t.vin=t.vin.map(n=>({...zb,...n})),t.vout=t.vout.map(n=>({...Fb,...n})),t}function zr(e,t){const{version:n,vin:r,vout:s,locktime:o}=Pc(e),i=t!==!0&&Wb(r),a=[Uc(n)];i&&a.push(T.hex("0001")),a.push(Gb(r)),a.push(Yb(s));for(const c of r)i&&a.push(Jb(c.witness));return a.push(Nc(o)),T.join(a)}function Wb(e){for(const t of e){const{witness:n}=t;if(typeof n=="string"||n instanceof Uint8Array||Array.isArray(n)&&n.length>0)return!0}return!1}function Uc(e){return T.num(e,4).reverse()}function Vs(e){return T.hex(e,32).reverse()}function qs(e){return T.num(e,4).reverse()}function zs(e){if(typeof e=="string")return T.hex(e,4).reverse();if(typeof e=="number")return T.num(e,4).reverse();throw new Error("Unrecognized format: "+String(e))}function Gb(e){const t=[T.varInt(e.length,"le")];for(const n of e){const{txid:r,vout:s,scriptSig:o,sequence:i}=n;t.push(Vs(r)),t.push(qs(s)),t.push(br(o,!0)),t.push(zs(i))}return T.join(t)}function Un(e){if(typeof e=="number"){if(e%1!==0)throw new Error("Value must be an integer:"+String(e));return T.num(e,8).reverse()}return T.big(e,8).reverse()}function Yb(e){const t=[T.varInt(e.length,"le")];for(const n of e)t.push(Xb(n));return T.join(t)}function Xb(e){const{value:t,scriptPubKey:n}=e,r=[];return r.push(Un(t)),r.push(br(n,!0)),T.join(r)}function Jb(e=[]){const t=[];if(Array.isArray(e)){const n=T.varInt(e.length);t.push(n);for(const r of e)t.push(Qb(r));return T.join(t)}else return T.bytes(e)}function Qb(e){return e1(e)?new T(0):br(e,!0)}function e1(e){if(Array.isArray(e))return e.length===0;if(typeof e=="string"&&e==="")return!0;const t=T.bytes(e);return t.length===1&&t[0]===0}function Nc(e){if(typeof e=="string")return T.hex(e,4);if(typeof e=="number")return T.num(e,4).reverse();throw new Error("Unrecognized format: "+String(e))}function Lc(e){typeof e=="string"&&(e=T.hex(e).raw);const t=new as(e),n=t1(t),r=n1(t),s=r1(t),o=o1(t);if(r)for(const a of s)a.witness=a1(t);const i=c1(t);return{version:n,vin:s,vout:o,locktime:i}}function t1(e){return e.read(4).reverse().toNum()}function n1(e){const[t,n]=[...e.peek(2)];if(t===0){if(e.read(2),n===1)return!0;throw new Error(`Invalid witness flag: ${n}`)}return!1}function r1(e){const t=[],n=e.readSize("le");for(let r=0;r0?e.read(n).hex:null}function Kd(e,t){const n=jd(e);return n!==null?n:[]}function c1(e){return e.read(4).reverse().toNum()}function l1(e){if(Sf(e))return Lc(e);if(typeof e=="object"&&!(e instanceof Uint8Array))return zr(e),Pc(e);throw new Error("Invalid format: "+typeof e)}function u1(e){if(Sf(e))return Lc(e),T.bytes(e);if(typeof e=="object")return zr(e);throw new Error("Invalid format: "+typeof e)}const Hc={toBytes:u1,toJson:l1},f1=[["p2pkh",/^76a914(?\w{40})88ac$/],["p2sh",/^a914(?\w{40})87$/],["p2w-pkh",/^0014(?\w{40})$/],["p2w-sh",/^0020(?\w{64})$/],["p2tr",/^5120(?\w{64})$/]],d1=[192,194,196,198,200,202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,238,240,242,244,246,248,250,252,254,102,126,128,132,150,152,186,188,190];function h1(e){let t=e.at(-1);return un(t)&&(t=T.hex(t)),e.length>1&&t instanceof Uint8Array&&t[0]===80?(e.pop(),T.raw(t)):null}function p1(e){let t=e.at(-1);return un(t)&&(t=T.hex(t)),e.length>1&&t instanceof Uint8Array&&t.length>32&&d1.includes(t[0]&254)?(e.pop(),T.raw(t)):null}function g1(e){if(e.length>1){const t=e.at(-1);try{const n=Ce.fmt.toBytes(t);return e.pop(),n}catch{return null}}return null}function m1(e){const t=[];for(const n of e)if(un(n)||n instanceof Uint8Array||typeof n=="number")t.push(T.bytes(n));else throw new Error("unrecognized value: "+String(n));return t}function y1(e=[]){const t=[...e],n=h1(t),r=p1(t),s=g1(t),o=m1(t);return{annex:n,cblock:r,script:s,params:o}}function w1(e){const t=Ce.fmt.toBytes(e,!1).hex;for(const[n,r]of f1){const s=n,{groups:o}=r.exec(t)??{},{hash:i}=o??{};if(un(i))return{type:s,data:T.hex(i)}}return{type:"raw",data:T.hex(t)}}function b1(e){const t=Hc.toJson(e),n=zr(t,!0);return qr(n).reverse().hex}function x1(e){const t=Hc.toJson(e),n=zr(t,!0).length,r=zr(t,!1).length,s=n*3+r,o=s%4>0?1:0,i=Math.floor(s/4)+o;return{size:r,bsize:n,vsize:i,weight:s}}const X={create:Pc,encode:zr,decode:Lc,fmt:Hc,util:{getTxSize:x1,getTxid:b1,readScriptPubKey:w1,readWitness:y1}},v1=[["1","p2pkh","main",20,"base58"],["3","p2sh","main",20,"base58"],["m","p2pkh","testnet",20,"base58"],["n","p2pkh","testnet",20,"base58"],["2","p2sh","testnet",20,"base58"],["bc1q","p2w-pkh","main",20,"bech32"],["tb1q","p2w-pkh","testnet",20,"bech32"],["bcrt1q","p2w-pkh","regtest",20,"bech32"],["bc1q","p2w-sh","main",32,"bech32"],["tb1q","p2w-sh","testnet",32,"bech32"],["bcrt1q","p2w-sh","regtest",32,"bech32"],["bc1p","p2tr","main",32,"bech32m"],["tb1p","p2tr","testnet",32,"bech32m"],["bcrt1p","p2tr","regtest",32,"bech32m"]];function k1(e,t){switch(t){case"base58":return T.b58chk(e).slice(1);case"bech32":return T.bech32(e);case"bech32m":return T.bech32(e);default:throw new Error("Invalid address format: "+t)}}function $1(e){for(const t of v1){const[n,r,s,o,i]=t;if(e.startsWith(n)&&k1(e,i).length===o)return t}throw new Error("Invalid address: "+e)}function Md(e){switch(e){case"p2pkh":return _d;case"p2sh":return Td;case"p2w-pkh":return Cd;case"p2w-sh":return Nd;case"p2tr":return Rd;default:throw new Error("Invalid address type: "+e)}}function Dd(e){const[t,n,r]=$1(e),s=Md(n),o=s.decode(e,r),i=s.scriptPubKey(o);return{prefix:t,type:n,network:r,data:o,script:i}}function E1(e,t){const{type:n,data:r}=X.util.readScriptPubKey(e);return Md(n).encode(r,t)}function S1(e){const{script:t}=Dd(e);return Ce.fmt.toAsm(t,!1)}const As={p2pkh:_d,p2sh:Td,p2wpkh:Cd,p2wsh:Nd,p2tr:Rd,decode:Dd,fromScriptPubKey:E1,toScriptPubKey:S1},_1=[1,2,3];function Rc(e,t,n={}){const{sigflag:r=1}=n,s=(r&128)===128,o=r%128;if(!_1.includes(o))throw new Error("Invalid hash type: "+String(r));const i=X.fmt.toJson(e),{version:a,vin:c,vout:l,locktime:f}=i,{txid:u,vout:d,prevout:h,sequence:g}=c[t],{value:p}=h??{};if(p===void 0)throw new Error("Prevout value is empty!");let m=n.script;if(m===void 0&&n.pubkey!==void 0&&(m=`76a914${Oc(n.pubkey).hex}88ac`),m===void 0)throw new Error("No pubkey / script has been set!");if(Ce.fmt.toAsm(m).includes("OP_CODESEPARATOR"))throw new Error("This library does not currently support the use of OP_CODESEPARATOR in segwit scripts.");const w=[Uc(a),A1(c,s),B1(c,o,s),Vs(u),qs(d),Ce.encode(m,!0),Un(p),zs(g),T1(l,t,o),Nc(f),T.num(r,4).reverse()];return qr(T.join(w))}function A1(e,t){if(t===!0)return T.num(0,32);const n=[];for(const{txid:r,vout:s}of e)n.push(Vs(r)),n.push(qs(s));return qr(T.join(n))}function B1(e,t,n){if(n||t!==1)return T.num(0,32);const r=[];for(const{sequence:s}of e)r.push(zs(s));return qr(T.join(r))}function T1(e,t,n){const r=[];if(n===1){for(const{value:s,scriptPubKey:o}of e)r.push(Un(s)),r.push(Ce.encode(o,!0));return qr(T.join(r))}if(n===3&&t1&&c[1].length===33)l=T.bytes(c[1]);else return Je("No pubkey provided!",s);const f=Ce.fmt.toParam(c[0]),u=f.slice(0,-1),d=f.slice(-1)[0],h=Rc(r,t,{...n,sigflag:d});return vd.secp.verify(u,h,l)?!0:Je("Invalid signature!",s)}const C1={hash:Rc,sign:O1,verify:I1},P1=[0,1,2,3,129,130,131];function jc(e,t,n={}){const{extension:r,sigflag:s=0,extflag:o=0,key_version:i=0,separator_pos:a=4294967295}=n,c=X.fmt.toJson(e),{version:l,vin:f,vout:u,locktime:d}=c;if(t>=f.length)throw new Error("Index out of bounds: "+String(t));if(!P1.includes(s))throw new Error("Invalid hash type: "+String(s));if(o<0||o>127)throw new Error("Extention flag out of range: "+String(o));const{txid:h,vout:g,sequence:p,witness:m=[]}=f[t],w=(s&128)===128,y=K1(m),b=y!==void 0?1:0,$=(o+(r!==void 0?1:0))*2+b,x=T.str("TapSighash").digest,C=[x,x,T.num(0,1),T.num(s,1),Uc(l),Nc(d)];if(!w){const P=f.map(O=>eu(O));C.push(U1(f),L1(P),H1(P),N1(f))}if(((s&3)<2||(s&3)>3)&&C.push(R1(u)),C.push(T.num($,1)),w){const{value:P,scriptPubKey:O}=eu(f[t]);C.push(Vs(h),qs(g),Un(P),Ce.encode(O,!0),zs(p))}else C.push(T.num(t,4).reverse());return y!==void 0&&C.push(y),(s&3)===3&&C.push(j1(u[t])),r!==void 0&&C.push(T.bytes(r),T.num(i),T.num(a,4,"le")),T.join(C).digest}function U1(e){const t=[];for(const{txid:n,vout:r}of e)t.push(Vs(n)),t.push(qs(r));return T.join(t).digest}function N1(e){const t=[];for(const{sequence:n}of e)t.push(zs(n));return T.join(t).digest}function L1(e){const t=[];for(const{value:n}of e)t.push(Un(n));return T.join(t).digest}function H1(e){const t=[];for(const{scriptPubKey:n}of e)t.push(br(n,!0));return T.join(t).digest}function R1(e){const t=[];for(const{value:n,scriptPubKey:r}of e)t.push(Un(n)),t.push(Ce.encode(r,!0));return T.join(t).digest}function j1(e){return T.join([Un(e.value),Ce.encode(e.scriptPubKey,!0)]).digest}function K1(e){if(e===void 0||e.length<2)return;let t=e.at(-1);if(typeof t=="string"&&(t=T.hex(t)),t instanceof Uint8Array&&t[0]===80)return T.raw(t).prefixSize("be").digest}function eu(e){if(e.prevout===void 0)throw new Error("Prevout data missing for input: "+String(e.txid));return e.prevout}const M1=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,D1=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;function Z1(e,t,n,r={}){const{sigflag:s=0}=r,o=jc(t,n,r),i=V1(e,o);return s===0?T.raw(i):T.join([i,s])}function V1(e,t,n=T.random(32)){const r=T.bytes(t),s=new nt(e),o=s.point,i=o.hasEvenY?s.big:s.negated.big,a=Eo("BIP0340/aux",T.bytes(n)),c=i^a.big,l=Eo("BIP0340/nonce",c,o.x.raw,r),f=new nt(l),u=f.point,d=u.hasEvenY?f.big:f.negated.big,h=new nt(Eo("BIP0340/challenge",u.x.raw,o.x.raw,r)),g=new nt(d+h.big*i);return T.join([u.x.raw,g.raw])}function q1(e,t,n,r=!1){const s=xr.from_x(cr(n)),o=T.bytes(t),i=T.bytes(e).stream;i.size<64&&Je("Signature length is too small: "+String(i.size),r);const a=i.read(32);a.big>M1&&Je("Signature r value greater than field size!",r);const c=i.read(32);c.big>D1&&Je("Signature s value greater than curve order!",r);const l=new nt(Eo("BIP0340/challenge",a.raw,s.x.raw,o)),f=new nt(c).point,u=s.mul(l.big),d=f.sub(u);return d.hasOddY&&Je("Signature R value has odd Y coordinate!",r),d.x.big===0n&&Je("Signature R value is infinite!",r),d.x.big===a.big}const z1=192;function bi(e){const t=T.str(e).digest;return T.join([t,t])}function Kc(e,t=z1){return T.join([bi("TapLeaf"),G1(t),T.bytes(e)]).digest.hex}function F1(e,t){return Kc(Ce.fmt.toBytes(e),t)}function Mc(e,t){return t0){const[h,g,p]=Ro(r,i);c=p,a=Hr(e,h,n)}else i!==void 0?a=Hr(e,i,n):a=Hr(e,void 0,n);const l=n?Ua.getPublicKey(a)[0]:a[0],u=[T.num(s+Wd(l)),o];c.length>0&&c.forEach(h=>u.push(T.hex(h)));const d=T.join(u);if(i!==void 0&&!Dc(a,i,d,t))throw new Error("Path checking failed! Unable to generate path.");return[cr(a).hex,d.hex]}function Dc(e,t,n,r={}){const{isPrivate:s=!1,throws:o=!1}=r,{parity:i,paths:a,intkey:c}=Fd(n),l=s?Ua.getPublicKey(e,!0):cr(e),f=T.join([i,l]);if(f.length!==33)return Je("Invalid tapkey: "+f.hex,o);let u=T.bytes(t).hex;for(const h of a)u=Mc(u,h);const d=Hr(c,u);return T.raw(d).hex===T.raw(f).hex}function Fd(e){const t=new as(T.bytes(e)),n=t.read(1).num,r=t.read(32),[s,o]=n%2===0?[n,2]:[n-1,3],i=[];for(;t.size>=32;)i.push(t.read(32).hex);if(t.size!==0)throw new Error("Non-empty buffer on control block: "+String(t));return{intkey:r,paths:i,parity:o,version:s}}function Wd(e=2){if(e===0||e===1)return e;if(e===2||e==="02")return 0;if(e===3||e==="03")return 1;throw new Error("Invalid parity bit: "+String(e))}function rx(e,t,n={}){const r=X.fmt.toJson(e),{throws:s=!1}=n,{prevout:o,witness:i=[]}=r.vin[t],a=X.util.readWitness(i),{cblock:c,script:l,params:f}=a;let u;if(f.length<1)return Je("Invalid witness data: "+String(i),s);const{scriptPubKey:d}=o??{};if(d===void 0)return Je("Prevout scriptPubKey is empty!",s);const{type:h,data:g}=X.util.readScriptPubKey(d);if(h!=="p2tr")return Je("Prevout script is not a valid taproot output:"+g.hex,s);if(g.length!==32)return Je("Invalid tapkey length: "+String(g.length),s);if(c!==null&&l!==null){const b=c[0]&254,_=Kc(l,b);if(n.extension=_,!Dc(g,_,c,{throws:s}))return Je("cblock verification failed!",s)}n.pubkey!==void 0?u=T.bytes(n.pubkey):f.length>1&&f[1].length===32?u=T.bytes(f[1]):u=T.bytes(g);const p=Ce.fmt.toParam(f[0]),m=new as(p),w=m.read(64).raw;if(m.size===1&&(n.sigflag=m.read(1).num,n.sigflag===0))return Je("0x00 is not a valid appended sigflag!",s);const y=jc(r,t,n);return q1(w,y,u,s)?!0:Je("Invalid signature!",s)}const sx={hash:jc,sign:Z1,verify:rx},lr={segwit:C1,taproot:sx},ox={getTag:bi,getLeaf:Kc,getBranch:Mc,getRoot:W1},ix={readCtrlBlock:Fd,readParityBit:Wd},ax={getPubKey:Y1,getSecKey:X1,getTweak:Zd,tweakSecKey:Vd,tweakPubKey:qd},Fs={getPubKey:nx,getSecKey:tx,encodeScript:F1,checkPath:Dc,tree:ox,tweak:ax,util:ix,SCRIPT_PUBKEY:Q1};var ye;(function(e){e.assertEqual=s=>s;function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{const o={};for(const i of s)o[i]=i;return o},e.getValidEnumValues=s=>{const o=e.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(const a of o)i[a]=s[a];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},e.find=(s,o)=>{for(const i of s)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(ye||(ye={}));var Na;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Na||(Na={}));const z=ye.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),An=e=>{switch(typeof e){case"undefined":return z.undefined;case"string":return z.string;case"number":return isNaN(e)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(e)?z.array:e===null?z.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?z.promise:typeof Map<"u"&&e instanceof Map?z.map:typeof Set<"u"&&e instanceof Set?z.set:typeof Date<"u"&&e instanceof Date?z.date:z.object;default:return z.unknown}},D=ye.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),cx=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Bt extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(const i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;cn.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Bt.create=e=>new Bt(e);const Bs=(e,t)=>{let n;switch(e.code){case D.invalid_type:e.received===z.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case D.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ye.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:n=`Unrecognized key(s) in object: ${ye.joinValues(e.keys,", ")}`;break;case D.invalid_union:n="Invalid input";break;case D.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ye.joinValues(e.options)}`;break;case D.invalid_enum_value:n=`Invalid enum value. Expected ${ye.joinValues(e.options)}, received '${e.received}'`;break;case D.invalid_arguments:n="Invalid function arguments";break;case D.invalid_return_type:n="Invalid function return type";break;case D.invalid_date:n="Invalid date";break;case D.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:ye.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case D.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case D.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case D.custom:n="Invalid input";break;case D.invalid_intersection_types:n="Intersection results could not be merged";break;case D.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case D.not_finite:n="Number must be finite";break;default:n=t.defaultError,ye.assertNever(e)}return{message:n}};let Gd=Bs;function lx(e){Gd=e}function jo(){return Gd}const Ko=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],i={...s,path:o};let a="";const c=r.filter(l=>!!l).slice().reverse();for(const l of c)a=l(i,{data:t,defaultError:a}).message;return{...s,path:o,message:s.message||a}},ux=[];function F(e,t){const n=Ko({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,jo(),Bs].filter(r=>!!r)});e.common.issues.push(n)}class et{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const s of n){if(s.status==="aborted")return te;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const s of n)r.push({key:await s.key,value:await s.value});return et.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const s of n){const{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return te;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}}const te=Object.freeze({status:"aborted"}),Yd=e=>({status:"dirty",value:e}),it=e=>({status:"valid",value:e}),La=e=>e.status==="aborted",Ha=e=>e.status==="dirty",Mo=e=>e.status==="valid",Do=e=>typeof Promise<"u"&&e instanceof Promise;var J;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(J||(J={}));class Kt{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const tu=(e,t)=>{if(Mo(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Bt(e.common.issues);return this._error=n,this._error}}};function se(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(i,a)=>i.code!=="invalid_type"?{message:a.defaultError}:typeof a.data>"u"?{message:r??a.defaultError}:{message:n??a.defaultError},description:s}}class ae{constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return An(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:An(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new et,ctx:{common:t.parent.common,data:t.data,parsedType:An(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Do(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const s={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:An(t)},o=this._parseSync({data:t,path:s.path,parent:s});return tu(s,o)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:An(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(Do(s)?s:Promise.resolve(s));return tu(r,o)}refine(t,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{const i=t(s),a=()=>o.addIssue({code:D.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new Ot({schema:this,typeName:Q.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return nn.create(this,this._def)}nullable(){return dr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Tt.create(this,this._def)}promise(){return Wr.create(this,this._def)}or(t){return Cs.create([this,t],this._def)}and(t){return Ps.create(this,t,this._def)}transform(t){return new Ot({...se(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Rs({...se(this._def),innerType:this,defaultValue:n,typeName:Q.ZodDefault})}brand(){return new Jd({typeName:Q.ZodBranded,type:this,...se(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new zo({...se(this._def),innerType:this,catchValue:n,typeName:Q.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Ws.create(this,t)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const fx=/^c[^\s-]{8,}$/i,dx=/^[a-z][a-z0-9]*$/,hx=/[0-9A-HJKMNP-TV-Z]{26}/,px=/^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i,gx=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/,mx=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u"),yx=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,wx=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,bx=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):e.precision===0?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function xx(e,t){return!!((t==="v4"||!t)&&yx.test(e)||(t==="v6"||!t)&&wx.test(e))}class St extends ae{constructor(){super(...arguments),this._regex=(t,n,r)=>this.refinement(s=>t.test(s),{validation:n,code:D.invalid_string,...J.errToObj(r)}),this.nonempty=t=>this.min(1,J.errToObj(t)),this.trim=()=>new St({...this._def,checks:[...this._def.checks,{kind:"trim"}]}),this.toLowerCase=()=>new St({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]}),this.toUpperCase=()=>new St({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==z.string){const o=this._getOrReturnCtx(t);return F(o,{code:D.invalid_type,expected:z.string,received:o.parsedType}),te}const r=new et;let s;for(const o of this._def.checks)if(o.kind==="min")t.data.lengtho.value&&(s=this._getOrReturnCtx(t,s),F(s,{code:D.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){const i=t.data.length>o.value,a=t.data.length"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...J.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...J.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...J.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...J.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...J.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...J.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...J.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...J.errToObj(n)})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new St({checks:[],typeName:Q.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...se(e)})};function vx(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=parseInt(e.toFixed(s).replace(".","")),i=parseInt(t.toFixed(s).replace(".",""));return o%i/Math.pow(10,s)}class Nn extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==z.number){const o=this._getOrReturnCtx(t);return F(o,{code:D.invalid_type,expected:z.number,received:o.parsedType}),te}let r;const s=new et;for(const o of this._def.checks)o.kind==="int"?ye.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),F(r,{code:D.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),F(r,{code:D.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?vx(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),F(r,{code:D.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),F(r,{code:D.not_finite,message:o.message}),s.dirty()):ye.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,J.toString(n))}gt(t,n){return this.setLimit("min",t,!1,J.toString(n))}lte(t,n){return this.setLimit("max",t,!0,J.toString(n))}lt(t,n){return this.setLimit("max",t,!1,J.toString(n))}setLimit(t,n,r,s){return new Nn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:J.toString(s)}]})}_addCheck(t){return new Nn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:J.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:J.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:J.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:J.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:J.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:J.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:J.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:J.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:J.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&ye.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.valuenew Nn({checks:[],typeName:Q.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...se(e)});class Ln extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==z.bigint){const o=this._getOrReturnCtx(t);return F(o,{code:D.invalid_type,expected:z.bigint,received:o.parsedType}),te}let r;const s=new et;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),F(r,{code:D.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),F(r,{code:D.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):ye.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,J.toString(n))}gt(t,n){return this.setLimit("min",t,!1,J.toString(n))}lte(t,n){return this.setLimit("max",t,!0,J.toString(n))}lt(t,n){return this.setLimit("max",t,!1,J.toString(n))}setLimit(t,n,r,s){return new Ln({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:J.toString(s)}]})}_addCheck(t){return new Ln({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:J.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:J.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:J.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:J.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:J.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new Ln({checks:[],typeName:Q.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...se(e)})};class Ts extends ae{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==z.boolean){const r=this._getOrReturnCtx(t);return F(r,{code:D.invalid_type,expected:z.boolean,received:r.parsedType}),te}return it(t.data)}}Ts.create=e=>new Ts({typeName:Q.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...se(e)});class ur extends ae{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==z.date){const o=this._getOrReturnCtx(t);return F(o,{code:D.invalid_type,expected:z.date,received:o.parsedType}),te}if(isNaN(t.data.getTime())){const o=this._getOrReturnCtx(t);return F(o,{code:D.invalid_date}),te}const r=new et;let s;for(const o of this._def.checks)o.kind==="min"?t.data.getTime()o.value&&(s=this._getOrReturnCtx(t,s),F(s,{code:D.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):ye.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new ur({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:J.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:J.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew ur({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Q.ZodDate,...se(e)});class Zo extends ae{_parse(t){if(this._getType(t)!==z.symbol){const r=this._getOrReturnCtx(t);return F(r,{code:D.invalid_type,expected:z.symbol,received:r.parsedType}),te}return it(t.data)}}Zo.create=e=>new Zo({typeName:Q.ZodSymbol,...se(e)});class Os extends ae{_parse(t){if(this._getType(t)!==z.undefined){const r=this._getOrReturnCtx(t);return F(r,{code:D.invalid_type,expected:z.undefined,received:r.parsedType}),te}return it(t.data)}}Os.create=e=>new Os({typeName:Q.ZodUndefined,...se(e)});class Is extends ae{_parse(t){if(this._getType(t)!==z.null){const r=this._getOrReturnCtx(t);return F(r,{code:D.invalid_type,expected:z.null,received:r.parsedType}),te}return it(t.data)}}Is.create=e=>new Is({typeName:Q.ZodNull,...se(e)});class Fr extends ae{constructor(){super(...arguments),this._any=!0}_parse(t){return it(t.data)}}Fr.create=e=>new Fr({typeName:Q.ZodAny,...se(e)});class or extends ae{constructor(){super(...arguments),this._unknown=!0}_parse(t){return it(t.data)}}or.create=e=>new or({typeName:Q.ZodUnknown,...se(e)});class on extends ae{_parse(t){const n=this._getOrReturnCtx(t);return F(n,{code:D.invalid_type,expected:z.never,received:n.parsedType}),te}}on.create=e=>new on({typeName:Q.ZodNever,...se(e)});class Vo extends ae{_parse(t){if(this._getType(t)!==z.undefined){const r=this._getOrReturnCtx(t);return F(r,{code:D.invalid_type,expected:z.void,received:r.parsedType}),te}return it(t.data)}}Vo.create=e=>new Vo({typeName:Q.ZodVoid,...se(e)});class Tt extends ae{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==z.array)return F(n,{code:D.invalid_type,expected:z.array,received:n.parsedType}),te;if(s.exactLength!==null){const i=n.data.length>s.exactLength.value,a=n.data.lengths.maxLength.value&&(F(n,{code:D.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new Kt(n,i,n.path,a)))).then(i=>et.mergeArray(r,i));const o=[...n.data].map((i,a)=>s.type._parseSync(new Kt(n,i,n.path,a)));return et.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new Tt({...this._def,minLength:{value:t,message:J.toString(n)}})}max(t,n){return new Tt({...this._def,maxLength:{value:t,message:J.toString(n)}})}length(t,n){return new Tt({...this._def,exactLength:{value:t,message:J.toString(n)}})}nonempty(t){return this.min(1,t)}}Tt.create=(e,t)=>new Tt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...se(t)});function Ur(e){if(e instanceof Ue){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=nn.create(Ur(r))}return new Ue({...e._def,shape:()=>t})}else return e instanceof Tt?new Tt({...e._def,type:Ur(e.element)}):e instanceof nn?nn.create(Ur(e.unwrap())):e instanceof dr?dr.create(Ur(e.unwrap())):e instanceof Mt?Mt.create(e.items.map(t=>Ur(t))):e}class Ue extends ae{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=ye.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==z.object){const l=this._getOrReturnCtx(t);return F(l,{code:D.invalid_type,expected:z.object,received:l.parsedType}),te}const{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof on&&this._def.unknownKeys==="strip"))for(const l in s.data)i.includes(l)||a.push(l);const c=[];for(const l of i){const f=o[l],u=s.data[l];c.push({key:{status:"valid",value:l},value:f._parse(new Kt(s,u,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof on){const l=this._def.unknownKeys;if(l==="passthrough")for(const f of a)c.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(l==="strict")a.length>0&&(F(s,{code:D.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const f of a){const u=s.data[f];c.push({key:{status:"valid",value:f},value:l._parse(new Kt(s,u,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const f of c){const u=await f.key;l.push({key:u,value:await f.value,alwaysSet:f.alwaysSet})}return l}).then(l=>et.mergeObjectSync(r,l)):et.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return new Ue({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,o,i,a;const c=(i=(o=(s=this._def).errorMap)===null||o===void 0?void 0:o.call(s,n,r).message)!==null&&i!==void 0?i:r.defaultError;return n.code==="unrecognized_keys"?{message:(a=J.errToObj(t).message)!==null&&a!==void 0?a:c}:{message:c}}}:{}})}strip(){return new Ue({...this._def,unknownKeys:"strip"})}passthrough(){return new Ue({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ue({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ue({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Q.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Ue({...this._def,catchall:t})}pick(t){const n={};return ye.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}omit(t){const n={};return ye.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}deepPartial(){return Ur(this)}partial(t){const n={};return ye.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}),new Ue({...this._def,shape:()=>n})}required(t){const n={};return ye.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof nn;)o=o._def.innerType;n[r]=o}}),new Ue({...this._def,shape:()=>n})}keyof(){return Xd(ye.objectKeys(this.shape))}}Ue.create=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strip",catchall:on.create(),typeName:Q.ZodObject,...se(t)});Ue.strictCreate=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strict",catchall:on.create(),typeName:Q.ZodObject,...se(t)});Ue.lazycreate=(e,t)=>new Ue({shape:e,unknownKeys:"strip",catchall:on.create(),typeName:Q.ZodObject,...se(t)});class Cs extends ae{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(const a of o)if(a.result.status==="valid")return a.result;for(const a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;const i=o.map(a=>new Bt(a.ctx.common.issues));return F(n,{code:D.invalid_union,unionErrors:i}),te}if(n.common.async)return Promise.all(r.map(async o=>{const i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o;const i=[];for(const c of r){const l={...n,common:{...n.common,issues:[]},parent:null},f=c._parseSync({data:n.data,path:n.path,parent:l});if(f.status==="valid")return f;f.status==="dirty"&&!o&&(o={result:f,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(c=>new Bt(c));return F(n,{code:D.invalid_union,unionErrors:a}),te}}get options(){return this._def.options}}Cs.create=(e,t)=>new Cs({options:e,typeName:Q.ZodUnion,...se(t)});const So=e=>e instanceof Ns?So(e.schema):e instanceof Ot?So(e.innerType()):e instanceof Ls?[e.value]:e instanceof Hn?e.options:e instanceof Hs?Object.keys(e.enum):e instanceof Rs?So(e._def.innerType):e instanceof Os?[void 0]:e instanceof Is?[null]:null;class xi extends ae{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==z.object)return F(n,{code:D.invalid_type,expected:z.object,received:n.parsedType}),te;const r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(F(n,{code:D.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),te)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const s=new Map;for(const o of n){const i=So(o.shape[t]);if(!i)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const a of i){if(s.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);s.set(a,o)}}return new xi({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...se(r)})}}function Ra(e,t){const n=An(e),r=An(t);if(e===t)return{valid:!0,data:e};if(n===z.object&&r===z.object){const s=ye.objectKeys(t),o=ye.objectKeys(e).filter(a=>s.indexOf(a)!==-1),i={...e,...t};for(const a of o){const c=Ra(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===z.array&&r===z.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let o=0;o{if(La(o)||La(i))return te;const a=Ra(o.value,i.value);return a.valid?((Ha(o)||Ha(i))&&n.dirty(),{status:n.value,value:a.data}):(F(r,{code:D.invalid_intersection_types}),te)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Ps.create=(e,t,n)=>new Ps({left:e,right:t,typeName:Q.ZodIntersection,...se(n)});class Mt extends ae{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==z.array)return F(r,{code:D.invalid_type,expected:z.array,received:r.parsedType}),te;if(r.data.lengththis._def.items.length&&(F(r,{code:D.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const o=[...r.data].map((i,a)=>{const c=this._def.items[a]||this._def.rest;return c?c._parse(new Kt(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>et.mergeArray(n,i)):et.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new Mt({...this._def,rest:t})}}Mt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Mt({items:e,typeName:Q.ZodTuple,rest:null,...se(t)})};class Us extends ae{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==z.object)return F(r,{code:D.invalid_type,expected:z.object,received:r.parsedType}),te;const s=[],o=this._def.keyType,i=this._def.valueType;for(const a in r.data)s.push({key:o._parse(new Kt(r,a,r.path,a)),value:i._parse(new Kt(r,r.data[a],r.path,a))});return r.common.async?et.mergeObjectAsync(n,s):et.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof ae?new Us({keyType:t,valueType:n,typeName:Q.ZodRecord,...se(r)}):new Us({keyType:St.create(),valueType:t,typeName:Q.ZodRecord,...se(n)})}}class qo extends ae{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==z.map)return F(r,{code:D.invalid_type,expected:z.map,received:r.parsedType}),te;const s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,c],l)=>({key:s._parse(new Kt(r,a,r.path,[l,"key"])),value:o._parse(new Kt(r,c,r.path,[l,"value"]))}));if(r.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const c of i){const l=await c.key,f=await c.value;if(l.status==="aborted"||f.status==="aborted")return te;(l.status==="dirty"||f.status==="dirty")&&n.dirty(),a.set(l.value,f.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const c of i){const l=c.key,f=c.value;if(l.status==="aborted"||f.status==="aborted")return te;(l.status==="dirty"||f.status==="dirty")&&n.dirty(),a.set(l.value,f.value)}return{status:n.value,value:a}}}}qo.create=(e,t,n)=>new qo({valueType:t,keyType:e,typeName:Q.ZodMap,...se(n)});class fr extends ae{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==z.set)return F(r,{code:D.invalid_type,expected:z.set,received:r.parsedType}),te;const s=this._def;s.minSize!==null&&r.data.sizes.maxSize.value&&(F(r,{code:D.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const o=this._def.valueType;function i(c){const l=new Set;for(const f of c){if(f.status==="aborted")return te;f.status==="dirty"&&n.dirty(),l.add(f.value)}return{status:n.value,value:l}}const a=[...r.data.values()].map((c,l)=>o._parse(new Kt(r,c,r.path,l)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(t,n){return new fr({...this._def,minSize:{value:t,message:J.toString(n)}})}max(t,n){return new fr({...this._def,maxSize:{value:t,message:J.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}fr.create=(e,t)=>new fr({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...se(t)});class Rr extends ae{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==z.function)return F(n,{code:D.invalid_type,expected:z.function,received:n.parsedType}),te;function r(a,c){return Ko({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,jo(),Bs].filter(l=>!!l),issueData:{code:D.invalid_arguments,argumentsError:c}})}function s(a,c){return Ko({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,jo(),Bs].filter(l=>!!l),issueData:{code:D.invalid_return_type,returnTypeError:c}})}const o={errorMap:n.common.contextualErrorMap},i=n.data;return this._def.returns instanceof Wr?it(async(...a)=>{const c=new Bt([]),l=await this._def.args.parseAsync(a,o).catch(d=>{throw c.addIssue(r(a,d)),c}),f=await i(...l);return await this._def.returns._def.type.parseAsync(f,o).catch(d=>{throw c.addIssue(s(f,d)),c})}):it((...a)=>{const c=this._def.args.safeParse(a,o);if(!c.success)throw new Bt([r(a,c.error)]);const l=i(...c.data),f=this._def.returns.safeParse(l,o);if(!f.success)throw new Bt([s(l,f.error)]);return f.data})}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Rr({...this._def,args:Mt.create(t).rest(or.create())})}returns(t){return new Rr({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Rr({args:t||Mt.create([]).rest(or.create()),returns:n||or.create(),typeName:Q.ZodFunction,...se(r)})}}class Ns extends ae{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Ns.create=(e,t)=>new Ns({getter:e,typeName:Q.ZodLazy,...se(t)});class Ls extends ae{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return F(n,{received:n.data,code:D.invalid_literal,expected:this._def.value}),te}return{status:"valid",value:t.data}}get value(){return this._def.value}}Ls.create=(e,t)=>new Ls({value:e,typeName:Q.ZodLiteral,...se(t)});function Xd(e,t){return new Hn({values:e,typeName:Q.ZodEnum,...se(t)})}class Hn extends ae{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return F(n,{expected:ye.joinValues(r),received:n.parsedType,code:D.invalid_type}),te}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return F(n,{received:n.data,code:D.invalid_enum_value,options:r}),te}return it(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t){return Hn.create(t)}exclude(t){return Hn.create(this.options.filter(n=>!t.includes(n)))}}Hn.create=Xd;class Hs extends ae{_parse(t){const n=ye.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==z.string&&r.parsedType!==z.number){const s=ye.objectValues(n);return F(r,{expected:ye.joinValues(s),received:r.parsedType,code:D.invalid_type}),te}if(n.indexOf(t.data)===-1){const s=ye.objectValues(n);return F(r,{received:r.data,code:D.invalid_enum_value,options:s}),te}return it(t.data)}get enum(){return this._def.values}}Hs.create=(e,t)=>new Hs({values:e,typeName:Q.ZodNativeEnum,...se(t)});class Wr extends ae{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==z.promise&&n.common.async===!1)return F(n,{code:D.invalid_type,expected:z.promise,received:n.parsedType}),te;const r=n.parsedType===z.promise?n.data:Promise.resolve(n.data);return it(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Wr.create=(e,t)=>new Wr({type:e,typeName:Q.ZodPromise,...se(t)});class Ot extends ae{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null;if(s.type==="preprocess"){const i=s.transform(r.data);return r.common.async?Promise.resolve(i).then(a=>this._def.schema._parseAsync({data:a,path:r.path,parent:r})):this._def.schema._parseSync({data:i,path:r.path,parent:r})}const o={addIssue:i=>{F(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="refinement"){const i=a=>{const c=s.refinement(a,o);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?te:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?te:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Mo(i))return i;const a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>Mo(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):i);ye.assertNever(s)}}Ot.create=(e,t,n)=>new Ot({schema:e,typeName:Q.ZodEffects,effect:t,...se(n)});Ot.createWithPreprocess=(e,t,n)=>new Ot({schema:t,effect:{type:"preprocess",transform:e},typeName:Q.ZodEffects,...se(n)});class nn extends ae{_parse(t){return this._getType(t)===z.undefined?it(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}nn.create=(e,t)=>new nn({innerType:e,typeName:Q.ZodOptional,...se(t)});class dr extends ae{_parse(t){return this._getType(t)===z.null?it(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}dr.create=(e,t)=>new dr({innerType:e,typeName:Q.ZodNullable,...se(t)});class Rs extends ae{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===z.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Rs.create=(e,t)=>new Rs({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...se(t)});class zo extends ae{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Do(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Bt(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Bt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}zo.create=(e,t)=>new zo({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...se(t)});class Fo extends ae{_parse(t){if(this._getType(t)!==z.nan){const r=this._getOrReturnCtx(t);return F(r,{code:D.invalid_type,expected:z.nan,received:r.parsedType}),te}return{status:"valid",value:t.data}}}Fo.create=e=>new Fo({typeName:Q.ZodNaN,...se(e)});const kx=Symbol("zod_brand");class Jd extends ae{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Ws extends ae{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?te:o.status==="dirty"?(n.dirty(),Yd(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?te:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new Ws({in:t,out:n,typeName:Q.ZodPipeline})}}const Qd=(e,t={},n)=>e?Fr.create().superRefine((r,s)=>{var o,i;if(!e(r)){const a=typeof t=="function"?t(r):typeof t=="string"?{message:t}:t,c=(i=(o=a.fatal)!==null&&o!==void 0?o:n)!==null&&i!==void 0?i:!0,l=typeof a=="string"?{message:a}:a;s.addIssue({code:"custom",...l,fatal:c})}}):Fr.create(),$x={object:Ue.lazycreate};var Q;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline"})(Q||(Q={}));const Ex=(e,t={message:`Input not instance of ${e.name}`})=>Qd(n=>n instanceof e,t),eh=St.create,th=Nn.create,Sx=Fo.create,_x=Ln.create,nh=Ts.create,Ax=ur.create,Bx=Zo.create,Tx=Os.create,Ox=Is.create,Ix=Fr.create,Cx=or.create,Px=on.create,Ux=Vo.create,Nx=Tt.create,Lx=Ue.create,Hx=Ue.strictCreate,Rx=Cs.create,jx=xi.create,Kx=Ps.create,Mx=Mt.create,Dx=Us.create,Zx=qo.create,Vx=fr.create,qx=Rr.create,zx=Ns.create,Fx=Ls.create,Wx=Hn.create,Gx=Hs.create,Yx=Wr.create,nu=Ot.create,Xx=nn.create,Jx=dr.create,Qx=Ot.createWithPreprocess,e2=Ws.create,t2=()=>eh().optional(),n2=()=>th().optional(),r2=()=>nh().optional(),s2={string:(e=>St.create({...e,coerce:!0})),number:(e=>Nn.create({...e,coerce:!0})),boolean:(e=>Ts.create({...e,coerce:!0})),bigint:(e=>Ln.create({...e,coerce:!0})),date:(e=>ur.create({...e,coerce:!0}))},o2=te;var st=Object.freeze({__proto__:null,defaultErrorMap:Bs,setErrorMap:lx,getErrorMap:jo,makeIssue:Ko,EMPTY_PATH:ux,addIssueToContext:F,ParseStatus:et,INVALID:te,DIRTY:Yd,OK:it,isAborted:La,isDirty:Ha,isValid:Mo,isAsync:Do,get util(){return ye},get objectUtil(){return Na},ZodParsedType:z,getParsedType:An,ZodType:ae,ZodString:St,ZodNumber:Nn,ZodBigInt:Ln,ZodBoolean:Ts,ZodDate:ur,ZodSymbol:Zo,ZodUndefined:Os,ZodNull:Is,ZodAny:Fr,ZodUnknown:or,ZodNever:on,ZodVoid:Vo,ZodArray:Tt,ZodObject:Ue,ZodUnion:Cs,ZodDiscriminatedUnion:xi,ZodIntersection:Ps,ZodTuple:Mt,ZodRecord:Us,ZodMap:qo,ZodSet:fr,ZodFunction:Rr,ZodLazy:Ns,ZodLiteral:Ls,ZodEnum:Hn,ZodNativeEnum:Hs,ZodPromise:Wr,ZodEffects:Ot,ZodTransformer:Ot,ZodOptional:nn,ZodNullable:dr,ZodDefault:Rs,ZodCatch:zo,ZodNaN:Fo,BRAND:kx,ZodBranded:Jd,ZodPipeline:Ws,custom:Qd,Schema:ae,ZodSchema:ae,late:$x,get ZodFirstPartyTypeKind(){return Q},coerce:s2,any:Ix,array:Nx,bigint:_x,boolean:nh,date:Ax,discriminatedUnion:jx,effect:nu,enum:Wx,function:qx,instanceof:Ex,intersection:Kx,lazy:zx,literal:Fx,map:Zx,nan:Sx,nativeEnum:Gx,never:Px,null:Ox,nullable:Jx,number:th,object:Lx,oboolean:r2,onumber:n2,optional:Xx,ostring:t2,pipeline:e2,preprocess:Qx,promise:Yx,record:Dx,set:Vx,strictObject:Hx,string:eh,symbol:Bx,transformer:nu,tuple:Mx,undefined:Tx,union:Rx,unknown:Cx,void:Ux,NEVER:o2,ZodIssueCode:D,quotelessJson:cx,ZodError:Bt});const rh=st.string().regex(/^[a-fA-F0-9]$/),i2=st.string().regex(/^[a-fA-F0-9]{64}$/),Gr=st.number().min(0).max(4294967295),a2=st.bigint(),sh=st.instanceof(Uint8Array),c2=st.union([rh,Gr,st.string(),sh]).array(),Zc=st.union([c2,rh,sh]),l2=st.array(Zc),oh=st.object({value:st.union([Gr,a2]),scriptPubKey:Zc}),u2=st.object({txid:i2,vout:Gr,scriptSig:Zc,sequence:Gr,prevout:oh.optional(),witness:l2});st.object({version:Gr,vin:st.array(u2),vout:st.array(oh),locktime:Gr});const ja=2048,f2=new TextEncoder;function ih(e){const t=[],n=(s,o)=>{if(o<24)t.push(s*32+o);else if(o<=255)t.push(s*32+24,o);else if(o<=65535)t.push(s*32+25,o>>>8,o&255);else if(o<=4294967295){const i=new Uint8Array(4);new DataView(i.buffer).setUint32(0,o),t.push(s*32+26,...i)}else{t.push(s*32+27);const i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,BigInt(o)),t.push(...i)}},r=(s,o=0)=>{if(o>64)throw new Error("Metadata nesting exceeds 64 levels.");if(s===null)t.push(246);else if(typeof s=="boolean")t.push(s?245:244);else if(typeof s=="number"&&Number.isFinite(s))if(Number.isSafeInteger(s)&&!Object.is(s,-0))n(s>=0?0:1,s>=0?s:-1-s);else{const i=new Uint8Array(8);new DataView(i.buffer).setFloat64(0,s),t.push(251,...i)}else if(typeof s=="string"){const i=f2.encode(s);n(3,i.length);for(const a of i)t.push(a)}else if(Array.isArray(s))n(4,s.length),s.forEach(i=>r(i,o+1));else if(typeof s=="object"&&Object.getPrototypeOf(s)===Object.prototype){const i=Object.entries(s);n(5,i.length);for(const[a,c]of i)r(a,o+1),r(c,o+1)}else throw new Error("Metadata must contain only JSON values.");if(t.length>ja)throw new Error(`Metadata must be at most ${ja} CBOR bytes.`)};return r(e),Uint8Array.from(t)}function d2(e){if(e=new Uint8Array(e),!e.length||e.length>ja)throw new Error("Invalid CBOR metadata size.");let t=0;const n=o=>{if(t+o>e.length)throw new Error("Truncated CBOR metadata.");const i=e.slice(t,t+o);return t+=o,i},r=(o=0)=>{if(o>64)throw new Error("Metadata nesting exceeds 64 levels.");const i=n(1)[0],a=i>>5,c=i&31;if(a===7){if(c===20)return!1;if(c===21)return!0;if(c===22)return null;if(c===27){const f=new DataView(n(8).buffer).getFloat64(0);if(Number.isFinite(f))return f}throw new Error("Unsupported CBOR value.")}let l=c;if(c>=24&&c<=27){l=0;for(const f of n(2**(c-24)))l=l*256+f}else if(c>=28)throw new Error("Unsupported CBOR length.");if(!Number.isSafeInteger(l))throw new Error("CBOR integer exceeds JSON precision.");if(a===0)return l;if(a===1)return-1-l;if(a===3)return new TextDecoder("utf-8",{fatal:!0}).decode(n(l));if((a===4||a===5)&&l>e.length)throw new Error("Invalid CBOR collection length.");if(a===4)return Array.from({length:l},()=>r(o+1));if(a===5){const f={};for(let u=0;u({txid:e,vout:t,sequence:4294967295,prevout:{value:n,scriptPubKey:r}}),de=(e,t)=>({value:e,scriptPubKey:t}),ru=16*1024,Ht=1e3,W=500,Wo="text/plain;charset=utf-8",h2=["text/plain","application/json","text/html","image/svg+xml","image/png","image/jpeg","image/webp"],ah=new TextEncoder,ks=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""),Yn=e=>Uint8Array.from(e.match(/../g)??[],t=>parseInt(t,16)),Go=e=>ks(ah.encode(e));function Vc(e){const t=typeof e=="string"?{contentType:Wo,bytes:ah.encode(e)}:e;if(!t||![...h2,Wo].includes(t.contentType))throw new Error("Unsupported MIME type.");if(!(t.bytes instanceof Uint8Array)||!t.bytes.length)throw new Error("Enter non-empty inscription bytes.");if(t.bytes.length>ru)throw new Error(`Body must be at most ${ru} bytes.`);return{contentType:t.contentType,bytes:new Uint8Array(t.bytes)}}function Yo(e){const t=/^([0-9a-f]{64})i(0|[1-9][0-9]*)$/.exec(e);if(!t||Number(t[2])>4294967295)throw new Error("Invalid parent inscription id.");let n=Number(t[2]),r="";for(;n;)r+=(n%256).toString(16).padStart(2,"0"),n=Math.floor(n/256);return t[1].match(/../g).reverse().join("")+r}function su(e){if(typeof e!="string"||!/^[0-9a-f]{64,72}$/.test(e)||e.length%2)throw new Error("Invalid parent tag.");const t=[...Yn(e.slice(64))].reduce((r,s,o)=>r+s*256**o,0),n=`${e.slice(0,64).match(/../g).reverse().join("")}i${t}`;if(Yo(n)!==e)throw new Error("Non-canonical parent tag.");return n}function qc(e,t,n=null,r=void 0,s={}){const{contentType:o,bytes:i}=Vc(t),{delegate:a=null,pointer:c,metaprotocol:l=null}=s,f=l==null||l===""?null:new TextEncoder().encode(String(l));if(f&&f.length>520)throw new Error("Metaprotocol identifier must be 520 bytes or less.");const u=r===void 0?void 0:ih(r),d=[];for(let g=0;g{const p=g.length/2;return(p<=75?p.toString(16).padStart(2,"0"):p<=255?"4c"+p.toString(16).padStart(2,"0"):"4d"+(p%256).toString(16).padStart(2,"0")+Math.floor(p/256).toString(16).padStart(2,"0"))+g};return h(e)+"ac0063"+h(Go("ord"))+h("01")+h(Go(o))+(a?h("0b")+h(Yo(a)):"")+(c===void 0?"":h("02")+h(lh(c)))+(n?h("03")+h(Yo(n)):"")+(u===void 0?"":Array.from({length:Math.ceil(u.length/520)},(g,p)=>h("05")+h(ks(u.slice(p*520,(p+1)*520)))).join(""))+(f?h("07")+h(ks(f)):"")+"00"+d.map(h).join("")+"68"}const ch=e=>Fs.tree.getLeaf(Ce.encode(e,!0));function zc(e){if(!Array.isArray(e)||e.length!==3)throw new Error("Unsupported script-path witness.");const t=Ce.decode(e[1]);let n=7,r=null,s=null,o;t[n]==="0b"&&(s=su(t[n+1]),n+=2),t[n]==="02"&&(o=g2(t[n+1]==="OP_0"?"":t[n+1]),n+=2),t[n]==="03"&&(r=su(t[n+1]),n+=2);const i=[];for(;t[n]==="05";){const g=t[n+1];if(typeof g!="string"||!/^(?:[0-9a-f]{2}){1,520}$/.test(g))throw new Error("Invalid metadata push.");i.push(g),n+=2}const a=i.length?d2(Yn(i.join(""))):void 0;let c=null;if(t[n]==="07"){const g=t[n+1];if(typeof g!="string"||!/^(?:[0-9a-f]{2}){1,520}$/.test(g))throw new Error("Invalid metaprotocol field.");c=new TextDecoder().decode(Yn(g)),n+=2}if(t[n]!=="OP_0")throw new Error("Unsupported ord tag or missing body separator.");const l=t.slice(n+1,-1);if(!l.length||l.some(g=>typeof g!="string"||!/^(?:[0-9a-f]{2})+$/.test(g)))throw new Error("Invalid body envelope.");const f=new TextDecoder().decode(Yn(t[6])),u=Vc({contentType:f,bytes:Yn(l.join(""))}),d=qc(t[0],u,r,a,{delegate:s,pointer:o,metaprotocol:c}),h=a===void 0&&!r&&f===Wo&&u.bytes.length<=280&&Ce.encode([t[0],"OP_CHECKSIG","OP_0","OP_IF",Go("ord"),"01",Go(Wo),"OP_0",ks(u.bytes),"OP_ENDIF"],!1).hex;if(d!==e[1]&&h!==e[1])throw new Error("Unsupported ord envelope.");if(!/^[0-9a-f]{64}$/.test(t[0]))throw new Error("Invalid inscription signing key.");return{...u,parent:r,delegate:s,pointer:o,metaprotocol:c,metadata:a,metadataBytes:i.length?Yn(i.join("")):void 0,text:new TextDecoder().decode(u.bytes),pubkey:t[0]}}class p2{constructor(t,n){this.chain=t,this.wallet=n}prepare(t,n=null,r=void 0,s={}){const o=Vc(t);if(r!==void 0&&ih(r),s.delegate&&Yo(s.delegate),s.pointer!==void 0&&lh(s.pointer),s.metaprotocol!==void 0&&s.metaprotocol!==null&&s.metaprotocol!==""&&new TextEncoder().encode(String(s.metaprotocol)).length>520)throw new Error("Metaprotocol identifier must be 520 bytes or less.");if(n&&s.reinscribe)throw new Error("Choose parent or reinscription, not both.");const i=this.chain.coins(this.wallet.script),a=n?i.find(f=>{var u;return(u=f.inscriptions)==null?void 0:u.some(d=>d.id===n)}):null;if(n&&!a)throw new Error("Parent must be an owned, unspent inscription.");const c=s.reinscribe?i.find(f=>{var u;return(u=f.inscriptions)==null?void 0:u.some(d=>d.id===s.reinscribe)}):null;if(s.reinscribe&&!c)throw new Error("Reinscription must spend an owned sat.");const l=i.find(f=>!f.inscription&&f.value>=Ht+2*W+330);if(!l)throw new Error("Mine a block first to get spendable fake BTC.");return{...o,coin:l,parent:a,reinscribe:c,totalFee:W*2,postage:Ht}}inscribe(t,n=null,r=void 0,s={}){const{coin:o,parent:i,reinscribe:a,...c}=this.prepare(t,n,r,s),l=i??a,f=a==null?void 0:a.inscriptions.find(_=>_.id===s.reinscribe),u=f?this.chain.satLocation(f.sat).offset:s.pointer??(i?i.value:void 0),d=qc(this.wallet.pubkey,c,n,r,{...s,pointer:u}),h=ch(d),[g,p]=Fs.getPubKey(this.wallet.pubkey,{target:h}),m=X.create({vin:[Fe(o.txid,o.vout,o.value,o.scriptPubKey)],vout:[de(Ht+W,["OP_1",g]),de(o.value-Ht-2*W,this.wallet.script)]});m.vin[0].witness=[this.wallet.sign(m)];const w=X.util.getTxid(m),y=X.create({vin:[...l?[Fe(l.txid,l.vout,l.value,l.scriptPubKey)]:[],Fe(w,0,Ht+W,["OP_1",g])],vout:[...l?[de(l.value,this.wallet.script)]:[],de(Ht,this.wallet.script)]}),b=l?1:0;return y.vin[b].witness=[this.wallet.sign(y,h,b),Ce.encode(d,!1).hex,p],l&&(y.vin[0].witness=[this.wallet.sign(y)]),this.chain.submitPackage([X.encode(m).hex,X.encode(y).hex]),`${X.util.getTxid(y)}i0`}list(){return this.chain.coins(this.wallet.script).flatMap(t=>t.inscriptions??[])}}function lh(e){let t;try{t=BigInt(e)}catch{throw new Error("Invalid pointer.")}if(t<0n||t>0xffffffffffffffffn||typeof e=="number"&&!Number.isSafeInteger(e))throw new Error("Invalid pointer.");let n="";for(;t;)n+=Number(t&255n).toString(16).padStart(2,"0"),t>>=8n;return n}function g2(e){if(typeof e!="string"||!/^(?:[0-9a-f]{2}){0,8}$/.test(e))throw new Error("Invalid pointer tag.");return[...Yn(e)].reduce((t,n,r)=>t+(BigInt(n)<this.utxos.set(`${r.txid}:${r.vout}`,{txid:r.txid,vout:r.vout,value:r.value,ranges:Xu(s,r.value)}));const n=(r,s,o)=>{var w;const i=X.decode(r),a=X.util.getTxid(i),c=i.vin[0].txid==="0".repeat(64),l=c?[]:i.vin.map(y=>this.utxos.get(`${y.txid}:${y.vout}`)),f=ef(i,l,s,c);i.vin.forEach(y=>this.utxos.delete(`${y.txid}:${y.vout}`)),i.vout.forEach((y,b)=>this.utxos.set(`${a}:${b}`,{txid:a,vout:b,value:Number(y.value),ranges:f[b]}));const u=(w=i.vin.find(y=>{var b;return((b=y.witness)==null?void 0:b.length)===3}))==null?void 0:w.witness;if(!u)return;const d=zc(u),h=BigInt(d.pointer??0),g=i.vout.reduce((y,b)=>y+Number(b.value),0),p=Qu(f.flat(),hy.sat===p).length,status:s===null?"pending":"confirmed",height:s,block:o,metadata:m??null,hasMetadata:m!==void 0,parent:d.parent,protocol:d.metaprotocol??(m&&!Array.isArray(m)&&typeof m=="object"&&Object.hasOwn(m,"protocol")&&typeof m.protocol=="string"?m.protocol:null)})};for(const r of t.blocks)for(const s of r.raws)n(s,r.height,r.hash);for(const r of t.mempool)n(r,null,null);for(const r of this.events){r.location=null;for(const s of this.utxos.values()){const o=Bn(s.ranges,r.sat);if(o!==null){r.location={txid:s.txid,vout:s.vout,offset:o};break}}r.delegatedBy=this.events.filter(s=>s.delegate===r.id).map(s=>s.id),r.inscriptions=this.events.filter(s=>s.sat===r.sat).map(s=>s.id)}}forProtocol(t){return this.events.filter(n=>n.protocol===t)}get protocols(){return[...new Set(this.events.filter(t=>t.protocol!==null).map(t=>t.protocol))].sort()}get stats(){return{events:this.events.length,withMetadata:this.events.filter(t=>t.hasMetadata).length,confirmed:this.events.filter(t=>t.status==="confirmed").length,pending:this.events.filter(t=>t.status==="pending").length,protocols:this.protocols}}}const Tr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Gs(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Rt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Ve(e,...t){if(!Gs(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Ys(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Rt(e.outputLen),Rt(e.blockLen)}function Yr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function uh(e,t){Ve(e);const n=t.outputLen;if(e.length>>t}function co(e,t){return e<>>32-t>>>0}const y2=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function w2(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function b2(e){for(let t=0;te:b2,fh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",x2=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ie(e){if(Ve(e),fh)return e.toHex();let t="";for(let n=0;n=Xt._0&&e<=Xt._9)return e-Xt._0;if(e>=Xt.A&&e<=Xt.F)return e-(Xt.A-10);if(e>=Xt.a&&e<=Xt.f)return e-(Xt.a-10)}function bt(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(fh)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let s=0,o=0;se().update(Xr(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function kr(e=32){if(Tr&&typeof Tr.getRandomValues=="function")return Tr.getRandomValues(new Uint8Array(e));if(Tr&&typeof Tr.randomBytes=="function")return Uint8Array.from(Tr.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function k2(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const s=BigInt(32),o=BigInt(4294967295),i=Number(n>>s&o),a=Number(n&o),c=r?4:0,l=r?0:4;e.setUint32(t+c,i,r),e.setUint32(t+l,a,r)}function $2(e,t,n){return e&t^~e&n}function E2(e,t,n){return e&t^e&n^t&n}class Wc extends Fc{constructor(t,n,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(t),this.view=ir(this.buffer)}update(t){Yr(this),t=Xr(t),Ve(t);const{view:n,buffer:r,blockLen:s}=this,o=t.length;for(let i=0;is-i&&(this.process(r,0),i=0);for(let u=i;uf.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u>cu&lo)}:{h:Number(e>>cu&lo)|0,l:Number(e&lo)|0}}function dh(e,t=!1){const n=e.length;let r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;oe>>>n,uu=(e,t,n)=>e<<32-n|t>>>n,Or=(e,t,n)=>e>>>n|t<<32-n,Ir=(e,t,n)=>e<<32-n|t>>>n,uo=(e,t,n)=>e<<64-n|t>>>n-32,fo=(e,t,n)=>e>>>n-32|t<<64-n,_2=(e,t,n)=>e<>>32-n,A2=(e,t,n)=>t<>>32-n,B2=(e,t,n)=>t<>>64-n,T2=(e,t,n)=>e<>>64-n;function Jt(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}const O2=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),I2=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,C2=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),P2=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,U2=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),N2=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,L2=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),kn=new Uint32Array(64);class H2 extends Wc{constructor(t=32){super(64,t,8,!1),this.A=vn[0]|0,this.B=vn[1]|0,this.C=vn[2]|0,this.D=vn[3]|0,this.E=vn[4]|0,this.F=vn[5]|0,this.G=vn[6]|0,this.H=vn[7]|0}get(){const{A:t,B:n,C:r,D:s,E:o,F:i,G:a,H:c}=this;return[t,n,r,s,o,i,a,c]}set(t,n,r,s,o,i,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,n){for(let u=0;u<16;u++,n+=4)kn[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const d=kn[u-15],h=kn[u-2],g=Lt(d,7)^Lt(d,18)^d>>>3,p=Lt(h,17)^Lt(h,19)^h>>>10;kn[u]=p+kn[u-7]+g+kn[u-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){const d=Lt(a,6)^Lt(a,11)^Lt(a,25),h=f+d+$2(a,c,l)+L2[u]+kn[u]|0,p=(Lt(r,2)^Lt(r,13)^Lt(r,22))+E2(r,s,o)|0;f=l,l=c,c=a,a=i+h|0,i=o,o=s,s=r,r=h+p|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,f=f+this.H|0,this.set(r,s,o,i,a,c,l,f)}roundClean(){wt(kn)}destroy(){this.set(0,0,0,0,0,0,0,0),wt(this.buffer)}}const hh=dh(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),R2=hh[0],j2=hh[1],$n=new Uint32Array(80),En=new Uint32Array(80);class K2 extends Wc{constructor(t=64){super(128,t,16,!1),this.Ah=Xe[0]|0,this.Al=Xe[1]|0,this.Bh=Xe[2]|0,this.Bl=Xe[3]|0,this.Ch=Xe[4]|0,this.Cl=Xe[5]|0,this.Dh=Xe[6]|0,this.Dl=Xe[7]|0,this.Eh=Xe[8]|0,this.El=Xe[9]|0,this.Fh=Xe[10]|0,this.Fl=Xe[11]|0,this.Gh=Xe[12]|0,this.Gl=Xe[13]|0,this.Hh=Xe[14]|0,this.Hl=Xe[15]|0}get(){const{Ah:t,Al:n,Bh:r,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:f,Fh:u,Fl:d,Gh:h,Gl:g,Hh:p,Hl:m}=this;return[t,n,r,s,o,i,a,c,l,f,u,d,h,g,p,m]}set(t,n,r,s,o,i,a,c,l,f,u,d,h,g,p,m){this.Ah=t|0,this.Al=n|0,this.Bh=r|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=f|0,this.Fh=u|0,this.Fl=d|0,this.Gh=h|0,this.Gl=g|0,this.Hh=p|0,this.Hl=m|0}process(t,n){for(let b=0;b<16;b++,n+=4)$n[b]=t.getUint32(n),En[b]=t.getUint32(n+=4);for(let b=16;b<80;b++){const _=$n[b-15]|0,$=En[b-15]|0,x=Or(_,$,1)^Or(_,$,8)^lu(_,$,7),C=Ir(_,$,1)^Ir(_,$,8)^uu(_,$,7),P=$n[b-2]|0,O=En[b-2]|0,N=Or(P,O,19)^uo(P,O,61)^lu(P,O,6),R=Ir(P,O,19)^fo(P,O,61)^uu(P,O,6),B=C2(C,R,En[b-7],En[b-16]),k=P2(B,x,N,$n[b-7],$n[b-16]);$n[b]=k|0,En[b]=B|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:f,Eh:u,El:d,Fh:h,Fl:g,Gh:p,Gl:m,Hh:w,Hl:y}=this;for(let b=0;b<80;b++){const _=Or(u,d,14)^Or(u,d,18)^uo(u,d,41),$=Ir(u,d,14)^Ir(u,d,18)^fo(u,d,41),x=u&h^~u&p,C=d&g^~d&m,P=U2(y,$,C,j2[b],En[b]),O=N2(P,w,_,x,R2[b],$n[b]),N=P|0,R=Or(r,s,28)^uo(r,s,34)^uo(r,s,39),B=Ir(r,s,28)^fo(r,s,34)^fo(r,s,39),k=r&o^r&a^o&a,E=s&i^s&c^i&c;w=p|0,y=m|0,p=h|0,m=g|0,h=u|0,g=d|0,{h:u,l:d}=Jt(l|0,f|0,O|0,N|0),l=a|0,f=c|0,a=o|0,c=i|0,o=r|0,i=s|0;const v=O2(N,B,E);r=I2(v,O,R,k),s=v|0}({h:r,l:s}=Jt(this.Ah|0,this.Al|0,r|0,s|0)),{h:o,l:i}=Jt(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=Jt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:f}=Jt(this.Dh|0,this.Dl|0,l|0,f|0),{h:u,l:d}=Jt(this.Eh|0,this.El|0,u|0,d|0),{h,l:g}=Jt(this.Fh|0,this.Fl|0,h|0,g|0),{h:p,l:m}=Jt(this.Gh|0,this.Gl|0,p|0,m|0),{h:w,l:y}=Jt(this.Hh|0,this.Hl|0,w|0,y|0),this.set(r,s,o,i,a,c,l,f,u,d,h,g,p,m,w,y)}roundClean(){wt($n,En)}destroy(){wt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Ae=vi(()=>new H2),js=vi(()=>new K2);class ph extends Fc{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Ys(t);const r=Xr(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?t.create().update(r).digest():r);for(let i=0;inew ph(e,t).update(n).digest();Rn.create=(e,t)=>new ph(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Gc=BigInt(0),Ka=BigInt(1);function hr(e,t=""){if(typeof e!="boolean"){const n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function _t(e,t,n=""){const r=Gs(e),s=e==null?void 0:e.length,o=t!==void 0;if(!r||o&&s!==t){const i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function ho(e){const t=e.toString(16);return t.length&1?"0"+t:t}function gh(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Gc:BigInt("0x"+e)}function $r(e){return gh(Ie(e))}function pr(e){return Ve(e),gh(Ie(Uint8Array.from(e).reverse()))}function ki(e,t){return bt(e.toString(16).padStart(t*2,"0"))}function Yc(e,t){return ki(e,t).reverse()}function be(e,t,n){let r;if(typeof t=="string")try{r=bt(t)}catch(o){throw new Error(e+" must be hex string or Uint8Array, cause: "+o)}else if(Gs(t))r=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const s=r.length;if(typeof n=="number"&&s!==n)throw new Error(e+" of length "+n+" expected, got "+s);return r}function fu(e){return Uint8Array.from(e)}const ea=e=>typeof e=="bigint"&&Gc<=e;function Ma(e,t,n){return ea(e)&&ea(t)&&ea(n)&&t<=e&&eGc;e>>=Ka,t+=1);return t}const Xs=e=>(Ka<new Uint8Array(h),s=h=>Uint8Array.of(h);let o=r(e),i=r(e),a=0;const c=()=>{o.fill(1),i.fill(0),a=0},l=(...h)=>n(i,o,...h),f=(h=r(0))=>{i=l(s(0),h),o=l(),h.length!==0&&(i=l(s(1),h),o=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const g=[];for(;h{c(),f(h);let p;for(;!(p=g(u()));)f();return c(),p}}function ls(e,t,n={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function r(s,o,i){const a=e[s];if(i&&a===void 0)return;const c=typeof a;if(c!==o||a===null)throw new Error(`param "${s}" is invalid: expected ${o}, got ${c}`)}Object.entries(t).forEach(([s,o])=>r(s,o,!1)),Object.entries(n).forEach(([s,o])=>r(s,o,!0))}function Xo(e){const t=new WeakMap;return(n,...r)=>{const s=t.get(n);if(s!==void 0)return s;const o=e(n,...r);return t.set(n,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const lt=BigInt(0),Ye=BigInt(1),tr=BigInt(2),yh=BigInt(3),wh=BigInt(4),bh=BigInt(5),D2=BigInt(7),xh=BigInt(8),Z2=BigInt(9),vh=BigInt(16);function Te(e,t){const n=e%t;return n>=lt?n:t+n}function Pe(e,t,n){let r=e;for(;t-- >lt;)r*=r,r%=n;return r}function du(e,t){if(e===lt)throw new Error("invert: expected non-zero number");if(t<=lt)throw new Error("invert: expected positive modulus, got "+t);let n=Te(e,t),r=t,s=lt,o=Ye;for(;n!==lt;){const a=r/n,c=r%n,l=s-o*a;r=n,n=c,s=o,o=l}if(r!==Ye)throw new Error("invert: does not exist");return Te(s,t)}function Xc(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function kh(e,t){const n=(e.ORDER+Ye)/wh,r=e.pow(t,n);return Xc(e,r,t),r}function V2(e,t){const n=(e.ORDER-bh)/xh,r=e.mul(t,tr),s=e.pow(r,n),o=e.mul(t,s),i=e.mul(e.mul(o,tr),s),a=e.mul(o,e.sub(i,e.ONE));return Xc(e,a,t),a}function q2(e){const t=Er(e),n=$h(e),r=n(t,t.neg(t.ONE)),s=n(t,r),o=n(t,t.neg(r)),i=(e+D2)/vh;return(a,c)=>{let l=a.pow(c,i),f=a.mul(l,r);const u=a.mul(l,s),d=a.mul(l,o),h=a.eql(a.sqr(f),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,f,h),f=a.cmov(d,u,g);const p=a.eql(a.sqr(f),c),m=a.cmov(l,f,p);return Xc(a,m,c),m}}function $h(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return kh;let o=s.pow(r,t);const i=(t+Ye)/tr;return function(c,l){if(c.is0(l))return l;if(hu(c,l)!==1)throw new Error("Cannot find square root");let f=n,u=c.mul(c.ONE,o),d=c.pow(l,t),h=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let g=1,p=c.sqr(d);for(;!c.eql(p,c.ONE);)if(g++,p=c.sqr(p),g===f)throw new Error("Cannot find square root");const m=Ye<(Te(e,t)&Ye)===Ye,W2=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function G2(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=W2.reduce((r,s)=>(r[s]="function",r),t);return ls(e,n),e}function Y2(e,t,n){if(nlt;)n&Ye&&(r=e.mul(r,s)),s=e.sqr(s),n>>=Ye;return r}function Eh(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),s=t.reduce((i,a,c)=>e.is0(a)?i:(r[c]=i,e.mul(i,a)),e.ONE),o=e.inv(s);return t.reduceRight((i,a,c)=>e.is0(a)?i:(r[c]=e.mul(i,r[c]),e.mul(i,a)),o),r}function hu(e,t){const n=(e.ORDER-Ye)/tr,r=e.pow(t,n),s=e.eql(r,e.ONE),o=e.eql(r,e.ZERO),i=e.eql(r,e.neg(e.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function Sh(e,t){t!==void 0&&Rt(t);const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Er(e,t,n=!1,r={}){if(e<=lt)throw new Error("invalid field: expected ORDER > 0, got "+e);let s,o,i=!1,a;if(typeof t=="object"&&t!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const d=t;d.BITS&&(s=d.BITS),d.sqrt&&(o=d.sqrt),typeof d.isLE=="boolean"&&(n=d.isLE),typeof d.modFromBytes=="boolean"&&(i=d.modFromBytes),a=d.allowedLengths}else typeof t=="number"&&(s=t),r.sqrt&&(o=r.sqrt);const{nBitLength:c,nByteLength:l}=Sh(e,s);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let f;const u=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:Xs(c),ZERO:lt,ONE:Ye,allowedLengths:a,create:d=>Te(d,e),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return lt<=d&&dd===lt,isValidNot0:d=>!u.is0(d)&&u.isValid(d),isOdd:d=>(d&Ye)===Ye,neg:d=>Te(-d,e),eql:(d,h)=>d===h,sqr:d=>Te(d*d,e),add:(d,h)=>Te(d+h,e),sub:(d,h)=>Te(d-h,e),mul:(d,h)=>Te(d*h,e),pow:(d,h)=>Y2(u,d,h),div:(d,h)=>Te(d*du(h,e),e),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>du(d,e),sqrt:o||(d=>(f||(f=z2(e)),f(u,d))),toBytes:d=>n?Yc(d,l):ki(d,l),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);const p=new Uint8Array(l);p.set(d,n?0:p.length-d.length),d=p}if(d.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+d.length);let g=n?pr(d):$r(d);if(i&&(g=Te(g,e)),!h&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:d=>Eh(u,d),cmov:(d,h,g)=>g?h:d});return Object.freeze(u)}function _h(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Ah(e){const t=_h(e);return t+Math.ceil(t/2)}function Bh(e,t,n=!1){const r=e.length,s=_h(t),o=Ah(t);if(r<16||r1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);const i=n?pr(e):$r(e),a=Te(i,t-Ye)+Ye;return n?Yc(a,s):ki(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Jr=BigInt(0),nr=BigInt(1);function Jo(e,t){const n=t.negate();return e?n:t}function rr(e,t){const n=Eh(e.Fp,t.map(r=>r.Z));return t.map((r,s)=>e.fromAffine(r.toAffine(n[s])))}function Th(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function ta(e,t){Th(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1),s=2**e,o=Xs(e),i=BigInt(e);return{windows:n,windowSize:r,mask:o,maxNumber:s,shiftBy:i}}function pu(e,t,n){const{windowSize:r,mask:s,maxNumber:o,shiftBy:i}=n;let a=Number(e&s),c=e>>i;a>r&&(a-=o,c+=nr);const l=t*r,f=l+Math.abs(a)-1,u=a===0,d=a<0,h=t%2!==0;return{nextN:c,offset:f,isZero:u,isNeg:d,isNegF:h,offsetF:l}}function X2(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function J2(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,r)=>{if(!t.isValid(n))throw new Error("invalid scalar at index "+r)})}const na=new WeakMap,Oh=new WeakMap;function ra(e){return Oh.get(e)||1}function gu(e){if(e!==Jr)throw new Error("invalid wNAF")}class Ih{constructor(t,n){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=n}_unsafeLadder(t,n,r=this.ZERO){let s=t;for(;n>Jr;)n&nr&&(r=r.add(s)),s=s.double(),n>>=nr;return r}precomputeWindow(t,n){const{windows:r,windowSize:s}=ta(n,this.bits),o=[];let i=t,a=i;for(let c=0;cJr||r>Jr;)n&nr&&(o=o.add(s)),r&nr&&(i=i.add(s)),s=s.double(),n>>=nr,r>>=nr;return{p1:o,p2:i}}function Ch(e,t,n,r){X2(n,e),J2(r,t);const s=n.length,o=r.length;if(s!==o)throw new Error("arrays of points and scalars must have equal length");const i=e.ZERO,a=mh(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Xs(c),f=new Array(Number(l)+1).fill(i),u=Math.floor((t.BITS-1)/c)*c;let d=i;for(let h=u;h>=0;h-=c){f.fill(i);for(let p=0;p>BigInt(h)&l);f[w]=f[w].add(n[p])}let g=i;for(let p=f.length-1,m=i;p>0;p--)m=m.add(f[p]),g=g.add(m);if(d=d.add(g),h!==0)for(let p=0;pJr))throw new Error(`CURVE.${c} must be positive bigint`)}const s=mu(t.p,n.Fp,r),o=mu(t.n,n.Fn,r),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(const c of a)if(!s.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:s,Fn:o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const yu=(e,t)=>(e+(e>=0?t:-t)/Uh)/t;function ev(e,t,n){const[[r,s],[o,i]]=t,a=yu(i*e,n),c=yu(-s*e,n);let l=e-a*r-c*o,f=-a*s-c*i;const u=l=h||f=h)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:u,k1:l,k2neg:d,k2:f}}function Da(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function sa(e,t){const n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return hr(n.lowS,"lowS"),hr(n.prehash,"prehash"),n.format!==void 0&&Da(n.format),n}class tv extends Error{constructor(t=""){super(t)}}const Qt={Err:tv,_tlv:{encode:(e,t)=>{const{Err:n}=Qt;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length&1)throw new n("tlv.encode: unpadded data");const r=t.length/2,s=ho(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const o=r>127?ho(s.length/2|128):"";return ho(e)+o+s+t},decode(e,t){const{Err:n}=Qt;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const s=t[r++],o=!!(s&128);let i=0;if(!o)i=s;else{const c=s&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");const l=t.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const f of l)i=i<<8|f;if(r+=c,i<128)throw new n("tlv.decode(long): not minimal encoding")}const 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){const{Err:t}=Qt;if(e{const{X:E,Y:v,Z:A}=B;if(r.eql(A,r.ONE))return{x:E,y:v};const U=B.is0();k==null&&(k=U?r.ONE:r.inv(A));const K=r.mul(E,k),H=r.mul(v,k),M=r.mul(A,k);if(U)return{x:r.ZERO,y:r.ZERO};if(!r.eql(M,r.ONE))throw new Error("invZ was invalid");return{x:K,y:H}}),C=Xo(B=>{if(B.is0()){if(t.allowInfinityPoint&&!r.is0(B.Y))return;throw new Error("bad point: ZERO")}const{x:k,y:E}=B.toAffine();if(!r.isValid(k)||!r.isValid(E))throw new Error("bad point: x or y not field elements");if(!m(k,E))throw new Error("bad point: equation left != right");if(!B.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function P(B,k,E,v,A){return E=new O(r.mul(E.X,B),E.Y,E.Z),k=Jo(v,k),E=Jo(A,E),k.add(E)}class O{constructor(k,E,v){this.X=b("x",k),this.Y=b("y",E,!0),this.Z=b("z",v),Object.freeze(this)}static CURVE(){return o}static fromAffine(k){const{x:E,y:v}=k||{};if(!k||!r.isValid(E)||!r.isValid(v))throw new Error("invalid affine point");if(k instanceof O)throw new Error("projective point not allowed");return r.is0(E)&&r.is0(v)?O.ZERO:new O(E,v,r.ONE)}static fromBytes(k){const E=O.fromAffine(g(_t(k,void 0,"point")));return E.assertValidity(),E}static fromHex(k){return O.fromBytes(be("pointHex",k))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(k=8,E=!0){return R.createCache(this,k),E||this.multiply(po),this}assertValidity(){C(this)}hasEvenY(){const{y:k}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(k)}equals(k){_(k);const{X:E,Y:v,Z:A}=this,{X:U,Y:K,Z:H}=k,M=r.eql(r.mul(E,H),r.mul(U,A)),V=r.eql(r.mul(v,H),r.mul(K,A));return M&&V}negate(){return new O(this.X,r.neg(this.Y),this.Z)}double(){const{a:k,b:E}=o,v=r.mul(E,po),{X:A,Y:U,Z:K}=this;let H=r.ZERO,M=r.ZERO,V=r.ZERO,G=r.mul(A,A),fe=r.mul(U,U),ce=r.mul(K,K),ne=r.mul(A,U);return ne=r.add(ne,ne),V=r.mul(A,K),V=r.add(V,V),H=r.mul(k,V),M=r.mul(v,ce),M=r.add(H,M),H=r.sub(fe,M),M=r.add(fe,M),M=r.mul(H,M),H=r.mul(ne,H),V=r.mul(v,V),ce=r.mul(k,ce),ne=r.sub(G,ce),ne=r.mul(k,ne),ne=r.add(ne,V),V=r.add(G,G),G=r.add(V,G),G=r.add(G,ce),G=r.mul(G,ne),M=r.add(M,G),ce=r.mul(U,K),ce=r.add(ce,ce),G=r.mul(ce,ne),H=r.sub(H,G),V=r.mul(ce,fe),V=r.add(V,V),V=r.add(V,V),new O(H,M,V)}add(k){_(k);const{X:E,Y:v,Z:A}=this,{X:U,Y:K,Z:H}=k;let M=r.ZERO,V=r.ZERO,G=r.ZERO;const fe=o.a,ce=r.mul(o.b,po);let ne=r.mul(E,U),ge=r.mul(v,K),me=r.mul(A,H),Le=r.add(E,v),pe=r.add(U,K);Le=r.mul(Le,pe),pe=r.add(ne,ge),Le=r.sub(Le,pe),pe=r.add(E,A);let _e=r.add(U,H);return pe=r.mul(pe,_e),_e=r.add(ne,me),pe=r.sub(pe,_e),_e=r.add(v,A),M=r.add(K,H),_e=r.mul(_e,M),M=r.add(ge,me),_e=r.sub(_e,M),G=r.mul(fe,pe),M=r.mul(ce,me),G=r.add(M,G),M=r.sub(ge,G),G=r.add(ge,G),V=r.mul(M,G),ge=r.add(ne,ne),ge=r.add(ge,ne),me=r.mul(fe,me),pe=r.mul(ce,pe),ge=r.add(ge,me),me=r.sub(ne,me),me=r.mul(fe,me),pe=r.add(pe,me),ne=r.mul(ge,pe),V=r.add(V,ne),ne=r.mul(_e,pe),M=r.mul(Le,M),M=r.sub(M,ne),ne=r.mul(Le,ge),G=r.mul(_e,G),G=r.add(G,ne),new O(M,V,G)}subtract(k){return this.add(k.negate())}is0(){return this.equals(O.ZERO)}multiply(k){const{endo:E}=t;if(!s.isValidNot0(k))throw new Error("invalid scalar: out of range");let v,A;const U=K=>R.cached(this,K,H=>rr(O,H));if(E){const{k1neg:K,k1:H,k2neg:M,k2:V}=$(k),{p:G,f:fe}=U(H),{p:ce,f:ne}=U(V);A=fe.add(ne),v=P(E.beta,G,ce,K,M)}else{const{p:K,f:H}=U(k);v=K,A=H}return rr(O,[v,A])[0]}multiplyUnsafe(k){const{endo:E}=t,v=this;if(!s.isValid(k))throw new Error("invalid scalar: out of range");if(k===en||v.is0())return O.ZERO;if(k===jr)return v;if(R.hasCache(this))return this.multiply(k);if(E){const{k1neg:A,k1:U,k2neg:K,k2:H}=$(k),{p1:M,p2:V}=Q2(O,v,U,H);return P(E.beta,M,V,A,K)}else return R.unsafe(v,k)}multiplyAndAddUnsafe(k,E,v){const A=this.multiplyUnsafe(E).add(k.multiplyUnsafe(v));return A.is0()?void 0:A}toAffine(k){return x(this,k)}isTorsionFree(){const{isTorsionFree:k}=t;return i===jr?!0:k?k(O,this):R.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:k}=t;return i===jr?this:k?k(O,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(k=!0){return hr(k,"isCompressed"),this.assertValidity(),h(O,this,k)}toHex(k=!0){return Ie(this.toBytes(k))}toString(){return``}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(k=!0){return this.toBytes(k)}_setWindowSize(k){this.precompute(k)}static normalizeZ(k){return rr(O,k)}static msm(k,E){return Ch(O,s,k,E)}static fromPrivateKey(k){return O.BASE.multiply(sr(s,k))}}O.BASE=new O(o.Gx,o.Gy,r.ONE),O.ZERO=new O(r.ZERO,r.ONE,r.ZERO),O.Fp=r,O.Fn=s;const N=s.BITS,R=new Ih(O,t.endo?Math.ceil(N/2):N);return O.BASE.precompute(8),O}function Nh(e){return Uint8Array.of(e?2:3)}function Lh(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function sv(e,t={}){const{Fn:n}=e,r=t.randomBytes||kr,s=Object.assign(Lh(e.Fp,n),{seed:Ah(n.ORDER)});function o(h){try{return!!sr(n,h)}catch{return!1}}function i(h,g){const{publicKey:p,publicKeyUncompressed:m}=s;try{const w=h.length;return g===!0&&w!==p||g===!1&&w!==m?!1:!!e.fromBytes(h)}catch{return!1}}function a(h=r(s.seed)){return Bh(_t(h,s.seed,"seed"),n.ORDER)}function c(h,g=!0){return e.BASE.multiply(sr(n,h)).toBytes(g)}function l(h){const g=a(h);return{secretKey:g,publicKey:c(g)}}function f(h){if(typeof h=="bigint")return!1;if(h instanceof e)return!0;const{secretKey:g,publicKey:p,publicKeyUncompressed:m}=s;if(n.allowedLengths||g===p)return;const w=be("key",h).length;return w===p||w===m}function u(h,g,p=!0){if(f(h)===!0)throw new Error("first arg must be private key");if(f(g)===!1)throw new Error("second arg must be public key");const m=sr(n,h);return e.fromHex(g).multiply(m).toBytes(p)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:e,utils:{isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:h=>sr(n,h),precompute(h=8,g=e.BASE){return g.precompute(h,!1)}},lengths:s})}function ov(e,t,n={}){Ys(t),ls(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||kr,s=n.hmac||((E,...v)=>Rn(t,E,le(...v))),{Fp:o,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:h}=sv(e,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},p="compact";function m(E){const v=a>>jr;return E>v}function w(E,v){if(!i.isValidNot0(v))throw new Error(`invalid signature ${E}: out of range 1..Point.Fn.ORDER`);return v}function y(E,v){Da(v);const A=h.signature,U=v==="compact"?A:v==="recovered"?A+1:void 0;return _t(E,U,`${v} signature`)}class b{constructor(v,A,U){this.r=w("r",v),this.s=w("s",A),U!=null&&(this.recovery=U),Object.freeze(this)}static fromBytes(v,A=p){y(v,A);let U;if(A==="der"){const{r:V,s:G}=Qt.toSig(_t(v));return new b(V,G)}A==="recovered"&&(U=v[0],A="compact",v=v.subarray(1));const K=i.BYTES,H=v.subarray(0,K),M=v.subarray(K,K*2);return new b(i.fromBytes(H),i.fromBytes(M),U)}static fromHex(v,A){return this.fromBytes(bt(v),A)}addRecoveryBit(v){return new b(this.r,this.s,v)}recoverPublicKey(v){const A=o.ORDER,{r:U,s:K,recovery:H}=this;if(H==null||![0,1,2,3].includes(H))throw new Error("recovery id invalid");if(a*Uh1)throw new Error("recovery id is ambiguous for h>1 curve");const V=H===2||H===3?U+a:U;if(!o.isValid(V))throw new Error("recovery id 2 or 3 invalid");const G=o.toBytes(V),fe=e.fromBytes(le(Nh((H&1)===0),G)),ce=i.inv(V),ne=$(be("msgHash",v)),ge=i.create(-ne*ce),me=i.create(K*ce),Le=e.BASE.multiplyUnsafe(ge).add(fe.multiplyUnsafe(me));if(Le.is0())throw new Error("point at infinify");return Le.assertValidity(),Le}hasHighS(){return m(this.s)}toBytes(v=p){if(Da(v),v==="der")return bt(Qt.hexFromSig(this));const A=i.toBytes(this.r),U=i.toBytes(this.s);if(v==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return le(Uint8Array.of(this.recovery),A,U)}return le(A,U)}toHex(v){return Ie(this.toBytes(v))}assertValidity(){}static fromCompact(v){return b.fromBytes(be("sig",v),"compact")}static fromDER(v){return b.fromBytes(be("sig",v),"der")}normalizeS(){return this.hasHighS()?new b(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ie(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ie(this.toBytes("compact"))}}const _=n.bits2int||function(v){if(v.length>8192)throw new Error("input is too large");const A=$r(v),U=v.length*8-c;return U>0?A>>BigInt(U):A},$=n.bits2int_modN||function(v){return i.create(_(v))},x=Xs(c);function C(E){return Ks("num < 2^"+c,E,en,x),i.toBytes(E)}function P(E,v){return _t(E,void 0,"message"),v?_t(t(E),void 0,"prehashed message"):E}function O(E,v,A){if(["recovered","canonical"].some(ge=>ge in A))throw new Error("sign() legacy options not supported");const{lowS:U,prehash:K,extraEntropy:H}=sa(A,g);E=P(E,K);const M=$(E),V=sr(i,v),G=[C(V),C(M)];if(H!=null&&H!==!1){const ge=H===!0?r(h.secretKey):H;G.push(be("extraEntropy",ge))}const fe=le(...G),ce=M;function ne(ge){const me=_(ge);if(!i.isValidNot0(me))return;const Le=i.inv(me),pe=e.BASE.multiply(me).toAffine(),_e=i.create(pe.x);if(_e===en)return;const Wt=i.create(Le*i.create(ce+_e*V));if(Wt===en)return;let pt=(pe.x===_e?0:2)|Number(pe.y&jr),We=Wt;return U&&m(Wt)&&(We=i.neg(Wt),pt^=1),new b(_e,We,pt)}return{seed:fe,k2sig:ne}}function N(E,v,A={}){E=be("message",E);const{seed:U,k2sig:K}=O(E,v,A);return M2(t.outputLen,i.BYTES,s)(U,K)}function R(E){let v;const A=typeof E=="string"||Gs(E),U=!A&&E!==null&&typeof E=="object"&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!A&&!U)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(U)v=new b(E.r,E.s);else if(A){try{v=b.fromBytes(be("sig",E),"der")}catch(K){if(!(K instanceof Qt.Err))throw K}if(!v)try{v=b.fromBytes(be("sig",E),"compact")}catch{return!1}}return v||!1}function B(E,v,A,U={}){const{lowS:K,prehash:H,format:M}=sa(U,g);if(A=be("publicKey",A),v=P(be("message",v),H),"strict"in U)throw new Error("options.strict was renamed to lowS");const V=M===void 0?R(E):b.fromBytes(be("sig",E),M);if(V===!1)return!1;try{const G=e.fromBytes(A);if(K&&V.hasHighS())return!1;const{r:fe,s:ce}=V,ne=$(v),ge=i.inv(ce),me=i.create(ne*ge),Le=i.create(fe*ge),pe=e.BASE.multiplyUnsafe(me).add(G.multiplyUnsafe(Le));return pe.is0()?!1:i.create(pe.x)===fe}catch{return!1}}function k(E,v,A={}){const{prehash:U}=sa(A,g);return v=P(v,U),b.fromBytes(E,"recovered").recoverPublicKey(v).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:h,Point:e,sign:N,verify:B,recoverPublicKey:k,Signature:b,hash:t})}function iv(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0;const s=Er(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),o={Fp:n,Fn:s,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:o}}function av(e){const{CURVE:t,curveOpts:n}=iv(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function cv(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Sh(n.Fn.ORDER,n.Fn.BITS))})}function lv(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:s}=av(e),o=rv(t,n),i=ov(o,r,s);return cv(e,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function uv(e,t){const n=r=>lv({...e,hash:r});return{...n(t),create:n}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Qr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},fv={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},dv=BigInt(0),wu=BigInt(1),Za=BigInt(2);function hv(e){const t=Qr.p,n=BigInt(3),r=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,f=l*l*e%t,u=Pe(f,n,t)*f%t,d=Pe(u,n,t)*f%t,h=Pe(d,Za,t)*l%t,g=Pe(h,s,t)*h%t,p=Pe(g,o,t)*g%t,m=Pe(p,a,t)*p%t,w=Pe(m,c,t)*m%t,y=Pe(w,a,t)*p%t,b=Pe(y,n,t)*f%t,_=Pe(b,i,t)*g%t,$=Pe(_,r,t)*l%t,x=Pe($,Za,t);if(!Qo.eql(Qo.sqr(x),e))throw new Error("Cannot find square root");return x}const Qo=Er(Qr.p,{sqrt:hv}),Oe=uv({...Qr,Fp:Qo,lowS:!0,endo:fv},Ae),bu={};function ei(e,...t){let n=bu[e];if(n===void 0){const r=Ae(Ke(e));n=le(r,r),bu[e]=n}return Ae(le(n,...t))}const Jc=e=>e.toBytes(!0).slice(1),us=Oe.Point,Qc=e=>e%Za===dv;function Va(e){const{Fn:t,BASE:n}=us,r=sr(t,e),s=n.multiply(r);return{scalar:Qc(s.y)?r:t.neg(r),bytes:Jc(s)}}function Hh(e){const t=Qo;if(!t.isValidNot0(e))throw new Error("invalid x: Fail if x ≥ p");const n=t.create(e*e),r=t.create(n*e+BigInt(7));let s=t.sqrt(r);Qc(s)||(s=t.neg(s));const o=us.fromAffine({x:e,y:s});return o.assertValidity(),o}const $s=$r;function Rh(...e){return us.Fn.create($s(ei("BIP0340/challenge",...e)))}function xu(e){return Va(e).bytes}function pv(e,t,n=kr(32)){const{Fn:r}=us,s=be("message",e),{bytes:o,scalar:i}=Va(t),a=be("auxRand",n,32),c=r.toBytes(i^$s(ei("BIP0340/aux",a))),l=ei("BIP0340/nonce",c,o,s),{bytes:f,scalar:u}=Va(l),d=Rh(f,o,s),h=new Uint8Array(64);if(h.set(f,0),h.set(r.toBytes(r.create(u+d*i)),32),!jh(h,s,o))throw new Error("sign: Invalid signature produced");return h}function jh(e,t,n){const{Fn:r,BASE:s}=us,o=be("signature",e,64),i=be("message",t),a=be("publicKey",n,32);try{const c=Hh($s(a)),l=$s(o.subarray(0,32));if(!Ma(l,wu,Qr.p))return!1;const f=$s(o.subarray(32,64));if(!Ma(f,wu,Qr.n))return!1;const u=Rh(r.toBytes(l),Jc(c),i),d=s.multiplyUnsafe(f).add(c.multiplyUnsafe(r.neg(u))),{x:h,y:g}=d.toAffine();return!(d.is0()||!Qc(g)||h!==l)}catch{return!1}}const jn=(()=>{const n=(s=kr(48))=>Bh(s,Qr.n);Oe.utils.randomSecretKey;function r(s){const o=n(s);return{secretKey:o,publicKey:xu(o)}}return{keygen:r,getPublicKey:xu,sign:pv,verify:jh,Point:us,utils:{randomSecretKey:n,randomPrivateKey:n,taggedHash:ei,lift_x:Hh,pointToBytes:Jc,numberToBytesBE:ki,bytesToNumberBE:$r,mod:Te},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})(),gv=BigInt(0),gs=BigInt(1),mv=BigInt(2),yv=BigInt(7),wv=BigInt(256),bv=BigInt(113),Kh=[],Mh=[],Dh=[];for(let e=0,t=gs,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Kh.push(2*(5*r+n)),Mh.push((e+1)*(e+2)/2%64);let s=gv;for(let o=0;o<7;o++)t=(t<>yv)*bv)%wv,t&mv&&(s^=gs<<(gs<n>32?B2(e,t,n):_2(e,t,n),ku=(e,t,n)=>n>32?T2(e,t,n):A2(e,t,n);function kv(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let i=0;i<10;i++)n[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=n[c],f=n[c+1],u=vu(l,f,1)^n[a],d=ku(l,f,1)^n[a+1];for(let h=0;h<50;h+=10)e[i+h]^=u,e[i+h+1]^=d}let s=e[2],o=e[3];for(let i=0;i<24;i++){const a=Mh[i],c=vu(s,o,a),l=ku(s,o,a),f=Kh[i];s=e[f],o=e[f+1],e[f]=c,e[f+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)n[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~n[(a+2)%10]&n[(a+4)%10]}e[0]^=xv[r],e[1]^=vv[r]}wt(n)}class el extends Fc{constructor(t,n,r,s=!1,o=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,Rt(r),!(0=r&&this.keccak();const i=Math.min(r-this.posOut,o-s);t.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Rt(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(uh(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,wt(this.state)}_cloneInto(t){const{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return t||(t=new el(n,r,s,i,o)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=o,t.suffix=r,t.outputLen=s,t.enableXOF=i,t.destroyed=this.destroyed,t}}const $v=(e,t,n)=>vi(()=>new el(t,e,n)),tl=$v(1,136,256/8),Ev=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Vh=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),Sv=Vh.map(e=>(9*e+5)%16),qh=(()=>{const n=[[Vh],[Sv]];for(let r=0;r<4;r++)for(let s of n)s.push(s[r].map(o=>Ev[o]));return n})(),zh=qh[0],Fh=qh[1],Wh=[[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)),_v=zh.map((e,t)=>e.map(n=>Wh[t][n])),Av=Fh.map((e,t)=>e.map(n=>Wh[t][n])),Bv=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Tv=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function $u(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)}const go=new Uint32Array(16);class Ov extends Wc{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:n,h2:r,h3:s,h4:o}=this;return[t,n,r,s,o]}set(t,n,r,s,o){this.h0=t|0,this.h1=n|0,this.h2=r|0,this.h3=s|0,this.h4=o|0}process(t,n){for(let h=0;h<16;h++,n+=4)go[h]=t.getUint32(n,!0);let r=this.h0|0,s=r,o=this.h1|0,i=o,a=this.h2|0,c=a,l=this.h3|0,f=l,u=this.h4|0,d=u;for(let h=0;h<5;h++){const g=4-h,p=Bv[h],m=Tv[h],w=zh[h],y=Fh[h],b=_v[h],_=Av[h];for(let $=0;$<16;$++){const x=co(r+$u(h,o,a,l)+go[w[$]]+p,b[$])+u|0;r=u,u=l,l=co(a,10)|0,a=o,o=x}for(let $=0;$<16;$++){const x=co(s+$u(g,i,c,f)+go[y[$]]+m,_[$])+d|0;s=d,d=f,f=co(c,10)|0,c=i,i=x}}this.set(this.h1+a+f|0,this.h2+l+d|0,this.h3+u+s|0,this.h4+r+i|0,this.h0+o+c|0)}roundClean(){wt(go)}destroy(){this.destroyed=!0,wt(this.buffer),this.set(0,0,0,0,0)}}const nl=vi(()=>new Ov);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function es(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Iv(e,...t){if(!es(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Gh(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 Yh(e){if(typeof e!="function")throw new Error("function expected");return!0}function gr(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function fs(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function ti(e){if(!Array.isArray(e))throw new Error("array expected")}function ni(e,t){if(!Gh(!0,t))throw new Error(`${e}: array of strings expected`)}function rl(e,t){if(!Gh(!1,t))throw new Error(`${e}: array of numbers expected`)}function Js(...e){const t=o=>o,n=(o,i)=>a=>o(i(a)),r=e.map(o=>o.encode).reduceRight(n,t),s=e.map(o=>o.decode).reduce(n,t);return{encode:r,decode:s}}function $i(e){const t=typeof e=="string"?e.split(""):e,n=t.length;ni("alphabet",t);const r=new Map(t.map((s,o)=>[s,o]));return{encode:s=>(ti(s),s.map(o=>{if(!Number.isSafeInteger(o)||o<0||o>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${e}`);return t[o]})),decode:s=>(ti(s),s.map(o=>{gr("alphabet.decode",o);const i=r.get(o);if(i===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${e}`);return i}))}}function Ei(e=""){return gr("join",e),{encode:t=>(ni("join.decode",t),t.join(e)),decode:t=>(gr("join.decode",t),t.split(e))}}function Xh(e,t="="){return fs(e),gr("padding",t),{encode(n){for(ni("padding.encode",n);n.length*e%8;)n.push(t);return n},decode(n){ni("padding.decode",n);let r=n.length;if(r*e%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===t;r--)if((r-1)*e%8===0)throw new Error("padding: invalid, string has too much padding");return n.slice(0,r)}}}function qa(e,t,n){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: invalid to=${n}, base cannot be less than 2`);if(ti(e),!e.length)return[];let r=0;const s=[],o=Array.from(e,a=>{if(fs(a),a<0||a>=t)throw new Error(`invalid integer: ${a}`);return a}),i=o.length;for(;;){let a=0,c=!0;for(let l=r;lt===0?e:Jh(t,e%t),ri=(e,t)=>e+(t-Jh(e,t)),_o=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function si(e,t,n,r){if(ti(e),t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(ri(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${ri(t,n)}`);let s=0,o=0;const i=_o[t],a=_o[n]-1,c=[];for(const l of e){if(fs(l),l>=i)throw new Error(`convertRadix2: invalid data word=${l} from=${t}`);if(s=s<32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${t}`);for(o+=t;o>=n;o-=n)c.push((s>>o-n&a)>>>0);const f=_o[o];if(f===void 0)throw new Error("invalid carry");s&=f-1}if(s=s<=t)throw new Error("Excess padding");if(!r&&s>0)throw new Error(`Non-zero padding: ${s}`);return r&&o>0&&c.push(s>>>0),c}function Qh(e){fs(e);const t=2**8;return{encode:n=>{if(!es(n))throw new Error("radix.encode input should be Uint8Array");return qa(Array.from(n),t,e)},decode:n=>(rl("radix.decode",n),Uint8Array.from(qa(n,e,t)))}}function sl(e,t=!1){if(fs(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(ri(8,e)>32||ri(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!es(n))throw new Error("radix2.encode input should be Uint8Array");return si(Array.from(n),8,e,!t)},decode:n=>(rl("radix2.decode",n),Uint8Array.from(si(n,e,8,t)))}}function Eu(e){return Yh(e),function(...t){try{return e.apply(null,t)}catch{}}}function ep(e,t){return fs(e),Yh(t),{encode(n){if(!es(n))throw new Error("checksum.encode: input should be Uint8Array");const r=t(n).slice(0,e),s=new Uint8Array(n.length+e);return s.set(n),s.set(r,n.length),s},decode(n){if(!es(n))throw new Error("checksum.decode: input should be Uint8Array");const r=n.slice(0,-e),s=n.slice(-e),o=t(r).slice(0,e);for(let i=0;i{gr("base64",e);const n=/^[A-Za-z0-9=+/]+$/,r="base64";if(e.length>0&&!n.test(e))throw new Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},yt=Cv?{encode(e){return Iv(e),e.toBase64()},decode(e){return Pv(e)}}:Js(sl(6),$i("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Xh(6),Ei("")),Uv=e=>Js(Qh(58),$i(e),Ei("")),Nv=Uv("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),tp=e=>Js(ep(4,t=>e(e(t))),Nv),za=Js($i("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Ei("")),Su=[996825010,642813549,513874426,1027748829,705979059];function ms(e){const t=e>>25;let n=(e&33554431)<<5;for(let r=0;r>r&1)===1&&(n^=Su[r]);return n}function _u(e,t,n=1){const r=e.length;let s=1;for(let o=0;o126)throw new Error(`Invalid prefix (${e})`);s=ms(s)^i>>5}s=ms(s);for(let o=0;oh)throw new TypeError(`Length ${p} exceeds limit ${h}`);const m=u.toLowerCase(),w=_u(m,d,t);return`${m}1${za.encode(d)}${w}`}function a(u,d=90){gr("bech32.decode input",u);const h=u.length;if(h<8||d!==!1&&h>d)throw new TypeError(`invalid string length: ${h} (${u}). Expected (8..${d})`);const g=u.toLowerCase();if(u!==g&&u!==u.toUpperCase())throw new Error("String must be lowercase or uppercase");const p=g.lastIndexOf("1");if(p===0||p===-1)throw new Error('Letter "1" must be present between prefix and data only');const m=g.slice(0,p),w=g.slice(p+1);if(w.length<6)throw new Error("Data must be at least 6 characters long");const y=za.decode(w).slice(0,-6),b=_u(m,y,t);if(!w.endsWith(b))throw new Error(`Invalid checksum in ${u}: expected "${b}"`);return{prefix:m,words:y}}const c=Eu(a);function l(u){const{prefix:d,words:h}=a(u,!1);return{prefix:d,words:h,bytes:r(h)}}function f(u,d){return i(u,s(d))}return{encode:i,decode:a,encodeFromBytes:f,decodeToBytes:l,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:o,toWords:s}}const mr=np("bech32"),Lv=np("bech32m");/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */const yo=Oe.ProjectivePoint,oa=tp(Ae);function Au(e){Ve(e);const t=e.length===0?"0":Ie(e);return BigInt("0x"+t)}function Hv(e){if(typeof e!="bigint")throw new Error("bigint expected");return bt(e.toString(16).padStart(64,"0"))}const Rv=Ke("Bitcoin seed"),ia={private:76066276,public:76067358},aa=2147483648,jv=e=>nl(Ae(e)),Kv=e=>ir(e).getUint32(0,!1),wo=e=>{if(!Number.isSafeInteger(e)||e<0||e>2**32-1)throw new Error("invalid number, should be from 0 to 2**32-1, got "+e);const t=new Uint8Array(4);return ir(t).setUint32(0,e,!1),t};class Xn{get fingerprint(){if(!this.pubHash)throw new Error("No publicKey set!");return Kv(this.pubHash)}get identifier(){return this.pubHash}get pubKeyHash(){return this.pubHash}get privateKey(){return this.privKeyBytes||null}get publicKey(){return this.pubKey||null}get privateExtendedKey(){const t=this.privateKey;if(!t)throw new Error("No private key");return oa.encode(this.serialize(this.versions.private,le(new Uint8Array([0]),t)))}get publicExtendedKey(){if(!this.pubKey)throw new Error("No public key");return oa.encode(this.serialize(this.versions.public,this.pubKey))}static fromMasterSeed(t,n=ia){if(Ve(t),8*t.length<128||8*t.length>512)throw new Error("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got "+t.length);const r=Rn(js,Rv,t);return new Xn({versions:n,chainCode:r.slice(32),privateKey:r.slice(0,32)})}static fromExtendedKey(t,n=ia){const r=oa.decode(t),s=ir(r),o=s.getUint32(0,!1),i={versions:n,depth:r[4],parentFingerprint:s.getUint32(5,!1),index:s.getUint32(9,!1),chainCode:r.slice(13,45)},a=r.slice(45),c=a[0]===0;if(o!==n[c?"private":"public"])throw new Error("Version mismatch");return c?new Xn({...i,privateKey:a.slice(1)}):new Xn({...i,publicKey:a})}static fromJSON(t){return Xn.fromExtendedKey(t.xpriv)}constructor(t){if(this.depth=0,this.index=0,this.chainCode=null,this.parentFingerprint=0,!t||typeof t!="object")throw new Error("HDKey.constructor must not be called directly");if(this.versions=t.versions||ia,this.depth=t.depth||0,this.chainCode=t.chainCode||null,this.index=t.index||0,this.parentFingerprint=t.parentFingerprint||0,!this.depth&&(this.parentFingerprint||this.index))throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");if(t.publicKey&&t.privateKey)throw new Error("HDKey: publicKey and privateKey at same time.");if(t.privateKey){if(!Oe.utils.isValidPrivateKey(t.privateKey))throw new Error("Invalid private key");this.privKey=typeof t.privateKey=="bigint"?t.privateKey:Au(t.privateKey),this.privKeyBytes=Hv(this.privKey),this.pubKey=Oe.getPublicKey(t.privateKey,!0)}else if(t.publicKey)this.pubKey=yo.fromHex(t.publicKey).toRawBytes(!0);else throw new Error("HDKey: no public or private key provided");this.pubHash=jv(this.pubKey)}derive(t){if(!/^[mM]'?/.test(t))throw new Error('Path must start with "m" or "M"');if(/^[mM]'?$/.test(t))return this;const n=t.replace(/^[mM]'?\//,"").split("/");let r=this;for(const s of n){const o=/^(\d+)('?)$/.exec(s),i=o&&o[1];if(!o||o.length!==3||typeof i!="string")throw new Error("invalid child index: "+s);let a=+i;if(!Number.isSafeInteger(a)||a>=aa)throw new Error("Invalid index");o[2]==="'"&&(a+=aa),r=r.deriveChild(a)}return r}deriveChild(t){if(!this.pubKey||!this.chainCode)throw new Error("No publicKey or chainCode set");let n=wo(t);if(t>=aa){const a=this.privateKey;if(!a)throw new Error("Could not derive hardened child key");n=le(new Uint8Array([0]),a,n)}else n=le(this.pubKey,n);const r=Rn(js,this.chainCode,n),s=Au(r.slice(0,32)),o=r.slice(32);if(!Oe.utils.isValidPrivateKey(s))throw new Error("Tweak bigger than curve order");const i={versions:this.versions,chainCode:o,depth:this.depth+1,parentFingerprint:this.fingerprint,index:t};try{if(this.privateKey){const a=Te(this.privKey+s,Oe.CURVE.n);if(!Oe.utils.isValidPrivateKey(a))throw new Error("The tweak was out of range or the resulted private key is invalid");i.privateKey=a}else{const a=yo.fromHex(this.pubKey).add(yo.fromPrivateKey(s));if(a.equals(yo.ZERO))throw new Error("The tweak was equal to negative P, which made the result key invalid");i.publicKey=a.toRawBytes(!0)}return new Xn(i)}catch{return this.deriveChild(t+1)}}sign(t){if(!this.privateKey)throw new Error("No privateKey set!");return Ve(t,32),Oe.sign(t,this.privKey).toCompactRawBytes()}verify(t,n){if(Ve(t,32),Ve(n,64),!this.publicKey)throw new Error("No publicKey set!");let r;try{r=Oe.Signature.fromCompact(n)}catch{return!1}return Oe.verify(r,t,this.publicKey)}wipePrivateData(){return this.privKey=void 0,this.privKeyBytes&&(this.privKeyBytes.fill(0),this.privKeyBytes=void 0),this}toJSON(){return{xpriv:this.privateExtendedKey,xpub:this.publicExtendedKey}}serialize(t,n){if(!this.chainCode)throw new Error("No chainCode set");return Ve(n,33),le(wo(t),new Uint8Array([this.depth]),wo(this.parentFingerprint),wo(this.index),this.chainCode,n)}}function Mv(e,t,n,r){Ys(e);const s=v2({dkLen:32,asyncTick:10},r),{c:o,dkLen:i,asyncTick:a}=s;if(Rt(o),Rt(i),Rt(a),o<1)throw new Error("iterations (c) should be >= 1");const c=au(t),l=au(n),f=new Uint8Array(i),u=Rn.create(e,c),d=u._cloneInto().update(l);return{c:o,dkLen:i,asyncTick:a,DK:f,PRF:u,PRFSalt:d}}function Dv(e,t,n,r,s){return e.destroy(),t.destroy(),r&&r.destroy(),wt(s),n}function Zv(e,t,n,r){const{c:s,dkLen:o,DK:i,PRF:a,PRFSalt:c}=Mv(e,t,n,r);let l;const f=new Uint8Array(4),u=ir(f),d=new Uint8Array(a.outputLen);for(let h=1,g=0;ge[0]==="あいこくしん";function rp(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function sp(e){const t=rp(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}function op(e){Ve(e,16,20,24,28,32)}function qv(e,t=128){if(Rt(t),t%32!==0||t>256)throw new TypeError("Invalid entropy");return ap(kr(t/8),e)}const zv=e=>{const t=8-e.length/4;return new Uint8Array([Ae(e)[0]>>t<{if(typeof t!="string")throw new Error("wordlist: non-string element: "+t)}),mo.chain(mo.checksum(1,zv),mo.radix2(11,!0),mo.alphabet(e))}function Fv(e,t){const{words:n}=sp(e),r=ip(t).decode(n);return op(r),r}function ap(e,t){return op(e),ip(t).encode(e).join(Vv(t)?" ":" ")}function Wv(e,t){try{Fv(e,t)}catch{return!1}return!0}const Gv=e=>rp("mnemonic"+e);function Yv(e,t=""){return Zv(js,sp(e).nfkd,Gv(t),{c:2048,dkLen:64})}const ol=`abandon +ability +able +about +above +absent +absorb +abstract +absurd +abuse +access +accident +account +accuse +achieve +acid +acoustic +acquire +across +act +action +actor +actress +actual +adapt +add +addict +address +adjust +admit +adult +advance +advice +aerobic +affair +afford +afraid +again +age +agent +agree +ahead +aim +air +airport +aisle +alarm +album +alcohol +alert +alien +all +alley +allow +almost +alone +alpha +already +also +alter +always +amateur +amazing +among +amount +amused +analyst +anchor +ancient +anger +angle +angry +animal +ankle +announce +annual +another +answer +antenna +antique +anxiety +any +apart +apology +appear +apple +approve +april +arch +arctic +area +arena +argue +arm +armed +armor +army +around +arrange +arrest +arrive +arrow +art +artefact +artist +artwork +ask +aspect +assault +asset +assist +assume +asthma +athlete +atom +attack +attend +attitude +attract +auction +audit +august +aunt +author +auto +autumn +average +avocado +avoid +awake +aware +away +awesome +awful +awkward +axis +baby +bachelor +bacon +badge +bag +balance +balcony +ball +bamboo +banana +banner +bar +barely +bargain +barrel +base +basic +basket +battle +beach +bean +beauty +because +become +beef +before +begin +behave +behind +believe +below +belt +bench +benefit +best +betray +better +between +beyond +bicycle +bid +bike +bind +biology +bird +birth +bitter +black +blade +blame +blanket +blast +bleak +bless +blind +blood +blossom +blouse +blue +blur +blush +board +boat +body +boil +bomb +bone +bonus +book +boost +border +boring +borrow +boss +bottom +bounce +box +boy +bracket +brain +brand +brass +brave +bread +breeze +brick +bridge +brief +bright +bring +brisk +broccoli +broken +bronze +broom +brother +brown +brush +bubble +buddy +budget +buffalo +build +bulb +bulk +bullet +bundle +bunker +burden +burger +burst +bus +business +busy +butter +buyer +buzz +cabbage +cabin +cable +cactus +cage +cake +call +calm +camera +camp +can +canal +cancel +candy +cannon +canoe +canvas +canyon +capable +capital +captain +car +carbon +card +cargo +carpet +carry +cart +case +cash +casino +castle +casual +cat +catalog +catch +category +cattle +caught +cause +caution +cave +ceiling +celery +cement +census +century +cereal +certain +chair +chalk +champion +change +chaos +chapter +charge +chase +chat +cheap +check +cheese +chef +cherry +chest +chicken +chief +child +chimney +choice +choose +chronic +chuckle +chunk +churn +cigar +cinnamon +circle +citizen +city +civil +claim +clap +clarify +claw +clay +clean +clerk +clever +click +client +cliff +climb +clinic +clip +clock +clog +close +cloth +cloud +clown +club +clump +cluster +clutch +coach +coast +coconut +code +coffee +coil +coin +collect +color +column +combine +come +comfort +comic +common +company +concert +conduct +confirm +congress +connect +consider +control +convince +cook +cool +copper +copy +coral +core +corn +correct +cost +cotton +couch +country +couple +course +cousin +cover +coyote +crack +cradle +craft +cram +crane +crash +crater +crawl +crazy +cream +credit +creek +crew +cricket +crime +crisp +critic +crop +cross +crouch +crowd +crucial +cruel +cruise +crumble +crunch +crush +cry +crystal +cube +culture +cup +cupboard +curious +current +curtain +curve +cushion +custom +cute +cycle +dad +damage +damp +dance +danger +daring +dash +daughter +dawn +day +deal +debate +debris +decade +december +decide +decline +decorate +decrease +deer +defense +define +defy +degree +delay +deliver +demand +demise +denial +dentist +deny +depart +depend +deposit +depth +deputy +derive +describe +desert +design +desk +despair +destroy +detail +detect +develop +device +devote +diagram +dial +diamond +diary +dice +diesel +diet +differ +digital +dignity +dilemma +dinner +dinosaur +direct +dirt +disagree +discover +disease +dish +dismiss +disorder +display +distance +divert +divide +divorce +dizzy +doctor +document +dog +doll +dolphin +domain +donate +donkey +donor +door +dose +double +dove +draft +dragon +drama +drastic +draw +dream +dress +drift +drill +drink +drip +drive +drop +drum +dry +duck +dumb +dune +during +dust +dutch +duty +dwarf +dynamic +eager +eagle +early +earn +earth +easily +east +easy +echo +ecology +economy +edge +edit +educate +effort +egg +eight +either +elbow +elder +electric +elegant +element +elephant +elevator +elite +else +embark +embody +embrace +emerge +emotion +employ +empower +empty +enable +enact +end +endless +endorse +enemy +energy +enforce +engage +engine +enhance +enjoy +enlist +enough +enrich +enroll +ensure +enter +entire +entry +envelope +episode +equal +equip +era +erase +erode +erosion +error +erupt +escape +essay +essence +estate +eternal +ethics +evidence +evil +evoke +evolve +exact +example +excess +exchange +excite +exclude +excuse +execute +exercise +exhaust +exhibit +exile +exist +exit +exotic +expand +expect +expire +explain +expose +express +extend +extra +eye +eyebrow +fabric +face +faculty +fade +faint +faith +fall +false +fame +family +famous +fan +fancy +fantasy +farm +fashion +fat +fatal +father +fatigue +fault +favorite +feature +february +federal +fee +feed +feel +female +fence +festival +fetch +fever +few +fiber +fiction +field +figure +file +film +filter +final +find +fine +finger +finish +fire +firm +first +fiscal +fish +fit +fitness +fix +flag +flame +flash +flat +flavor +flee +flight +flip +float +flock +floor +flower +fluid +flush +fly +foam +focus +fog +foil +fold +follow +food +foot +force +forest +forget +fork +fortune +forum +forward +fossil +foster +found +fox +fragile +frame +frequent +fresh +friend +fringe +frog +front +frost +frown +frozen +fruit +fuel +fun +funny +furnace +fury +future +gadget +gain +galaxy +gallery +game +gap +garage +garbage +garden +garlic +garment +gas +gasp +gate +gather +gauge +gaze +general +genius +genre +gentle +genuine +gesture +ghost +giant +gift +giggle +ginger +giraffe +girl +give +glad +glance +glare +glass +glide +glimpse +globe +gloom +glory +glove +glow +glue +goat +goddess +gold +good +goose +gorilla +gospel +gossip +govern +gown +grab +grace +grain +grant +grape +grass +gravity +great +green +grid +grief +grit +grocery +group +grow +grunt +guard +guess +guide +guilt +guitar +gun +gym +habit +hair +half +hammer +hamster +hand +happy +harbor +hard +harsh +harvest +hat +have +hawk +hazard +head +health +heart +heavy +hedgehog +height +hello +helmet +help +hen +hero +hidden +high +hill +hint +hip +hire +history +hobby +hockey +hold +hole +holiday +hollow +home +honey +hood +hope +horn +horror +horse +hospital +host +hotel +hour +hover +hub +huge +human +humble +humor +hundred +hungry +hunt +hurdle +hurry +hurt +husband +hybrid +ice +icon +idea +identify +idle +ignore +ill +illegal +illness +image +imitate +immense +immune +impact +impose +improve +impulse +inch +include +income +increase +index +indicate +indoor +industry +infant +inflict +inform +inhale +inherit +initial +inject +injury +inmate +inner +innocent +input +inquiry +insane +insect +inside +inspire +install +intact +interest +into +invest +invite +involve +iron +island +isolate +issue +item +ivory +jacket +jaguar +jar +jazz +jealous +jeans +jelly +jewel +job +join +joke +journey +joy +judge +juice +jump +jungle +junior +junk +just +kangaroo +keen +keep +ketchup +key +kick +kid +kidney +kind +kingdom +kiss +kit +kitchen +kite +kitten +kiwi +knee +knife +knock +know +lab +label +labor +ladder +lady +lake +lamp +language +laptop +large +later +latin +laugh +laundry +lava +law +lawn +lawsuit +layer +lazy +leader +leaf +learn +leave +lecture +left +leg +legal +legend +leisure +lemon +lend +length +lens +leopard +lesson +letter +level +liar +liberty +library +license +life +lift +light +like +limb +limit +link +lion +liquid +list +little +live +lizard +load +loan +lobster +local +lock +logic +lonely +long +loop +lottery +loud +lounge +love +loyal +lucky +luggage +lumber +lunar +lunch +luxury +lyrics +machine +mad +magic +magnet +maid +mail +main +major +make +mammal +man +manage +mandate +mango +mansion +manual +maple +marble +march +margin +marine +market +marriage +mask +mass +master +match +material +math +matrix +matter +maximum +maze +meadow +mean +measure +meat +mechanic +medal +media +melody +melt +member +memory +mention +menu +mercy +merge +merit +merry +mesh +message +metal +method +middle +midnight +milk +million +mimic +mind +minimum +minor +minute +miracle +mirror +misery +miss +mistake +mix +mixed +mixture +mobile +model +modify +mom +moment +monitor +monkey +monster +month +moon +moral +more +morning +mosquito +mother +motion +motor +mountain +mouse +move +movie +much +muffin +mule +multiply +muscle +museum +mushroom +music +must +mutual +myself +mystery +myth +naive +name +napkin +narrow +nasty +nation +nature +near +neck +need +negative +neglect +neither +nephew +nerve +nest +net +network +neutral +never +news +next +nice +night +noble +noise +nominee +noodle +normal +north +nose +notable +note +nothing +notice +novel +now +nuclear +number +nurse +nut +oak +obey +object +oblige +obscure +observe +obtain +obvious +occur +ocean +october +odor +off +offer +office +often +oil +okay +old +olive +olympic +omit +once +one +onion +online +only +open +opera +opinion +oppose +option +orange +orbit +orchard +order +ordinary +organ +orient +original +orphan +ostrich +other +outdoor +outer +output +outside +oval +oven +over +own +owner +oxygen +oyster +ozone +pact +paddle +page +pair +palace +palm +panda +panel +panic +panther +paper +parade +parent +park +parrot +party +pass +patch +path +patient +patrol +pattern +pause +pave +payment +peace +peanut +pear +peasant +pelican +pen +penalty +pencil +people +pepper +perfect +permit +person +pet +phone +photo +phrase +physical +piano +picnic +picture +piece +pig +pigeon +pill +pilot +pink +pioneer +pipe +pistol +pitch +pizza +place +planet +plastic +plate +play +please +pledge +pluck +plug +plunge +poem +poet +point +polar +pole +police +pond +pony +pool +popular +portion +position +possible +post +potato +pottery +poverty +powder +power +practice +praise +predict +prefer +prepare +present +pretty +prevent +price +pride +primary +print +priority +prison +private +prize +problem +process +produce +profit +program +project +promote +proof +property +prosper +protect +proud +provide +public +pudding +pull +pulp +pulse +pumpkin +punch +pupil +puppy +purchase +purity +purpose +purse +push +put +puzzle +pyramid +quality +quantum +quarter +question +quick +quit +quiz +quote +rabbit +raccoon +race +rack +radar +radio +rail +rain +raise +rally +ramp +ranch +random +range +rapid +rare +rate +rather +raven +raw +razor +ready +real +reason +rebel +rebuild +recall +receive +recipe +record +recycle +reduce +reflect +reform +refuse +region +regret +regular +reject +relax +release +relief +rely +remain +remember +remind +remove +render +renew +rent +reopen +repair +repeat +replace +report +require +rescue +resemble +resist +resource +response +result +retire +retreat +return +reunion +reveal +review +reward +rhythm +rib +ribbon +rice +rich +ride +ridge +rifle +right +rigid +ring +riot +ripple +risk +ritual +rival +river +road +roast +robot +robust +rocket +romance +roof +rookie +room +rose +rotate +rough +round +route +royal +rubber +rude +rug +rule +run +runway +rural +sad +saddle +sadness +safe +sail +salad +salmon +salon +salt +salute +same +sample +sand +satisfy +satoshi +sauce +sausage +save +say +scale +scan +scare +scatter +scene +scheme +school +science +scissors +scorpion +scout +scrap +screen +script +scrub +sea +search +season +seat +second +secret +section +security +seed +seek +segment +select +sell +seminar +senior +sense +sentence +series +service +session +settle +setup +seven +shadow +shaft +shallow +share +shed +shell +sheriff +shield +shift +shine +ship +shiver +shock +shoe +shoot +shop +short +shoulder +shove +shrimp +shrug +shuffle +shy +sibling +sick +side +siege +sight +sign +silent +silk +silly +silver +similar +simple +since +sing +siren +sister +situate +six +size +skate +sketch +ski +skill +skin +skirt +skull +slab +slam +sleep +slender +slice +slide +slight +slim +slogan +slot +slow +slush +small +smart +smile +smoke +smooth +snack +snake +snap +sniff +snow +soap +soccer +social +sock +soda +soft +solar +soldier +solid +solution +solve +someone +song +soon +sorry +sort +soul +sound +soup +source +south +space +spare +spatial +spawn +speak +special +speed +spell +spend +sphere +spice +spider +spike +spin +spirit +split +spoil +sponsor +spoon +sport +spot +spray +spread +spring +spy +square +squeeze +squirrel +stable +stadium +staff +stage +stairs +stamp +stand +start +state +stay +steak +steel +stem +step +stereo +stick +still +sting +stock +stomach +stone +stool +story +stove +strategy +street +strike +strong +struggle +student +stuff +stumble +style +subject +submit +subway +success +such +sudden +suffer +sugar +suggest +suit +summer +sun +sunny +sunset +super +supply +supreme +sure +surface +surge +surprise +surround +survey +suspect +sustain +swallow +swamp +swap +swarm +swear +sweet +swift +swim +swing +switch +sword +symbol +symptom +syrup +system +table +tackle +tag +tail +talent +talk +tank +tape +target +task +taste +tattoo +taxi +teach +team +tell +ten +tenant +tennis +tent +term +test +text +thank +that +theme +then +theory +there +they +thing +this +thought +three +thrive +throw +thumb +thunder +ticket +tide +tiger +tilt +timber +time +tiny +tip +tired +tissue +title +toast +tobacco +today +toddler +toe +together +toilet +token +tomato +tomorrow +tone +tongue +tonight +tool +tooth +top +topic +topple +torch +tornado +tortoise +toss +total +tourist +toward +tower +town +toy +track +trade +traffic +tragic +train +transfer +trap +trash +travel +tray +treat +tree +trend +trial +tribe +trick +trigger +trim +trip +trophy +trouble +truck +true +truly +trumpet +trust +truth +try +tube +tuition +tumble +tuna +tunnel +turkey +turn +turtle +twelve +twenty +twice +twin +twist +two +type +typical +ugly +umbrella +unable +unaware +uncle +uncover +under +undo +unfair +unfold +unhappy +uniform +unique +unit +universe +unknown +unlock +until +unusual +unveil +update +upgrade +uphold +upon +upper +upset +urban +urge +usage +use +used +useful +useless +usual +utility +vacant +vacuum +vague +valid +valley +valve +van +vanish +vapor +various +vast +vault +vehicle +velvet +vendor +venture +venue +verb +verify +version +very +vessel +veteran +viable +vibrant +vicious +victory +video +view +village +vintage +violin +virtual +virus +visa +visit +visual +vital +vivid +vocal +voice +void +volcano +volume +vote +voyage +wage +wagon +wait +walk +wall +walnut +want +warfare +warm +warrior +wash +wasp +waste +water +wave +way +wealth +weapon +wear +weasel +weather +web +wedding +weekend +weird +welcome +west +wet +whale +what +wheat +wheel +when +where +whip +whisper +wide +width +wife +wild +will +win +window +wine +wing +wink +winner +winter +wire +wisdom +wise +wish +witness +wolf +woman +wonder +wood +wool +word +work +world +worry +worth +wrap +wreck +wrestle +wrist +write +wrong +yard +year +yellow +you +young +youth +zebra +zero +zone +zoo`.split(` +`),rt={orgSeed:e=>`m/83696968'/39'/0'/24'/${e}'`,wallet:(e,t=1)=>`m/86'/${t}'/${e}'/0/0`,segwit:(e,t=1)=>`m/84'/${t}'/${e}'/0/0`,nostr:e=>`m/44'/1237'/${e}'/0/0`,ethereum:e=>`m/44'/60'/${e}'/0/0`},Xv=2**31-1,ca=new Map,la=new Map,Bu=()=>qv(ol,256);function cp(e,t=0){if(typeof e!="string"||!Wv(e,ol)||t&&e.split(" ").length!==t)throw new Error("Invalid lab mnemonic.");return e}function qn(e,t){if(!Number.isSafeInteger(e)||e<0||e>Xv)throw new Error(`Invalid ${t}.`);return e}const ua=new Map;function il(e){return ua.has(e)||ua.set(e,Yv(cp(e))),ua.get(e)}function zn(e){return ca.has(e)||ca.set(e,Xn.fromMasterSeed(il(e))),ca.get(e)}function Jv(e,t){const n=e.derive(t).privateKey;if(!n)throw new Error("BIP-85 path produced no private key.");return Rn(js,Ke("bip-entropy-from-k"),n)}function Qv(e,t){const n=`${e}|${qn(t,"child index")}`;return la.has(n)||la.set(n,ap(Jv(zn(e),rt.orgSeed(t)).slice(0,32),ol)),la.get(n)}function Fa(e,t=0,n=1){return Ie(zn(e).derive(rt.wallet(qn(t,"account"),n)).privateKey)}function al(e,t=0,n=1){return Ie(zn(e).derive(rt.segwit(qn(t,"account"),n)).privateKey)}function lp(e,t=0,n=1){return Ie(zn(e).derive(rt.segwit(qn(t,"account"),n)).publicKey)}function Si(e,t=0){return Ie(zn(e).derive(rt.nostr(qn(t,"account"))).privateKey)}function up(e){const t=e.toLowerCase(),n=Ie(tl(Ke(t)));return`0x${[...t].map((r,s)=>parseInt(n[s],16)>=8?r.toUpperCase():r).join("")}`}const fp=e=>up(Ie(tl(Oe.ProjectivePoint.fromHex(e).toRawBytes(!1).slice(1)).slice(-20)));function dp(e,t=0){return Ie(zn(e).derive(rt.ethereum(qn(t,"account"))).privateKey)}const fa=new Map;function ek(e,t=0){const n=`${e}|${t}`;return fa.has(n)||fa.set(n,fp(zn(e).derive(rt.ethereum(qn(t,"account"))).publicKey)),fa.get(n)}function tk(e,t=0){const n=jn.getPublicKey(zn(e).derive(rt.nostr(qn(t,"account"))).privateKey);return{pubkey:Ie(n),npub:mr.encode("npub",mr.toWords(n))}}const It=["taproot","segwit","nostr","ethereum"],_i=(e,t)=>["lineage/v0 keyring",`node: ${e}`,...It.map(n=>`${n}: ${t[n]}`)].join(` +`),nk=["bc","tb","bcrt"],hp=new Uint8Array(32),ct=e=>{const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),t},Ms=e=>le(e.length<253?Uint8Array.of(e.length):Uint8Array.of(253,e.length&255,e.length>>8),e),vs=e=>Ae(Ae(e)),pp=(e,...t)=>{const n=Ae(Ke(e));return Ae(le(n,n,...t))},rk=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]);function Ds(e){if(typeof e!="string"||e!==e.toLowerCase())return null;for(const[t,n]of[[mr,0],[Lv,1]])try{const{prefix:r,words:s}=t.decode(e,90);if(s[0]===n&&nk.includes(r))return{network:r,version:n,program:Uint8Array.from(t.fromWords(s.slice(1)))}}catch{}return null}const cl=e=>(e==null?void 0:e.version)===1&&e.program.length===32,ll=e=>(e==null?void 0:e.version)===0&&e.program.length===20,gp=({version:e,program:t})=>le(Uint8Array.of(e?80+e:0,t.length),t),sk=e=>pp("BIP0322-signed-message",Ke(e)),oi=new Uint8Array(8),Tu=le(oi,Ms(Uint8Array.of(106)));function ok(e,t){const n=gp(e),r=le(Uint8Array.of(0,32),sk(t));return vs(le(ct(0),Uint8Array.of(1),new Uint8Array(32),ct(4294967295),Ms(r),ct(0),Uint8Array.of(1),oi,Ms(n),ct(0)))}function ii(e,t,n=0){const r=gp(e),s=le(ok(e,t),ct(0));if(e.version===0){const o=le(Uint8Array.of(25,118,169,20),e.program,Uint8Array.of(136,172));return vs(le(ct(0),vs(s),vs(ct(0)),s,o,oi,ct(0),vs(Tu),ct(0),ct(1)))}return pp("TapSighash",Uint8Array.of(0,n),ct(0),ct(0),Ae(s),Ae(oi),Ae(Ms(r)),Ae(ct(0)),Ae(Tu),Uint8Array.of(0),ct(0))}const Ou=e=>yt.encode(le(Uint8Array.of(e.length),...e.map(Ms)));function ik(e){try{const t=yt.decode(e);let n=0;const r=()=>{if(n>=t.length)throw new Error("short");const o=t[n++];if(o<253)return o;if(o>253||n+2>t.length)throw new Error("size");return n+=2,t[n-2]|t[n-1]<<8},s=Array.from({length:r()},()=>{const o=r();if(n+o>t.length)throw new Error("short");return n+=o,t.slice(n-o,n)});return n===t.length?s:null}catch{return null}}function Iu(e,t,n){const r=Ds(e);if(cl(r))return Ou([jn.sign(ii(r,t),n,hp)]);if(!ll(r))throw new Error("BIP-322 here signs for Taproot and P2WPKH addresses only.");const s=Oe.sign(ii(r,t),n).toDERRawBytes();return Ou([le(s,Uint8Array.of(1)),Oe.getPublicKey(n,!0)])}function Cu(e,t,n){const r=Ds(e),s=typeof n=="string"?ik(n):null;if(!r||!s)return!1;try{if(cl(r)){const[o]=s;return s.length!==1||!(o.length===64||o.length===65&&o[64]===1)?!1:jn.verify(o.slice(0,64),ii(r,t,o.length===65?1:0),r.program)}if(ll(r)){const[o,i]=s;return s.length!==2||i.length!==33||o.at(-1)!==1||!rk(nl(Ae(i)),r.program)?!1:Oe.verify(Oe.Signature.fromDER(o.slice(0,-1)),ii(r,t),i)}}catch{}return!1}const mp=e=>{const t=Ke(e);return tl(le(Ke(`Ethereum Signed Message: +${t.length}`),t))},yp=e=>typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e)&&up(e.slice(2))===e;function ak(e,t){const n=Oe.sign(mp(e),t);return`0x${Ie(n.toCompactRawBytes())}${(27+n.recovery).toString(16)}`}function ck(e,t,n){if(!yp(e)||typeof n!="string"||!/^0x[0-9a-f]{130}$/.test(n))return!1;try{const r=bt(n.slice(2)),s=r[64]-27;if(s!==0&&s!==1)return!1;const o=Oe.Signature.fromCompact(r.slice(0,64)).addRecoveryBit(s).recoverPublicKey(mp(t));return fp(o.toRawBytes(!1))===e}catch{return!1}}const wp=(e,t)=>Ae(Ke(JSON.stringify([0,e,0,1,[],t])));function ul(e){try{const{prefix:t,words:n}=mr.decode(e,90),r=mr.fromWords(n);return t==="npub"&&r.length===32&&e===e.toLowerCase()?Ie(Uint8Array.from(r)):null}catch{return null}}const lk=(e,t)=>Ie(jn.sign(wp(Ie(jn.getPublicKey(t)),e),t,hp));function uk(e,t,n){const r=ul(e);try{return!!r&&typeof n=="string"&&/^[0-9a-f]{128}$/.test(n)&&jn.verify(n,wp(r,t),r)}catch{return!1}}const fk={taproot:Iu,segwit:Iu,nostr:(e,t,n)=>lk(t,n),ethereum:(e,t,n)=>ak(t,n)},dk={taproot:Cu,segwit:Cu,nostr:uk,ethereum:ck};function bp(e){const t=Ds(e.taproot),n=Ds(e.segwit);return cl(t)?ll(n)?t.network!==n.network?"its Taproot and SegWit addresses must be on one network":ul(e.nostr)?yp(e.ethereum)?"":"ethereum must be an EIP-55 address":"nostr must be an npub":"segwit must be a P2WPKH address":"taproot must be a Taproot address"}function hk(e,t,n){const r=bp(t);if(r)throw new Error(`${r[0].toUpperCase()}${r.slice(1)}.`);const s=_i(e,t);return{...Object.fromEntries(It.map(o=>[o,t[o]])),proof:Object.fromEntries(It.map(o=>[o,fk[o](t[o],s,n[o])]))}}const ys=new Map;function pk(e,t){const n=t.proof&&typeof t.proof=="object"&&!Array.isArray(t.proof)?t.proof:{},r=JSON.stringify([e,...It.map(s=>[t[s]??null,n[s]??null])]);if(!ys.has(r)){ys.size>=1e3&&ys.clear();let s=bp(t);if(!s){const o=_i(e,t),i=It.find(a=>!dk[a](t[a],o,n[a]));i&&(s=`the ${i} key did not sign this keyring`)}ys.set(r,s)}return ys.get(r)}const Pu=e=>It.map(t=>`${t}:${t==="nostr"?ul(e[t]):t==="ethereum"?e[t].toLowerCase():Ie(Ds(e[t]).program)}`),Ai="lineage/v0",gk=["white","green","black"],Uu=["sole","llc","series-llc","series","corp"],mk={sole:"sole proprietor",llc:"LLC","series-llc":"series LLC",series:"series",corp:"corporation"},Nu=/^[A-Z]{2}(-[A-Z0-9]{1,3})?$/,yk=/^[0-9a-f]{64}$/,rn=e=>e.kind==="agent"&&e.root!==e.id,bo="names are 1-40 lowercase letters, digits or hyphens (they become domains)",wk=/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/,ws=e=>typeof e=="string"&&wk.test(e),Nr=(e,t)=>typeof e=="string"?e.trim().slice(0,t):"";function Qs(e){return String(e??"").toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/,"")}const Sr=e=>e.events.filter(t=>t.protocol===Ai),bk=e=>e.sat!==void 0&&e.sat!==null?`sat ${e.sat}`:e.satpoint?`satpoint ${e.satpoint}`:null;function Dt(e,{upTo:t=1/0,pending:n=!1}={}){var g,p;const r=new Map,s=[],o=[],i=new Map,a=new Map,c=new Map,l=new Map,f=m=>m.status==="active",u=m=>_r(r,m),d=m=>{if(m.keyring&&!m.keyring.retired)for(const w of Pu(m.keyring.keys))a.delete(w)},h=(m,w,y,b)=>{m.keyring&&!m.keyring.retired&&(d(m),m.keyring.retired={cause:w,by:y,beat:b})};for(const m of e){const w=m.status==="confirmed";if(w?m.height>t:!n)continue;l.set(m.id,bk(m));const y=m.metadata&&typeof m.metadata=="object"&&!Array.isArray(m.metadata)?m.metadata:{},b={id:m.id,op:typeof y.op=="string"?y.op.slice(0,20):"?",beat:w?m.height:null,pending:!w,meta:y,parent:m.parent??null,ok:!0,why:"",node:null,root:null,also:[]},_=b.parent?r.get(b.parent):null,$=b.beat??"cued",x=B=>{b.ok=!1,b.why=B},C=B=>_?f(_)?"":`the ${B} is ${_.status}`:`the ${B} is not in this lineage`;let P="",O=[];const N=(_==null?void 0:_.root)??null;switch(b.op){case"found":if(b.parent)x("a holding has no parent");else if(!ws(y.name))x(bo);else if(s.some(B=>f(B)&&B.name===y.name))x(`an active holding is already named ${y.name}`);else{const B=Lu(m,y.name,null,"holding");r.set(B.id,B),s.push(B),b.node=B.id}break;case"birth":{const B=y.kind==="agent"?"agent":"org";if(P=C("parent"))x(P);else if(rn(_))x("agents give birth only once they graduate");else if(!ws(y.name))x(bo);else if(u(_).some(k=>f(k)&&k.name===y.name))x(`${_.name} already has an active ${y.name}`);else{const k=Lu(m,y.name,_,B);k.index=_.children.filter(E=>r.get(E).kind===B).length,_.children.push(k.id),r.set(k.id,k),b.node=k.id}break}case"award":{const B=r.get(y.to);if(P=C("issuer"))x(P);else if(rn(_))x("agents award belts only once they graduate");else if(!B||B.id===_.id)x("the recipient must be another node in this lineage");else if(!f(B))x(`the recipient is ${B.status}`);else if(!ws(y.skill)||!gk.includes(y.belt))x("an award needs a skill name and a belt (white, green or black)");else if(!l.get(B.id)||l.get(m.id)!==l.get(B.id))x("a belt counts only on its recipient's own sat");else{const k=B.badges.find(E=>E.skill===y.skill);B.badges=B.badges.filter(E=>E.skill!==y.skill),B.badges.push({skill:y.skill,belt:y.belt,by:_.id,beat:$,id:m.id,earlier:k?[...k.earlier,{belt:k.belt,by:k.by,beat:k.beat,id:k.id}]:[]}),b.node=B.id}break}case"decide":(P=C("decider"))?x(P):Nr(y.title,140)?(_.decisions.push({title:Nr(y.title,140),why:Nr(y.why,400),beat:$,id:m.id}),b.node=_.id):x("a decision needs a title");break;case"make":(P=C("maker"))?x(P):ws(y.name)?_.made.some(B=>i.get(B).name===y.name)?x(`there is already a ${y.name} by ${_.name}`):(i.set(m.id,{id:m.id,name:y.name,note:Nr(y.note,280),maker:_.id,beat:$}),_.made.push(m.id),b.node=_.id):x(bo);break;case"graduate":{const B=r.get(y.of);if(P=C("parent"))x(P);else if(!B||B.parent!==_.id)x("only its parent can graduate a child");else if(!f(B))x(`the child is ${B.status}`);else if(B.edge==="adopted")x("already graduated");else if(B.joining)x(`${B.name} is joining ${r.get(B.joining.to).name}`);else{const k=B.root,E=A=>{A.root=B.id;for(const U of u(A))U.root===k&&E(U)};B.edge="adopted",B.graduated=$,B.rooted=m.id,b.node=B.id,b.rekeys=!0,E(B),s.push(B);const v=A=>{h(A,"graduate",B.id,$);for(const U of u(A))U.edge==="derived"&&v(U)};v(B)}break}case"close":if(!_)x(b.parent?"that node is not in this lineage":"a close spends the node it closes");else if(!f(_))x(`already ${_.status}`);else{const B=k=>{k.status="closed",k.closed=$,h(k,"close",_.id,$);for(const E of u(k))E.edge==="derived"&&f(E)&&(b.also.push(E.id),B(E))};B(_),b.node=_.id}break;case"charter":{const B=y.form==="series",k=B?r.get(y.of):_,E=_&&(_.kind==="holding"||_.kind==="agent");(P=C(B?"master":"node"))?x(P):Uu.includes(y.form)?!B&&y.of!==void 0&&y.of!==_.id?x("a node charters itself; only a series is chartered by its master"):B&&(!k||!xp(r,k,_))?x("a series must descend from its master"):B&&!f(k)?x(`the series is ${k.status}`):B&&k.kind!=="org"?x("only orgs become series"):B&&((g=_.charter)==null?void 0:g.form)!=="series-llc"?x(`${_.name} is not chartered as a series LLC`):B&&y.jurisdiction!==void 0?x("a series takes its master's jurisdiction"):y.form==="sole"&&!E?x("a sole proprietor is a person: a holding or an agent"):y.form!=="sole"&&!B&&rn(_)?x("an agent graduates before it incorporates"):y.form!=="sole"&&!B&&!Nu.test(y.jurisdiction??"")||y.form==="sole"&&y.jurisdiction!==void 0&&!Nu.test(y.jurisdiction)?x("a jurisdiction is an ISO code such as US-WY"):y.provider!==void 0&&!ws(y.provider)?x(`a provider's name follows the name rule: ${bo}`):y.filing!==void 0&&!yk.test(y.filing)?x("a filing is the SHA-256 of the filed documents, in hex"):(k.charter={id:m.id,beat:$,form:y.form,jurisdiction:B?null:y.jurisdiction??null,legal:Nr(y.legal,120)||null,provider:y.provider??null,filing:y.filing??null,master:B?_.id:null},b.node=k.id):x(`a charter's form is ${Uu.join(", ")}`);break}case"keyring":{if(P=C("node"))x(P);else if(P=pk(_.id,y))x(P);else{const B=Object.fromEntries(It.map(v=>[v,y[v]])),k=Pu(B),E=k.findIndex(v=>a.has(v)&&a.get(v)!==_.id);if(E>=0)x(`its ${It[E]} key is already bound to ${r.get(a.get(k[E])).name}`);else{d(_),_.keyring={id:m.id,beat:$,keys:B,retired:null};for(const v of k)a.set(v,_.id);b.node=_.id}}break}case"join":case"adopt":{const B=b.op==="join",k=B?_:r.get(y.of),E=B?r.get(y.to)??null:_;if(P=C(B?"node":"parent"))x(P);else if(P=Zt(r,k,E))x(P);else{const v=`${E.id}>${k.id}`,A=B?c.get(v):((p=k.joining)==null?void 0:p.to)===E.id?k.joining:null;if(b.node=k.id,O=[k.root,E.root],!A&&B)k.joining={to:E.id,id:m.id,beat:$};else if(!A)c.set(v,{id:m.id});else{c.delete(v),k.joining=null;const U=k.root,K=M=>{M.root=E.root;for(const V of u(M))V.root===U&&K(V)};k.moves.push({from:k.parent,index:k.index,to:E.id,beat:$,join:B?m.id:A.id,adopt:B?A.id:m.id}),k.root===k.id&&s.splice(s.indexOf(k),1),k.kind==="holding"&&(k.kind="org"),k.index=E.children.filter(M=>r.get(M).kind===k.kind).length,k.parent=E.id,k.edge="derived",E.children.push(k.id),K(k);const H=M=>{h(M,"move",E.id,$);for(const V of u(M))V.edge==="derived"&&H(V)};H(k),b.rekeys=!0}}break}default:x("not a lineage/v0 op")}const R=b.node?r.get(b.node).root:null;b.root=N??R,b.roots=[...new Set([b.root,R,...O].filter(Boolean))],o.push(b)}return{nodes:r,roots:s,log:o,items:i,bound:a}}function Lu(e,t,n,r){return{id:e.id,name:t,kind:r,parent:(n==null?void 0:n.id)??null,root:n?n.root:e.id,edge:n?"derived":null,status:"active",index:null,born:e.status==="confirmed"?e.height:"cued",children:[],badges:[],decisions:[],made:[],keyring:null,charter:null,graduated:null,rooted:null,closed:null,joining:null,moves:[]}}function xp(e,t,n){for(let r=e.get(t.parent);r;r=e.get(r.parent))if(r.id===n.id)return!0;return!1}const _r=(e,t)=>[...new Set(t.children)].map(n=>e.get(n)).filter(n=>n.parent===t.id);function Zt(e,t,n){return t?t.kind==="agent"?"an agent changes hands only with the org it sits in":t.status!=="active"?`${t.name} is ${t.status}`:n===void 0?"":n?n.status!=="active"?`the new parent is ${n.status}`:rn(n)?"agents adopt only once they graduate":n.id===t.id||xp(e,n,t)?`${t.name} cannot join itself or anything below it`:n.id===t.parent?`${t.name} is already ${n.name}'s`:_r(e,n).some(r=>r.status==="active"&&r.name===t.name)?`${n.name} already has an active ${t.name}`:"":"the new parent must be a node in this lineage":"that node is not in this lineage"}function Es(e,t){var s;const n=t==null?void 0:t.charter;if(!n)return null;if(t.status!=="active")return{ok:!1,why:`${t.name} is closed`};if(n.form==="sole"&&t.kind==="org")return{ok:!1,why:`${t.name} joined another holding, and a sole proprietor is a person`};if(n.form!=="series")return{ok:!0,why:""};const r=e.nodes.get(n.master);return r.status!=="active"?{ok:!1,why:`${r.name} is closed`}:((s=r.charter)==null?void 0:s.form)!=="series-llc"?{ok:!1,why:`${r.name} no longer holds series`}:t.root!==r.root?{ok:!1,why:`${t.name} is no longer in ${r.name}'s holding`}:{ok:!0,why:""}}function xk(e,t){const n=[],r=e.nodes.get(t),s=(o,i,a,c=null)=>{const l=!!c&&(o.parent!==c.parent||o.index!==c.index),f=l||o.root!==t;if(n.push({type:"node",node:o,guide:i,path:o.id===t?"●":`${c?c.index:o.index}'`,away:f,moved:l}),f)return;const u={agent:[],org:[]};for(const h of o.children){const g=e.nodes.get(h),p=u[g.kind==="agent"?"agent":"org"];p.push([g,{parent:o.id,index:p.length}])}const d=[["agents",u.agent],["orgs",u.org]].filter(([,h])=>h.length);d.forEach(([h,g],p)=>{const m=p===d.length-1,w=a+(m?" ":"│ ");n.push({type:"group",label:h,guide:a+(m?"└─ ":"├─ ")}),g.forEach(([y,b],_)=>{const $=_===g.length-1;s(y,w+($?"└─ ":"├─ "),w+($?" ":"│ "),b)})})};return r&&s(r,"",""),n}function vk(e,t){const n={orgs:0,agents:0,belts:0,decisions:0,closed:0};for(const r of e.nodes.values())r.root===t&&(r.id!==t&&(n[r.kind==="agent"?"agents":"orgs"]++,r.status==="closed"&&n.closed++),n.belts+=r.badges.length,n.decisions+=r.decisions.length);return n}function ts(e,t){const n=[];for(let r=e.nodes.get(t);r;r=r.id===r.root?null:e.nodes.get(r.parent))n.unshift(r.name);return n.join(" / ")}function vp(e,t){var s;const n=e.meta,r=o=>{var i;return((i=t.nodes.get(o))==null?void 0:i.name)??(typeof o=="string"?`${o.slice(0,8)}…`:"?")};if(!e.ok)return`${e.op}: ${e.why}`;switch(e.op){case"found":return`found ${n.name}`;case"birth":return`birth ${n.name}${n.kind==="agent"?" (agent)":""} ← ${r(e.parent)}`;case"award":return`award ${n.skill} · ${n.belt} → ${r(n.to)}, from ${r(e.parent)}`;case"decide":return`decide “${Nr(n.title,140)}” · ${r(e.parent)}`;case"make":return`make ${n.name} · ${r(e.parent)}`;case"keyring":return`keyring · ${r(e.parent)}`;case"charter":return n.form==="series"?`charter ${r(n.of)} as a series of ${r(e.parent)}`:`charter ${r(e.parent)} · ${mk[n.form]}${n.jurisdiction?` (${n.jurisdiction})`:""}`;case"graduate":return`graduate ${r(n.of)} from ${r(e.parent)}`;case"close":return`close ${r(e.parent)}${e.also.length?` and ${e.also.length} derived`:""}`;case"join":case"adopt":{const o=e.op==="join"?e.parent:n.of,i=e.op==="join"?n.to:e.parent,a=(s=t.nodes.get(o))==null?void 0:s.moves.find(c=>c.join===e.id||c.adopt===e.id);return`${e.op==="join"?`join ${r(o)} to ${r(i)}`:`adopt ${r(o)} into ${r(i)}`}${a?a.from?`, from ${r(a.from)}`:", a holding till now":e.op==="join"?`, for ${r(i)} to adopt`:`, once ${r(o)} joins`}`}default:return e.op}}const Tn=Ie,kk=le,Wa=bt,$k=$r,On="super-testnet-local-v0";class Kn{constructor(t){if(!/^[0-9a-f]{64}$/.test(t)||!Oe.utils.isValidPrivateKey(t))throw new Error("Invalid test wallet key. Load a Super Testnet v0 backup.");this.kind="test-wallet",this.secret=t,this.pubkey=Tn(jn.getPublicKey(t)),this.address=As.p2tr.fromPubKey(this.pubkey,"regtest"),this.script=["OP_1",this.pubkey]}static create(){return new Kn(Tn(Oe.utils.randomPrivateKey()))}static load(t){if((t==null?void 0:t.network)!==On||(t==null?void 0:t.version)!==1||(t==null?void 0:t.kind)!=="test-wallet")throw new Error("Only Super Testnet v0 test-wallet backups are accepted.");return new Kn(t.secret)}backup(){return{kind:"test-wallet",version:1,network:On,secret:this.secret}}sign(t,n,r=0){return lr.taproot.sign(this.secret,t,r,n?{extension:n}:{}).hex}}const xo=50*1e8,vo="0".repeat(64),Hu=e=>Tn(Ae(new TextEncoder().encode(JSON.stringify(e)))),Cr=(e,t)=>`${e}:${t}`,Me=e=>Ce.encode(e,!1).hex,ue=(e,t)=>{if(!e)throw new Error(t)},Ru=/^5120[0-9a-f]{64}$/,ko=/^0014[0-9a-f]{40}$/,kp=64,xt=64,Ek=e=>Tn(nl(Ae(Wa(e))));function Sk(e,t){const[n,r]=e.vin[t].witness;return Oe.verify(n.slice(0,-2),lr.segwit.hash(e,t,{pubkey:r,sigflag:1}),r,{lowS:!0,format:"der"})}const da=(e,...t)=>{const n=Ae(new TextEncoder().encode(e));return Ae(kk(n,n,...t))},_k=e=>e<253?Uint8Array.of(e):Uint8Array.of(253,e&255,e>>8);function Ak(e,t){const[n,r,s]=e.vin[t].witness,o=Wa(s),i=Wa(r);if(o.length<33||(o.length-33)%32||i.length>65535||!/^20[0-9a-f]{64}ac/.test(r))return!1;const a=da("TapLeaf",Uint8Array.of(o[0]&254),_k(i.length),i);let c=a;for(let u=33;u=Oe.CURVE.n)return!1;const f=Oe.ProjectivePoint.fromHex(`02${Tn(o.slice(1,33))}`).add(Oe.ProjectivePoint.BASE.multiply(l)).toAffine();return`5120${f.x.toString(16).padStart(64,"0")}`!==Me(e.vin[t].prevout.scriptPubKey)||Number(f.y&1n)!==(o[0]&1)?!1:jn.verify(n,lr.taproot.hash(e,t,{extension:Tn(a)}),r.slice(2,66))}class Bi{constructor(t){if(this.blocks=[],this.mempool=[],this.utxos=new Map,this.transactions=new Map,this.imports=[],t){ue(t.network===On&&t.version===1,"Unsupported local chain version/network."),ue(Array.isArray(t.blocks)&&Array.isArray(t.mempool)&&Array.isArray(t.imports??[]),"Invalid chain snapshot.");for(const n of t.imports??[])this.importCoin(n);for(const n of t.blocks)this.acceptBlock(structuredClone(n));this.submitPackage(t.mempool)}}snapshot(){return{network:On,version:1,blocks:structuredClone(this.blocks),mempool:[...this.mempool],...this.imports.length?{imports:structuredClone(this.imports)}:{}}}importCoin({txid:t,vout:n,value:r,script:s}){ue(/^[0-9a-f]{64}$/.test(t)&&Number.isSafeInteger(n)&&n>=0&&Number.isSafeInteger(r)&&r>=330&&r<=xo&&(Ru.test(s)||ko.test(s)),"Invalid imported coin."),ue(!this.utxos.has(Cr(t,n))&&!this.transactions.has(t)&&!this.imported(t,n),"That coin is already in this chain."),this.utxos.set(Cr(t,n),{txid:t,vout:n,value:r,scriptPubKey:s,height:0,ranges:Xu(this.imports.length,r),inscriptions:[]}),this.imports.push({txid:t,vout:n,value:r,script:s})}imported(t,n){const r=this.imports.find(s=>s.txid===t&&s.vout===n);return r?{value:r.value,scriptPubKey:r.script}:null}coins(t){return[...this.utxos.values()].filter(n=>Me(n.scriptPubKey)===Me(t))}satLocation(t){for(const n of this.utxos.values()){const r=Bn(n.ranges,t);if(r!==null)return{txid:n.txid,vout:n.vout,offset:r}}return null}balance(t){return this.coins(t).reduce((n,r)=>n+r.value,0)}apply(t,n,r=!1){var m,w,y,b,_;ue(typeof t=="string"&&t.length<4e4&&/^(?:[a-f0-9]{2})+$/.test(t),"Invalid raw transaction.");const s=X.decode(t),o=X.util.getTxid(s);ue(!this.transactions.has(o),"Duplicate transaction."),ue(s.version===2&&s.locktime===0,"Unsupported transaction version or locktime.");const i=!r&&s.vin.some($=>{var x;return((x=$.witness)==null?void 0:x.length)===3}),a=r?1:i?3:xt,c=r?kp:i?2:xt;ue(s.vin.length>=1&&s.vin.length<=a&&s.vout.length>=1&&s.vout.length<=c,"Unsupported transaction shape.");let l=0;for(const $ of s.vout){const x=Number($.value);ue(Number.isSafeInteger(x)&&x>=330&&x<=xo,"Invalid output amount.");const C=Me($.scriptPubKey);ue(Ru.test(C)||ko.test(C),"Only Taproot and P2WPKH outputs are supported."),l+=x}let f,u=[];const d=s.vin.findIndex($=>{var x;return((x=$.witness)==null?void 0:x.length)===3}),h=s.vin[d<0?0:d];if(r)ue(h.txid===vo&&h.vout===4294967295&&l===xo,"Invalid local coinbase."),ue(Me(h.scriptSig)===Ce.encode([new TextEncoder().encode(`${On}:${n}`)],!1).hex,"Wrong coinbase height."),ue(!((m=h.witness)!=null&&m.length),"Unexpected coinbase witness.");else{u=s.vin.map(x=>this.utxos.get(Cr(x.txid,x.vout))),ue(u.every(Boolean),"Input is missing or already spent."),ue(new Set(s.vin.map(x=>Cr(x.txid,x.vout))).size===s.vin.length,"Duplicate input."),s.vin.forEach((x,C)=>{var O,N,R;ue(x.sequence==="ffffffff"&&Me(x.scriptSig)==="","Unsupported input flags."),x.prevout={value:u[C].value,scriptPubKey:u[C].scriptPubKey};const P=Me(u[C].scriptPubKey);if(ko.test(P)){const[B,k]=x.witness??[];ue(C!==d&&((O=x.witness)==null?void 0:O.length)===2,"Unsupported witness."),ue(/^30[0-9a-f]{12,140}01$/.test(B)&&/^0[23][0-9a-f]{64}$/.test(k)&&Ek(k)===P.slice(4),"P2WPKH spends need a SIGHASH_ALL signature by the key they pay.");return}ue(((N=x.witness)==null?void 0:N.length)===1||C===d&&((R=x.witness)==null?void 0:R.length)===3,"Unsupported witness."),ue(/^[0-9a-f]{128}$/.test(x.witness[0])||!i&&/^[0-9a-f]{128}83$/.test(x.witness[0]),"Only default 64-byte Schnorr signatures, or SIGHASH_SINGLE|ANYONECANPAY outside reveals, are accepted.")}),ue(u.reduce((x,C)=>x+C.value,0)-l===W,"v0 requires a fixed 500 sat fee per transaction.");let $={};if(h.witness.length===3){const x=zc(h.witness),C=d;if(s.vin.length===3){const[P,O]=u,N=x.pointer===void 0?null:Number(x.pointer);ue(d===2&&x.parent&&((w=O.inscriptions)==null?void 0:w.some(R=>R.id===x.parent))&&Me(O.scriptPubKey)===`5120${x.pubkey}`,"An inscription on a held sat needs its parent spent, from the inscriber's key."),ue(s.vout.length===2&&[P,O].every((R,B)=>Number(s.vout[B].value)===R.value&&Me(s.vout[B].scriptPubKey)===Me(R.scriptPubKey)),"An inscription on a held sat returns both coins unchanged."),ue(N!==null&&NBn(P.ranges,R.sat)===N)),"An inscription on a held sat must point at an inscribed sat.")}else if(ue(Number(s.vout[C].value)===Ht,"Invalid reveal postage."),ue(Me(s.vout[C].scriptPubKey)===`5120${x.pubkey}`,"Reveal must return to its signing wallet."),x.parent){const P=d===0?1:0,O=u[P];ue((b=O==null?void 0:O.inscriptions)==null?void 0:b.some(N=>N.id===x.parent),"Referenced parent inscription must actually be spent."),ue(s.vout.length===2&&Number(s.vout[P].value)===O.value&&Me(O.scriptPubKey)===`5120${x.pubkey}`&&Me(s.vout[P].scriptPubKey)===Me(O.scriptPubKey),"Parent must be owned and preserved in the same wallet.")}else s.vin.length===2&&(ue(d===1&&((_=u[0].inscriptions)==null?void 0:_.length)&&x.pointer!==void 0,"Reinscription spend requires correct tag and owned sat."),ue(Number(s.vout[0].value)===u[0].value&&Me(s.vout[0].scriptPubKey)===Me(u[0].scriptPubKey)&&Me(u[0].scriptPubKey)===`5120${x.pubkey}`,"Reinscription sat must be returned to owner."));$={pubkey:x.pubkey},f={id:`${o}i0`,txid:o,commitTxid:h.txid,text:x.text,bytes:Array.from(x.bytes),contentType:x.contentType,parent:x.parent,delegate:x.delegate,pointer:x.pointer,metaprotocol:x.metaprotocol,metadata:x.metadata,height:n,value:Ht}}s.vin.forEach((x,C)=>{let P=!1;try{P=ko.test(Me(u[C].scriptPubKey))?Sk(s,C):C===d?Ak(s,C)||lr.taproot.verify(s,C,$):lr.taproot.verify(s,C,{})}catch{}ue(P,"Invalid signature or Taproot commitment.")})}const g=ef(s,u,n,r),p=u.flatMap($=>$.inscriptions??[]);if(f){const $=BigInt(f.pointer??0),x=${var P;return((P=C.inscription)==null?void 0:P.sat)===f.sat}).length,p.push(f)}return ue(p.every($=>g.some(x=>Bn(x,$.sat)!==null)),"Local lab protects inscription sats from fee loss."),r||s.vin.forEach($=>this.utxos.delete(Cr($.txid,$.vout))),s.vout.forEach(($,x)=>{const C=p.filter(P=>Bn(g[x],P.sat)!==null);this.utxos.set(Cr(o,x),{txid:o,vout:x,value:Number($.value),scriptPubKey:$.scriptPubKey,height:n,ranges:g[x],inscriptions:C,...C.length?{inscription:C[0]}:{}})}),this.transactions.set(o,{txid:o,raw:t,height:n,coinbase:r,tx:s,...f?{inscription:f}:{}}),o}submitPackage(t){ue(Array.isArray(t)&&this.mempool.length+t.length<=1e3,"Invalid package or mempool full; mine a block first.");const n=new Map(this.utxos),r=new Map(this.transactions);try{t.forEach(s=>this.apply(s,null))}catch(s){throw this.utxos=n,this.transactions=r,s}this.mempool.push(...t)}acceptBlock(t){var i;ue(t.height===this.blocks.length+1&&t.previous===(((i=this.blocks.at(-1))==null?void 0:i.hash)??vo),"Invalid block ancestry."),ue(Number.isSafeInteger(t.time)&&t.time>0&&Array.isArray(t.raws)&&t.raws.length>0&&t.raws.length<=1001,"Invalid block.");const{hash:n,...r}=t;ue(Hu(r)===n,"Invalid local block hash.");const s=new Map(this.utxos),o=new Map(this.transactions);try{t.raws.forEach((a,c)=>this.apply(a,t.height,c===0))}catch(a){throw this.utxos=s,this.transactions=o,a}this.blocks.push(t)}mine(t){return this.mineTo([de(xo,t)])}mineTo(t){var a;const n=new Bi({...this.snapshot(),mempool:[]}),r=this.blocks.length+1,s=X.create({vin:[{txid:vo,vout:4294967295,scriptSig:[new TextEncoder().encode(`${On}:${r}`)]}],vout:t}),o={height:r,previous:((a=this.blocks.at(-1))==null?void 0:a.hash)??vo,time:Date.now(),raws:[X.encode(s).hex,...this.mempool]},i={...o,hash:Hu(o)};return n.acceptBlock(i),Object.assign(this,n),i}}const $p="lineage-claim",Ga=330,ai=e=>Ce.encode(e,!1).hex,ju=e=>({txid:e.txid,vout:e.vout,value:e.value,script:ai(e.scriptPubKey)}),ha=/^[0-9a-f]{64}$/,Bk=/^5120[0-9a-f]{64}$/;function an(e,t){var n;for(const r of e.utxos.values())if((n=r.inscriptions)!=null&&n.some(s=>s.id===t))return r;return null}function Ep(e){return X.create({vin:[Fe(e.holder.txid,e.holder.vout,e.holder.value,e.holder.script),Fe(e.payer.txid,e.payer.vout,e.payer.value,e.payer.script)],vout:[de(e.holder.value,["OP_1",e.to]),de(e.payer.value-W,["OP_1",e.to])]})}function Tk(e,t,n,r=Date.now()){if((n==null?void 0:n.kind)!=="test-wallet")throw new Error("Claims are signed by local test wallets.");const s=an(e,t);if(!s)throw new Error("That inscription is not in an unspent output.");if(ai(s.scriptPubKey)===ai(n.script))throw new Error("The recipient already holds that inscription.");const o=e.coins(n.script).find(c=>{var l;return!((l=c.inscriptions)!=null&&l.length)&&c.value>=W+Ga});if(!o)throw new Error("The recipient needs a plain coin for the 500-sat fee. Mine a block to it first.");const i={kind:$p,version:1,inscription:t,carried:s.inscriptions.map(c=>c.id),holder:ju(s),payer:ju(o),to:n.pubkey,at:r},a=Ep(i);return i.txid=X.util.getTxid(a),i.sig=n.sign(a,void 0,1),i}function Ok(e,t,n){const r=Ck(t);if((n==null?void 0:n.kind)!=="test-wallet")throw new Error("Countersigning needs a local test wallet.");if(ai(n.script)!==r.holder.script)throw new Error("Only the current holder can countersign.");if(Ik(e,r)!=="open")throw new Error("This claim is stale: an input it spends was already spent.");const s=Ep(r);return s.vin[1].witness=[r.sig],s.vin[0].witness=[n.sign(s,void 0,0)],e.submitPackage([X.encode(s).hex]),X.util.getTxid(s)}function Ik(e,t){return e.utxos.has(`${t.holder.txid}:${t.holder.vout}`)&&e.utxos.has(`${t.payer.txid}:${t.payer.vout}`)?"open":"stale"}function Ck(e){const t=n=>n&&ha.test(n.txid)&&Number.isSafeInteger(n.vout)&&n.vout>=0&&Number.isSafeInteger(n.value)&&n.value>=Ga&&Bk.test(n.script);if((e==null?void 0:e.kind)!==$p||e.version!==1||!/^[0-9a-f]{64}i\d+$/.test(e.inscription)||!Array.isArray(e.carried)||!t(e.holder)||!t(e.payer)||e.payer.value255*s)throw new Error("Length should be <= 255*HashLen");const o=Math.ceil(r/s);n===void 0&&(n=Ku);const i=new Uint8Array(o*s),a=Rn.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let f=0;fUk(e,Pk(e,t,n),r,s);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Sn=BigInt(0),De=BigInt(1),ga=BigInt(2),Lk=BigInt(8);function Hk(e,t,n,r){const s=e.sqr(n),o=e.sqr(r),i=e.add(e.mul(t.a,s),o),a=e.add(e.ONE,e.mul(t.d,e.mul(s,o)));return e.eql(i,a)}function Rk(e,t={}){const n=Ph("edwards",e,t,t.FpFnLE),{Fp:r,Fn:s}=n;let o=n.CURVE;const{h:i}=o;ls(t,{},{uvRatio:"function"});const a=ga<r.create(m),l=t.uvRatio||((m,w)=>{try{return{isValid:!0,value:r.sqrt(r.div(m,w))}}catch{return{isValid:!1,value:Sn}}});if(!Hk(r,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function f(m,w,y=!1){const b=y?De:Sn;return Ks("coordinate "+m,w,b,a),w}function u(m){if(!(m instanceof g))throw new Error("ExtendedPoint expected")}const d=Xo((m,w)=>{const{X:y,Y:b,Z:_}=m,$=m.is0();w==null&&(w=$?Lk:r.inv(_));const x=c(y*w),C=c(b*w),P=r.mul(_,w);if($)return{x:Sn,y:De};if(P!==De)throw new Error("invZ was invalid");return{x,y:C}}),h=Xo(m=>{const{a:w,d:y}=o;if(m.is0())throw new Error("bad point: ZERO");const{X:b,Y:_,Z:$,T:x}=m,C=c(b*b),P=c(_*_),O=c($*$),N=c(O*O),R=c(C*w),B=c(O*c(R+P)),k=c(N+c(y*c(C*P)));if(B!==k)throw new Error("bad point: equation left != right (1)");const E=c(b*_),v=c($*x);if(E!==v)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(w,y,b,_){this.X=f("x",w),this.Y=f("y",y),this.Z=f("z",b,!0),this.T=f("t",_),Object.freeze(this)}static CURVE(){return o}static fromAffine(w){if(w instanceof g)throw new Error("extended point not allowed");const{x:y,y:b}=w||{};return f("x",y),f("y",b),new g(y,b,De,c(y*b))}static fromBytes(w,y=!1){const b=r.BYTES,{a:_,d:$}=o;w=fu(_t(w,b,"point")),hr(y,"zip215");const x=fu(w),C=w[b-1];x[b-1]=C&-129;const P=pr(x),O=y?a:r.ORDER;Ks("point.y",P,Sn,O);const N=c(P*P),R=c(N-De),B=c($*N-_);let{isValid:k,value:E}=l(R,B);if(!k)throw new Error("bad point: invalid y coordinate");const v=(E&De)===De,A=(C&128)!==0;if(!y&&E===Sn&&A)throw new Error("bad point: x=0 and x_0=1");return A!==v&&(E=c(-E)),g.fromAffine({x:E,y:P})}static fromHex(w,y=!1){return g.fromBytes(be("point",w),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,y=!0){return p.createCache(this,w),y||this.multiply(ga),this}assertValidity(){h(this)}equals(w){u(w);const{X:y,Y:b,Z:_}=this,{X:$,Y:x,Z:C}=w,P=c(y*C),O=c($*_),N=c(b*C),R=c(x*_);return P===O&&N===R}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:w}=o,{X:y,Y:b,Z:_}=this,$=c(y*y),x=c(b*b),C=c(ga*c(_*_)),P=c(w*$),O=y+b,N=c(c(O*O)-$-x),R=P+x,B=R-C,k=P-x,E=c(N*B),v=c(R*k),A=c(N*k),U=c(B*R);return new g(E,v,U,A)}add(w){u(w);const{a:y,d:b}=o,{X:_,Y:$,Z:x,T:C}=this,{X:P,Y:O,Z:N,T:R}=w,B=c(_*P),k=c($*O),E=c(C*b*R),v=c(x*N),A=c((_+$)*(P+O)-B-k),U=v-E,K=v+E,H=c(k-y*B),M=c(A*U),V=c(K*H),G=c(A*H),fe=c(U*K);return new g(M,V,fe,G)}subtract(w){return this.add(w.negate())}multiply(w){if(!s.isValidNot0(w))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:y,f:b}=p.cached(this,w,_=>rr(g,_));return rr(g,[y,b])[0]}multiplyUnsafe(w,y=g.ZERO){if(!s.isValid(w))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return w===Sn?g.ZERO:this.is0()||w===De?this:p.unsafe(this,w,b=>rr(g,b),y)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return p.unsafe(this,o.n).is0()}toAffine(w){return d(this,w)}clearCofactor(){return i===De?this:this.multiplyUnsafe(i)}toBytes(){const{x:w,y}=this.toAffine(),b=r.toBytes(y);return b[b.length-1]|=w&De?128:0,b}toHex(){return Ie(this.toBytes())}toString(){return``}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(w){return rr(g,w)}static msm(w,y){return Ch(g,s,w,y)}_setWindowSize(w){this.precompute(w)}toRawBytes(){return this.toBytes()}}g.BASE=new g(o.Gx,o.Gy,De,c(o.Gx*o.Gy)),g.ZERO=new g(Sn,De,De,Sn),g.Fp=r,g.Fn=s;const p=new Ih(g,s.BITS);return g.BASE.precompute(8),g}function jk(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');ls(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:s,Fp:o,Fn:i}=e,a=n.randomBytes||kr,c=n.adjustScalarBytes||(O=>O),l=n.domain||((O,N,R)=>{if(hr(R,"phflag"),N.length||R)throw new Error("Contexts/pre-hash are not supported");return O});function f(O){return i.create(pr(O))}function u(O){const N=b.secretKey;O=be("private key",O,N);const R=be("hashed private key",t(O),2*N),B=c(R.slice(0,N)),k=R.slice(N,2*N),E=f(B);return{head:B,prefix:k,scalar:E}}function d(O){const{head:N,prefix:R,scalar:B}=u(O),k=s.multiply(B),E=k.toBytes();return{head:N,prefix:R,scalar:B,point:k,pointBytes:E}}function h(O){return d(O).pointBytes}function g(O=Uint8Array.of(),...N){const R=le(...N);return f(t(l(R,be("context",O),!!r)))}function p(O,N,R={}){O=be("message",O),r&&(O=r(O));const{prefix:B,scalar:k,pointBytes:E}=d(N),v=g(R.context,B,O),A=s.multiply(v).toBytes(),U=g(R.context,A,E,O),K=i.create(v+U*k);if(!i.isValid(K))throw new Error("sign failed: invalid s");const H=le(A,i.toBytes(K));return _t(H,b.signature,"result")}const m={zip215:!0};function w(O,N,R,B=m){const{context:k,zip215:E}=B,v=b.signature;O=be("signature",O,v),N=be("message",N),R=be("publicKey",R,b.publicKey),E!==void 0&&hr(E,"zip215"),r&&(N=r(N));const A=v/2,U=O.subarray(0,A),K=pr(O.subarray(A,v));let H,M,V;try{H=e.fromBytes(R,E),M=e.fromBytes(U,E),V=s.multiplyUnsafe(K)}catch{return!1}if(!E&&H.isSmallOrder())return!1;const G=g(k,M.toBytes(),H.toBytes(),N);return M.add(H.multiplyUnsafe(G)).subtract(V).clearCofactor().is0()}const y=o.BYTES,b={secretKey:y,publicKey:y,signature:2*y,seed:y};function _(O=a(b.seed)){return _t(O,b.seed,"seed")}function $(O){const N=P.randomSecretKey(O);return{secretKey:N,publicKey:h(N)}}function x(O){return Gs(O)&&O.length===i.BYTES}function C(O,N){try{return!!e.fromBytes(O,N)}catch{return!1}}const P={getExtendedPublicKey:d,randomSecretKey:_,isValidSecretKey:x,isValidPublicKey:C,toMontgomery(O){const{y:N}=e.fromBytes(O),R=b.publicKey,B=R===32;if(!B&&R!==57)throw new Error("only defined for 25519 and 448");const k=B?o.div(De+N,De-N):o.div(N-De,N+De);return o.toBytes(k)},toMontgomerySecret(O){const N=b.secretKey;_t(O,N);const R=t(O.subarray(0,N));return c(R).subarray(0,N)},randomPrivateKey:_,precompute(O=8,N=e.BASE){return N.precompute(O,!1)}};return Object.freeze({keygen:$,getPublicKey:h,sign:p,verify:w,utils:P,Point:e,lengths:b})}function Kk(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp,r=Er(t.n,e.nBitLength,!0),s={Fp:n,Fn:r,uvRatio:e.uvRatio},o={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:s,hash:e.hash,eddsaOpts:o}}function Mk(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function Dk(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:s}=Kk(e),o=Rk(t,n),i=jk(o,r,s);return Mk(e,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const bs=BigInt(0),Pr=BigInt(1),$o=BigInt(2);function Zk(e){return ls(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function Vk(e){const t=Zk(e),{P:n,type:r,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=t,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=i||kr,l=a?255:448,f=a?32:56,u=BigInt(a?9:5),d=BigInt(a?121665:39081),h=a?$o**BigInt(254):$o**BigInt(447),g=a?BigInt(8)*$o**BigInt(251)-Pr:BigInt(4)*$o**BigInt(445)-Pr,p=h+g+Pr,m=k=>Te(k,n),w=y(u);function y(k){return Yc(m(k),f)}function b(k){const E=be("u coordinate",k,f);return a&&(E[31]&=127),m(pr(E))}function _(k){return pr(s(be("scalar",k,f)))}function $(k,E){const v=P(b(E),_(k));if(v===bs)throw new Error("invalid private or public key received");return y(v)}function x(k){return $(k,w)}function C(k,E,v){const A=m(k*(E-v));return E=m(E-A),v=m(v+A),{x_2:E,x_3:v}}function P(k,E){Ks("u",k,bs,n),Ks("scalar",E,h,p);const v=E,A=k;let U=Pr,K=bs,H=k,M=Pr,V=bs;for(let fe=BigInt(l-1);fe>=bs;fe--){const ce=v>>fe⪻V^=ce,{x_2:U,x_3:H}=C(V,U,H),{x_2:K,x_3:M}=C(V,K,M),V=ce;const ne=U+K,ge=m(ne*ne),me=U-K,Le=m(me*me),pe=ge-Le,_e=H+M,Wt=H-M,pt=m(Wt*ne),We=m(_e*me),Gt=pt+We,hs=pt-We;H=m(Gt*Gt),M=m(A*m(hs*hs)),U=m(ge*Le),K=m(pe*(ge+m(d*pe)))}({x_2:U,x_3:H}=C(V,U,H)),{x_2:K,x_3:M}=C(V,K,M);const G=o(K);return m(U*G)}const O={secretKey:f,publicKey:f,seed:f},N=(k=c(f))=>(Ve(k,O.seed),k);function R(k){const E=N(k);return{secretKey:E,publicKey:x(E)}}return{keygen:R,getSharedSecret:(k,E)=>$(k,E),getPublicKey:k=>x(k),scalarMult:$,scalarMultBase:x,utils:{randomSecretKey:N,randomPrivateKey:N},GuBytes:w.slice(),lengths:O}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const qk=BigInt(1),Mu=BigInt(2),zk=BigInt(3),Fk=BigInt(5),Wk=BigInt(8),fl=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Sp={p:fl,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Wk,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function _p(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),o=fl,a=e*e%o*e%o,c=Pe(a,Mu,o)*a%o,l=Pe(c,qk,o)*e%o,f=Pe(l,Fk,o)*l%o,u=Pe(f,t,o)*f%o,d=Pe(u,n,o)*u%o,h=Pe(d,r,o)*d%o,g=Pe(h,s,o)*h%o,p=Pe(g,s,o)*h%o,m=Pe(p,t,o)*f%o;return{pow_p_5_8:Pe(m,Mu,o)*e%o,b2:a}}function Ap(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Du=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Gk(e,t){const n=fl,r=Te(t*t*t,n),s=Te(r*r*t,n),o=_p(e*s).pow_p_5_8;let i=Te(e*r*o,n);const a=Te(t*i*i,n),c=i,l=Te(i*Du,n),f=a===e,u=a===Te(-e,n),d=a===Te(-e*Du,n);return f&&(i=c),(u||d)&&(i=l),F2(i,n)&&(i=Te(-i,n)),{isValid:f||u,value:i}}const Bp=Er(Sp.p,{isLE:!0}),Yk={...Sp,Fp:Bp,hash:js,adjustScalarBytes:Ap,uvRatio:Gk},Ti=Dk(Yk),Tp=(()=>{const e=Bp.ORDER;return Vk({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:n,b2:r}=_p(t);return Te(Pe(n,zk,e)*r,e)},adjustScalarBytes:Ap})})(),Xk=Ke("lineage/v0"),jt=(e,t)=>Nk(Ae,e,Xk,Ke(t),32),Oi=e=>{const t=Uint8Array.from(e);return t[0]&=248,t[31]&=127,t[31]|=64,t},Op=e=>{const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t},vt=e=>le(Op(e.length),e),dl=e=>le(vt(Ke("ssh-ed25519")),vt(e)),Ya=(e,t)=>`ssh-ed25519 ${yt.encode(dl(e))}${t?` ${t}`:""}`,Xa=e=>`SHA256:${yt.encode(Ae(dl(e))).replace(/=+$/,"")}`;function Jk(e){const t=bt(e),n=r=>Ti.getPublicKey(jt(t,r));return{ssh:n("ssh"),git:n("git"),dkim:n("dkim"),wg:Tp.getPublicKey(Oi(jt(t,"wg")))}}function Qk(e){const t=n=>Ti.getPublicKey(jt(e,n));return{"ssh-ca":t("node/ssh-ca"),mtls:t("node/mtls"),noise:Tp.getPublicKey(Oi(jt(e,"node/noise")))}}function e$(e,t,n,r){return[["ssh",Xa(e.ssh),Ya(e.ssh,t)],["git",Xa(e.git),`${t} namespaces="git" ${Ya(e.git,t)}`],["dkim",`${n}._domainkey.${r}`,`${n}._domainkey.${r}. IN TXT "v=DKIM1; k=ed25519; p=${yt.encode(e.dkim)}"`],["wg",yt.encode(e.wg),`[Peer] +# ${t} +PublicKey = ${yt.encode(e.wg)}`]]}function t$(e,t){return[["ssh-ca",Xa(e["ssh-ca"]),Ya(e["ssh-ca"],`lineage-ca@${t}`)],["mtls",yt.encode(e.mtls),null],["noise",`mkey:${Ie(e.noise)}`,null]]}const n$=bt("302e020100300506032b657004220420");function Ip(e,t,n){const r=Ae(e).slice(0,4);let s=le(r,r,vt(Ke("ssh-ed25519")),vt(t),vt(le(e,t)),vt(Ke(n)));s=le(s,new Uint8Array((8-s.length%8)%8).map((i,a)=>a+1));const o=le(Ke("openssh-key-v1\0"),vt(Ke("none")),vt(Ke("none")),vt(new Uint8Array(0)),Op(1),vt(dl(t)),vt(s));return`-----BEGIN OPENSSH PRIVATE KEY----- +${yt.encode(o).match(/.{1,70}/g).join(` +`)} +-----END OPENSSH PRIVATE KEY----- +`}const r$=(e,t)=>`-----BEGIN ${e}----- +${yt.encode(t).match(/.{1,64}/g).join(` +`)} +-----END ${e}----- +`;function s$(e,t){const n=bt(e),r=s=>{const o=jt(n,s);return Ip(o,Ti.getPublicKey(o),t)};return[["ssh","OpenSSH private key",r("ssh")],["git","OpenSSH private key",r("git")],["dkim","Ed25519 private key (base64)",yt.encode(jt(n,"dkim"))],["wg","Interface entry",`[Interface] +PrivateKey = ${yt.encode(Oi(jt(n,"wg")))}`]]}function o$(e,t){const n=jt(e,"node/ssh-ca");return[["ssh-ca","OpenSSH private key",Ip(n,Ti.getPublicKey(n),`lineage-ca@${t}`)],["mtls","Private key (PKCS#8 PEM)",r$("PRIVATE KEY",le(n$,jt(e,"node/mtls")))],["noise","noise_private.key",`privkey:${Ie(Oi(jt(e,"node/noise")))}`]]}const i$=["bip86","tapkey","wallet"],hl=()=>({scheme:"bip86",roots:{},adopted:{}}),a$=e=>Fs.getPubKey(e)[0];function Cp(e,t,n){return e.scheme==="wallet"?Fa(t,n):Fs.getSecKey(e.scheme==="tapkey"?Si(t,n):Fa(t,n))[0]}const Pp=(e,t)=>e.scheme==="tapkey"?rt.nostr(t):rt.wallet(t),c$=(e,t)=>new Kn(Cp(e,t,0)),Se=e=>Ce.encode(e,!1).hex;function cn(e,t,n){if(!n)return null;const r=i=>i?{mnemonic:i,account:0,origin:`${n.name} root`,steps:[]}:null;if(n.kind==="holding")return r(e.roots[n.id]);if(n.edge==="adopted")return r(e.adopted[n.rooted]??e.adopted[n.id]);const s=t.nodes.get(n.parent);if(n.kind==="agent"){const i=cn(e,t,s);return i&&{...i,account:n.index+1}}const o=cn(e,t,s);return o&&{mnemonic:Qv(o.mnemonic,n.index),account:0,origin:o.origin,steps:[...o.steps,`${n.index}'`]}}const ma=new Map;function $e(e,t,n){const r=cn(e,t,n);if(!r)return null;const s=`${e.scheme}|${r.mnemonic}|${r.account}`;if(!ma.has(s)){const{npub:l,pubkey:f}=tk(r.mnemonic,r.account);ma.set(s,{wallet:new Kn(Cp(e,r.mnemonic,r.account)),npub:l,pubkey:f})}const{wallet:o,npub:i,pubkey:a}=ma.get(s),c=[r.origin,...r.steps].join(" › ");return{wallet:o,npub:i,pubkey:a,scheme:e.scheme,account:r.account,from:c,path:`${c} · ${Pp(e,r.account)}`}}function pl(e,t,n){const r=cn(e,t,n);if(!r)return null;const s=$e(e,t,n),o=lp(r.mnemonic,r.account);return{taproot:{address:s.wallet.address,path:Pp(e,r.account)},segwit:{address:As.p2wpkh.fromPubKey(o,"regtest"),path:rt.segwit(r.account)},tapkey:{address:As.p2tr.fromPubKey(a$(s.pubkey),"regtest"),path:rt.nostr(r.account)},npub:{address:s.npub,path:rt.nostr(r.account)},ethereum:{address:ek(r.mnemonic,r.account),path:rt.ethereum(r.account)}}}function l$(e,t,n){const r=cn(e,t,n);if(!r)return null;const s=$e(e,t,n),o=pl(e,t,n),{mnemonic:i,account:a}=r;return{keys:{taproot:o.taproot.address,segwit:o.segwit.address,nostr:o.npub.address,ethereum:o.ethereum.address},secrets:{taproot:s.wallet.secret,segwit:al(i,a),nostr:Si(i,a),ethereum:dp(i,a)}}}function Ii(e,t,n){const r=an(e.chain,n);if(!r)return null;const s=Se(r.scriptPubKey),o=t.nodes.get(n),i=$e(e.keys,t,o),a=o&&$e(e.keys,t,t.nodes.get(o.parent));return i&&Se(i.wallet.script)===s?{wallet:i.wallet,who:"own"}:e.wallet&&Se(e.wallet.script)===s?{wallet:e.wallet,who:"lab"}:a&&Se(a.wallet.script)===s?{wallet:a.wallet,who:"parent"}:{wallet:null,who:"other",script:s}}function Fn(e,t){const n=e.nodes.get(t),r=[n];for(const s of _r(e.nodes,n))s.status==="active"&&s.edge==="derived"&&r.push(...Fn(e,s.id));return r}function Ja(e,t){const n=[];for(let r=t;r;r=e.nodes.get(r.parent))n.push(r.name);return n.join(".")}function u$(e,t,n){const r=cn(e,t,n);if(!r)return null;if(n.kind!=="agent")return t$(Qk(il(r.mnemonic)),Ja(t,n));const s=Ja(t,t.nodes.get(n.parent));return e$(Jk(Si(r.mnemonic,r.account)),`${n.name}@${s}`,n.name,s)}const f$=tp(Ae),xs=(e,t=239)=>f$.encode(le(Uint8Array.of(t),bt(e),Uint8Array.of(1))),d$=e=>mr.encode("nsec",mr.toWords(bt(e))),h$="0123456789()[],'/*abcdefgh@:$%{}IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ",p$=[0xf5dee51989n,0xa9fdca3312n,0x1bab10e32dn,0x3706b1677an,0x644d626ffdn];function ya(e){const t=(i,a)=>{const c=i>>35n;return i=(i&0x7ffffffffn)<<5n^BigInt(a),p$.forEach((l,f)=>{c>>BigInt(f)&1n&&(i^=l)}),i};let n=1n,r=0,s=0;for(const i of e){const a=h$.indexOf(i);if(a<0)throw new Error("Invalid descriptor character.");n=t(n,a&31),r=r*3+(a>>5),++s===3&&(n=t(n,r),r=0,s=0)}s&&(n=t(n,r));for(let i=0;i<8;i++)n=t(n,0);n^=1n;let o="";for(let i=0;i<8;i++)o+="qpzry9x8gf2tvdw0s3jn54khce6mua7l"[Number(n>>BigInt(5*(7-i))&31n)];return`${e}#${o}`}function g$(e,t,n){const r=cn(e,t,n);if(!r)return null;const s=Si(r.mnemonic,r.account),o=Fa(r.mnemonic,r.account),i={bip86:`tr(${xs(o)})`,tapkey:`tr(${xs(s)})`,wallet:`rawtr(${xs(o)})`}[e.scheme],a=n.kind==="agent",c=Ja(t,a?t.nodes.get(n.parent):n);return{seed:a&&n.edge!=="adopted"?null:{from:[r.origin,...r.steps].join(" › "),mnemonic:r.mnemonic},account:[["nsec","NIP-06",d$(s)],["taproot","descriptor",ya(i)],["segwit","descriptor",ya(`wpkh(${xs(al(r.mnemonic,r.account))})`)],["tapkey","descriptor",ya(`tr(${xs(s)})`)],["ethereum","private key",`0x${dp(r.mnemonic,r.account)}`]],leaves:a?s$(s,`${n.name}@${c}`):o$(il(r.mnemonic),c)}}const Kr=1e8,Ge=50*Kr,we=330,Up=e=>(e/Kr).toFixed(8).replace(/\.?0+$/,""),Y=e=>`${Up(e)} tBTC`;function gl(e){if(e<1e6)return Y(e);const t=Math.round(e/1e6)*1e6;return`${t===e?"":"≈"}${Y(t)}`}function Ci(e){const t=/^\s*(\d{0,7})(?:\.(\d{0,8}))?\s*$/.exec(String(e??""));return!t||!(t[1]||t[2])?null:Number(t[1]||0)*Kr+Number((t[2]??"").padEnd(8,"0"))}class ml{constructor(t,n,r){this.secret=t,this.pubkey=n,this.path=r,this.address=As.p2wpkh.fromPubKey(n,"regtest"),this.script=As.toScriptPubKey(this.address)}sign(t,n){return[lr.segwit.sign(this.secret,t,n,{pubkey:this.pubkey}).hex,this.pubkey]}}const wa=new Map;function xe(e,t,n){const r=cn(e,t,n);if(!r)return null;const s=`${r.mnemonic}|${r.account}`;return wa.has(s)||wa.set(s,new ml(al(r.mnemonic,r.account),lp(r.mnemonic,r.account),rt.segwit(r.account))),wa.get(s)}function m$(e,t,n){var s;const r=n?t.nodes.get(n):null;return r&&r.root===r.id&&r.status==="active"?((s=xe(e,t,r))==null?void 0:s.script)??null:null}const Mr=(e,t)=>{var n,r;return((r=(n=e.mining)==null?void 0:n.rigs)==null?void 0:r[t])??1};function Np(e,t,n){if((e.asks??[]).some(o=>o.lot===n.id&&!o.taken&&e.chain.utxos.has(`${o.holder.txid}:${o.holder.vout}`)))return!0;const r=an(e.chain,n.id),s=$e(e.keys,t,n);return!!r&&!!s&&Se(r.scriptPubKey)!==Se(s.wallet.script)}function yl(e,t){var n;return((n=e.mining)==null?void 0:n.rule)==="none"?[]:t.roots.filter(r=>r.status==="active"&&Mr(e,r.id)>0&&xe(e.keys,t,r)&&!Np(e,t,r)).slice(0,kp)}function Lp(e,t,n){var i,a;if(((i=e.mining)==null?void 0:i.rule)==="none")return null;if(((a=e.mining)==null?void 0:a.rule)==="last"){const c=n?t.nodes.get(n):null,l=c&&!Np(e,t,c)?m$(e.keys,t,n):null;return l?[{script:l,value:Ge}]:null}const r=yl(e,t),s=r.reduce((c,l)=>c+Mr(e,l.id),0);let o=Ge;return r.length?r.map((c,l)=>{const f=l===r.length-1?o:Math.floor(Ge*Mr(e,c.id)/s);return o-=f,{script:xe(e.keys,t,c).script,value:f}}):null}function yr(e,t,n=xt){const r=t+W,s=l=>l===r||l-r>=we&&l-r<=Ge,o=[...e].sort((l,f)=>l.value-f.value),i=o.find(l=>s(l.value));if(i||n<2)return i?[i]:null;let a=null;for(let l=0;le.reduce((t,n)=>t+n.value,0);function bl(e,t=xt){let n=0,r=-W;for(const s of e.map(o=>o.value).sort((o,i)=>i-o).slice(0,t)){r+=s;const o=r<=Ge?r:r-Ge>=we?Ge:r-we;o>=we&&r-o<=Ge&&(n=Math.max(n,o))}return n}function xl(e,t,n,r=xt,s="send"){const o=wl(t),i=n+W,a=bl(t,r),c=`${s[0].toUpperCase()}${s.slice(1)}`;if(od.value).sort((d,h)=>h-d),f=l.slice(0,r).map((d,h)=>l.slice(0,h+1).reduce((g,p)=>g+p,0)),u=Math.min(...[...l,...l.flatMap((d,h)=>l.slice(h+1).map(g=>d+g)),...f].filter(d=>d>=i));return Number.isFinite(u)&&u-inew Set((e.offers??[]).flatMap(t=>t.payers.map(n=>`${n.txid}:${n.vout}`))),Hp=(e,t)=>e.chain.coins(t.script).filter(n=>{var r;return!((r=n.inscriptions)!=null&&r.length)}),Rp=(e,t,n=xt)=>!!yr(e,t,n),jp=(e,t,n)=>Rp(Hp(e,t),n);function kl(e,t,n,r,s="This node",o="send"){const i=Hp(e,t),a=vl(e),c=yr(i.filter(d=>!a.has(`${d.txid}:${d.vout}`)),r)??yr(i,r);if(!c)throw new Error(xl(s,i,r,xt,o));const l=wl(c)-r-W,f=X.create({vin:c.map(d=>Fe(d.txid,d.vout,d.value,d.scriptPubKey)),vout:[de(r,n),...l?[de(l,t.script)]:[]]});c.forEach((d,h)=>{f.vin[h].witness=t instanceof ml?t.sign(f,h):[t.sign(f,void 0,h)]});const u=X.encode(f).hex;return e.chain.submitPackage([u]),X.util.getTxid(u)}function Kp(e,t,n,r,s){const o=t.nodes.get(n),i=t.nodes.get(r);if(!o||!i)throw new Error("Pick who sends and who receives.");if(o.id===i.id)throw new Error(`${o.name} cannot send to itself.`);for(const l of[o,i])if(l.status!=="active")throw new Error(`${l.name} is ${l.status}.`);const a=xe(e.keys,t,o),c=xe(e.keys,t,i);if(!a||!c)throw new Error("A holding that predates lab keys has no SegWit addresses.");if(!Number.isSafeInteger(s)||sGe)throw new Error("Send at most 50 test BTC at a time: no output on this chain is bigger than one block reward.");return kl(e,a,c.script,s,o.name)}function y$(e,t,n){if(!t||!n||Se(t.script)===Se(n.script))return 0;let r=0;for(const s of e.chain.coins(t.script)){if(s.value-W{var l;return r||!((l=c.inscriptions)!=null&&l.length)}).sort((c,l)=>l.value-c.value);let o=[],i=0;const a=()=>{const c=o.reduce((l,f)=>l+f.value,0);if(o.length&&c-W>=we){const l=X.create({vin:o.map(f=>Fe(f.txid,f.vout,f.value,f.scriptPubKey)),vout:[de(c-W,n)]});o.forEach((f,u)=>{l.vin[u].witness=r?t.sign(l,u):[t.sign(l,void 0,u)]}),e.chain.submitPackage([X.encode(l).hex]),i++}o=[]};for(const c of s)(o.length===xt||o.reduce((l,f)=>l+f.value,0)+c.value-W>Ge)&&a(),o.push(c);return a(),i}const Mp=(e,t)=>[t,...t.log.flatMap((n,r)=>n.ok&&n.rekeys?[Dt(e.slice(0,r),{pending:!0})]:[])];function Dp(e,t){const n=new Map;for(const r of e)for(const s of r.nodes.values()){const o=t(r,s);o&&!n.has(o)&&n.set(o,s.id)}return n}const w$=(e,t,n)=>Dp(Mp(t,n),(r,s)=>{const o=xe(e,r,s);return o&&Se(o.script)}),ba=new Map,b$=(e,t,n)=>Dp(Mp(t,n),(r,s)=>{const o=cn(e,r,s),i=o&&`${e.scheme}|${o.mnemonic}|${o.account}`;return i&&!ba.has(i)&&ba.set(i,Se($e(e,r,s).wallet.script)),i?ba.get(i):null}),$l=(e,t)=>e.coins(t.script).filter(n=>{var r;return!((r=n.inscriptions)!=null&&r.length)}).reduce((n,r)=>n+r.value,0),Vu=new WeakMap,xa=new WeakMap;function qu(e,t){let n=Vu.get(t);if(!n){n=new Map;for(const r of t.nodes.values()){const s=$e(e,t,r),o=s&&Se(s.wallet.script);o&&!n.has(o)&&n.set(o,{node:r.id,wallet:s.wallet})}Vu.set(t,n)}return n}function Pi(e,t,n,r){const s=qu(e,n).get(r);if(s)return s;xa.has(n)||xa.set(n,n.log.flatMap((o,i)=>o.ok&&o.rekeys?[{i,state:null}]:[]));for(const o of xa.get(n)){o.state??(o.state=Dt(t.slice(0,o.i),{pending:!0}));const i=qu(e,o.state).get(r);if(i)return i}return null}function x$(e,t,n=new Map,r=new Map){var a,c;const s=[],o=l=>t.get(Se(l))??null,i=l=>l.reduce((f,u)=>f+u.value,0);for(const{txid:l,tx:f,height:u,coinbase:d}of e.transactions.values()){const h=f.vout.map($=>({script:Se($.scriptPubKey),node:o($.scriptPubKey),value:Number($.value)}));if(d){h.forEach(($,x)=>{$.node&&s.push({kind:"mine",key:`${l}:${x}`,txid:l,beat:u,from:null,to:$.node,amount:$.value,fee:0,change:0})});continue}const g=f.vin.map($=>{var C,P;const x=((C=e.transactions.get($.txid))==null?void 0:C.tx.vout[$.vout])??((P=e.imported)==null?void 0:P.call(e,$.txid,$.vout));return x?{node:o(x.scriptPubKey),tank:n.get(Se(x.scriptPubKey))??null,value:Number(x.value)}:null}),p=r.get(l);if(p!=null&&p.prep)continue;if(p!=null&&p.ask){s.push({kind:"deal",key:l,txid:l,beat:u,from:p.buyer,to:p.seller,amount:p.price,item:p.item,fee:2*W,change:0,ask:!0});continue}if(p&&g.length>1&&g[0]&&g.slice(((a=p.holders)==null?void 0:a.length)??1).every($=>($==null?void 0:$.node)===p.buyer)){s.push({kind:"deal",key:l,txid:l,beat:u,from:p.buyer,to:p.seller,amount:p.price,item:p.item,fee:i(g)-i(h),change:i(h.filter($=>$.node===p.buyer))});continue}if(g.every($=>$&&!$.node)){const $=h.filter(C=>C.node),x=g[0].tank&&g.every(C=>C.tank===g[0].tank)?g[0].tank:null;$.length&&x?s.push({kind:"pay",key:l,txid:l,beat:u,from:x,to:$[0].node,amount:$[0].value,fee:i(g)-i(h),change:0}):$.length&&s.push({kind:"fund",key:l,txid:l,beat:u,from:null,to:$[0].node,amount:$[0].value,fee:i(g)-i(h),change:i(h.filter(C=>!C.node))});continue}const m=(c=g[0])==null?void 0:c.node;if(!m||!g.every($=>($==null?void 0:$.node)===m))continue;const w=h.filter($=>$.node!==m),y=h.filter($=>$.node===m),b=i(g)-i(h),_={key:l,txid:l,beat:u,from:m,fee:b};w.length&&w.every($=>n.get($.script)===m)?s.push({..._,kind:"gas",to:m,amount:i(w),change:i(y)}):w.length?s.push({..._,kind:"pay",to:w[0].node,amount:w[0].value,change:i(y)}):s.push({..._,kind:"move",to:m,amount:i(y),change:0})}return s}function Qa(e,t,n=1/0){const r=new Map;for(const{txid:o,tx:i,height:a,coinbase:c}of e.transactions.values())if(!(a===null?n!==1/0:a>n)){if(!c)for(const l of i.vin)r.delete(`${l.txid}:${l.vout}`);i.vout.forEach((l,f)=>{const u=t.get(Se(l.scriptPubKey));u&&r.set(`${o}:${f}`,{node:u,value:Number(l.value)})})}const s=new Map;for(const{node:o,value:i}of r.values())s.set(o,(s.get(o)??0)+i);return s}const ec="lineage-offer",tc="lineage-ask",Et=600,ci=xt-1,li=/^[0-9a-f]{64}$/,Mn=/^[0-9a-f]{64}i0$/,ui=/^5120[0-9a-f]{64}$/,nc=/^0014[0-9a-f]{40}$/,v$=/^[0-9a-f]{128}83$/,k$="0".repeat(64),rc=e=>({txid:e.txid,vout:e.vout,value:e.value,script:Se(e.scriptPubKey)}),sc=(e,t)=>!e.utxos.has(`${t.txid}:${t.vout}`),Zs=e=>{const t=Sr(new Vn(e.chain));return{events:t,state:Dt(t,{pending:!0})}},El=e=>`${e[0].toUpperCase()}${e.slice(1)}`,Ss=e=>e.reduce((t,n)=>t+n.value,0),$$=e=>Fe(e.txid,e.vout,e.value,e.scriptPubKey);function Ui(e,t,n){var s,o;const r=n?(s=xe(e.keys,t,n))==null?void 0:s.script:(o=e.wallet)==null?void 0:o.script;return r?Se(r):null}function Zp(e){return X.create({vin:[...e.holders,...e.payers].map(t=>Fe(t.txid,t.vout,t.value,t.script)),vout:[de(Ss(e.holders),e.to),...e.price?[de(e.price,e.pay)]:[],...e.change?[de(e.change,e.back)]:[]]})}function Dn(e,t,n,r){const s=an(e.chain,r),o=s&&Pi(e.keys,t,n,Se(s.scriptPubKey));return o?{coin:s,node:n.nodes.get(o.node),wallet:o.wallet}:null}function Zn(e,t,n,r){const s=n.items.get(r)??null,o=s?null:n.nodes.get(r)??null;if(!s&&!o)return null;const i=Dn(e,t,n,r),a=s?(i==null?void 0:i.node)??null:o.root===o.id?null:n.nodes.get(o.parent)??null;return{id:r,name:(s??o).name,item:s,node:o,holder:i,seller:a}}function wr(e,t,n,r){var l;if(!(r!=null&&r.holder))return{nodes:[],coins:[],layout:[]};if(r.item)return{nodes:[],coins:[r.holder.coin],layout:[]};const s=Fn(n,r.node.id),o=new Set(s.map(f=>f.id)),i=new Map,a=[],c=f=>{f&&!i.has(`${f.txid}:${f.vout}`)&&i.set(`${f.txid}:${f.vout}`,f)};for(const f of s)c(an(e.chain,f.id));for(const f of n.items.keys()){const u=Dn(e,t,n,f);u&&o.has(u.node.id)&&(c(u.coin),a.push([f,u.node.id]))}return{nodes:s,coins:[...i.values()],layout:((l=Ni(e,n,r.id))==null?void 0:l.layout)??a}}function Sl(e,t,n,r,s=wr(e,t,n,r)){var f;if(!r.holder)return`no node in this lab holds ${r.name}`;const o=r.holder.coin.inscriptions.map(u=>n.nodes.get(u.id)).find(Boolean);if(o&&o.id!==r.id)return`${r.name} goes with ${o.name}'s tree while it changes hands`;if(r.item)return"";const i=Zt(n.nodes,r.node);if(i)return i;if(r.holder.node.id!==r.node.id)return`${r.name} is held by ${r.holder.node.name}`;const a=new Set(s.nodes.map(u=>u.id)),c=u=>{const d=Ni(e,n,u);return d?Y(d.price):""};for(const u of s.nodes.slice(1)){if(c(u.id))return`${u.name} is listed on its own at ${c(u.id)}. Withdraw its ask first`;const d=Dn(e,t,n,u.id);if(!d||!a.has(d.node.id))return`${u.name} is held by ${(d==null?void 0:d.node.name)??"no node in this lab"}`}for(const[u]of s.layout)if(c(u))return`${n.items.get(u).name} is listed on its own at ${c(u)}. Withdraw its ask first`;for(const u of s.nodes){const d=(f=$e(e.keys,n,u))==null?void 0:f.wallet,h=d&&e.chain.coins(d.script).flatMap(g=>g.inscriptions??[]).map(g=>n.nodes.get(g.id)).find(g=>g&&!a.has(g.id));if(h)return`${u.name} holds ${h.name}, which it bought, and adopts it first`}const l=s.coins.reduce((u,d)=>u+new Set(d.inscriptions.map(h=>Bn(d.ranges,h.sat))).size,0);return l>ci?`${r.name}'s tree holds ${l} inscribed sats, and one deal carries ${ci} at most`:""}function Vp(e,t,n,r){var a;const s=n.nodes.get(r),o=(s==null?void 0:s.status)==="active"?Dn(e,t,n,r):null;if(!o)return null;for(let c=s;c;c=c.edge==="derived"?n.nodes.get(c.parent):null)if(c.id===o.node.id)return null;const i=s.edge==="derived"?n.nodes.get(s.parent):null;return i&&((a=Dn(e,t,n,i.id))==null?void 0:a.node.id)===o.node.id?null:o.node}function qp(e,t,n,r,s=Date.now()){const{events:o,state:i}=Zs(e),a=Zn(e,o,i,t),c=i.nodes.get(n);if(!a)throw new Error("Pick an item, an org or a holding to make an offer on.");if(!c)throw new Error("Pick who makes the offer.");if(!Number.isSafeInteger(r)||r<0||r>0&&rGe)throw new Error("Offer at most 50 test BTC: no output on this chain is bigger than one block reward.");const l=wr(e,o,i,a),f=Sl(e,o,i,a,l)||(a.node?Zt(i.nodes,a.node,c):"");if(f)throw new Error(`${El(f)}.`);const u=a.seller;if((u==null?void 0:u.id)===c.id)throw new Error(`${c.name} already holds ${a.name}.`);for(const $ of[c,u])if($&&$.status!=="active")throw new Error(`${$.name} is ${$.status}.`);const d=xe(e.keys,i,c),h=Ui(e,i,u),g=$e(e.keys,i,c);if(!d||!h||!g)throw new Error("A holding that predates lab keys cannot trade.");if((e.offers??[]).some($=>$.item===t&&$.buyer===c.id&&Ao(e,i,$,o)==="open"))throw new Error(`${c.name} already has an open offer on ${a.name}. Withdraw it first.`);const p=e.chain.coins(d.script),m=vl(e),w=xt-l.coins.length,y=yr(p.filter($=>!m.has(`${$.txid}:${$.vout}`)),r,w)??yr(p,r,w);if(!y)throw new Error(xl(c.name,p,r,w,"offer"));const b={kind:ec,version:1,item:t,buyer:c.id,seller:(u==null?void 0:u.id)??null,price:r,holders:l.coins.map($=>({...rc($),ids:$.inscriptions.map(x=>x.id)})),layout:l.layout,payers:y.map(rc),to:Se(g.wallet.script),pay:h,back:Se(d.script),change:Ss(y)-r-W,at:s},_=Zp(b);return b.txid=X.util.getTxid(_),b.witnesses=y.map(($,x)=>d.sign(_,b.holders.length+x)),(e.offers??(e.offers=[])).push(b),b}function _l(e,t,n,r=null){var d,h,g;const s=t.nodes.get(n.item),o=(s==null?void 0:s.name)??((d=t.items.get(n.item))==null?void 0:d.name)??"the item",i=p=>{var m,w;return((m=t.nodes.get(p))==null?void 0:m.name)??((w=t.items.get(p))==null?void 0:w.name)??null},a=p=>p?Se(p.script):"",c=n.holders.find(p=>sc(e.chain,p));if(c===n.holders[0])return s?`${o}'s inscription has moved since`:`${o} has moved since`;if(c){const p=(h=c.ids)==null?void 0:h.find(m=>i(m));return`${p?t.nodes.has(p)?`${i(p)}'s inscription`:i(p):`something in ${o}'s tree`} has moved since`}if(n.payers.some(p=>sc(e.chain,p)))return`${i(n.buyer)??"the buyer"} has spent a coin the offer promised`;for(const p of[n.buyer,n.seller]){const m=p&&t.nodes.get(p);if(p&&(m==null?void 0:m.status)!=="active")return`${(m==null?void 0:m.name)??"a node"} is ${(m==null?void 0:m.status)??"gone"}`}const l=t.nodes.get(n.buyer),f=n.seller?t.nodes.get(n.seller):null;if(s&&f&&s.parent!==f.id)return`${o} is no longer ${f.name}'s`;if(s&&!f&&s.root!==s.id)return`${o} is no longer a holding`;const u=s?Zt(t.nodes,s,l):"";if(u)return u;if(a((g=$e(e.keys,t,l))==null?void 0:g.wallet)!==n.to||a(xe(e.keys,t,l))!==n.back)return`${l.name} has new keys since`;if(n.price&&Ui(e,t,f)!==n.pay)return f?`${f.name} has new keys since`:"the lab wallet has changed since";if(s){const p=r??Sr(new Vn(e.chain)),m=wr(e,p,t,Zn(e,p,t,n.item)).coins,w=new Set(n.holders.map(y=>`${y.txid}:${y.vout}`));if(m.length!==w.size||m.some(y=>!w.has(`${y.txid}:${y.vout}`)))return`${o}'s tree has changed since`}return""}const Ao=(e,t,n,r=null)=>e.chain.transactions.has(n.txid)?"done":_l(e,t,n,r)?"stale":"open";function E$(e,t,n=null){var f;const r=(e.offers??[]).find(u=>u.txid===t);if(!r)throw new Error("That offer is gone.");if(e.chain.transactions.has(r.txid))throw new Error("That offer was already accepted.");const{events:s,state:o}=Zs(e),i=_l(e,o,r,s);if(i)throw new Error(`This offer is stale: ${i}.`);const a=Zn(e,s,o,r.item);if(!a||(((f=a.seller)==null?void 0:f.id)??null)!==r.seller||Sl(e,s,o,a))throw new Error("Only the holder can accept.");n==null||n(o,a);const c=Zp(r),l=r.holders.length;return r.witnesses.forEach((u,d)=>{c.vin[l+d].witness=u}),r.holders.forEach((u,d)=>{c.vin[d].witness=[Pi(e.keys,s,o,u.script).wallet.sign(c,void 0,d)]}),e.chain.submitPackage([X.encode(c).hex]),r}function S$(e,t){const n=(e.offers??[]).find(r=>r.txid===t);if(!n)throw new Error("That offer is gone.");if(e.chain.transactions.has(n.txid))throw new Error("That offer was accepted: it is on the chain now.");return e.offers=e.offers.filter(r=>r!==n),n}const Ar=e=>`${e.holder.txid}:${e.holder.vout}`,_$=e=>X.create({vin:[Fe(k$,0,Et,e.pay),Fe(e.holder.txid,e.holder.vout,e.holder.value,e.holder.script)],vout:[de(Et+e.holder.value,e.holder.script),de(e.price,e.pay)]});function A$(e,t,n,r=Date.now(),s=null){var m;let{events:o,state:i}=Zs(e),a=Zn(e,o,i,t);if(!a)throw new Error("Pick an item, an org or a holding to sell.");if(!Number.isSafeInteger(n)||nGe-W)throw new Error(`Ask at most ${Y(Ge-W)}: the buyer funds the price and its fee in one output.`);const c=wr(e,o,i,a),l=Sl(e,o,i,a,c);if(l)throw new Error(`${El(l)}.`);const f=a.seller,u=Ui(e,i,f);if(f&&f.status!=="active")throw new Error(`${f.name} is ${f.status}.`);if(!u||!((m=a.holder.wallet)!=null&&m.secret))throw new Error("A holding that predates lab keys cannot trade.");const d=Ni(e,i,t);if(d)throw new Error(`${a.name} is already listed at ${Y(d.price)}. Withdraw that ask first.`);s==null||s(i,a,c),{events:o,state:i}=Zs(e),a=Zn(e,o,i,t);const[h,...g]=wr(e,o,i,a).coins;if(!h||g.length)throw new Error(`${a.name}'s tree is not in one coin at its key.`);const p={kind:tc,version:1,lot:t,seller:(f==null?void 0:f.id)??null,price:n,holder:{...rc(h),ids:h.inscriptions.map(w=>w.id)},layout:c.layout,pay:u,at:r,taken:null};return p.sig=lr.taproot.sign(a.holder.wallet.secret,_$(p),1,{sigflag:131}).hex,(e.asks??(e.asks=[])).push(p),p}function Al(e,t,n){var i;const r=t.nodes.get(n.lot),s=(r==null?void 0:r.name)??((i=t.items.get(n.lot))==null?void 0:i.name)??"the item",o=n.seller?t.nodes.get(n.seller):null;return sc(e.chain,n.holder)?r?`${s}'s inscription has moved since`:`${s} has moved since`:n.seller&&(o==null?void 0:o.status)!=="active"?`${(o==null?void 0:o.name)??"the seller"} is ${(o==null?void 0:o.status)??"gone"}`:Ui(e,t,o)!==n.pay?o?`${o.name} has new keys since`:"the lab wallet has changed since":r&&o&&r.parent!==o.id?`${s} is no longer ${o.name}'s`:r&&!o&&r.root!==r.id?`${s} is no longer a holding`:r?Zt(t.nodes,r):""}const Bl=(e,t,n)=>n.taken&&e.chain.transactions.has(n.taken.txid)?"done":Al(e,t,n)?"stale":"open",Ni=(e,t,n)=>(e.asks??[]).find(r=>r.lot===n&&Bl(e,t,r)==="open")??null;function B$(e,t,n,r=Date.now()){const s=(e.asks??[]).find(C=>Ar(C)===t);if(!s)throw new Error("That ask is gone.");if(s.taken)throw new Error("That ask was already taken.");const{state:o}=Zs(e),i=Al(e,o,s),a=o.nodes.get(n);if(i)throw new Error(`This ask is stale: ${i}.`);if(!a)throw new Error("Pick who takes the ask.");if(a.status!=="active")throw new Error(`${a.name} is ${a.status}.`);if(a.id===s.seller)throw new Error(`${a.name} is the seller.`);const c=o.nodes.get(s.lot),l=c?Zt(o.nodes,c,a):"";if(l)throw new Error(`${El(l)}.`);const f=xe(e.keys,o,a),u=$e(e.keys,o,a);if(!f||!u)throw new Error("A holding that predates lab keys cannot trade.");const d=e.chain.coins(f.script),h=vl(e),g=Et+s.price+W,p=yr(d.filter(C=>!h.has(`${C.txid}:${C.vout}`)),g)??yr(d,g);if(!p)throw Ss(d){y.vin[P].witness=f.sign(y,P)});const b=X.encode(y).hex,_=X.util.getTxid(b),$=X.create({vin:[Fe(_,0,Et,w),Fe(s.holder.txid,s.holder.vout,s.holder.value,s.holder.script),Fe(_,1,s.price+W,w)],vout:[de(Et+s.holder.value,u.wallet.script),de(s.price,s.pay)]});$.vin[1].witness=[s.sig],$.vin[0].witness=f.sign($,0),$.vin[2].witness=f.sign($,2);const x=X.encode($).hex;return e.chain.submitPackage([b,x]),s.taken={txid:X.util.getTxid(x),prep:_,buyer:a.id,at:r},s}function zu(e,t){const n=(e.asks??[]).find(r=>Ar(r)===t);if(!n)throw new Error("That ask is gone.");if(n.taken)throw new Error("That ask was taken: it is on the chain now.");return e.asks=e.asks.filter(r=>r!==n),n}function T$(e){const t=(e.asks??[]).filter(n=>n.taken).flatMap(n=>[[n.taken.txid,{ask:!0,buyer:n.taken.buyer,seller:n.seller,price:n.price,item:n.lot,ids:n.holder.ids??[n.lot]}],[n.taken.prep,{prep:!0}]]);return new Map([...(e.offers??[]).map(n=>[n.txid,n]),...t])}const oc=(e,t)=>e&&li.test(e.txid)&&Number.isSafeInteger(e.vout)&&e.vout>=0&&Number.isSafeInteger(e.value)&&e.value>=we&&e.value<=Ge&&t.test(e.script),zp=e=>e===void 0||Array.isArray(e)&&e.length<=1024&&e.every(t=>Mn.test(t)),Fp=e=>e===void 0||Array.isArray(e)&&e.length<=ci&&e.every(t=>Array.isArray(t)&&t.length===2&&Mn.test(t[0])&&Mn.test(t[1])),Wp=(e,t)=>e===null?ui.test(t):Mn.test(e)&&nc.test(t);function O$(e){const t=r=>Number.isSafeInteger(r)&&(r===0||r>=we&&r<=Ge),n=Array.isArray(e==null?void 0:e.holders)?e.holders:e!=null&&e.holder?[e.holder]:[];if((e==null?void 0:e.kind)!==ec||e.version!==1||!Mn.test(e.item)||!Mn.test(e.buyer)||!Wp(e.seller,e.pay)||e.buyer===e.seller||!t(e.price)||!t(e.change)||!n.length||n.length>ci||!n.every(r=>oc(r,ui)&&zp(r.ids))||!Array.isArray(e.payers)||!e.payers.length||n.length+e.payers.length>xt||!e.payers.every(r=>oc(r,nc))||!ui.test(e.to)||!nc.test(e.back)||!Fp(e.layout)||!li.test(e.txid)||!Array.isArray(e.witnesses)||e.witnesses.length!==e.payers.length||!e.witnesses.every(r=>Array.isArray(r)&&r.length===2&&/^30[0-9a-f]{12,140}01$/.test(r[0])&&/^0[23][0-9a-f]{64}$/.test(r[1]))||!Number.isSafeInteger(e.at))throw new Error("Invalid offer.");return{kind:ec,version:1,item:e.item,buyer:e.buyer,seller:e.seller,price:e.price,holders:n.map(r=>({txid:r.txid,vout:r.vout,value:r.value,script:r.script,...r.ids?{ids:[...r.ids]}:{}})),layout:(e.layout??[]).map(r=>[...r]),payers:e.payers.map(r=>({...r})),to:e.to,pay:e.pay,back:e.back,change:e.change,at:e.at,txid:e.txid,witnesses:e.witnesses.map(r=>[...r])}}function I$(e){const t=e==null?void 0:e.taken;if((e==null?void 0:e.kind)!==tc||e.version!==1||!Mn.test(e.lot)||!Wp(e.seller,e.pay)||!Number.isSafeInteger(e.price)||e.priceGe-W||!oc(e.holder,ui)||!zp(e.holder.ids)||!Fp(e.layout)||typeof e.sig!="string"||!v$.test(e.sig)||!Number.isSafeInteger(e.at)||!(t===null||t&&li.test(t.txid)&&li.test(t.prep)&&Mn.test(t.buyer)&&Number.isSafeInteger(t.at)))throw new Error("Invalid ask.");return{kind:tc,version:1,lot:e.lot,seller:e.seller,price:e.price,holder:{txid:e.holder.txid,vout:e.holder.vout,value:e.holder.value,script:e.holder.script,...e.holder.ids?{ids:[...e.holder.ids]}:{}},layout:(e.layout??[]).map(n=>[...n]),pay:e.pay,at:e.at,sig:e.sig,taken:t?{txid:t.txid,prep:t.prep,buyer:t.buyer,at:t.at}:null}}const Li="orgchain:lab:v1",C$=["each",10,30,60,"manual"];function eo(e={tempo:"each",nextAt:null}){const{tempo:t,nextAt:n}=e??{},r=typeof t=="number";if(!C$.includes(t)||!(n===null||r&&Number.isSafeInteger(n)&&n>0))throw new Error("Invalid clock.");return{tempo:t,nextAt:n}}function Gp(e){const t=hl();for(const n of["roots","adopted"])for(const[r,s]of Object.entries((e==null?void 0:e[n])??{})){if(!/^[0-9a-f]{64}i0$/.test(r))throw new Error("Invalid lab keys.");t[n][r]=cp(s,24)}if(t.scheme=(e==null?void 0:e.scheme)??(Object.keys(t.roots).length?"wallet":"bip86"),!i$.includes(t.scheme))throw new Error("Invalid lab keys.");return t}const P$=["split","last","none"];function to(e){const t=(e==null?void 0:e.rule)??"split",n={};if(!P$.includes(t))throw new Error("Invalid mining rule.");for(const[r,s]of Object.entries((e==null?void 0:e.rigs)??{})){if(!/^[0-9a-f]{64}i0$/.test(r)||!Number.isSafeInteger(s)||s<0||s>9)throw new Error("Invalid hashrate.");s!==1&&(n[r]=s)}return{rule:t,rigs:n}}function Yp(e=[]){if(!Array.isArray(e)||e.length>1e3)throw new Error("Invalid offers.");const t=e.map(O$);if(new Set(t.map(n=>n.txid)).size!==t.length)throw new Error("Invalid offers.");return t}function Xp(e=[]){if(!Array.isArray(e)||e.length>1e3)throw new Error("Invalid asks.");const t=e.map(I$);if(new Set(t.map(Ar)).size!==t.length)throw new Error("Invalid asks.");return t}const no=()=>({wallet:null,chain:new Bi,clock:eo(),keys:hl(),mining:to(),offers:[],asks:[]});function Jp(e){if(!e)return no();const t=JSON.parse(e);if((t==null?void 0:t.kind)!=="orgchain-lab"||t.network!==On||t.version!==1)throw new Error("That is not an Orgchain v1 lab.");return{wallet:t.wallet?Kn.load(t.wallet):null,chain:new Bi(t.chain),clock:eo(t.clock),keys:Gp(t.keys),mining:to(t.mining),offers:Yp(t.offers),asks:Xp(t.asks)}}const Qp=e=>{var t;return JSON.stringify({kind:"orgchain-lab",network:On,version:1,wallet:((t=e.wallet)==null?void 0:t.backup())??null,chain:e.chain.snapshot(),clock:eo(e.clock),keys:Gp(e.keys),mining:to(e.mining),offers:Yp(e.offers),asks:Xp(e.asks)})};function U$(e,t,n){var r;e.mining=to({...e.mining,rigs:{...(r=e.mining)==null?void 0:r.rigs,[t]:n}})}function N$(e,t){e.mining=to({...e.mining,rule:t})}const Tl=()=>Jp(localStorage.getItem(Li));function L$(e){try{localStorage.setItem(Li,Qp(e))}catch{throw new Error("Browser storage is full or unavailable, so nothing was saved. Save a backup, then reset.")}}async function H$(e,{locks:t=(s=>(s=globalThis.navigator)==null?void 0:s.locks)(),read:n=Tl,save:r=L$}={}){if(!t)throw new Error("Orgchain needs Web Locks: open it over HTTPS or on localhost.");return t.request(Li,async()=>{const o=n(),i=await e(o);return i!==!1&&r(o),{lab:o,result:i}})}function at(e,t=null){e.wallet||(e.wallet=Kn.create());const n=t!=null&&t.length?e.chain.mineTo(t.map(r=>de(r.value,r.script))):e.chain.mine(e.wallet.script);return e.clock=eo({tempo:e.clock.tempo,nextAt:null}),n}function Ft(e,t=Date.now()){const{tempo:n,nextAt:r}=e.clock;typeof n=="number"&&e.chain.mempool.length&&r===null&&(e.clock={tempo:n,nextAt:t+n*1e3})}function R$(e,t,n=Date.now(),r=null){e.clock=eo({tempo:t,nextAt:null}),t==="each"&&e.chain.mempool.length?at(e,r):Ft(e,n)}function j$(e,t=Date.now(),n=null){const{tempo:r,nextAt:s}=e.clock;return typeof r!="number"||!e.chain.mempool.length?!1:s===null?(Ft(e,t),!0):tFe(e.txid,e.vout,e.value,e.scriptPubKey);function K$(e,{inscriber:t,holder:n,parent:r,on:s,value:o,metadata:i,metaprotocol:a}){const c=an(e,s),l=an(e,r);if(!c||!l)throw new Error("Both inscriptions must be unspent.");if(c===l)throw new Error("A belt goes on another node's sat.");const f=e.coins(t.script).find(b=>{var _;return!((_=b.inscriptions)!=null&&_.length)&&b.value>=ic+330});if(!f)throw new Error("The issuer needs a plain coin for the two fees.");const u=Bn(c.ranges,c.inscriptions.find(b=>b.id===s).sat),d=qc(t.pubkey,o,r,i,{pointer:u,metaprotocol:a}),h=ch(d),[g,p]=Fs.getPubKey(t.pubkey,{target:h}),m=X.create({vin:[va(f)],vout:[de(W,["OP_1",g]),de(f.value-ic,t.script)]});m.vin[0].witness=[t.sign(m)];const w=X.util.getTxid(m),y=X.create({vin:[va(c),va(l),Fe(w,0,W,["OP_1",g])],vout:[de(c.value,c.scriptPubKey),de(l.value,l.scriptPubKey)]});return y.vin[2].witness=[t.sign(y,h,2),Ce.encode(d,!1).hex,p],y.vin[1].witness=[t.sign(y,void 0,1)],y.vin[0].witness=[n.sign(y,void 0,0)],e.submitPackage([X.encode(m).hex,X.encode(y).hex]),`${X.util.getTxid(y)}i0`}const e0={reinscription:"♻️",vindicated:"❤️‍🔥"};function M$(e,t,n){const r=i=>{var l;const a=(l=e.transactions.get(i.id.slice(0,-2)))==null?void 0:l.tx;return(a?a.vin.findIndex(f=>{var u;return((u=f.witness)==null?void 0:u.length)===3}):0)>0||i.pointer!==void 0},s=t.events.find(i=>i.sat===n.sat),o=s&&s.id!==n.id;return[...o?["reinscription"]:[],...r(n)||o&&!r(s)?["vindicated"]:[]]}const Fu={found:["name"],birth:["name","kind"],award:["to","skill","belt"],decide:["title","why"],make:["name","note"],keyring:It,charter:["form","of","jurisdiction","legal","provider","filing"],graduate:["of"],close:[],join:["to"],adopt:["of"]},t0={found:e=>`found ${e.name}`,birth:e=>`birth ${e.name}`,award:e=>`award ${e.skill} ${e.belt}`,decide:e=>`decide ${e.title}`,make:e=>`make ${e.name}`,keyring:(e,t)=>_i(t,e),charter:e=>`charter ${e.form}${e.jurisdiction?` ${e.jurisdiction}`:""}`,graduate:()=>"graduate",close:()=>"close",join:()=>"join",adopt:()=>"adopt"};function D$(e,t={}){if(!Object.hasOwn(Fu,e))throw new Error("Unknown verb.");const n={op:e};for(const s of Fu[e]){const o=t[s];typeof o=="string"&&o.trim()&&(n[s]=o.trim())}const r=e==="keyring"&&t.proof&&typeof t.proof=="object"?t.proof:null;return r&&(n.proof=Object.fromEntries(It.filter(s=>typeof r[s]=="string").map(s=>[s,r[s]]))),n}function n0(e,t){const n=Re(e),r=n.nodes.get(t),s=r&&l$(e.keys,n,r);if(!s)throw new Error(`${(r==null?void 0:r.name)??"That node"} predates lab keys, so it has no keys to list.`);return hk(t,s.keys,s.secrets)}function Ol(e,t,n,r={}){if(t==="keyring"){for(let s=e.nodes.get(n);s;s=s.edge==="derived"?e.nodes.get(s.parent):null)if(s.graduated==="cued")return`${s.name}'s graduation is cued, and it changes ${s.id===n?"its":`${e.nodes.get(n).name}'s`} keys. Publish the keyring once it lands`}if(t==="graduate"&&e.nodes.has(r.of)){const s=new Set(Fn(e,r.of).map(i=>i.id)),o=e.log.find(i=>i.pending&&i.ok&&i.op==="keyring"&&s.has(i.node));if(o)return`${e.nodes.get(o.node).name}'s keyring is cued. Graduate ${e.nodes.get(r.of).name} once it lands, so the graduation retires it`}return""}const Re=e=>Dt(Sr(new Vn(e.chain)),{pending:!0}),Hi=e=>{const t=Sr(new Vn(e.chain));return{events:t,state:Dt(t,{pending:!0})}};function fi(e,t,n,r){var f;const s=D$(t,r),o=Sr(new Vn(e.chain)),i=t==="award"?(f=o.find(u=>u.id===s.to))==null?void 0:f.sat:void 0,a={id:"check",status:"pending",height:null,metadata:s,parent:n??null,protocol:Ai,sat:i},{ok:c,why:l}=Dt([...o,a],{pending:!0}).log.at(-1);if(!c)throw new Error(`${l[0].toUpperCase()}${l.slice(1)}.`);return s}const ac=Ht+2*W+330,r0=1e5,Ri=1e4,tn=(e,t=0)=>(e==="award"?ic:Ht+2*W+(e==="birth"||e==="join"?1:e==="graduate"?Math.max(0,t-1):0)*W)+330,Z$=(e,t=0)=>tn(e,t)-330,ln=(e,t,n)=>e.chain.coins(t.script).find(r=>{var s;return!((s=r.inscriptions)!=null&&s.length)&&r.value>=n}),ns=e=>Fe(e.txid,e.vout,e.value,e.scriptPubKey),ji=(e,t)=>(t.forEach((n,r)=>{e.vin[r].witness=[n.sign(e,void 0,r)]}),X.encode(e).hex);function ro(e){e.keys??(e.keys=hl()),e.wallet||(e.wallet=Kn.create()),ln(e,e.wallet,r0+W+330)||at(e)}function s0(e,t,n=ac,r=r0){if(t===e.wallet||ln(e,t,n))return;const s=ln(e,e.wallet,r+W+330),o=X.create({vin:[ns(s)],vout:[de(r,t.script),de(s.value-r-W,e.wallet.script)]});e.chain.submitPackage([ji(o,[e.wallet])])}function ar(e,t,n,r,s){if(r===e.wallet||ln(e,r,s))return;const o=n&&xe(e.keys,t,n);if(!o)return s0(e,r,s);kl(e,o,r.script,Math.max(Ri,s),n.name)}function Il(e,t,n,r,s){if(r===e.wallet||ln(e,r,s))return!0;const o=n&&xe(e.keys,t,n);return!o||jp(e,o,Math.max(Ri,s))}function Cl(e,t,n,r,s={}){var f,u;const o=r?t.nodes.get(r):null,i=o&&((f=Ii(e,t,r))==null?void 0:f.wallet);if(n==="found"||!i)return"";const a=n==="graduate"?t.nodes.get(s.of):null,c=a&&$e(e.keys,t,a)?Fn(t,a.id).length:0;if(!Il(e,t,o,i,tn(n,c))){const d=t.nodes.get(o.parent);return`${o.name} has no test BTC for gas. ${d?`${d.name} can send some`:((u=e.mining)==null?void 0:u.rule)==="none"?"Fund it from the lab wallet":"It earns some each beat it mines"}`}const l=c?xe(e.keys,t,a):null;return l&&!Rp(e.chain.coins(l.script).filter(d=>d.value-W>=we).map(d=>({value:d.value-W})),Ri)?`${a.name} needs test BTC of its own to claim its new root. Send it some first`:""}function Wu(e,t,n,r,s=n){const o=an(e.chain,t),i=ln(e,s,W+330),a=X.create({vin:[ns(o),ns(i)],vout:[de(o.value,r.script),de(i.value-W,s.script)]});e.chain.submitPackage([ji(a,[n,s])])}function di(e,t,n,r,s){return new p2(e.chain,t).inscribe(t0[n](s,r),r??null,s,{metaprotocol:Ai})}const Wn=(e,t)=>{var r;const n=Re(e);return Lp(e,n,((r=n.nodes.get(t))==null?void 0:r.root)??null)},Ki=(e,t)=>Lp(e,Re(e),t);function Pl(e){var r,s,o;const t=Re(e),n=new Map;for(const i of t.nodes.values())for(const a of[xe(e.keys,t,i),(r=$e(e.keys,t,i))==null?void 0:r.wallet])a&&n.set(Se(a.script),i.root);for(const i of[...e.chain.mempool].reverse()){const a=e.chain.transactions.get(X.util.getTxid(i));if(a!=null&&a.inscription){const c=(s=t.log.find(l=>l.id===a.inscription.id))==null?void 0:s.root;if(c)return c;continue}for(const c of(a==null?void 0:a.tx.vin)??[]){const l=((o=e.chain.transactions.get(c.txid))==null?void 0:o.tx.vout[c.vout])??e.chain.imported(c.txid,c.vout),f=l&&n.get(Se(l.scriptPubKey));if(f)return f}}return null}function rs(e,t,n){var s;const r=Ii(e,t,n);if(!(r!=null&&r.wallet))throw new Error(`No key in this lab holds ${((s=t.nodes.get(n))==null?void 0:s.name)??"that node"}'s inscription.`);return r.wallet}function o0(e,t,n,r){var u,d;if(t==="found"){const h=Bu(),g=c$(e.keys,h);s0(e,g,ac,ac);const p=di(e,g,t,null,r);return e.keys.roots[p]=h,p}const s=Re(e),o=rs(e,s,n),i=s.nodes.get(n),a=t==="graduate"?s.nodes.get(r.of):null,c=a&&$e(e.keys,s,a)?Fn(s,a.id).map(h=>[h.id,rs(e,s,h.id)]):[],l=t==="award"?(u=Ii(e,s,r.to))==null?void 0:u.wallet:null;if(t==="award"&&!l)throw new Error(`No key in this lab holds ${((d=s.nodes.get(r.to))==null?void 0:d.name)??"the recipient"}'s inscription, so it can't take a belt.`);ar(e,s,i,o,tn(t,c.length));const f=t==="award"?K$(e.chain,{inscriber:o,holder:l,parent:n,on:r.to,value:t0.award(r),metadata:r,metaprotocol:Ai}):di(e,o,t,n,r);if(t==="birth"){const h=Re(e),g=$e(e.keys,h,h.nodes.get(f));g&&Wu(e,f,o,g.wallet)}if(c.length){e.keys.adopted[f]=Bu();const h=Re(e);for(const[g,p]of c){const m=$e(e.keys,h,h.nodes.get(g)).wallet;if(y$(e,xe(e.keys,s,s.nodes.get(g)),xe(e.keys,h,h.nodes.get(g))),g!==a.id){Wu(e,g,p,m,o);continue}ar(e,h,h.nodes.get(g),m,W+330),Ok(e.chain,Tk(e.chain,g,m),p)}}return f}function V$(e,t,n,r,s=Date.now()){if(t==="join"||t==="adopt")throw new Error("An org or a holding changes hands through Sell and Buy, and its buyer adopts it.");const o=Vt(e,Re(e),t,n??null,r??{});if(o)throw new Error(`${o}.`);const i=Ol(Re(e),t,n??null,r??{});if(i)throw new Error(`${i}.`);const a=fi(e,t,n,t==="keyring"?n0(e,n):r),c=Cl(e,Re(e),t,n??null,a);if(c)throw new Error(`${c}.`);ro(e);const l=o0(e,t,n??null,a);return e.clock.tempo==="each"?at(e,Wn(e,n??l)):Ft(e,s),l}function q$(e,t,n,r,s=Date.now()){const o=Vt(e,Re(e),"send",t)||Vt(e,Re(e),"send",n);if(o)throw new Error(`${o}.`);const i=Kp(e,Re(e),t,n,r);return e.clock.tempo==="each"?at(e,Wn(e,t)):Ft(e,s),i}function z$(e,t,n,r,s=Date.now()){const o=Vt(e,Re(e),"offer",n);if(o)throw new Error(`${o}.`);return qp(e,t,n,r,s)}function F$(e,t,n=Date.now()){const r=E$(e,t,(s,o)=>{o.node&&i0(e,s,o)});return e.clock.tempo==="each"?at(e,Wn(e,r.seller??r.item)):Ft(e,n),r}const W$=(e,t)=>S$(e,t);function Vt(e,t,n,r,s={},o=Sr(new Vn(e.chain))){const i=l=>{const f=Ni(e,t,l.id),u=f?null:Vp(e,o,t,l.id);return f?`${l.name} is listed for sale at ${Y(f.price)}. Withdraw its ask first`:u?`${l.name} was sold to ${u.name}, which adopts it next`:""},a=l=>{const f=[];for(let u=l?t.nodes.get(l):null;u;u=u.edge==="derived"?t.nodes.get(u.parent):null)f.unshift(u);return f},c=t.nodes.get(n==="graduate"?s.of:n==="close"?r:null);for(const l of[...a(r),...n==="award"?a(s.to):[],...c?Fn(t,c.id):[]]){const f=i(l);if(f)return f}return""}function i0(e,t,n){var o,i,a;const r=n.seller?(o=xe(e.keys,t,n.seller))==null?void 0:o.script:(i=e.wallet)==null?void 0:i.script,s=c=>[c,..._r(t.nodes,c).filter(l=>l.edge==="derived").flatMap(s)];if(r)for(const c of s(n.node)){const l=(a=$e(e.keys,t,c))==null?void 0:a.wallet,f=xe(e.keys,t,c);l&&Zu(e,l,r),f&&Zu(e,f,r)}}function G$(e,t,n){const{events:r,state:s}=Hi(e),o=Zn(e,r,s,t),{coins:i}=wr(e,r,s,o);if(i.length<2)return;const a=$e(e.keys,s,o.node).wallet,c=ln(e,n,W+we);if(!c)throw new Error(`There is no test BTC for the fee that bundles ${o.name}'s tree.`);const l=i.map(u=>Pi(e.keys,r,s,Se(u.scriptPubKey)).wallet),f=X.create({vin:[...i,c].map(ns),vout:[de(i.reduce((u,d)=>u+d.value,0),a.script),de(c.value-W,n.script)]});e.chain.submitPackage([ji(f,[...l,n])])}function a0(e,t,n,r,s,o,i){var g;const a=new Set(Fn(t,s.id).map(p=>p.id)),c=new Map(o),l=p=>{const m=t.nodes.get(a.has(p)?p:c.get(p));return $e(e.keys,t,m&&a.has(m.id)?m:s).wallet.script},f=[];for(const{id:p,offset:m}of n.inscriptions.map(w=>({id:w.id,offset:Bn(n.ranges,w.sat)})).sort((w,y)=>w.offset-y.offset))((g=f.at(-1))==null?void 0:g.offset)===m?f.at(-1).ids.push(p):f.push({offset:m,ids:[p]});const u=f.map((p,m)=>{var w;return[(((w=f[m+1])==null?void 0:w.offset)??n.value)-(m?p.offset:0),l(p.ids.find(y=>t.nodes.has(y))??p.ids[0])]});if(u.some(([p])=>pde(p,m)),de(d.value-W,i.script)]});e.chain.submitPackage([ji(h,[r,i])])}function c0(e,t,n,r=[]){const{events:s,state:o}=Hi(e),i=o.nodes.get(t),a=o.nodes.get(n),c=Dn(e,s,o,t);if(!i||!a||(c==null?void 0:c.node.id)!==a.id)throw new Error(`${(a==null?void 0:a.name)??"That node"} does not hold ${(i==null?void 0:i.name)??"that org"}.`);const l=rs(e,o,a.id),f=c.wallet,u=fi(e,"adopt",a.id,{of:i.id});if(!Il(e,o,a,l,tn("adopt")+tn("join")))throw new Error(`${a.name} has no test BTC for gas.`);ar(e,o,a,l,tn("adopt")),di(e,l,"adopt",a.id,u);const d=fi(e,"join",i.id,{to:a.id});ar(e,o,a,f,tn("join")),di(e,f,"join",i.id,d);const h=Re(e);ar(e,h,h.nodes.get(a.id),f,W+we),a0(e,h,an(e.chain,i.id),f,h.nodes.get(i.id),r,f)}function Y$(e,t,n,r){const s=t.nodes.get(r),o=t.nodes.get(n.lot),i=s&&xe(e.keys,t,s);if(!o||!i)return"";const a=Zt(t.nodes,o,s);if(a)return`${a[0].toUpperCase()}${a.slice(1)}`;const c=rs(e,t,s.id),l=tn("adopt")+tn("join"),f=n.price+Et+2*W+(ln(e,c,l)?0:Ri+W),u=e.chain.balance(i.script);return u{if(!h.node)return;const p=h.seller?rs(e,d,h.seller.id):e.wallet,m=g.coins.length>1;if(m&&h.seller&&!Il(e,d,h.seller,p,W+we))throw new Error(`${h.seller.name} has no test BTC for the fee that bundles ${h.name}'s tree.`);i0(e,d,h),m&&(h.seller&&ar(e,Re(e),h.seller,p,W+we),G$(e,h.id,p))});return e.chain.mempool.length>c&&(e.clock.tempo==="each"?at(e,Wn(e,l.seller??l.lot)):Ft(e,r)),l}function X$(e,t,n=Date.now()){var l;const r=(e.asks??[]).find(f=>Ar(f)===t);if(!r||r.taken||!(((l=e.chain.utxos.get(t))==null?void 0:l.inscriptions.length)>1))return zu(e,t);r.seller||ro(e);const{events:s,state:o}=Hi(e),i=e.chain.utxos.get(t),a=r.seller?o.nodes.get(r.seller):null,c=a?rs(e,o,a.id):e.wallet;return a&&ar(e,o,a,c,W+we),a0(e,o,i,Pi(e.keys,s,o,Se(i.scriptPubKey)).wallet,o.nodes.get(r.lot),r.layout??[],c),zu(e,t),e.clock.tempo==="each"?at(e,Wn(e,r.seller??r.lot)):Ft(e,n),r}function J$(e,t,n,r=Date.now()){const s=Re(e),o=(e.asks??[]).find(a=>Ar(a)===t),i=Vt(e,s,"take",n)||(o&&!o.taken?Y$(e,s,o,n):"");if(i)throw new Error(`${i}.`);return B$(e,t,n,r),s.nodes.has(o.lot)&&c0(e,o.lot,n,o.layout??[]),e.clock.tempo==="each"?at(e,Wn(e,n)):Ft(e,r),o}function Q$(e,t,n,r=Date.now()){var i;const s=Vt(e,Re(e),"adopt",n);if(s)throw new Error(`${s}.`);const o=[...(e.offers??[]).filter(a=>a.item===t&&a.buyer===n&&e.chain.transactions.has(a.txid)).map(a=>[a.at,a.layout]),...(e.asks??[]).filter(a=>{var c;return a.lot===t&&((c=a.taken)==null?void 0:c.buyer)===n}).map(a=>[a.taken.at,a.layout])].sort((a,c)=>a[0]-c[0]);c0(e,t,n,((i=o.at(-1))==null?void 0:i[1])??[]),e.clock.tempo==="each"?at(e,Wn(e,n)):Ft(e,r)}function eE(e,t,n,r=Date.now()){const s=Re(e),o=s.nodes.get(t);if(!o||o.root!==o.id)throw new Error("Pick a holding to fund.");if(o.status!=="active")throw new Error(`${o.name} is closed.`);const i=Vt(e,s,"fund",o.id);if(i)throw new Error(`${i}.`);const a=xe(e.keys,s,o);if(!a)throw new Error("A holding that predates lab keys has no SegWit address to fund.");if(!Number.isSafeInteger(n)||nGe)throw new Error("Fund at most 50 test BTC at a time: no output on this chain is bigger than one block reward.");ro(e),jp(e,e.wallet,n)||at(e);const c=kl(e,e.wallet,a.script,n,"The lab wallet","fund");return e.clock.tempo==="each"?at(e,Wn(e,t)):Ft(e,r),c}const cc="yolopreneur",tE=[[["found",null,{name:"yolopreneur"}]],[["birth","yolopreneur",{name:"well-known",kind:"org"}],["birth","yolopreneur",{name:"time",kind:"org"}],["keyring","yolopreneur",{}],["charter","yolopreneur",{form:"series-llc",jurisdiction:"US-WY",legal:"Yolopreneur Holdings LLC",provider:"doola"}]],[["send","yolopreneur",{to:"time",amount:40}],["send","yolopreneur",{to:"well-known",amount:10}],["birth","well-known",{name:"mailr",kind:"org"}],["birth","well-known",{name:"lineage",kind:"org"}],["birth","time",{name:"luna",kind:"agent"}],["birth","time",{name:"sol",kind:"agent"}],["birth","time",{name:"astra",kind:"agent"}],["charter","yolopreneur",{form:"series",of:"well-known"}],["charter","yolopreneur",{form:"series",of:"time"}]],[["send","well-known",{to:"lineage",amount:2}],["birth","time",{name:"docscope",kind:"org"}],["birth","time",{name:"dollhouse",kind:"org"}],["birth","time",{name:"doodleloop",kind:"org"}],["birth","time",{name:"hearthframe",kind:"org"}],["award","time",{to:"sol",skill:"launch",belt:"white"}],["charter","yolopreneur",{form:"series",of:"lineage"}]],[["send","time",{to:"sol",amount:1}],["send","time",{to:"luna",amount:.5}],["award","time",{to:"sol",skill:"launch",belt:"green"}],["award","time",{to:"luna",skill:"post",belt:"white"}],["decide","yolopreneur",{title:"Every venture gets a page",why:".yolopreneur.lol, served from one pages branch."}],["make","sol",{name:"launch-kit",note:"The page, the post and the checklist every venture launches with."}],["keyring","sol",{}],["keyring","lineage",{}]],[["graduate","well-known",{of:"lineage"}],["decide","lineage",{title:"Lineage gets its own org",why:"Its own repo on Teahub now, lineage.llc later: adopted, not derived."}],["charter","lineage",{form:"llc",jurisdiction:"US-WY",legal:"Lineage LLC",provider:"doola"}],["offer","lineage",{item:"launch-kit",price:.1}],["sell","well-known",{lot:"mailr",price:1}]]];function nE(e){ro(e),e.chain.mempool.length&&at(e);const t={},n={};for(const r of tE){for(const[s,o,i]of r){if(s==="send"){Kp(e,Re(e),t[o],t[i.to],i.amount*Kr);continue}if(s==="offer"){qp(e,n[i.item],t[o],i.price*Kr);continue}if(s==="sell"){l0(e,t[i.lot]??n[i.lot],i.price*Kr);continue}const a=s==="keyring"?n0(e,t[o]):Object.fromEntries(Object.entries(i).map(([f,u])=>[f,f==="to"||f==="of"?t[u]:u])),c=o?t[o]:null,l=o0(e,s,c,fi(e,s,c,a));(s==="found"||s==="birth")&&(t[i.name]=l),s==="make"&&(n[i.name]=l)}at(e,Ki(e,t[cc]))}return t[cc]}const L=e=>document.getElementById(e);function S(e,t={},...n){const r=document.createElement(e);for(const[s,o]of Object.entries(t))o==null||o===!1||(s==="class"?r.className=o:s==="text"?r.textContent=o:s.startsWith("on")?r.addEventListener(s.slice(2),o):r.setAttribute(s,o===!0?"":String(o)));for(const s of n.flat(1/0))s!=null&&s!==!1&&s!==""&&r.append(s instanceof Node?s:String(s));return r}const Cn=(e,t)=>`${e} ${t}${e===1?"":"s"}`,ht=e=>e==="cued"?"cued":`beat ${e}`,rE=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}),Gu=e=>JSON.stringify(e,(t,n)=>typeof n=="bigint"?String(n):n,2),I={holding:null,node:null,event:null,tx:null,beat:null,verb:"birth",busy:!1,replay:null,closing:null,reveal:null};let Z=no(),ss=new Vn(Z.chain),Ze=[],j=Dt([]),Ee=j,ze={owner:new Map,ledger:[],now:new Map,view:new Map},At=new Map;const ut=()=>Z.chain.blocks.length,lc=()=>Ze.filter(e=>e.status==="pending").length,uc=e=>ze.ledger.filter(t=>t.beat===null&&t.kind===e).length,Bo=[["pay","cued send"],["deal","cued deal"],["fund","cued deposit"]],sE=()=>lc()+Bo.reduce((e,[t])=>e+uc(t),0),Ne=e=>{var t,n;return((t=j.items.get(e))==null?void 0:t.name)??((n=j.nodes.get(e))==null?void 0:n.name)??"an item"},To=()=>Z.offers??[],Ul=()=>Z.asks??[];let ot=new Map,dt=new Map,ft=new Map,fc=new Map;const oE=e=>{var t,n;return((t=ot.get(e))==null?void 0:t.layout)??((n=[...To().filter(r=>r.item===e&&Z.chain.transactions.has(r.txid)).map(r=>[r.at,r.layout]),...Ul().filter(r=>r.lot===e&&r.taken).map(r=>[r.taken.at,r.layout])].sort((r,s)=>r[0]-s[0]).at(-1))==null?void 0:n[1])??[]},u0=e=>e?ke(e):"its owner, the lab wallet",Oo=e=>ze.view.get(e)??0,f0=e=>ze.now.get(e)??0,q=(e,t=j)=>e?t.nodes.get(e)??null:null,iE=e=>{var t;return!!e&&(e.root===I.holding||((t=q(e.parent))==null?void 0:t.root)===I.holding||e.moves.some(n=>{var r;return((r=q(n.from))==null?void 0:r.root)===I.holding}))},Nl=e=>Object.assign(I,{event:null,tx:null,closing:null,reveal:null},e),Br=e=>{Nl(e),Mi()};function he(e,t=!1){const n=L("say");n.textContent=e,n.classList.toggle("bad",t)}function d0(){try{Z=Tl()}catch(e){Z=no(),he(`This browser's saved lab could not be read (${e.message}) Load a backup, or reset to start over.`,!0)}Ll()}function Ll(){var t,n,r;ss=new Vn(Z.chain),Ze=Sr(ss),j=Dt(Ze,{pending:!0}),I.beat!==null&&I.beat>=ut()&&(I.beat=null),q(I.holding)&&q(I.holding).root!==I.holding&&(I.holding=q(I.holding).root),q(I.holding)||(I.holding=((t=j.roots.filter(s=>s.kind==="holding").at(-1)??j.roots.at(-1))==null?void 0:t.id)??null),iE(q(I.node))||(I.node=I.holding),I.event&&!j.log.some(s=>s.id===I.event)&&(I.event=null),Ee=I.beat===null?j:Dt(Ze,{upTo:I.beat});const e=w$(Z.keys,Ze,j);fc=T$(Z),ze={owner:e,ledger:x$(Z.chain,e,b$(Z.keys,Ze,j),fc),now:Qa(Z.chain,e)},At=new Map([...j.items.keys()].map(s=>{var o;return[s,((o=Dn(Z,Ze,j,s))==null?void 0:o.node.id)??null]})),ot=new Map(Ul().filter(s=>Bl(Z,j,s)==="open").map(s=>[s.lot,s])),dt=new Map([...j.nodes.values()].filter(s=>s.kind!=="agent"&&s.status==="active").map(s=>{var o;return[s.id,(o=Vp(Z,Ze,j,s.id))==null?void 0:o.id]}).filter(([,s])=>s)),ft=new Map;for(const s of Z.chain.utxos.values()){const o=((n=s.inscriptions)==null?void 0:n.length)>1?(r=s.inscriptions.find(i=>j.nodes.has(i.id)))==null?void 0:r.id:null;if(o)for(const i of s.inscriptions)i.id!==o&&ft.set(i.id,o)}for(const s of new Set(ft.values()))for(const[o,i]of oE(s))ft.has(o)&&At.set(o,i);ze.view=I.beat===null?ze.now:Qa(Z.chain,e,I.beat),I.tx&&!ze.ledger.some(s=>s.key===I.tx)&&(I.tx=null),Mi()}function hi(e){I.beat=e>=ut()?null:Math.max(0,e),Ee=I.beat===null?j:Dt(Ze,{upTo:I.beat}),ze.view=I.beat===null?ze.now:Qa(Z.chain,ze.owner,I.beat),Mi()}async function tt(e,t){if(I.busy)return!1;I.busy=!0,document.body.classList.add("busy");try{return Z=(await H$(e,t)).lab,!0}catch(n){return he((n==null?void 0:n.message)||String(n),!0),!1}finally{I.busy=!1,document.body.classList.remove("busy"),Ll()}}async function qt(e,t,n,r){let s=null;if(!await tt(i=>{s=V$(i,e,t,n)}))return!1;const o=ss.events.find(i=>i.id===s);return he(r(s,(o==null?void 0:o.status)==="confirmed"?`at beat ${o.height}`:"cued for the next beat")),Mi(),!0}async function h0(e){const t=[lc(),...Bo.map(([a])=>uc(a))],n=ut();if(!await tt(e)||ut()===n)return;const r=[lc(),...Bo.map(([a])=>uc(a))],s=["cued act",...Bo.map(([,a])=>a)],o=t.map((a,c)=>[a-r[c],s[c]]).filter(([a])=>a>0).map(([a,c])=>Cn(a,c)),i=aE(ze.ledger.filter(a=>a.kind==="mine"&&a.beat===ut()));he(`Beat ${ut()}: ${o.length?`${o.join(" and ")} landed, and ${i}`:i}.`)}function aE(e){if(!e.length)return"the lab wallet earned 50 tBTC";const t=e.map(r=>{var s;return((s=q(r.to))==null?void 0:s.name)??"?"}),n=e.map(r=>gl(r.amount));return e.length===1?`${t[0]} earned ${Y(e[0].amount)}`:n.every(r=>r===n[0])?`${t.slice(0,-1).join(", ")} and ${t.at(-1)} earned ${n[0]} each`:e.map((r,s)=>`${t[s]}${s?"":" earned"} ${n[s]}`).join(", ")}function cE(){var t;if(((t=Z.mining)==null?void 0:t.rule)==="last")return"the holding that acts";const e=yl(Z,j);return e.length?e.length===1?e[0].name:`${e.length} holdings, split by hashrate`:"the lab wallet"}function Mi(){p0(),fE(),dE(),ds(),_0(),jl()}function p0(){const e=sE(),{tempo:t}=Z.clock;for(const r of document.querySelectorAll("[data-tempo]"))r.setAttribute("aria-pressed",String(String(t)===r.dataset.tempo));L("clock-beat").textContent=String(ut()),L("clock-cued").textContent=e?`${e} cued · ${lE()}`:"nothing cued";const n=cE();L("clock-pays").textContent=`beats pay ${n}`,L("beat-now").title=`Beat now: ${e?"land what is cued, and ":""}pay ${n} 50 test BTC`}function lE(){const{tempo:e,nextAt:t}=Z.clock;return e==="manual"?"waiting for Beat now":typeof e=="number"&&t?`next beat in ${Math.max(0,Math.ceil((t-Date.now())/1e3))}s`:"landing on the next beat"}const uE={split:"Every active holding mines: each beat's 50 tBTC splits by hashrate, set on each holding (0 sits out).",last:"The holding behind the latest act or send takes the whole beat; with nothing cued, Beat now pays the one you're working in. At a timed tempo it's a race for the next beat.",none:"Mainnet has no mining to join: beats pay the lab wallet, standing in for the world's miners. Fund a holding from it, the way you'd fund a seed from a wallet you already have."};function fE(){var a,c;const e=((a=Z.mining)==null?void 0:a.rule)??"split",t=e==="split",n=t?yl(Z,j):[],r=n.reduce((l,f)=>l+Mr(Z,f.id),0);L("holdings-list").replaceChildren(...j.roots.map(l=>{var w;const f=vk(j,l.id),u=l.id===I.holding,d=l.status==="active",h=n.some(y=>y.id===l.id)?Mr(Z,l.id)/r:0,g=[...j.nodes.values()].reduce((y,b)=>y+(b.root===l.id?f0(b.id):0),0),m=[l.graduated!==null&&`from ${((w=q(l.parent))==null?void 0:w.name)??"?"}${l.graduated==="cued"?", cued":` at beat ${l.graduated}`}`||ht(l.born),Cn(f.orgs,"org"),Cn(f.agents,"agent"),Cn(f.belts,"belt"),g>0&&gl(g),t&&d&&(h?`${Math.round(h*100)}% of each beat`:"not mining"),!d&&"closed"].filter(Boolean);return S("li",{},S("button",{type:"button",class:`hold${u?" on":""}${d?"":" gone"}`,"aria-pressed":String(u),onclick:()=>Br({holding:l.id,node:l.id})},S("span",{class:"hn",text:l.name})," ",S("span",{class:"hm",text:m.join(" · ")})),t&&d&&xe(Z.keys,j,l)&&$E(l,Mr(Z,l.id)))}));for(const l of document.querySelectorAll("[data-rule]"))l.setAttribute("aria-pressed",String(e===l.dataset.rule));L("mining-note").textContent=uE[e];const s=j.roots.filter(l=>l.status==="active"&&xe(Z.keys,j,l)&&!ot.has(l.id)&&!dt.has(l.id)),o=L("fund-to"),i=o.value;L("f-fund").hidden=e!=="none"||!s.length||I.beat!==null,o.replaceChildren(...s.map(l=>S("option",{value:l.id,text:l.name}))),o.value=s.some(l=>l.id===i)?i:s.some(l=>l.id===I.holding)?I.holding:((c=s[0])==null?void 0:c.id)??"",L("fund-has").textContent=Y(Z.wallet?$l(Z.chain,Z.wallet):0),L("holdings-empty").hidden=j.roots.length>0,L("holdings-sub").textContent=j.roots.length?String(j.roots.length):"",L("sample").disabled=j.roots.some(l=>l.name===cc&&l.status==="active")}function dE(){var r;const e=L("tree-rows"),t=q(I.holding);if(L("tree-sub").textContent=t?`${t.name} · ${I.beat===null?"now":`beat ${I.beat} of ${ut()}`}`:"",!t)return e.replaceChildren(S("p",{class:"wait",text:"No holding yet. Found one, or load the yolopreneur sample."}));if(!Ee.nodes.has(t.id))return e.replaceChildren(S("p",{class:"wait",text:`${t.name} is founded at ${ht(t.born)}. Move the slider forward.`}));const n=e.contains(document.activeElement)?document.activeElement.dataset.id:null;e.replaceChildren(...xk(Ee,t.id).map(s=>s.type==="group"?S("div",{class:"row grp"},S("span",{class:"g","aria-hidden":"true",text:s.guide}),S("span",{class:"gl",text:s.label})):hE(s))),n&&((r=e.querySelector(`[data-id="${n}"]`))==null||r.focus())}function hE({node:e,guide:t,path:n,away:r,moved:s}){const o=e.id===I.node,i=s&&q(e.parent,Ee),a=["row",o&&"on",e.status==="closed"&&"gone",e.born==="cued"&&"cue",s&&"moved"].filter(Boolean).join(" ");return S("div",{class:a},S("button",{type:"button",class:"sel","data-id":e.id,"aria-pressed":String(o),onclick:()=>Br({node:e.id}),title:s?`${e.name} changed hands: it's ${(i==null?void 0:i.name)??"?"}'s now`:r?`${e.name} graduated into a holding of its own`:null},S("span",{class:"g","aria-hidden":"true",text:t}),S("span",{class:"p",text:`${n} `}),S("span",{class:"l",text:e.name})," ",S("span",{class:"v"},s?S("span",{class:"mk",text:`to ${(i==null?void 0:i.name)??"?"}`}):pE(e))))}function pE(e){var n;return[e.kind==="agent"&&S("span",{class:"mk",text:"agent"}),I.beat===null&&ot.has(e.id)&&S("span",{class:"mk ok",title:`${Y(ot.get(e.id).price)}, asked by ${u0(ot.get(e.id).seller)}`,text:"for sale"}),I.beat===null&&dt.has(e.id)&&S("span",{class:"mk",title:`bought by ${ke(dt.get(e.id))}, which adopts it next`,text:"sold"}),e.edge==="adopted"&&S("span",{class:"mk ok",text:"graduated"}),e.charter&&S("span",{class:`mk form${(n=Es(Ee,e))!=null&&n.ok?"":" lapsed"}`,title:Rl(e),text:mE[e.charter.form]}),e.status==="closed"&&S("span",{class:"mk bad",text:"closed"}),e.born==="cued"&&S("span",{class:"mk",text:"cued"}),...e.badges.map(g0),Oo(e.id)>0&&S("span",{class:"mk sats",title:`${Y(Oo(e.id))} at its SegWit address`,text:gl(Oo(e.id))})].filter(Boolean).flatMap((r,s)=>s?[" ",r]:[r])}const g0=e=>S("span",{class:`belt ${e.belt}`,title:`${e.skill}: ${e.belt} belt`},e.skill,S("span",{class:"sr",text:` (${e.belt} belt)`}));function gE(e){const t=e.earlier.map(n=>{var r;return`${n.belt}${n.by===e.by?"":` from ${((r=q(n.by))==null?void 0:r.name)??"?"}`} (${ht(n.beat)})`});return t.length?`, re-inscribed over ${t.length>1?`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`:t[0]}`:""}const dc=e=>{const t=ss.events.find(n=>n.id===e);return t?M$(Z.chain,ss,t):[]},Hl=e=>`${e0[e]} ${e}`,mE={sole:"sole",llc:"llc","series-llc":"series llc",series:"series",corp:"corp"},yE={sole:"Sole proprietor",llc:"LLC","series-llc":"Series LLC",series:"Series",corp:"Corporation"},wE={sole:"a sole proprietor",llc:"an LLC","series-llc":"a series LLC",corp:"a corporation"};function Rl(e,t=Ee){var o;const n=e.charter,r=n.master&&q(n.master,t),s=n.form==="series"?(o=r==null?void 0:r.charter)==null?void 0:o.jurisdiction:n.jurisdiction;return[n.form==="series"?`Series of ${(r==null?void 0:r.name)??"?"}`:yE[n.form],s,n.legal,n.provider&&`via ${n.provider}`,`since ${ht(n.beat)}`].filter(Boolean).join(" · ")}function Di(e){var t;for(let n=q(e.parent);n&&n.root===e.root;n=q(n.parent))if(n.status==="active"&&((t=n.charter)==null?void 0:t.form)==="series-llc")return n;return null}function bE(e){var r;const t=e.kind==="org"&&Di(e),n=e.kind==="org"&&e.edge==="derived";return[(e.kind==="holding"||e.kind==="agent")&&["sole","Sole proprietor","a person trading under their own name"],t&&["series",`Series of ${t.name}`,`a cell of ${t.name}'s LLC, chartered by ${t.name}`],!rn(e)&&["llc","LLC",n?`a company of its own, owned through ${(r=q(e.parent))==null?void 0:r.name} while it is derived`:"a company of its own"],!rn(e)&&["series-llc","Series LLC","an LLC that can hold series, one for each venture"],!rn(e)&&["corp","Corporation","a company with shares"]].filter(Boolean)}function m0(e){return bE(e).map(([t,n,r])=>{const s=t==="series"?Di(e):e,o=Cl(Z,j,"charter",s.id);return{form:t,label:n,hint:o?`${o}.`:r,off:!!o}})}const xE=e=>{var n;const t=m0(e);return t.some(r=>!r.off)?"":((n=t[0])==null?void 0:n.hint.replace(/\.$/,""))??"No legal form fits"},pi=()=>{var e;return((e=document.querySelector("#charter-forms input:checked"))==null?void 0:e.value)??null};function vE(e){var i;const t=L("charter-forms"),n=m0(e),r=n.map(a=>`${a.form}=${a.label}=${a.off}`).join("|");if(t.dataset.sig!==r){const a=pi(),c=n.filter(f=>!f.off),l=c.some(f=>f.form===a)?a:(i=c[0])==null?void 0:i.form;t.dataset.sig=r,t.replaceChildren(S("legend",{class:"lab",text:"Form"}),...n.map(f=>S("label",{class:f.off?"off":null},S("input",{type:"radio",name:"form",value:f.form,checked:f.form===l,disabled:f.off}),` ${f.label} `,S("span",{text:f.hint}))))}const s=pi()==="series",o=Es(j,e);L("charter-where").hidden=s,L("charter-now").textContent=e.charter?`Now: ${Rl(e,j)}${o.ok?"":`, lapsed: ${o.why}`}.`:"It has no legal form yet."}const y0=(e,t)=>{for(let n=q(e.parent);n;n=q(n.parent))if(n.id===t.id)return!0;return!1},kE=e=>{for(let t=e;t;t=t.edge==="derived"?q(t.parent):null)if(ot.has(t.id)||dt.has(t.id))return!0;return!1},w0=e=>[...j.nodes.values()].filter(t=>t.id!==e.id&&t.status==="active"&&!kE(t)).map(t=>[t,(t.root===e.root?0:4)+(y0(t,e)?0:2)+(t.kind==="agent"?0:1)]).sort((t,n)=>t[1]-n[1]).map(([t])=>t),os=e=>_r(j.nodes,e).reduce((t,n)=>n.edge==="derived"&&n.status==="active"?t+1+os(n):t,0);function $E(e,t){const n=async r=>{await tt(s=>U$(s,e.id,r))&&he(r?`${e.name} mines at hashrate ${r}.`:`${e.name} sits out of mining.`)};return S("span",{class:"rig"},S("span",{class:"rl",text:"hashrate"}),S("span",{class:"rn"},S("button",{type:"button",class:"rb","aria-label":`Lower ${e.name}'s hashrate`,disabled:t<=0,onclick:()=>n(t-1)},"−"),S("b",{text:String(t)}),S("button",{type:"button",class:"rb","aria-label":`Raise ${e.name}'s hashrate`,disabled:t>=9,onclick:()=>n(t+1)},"+")))}const b0=e=>[...j.nodes.values()].filter(t=>t.id!==e.id&&t.status==="active").map(t=>[t,(t.root===e.root?0:4)+(y0(t,e)?0:2)+(t.kind==="agent"?0:1)]).sort((t,n)=>t[1]-n[1]).map(([t])=>t);function EE(e){const t=xe(Z.keys,j,e);return t?bl(Z.chain.coins(t.script))!ft.has(r.id)).map(r=>[r,q(At.get(r.id))]).filter(([,r])=>r&&r.id!==e.id&&r.status==="active"),n=[...j.nodes.values()].filter(r=>r.kind!=="agent"&&!ft.has(r.id)&&!dt.has(r.id)&&!Zt(j.nodes,r,e)).map(r=>[r,r]);return[...t,...n].sort((r,s)=>(r[1].root===e.root?0:1)-(s[1].root===e.root?0:1)).map(([r])=>r)}const hc=e=>os(e)?`, with ${os(e)} below it`:"",SE=e=>(j.items.has(e.id)?`${e.name} · held by ${ke(At.get(e.id))}`:`${e.name} · ${e.root===e.id?"a holding":`an org of ${ke(e.parent)}`}${hc(e)}`)+(ot.has(e.id)?` · asks ${Y(ot.get(e.id).price)}`:"");function _E(e){const t=xe(Z.keys,j,e);return t?v0(e).length?Z.chain.coins(t.script).some(n=>n.value>=W+we||n.value===W)?"":x0(e,"to pay with"):"Nothing to buy yet. Items come from Make, and orgs and holdings change hands from other trees":"This holding predates lab keys, so it has no SegWit address to pay from"}const k0=e=>[...[...j.items.values()].filter(t=>At.get(t.id)===e.id&&!ft.has(t.id)),..._r(j.nodes,e).filter(t=>t.kind==="org"&&t.edge==="derived"&&!dt.has(t.id)&&!ft.has(t.id)&&!Zt(j.nodes,t)),...e.root===e.id&&e.kind!=="agent"&&!dt.has(e.id)&&!Zt(j.nodes,e)?[e]:[]],$0=e=>k0(e).filter(t=>!ot.has(t.id));function AE(e){return xe(Z.keys,j,e)?$0(e).length?"":k0(e).length?`Everything ${e.name} can sell is listed. Its asks are in Inspect, to withdraw`:`${e.name} has nothing to sell yet: no item, and no org of its own free to change hands`:"This holding predates lab keys, so it has no SegWit address to be paid at"}function BE(e){const t=L("offer-item").value,n=ot.get(t),r=j.items.has(t)?null:q(t),s=!!r&&r.root===r.id,o=r?s?`${r.name}'s owner`:ke(r.parent):ke(At.get(t)),i=r?os(r):0,a=r?i?`${r.name}'s tree, ${Cn(i+1,"node")} and the items they hold,`:`${r.name}'s inscription and its items`:"the item";L("offer-ask").hidden=!n,L("offer-go").classList.toggle("primary",!n),n&&(L("offer-ask-line").textContent=`${n.seller?ke(n.seller):`${r.name}'s owner`} asks ${Y(n.price)} for ${Ne(t)}${s?", whole":""}. Taking it costs the price, two ${W}-sat fees and a ${Et}-sat coin of ${e.name}'s that leads the deal${r?`, and gas to adopt ${r.name} at once`:""}.`,L("offer-take").textContent=`Take it for ${Y(n.price)}`),L("offer-note").textContent=`${n?"Or offer less. ":""}${e.name}'s SegWit key signs the whole deal now: ${a} to its Taproot key, the price to ${s?"the lab wallet":o}, the ${W}-sat fee from its balance. Nothing reaches the chain until ${o} accepts. ${r?`Accepting takes the money in ${r.name}'s tree home to ${s?"the lab wallet":o} first, and its items go with it; then ${e.name} adopts it. Each act in ${r.name}'s tree moves an inscription, which voids the offer.`:"Until then the offer stands, unless it's withdrawn or a coin it promised moves."}`}function TE(e){const t=q(L("sell-lot").value),n=(t==null?void 0:t.id)===e.id,r=t?os(t):0,s=E0(t);L("sell-note").textContent=t?`Cash-free: ${n?"its owner, the lab wallet,":e.name} takes home the money in ${t.name}'s tree first, every gas tank included, and its items go with it. ${s>1?`Its ${s} inscriptions become one coin at ${t.name}'s key, since an ask signs one input, and ${r?"all of its tree is":"it is"} frozen while it's listed.`:`${t.name} is frozen while it's listed.`} ${n?`${t.name}'s root key`:"Its own key"} signs that input alone, SIGHASH_SINGLE|ANYONECANPAY, for the price to ${n?"the lab wallet":`${e.name}'s SegWit address`}. Whoever takes it adopts it${n?" as an org":""}, and ${r?"its tree takes":"it takes"} new keys from its buyer's seed.`:`The key that holds it signs its input alone, SIGHASH_SINGLE|ANYONECANPAY: that input, for the price to ${e.name}'s SegWit address, and nothing else. Any node can complete the deal around it, so nothing reaches the chain until one does.`}function OE(e){const t=q(L("award-to").value);L("award-note").textContent=t?`${e.name}'s key signs as the belt's parent, and ${t.name}'s co-signs, accepting it. The belt is inscribed on ${t.name}'s own sat, so it goes wherever ${t.name} goes and never sells apart from it; ord marks it ${Hl("reinscription")}.`:""}const E0=e=>e?wr(Z,Ze,j,Zn(Z,Ze,j,e.id)).coins.reduce((t,n)=>t+n.inscriptions.length,0):1;function S0(e,t=j){const n=pl(Z.keys,t,e);return n&&{taproot:n.taproot.address,segwit:n.segwit.address,nostr:n.npub.address,ethereum:n.ethereum.address}}function IE(e){const t=S0(e),n=e.keyring;if(!t)return"This holding predates lab keys, so it has no keys to list";const r=Ol(j,"keyring",e.id);return r||(!n||n.retired||It.some(s=>n.keys[s]!==t[s])?"":n.beat==="cued"?`${e.name}'s keyring is cued for the next beat`:`${e.name}'s keyring already lists these keys, since beat ${n.beat}`)}function CE(e){const t=q(e.parent),n=e.status==="closed"?`${e.name} is closed`:"",r=n?"":Vt(Z,j,"act",e.id,{},Ze),s=(o,i=e.id,a={})=>Cl(Z,j,o,i,a);return{birth:n||r||(rn(e)?"Agents give birth only once they graduate":s("birth")),award:n||r||(rn(e)?"Agents award belts only once they graduate":w0(e).length?s("award"):"There is nobody else to award yet"),charter:n||r||xE(e),decide:n||r||s("decide"),make:n||r||s("make"),keyring:n||r||IE(e)||s("keyring"),send:n||r||EE(e),offer:n||r||_E(e),sell:n||r||AE(e),graduate:n||(t?e.edge==="adopted"?`${e.name} has already graduated`:t.status!=="active"?`${t.name} is closed`:Vt(Z,j,"graduate",t.id,{of:e.id},Ze)||Ol(j,"graduate",t.id,{of:e.id})||s("graduate",t.id,{of:e.id}):"A holding has no parent to graduate from"),close:n||r||s("close")}}function ds(){const e=q(I.node),t=I.beat!==null;if(L("act-none").hidden=!!e,L("act-past").hidden=!e||!t,L("act-on").hidden=!e||t,L("act-sub").textContent=(e==null?void 0:e.name)??"",L("past-beat").textContent=String(I.beat??""),!e||t)return;const n=CE(e),r=q(e.parent);for(const p of document.querySelectorAll("[data-verb]"))p.setAttribute("aria-pressed",String(p.dataset.verb===I.verb)),p.classList.toggle("off",!!n[p.dataset.verb]);for(const p of document.querySelectorAll("form[data-form]"))p.hidden=p.dataset.form!==I.verb||!!n[I.verb];L("act-why").textContent=n[I.verb]?`${n[I.verb]}.`:"";for(const p of document.querySelectorAll("#act-on [data-name]"))p.textContent=e.name;for(const p of document.querySelectorAll("#act-on [data-parent]"))p.textContent=(r==null?void 0:r.name)??"";const s=p=>p.map(m=>`${m.value}=${m.textContent}`).join("|"),o=[[L("award-to"),w0(e).map(p=>[p.id,`${ts(j,p.id)}${p.kind==="agent"?" (agent)":""}`])],[L("send-to"),b0(e).map(p=>[p.id,`${ts(j,p.id)}${p.kind==="agent"?" (agent)":""}`])],[L("offer-item"),v0(e).map(p=>[p.id,SE(p)])],[L("sell-lot"),$0(e).map(p=>[p.id,j.items.has(p.id)?`${p.name} · an item`:p.id===e.id?`${p.name} · the whole holding${hc(p)}`:`${p.name} · org ${p.index}'${hc(p)}`])]];for(const[p,m]of o){const w=p.value,y=m.map(([b,_])=>S("option",{value:b,text:_}));s(y)!==s([...p.options])&&(p.replaceChildren(...y),y.some(b=>b.value===w)&&(p.value=w))}for(const p of["send-has","offer-has"])L(p).textContent=Y(f0(e.id));L("graduate-go").textContent=`Graduate ${e.name}`,I.verb==="charter"&&!n.charter&&vE(e),I.verb==="award"&&!n.award&&OE(e),I.verb==="offer"&&!n.offer&&BE(e),I.verb==="sell"&&!n.sell&&TE(e);const i=I.verb==="keyring"&&!n.keyring&&S0(e);i&&L("keyring-keys").replaceChildren(...[["Taproot",i.taproot],["SegWit",i.segwit],["nostr",i.nostr],["Ethereum",i.ethereum]].map(is));const a=I.verb==="sell"&&q(L("sell-lot").value),c=I.verb==="graduate"?r:I.verb==="charter"&&pi()==="series"?Di(e):a||e,l=c&&$e(Z.keys,j,c),f=I.verb==="send"||I.verb==="offer",u=l&&(f?`${l.from} · ${xe(Z.keys,j,c).path}`:l.path);L("act-key").textContent=!c||n[I.verb]?"":l?`Signs as ${c.name}: ${u}`:"Signs with the lab wallet: this holding predates lab keys.";const d=I.verb==="graduate"&&$e(Z.keys,j,e)?Fn(j,e.id).length:0;L("act-gas").textContent=!c||n[I.verb]||!l?"":I.verb==="send"?`Fee: ${W} sats, from ${e.name}'s balance.`:I.verb==="offer"?`Fee: ${W} sats, from ${e.name}'s balance, paid only if the holder accepts.`:I.verb==="sell"?E0(a||null)>1?`Bundling its tree costs one ${W}-sat fee, from ${a.id===e.id?"the lab wallet":`${e.name}'s tank`}; whoever takes the ask pays the deal's fees.`:"No fee to list: whoever takes the ask pays the fees.":`Gas: ${Z$(I.verb,d).toLocaleString("en-US")} sats from ${c.name}'s tank (${Y($l(Z.chain,l.wallet))}), which tops up from its balance.${d?` ${e.name} pays ${W} more, from its own money, to claim its new root.`:""}`;const h=os(e),g=I.closing===e.id;L("close-note").textContent=h?`Closing ${e.name} spends it for the last time, and its ${Cn(h,"derived descendant")} close with it. Graduated children hold their own roots and stay open.`:`Closing ${e.name} spends its inscription for the last time. Nothing can act through it afterwards.`,L("close-go").textContent=g?`Yes, close ${e.name}`:`Close ${e.name}`,L("close-keep").hidden=!g}function _0(){const e=L("inspect-body"),t=I.event?j.log.find(o=>o.id===I.event):null;if(t)return L("inspect-sub").textContent="event",e.replaceChildren(...WE(t));const n=I.tx?ze.ledger.find(o=>o.key===I.tx):null;if(n)return L("inspect-sub").textContent="money",e.replaceChildren(...GE(n));const r=q(I.node);if(L("inspect-sub").textContent=(r==null?void 0:r.kind)??"",!r)return e.replaceChildren(S("p",{class:"note pad",text:"Select a node in the tree, or an event in the timeline."}));const s=q(I.node,Ee);if(!s)return e.replaceChildren(S("p",{class:"note pad",text:`${r.name} is not born yet at beat ${I.beat}.`}));e.replaceChildren(...PE(s))}const is=([e,t,n])=>S("div",{class:"f"},S("dt",{text:e}),S("dd",{},t,n&&S("span",{class:"fn",text:n})));function PE(e){var r;const t=q(e.parent,Ee),n=[["Born",e.born==="cued"?"cued for the next beat":`beat ${e.born}`],t&&["Parent",`${t.name} · ${e.kind} ${e.index}'`],t&&["Edge",e.edge==="adopted"?`adopted at ${ht(e.graduated)}: it holds its own root`:`derived: ${t.name} holds its seed`],e.moves.length>0&&["Changed hands",e.moves.map(s=>{var o,i;return`${s.from?`from ${((o=q(s.from,Ee))==null?void 0:o.name)??"?"}`:"whole, from its owner,"} to ${((i=q(s.to,Ee))==null?void 0:i.name)??"?"}, ${ht(s.beat)}`}).join("; "),"Each time, it took the next index under its new parent, and keys derived there, with its tree."],I.beat===null&&(ot.has(e.id)||dt.has(e.id)||ft.has(e.id))&&NE(e),t&&e.root===e.id&&["Holding",S("span",{},"its own, since it graduated",e.id!==I.holding&&S("button",{type:"button",class:"btn sm open",onclick:()=>{Br({holding:e.id,node:e.id}),HE()}},`Open ${e.name}`))],e.closed!==null&&["Closed",ht(e.closed)],["Charter",e.charter?Rl(e):"none yet",e.charter?Es(Ee,e).ok?e.charter.filing?`Filing SHA-256 ${e.charter.filing.slice(0,16)}…`:"":`Lapsed: ${Es(Ee,e).why}.`:"Charter gives it a legal form: sole proprietor, LLC, series LLC, series or corporation."],((r=e.charter)==null?void 0:r.form)==="series-llc"&&["Series",[...Ee.nodes.values()].filter(s=>{var o;return((o=s.charter)==null?void 0:o.master)===e.id}).map(s=>`${s.name}${Es(Ee,s).ok?"":" (lapsed)"}`).join(", ")||"none yet"],["Children",_r(Ee.nodes,e).map(s=>s.name).join(", ")||"none yet"],xe(Z.keys,Ee,e)&&["Balance",Y(Oo(e.id)),`Test BTC at its SegWit address${I.beat===null?"":`, as of beat ${I.beat}`}.`],I.beat===null&&$e(Z.keys,j,e)&&["Gas tank",Y($l(Z.chain,$e(Z.keys,j,e).wallet)),"Plain coins at its Taproot key. Its acts burn their fees from here, and the tank tops up from its balance, 0.0001 tBTC at a time."],["Inscription",e.id,dc(e.id).length?`ord charms: ${dc(e.id).map(Hl).join(", ")}`:""]].filter(Boolean);return[S("div",{class:"ih"},S("p",{class:"eyebrow",text:ts(Ee,e.id)}),S("h3",{class:"it",text:e.name}),S("div",{class:"chips"},S("span",{class:"chip",text:e.kind}),S("span",{class:`chip ${e.status==="active"?"ok":"bad"}`,text:e.status}),e.edge==="adopted"&&S("span",{class:"chip ok",text:"graduated"}),e.born==="cued"&&S("span",{class:"chip",text:"cued"}))),S("div",{class:"ib"},S("dl",{class:"fl"},n.map(is)),e.badges.length>0&&S("div",{},S("p",{class:"lab"},"Belts",S("span",{text:` · soulbound to ${e.name}`})),S("ul",{class:"list"},e.badges.map(s=>{var o;return S("li",{},g0(s),S("span",{class:"when",text:` from ${((o=q(s.by))==null?void 0:o.name)??"?"}, ${ht(s.beat)} · ${e0.reinscription} on ${e.name}'s own sat${gE(s)}`}))}))),e.decisions.length>0&&S("div",{},S("p",{class:"lab",text:"Decisions"}),S("ul",{class:"list"},e.decisions.map(s=>S("li",{},S("b",{text:s.title}),s.why&&` · ${s.why}`,S("span",{class:"when",text:` (${ht(s.beat)})`}))))),UE(e),RE(e),ZE(e))]}function UE(e){const t=(u,d)=>d.length>0&&S("div",{},S("p",{class:"lab",text:u}),S("ul",{class:"list items"},d)),n=(u,d)=>S("li",{},S("b",{text:u.name}),u.note&&` · ${u.note}`,S("span",{class:"when",text:` (${d})`}));if(I.beat!==null)return t("Made",e.made.map(u=>Ee.items.get(u)).filter(Boolean).map(u=>n(u,ht(u.beat))));const r=u=>`made${u.maker===e.id?"":` by ${ke(u.maker)}`}${u.beat==="cued"?", cued":` at beat ${u.beat}`}`,s=[...j.items.values()].filter(u=>At.get(u.id)===e.id).map(u=>{const d=n(u,`${r(u)}${ft.has(u.id)?`, in one coin with ${Ne(ft.get(u.id))}'s tree`:""}`),h=To().filter(g=>g.item===u.id&&g.seller===e.id&&Ao(Z,j,g,Ze)==="open");return h.length&&d.append(S("ul",{class:"bids"},h.map(g=>S("li",{},S("span",{text:`${ke(g.buyer)} offers ${g.price?Y(g.price):"nothing, a free claim"}`}),e.status==="active"&&S("button",{type:"button",class:"btn sm","aria-label":`Accept ${ke(g.buyer)}'s offer for ${u.name}`,onclick:()=>Yu(g)},"Accept"))))),d}),o=e.made.map(u=>j.items.get(u)).filter(u=>u&&At.get(u.id)!==e.id).map(u=>n(u,At.get(u.id)?`now held by ${ke(At.get(u.id))}`:"held outside this lab")),i=To().filter(u=>u.buyer===e.id&&Ao(Z,j,u,Ze)!=="done").map(u=>{const d=_l(Z,j,u,Ze);return S("li",{},S("b",{text:u.price?Y(u.price):"nothing"}),` for ${Ne(u.item)}`,S("span",{class:"when",text:d?` (stale: ${d})`:` (open until ${u.seller?ke(u.seller):`${Ne(u.item)}'s owner`} accepts)`}),S("button",{type:"button",class:"btn sm","aria-label":`Withdraw the offer for ${Ne(u.item)}`,onclick:()=>LE(u)},"Withdraw"))}),a=u=>u.seller===e.id||u.seller===null&&(u.item??u.lot)===e.id,c=To().filter(u=>a(u)&&j.nodes.has(u.item)&&Ao(Z,j,u,Ze)==="open").map(u=>S("li",{},S("b",{text:Ne(u.item)}),S("span",{class:"when",text:` ${ke(u.buyer)} offers ${u.price?Y(u.price):"nothing, a free claim"}`}),e.status==="active"&&S("button",{type:"button",class:"btn sm","aria-label":`Accept ${ke(u.buyer)}'s offer for ${Ne(u.item)}`,onclick:()=>Yu(u)},"Accept"))),l=Ul().filter(u=>a(u)&&Bl(Z,j,u)!=="done").map(u=>{const d=Al(Z,j,u);return S("li",{},S("b",{text:Y(u.price)}),` for ${Ne(u.lot)}`,S("span",{class:"when",text:d?` (stale: ${d})`:" (open: any node can take it)"}),S("button",{type:"button",class:"btn sm","aria-label":`Withdraw the ask for ${Ne(u.lot)}`,onclick:()=>A0(u)},"Withdraw"))}),f=[...dt].filter(([,u])=>u===e.id).map(([u])=>S("li",{},S("b",{text:Ne(u)}),S("span",{class:"when",text:q(u).root===u?" bought whole":` bought from ${ke(q(u).parent)}`}),S("button",{type:"button",class:"btn sm","aria-label":`Adopt ${Ne(u)}`,onclick:()=>B0(u,e.id)},"Adopt")));return[t("Items",s),t("Made, held elsewhere",o),t(e.root===e.id?"Offers on it or its orgs":"Offers on its orgs",c),t("Asks",l),t("Offers made",i),t("Bought, to adopt",f)]}const ke=e=>{const t=q(e);return t?t.root===I.holding?t.name:ts(j,e):"?"};async function Yu(e){const t=Ne(e.item),n=ke(e.buyer),r=e.seller?ke(e.seller):`${t}'s owner`,s=j.nodes.has(e.item);if(!await tt(i=>{F$(i,e.txid)}))return;const o=ze.ledger.find(i=>i.txid===e.txid);he(`${r} accepted: ${t} goes to ${n}${e.price?` for ${Y(e.price)}`:", free"}, ${o!=null&&o.beat?`at beat ${o.beat}`:"cued for the next beat"}.${s?` The money in its tree went ${e.seller?`home to ${r}`:"to the lab wallet"} first, its items went with it, and ${n} adopts it next.`:""}`)}function NE(e){var o;const t=ot.get(e.id),n=q(dt.get(e.id)),r=q(ft.get(e.id)),s=[...ft.values()].includes(e.id);return!t&&!n?["Changing hands",`with ${(r==null?void 0:r.name)??"?"}'s tree`,ot.has(r==null?void 0:r.id)?`${r.name} is listed for sale: its tree is one coin at its key, frozen until the ask is taken or withdrawn.`:`${ke(dt.get(r==null?void 0:r.id))} bought ${(r==null?void 0:r.name)??"?"}'s tree, and adopts it next.`]:t?["For sale",S("span",{},`${Y(t.price)}, asked by ${u0(t.seller)}`,S("button",{type:"button",class:"btn sm open",onclick:()=>A0(t)},"Withdraw")),s?`Its tree is one coin at its key, ${Cn(((o=t.holder.ids)==null?void 0:o.length)??2,"inscription")}, and its own key signed that input, SIGHASH_SINGLE|ANYONECANPAY: any node can take it. All of the tree is frozen until then.`:"Its own key signed its input, SIGHASH_SINGLE|ANYONECANPAY: any node can take it. It's frozen until then."]:["Sold",S("span",{},`to ${ke(n.id)}, which adopts it next`,S("button",{type:"button",class:"btn sm open",onclick:()=>B0(e.id,n.id)},`Adopt into ${n.name}`)),`${n.name}'s key holds its ${s?"tree, in one coin,":"inscription"} now.`]}async function A0(e){var s;const t=Ne(e.lot),n=e.seller?ke(e.seller):`${t}'s owner`,r=(((s=e.holder.ids)==null?void 0:s.length)??1)>1;await tt(o=>{X$(o,Ar(e))})&&he(`${n} withdrew its ask for ${t}.${r?" Its tree split back, each node and item to its own key.":""}`)}async function B0(e,t){const n=Ne(e),r=ke(t);if(!await tt(o=>{Q$(o,e,t)}))return;const s=j.log.findLast(o=>o.op==="join"&&o.node===e);he(`${r} adopted ${n}, ${s!=null&&s.pending?"cued for the next beat":`at beat ${s==null?void 0:s.beat}`}: its keys derive from ${r}'s seed now.`)}async function LE(e){const t=Ne(e.item),n=ke(e.buyer);await tt(r=>{W$(r,e.txid)})&&he(`${n} withdrew its offer for ${t}.`)}function HE(){const e=document.querySelector(".tree-blk").getBoundingClientRect().top+scrollY-document.querySelector(".clock").offsetHeight-12;e(n.to===e.id||n.from===e.id)&&(I.beat===null||n.beat!==null&&n.beat<=I.beat)).slice(-6).reverse();return t.length>0&&S("div",{},S("p",{class:"lab",text:"Money"}),S("ul",{class:"list"},t.map(n=>S("li",{},S("b",{text:jE(n,e.id)}),S("span",{class:"when",text:` (${ht(n.beat??"cued")})`})))))}function jE(e,t){const n=r=>{var s;return r?((s=q(r))==null?void 0:s.name)??"?":"the lab wallet"};if(e.kind==="mine")return`+${Y(e.amount)}, a beat's reward`;if(e.kind==="move")return`${Y(e.amount)} moved to its new key, after a ${e.fee}-sat fee`;if(e.kind==="gas")return`−${Y(e.amount)} into its gas tank, and a ${e.fee}-sat fee`;if(e.kind==="fund")return`+${Y(e.amount)} from the lab wallet`;if(e.kind==="deal"){const r=Ne(e.item);return e.to===t?e.amount?`+${Y(e.amount)} from ${n(e.from)} for ${r}`:`${r} to ${n(e.from)}, free`:e.amount?`−${Y(e.amount)} to ${n(e.to)} for ${r}, and a ${e.fee}-sat fee`:`${r} from ${n(e.to)}, free but for a ${e.fee}-sat fee`}return e.to===t?`+${Y(e.amount)} from ${n(e.from)}`:`−${Y(e.amount)} to ${n(e.to)}, and a ${e.fee}-sat fee`}function T0(e){const t=n=>{const r=q(n);return n?r?r.root===I.holding?r.name:ts(j,n):"?":"lab wallet"};return e.kind==="mine"?`${Y(e.amount)} → ${t(e.to)}`:e.kind==="move"?`${Y(e.amount)} → ${t(e.to)}'s new key`:e.kind==="gas"?`${Y(e.amount)} → ${t(e.to)}'s gas tank`:e.kind==="fund"?`${Y(e.amount)} lab wallet → ${t(e.to)}`:e.kind==="deal"?`${Ne(e.item)} ${t(e.to)} → ${t(e.from)}, ${e.amount?`for ${Y(e.amount)}`:"free"}`:`${Y(e.amount)} ${t(e.from)} → ${t(e.to)}`}const KE={own:"its own key",lab:"the lab wallet",parent:"its parent's key (its handoff is cued)",other:"a key outside this lab"},ME={ssh:"shell access, certified by the CA",git:"commit signing",dkim:"mail signing",wg:"WireGuard peer key","ssh-ca":"SSH certificate authority",mtls:"TLS identity between nodes",noise:"Headscale noise key"};function DE(e){var s;const t=Ii(Z,j,e.id),n=q(ft.get(e.id)),r=(s=Dn(Z,Ze,j,e.id))==null?void 0:s.node;return t?n?`${ke(r==null?void 0:r.id)}'s key, in one coin with ${n.name}'s tree while it changes hands`:dt.has(e.id)?`${ke(dt.get(e.id))}'s key: it bought ${e.name}, and adopts it next`:KE[t.who]:"nobody: its inscription has been spent"}function ZE(e){const t=$e(Z.keys,Ee,e),n=["Held now by",DE(e)];if(!t)return S("div",{class:"keys"},S("p",{class:"lab",text:"Keys"}),S("dl",{class:"fl"},[["Signs with","the lab wallet: this holding predates lab keys, so it has no addresses, leaves or secrets of its own"],n].map(is)));const r=e.kind==="agent",s=pl(Z.keys,Ee,e),o=u$(Z.keys,Ee,e),i=o.map(([,,u])=>u).filter(Boolean),a="Reset the lab for standard BIP-86 keys.",c=r?"Holds this seat's inscription, and inscriptions sent to it land here.":"Holds this org's inscription and signs its acts. Inscriptions sent to it land here.",l={bip86:`BIP-86 at ${s.taproot.path}. ${c}`,tapkey:`Its npub's key with the BIP-86 tweak, the way v1.2 keyed this lab. ${c} ${a}`,wallet:`An untweaked key at ${s.taproot.path}, the way v1.1 keyed this lab. ${c} ${a}`}[t.scheme],f=[["Taproot",s.taproot.address,l],["SegWit",s.segwit.address,`BIP-84 at ${s.segwit.path}. Its money: ${e.kind==="holding"?"the beats it earns land here, and ":""}sends come and go here.`],["Tapkey",s.tapkey.address,"Its npub as a Taproot address (its nostr key with the BIP-86 tweak), so the npub alone finds it. Nostr secrets get pasted into clients, so treat it as an inbox."],["npub",s.npub.address,`NIP-06 at ${s.npub.path}. Its nostr name; the leaves below hang off it.`],["Ethereum",s.ethereum.address,r&&e.edge!=="adopted"?`BIP-44 at ${s.ethereum.path}: account ${t.account} of its org's seed, the way Ledger Live numbers Ethereum accounts.`:`BIP-44 at ${s.ethereum.path}. Its legal-control key, the one that holds the entity NFT, as on the lineage key tree page.`],["From",`${t.from} · account ${t.account}`],n,VE(e)];return S("div",{class:"keys"},S("p",{class:"lab",text:"Keys"}),S("dl",{class:"fl"},f.map(is)),e.keyring&&Dr(`${e.keyring.retired?"Retired keyring":"Keyring"} · what each key signed`,_i(e.id,e.keyring.keys)),S("p",{class:"lab"},"Leaves",S("span",{text:` · HKDF-SHA256 from its ${r?"nostr secret":"seed"}`})),S("ul",{class:"list leaves"},o.map(([u,d])=>S("li",{},S("b",{text:u}),S("span",{class:"when",text:` ${ME[u]}`}),S("code",{text:d})))),Dr(r?"Public lines to paste":"CA key for TrustedUserCAKeys",i.join(` + +`)),zE(e,t))}function VE(e){var r,s;const t=e.keyring,n=(t==null?void 0:t.retired)&&(t.retired.by===e.id?"It":((r=q(t.retired.by,Ee))==null?void 0:r.name)??"Its parent");return t?t.retired?["Keyring",`retired at ${ht(t.retired.beat)}`,t.retired.cause==="close"?`${n} closed, which freed the keys it listed.`:t.retired.cause==="move"?`Its tree changed hands to ${((s=q(t.retired.by,Ee))==null?void 0:s.name)??"?"}, so its keys changed with its new parent's seed. Keyring publishes a new one.`:n==="It"?"It graduated, so its keys changed with its new root. Keyring publishes a new one.":`${n} graduated, so ${e.name}'s keys changed with ${n}'s new root. Keyring publishes a new one.`]:["Keyring",`published at ${ht(t.beat)}`,"Each key signed it: Taproot and SegWit by BIP-322, the npub as a nostr event, Ethereum by EIP-191."]:["Keyring","none yet","Keyring publishes one: an inscription that lists these keys, each key signing it."]}function Dr(e,t,n=t){const r=S("pre",{text:n}),s=S("button",{type:"button",class:"cp","aria-label":`Copy ${e}`,onclick:()=>qE(t,s,r)},"Copy");return S("div",{class:"code"},S("div",{class:"code-h cph"},S("span",{text:e}),s),r)}async function qE(e,t,n){const r=s=>{t.textContent=s,setTimeout(()=>{t.textContent="Copy"},1400)};try{await navigator.clipboard.writeText(e),r("Copied")}catch{getSelection().selectAllChildren(n),r("Selected")}}function zE(e,t){var a;const n=I.reveal===e.id,r=n&&g$(Z.keys,Ee,e),s=q(e.parent,Ee),o=()=>{var c;I.reveal=n?null:e.id,_0(),(c=L("reveal"))==null||c.focus()},i=(a=r==null?void 0:r.seed)==null?void 0:a.mnemonic.split(" ");return S("div",{class:"secret"},S("div",{class:"hz"},S("span",{class:"hz-l",text:"Secret · stays in this tab"}),S("button",{type:"button",class:"btn sm",id:"reveal","aria-expanded":String(n),onclick:o},n?"Hide":"Reveal")),r&&S("div",{class:"sb"},r.seed?Dr(`Seed · ${r.seed.from}`,r.seed.mnemonic,i.map((c,l)=>`${String(l+1).padStart(2,"0")} ${c}`).reduce((c,l,f)=>(f%3?c[c.length-1].push(l):c.push([l]),c),[]).map(c=>c.join(" ")).join(` +`)):S("p",{class:"note",text:`A seat has no seed of its own: these are account ${t.account} of ${(s==null?void 0:s.name)??"its org"}'s seed.`}),r.account.map(([c,l,f])=>Dr(`${c} · ${l}`,f)),r.leaves.map(([c,l,f])=>Dr(`${c} · ${l}`,f))))}function FE(e){var i,a,c;const t=(a=(i=Z.chain.transactions.get(e.id.slice(0,-2)))==null?void 0:i.tx.vin.find(l=>{var f;return((f=l.witness)==null?void 0:f.length)===3}))==null?void 0:a.witness;if(!t)return"?";const n=zc(t).pubkey,r=q(e.parent),s=e.op==="found"?q(e.node):null,o=[[s&&$e(Z.keys,j,s),`${s==null?void 0:s.name}'s root`],[r&&$e(Z.keys,j,r),`${r==null?void 0:r.name}'s key`],[(r==null?void 0:r.edge)==="adopted"&&$e(Z.keys,j,{...r,edge:"derived"}),`${r==null?void 0:r.name}'s derived key, from before it graduated`]];for(const[l,f]of o)if(l&&l.wallet.pubkey===n)return f;return((c=Z.wallet)==null?void 0:c.pubkey)===n?"the lab wallet":`a key outside this lab (${n.slice(0,12)}…)`}function WE(e){var o,i,a;const t=ss.events.find(c=>c.id===e.id),n=(i=(o=Z.chain.transactions.get(e.id.slice(0,-2)))==null?void 0:o.inscription)==null?void 0:i.text,r=[["When",e.pending?"cued for the next beat":`beat ${e.beat}`],["Authorized by",e.parent?`${((a=q(e.parent))==null?void 0:a.name)??"an unknown inscription"}, whose inscription this event spent`:"nothing: a founding has no parent"],["Signed by",FE(e)],["Inscription",e.id],n&&["Body",n],(t==null?void 0:t.block)&&["Block",t.block]].filter(Boolean),s=t&&{id:t.id,status:t.status,height:t.height,block:t.block,parent:t.parent??null,metaprotocol:t.metaprotocol??null,contentType:t.contentType,sat:t.sat,location:t.location};return[S("div",{class:"ih"},S("p",{class:"eyebrow",text:`${e.op} · ${e.pending?"cued":`beat ${e.beat}`}`}),S("h3",{class:"it",text:vp(e,j)}),S("div",{class:"chips"},S("span",{class:"chip",text:(t==null?void 0:t.protocol)??"?"}),S("span",{class:`chip ${e.ok?"ok":"bad"}`,text:e.ok?"applied":"rejected"}),...dc(e.id).map(c=>S("span",{class:"chip",title:`ord charm: ${c}`,text:Hl(c)}))),!e.ok&&S("p",{class:"idesc",text:"The reducer rejected this event. It stays on the chain, but it does not change the tree."})),S("div",{class:"ib"},S("dl",{class:"fl"},r.map(is)),S("div",{class:"code"},S("p",{class:"code-h",text:"Metadata · CBOR, tag 5"}),S("pre",{text:Gu(e.meta)})),s&&S("div",{class:"code"},S("p",{class:"code-h",text:"Raw index entry"}),S("pre",{text:Gu(s)})))]}function GE(e){var c;const t=l=>{var f;return((f=q(l))==null?void 0:f.name)??"a key outside this lab"},n=Z.chain.transactions.get(e.txid),r=e.kind==="deal",s=e.kind==="fund",o=fc.get(e.txid),i=o!=null&&o.holders?o.holders.reduce((l,f)=>{var u;return l+(((u=f.ids)==null?void 0:u.length)??1)},0):((c=o==null?void 0:o.ids)==null?void 0:c.length)??1,a=[["When",e.beat===null?"cued for the next beat":`beat ${e.beat}`],r&&(j.nodes.has(e.item)?[e.to?"Org":"Holding",i>1?`${Ne(e.item)} and its tree: ${Cn(i,"inscription")} in one coin, from its key to ${t(e.from)}'s Taproot key. It sold cash-free, and ${t(e.from)} adopts it.`:`${Ne(e.item)}: its inscription, from its own key to ${t(e.from)}'s Taproot key. It sold cash-free, and ${t(e.from)} adopts it.`]:["Item",`${Ne(e.item)}, an inscription: from ${t(e.to)}'s Taproot key to ${t(e.from)}'s`]),["From",e.kind==="mine"?"its share of the beat's block reward (the coinbase)":s?"the lab wallet, standing in for a wallet you already have":`${t(e.from)}'s SegWit address${e.kind==="move"?", from before it graduated":""}`],["To",e.kind==="gas"?`${t(e.to)}'s gas tank, at its Taproot key`:r&&!e.amount?"nobody: a free claim pays no price":e.to===null?"the lab wallet, which plays the owner of every holding":`${t(e.to)}'s ${e.kind==="move"?"new ":""}SegWit address`],[r?"Price":"Amount",r&&!e.amount?"nothing":Y(e.amount)],e.kind!=="mine"&&["Fee",`${e.fee} sats${e.ask?` over two transactions (the buyer's split, then the deal), and a ${Et}-sat coin of the buyer's that leads the deal and pads the lot's coin now`:""}, retired: this toy chain pays no fees to miners`],e.change>0&&["Change",`${Y(e.change)} back to ${s?"the lab wallet":t(e.from)}`],["Signed by",e.kind==="mine"?"nobody: a coinbase spends nothing":s?"the lab wallet's Taproot key":r&&e.ask?`the lot's Taproot key (SIGHASH_SINGLE|ANYONECANPAY) when ${e.to?t(e.to):"its owner"} listed it, then ${t(e.from)}'s SegWit key (SIGHASH_ALL) when it took it`:r&&j.nodes.has(e.item)?`${t(e.from)}'s SegWit key (SIGHASH_ALL) when it made the offer, then the Taproot keys that held ${i>1?"its tree":"it"}, when ${e.to?t(e.to):"its owner"} accepted`:r?`${t(e.from)}'s SegWit key (SIGHASH_ALL) when it made the offer, then ${t(e.to)}'s Taproot key when it accepted`:`${t(e.from)}'s SegWit key (BIP-143, SIGHASH_ALL)`],["Transaction",e.txid]].filter(Boolean);return[S("div",{class:"ih"},S("p",{class:"eyebrow",text:`${e.kind} · ${e.beat===null?"cued":`beat ${e.beat}`}`}),S("h3",{class:"it",text:T0(e)}),S("div",{class:"chips"},S("span",{class:"chip",text:"test BTC"}),S("span",{class:`chip${e.beat===null?"":" ok"}`,text:e.beat===null?"cued":"confirmed"}))),S("div",{class:"ib"},S("dl",{class:"fl"},a.map(is)),n&&Dr("Raw transaction",n.raw))]}function jl(){const e=ut(),t=L("beat"),n=q(I.holding);t.max=String(e),t.value=String(I.beat??e),t.disabled=e===0,L("beat-label").textContent=I.beat===null?`Now · beat ${e}`:`Beat ${I.beat} of ${e}`,L("replay").textContent=I.replay?"Stop":"Replay",L("replay").disabled=!n||e===0,L("to-now").disabled=I.beat===null,L("timeline-sub").textContent=(n==null?void 0:n.name)??"";const r=new Map,s=new Map([...Z.chain.transactions.keys()].map((a,c)=>[a,c])),o=(a,c)=>r.set(a,[...r.get(a)??[],c]);for(const a of j.log)a.roots.some(c=>{var l;return((l=q(c))==null?void 0:l.root)===I.holding})&&o(a.pending?"cued":a.beat,{e:a,at:s.get(a.id.slice(0,-2))??0});for(const a of ze.ledger)[a.to,a.from].some(c=>{var l;return c&&((l=q(c))==null?void 0:l.root)===I.holding})&&o(a.beat??"cued",{m:a,at:s.get(a.txid)??0});const i=[...r.keys()].sort((a,c)=>a==="cued"?-1:c==="cued"?1:c-a);if(!i.length)return L("timeline-list").replaceChildren(S("li",{class:"wait",text:n?"Nothing yet.":"Found a holding to start its timeline."}));L("timeline-list").replaceChildren(...i.map(a=>{const c=a==="cued"?null:Z.chain.blocks[a-1],l=I.beat!==null&&(a==="cued"||a>I.beat),f=I.beat!==null&&a===I.beat;return S("li",{class:`beat${l?" later":""}${f?" now":""}`},S("p",{class:"bh"},S("span",{class:"bn",text:a==="cued"?"Cued":`Beat ${a}`}),S("span",{class:"bt",text:c?rE(c.time):Z.clock.tempo==="manual"?"waiting for Beat now":"landing on the next beat"})),S("ol",{class:"evs"},r.get(a).sort((u,d)=>u.at-d.at).map(({e:u,m:d})=>d?XE(d):YE(u))))}))}function YE(e){const[t,...n]=vp(e,j).split(" ");return S("li",{},S("button",{type:"button",class:`ev${e.ok?"":" bad"}${e.id===I.event?" on":""}`,"aria-pressed":String(e.id===I.event),onclick:()=>Br({event:e.id,node:e.node??I.node})},S("span",{class:"op",text:e.ok?t:`✕ ${t.replace(/:$/,"")}`})," ",S("span",{class:"es",text:n.join(" ")})))}const XE=e=>S("li",{},S("button",{type:"button",class:`ev money${e.kind==="gas"?" gas":""}${e.kind==="deal"?" deal":""}${e.key===I.tx?" on":""}`,"aria-pressed":String(e.key===I.tx),onclick:()=>{var t;return Br({tx:e.key,node:((t=q(e.to))==null?void 0:t.root)===I.holding?e.to:I.node})}},S("span",{class:"op",text:e.kind})," ",S("span",{class:"es",text:T0(e)})));L("f-found").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=Qs(t.elements.name.value);if(!n)return he("Name the holding: lowercase letters, digits and hyphens.",!0);await qt("found",null,{name:n},(r,s)=>(Nl({holding:r,node:r}),`${n} is founded, ${s}.`))&&t.reset()});L("sample").addEventListener("click",async()=>{let e=null;he("Rehearsing the yolopreneur tree over six beats…"),await tt(t=>{e=nE(t)})&&(Br({holding:e,node:e}),he("Loaded the yolopreneur sample: six beats of history, ending on both sides of a deal: lineage's offer for sol's launch-kit, and well-known's ask for mailr. Press Replay to watch it grow."))});L("f-birth").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=q(I.node),r=Qs(t.elements.name.value),s=t.elements.kind.value;if(!r)return he("Name the child: lowercase letters, digits and hyphens.",!0);await qt("birth",n.id,{name:r,kind:s},(o,i)=>`${r} is born to ${n.name}, ${i}.`)&&(t.elements.name.value="")});L("f-award").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=q(I.node),r=t.elements.to.value,s=Qs(t.elements.skill.value),o=t.elements.belt.value;if(!s)return he("Name the skill, for example launch.",!0);await qt("award",n.id,{to:r,skill:s,belt:o},(i,a)=>{var c;return`${(c=q(r))==null?void 0:c.name} holds a ${o} belt in ${s}, ${a}, on its own sat.`})&&(t.elements.skill.value="")});L("f-decide").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=q(I.node),r=t.elements.title.value.trim(),s=t.elements.why.value.trim();if(!r)return he("A decision needs a title.",!0);await qt("decide",n.id,{title:r,why:s},(o,i)=>`${n.name} decided “${r}”, ${i}.`)&&t.reset()});L("f-send").addEventListener("submit",async e=>{var a;e.preventDefault();const t=e.currentTarget,n=q(I.node),r=t.elements.to.value,s=Ci(t.elements.amount.value);if(s===null)return he("Write an amount in test BTC, for example 1.5 (at most eight decimals).",!0);let o=null;if(!await tt(c=>{o=q$(c,n.id,r,s)}))return;const i=ze.ledger.find(c=>c.txid===o);he(`${n.name} sent ${Y(s)} to ${((a=q(r))==null?void 0:a.root)===n.root?q(r).name:ts(j,r)}, ${i!=null&&i.beat?`at beat ${i.beat}`:"cued for the next beat"}.`),t.elements.amount.value=""});L("f-make").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=q(I.node),r=Qs(t.elements.name.value),s=t.elements.note.value.trim();if(!r)return he("Name the item: lowercase letters, digits and hyphens.",!0);await qt("make",n.id,{name:r,note:s},(o,i)=>`${n.name} made ${r}, ${i}.`)&&t.reset()});L("f-charter").addEventListener("change",e=>{e.target.name==="form"&&ds()});L("charter-file").addEventListener("change",async e=>{var r;const t=(r=e.target.files)==null?void 0:r[0];if(!t)return;const n=new Uint8Array(await crypto.subtle.digest("SHA-256",await t.arrayBuffer()));L("charter-filing").value=[...n].map(s=>s.toString(16).padStart(2,"0")).join(""),e.target.value="",he(`Hashed ${t.name} in this tab: only its SHA-256 would go on chain.`)});L("f-charter").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=q(I.node),r=pi();if(!r)return he("Pick a legal form.",!0);if(r==="series"){const a=Di(n);await qt("charter",a.id,{form:"series",of:n.id},(c,l)=>`${n.name} is a series of ${a.name}, ${l}.`);return}const s=a=>t.querySelector(`[name="${a}"]`).value.trim(),o={form:r,jurisdiction:s("jurisdiction").toUpperCase(),legal:s("legal"),provider:Qs(s("provider")),filing:s("filing").toLowerCase()},i=(a,c)=>`${n.name} is chartered as ${wE[r]}${o.jurisdiction?` in ${o.jurisdiction}`:""}, ${c}.`;if(await qt("charter",n.id,o,i))for(const a of["legal","filing"])t.querySelector(`[name="${a}"]`).value=""});L("f-keyring").addEventListener("submit",async e=>{e.preventDefault();const t=q(I.node);await qt("keyring",t.id,{},(n,r)=>`${t.name} published its keyring, ${r}: four keys, each signing the same statement.`)});L("f-offer").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=q(I.node),r=L("offer-item").value,s=Ci(t.elements.price.value);if(s===null)return he("Write a price in test BTC, for example 0.1, or 0 for a free claim.",!0);const o=q(r),i=Ne(r),a=j.items.has(r)?ke(At.get(r)):(o==null?void 0:o.root)===(o==null?void 0:o.id)?`${i}'s owner`:ke(o==null?void 0:o.parent);await tt(c=>{z$(c,r,n.id,s)})&&(he(`${n.name} offers ${s?Y(s):"nothing"} for ${i}. The offer stands until ${a} accepts it.`),t.elements.price.value="")});L("offer-take").addEventListener("click",async()=>{const e=q(I.node),t=L("offer-item").value,n=ot.get(t),r=j.nodes.has(t);if(!n)return;const s=Ne(t),o=ke(n.seller);if(!await tt(c=>{J$(c,Ar(n),e.id)}))return;const i=ze.ledger.findLast(c=>c.kind==="deal"&&c.item===t),a=i!=null&&i.beat?`at beat ${i.beat}`:"cued for the next beat";if(!r)return he(`${e.name} took ${s} from ${o} for ${Y(n.price)}, ${a}.`);Br({holding:e.root,node:t}),he(`${e.name} bought ${s}${n.seller?` from ${o}`:" whole"} for ${Y(n.price)} and adopted it, ${a}: its keys derive from ${e.name}'s seed now.`)});L("f-sell").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=q(I.node),r=L("sell-lot").value,s=Ci(t.elements.price.value),o=j.nodes.has(r);if(s===null)return he("Write a price in test BTC, for example 1.",!0);const i=Ne(r);await tt(a=>{l0(a,r,s)})&&(he(r===n.id?`${n.name}'s owner lists it whole at ${Y(s)}: any node can take it. The money in its tree went to the lab wallet first, its items go with it, and it's frozen until the ask is taken or withdrawn.`:`${n.name} lists ${i} at ${Y(s)}: any node can take it.${o?` The money in its tree went home to ${n.name} first, its items go with it, and it's frozen until the ask is taken or withdrawn.`:""}`),t.elements.price.value="")});for(const e of["offer-item","sell-lot","award-to"])L(e).addEventListener("change",()=>ds());L("send-max").addEventListener("click",()=>{const e=q(I.node),t=e&&xe(Z.keys,j,e);t&&(L("send-amount").value=Up(bl(Z.chain.coins(t.script))))});L("f-graduate").addEventListener("submit",async e=>{e.preventDefault();const t=q(I.node),n=q(t.parent);await qt("graduate",n.id,{of:t.id},(r,s)=>(Nl({node:t.id}),`${t.name} graduates from ${n.name}, ${s}. It's a holding of its own now.`))});L("f-close").addEventListener("submit",async e=>{e.preventDefault();const t=q(I.node);if(I.closing!==t.id)return I.closing=t.id,ds(),L("close-go").focus();I.closing=null,await qt("close",t.id,{},(n,r)=>`${t.name} is closed, ${r}.`)});L("close-keep").addEventListener("click",()=>{I.closing=null,ds(),L("close-go").focus()});for(const e of document.querySelectorAll("[data-verb]"))e.addEventListener("click",()=>{I.verb=e.dataset.verb,I.closing=null,ds()});for(const e of document.querySelectorAll("[data-rule]"))e.addEventListener("click",async()=>{const t=e.dataset.rule;await tt(n=>N$(n,t))&&he({split:"Each beat splits across the holdings that mine, by hashrate.",last:"Each beat goes whole to the holding that acts.",none:"Mainnet: no holding mines. Beats pay the lab wallet, and you fund holdings from it."}[t])});L("f-fund").addEventListener("submit",async e=>{var i;e.preventDefault();const t=e.currentTarget,n=t.elements.to.value,r=Ci(t.elements.amount.value);if(r===null)return he("Write an amount in test BTC, for example 5 (at most eight decimals).",!0);let s=null;if(!await tt(a=>{s=eE(a,n,r)}))return;const o=ze.ledger.find(a=>a.txid===s);he(`The lab wallet funded ${(i=q(n))==null?void 0:i.name} with ${Y(r)}, ${o!=null&&o.beat?`at beat ${o.beat}`:"cued for the next beat"}.`),t.elements.amount.value=""});for(const e of document.querySelectorAll("[data-tempo]"))e.addEventListener("click",async()=>{const t=e.dataset.tempo,n=/^\d+$/.test(t)?Number(t):t;await tt(r=>R$(r,n,Date.now(),Ki(r,Pl(r)??I.holding)))&&he(t==="each"?"Each act is its own beat.":t==="manual"?"Acts are cued until you press Beat now.":`Acts are cued and land together on the next beat, at most ${t} seconds after the first.`)});L("beat-now").addEventListener("click",()=>h0(e=>{at(e,Ki(e,Pl(e)??I.holding))}));setInterval(()=>{p0();const{tempo:e,nextAt:t}=Z.clock;I.busy||document.hidden||typeof e!="number"||!Z.chain.mempool.length||t&&Date.now()j$(n,Date.now(),Ki(n,Pl(n)??I.holding)))},1e3);addEventListener("storage",e=>{(e.key===Li||e.key===null)&&d0()});function so(){I.replay&&(clearInterval(I.replay),I.replay=null,jl())}function JE(){const e=q(I.holding);if(!(!e||!ut())){if(hi(typeof e.born=="number"?e.born:ut()),I.beat===null)return he("Nothing to replay yet: this holding has one beat of history.");I.replay=setInterval(()=>{(I.beat===null||I.beat+1>=ut())&&so(),hi(I.beat===null?ut():I.beat+1)},800),jl()}}L("beat").addEventListener("input",e=>{so(),hi(Number(e.target.value))});L("replay").addEventListener("click",()=>I.replay?so():JE());for(const e of["to-now","past-now"])L(e).addEventListener("click",()=>{so(),hi(ut())});const ka=["system","light","dark"],O0=()=>{L("theme").textContent=`Theme: ${document.documentElement.dataset.theme??"system"}`};L("theme").addEventListener("click",()=>{const e=ka[(ka.indexOf(document.documentElement.dataset.theme??"system")+1)%ka.length];e==="system"?delete document.documentElement.dataset.theme:document.documentElement.dataset.theme=e;try{e==="system"?localStorage.removeItem("orgchain-theme"):localStorage.setItem("orgchain-theme",e)}catch{}O0()});function I0(e,t,n){const r=L("confirm");r.replaceChildren(S("span",{text:e}),S("button",{type:"button",class:"btn sm danger",text:t,onclick:()=>{r.hidden=!0,n()}}),S("button",{type:"button",class:"btn sm",text:"Cancel",onclick:()=>{r.hidden=!0}})),r.hidden=!1,r.querySelector("button").focus()}const QE={read:()=>{try{return Tl()}catch{return no()}}};async function C0(e,t){so(),await tt(n=>{Object.assign(n,e())},QE)&&(Object.assign(I,{holding:null,node:null,event:null,tx:null,beat:null,closing:null}),Ll(),he(t))}L("save").addEventListener("click",()=>{const e=S("a",{href:URL.createObjectURL(new Blob([Qp(Z)],{type:"application/json"})),download:`orgchain-lab-${new Date().toISOString().slice(0,10)}.json`});document.body.append(e),e.click(),e.remove(),setTimeout(()=>URL.revokeObjectURL(e.href),5e3),he("Saved a backup of this lab, test wallet included. Load it in any browser to carry on.")});L("load").addEventListener("click",()=>L("load-file").click());L("load-file").addEventListener("change",async e=>{var r;const t=(r=e.target.files)==null?void 0:r[0];if(e.target.value="",!t)return;let n;try{n=Jp(await t.text())}catch(s){return he(`${t.name} is not an Orgchain lab: ${s.message}`,!0)}I0(`Replace this browser's lab with ${t.name}?`,"Replace",()=>C0(()=>n,`Loaded ${t.name}.`))});L("reset").addEventListener("click",()=>I0("Erase this browser's lab: every holding, the chain and the test wallet?","Erase",()=>C0(no,"Erased. This is a fresh lab.")));O0();d0(); diff --git a/ventures/lineage/orgchain/index.html b/ventures/lineage/orgchain/index.html index 6b63ef9..5403f57 100644 --- a/ventures/lineage/orgchain/index.html +++ b/ventures/lineage/orgchain/index.html @@ -8,7 +8,7 @@ - +