diff --git a/ventures/lineage/orgchain/assets/index-Ce2tG4vI.js b/ventures/lineage/orgchain/assets/index-Ce2tG4vI.js new file mode 100644 index 0000000..a08b57c --- /dev/null +++ b/ventures/lineage/orgchain/assets/index-Ce2tG4vI.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 Oo=5e9,Ll=2**52,zu=(e,t)=>[[Ll+e*Oo,Ll+e*Oo+t]];function Fu(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 Wu(e,t){var n;return(n=Fu(e,t,1)[0])==null?void 0:n[0]}function xs(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=Fu(s,o,Number(i.value));return o+=Number(i.value),a})}function xa(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function _0(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function Yu(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 A0(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");xa(e.outputLen),xa(e.blockLen)}function B0(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 T0(e,t){Yu(e);const n=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),Ct=(e,t)=>e<<32-t|e>>>t,I0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!I0)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function C0(e){if(typeof e!="string")throw new TypeError(`utf8ToBytes expected string, got ${typeof e}`);return new TextEncoder().encode(e)}function Xu(e){if(typeof e=="string"&&(e=C0(e)),!(e instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof e})`);return e}let P0=class{clone(){return this._cloneInto()}};function Ju(e){const t=r=>e().update(Xu(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function U0(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 N0=class extends P0{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=Mi(this.buffer)}update(t){Di.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=Xu(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,H0=(e,t,n)=>e&t^e&n^t&n,R0=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]),un=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),fn=new Uint32Array(64);let Qu=class extends N0{constructor(){super(64,32,8,!1),this.A=un[0]|0,this.B=un[1]|0,this.C=un[2]|0,this.D=un[3]|0,this.E=un[4]|0,this.F=un[5]|0,this.G=un[6]|0,this.H=un[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)fn[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const d=fn[u-15],p=fn[u-2],g=Ct(d,7)^Ct(d,18)^d>>>3,h=Ct(p,17)^Ct(p,19)^p>>>10;fn[u]=h+fn[u-7]+g+fn[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),p=f+d+L0(a,c,l)+R0[u]+fn[u]|0,h=(Ct(r,2)^Ct(r,13)^Ct(r,22))+H0(r,s,o)|0;f=l,l=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,l=l+this.G|0,f=f+this.H|0,this.set(r,s,o,i,a,c,l,f)}roundClean(){fn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},j0=class extends Qu{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 va=Ju(()=>new Qu);Ju(()=>new j0);function K0(e,t){if(e.length>t)throw new TypeError(`Data is larger than array size: ${e.length} > ${t}`)}function D0(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 M0(e){if(e>Number.MAX_SAFE_INTEGER)throw new TypeError("Number exceeds safe bounds!")}const{getRandomValues:Z0}=crypto??globalThis.crypto??window.crypto;function V0(e=32){if(typeof Z0=="function")return crypto.getRandomValues(new Uint8Array(e));throw new Error("Crypto module missing getRandomValues!")}function q0(e,t,n="be"){t===void 0&&(t=e.length),K0(e,t);const r=new Uint8Array(t).fill(0),s=n==="be"?0:t-e.length;return r.set(e,s),r}function ef(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 G0(e,t){const n=tf(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 nf(e){return va(va(e))}function Y0(e){const t=nf(e);return ef([e,t.slice(0,4)])}function X0(e){const t=e.slice(0,-4),n=e.slice(-4);if(nf(t).slice(0,4).toString()!==n.toString())throw new Error("Invalid checksum!");return t}const Hl={encode:W0,decode:G0},rf={encode:e=>{const t=Y0(e);return Hl.encode(t,"base58")},decode:e=>{const t=Hl.decode(e,"base58");return X0(t)}},sf="qpzry9x8gf2tvdw0s3jn54khce6mua7l",J0=[996825010,642813549,513874426,1027748829,705979059],Io=[{version:0,name:"bech32",const:1},{version:1,name:"bech32m",const:734539939}];function of(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^=J0[s])}return t}function af(e){const t=[];let n;for(n=0;n>5);for(t.push(0),n=0;n>5*(5-i)&31);return o}function cf(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 tg(e,t,n){const r=t.concat(eg(e,t,n));let s=e+"1";for(let o=0;oo.version===t[0])??Io[0];if(!Q0(r,t,s))throw new Error("Checksum verification failed!");return[r,t.slice(0,t.length-6)]}function ng(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 rg(e){const t=e.lastIndexOf("1");return!(t<1||t+7>e.length||e.length>90)}function sg(e,t="bc",n=0){const r=[n,...cf([...e],8,5)],s=Io.find(i=>i.version===n)??Io[0],o=tg(t,r,s);return uf(o),o}function uf(e){e=e.toLowerCase();const t=e.split("1",1)[0],[n,r]=lf(e),s=cf(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 og(e){e=e.toLowerCase();const[t,n]=lf(e);return n[0]}const ff={encode:sg,decode:uf,version:og},df="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",hf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",ig=new TextEncoder;function pf(e,t=!1,n=!0){typeof e=="string"&&(e=ig.encode(e));const r=t?hf:df;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 gf(e,t=!1){const n=t||e.includes("-")||e.includes("_")?hf.split(""):df.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 mf={encode:pf,decode:gf},yf={encode:e=>pf(e,!0,!1),decode:e=>gf(e,!0)},ag=BigInt(0),cg=BigInt(255),wf=BigInt(256);function lg(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 ug(e,t,n="be"){t===void 0&&(t=lg(e));const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(;e>ag;){const a=e&cg,c=Number(a);r?o.setUint8(i++,c):o.setUint8(i--,c),e=(e-a)/wf}return new Uint8Array(s)}function fg(e){let t=BigInt(0);for(let n=e.length-1;n>=0;n--)t=t*wf+BigInt(e[n]);return BigInt(t)}function dg(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 pg(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 gg(e,t,n="be"){t===void 0&&(t=pg(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 mg(e){let t=0;for(let n=e.length-1;n>=0;n--)t=t*256+e[n],M0(t);return t}const yg=new TextEncoder,wg=new TextDecoder;function lc(e){return yg.encode(e)}function Zi(e){return wg.decode(e)}function bg(e,t){D0(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 xg(e,t,n="le"){t=bg(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 lc(t)}function $g(e,t,n){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Uint8Array)return q0(e,t,n);if(typeof e=="string")return xg(e,t,n);if(typeof e=="bigint")return ug(e,t,n);if(typeof e=="number")return gg(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=V0(t);return new re(n,t)}constructor(t,n,r){const s=$g(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 os(this)}toNum(t="be"){const n=t==="be"?this.reverse():this;return mg(n)}toBin(){return hg(this)}toBig(t="be"){const n=t==="be"?this.reverse():this;return fg(n)}toHash(){const t=va(this);return new re(t)}toJson(){const t=Zi(this);return JSON.parse(t)}toBech32(t,n=0){return ff.encode(this,t,n)}toStr(){return Zi(this)}toHex(){return vg(this)}toBytes(){return new Uint8Array(this)}tob58chk(){return rf.encode(this)}toBase64(){return mf.encode(this)}toB64url(){return yf.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=ef(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=Eg,re.big=_g,re.bin=Sg,re.raw=Ag,re.str=Bg,re.hex=Tg,re.bytes=Og,re.json=Ig,re.base64=Cg,re.b64url=Pg,re.bech32=Ug,re.b58chk=Ng,re.encode=lc,re.decode=Zi,re);function Eg(e,t,n){return new B(e,t,n)}function Sg(e,t,n){return new B(dg(e),t,n)}function _g(e,t,n){return new B(e,t,n)}function Ag(e,t,n){return new B(e,t,n)}function Bg(e,t,n){return new B(lc(e),t,n)}function Tg(e,t,n){return new B(e,t,n)}function Og(e,t,n){return new B(e,t,n)}function Ig(e){return new B(kg(e))}function Cg(e){return new B(mf.decode(e))}function Pg(e){return new B(yf.decode(e))}function Ug(e){return new B(ff.decode(e))}function Ng(e){return new B(rf.decode(e))}let os=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 zt(e,t){const n=B.bytes(e);if(n.length!==t)throw new Error(`Invalid input size: ${n.hex} !== ${t}`)}function Ye(e,t){if(t)throw new Error(e);return!1}function $o(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 bf={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 Lg(e){if(e>186&&e<255)return"OP_SUCCESS"+String(e);for(const[t,n]of Object.entries(bf))if(n===e)return t;throw new Error("OPCODE not found:"+String(e))}function Hg(e){for(const[t,n]of Object.entries(bf))if(t===e)return Number(n);throw new Error("OPCODE not found:"+e)}function Rg(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 jg(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 Kg(e){let t=new Uint8Array;if(typeof e=="string"){if(e.startsWith("OP_"))return B.num(Hg(e),1);ln(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([Rl(t.length),t]));if(t.length>Co){const n=Dg(t);return vf(n)}else return B.join([Rl(t.length),t])}function Rl(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<=Co):return B.join([n,B.num(e,2,"le")]);default:throw new Error("Invalid word size:"+e.toString())}}function Dg(e){const t=[],n=new os(e);for(;n.size>Co;)t.push(n.read(Co));return t.push(n.read(n.size)),t}function uc(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 Mg(n)}function Mg(e){const t=new os(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 Wg(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ka(e.outputLen),ka(e.blockLen)}function Gg(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 Yg(e,t){kf(e);const n=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),Pt=(e,t)=>e<<32-t|e>>>t,Jg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Jg)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Qg(e){if(typeof e!="string")throw new TypeError(`utf8ToBytes expected string, got ${typeof e}`);return new TextEncoder().encode(e)}function fc(e){if(typeof e=="string"&&(e=Qg(e)),!(e instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof e})`);return e}function em(...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(fc(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function tm(e=32){if(Vi&&typeof Vi.getRandomValues=="function")return Vi.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function nm(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 rm=class extends $f{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){Yn.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=fc(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,om=(e,t,n)=>e&t^e&n^t&n,im=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 rm{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 u=0;u<16;u++,n+=4)hn[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const d=hn[u-15],p=hn[u-2],g=Pt(d,7)^Pt(d,18)^d>>>3,h=Pt(p,17)^Pt(p,19)^p>>>10;hn[u]=h+hn[u-7]+g+hn[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),p=f+d+sm(a,c,l)+im[u]+hn[u]|0,h=(Pt(r,2)^Pt(r,13)^Pt(r,22))+om(r,s,o)|0;f=l,l=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,l=l+this.G|0,f=f+this.H|0,this.set(r,s,o,i,a,c,l,f)}roundClean(){hn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},am=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 _f=Ef(()=>new Sf);Ef(()=>new am);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const cm=BigInt(0),dc=BigInt(1),lm=BigInt(2),pi=e=>e instanceof Uint8Array,um=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Mr(e){if(!pi(e))throw new Error("Uint8Array expected");let t="";for(let n=0;nZr(e.toString(16).padStart(t*2,"0")),Bf=(e,t)=>Nr(e,t).reverse(),fm=e=>Zr(Af(e));function gt(e,t,n){let r;if(typeof t=="string")try{r=Zr(t)}catch(o){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${o}`)}else if(pi(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(!pi(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}function dm(e,t){if(e.length!==t.length)return!1;for(let n=0;n0n;e>>=dc,t+=1);return t}const pm=(e,t)=>e>>BigInt(t)&1n,gm=(e,t,n)=>e|(n?dc:cm)<(lm<new Uint8Array(e),jl=e=>Uint8Array.from(e);function Tf(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=zi(e),s=zi(e),o=0;const i=()=>{r.fill(1),s.fill(0),o=0},a=(...u)=>n(s,r,...u),c=(u=zi())=>{s=a(jl([0]),u),r=a(),u.length!==0&&(s=a(jl([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 p;for(;!(p=d(l()));)c();return i(),p}}const mm={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 is(e,t,n={}){const r=(s,o,i)=>{const a=mm[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 ym=Object.freeze({__proto__:null,bitGet:pm,bitLen:hm,bitMask:gc,bitSet:gm,bytesToHex:Mr,bytesToNumberBE:Tn,bytesToNumberLE:pc,concatBytes:kt,createHmacDrbg:Tf,ensureBytes:gt,equalBytes:dm,hexToBytes:Zr,hexToNumber:hc,numberToBytesBE:Nr,numberToBytesLE:Bf,numberToHexUnpadded:Af,numberToVarBytesBE:fm,utf8ToBytes:gi,validateObject:is});/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ve=BigInt(0),He=BigInt(1),Fn=BigInt(2),wm=BigInt(3),$a=BigInt(4),Kl=BigInt(5),Dl=BigInt(8);BigInt(9);BigInt(16);function Xe(e,t){const n=e%t;return n>=Ve?n:t+n}function bm(e,t,n){if(n<=Ve||t 0");if(n===He)return Ve;let r=He;for(;t>Ve;)t&He&&(r=r*e%n),e=e*e%n,t>>=He;return r}function pt(e,t,n){let r=e;for(;t-- >Ve;)r*=r,r%=n;return r}function Ea(e,t){if(e===Ve||t<=Ve)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let n=Xe(e,t),r=t,s=Ve,o=He;for(;n!==Ve;){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 Xe(s,t)}function xm(e){const t=(e-He)/Fn;let n,r,s;for(n=e-He,r=0;n%Fn===Ve;n/=Fn,r++);for(s=Fn;s(r[s]="function",r),t);return is(e,n)}function $m(e,t,n){if(n 0");if(n===Ve)return e.ONE;if(n===He)return t;let r=e.ONE,s=t;for(;n>Ve;)n&He&&(r=e.mul(r,s)),s=e.sqr(s),n>>=He;return r}function Em(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 mc(e,t){const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function If(e,t,n=!1,r={}){if(e<=Ve)throw new Error(`Expected Fp ORDER > 0, got ${e}`);const{nBitLength:s,nByteLength:o}=mc(e,t);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");const i=vm(e),a=Object.freeze({ORDER:e,BITS:s,BYTES:o,MASK:gc(s),ZERO:Ve,ONE:He,create:c=>Xe(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Ve<=c&&cc===Ve,isOdd:c=>(c&He)===He,neg:c=>Xe(-c,e),eql:(c,l)=>c===l,sqr:c=>Xe(c*c,e),add:(c,l)=>Xe(c+l,e),sub:(c,l)=>Xe(c-l,e),mul:(c,l)=>Xe(c*l,e),pow:(c,l)=>$m(a,c,l),div:(c,l)=>Xe(c*Ea(l,e),e),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Ea(c,e),sqrt:r.sqrt||(c=>i(a,c)),invertBatch:c=>Em(a,c),cmov:(c,l,f)=>f?l:c,toBytes:c=>n?Bf(c,o):Nr(c,o),fromBytes:c=>{if(c.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${c.length}`);return n?pc(c):Tn(c)}});return Object.freeze(a)}function Sm(e,t,n=!1){e=gt("privateHash",e);const r=e.length,s=mc(t).nByteLength+8;if(s<24||r1024)throw new Error(`hashToPrivateScalar: expected ${s}-1024 bytes of input, got ${r}`);const o=n?pc(e):Tn(e);return Xe(o,t-He)+He}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _m=BigInt(0),Fi=BigInt(1);function Am(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>_m;)o&Fi&&(i=i.add(a)),a=a.double(),o>>=Fi;return i},precomputeWindow(s,o){const{windows:i,windowSize:a}=r(o),c=[];let l=s,f=l;for(let u=0;u>=p,w>c&&(w-=d,i+=Fi);const m=h,x=h+Math.abs(w)-1,y=g%2!==0,$=w<0;w===0?f=f.add(n(y,o[m])):l=l.add(n($,o[x]))}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 Cf(e){return Of(e.Fp),is(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...mc(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Bm(e){const t=Cf(e);is(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:Tm,hexToBytes:Om}=ym,Xn={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){const{Err:t}=Xn;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:Tm(r),l:e.subarray(n+2)}},toSig(e){const{Err:t}=Xn,n=typeof e=="string"?Om(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}=Xn._parseInt(n.subarray(2)),{d:i,l:a}=Xn._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),Po=BigInt(3),Ml=BigInt(4);function Im(e){const t=Bm(e),{Fp:n}=t,r=t.toBytes||((g,h,w)=>{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),w=n.fromBytes(h.subarray(0,n.BYTES)),m=n.fromBytes(h.subarray(n.BYTES,2*n.BYTES));return{x:w,y:m}});function o(g){const{a:h,b:w}=t,m=n.sqr(g),x=n.mul(m,g);return n.add(n.add(x,n.mul(g,h)),w)}function i(g){return typeof g=="bigint"&&$tn.eql(y,n.ZERO);return x(w)&&x(m)?u.ZERO:new u(w,m,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){const w=n.invertBatch(h.map(m=>m.pz));return h.map((m,x)=>m.toAffine(w[x])).map(u.fromAffine)}static fromHex(h){const w=u.fromAffine(s(gt("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return u.BASE.multiply(c(h))}_setWindowSize(h){this._WINDOW_SIZE=h,l.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint)return;throw new Error("bad point: ZERO")}const{x:h,y:w}=this.toAffine();if(!n.isValid(h)||!n.isValid(w))throw new Error("bad point: x or y not FE");const m=n.sqr(w),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:w,py:m,pz:x}=this,{px:y,py:$,pz:b}=h,O=n.eql(n.mul(w,b),n.mul(y,x)),C=n.eql(n.mul(m,b),n.mul($,x));return O&&C}negate(){return new u(this.px,n.neg(this.py),this.pz)}double(){const{a:h,b:w}=t,m=n.mul(w,Po),{px:x,py:y,pz:$}=this;let b=n.ZERO,O=n.ZERO,C=n.ZERO,N=n.mul(x,x),I=n.mul(y,y),R=n.mul($,$),A=n.mul(x,y);return A=n.add(A,A),C=n.mul(x,$),C=n.add(C,C),b=n.mul(h,C),O=n.mul(m,R),O=n.add(b,O),b=n.sub(I,O),O=n.add(I,O),O=n.mul(b,O),b=n.mul(A,b),C=n.mul(m,C),R=n.mul(h,R),A=n.sub(N,R),A=n.mul(h,A),A=n.add(A,C),C=n.add(N,N),N=n.add(C,N),N=n.add(N,R),N=n.mul(N,A),O=n.add(O,N),R=n.mul(y,$),R=n.add(R,R),N=n.mul(R,A),b=n.sub(b,N),C=n.mul(R,I),C=n.add(C,C),C=n.add(C,C),new u(b,O,C)}add(h){f(h);const{px:w,py:m,pz:x}=this,{px:y,py:$,pz:b}=h;let O=n.ZERO,C=n.ZERO,N=n.ZERO;const I=t.a,R=n.mul(t.b,Po);let A=n.mul(w,y),P=n.mul(m,$),k=n.mul(x,b),S=n.add(w,m),v=n.add(y,$);S=n.mul(S,v),v=n.add(A,P),S=n.sub(S,v),v=n.add(w,x);let _=n.add(y,b);return v=n.mul(v,_),_=n.add(A,k),v=n.sub(v,_),_=n.add(m,x),O=n.add($,b),_=n.mul(_,O),O=n.add(P,k),_=n.sub(_,O),N=n.mul(I,v),O=n.mul(R,k),N=n.add(O,N),O=n.sub(P,N),N=n.add(P,N),C=n.mul(O,N),P=n.add(A,A),P=n.add(P,A),k=n.mul(I,k),v=n.mul(R,v),P=n.add(P,k),k=n.sub(A,k),k=n.mul(I,k),v=n.add(v,k),A=n.mul(P,v),C=n.add(C,A),A=n.mul(_,v),O=n.mul(S,O),O=n.sub(O,A),A=n.mul(S,P),N=n.mul(_,N),N=n.add(N,A),new u(O,C,N)}subtract(h){return this.add(h.negate())}is0(){return this.equals(u.ZERO)}wNAF(h){return p.wNAFCached(this,l,h,w=>{const m=n.invertBatch(w.map(x=>x.pz));return w.map((x,y)=>x.toAffine(m[y])).map(u.fromAffine)})}multiplyUnsafe(h){const w=u.ZERO;if(h===$t)return w;if(a(h),h===je)return this;const{endo:m}=t;if(!m)return p.unsafeLadder(this,h);let{k1neg:x,k1:y,k2neg:$,k2:b}=m.splitScalar(h),O=w,C=w,N=this;for(;y>$t||b>$t;)y&je&&(O=O.add(N)),b&je&&(C=C.add(N)),N=N.double(),y>>=je,b>>=je;return x&&(O=O.negate()),$&&(C=C.negate()),C=new u(n.mul(C.px,m.beta),C.py,C.pz),O.add(C)}multiply(h){a(h);let w=h,m,x;const{endo:y}=t;if(y){const{k1neg:$,k1:b,k2neg:O,k2:C}=y.splitScalar(w);let{p:N,f:I}=this.wNAF(b),{p:R,f:A}=this.wNAF(C);N=p.constTimeNegate($,N),R=p.constTimeNegate(O,R),R=new u(n.mul(R.px,y.beta),R.py,R.pz),m=N.add(R),x=I.add(A)}else{const{p:$,f:b}=this.wNAF(w);m=$,x=b}return u.normalizeZ([m,x])[0]}multiplyAndAddUnsafe(h,w,m){const x=u.BASE,y=(b,O)=>O===$t||O===je||!b.equals(x)?b.multiplyUnsafe(O):b.multiply(O),$=y(this,w).add(y(h,m));return $.is0()?void 0:$}toAffine(h){const{px:w,py:m,pz:x}=this,y=this.is0();h==null&&(h=y?n.ONE:n.inv(x));const $=n.mul(w,h),b=n.mul(m,h),O=n.mul(x,h);if(y)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:$,y:b}}isTorsionFree(){const{h,isTorsionFree:w}=t;if(h===je)return!0;if(w)return w(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h,clearCofactor:w}=t;return h===je?this:w?w(u,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return this.assertValidity(),r(u,this,h)}toHex(h=!0){return Mr(this.toRawBytes(h))}}u.BASE=new u(t.Gx,t.Gy,n.ONE),u.ZERO=new u(n.ZERO,n.ONE,n.ZERO);const d=t.nBitLength,p=Am(u,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:i}}function Cm(e){const t=Cf(e);return is(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Pm(e){const t=Cm(e),{Fp:n,n:r}=t,s=n.BYTES+1,o=2*n.BYTES+1;function i(v){return $tMr(Nr(v,t.nByteLength));function g(v){const _=r>>je;return v>_}function h(v){return g(v)?a(-v):v}const w=(v,_,U)=>Tn(v.slice(_,U));class m{constructor(_,U,K){this.r=_,this.s=U,this.recovery=K,this.assertValidity()}static fromCompact(_){const U=t.nByteLength;return _=gt("compactSignature",_,U*2),new m(w(_,0,U),w(_,U,2*U))}static fromDER(_){const{r:U,s:K}=Xn.toSig(gt("DER",_));return new m(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(_){return new m(this.r,this.s,_)}recoverPublicKey(_){const{r:U,s:K,recovery:L}=this,D=C(gt("msgHash",_));if(L==null||![0,1,2,3].includes(L))throw new Error("recovery id invalid");const q=L===2||L===3?U+t.n:U;if(q>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const G=(L&1)===0?"02":"03",ue=l.fromHex(G+p(q)),ce=c(q),ne=a(-D*ce),pe=a(K*ce),ge=l.BASE.multiplyAndAddUnsafe(ue,ne,pe);if(!ge)throw new Error("point at infinify");return ge.assertValidity(),ge}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new m(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Zr(this.toDERHex())}toDERHex(){return Xn.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Zr(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),_=Sm(v,r);return Nr(_,t.nByteLength)},precompute(v=8,_=l.BASE){return _._setWindowSize(v),_.multiply(BigInt(3)),_}};function y(v,_=!0){return l.fromPrivateKey(v).toRawBytes(_)}function $(v){const _=v instanceof Uint8Array,U=typeof v=="string",K=(_||U)&&v.length;return _?K===s||K===o:U?K===2*s||K===2*o:v instanceof l}function b(v,_,U=!0){if($(v))throw new Error("first arg must be private key");if(!$(_))throw new Error("second arg must be public key");return l.fromHex(_).multiply(f(v)).toRawBytes(U)}const O=t.bits2int||function(v){const _=Tn(v),U=v.length*8-t.nBitLength;return U>0?_>>BigInt(U):_},C=t.bits2int_modN||function(v){return a(O(v))},N=gc(t.nBitLength);function I(v){if(typeof v!="bigint")throw new Error("bigint expected");if(!($t<=v&&vde in U))throw new Error("sign() legacy options not supported");const{hash:K,randomBytes:L}=t;let{lowS:D,prehash:q,extraEntropy:G}=U;D==null&&(D=!0),v=gt("msgHash",v),q&&(v=gt("prehashed msgHash",K(v)));const ue=C(v),ce=f(_),ne=[I(ce),I(ue)];if(G!=null){const de=G===!0?L(n.BYTES):G;ne.push(gt("extraEntropy",de,n.BYTES))}const pe=kt(...ne),ge=ue;function Le(de){const _e=O(de);if(!d(_e))return;const Wt=c(_e),ht=l.BASE.multiply(_e).toAffine(),ze=a(ht.x);if(ze===$t)return;const Gt=a(Wt*a(ge+ze*ce));if(Gt===$t)return;let fs=(ht.x===ze?0:2)|Number(ht.y&je),Nl=Gt;return D&&g(Gt)&&(Nl=h(Gt),fs^=1),new m(ze,Nl,fs)}return{seed:pe,k2sig:Le}}const A={lowS:t.lowS,prehash:!1},P={lowS:t.lowS,prehash:!1};function k(v,_,U=A){const{seed:K,k2sig:L}=R(v,_,U);return Tf(t.hash.outputLen,t.nByteLength,t.hmac)(K,L)}l.BASE._setWindowSize(8);function S(v,_,U,K=P){var ht;const L=v;if(_=gt("msgHash",_),U=gt("publicKey",U),"strict"in K)throw new Error("options.strict was renamed to lowS");const{lowS:D,prehash:q}=K;let G,ue;try{if(typeof L=="string"||L instanceof Uint8Array)try{G=m.fromDER(L)}catch(ze){if(!(ze instanceof Xn.Err))throw ze;G=m.fromCompact(L)}else if(typeof L=="object"&&typeof L.r=="bigint"&&typeof L.s=="bigint"){const{r:ze,s:Gt}=L;G=new m(ze,Gt)}else throw new Error("PARSE");ue=l.fromHex(U)}catch(ze){if(ze.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(D&&G.hasHighS())return!1;q&&(_=t.hash(_));const{r:ce,s:ne}=G,pe=C(_),ge=c(ne),Le=a(pe*ge),de=a(ce*ge),_e=(ht=l.BASE.multiplyAndAddUnsafe(ue,Le,de))==null?void 0:ht.toAffine();return _e?a(_e.x)===ce:!1}return{CURVE:t,getPublicKey:y,getSharedSecret:b,sign:k,verify:S,ProjectivePoint:l,Signature:m,utils:x}}function Um(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,p)=>{let g=l,h=e.pow(p,a),w=e.sqr(h);w=e.mul(w,p);let m=e.mul(d,w);m=e.pow(m,i),m=e.mul(m,h),h=e.mul(m,p),w=e.mul(m,d);let x=e.mul(w,h);m=e.pow(x,c);let y=e.eql(m,e.ONE);h=e.mul(w,f),m=e.mul(x,g),w=e.cmov(h,w,y),x=e.cmov(m,x,y);for(let $=s;$>1;$--){let b=Yt**($-Yt),O=e.pow(x,b);const C=e.eql(O,e.ONE);h=e.mul(w,g),g=e.mul(g,g),O=e.mul(x,g),w=e.cmov(h,w,C),x=e.cmov(O,x,C)}return{isValid:y,value:w}};if(e.ORDER%Ml===Po){const d=(e.ORDER-Po)/Ml,p=e.sqrt(e.neg(t));u=(g,h)=>{let w=e.sqr(h);const m=e.mul(g,h);w=e.mul(w,m);let x=e.pow(w,d);x=e.mul(x,m);const y=e.mul(x,p),$=e.mul(e.sqr(x),h),b=e.eql($,g);let O=e.cmov(y,x,b);return{isValid:b,value:O}}}return u}function Nm(e,t){if(Of(e),!e.isValid(t.A)||!e.isValid(t.B)||!e.isValid(t.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");const n=Um(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:p}=n(o,l);u=e.mul(s,r),u=e.mul(u,p),f=e.cmov(f,i,d),u=e.cmov(u,p,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 Lm(e){if(e instanceof Uint8Array)return e;if(typeof e=="string")return gi(e);throw new Error("DST must be Uint8Array or string")}const Hm=Tn;function Sn(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 Rm(e,t){const n=new Uint8Array(e.length);for(let r=0;r255&&(t=r(kt(gi("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,Sn(t.length,1)),c=Sn(0,o),l=Sn(n,2),f=new Array(i),u=r(kt(c,e,l,Sn(0,1),a));f[0]=r(kt(u,Sn(1,1),a));for(let p=1;p<=i;p++){const g=[Rm(u,f[p-1]),Sn(p+1,1),a];f[p]=r(kt(...g))}return kt(...f).slice(0,n)}function Km(e,t,n,r,s){if(Ss(e),Ss(t),yc(n),t.length>255){const o=Math.ceil(2*r/8);t=s.create({dkLen:o}).update(gi("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(Sn(n,2)).update(t).update(Sn(t.length,1)).digest()}function Zl(e,t,n){is(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;Ss(e),yc(t);const l=Lm(c),f=r.toString(2).length,u=Math.ceil((f+s)/8),d=t*o*u;let p;if(a==="xmd")p=jm(e,l,d,i);else if(a==="xof")p=Km(e,l,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(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 Mm(e,t,n){if(typeof t!="function")throw new Error("mapToCurve() must be defined");return{hashToCurve(r,s){const o=Zl(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=Zl(r,1,{...n,DST:n.encodeDST,...s}),i=e.fromAffine(t(o[0])).clearCofactor();return i.assertValidity(),i}}}let Pf=class extends $f{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Yn.hash(t);const r=fc(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 Pf(e,t).update(n).digest();Uf.create=(e,t)=>new Pf(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Zm(e){return{hash:e,hmac:(t,...n)=>Uf(e,t,em(...n)),randomBytes:tm}}function Vm(e,t){const n=r=>Pm({...e,...Zm(r)});return Object.freeze({...n(t),create:n})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Nf=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Vl=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),qm=BigInt(1),Sa=BigInt(2),ql=(e,t)=>(e+t/Sa)/t;function zm(e){const t=Nf,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=pt(f,n,t)*f%t,d=pt(u,n,t)*f%t,p=pt(d,Sa,t)*l%t,g=pt(p,s,t)*p%t,h=pt(g,o,t)*g%t,w=pt(h,a,t)*h%t,m=pt(w,c,t)*w%t,x=pt(m,a,t)*h%t,y=pt(x,n,t)*f%t,$=pt(y,i,t)*g%t,b=pt($,r,t)*l%t,O=pt(b,Sa,t);if(!In.eql(In.sqr(O),e))throw new Error("Cannot find square root");return O}const In=If(Nf,void 0,void 0,{sqrt:zm}),sn=Vm({a:BigInt(0),b:BigInt(7),Fp:In,n:Vl,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Vl,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-qm*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=n,i=BigInt("0x100000000000000000000000000000000"),a=ql(o*e,t),c=ql(-r*e,t);let l=Xe(e-a*n-c*s,t),f=Xe(-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}}}},_f);BigInt(0);sn.ProjectivePoint;sn.utils.randomPrivateKey;const Fm=Dm(In,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),Wm=Nm(In,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:In.create(BigInt("-11"))});Mm(sn.ProjectivePoint,e=>{const{x:t,y:n}=Wm(In.create(e[0]));return Fm(t,n)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:In.ORDER,m:1,k:128,expand:"xmd",hash:_f});function _a(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function Gm(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function Lf(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 Ym(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 Xm(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 Jm(e,t){Lf(e);const n=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),Ut=(e,t)=>e<<32-t|e>>>t,ey=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ey)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function ty(e){if(typeof e!="string")throw new TypeError(`utf8ToBytes expected string, got ${typeof e}`);return new TextEncoder().encode(e)}function Hf(e){if(typeof e=="string"&&(e=ty(e)),!(e instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof e})`);return e}let ny=class{clone(){return this._cloneInto()}};function Rf(e){const t=r=>e().update(Hf(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function ry(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 sy=class extends ny{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=Gi(this.buffer)}update(t){Wi.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=Hf(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,iy=(e,t,n)=>e&t^e&n^t&n,ay=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 jf=class extends sy{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 u=0;u<16;u++,n+=4)gn[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const d=gn[u-15],p=gn[u-2],g=Ut(d,7)^Ut(d,18)^d>>>3,h=Ut(p,17)^Ut(p,19)^p>>>10;gn[u]=h+gn[u-7]+g+gn[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),p=f+d+oy(a,c,l)+ay[u]+gn[u]|0,h=(Ut(r,2)^Ut(r,13)^Ut(r,22))+iy(r,s,o)|0;f=l,l=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,l=l+this.G|0,f=f+this.H|0,this.set(r,s,o,i,a,c,l,f)}roundClean(){gn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},cy=class extends jf{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 Aa=Rf(()=>new jf);Rf(()=>new cy);function ly(e,t){if(e.length>t)throw new TypeError(`Data is larger than array size: ${e.length} > ${t}`)}function uy(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 fy(e){if(e>Number.MAX_SAFE_INTEGER)throw new TypeError("Number exceeds safe bounds!")}const{getRandomValues:dy}=crypto??globalThis.crypto??window.crypto;function hy(e=32){if(typeof dy=="function")return crypto.getRandomValues(new Uint8Array(e));throw new Error("Crypto module missing getRandomValues!")}function py(e,t,n="be"){t===void 0&&(t=e.length),ly(e,t);const r=new Uint8Array(t).fill(0),s=n==="be"?0:t-e.length;return r.set(e,s),r}function Kf(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 wy(e,t){const n=Df(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 Mf(e){return Aa(Aa(e))}function by(e){const t=Mf(e);return Kf([e,t.slice(0,4)])}function xy(e){const t=e.slice(0,-4),n=e.slice(-4);if(Mf(t).slice(0,4).toString()!==n.toString())throw new Error("Invalid checksum!");return t}const zl={encode:yy,decode:wy},Zf={encode:e=>{const t=by(e);return zl.encode(t,"base58")},decode:e=>{const t=zl.decode(e,"base58");return xy(t)}},Vf="qpzry9x8gf2tvdw0s3jn54khce6mua7l",vy=[996825010,642813549,513874426,1027748829,705979059],Uo=[{version:0,name:"bech32",const:1},{version:1,name:"bech32m",const:734539939}];function qf(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^=vy[s])}return t}function zf(e){const t=[];let n;for(n=0;n>5);for(t.push(0),n=0;n>5*(5-i)&31);return o}function Ff(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 Ey(e,t,n){const r=t.concat($y(e,t,n));let s=e+"1";for(let o=0;oo.version===t[0])??Uo[0];if(!ky(r,t,s))throw new Error("Checksum verification failed!");return[r,t.slice(0,t.length-6)]}function Sy(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 _y(e){const t=e.lastIndexOf("1");return!(t<1||t+7>e.length||e.length>90)}function Ay(e,t="bc",n=0){const r=[n,...Ff([...e],8,5)],s=Uo.find(i=>i.version===n)??Uo[0],o=Ey(t,r,s);return Gf(o),o}function Gf(e){e=e.toLowerCase();const t=e.split("1",1)[0],[n,r]=Wf(e),s=Ff(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 By(e){e=e.toLowerCase();const[t,n]=Wf(e);return n[0]}const Yf={encode:Ay,decode:Gf,version:By},Xf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Jf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Ty=new TextEncoder;function Qf(e,t=!1,n=!0){typeof e=="string"&&(e=Ty.encode(e));const r=t?Jf:Xf;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 ed(e,t=!1){const n=t||e.includes("-")||e.includes("_")?Jf.split(""):Xf.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 td={encode:Qf,decode:ed},nd={encode:e=>Qf(e,!0,!1),decode:e=>ed(e,!0)},Oy=BigInt(0),Iy=BigInt(255),rd=BigInt(256);function Cy(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 Py(e,t,n="be"){t===void 0&&(t=Cy(e));const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(;e>Oy;){const a=e&Iy,c=Number(a);r?o.setUint8(i++,c):o.setUint8(i--,c),e=(e-a)/rd}return new Uint8Array(s)}function Uy(e){let t=BigInt(0);for(let n=e.length-1;n>=0;n--)t=t*rd+BigInt(e[n]);return BigInt(t)}function Ny(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 Hy(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 Ry(e,t,n="be"){t===void 0&&(t=Hy(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 jy(e){let t=0;for(let n=e.length-1;n>=0;n--)t=t*256+e[n],fy(t);return t}const Ky=new TextEncoder,Dy=new TextDecoder;function wc(e){return Ky.encode(e)}function Yi(e){return Dy.decode(e)}function My(e,t){uy(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 Zy(e,t,n="le"){t=My(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 wc(t)}function zy(e,t,n){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Uint8Array)return py(e,t,n);if(typeof e=="string")return Zy(e,t,n);if(typeof e=="bigint")return Py(e,t,n);if(typeof e=="number")return Ry(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=hy(t);return new ie(n,t)}constructor(t,n,r){const s=zy(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 ow(this)}toNum(t="be"){const n=t==="be"?this.reverse():this;return jy(n)}toBin(){return Ly(this)}toBig(t="be"){const n=t==="be"?this.reverse():this;return Uy(n)}toHash(){const t=Aa(this);return new ie(t)}toJson(){const t=Yi(this);return JSON.parse(t)}toBech32(t,n=0){return Yf.encode(this,t,n)}toStr(){return Yi(this)}toHex(){return Vy(this)}toBytes(){return new Uint8Array(this)}tob58chk(){return Zf.encode(this)}toBase64(){return td.encode(this)}toB64url(){return nd.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=Kf(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=Fy,ie.big=Gy,ie.bin=Wy,ie.raw=Yy,ie.str=Xy,ie.hex=Jy,ie.bytes=Qy,ie.json=ew,ie.base64=tw,ie.b64url=nw,ie.bech32=rw,ie.b58chk=sw,ie.encode=wc,ie.decode=Yi;let ee=ie;function Fy(e,t,n){return new ee(e,t,n)}function Wy(e,t,n){return new ee(Ny(e),t,n)}function Gy(e,t,n){return new ee(e,t,n)}function Yy(e,t,n){return new ee(e,t,n)}function Xy(e,t,n){return new ee(wc(e),t,n)}function Jy(e,t,n){return new ee(e,t,n)}function Qy(e,t,n){return new ee(e,t,n)}function ew(e){return new ee(qy(e))}function tw(e){return new ee(td.decode(e))}function nw(e){return new ee(nd.decode(e))}function rw(e){return new ee(Yf.decode(e))}function sw(e){return new ee(Zf.decode(e))}class ow{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 No=sn.CURVE,bc=No.n,iw=No.p,aw={x:No.Gx,y:No.Gy},cw=BigInt(0);BigInt(1);BigInt(2);BigInt(3);BigInt(4);const Ba={N:bc,P:iw,G:aw,_0n:cw},ds=If(bc,32,!0),sd=e=>Xe(e,bc);function xc(e,t=!1){if(t)throw new Error(e);return!1}function od(e){return ee.random(e)}function lw(e){const t=ee.bytes(e).big;return ee.big(sd(t),32)}var uw=Object.freeze({__proto__:null,fail:xc,mod_bytes:lw,random:od});const{N:fw,_0n:dw}=Ba;function hw(e,t,n){const r=ee.bytes(e);return r.length!==t?xc(`Invalid byte size: ${r.hex} !== ${t}`,n):!0}function pw(e,t){return typeof e=="bigint"&&dwthis.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 ww(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 bw(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 xw(e,t){id(e);const n=t.outputLen;if(e.lengthe instanceof Uint8Array,Xi=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),Nt=(e,t)=>e<<32-t|e>>>t,$w=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!$w)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ew(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function vc(e){if(typeof e=="string"&&(e=Ew(e)),!kw(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}let ad=class{clone(){return this._cloneInto()}};function br(e){const t=r=>e().update(vc(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Sw(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 kc extends ad{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){Jn.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=vc(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,Aw=(e,t,n)=>e&t^e&n^t&n,Bw=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 cd=class extends kc{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 u=0;u<16;u++,n+=4)yn[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const d=yn[u-15],p=yn[u-2],g=Nt(d,7)^Nt(d,18)^d>>>3,h=Nt(p,17)^Nt(p,19)^p>>>10;yn[u]=h+yn[u-7]+g+yn[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),p=f+d+_w(a,c,l)+Bw[u]+yn[u]|0,h=(Nt(r,2)^Nt(r,13)^Nt(r,22))+Aw(r,s,o)|0;f=l,l=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,l=l+this.G|0,f=f+this.H|0,this.set(r,s,o,i,a,c,l,f)}roundClean(){yn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};class Tw extends cd{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 Lo=br(()=>new cd);br(()=>new Tw);const so=BigInt(2**32-1),Oa=BigInt(32);function ld(e,t=!1){return t?{h:Number(e&so),l:Number(e>>Oa&so)}:{h:Number(e>>Oa&so)|0,l:Number(e&so)|0}}function Ow(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let s=0;sBigInt(e>>>0)<>>0),Cw=(e,t,n)=>e>>>n,Pw=(e,t,n)=>e<<32-n|t>>>n,Uw=(e,t,n)=>e>>>n|t<<32-n,Nw=(e,t,n)=>e<<32-n|t>>>n,Lw=(e,t,n)=>e<<64-n|t>>>n-32,Hw=(e,t,n)=>e>>>n-32|t<<64-n,Rw=(e,t)=>t,jw=(e,t)=>e,Kw=(e,t,n)=>e<>>32-n,Dw=(e,t,n)=>t<>>32-n,Mw=(e,t,n)=>t<>>64-n,Zw=(e,t,n)=>e<>>64-n;function Vw(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}const qw=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),zw=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Fw=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Ww=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,Gw=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Yw=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,Xw={fromBig:ld,split:Ow,toBig:Iw,shrSH:Cw,shrSL:Pw,rotrSH:Uw,rotrSL:Nw,rotrBH:Lw,rotrBL:Hw,rotr32H:Rw,rotr32L:jw,rotlSH:Kw,rotlSL:Dw,rotlBH:Mw,rotlBL:Zw,add:Vw,add3L:qw,add3H:zw,add4L:Fw,add4H:Ww,add5H:Yw,add5L:Gw};var oe=Xw;const[Jw,Qw]=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))),wn=new Uint32Array(80),bn=new Uint32Array(80);let mi=class extends kc{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:p,Gl:g,Hh:h,Hl:w}=this;return[t,n,r,s,o,i,a,c,l,f,u,d,p,g,h,w]}set(t,n,r,s,o,i,a,c,l,f,u,d,p,g,h,w){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=p|0,this.Gl=g|0,this.Hh=h|0,this.Hl=w|0}process(t,n){for(let y=0;y<16;y++,n+=4)wn[y]=t.getUint32(n),bn[y]=t.getUint32(n+=4);for(let y=16;y<80;y++){const $=wn[y-15]|0,b=bn[y-15]|0,O=oe.rotrSH($,b,1)^oe.rotrSH($,b,8)^oe.shrSH($,b,7),C=oe.rotrSL($,b,1)^oe.rotrSL($,b,8)^oe.shrSL($,b,7),N=wn[y-2]|0,I=bn[y-2]|0,R=oe.rotrSH(N,I,19)^oe.rotrBH(N,I,61)^oe.shrSH(N,I,6),A=oe.rotrSL(N,I,19)^oe.rotrBL(N,I,61)^oe.shrSL(N,I,6),P=oe.add4L(C,A,bn[y-7],bn[y-16]),k=oe.add4H(P,O,R,wn[y-7],wn[y-16]);wn[y]=k|0,bn[y]=P|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:f,Eh:u,El:d,Fh:p,Fl:g,Gh:h,Gl:w,Hh:m,Hl:x}=this;for(let y=0;y<80;y++){const $=oe.rotrSH(u,d,14)^oe.rotrSH(u,d,18)^oe.rotrBH(u,d,41),b=oe.rotrSL(u,d,14)^oe.rotrSL(u,d,18)^oe.rotrBL(u,d,41),O=u&p^~u&h,C=d&g^~d&w,N=oe.add5L(x,b,C,Qw[y],bn[y]),I=oe.add5H(N,m,$,O,Jw[y],wn[y]),R=N|0,A=oe.rotrSH(r,s,28)^oe.rotrBH(r,s,34)^oe.rotrBH(r,s,39),P=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=w|0,h=p|0,w=g|0,p=u|0,g=d|0,{h:u,l:d}=oe.add(l|0,f|0,I|0,R|0),l=a|0,f=c|0,a=o|0,c=i|0,o=r|0,i=s|0;const v=oe.add3L(R,P,S);r=oe.add3H(v,I,A,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:p,l:g}=oe.add(this.Fh|0,this.Fl|0,p|0,g|0),{h,l:w}=oe.add(this.Gh|0,this.Gl|0,h|0,w|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,l,f,u,d,p,g,h,w,m,x)}roundClean(){wn.fill(0),bn.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 eb extends mi{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 tb extends mi{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 nb extends mi{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 rb=br(()=>new mi);br(()=>new eb);br(()=>new tb);br(()=>new nb);const sb=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),ud=Uint8Array.from({length:16},(e,t)=>t),ob=ud.map(e=>(9*e+5)%16);let $c=[ud],Ec=[ob];for(let e=0;e<4;e++)for(let t of[$c,Ec])t.push(t[e].map(n=>sb[n]));const fd=[[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)),ib=$c.map((e,t)=>e.map(n=>fd[t][n])),ab=Ec.map((e,t)=>e.map(n=>fd[t][n])),cb=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),lb=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),oo=(e,t)=>e<>>32-t;function Wl(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 io=new Uint32Array(16);let ub=class extends kc{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)io[p]=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 p=0;p<5;p++){const g=4-p,h=cb[p],w=lb[p],m=$c[p],x=Ec[p],y=ib[p],$=ab[p];for(let b=0;b<16;b++){const O=oo(r+Wl(p,o,a,l)+io[m[b]]+h,y[b])+u|0;r=u,u=l,l=oo(a,10)|0,a=o,o=O}for(let b=0;b<16;b++){const O=oo(s+Wl(g,i,c,f)+io[x[b]]+w,$[b])+d|0;s=d,d=f,f=oo(c,10)|0,c=i,i=O}}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(){io.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}};const fb=br(()=>new ub);let dd=class extends ad{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Jn.hash(t);const r=vc(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 dd(e,t).update(n).digest();hd.create=(e,t)=>new dd(e,t);function db(e){const t=ee.bytes(e);return ee.raw(Lo(t))}function Vr(e){const t=ee.bytes(e);return ee.raw(Lo(Lo(t)))}function Sc(e){const t=ee.bytes(e);return ee.raw(fb(Lo(t)))}function hb(e,t){const n=ee.bytes(e),r=ee.bytes(t);return ee.raw(hd(rb,n,r))}function pb(e){const t=ee.str(e).digest;return ee.join([t,t])}function gb(e=32){return _c(od(e))}function _c(e){return nt.mod(e).buff}function pd(e,t=!1){const n=nt.mod(e).point;return t?n.x:n.buff}function gd(e,t){const n=wr.from_x(t),r=nt.mod(e);return n.mul(r).buff}function mb(e,t,n="ecdh/code"){const r=pb(n),s=_c(e),o=pd(s),i=ee.bytes(t),a=gd(s,i),c=[o.hex,i.hex];return c.sort(),hb(a,ee.join([r,...c]))}function yb(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 wb(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 bb=Object.freeze({__proto__:null,genSecretKey:gb,getPublicKey:pd,getSecretKey:_c,getSharedCode:mb,getSharedKey:gd,is_even_pub:yb,xonly_pub:wb});ee.random(32);const md={secp:sn},Ia={...bb,...uw};function yi(e){const t=B.bytes(e);return zt(t,33),Sc(t)}function yd(e){const t=Ne.fmt.toBytes(e,!1);return Sc(t)}function wd(e){const t=Ne.fmt.toBytes(e,!1);return db(t)}function bd(e,t="main"){const n=t==="main"?["1"]:["m","n"];for(const r of n)if(e.startsWith(r))return!0;return!1}function xd(e,t="main"){const n=B.bytes(e),r=t==="main"?B.num(0):B.num(111);return zt(e,20),n.prepend(r).tob58chk()}function xb(e,t="main"){if(!bd(e,t))throw new TypeError("Invalid p2pkh address!");return B.b58chk(e).slice(1)}function vb(e){const t=B.bytes(e);return zt(t,20),["OP_DUP","OP_HASH160",t.hex,"OP_EQUALVERIFY","OP_CHECKSIG"]}function kb(e,t){const n=yi(e);return xd(n,t)}const vd={check:bd,encode:xd,decode:xb,hash:yi,scriptPubKey:vb,fromPubKey:kb};function kd(e,t="main"){const n=t==="main"?["3"]:["2"];for(const r of n)if(e.startsWith(r))return!0;return!1}function $d(e,t="main"){const n=t==="main"?B.num(5):B.num(196),r=B.bytes(e);return zt(r,20),r.prepend(n).tob58chk()}function $b(e,t="main"){if(!kd(e,t))throw new TypeError(`Invalid p2sh address for network ${t}:`+e);return B.b58chk(e).slice(1)}function Eb(e){return["OP_HASH160",B.bytes(e).hex,"OP_EQUAL"]}function Sb(e,t){const n=yd(e);return $d(n,t)}const Ed={check:kd,encode:$d,decode:$b,hash:yd,scriptPubKey:Eb,fromScript:Sb},Ac={main:"bc",testnet:"tb",signet:"tb",regtest:"bcrt"},_b=["bc1q","tb1q","bcrt1q"];function Sd(e){for(const t of _b)if(e.startsWith(t))return!0;return!1}function _d(e,t="main"){const n=Ac[t],r=B.bytes(e);return zt(r,20),r.toBech32(n,0)}function Ab(e){if(!Sd(e))throw new TypeError("Invalid segwit address!");return B.bech32(e)}function Bb(e){const t=B.bytes(e);return zt(t,20),["OP_0",t.hex]}function Tb(e,t){const n=yi(e);return _d(n,t)}const Ad={check:Sd,encode:_d,decode:Ab,hash:yi,scriptPubKey:Bb,fromPubKey:Tb},Ob=["bc1q","tb1q","bcrt1q"];function Bd(e){for(const t of Ob)if(e.startsWith(t))return!0;return!1}function Td(e,t="main"){const n=Ac[t],r=B.bytes(e);return zt(r,32),r.toBech32(n,0)}function Ib(e){if(!Bd(e))throw new TypeError("Invalid segwit address!");return B.bech32(e)}function Cb(e){const t=B.bytes(e);return zt(t,32),["OP_0",t.hex]}function Pb(e,t){const n=wd(e);return Td(n,t)}const Od={check:Bd,encode:Td,decode:Ib,hash:wd,scriptPubKey:Cb,fromScript:Pb};function ir(e){const t=B.bytes(e);return t.length>32?t.slice(1,33):t}const Ub=["bc1p","tb1p","bcrt1p"];function Id(e){for(const t of Ub)if(e.startsWith(t))return!0;return!1}function Cd(e,t="main"){const n=Ac[t],r=B.bytes(e);return zt(r,32),r.toBech32(n,1)}function Nb(e){if(!Id(e))throw new TypeError("Invalid taproot address!");return B.bech32(e)}function Lb(e){const t=B.bytes(e);return zt(t,32),["OP_1",t.hex]}function Hb(e,t){const n=ir(e);return Cd(n,t)}const Pd={check:Id,encode:Cd,decode:Nb,scriptPubKey:Lb,fromPubKey:Hb},Rb={version:2,vin:[],vout:[],locktime:0},jb={scriptSig:[],sequence:4294967293,witness:[]},Kb={value:0n,scriptPubKey:[]};function Bc(e){const t={...Rb,...e};return t.vin=t.vin.map(n=>({...jb,...n})),t.vout=t.vout.map(n=>({...Kb,...n})),t}function qr(e,t){const{version:n,vin:r,vout:s,locktime:o}=Bc(e),i=t!==!0&&Db(r),a=[Tc(n)];i&&a.push(B.hex("0001")),a.push(Mb(r)),a.push(Zb(s));for(const c of r)i&&a.push(qb(c.witness));return a.push(Oc(o)),B.join(a)}function Db(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 Tc(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 Mb(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(yr(o,!0)),t.push(zs(i))}return B.join(t)}function Cn(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 Zb(e){const t=[B.varInt(e.length,"le")];for(const n of e)t.push(Vb(n));return B.join(t)}function Vb(e){const{value:t,scriptPubKey:n}=e,r=[];return r.push(Cn(t)),r.push(yr(n,!0)),B.join(r)}function qb(e=[]){const t=[];if(Array.isArray(e)){const n=B.varInt(e.length);t.push(n);for(const r of e)t.push(zb(r));return B.join(t)}else return B.bytes(e)}function zb(e){return Fb(e)?new B(0):yr(e,!0)}function Fb(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 Oc(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 Ic(e){typeof e=="string"&&(e=B.hex(e).raw);const t=new os(e),n=Wb(t),r=Gb(t),s=Yb(t),o=Jb(t);if(r)for(const a of s)a.witness=e1(t);const i=t1(t);return{version:n,vin:s,vout:o,locktime:i}}function Wb(e){return e.read(4).reverse().toNum()}function Gb(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 Yb(e){const t=[],n=e.readSize("le");for(let r=0;r0?e.read(n).hex:null}function Nd(e,t){const n=Ud(e);return n!==null?n:[]}function t1(e){return e.read(4).reverse().toNum()}function n1(e){if(xf(e))return Ic(e);if(typeof e=="object"&&!(e instanceof Uint8Array))return qr(e),Bc(e);throw new Error("Invalid format: "+typeof e)}function r1(e){if(xf(e))return Ic(e),B.bytes(e);if(typeof e=="object")return qr(e);throw new Error("Invalid format: "+typeof e)}const Cc={toBytes:r1,toJson:n1},s1=[["p2pkh",/^76a914(?\w{40})88ac$/],["p2sh",/^a914(?\w{40})87$/],["p2w-pkh",/^0014(?\w{40})$/],["p2w-sh",/^0020(?\w{64})$/],["p2tr",/^5120(?\w{64})$/]],o1=[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 i1(e){let t=e.at(-1);return ln(t)&&(t=B.hex(t)),e.length>1&&t instanceof Uint8Array&&t[0]===80?(e.pop(),B.raw(t)):null}function a1(e){let t=e.at(-1);return ln(t)&&(t=B.hex(t)),e.length>1&&t instanceof Uint8Array&&t.length>32&&o1.includes(t[0]&254)?(e.pop(),B.raw(t)):null}function c1(e){if(e.length>1){const t=e.at(-1);try{const n=Ne.fmt.toBytes(t);return e.pop(),n}catch{return null}}return null}function l1(e){const t=[];for(const n of e)if(ln(n)||n instanceof Uint8Array||typeof n=="number")t.push(B.bytes(n));else throw new Error("unrecognized value: "+String(n));return t}function u1(e=[]){const t=[...e],n=i1(t),r=a1(t),s=c1(t),o=l1(t);return{annex:n,cblock:r,script:s,params:o}}function f1(e){const t=Ne.fmt.toBytes(e,!1).hex;for(const[n,r]of s1){const s=n,{groups:o}=r.exec(t)??{},{hash:i}=o??{};if(ln(i))return{type:s,data:B.hex(i)}}return{type:"raw",data:B.hex(t)}}function d1(e){const t=Cc.toJson(e),n=qr(t,!0);return Vr(n).reverse().hex}function h1(e){const t=Cc.toJson(e),n=qr(t,!0).length,r=qr(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 J={create:Bc,encode:qr,decode:Ic,fmt:Cc,util:{getTxSize:h1,getTxid:d1,readScriptPubKey:f1,readWitness:u1}},p1=[["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 g1(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 m1(e){for(const t of p1){const[n,r,s,o,i]=t;if(e.startsWith(n)&&g1(e,i).length===o)return t}throw new Error("Invalid address: "+e)}function Ld(e){switch(e){case"p2pkh":return vd;case"p2sh":return Ed;case"p2w-pkh":return Ad;case"p2w-sh":return Od;case"p2tr":return Pd;default:throw new Error("Invalid address type: "+e)}}function Hd(e){const[t,n,r]=m1(e),s=Ld(n),o=s.decode(e,r),i=s.scriptPubKey(o);return{prefix:t,type:n,network:r,data:o,script:i}}function y1(e,t){const{type:n,data:r}=J.util.readScriptPubKey(e);return Ld(n).encode(r,t)}function w1(e){const{script:t}=Hd(e);return Ne.fmt.toAsm(t,!1)}const _s={p2pkh:vd,p2sh:Ed,p2wpkh:Ad,p2wsh:Od,p2tr:Pd,decode:Hd,fromScriptPubKey:y1,toScriptPubKey:w1},b1=[1,2,3];function Pc(e,t,n={}){const{sigflag:r=1}=n,s=(r&128)===128,o=r%128;if(!b1.includes(o))throw new Error("Invalid hash type: "+String(r));const i=J.fmt.toJson(e),{version:a,vin:c,vout:l,locktime:f}=i,{txid:u,vout:d,prevout:p,sequence:g}=c[t],{value:h}=p??{};if(h===void 0)throw new Error("Prevout value is empty!");let w=n.script;if(w===void 0&&n.pubkey!==void 0&&(w=`76a914${Sc(n.pubkey).hex}88ac`),w===void 0)throw new Error("No pubkey / script has been set!");if(Ne.fmt.toAsm(w).includes("OP_CODESEPARATOR"))throw new Error("This library does not currently support the use of OP_CODESEPARATOR in segwit scripts.");const m=[Tc(a),x1(c,s),v1(c,o,s),Vs(u),qs(d),Ne.encode(w,!0),Cn(h),zs(g),k1(l,t,o),Oc(f),B.num(r,4).reverse()];return Vr(B.join(m))}function x1(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 Vr(B.join(n))}function v1(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 Vr(B.join(r))}function k1(e,t,n){const r=[];if(n===1){for(const{value:s,scriptPubKey:o}of e)r.push(Cn(s)),r.push(Ne.encode(o,!0));return Vr(B.join(r))}if(n===3&&t1&&c[1].length===33)l=B.bytes(c[1]);else return Ye("No pubkey provided!",s);const f=Ne.fmt.toParam(c[0]),u=f.slice(0,-1),d=f.slice(-1)[0],p=Pc(r,t,{...n,sigflag:d});return md.secp.verify(u,p,l)?!0:Ye("Invalid signature!",s)}const S1={hash:Pc,sign:$1,verify:E1},_1=[0,1,2,3,129,130,131];function Uc(e,t,n={}){const{extension:r,sigflag:s=0,extflag:o=0,key_version:i=0,separator_pos:a=4294967295}=n,c=J.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(!_1.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:w=[]}=f[t],m=(s&128)===128,x=P1(w),y=x!==void 0?1:0,b=(o+(r!==void 0?1:0))*2+y,O=B.str("TapSighash").digest,C=[O,O,B.num(0,1),B.num(s,1),Tc(l),Oc(d)];if(!m){const N=f.map(I=>Gl(I));C.push(A1(f),T1(N),O1(N),B1(f))}if(((s&3)<2||(s&3)>3)&&C.push(I1(u)),C.push(B.num(b,1)),m){const{value:N,scriptPubKey:I}=Gl(f[t]);C.push(Vs(p),qs(g),Cn(N),Ne.encode(I,!0),zs(h))}else C.push(B.num(t,4).reverse());return x!==void 0&&C.push(x),(s&3)===3&&C.push(C1(u[t])),r!==void 0&&C.push(B.bytes(r),B.num(i),B.num(a,4,"le")),B.join(C).digest}function A1(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 B1(e){const t=[];for(const{sequence:n}of e)t.push(zs(n));return B.join(t).digest}function T1(e){const t=[];for(const{value:n}of e)t.push(Cn(n));return B.join(t).digest}function O1(e){const t=[];for(const{scriptPubKey:n}of e)t.push(yr(n,!0));return B.join(t).digest}function I1(e){const t=[];for(const{value:n,scriptPubKey:r}of e)t.push(Cn(n)),t.push(Ne.encode(r,!0));return B.join(t).digest}function C1(e){return B.join([Cn(e.value),Ne.encode(e.scriptPubKey,!0)]).digest}function P1(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 Gl(e){if(e.prevout===void 0)throw new Error("Prevout data missing for input: "+String(e.txid));return e.prevout}const U1=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,N1=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;function L1(e,t,n,r={}){const{sigflag:s=0}=r,o=Uc(t,n,r),i=H1(e,o);return s===0?B.raw(i):B.join([i,s])}function H1(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=$o("BIP0340/aux",B.bytes(n)),c=i^a.big,l=$o("BIP0340/nonce",c,o.x.raw,r),f=new nt(l),u=f.point,d=u.hasEvenY?f.big:f.negated.big,p=new nt($o("BIP0340/challenge",u.x.raw,o.x.raw,r)),g=new nt(d+p.big*i);return B.join([u.x.raw,g.raw])}function R1(e,t,n,r=!1){const s=wr.from_x(ir(n)),o=B.bytes(t),i=B.bytes(e).stream;i.size<64&&Ye("Signature length is too small: "+String(i.size),r);const a=i.read(32);a.big>U1&&Ye("Signature r value greater than field size!",r);const c=i.read(32);c.big>N1&&Ye("Signature s value greater than curve order!",r);const l=new nt($o("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&&Ye("Signature R value has odd Y coordinate!",r),d.x.big===0n&&Ye("Signature R value is infinite!",r),d.x.big===a.big}const j1=192;function wi(e){const t=B.str(e).digest;return B.join([t,t])}function Nc(e,t=j1){return B.join([wi("TapLeaf"),M1(t),B.bytes(e)]).digest.hex}function K1(e,t){return Nc(Ne.fmt.toBytes(e),t)}function Lc(e,t){return t0){const[p,g,h]=Ho(r,i);c=h,a=Lr(e,p,n)}else i!==void 0?a=Lr(e,i,n):a=Lr(e,void 0,n);const l=n?Ia.getPublicKey(a)[0]:a[0],u=[B.num(s+Zd(l)),o];c.length>0&&c.forEach(p=>u.push(B.hex(p)));const d=B.join(u);if(i!==void 0&&!Hc(a,i,d,t))throw new Error("Path checking failed! Unable to generate path.");return[ir(a).hex,d.hex]}function Hc(e,t,n,r={}){const{isPrivate:s=!1,throws:o=!1}=r,{parity:i,paths:a,intkey:c}=Md(n),l=s?Ia.getPublicKey(e,!0):ir(e),f=B.join([i,l]);if(f.length!==33)return Ye("Invalid tapkey: "+f.hex,o);let u=B.bytes(t).hex;for(const p of a)u=Lc(u,p);const d=Lr(c,u);return B.raw(d).hex===B.raw(f).hex}function Md(e){const t=new os(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 Zd(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 Y1(e,t,n={}){const r=J.fmt.toJson(e),{throws:s=!1}=n,{prevout:o,witness:i=[]}=r.vin[t],a=J.util.readWitness(i),{cblock:c,script:l,params:f}=a;let u;if(f.length<1)return Ye("Invalid witness data: "+String(i),s);const{scriptPubKey:d}=o??{};if(d===void 0)return Ye("Prevout scriptPubKey is empty!",s);const{type:p,data:g}=J.util.readScriptPubKey(d);if(p!=="p2tr")return Ye("Prevout script is not a valid taproot output:"+g.hex,s);if(g.length!==32)return Ye("Invalid tapkey length: "+String(g.length),s);if(c!==null&&l!==null){const y=c[0]&254,$=Nc(l,y);if(n.extension=$,!Hc(g,$,c,{throws:s}))return Ye("cblock verification failed!",s)}n.pubkey!==void 0?u=B.bytes(n.pubkey):f.length>1&&f[1].length===32?u=B.bytes(f[1]):u=B.bytes(g);const h=Ne.fmt.toParam(f[0]),w=new os(h),m=w.read(64).raw;if(w.size===1&&(n.sigflag=w.read(1).num,n.sigflag===0))return Ye("0x00 is not a valid appended sigflag!",s);const x=Uc(r,t,n);return R1(m,x,u,s)?!0:Ye("Invalid signature!",s)}const X1={hash:Uc,sign:L1,verify:Y1},ar={segwit:S1,taproot:X1},J1={getTag:wi,getLeaf:Nc,getBranch:Lc,getRoot:D1},Q1={readCtrlBlock:Md,readParityBit:Zd},ex={getPubKey:Z1,getSecKey:V1,getTweak:Rd,tweakSecKey:jd,tweakPubKey:Kd},bi={getPubKey:G1,getSecKey:W1,encodeScript:K1,checkPath:Hc,tree:J1,tweak:ex,util:Q1,SCRIPT_PUBKEY:z1};var me;(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})(me||(me={}));var Ca;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ca||(Ca={}));const z=me.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),_n=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=me.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"]),tx=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 As=(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,me.jsonStringifyReplacer)}`;break;case M.unrecognized_keys:n=`Unrecognized key(s) in object: ${me.joinValues(e.keys,", ")}`;break;case M.invalid_union:n="Invalid input";break;case M.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${me.joinValues(e.options)}`;break;case M.invalid_enum_value:n=`Invalid enum value. Expected ${me.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}"`:me.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,me.assertNever(e)}return{message:n}};let Vd=As;function nx(e){Vd=e}function Ro(){return Vd}const jo=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}},rx=[];function F(e,t){const n=jo({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,Ro(),As].filter(r=>!!r)});e.common.issues.push(n)}class Qe{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 Qe.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"}),qd=e=>({status:"dirty",value:e}),ot=e=>({status:"valid",value:e}),Pa=e=>e.status==="aborted",Ua=e=>e.status==="dirty",Ko=e=>e.status==="valid",Do=e=>typeof Promise<"u"&&e instanceof Promise;var X;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(X||(X={}));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 Yl=(e,t)=>{if(Ko(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 _n(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:_n(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Qe,ctx:{common:t.parent.common,data:t.data,parsedType:_n(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:_n(t)},o=this._parseSync({data:t,path:s.path,parent:s});return Yl(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:_n(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(Do(s)?s:Promise.resolve(s));return Yl(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 nn.create(this,this._def)}nullable(){return ur.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Tt.create(this,this._def)}promise(){return Fr.create(this,this._def)}or(t){return Is.create([this,t],this._def)}and(t){return Cs.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 Hs({...se(this._def),innerType:this,defaultValue:n,typeName:Q.ZodDefault})}brand(){return new Fd({typeName:Q.ZodBranded,type:this,...se(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new qo({...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 Fs.create(this,t)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const sx=/^c[^\s-]{8,}$/i,ox=/^[a-z][a-z0-9]*$/,ix=/[0-9A-HJKMNP-TV-Z]{26}/,ax=/^([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,cx=/^(([^<>()[\]\\.,;:\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,})+))$/,lx=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u"),ux=/^(((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}))$/,fx=/^(([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})))$/,dx=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 hx(e,t){return!!((t==="v4"||!t)&&ux.test(e)||(t==="v6"||!t)&&fx.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,...X.errToObj(r)}),this.nonempty=t=>this.min(1,X.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 Qe;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,...X.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...X.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...X.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...X.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...X.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...X.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...X.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...X.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 px(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 Pn 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 Qe;for(const o of this._def.checks)o.kind==="int"?me.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"?px(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()):me.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,X.toString(n))}gt(t,n){return this.setLimit("min",t,!1,X.toString(n))}lte(t,n){return this.setLimit("max",t,!0,X.toString(n))}lt(t,n){return this.setLimit("max",t,!1,X.toString(n))}setLimit(t,n,r,s){return new Pn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:X.toString(s)}]})}_addCheck(t){return new Pn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:X.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:X.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:X.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:X.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:X.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:X.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:X.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:X.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:X.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"&&me.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 Pn({checks:[],typeName:Q.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...se(e)});class Un 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 Qe;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()):me.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,X.toString(n))}gt(t,n){return this.setLimit("min",t,!1,X.toString(n))}lte(t,n){return this.setLimit("max",t,!0,X.toString(n))}lt(t,n){return this.setLimit("max",t,!1,X.toString(n))}setLimit(t,n,r,s){return new Un({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:X.toString(s)}]})}_addCheck(t){return new Un({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:X.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:X.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:X.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:X.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:X.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 Un({checks:[],typeName:Q.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...se(e)})};class Bs 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 ot(t.data)}}Bs.create=e=>new Bs({typeName:Q.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...se(e)});class cr 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 Qe;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()):me.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new cr({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:X.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:X.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 cr({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Q.ZodDate,...se(e)});class Mo 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 ot(t.data)}}Mo.create=e=>new Mo({typeName:Q.ZodSymbol,...se(e)});class Ts 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 ot(t.data)}}Ts.create=e=>new Ts({typeName:Q.ZodUndefined,...se(e)});class Os 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 ot(t.data)}}Os.create=e=>new Os({typeName:Q.ZodNull,...se(e)});class zr extends ae{constructor(){super(...arguments),this._any=!0}_parse(t){return ot(t.data)}}zr.create=e=>new zr({typeName:Q.ZodAny,...se(e)});class rr extends ae{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ot(t.data)}}rr.create=e=>new rr({typeName:Q.ZodUnknown,...se(e)});class on extends ae{_parse(t){const n=this._getOrReturnCtx(t);return F(n,{code:M.invalid_type,expected:z.never,received:n.parsedType}),te}}on.create=e=>new on({typeName:Q.ZodNever,...se(e)});class Zo 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 ot(t.data)}}Zo.create=e=>new Zo({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 Kt(n,i,n.path,a)))).then(i=>Qe.mergeArray(r,i));const o=[...n.data].map((i,a)=>s.type._parseSync(new Kt(n,i,n.path,a)));return Qe.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new Tt({...this._def,minLength:{value:t,message:X.toString(n)}})}max(t,n){return new Tt({...this._def,maxLength:{value:t,message:X.toString(n)}})}length(t,n){return new Tt({...this._def,exactLength:{value:t,message:X.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 Pr(e){if(e instanceof Pe){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=nn.create(Pr(r))}return new Pe({...e._def,shape:()=>t})}else return e instanceof Tt?new Tt({...e._def,type:Pr(e.element)}):e instanceof nn?nn.create(Pr(e.unwrap())):e instanceof ur?ur.create(Pr(e.unwrap())):e instanceof Dt?Dt.create(e.items.map(t=>Pr(t))):e}class Pe 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=me.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:M.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:M.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=>Qe.mergeObjectSync(r,l)):Qe.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return new Pe({...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=X.errToObj(t).message)!==null&&a!==void 0?a:c}:{message:c}}}:{}})}strip(){return new Pe({...this._def,unknownKeys:"strip"})}passthrough(){return new Pe({...this._def,unknownKeys:"passthrough"})}extend(t){return new Pe({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Pe({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 Pe({...this._def,catchall:t})}pick(t){const n={};return me.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Pe({...this._def,shape:()=>n})}omit(t){const n={};return me.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Pe({...this._def,shape:()=>n})}deepPartial(){return Pr(this)}partial(t){const n={};return me.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}),new Pe({...this._def,shape:()=>n})}required(t){const n={};return me.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 Pe({...this._def,shape:()=>n})}keyof(){return zd(me.objectKeys(this.shape))}}Pe.create=(e,t)=>new Pe({shape:()=>e,unknownKeys:"strip",catchall:on.create(),typeName:Q.ZodObject,...se(t)});Pe.strictCreate=(e,t)=>new Pe({shape:()=>e,unknownKeys:"strict",catchall:on.create(),typeName:Q.ZodObject,...se(t)});Pe.lazycreate=(e,t)=>new Pe({shape:e,unknownKeys:"strip",catchall:on.create(),typeName:Q.ZodObject,...se(t)});class Is 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 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:M.invalid_union,unionErrors:a}),te}}get options(){return this._def.options}}Is.create=(e,t)=>new Is({options:e,typeName:Q.ZodUnion,...se(t)});const Eo=e=>e instanceof Us?Eo(e.schema):e instanceof Ot?Eo(e.innerType()):e instanceof Ns?[e.value]:e instanceof Nn?e.options:e instanceof Ls?Object.keys(e.enum):e instanceof Hs?Eo(e._def.innerType):e instanceof Ts?[void 0]:e instanceof Os?[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=Eo(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 Na(e,t){const n=_n(e),r=_n(t);if(e===t)return{valid:!0,data:e};if(n===z.object&&r===z.object){const s=me.objectKeys(t),o=me.objectKeys(e).filter(a=>s.indexOf(a)!==-1),i={...e,...t};for(const a of o){const c=Na(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(Pa(o)||Pa(i))return te;const a=Na(o.value,i.value);return a.valid?((Ua(o)||Ua(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}))}}Cs.create=(e,t,n)=>new Cs({left:e,right:t,typeName:Q.ZodIntersection,...se(n)});class Dt 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 Kt(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>Qe.mergeArray(n,i)):Qe.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new Dt({...this._def,rest:t})}}Dt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dt({items:e,typeName:Q.ZodTuple,rest:null,...se(t)})};class Ps 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 Kt(r,a,r.path,a)),value:i._parse(new Kt(r,r.data[a],r.path,a))});return r.common.async?Qe.mergeObjectAsync(n,s):Qe.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof ae?new Ps({keyType:t,valueType:n,typeName:Q.ZodRecord,...se(r)}):new Ps({keyType:St.create(),valueType:t,typeName:Q.ZodRecord,...se(n)})}}class Vo 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],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}}}}Vo.create=(e,t,n)=>new Vo({valueType:t,keyType:e,typeName:Q.ZodMap,...se(n)});class lr 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 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 lr({...this._def,minSize:{value:t,message:X.toString(n)}})}max(t,n){return new lr({...this._def,maxSize:{value:t,message:X.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}lr.create=(e,t)=>new lr({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...se(t)});class Hr 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 jo({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ro(),As].filter(l=>!!l),issueData:{code:M.invalid_arguments,argumentsError:c}})}function s(a,c){return jo({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ro(),As].filter(l=>!!l),issueData:{code:M.invalid_return_type,returnTypeError:c}})}const o={errorMap:n.common.contextualErrorMap},i=n.data;return this._def.returns instanceof Fr?ot(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})}):ot((...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 Hr({...this._def,args:Dt.create(t).rest(rr.create())})}returns(t){return new Hr({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Hr({args:t||Dt.create([]).rest(rr.create()),returns:n||rr.create(),typeName:Q.ZodFunction,...se(r)})}}class Us 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})}}Us.create=(e,t)=>new Us({getter:e,typeName:Q.ZodLazy,...se(t)});class Ns 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}}Ns.create=(e,t)=>new Ns({value:e,typeName:Q.ZodLiteral,...se(t)});function zd(e,t){return new Nn({values:e,typeName:Q.ZodEnum,...se(t)})}class Nn extends ae{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return F(n,{expected:me.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 ot(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 Nn.create(t)}exclude(t){return Nn.create(this.options.filter(n=>!t.includes(n)))}}Nn.create=zd;class Ls extends ae{_parse(t){const n=me.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==z.string&&r.parsedType!==z.number){const s=me.objectValues(n);return F(r,{expected:me.joinValues(s),received:r.parsedType,code:M.invalid_type}),te}if(n.indexOf(t.data)===-1){const s=me.objectValues(n);return F(r,{received:r.data,code:M.invalid_enum_value,options:s}),te}return ot(t.data)}get enum(){return this._def.values}}Ls.create=(e,t)=>new Ls({values:e,typeName:Q.ZodNativeEnum,...se(t)});class Fr 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 ot(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Fr.create=(e,t)=>new Fr({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(!Ko(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=>Ko(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):i);me.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?ot(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 ur extends ae{_parse(t){return this._getType(t)===z.null?ot(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ur.create=(e,t)=>new ur({innerType:e,typeName:Q.ZodNullable,...se(t)});class Hs 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}}Hs.create=(e,t)=>new Hs({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...se(t)});class qo 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}}qo.create=(e,t)=>new qo({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...se(t)});class zo 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}}}zo.create=e=>new zo({typeName:Q.ZodNaN,...se(e)});const gx=Symbol("zod_brand");class Fd 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 Fs 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(),qd(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 Fs({in:t,out:n,typeName:Q.ZodPipeline})}}const Wd=(e,t={},n)=>e?zr.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})}}):zr.create(),mx={object:Pe.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 yx=(e,t={message:`Input not instance of ${e.name}`})=>Wd(n=>n instanceof e,t),Gd=St.create,Yd=Pn.create,wx=zo.create,bx=Un.create,Xd=Bs.create,xx=cr.create,vx=Mo.create,kx=Ts.create,$x=Os.create,Ex=zr.create,Sx=rr.create,_x=on.create,Ax=Zo.create,Bx=Tt.create,Tx=Pe.create,Ox=Pe.strictCreate,Ix=Is.create,Cx=xi.create,Px=Cs.create,Ux=Dt.create,Nx=Ps.create,Lx=Vo.create,Hx=lr.create,Rx=Hr.create,jx=Us.create,Kx=Ns.create,Dx=Nn.create,Mx=Ls.create,Zx=Fr.create,Xl=Ot.create,Vx=nn.create,qx=ur.create,zx=Ot.createWithPreprocess,Fx=Fs.create,Wx=()=>Gd().optional(),Gx=()=>Yd().optional(),Yx=()=>Xd().optional(),Xx={string:(e=>St.create({...e,coerce:!0})),number:(e=>Pn.create({...e,coerce:!0})),boolean:(e=>Bs.create({...e,coerce:!0})),bigint:(e=>Un.create({...e,coerce:!0})),date:(e=>cr.create({...e,coerce:!0}))},Jx=te;var st=Object.freeze({__proto__:null,defaultErrorMap:As,setErrorMap:nx,getErrorMap:Ro,makeIssue:jo,EMPTY_PATH:rx,addIssueToContext:F,ParseStatus:Qe,INVALID:te,DIRTY:qd,OK:ot,isAborted:Pa,isDirty:Ua,isValid:Ko,isAsync:Do,get util(){return me},get objectUtil(){return Ca},ZodParsedType:z,getParsedType:_n,ZodType:ae,ZodString:St,ZodNumber:Pn,ZodBigInt:Un,ZodBoolean:Bs,ZodDate:cr,ZodSymbol:Mo,ZodUndefined:Ts,ZodNull:Os,ZodAny:zr,ZodUnknown:rr,ZodNever:on,ZodVoid:Zo,ZodArray:Tt,ZodObject:Pe,ZodUnion:Is,ZodDiscriminatedUnion:xi,ZodIntersection:Cs,ZodTuple:Dt,ZodRecord:Ps,ZodMap:Vo,ZodSet:lr,ZodFunction:Hr,ZodLazy:Us,ZodLiteral:Ns,ZodEnum:Nn,ZodNativeEnum:Ls,ZodPromise:Fr,ZodEffects:Ot,ZodTransformer:Ot,ZodOptional:nn,ZodNullable:ur,ZodDefault:Hs,ZodCatch:qo,ZodNaN:zo,BRAND:gx,ZodBranded:Fd,ZodPipeline:Fs,custom:Wd,Schema:ae,ZodSchema:ae,late:mx,get ZodFirstPartyTypeKind(){return Q},coerce:Xx,any:Ex,array:Bx,bigint:bx,boolean:Xd,date:xx,discriminatedUnion:Cx,effect:Xl,enum:Dx,function:Rx,instanceof:yx,intersection:Px,lazy:jx,literal:Kx,map:Lx,nan:wx,nativeEnum:Mx,never:_x,null:$x,nullable:qx,number:Yd,object:Tx,oboolean:Yx,onumber:Gx,optional:Vx,ostring:Wx,pipeline:Fx,preprocess:zx,promise:Zx,record:Nx,set:Hx,strictObject:Ox,string:Gd,symbol:vx,transformer:Xl,tuple:Ux,undefined:kx,union:Ix,unknown:Sx,void:Ax,NEVER:Jx,ZodIssueCode:M,quotelessJson:tx,ZodError:Bt});const Jd=st.string().regex(/^[a-fA-F0-9]$/),Qx=st.string().regex(/^[a-fA-F0-9]{64}$/),Wr=st.number().min(0).max(4294967295),e2=st.bigint(),Qd=st.instanceof(Uint8Array),t2=st.union([Jd,Wr,st.string(),Qd]).array(),Rc=st.union([t2,Jd,Qd]),n2=st.array(Rc),eh=st.object({value:st.union([Wr,e2]),scriptPubKey:Rc}),r2=st.object({txid:Qx,vout:Wr,scriptSig:Rc,sequence:Wr,prevout:eh.optional(),witness:n2});st.object({version:Wr,vin:st.array(r2),vout:st.array(eh),locktime:Wr});const La=2048,s2=new TextEncoder;function th(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=s2.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>La)throw new Error(`Metadata must be at most ${La} CBOR bytes.`)};return r(e),Uint8Array.from(t)}function o2(e){if(e=new Uint8Array(e),!e.length||e.length>La)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}}),we=(e,t)=>({value:e,scriptPubKey:t}),Jl=16*1024,Ht=1e3,W=500,Fo="text/plain;charset=utf-8",i2=["text/plain","application/json","text/html","image/svg+xml","image/png","image/jpeg","image/webp"],nh=new TextEncoder,vs=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""),Wn=e=>Uint8Array.from(e.match(/../g)??[],t=>parseInt(t,16)),Wo=e=>vs(nh.encode(e));function jc(e){const t=typeof e=="string"?{contentType:Fo,bytes:nh.encode(e)}:e;if(!t||![...i2,Fo].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>Jl)throw new Error(`Body must be at most ${Jl} bytes.`);return{contentType:t.contentType,bytes:new Uint8Array(t.bytes)}}function Go(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 Ql(e){if(typeof e!="string"||!/^[0-9a-f]{64,72}$/.test(e)||e.length%2)throw new Error("Invalid parent tag.");const t=[...Wn(e.slice(64))].reduce((r,s,o)=>r+s*256**o,0),n=`${e.slice(0,64).match(/../g).reverse().join("")}i${t}`;if(Go(n)!==e)throw new Error("Non-canonical parent tag.");return n}function rh(e,t,n=null,r=void 0,s={}){const{contentType:o,bytes:i}=jc(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:th(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(Wo("ord"))+p("01")+p(Wo(o))+(a?p("0b")+p(Go(a)):"")+(c===void 0?"":p("02")+p(sh(c)))+(n?p("03")+p(Go(n)):"")+(u===void 0?"":Array.from({length:Math.ceil(u.length/520)},(g,h)=>p("05")+p(vs(u.slice(h*520,(h+1)*520)))).join(""))+(f?p("07")+p(vs(f)):"")+"00"+d.map(p).join("")+"68"}const a2=e=>bi.tree.getLeaf(Ne.encode(e,!0));function Kc(e){if(!Array.isArray(e)||e.length!==3)throw new Error("Unsupported script-path witness.");const t=Ne.decode(e[1]);let n=7,r=null,s=null,o;t[n]==="0b"&&(s=Ql(t[n+1]),n+=2),t[n]==="02"&&(o=l2(t[n+1]==="OP_0"?"":t[n+1]),n+=2),t[n]==="03"&&(r=Ql(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?o2(Wn(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(Wn(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(Wn(t[6])),u=jc({contentType:f,bytes:Wn(l.join(""))}),d=rh(t[0],u,r,a,{delegate:s,pointer:o,metaprotocol:c}),p=a===void 0&&!r&&f===Fo&&u.bytes.length<=280&&Ne.encode([t[0],"OP_CHECKSIG","OP_0","OP_IF",Wo("ord"),"01",Wo(Fo),"OP_0",vs(u.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{...u,parent:r,delegate:s,pointer:o,metaprotocol:c,metadata:a,metadataBytes:i.length?Wn(i.join("")):void 0,text:new TextDecoder().decode(u.bytes),pubkey:t[0]}}class c2{constructor(t,n){this.chain=t,this.wallet=n}prepare(t,n=null,r=void 0,s={}){const o=jc(t);if(r!==void 0&&th(r),s.delegate&&Go(s.delegate),s.pointer!==void 0&&sh(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=rh(this.wallet.pubkey,c,n,r,{...s,pointer:u}),p=a2(d),[g,h]=bi.getPubKey(this.wallet.pubkey,{target:p}),w=J.create({vin:[Je(o.txid,o.vout,o.value,o.scriptPubKey)],vout:[we(Ht+W,["OP_1",g]),we(o.value-Ht-2*W,this.wallet.script)]});w.vin[0].witness=[this.wallet.sign(w)];const m=J.util.getTxid(w),x=J.create({vin:[...l?[Je(l.txid,l.vout,l.value,l.scriptPubKey)]:[],Je(m,0,Ht+W,["OP_1",g])],vout:[...l?[we(l.value,this.wallet.script)]:[],we(Ht,this.wallet.script)]}),y=l?1:0;return x.vin[y].witness=[this.wallet.sign(x,p,y),Ne.encode(d,!1).hex,h],l&&(x.vin[0].witness=[this.wallet.sign(x)]),this.chain.submitPackage([J.encode(w).hex,J.encode(x).hex]),`${J.util.getTxid(x)}i0`}list(){return this.chain.coins(this.wallet.script).flatMap(t=>t.inscriptions??[])}}function sh(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 l2(e){if(typeof e!="string"||!/^(?:[0-9a-f]{2}){0,8}$/.test(e))throw new Error("Invalid pointer tag.");return[...Wn(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:zu(s,r.value)}));const n=(r,s,o)=>{var m;const i=J.decode(r),a=J.util.getTxid(i),c=i.vin[0].txid==="0".repeat(64),l=c?[]:i.vin.map(x=>this.utxos.get(`${x.txid}:${x.vout}`)),f=Gu(i,l,s,c);i.vin.forEach(x=>this.utxos.delete(`${x.txid}:${x.vout}`)),i.vout.forEach((x,y)=>this.utxos.set(`${a}:${y}`,{txid:a,vout:y,value:Number(x.value),ranges:f[y]}));const u=(m=i.vin.find(x=>{var y;return((y=x.witness)==null?void 0:y.length)===3}))==null?void 0:m.witness;if(!u)return;const d=Kc(u),p=BigInt(d.pointer??0),g=i.vout.reduce((x,y)=>x+Number(y.value),0),h=Wu(f.flat(),px.sat===h).length,status:s===null?"pending":"confirmed",height:s,block:o,metadata:w??null,hasMetadata:w!==void 0,parent:d.parent,protocol:d.metaprotocol??(w&&!Array.isArray(w)&&typeof w=="object"&&Object.hasOwn(w,"protocol")&&typeof w.protocol=="string"?w.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=xs(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 Br=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ws(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 Ze(e,...t){if(!Ws(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 Gs(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 Gr(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 oh(e,t){Ze(e);const n=t.outputLen;if(e.length>>t}function ao(e,t){return e<>>32-t>>>0}const f2=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function d2(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function h2(e){for(let t=0;te:h2,ih=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",p2=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ie(e){if(Ze(e),ih)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(ih)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(Yr(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function xr(e=32){if(Br&&typeof Br.getRandomValues=="function")return Br.getRandomValues(new Uint8Array(e));if(Br&&typeof Br.randomBytes=="function")return Uint8Array.from(Br.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function m2(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 y2(e,t,n){return e&t^~e&n}function w2(e,t,n){return e&t^e&n^t&n}class Mc extends Dc{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=sr(this.buffer)}update(t){Gr(this),t=Yr(t),Ze(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>ru&co)}:{h:Number(e>>ru&co)|0,l:Number(e&co)|0}}function ah(e,t=!1){const n=e.length;let r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;oe>>>n,ou=(e,t,n)=>e<<32-n|t>>>n,Tr=(e,t,n)=>e>>>n|t<<32-n,Or=(e,t,n)=>e<<32-n|t>>>n,lo=(e,t,n)=>e<<64-n|t>>>n-32,uo=(e,t,n)=>e>>>n-32|t<<64-n,x2=(e,t,n)=>e<>>32-n,v2=(e,t,n)=>t<>>32-n,k2=(e,t,n)=>t<>>64-n,$2=(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 E2=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),S2=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,_2=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),A2=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,B2=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),T2=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,O2=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]),vn=new Uint32Array(64);class I2 extends Mc{constructor(t=32){super(64,t,8,!1),this.A=xn[0]|0,this.B=xn[1]|0,this.C=xn[2]|0,this.D=xn[3]|0,this.E=xn[4]|0,this.F=xn[5]|0,this.G=xn[6]|0,this.H=xn[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)vn[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const d=vn[u-15],p=vn[u-2],g=Lt(d,7)^Lt(d,18)^d>>>3,h=Lt(p,17)^Lt(p,19)^p>>>10;vn[u]=h+vn[u-7]+g+vn[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),p=f+d+y2(a,c,l)+O2[u]+vn[u]|0,h=(Lt(r,2)^Lt(r,13)^Lt(r,22))+w2(r,s,o)|0;f=l,l=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,l=l+this.G|0,f=f+this.H|0,this.set(r,s,o,i,a,c,l,f)}roundClean(){wt(vn)}destroy(){this.set(0,0,0,0,0,0,0,0),wt(this.buffer)}}const ch=ah(["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))),C2=ch[0],P2=ch[1],kn=new Uint32Array(80),$n=new Uint32Array(80);class U2 extends Mc{constructor(t=64){super(128,t,16,!1),this.Ah=Ge[0]|0,this.Al=Ge[1]|0,this.Bh=Ge[2]|0,this.Bl=Ge[3]|0,this.Ch=Ge[4]|0,this.Cl=Ge[5]|0,this.Dh=Ge[6]|0,this.Dl=Ge[7]|0,this.Eh=Ge[8]|0,this.El=Ge[9]|0,this.Fh=Ge[10]|0,this.Fl=Ge[11]|0,this.Gh=Ge[12]|0,this.Gl=Ge[13]|0,this.Hh=Ge[14]|0,this.Hl=Ge[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:p,Gl:g,Hh:h,Hl:w}=this;return[t,n,r,s,o,i,a,c,l,f,u,d,p,g,h,w]}set(t,n,r,s,o,i,a,c,l,f,u,d,p,g,h,w){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=p|0,this.Gl=g|0,this.Hh=h|0,this.Hl=w|0}process(t,n){for(let y=0;y<16;y++,n+=4)kn[y]=t.getUint32(n),$n[y]=t.getUint32(n+=4);for(let y=16;y<80;y++){const $=kn[y-15]|0,b=$n[y-15]|0,O=Tr($,b,1)^Tr($,b,8)^su($,b,7),C=Or($,b,1)^Or($,b,8)^ou($,b,7),N=kn[y-2]|0,I=$n[y-2]|0,R=Tr(N,I,19)^lo(N,I,61)^su(N,I,6),A=Or(N,I,19)^uo(N,I,61)^ou(N,I,6),P=_2(C,A,$n[y-7],$n[y-16]),k=A2(P,O,R,kn[y-7],kn[y-16]);kn[y]=k|0,$n[y]=P|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:f,Eh:u,El:d,Fh:p,Fl:g,Gh:h,Gl:w,Hh:m,Hl:x}=this;for(let y=0;y<80;y++){const $=Tr(u,d,14)^Tr(u,d,18)^lo(u,d,41),b=Or(u,d,14)^Or(u,d,18)^uo(u,d,41),O=u&p^~u&h,C=d&g^~d&w,N=B2(x,b,C,P2[y],$n[y]),I=T2(N,m,$,O,C2[y],kn[y]),R=N|0,A=Tr(r,s,28)^lo(r,s,34)^lo(r,s,39),P=Or(r,s,28)^uo(r,s,34)^uo(r,s,39),k=r&o^r&a^o&a,S=s&i^s&c^i&c;m=h|0,x=w|0,h=p|0,w=g|0,p=u|0,g=d|0,{h:u,l:d}=Jt(l|0,f|0,I|0,R|0),l=a|0,f=c|0,a=o|0,c=i|0,o=r|0,i=s|0;const v=E2(R,P,S);r=S2(v,I,A,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:p,l:g}=Jt(this.Fh|0,this.Fl|0,p|0,g|0),{h,l:w}=Jt(this.Gh|0,this.Gl|0,h|0,w|0),{h:m,l:x}=Jt(this.Hh|0,this.Hl|0,m|0,x|0),this.set(r,s,o,i,a,c,l,f,u,d,p,g,h,w,m,x)}roundClean(){wt(kn,$n)}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 I2),Rs=vi(()=>new U2);class lh extends Dc{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Gs(t);const r=Yr(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 lh(e,t).update(n).digest();Ln.create=(e,t)=>new lh(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Zc=BigInt(0),Ha=BigInt(1);function fr(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=Ws(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 fo(e){const t=e.toString(16);return t.length&1?"0"+t:t}function uh(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Zc:BigInt("0x"+e)}function vr(e){return uh(Ie(e))}function dr(e){return Ze(e),uh(Ie(Uint8Array.from(e).reverse()))}function ki(e,t){return bt(e.toString(16).padStart(t*2,"0"))}function Vc(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(Ws(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 iu(e){return Uint8Array.from(e)}const Ji=e=>typeof e=="bigint"&&Zc<=e;function Ra(e,t,n){return Ji(e)&&Ji(t)&&Ji(n)&&t<=e&&eZc;e>>=Ha,t+=1);return t}const Ys=e=>(Ha<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},l=(...p)=>n(i,o,...p),f=(p=r(0))=>{i=l(s(0),p),o=l(),p.length!==0&&(i=l(s(1),p),o=l())},u=()=>{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(u()));)f();return c(),h}}function as(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 Yo(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 ct=BigInt(0),We=BigInt(1),Qn=BigInt(2),dh=BigInt(3),hh=BigInt(4),ph=BigInt(5),L2=BigInt(7),gh=BigInt(8),H2=BigInt(9),mh=BigInt(16);function Te(e,t){const n=e%t;return n>=ct?n:t+n}function Ce(e,t,n){let r=e;for(;t-- >ct;)r*=r,r%=n;return r}function au(e,t){if(e===ct)throw new Error("invert: expected non-zero number");if(t<=ct)throw new Error("invert: expected positive modulus, got "+t);let n=Te(e,t),r=t,s=ct,o=We;for(;n!==ct;){const a=r/n,c=r%n,l=s-o*a;r=n,n=c,s=o,o=l}if(r!==We)throw new Error("invert: does not exist");return Te(s,t)}function qc(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function yh(e,t){const n=(e.ORDER+We)/hh,r=e.pow(t,n);return qc(e,r,t),r}function R2(e,t){const n=(e.ORDER-ph)/gh,r=e.mul(t,Qn),s=e.pow(r,n),o=e.mul(t,s),i=e.mul(e.mul(o,Qn),s),a=e.mul(o,e.sub(i,e.ONE));return qc(e,a,t),a}function j2(e){const t=kr(e),n=wh(e),r=n(t,t.neg(t.ONE)),s=n(t,r),o=n(t,t.neg(r)),i=(e+L2)/mh;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),p=a.eql(a.sqr(f),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,f,p),f=a.cmov(d,u,g);const h=a.eql(a.sqr(f),c),w=a.cmov(l,f,h);return qc(a,w,c),w}}function wh(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return yh;let o=s.pow(r,t);const i=(t+We)/Qn;return function(c,l){if(c.is0(l))return l;if(cu(c,l)!==1)throw new Error("Cannot find square root");let f=n,u=c.mul(c.ONE,o),d=c.pow(l,t),p=c.pow(l,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 w=We<(Te(e,t)&We)===We,M2=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Z2(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=M2.reduce((r,s)=>(r[s]="function",r),t);return as(e,n),e}function V2(e,t,n){if(nct;)n&We&&(r=e.mul(r,s)),s=e.sqr(s),n>>=We;return r}function bh(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 cu(e,t){const n=(e.ORDER-We)/Qn,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 xh(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 kr(e,t,n=!1,r={}){if(e<=ct)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}=xh(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:Ys(c),ZERO:ct,ONE:We,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 ct<=d&&dd===ct,isValidNot0:d=>!u.is0(d)&&u.isValid(d),isOdd:d=>(d&We)===We,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)=>V2(u,d,p),div:(d,p)=>Te(d*au(p,e),e),sqrN:d=>d*d,addN:(d,p)=>d+p,subN:(d,p)=>d-p,mulN:(d,p)=>d*p,inv:d=>au(d,e),sqrt:o||(d=>(f||(f=K2(e)),f(u,d))),toBytes:d=>n?Vc(d,l):ki(d,l),fromBytes:(d,p=!0)=>{if(a){if(!a.includes(d.length)||d.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);const h=new Uint8Array(l);h.set(d,n?0:h.length-d.length),d=h}if(d.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+d.length);let g=n?dr(d):vr(d);if(i&&(g=Te(g,e)),!p&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:d=>bh(u,d),cmov:(d,p,g)=>g?p:d});return Object.freeze(u)}function vh(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 kh(e){const t=vh(e);return t+Math.ceil(t/2)}function $h(e,t,n=!1){const r=e.length,s=vh(t),o=kh(t);if(r<16||r1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);const i=n?dr(e):vr(e),a=Te(i,t-We)+We;return n?Vc(a,s):ki(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Xr=BigInt(0),er=BigInt(1);function Xo(e,t){const n=t.negate();return e?n:t}function tr(e,t){const n=bh(e.Fp,t.map(r=>r.Z));return t.map((r,s)=>e.fromAffine(r.toAffine(n[s])))}function Eh(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Qi(e,t){Eh(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1),s=2**e,o=Ys(e),i=BigInt(e);return{windows:n,windowSize:r,mask:o,maxNumber:s,shiftBy:i}}function lu(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+=er);const l=t*r,f=l+Math.abs(a)-1,u=a===0,d=a<0,p=t%2!==0;return{nextN:c,offset:f,isZero:u,isNeg:d,isNegF:p,offsetF:l}}function q2(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 z2(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 ea=new WeakMap,Sh=new WeakMap;function ta(e){return Sh.get(e)||1}function uu(e){if(e!==Xr)throw new Error("invalid wNAF")}class _h{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>Xr;)n&er&&(r=r.add(s)),s=s.double(),n>>=er;return r}precomputeWindow(t,n){const{windows:r,windowSize:s}=Qi(n,this.bits),o=[];let i=t,a=i;for(let c=0;cXr||r>Xr;)n&er&&(o=o.add(s)),r&er&&(i=i.add(s)),s=s.double(),n>>=er,r>>=er;return{p1:o,p2:i}}function Ah(e,t,n,r){q2(n,e),z2(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=fh(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Ys(c),f=new Array(Number(l)+1).fill(i),u=Math.floor((t.BITS-1)/c)*c;let d=i;for(let p=u;p>=0;p-=c){f.fill(i);for(let h=0;h>BigInt(p)&l);f[m]=f[m].add(n[h])}let g=i;for(let h=f.length-1,w=i;h>0;h--)w=w.add(f[h]),g=g.add(w);if(d=d.add(g),p!==0)for(let h=0;hXr))throw new Error(`CURVE.${c} must be positive bigint`)}const s=fu(t.p,n.Fp,r),o=fu(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 du=(e,t)=>(e+(e>=0?t:-t)/Th)/t;function W2(e,t,n){const[[r,s],[o,i]]=t,a=du(i*e,n),c=du(-s*e,n);let l=e-a*r-c*o,f=-a*s-c*i;const u=l=p||f=p)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:u,k1:l,k2neg:d,k2:f}}function ja(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function na(e,t){const n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return fr(n.lowS,"lowS"),fr(n.prehash,"prehash"),n.format!==void 0&&ja(n.format),n}class G2 extends Error{constructor(t=""){super(t)}}const Qt={Err:G2,_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=fo(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const o=r>127?fo(s.length/2|128):"";return fo(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:S,Y:v,Z:_}=P;if(r.eql(_,r.ONE))return{x:S,y:v};const U=P.is0();k==null&&(k=U?r.ONE:r.inv(_));const K=r.mul(S,k),L=r.mul(v,k),D=r.mul(_,k);if(U)return{x:r.ZERO,y:r.ZERO};if(!r.eql(D,r.ONE))throw new Error("invZ was invalid");return{x:K,y:L}}),C=Yo(P=>{if(P.is0()){if(t.allowInfinityPoint&&!r.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:k,y:S}=P.toAffine();if(!r.isValid(k)||!r.isValid(S))throw new Error("bad point: x or y not field elements");if(!w(k,S))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(P,k,S,v,_){return S=new I(r.mul(S.X,P),S.Y,S.Z),k=Xo(v,k),S=Xo(_,S),k.add(S)}class I{constructor(k,S,v){this.X=y("x",k),this.Y=y("y",S,!0),this.Z=y("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 I)throw new Error("projective point not allowed");return r.is0(S)&&r.is0(v)?I.ZERO:new I(S,v,r.ONE)}static fromBytes(k){const S=I.fromAffine(g(_t(k,void 0,"point")));return S.assertValidity(),S}static fromHex(k){return I.fromBytes(be("pointHex",k))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(k=8,S=!0){return A.createCache(this,k),S||this.multiply(ho),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:S,Y:v,Z:_}=this,{X:U,Y:K,Z:L}=k,D=r.eql(r.mul(S,L),r.mul(U,_)),q=r.eql(r.mul(v,L),r.mul(K,_));return D&&q}negate(){return new I(this.X,r.neg(this.Y),this.Z)}double(){const{a:k,b:S}=o,v=r.mul(S,ho),{X:_,Y:U,Z:K}=this;let L=r.ZERO,D=r.ZERO,q=r.ZERO,G=r.mul(_,_),ue=r.mul(U,U),ce=r.mul(K,K),ne=r.mul(_,U);return ne=r.add(ne,ne),q=r.mul(_,K),q=r.add(q,q),L=r.mul(k,q),D=r.mul(v,ce),D=r.add(L,D),L=r.sub(ue,D),D=r.add(ue,D),D=r.mul(L,D),L=r.mul(ne,L),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(U,K),ce=r.add(ce,ce),G=r.mul(ce,ne),L=r.sub(L,G),q=r.mul(ce,ue),q=r.add(q,q),q=r.add(q,q),new I(L,D,q)}add(k){$(k);const{X:S,Y:v,Z:_}=this,{X:U,Y:K,Z:L}=k;let D=r.ZERO,q=r.ZERO,G=r.ZERO;const ue=o.a,ce=r.mul(o.b,ho);let ne=r.mul(S,U),pe=r.mul(v,K),ge=r.mul(_,L),Le=r.add(S,v),de=r.add(U,K);Le=r.mul(Le,de),de=r.add(ne,pe),Le=r.sub(Le,de),de=r.add(S,_);let _e=r.add(U,L);return de=r.mul(de,_e),_e=r.add(ne,ge),de=r.sub(de,_e),_e=r.add(v,_),D=r.add(K,L),_e=r.mul(_e,D),D=r.add(pe,ge),_e=r.sub(_e,D),G=r.mul(ue,de),D=r.mul(ce,ge),G=r.add(D,G),D=r.sub(pe,G),G=r.add(pe,G),q=r.mul(D,G),pe=r.add(ne,ne),pe=r.add(pe,ne),ge=r.mul(ue,ge),de=r.mul(ce,de),pe=r.add(pe,ge),ge=r.sub(ne,ge),ge=r.mul(ue,ge),de=r.add(de,ge),ne=r.mul(pe,de),q=r.add(q,ne),ne=r.mul(_e,de),D=r.mul(Le,D),D=r.sub(D,ne),ne=r.mul(Le,pe),G=r.mul(_e,G),G=r.add(G,ne),new I(D,q,G)}subtract(k){return this.add(k.negate())}is0(){return this.equals(I.ZERO)}multiply(k){const{endo:S}=t;if(!s.isValidNot0(k))throw new Error("invalid scalar: out of range");let v,_;const U=K=>A.cached(this,K,L=>tr(I,L));if(S){const{k1neg:K,k1:L,k2neg:D,k2:q}=b(k),{p:G,f:ue}=U(L),{p:ce,f:ne}=U(q);_=ue.add(ne),v=N(S.beta,G,ce,K,D)}else{const{p:K,f:L}=U(k);v=K,_=L}return tr(I,[v,_])[0]}multiplyUnsafe(k){const{endo:S}=t,v=this;if(!s.isValid(k))throw new Error("invalid scalar: out of range");if(k===en||v.is0())return I.ZERO;if(k===Rr)return v;if(A.hasCache(this))return this.multiply(k);if(S){const{k1neg:_,k1:U,k2neg:K,k2:L}=b(k),{p1:D,p2:q}=F2(I,v,U,L);return N(S.beta,D,q,_,K)}else return A.unsafe(v,k)}multiplyAndAddUnsafe(k,S,v){const _=this.multiplyUnsafe(S).add(k.multiplyUnsafe(v));return _.is0()?void 0:_}toAffine(k){return O(this,k)}isTorsionFree(){const{isTorsionFree:k}=t;return i===Rr?!0:k?k(I,this):A.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:k}=t;return i===Rr?this:k?k(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(k=!0){return fr(k,"isCompressed"),this.assertValidity(),p(I,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 tr(I,k)}static msm(k,S){return Ah(I,s,k,S)}static fromPrivateKey(k){return I.BASE.multiply(nr(s,k))}}I.BASE=new I(o.Gx,o.Gy,r.ONE),I.ZERO=new I(r.ZERO,r.ONE,r.ZERO),I.Fp=r,I.Fn=s;const R=s.BITS,A=new _h(I,t.endo?Math.ceil(R/2):R);return I.BASE.precompute(8),I}function Oh(e){return Uint8Array.of(e?2:3)}function Ih(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function J2(e,t={}){const{Fn:n}=e,r=t.randomBytes||xr,s=Object.assign(Ih(e.Fp,n),{seed:kh(n.ORDER)});function o(p){try{return!!nr(n,p)}catch{return!1}}function i(p,g){const{publicKey:h,publicKeyUncompressed:w}=s;try{const m=p.length;return g===!0&&m!==h||g===!1&&m!==w?!1:!!e.fromBytes(p)}catch{return!1}}function a(p=r(s.seed)){return $h(_t(p,s.seed,"seed"),n.ORDER)}function c(p,g=!0){return e.BASE.multiply(nr(n,p)).toBytes(g)}function l(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:w}=s;if(n.allowedLengths||g===h)return;const m=be("key",p).length;return m===h||m===w}function u(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 w=nr(n,p);return e.fromHex(g).multiply(w).toBytes(h)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:e,utils:{isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:p=>nr(n,p),precompute(p=8,g=e.BASE){return g.precompute(p,!1)}},lengths:s})}function Q2(e,t,n={}){Gs(t),as(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||xr,s=n.hmac||((S,...v)=>Ln(t,S,le(...v))),{Fp:o,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:p}=J2(e,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},h="compact";function w(S){const v=a>>Rr;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){ja(v);const _=p.signature,U=v==="compact"?_:v==="recovered"?_+1:void 0;return _t(S,U,`${v} signature`)}class y{constructor(v,_,U){this.r=m("r",v),this.s=m("s",_),U!=null&&(this.recovery=U),Object.freeze(this)}static fromBytes(v,_=h){x(v,_);let U;if(_==="der"){const{r:q,s:G}=Qt.toSig(_t(v));return new y(q,G)}_==="recovered"&&(U=v[0],_="compact",v=v.subarray(1));const K=i.BYTES,L=v.subarray(0,K),D=v.subarray(K,K*2);return new y(i.fromBytes(L),i.fromBytes(D),U)}static fromHex(v,_){return this.fromBytes(bt(v),_)}addRecoveryBit(v){return new y(this.r,this.s,v)}recoverPublicKey(v){const _=o.ORDER,{r:U,s:K,recovery:L}=this;if(L==null||![0,1,2,3].includes(L))throw new Error("recovery id invalid");if(a*Th<_&&L>1)throw new Error("recovery id is ambiguous for h>1 curve");const q=L===2||L===3?U+a:U;if(!o.isValid(q))throw new Error("recovery id 2 or 3 invalid");const G=o.toBytes(q),ue=e.fromBytes(le(Oh((L&1)===0),G)),ce=i.inv(q),ne=b(be("msgHash",v)),pe=i.create(-ne*ce),ge=i.create(K*ce),Le=e.BASE.multiplyUnsafe(pe).add(ue.multiplyUnsafe(ge));if(Le.is0())throw new Error("point at infinify");return Le.assertValidity(),Le}hasHighS(){return w(this.s)}toBytes(v=h){if(ja(v),v==="der")return bt(Qt.hexFromSig(this));const _=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),_,U)}return le(_,U)}toHex(v){return Ie(this.toBytes(v))}assertValidity(){}static fromCompact(v){return y.fromBytes(be("sig",v),"compact")}static fromDER(v){return y.fromBytes(be("sig",v),"der")}normalizeS(){return this.hasHighS()?new y(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 _=vr(v),U=v.length*8-c;return U>0?_>>BigInt(U):_},b=n.bits2int_modN||function(v){return i.create($(v))},O=Ys(c);function C(S){return js("num < 2^"+c,S,en,O),i.toBytes(S)}function N(S,v){return _t(S,void 0,"message"),v?_t(t(S),void 0,"prehashed message"):S}function I(S,v,_){if(["recovered","canonical"].some(pe=>pe in _))throw new Error("sign() legacy options not supported");const{lowS:U,prehash:K,extraEntropy:L}=na(_,g);S=N(S,K);const D=b(S),q=nr(i,v),G=[C(q),C(D)];if(L!=null&&L!==!1){const pe=L===!0?r(p.secretKey):L;G.push(be("extraEntropy",pe))}const ue=le(...G),ce=D;function ne(pe){const ge=$(pe);if(!i.isValidNot0(ge))return;const Le=i.inv(ge),de=e.BASE.multiply(ge).toAffine(),_e=i.create(de.x);if(_e===en)return;const Wt=i.create(Le*i.create(ce+_e*q));if(Wt===en)return;let ht=(de.x===_e?0:2)|Number(de.y&Rr),ze=Wt;return U&&w(Wt)&&(ze=i.neg(Wt),ht^=1),new y(_e,ze,ht)}return{seed:ue,k2sig:ne}}function R(S,v,_={}){S=be("message",S);const{seed:U,k2sig:K}=I(S,v,_);return N2(t.outputLen,i.BYTES,s)(U,K)}function A(S){let v;const _=typeof S=="string"||Ws(S),U=!_&&S!==null&&typeof S=="object"&&typeof S.r=="bigint"&&typeof S.s=="bigint";if(!_&&!U)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(U)v=new y(S.r,S.s);else if(_){try{v=y.fromBytes(be("sig",S),"der")}catch(K){if(!(K instanceof Qt.Err))throw K}if(!v)try{v=y.fromBytes(be("sig",S),"compact")}catch{return!1}}return v||!1}function P(S,v,_,U={}){const{lowS:K,prehash:L,format:D}=na(U,g);if(_=be("publicKey",_),v=N(be("message",v),L),"strict"in U)throw new Error("options.strict was renamed to lowS");const q=D===void 0?A(S):y.fromBytes(be("sig",S),D);if(q===!1)return!1;try{const G=e.fromBytes(_);if(K&&q.hasHighS())return!1;const{r:ue,s:ce}=q,ne=b(v),pe=i.inv(ce),ge=i.create(ne*pe),Le=i.create(ue*pe),de=e.BASE.multiplyUnsafe(ge).add(G.multiplyUnsafe(Le));return de.is0()?!1:i.create(de.x)===ue}catch{return!1}}function k(S,v,_={}){const{prehash:U}=na(_,g);return v=N(v,U),y.fromBytes(S,"recovered").recoverPublicKey(v).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:p,Point:e,sign:R,verify:P,recoverPublicKey:k,Signature:y,hash:t})}function ev(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=kr(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 tv(e){const{CURVE:t,curveOpts:n}=ev(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 nv(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,xh(n.Fn.ORDER,n.Fn.BITS))})}function rv(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:s}=tv(e),o=X2(t,n),i=Q2(o,r,s);return nv(e,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function sv(e,t){const n=r=>rv({...e,hash:r});return{...n(t),create:n}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Jr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},ov={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},iv=BigInt(0),hu=BigInt(1),Ka=BigInt(2);function av(e){const t=Jr.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=Ce(f,n,t)*f%t,d=Ce(u,n,t)*f%t,p=Ce(d,Ka,t)*l%t,g=Ce(p,s,t)*p%t,h=Ce(g,o,t)*g%t,w=Ce(h,a,t)*h%t,m=Ce(w,c,t)*w%t,x=Ce(m,a,t)*h%t,y=Ce(x,n,t)*f%t,$=Ce(y,i,t)*g%t,b=Ce($,r,t)*l%t,O=Ce(b,Ka,t);if(!Jo.eql(Jo.sqr(O),e))throw new Error("Cannot find square root");return O}const Jo=kr(Jr.p,{sqrt:av}),Oe=sv({...Jr,Fp:Jo,lowS:!0,endo:ov},Ae),pu={};function Qo(e,...t){let n=pu[e];if(n===void 0){const r=Ae(Ke(e));n=le(r,r),pu[e]=n}return Ae(le(n,...t))}const zc=e=>e.toBytes(!0).slice(1),cs=Oe.Point,Fc=e=>e%Ka===iv;function Da(e){const{Fn:t,BASE:n}=cs,r=nr(t,e),s=n.multiply(r);return{scalar:Fc(s.y)?r:t.neg(r),bytes:zc(s)}}function Ch(e){const t=Jo;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);Fc(s)||(s=t.neg(s));const o=cs.fromAffine({x:e,y:s});return o.assertValidity(),o}const ks=vr;function Ph(...e){return cs.Fn.create(ks(Qo("BIP0340/challenge",...e)))}function gu(e){return Da(e).bytes}function cv(e,t,n=xr(32)){const{Fn:r}=cs,s=be("message",e),{bytes:o,scalar:i}=Da(t),a=be("auxRand",n,32),c=r.toBytes(i^ks(Qo("BIP0340/aux",a))),l=Qo("BIP0340/nonce",c,o,s),{bytes:f,scalar:u}=Da(l),d=Ph(f,o,s),p=new Uint8Array(64);if(p.set(f,0),p.set(r.toBytes(r.create(u+d*i)),32),!Uh(p,s,o))throw new Error("sign: Invalid signature produced");return p}function Uh(e,t,n){const{Fn:r,BASE:s}=cs,o=be("signature",e,64),i=be("message",t),a=be("publicKey",n,32);try{const c=Ch(ks(a)),l=ks(o.subarray(0,32));if(!Ra(l,hu,Jr.p))return!1;const f=ks(o.subarray(32,64));if(!Ra(f,hu,Jr.n))return!1;const u=Ph(r.toBytes(l),zc(c),i),d=s.multiplyUnsafe(f).add(c.multiplyUnsafe(r.neg(u))),{x:p,y:g}=d.toAffine();return!(d.is0()||!Fc(g)||p!==l)}catch{return!1}}const Hn=(()=>{const n=(s=xr(48))=>$h(s,Jr.n);Oe.utils.randomSecretKey;function r(s){const o=n(s);return{secretKey:o,publicKey:gu(o)}}return{keygen:r,getPublicKey:gu,sign:cv,verify:Uh,Point:cs,utils:{randomSecretKey:n,randomPrivateKey:n,taggedHash:Qo,lift_x:Ch,pointToBytes:zc,numberToBytesBE:ki,bytesToNumberBE:vr,mod:Te},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})(),lv=BigInt(0),hs=BigInt(1),uv=BigInt(2),fv=BigInt(7),dv=BigInt(256),hv=BigInt(113),Nh=[],Lh=[],Hh=[];for(let e=0,t=hs,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Nh.push(2*(5*r+n)),Lh.push((e+1)*(e+2)/2%64);let s=lv;for(let o=0;o<7;o++)t=(t<>fv)*hv)%dv,t&uv&&(s^=hs<<(hs<n>32?k2(e,t,n):x2(e,t,n),yu=(e,t,n)=>n>32?$2(e,t,n):v2(e,t,n);function mv(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=mu(l,f,1)^n[a],d=yu(l,f,1)^n[a+1];for(let p=0;p<50;p+=10)e[i+p]^=u,e[i+p+1]^=d}let s=e[2],o=e[3];for(let i=0;i<24;i++){const a=Lh[i],c=mu(s,o,a),l=yu(s,o,a),f=Nh[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]^=pv[r],e[1]^=gv[r]}wt(n)}class Wc extends Dc{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(oh(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 Wc(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 yv=(e,t,n)=>vi(()=>new Wc(t,e,n)),Gc=yv(1,136,256/8),wv=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),jh=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),bv=jh.map(e=>(9*e+5)%16),Kh=(()=>{const n=[[jh],[bv]];for(let r=0;r<4;r++)for(let s of n)s.push(s[r].map(o=>wv[o]));return n})(),Dh=Kh[0],Mh=Kh[1],Zh=[[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)),xv=Dh.map((e,t)=>e.map(n=>Zh[t][n])),vv=Mh.map((e,t)=>e.map(n=>Zh[t][n])),kv=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),$v=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function wu(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 po=new Uint32Array(16);class Ev extends Mc{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)po[p]=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 p=0;p<5;p++){const g=4-p,h=kv[p],w=$v[p],m=Dh[p],x=Mh[p],y=xv[p],$=vv[p];for(let b=0;b<16;b++){const O=ao(r+wu(p,o,a,l)+po[m[b]]+h,y[b])+u|0;r=u,u=l,l=ao(a,10)|0,a=o,o=O}for(let b=0;b<16;b++){const O=ao(s+wu(g,i,c,f)+po[x[b]]+w,$[b])+d|0;s=d,d=f,f=ao(c,10)|0,c=i,i=O}}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(po)}destroy(){this.destroyed=!0,wt(this.buffer),this.set(0,0,0,0,0)}}const Yc=vi(()=>new Ev);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Qr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Sv(e,...t){if(!Qr(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 Vh(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 qh(e){if(typeof e!="function")throw new Error("function expected");return!0}function hr(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function ls(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function ei(e){if(!Array.isArray(e))throw new Error("array expected")}function ti(e,t){if(!Vh(!0,t))throw new Error(`${e}: array of strings expected`)}function Xc(e,t){if(!Vh(!1,t))throw new Error(`${e}: array of numbers expected`)}function Xs(...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;ti("alphabet",t);const r=new Map(t.map((s,o)=>[s,o]));return{encode:s=>(ei(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=>(ei(s),s.map(o=>{hr("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 hr("join",e),{encode:t=>(ti("join.decode",t),t.join(e)),decode:t=>(hr("join.decode",t),t.split(e))}}function zh(e,t="="){return ls(e),hr("padding",t),{encode(n){for(ti("padding.encode",n);n.length*e%8;)n.push(t);return n},decode(n){ti("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 Ma(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(ei(e),!e.length)return[];let r=0;const s=[],o=Array.from(e,a=>{if(ls(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:Fh(t,e%t),ni=(e,t)=>e+(t-Fh(e,t)),So=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function ri(e,t,n,r){if(ei(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(ni(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${ni(t,n)}`);let s=0,o=0;const i=So[t],a=So[n]-1,c=[];for(const l of e){if(ls(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=So[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 Wh(e){ls(e);const t=2**8;return{encode:n=>{if(!Qr(n))throw new Error("radix.encode input should be Uint8Array");return Ma(Array.from(n),t,e)},decode:n=>(Xc("radix.decode",n),Uint8Array.from(Ma(n,e,t)))}}function Jc(e,t=!1){if(ls(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(ni(8,e)>32||ni(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!Qr(n))throw new Error("radix2.encode input should be Uint8Array");return ri(Array.from(n),8,e,!t)},decode:n=>(Xc("radix2.decode",n),Uint8Array.from(ri(n,e,8,t)))}}function bu(e){return qh(e),function(...t){try{return e.apply(null,t)}catch{}}}function Gh(e,t){return ls(e),qh(t),{encode(n){if(!Qr(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(!Qr(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{hr("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=_v?{encode(e){return Sv(e),e.toBase64()},decode(e){return Av(e)}}:Xs(Jc(6),$i("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),zh(6),Ei("")),Bv=e=>Xs(Wh(58),$i(e),Ei("")),Tv=Bv("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),Yh=e=>Xs(Gh(4,t=>e(e(t))),Tv),Za=Xs($i("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Ei("")),xu=[996825010,642813549,513874426,1027748829,705979059];function ps(e){const t=e>>25;let n=(e&33554431)<<5;for(let r=0;r>r&1)===1&&(n^=xu[r]);return n}function vu(e,t,n=1){const r=e.length;let s=1;for(let o=0;o126)throw new Error(`Invalid prefix (${e})`);s=ps(s)^i>>5}s=ps(s);for(let o=0;op)throw new TypeError(`Length ${h} exceeds limit ${p}`);const w=u.toLowerCase(),m=vu(w,d,t);return`${w}1${Za.encode(d)}${m}`}function a(u,d=90){hr("bech32.decode input",u);const p=u.length;if(p<8||d!==!1&&p>d)throw new TypeError(`invalid string length: ${p} (${u}). Expected (8..${d})`);const g=u.toLowerCase();if(u!==g&&u!==u.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 w=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),y=vu(w,x,t);if(!m.endsWith(y))throw new Error(`Invalid checksum in ${u}: expected "${y}"`);return{prefix:w,words:x}}const c=bu(a);function l(u){const{prefix:d,words:p}=a(u,!1);return{prefix:d,words:p,bytes:r(p)}}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 pr=Xh("bech32"),Ov=Xh("bech32m");/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */const mo=Oe.ProjectivePoint,ra=Yh(Ae);function ku(e){Ze(e);const t=e.length===0?"0":Ie(e);return BigInt("0x"+t)}function Iv(e){if(typeof e!="bigint")throw new Error("bigint expected");return bt(e.toString(16).padStart(64,"0"))}const Cv=Ke("Bitcoin seed"),sa={private:76066276,public:76067358},oa=2147483648,Pv=e=>Yc(Ae(e)),Uv=e=>sr(e).getUint32(0,!1),yo=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 sr(t).setUint32(0,e,!1),t};class Gn{get fingerprint(){if(!this.pubHash)throw new Error("No publicKey set!");return Uv(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 ra.encode(this.serialize(this.versions.private,le(new Uint8Array([0]),t)))}get publicExtendedKey(){if(!this.pubKey)throw new Error("No public key");return ra.encode(this.serialize(this.versions.public,this.pubKey))}static fromMasterSeed(t,n=sa){if(Ze(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=Ln(Rs,Cv,t);return new Gn({versions:n,chainCode:r.slice(32),privateKey:r.slice(0,32)})}static fromExtendedKey(t,n=sa){const r=ra.decode(t),s=sr(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 Gn({...i,privateKey:a.slice(1)}):new Gn({...i,publicKey:a})}static fromJSON(t){return Gn.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||sa,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:ku(t.privateKey),this.privKeyBytes=Iv(this.privKey),this.pubKey=Oe.getPublicKey(t.privateKey,!0)}else if(t.publicKey)this.pubKey=mo.fromHex(t.publicKey).toRawBytes(!0);else throw new Error("HDKey: no public or private key provided");this.pubHash=Pv(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>=oa)throw new Error("Invalid index");o[2]==="'"&&(a+=oa),r=r.deriveChild(a)}return r}deriveChild(t){if(!this.pubKey||!this.chainCode)throw new Error("No publicKey or chainCode set");let n=yo(t);if(t>=oa){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=Ln(Rs,this.chainCode,n),s=ku(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=mo.fromHex(this.pubKey).add(mo.fromPrivateKey(s));if(a.equals(mo.ZERO))throw new Error("The tweak was equal to negative P, which made the result key invalid");i.publicKey=a.toRawBytes(!0)}return new Gn(i)}catch{return this.deriveChild(t+1)}}sign(t){if(!this.privateKey)throw new Error("No privateKey set!");return Ze(t,32),Oe.sign(t,this.privKey).toCompactRawBytes()}verify(t,n){if(Ze(t,32),Ze(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 Ze(n,33),le(yo(t),new Uint8Array([this.depth]),yo(this.parentFingerprint),yo(this.index),this.chainCode,n)}}function Nv(e,t,n,r){Gs(e);const s=g2({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=nu(t),l=nu(n),f=new Uint8Array(i),u=Ln.create(e,c),d=u._cloneInto().update(l);return{c:o,dkLen:i,asyncTick:a,DK:f,PRF:u,PRFSalt:d}}function Lv(e,t,n,r,s){return e.destroy(),t.destroy(),r&&r.destroy(),wt(s),n}function Hv(e,t,n,r){const{c:s,dkLen:o,DK:i,PRF:a,PRFSalt:c}=Nv(e,t,n,r);let l;const f=new Uint8Array(4),u=sr(f),d=new Uint8Array(a.outputLen);for(let p=1,g=0;ge[0]==="あいこくしん";function Jh(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function Qh(e){const t=Jh(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}function ep(e){Ze(e,16,20,24,28,32)}function jv(e,t=128){if(Rt(t),t%32!==0||t>256)throw new TypeError("Invalid entropy");return np(xr(t/8),e)}const Kv=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)}),go.chain(go.checksum(1,Kv),go.radix2(11,!0),go.alphabet(e))}function Dv(e,t){const{words:n}=Qh(e),r=tp(t).decode(n);return ep(r),r}function np(e,t){return ep(e),tp(t).encode(e).join(Rv(t)?" ":" ")}function Mv(e,t){try{Dv(e,t)}catch{return!1}return!0}const Zv=e=>Jh("mnemonic"+e);function Vv(e,t=""){return Hv(Rs,Qh(e).nfkd,Zv(t),{c:2048,dkLen:64})}const Qc=`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`},qv=2**31-1,ia=new Map,aa=new Map,$u=()=>jv(Qc,256);function rp(e,t=0){if(typeof e!="string"||!Mv(e,Qc)||t&&e.split(" ").length!==t)throw new Error("Invalid lab mnemonic.");return e}function Zn(e,t){if(!Number.isSafeInteger(e)||e<0||e>qv)throw new Error(`Invalid ${t}.`);return e}const ca=new Map;function el(e){return ca.has(e)||ca.set(e,Vv(rp(e))),ca.get(e)}function Vn(e){return ia.has(e)||ia.set(e,Gn.fromMasterSeed(el(e))),ia.get(e)}function zv(e,t){const n=e.derive(t).privateKey;if(!n)throw new Error("BIP-85 path produced no private key.");return Ln(Rs,Ke("bip-entropy-from-k"),n)}function Fv(e,t){const n=`${e}|${Zn(t,"child index")}`;return aa.has(n)||aa.set(n,np(zv(Vn(e),rt.orgSeed(t)).slice(0,32),Qc)),aa.get(n)}function Va(e,t=0,n=1){return Ie(Vn(e).derive(rt.wallet(Zn(t,"account"),n)).privateKey)}function tl(e,t=0,n=1){return Ie(Vn(e).derive(rt.segwit(Zn(t,"account"),n)).privateKey)}function sp(e,t=0,n=1){return Ie(Vn(e).derive(rt.segwit(Zn(t,"account"),n)).publicKey)}function Si(e,t=0){return Ie(Vn(e).derive(rt.nostr(Zn(t,"account"))).privateKey)}function op(e){const t=e.toLowerCase(),n=Ie(Gc(Ke(t)));return`0x${[...t].map((r,s)=>parseInt(n[s],16)>=8?r.toUpperCase():r).join("")}`}const ip=e=>op(Ie(Gc(Oe.ProjectivePoint.fromHex(e).toRawBytes(!1).slice(1)).slice(-20)));function ap(e,t=0){return Ie(Vn(e).derive(rt.ethereum(Zn(t,"account"))).privateKey)}const la=new Map;function Wv(e,t=0){const n=`${e}|${t}`;return la.has(n)||la.set(n,ip(Vn(e).derive(rt.ethereum(Zn(t,"account"))).publicKey)),la.get(n)}function Gv(e,t=0){const n=Hn.getPublicKey(Vn(e).derive(rt.nostr(Zn(t,"account"))).privateKey);return{pubkey:Ie(n),npub:pr.encode("npub",pr.toWords(n))}}const It=["taproot","segwit","nostr","ethereum"],_i=(e,t)=>["lineage/v0 keyring",`node: ${e}`,...It.map(n=>`${n}: ${t[n]}`)].join(` +`),Yv=["bc","tb","bcrt"],cp=new Uint8Array(32),at=e=>{const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),t},Ks=e=>le(e.length<253?Uint8Array.of(e.length):Uint8Array.of(253,e.length&255,e.length>>8),e),bs=e=>Ae(Ae(e)),lp=(e,...t)=>{const n=Ae(Ke(e));return Ae(le(n,n,...t))},Xv=(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[[pr,0],[Ov,1]])try{const{prefix:r,words:s}=t.decode(e,90);if(s[0]===n&&Yv.includes(r))return{network:r,version:n,program:Uint8Array.from(t.fromWords(s.slice(1)))}}catch{}return null}const nl=e=>(e==null?void 0:e.version)===1&&e.program.length===32,rl=e=>(e==null?void 0:e.version)===0&&e.program.length===20,up=({version:e,program:t})=>le(Uint8Array.of(e?80+e:0,t.length),t),Jv=e=>lp("BIP0322-signed-message",Ke(e)),si=new Uint8Array(8),Eu=le(si,Ks(Uint8Array.of(106)));function Qv(e,t){const n=up(e),r=le(Uint8Array.of(0,32),Jv(t));return bs(le(at(0),Uint8Array.of(1),new Uint8Array(32),at(4294967295),Ks(r),at(0),Uint8Array.of(1),si,Ks(n),at(0)))}function oi(e,t,n=0){const r=up(e),s=le(Qv(e,t),at(0));if(e.version===0){const o=le(Uint8Array.of(25,118,169,20),e.program,Uint8Array.of(136,172));return bs(le(at(0),bs(s),bs(at(0)),s,o,si,at(0),bs(Eu),at(0),at(1)))}return lp("TapSighash",Uint8Array.of(0,n),at(0),at(0),Ae(s),Ae(si),Ae(Ks(r)),Ae(at(0)),Ae(Eu),Uint8Array.of(0),at(0))}const Su=e=>yt.encode(le(Uint8Array.of(e.length),...e.map(Ks)));function ek(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 _u(e,t,n){const r=Ds(e);if(nl(r))return Su([Hn.sign(oi(r,t),n,cp)]);if(!rl(r))throw new Error("BIP-322 here signs for Taproot and P2WPKH addresses only.");const s=Oe.sign(oi(r,t),n).toDERRawBytes();return Su([le(s,Uint8Array.of(1)),Oe.getPublicKey(n,!0)])}function Au(e,t,n){const r=Ds(e),s=typeof n=="string"?ek(n):null;if(!r||!s)return!1;try{if(nl(r)){const[o]=s;return s.length!==1||!(o.length===64||o.length===65&&o[64]===1)?!1:Hn.verify(o.slice(0,64),oi(r,t,o.length===65?1:0),r.program)}if(rl(r)){const[o,i]=s;return s.length!==2||i.length!==33||o.at(-1)!==1||!Xv(Yc(Ae(i)),r.program)?!1:Oe.verify(Oe.Signature.fromDER(o.slice(0,-1)),oi(r,t),i)}}catch{}return!1}const fp=e=>{const t=Ke(e);return Gc(le(Ke(`Ethereum Signed Message: +${t.length}`),t))},dp=e=>typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e)&&op(e.slice(2))===e;function tk(e,t){const n=Oe.sign(fp(e),t);return`0x${Ie(n.toCompactRawBytes())}${(27+n.recovery).toString(16)}`}function nk(e,t,n){if(!dp(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(fp(t));return ip(o.toRawBytes(!1))===e}catch{return!1}}const hp=(e,t)=>Ae(Ke(JSON.stringify([0,e,0,1,[],t])));function sl(e){try{const{prefix:t,words:n}=pr.decode(e,90),r=pr.fromWords(n);return t==="npub"&&r.length===32&&e===e.toLowerCase()?Ie(Uint8Array.from(r)):null}catch{return null}}const rk=(e,t)=>Ie(Hn.sign(hp(Ie(Hn.getPublicKey(t)),e),t,cp));function sk(e,t,n){const r=sl(e);try{return!!r&&typeof n=="string"&&/^[0-9a-f]{128}$/.test(n)&&Hn.verify(n,hp(r,t),r)}catch{return!1}}const ok={taproot:_u,segwit:_u,nostr:(e,t,n)=>rk(t,n),ethereum:(e,t,n)=>tk(t,n)},ik={taproot:Au,segwit:Au,nostr:sk,ethereum:nk};function pp(e){const t=Ds(e.taproot),n=Ds(e.segwit);return nl(t)?rl(n)?t.network!==n.network?"its Taproot and SegWit addresses must be on one network":sl(e.nostr)?dp(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 ak(e,t,n){const r=pp(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,ok[o](t[o],s,n[o])]))}}const gs=new Map;function ck(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(!gs.has(r)){gs.size>=1e3&&gs.clear();let s=pp(t);if(!s){const o=_i(e,t),i=It.find(a=>!ik[a](t[a],o,n[a]));i&&(s=`the ${i} key did not sign this keyring`)}gs.set(r,s)}return gs.get(r)}const Bu=e=>It.map(t=>`${t}:${t==="nostr"?sl(e[t]):t==="ethereum"?e[t].toLowerCase():Ie(Ds(e[t]).program)}`),ol="lineage/v0",lk=["white","green","black"],Tu=["sole","llc","series-llc","series","corp"],uk={sole:"sole proprietor",llc:"LLC","series-llc":"series LLC",series:"series",corp:"corporation"},Ou=/^[A-Z]{2}(-[A-Z0-9]{1,3})?$/,fk=/^[0-9a-f]{64}$/,rn=e=>e.kind==="agent"&&e.root!==e.id,wo="names are 1-40 lowercase letters, digits or hyphens (they become domains)",dk=/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/,ms=e=>typeof e=="string"&&dk.test(e),Ur=(e,t)=>typeof e=="string"?e.trim().slice(0,t):"";function Js(e){return String(e??"").toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/,"")}const $r=e=>e.events.filter(t=>t.protocol===ol);function Mt(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,l=h=>h.status==="active",f=h=>Er(r,h),u=h=>{if(h.keyring&&!h.keyring.retired)for(const w of Bu(h.keyring.keys))a.delete(w)},d=(h,w,m,x)=>{h.keyring&&!h.keyring.retired&&(u(h),h.keyring.retired={cause:w,by:m,beat:x})};for(const h of e){const w=h.status==="confirmed";if(w?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:w?h.height:null,pending:!w,meta:m,parent:h.parent??null,ok:!0,why:"",node:null,root:null,also:[]},y=x.parent?r.get(x.parent):null,$=x.beat??"cued",b=A=>{x.ok=!1,x.why=A},O=A=>y?l(y)?"":`the ${A} is ${y.status}`:`the ${A} is not in this lineage`;let C="",N=[];const I=(y==null?void 0:y.root)??null;switch(x.op){case"found":if(x.parent)b("a holding has no parent");else if(!ms(m.name))b(wo);else if(s.some(A=>l(A)&&A.name===m.name))b(`an active holding is already named ${m.name}`);else{const A=Iu(h,m.name,null,"holding");r.set(A.id,A),s.push(A),x.node=A.id}break;case"birth":{const A=m.kind==="agent"?"agent":"org";if(C=O("parent"))b(C);else if(rn(y))b("agents give birth only once they graduate");else if(!ms(m.name))b(wo);else if(f(y).some(P=>l(P)&&P.name===m.name))b(`${y.name} already has an active ${m.name}`);else{const P=Iu(h,m.name,y,A);P.index=y.children.filter(k=>r.get(k).kind===A).length,y.children.push(P.id),r.set(P.id,P),x.node=P.id}break}case"award":{const A=r.get(m.to);(C=O("issuer"))?b(C):rn(y)?b("agents award belts only once they graduate"):!A||A.id===y.id?b("the recipient must be another node in this lineage"):l(A)?!ms(m.skill)||!lk.includes(m.belt)?b("an award needs a skill name and a belt (white, green or black)"):(A.badges=A.badges.filter(P=>P.skill!==m.skill),A.badges.push({skill:m.skill,belt:m.belt,by:y.id,beat:$,id:h.id}),x.node=A.id):b(`the recipient is ${A.status}`);break}case"decide":(C=O("decider"))?b(C):Ur(m.title,140)?(y.decisions.push({title:Ur(m.title,140),why:Ur(m.why,400),beat:$,id:h.id}),x.node=y.id):b("a decision needs a title");break;case"make":(C=O("maker"))?b(C):ms(m.name)?y.made.some(A=>i.get(A).name===m.name)?b(`there is already a ${m.name} by ${y.name}`):(i.set(h.id,{id:h.id,name:m.name,note:Ur(m.note,280),maker:y.id,beat:$}),y.made.push(h.id),x.node=y.id):b(wo);break;case"graduate":{const A=r.get(m.of);if(C=O("parent"))b(C);else if(!A||A.parent!==y.id)b("only its parent can graduate a child");else if(!l(A))b(`the child is ${A.status}`);else if(A.edge==="adopted")b("already graduated");else if(A.joining)b(`${A.name} is joining ${r.get(A.joining.to).name}`);else{const P=A.root,k=v=>{v.root=A.id;for(const _ of f(v))_.root===P&&k(_)};A.edge="adopted",A.graduated=$,A.rooted=h.id,x.node=A.id,x.rekeys=!0,k(A),s.push(A);const S=v=>{d(v,"graduate",A.id,$);for(const _ of f(v))_.edge==="derived"&&S(_)};S(A)}break}case"close":if(!y)b(x.parent?"that node is not in this lineage":"a close spends the node it closes");else if(!l(y))b(`already ${y.status}`);else{const A=P=>{P.status="closed",P.closed=$,d(P,"close",y.id,$);for(const k of f(P))k.edge==="derived"&&l(k)&&(x.also.push(k.id),A(k))};A(y),x.node=y.id}break;case"charter":{const A=m.form==="series",P=A?r.get(m.of):y,k=y&&(y.kind==="holding"||y.kind==="agent");(C=O(A?"master":"node"))?b(C):Tu.includes(m.form)?!A&&m.of!==void 0&&m.of!==y.id?b("a node charters itself; only a series is chartered by its master"):A&&(!P||!gp(r,P,y))?b("a series must descend from its master"):A&&!l(P)?b(`the series is ${P.status}`):A&&P.kind!=="org"?b("only orgs become series"):A&&((p=y.charter)==null?void 0:p.form)!=="series-llc"?b(`${y.name} is not chartered as a series LLC`):A&&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"&&!A&&rn(y)?b("an agent graduates before it incorporates"):m.form!=="sole"&&!A&&!Ou.test(m.jurisdiction??"")||m.form==="sole"&&m.jurisdiction!==void 0&&!Ou.test(m.jurisdiction)?b("a jurisdiction is an ISO code such as US-WY"):m.provider!==void 0&&!ms(m.provider)?b(`a provider's name follows the name rule: ${wo}`):m.filing!==void 0&&!fk.test(m.filing)?b("a filing is the SHA-256 of the filed documents, in hex"):(P.charter={id:h.id,beat:$,form:m.form,jurisdiction:A?null:m.jurisdiction??null,legal:Ur(m.legal,120)||null,provider:m.provider??null,filing:m.filing??null,master:A?y.id:null},x.node=P.id):b(`a charter's form is ${Tu.join(", ")}`);break}case"keyring":{if(C=O("node"))b(C);else if(C=ck(y.id,m))b(C);else{const A=Object.fromEntries(It.map(S=>[S,m[S]])),P=Bu(A),k=P.findIndex(S=>a.has(S)&&a.get(S)!==y.id);if(k>=0)b(`its ${It[k]} key is already bound to ${r.get(a.get(P[k])).name}`);else{u(y),y.keyring={id:h.id,beat:$,keys:A,retired:null};for(const S of P)a.set(S,y.id);x.node=y.id}}break}case"join":case"adopt":{const A=x.op==="join",P=A?y:r.get(m.of),k=A?r.get(m.to)??null:y;if(C=O(A?"node":"parent"))b(C);else if(C=Zt(r,P,k))b(C);else{const S=`${k.id}>${P.id}`,v=A?c.get(S):((g=P.joining)==null?void 0:g.to)===k.id?P.joining:null;if(x.node=P.id,N=[P.root,k.root],!v&&A)P.joining={to:k.id,id:h.id,beat:$};else if(!v)c.set(S,{id:h.id});else{c.delete(S),P.joining=null;const _=P.root,U=L=>{L.root=k.root;for(const D of f(L))D.root===_&&U(D)};P.moves.push({from:P.parent,index:P.index,to:k.id,beat:$,join:A?h.id:v.id,adopt:A?v.id:h.id}),P.root===P.id&&s.splice(s.indexOf(P),1),P.kind==="holding"&&(P.kind="org"),P.index=k.children.filter(L=>r.get(L).kind===P.kind).length,P.parent=k.id,P.edge="derived",k.children.push(P.id),U(P);const K=L=>{d(L,"move",k.id,$);for(const D of f(L))D.edge==="derived"&&K(D)};K(P),x.rekeys=!0}}break}default:b("not a lineage/v0 op")}const R=x.node?r.get(x.node).root:null;x.root=I??R,x.roots=[...new Set([x.root,R,...N].filter(Boolean))],o.push(x)}return{nodes:r,roots:s,log:o,items:i,bound:a}}function Iu(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 gp(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 Er=(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||gp(e,n,t)?`${t.name} cannot join itself or anything below it`:n.id===t.parent?`${t.name} is already ${n.name}'s`:Er(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 $s(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 hk(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 p of o.children){const g=e.nodes.get(p),h=u[g.kind==="agent"?"agent":"org"];h.push([g,{parent:o.id,index:h.length}])}const d=[["agents",u.agent],["orgs",u.org]].filter(([,p])=>p.length);d.forEach(([p,g],h)=>{const w=h===d.length-1,m=a+(w?" ":"│ ");n.push({type:"group",label:p,guide:a+(w?"└─ ":"├─ ")}),g.forEach(([x,y],$)=>{const b=$===g.length-1;s(x,m+(b?"└─ ":"├─ "),m+(b?" ":"│ "),y)})})};return r&&s(r,"",""),n}function pk(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 es(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 mp(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 “${Ur(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)} · ${uk[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 An=Ie,gk=le,qa=bt,mk=vr,Bn="super-testnet-local-v0";class Rn{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=An(Hn.getPublicKey(t)),this.address=_s.p2tr.fromPubKey(this.pubkey,"regtest"),this.script=["OP_1",this.pubkey]}static create(){return new Rn(An(Oe.utils.randomPrivateKey()))}static load(t){if((t==null?void 0:t.network)!==Bn||(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 Rn(t.secret)}backup(){return{kind:"test-wallet",version:1,network:Bn,secret:this.secret}}sign(t,n,r=0){return ar.taproot.sign(this.secret,t,r,n?{extension:n}:{}).hex}}const bo=50*1e8,xo="0".repeat(64),Cu=e=>An(Ae(new TextEncoder().encode(JSON.stringify(e)))),Ir=(e,t)=>`${e}:${t}`,tt=e=>Ne.encode(e,!1).hex,he=(e,t)=>{if(!e)throw new Error(t)},Pu=/^5120[0-9a-f]{64}$/,vo=/^0014[0-9a-f]{40}$/,yp=64,xt=64,yk=e=>An(Yc(Ae(qa(e))));function wk(e,t){const[n,r]=e.vin[t].witness;return Oe.verify(n.slice(0,-2),ar.segwit.hash(e,t,{pubkey:r,sigflag:1}),r,{lowS:!0,format:"der"})}const ua=(e,...t)=>{const n=Ae(new TextEncoder().encode(e));return Ae(gk(n,n,...t))},bk=e=>e<253?Uint8Array.of(e):Uint8Array.of(253,e&255,e>>8);function xk(e,t){const[n,r,s]=e.vin[t].witness,o=qa(s),i=qa(r);if(o.length<33||(o.length-33)%32||i.length>65535||!/^20[0-9a-f]{64}ac/.test(r))return!1;const a=ua("TapLeaf",Uint8Array.of(o[0]&254),bk(i.length),i);let c=a;for(let u=33;u=Oe.CURVE.n)return!1;const f=Oe.ProjectivePoint.fromHex(`02${An(o.slice(1,33))}`).add(Oe.ProjectivePoint.BASE.multiply(l)).toAffine();return`5120${f.x.toString(16).padStart(64,"0")}`!==tt(e.vin[t].prevout.scriptPubKey)||Number(f.y&1n)!==(o[0]&1)?!1:Hn.verify(n,ar.taproot.hash(e,t,{extension:An(a)}),r.slice(2,66))}class Ai{constructor(t){if(this.blocks=[],this.mempool=[],this.utxos=new Map,this.transactions=new Map,this.imports=[],t){he(t.network===Bn&&t.version===1,"Unsupported local chain version/network."),he(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:Bn,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}){he(/^[0-9a-f]{64}$/.test(t)&&Number.isSafeInteger(n)&&n>=0&&Number.isSafeInteger(r)&&r>=330&&r<=bo&&(Pu.test(s)||vo.test(s)),"Invalid imported coin."),he(!this.utxos.has(Ir(t,n))&&!this.transactions.has(t)&&!this.imported(t,n),"That coin is already in this chain."),this.utxos.set(Ir(t,n),{txid:t,vout:n,value:r,scriptPubKey:s,height:0,ranges:zu(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=>tt(n.scriptPubKey)===tt(t))}satLocation(t){for(const n of this.utxos.values()){const r=xs(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 w,m,x;he(typeof t=="string"&&t.length<4e4&&/^(?:[a-f0-9]{2})+$/.test(t),"Invalid raw transaction.");const s=J.decode(t),o=J.util.getTxid(s);he(!this.transactions.has(o),"Duplicate transaction."),he(s.version===2&&s.locktime===0,"Unsupported transaction version or locktime.");const i=!r&&s.vin.some(y=>{var $;return(($=y.witness)==null?void 0:$.length)===3}),a=r?1:i?2:xt,c=r?yp:i?2:xt;he(s.vin.length>=1&&s.vin.length<=a&&s.vout.length>=1&&s.vout.length<=c,"Unsupported transaction shape.");let l=0;for(const y of s.vout){const $=Number(y.value);he(Number.isSafeInteger($)&&$>=330&&$<=bo,"Invalid output amount.");const b=tt(y.scriptPubKey);he(Pu.test(b)||vo.test(b),"Only Taproot and P2WPKH outputs are supported."),l+=$}let f,u=[];const d=s.vin.findIndex(y=>{var $;return(($=y.witness)==null?void 0:$.length)===3}),p=s.vin[d<0?0:d];if(r)he(p.txid===xo&&p.vout===4294967295&&l===bo,"Invalid local coinbase."),he(tt(p.scriptSig)===Ne.encode([new TextEncoder().encode(`${Bn}:${n}`)],!1).hex,"Wrong coinbase height."),he(!((w=p.witness)!=null&&w.length),"Unexpected coinbase witness.");else{u=s.vin.map($=>this.utxos.get(Ir($.txid,$.vout))),he(u.every(Boolean),"Input is missing or already spent."),he(new Set(s.vin.map($=>Ir($.txid,$.vout))).size===s.vin.length,"Duplicate input."),s.vin.forEach(($,b)=>{var C,N,I;he($.sequence==="ffffffff"&&tt($.scriptSig)==="","Unsupported input flags."),$.prevout={value:u[b].value,scriptPubKey:u[b].scriptPubKey};const O=tt(u[b].scriptPubKey);if(vo.test(O)){const[R,A]=$.witness??[];he(b!==d&&((C=$.witness)==null?void 0:C.length)===2,"Unsupported witness."),he(/^30[0-9a-f]{12,140}01$/.test(R)&&/^0[23][0-9a-f]{64}$/.test(A)&&yk(A)===O.slice(4),"P2WPKH spends need a SIGHASH_ALL signature by the key they pay.");return}he(((N=$.witness)==null?void 0:N.length)===1||b===d&&((I=$.witness)==null?void 0:I.length)===3,"Unsupported witness."),he(/^[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.")}),he(u.reduce(($,b)=>$+b.value,0)-l===W,"v0 requires a fixed 500 sat fee per transaction.");let y={};if(p.witness.length===3){const $=Kc(p.witness),b=d;if(he(Number(s.vout[b].value)===Ht,"Invalid reveal postage."),he(tt(s.vout[b].scriptPubKey)===`5120${$.pubkey}`,"Reveal must return to its signing wallet."),$.parent){const O=d===0?1:0,C=u[O];he((m=C==null?void 0:C.inscriptions)==null?void 0:m.some(N=>N.id===$.parent),"Referenced parent inscription must actually be spent."),he(s.vout.length===2&&Number(s.vout[O].value)===C.value&&tt(C.scriptPubKey)===`5120${$.pubkey}`&&tt(s.vout[O].scriptPubKey)===tt(C.scriptPubKey),"Parent must be owned and preserved in the same wallet.")}else s.vin.length===2&&(he(d===1&&((x=u[0].inscriptions)==null?void 0:x.length)&&$.pointer!==void 0,"Reinscription spend requires correct tag and owned sat."),he(Number(s.vout[0].value)===u[0].value&&tt(s.vout[0].scriptPubKey)===tt(u[0].scriptPubKey)&&tt(u[0].scriptPubKey)===`5120${$.pubkey}`,"Reinscription sat must be returned to owner."));y={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:Ht}}s.vin.forEach(($,b)=>{let O=!1;try{O=vo.test(tt(u[b].scriptPubKey))?wk(s,b):b===d?xk(s,b)||ar.taproot.verify(s,b,y):ar.taproot.verify(s,b,{})}catch{}he(O,"Invalid signature or Taproot commitment.")})}const g=Gu(s,u,n,r),h=u.flatMap(y=>y.inscriptions??[]);if(f){const y=BigInt(f.pointer??0),$=y{var O;return((O=b.inscription)==null?void 0:O.sat)===f.sat}).length,h.push(f)}return he(h.every(y=>g.some($=>xs($,y.sat)!==null)),"Local lab protects inscription sats from fee loss."),r||s.vin.forEach(y=>this.utxos.delete(Ir(y.txid,y.vout))),s.vout.forEach((y,$)=>{const b=h.filter(O=>xs(g[$],O.sat)!==null);this.utxos.set(Ir(o,$),{txid:o,vout:$,value:Number(y.value),scriptPubKey:y.scriptPubKey,height:n,ranges:g[$],inscriptions:b,...b.length?{inscription:b[0]}:{}})}),this.transactions.set(o,{txid:o,raw:t,height:n,coinbase:r,tx:s,...f?{inscription:f}:{}}),o}submitPackage(t){he(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;he(t.height===this.blocks.length+1&&t.previous===(((i=this.blocks.at(-1))==null?void 0:i.hash)??xo),"Invalid block ancestry."),he(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;he(Cu(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([we(bo,t)])}mineTo(t){var a;const n=new Ai({...this.snapshot(),mempool:[]}),r=this.blocks.length+1,s=J.create({vin:[{txid:xo,vout:4294967295,scriptSig:[new TextEncoder().encode(`${Bn}:${r}`)]}],vout:t}),o={height:r,previous:((a=this.blocks.at(-1))==null?void 0:a.hash)??xo,time:Date.now(),raws:[J.encode(s).hex,...this.mempool]},i={...o,hash:Cu(o)};return n.acceptBlock(i),Object.assign(this,n),i}}const wp="lineage-claim",za=330,ii=e=>Ne.encode(e,!1).hex,Uu=e=>({txid:e.txid,vout:e.vout,value:e.value,script:ii(e.scriptPubKey)}),fa=/^[0-9a-f]{64}$/,vk=/^5120[0-9a-f]{64}$/;function Sr(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 bp(e){return J.create({vin:[Je(e.holder.txid,e.holder.vout,e.holder.value,e.holder.script),Je(e.payer.txid,e.payer.vout,e.payer.value,e.payer.script)],vout:[we(e.holder.value,["OP_1",e.to]),we(e.payer.value-W,["OP_1",e.to])]})}function kk(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=Sr(e,t);if(!s)throw new Error("That inscription is not in an unspent output.");if(ii(s.scriptPubKey)===ii(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+za});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:wp,version:1,inscription:t,carried:s.inscriptions.map(c=>c.id),holder:Uu(s),payer:Uu(o),to:n.pubkey,at:r},a=bp(i);return i.txid=J.util.getTxid(a),i.sig=n.sign(a,void 0,1),i}function $k(e,t,n){const r=Sk(t);if((n==null?void 0:n.kind)!=="test-wallet")throw new Error("Countersigning needs a local test wallet.");if(ii(n.script)!==r.holder.script)throw new Error("Only the current holder can countersign.");if(Ek(e,r)!=="open")throw new Error("This claim is stale: an input it spends was already spent.");const s=bp(r);return s.vin[1].witness=[r.sig],s.vin[0].witness=[n.sign(s,void 0,0)],e.submitPackage([J.encode(s).hex]),J.util.getTxid(s)}function Ek(e,t){return e.utxos.has(`${t.holder.txid}:${t.holder.vout}`)&&e.utxos.has(`${t.payer.txid}:${t.payer.vout}`)?"open":"stale"}function Sk(e){const t=n=>n&&fa.test(n.txid)&&Number.isSafeInteger(n.vout)&&n.vout>=0&&Number.isSafeInteger(n.value)&&n.value>=za&&vk.test(n.script);if((e==null?void 0:e.kind)!==wp||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=Nu);const i=new Uint8Array(o*s),a=Ln.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let f=0;fAk(e,_k(e,t,n),r,s);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const En=BigInt(0),De=BigInt(1),ha=BigInt(2),Tk=BigInt(8);function Ok(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 Ik(e,t={}){const n=Bh("edwards",e,t,t.FpFnLE),{Fp:r,Fn:s}=n;let o=n.CURVE;const{h:i}=o;as(t,{},{uvRatio:"function"});const a=ha<r.create(w),l=t.uvRatio||((w,m)=>{try{return{isValid:!0,value:r.sqrt(r.div(w,m))}}catch{return{isValid:!1,value:En}}});if(!Ok(r,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function f(w,m,x=!1){const y=x?De:En;return js("coordinate "+w,m,y,a),m}function u(w){if(!(w instanceof g))throw new Error("ExtendedPoint expected")}const d=Yo((w,m)=>{const{X:x,Y:y,Z:$}=w,b=w.is0();m==null&&(m=b?Tk:r.inv($));const O=c(x*m),C=c(y*m),N=r.mul($,m);if(b)return{x:En,y:De};if(N!==De)throw new Error("invZ was invalid");return{x:O,y:C}}),p=Yo(w=>{const{a:m,d:x}=o;if(w.is0())throw new Error("bad point: ZERO");const{X:y,Y:$,Z:b,T:O}=w,C=c(y*y),N=c($*$),I=c(b*b),R=c(I*I),A=c(C*m),P=c(I*c(A+N)),k=c(R+c(x*c(C*N)));if(P!==k)throw new Error("bad point: equation left != right (1)");const S=c(y*$),v=c(b*O);if(S!==v)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(m,x,y,$){this.X=f("x",m),this.Y=f("y",x),this.Z=f("z",y,!0),this.T=f("t",$),Object.freeze(this)}static CURVE(){return o}static fromAffine(m){if(m instanceof g)throw new Error("extended point not allowed");const{x,y}=m||{};return f("x",x),f("y",y),new g(x,y,De,c(x*y))}static fromBytes(m,x=!1){const y=r.BYTES,{a:$,d:b}=o;m=iu(_t(m,y,"point")),fr(x,"zip215");const O=iu(m),C=m[y-1];O[y-1]=C&-129;const N=dr(O),I=x?a:r.ORDER;js("point.y",N,En,I);const R=c(N*N),A=c(R-De),P=c(b*R-$);let{isValid:k,value:S}=l(A,P);if(!k)throw new Error("bad point: invalid y coordinate");const v=(S&De)===De,_=(C&128)!==0;if(!x&&S===En&&_)throw new Error("bad point: x=0 and x_0=1");return _!==v&&(S=c(-S)),g.fromAffine({x:S,y:N})}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(ha),this}assertValidity(){p(this)}equals(m){u(m);const{X:x,Y:y,Z:$}=this,{X:b,Y:O,Z:C}=m,N=c(x*C),I=c(b*$),R=c(y*C),A=c(O*$);return N===I&&R===A}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:y,Z:$}=this,b=c(x*x),O=c(y*y),C=c(ha*c($*$)),N=c(m*b),I=x+y,R=c(c(I*I)-b-O),A=N+O,P=A-C,k=N-O,S=c(R*P),v=c(A*k),_=c(R*k),U=c(P*A);return new g(S,v,U,_)}add(m){u(m);const{a:x,d:y}=o,{X:$,Y:b,Z:O,T:C}=this,{X:N,Y:I,Z:R,T:A}=m,P=c($*N),k=c(b*I),S=c(C*y*A),v=c(O*R),_=c(($+b)*(N+I)-P-k),U=v-S,K=v+S,L=c(k-x*P),D=c(_*U),q=c(K*L),G=c(_*L),ue=c(U*K);return new g(D,q,ue,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:y}=h.cached(this,m,$=>tr(g,$));return tr(g,[x,y])[0]}multiplyUnsafe(m,x=g.ZERO){if(!s.isValid(m))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return m===En?g.ZERO:this.is0()||m===De?this:h.unsafe(this,m,y=>tr(g,y),x)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return h.unsafe(this,o.n).is0()}toAffine(m){return d(this,m)}clearCofactor(){return i===De?this:this.multiplyUnsafe(i)}toBytes(){const{x:m,y:x}=this.toAffine(),y=r.toBytes(x);return y[y.length-1]|=m&De?128:0,y}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 tr(g,m)}static msm(m,x){return Ah(g,s,m,x)}_setWindowSize(m){this.precompute(m)}toRawBytes(){return this.toBytes()}}g.BASE=new g(o.Gx,o.Gy,De,c(o.Gx*o.Gy)),g.ZERO=new g(En,De,De,En),g.Fp=r,g.Fn=s;const h=new _h(g,s.BITS);return g.BASE.precompute(8),g}function Ck(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');as(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||xr,c=n.adjustScalarBytes||(I=>I),l=n.domain||((I,R,A)=>{if(fr(A,"phflag"),R.length||A)throw new Error("Contexts/pre-hash are not supported");return I});function f(I){return i.create(dr(I))}function u(I){const R=y.secretKey;I=be("private key",I,R);const A=be("hashed private key",t(I),2*R),P=c(A.slice(0,R)),k=A.slice(R,2*R),S=f(P);return{head:P,prefix:k,scalar:S}}function d(I){const{head:R,prefix:A,scalar:P}=u(I),k=s.multiply(P),S=k.toBytes();return{head:R,prefix:A,scalar:P,point:k,pointBytes:S}}function p(I){return d(I).pointBytes}function g(I=Uint8Array.of(),...R){const A=le(...R);return f(t(l(A,be("context",I),!!r)))}function h(I,R,A={}){I=be("message",I),r&&(I=r(I));const{prefix:P,scalar:k,pointBytes:S}=d(R),v=g(A.context,P,I),_=s.multiply(v).toBytes(),U=g(A.context,_,S,I),K=i.create(v+U*k);if(!i.isValid(K))throw new Error("sign failed: invalid s");const L=le(_,i.toBytes(K));return _t(L,y.signature,"result")}const w={zip215:!0};function m(I,R,A,P=w){const{context:k,zip215:S}=P,v=y.signature;I=be("signature",I,v),R=be("message",R),A=be("publicKey",A,y.publicKey),S!==void 0&&fr(S,"zip215"),r&&(R=r(R));const _=v/2,U=I.subarray(0,_),K=dr(I.subarray(_,v));let L,D,q;try{L=e.fromBytes(A,S),D=e.fromBytes(U,S),q=s.multiplyUnsafe(K)}catch{return!1}if(!S&&L.isSmallOrder())return!1;const G=g(k,D.toBytes(),L.toBytes(),R);return D.add(L.multiplyUnsafe(G)).subtract(q).clearCofactor().is0()}const x=o.BYTES,y={secretKey:x,publicKey:x,signature:2*x,seed:x};function $(I=a(y.seed)){return _t(I,y.seed,"seed")}function b(I){const R=N.randomSecretKey(I);return{secretKey:R,publicKey:p(R)}}function O(I){return Ws(I)&&I.length===i.BYTES}function C(I,R){try{return!!e.fromBytes(I,R)}catch{return!1}}const N={getExtendedPublicKey:d,randomSecretKey:$,isValidSecretKey:O,isValidPublicKey:C,toMontgomery(I){const{y:R}=e.fromBytes(I),A=y.publicKey,P=A===32;if(!P&&A!==57)throw new Error("only defined for 25519 and 448");const k=P?o.div(De+R,De-R):o.div(R-De,R+De);return o.toBytes(k)},toMontgomerySecret(I){const R=y.secretKey;_t(I,R);const A=t(I.subarray(0,R));return c(A).subarray(0,R)},randomPrivateKey:$,precompute(I=8,R=e.BASE){return R.precompute(I,!1)}};return Object.freeze({keygen:b,getPublicKey:p,sign:h,verify:m,utils:N,Point:e,lengths:y})}function Pk(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=kr(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 Uk(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function Nk(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:s}=Pk(e),o=Ik(t,n),i=Ck(o,r,s);return Uk(e,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ys=BigInt(0),Cr=BigInt(1),ko=BigInt(2);function Lk(e){return as(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function Hk(e){const t=Lk(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||xr,l=a?255:448,f=a?32:56,u=BigInt(a?9:5),d=BigInt(a?121665:39081),p=a?ko**BigInt(254):ko**BigInt(447),g=a?BigInt(8)*ko**BigInt(251)-Cr:BigInt(4)*ko**BigInt(445)-Cr,h=p+g+Cr,w=k=>Te(k,n),m=x(u);function x(k){return Vc(w(k),f)}function y(k){const S=be("u coordinate",k,f);return a&&(S[31]&=127),w(dr(S))}function $(k){return dr(s(be("scalar",k,f)))}function b(k,S){const v=N(y(S),$(k));if(v===ys)throw new Error("invalid private or public key received");return x(v)}function O(k){return b(k,m)}function C(k,S,v){const _=w(k*(S-v));return S=w(S-_),v=w(v+_),{x_2:S,x_3:v}}function N(k,S){js("u",k,ys,n),js("scalar",S,p,h);const v=S,_=k;let U=Cr,K=ys,L=k,D=Cr,q=ys;for(let ue=BigInt(l-1);ue>=ys;ue--){const ce=v>>ue&Cr;q^=ce,{x_2:U,x_3:L}=C(q,U,L),{x_2:K,x_3:D}=C(q,K,D),q=ce;const ne=U+K,pe=w(ne*ne),ge=U-K,Le=w(ge*ge),de=pe-Le,_e=L+D,Wt=L-D,ht=w(Wt*ne),ze=w(_e*ge),Gt=ht+ze,fs=ht-ze;L=w(Gt*Gt),D=w(_*w(fs*fs)),U=w(pe*Le),K=w(de*(pe+w(d*de)))}({x_2:U,x_3:L}=C(q,U,L)),{x_2:K,x_3:D}=C(q,K,D);const G=o(K);return w(U*G)}const I={secretKey:f,publicKey:f,seed:f},R=(k=c(f))=>(Ze(k,I.seed),k);function A(k){const S=R(k);return{secretKey:S,publicKey:O(S)}}return{keygen:A,getSharedSecret:(k,S)=>b(k,S),getPublicKey:k=>O(k),scalarMult:b,scalarMultBase:O,utils:{randomSecretKey:R,randomPrivateKey:R},GuBytes:m.slice(),lengths:I}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Rk=BigInt(1),Lu=BigInt(2),jk=BigInt(3),Kk=BigInt(5),Dk=BigInt(8),il=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),xp={p:il,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Dk,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function vp(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),o=il,a=e*e%o*e%o,c=Ce(a,Lu,o)*a%o,l=Ce(c,Rk,o)*e%o,f=Ce(l,Kk,o)*l%o,u=Ce(f,t,o)*f%o,d=Ce(u,n,o)*u%o,p=Ce(d,r,o)*d%o,g=Ce(p,s,o)*p%o,h=Ce(g,s,o)*p%o,w=Ce(h,t,o)*f%o;return{pow_p_5_8:Ce(w,Lu,o)*e%o,b2:a}}function kp(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Hu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Mk(e,t){const n=il,r=Te(t*t*t,n),s=Te(r*r*t,n),o=vp(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*Hu,n),f=a===e,u=a===Te(-e,n),d=a===Te(-e*Hu,n);return f&&(i=c),(u||d)&&(i=l),D2(i,n)&&(i=Te(-i,n)),{isValid:f||u,value:i}}const $p=kr(xp.p,{isLE:!0}),Zk={...xp,Fp:$p,hash:Rs,adjustScalarBytes:kp,uvRatio:Mk},Bi=Nk(Zk),Ep=(()=>{const e=$p.ORDER;return Hk({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:n,b2:r}=vp(t);return Te(Ce(n,jk,e)*r,e)},adjustScalarBytes:kp})})(),Vk=Ke("lineage/v0"),jt=(e,t)=>Bk(Ae,e,Vk,Ke(t),32),Ti=e=>{const t=Uint8Array.from(e);return t[0]&=248,t[31]&=127,t[31]|=64,t},Sp=e=>{const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t},vt=e=>le(Sp(e.length),e),al=e=>le(vt(Ke("ssh-ed25519")),vt(e)),Fa=(e,t)=>`ssh-ed25519 ${yt.encode(al(e))}${t?` ${t}`:""}`,Wa=e=>`SHA256:${yt.encode(Ae(al(e))).replace(/=+$/,"")}`;function qk(e){const t=bt(e),n=r=>Bi.getPublicKey(jt(t,r));return{ssh:n("ssh"),git:n("git"),dkim:n("dkim"),wg:Ep.getPublicKey(Ti(jt(t,"wg")))}}function zk(e){const t=n=>Bi.getPublicKey(jt(e,n));return{"ssh-ca":t("node/ssh-ca"),mtls:t("node/mtls"),noise:Ep.getPublicKey(Ti(jt(e,"node/noise")))}}function Fk(e,t,n,r){return[["ssh",Wa(e.ssh),Fa(e.ssh,t)],["git",Wa(e.git),`${t} namespaces="git" ${Fa(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 Wk(e,t){return[["ssh-ca",Wa(e["ssh-ca"]),Fa(e["ssh-ca"],`lineage-ca@${t}`)],["mtls",yt.encode(e.mtls),null],["noise",`mkey:${Ie(e.noise)}`,null]]}const Gk=bt("302e020100300506032b657004220420");function _p(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)),Sp(1),vt(al(t)),vt(s));return`-----BEGIN OPENSSH PRIVATE KEY----- +${yt.encode(o).match(/.{1,70}/g).join(` +`)} +-----END OPENSSH PRIVATE KEY----- +`}const Yk=(e,t)=>`-----BEGIN ${e}----- +${yt.encode(t).match(/.{1,64}/g).join(` +`)} +-----END ${e}----- +`;function Xk(e,t){const n=bt(e),r=s=>{const o=jt(n,s);return _p(o,Bi.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(Ti(jt(n,"wg")))}`]]}function Jk(e,t){const n=jt(e,"node/ssh-ca");return[["ssh-ca","OpenSSH private key",_p(n,Bi.getPublicKey(n),`lineage-ca@${t}`)],["mtls","Private key (PKCS#8 PEM)",Yk("PRIVATE KEY",le(Gk,jt(e,"node/mtls")))],["noise","noise_private.key",`privkey:${Ie(Ti(jt(e,"node/noise")))}`]]}const Qk=["bip86","tapkey","wallet"],cl=()=>({scheme:"bip86",roots:{},adopted:{}}),e$=e=>bi.getPubKey(e)[0];function Ap(e,t,n){return e.scheme==="wallet"?Va(t,n):bi.getSecKey(e.scheme==="tapkey"?Si(t,n):Va(t,n))[0]}const Bp=(e,t)=>e.scheme==="tapkey"?rt.nostr(t):rt.wallet(t),t$=(e,t)=>new Rn(Ap(e,t,0)),Se=e=>Ne.encode(e,!1).hex;function an(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=an(e,t,s);return i&&{...i,account:n.index+1}}const o=an(e,t,s);return o&&{mnemonic:Fv(o.mnemonic,n.index),account:0,origin:o.origin,steps:[...o.steps,`${n.index}'`]}}const pa=new Map;function $e(e,t,n){const r=an(e,t,n);if(!r)return null;const s=`${e.scheme}|${r.mnemonic}|${r.account}`;if(!pa.has(s)){const{npub:l,pubkey:f}=Gv(r.mnemonic,r.account);pa.set(s,{wallet:new Rn(Ap(e,r.mnemonic,r.account)),npub:l,pubkey:f})}const{wallet:o,npub:i,pubkey:a}=pa.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} · ${Bp(e,r.account)}`}}function ll(e,t,n){const r=an(e,t,n);if(!r)return null;const s=$e(e,t,n),o=sp(r.mnemonic,r.account);return{taproot:{address:s.wallet.address,path:Bp(e,r.account)},segwit:{address:_s.p2wpkh.fromPubKey(o,"regtest"),path:rt.segwit(r.account)},tapkey:{address:_s.p2tr.fromPubKey(e$(s.pubkey),"regtest"),path:rt.nostr(r.account)},npub:{address:s.npub,path:rt.nostr(r.account)},ethereum:{address:Wv(r.mnemonic,r.account),path:rt.ethereum(r.account)}}}function n$(e,t,n){const r=an(e,t,n);if(!r)return null;const s=$e(e,t,n),o=ll(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:tl(i,a),nostr:Si(i,a),ethereum:ap(i,a)}}}function ul(e,t,n){const r=Sr(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 qn(e,t){const n=e.nodes.get(t),r=[n];for(const s of Er(e.nodes,n))s.status==="active"&&s.edge==="derived"&&r.push(...qn(e,s.id));return r}function Ga(e,t){const n=[];for(let r=t;r;r=e.nodes.get(r.parent))n.push(r.name);return n.join(".")}function r$(e,t,n){const r=an(e,t,n);if(!r)return null;if(n.kind!=="agent")return Wk(zk(el(r.mnemonic)),Ga(t,n));const s=Ga(t,t.nodes.get(n.parent));return Fk(qk(Si(r.mnemonic,r.account)),`${n.name}@${s}`,n.name,s)}const s$=Yh(Ae),ws=(e,t=239)=>s$.encode(le(Uint8Array.of(t),bt(e),Uint8Array.of(1))),o$=e=>pr.encode("nsec",pr.toWords(bt(e))),i$="0123456789()[],'/*abcdefgh@:$%{}IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ",a$=[0xf5dee51989n,0xa9fdca3312n,0x1bab10e32dn,0x3706b1677an,0x644d626ffdn];function ga(e){const t=(i,a)=>{const c=i>>35n;return i=(i&0x7ffffffffn)<<5n^BigInt(a),a$.forEach((l,f)=>{c>>BigInt(f)&1n&&(i^=l)}),i};let n=1n,r=0,s=0;for(const i of e){const a=i$.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 c$(e,t,n){const r=an(e,t,n);if(!r)return null;const s=Si(r.mnemonic,r.account),o=Va(r.mnemonic,r.account),i={bip86:`tr(${ws(o)})`,tapkey:`tr(${ws(s)})`,wallet:`rawtr(${ws(o)})`}[e.scheme],a=n.kind==="agent",c=Ga(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",o$(s)],["taproot","descriptor",ga(i)],["segwit","descriptor",ga(`wpkh(${ws(tl(r.mnemonic,r.account))})`)],["tapkey","descriptor",ga(`tr(${ws(s)})`)],["ethereum","private key",`0x${ap(r.mnemonic,r.account)}`]],leaves:a?Xk(s,`${n.name}@${c}`):Jk(el(r.mnemonic),c)}}const jr=1e8,Fe=50*jr,ye=330,Tp=e=>(e/jr).toFixed(8).replace(/\.?0+$/,""),Y=e=>`${Tp(e)} tBTC`;function fl(e){if(e<1e6)return Y(e);const t=Math.round(e/1e6)*1e6;return`${t===e?"":"≈"}${Y(t)}`}function Oi(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)*jr+Number((t[2]??"").padEnd(8,"0"))}class dl{constructor(t,n,r){this.secret=t,this.pubkey=n,this.path=r,this.address=_s.p2wpkh.fromPubKey(n,"regtest"),this.script=_s.toScriptPubKey(this.address)}sign(t,n){return[ar.segwit.sign(this.secret,t,n,{pubkey:this.pubkey}).hex,this.pubkey]}}const ma=new Map;function xe(e,t,n){const r=an(e,t,n);if(!r)return null;const s=`${r.mnemonic}|${r.account}`;return ma.has(s)||ma.set(s,new dl(tl(r.mnemonic,r.account),sp(r.mnemonic,r.account),rt.segwit(r.account))),ma.get(s)}function l$(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 Kr=(e,t)=>{var n,r;return((r=(n=e.mining)==null?void 0:n.rigs)==null?void 0:r[t])??1};function Op(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=Sr(e.chain,n.id),s=$e(e.keys,t,n);return!!r&&!!s&&Se(r.scriptPubKey)!==Se(s.wallet.script)}function hl(e,t){var n;return((n=e.mining)==null?void 0:n.rule)==="none"?[]:t.roots.filter(r=>r.status==="active"&&Kr(e,r.id)>0&&xe(e.keys,t,r)&&!Op(e,t,r)).slice(0,yp)}function Ip(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&&!Op(e,t,c)?l$(e.keys,t,n):null;return l?[{script:l,value:Fe}]:null}const r=hl(e,t),s=r.reduce((c,l)=>c+Kr(e,l.id),0);let o=Fe;return r.length?r.map((c,l)=>{const f=l===r.length-1?o:Math.floor(Fe*Kr(e,c.id)/s);return o-=f,{script:xe(e.keys,t,c).script,value:f}}):null}function gr(e,t,n=xt){const r=t+W,s=l=>l===r||l-r>=ye&&l-r<=Fe,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 gl(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<=Fe?r:r-Fe>=ye?Fe:r-ye;o>=ye&&r-o<=Fe&&(n=Math.max(n,o))}return n}function ml(e,t,n,r=xt,s="send"){const o=pl(t),i=n+W,a=gl(t,r),c=`${s[0].toUpperCase()}${s.slice(1)}`;if(od.value).sort((d,p)=>p-d),f=l.slice(0,r).map((d,p)=>l.slice(0,p+1).reduce((g,h)=>g+h,0)),u=Math.min(...[...l,...l.flatMap((d,p)=>l.slice(p+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}`))),Cp=(e,t)=>e.chain.coins(t.script).filter(n=>{var r;return!((r=n.inscriptions)!=null&&r.length)}),Pp=(e,t,n=xt)=>!!gr(e,t,n),Up=(e,t,n)=>Pp(Cp(e,t),n);function wl(e,t,n,r,s="This node",o="send"){const i=Cp(e,t),a=yl(e),c=gr(i.filter(d=>!a.has(`${d.txid}:${d.vout}`)),r)??gr(i,r);if(!c)throw new Error(ml(s,i,r,xt,o));const l=pl(c)-r-W,f=J.create({vin:c.map(d=>Je(d.txid,d.vout,d.value,d.scriptPubKey)),vout:[we(r,n),...l?[we(l,t.script)]:[]]});c.forEach((d,p)=>{f.vin[p].witness=t instanceof dl?t.sign(f,p):[t.sign(f,void 0,p)]});const u=J.encode(f).hex;return e.chain.submitPackage([u]),J.util.getTxid(u)}function Np(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)||sFe)throw new Error("Send at most 50 test BTC at a time: no output on this chain is bigger than one block reward.");return wl(e,a,c.script,s,o.name)}function u$(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>=ye){const l=J.create({vin:o.map(f=>Je(f.txid,f.vout,f.value,f.scriptPubKey)),vout:[we(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([J.encode(l).hex]),i++}o=[]};for(const c of s)(o.length===xt||o.reduce((l,f)=>l+f.value,0)+c.value-W>Fe)&&a(),o.push(c);return a(),i}const Lp=(e,t)=>[t,...t.log.flatMap((n,r)=>n.ok&&n.rekeys?[Mt(e.slice(0,r),{pending:!0})]:[])];function Hp(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 f$=(e,t,n)=>Hp(Lp(t,n),(r,s)=>{const o=xe(e,r,s);return o&&Se(o.script)}),ya=new Map,d$=(e,t,n)=>Hp(Lp(t,n),(r,s)=>{const o=an(e,r,s),i=o&&`${e.scheme}|${o.mnemonic}|${o.account}`;return i&&!ya.has(i)&&ya.set(i,Se($e(e,r,s).wallet.script)),i?ya.get(i):null}),bl=(e,t)=>e.coins(t.script).filter(n=>{var r;return!((r=n.inscriptions)!=null&&r.length)}).reduce((n,r)=>n+r.value,0),ju=new WeakMap,wa=new WeakMap;function Ku(e,t){let n=ju.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})}ju.set(t,n)}return n}function Ii(e,t,n,r){const s=Ku(e,n).get(r);if(s)return s;wa.has(n)||wa.set(n,n.log.flatMap((o,i)=>o.ok&&o.rekeys?[{i,state:null}]:[]));for(const o of wa.get(n)){o.state??(o.state=Mt(t.slice(0,o.i),{pending:!0}));const i=Ku(e,o.state).get(r);if(i)return i}return null}function h$(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 p=f.vout.map(b=>({script:Se(b.scriptPubKey),node:o(b.scriptPubKey),value:Number(b.value)}));if(d){p.forEach((b,O)=>{b.node&&s.push({kind:"mine",key:`${l}:${O}`,txid:l,beat:u,from:null,to:b.node,amount:b.value,fee:0,change:0})});continue}const g=f.vin.map(b=>{var C,N;const O=((C=e.transactions.get(b.txid))==null?void 0:C.tx.vout[b.vout])??((N=e.imported)==null?void 0:N.call(e,b.txid,b.vout));return O?{node:o(O.scriptPubKey),tank:n.get(Se(O.scriptPubKey))??null,value:Number(O.value)}:null}),h=r.get(l);if(h!=null&&h.prep)continue;if(h!=null&&h.ask){s.push({kind:"deal",key:l,txid:l,beat:u,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:l,txid:l,beat:u,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(C=>C.node),O=g[0].tank&&g.every(C=>C.tank===g[0].tank)?g[0].tank:null;b.length&&O?s.push({kind:"pay",key:l,txid:l,beat:u,from:O,to:b[0].node,amount:b[0].value,fee:i(g)-i(p),change:0}):b.length&&s.push({kind:"fund",key:l,txid:l,beat:u,from:null,to:b[0].node,amount:b[0].value,fee:i(g)-i(p),change:i(p.filter(C=>!C.node))});continue}const w=(c=g[0])==null?void 0:c.node;if(!w||!g.every(b=>(b==null?void 0:b.node)===w))continue;const m=p.filter(b=>b.node!==w),x=p.filter(b=>b.node===w),y=i(g)-i(p),$={key:l,txid:l,beat:u,from:w,fee:y};m.length&&m.every(b=>n.get(b.script)===w)?s.push({...$,kind:"gas",to:w,amount:i(m),change:i(x)}):m.length?s.push({...$,kind:"pay",to:m[0].node,amount:m[0].value,change:i(x)}):s.push({...$,kind:"move",to:w,amount:i(x),change:0})}return s}function Ya(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 Xa="lineage-offer",Ja="lineage-ask",Et=600,Ms=xt-1,ai=/^[0-9a-f]{64}$/,jn=/^[0-9a-f]{64}i0$/,ci=/^5120[0-9a-f]{64}$/,Qa=/^0014[0-9a-f]{40}$/,p$=/^[0-9a-f]{128}83$/,g$="0".repeat(64),ec=e=>({txid:e.txid,vout:e.vout,value:e.value,script:Se(e.scriptPubKey)}),tc=(e,t)=>!e.utxos.has(`${t.txid}:${t.vout}`),Zs=e=>{const t=$r(new Mn(e.chain));return{events:t,state:Mt(t,{pending:!0})}},xl=e=>`${e[0].toUpperCase()}${e.slice(1)}`,Es=e=>e.reduce((t,n)=>t+n.value,0),m$=e=>Je(e.txid,e.vout,e.value,e.scriptPubKey);function Ci(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 Rp(e){return J.create({vin:[...e.holders,...e.payers].map(t=>Je(t.txid,t.vout,t.value,t.script)),vout:[we(Es(e.holders),e.to),...e.price?[we(e.price,e.pay)]:[],...e.change?[we(e.change,e.back)]:[]]})}function Kn(e,t,n,r){const s=Sr(e.chain,r),o=s&&Ii(e.keys,t,n,Se(s.scriptPubKey));return o?{coin:s,node:n.nodes.get(o.node),wallet:o.wallet}:null}function Dn(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=Kn(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 mr(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=qn(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(Sr(e.chain,f.id));for(const f of n.items.keys()){const u=Kn(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=Pi(e,n,r.id))==null?void 0:l.layout)??a}}function vl(e,t,n,r,s=mr(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=Pi(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=Kn(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,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`${u.name} holds ${p.name}, which it bought, and adopts it first`}const l=s.coins.reduce((u,d)=>u+d.inscriptions.length,0);return l>Ms?`${r.name}'s tree holds ${l} inscriptions, and one deal carries ${Ms} at most`:""}function jp(e,t,n,r){var a;const s=n.nodes.get(r),o=(s==null?void 0:s.status)==="active"?Kn(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=Kn(e,t,n,i.id))==null?void 0:a.node.id)===o.node.id?null:o.node}function Kp(e,t,n,r,s=Date.now()){const{events:o,state:i}=Zs(e),a=Dn(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&&rFe)throw new Error("Offer at most 50 test BTC: no output on this chain is bigger than one block reward.");const l=mr(e,o,i,a),f=vl(e,o,i,a,l)||(a.node?Zt(i.nodes,a.node,c):"");if(f)throw new Error(`${xl(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 b of[c,u])if(b&&b.status!=="active")throw new Error(`${b.name} is ${b.status}.`);const d=xe(e.keys,i,c),p=Ci(e,i,u),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&&_o(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),w=yl(e),m=xt-l.coins.length,x=gr(h.filter(b=>!w.has(`${b.txid}:${b.vout}`)),r,m)??gr(h,r,m);if(!x)throw new Error(ml(c.name,h,r,m,"offer"));const y={kind:Xa,version:1,item:t,buyer:c.id,seller:(u==null?void 0:u.id)??null,price:r,holders:l.coins.map(b=>({...ec(b),ids:b.inscriptions.map(O=>O.id)})),layout:l.layout,payers:x.map(ec),to:Se(g.wallet.script),pay:p,back:Se(d.script),change:Es(x)-r-W,at:s},$=Rp(y);return y.txid=J.util.getTxid($),y.witnesses=x.map((b,O)=>d.sign($,y.holders.length+O)),(e.offers??(e.offers=[])).push(y),y}function kl(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 w,m;return((w=t.nodes.get(h))==null?void 0:w.name)??((m=t.items.get(h))==null?void 0:m.name)??null},a=h=>h?Se(h.script):"",c=n.holders.find(h=>tc(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(w=>i(w));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=>tc(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 w=h&&t.nodes.get(h);if(h&&(w==null?void 0:w.status)!=="active")return`${(w==null?void 0:w.name)??"a node"} is ${(w==null?void 0:w.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&&Ci(e,t,f)!==n.pay)return f?`${f.name} has new keys since`:"the lab wallet has changed since";if(s){const h=r??$r(new Mn(e.chain)),w=mr(e,h,t,Dn(e,h,t,n.item)).coins,m=new Set(n.holders.map(x=>`${x.txid}:${x.vout}`));if(w.length!==m.size||w.some(x=>!m.has(`${x.txid}:${x.vout}`)))return`${o}'s tree has changed since`}return""}const _o=(e,t,n,r=null)=>e.chain.transactions.has(n.txid)?"done":kl(e,t,n,r)?"stale":"open";function y$(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=kl(e,o,r,s);if(i)throw new Error(`This offer is stale: ${i}.`);const a=Dn(e,s,o,r.item);if(!a||(((f=a.seller)==null?void 0:f.id)??null)!==r.seller||vl(e,s,o,a))throw new Error("Only the holder can accept.");n==null||n(o,a);const c=Rp(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=[Ii(e.keys,s,o,u.script).wallet.sign(c,void 0,d)]}),e.chain.submitPackage([J.encode(c).hex]),r}function w$(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 _r=e=>`${e.holder.txid}:${e.holder.vout}`,b$=e=>J.create({vin:[Je(g$,0,Et,e.pay),Je(e.holder.txid,e.holder.vout,e.holder.value,e.holder.script)],vout:[we(Et+e.holder.value,e.holder.script),we(e.price,e.pay)]});function x$(e,t,n,r=Date.now(),s=null){var w;let{events:o,state:i}=Zs(e),a=Dn(e,o,i,t);if(!a)throw new Error("Pick an item, an org or a holding to sell.");if(!Number.isSafeInteger(n)||nFe-W)throw new Error(`Ask at most ${Y(Fe-W)}: the buyer funds the price and its fee in one output.`);const c=mr(e,o,i,a),l=vl(e,o,i,a,c);if(l)throw new Error(`${xl(l)}.`);const f=a.seller,u=Ci(e,i,f);if(f&&f.status!=="active")throw new Error(`${f.name} is ${f.status}.`);if(!u||!((w=a.holder.wallet)!=null&&w.secret))throw new Error("A holding that predates lab keys cannot trade.");const d=Pi(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=Dn(e,o,i,t);const[p,...g]=mr(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:Ja,version:1,lot:t,seller:(f==null?void 0:f.id)??null,price:n,holder:{...ec(p),ids:p.inscriptions.map(m=>m.id)},layout:c.layout,pay:u,at:r,taken:null};return h.sig=ar.taproot.sign(a.holder.wallet.secret,b$(h),1,{sigflag:131}).hex,(e.asks??(e.asks=[])).push(h),h}function $l(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 tc(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"}`:Ci(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 El=(e,t,n)=>n.taken&&e.chain.transactions.has(n.taken.txid)?"done":$l(e,t,n)?"stale":"open",Pi=(e,t,n)=>(e.asks??[]).find(r=>r.lot===n&&El(e,t,r)==="open")??null;function v$(e,t,n,r=Date.now()){const s=(e.asks??[]).find(C=>_r(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=$l(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(`${xl(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),p=yl(e),g=Et+s.price+W,h=gr(d.filter(C=>!p.has(`${C.txid}:${C.vout}`)),g)??gr(d,g);if(!h)throw Es(d){x.vin[N].witness=f.sign(x,N)});const y=J.encode(x).hex,$=J.util.getTxid(y),b=J.create({vin:[Je($,0,Et,m),Je(s.holder.txid,s.holder.vout,s.holder.value,s.holder.script),Je($,1,s.price+W,m)],vout:[we(Et+s.holder.value,u.wallet.script),we(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 O=J.encode(b).hex;return e.chain.submitPackage([y,O]),s.taken={txid:J.util.getTxid(O),prep:$,buyer:a.id,at:r},s}function Du(e,t){const n=(e.asks??[]).find(r=>_r(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 k$(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 nc=(e,t)=>e&&ai.test(e.txid)&&Number.isSafeInteger(e.vout)&&e.vout>=0&&Number.isSafeInteger(e.value)&&e.value>=ye&&e.value<=Fe&&t.test(e.script),Dp=e=>e===void 0||Array.isArray(e)&&e.length<=Ms&&e.every(t=>jn.test(t)),Mp=e=>e===void 0||Array.isArray(e)&&e.length<=Ms&&e.every(t=>Array.isArray(t)&&t.length===2&&jn.test(t[0])&&jn.test(t[1])),Zp=(e,t)=>e===null?ci.test(t):jn.test(e)&&Qa.test(t);function $$(e){const t=r=>Number.isSafeInteger(r)&&(r===0||r>=ye&&r<=Fe),n=Array.isArray(e==null?void 0:e.holders)?e.holders:e!=null&&e.holder?[e.holder]:[];if((e==null?void 0:e.kind)!==Xa||e.version!==1||!jn.test(e.item)||!jn.test(e.buyer)||!Zp(e.seller,e.pay)||e.buyer===e.seller||!t(e.price)||!t(e.change)||!n.length||n.length>Ms||!n.every(r=>nc(r,ci)&&Dp(r.ids))||!Array.isArray(e.payers)||!e.payers.length||n.length+e.payers.length>xt||!e.payers.every(r=>nc(r,Qa))||!ci.test(e.to)||!Qa.test(e.back)||!Mp(e.layout)||!ai.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:Xa,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 E$(e){const t=e==null?void 0:e.taken;if((e==null?void 0:e.kind)!==Ja||e.version!==1||!jn.test(e.lot)||!Zp(e.seller,e.pay)||!Number.isSafeInteger(e.price)||e.priceFe-W||!nc(e.holder,ci)||!Dp(e.holder.ids)||!Mp(e.layout)||typeof e.sig!="string"||!p$.test(e.sig)||!Number.isSafeInteger(e.at)||!(t===null||t&&ai.test(t.txid)&&ai.test(t.prep)&&jn.test(t.buyer)&&Number.isSafeInteger(t.at)))throw new Error("Invalid ask.");return{kind:Ja,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 Ui="orgchain:lab:v1",S$=["each",10,30,60,"manual"];function Qs(e={tempo:"each",nextAt:null}){const{tempo:t,nextAt:n}=e??{},r=typeof t=="number";if(!S$.includes(t)||!(n===null||r&&Number.isSafeInteger(n)&&n>0))throw new Error("Invalid clock.");return{tempo:t,nextAt:n}}function Vp(e){const t=cl();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]=rp(s,24)}if(t.scheme=(e==null?void 0:e.scheme)??(Object.keys(t.roots).length?"wallet":"bip86"),!Qk.includes(t.scheme))throw new Error("Invalid lab keys.");return t}const _$=["split","last","none"];function eo(e){const t=(e==null?void 0:e.rule)??"split",n={};if(!_$.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 qp(e=[]){if(!Array.isArray(e)||e.length>1e3)throw new Error("Invalid offers.");const t=e.map($$);if(new Set(t.map(n=>n.txid)).size!==t.length)throw new Error("Invalid offers.");return t}function zp(e=[]){if(!Array.isArray(e)||e.length>1e3)throw new Error("Invalid asks.");const t=e.map(E$);if(new Set(t.map(_r)).size!==t.length)throw new Error("Invalid asks.");return t}const to=()=>({wallet:null,chain:new Ai,clock:Qs(),keys:cl(),mining:eo(),offers:[],asks:[]});function Fp(e){if(!e)return to();const t=JSON.parse(e);if((t==null?void 0:t.kind)!=="orgchain-lab"||t.network!==Bn||t.version!==1)throw new Error("That is not an Orgchain v1 lab.");return{wallet:t.wallet?Rn.load(t.wallet):null,chain:new Ai(t.chain),clock:Qs(t.clock),keys:Vp(t.keys),mining:eo(t.mining),offers:qp(t.offers),asks:zp(t.asks)}}const Wp=e=>{var t;return JSON.stringify({kind:"orgchain-lab",network:Bn,version:1,wallet:((t=e.wallet)==null?void 0:t.backup())??null,chain:e.chain.snapshot(),clock:Qs(e.clock),keys:Vp(e.keys),mining:eo(e.mining),offers:qp(e.offers),asks:zp(e.asks)})};function A$(e,t,n){var r;e.mining=eo({...e.mining,rigs:{...(r=e.mining)==null?void 0:r.rigs,[t]:n}})}function B$(e,t){e.mining=eo({...e.mining,rule:t})}const Sl=()=>Fp(localStorage.getItem(Ui));function T$(e){try{localStorage.setItem(Ui,Wp(e))}catch{throw new Error("Browser storage is full or unavailable, so nothing was saved. Save a backup, then reset.")}}async function O$(e,{locks:t=(s=>(s=globalThis.navigator)==null?void 0:s.locks)(),read:n=Sl,save:r=T$}={}){if(!t)throw new Error("Orgchain needs Web Locks: open it over HTTPS or on localhost.");return t.request(Ui,async()=>{const o=n(),i=await e(o);return i!==!1&&r(o),{lab:o,result:i}})}function it(e,t=null){e.wallet||(e.wallet=Rn.create());const n=t!=null&&t.length?e.chain.mineTo(t.map(r=>we(r.value,r.script))):e.chain.mine(e.wallet.script);return e.clock=Qs({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 I$(e,t,n=Date.now(),r=null){e.clock=Qs({tempo:t,nextAt:null}),t==="each"&&e.chain.mempool.length?it(e,r):Ft(e,n)}function C$(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):t`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 U$(e,t={}){if(!Object.hasOwn(Mu,e))throw new Error("Unknown verb.");const n={op:e};for(const s of Mu[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 Gp(e,t){const n=Re(e),r=n.nodes.get(t),s=r&&n$(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 ak(t,s.keys,s.secrets)}function _l(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(qn(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=>Mt($r(new Mn(e.chain)),{pending:!0}),Ni=e=>{const t=$r(new Mn(e.chain));return{events:t,state:Mt(t,{pending:!0})}};function li(e,t,n,r){const s=U$(t,r),o=$r(new Mn(e.chain)),i={id:"check",status:"pending",height:null,metadata:s,parent:n??null,protocol:ol},{ok:a,why:c}=Mt([...o,i],{pending:!0}).log.at(-1);if(!a)throw new Error(`${c[0].toUpperCase()}${c.slice(1)}.`);return s}const rc=Ht+2*W+330,Yp=1e5,Li=1e4,tn=(e,t=0)=>Ht+2*W+(e==="birth"||e==="join"?1:e==="graduate"?Math.max(0,t-1):0)*W+330,N$=(e,t=0)=>tn(e,t)-330,cn=(e,t,n)=>e.chain.coins(t.script).find(r=>{var s;return!((s=r.inscriptions)!=null&&s.length)&&r.value>=n}),ts=e=>Je(e.txid,e.vout,e.value,e.scriptPubKey),Hi=(e,t)=>(t.forEach((n,r)=>{e.vin[r].witness=[n.sign(e,void 0,r)]}),J.encode(e).hex);function no(e){e.keys??(e.keys=cl()),e.wallet||(e.wallet=Rn.create()),cn(e,e.wallet,Yp+W+330)||it(e)}function Xp(e,t,n=rc,r=Yp){if(t===e.wallet||cn(e,t,n))return;const s=cn(e,e.wallet,r+W+330),o=J.create({vin:[ts(s)],vout:[we(r,t.script),we(s.value-r-W,e.wallet.script)]});e.chain.submitPackage([Hi(o,[e.wallet])])}function or(e,t,n,r,s){if(r===e.wallet||cn(e,r,s))return;const o=n&&xe(e.keys,t,n);if(!o)return Xp(e,r,s);wl(e,o,r.script,Math.max(Li,s),n.name)}function Al(e,t,n,r,s){if(r===e.wallet||cn(e,r,s))return!0;const o=n&&xe(e.keys,t,n);return!o||Up(e,o,Math.max(Li,s))}function Bl(e,t,n,r,s={}){var f,u;const o=r?t.nodes.get(r):null,i=o&&((f=ul(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)?qn(t,a.id).length:0;if(!Al(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&&!Pp(e.chain.coins(l.script).filter(d=>d.value-W>=ye).map(d=>({value:d.value-W})),Li)?`${a.name} needs test BTC of its own to claim its new root. Send it some first`:""}function Zu(e,t,n,r,s=n){const o=Sr(e.chain,t),i=cn(e,s,W+330),a=J.create({vin:[ts(o),ts(i)],vout:[we(o.value,r.script),we(i.value-W,s.script)]});e.chain.submitPackage([Hi(a,[n,s])])}function ui(e,t,n,r,s){return new c2(e.chain,t).inscribe(P$[n](s,r),r??null,s,{metaprotocol:ol})}const zn=(e,t)=>{var r;const n=Re(e);return Ip(e,n,((r=n.nodes.get(t))==null?void 0:r.root)??null)},Ri=(e,t)=>Ip(e,Re(e),t);function Tl(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(J.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 ns(e,t,n){var s;const r=ul(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 Jp(e,t,n,r){if(t==="found"){const f=$u(),u=t$(e.keys,f);Xp(e,u,rc,rc);const d=ui(e,u,t,null,r);return e.keys.roots[d]=f,d}const s=Re(e),o=ns(e,s,n),i=s.nodes.get(n),a=t==="graduate"?s.nodes.get(r.of):null,c=a&&$e(e.keys,s,a)?qn(s,a.id).map(f=>[f.id,ns(e,s,f.id)]):[];or(e,s,i,o,tn(t,c.length));const l=ui(e,o,t,n,r);if(t==="birth"){const f=Re(e),u=$e(e.keys,f,f.nodes.get(l));u&&Zu(e,l,o,u.wallet)}if(c.length){e.keys.adopted[l]=$u();const f=Re(e);for(const[u,d]of c){const p=$e(e.keys,f,f.nodes.get(u)).wallet;if(u$(e,xe(e.keys,s,s.nodes.get(u)),xe(e.keys,f,f.nodes.get(u))),u!==a.id){Zu(e,u,d,p,o);continue}or(e,f,f.nodes.get(u),p,W+330),$k(e.chain,kk(e.chain,u,p),d)}}return l}function L$(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=_l(Re(e),t,n??null,r??{});if(i)throw new Error(`${i}.`);const a=li(e,t,n,t==="keyring"?Gp(e,n):r),c=Bl(e,Re(e),t,n??null,a);if(c)throw new Error(`${c}.`);no(e);const l=Jp(e,t,n??null,a);return e.clock.tempo==="each"?it(e,zn(e,n??l)):Ft(e,s),l}function H$(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=Np(e,Re(e),t,n,r);return e.clock.tempo==="each"?it(e,zn(e,t)):Ft(e,s),i}function R$(e,t,n,r,s=Date.now()){const o=Vt(e,Re(e),"offer",n);if(o)throw new Error(`${o}.`);return Kp(e,t,n,r,s)}function j$(e,t,n=Date.now()){const r=y$(e,t,(s,o)=>{o.node&&Qp(e,s,o)});return e.clock.tempo==="each"?it(e,zn(e,r.seller??r.item)):Ft(e,n),r}const K$=(e,t)=>w$(e,t);function Vt(e,t,n,r,s={},o=$r(new Mn(e.chain))){const i=l=>{const f=Pi(e,t,l.id),u=f?null:jp(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=[],c=t.nodes.get(n==="graduate"?s.of:n==="close"?r:null);for(let l=r?t.nodes.get(r):null;l;l=l.edge==="derived"?t.nodes.get(l.parent):null)a.unshift(l);for(const l of[...a,...c?qn(t,c.id):[]]){const f=i(l);if(f)return f}return""}function Qp(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,...Er(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&&Ru(e,l,r),f&&Ru(e,f,r)}}function D$(e,t,n){const{events:r,state:s}=Ni(e),o=Dn(e,r,s,t),{coins:i}=mr(e,r,s,o);if(i.length<2)return;const a=$e(e.keys,s,o.node).wallet,c=cn(e,n,W+ye);if(!c)throw new Error(`There is no test BTC for the fee that bundles ${o.name}'s tree.`);const l=i.map(u=>Ii(e.keys,r,s,Se(u.scriptPubKey)).wallet),f=J.create({vin:[...i,c].map(ts),vout:[we(i.reduce((u,d)=>u+d.value,0),a.script),we(c.value-W,n.script)]});e.chain.submitPackage([Hi(f,[...l,n])])}function e0(e,t,n,r,s,o,i){const a=new Set(qn(t,s.id).map(g=>g.id)),c=new Map(o),l=g=>{const h=t.nodes.get(a.has(g)?g:c.get(g));return $e(e.keys,t,h&&a.has(h.id)?h:s).wallet.script},f=n.inscriptions.map(g=>({id:g.id,offset:xs(n.ranges,g.sat)})).sort((g,h)=>g.offset-h.offset),u=f.map((g,h)=>{var w;return[(((w=f[h+1])==null?void 0:w.offset)??n.value)-(h?g.offset:0),l(g.id)]});if(u.some(([g])=>gwe(g,h)),we(d.value-W,i.script)]});e.chain.submitPackage([Hi(p,[r,i])])}function t0(e,t,n,r=[]){const{events:s,state:o}=Ni(e),i=o.nodes.get(t),a=o.nodes.get(n),c=Kn(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=ns(e,o,a.id),f=c.wallet,u=li(e,"adopt",a.id,{of:i.id});if(!Al(e,o,a,l,tn("adopt")+tn("join")))throw new Error(`${a.name} has no test BTC for gas.`);or(e,o,a,l,tn("adopt")),ui(e,l,"adopt",a.id,u);const d=li(e,"join",i.id,{to:a.id});or(e,o,a,f,tn("join")),ui(e,f,"join",i.id,d);const p=Re(e);or(e,p,p.nodes.get(a.id),f,W+ye),e0(e,p,Sr(e.chain,i.id),f,p.nodes.get(i.id),r,f)}function M$(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=ns(e,t,s.id),l=tn("adopt")+tn("join"),f=n.price+Et+2*W+(cn(e,c,l)?0:Li+W),u=e.chain.balance(i.script);return u{if(!p.node)return;const h=p.seller?ns(e,d,p.seller.id):e.wallet,w=g.coins.length>1;if(w&&p.seller&&!Al(e,d,p.seller,h,W+ye))throw new Error(`${p.seller.name} has no test BTC for the fee that bundles ${p.name}'s tree.`);Qp(e,d,p),w&&(p.seller&&or(e,Re(e),p.seller,h,W+ye),D$(e,p.id,h))});return e.chain.mempool.length>c&&(e.clock.tempo==="each"?it(e,zn(e,l.seller??l.lot)):Ft(e,r)),l}function Z$(e,t,n=Date.now()){var l;const r=(e.asks??[]).find(f=>_r(f)===t);if(!r||r.taken||!(((l=e.chain.utxos.get(t))==null?void 0:l.inscriptions.length)>1))return Du(e,t);r.seller||no(e);const{events:s,state:o}=Ni(e),i=e.chain.utxos.get(t),a=r.seller?o.nodes.get(r.seller):null,c=a?ns(e,o,a.id):e.wallet;return a&&or(e,o,a,c,W+ye),e0(e,o,i,Ii(e.keys,s,o,Se(i.scriptPubKey)).wallet,o.nodes.get(r.lot),r.layout??[],c),Du(e,t),e.clock.tempo==="each"?it(e,zn(e,r.seller??r.lot)):Ft(e,n),r}function V$(e,t,n,r=Date.now()){const s=Re(e),o=(e.asks??[]).find(a=>_r(a)===t),i=Vt(e,s,"take",n)||(o&&!o.taken?M$(e,s,o,n):"");if(i)throw new Error(`${i}.`);return v$(e,t,n,r),s.nodes.has(o.lot)&&t0(e,o.lot,n,o.layout??[]),e.clock.tempo==="each"?it(e,zn(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]);t0(e,t,n,((i=o.at(-1))==null?void 0:i[1])??[]),e.clock.tempo==="each"?it(e,zn(e,n)):Ft(e,r)}function z$(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)||nFe)throw new Error("Fund at most 50 test BTC at a time: no output on this chain is bigger than one block reward.");no(e),Up(e,e.wallet,n)||it(e);const c=wl(e,e.wallet,a.script,n,"The lab wallet","fund");return e.clock.tempo==="each"?it(e,zn(e,t)):Ft(e,r),c}const sc="yolopreneur",F$=[[["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 W$(e){no(e),e.chain.mempool.length&&it(e);const t={},n={};for(const r of F$){for(const[s,o,i]of r){if(s==="send"){Np(e,Re(e),t[o],t[i.to],i.amount*jr);continue}if(s==="offer"){Kp(e,n[i.item],t[o],i.price*jr);continue}if(s==="sell"){n0(e,t[i.lot]??n[i.lot],i.price*jr);continue}const a=s==="keyring"?Gp(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=Jp(e,s,c,li(e,s,c,a));(s==="found"||s==="birth")&&(t[i.name]=l),s==="make"&&(n[i.name]=l)}it(e,Ri(e,t[sc]))}return t[sc]}const H=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 On=(e,t)=>`${e} ${t}${e===1?"":"s"}`,mt=e=>e==="cued"?"cued":`beat ${e}`,G$=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}),Vu=e=>JSON.stringify(e,(t,n)=>typeof n=="bigint"?String(n):n,2),T={holding:null,node:null,event:null,tx:null,beat:null,verb:"birth",busy:!1,replay:null,closing:null,reveal:null};let Z=to(),fi=new Mn(Z.chain),Me=[],j=Mt([]),Ee=j,qe={owner:new Map,ledger:[],now:new Map,view:new Map},At=new Map;const lt=()=>Z.chain.blocks.length,oc=()=>Me.filter(e=>e.status==="pending").length,ic=e=>qe.ledger.filter(t=>t.beat===null&&t.kind===e).length,Ao=[["pay","cued send"],["deal","cued deal"],["fund","cued deposit"]],Y$=()=>oc()+Ao.reduce((e,[t])=>e+ic(t),0),Ue=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"},Bo=()=>Z.offers??[],Ol=()=>Z.asks??[];let ft=new Map,dt=new Map,ut=new Map,ac=new Map;const X$=e=>{var t,n;return((t=ft.get(e))==null?void 0:t.layout)??((n=[...Bo().filter(r=>r.item===e&&Z.chain.transactions.has(r.txid)).map(r=>[r.at,r.layout]),...Ol().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])??[]},r0=e=>e?ke(e):"its owner, the lab wallet",To=e=>qe.view.get(e)??0,s0=e=>qe.now.get(e)??0,V=(e,t=j)=>e?t.nodes.get(e)??null:null,J$=e=>{var t;return!!e&&(e.root===T.holding||((t=V(e.parent))==null?void 0:t.root)===T.holding||e.moves.some(n=>{var r;return((r=V(n.from))==null?void 0:r.root)===T.holding}))},Il=e=>Object.assign(T,{event:null,tx:null,closing:null,reveal:null},e),Ar=e=>{Il(e),ji()};function fe(e,t=!1){const n=H("say");n.textContent=e,n.classList.toggle("bad",t)}function o0(){try{Z=Sl()}catch(e){Z=to(),fe(`This browser's saved lab could not be read (${e.message}) Load a backup, or reset to start over.`,!0)}Cl()}function Cl(){var t,n,r;fi=new Mn(Z.chain),Me=$r(fi),j=Mt(Me,{pending:!0}),T.beat!==null&&T.beat>=lt()&&(T.beat=null),V(T.holding)&&V(T.holding).root!==T.holding&&(T.holding=V(T.holding).root),V(T.holding)||(T.holding=((t=j.roots.filter(s=>s.kind==="holding").at(-1)??j.roots.at(-1))==null?void 0:t.id)??null),J$(V(T.node))||(T.node=T.holding),T.event&&!j.log.some(s=>s.id===T.event)&&(T.event=null),Ee=T.beat===null?j:Mt(Me,{upTo:T.beat});const e=f$(Z.keys,Me,j);ac=k$(Z),qe={owner:e,ledger:h$(Z.chain,e,d$(Z.keys,Me,j),ac),now:Ya(Z.chain,e)},At=new Map([...j.items.keys()].map(s=>{var o;return[s,((o=Kn(Z,Me,j,s))==null?void 0:o.node.id)??null]})),ft=new Map(Ol().filter(s=>El(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=jp(Z,Me,j,s.id))==null?void 0:o.id]}).filter(([,s])=>s)),ut=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&&ut.set(i.id,o)}for(const s of new Set(ut.values()))for(const[o,i]of X$(s))ut.has(o)&&At.set(o,i);qe.view=T.beat===null?qe.now:Ya(Z.chain,e,T.beat),T.tx&&!qe.ledger.some(s=>s.key===T.tx)&&(T.tx=null),ji()}function di(e){T.beat=e>=lt()?null:Math.max(0,e),Ee=T.beat===null?j:Mt(Me,{upTo:T.beat}),qe.view=T.beat===null?qe.now:Ya(Z.chain,qe.owner,T.beat),ji()}async function et(e,t){if(T.busy)return!1;T.busy=!0,document.body.classList.add("busy");try{return Z=(await O$(e,t)).lab,!0}catch(n){return fe((n==null?void 0:n.message)||String(n),!0),!1}finally{T.busy=!1,document.body.classList.remove("busy"),Cl()}}async function qt(e,t,n,r){let s=null;if(!await et(i=>{s=L$(i,e,t,n)}))return!1;const o=fi.events.find(i=>i.id===s);return fe(r(s,(o==null?void 0:o.status)==="confirmed"?`at beat ${o.height}`:"cued for the next beat")),ji(),!0}async function i0(e){const t=[oc(),...Ao.map(([a])=>ic(a))],n=lt();if(!await et(e)||lt()===n)return;const r=[oc(),...Ao.map(([a])=>ic(a))],s=["cued act",...Ao.map(([,a])=>a)],o=t.map((a,c)=>[a-r[c],s[c]]).filter(([a])=>a>0).map(([a,c])=>On(a,c)),i=Q$(qe.ledger.filter(a=>a.kind==="mine"&&a.beat===lt()));fe(`Beat ${lt()}: ${o.length?`${o.join(" and ")} landed, and ${i}`:i}.`)}function Q$(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=>fl(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 eE(){var t;if(((t=Z.mining)==null?void 0:t.rule)==="last")return"the holding that acts";const e=hl(Z,j);return e.length?e.length===1?e[0].name:`${e.length} holdings, split by hashrate`:"the lab wallet"}function ji(){a0(),rE(),sE(),us(),b0(),Ul()}function a0(){const e=Y$(),{tempo:t}=Z.clock;for(const r of document.querySelectorAll("[data-tempo]"))r.setAttribute("aria-pressed",String(String(t)===r.dataset.tempo));H("clock-beat").textContent=String(lt()),H("clock-cued").textContent=e?`${e} cued · ${tE()}`:"nothing cued";const n=eE();H("clock-pays").textContent=`beats pay ${n}`,H("beat-now").title=`Beat now: ${e?"land what is cued, and ":""}pay ${n} 50 test BTC`}function tE(){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 nE={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 rE(){var a,c;const e=((a=Z.mining)==null?void 0:a.rule)??"split",t=e==="split",n=t?hl(Z,j):[],r=n.reduce((l,f)=>l+Kr(Z,f.id),0);H("holdings-list").replaceChildren(...j.roots.map(l=>{var m;const f=pk(j,l.id),u=l.id===T.holding,d=l.status==="active",p=n.some(x=>x.id===l.id)?Kr(Z,l.id)/r:0,g=[...j.nodes.values()].reduce((x,y)=>x+(y.root===l.id?s0(y.id):0),0),w=[l.graduated!==null&&`from ${((m=V(l.parent))==null?void 0:m.name)??"?"}${l.graduated==="cued"?", cued":` at beat ${l.graduated}`}`||mt(l.born),On(f.orgs,"org"),On(f.agents,"agent"),On(f.belts,"belt"),g>0&&fl(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${u?" on":""}${d?"":" gone"}`,"aria-pressed":String(u),onclick:()=>Ar({holding:l.id,node:l.id})},E("span",{class:"hn",text:l.name})," ",E("span",{class:"hm",text:w.join(" · ")})),t&&d&&xe(Z.keys,j,l)&&hE(l,Kr(Z,l.id)))}));for(const l of document.querySelectorAll("[data-rule]"))l.setAttribute("aria-pressed",String(e===l.dataset.rule));H("mining-note").textContent=nE[e];const s=j.roots.filter(l=>l.status==="active"&&xe(Z.keys,j,l)&&!ft.has(l.id)&&!dt.has(l.id)),o=H("fund-to"),i=o.value;H("f-fund").hidden=e!=="none"||!s.length||T.beat!==null,o.replaceChildren(...s.map(l=>E("option",{value:l.id,text:l.name}))),o.value=s.some(l=>l.id===i)?i:s.some(l=>l.id===T.holding)?T.holding:((c=s[0])==null?void 0:c.id)??"",H("fund-has").textContent=Y(Z.wallet?bl(Z.chain,Z.wallet):0),H("holdings-empty").hidden=j.roots.length>0,H("holdings-sub").textContent=j.roots.length?String(j.roots.length):"",H("sample").disabled=j.roots.some(l=>l.name===sc&&l.status==="active")}function sE(){var r;const e=H("tree-rows"),t=V(T.holding);if(H("tree-sub").textContent=t?`${t.name} · ${T.beat===null?"now":`beat ${T.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(...hk(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})):oE(s))),n&&((r=e.querySelector(`[data-id="${n}"]`))==null||r.focus())}function oE({node:e,guide:t,path:n,away:r,moved:s}){const o=e.id===T.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:()=>Ar({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)??"?"}`}):iE(e))))}function iE(e){var n;return[e.kind==="agent"&&E("span",{class:"mk",text:"agent"}),T.beat===null&&ft.has(e.id)&&E("span",{class:"mk ok",title:`${Y(ft.get(e.id).price)}, asked by ${r0(ft.get(e.id).seller)}`,text:"for sale"}),T.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=$s(Ee,e))!=null&&n.ok?"":" lapsed"}`,title:Pl(e),text:aE[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(c0),To(e.id)>0&&E("span",{class:"mk sats",title:`${Y(To(e.id))} at its SegWit address`,text:fl(To(e.id))})].filter(Boolean).flatMap((r,s)=>s?[" ",r]:[r])}const c0=e=>E("span",{class:`belt ${e.belt}`,title:`${e.skill}: ${e.belt} belt`},e.skill,E("span",{class:"sr",text:` (${e.belt} belt)`})),aE={sole:"sole",llc:"llc","series-llc":"series llc",series:"series",corp:"corp"},cE={sole:"Sole proprietor",llc:"LLC","series-llc":"Series LLC",series:"Series",corp:"Corporation"},lE={sole:"a sole proprietor",llc:"an LLC","series-llc":"a series LLC",corp:"a corporation"};function Pl(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)??"?"}`:cE[n.form],s,n.legal,n.provider&&`via ${n.provider}`,`since ${mt(n.beat)}`].filter(Boolean).join(" · ")}function Ki(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 uE(e){var r;const t=e.kind==="org"&&Ki(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=V(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 l0(e){return uE(e).map(([t,n,r])=>{const s=t==="series"?Ki(e):e,o=Bl(Z,j,"charter",s.id);return{form:t,label:n,hint:o?`${o}.`:r,off:!!o}})}const fE=e=>{var n;const t=l0(e);return t.some(r=>!r.off)?"":((n=t[0])==null?void 0:n.hint.replace(/\.$/,""))??"No legal form fits"},hi=()=>{var e;return((e=document.querySelector("#charter-forms input:checked"))==null?void 0:e.value)??null};function dE(e){var i;const t=H("charter-forms"),n=l0(e),r=n.map(a=>`${a.form}=${a.label}=${a.off}`).join("|");if(t.dataset.sig!==r){const a=hi(),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(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===l,disabled:f.off}),` ${f.label} `,E("span",{text:f.hint}))))}const s=hi()==="series",o=$s(j,e);H("charter-where").hidden=s,H("charter-now").textContent=e.charter?`Now: ${Pl(e,j)}${o.ok?"":`, lapsed: ${o.why}`}.`:"It has no legal form yet."}const u0=(e,t)=>{for(let n=V(e.parent);n;n=V(n.parent))if(n.id===t.id)return!0;return!1},f0=e=>[...j.nodes.values()].filter(t=>t.id!==e.id&&t.status==="active").map(t=>[t,(t.root===e.root?0:4)+(u0(t,e)?0:2)+(t.kind==="agent"?0:1)]).sort((t,n)=>t[1]-n[1]).map(([t])=>t),rs=e=>Er(j.nodes,e).reduce((t,n)=>n.edge==="derived"&&n.status==="active"?t+1+rs(n):t,0);function hE(e,t){const n=async r=>{await et(s=>A$(s,e.id,r))&&fe(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 d0=e=>[...j.nodes.values()].filter(t=>t.id!==e.id&&t.status==="active").map(t=>[t,(t.root===e.root?0:4)+(u0(t,e)?0:2)+(t.kind==="agent"?0:1)]).sort((t,n)=>t[1]-n[1]).map(([t])=>t);function pE(e){const t=xe(Z.keys,j,e);return t?gl(Z.chain.coins(t.script))!ut.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"&&!ut.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 cc=e=>rs(e)?`, with ${rs(e)} below it`:"",gE=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)}`}${cc(e)}`)+(ft.has(e.id)?` · asks ${Y(ft.get(e.id).price)}`:"");function mE(e){const t=xe(Z.keys,j,e);return t?p0(e).length?Z.chain.coins(t.script).some(n=>n.value>=W+ye||n.value===W)?"":h0(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 g0=e=>[...[...j.items.values()].filter(t=>At.get(t.id)===e.id&&!ut.has(t.id)),...Er(j.nodes,e).filter(t=>t.kind==="org"&&t.edge==="derived"&&!dt.has(t.id)&&!ut.has(t.id)&&!Zt(j.nodes,t)),...e.root===e.id&&e.kind!=="agent"&&!dt.has(e.id)&&!Zt(j.nodes,e)?[e]:[]],m0=e=>g0(e).filter(t=>!ft.has(t.id));function yE(e){return xe(Z.keys,j,e)?m0(e).length?"":g0(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 wE(e){const t=H("offer-item").value,n=ft.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?rs(r):0,a=r?i?`${r.name}'s tree, ${On(i+1,"node")} and the items they hold,`:`${r.name}'s inscription and its items`:"the item";H("offer-ask").hidden=!n,H("offer-go").classList.toggle("primary",!n),n&&(H("offer-ask-line").textContent=`${n.seller?ke(n.seller):`${r.name}'s owner`} asks ${Y(n.price)} for ${Ue(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`:""}.`,H("offer-take").textContent=`Take it for ${Y(n.price)}`),H("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(H("sell-lot").value),n=(t==null?void 0:t.id)===e.id,r=t?rs(t):0,s=y0(t);H("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.`}const y0=e=>e?mr(Z,Me,j,Dn(Z,Me,j,e.id)).coins.reduce((t,n)=>t+n.inscriptions.length,0):1;function w0(e,t=j){const n=ll(Z.keys,t,e);return n&&{taproot:n.taproot.address,segwit:n.segwit.address,nostr:n.npub.address,ethereum:n.ethereum.address}}function xE(e){const t=w0(e),n=e.keyring;if(!t)return"This holding predates lab keys, so it has no keys to list";const r=_l(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 vE(e){const t=V(e.parent),n=e.status==="closed"?`${e.name} is closed`:"",r=n?"":Vt(Z,j,"act",e.id,{},Me),s=(o,i=e.id,a={})=>Bl(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":f0(e).length?s("award"):"There is nobody else to award yet"),charter:n||r||fE(e),decide:n||r||s("decide"),make:n||r||s("make"),keyring:n||r||xE(e)||s("keyring"),send:n||r||pE(e),offer:n||r||mE(e),sell:n||r||yE(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},Me)||_l(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 us(){const e=V(T.node),t=T.beat!==null;if(H("act-none").hidden=!!e,H("act-past").hidden=!e||!t,H("act-on").hidden=!e||t,H("act-sub").textContent=(e==null?void 0:e.name)??"",H("past-beat").textContent=String(T.beat??""),!e||t)return;const n=vE(e),r=V(e.parent);for(const h of document.querySelectorAll("[data-verb]"))h.setAttribute("aria-pressed",String(h.dataset.verb===T.verb)),h.classList.toggle("off",!!n[h.dataset.verb]);for(const h of document.querySelectorAll("form[data-form]"))h.hidden=h.dataset.form!==T.verb||!!n[T.verb];H("act-why").textContent=n[T.verb]?`${n[T.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(w=>`${w.value}=${w.textContent}`).join("|"),o=[[H("award-to"),f0(e).map(h=>[h.id,`${es(j,h.id)}${h.kind==="agent"?" (agent)":""}`])],[H("send-to"),d0(e).map(h=>[h.id,`${es(j,h.id)}${h.kind==="agent"?" (agent)":""}`])],[H("offer-item"),p0(e).map(h=>[h.id,gE(h)])],[H("sell-lot"),m0(e).map(h=>[h.id,j.items.has(h.id)?`${h.name} · an item`:h.id===e.id?`${h.name} · the whole holding${cc(h)}`:`${h.name} · org ${h.index}'${cc(h)}`])]];for(const[h,w]of o){const m=h.value,x=w.map(([y,$])=>E("option",{value:y,text:$}));s(x)!==s([...h.options])&&(h.replaceChildren(...x),x.some(y=>y.value===m)&&(h.value=m))}for(const h of["send-has","offer-has"])H(h).textContent=Y(s0(e.id));H("graduate-go").textContent=`Graduate ${e.name}`,T.verb==="charter"&&!n.charter&&dE(e),T.verb==="offer"&&!n.offer&&wE(e),T.verb==="sell"&&!n.sell&&bE(e);const i=T.verb==="keyring"&&!n.keyring&&w0(e);i&&H("keyring-keys").replaceChildren(...[["Taproot",i.taproot],["SegWit",i.segwit],["nostr",i.nostr],["Ethereum",i.ethereum]].map(ss));const a=T.verb==="sell"&&V(H("sell-lot").value),c=T.verb==="graduate"?r:T.verb==="charter"&&hi()==="series"?Ki(e):a||e,l=c&&$e(Z.keys,j,c),f=T.verb==="send"||T.verb==="offer",u=l&&(f?`${l.from} · ${xe(Z.keys,j,c).path}`:l.path);H("act-key").textContent=!c||n[T.verb]?"":l?`Signs as ${c.name}: ${u}`:"Signs with the lab wallet: this holding predates lab keys.";const d=T.verb==="graduate"&&$e(Z.keys,j,e)?qn(j,e.id).length:0;H("act-gas").textContent=!c||n[T.verb]||!l?"":T.verb==="send"?`Fee: ${W} sats, from ${e.name}'s balance.`:T.verb==="offer"?`Fee: ${W} sats, from ${e.name}'s balance, paid only if the holder accepts.`:T.verb==="sell"?y0(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: ${N$(T.verb,d).toLocaleString("en-US")} sats from ${c.name}'s tank (${Y(bl(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 p=rs(e),g=T.closing===e.id;H("close-note").textContent=p?`Closing ${e.name} spends it for the last time, and its ${On(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.`,H("close-go").textContent=g?`Yes, close ${e.name}`:`Close ${e.name}`,H("close-keep").hidden=!g}function b0(){const e=H("inspect-body"),t=T.event?j.log.find(o=>o.id===T.event):null;if(t)return H("inspect-sub").textContent="event",e.replaceChildren(...HE(t));const n=T.tx?qe.ledger.find(o=>o.key===T.tx):null;if(n)return H("inspect-sub").textContent="money",e.replaceChildren(...RE(n));const r=V(T.node);if(H("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(T.node,Ee);if(!s)return e.replaceChildren(E("p",{class:"note pad",text:`${r.name} is not born yet at beat ${T.beat}.`}));e.replaceChildren(...kE(s))}const ss=([e,t,n])=>E("div",{class:"f"},E("dt",{text:e}),E("dd",{},t,n&&E("span",{class:"fn",text:n})));function kE(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."],T.beat===null&&(ft.has(e.id)||dt.has(e.id)||ut.has(e.id))&&EE(e),t&&e.root===e.id&&["Holding",E("span",{},"its own, since it graduated",e.id!==T.holding&&E("button",{type:"button",class:"btn sm open",onclick:()=>{Ar({holding:e.id,node:e.id}),_E()}},`Open ${e.name}`))],e.closed!==null&&["Closed",mt(e.closed)],["Charter",e.charter?Pl(e):"none yet",e.charter?$s(Ee,e).ok?e.charter.filing?`Filing SHA-256 ${e.charter.filing.slice(0,16)}…`:"":`Lapsed: ${$s(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}${$s(Ee,s).ok?"":" (lapsed)"}`).join(", ")||"none yet"],["Children",Er(Ee.nodes,e).map(s=>s.name).join(", ")||"none yet"],xe(Z.keys,Ee,e)&&["Balance",Y(To(e.id)),`Test BTC at its SegWit address${T.beat===null?"":`, as of beat ${T.beat}`}.`],T.beat===null&&$e(Z.keys,j,e)&&["Gas tank",Y(bl(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]].filter(Boolean);return[E("div",{class:"ih"},E("p",{class:"eyebrow",text:es(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(ss)),e.badges.length>0&&E("div",{},E("p",{class:"lab",text:"Belts"}),E("ul",{class:"list"},e.badges.map(s=>{var o;return E("li",{},c0(s),E("span",{class:"when",text:` from ${((o=V(s.by))==null?void 0:o.name)??"?"}, ${mt(s.beat)}`}))}))),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)})`}))))),$E(e),AE(e),CE(e))]}function $E(e){const t=(u,d)=>d.length>0&&E("div",{},E("p",{class:"lab",text:u}),E("ul",{class:"list items"},d)),n=(u,d)=>E("li",{},E("b",{text:u.name}),u.note&&` · ${u.note}`,E("span",{class:"when",text:` (${d})`}));if(T.beat!==null)return t("Made",e.made.map(u=>Ee.items.get(u)).filter(Boolean).map(u=>n(u,mt(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)}${ut.has(u.id)?`, in one coin with ${Ue(ut.get(u.id))}'s tree`:""}`),p=Bo().filter(g=>g.item===u.id&&g.seller===e.id&&_o(Z,j,g,Me)==="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 ${u.name}`,onclick:()=>qu(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=Bo().filter(u=>u.buyer===e.id&&_o(Z,j,u,Me)!=="done").map(u=>{const d=kl(Z,j,u,Me);return E("li",{},E("b",{text:u.price?Y(u.price):"nothing"}),` for ${Ue(u.item)}`,E("span",{class:"when",text:d?` (stale: ${d})`:` (open until ${u.seller?ke(u.seller):`${Ue(u.item)}'s owner`} accepts)`}),E("button",{type:"button",class:"btn sm","aria-label":`Withdraw the offer for ${Ue(u.item)}`,onclick:()=>SE(u)},"Withdraw"))}),a=u=>u.seller===e.id||u.seller===null&&(u.item??u.lot)===e.id,c=Bo().filter(u=>a(u)&&j.nodes.has(u.item)&&_o(Z,j,u,Me)==="open").map(u=>E("li",{},E("b",{text:Ue(u.item)}),E("span",{class:"when",text:` ${ke(u.buyer)} offers ${u.price?Y(u.price):"nothing, a free claim"}`}),e.status==="active"&&E("button",{type:"button",class:"btn sm","aria-label":`Accept ${ke(u.buyer)}'s offer for ${Ue(u.item)}`,onclick:()=>qu(u)},"Accept"))),l=Ol().filter(u=>a(u)&&El(Z,j,u)!=="done").map(u=>{const d=$l(Z,j,u);return E("li",{},E("b",{text:Y(u.price)}),` for ${Ue(u.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 ${Ue(u.lot)}`,onclick:()=>x0(u)},"Withdraw"))}),f=[...dt].filter(([,u])=>u===e.id).map(([u])=>E("li",{},E("b",{text:Ue(u)}),E("span",{class:"when",text:V(u).root===u?" bought whole":` bought from ${ke(V(u).parent)}`}),E("button",{type:"button",class:"btn sm","aria-label":`Adopt ${Ue(u)}`,onclick:()=>v0(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=V(e);return t?t.root===T.holding?t.name:es(j,e):"?"};async function qu(e){const t=Ue(e.item),n=ke(e.buyer),r=e.seller?ke(e.seller):`${t}'s owner`,s=j.nodes.has(e.item);if(!await et(i=>{j$(i,e.txid)}))return;const o=qe.ledger.find(i=>i.txid===e.txid);fe(`${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 EE(e){var o;const t=ft.get(e.id),n=V(dt.get(e.id)),r=V(ut.get(e.id)),s=[...ut.values()].includes(e.id);return!t&&!n?["Changing hands",`with ${(r==null?void 0:r.name)??"?"}'s tree`,ft.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 ${r0(t.seller)}`,E("button",{type:"button",class:"btn sm open",onclick:()=>x0(t)},"Withdraw")),s?`Its tree is one coin at its key, ${On(((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:()=>v0(e.id,n.id)},`Adopt into ${n.name}`)),`${n.name}'s key holds its ${s?"tree, in one coin,":"inscription"} now.`]}async function x0(e){var s;const t=Ue(e.lot),n=e.seller?ke(e.seller):`${t}'s owner`,r=(((s=e.holder.ids)==null?void 0:s.length)??1)>1;await et(o=>{Z$(o,_r(e))})&&fe(`${n} withdrew its ask for ${t}.${r?" Its tree split back, each inscription to its own key.":""}`)}async function v0(e,t){const n=Ue(e),r=ke(t);if(!await et(o=>{q$(o,e,t)}))return;const s=j.log.findLast(o=>o.op==="join"&&o.node===e);fe(`${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 SE(e){const t=Ue(e.item),n=ke(e.buyer);await et(r=>{K$(r,e.txid)})&&fe(`${n} withdrew its offer for ${t}.`)}function _E(){const e=document.querySelector(".tree-blk").getBoundingClientRect().top+scrollY-document.querySelector(".clock").offsetHeight-12;e(n.to===e.id||n.from===e.id)&&(T.beat===null||n.beat!==null&&n.beat<=T.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:BE(n,e.id)}),E("span",{class:"when",text:` (${mt(n.beat??"cued")})`})))))}function BE(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=Ue(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 k0(e){const t=n=>{const r=V(n);return n?r?r.root===T.holding?r.name:es(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"?`${Ue(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 TE={own:"its own key",lab:"the lab wallet",parent:"its parent's key (its handoff is cued)",other:"a key outside this lab"},OE={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 IE(e){var s;const t=ul(Z,j,e.id),n=V(ut.get(e.id)),r=(s=Kn(Z,Me,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`:TE[t.who]:"nobody: its inscription has been spent"}function CE(e){const t=$e(Z.keys,Ee,e),n=["Held now by",IE(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(ss)));const r=e.kind==="agent",s=ll(Z.keys,Ee,e),o=r$(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,PE(e)];return E("div",{class:"keys"},E("p",{class:"lab",text:"Keys"}),E("dl",{class:"fl"},f.map(ss)),e.keyring&&Dr(`${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(([u,d])=>E("li",{},E("b",{text:u}),E("span",{class:"when",text:` ${OE[u]}`}),E("code",{text:d})))),Dr(r?"Public lines to paste":"CA key for TrustedUserCAKeys",i.join(` + +`)),NE(e,t))}function PE(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 Dr(e,t,n=t){const r=E("pre",{text:n}),s=E("button",{type:"button",class:"cp","aria-label":`Copy ${e}`,onclick:()=>UE(t,s,r)},"Copy");return E("div",{class:"code"},E("div",{class:"code-h cph"},E("span",{text:e}),s),r)}async function UE(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 NE(e,t){var a;const n=T.reveal===e.id,r=n&&c$(Z.keys,Ee,e),s=V(e.parent,Ee),o=()=>{var c;T.reveal=n?null:e.id,b0(),(c=H("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?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(` +`)):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,l,f])=>Dr(`${c} · ${l}`,f)),r.leaves.map(([c,l,f])=>Dr(`${c} · ${l}`,f))))}function LE(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=Kc(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[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 HE(e){var o,i,a;const t=fi.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",LE(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:mp(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"})),!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(ss)),E("div",{class:"code"},E("p",{class:"code-h",text:"Metadata · CBOR, tag 5"}),E("pre",{text:Vu(e.meta)})),s&&E("div",{class:"code"},E("p",{class:"code-h",text:"Raw index entry"}),E("pre",{text:Vu(s)})))]}function RE(e){var c;const t=l=>{var f;return((f=V(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=ac.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?`${Ue(e.item)} and its tree: ${On(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.`:`${Ue(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",`${Ue(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:k0(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(ss)),n&&Dr("Raw transaction",n.raw))]}function Ul(){const e=lt(),t=H("beat"),n=V(T.holding);t.max=String(e),t.value=String(T.beat??e),t.disabled=e===0,H("beat-label").textContent=T.beat===null?`Now · beat ${e}`:`Beat ${T.beat} of ${e}`,H("replay").textContent=T.replay?"Stop":"Replay",H("replay").disabled=!n||e===0,H("to-now").disabled=T.beat===null,H("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=V(c))==null?void 0:l.root)===T.holding})&&o(a.pending?"cued":a.beat,{e:a,at:s.get(a.id.slice(0,-2))??0});for(const a of qe.ledger)[a.to,a.from].some(c=>{var l;return c&&((l=V(c))==null?void 0:l.root)===T.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 H("timeline-list").replaceChildren(E("li",{class:"wait",text:n?"Nothing yet.":"Found a holding to start its timeline."}));H("timeline-list").replaceChildren(...i.map(a=>{const c=a==="cued"?null:Z.chain.blocks[a-1],l=T.beat!==null&&(a==="cued"||a>T.beat),f=T.beat!==null&&a===T.beat;return E("li",{class:`beat${l?" later":""}${f?" now":""}`},E("p",{class:"bh"},E("span",{class:"bn",text:a==="cued"?"Cued":`Beat ${a}`}),E("span",{class:"bt",text:c?G$(c.time):Z.clock.tempo==="manual"?"waiting for Beat now":"landing on the next beat"})),E("ol",{class:"evs"},r.get(a).sort((u,d)=>u.at-d.at).map(({e:u,m:d})=>d?KE(d):jE(u))))}))}function jE(e){const[t,...n]=mp(e,j).split(" ");return E("li",{},E("button",{type:"button",class:`ev${e.ok?"":" bad"}${e.id===T.event?" on":""}`,"aria-pressed":String(e.id===T.event),onclick:()=>Ar({event:e.id,node:e.node??T.node})},E("span",{class:"op",text:e.ok?t:`✕ ${t.replace(/:$/,"")}`})," ",E("span",{class:"es",text:n.join(" ")})))}const KE=e=>E("li",{},E("button",{type:"button",class:`ev money${e.kind==="gas"?" gas":""}${e.kind==="deal"?" deal":""}${e.key===T.tx?" on":""}`,"aria-pressed":String(e.key===T.tx),onclick:()=>{var t;return Ar({tx:e.key,node:((t=V(e.to))==null?void 0:t.root)===T.holding?e.to:T.node})}},E("span",{class:"op",text:e.kind})," ",E("span",{class:"es",text:k0(e)})));H("f-found").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=Js(t.elements.name.value);if(!n)return fe("Name the holding: lowercase letters, digits and hyphens.",!0);await qt("found",null,{name:n},(r,s)=>(Il({holding:r,node:r}),`${n} is founded, ${s}.`))&&t.reset()});H("sample").addEventListener("click",async()=>{let e=null;fe("Rehearsing the yolopreneur tree over six beats…"),await et(t=>{e=W$(t)})&&(Ar({holding:e,node:e}),fe("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."))});H("f-birth").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=V(T.node),r=Js(t.elements.name.value),s=t.elements.kind.value;if(!r)return fe("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="")});H("f-award").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=V(T.node),r=t.elements.to.value,s=Js(t.elements.skill.value),o=t.elements.belt.value;if(!s)return fe("Name the skill, for example launch.",!0);await qt("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}.`})&&(t.elements.skill.value="")});H("f-decide").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=V(T.node),r=t.elements.title.value.trim(),s=t.elements.why.value.trim();if(!r)return fe("A decision needs a title.",!0);await qt("decide",n.id,{title:r,why:s},(o,i)=>`${n.name} decided “${r}”, ${i}.`)&&t.reset()});H("f-send").addEventListener("submit",async e=>{var a;e.preventDefault();const t=e.currentTarget,n=V(T.node),r=t.elements.to.value,s=Oi(t.elements.amount.value);if(s===null)return fe("Write an amount in test BTC, for example 1.5 (at most eight decimals).",!0);let o=null;if(!await et(c=>{o=H$(c,n.id,r,s)}))return;const i=qe.ledger.find(c=>c.txid===o);fe(`${n.name} sent ${Y(s)} to ${((a=V(r))==null?void 0:a.root)===n.root?V(r).name:es(j,r)}, ${i!=null&&i.beat?`at beat ${i.beat}`:"cued for the next beat"}.`),t.elements.amount.value=""});H("f-make").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=V(T.node),r=Js(t.elements.name.value),s=t.elements.note.value.trim();if(!r)return fe("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()});H("f-charter").addEventListener("change",e=>{e.target.name==="form"&&us()});H("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()));H("charter-filing").value=[...n].map(s=>s.toString(16).padStart(2,"0")).join(""),e.target.value="",fe(`Hashed ${t.name} in this tab: only its SHA-256 would go on chain.`)});H("f-charter").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=V(T.node),r=hi();if(!r)return fe("Pick a legal form.",!0);if(r==="series"){const a=Ki(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:Js(s("provider")),filing:s("filing").toLowerCase()},i=(a,c)=>`${n.name} is chartered as ${lE[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=""});H("f-keyring").addEventListener("submit",async e=>{e.preventDefault();const t=V(T.node);await qt("keyring",t.id,{},(n,r)=>`${t.name} published its keyring, ${r}: four keys, each signing the same statement.`)});H("f-offer").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=V(T.node),r=H("offer-item").value,s=Oi(t.elements.price.value);if(s===null)return fe("Write a price in test BTC, for example 0.1, or 0 for a free claim.",!0);const o=V(r),i=Ue(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 et(c=>{R$(c,r,n.id,s)})&&(fe(`${n.name} offers ${s?Y(s):"nothing"} for ${i}. The offer stands until ${a} accepts it.`),t.elements.price.value="")});H("offer-take").addEventListener("click",async()=>{const e=V(T.node),t=H("offer-item").value,n=ft.get(t),r=j.nodes.has(t);if(!n)return;const s=Ue(t),o=ke(n.seller);if(!await et(c=>{V$(c,_r(n),e.id)}))return;const i=qe.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 fe(`${e.name} took ${s} from ${o} for ${Y(n.price)}, ${a}.`);Ar({holding:e.root,node:t}),fe(`${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.`)});H("f-sell").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=V(T.node),r=H("sell-lot").value,s=Oi(t.elements.price.value),o=j.nodes.has(r);if(s===null)return fe("Write a price in test BTC, for example 1.",!0);const i=Ue(r);await et(a=>{n0(a,r,s)})&&(fe(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"])H(e).addEventListener("change",()=>us());H("send-max").addEventListener("click",()=>{const e=V(T.node),t=e&&xe(Z.keys,j,e);t&&(H("send-amount").value=Tp(gl(Z.chain.coins(t.script))))});H("f-graduate").addEventListener("submit",async e=>{e.preventDefault();const t=V(T.node),n=V(t.parent);await qt("graduate",n.id,{of:t.id},(r,s)=>(Il({node:t.id}),`${t.name} graduates from ${n.name}, ${s}. It's a holding of its own now.`))});H("f-close").addEventListener("submit",async e=>{e.preventDefault();const t=V(T.node);if(T.closing!==t.id)return T.closing=t.id,us(),H("close-go").focus();T.closing=null,await qt("close",t.id,{},(n,r)=>`${t.name} is closed, ${r}.`)});H("close-keep").addEventListener("click",()=>{T.closing=null,us(),H("close-go").focus()});for(const e of document.querySelectorAll("[data-verb]"))e.addEventListener("click",()=>{T.verb=e.dataset.verb,T.closing=null,us()});for(const e of document.querySelectorAll("[data-rule]"))e.addEventListener("click",async()=>{const t=e.dataset.rule;await et(n=>B$(n,t))&&fe({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])});H("f-fund").addEventListener("submit",async e=>{var i;e.preventDefault();const t=e.currentTarget,n=t.elements.to.value,r=Oi(t.elements.amount.value);if(r===null)return fe("Write an amount in test BTC, for example 5 (at most eight decimals).",!0);let s=null;if(!await et(a=>{s=z$(a,n,r)}))return;const o=qe.ledger.find(a=>a.txid===s);fe(`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 et(r=>I$(r,n,Date.now(),Ri(r,Tl(r)??T.holding)))&&fe(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.`)});H("beat-now").addEventListener("click",()=>i0(e=>{it(e,Ri(e,Tl(e)??T.holding))}));setInterval(()=>{a0();const{tempo:e,nextAt:t}=Z.clock;T.busy||document.hidden||typeof e!="number"||!Z.chain.mempool.length||t&&Date.now()C$(n,Date.now(),Ri(n,Tl(n)??T.holding)))},1e3);addEventListener("storage",e=>{(e.key===Ui||e.key===null)&&o0()});function ro(){T.replay&&(clearInterval(T.replay),T.replay=null,Ul())}function DE(){const e=V(T.holding);if(!(!e||!lt())){if(di(typeof e.born=="number"?e.born:lt()),T.beat===null)return fe("Nothing to replay yet: this holding has one beat of history.");T.replay=setInterval(()=>{(T.beat===null||T.beat+1>=lt())&&ro(),di(T.beat===null?lt():T.beat+1)},800),Ul()}}H("beat").addEventListener("input",e=>{ro(),di(Number(e.target.value))});H("replay").addEventListener("click",()=>T.replay?ro():DE());for(const e of["to-now","past-now"])H(e).addEventListener("click",()=>{ro(),di(lt())});const ba=["system","light","dark"],$0=()=>{H("theme").textContent=`Theme: ${document.documentElement.dataset.theme??"system"}`};H("theme").addEventListener("click",()=>{const e=ba[(ba.indexOf(document.documentElement.dataset.theme??"system")+1)%ba.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{}$0()});function E0(e,t,n){const r=H("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 ME={read:()=>{try{return Sl()}catch{return to()}}};async function S0(e,t){ro(),await et(n=>{Object.assign(n,e())},ME)&&(Object.assign(T,{holding:null,node:null,event:null,tx:null,beat:null,closing:null}),Cl(),fe(t))}H("save").addEventListener("click",()=>{const e=E("a",{href:URL.createObjectURL(new Blob([Wp(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),fe("Saved a backup of this lab, test wallet included. Load it in any browser to carry on.")});H("load").addEventListener("click",()=>H("load-file").click());H("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=Fp(await t.text())}catch(s){return fe(`${t.name} is not an Orgchain lab: ${s.message}`,!0)}E0(`Replace this browser's lab with ${t.name}?`,"Replace",()=>S0(()=>n,`Loaded ${t.name}.`))});H("reset").addEventListener("click",()=>E0("Erase this browser's lab: every holding, the chain and the test wallet?","Erase",()=>S0(to,"Erased. This is a fresh lab.")));$0();o0(); diff --git a/ventures/lineage/orgchain/assets/index-Ox6KvI0i.js b/ventures/lineage/orgchain/assets/index-Ox6KvI0i.js deleted file mode 100644 index 3e7aa7b..0000000 --- a/ventures/lineage/orgchain/assets/index-Ox6KvI0i.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 xo=5e9,Su=2**52,Ol=(e,t)=>[[Su+e*xo,Su+e*xo+t]];function Cl(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 Pl(e,t){var n;return(n=Cl(e,t,1)[0])==null?void 0:n[0]}function lo(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=Cl(s,o,Number(i.value));return o+=Number(i.value),a})}function ua(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function i0(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function Nl(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 a0(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ua(e.outputLen),ua(e.blockLen)}function c0(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 u0(e,t){Nl(e);const n=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),Tt=(e,t)=>e<<32-t|e>>>t,f0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!f0)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function d0(e){if(typeof e!="string")throw new TypeError(`utf8ToBytes expected string, got ${typeof e}`);return new TextEncoder().encode(e)}function Ll(e){if(typeof e=="string"&&(e=d0(e)),!(e instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof e})`);return e}let h0=class{clone(){return this._cloneInto()}};function Hl(e){const t=r=>e().update(Ll(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function p0(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 g0=class extends h0{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=Oi(this.buffer)}update(t){Ii.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=Ll(t);const o=t.length;for(let i=0;is-i&&(this.process(r,0),i=0);for(let f=i;fl.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;fe&t^~e&n,y0=(e,t,n)=>e&t^e&n^t&n,w0=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]),sn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),on=new Uint32Array(64);let Rl=class extends g0{constructor(){super(64,32,8,!1),this.A=sn[0]|0,this.B=sn[1]|0,this.C=sn[2]|0,this.D=sn[3]|0,this.E=sn[4]|0,this.F=sn[5]|0,this.G=sn[6]|0,this.H=sn[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 f=0;f<16;f++,n+=4)on[f]=t.getUint32(n,!1);for(let f=16;f<64;f++){const d=on[f-15],h=on[f-2],g=Tt(d,7)^Tt(d,18)^d>>>3,p=Tt(h,17)^Tt(h,19)^h>>>10;on[f]=p+on[f-7]+g+on[f-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const d=Tt(a,6)^Tt(a,11)^Tt(a,25),h=l+d+m0(a,c,u)+w0[f]+on[f]|0,p=(Tt(r,2)^Tt(r,13)^Tt(r,22))+y0(r,s,o)|0;l=u,u=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,u=u+this.G|0,l=l+this.H|0,this.set(r,s,o,i,a,c,u,l)}roundClean(){on.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},b0=class extends Rl{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 la=Hl(()=>new Rl);Hl(()=>new b0);function x0(e,t){if(e.length>t)throw new TypeError(`Data is larger than array size: ${e.length} > ${t}`)}function v0(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 k0(e){if(e>Number.MAX_SAFE_INTEGER)throw new TypeError("Number exceeds safe bounds!")}const{getRandomValues:E0}=crypto??globalThis.crypto??window.crypto;function $0(e=32){if(typeof E0=="function")return crypto.getRandomValues(new Uint8Array(e));throw new Error("Crypto module missing getRandomValues!")}function S0(e,t,n="be"){t===void 0&&(t=e.length),x0(e,t);const r=new Uint8Array(t).fill(0),s=n==="be"?0:t-e.length;return r.set(e,s),r}function jl(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;)l=o[c],l=l>0?l*256+u:u,u=l/s|0,o[c]=l%s,c++;for(;c-- >0;)i+=r[o[c]];return n&&i.length%4>0?i+"=".repeat(4-i.length%4):i}function T0(e,t){const n=Kl(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 Dl(e){return la(la(e))}function I0(e){const t=Dl(e);return jl([e,t.slice(0,4)])}function O0(e){const t=e.slice(0,-4),n=e.slice(-4);if(Dl(t).slice(0,4).toString()!==n.toString())throw new Error("Invalid checksum!");return t}const _u={encode:B0,decode:T0},Ml={encode:e=>{const t=I0(e);return _u.encode(t,"base58")},decode:e=>{const t=_u.decode(e,"base58");return O0(t)}},Zl="qpzry9x8gf2tvdw0s3jn54khce6mua7l",C0=[996825010,642813549,513874426,1027748829,705979059],vo=[{version:0,name:"bech32",const:1},{version:1,name:"bech32m",const:734539939}];function Vl(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^=C0[s])}return t}function ql(e){const t=[];let n;for(n=0;n>5);for(t.push(0),n=0;n>5*(5-i)&31);return o}function zl(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 N0(e,t,n){const r=t.concat(U0(e,t,n));let s=e+"1";for(let o=0;oo.version===t[0])??vo[0];if(!P0(r,t,s))throw new Error("Checksum verification failed!");return[r,t.slice(0,t.length-6)]}function L0(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 H0(e){const t=e.lastIndexOf("1");return!(t<1||t+7>e.length||e.length>90)}function R0(e,t="bc",n=0){const r=[n,...zl([...e],8,5)],s=vo.find(i=>i.version===n)??vo[0],o=N0(t,r,s);return Wl(o),o}function Wl(e){e=e.toLowerCase();const t=e.split("1",1)[0],[n,r]=Fl(e),s=zl(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 j0(e){e=e.toLowerCase();const[t,n]=Fl(e);return n[0]}const Gl={encode:R0,decode:Wl,version:j0},Yl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Xl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",K0=new TextEncoder;function Jl(e,t=!1,n=!0){typeof e=="string"&&(e=K0.encode(e));const r=t?Xl:Yl;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 Ql(e,t=!1){const n=t||e.includes("-")||e.includes("_")?Xl.split(""):Yl.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 ef={encode:Jl,decode:Ql},tf={encode:e=>Jl(e,!0,!1),decode:e=>Ql(e,!0)},D0=BigInt(0),M0=BigInt(255),nf=BigInt(256);function Z0(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 V0(e,t,n="be"){t===void 0&&(t=Z0(e));const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(;e>D0;){const a=e&M0,c=Number(a);r?o.setUint8(i++,c):o.setUint8(i--,c),e=(e-a)/nf}return new Uint8Array(s)}function q0(e){let t=BigInt(0);for(let n=e.length-1;n>=0;n--)t=t*nf+BigInt(e[n]);return BigInt(t)}function z0(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 W0(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 G0(e,t,n="be"){t===void 0&&(t=W0(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 Y0(e){let t=0;for(let n=e.length-1;n>=0;n--)t=t*256+e[n],k0(t);return t}const X0=new TextEncoder,J0=new TextDecoder;function Xa(e){return X0.encode(e)}function Ci(e){return J0.decode(e)}function Q0(e,t){v0(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 eg(e,t,n="le"){t=Q0(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 Xa(t)}function rg(e,t,n){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Uint8Array)return S0(e,t,n);if(typeof e=="string")return eg(e,t,n);if(typeof e=="bigint")return V0(e,t,n);if(typeof e=="number")return G0(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=$0(t);return new re(n,t)}constructor(t,n,r){const s=rg(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 zr(this)}toNum(t="be"){const n=t==="be"?this.reverse():this;return Y0(n)}toBin(){return F0(this)}toBig(t="be"){const n=t==="be"?this.reverse():this;return q0(n)}toHash(){const t=la(this);return new re(t)}toJson(){const t=Ci(this);return JSON.parse(t)}toBech32(t,n=0){return Gl.encode(this,t,n)}toStr(){return Ci(this)}toHex(){return tg(this)}toBytes(){return new Uint8Array(this)}tob58chk(){return Ml.encode(this)}toBase64(){return ef.encode(this)}toB64url(){return tf.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=jl(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=sg,re.big=ig,re.bin=og,re.raw=ag,re.str=cg,re.hex=ug,re.bytes=lg,re.json=fg,re.base64=dg,re.b64url=hg,re.bech32=pg,re.b58chk=gg,re.encode=Xa,re.decode=Ci,re);function sg(e,t,n){return new B(e,t,n)}function og(e,t,n){return new B(z0(e),t,n)}function ig(e,t,n){return new B(e,t,n)}function ag(e,t,n){return new B(e,t,n)}function cg(e,t,n){return new B(Xa(e),t,n)}function ug(e,t,n){return new B(e,t,n)}function lg(e,t,n){return new B(e,t,n)}function fg(e){return new B(ng(e))}function dg(e){return new B(ef.decode(e))}function hg(e){return new B(tf.decode(e))}function pg(e){return new B(Gl.decode(e))}function gg(e){return new B(Ml.decode(e))}let zr=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 Dt(e,t){const n=B.bytes(e);if(n.length!==t)throw new Error(`Invalid input size: ${n.hex} !== ${t}`)}function Ge(e,t){if(t)throw new Error(e);return!1}function fo(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 rf={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 mg(e){if(e>186&&e<255)return"OP_SUCCESS"+String(e);for(const[t,n]of Object.entries(rf))if(n===e)return t;throw new Error("OPCODE not found:"+String(e))}function yg(e){for(const[t,n]of Object.entries(rf))if(t===e)return Number(n);throw new Error("OPCODE not found:"+e)}function wg(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 bg(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 xg(e){let t=new Uint8Array;if(typeof e=="string"){if(e.startsWith("OP_"))return B.num(yg(e),1);tn(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([Au(t.length),t]));if(t.length>ko){const n=vg(t);return of(n)}else return B.join([Au(t.length),t])}function Au(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<=ko):return B.join([n,B.num(e,2,"le")]);default:throw new Error("Invalid word size:"+e.toString())}}function vg(e){const t=[],n=new zr(e);for(;n.size>ko;)t.push(n.read(ko));return t.push(n.read(n.size)),t}function Ja(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 kg(n)}function kg(e){const t=new zr(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 Bg(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");fa(e.outputLen),fa(e.blockLen)}function Tg(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 Ig(e,t){af(e);const n=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),It=(e,t)=>e<<32-t|e>>>t,Cg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Cg)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Pg(e){if(typeof e!="string")throw new TypeError(`utf8ToBytes expected string, got ${typeof e}`);return new TextEncoder().encode(e)}function Qa(e){if(typeof e=="string"&&(e=Pg(e)),!(e instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof e})`);return e}function Ug(...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(Qa(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Ng(e=32){if(Pi&&typeof Pi.getRandomValues=="function")return Pi.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function Lg(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 Hg=class extends cf{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=Ui(this.buffer)}update(t){Dn.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=Qa(t);const o=t.length;for(let i=0;is-i&&(this.process(r,0),i=0);for(let f=i;fl.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;fe&t^~e&n,jg=(e,t,n)=>e&t^e&n^t&n,Kg=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]),an=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),cn=new Uint32Array(64);let lf=class extends Hg{constructor(){super(64,32,8,!1),this.A=an[0]|0,this.B=an[1]|0,this.C=an[2]|0,this.D=an[3]|0,this.E=an[4]|0,this.F=an[5]|0,this.G=an[6]|0,this.H=an[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 f=0;f<16;f++,n+=4)cn[f]=t.getUint32(n,!1);for(let f=16;f<64;f++){const d=cn[f-15],h=cn[f-2],g=It(d,7)^It(d,18)^d>>>3,p=It(h,17)^It(h,19)^h>>>10;cn[f]=p+cn[f-7]+g+cn[f-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const d=It(a,6)^It(a,11)^It(a,25),h=l+d+Rg(a,c,u)+Kg[f]+cn[f]|0,p=(It(r,2)^It(r,13)^It(r,22))+jg(r,s,o)|0;l=u,u=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,u=u+this.G|0,l=l+this.H|0,this.set(r,s,o,i,a,c,u,l)}roundClean(){cn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},Dg=class extends lf{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 ff=uf(()=>new lf);uf(()=>new Dg);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Mg=BigInt(0),ec=BigInt(1),Zg=BigInt(2),si=e=>e instanceof Uint8Array,Vg=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Cr(e){if(!si(e))throw new Error("Uint8Array expected");let t="";for(let n=0;nPr(e.toString(16).padStart(t*2,"0")),hf=(e,t)=>$r(e,t).reverse(),qg=e=>Pr(df(e));function dt(e,t,n){let r;if(typeof t=="string")try{r=Pr(t)}catch(o){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${o}`)}else if(si(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 bt(...e){const t=new Uint8Array(e.reduce((r,s)=>r+s.length,0));let n=0;return e.forEach(r=>{if(!si(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}function zg(e,t){if(e.length!==t.length)return!1;for(let n=0;n0n;e>>=ec,t+=1);return t}const Wg=(e,t)=>e>>BigInt(t)&1n,Gg=(e,t,n)=>e|(n?ec:Mg)<(Zg<new Uint8Array(e),Bu=e=>Uint8Array.from(e);function pf(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=Ni(e),s=Ni(e),o=0;const i=()=>{r.fill(1),s.fill(0),o=0},a=(...f)=>n(s,r,...f),c=(f=Ni())=>{s=a(Bu([0]),f),r=a(),f.length!==0&&(s=a(Bu([1]),f),r=a())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const d=[];for(;f{i(),c(f);let h;for(;!(h=d(u()));)c();return i(),h}}const Yg={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 Fr(e,t,n={}){const r=(s,o,i)=>{const a=Yg[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 Xg=Object.freeze({__proto__:null,bitGet:Wg,bitLen:Fg,bitMask:rc,bitSet:Gg,bytesToHex:Cr,bytesToNumberBE:$n,bytesToNumberLE:nc,concatBytes:bt,createHmacDrbg:pf,ensureBytes:dt,equalBytes:zg,hexToBytes:Pr,hexToNumber:tc,numberToBytesBE:$r,numberToBytesLE:hf,numberToHexUnpadded:df,numberToVarBytesBE:qg,utf8ToBytes:oi,validateObject:Fr});/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ze=BigInt(0),Le=BigInt(1),Rn=BigInt(2),Jg=BigInt(3),da=BigInt(4),Tu=BigInt(5),Iu=BigInt(8);BigInt(9);BigInt(16);function Ye(e,t){const n=e%t;return n>=Ze?n:t+n}function Qg(e,t,n){if(n<=Ze||t 0");if(n===Le)return Ze;let r=Le;for(;t>Ze;)t&Le&&(r=r*e%n),e=e*e%n,t>>=Le;return r}function ft(e,t,n){let r=e;for(;t-- >Ze;)r*=r,r%=n;return r}function ha(e,t){if(e===Ze||t<=Ze)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let n=Ye(e,t),r=t,s=Ze,o=Le;for(;n!==Ze;){const a=r/n,c=r%n,u=s-o*a;r=n,n=c,s=o,o=u}if(r!==Le)throw new Error("invert: does not exist");return Ye(s,t)}function em(e){const t=(e-Le)/Rn;let n,r,s;for(n=e-Le,r=0;n%Rn===Ze;n/=Rn,r++);for(s=Rn;s(r[s]="function",r),t);return Fr(e,n)}function rm(e,t,n){if(n 0");if(n===Ze)return e.ONE;if(n===Le)return t;let r=e.ONE,s=t;for(;n>Ze;)n&Le&&(r=e.mul(r,s)),s=e.sqr(s),n>>=Le;return r}function sm(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 sc(e,t){const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function mf(e,t,n=!1,r={}){if(e<=Ze)throw new Error(`Expected Fp ORDER > 0, got ${e}`);const{nBitLength:s,nByteLength:o}=sc(e,t);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");const i=tm(e),a=Object.freeze({ORDER:e,BITS:s,BYTES:o,MASK:rc(s),ZERO:Ze,ONE:Le,create:c=>Ye(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Ze<=c&&cc===Ze,isOdd:c=>(c&Le)===Le,neg:c=>Ye(-c,e),eql:(c,u)=>c===u,sqr:c=>Ye(c*c,e),add:(c,u)=>Ye(c+u,e),sub:(c,u)=>Ye(c-u,e),mul:(c,u)=>Ye(c*u,e),pow:(c,u)=>rm(a,c,u),div:(c,u)=>Ye(c*ha(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>ha(c,e),sqrt:r.sqrt||(c=>i(a,c)),invertBatch:c=>sm(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>n?hf(c,o):$r(c,o),fromBytes:c=>{if(c.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${c.length}`);return n?nc(c):$n(c)}});return Object.freeze(a)}function om(e,t,n=!1){e=dt("privateHash",e);const r=e.length,s=sc(t).nByteLength+8;if(s<24||r1024)throw new Error(`hashToPrivateScalar: expected ${s}-1024 bytes of input, got ${r}`);const o=n?nc(e):$n(e);return Ye(o,t-Le)+Le}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const im=BigInt(0),Li=BigInt(1);function am(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>im;)o&Li&&(i=i.add(a)),a=a.double(),o>>=Li;return i},precomputeWindow(s,o){const{windows:i,windowSize:a}=r(o),c=[];let u=s,l=u;for(let f=0;f>=h,w>c&&(w-=d,i+=Li);const y=p,v=p+Math.abs(w)-1,m=g%2!==0,x=w<0;w===0?l=l.add(n(m,o[y])):u=u.add(n(x,o[v]))}return{p:u,f:l}},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 yf(e){return gf(e.Fp),Fr(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...sc(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function cm(e){const t=yf(e);Fr(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:um,hexToBytes:lm}=Xg,Mn={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){const{Err:t}=Mn;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:um(r),l:e.subarray(n+2)}},toSig(e){const{Err:t}=Mn,n=typeof e=="string"?lm(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}=Mn._parseInt(n.subarray(2)),{d:i,l:a}=Mn._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 l=u.toString(16);return l.length&1?`0${l}`:l},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}`}},xt=BigInt(0),je=BigInt(1),Vt=BigInt(2),Eo=BigInt(3),Ou=BigInt(4);function fm(e){const t=cm(e),{Fp:n}=t,r=t.toBytes||((g,p,w)=>{const y=p.toAffine();return bt(Uint8Array.from([4]),n.toBytes(y.x),n.toBytes(y.y))}),s=t.fromBytes||(g=>{const p=g.subarray(1),w=n.fromBytes(p.subarray(0,n.BYTES)),y=n.fromBytes(p.subarray(n.BYTES,2*n.BYTES));return{x:w,y}});function o(g){const{a:p,b:w}=t,y=n.sqr(g),v=n.mul(y,g);return n.add(n.add(v,n.mul(g,p)),w)}function i(g){return typeof g=="bigint"&&xtn.eql(m,n.ZERO);return v(w)&&v(y)?f.ZERO:new f(w,y,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(p){const w=n.invertBatch(p.map(y=>y.pz));return p.map((y,v)=>y.toAffine(w[v])).map(f.fromAffine)}static fromHex(p){const w=f.fromAffine(s(dt("pointHex",p)));return w.assertValidity(),w}static fromPrivateKey(p){return f.BASE.multiply(c(p))}_setWindowSize(p){this._WINDOW_SIZE=p,u.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint)return;throw new Error("bad point: ZERO")}const{x:p,y:w}=this.toAffine();if(!n.isValid(p)||!n.isValid(w))throw new Error("bad point: x or y not FE");const y=n.sqr(w),v=o(p);if(!n.eql(y,v))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){l(p);const{px:w,py:y,pz:v}=this,{px:m,py:x,pz:k}=p,I=n.eql(n.mul(w,k),n.mul(m,v)),C=n.eql(n.mul(y,k),n.mul(x,v));return I&&C}negate(){return new f(this.px,n.neg(this.py),this.pz)}double(){const{a:p,b:w}=t,y=n.mul(w,Eo),{px:v,py:m,pz:x}=this;let k=n.ZERO,I=n.ZERO,C=n.ZERO,N=n.mul(v,v),O=n.mul(m,m),R=n.mul(x,x),A=n.mul(v,m);return A=n.add(A,A),C=n.mul(v,x),C=n.add(C,C),k=n.mul(p,C),I=n.mul(y,R),I=n.add(k,I),k=n.sub(O,I),I=n.add(O,I),I=n.mul(k,I),k=n.mul(A,k),C=n.mul(y,C),R=n.mul(p,R),A=n.sub(N,R),A=n.mul(p,A),A=n.add(A,C),C=n.add(N,N),N=n.add(C,N),N=n.add(N,R),N=n.mul(N,A),I=n.add(I,N),R=n.mul(m,x),R=n.add(R,R),N=n.mul(R,A),k=n.sub(k,N),C=n.mul(R,O),C=n.add(C,C),C=n.add(C,C),new f(k,I,C)}add(p){l(p);const{px:w,py:y,pz:v}=this,{px:m,py:x,pz:k}=p;let I=n.ZERO,C=n.ZERO,N=n.ZERO;const O=t.a,R=n.mul(t.b,Eo);let A=n.mul(w,m),P=n.mul(y,x),E=n.mul(v,k),S=n.add(w,y),b=n.add(m,x);S=n.mul(S,b),b=n.add(A,P),S=n.sub(S,b),b=n.add(w,v);let _=n.add(m,k);return b=n.mul(b,_),_=n.add(A,E),b=n.sub(b,_),_=n.add(y,v),I=n.add(x,k),_=n.mul(_,I),I=n.add(P,E),_=n.sub(_,I),N=n.mul(O,b),I=n.mul(R,E),N=n.add(I,N),I=n.sub(P,N),N=n.add(P,N),C=n.mul(I,N),P=n.add(A,A),P=n.add(P,A),E=n.mul(O,E),b=n.mul(R,b),P=n.add(P,E),E=n.sub(A,E),E=n.mul(O,E),b=n.add(b,E),A=n.mul(P,b),C=n.add(C,A),A=n.mul(_,b),I=n.mul(S,I),I=n.sub(I,A),A=n.mul(S,P),N=n.mul(_,N),N=n.add(N,A),new f(I,C,N)}subtract(p){return this.add(p.negate())}is0(){return this.equals(f.ZERO)}wNAF(p){return h.wNAFCached(this,u,p,w=>{const y=n.invertBatch(w.map(v=>v.pz));return w.map((v,m)=>v.toAffine(y[m])).map(f.fromAffine)})}multiplyUnsafe(p){const w=f.ZERO;if(p===xt)return w;if(a(p),p===je)return this;const{endo:y}=t;if(!y)return h.unsafeLadder(this,p);let{k1neg:v,k1:m,k2neg:x,k2:k}=y.splitScalar(p),I=w,C=w,N=this;for(;m>xt||k>xt;)m&je&&(I=I.add(N)),k&je&&(C=C.add(N)),N=N.double(),m>>=je,k>>=je;return v&&(I=I.negate()),x&&(C=C.negate()),C=new f(n.mul(C.px,y.beta),C.py,C.pz),I.add(C)}multiply(p){a(p);let w=p,y,v;const{endo:m}=t;if(m){const{k1neg:x,k1:k,k2neg:I,k2:C}=m.splitScalar(w);let{p:N,f:O}=this.wNAF(k),{p:R,f:A}=this.wNAF(C);N=h.constTimeNegate(x,N),R=h.constTimeNegate(I,R),R=new f(n.mul(R.px,m.beta),R.py,R.pz),y=N.add(R),v=O.add(A)}else{const{p:x,f:k}=this.wNAF(w);y=x,v=k}return f.normalizeZ([y,v])[0]}multiplyAndAddUnsafe(p,w,y){const v=f.BASE,m=(k,I)=>I===xt||I===je||!k.equals(v)?k.multiplyUnsafe(I):k.multiply(I),x=m(this,w).add(m(p,y));return x.is0()?void 0:x}toAffine(p){const{px:w,py:y,pz:v}=this,m=this.is0();p==null&&(p=m?n.ONE:n.inv(v));const x=n.mul(w,p),k=n.mul(y,p),I=n.mul(v,p);if(m)return{x:n.ZERO,y:n.ZERO};if(!n.eql(I,n.ONE))throw new Error("invZ was invalid");return{x,y:k}}isTorsionFree(){const{h:p,isTorsionFree:w}=t;if(p===je)return!0;if(w)return w(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:p,clearCofactor:w}=t;return p===je?this:w?w(f,this):this.multiplyUnsafe(t.h)}toRawBytes(p=!0){return this.assertValidity(),r(f,this,p)}toHex(p=!0){return Cr(this.toRawBytes(p))}}f.BASE=new f(t.Gx,t.Gy,n.ONE),f.ZERO=new f(n.ZERO,n.ONE,n.ZERO);const d=t.nBitLength,h=am(f,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:i}}function dm(e){const t=yf(e);return Fr(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function hm(e){const t=dm(e),{Fp:n,n:r}=t,s=n.BYTES+1,o=2*n.BYTES+1;function i(b){return xtCr($r(b,t.nByteLength));function g(b){const _=r>>je;return b>_}function p(b){return g(b)?a(-b):b}const w=(b,_,U)=>$n(b.slice(_,U));class y{constructor(_,U,j){this.r=_,this.s=U,this.recovery=j,this.assertValidity()}static fromCompact(_){const U=t.nByteLength;return _=dt("compactSignature",_,U*2),new y(w(_,0,U),w(_,U,2*U))}static fromDER(_){const{r:U,s:j}=Mn.toSig(dt("DER",_));return new y(U,j)}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(_){return new y(this.r,this.s,_)}recoverPublicKey(_){const{r:U,s:j,recovery:L}=this,M=C(dt("msgHash",_));if(L==null||![0,1,2,3].includes(L))throw new Error("recovery id invalid");const V=L===2||L===3?U+t.n:U;if(V>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const W=(L&1)===0?"02":"03",le=u.fromHex(W+h(V)),ce=c(V),ne=a(-M*ce),pe=a(j*ce),ge=u.BASE.multiplyAndAddUnsafe(le,ne,pe);if(!ge)throw new Error("point at infinify");return ge.assertValidity(),ge}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Pr(this.toDERHex())}toDERHex(){return Mn.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Pr(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}const v={isValidPrivateKey(b){try{return l(b),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const b=t.randomBytes(n.BYTES+8),_=om(b,r);return $r(_,t.nByteLength)},precompute(b=8,_=u.BASE){return _._setWindowSize(b),_.multiply(BigInt(3)),_}};function m(b,_=!0){return u.fromPrivateKey(b).toRawBytes(_)}function x(b){const _=b instanceof Uint8Array,U=typeof b=="string",j=(_||U)&&b.length;return _?j===s||j===o:U?j===2*s||j===2*o:b instanceof u}function k(b,_,U=!0){if(x(b))throw new Error("first arg must be private key");if(!x(_))throw new Error("second arg must be public key");return u.fromHex(_).multiply(l(b)).toRawBytes(U)}const I=t.bits2int||function(b){const _=$n(b),U=b.length*8-t.nBitLength;return U>0?_>>BigInt(U):_},C=t.bits2int_modN||function(b){return a(I(b))},N=rc(t.nBitLength);function O(b){if(typeof b!="bigint")throw new Error("bigint expected");if(!(xt<=b&&bde in U))throw new Error("sign() legacy options not supported");const{hash:j,randomBytes:L}=t;let{lowS:M,prehash:V,extraEntropy:W}=U;M==null&&(M=!0),b=dt("msgHash",b),V&&(b=dt("prehashed msgHash",j(b)));const le=C(b),ce=l(_),ne=[O(ce),O(le)];if(W!=null){const de=W===!0?L(n.BYTES):W;ne.push(dt("extraEntropy",de,n.BYTES))}const pe=bt(...ne),ge=le;function Ne(de){const ve=I(de);if(!d(ve))return;const Mt=c(ve),lt=u.BASE.multiply(ve).toAffine(),qe=a(lt.x);if(qe===xt)return;const Zt=a(Mt*a(ge+qe*ce));if(Zt===xt)return;let es=(lt.x===qe?0:2)|Number(lt.y&je),$u=Zt;return M&&g(Zt)&&($u=p(Zt),es^=1),new y(qe,$u,es)}return{seed:pe,k2sig:Ne}}const A={lowS:t.lowS,prehash:!1},P={lowS:t.lowS,prehash:!1};function E(b,_,U=A){const{seed:j,k2sig:L}=R(b,_,U);return pf(t.hash.outputLen,t.nByteLength,t.hmac)(j,L)}u.BASE._setWindowSize(8);function S(b,_,U,j=P){var lt;const L=b;if(_=dt("msgHash",_),U=dt("publicKey",U),"strict"in j)throw new Error("options.strict was renamed to lowS");const{lowS:M,prehash:V}=j;let W,le;try{if(typeof L=="string"||L instanceof Uint8Array)try{W=y.fromDER(L)}catch(qe){if(!(qe instanceof Mn.Err))throw qe;W=y.fromCompact(L)}else if(typeof L=="object"&&typeof L.r=="bigint"&&typeof L.s=="bigint"){const{r:qe,s:Zt}=L;W=new y(qe,Zt)}else throw new Error("PARSE");le=u.fromHex(U)}catch(qe){if(qe.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(M&&W.hasHighS())return!1;V&&(_=t.hash(_));const{r:ce,s:ne}=W,pe=C(_),ge=c(ne),Ne=a(pe*ge),de=a(ce*ge),ve=(lt=u.BASE.multiplyAndAddUnsafe(le,Ne,de))==null?void 0:lt.toAffine();return ve?a(ve.x)===ce:!1}return{CURVE:t,getPublicKey:m,getSharedSecret:k,sign:E,verify:S,ProjectivePoint:u,Signature:y,utils:v}}function pm(e,t){const n=e.ORDER;let r=xt;for(let d=n-je;d%Vt===xt;d/=Vt)r+=je;const s=r,o=(n-je)/Vt**s,i=(o-je)/Vt,a=Vt**s-je,c=Vt**(s-je),u=e.pow(t,o),l=e.pow(t,(o+je)/Vt);let f=(d,h)=>{let g=u,p=e.pow(h,a),w=e.sqr(p);w=e.mul(w,h);let y=e.mul(d,w);y=e.pow(y,i),y=e.mul(y,p),p=e.mul(y,h),w=e.mul(y,d);let v=e.mul(w,p);y=e.pow(v,c);let m=e.eql(y,e.ONE);p=e.mul(w,l),y=e.mul(v,g),w=e.cmov(p,w,m),v=e.cmov(y,v,m);for(let x=s;x>1;x--){let k=Vt**(x-Vt),I=e.pow(v,k);const C=e.eql(I,e.ONE);p=e.mul(w,g),g=e.mul(g,g),I=e.mul(v,g),w=e.cmov(p,w,C),v=e.cmov(I,v,C)}return{isValid:m,value:w}};if(e.ORDER%Ou===Eo){const d=(e.ORDER-Eo)/Ou,h=e.sqrt(e.neg(t));f=(g,p)=>{let w=e.sqr(p);const y=e.mul(g,p);w=e.mul(w,y);let v=e.pow(w,d);v=e.mul(v,y);const m=e.mul(v,h),x=e.mul(e.sqr(v),p),k=e.eql(x,g);let I=e.cmov(m,v,k);return{isValid:k,value:I}}}return f}function gm(e,t){if(gf(e),!e.isValid(t.A)||!e.isValid(t.B)||!e.isValid(t.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");const n=pm(e,t.Z);if(!e.isOdd)throw new Error("Fp.isOdd is not implemented!");return r=>{let s,o,i,a,c,u,l,f;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),l=e.mul(s,i);const{isValid:d,value:h}=n(o,u);f=e.mul(s,r),f=e.mul(f,h),l=e.cmov(l,i,d),f=e.cmov(f,h,d);const g=e.isOdd(r)===e.isOdd(f);return f=e.cmov(e.neg(f),f,g),l=e.div(l,a),{x:l,y:f}}}function mm(e){if(e instanceof Uint8Array)return e;if(typeof e=="string")return oi(e);throw new Error("DST must be Uint8Array or string")}const ym=$n;function xn(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 wm(e,t){const n=new Uint8Array(e.length);for(let r=0;r255&&(t=r(bt(oi("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=bt(t,xn(t.length,1)),c=xn(0,o),u=xn(n,2),l=new Array(i),f=r(bt(c,e,u,xn(0,1),a));l[0]=r(bt(f,xn(1,1),a));for(let h=1;h<=i;h++){const g=[wm(f,l[h-1]),xn(h+1,1),a];l[h]=r(bt(...g))}return bt(...l).slice(0,n)}function xm(e,t,n,r,s){if(hs(e),hs(t),oc(n),t.length>255){const o=Math.ceil(2*r/8);t=s.create({dkLen:o}).update(oi("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(xn(n,2)).update(t).update(xn(t.length,1)).digest()}function Cu(e,t,n){Fr(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;hs(e),oc(t);const u=mm(c),l=r.toString(2).length,f=Math.ceil((l+s)/8),d=t*o*f;let h;if(a==="xmd")h=bm(e,u,d,i);else if(a==="xof")h=xm(e,u,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(u=>u.reduce((l,f)=>e.add(e.mul(l,r),f)));return r=e.div(o,i),s=e.mul(s,e.div(a,c)),{x:r,y:s}}}function km(e,t,n){if(typeof t!="function")throw new Error("mapToCurve() must be defined");return{hashToCurve(r,s){const o=Cu(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=Cu(r,1,{...n,DST:n.encodeDST,...s}),i=e.fromAffine(t(o[0])).clearCofactor();return i.assertValidity(),i}}}let wf=class extends cf{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Dn.hash(t);const r=Qa(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 wf(e,t).update(n).digest();bf.create=(e,t)=>new wf(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Em(e){return{hash:e,hmac:(t,...n)=>bf(e,t,Ug(...n)),randomBytes:Ng}}function $m(e,t){const n=r=>hm({...e,...Em(r)});return Object.freeze({...n(t),create:n})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const xf=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Pu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Sm=BigInt(1),pa=BigInt(2),Uu=(e,t)=>(e+t/pa)/t;function _m(e){const t=xf,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,l=u*u*e%t,f=ft(l,n,t)*l%t,d=ft(f,n,t)*l%t,h=ft(d,pa,t)*u%t,g=ft(h,s,t)*h%t,p=ft(g,o,t)*g%t,w=ft(p,a,t)*p%t,y=ft(w,c,t)*w%t,v=ft(y,a,t)*p%t,m=ft(v,n,t)*l%t,x=ft(m,i,t)*g%t,k=ft(x,r,t)*u%t,I=ft(k,pa,t);if(!Sn.eql(Sn.sqr(I),e))throw new Error("Cannot find square root");return I}const Sn=mf(xf,void 0,void 0,{sqrt:_m}),Jt=$m({a:BigInt(0),b:BigInt(7),Fp:Sn,n:Pu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Pu,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Sm*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=n,i=BigInt("0x100000000000000000000000000000000"),a=Uu(o*e,t),c=Uu(-r*e,t);let u=Ye(e-a*n-c*s,t),l=Ye(-a*r-c*o,t);const f=u>i,d=l>i;if(f&&(u=t-u),d&&(l=t-l),u>i||l>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:f,k1:u,k2neg:d,k2:l}}}},ff);BigInt(0);Jt.ProjectivePoint;Jt.utils.randomPrivateKey;const Am=vm(Sn,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),Bm=gm(Sn,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:Sn.create(BigInt("-11"))});km(Jt.ProjectivePoint,e=>{const{x:t,y:n}=Bm(Sn.create(e[0]));return Am(t,n)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:Sn.ORDER,m:1,k:128,expand:"xmd",hash:ff});function ga(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function Tm(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function vf(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 Im(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ga(e.outputLen),ga(e.blockLen)}function Om(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 Cm(e,t){vf(e);const n=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),Ot=(e,t)=>e<<32-t|e>>>t,Um=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Um)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Nm(e){if(typeof e!="string")throw new TypeError(`utf8ToBytes expected string, got ${typeof e}`);return new TextEncoder().encode(e)}function kf(e){if(typeof e=="string"&&(e=Nm(e)),!(e instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof e})`);return e}let Lm=class{clone(){return this._cloneInto()}};function Ef(e){const t=r=>e().update(kf(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Hm(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 Rm=class extends Lm{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=Ri(this.buffer)}update(t){Hi.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=kf(t);const o=t.length;for(let i=0;is-i&&(this.process(r,0),i=0);for(let f=i;fl.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;fe&t^~e&n,Km=(e,t,n)=>e&t^e&n^t&n,Dm=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]),un=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ln=new Uint32Array(64);let $f=class extends Rm{constructor(){super(64,32,8,!1),this.A=un[0]|0,this.B=un[1]|0,this.C=un[2]|0,this.D=un[3]|0,this.E=un[4]|0,this.F=un[5]|0,this.G=un[6]|0,this.H=un[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 f=0;f<16;f++,n+=4)ln[f]=t.getUint32(n,!1);for(let f=16;f<64;f++){const d=ln[f-15],h=ln[f-2],g=Ot(d,7)^Ot(d,18)^d>>>3,p=Ot(h,17)^Ot(h,19)^h>>>10;ln[f]=p+ln[f-7]+g+ln[f-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const d=Ot(a,6)^Ot(a,11)^Ot(a,25),h=l+d+jm(a,c,u)+Dm[f]+ln[f]|0,p=(Ot(r,2)^Ot(r,13)^Ot(r,22))+Km(r,s,o)|0;l=u,u=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,u=u+this.G|0,l=l+this.H|0,this.set(r,s,o,i,a,c,u,l)}roundClean(){ln.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},Mm=class extends $f{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 ma=Ef(()=>new $f);Ef(()=>new Mm);function Zm(e,t){if(e.length>t)throw new TypeError(`Data is larger than array size: ${e.length} > ${t}`)}function Vm(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 qm(e){if(e>Number.MAX_SAFE_INTEGER)throw new TypeError("Number exceeds safe bounds!")}const{getRandomValues:zm}=crypto??globalThis.crypto??window.crypto;function Fm(e=32){if(typeof zm=="function")return crypto.getRandomValues(new Uint8Array(e));throw new Error("Crypto module missing getRandomValues!")}function Wm(e,t,n="be"){t===void 0&&(t=e.length),Zm(e,t);const r=new Uint8Array(t).fill(0),s=n==="be"?0:t-e.length;return r.set(e,s),r}function Sf(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;)l=o[c],l=l>0?l*256+u:u,u=l/s|0,o[c]=l%s,c++;for(;c-- >0;)i+=r[o[c]];return n&&i.length%4>0?i+"=".repeat(4-i.length%4):i}function Jm(e,t){const n=_f(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 Af(e){return ma(ma(e))}function Qm(e){const t=Af(e);return Sf([e,t.slice(0,4)])}function ey(e){const t=e.slice(0,-4),n=e.slice(-4);if(Af(t).slice(0,4).toString()!==n.toString())throw new Error("Invalid checksum!");return t}const Nu={encode:Xm,decode:Jm},Bf={encode:e=>{const t=Qm(e);return Nu.encode(t,"base58")},decode:e=>{const t=Nu.decode(e,"base58");return ey(t)}},Tf="qpzry9x8gf2tvdw0s3jn54khce6mua7l",ty=[996825010,642813549,513874426,1027748829,705979059],$o=[{version:0,name:"bech32",const:1},{version:1,name:"bech32m",const:734539939}];function If(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^=ty[s])}return t}function Of(e){const t=[];let n;for(n=0;n>5);for(t.push(0),n=0;n>5*(5-i)&31);return o}function Cf(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 sy(e,t,n){const r=t.concat(ry(e,t,n));let s=e+"1";for(let o=0;oo.version===t[0])??$o[0];if(!ny(r,t,s))throw new Error("Checksum verification failed!");return[r,t.slice(0,t.length-6)]}function oy(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 iy(e){const t=e.lastIndexOf("1");return!(t<1||t+7>e.length||e.length>90)}function ay(e,t="bc",n=0){const r=[n,...Cf([...e],8,5)],s=$o.find(i=>i.version===n)??$o[0],o=sy(t,r,s);return Uf(o),o}function Uf(e){e=e.toLowerCase();const t=e.split("1",1)[0],[n,r]=Pf(e),s=Cf(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 cy(e){e=e.toLowerCase();const[t,n]=Pf(e);return n[0]}const Nf={encode:ay,decode:Uf,version:cy},Lf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Hf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",uy=new TextEncoder;function Rf(e,t=!1,n=!0){typeof e=="string"&&(e=uy.encode(e));const r=t?Hf:Lf;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 jf(e,t=!1){const n=t||e.includes("-")||e.includes("_")?Hf.split(""):Lf.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 Kf={encode:Rf,decode:jf},Df={encode:e=>Rf(e,!0,!1),decode:e=>jf(e,!0)},ly=BigInt(0),fy=BigInt(255),Mf=BigInt(256);function dy(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 hy(e,t,n="be"){t===void 0&&(t=dy(e));const r=n==="le",s=new ArrayBuffer(t),o=new DataView(s);let i=r?0:t-1;for(;e>ly;){const a=e&fy,c=Number(a);r?o.setUint8(i++,c):o.setUint8(i--,c),e=(e-a)/Mf}return new Uint8Array(s)}function py(e){let t=BigInt(0);for(let n=e.length-1;n>=0;n--)t=t*Mf+BigInt(e[n]);return BigInt(t)}function gy(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 yy(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 wy(e,t,n="be"){t===void 0&&(t=yy(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 by(e){let t=0;for(let n=e.length-1;n>=0;n--)t=t*256+e[n],qm(t);return t}const xy=new TextEncoder,vy=new TextDecoder;function ic(e){return xy.encode(e)}function ji(e){return vy.decode(e)}function ky(e,t){Vm(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 Ey(e,t,n="le"){t=ky(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 ic(t)}function _y(e,t,n){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Uint8Array)return Wm(e,t,n);if(typeof e=="string")return Ey(e,t,n);if(typeof e=="bigint")return hy(e,t,n);if(typeof e=="number")return wy(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=Fm(t);return new ie(n,t)}constructor(t,n,r){const s=_y(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 jy(this)}toNum(t="be"){const n=t==="be"?this.reverse():this;return by(n)}toBin(){return my(this)}toBig(t="be"){const n=t==="be"?this.reverse():this;return py(n)}toHash(){const t=ma(this);return new ie(t)}toJson(){const t=ji(this);return JSON.parse(t)}toBech32(t,n=0){return Nf.encode(this,t,n)}toStr(){return ji(this)}toHex(){return $y(this)}toBytes(){return new Uint8Array(this)}tob58chk(){return Bf.encode(this)}toBase64(){return Kf.encode(this)}toB64url(){return Df.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=Sf(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=Ay,ie.big=Ty,ie.bin=By,ie.raw=Iy,ie.str=Oy,ie.hex=Cy,ie.bytes=Py,ie.json=Uy,ie.base64=Ny,ie.b64url=Ly,ie.bech32=Hy,ie.b58chk=Ry,ie.encode=ic,ie.decode=ji;let Q=ie;function Ay(e,t,n){return new Q(e,t,n)}function By(e,t,n){return new Q(gy(e),t,n)}function Ty(e,t,n){return new Q(e,t,n)}function Iy(e,t,n){return new Q(e,t,n)}function Oy(e,t,n){return new Q(ic(e),t,n)}function Cy(e,t,n){return new Q(e,t,n)}function Py(e,t,n){return new Q(e,t,n)}function Uy(e){return new Q(Sy(e))}function Ny(e){return new Q(Kf.decode(e))}function Ly(e){return new Q(Df.decode(e))}function Hy(e){return new Q(Nf.decode(e))}function Ry(e){return new Q(Bf.decode(e))}class jy{constructor(t){this.data=Q.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 Q(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 So=Jt.CURVE,ac=So.n,Ky=So.p,Dy={x:So.Gx,y:So.Gy},My=BigInt(0);BigInt(1);BigInt(2);BigInt(3);BigInt(4);const ya={N:ac,P:Ky,G:Dy,_0n:My},ts=mf(ac,32,!0),Zf=e=>Ye(e,ac);function cc(e,t=!1){if(t)throw new Error(e);return!1}function Vf(e){return Q.random(e)}function Zy(e){const t=Q.bytes(e).big;return Q.big(Zf(t),32)}var Vy=Object.freeze({__proto__:null,fail:cc,mod_bytes:Zy,random:Vf});const{N:qy,_0n:zy}=ya;function Fy(e,t,n){const r=Q.bytes(e);return r.length!==t?cc(`Invalid byte size: ${r.hex} !== ${t}`,n):!0}function Wy(e,t){return typeof e=="bigint"&&zythis.big}lt(t){return new $e(t).big0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function Jy(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");wa(e.outputLen),wa(e.blockLen)}function Qy(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 ew(e,t){qf(e);const n=t.outputLen;if(e.lengthe instanceof Uint8Array,Ki=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),Ct=(e,t)=>e<<32-t|e>>>t,rw=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!rw)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function sw(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function uc(e){if(typeof e=="string"&&(e=sw(e)),!nw(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}let zf=class{clone(){return this._cloneInto()}};function lr(e){const t=r=>e().update(uc(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function ow(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 lc extends zf{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=Ki(this.buffer)}update(t){Zn.exists(this);const{view:n,buffer:r,blockLen:s}=this;t=uc(t);const o=t.length;for(let i=0;is-i&&(this.process(r,0),i=0);for(let f=i;fl.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;fe&t^~e&n,aw=(e,t,n)=>e&t^e&n^t&n,cw=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 Ff=class extends lc{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 f=0;f<16;f++,n+=4)dn[f]=t.getUint32(n,!1);for(let f=16;f<64;f++){const d=dn[f-15],h=dn[f-2],g=Ct(d,7)^Ct(d,18)^d>>>3,p=Ct(h,17)^Ct(h,19)^h>>>10;dn[f]=p+dn[f-7]+g+dn[f-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const d=Ct(a,6)^Ct(a,11)^Ct(a,25),h=l+d+iw(a,c,u)+cw[f]+dn[f]|0,p=(Ct(r,2)^Ct(r,13)^Ct(r,22))+aw(r,s,o)|0;l=u,u=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,u=u+this.G|0,l=l+this.H|0,this.set(r,s,o,i,a,c,u,l)}roundClean(){dn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};class uw extends Ff{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 _o=lr(()=>new Ff);lr(()=>new uw);const zs=BigInt(2**32-1),ba=BigInt(32);function Wf(e,t=!1){return t?{h:Number(e&zs),l:Number(e>>ba&zs)}:{h:Number(e>>ba&zs)|0,l:Number(e&zs)|0}}function lw(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let s=0;sBigInt(e>>>0)<>>0),dw=(e,t,n)=>e>>>n,hw=(e,t,n)=>e<<32-n|t>>>n,pw=(e,t,n)=>e>>>n|t<<32-n,gw=(e,t,n)=>e<<32-n|t>>>n,mw=(e,t,n)=>e<<64-n|t>>>n-32,yw=(e,t,n)=>e>>>n-32|t<<64-n,ww=(e,t)=>t,bw=(e,t)=>e,xw=(e,t,n)=>e<>>32-n,vw=(e,t,n)=>t<>>32-n,kw=(e,t,n)=>t<>>64-n,Ew=(e,t,n)=>e<>>64-n;function $w(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}const Sw=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),_w=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Aw=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Bw=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,Tw=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Iw=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,Ow={fromBig:Wf,split:lw,toBig:fw,shrSH:dw,shrSL:hw,rotrSH:pw,rotrSL:gw,rotrBH:mw,rotrBL:yw,rotr32H:ww,rotr32L:bw,rotlSH:xw,rotlSL:vw,rotlBH:kw,rotlBL:Ew,add:$w,add3L:Sw,add3H:_w,add4L:Aw,add4H:Bw,add5H:Iw,add5L:Tw};var oe=Ow;const[Cw,Pw]=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))),hn=new Uint32Array(80),pn=new Uint32Array(80);let ii=class extends lc{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:l,Fh:f,Fl:d,Gh:h,Gl:g,Hh:p,Hl:w}=this;return[t,n,r,s,o,i,a,c,u,l,f,d,h,g,p,w]}set(t,n,r,s,o,i,a,c,u,l,f,d,h,g,p,w){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=l|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=g|0,this.Hh=p|0,this.Hl=w|0}process(t,n){for(let m=0;m<16;m++,n+=4)hn[m]=t.getUint32(n),pn[m]=t.getUint32(n+=4);for(let m=16;m<80;m++){const x=hn[m-15]|0,k=pn[m-15]|0,I=oe.rotrSH(x,k,1)^oe.rotrSH(x,k,8)^oe.shrSH(x,k,7),C=oe.rotrSL(x,k,1)^oe.rotrSL(x,k,8)^oe.shrSL(x,k,7),N=hn[m-2]|0,O=pn[m-2]|0,R=oe.rotrSH(N,O,19)^oe.rotrBH(N,O,61)^oe.shrSH(N,O,6),A=oe.rotrSL(N,O,19)^oe.rotrBL(N,O,61)^oe.shrSL(N,O,6),P=oe.add4L(C,A,pn[m-7],pn[m-16]),E=oe.add4H(P,I,R,hn[m-7],hn[m-16]);hn[m]=E|0,pn[m]=P|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:g,Gh:p,Gl:w,Hh:y,Hl:v}=this;for(let m=0;m<80;m++){const x=oe.rotrSH(f,d,14)^oe.rotrSH(f,d,18)^oe.rotrBH(f,d,41),k=oe.rotrSL(f,d,14)^oe.rotrSL(f,d,18)^oe.rotrBL(f,d,41),I=f&h^~f&p,C=d&g^~d&w,N=oe.add5L(v,k,C,Pw[m],pn[m]),O=oe.add5H(N,y,x,I,Cw[m],hn[m]),R=N|0,A=oe.rotrSH(r,s,28)^oe.rotrBH(r,s,34)^oe.rotrBH(r,s,39),P=oe.rotrSL(r,s,28)^oe.rotrBL(r,s,34)^oe.rotrBL(r,s,39),E=r&o^r&a^o&a,S=s&i^s&c^i&c;y=p|0,v=w|0,p=h|0,w=g|0,h=f|0,g=d|0,{h:f,l:d}=oe.add(u|0,l|0,O|0,R|0),u=a|0,l=c|0,a=o|0,c=i|0,o=r|0,i=s|0;const b=oe.add3L(R,P,S);r=oe.add3H(b,O,A,E),s=b|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}=oe.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=oe.add(this.Eh|0,this.El|0,f|0,d|0),{h,l:g}=oe.add(this.Fh|0,this.Fl|0,h|0,g|0),{h:p,l:w}=oe.add(this.Gh|0,this.Gl|0,p|0,w|0),{h:y,l:v}=oe.add(this.Hh|0,this.Hl|0,y|0,v|0),this.set(r,s,o,i,a,c,u,l,f,d,h,g,p,w,y,v)}roundClean(){hn.fill(0),pn.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 Uw extends ii{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 Nw extends ii{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 Lw extends ii{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 Hw=lr(()=>new ii);lr(()=>new Uw);lr(()=>new Nw);lr(()=>new Lw);const Rw=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Gf=Uint8Array.from({length:16},(e,t)=>t),jw=Gf.map(e=>(9*e+5)%16);let fc=[Gf],dc=[jw];for(let e=0;e<4;e++)for(let t of[fc,dc])t.push(t[e].map(n=>Rw[n]));const Yf=[[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)),Kw=fc.map((e,t)=>e.map(n=>Yf[t][n])),Dw=dc.map((e,t)=>e.map(n=>Yf[t][n])),Mw=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Zw=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),Fs=(e,t)=>e<>>32-t;function Hu(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 Ws=new Uint32Array(16);let Vw=class extends lc{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)Ws[h]=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,l=u,f=this.h4|0,d=f;for(let h=0;h<5;h++){const g=4-h,p=Mw[h],w=Zw[h],y=fc[h],v=dc[h],m=Kw[h],x=Dw[h];for(let k=0;k<16;k++){const I=Fs(r+Hu(h,o,a,u)+Ws[y[k]]+p,m[k])+f|0;r=f,f=u,u=Fs(a,10)|0,a=o,o=I}for(let k=0;k<16;k++){const I=Fs(s+Hu(g,i,c,l)+Ws[v[k]]+w,x[k])+d|0;s=d,d=l,l=Fs(c,10)|0,c=i,i=I}}this.set(this.h1+a+l|0,this.h2+u+d|0,this.h3+f+s|0,this.h4+r+i|0,this.h0+o+c|0)}roundClean(){Ws.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}};const qw=lr(()=>new Vw);let Xf=class extends zf{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Zn.hash(t);const r=uc(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 Xf(e,t).update(n).digest();Jf.create=(e,t)=>new Xf(e,t);function zw(e){const t=Q.bytes(e);return Q.raw(_o(t))}function Ur(e){const t=Q.bytes(e);return Q.raw(_o(_o(t)))}function hc(e){const t=Q.bytes(e);return Q.raw(qw(_o(t)))}function Fw(e,t){const n=Q.bytes(e),r=Q.bytes(t);return Q.raw(Jf(Hw,n,r))}function Ww(e){const t=Q.str(e).digest;return Q.join([t,t])}function Gw(e=32){return pc(Vf(e))}function pc(e){return tt.mod(e).buff}function Qf(e,t=!1){const n=tt.mod(e).point;return t?n.x:n.buff}function ed(e,t){const n=ur.from_x(t),r=tt.mod(e);return n.mul(r).buff}function Yw(e,t,n="ecdh/code"){const r=Ww(n),s=pc(e),o=Qf(s),i=Q.bytes(t),a=ed(s,i),c=[o.hex,i.hex];return c.sort(),Fw(a,Q.join([r,...c]))}function Xw(e){const t=Q.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 Jw(e){const t=Q.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 Qw=Object.freeze({__proto__:null,genSecretKey:Gw,getPublicKey:Qf,getSecretKey:pc,getSharedCode:Yw,getSharedKey:ed,is_even_pub:Xw,xonly_pub:Jw});Q.random(32);const td={secp:Jt},xa={...Qw,...Vy};function ai(e){const t=B.bytes(e);return Dt(t,33),hc(t)}function nd(e){const t=Ue.fmt.toBytes(e,!1);return hc(t)}function rd(e){const t=Ue.fmt.toBytes(e,!1);return zw(t)}function sd(e,t="main"){const n=t==="main"?["1"]:["m","n"];for(const r of n)if(e.startsWith(r))return!0;return!1}function od(e,t="main"){const n=B.bytes(e),r=t==="main"?B.num(0):B.num(111);return Dt(e,20),n.prepend(r).tob58chk()}function eb(e,t="main"){if(!sd(e,t))throw new TypeError("Invalid p2pkh address!");return B.b58chk(e).slice(1)}function tb(e){const t=B.bytes(e);return Dt(t,20),["OP_DUP","OP_HASH160",t.hex,"OP_EQUALVERIFY","OP_CHECKSIG"]}function nb(e,t){const n=ai(e);return od(n,t)}const id={check:sd,encode:od,decode:eb,hash:ai,scriptPubKey:tb,fromPubKey:nb};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 cd(e,t="main"){const n=t==="main"?B.num(5):B.num(196),r=B.bytes(e);return Dt(r,20),r.prepend(n).tob58chk()}function rb(e,t="main"){if(!ad(e,t))throw new TypeError(`Invalid p2sh address for network ${t}:`+e);return B.b58chk(e).slice(1)}function sb(e){return["OP_HASH160",B.bytes(e).hex,"OP_EQUAL"]}function ob(e,t){const n=nd(e);return cd(n,t)}const ud={check:ad,encode:cd,decode:rb,hash:nd,scriptPubKey:sb,fromScript:ob},gc={main:"bc",testnet:"tb",signet:"tb",regtest:"bcrt"},ib=["bc1q","tb1q","bcrt1q"];function ld(e){for(const t of ib)if(e.startsWith(t))return!0;return!1}function fd(e,t="main"){const n=gc[t],r=B.bytes(e);return Dt(r,20),r.toBech32(n,0)}function ab(e){if(!ld(e))throw new TypeError("Invalid segwit address!");return B.bech32(e)}function cb(e){const t=B.bytes(e);return Dt(t,20),["OP_0",t.hex]}function ub(e,t){const n=ai(e);return fd(n,t)}const dd={check:ld,encode:fd,decode:ab,hash:ai,scriptPubKey:cb,fromPubKey:ub},lb=["bc1q","tb1q","bcrt1q"];function hd(e){for(const t of lb)if(e.startsWith(t))return!0;return!1}function pd(e,t="main"){const n=gc[t],r=B.bytes(e);return Dt(r,32),r.toBech32(n,0)}function fb(e){if(!hd(e))throw new TypeError("Invalid segwit address!");return B.bech32(e)}function db(e){const t=B.bytes(e);return Dt(t,32),["OP_0",t.hex]}function hb(e,t){const n=rd(e);return pd(n,t)}const gd={check:hd,encode:pd,decode:fb,hash:rd,scriptPubKey:db,fromScript:hb};function Yn(e){const t=B.bytes(e);return t.length>32?t.slice(1,33):t}const pb=["bc1p","tb1p","bcrt1p"];function md(e){for(const t of pb)if(e.startsWith(t))return!0;return!1}function yd(e,t="main"){const n=gc[t],r=B.bytes(e);return Dt(r,32),r.toBech32(n,1)}function gb(e){if(!md(e))throw new TypeError("Invalid taproot address!");return B.bech32(e)}function mb(e){const t=B.bytes(e);return Dt(t,32),["OP_1",t.hex]}function yb(e,t){const n=Yn(e);return yd(n,t)}const wd={check:md,encode:yd,decode:gb,scriptPubKey:mb,fromPubKey:yb},wb={version:2,vin:[],vout:[],locktime:0},bb={scriptSig:[],sequence:4294967293,witness:[]},xb={value:0n,scriptPubKey:[]};function mc(e){const t={...wb,...e};return t.vin=t.vin.map(n=>({...bb,...n})),t.vout=t.vout.map(n=>({...xb,...n})),t}function Nr(e,t){const{version:n,vin:r,vout:s,locktime:o}=mc(e),i=t!==!0&&vb(r),a=[yc(n)];i&&a.push(B.hex("0001")),a.push(kb(r)),a.push(Eb(s));for(const c of r)i&&a.push(Sb(c.witness));return a.push(wc(o)),B.join(a)}function vb(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 yc(e){return B.num(e,4).reverse()}function Cs(e){return B.hex(e,32).reverse()}function Ps(e){return B.num(e,4).reverse()}function Us(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 kb(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(Cs(r)),t.push(Ps(s)),t.push(cr(o,!0)),t.push(Us(i))}return B.join(t)}function _n(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 Eb(e){const t=[B.varInt(e.length,"le")];for(const n of e)t.push($b(n));return B.join(t)}function $b(e){const{value:t,scriptPubKey:n}=e,r=[];return r.push(_n(t)),r.push(cr(n,!0)),B.join(r)}function Sb(e=[]){const t=[];if(Array.isArray(e)){const n=B.varInt(e.length);t.push(n);for(const r of e)t.push(_b(r));return B.join(t)}else return B.bytes(e)}function _b(e){return Ab(e)?new B(0):cr(e,!0)}function Ab(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 wc(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 bc(e){typeof e=="string"&&(e=B.hex(e).raw);const t=new zr(e),n=Bb(t),r=Tb(t),s=Ib(t),o=Cb(t);if(r)for(const a of s)a.witness=Ub(t);const i=Nb(t);return{version:n,vin:s,vout:o,locktime:i}}function Bb(e){return e.read(4).reverse().toNum()}function Tb(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 Ib(e){const t=[],n=e.readSize("le");for(let r=0;r0?e.read(n).hex:null}function xd(e,t){const n=bd(e);return n!==null?n:[]}function Nb(e){return e.read(4).reverse().toNum()}function Lb(e){if(sf(e))return bc(e);if(typeof e=="object"&&!(e instanceof Uint8Array))return Nr(e),mc(e);throw new Error("Invalid format: "+typeof e)}function Hb(e){if(sf(e))return bc(e),B.bytes(e);if(typeof e=="object")return Nr(e);throw new Error("Invalid format: "+typeof e)}const xc={toBytes:Hb,toJson:Lb},Rb=[["p2pkh",/^76a914(?\w{40})88ac$/],["p2sh",/^a914(?\w{40})87$/],["p2w-pkh",/^0014(?\w{40})$/],["p2w-sh",/^0020(?\w{64})$/],["p2tr",/^5120(?\w{64})$/]],jb=[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 Kb(e){let t=e.at(-1);return tn(t)&&(t=B.hex(t)),e.length>1&&t instanceof Uint8Array&&t[0]===80?(e.pop(),B.raw(t)):null}function Db(e){let t=e.at(-1);return tn(t)&&(t=B.hex(t)),e.length>1&&t instanceof Uint8Array&&t.length>32&&jb.includes(t[0]&254)?(e.pop(),B.raw(t)):null}function Mb(e){if(e.length>1){const t=e.at(-1);try{const n=Ue.fmt.toBytes(t);return e.pop(),n}catch{return null}}return null}function Zb(e){const t=[];for(const n of e)if(tn(n)||n instanceof Uint8Array||typeof n=="number")t.push(B.bytes(n));else throw new Error("unrecognized value: "+String(n));return t}function Vb(e=[]){const t=[...e],n=Kb(t),r=Db(t),s=Mb(t),o=Zb(t);return{annex:n,cblock:r,script:s,params:o}}function qb(e){const t=Ue.fmt.toBytes(e,!1).hex;for(const[n,r]of Rb){const s=n,{groups:o}=r.exec(t)??{},{hash:i}=o??{};if(tn(i))return{type:s,data:B.hex(i)}}return{type:"raw",data:B.hex(t)}}function zb(e){const t=xc.toJson(e),n=Nr(t,!0);return Ur(n).reverse().hex}function Fb(e){const t=xc.toJson(e),n=Nr(t,!0).length,r=Nr(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 ee={create:mc,encode:Nr,decode:bc,fmt:xc,util:{getTxSize:Fb,getTxid:zb,readScriptPubKey:qb,readWitness:Vb}},Wb=[["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 Gb(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 Yb(e){for(const t of Wb){const[n,r,s,o,i]=t;if(e.startsWith(n)&&Gb(e,i).length===o)return t}throw new Error("Invalid address: "+e)}function vd(e){switch(e){case"p2pkh":return id;case"p2sh":return ud;case"p2w-pkh":return dd;case"p2w-sh":return gd;case"p2tr":return wd;default:throw new Error("Invalid address type: "+e)}}function kd(e){const[t,n,r]=Yb(e),s=vd(n),o=s.decode(e,r),i=s.scriptPubKey(o);return{prefix:t,type:n,network:r,data:o,script:i}}function Xb(e,t){const{type:n,data:r}=ee.util.readScriptPubKey(e);return vd(n).encode(r,t)}function Jb(e){const{script:t}=kd(e);return Ue.fmt.toAsm(t,!1)}const ps={p2pkh:id,p2sh:ud,p2wpkh:dd,p2wsh:gd,p2tr:wd,decode:kd,fromScriptPubKey:Xb,toScriptPubKey:Jb},Qb=[1,2,3];function vc(e,t,n={}){const{sigflag:r=1}=n,s=(r&128)===128,o=r%128;if(!Qb.includes(o))throw new Error("Invalid hash type: "+String(r));const i=ee.fmt.toJson(e),{version:a,vin:c,vout:u,locktime:l}=i,{txid:f,vout:d,prevout:h,sequence:g}=c[t],{value:p}=h??{};if(p===void 0)throw new Error("Prevout value is empty!");let w=n.script;if(w===void 0&&n.pubkey!==void 0&&(w=`76a914${hc(n.pubkey).hex}88ac`),w===void 0)throw new Error("No pubkey / script has been set!");if(Ue.fmt.toAsm(w).includes("OP_CODESEPARATOR"))throw new Error("This library does not currently support the use of OP_CODESEPARATOR in segwit scripts.");const y=[yc(a),e1(c,s),t1(c,o,s),Cs(f),Ps(d),Ue.encode(w,!0),_n(p),Us(g),n1(u,t,o),wc(l),B.num(r,4).reverse()];return Ur(B.join(y))}function e1(e,t){if(t===!0)return B.num(0,32);const n=[];for(const{txid:r,vout:s}of e)n.push(Cs(r)),n.push(Ps(s));return Ur(B.join(n))}function t1(e,t,n){if(n||t!==1)return B.num(0,32);const r=[];for(const{sequence:s}of e)r.push(Us(s));return Ur(B.join(r))}function n1(e,t,n){const r=[];if(n===1){for(const{value:s,scriptPubKey:o}of e)r.push(_n(s)),r.push(Ue.encode(o,!0));return Ur(B.join(r))}if(n===3&&t1&&c[1].length===33)u=B.bytes(c[1]);else return Ge("No pubkey provided!",s);const l=Ue.fmt.toParam(c[0]),f=l.slice(0,-1),d=l.slice(-1)[0],h=vc(r,t,{...n,sigflag:d});return td.secp.verify(f,h,u)?!0:Ge("Invalid signature!",s)}const o1={hash:vc,sign:r1,verify:s1},i1=[0,1,2,3,129,130,131];function kc(e,t,n={}){const{extension:r,sigflag:s=0,extflag:o=0,key_version:i=0,separator_pos:a=4294967295}=n,c=ee.fmt.toJson(e),{version:u,vin:l,vout:f,locktime:d}=c;if(t>=l.length)throw new Error("Index out of bounds: "+String(t));if(!i1.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:w=[]}=l[t],y=(s&128)===128,v=h1(w),m=v!==void 0?1:0,k=(o+(r!==void 0?1:0))*2+m,I=B.str("TapSighash").digest,C=[I,I,B.num(0,1),B.num(s,1),yc(u),wc(d)];if(!y){const N=l.map(O=>Ru(O));C.push(a1(l),u1(N),l1(N),c1(l))}if(((s&3)<2||(s&3)>3)&&C.push(f1(f)),C.push(B.num(k,1)),y){const{value:N,scriptPubKey:O}=Ru(l[t]);C.push(Cs(h),Ps(g),_n(N),Ue.encode(O,!0),Us(p))}else C.push(B.num(t,4).reverse());return v!==void 0&&C.push(v),(s&3)===3&&C.push(d1(f[t])),r!==void 0&&C.push(B.bytes(r),B.num(i),B.num(a,4,"le")),B.join(C).digest}function a1(e){const t=[];for(const{txid:n,vout:r}of e)t.push(Cs(n)),t.push(Ps(r));return B.join(t).digest}function c1(e){const t=[];for(const{sequence:n}of e)t.push(Us(n));return B.join(t).digest}function u1(e){const t=[];for(const{value:n}of e)t.push(_n(n));return B.join(t).digest}function l1(e){const t=[];for(const{scriptPubKey:n}of e)t.push(cr(n,!0));return B.join(t).digest}function f1(e){const t=[];for(const{value:n,scriptPubKey:r}of e)t.push(_n(n)),t.push(Ue.encode(r,!0));return B.join(t).digest}function d1(e){return B.join([_n(e.value),Ue.encode(e.scriptPubKey,!0)]).digest}function h1(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 Ru(e){if(e.prevout===void 0)throw new Error("Prevout data missing for input: "+String(e.txid));return e.prevout}const p1=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,g1=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;function m1(e,t,n,r={}){const{sigflag:s=0}=r,o=kc(t,n,r),i=y1(e,o);return s===0?B.raw(i):B.join([i,s])}function y1(e,t,n=B.random(32)){const r=B.bytes(t),s=new tt(e),o=s.point,i=o.hasEvenY?s.big:s.negated.big,a=fo("BIP0340/aux",B.bytes(n)),c=i^a.big,u=fo("BIP0340/nonce",c,o.x.raw,r),l=new tt(u),f=l.point,d=f.hasEvenY?l.big:l.negated.big,h=new tt(fo("BIP0340/challenge",f.x.raw,o.x.raw,r)),g=new tt(d+h.big*i);return B.join([f.x.raw,g.raw])}function w1(e,t,n,r=!1){const s=ur.from_x(Yn(n)),o=B.bytes(t),i=B.bytes(e).stream;i.size<64&&Ge("Signature length is too small: "+String(i.size),r);const a=i.read(32);a.big>p1&&Ge("Signature r value greater than field size!",r);const c=i.read(32);c.big>g1&&Ge("Signature s value greater than curve order!",r);const u=new tt(fo("BIP0340/challenge",a.raw,s.x.raw,o)),l=new tt(c).point,f=s.mul(u.big),d=l.sub(f);return d.hasOddY&&Ge("Signature R value has odd Y coordinate!",r),d.x.big===0n&&Ge("Signature R value is infinite!",r),d.x.big===a.big}const b1=192;function ci(e){const t=B.str(e).digest;return B.join([t,t])}function Ec(e,t=b1){return B.join([ci("TapLeaf"),k1(t),B.bytes(e)]).digest.hex}function x1(e,t){return Ec(Ue.fmt.toBytes(e),t)}function $c(e,t){return t0){const[h,g,p]=Ao(r,i);c=p,a=Sr(e,h,n)}else i!==void 0?a=Sr(e,i,n):a=Sr(e,void 0,n);const u=n?xa.getPublicKey(a)[0]:a[0],f=[B.num(s+Bd(u)),o];c.length>0&&c.forEach(h=>f.push(B.hex(h)));const d=B.join(f);if(i!==void 0&&!Sc(a,i,d,t))throw new Error("Path checking failed! Unable to generate path.");return[Yn(a).hex,d.hex]}function Sc(e,t,n,r={}){const{isPrivate:s=!1,throws:o=!1}=r,{parity:i,paths:a,intkey:c}=Ad(n),u=s?xa.getPublicKey(e,!0):Yn(e),l=B.join([i,u]);if(l.length!==33)return Ge("Invalid tapkey: "+l.hex,o);let f=B.bytes(t).hex;for(const h of a)f=$c(f,h);const d=Sr(c,f);return B.raw(d).hex===B.raw(l).hex}function Ad(e){const t=new zr(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 Bd(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 I1(e,t,n={}){const r=ee.fmt.toJson(e),{throws:s=!1}=n,{prevout:o,witness:i=[]}=r.vin[t],a=ee.util.readWitness(i),{cblock:c,script:u,params:l}=a;let f;if(l.length<1)return Ge("Invalid witness data: "+String(i),s);const{scriptPubKey:d}=o??{};if(d===void 0)return Ge("Prevout scriptPubKey is empty!",s);const{type:h,data:g}=ee.util.readScriptPubKey(d);if(h!=="p2tr")return Ge("Prevout script is not a valid taproot output:"+g.hex,s);if(g.length!==32)return Ge("Invalid tapkey length: "+String(g.length),s);if(c!==null&&u!==null){const m=c[0]&254,x=Ec(u,m);if(n.extension=x,!Sc(g,x,c,{throws:s}))return Ge("cblock verification failed!",s)}n.pubkey!==void 0?f=B.bytes(n.pubkey):l.length>1&&l[1].length===32?f=B.bytes(l[1]):f=B.bytes(g);const p=Ue.fmt.toParam(l[0]),w=new zr(p),y=w.read(64).raw;if(w.size===1&&(n.sigflag=w.read(1).num,n.sigflag===0))return Ge("0x00 is not a valid appended sigflag!",s);const v=kc(r,t,n);return w1(y,v,f,s)?!0:Ge("Invalid signature!",s)}const O1={hash:kc,sign:m1,verify:I1},Xn={segwit:o1,taproot:O1},C1={getTag:ci,getLeaf:Ec,getBranch:$c,getRoot:v1},P1={readCtrlBlock:Ad,readParityBit:Bd},U1={getPubKey:E1,getSecKey:$1,getTweak:Ed,tweakSecKey:$d,tweakPubKey:Sd},ui={getPubKey:T1,getSecKey:B1,encodeScript:x1,checkPath:Sc,tree:C1,tweak:U1,util:P1,SCRIPT_PUBKEY:_1};var me;(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})(me||(me={}));var va;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(va||(va={}));const q=me.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vn=e=>{switch(typeof e){case"undefined":return q.undefined;case"string":return q.string;case"number":return isNaN(e)?q.nan:q.number;case"boolean":return q.boolean;case"function":return q.function;case"bigint":return q.bigint;case"symbol":return q.symbol;case"object":return Array.isArray(e)?q.array:e===null?q.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?q.promise:typeof Map<"u"&&e instanceof Map?q.map:typeof Set<"u"&&e instanceof Set?q.set:typeof Date<"u"&&e instanceof Date?q.date:q.object;default:return q.unknown}},D=me.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"]),N1=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class $t 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()}}$t.create=e=>new $t(e);const gs=(e,t)=>{let n;switch(e.code){case D.invalid_type:e.received===q.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case D.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,me.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:n=`Unrecognized key(s) in object: ${me.joinValues(e.keys,", ")}`;break;case D.invalid_union:n="Invalid input";break;case D.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${me.joinValues(e.options)}`;break;case D.invalid_enum_value:n=`Invalid enum value. Expected ${me.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}"`:me.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,me.assertNever(e)}return{message:n}};let Td=gs;function L1(e){Td=e}function Bo(){return Td}const To=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}},H1=[];function z(e,t){const n=To({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,Bo(),gs].filter(r=>!!r)});e.common.issues.push(n)}class Je{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 Je.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"}),Id=e=>({status:"dirty",value:e}),st=e=>({status:"valid",value:e}),ka=e=>e.status==="aborted",Ea=e=>e.status==="dirty",Io=e=>e.status==="valid",Oo=e=>typeof Promise<"u"&&e instanceof Promise;var Y;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Y||(Y={}));class Rt{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 ju=(e,t)=>{if(Io(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 $t(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 vn(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:vn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Je,ctx:{common:t.parent.common,data:t.data,parsedType:vn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Oo(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:vn(t)},o=this._parseSync({data:t,path:s.path,parent:s});return ju(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:vn(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(Oo(s)?s:Promise.resolve(s));return ju(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 At({schema:this,typeName:J.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Yt.create(this,this._def)}nullable(){return er.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return St.create(this,this._def)}promise(){return Hr.create(this,this._def)}or(t){return bs.create([this,t],this._def)}and(t){return xs.create(this,t,this._def)}transform(t){return new At({...se(this._def),schema:this,typeName:J.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Ss({...se(this._def),innerType:this,defaultValue:n,typeName:J.ZodDefault})}brand(){return new Cd({typeName:J.ZodBranded,type:this,...se(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new No({...se(this._def),innerType:this,catchValue:n,typeName:J.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Ns.create(this,t)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const R1=/^c[^\s-]{8,}$/i,j1=/^[a-z][a-z0-9]*$/,K1=/[0-9A-HJKMNP-TV-Z]{26}/,D1=/^([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,M1=/^(([^<>()[\]\\.,;:\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,})+))$/,Z1=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u"),V1=/^(((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}))$/,q1=/^(([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})))$/,z1=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 F1(e,t){return!!((t==="v4"||!t)&&V1.test(e)||(t==="v6"||!t)&&q1.test(e))}class kt extends ae{constructor(){super(...arguments),this._regex=(t,n,r)=>this.refinement(s=>t.test(s),{validation:n,code:D.invalid_string,...Y.errToObj(r)}),this.nonempty=t=>this.min(1,Y.errToObj(t)),this.trim=()=>new kt({...this._def,checks:[...this._def.checks,{kind:"trim"}]}),this.toLowerCase=()=>new kt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]}),this.toUpperCase=()=>new kt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==q.string){const o=this._getOrReturnCtx(t);return z(o,{code:D.invalid_type,expected:q.string,received:o.parsedType}),te}const r=new Je;let s;for(const o of this._def.checks)if(o.kind==="min")t.data.lengtho.value&&(s=this._getOrReturnCtx(t,s),z(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,...Y.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Y.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Y.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Y.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Y.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Y.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Y.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Y.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 kt({checks:[],typeName:J.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...se(e)})};function W1(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 An 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)!==q.number){const o=this._getOrReturnCtx(t);return z(o,{code:D.invalid_type,expected:q.number,received:o.parsedType}),te}let r;const s=new Je;for(const o of this._def.checks)o.kind==="int"?me.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),z(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),z(r,{code:D.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?W1(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),z(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),z(r,{code:D.not_finite,message:o.message}),s.dirty()):me.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Y.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Y.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Y.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Y.toString(n))}setLimit(t,n,r,s){return new An({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Y.toString(s)}]})}_addCheck(t){return new An({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Y.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Y.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Y.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Y.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Y.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Y.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Y.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Y.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Y.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"&&me.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 An({checks:[],typeName:J.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...se(e)});class Bn 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)!==q.bigint){const o=this._getOrReturnCtx(t);return z(o,{code:D.invalid_type,expected:q.bigint,received:o.parsedType}),te}let r;const s=new Je;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),z(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),z(r,{code:D.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):me.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Y.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Y.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Y.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Y.toString(n))}setLimit(t,n,r,s){return new Bn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Y.toString(s)}]})}_addCheck(t){return new Bn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Y.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Y.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Y.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Y.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Y.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 Bn({checks:[],typeName:J.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...se(e)})};class ms extends ae{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==q.boolean){const r=this._getOrReturnCtx(t);return z(r,{code:D.invalid_type,expected:q.boolean,received:r.parsedType}),te}return st(t.data)}}ms.create=e=>new ms({typeName:J.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...se(e)});class Jn extends ae{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==q.date){const o=this._getOrReturnCtx(t);return z(o,{code:D.invalid_type,expected:q.date,received:o.parsedType}),te}if(isNaN(t.data.getTime())){const o=this._getOrReturnCtx(t);return z(o,{code:D.invalid_date}),te}const r=new Je;let s;for(const o of this._def.checks)o.kind==="min"?t.data.getTime()o.value&&(s=this._getOrReturnCtx(t,s),z(s,{code:D.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):me.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Jn({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Y.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Y.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 Jn({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:J.ZodDate,...se(e)});class Co extends ae{_parse(t){if(this._getType(t)!==q.symbol){const r=this._getOrReturnCtx(t);return z(r,{code:D.invalid_type,expected:q.symbol,received:r.parsedType}),te}return st(t.data)}}Co.create=e=>new Co({typeName:J.ZodSymbol,...se(e)});class ys extends ae{_parse(t){if(this._getType(t)!==q.undefined){const r=this._getOrReturnCtx(t);return z(r,{code:D.invalid_type,expected:q.undefined,received:r.parsedType}),te}return st(t.data)}}ys.create=e=>new ys({typeName:J.ZodUndefined,...se(e)});class ws extends ae{_parse(t){if(this._getType(t)!==q.null){const r=this._getOrReturnCtx(t);return z(r,{code:D.invalid_type,expected:q.null,received:r.parsedType}),te}return st(t.data)}}ws.create=e=>new ws({typeName:J.ZodNull,...se(e)});class Lr extends ae{constructor(){super(...arguments),this._any=!0}_parse(t){return st(t.data)}}Lr.create=e=>new Lr({typeName:J.ZodAny,...se(e)});class Wn extends ae{constructor(){super(...arguments),this._unknown=!0}_parse(t){return st(t.data)}}Wn.create=e=>new Wn({typeName:J.ZodUnknown,...se(e)});class Qt extends ae{_parse(t){const n=this._getOrReturnCtx(t);return z(n,{code:D.invalid_type,expected:q.never,received:n.parsedType}),te}}Qt.create=e=>new Qt({typeName:J.ZodNever,...se(e)});class Po extends ae{_parse(t){if(this._getType(t)!==q.undefined){const r=this._getOrReturnCtx(t);return z(r,{code:D.invalid_type,expected:q.void,received:r.parsedType}),te}return st(t.data)}}Po.create=e=>new Po({typeName:J.ZodVoid,...se(e)});class St extends ae{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==q.array)return z(n,{code:D.invalid_type,expected:q.array,received:n.parsedType}),te;if(s.exactLength!==null){const i=n.data.length>s.exactLength.value,a=n.data.lengths.maxLength.value&&(z(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 Rt(n,i,n.path,a)))).then(i=>Je.mergeArray(r,i));const o=[...n.data].map((i,a)=>s.type._parseSync(new Rt(n,i,n.path,a)));return Je.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new St({...this._def,minLength:{value:t,message:Y.toString(n)}})}max(t,n){return new St({...this._def,maxLength:{value:t,message:Y.toString(n)}})}length(t,n){return new St({...this._def,exactLength:{value:t,message:Y.toString(n)}})}nonempty(t){return this.min(1,t)}}St.create=(e,t)=>new St({type:e,minLength:null,maxLength:null,exactLength:null,typeName:J.ZodArray,...se(t)});function kr(e){if(e instanceof Oe){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Yt.create(kr(r))}return new Oe({...e._def,shape:()=>t})}else return e instanceof St?new St({...e._def,type:kr(e.element)}):e instanceof Yt?Yt.create(kr(e.unwrap())):e instanceof er?er.create(kr(e.unwrap())):e instanceof jt?jt.create(e.items.map(t=>kr(t))):e}class Oe 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=me.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==q.object){const u=this._getOrReturnCtx(t);return z(u,{code:D.invalid_type,expected:q.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 Qt&&this._def.unknownKeys==="strip"))for(const u in s.data)i.includes(u)||a.push(u);const c=[];for(const u of i){const l=o[u],f=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Rt(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Qt){const u=this._def.unknownKeys;if(u==="passthrough")for(const l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(u==="strict")a.length>0&&(z(s,{code:D.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 l of a){const f=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Rt(s,f,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const l of c){const f=await l.key;u.push({key:f,value:await l.value,alwaysSet:l.alwaysSet})}return u}).then(u=>Je.mergeObjectSync(r,u)):Je.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return new Oe({...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=Y.errToObj(t).message)!==null&&a!==void 0?a:c}:{message:c}}}:{}})}strip(){return new Oe({...this._def,unknownKeys:"strip"})}passthrough(){return new Oe({...this._def,unknownKeys:"passthrough"})}extend(t){return new Oe({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Oe({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:J.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Oe({...this._def,catchall:t})}pick(t){const n={};return me.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Oe({...this._def,shape:()=>n})}omit(t){const n={};return me.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Oe({...this._def,shape:()=>n})}deepPartial(){return kr(this)}partial(t){const n={};return me.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}),new Oe({...this._def,shape:()=>n})}required(t){const n={};return me.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Yt;)o=o._def.innerType;n[r]=o}}),new Oe({...this._def,shape:()=>n})}keyof(){return Od(me.objectKeys(this.shape))}}Oe.create=(e,t)=>new Oe({shape:()=>e,unknownKeys:"strip",catchall:Qt.create(),typeName:J.ZodObject,...se(t)});Oe.strictCreate=(e,t)=>new Oe({shape:()=>e,unknownKeys:"strict",catchall:Qt.create(),typeName:J.ZodObject,...se(t)});Oe.lazycreate=(e,t)=>new Oe({shape:e,unknownKeys:"strip",catchall:Qt.create(),typeName:J.ZodObject,...se(t)});class bs 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 $t(a.ctx.common.issues));return z(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 u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!o&&(o={result:l,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 $t(c));return z(n,{code:D.invalid_union,unionErrors:a}),te}}get options(){return this._def.options}}bs.create=(e,t)=>new bs({options:e,typeName:J.ZodUnion,...se(t)});const ho=e=>e instanceof ks?ho(e.schema):e instanceof At?ho(e.innerType()):e instanceof Es?[e.value]:e instanceof Tn?e.options:e instanceof $s?Object.keys(e.enum):e instanceof Ss?ho(e._def.innerType):e instanceof ys?[void 0]:e instanceof ws?[null]:null;class li extends ae{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==q.object)return z(n,{code:D.invalid_type,expected:q.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}):(z(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=ho(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 li({typeName:J.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...se(r)})}}function $a(e,t){const n=vn(e),r=vn(t);if(e===t)return{valid:!0,data:e};if(n===q.object&&r===q.object){const s=me.objectKeys(t),o=me.objectKeys(e).filter(a=>s.indexOf(a)!==-1),i={...e,...t};for(const a of o){const c=$a(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===q.array&&r===q.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let o=0;o{if(ka(o)||ka(i))return te;const a=$a(o.value,i.value);return a.valid?((Ea(o)||Ea(i))&&n.dirty(),{status:n.value,value:a.data}):(z(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}))}}xs.create=(e,t,n)=>new xs({left:e,right:t,typeName:J.ZodIntersection,...se(n)});class jt extends ae{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==q.array)return z(r,{code:D.invalid_type,expected:q.array,received:r.parsedType}),te;if(r.data.lengththis._def.items.length&&(z(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 Rt(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>Je.mergeArray(n,i)):Je.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new jt({...this._def,rest:t})}}jt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new jt({items:e,typeName:J.ZodTuple,rest:null,...se(t)})};class vs 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!==q.object)return z(r,{code:D.invalid_type,expected:q.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 Rt(r,a,r.path,a)),value:i._parse(new Rt(r,r.data[a],r.path,a))});return r.common.async?Je.mergeObjectAsync(n,s):Je.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof ae?new vs({keyType:t,valueType:n,typeName:J.ZodRecord,...se(r)}):new vs({keyType:kt.create(),valueType:t,typeName:J.ZodRecord,...se(n)})}}class Uo extends ae{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==q.map)return z(r,{code:D.invalid_type,expected:q.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 Rt(r,a,r.path,[u,"key"])),value:o._parse(new Rt(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,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return te;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const c of i){const u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return te;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}}}}Uo.create=(e,t,n)=>new Uo({valueType:t,keyType:e,typeName:J.ZodMap,...se(n)});class Qn extends ae{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==q.set)return z(r,{code:D.invalid_type,expected:q.set,received:r.parsedType}),te;const s=this._def;s.minSize!==null&&r.data.sizes.maxSize.value&&(z(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 u=new Set;for(const l of c){if(l.status==="aborted")return te;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}const a=[...r.data.values()].map((c,u)=>o._parse(new Rt(r,c,r.path,u)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(t,n){return new Qn({...this._def,minSize:{value:t,message:Y.toString(n)}})}max(t,n){return new Qn({...this._def,maxSize:{value:t,message:Y.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}Qn.create=(e,t)=>new Qn({valueType:e,minSize:null,maxSize:null,typeName:J.ZodSet,...se(t)});class _r extends ae{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==q.function)return z(n,{code:D.invalid_type,expected:q.function,received:n.parsedType}),te;function r(a,c){return To({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Bo(),gs].filter(u=>!!u),issueData:{code:D.invalid_arguments,argumentsError:c}})}function s(a,c){return To({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Bo(),gs].filter(u=>!!u),issueData:{code:D.invalid_return_type,returnTypeError:c}})}const o={errorMap:n.common.contextualErrorMap},i=n.data;return this._def.returns instanceof Hr?st(async(...a)=>{const c=new $t([]),u=await this._def.args.parseAsync(a,o).catch(d=>{throw c.addIssue(r(a,d)),c}),l=await i(...u);return await this._def.returns._def.type.parseAsync(l,o).catch(d=>{throw c.addIssue(s(l,d)),c})}):st((...a)=>{const c=this._def.args.safeParse(a,o);if(!c.success)throw new $t([r(a,c.error)]);const u=i(...c.data),l=this._def.returns.safeParse(u,o);if(!l.success)throw new $t([s(u,l.error)]);return l.data})}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new _r({...this._def,args:jt.create(t).rest(Wn.create())})}returns(t){return new _r({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new _r({args:t||jt.create([]).rest(Wn.create()),returns:n||Wn.create(),typeName:J.ZodFunction,...se(r)})}}class ks 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})}}ks.create=(e,t)=>new ks({getter:e,typeName:J.ZodLazy,...se(t)});class Es extends ae{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return z(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}}Es.create=(e,t)=>new Es({value:e,typeName:J.ZodLiteral,...se(t)});function Od(e,t){return new Tn({values:e,typeName:J.ZodEnum,...se(t)})}class Tn extends ae{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return z(n,{expected:me.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 z(n,{received:n.data,code:D.invalid_enum_value,options:r}),te}return st(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 Tn.create(t)}exclude(t){return Tn.create(this.options.filter(n=>!t.includes(n)))}}Tn.create=Od;class $s extends ae{_parse(t){const n=me.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==q.string&&r.parsedType!==q.number){const s=me.objectValues(n);return z(r,{expected:me.joinValues(s),received:r.parsedType,code:D.invalid_type}),te}if(n.indexOf(t.data)===-1){const s=me.objectValues(n);return z(r,{received:r.data,code:D.invalid_enum_value,options:s}),te}return st(t.data)}get enum(){return this._def.values}}$s.create=(e,t)=>new $s({values:e,typeName:J.ZodNativeEnum,...se(t)});class Hr extends ae{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==q.promise&&n.common.async===!1)return z(n,{code:D.invalid_type,expected:q.promise,received:n.parsedType}),te;const r=n.parsedType===q.promise?n.data:Promise.resolve(n.data);return st(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Hr.create=(e,t)=>new Hr({type:e,typeName:J.ZodPromise,...se(t)});class At extends ae{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===J.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=>{z(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(!Io(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=>Io(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):i);me.assertNever(s)}}At.create=(e,t,n)=>new At({schema:e,typeName:J.ZodEffects,effect:t,...se(n)});At.createWithPreprocess=(e,t,n)=>new At({schema:t,effect:{type:"preprocess",transform:e},typeName:J.ZodEffects,...se(n)});class Yt extends ae{_parse(t){return this._getType(t)===q.undefined?st(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Yt.create=(e,t)=>new Yt({innerType:e,typeName:J.ZodOptional,...se(t)});class er extends ae{_parse(t){return this._getType(t)===q.null?st(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}er.create=(e,t)=>new er({innerType:e,typeName:J.ZodNullable,...se(t)});class Ss extends ae{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===q.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Ss.create=(e,t)=>new Ss({innerType:e,typeName:J.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...se(t)});class No 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 Oo(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new $t(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new $t(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}No.create=(e,t)=>new No({innerType:e,typeName:J.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...se(t)});class Lo extends ae{_parse(t){if(this._getType(t)!==q.nan){const r=this._getOrReturnCtx(t);return z(r,{code:D.invalid_type,expected:q.nan,received:r.parsedType}),te}return{status:"valid",value:t.data}}}Lo.create=e=>new Lo({typeName:J.ZodNaN,...se(e)});const G1=Symbol("zod_brand");class Cd 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 Ns 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(),Id(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 Ns({in:t,out:n,typeName:J.ZodPipeline})}}const Pd=(e,t={},n)=>e?Lr.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})}}):Lr.create(),Y1={object:Oe.lazycreate};var J;(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"})(J||(J={}));const X1=(e,t={message:`Input not instance of ${e.name}`})=>Pd(n=>n instanceof e,t),Ud=kt.create,Nd=An.create,J1=Lo.create,Q1=Bn.create,Ld=ms.create,ex=Jn.create,tx=Co.create,nx=ys.create,rx=ws.create,sx=Lr.create,ox=Wn.create,ix=Qt.create,ax=Po.create,cx=St.create,ux=Oe.create,lx=Oe.strictCreate,fx=bs.create,dx=li.create,hx=xs.create,px=jt.create,gx=vs.create,mx=Uo.create,yx=Qn.create,wx=_r.create,bx=ks.create,xx=Es.create,vx=Tn.create,kx=$s.create,Ex=Hr.create,Ku=At.create,$x=Yt.create,Sx=er.create,_x=At.createWithPreprocess,Ax=Ns.create,Bx=()=>Ud().optional(),Tx=()=>Nd().optional(),Ix=()=>Ld().optional(),Ox={string:(e=>kt.create({...e,coerce:!0})),number:(e=>An.create({...e,coerce:!0})),boolean:(e=>ms.create({...e,coerce:!0})),bigint:(e=>Bn.create({...e,coerce:!0})),date:(e=>Jn.create({...e,coerce:!0}))},Cx=te;var rt=Object.freeze({__proto__:null,defaultErrorMap:gs,setErrorMap:L1,getErrorMap:Bo,makeIssue:To,EMPTY_PATH:H1,addIssueToContext:z,ParseStatus:Je,INVALID:te,DIRTY:Id,OK:st,isAborted:ka,isDirty:Ea,isValid:Io,isAsync:Oo,get util(){return me},get objectUtil(){return va},ZodParsedType:q,getParsedType:vn,ZodType:ae,ZodString:kt,ZodNumber:An,ZodBigInt:Bn,ZodBoolean:ms,ZodDate:Jn,ZodSymbol:Co,ZodUndefined:ys,ZodNull:ws,ZodAny:Lr,ZodUnknown:Wn,ZodNever:Qt,ZodVoid:Po,ZodArray:St,ZodObject:Oe,ZodUnion:bs,ZodDiscriminatedUnion:li,ZodIntersection:xs,ZodTuple:jt,ZodRecord:vs,ZodMap:Uo,ZodSet:Qn,ZodFunction:_r,ZodLazy:ks,ZodLiteral:Es,ZodEnum:Tn,ZodNativeEnum:$s,ZodPromise:Hr,ZodEffects:At,ZodTransformer:At,ZodOptional:Yt,ZodNullable:er,ZodDefault:Ss,ZodCatch:No,ZodNaN:Lo,BRAND:G1,ZodBranded:Cd,ZodPipeline:Ns,custom:Pd,Schema:ae,ZodSchema:ae,late:Y1,get ZodFirstPartyTypeKind(){return J},coerce:Ox,any:sx,array:cx,bigint:Q1,boolean:Ld,date:ex,discriminatedUnion:dx,effect:Ku,enum:vx,function:wx,instanceof:X1,intersection:hx,lazy:bx,literal:xx,map:mx,nan:J1,nativeEnum:kx,never:ix,null:rx,nullable:Sx,number:Nd,object:ux,oboolean:Ix,onumber:Tx,optional:$x,ostring:Bx,pipeline:Ax,preprocess:_x,promise:Ex,record:gx,set:yx,strictObject:lx,string:Ud,symbol:tx,transformer:Ku,tuple:px,undefined:nx,union:fx,unknown:ox,void:ax,NEVER:Cx,ZodIssueCode:D,quotelessJson:N1,ZodError:$t});const Hd=rt.string().regex(/^[a-fA-F0-9]$/),Px=rt.string().regex(/^[a-fA-F0-9]{64}$/),Rr=rt.number().min(0).max(4294967295),Ux=rt.bigint(),Rd=rt.instanceof(Uint8Array),Nx=rt.union([Hd,Rr,rt.string(),Rd]).array(),_c=rt.union([Nx,Hd,Rd]),Lx=rt.array(_c),jd=rt.object({value:rt.union([Rr,Ux]),scriptPubKey:_c}),Hx=rt.object({txid:Px,vout:Rr,scriptSig:_c,sequence:Rr,prevout:jd.optional(),witness:Lx});rt.object({version:Rr,vin:rt.array(Hx),vout:rt.array(jd),locktime:Rr});const Sa=2048,Rx=new TextEncoder;function Kd(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=Rx.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>Sa)throw new Error(`Metadata must be at most ${Sa} CBOR bytes.`)};return r(e),Uint8Array.from(t)}function jx(e){if(e=new Uint8Array(e),!e.length||e.length>Sa)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 l=new DataView(n(8).buffer).getFloat64(0);if(Number.isFinite(l))return l}throw new Error("Unsupported CBOR value.")}let u=c;if(c>=24&&c<=27){u=0;for(const l of n(2**(c-24)))u=u*256+l}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 l={};for(let f=0;f({txid:e,vout:t,sequence:4294967295,prevout:{value:n,scriptPubKey:r}}),xe=(e,t)=>({value:e,scriptPubKey:t}),Du=16*1024,Ut=1e3,X=500,Ho="text/plain;charset=utf-8",Kx=["text/plain","application/json","text/html","image/svg+xml","image/png","image/jpeg","image/webp"],Dd=new TextEncoder,us=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""),jn=e=>Uint8Array.from(e.match(/../g)??[],t=>parseInt(t,16)),Ro=e=>us(Dd.encode(e));function Ac(e){const t=typeof e=="string"?{contentType:Ho,bytes:Dd.encode(e)}:e;if(!t||![...Kx,Ho].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>Du)throw new Error(`Body must be at most ${Du} bytes.`);return{contentType:t.contentType,bytes:new Uint8Array(t.bytes)}}function jo(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 Mu(e){if(typeof e!="string"||!/^[0-9a-f]{64,72}$/.test(e)||e.length%2)throw new Error("Invalid parent tag.");const t=[...jn(e.slice(64))].reduce((r,s,o)=>r+s*256**o,0),n=`${e.slice(0,64).match(/../g).reverse().join("")}i${t}`;if(jo(n)!==e)throw new Error("Non-canonical parent tag.");return n}function Md(e,t,n=null,r=void 0,s={}){const{contentType:o,bytes:i}=Ac(t),{delegate:a=null,pointer:c,metaprotocol:u=null}=s,l=u==null||u===""?null:new TextEncoder().encode(String(u));if(l&&l.length>520)throw new Error("Metaprotocol identifier must be 520 bytes or less.");const f=r===void 0?void 0:Kd(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(Ro("ord"))+h("01")+h(Ro(o))+(a?h("0b")+h(jo(a)):"")+(c===void 0?"":h("02")+h(Zd(c)))+(n?h("03")+h(jo(n)):"")+(f===void 0?"":Array.from({length:Math.ceil(f.length/520)},(g,p)=>h("05")+h(us(f.slice(p*520,(p+1)*520)))).join(""))+(l?h("07")+h(us(l)):"")+"00"+d.map(h).join("")+"68"}const Dx=e=>ui.tree.getLeaf(Ue.encode(e,!0));function Bc(e){if(!Array.isArray(e)||e.length!==3)throw new Error("Unsupported script-path witness.");const t=Ue.decode(e[1]);let n=7,r=null,s=null,o;t[n]==="0b"&&(s=Mu(t[n+1]),n+=2),t[n]==="02"&&(o=Zx(t[n+1]==="OP_0"?"":t[n+1]),n+=2),t[n]==="03"&&(r=Mu(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?jx(jn(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(jn(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 l=new TextDecoder().decode(jn(t[6])),f=Ac({contentType:l,bytes:jn(u.join(""))}),d=Md(t[0],f,r,a,{delegate:s,pointer:o,metaprotocol:c}),h=a===void 0&&!r&&l===Ho&&f.bytes.length<=280&&Ue.encode([t[0],"OP_CHECKSIG","OP_0","OP_IF",Ro("ord"),"01",Ro(Ho),"OP_0",us(f.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{...f,parent:r,delegate:s,pointer:o,metaprotocol:c,metadata:a,metadataBytes:i.length?jn(i.join("")):void 0,text:new TextDecoder().decode(f.bytes),pubkey:t[0]}}class Mx{constructor(t,n){this.chain=t,this.wallet=n}prepare(t,n=null,r=void 0,s={}){const o=Ac(t);if(r!==void 0&&Kd(r),s.delegate&&jo(s.delegate),s.pointer!==void 0&&Zd(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(l=>{var f;return(f=l.inscriptions)==null?void 0:f.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(l=>{var f;return(f=l.inscriptions)==null?void 0:f.some(d=>d.id===s.reinscribe)}):null;if(s.reinscribe&&!c)throw new Error("Reinscription must spend an owned sat.");const u=i.find(l=>!l.inscription&&l.value>=Ut+2*X+330);if(!u)throw new Error("Mine a block first to get spendable fake BTC.");return{...o,coin:u,parent:a,reinscribe:c,totalFee:X*2,postage:Ut}}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,l=a==null?void 0:a.inscriptions.find(x=>x.id===s.reinscribe),f=l?this.chain.satLocation(l.sat).offset:s.pointer??(i?i.value:void 0),d=Md(this.wallet.pubkey,c,n,r,{...s,pointer:f}),h=Dx(d),[g,p]=ui.getPubKey(this.wallet.pubkey,{target:h}),w=ee.create({vin:[Xe(o.txid,o.vout,o.value,o.scriptPubKey)],vout:[xe(Ut+X,["OP_1",g]),xe(o.value-Ut-2*X,this.wallet.script)]});w.vin[0].witness=[this.wallet.sign(w)];const y=ee.util.getTxid(w),v=ee.create({vin:[...u?[Xe(u.txid,u.vout,u.value,u.scriptPubKey)]:[],Xe(y,0,Ut+X,["OP_1",g])],vout:[...u?[xe(u.value,this.wallet.script)]:[],xe(Ut,this.wallet.script)]}),m=u?1:0;return v.vin[m].witness=[this.wallet.sign(v,h,m),Ue.encode(d,!1).hex,p],u&&(v.vin[0].witness=[this.wallet.sign(v)]),this.chain.submitPackage([ee.encode(w).hex,ee.encode(v).hex]),`${ee.util.getTxid(v)}i0`}list(){return this.chain.coins(this.wallet.script).flatMap(t=>t.inscriptions??[])}}function Zd(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 Zx(e){if(typeof e!="string"||!/^(?:[0-9a-f]{2}){0,8}$/.test(e))throw new Error("Invalid pointer tag.");return[...jn(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:Ol(s,r.value)}));const n=(r,s,o)=>{var y;const i=ee.decode(r),a=ee.util.getTxid(i),c=i.vin[0].txid==="0".repeat(64),u=c?[]:i.vin.map(v=>this.utxos.get(`${v.txid}:${v.vout}`)),l=Ul(i,u,s,c);i.vin.forEach(v=>this.utxos.delete(`${v.txid}:${v.vout}`)),i.vout.forEach((v,m)=>this.utxos.set(`${a}:${m}`,{txid:a,vout:m,value:Number(v.value),ranges:l[m]}));const f=(y=i.vin.find(v=>{var m;return((m=v.witness)==null?void 0:m.length)===3}))==null?void 0:y.witness;if(!f)return;const d=Bc(f),h=BigInt(d.pointer??0),g=i.vout.reduce((v,m)=>v+Number(m.value),0),p=Pl(l.flat(),hv.sat===p).length,status:s===null?"pending":"confirmed",height:s,block:o,metadata:w??null,hasMetadata:w!==void 0,parent:d.parent,protocol:d.metaprotocol??(w&&!Array.isArray(w)&&typeof w=="object"&&Object.hasOwn(w,"protocol")&&typeof w.protocol=="string"?w.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=lo(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 yr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ls(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Lt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Me(e,...t){if(!Ls(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 Hs(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Lt(e.outputLen),Lt(e.blockLen)}function jr(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 Vd(e,t){Me(e);const n=t.outputLen;if(e.length>>t}function Gs(e,t){return e<>>32-t>>>0}const qx=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function zx(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Fx(e){for(let t=0;te:Fx,qd=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Wx=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Be(e){if(Me(e),qd)return e.toHex();let t="";for(let n=0;n=qt._0&&e<=qt._9)return e-qt._0;if(e>=qt.A&&e<=qt.F)return e-(qt.A-10);if(e>=qt.a&&e<=qt.f)return e-(qt.a-10)}function mt(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(qd)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(Kr(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function dr(e=32){if(yr&&typeof yr.getRandomValues=="function")return yr.getRandomValues(new Uint8Array(e));if(yr&&typeof yr.randomBytes=="function")return Uint8Array.from(yr.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Yx(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 Xx(e,t,n){return e&t^~e&n}function Jx(e,t,n){return e&t^e&n^t&n}class Ic extends Tc{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=Gn(this.buffer)}update(t){jr(this),t=Kr(t),Me(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 f=i;fl.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f>zu&Ys)}:{h:Number(e>>zu&Ys)|0,l:Number(e&Ys)|0}}function zd(e,t=!1){const n=e.length;let r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;oe>>>n,Wu=(e,t,n)=>e<<32-n|t>>>n,wr=(e,t,n)=>e>>>n|t<<32-n,br=(e,t,n)=>e<<32-n|t>>>n,Xs=(e,t,n)=>e<<64-n|t>>>n-32,Js=(e,t,n)=>e>>>n-32|t<<64-n,e2=(e,t,n)=>e<>>32-n,t2=(e,t,n)=>t<>>32-n,n2=(e,t,n)=>t<>>64-n,r2=(e,t,n)=>e<>>64-n;function zt(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}const s2=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),o2=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,i2=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),a2=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,c2=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),u2=(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]),mn=new Uint32Array(64);class f2 extends Ic{constructor(t=32){super(64,t,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 f=0;f<16;f++,n+=4)mn[f]=t.getUint32(n,!1);for(let f=16;f<64;f++){const d=mn[f-15],h=mn[f-2],g=Pt(d,7)^Pt(d,18)^d>>>3,p=Pt(h,17)^Pt(h,19)^h>>>10;mn[f]=p+mn[f-7]+g+mn[f-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const d=Pt(a,6)^Pt(a,11)^Pt(a,25),h=l+d+Xx(a,c,u)+l2[f]+mn[f]|0,p=(Pt(r,2)^Pt(r,13)^Pt(r,22))+Jx(r,s,o)|0;l=u,u=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,u=u+this.G|0,l=l+this.H|0,this.set(r,s,o,i,a,c,u,l)}roundClean(){gt(mn)}destroy(){this.set(0,0,0,0,0,0,0,0),gt(this.buffer)}}const Fd=zd(["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))),d2=Fd[0],h2=Fd[1],yn=new Uint32Array(80),wn=new Uint32Array(80);class p2 extends Ic{constructor(t=64){super(128,t,16,!1),this.Ah=We[0]|0,this.Al=We[1]|0,this.Bh=We[2]|0,this.Bl=We[3]|0,this.Ch=We[4]|0,this.Cl=We[5]|0,this.Dh=We[6]|0,this.Dl=We[7]|0,this.Eh=We[8]|0,this.El=We[9]|0,this.Fh=We[10]|0,this.Fl=We[11]|0,this.Gh=We[12]|0,this.Gl=We[13]|0,this.Hh=We[14]|0,this.Hl=We[15]|0}get(){const{Ah:t,Al:n,Bh:r,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:d,Gh:h,Gl:g,Hh:p,Hl:w}=this;return[t,n,r,s,o,i,a,c,u,l,f,d,h,g,p,w]}set(t,n,r,s,o,i,a,c,u,l,f,d,h,g,p,w){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=l|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=g|0,this.Hh=p|0,this.Hl=w|0}process(t,n){for(let m=0;m<16;m++,n+=4)yn[m]=t.getUint32(n),wn[m]=t.getUint32(n+=4);for(let m=16;m<80;m++){const x=yn[m-15]|0,k=wn[m-15]|0,I=wr(x,k,1)^wr(x,k,8)^Fu(x,k,7),C=br(x,k,1)^br(x,k,8)^Wu(x,k,7),N=yn[m-2]|0,O=wn[m-2]|0,R=wr(N,O,19)^Xs(N,O,61)^Fu(N,O,6),A=br(N,O,19)^Js(N,O,61)^Wu(N,O,6),P=i2(C,A,wn[m-7],wn[m-16]),E=a2(P,I,R,yn[m-7],yn[m-16]);yn[m]=E|0,wn[m]=P|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:g,Gh:p,Gl:w,Hh:y,Hl:v}=this;for(let m=0;m<80;m++){const x=wr(f,d,14)^wr(f,d,18)^Xs(f,d,41),k=br(f,d,14)^br(f,d,18)^Js(f,d,41),I=f&h^~f&p,C=d&g^~d&w,N=c2(v,k,C,h2[m],wn[m]),O=u2(N,y,x,I,d2[m],yn[m]),R=N|0,A=wr(r,s,28)^Xs(r,s,34)^Xs(r,s,39),P=br(r,s,28)^Js(r,s,34)^Js(r,s,39),E=r&o^r&a^o&a,S=s&i^s&c^i&c;y=p|0,v=w|0,p=h|0,w=g|0,h=f|0,g=d|0,{h:f,l:d}=zt(u|0,l|0,O|0,R|0),u=a|0,l=c|0,a=o|0,c=i|0,o=r|0,i=s|0;const b=s2(R,P,S);r=o2(b,O,A,E),s=b|0}({h:r,l:s}=zt(this.Ah|0,this.Al|0,r|0,s|0)),{h:o,l:i}=zt(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=zt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=zt(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=zt(this.Eh|0,this.El|0,f|0,d|0),{h,l:g}=zt(this.Fh|0,this.Fl|0,h|0,g|0),{h:p,l:w}=zt(this.Gh|0,this.Gl|0,p|0,w|0),{h:y,l:v}=zt(this.Hh|0,this.Hl|0,y|0,v|0),this.set(r,s,o,i,a,c,u,l,f,d,h,g,p,w,y,v)}roundClean(){gt(yn,wn)}destroy(){gt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Ee=fi(()=>new f2),_s=fi(()=>new p2);class Wd extends Tc{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Hs(t);const r=Kr(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 Wd(e,t).update(n).digest();In.create=(e,t)=>new Wd(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Oc=BigInt(0),_a=BigInt(1);function tr(e,t=""){if(typeof e!="boolean"){const n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function Et(e,t,n=""){const r=Ls(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 Qs(e){const t=e.toString(16);return t.length&1?"0"+t:t}function Gd(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Oc:BigInt("0x"+e)}function hr(e){return Gd(Be(e))}function nr(e){return Me(e),Gd(Be(Uint8Array.from(e).reverse()))}function di(e,t){return mt(e.toString(16).padStart(t*2,"0"))}function Cc(e,t){return di(e,t).reverse()}function we(e,t,n){let r;if(typeof t=="string")try{r=mt(t)}catch(o){throw new Error(e+" must be hex string or Uint8Array, cause: "+o)}else if(Ls(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 Gu(e){return Uint8Array.from(e)}const Di=e=>typeof e=="bigint"&&Oc<=e;function Aa(e,t,n){return Di(e)&&Di(t)&&Di(n)&&t<=e&&eOc;e>>=_a,t+=1);return t}const Rs=e=>(_a<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},u=(...h)=>n(i,o,...h),l=(h=r(0))=>{i=u(s(0),h),o=u(),h.length!==0&&(i=u(s(1),h),o=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const g=[];for(;h{c(),l(h);let p;for(;!(p=g(f()));)l();return c(),p}}function Wr(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 Ko(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 it=BigInt(0),Fe=BigInt(1),Vn=BigInt(2),Xd=BigInt(3),Jd=BigInt(4),Qd=BigInt(5),m2=BigInt(7),eh=BigInt(8),y2=BigInt(9),th=BigInt(16);function Se(e,t){const n=e%t;return n>=it?n:t+n}function Ie(e,t,n){let r=e;for(;t-- >it;)r*=r,r%=n;return r}function Yu(e,t){if(e===it)throw new Error("invert: expected non-zero number");if(t<=it)throw new Error("invert: expected positive modulus, got "+t);let n=Se(e,t),r=t,s=it,o=Fe;for(;n!==it;){const a=r/n,c=r%n,u=s-o*a;r=n,n=c,s=o,o=u}if(r!==Fe)throw new Error("invert: does not exist");return Se(s,t)}function Pc(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function nh(e,t){const n=(e.ORDER+Fe)/Jd,r=e.pow(t,n);return Pc(e,r,t),r}function w2(e,t){const n=(e.ORDER-Qd)/eh,r=e.mul(t,Vn),s=e.pow(r,n),o=e.mul(t,s),i=e.mul(e.mul(o,Vn),s),a=e.mul(o,e.sub(i,e.ONE));return Pc(e,a,t),a}function b2(e){const t=pr(e),n=rh(e),r=n(t,t.neg(t.ONE)),s=n(t,r),o=n(t,t.neg(r)),i=(e+m2)/th;return(a,c)=>{let u=a.pow(c,i),l=a.mul(u,r);const f=a.mul(u,s),d=a.mul(u,o),h=a.eql(a.sqr(l),c),g=a.eql(a.sqr(f),c);u=a.cmov(u,l,h),l=a.cmov(d,f,g);const p=a.eql(a.sqr(l),c),w=a.cmov(u,l,p);return Pc(a,w,c),w}}function rh(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return nh;let o=s.pow(r,t);const i=(t+Fe)/Vn;return function(c,u){if(c.is0(u))return u;if(Xu(c,u)!==1)throw new Error("Cannot find square root");let l=n,f=c.mul(c.ONE,o),d=c.pow(u,t),h=c.pow(u,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===l)throw new Error("Cannot find square root");const w=Fe<(Se(e,t)&Fe)===Fe,k2=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function E2(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=k2.reduce((r,s)=>(r[s]="function",r),t);return Wr(e,n),e}function $2(e,t,n){if(nit;)n&Fe&&(r=e.mul(r,s)),s=e.sqr(s),n>>=Fe;return r}function sh(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 Xu(e,t){const n=(e.ORDER-Fe)/Vn,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 oh(e,t){t!==void 0&&Lt(t);const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function pr(e,t,n=!1,r={}){if(e<=it)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}=oh(e,s);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const f=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:u,MASK:Rs(c),ZERO:it,ONE:Fe,allowedLengths:a,create:d=>Se(d,e),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return it<=d&&dd===it,isValidNot0:d=>!f.is0(d)&&f.isValid(d),isOdd:d=>(d&Fe)===Fe,neg:d=>Se(-d,e),eql:(d,h)=>d===h,sqr:d=>Se(d*d,e),add:(d,h)=>Se(d+h,e),sub:(d,h)=>Se(d-h,e),mul:(d,h)=>Se(d*h,e),pow:(d,h)=>$2(f,d,h),div:(d,h)=>Se(d*Yu(h,e),e),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>Yu(d,e),sqrt:o||(d=>(l||(l=x2(e)),l(f,d))),toBytes:d=>n?Cc(d,u):di(d,u),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);const p=new Uint8Array(u);p.set(d,n?0:p.length-d.length),d=p}if(d.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+d.length);let g=n?nr(d):hr(d);if(i&&(g=Se(g,e)),!h&&!f.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:d=>sh(f,d),cmov:(d,h,g)=>g?h:d});return Object.freeze(f)}function ih(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=ih(e);return t+Math.ceil(t/2)}function ch(e,t,n=!1){const r=e.length,s=ih(t),o=ah(t);if(r<16||r1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);const i=n?nr(e):hr(e),a=Se(i,t-Fe)+Fe;return n?Cc(a,s):di(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Dr=BigInt(0),qn=BigInt(1);function Do(e,t){const n=t.negate();return e?n:t}function zn(e,t){const n=sh(e.Fp,t.map(r=>r.Z));return t.map((r,s)=>e.fromAffine(r.toAffine(n[s])))}function uh(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Mi(e,t){uh(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1),s=2**e,o=Rs(e),i=BigInt(e);return{windows:n,windowSize:r,mask:o,maxNumber:s,shiftBy:i}}function Ju(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+=qn);const u=t*r,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=t%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}function S2(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 _2(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 Zi=new WeakMap,lh=new WeakMap;function Vi(e){return lh.get(e)||1}function Qu(e){if(e!==Dr)throw new Error("invalid wNAF")}class fh{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>Dr;)n&qn&&(r=r.add(s)),s=s.double(),n>>=qn;return r}precomputeWindow(t,n){const{windows:r,windowSize:s}=Mi(n,this.bits),o=[];let i=t,a=i;for(let c=0;cDr||r>Dr;)n&qn&&(o=o.add(s)),r&qn&&(i=i.add(s)),s=s.double(),n>>=qn,r>>=qn;return{p1:o,p2:i}}function dh(e,t,n,r){S2(n,e),_2(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=Yd(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Rs(c),l=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c;let d=i;for(let h=f;h>=0;h-=c){l.fill(i);for(let p=0;p>BigInt(h)&u);l[y]=l[y].add(n[p])}let g=i;for(let p=l.length-1,w=i;p>0;p--)w=w.add(l[p]),g=g.add(w);if(d=d.add(g),h!==0)for(let p=0;pDr))throw new Error(`CURVE.${c} must be positive bigint`)}const s=el(t.p,n.Fp,r),o=el(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 tl=(e,t)=>(e+(e>=0?t:-t)/ph)/t;function B2(e,t,n){const[[r,s],[o,i]]=t,a=tl(i*e,n),c=tl(-s*e,n);let u=e-a*r-c*o,l=-a*s-c*i;const f=u=h||l=h)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:f,k1:u,k2neg:d,k2:l}}function Ba(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function qi(e,t){const n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return tr(n.lowS,"lowS"),tr(n.prehash,"prehash"),n.format!==void 0&&Ba(n.format),n}class T2 extends Error{constructor(t=""){super(t)}}const Ft={Err:T2,_tlv:{encode:(e,t)=>{const{Err:n}=Ft;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=Qs(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const o=r>127?Qs(s.length/2|128):"";return Qs(e)+o+s+t},decode(e,t){const{Err:n}=Ft;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 l of u)i=i<<8|l;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}=Ft;if(e{const{X:S,Y:b,Z:_}=P;if(r.eql(_,r.ONE))return{x:S,y:b};const U=P.is0();E==null&&(E=U?r.ONE:r.inv(_));const j=r.mul(S,E),L=r.mul(b,E),M=r.mul(_,E);if(U)return{x:r.ZERO,y:r.ZERO};if(!r.eql(M,r.ONE))throw new Error("invZ was invalid");return{x:j,y:L}}),C=Ko(P=>{if(P.is0()){if(t.allowInfinityPoint&&!r.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:E,y:S}=P.toAffine();if(!r.isValid(E)||!r.isValid(S))throw new Error("bad point: x or y not field elements");if(!w(E,S))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(P,E,S,b,_){return S=new O(r.mul(S.X,P),S.Y,S.Z),E=Do(b,E),S=Do(_,S),E.add(S)}class O{constructor(E,S,b){this.X=m("x",E),this.Y=m("y",S,!0),this.Z=m("z",b),Object.freeze(this)}static CURVE(){return o}static fromAffine(E){const{x:S,y:b}=E||{};if(!E||!r.isValid(S)||!r.isValid(b))throw new Error("invalid affine point");if(E instanceof O)throw new Error("projective point not allowed");return r.is0(S)&&r.is0(b)?O.ZERO:new O(S,b,r.ONE)}static fromBytes(E){const S=O.fromAffine(g(Et(E,void 0,"point")));return S.assertValidity(),S}static fromHex(E){return O.fromBytes(we("pointHex",E))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(E=8,S=!0){return A.createCache(this,E),S||this.multiply(eo),this}assertValidity(){C(this)}hasEvenY(){const{y:E}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(E)}equals(E){x(E);const{X:S,Y:b,Z:_}=this,{X:U,Y:j,Z:L}=E,M=r.eql(r.mul(S,L),r.mul(U,_)),V=r.eql(r.mul(b,L),r.mul(j,_));return M&&V}negate(){return new O(this.X,r.neg(this.Y),this.Z)}double(){const{a:E,b:S}=o,b=r.mul(S,eo),{X:_,Y:U,Z:j}=this;let L=r.ZERO,M=r.ZERO,V=r.ZERO,W=r.mul(_,_),le=r.mul(U,U),ce=r.mul(j,j),ne=r.mul(_,U);return ne=r.add(ne,ne),V=r.mul(_,j),V=r.add(V,V),L=r.mul(E,V),M=r.mul(b,ce),M=r.add(L,M),L=r.sub(le,M),M=r.add(le,M),M=r.mul(L,M),L=r.mul(ne,L),V=r.mul(b,V),ce=r.mul(E,ce),ne=r.sub(W,ce),ne=r.mul(E,ne),ne=r.add(ne,V),V=r.add(W,W),W=r.add(V,W),W=r.add(W,ce),W=r.mul(W,ne),M=r.add(M,W),ce=r.mul(U,j),ce=r.add(ce,ce),W=r.mul(ce,ne),L=r.sub(L,W),V=r.mul(ce,le),V=r.add(V,V),V=r.add(V,V),new O(L,M,V)}add(E){x(E);const{X:S,Y:b,Z:_}=this,{X:U,Y:j,Z:L}=E;let M=r.ZERO,V=r.ZERO,W=r.ZERO;const le=o.a,ce=r.mul(o.b,eo);let ne=r.mul(S,U),pe=r.mul(b,j),ge=r.mul(_,L),Ne=r.add(S,b),de=r.add(U,j);Ne=r.mul(Ne,de),de=r.add(ne,pe),Ne=r.sub(Ne,de),de=r.add(S,_);let ve=r.add(U,L);return de=r.mul(de,ve),ve=r.add(ne,ge),de=r.sub(de,ve),ve=r.add(b,_),M=r.add(j,L),ve=r.mul(ve,M),M=r.add(pe,ge),ve=r.sub(ve,M),W=r.mul(le,de),M=r.mul(ce,ge),W=r.add(M,W),M=r.sub(pe,W),W=r.add(pe,W),V=r.mul(M,W),pe=r.add(ne,ne),pe=r.add(pe,ne),ge=r.mul(le,ge),de=r.mul(ce,de),pe=r.add(pe,ge),ge=r.sub(ne,ge),ge=r.mul(le,ge),de=r.add(de,ge),ne=r.mul(pe,de),V=r.add(V,ne),ne=r.mul(ve,de),M=r.mul(Ne,M),M=r.sub(M,ne),ne=r.mul(Ne,pe),W=r.mul(ve,W),W=r.add(W,ne),new O(M,V,W)}subtract(E){return this.add(E.negate())}is0(){return this.equals(O.ZERO)}multiply(E){const{endo:S}=t;if(!s.isValidNot0(E))throw new Error("invalid scalar: out of range");let b,_;const U=j=>A.cached(this,j,L=>zn(O,L));if(S){const{k1neg:j,k1:L,k2neg:M,k2:V}=k(E),{p:W,f:le}=U(L),{p:ce,f:ne}=U(V);_=le.add(ne),b=N(S.beta,W,ce,j,M)}else{const{p:j,f:L}=U(E);b=j,_=L}return zn(O,[b,_])[0]}multiplyUnsafe(E){const{endo:S}=t,b=this;if(!s.isValid(E))throw new Error("invalid scalar: out of range");if(E===Wt||b.is0())return O.ZERO;if(E===Ar)return b;if(A.hasCache(this))return this.multiply(E);if(S){const{k1neg:_,k1:U,k2neg:j,k2:L}=k(E),{p1:M,p2:V}=A2(O,b,U,L);return N(S.beta,M,V,_,j)}else return A.unsafe(b,E)}multiplyAndAddUnsafe(E,S,b){const _=this.multiplyUnsafe(S).add(E.multiplyUnsafe(b));return _.is0()?void 0:_}toAffine(E){return I(this,E)}isTorsionFree(){const{isTorsionFree:E}=t;return i===Ar?!0:E?E(O,this):A.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:E}=t;return i===Ar?this:E?E(O,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(E=!0){return tr(E,"isCompressed"),this.assertValidity(),h(O,this,E)}toHex(E=!0){return Be(this.toBytes(E))}toString(){return``}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(E=!0){return this.toBytes(E)}_setWindowSize(E){this.precompute(E)}static normalizeZ(E){return zn(O,E)}static msm(E,S){return dh(O,s,E,S)}static fromPrivateKey(E){return O.BASE.multiply(Fn(s,E))}}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 R=s.BITS,A=new fh(O,t.endo?Math.ceil(R/2):R);return O.BASE.precompute(8),O}function gh(e){return Uint8Array.of(e?2:3)}function mh(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function C2(e,t={}){const{Fn:n}=e,r=t.randomBytes||dr,s=Object.assign(mh(e.Fp,n),{seed:ah(n.ORDER)});function o(h){try{return!!Fn(n,h)}catch{return!1}}function i(h,g){const{publicKey:p,publicKeyUncompressed:w}=s;try{const y=h.length;return g===!0&&y!==p||g===!1&&y!==w?!1:!!e.fromBytes(h)}catch{return!1}}function a(h=r(s.seed)){return ch(Et(h,s.seed,"seed"),n.ORDER)}function c(h,g=!0){return e.BASE.multiply(Fn(n,h)).toBytes(g)}function u(h){const g=a(h);return{secretKey:g,publicKey:c(g)}}function l(h){if(typeof h=="bigint")return!1;if(h instanceof e)return!0;const{secretKey:g,publicKey:p,publicKeyUncompressed:w}=s;if(n.allowedLengths||g===p)return;const y=we("key",h).length;return y===p||y===w}function f(h,g,p=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(g)===!1)throw new Error("second arg must be public key");const w=Fn(n,h);return e.fromHex(g).multiply(w).toBytes(p)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:e,utils:{isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:h=>Fn(n,h),precompute(h=8,g=e.BASE){return g.precompute(h,!1)}},lengths:s})}function P2(e,t,n={}){Hs(t),Wr(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||dr,s=n.hmac||((S,...b)=>In(t,S,ue(...b))),{Fp:o,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h}=C2(e,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},p="compact";function w(S){const b=a>>Ar;return S>b}function y(S,b){if(!i.isValidNot0(b))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return b}function v(S,b){Ba(b);const _=h.signature,U=b==="compact"?_:b==="recovered"?_+1:void 0;return Et(S,U,`${b} signature`)}class m{constructor(b,_,U){this.r=y("r",b),this.s=y("s",_),U!=null&&(this.recovery=U),Object.freeze(this)}static fromBytes(b,_=p){v(b,_);let U;if(_==="der"){const{r:V,s:W}=Ft.toSig(Et(b));return new m(V,W)}_==="recovered"&&(U=b[0],_="compact",b=b.subarray(1));const j=i.BYTES,L=b.subarray(0,j),M=b.subarray(j,j*2);return new m(i.fromBytes(L),i.fromBytes(M),U)}static fromHex(b,_){return this.fromBytes(mt(b),_)}addRecoveryBit(b){return new m(this.r,this.s,b)}recoverPublicKey(b){const _=o.ORDER,{r:U,s:j,recovery:L}=this;if(L==null||![0,1,2,3].includes(L))throw new Error("recovery id invalid");if(a*ph<_&&L>1)throw new Error("recovery id is ambiguous for h>1 curve");const V=L===2||L===3?U+a:U;if(!o.isValid(V))throw new Error("recovery id 2 or 3 invalid");const W=o.toBytes(V),le=e.fromBytes(ue(gh((L&1)===0),W)),ce=i.inv(V),ne=k(we("msgHash",b)),pe=i.create(-ne*ce),ge=i.create(j*ce),Ne=e.BASE.multiplyUnsafe(pe).add(le.multiplyUnsafe(ge));if(Ne.is0())throw new Error("point at infinify");return Ne.assertValidity(),Ne}hasHighS(){return w(this.s)}toBytes(b=p){if(Ba(b),b==="der")return mt(Ft.hexFromSig(this));const _=i.toBytes(this.r),U=i.toBytes(this.s);if(b==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ue(Uint8Array.of(this.recovery),_,U)}return ue(_,U)}toHex(b){return Be(this.toBytes(b))}assertValidity(){}static fromCompact(b){return m.fromBytes(we("sig",b),"compact")}static fromDER(b){return m.fromBytes(we("sig",b),"der")}normalizeS(){return this.hasHighS()?new m(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Be(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Be(this.toBytes("compact"))}}const x=n.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");const _=hr(b),U=b.length*8-c;return U>0?_>>BigInt(U):_},k=n.bits2int_modN||function(b){return i.create(x(b))},I=Rs(c);function C(S){return As("num < 2^"+c,S,Wt,I),i.toBytes(S)}function N(S,b){return Et(S,void 0,"message"),b?Et(t(S),void 0,"prehashed message"):S}function O(S,b,_){if(["recovered","canonical"].some(pe=>pe in _))throw new Error("sign() legacy options not supported");const{lowS:U,prehash:j,extraEntropy:L}=qi(_,g);S=N(S,j);const M=k(S),V=Fn(i,b),W=[C(V),C(M)];if(L!=null&&L!==!1){const pe=L===!0?r(h.secretKey):L;W.push(we("extraEntropy",pe))}const le=ue(...W),ce=M;function ne(pe){const ge=x(pe);if(!i.isValidNot0(ge))return;const Ne=i.inv(ge),de=e.BASE.multiply(ge).toAffine(),ve=i.create(de.x);if(ve===Wt)return;const Mt=i.create(Ne*i.create(ce+ve*V));if(Mt===Wt)return;let lt=(de.x===ve?0:2)|Number(de.y&Ar),qe=Mt;return U&&w(Mt)&&(qe=i.neg(Mt),lt^=1),new m(ve,qe,lt)}return{seed:le,k2sig:ne}}function R(S,b,_={}){S=we("message",S);const{seed:U,k2sig:j}=O(S,b,_);return g2(t.outputLen,i.BYTES,s)(U,j)}function A(S){let b;const _=typeof S=="string"||Ls(S),U=!_&&S!==null&&typeof S=="object"&&typeof S.r=="bigint"&&typeof S.s=="bigint";if(!_&&!U)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(U)b=new m(S.r,S.s);else if(_){try{b=m.fromBytes(we("sig",S),"der")}catch(j){if(!(j instanceof Ft.Err))throw j}if(!b)try{b=m.fromBytes(we("sig",S),"compact")}catch{return!1}}return b||!1}function P(S,b,_,U={}){const{lowS:j,prehash:L,format:M}=qi(U,g);if(_=we("publicKey",_),b=N(we("message",b),L),"strict"in U)throw new Error("options.strict was renamed to lowS");const V=M===void 0?A(S):m.fromBytes(we("sig",S),M);if(V===!1)return!1;try{const W=e.fromBytes(_);if(j&&V.hasHighS())return!1;const{r:le,s:ce}=V,ne=k(b),pe=i.inv(ce),ge=i.create(ne*pe),Ne=i.create(le*pe),de=e.BASE.multiplyUnsafe(ge).add(W.multiplyUnsafe(Ne));return de.is0()?!1:i.create(de.x)===le}catch{return!1}}function E(S,b,_={}){const{prehash:U}=qi(_,g);return b=N(b,U),m.fromBytes(S,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h,Point:e,sign:R,verify:P,recoverPublicKey:E,Signature:m,hash:t})}function U2(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=pr(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 N2(e){const{CURVE:t,curveOpts:n}=U2(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 L2(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,oh(n.Fn.ORDER,n.Fn.BITS))})}function H2(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:s}=N2(e),o=O2(t,n),i=P2(o,r,s);return L2(e,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function R2(e,t){const n=r=>H2({...e,hash:r});return{...n(t),create:n}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Mr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},j2={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},K2=BigInt(0),nl=BigInt(1),Ta=BigInt(2);function D2(e){const t=Mr.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,l=u*u*e%t,f=Ie(l,n,t)*l%t,d=Ie(f,n,t)*l%t,h=Ie(d,Ta,t)*u%t,g=Ie(h,s,t)*h%t,p=Ie(g,o,t)*g%t,w=Ie(p,a,t)*p%t,y=Ie(w,c,t)*w%t,v=Ie(y,a,t)*p%t,m=Ie(v,n,t)*l%t,x=Ie(m,i,t)*g%t,k=Ie(x,r,t)*u%t,I=Ie(k,Ta,t);if(!Mo.eql(Mo.sqr(I),e))throw new Error("Cannot find square root");return I}const Mo=pr(Mr.p,{sqrt:D2}),_e=R2({...Mr,Fp:Mo,lowS:!0,endo:j2},Ee),rl={};function Zo(e,...t){let n=rl[e];if(n===void 0){const r=Ee(Ke(e));n=ue(r,r),rl[e]=n}return Ee(ue(n,...t))}const Uc=e=>e.toBytes(!0).slice(1),Gr=_e.Point,Nc=e=>e%Ta===K2;function Ia(e){const{Fn:t,BASE:n}=Gr,r=Fn(t,e),s=n.multiply(r);return{scalar:Nc(s.y)?r:t.neg(r),bytes:Uc(s)}}function yh(e){const t=Mo;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);Nc(s)||(s=t.neg(s));const o=Gr.fromAffine({x:e,y:s});return o.assertValidity(),o}const ls=hr;function wh(...e){return Gr.Fn.create(ls(Zo("BIP0340/challenge",...e)))}function sl(e){return Ia(e).bytes}function M2(e,t,n=dr(32)){const{Fn:r}=Gr,s=we("message",e),{bytes:o,scalar:i}=Ia(t),a=we("auxRand",n,32),c=r.toBytes(i^ls(Zo("BIP0340/aux",a))),u=Zo("BIP0340/nonce",c,o,s),{bytes:l,scalar:f}=Ia(u),d=wh(l,o,s),h=new Uint8Array(64);if(h.set(l,0),h.set(r.toBytes(r.create(f+d*i)),32),!bh(h,s,o))throw new Error("sign: Invalid signature produced");return h}function bh(e,t,n){const{Fn:r,BASE:s}=Gr,o=we("signature",e,64),i=we("message",t),a=we("publicKey",n,32);try{const c=yh(ls(a)),u=ls(o.subarray(0,32));if(!Aa(u,nl,Mr.p))return!1;const l=ls(o.subarray(32,64));if(!Aa(l,nl,Mr.n))return!1;const f=wh(r.toBytes(u),Uc(c),i),d=s.multiplyUnsafe(l).add(c.multiplyUnsafe(r.neg(f))),{x:h,y:g}=d.toAffine();return!(d.is0()||!Nc(g)||h!==u)}catch{return!1}}const On=(()=>{const n=(s=dr(48))=>ch(s,Mr.n);_e.utils.randomSecretKey;function r(s){const o=n(s);return{secretKey:o,publicKey:sl(o)}}return{keygen:r,getPublicKey:sl,sign:M2,verify:bh,Point:Gr,utils:{randomSecretKey:n,randomPrivateKey:n,taggedHash:Zo,lift_x:yh,pointToBytes:Uc,numberToBytesBE:di,bytesToNumberBE:hr,mod:Se},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})(),Z2=BigInt(0),ns=BigInt(1),V2=BigInt(2),q2=BigInt(7),z2=BigInt(256),F2=BigInt(113),xh=[],vh=[],kh=[];for(let e=0,t=ns,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],xh.push(2*(5*r+n)),vh.push((e+1)*(e+2)/2%64);let s=Z2;for(let o=0;o<7;o++)t=(t<>q2)*F2)%z2,t&V2&&(s^=ns<<(ns<n>32?n2(e,t,n):e2(e,t,n),il=(e,t,n)=>n>32?r2(e,t,n):t2(e,t,n);function Y2(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],l=n[c+1],f=ol(u,l,1)^n[a],d=il(u,l,1)^n[a+1];for(let h=0;h<50;h+=10)e[i+h]^=f,e[i+h+1]^=d}let s=e[2],o=e[3];for(let i=0;i<24;i++){const a=vh[i],c=ol(s,o,a),u=il(s,o,a),l=xh[i];s=e[l],o=e[l+1],e[l]=c,e[l+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]^=W2[r],e[1]^=G2[r]}gt(n)}class Lc extends Tc{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,Lt(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 Lt(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(Vd(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,gt(this.state)}_cloneInto(t){const{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return t||(t=new Lc(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 X2=(e,t,n)=>fi(()=>new Lc(t,e,n)),Hc=X2(1,136,256/8),J2=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),$h=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),Q2=$h.map(e=>(9*e+5)%16),Sh=(()=>{const n=[[$h],[Q2]];for(let r=0;r<4;r++)for(let s of n)s.push(s[r].map(o=>J2[o]));return n})(),_h=Sh[0],Ah=Sh[1],Bh=[[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)),ev=_h.map((e,t)=>e.map(n=>Bh[t][n])),tv=Ah.map((e,t)=>e.map(n=>Bh[t][n])),nv=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),rv=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function al(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 to=new Uint32Array(16);class sv extends Ic{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)to[h]=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,l=u,f=this.h4|0,d=f;for(let h=0;h<5;h++){const g=4-h,p=nv[h],w=rv[h],y=_h[h],v=Ah[h],m=ev[h],x=tv[h];for(let k=0;k<16;k++){const I=Gs(r+al(h,o,a,u)+to[y[k]]+p,m[k])+f|0;r=f,f=u,u=Gs(a,10)|0,a=o,o=I}for(let k=0;k<16;k++){const I=Gs(s+al(g,i,c,l)+to[v[k]]+w,x[k])+d|0;s=d,d=l,l=Gs(c,10)|0,c=i,i=I}}this.set(this.h1+a+l|0,this.h2+u+d|0,this.h3+f+s|0,this.h4+r+i|0,this.h0+o+c|0)}roundClean(){gt(to)}destroy(){this.destroyed=!0,gt(this.buffer),this.set(0,0,0,0,0)}}const Rc=fi(()=>new sv);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Zr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function ov(e,...t){if(!Zr(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 Th(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 Ih(e){if(typeof e!="function")throw new Error("function expected");return!0}function rr(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function Yr(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function Vo(e){if(!Array.isArray(e))throw new Error("array expected")}function qo(e,t){if(!Th(!0,t))throw new Error(`${e}: array of strings expected`)}function jc(e,t){if(!Th(!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 hi(e){const t=typeof e=="string"?e.split(""):e,n=t.length;qo("alphabet",t);const r=new Map(t.map((s,o)=>[s,o]));return{encode:s=>(Vo(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=>(Vo(s),s.map(o=>{rr("alphabet.decode",o);const i=r.get(o);if(i===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${e}`);return i}))}}function pi(e=""){return rr("join",e),{encode:t=>(qo("join.decode",t),t.join(e)),decode:t=>(rr("join.decode",t),t.split(e))}}function Oh(e,t="="){return Yr(e),rr("padding",t),{encode(n){for(qo("padding.encode",n);n.length*e%8;)n.push(t);return n},decode(n){qo("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 Oa(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(Vo(e),!e.length)return[];let r=0;const s=[],o=Array.from(e,a=>{if(Yr(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:Ch(t,e%t),zo=(e,t)=>e+(t-Ch(e,t)),po=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function Fo(e,t,n,r){if(Vo(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(zo(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${zo(t,n)}`);let s=0,o=0;const i=po[t],a=po[n]-1,c=[];for(const u of e){if(Yr(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 l=po[o];if(l===void 0)throw new Error("invalid carry");s&=l-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 Ph(e){Yr(e);const t=2**8;return{encode:n=>{if(!Zr(n))throw new Error("radix.encode input should be Uint8Array");return Oa(Array.from(n),t,e)},decode:n=>(jc("radix.decode",n),Uint8Array.from(Oa(n,e,t)))}}function Kc(e,t=!1){if(Yr(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(zo(8,e)>32||zo(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!Zr(n))throw new Error("radix2.encode input should be Uint8Array");return Fo(Array.from(n),8,e,!t)},decode:n=>(jc("radix2.decode",n),Uint8Array.from(Fo(n,e,8,t)))}}function cl(e){return Ih(e),function(...t){try{return e.apply(null,t)}catch{}}}function Uh(e,t){return Yr(e),Ih(t),{encode(n){if(!Zr(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(!Zr(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{rr("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"})},pt=iv?{encode(e){return ov(e),e.toBase64()},decode(e){return av(e)}}:js(Kc(6),hi("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Oh(6),pi("")),cv=e=>js(Ph(58),hi(e),pi("")),uv=cv("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),Nh=e=>js(Uh(4,t=>e(e(t))),uv),Ca=js(hi("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),pi("")),ul=[996825010,642813549,513874426,1027748829,705979059];function rs(e){const t=e>>25;let n=(e&33554431)<<5;for(let r=0;r>r&1)===1&&(n^=ul[r]);return n}function ll(e,t,n=1){const r=e.length;let s=1;for(let o=0;o126)throw new Error(`Invalid prefix (${e})`);s=rs(s)^i>>5}s=rs(s);for(let o=0;oh)throw new TypeError(`Length ${p} exceeds limit ${h}`);const w=f.toLowerCase(),y=ll(w,d,t);return`${w}1${Ca.encode(d)}${y}`}function a(f,d=90){rr("bech32.decode input",f);const h=f.length;if(h<8||d!==!1&&h>d)throw new TypeError(`invalid string length: ${h} (${f}). Expected (8..${d})`);const g=f.toLowerCase();if(f!==g&&f!==f.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 w=g.slice(0,p),y=g.slice(p+1);if(y.length<6)throw new Error("Data must be at least 6 characters long");const v=Ca.decode(y).slice(0,-6),m=ll(w,v,t);if(!y.endsWith(m))throw new Error(`Invalid checksum in ${f}: expected "${m}"`);return{prefix:w,words:v}}const c=cl(a);function u(f){const{prefix:d,words:h}=a(f,!1);return{prefix:d,words:h,bytes:r(h)}}function l(f,d){return i(f,s(d))}return{encode:i,decode:a,encodeFromBytes:l,decodeToBytes:u,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:o,toWords:s}}const sr=Lh("bech32"),lv=Lh("bech32m");/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */const ro=_e.ProjectivePoint,zi=Nh(Ee);function fl(e){Me(e);const t=e.length===0?"0":Be(e);return BigInt("0x"+t)}function fv(e){if(typeof e!="bigint")throw new Error("bigint expected");return mt(e.toString(16).padStart(64,"0"))}const dv=Ke("Bitcoin seed"),Fi={private:76066276,public:76067358},Wi=2147483648,hv=e=>Rc(Ee(e)),pv=e=>Gn(e).getUint32(0,!1),so=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 Gn(t).setUint32(0,e,!1),t};class Kn{get fingerprint(){if(!this.pubHash)throw new Error("No publicKey set!");return pv(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 zi.encode(this.serialize(this.versions.private,ue(new Uint8Array([0]),t)))}get publicExtendedKey(){if(!this.pubKey)throw new Error("No public key");return zi.encode(this.serialize(this.versions.public,this.pubKey))}static fromMasterSeed(t,n=Fi){if(Me(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=In(_s,dv,t);return new Kn({versions:n,chainCode:r.slice(32),privateKey:r.slice(0,32)})}static fromExtendedKey(t,n=Fi){const r=zi.decode(t),s=Gn(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 Kn({...i,privateKey:a.slice(1)}):new Kn({...i,publicKey:a})}static fromJSON(t){return Kn.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||Fi,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(!_e.utils.isValidPrivateKey(t.privateKey))throw new Error("Invalid private key");this.privKey=typeof t.privateKey=="bigint"?t.privateKey:fl(t.privateKey),this.privKeyBytes=fv(this.privKey),this.pubKey=_e.getPublicKey(t.privateKey,!0)}else if(t.publicKey)this.pubKey=ro.fromHex(t.publicKey).toRawBytes(!0);else throw new Error("HDKey: no public or private key provided");this.pubHash=hv(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>=Wi)throw new Error("Invalid index");o[2]==="'"&&(a+=Wi),r=r.deriveChild(a)}return r}deriveChild(t){if(!this.pubKey||!this.chainCode)throw new Error("No publicKey or chainCode set");let n=so(t);if(t>=Wi){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=In(_s,this.chainCode,n),s=fl(r.slice(0,32)),o=r.slice(32);if(!_e.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=Se(this.privKey+s,_e.CURVE.n);if(!_e.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=ro.fromHex(this.pubKey).add(ro.fromPrivateKey(s));if(a.equals(ro.ZERO))throw new Error("The tweak was equal to negative P, which made the result key invalid");i.publicKey=a.toRawBytes(!0)}return new Kn(i)}catch{return this.deriveChild(t+1)}}sign(t){if(!this.privateKey)throw new Error("No privateKey set!");return Me(t,32),_e.sign(t,this.privKey).toCompactRawBytes()}verify(t,n){if(Me(t,32),Me(n,64),!this.publicKey)throw new Error("No publicKey set!");let r;try{r=_e.Signature.fromCompact(n)}catch{return!1}return _e.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 Me(n,33),ue(so(t),new Uint8Array([this.depth]),so(this.parentFingerprint),so(this.index),this.chainCode,n)}}function gv(e,t,n,r){Hs(e);const s=Gx({dkLen:32,asyncTick:10},r),{c:o,dkLen:i,asyncTick:a}=s;if(Lt(o),Lt(i),Lt(a),o<1)throw new Error("iterations (c) should be >= 1");const c=qu(t),u=qu(n),l=new Uint8Array(i),f=In.create(e,c),d=f._cloneInto().update(u);return{c:o,dkLen:i,asyncTick:a,DK:l,PRF:f,PRFSalt:d}}function mv(e,t,n,r,s){return e.destroy(),t.destroy(),r&&r.destroy(),gt(s),n}function yv(e,t,n,r){const{c:s,dkLen:o,DK:i,PRF:a,PRFSalt:c}=gv(e,t,n,r);let u;const l=new Uint8Array(4),f=Gn(l),d=new Uint8Array(a.outputLen);for(let h=1,g=0;ge[0]==="あいこくしん";function Hh(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function Rh(e){const t=Hh(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}function jh(e){Me(e,16,20,24,28,32)}function bv(e,t=128){if(Lt(t),t%32!==0||t>256)throw new TypeError("Invalid entropy");return Dh(dr(t/8),e)}const xv=e=>{const t=8-e.length/4;return new Uint8Array([Ee(e)[0]>>t<{if(typeof t!="string")throw new Error("wordlist: non-string element: "+t)}),no.chain(no.checksum(1,xv),no.radix2(11,!0),no.alphabet(e))}function vv(e,t){const{words:n}=Rh(e),r=Kh(t).decode(n);return jh(r),r}function Dh(e,t){return jh(e),Kh(t).encode(e).join(wv(t)?" ":" ")}function kv(e,t){try{vv(e,t)}catch{return!1}return!0}const Ev=e=>Hh("mnemonic"+e);function $v(e,t=""){return yv(_s,Rh(e).nfkd,Ev(t),{c:2048,dkLen:64})}const Dc=`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(` -`),nt={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`},Sv=2**31-1,Gi=new Map,Yi=new Map,dl=()=>bv(Dc,256);function Mh(e,t=0){if(typeof e!="string"||!kv(e,Dc)||t&&e.split(" ").length!==t)throw new Error("Invalid lab mnemonic.");return e}function Ln(e,t){if(!Number.isSafeInteger(e)||e<0||e>Sv)throw new Error(`Invalid ${t}.`);return e}const Xi=new Map;function Mc(e){return Xi.has(e)||Xi.set(e,$v(Mh(e))),Xi.get(e)}function Hn(e){return Gi.has(e)||Gi.set(e,Kn.fromMasterSeed(Mc(e))),Gi.get(e)}function _v(e,t){const n=e.derive(t).privateKey;if(!n)throw new Error("BIP-85 path produced no private key.");return In(_s,Ke("bip-entropy-from-k"),n)}function Av(e,t){const n=`${e}|${Ln(t,"child index")}`;return Yi.has(n)||Yi.set(n,Dh(_v(Hn(e),nt.orgSeed(t)).slice(0,32),Dc)),Yi.get(n)}function Pa(e,t=0,n=1){return Be(Hn(e).derive(nt.wallet(Ln(t,"account"),n)).privateKey)}function Zc(e,t=0,n=1){return Be(Hn(e).derive(nt.segwit(Ln(t,"account"),n)).privateKey)}function Zh(e,t=0,n=1){return Be(Hn(e).derive(nt.segwit(Ln(t,"account"),n)).publicKey)}function gi(e,t=0){return Be(Hn(e).derive(nt.nostr(Ln(t,"account"))).privateKey)}function Vh(e){const t=e.toLowerCase(),n=Be(Hc(Ke(t)));return`0x${[...t].map((r,s)=>parseInt(n[s],16)>=8?r.toUpperCase():r).join("")}`}const qh=e=>Vh(Be(Hc(_e.ProjectivePoint.fromHex(e).toRawBytes(!1).slice(1)).slice(-20)));function zh(e,t=0){return Be(Hn(e).derive(nt.ethereum(Ln(t,"account"))).privateKey)}const Ji=new Map;function Bv(e,t=0){const n=`${e}|${t}`;return Ji.has(n)||Ji.set(n,qh(Hn(e).derive(nt.ethereum(Ln(t,"account"))).publicKey)),Ji.get(n)}function Tv(e,t=0){const n=On.getPublicKey(Hn(e).derive(nt.nostr(Ln(t,"account"))).privateKey);return{pubkey:Be(n),npub:sr.encode("npub",sr.toWords(n))}}const Bt=["taproot","segwit","nostr","ethereum"],mi=(e,t)=>["lineage/v0 keyring",`node: ${e}`,...Bt.map(n=>`${n}: ${t[n]}`)].join(` -`),Iv=["bc","tb","bcrt"],Fh=new Uint8Array(32),ot=e=>{const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),t},Bs=e=>ue(e.length<253?Uint8Array.of(e.length):Uint8Array.of(253,e.length&255,e.length>>8),e),cs=e=>Ee(Ee(e)),Wh=(e,...t)=>{const n=Ee(Ke(e));return Ee(ue(n,n,...t))},Ov=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]);function Ts(e){if(typeof e!="string"||e!==e.toLowerCase())return null;for(const[t,n]of[[sr,0],[lv,1]])try{const{prefix:r,words:s}=t.decode(e,90);if(s[0]===n&&Iv.includes(r))return{network:r,version:n,program:Uint8Array.from(t.fromWords(s.slice(1)))}}catch{}return null}const Vc=e=>(e==null?void 0:e.version)===1&&e.program.length===32,qc=e=>(e==null?void 0:e.version)===0&&e.program.length===20,Gh=({version:e,program:t})=>ue(Uint8Array.of(e?80+e:0,t.length),t),Cv=e=>Wh("BIP0322-signed-message",Ke(e)),Wo=new Uint8Array(8),hl=ue(Wo,Bs(Uint8Array.of(106)));function Pv(e,t){const n=Gh(e),r=ue(Uint8Array.of(0,32),Cv(t));return cs(ue(ot(0),Uint8Array.of(1),new Uint8Array(32),ot(4294967295),Bs(r),ot(0),Uint8Array.of(1),Wo,Bs(n),ot(0)))}function Go(e,t,n=0){const r=Gh(e),s=ue(Pv(e,t),ot(0));if(e.version===0){const o=ue(Uint8Array.of(25,118,169,20),e.program,Uint8Array.of(136,172));return cs(ue(ot(0),cs(s),cs(ot(0)),s,o,Wo,ot(0),cs(hl),ot(0),ot(1)))}return Wh("TapSighash",Uint8Array.of(0,n),ot(0),ot(0),Ee(s),Ee(Wo),Ee(Bs(r)),Ee(ot(0)),Ee(hl),Uint8Array.of(0),ot(0))}const pl=e=>pt.encode(ue(Uint8Array.of(e.length),...e.map(Bs)));function Uv(e){try{const t=pt.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 gl(e,t,n){const r=Ts(e);if(Vc(r))return pl([On.sign(Go(r,t),n,Fh)]);if(!qc(r))throw new Error("BIP-322 here signs for Taproot and P2WPKH addresses only.");const s=_e.sign(Go(r,t),n).toDERRawBytes();return pl([ue(s,Uint8Array.of(1)),_e.getPublicKey(n,!0)])}function ml(e,t,n){const r=Ts(e),s=typeof n=="string"?Uv(n):null;if(!r||!s)return!1;try{if(Vc(r)){const[o]=s;return s.length!==1||!(o.length===64||o.length===65&&o[64]===1)?!1:On.verify(o.slice(0,64),Go(r,t,o.length===65?1:0),r.program)}if(qc(r)){const[o,i]=s;return s.length!==2||i.length!==33||o.at(-1)!==1||!Ov(Rc(Ee(i)),r.program)?!1:_e.verify(_e.Signature.fromDER(o.slice(0,-1)),Go(r,t),i)}}catch{}return!1}const Yh=e=>{const t=Ke(e);return Hc(ue(Ke(`Ethereum Signed Message: -${t.length}`),t))},Xh=e=>typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e)&&Vh(e.slice(2))===e;function Nv(e,t){const n=_e.sign(Yh(e),t);return`0x${Be(n.toCompactRawBytes())}${(27+n.recovery).toString(16)}`}function Lv(e,t,n){if(!Xh(e)||typeof n!="string"||!/^0x[0-9a-f]{130}$/.test(n))return!1;try{const r=mt(n.slice(2)),s=r[64]-27;if(s!==0&&s!==1)return!1;const o=_e.Signature.fromCompact(r.slice(0,64)).addRecoveryBit(s).recoverPublicKey(Yh(t));return qh(o.toRawBytes(!1))===e}catch{return!1}}const Jh=(e,t)=>Ee(Ke(JSON.stringify([0,e,0,1,[],t])));function zc(e){try{const{prefix:t,words:n}=sr.decode(e,90),r=sr.fromWords(n);return t==="npub"&&r.length===32&&e===e.toLowerCase()?Be(Uint8Array.from(r)):null}catch{return null}}const Hv=(e,t)=>Be(On.sign(Jh(Be(On.getPublicKey(t)),e),t,Fh));function Rv(e,t,n){const r=zc(e);try{return!!r&&typeof n=="string"&&/^[0-9a-f]{128}$/.test(n)&&On.verify(n,Jh(r,t),r)}catch{return!1}}const jv={taproot:gl,segwit:gl,nostr:(e,t,n)=>Hv(t,n),ethereum:(e,t,n)=>Nv(t,n)},Kv={taproot:ml,segwit:ml,nostr:Rv,ethereum:Lv};function Qh(e){const t=Ts(e.taproot),n=Ts(e.segwit);return Vc(t)?qc(n)?t.network!==n.network?"its Taproot and SegWit addresses must be on one network":zc(e.nostr)?Xh(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 Dv(e,t,n){const r=Qh(t);if(r)throw new Error(`${r[0].toUpperCase()}${r.slice(1)}.`);const s=mi(e,t);return{...Object.fromEntries(Bt.map(o=>[o,t[o]])),proof:Object.fromEntries(Bt.map(o=>[o,jv[o](t[o],s,n[o])]))}}const ss=new Map;function Mv(e,t){const n=t.proof&&typeof t.proof=="object"&&!Array.isArray(t.proof)?t.proof:{},r=JSON.stringify([e,...Bt.map(s=>[t[s]??null,n[s]??null])]);if(!ss.has(r)){ss.size>=1e3&&ss.clear();let s=Qh(t);if(!s){const o=mi(e,t),i=Bt.find(a=>!Kv[a](t[a],o,n[a]));i&&(s=`the ${i} key did not sign this keyring`)}ss.set(r,s)}return ss.get(r)}const yl=e=>Bt.map(t=>`${t}:${t==="nostr"?zc(e[t]):t==="ethereum"?e[t].toLowerCase():Be(Ts(e[t]).program)}`),Fc="lineage/v0",Zv=["white","green","black"],wl=["sole","llc","series-llc","series","corp"],Vv={sole:"sole proprietor",llc:"LLC","series-llc":"series LLC",series:"series",corp:"corporation"},bl=/^[A-Z]{2}(-[A-Z0-9]{1,3})?$/,qv=/^[0-9a-f]{64}$/,Xt=e=>e.kind==="agent"&&e.root!==e.id,oo="names are 1-40 lowercase letters, digits or hyphens (they become domains)",zv=/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/,os=e=>typeof e=="string"&&zv.test(e),Er=(e,t)=>typeof e=="string"?e.trim().slice(0,t):"";function Ks(e){return String(e??"").toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/,"")}const Xr=e=>e.events.filter(t=>t.protocol===Fc);function Cn(e,{upTo:t=1/0,pending:n=!1}={}){var h,g;const r=new Map,s=[],o=[],i=new Map,a=new Map,c=new Map,u=p=>p.status==="active",l=p=>or(r,p),f=p=>{if(p.keyring&&!p.keyring.retired)for(const w of yl(p.keyring.keys))a.delete(w)},d=(p,w,y,v)=>{p.keyring&&!p.keyring.retired&&(f(p),p.keyring.retired={cause:w,by:y,beat:v})};for(const p of e){const w=p.status==="confirmed";if(w?p.height>t:!n)continue;const y=p.metadata&&typeof p.metadata=="object"&&!Array.isArray(p.metadata)?p.metadata:{},v={id:p.id,op:typeof y.op=="string"?y.op.slice(0,20):"?",beat:w?p.height:null,pending:!w,meta:y,parent:p.parent??null,ok:!0,why:"",node:null,root:null,also:[]},m=v.parent?r.get(v.parent):null,x=v.beat??"cued",k=A=>{v.ok=!1,v.why=A},I=A=>m?u(m)?"":`the ${A} is ${m.status}`:`the ${A} is not in this lineage`;let C="",N=[];const O=(m==null?void 0:m.root)??null;switch(v.op){case"found":if(v.parent)k("a holding has no parent");else if(!os(y.name))k(oo);else if(s.some(A=>u(A)&&A.name===y.name))k(`an active holding is already named ${y.name}`);else{const A=xl(p,y.name,null,"holding");r.set(A.id,A),s.push(A),v.node=A.id}break;case"birth":{const A=y.kind==="agent"?"agent":"org";if(C=I("parent"))k(C);else if(Xt(m))k("agents give birth only once they graduate");else if(!os(y.name))k(oo);else if(l(m).some(P=>u(P)&&P.name===y.name))k(`${m.name} already has an active ${y.name}`);else{const P=xl(p,y.name,m,A);P.index=m.children.filter(E=>r.get(E).kind===A).length,m.children.push(P.id),r.set(P.id,P),v.node=P.id}break}case"award":{const A=r.get(y.to);(C=I("issuer"))?k(C):Xt(m)?k("agents award belts only once they graduate"):!A||A.id===m.id?k("the recipient must be another node in this lineage"):u(A)?!os(y.skill)||!Zv.includes(y.belt)?k("an award needs a skill name and a belt (white, green or black)"):(A.badges=A.badges.filter(P=>P.skill!==y.skill),A.badges.push({skill:y.skill,belt:y.belt,by:m.id,beat:x,id:p.id}),v.node=A.id):k(`the recipient is ${A.status}`);break}case"decide":(C=I("decider"))?k(C):Er(y.title,140)?(m.decisions.push({title:Er(y.title,140),why:Er(y.why,400),beat:x,id:p.id}),v.node=m.id):k("a decision needs a title");break;case"make":(C=I("maker"))?k(C):os(y.name)?m.made.some(A=>i.get(A).name===y.name)?k(`there is already a ${y.name} by ${m.name}`):(i.set(p.id,{id:p.id,name:y.name,note:Er(y.note,280),maker:m.id,beat:x}),m.made.push(p.id),v.node=m.id):k(oo);break;case"graduate":{const A=r.get(y.of);if(C=I("parent"))k(C);else if(!A||A.parent!==m.id)k("only its parent can graduate a child");else if(!u(A))k(`the child is ${A.status}`);else if(A.edge==="adopted")k("already graduated");else if(A.joining)k(`${A.name} is joining ${r.get(A.joining.to).name}`);else{const P=A.root,E=b=>{b.root=A.id;for(const _ of l(b))_.root===P&&E(_)};A.edge="adopted",A.graduated=x,v.node=A.id,v.rekeys=!0,E(A),s.push(A);const S=b=>{d(b,"graduate",A.id,x);for(const _ of l(b))_.edge==="derived"&&S(_)};S(A)}break}case"close":if(!m)k(v.parent?"that node is not in this lineage":"a close spends the node it closes");else if(!u(m))k(`already ${m.status}`);else{const A=P=>{P.status="closed",P.closed=x,d(P,"close",m.id,x);for(const E of l(P))E.edge==="derived"&&u(E)&&(v.also.push(E.id),A(E))};A(m),v.node=m.id}break;case"charter":{const A=y.form==="series",P=A?r.get(y.of):m,E=m&&(m.kind==="holding"||m.kind==="agent");(C=I(A?"master":"node"))?k(C):wl.includes(y.form)?!A&&y.of!==void 0&&y.of!==m.id?k("a node charters itself; only a series is chartered by its master"):A&&(!P||!ep(r,P,m))?k("a series must descend from its master"):A&&!u(P)?k(`the series is ${P.status}`):A&&P.kind!=="org"?k("only orgs become series"):A&&((h=m.charter)==null?void 0:h.form)!=="series-llc"?k(`${m.name} is not chartered as a series LLC`):A&&y.jurisdiction!==void 0?k("a series takes its master's jurisdiction"):y.form==="sole"&&!E?k("a sole proprietor is a person: a holding or an agent"):y.form!=="sole"&&!A&&Xt(m)?k("an agent graduates before it incorporates"):y.form!=="sole"&&!A&&!bl.test(y.jurisdiction??"")||y.form==="sole"&&y.jurisdiction!==void 0&&!bl.test(y.jurisdiction)?k("a jurisdiction is an ISO code such as US-WY"):y.provider!==void 0&&!os(y.provider)?k(`a provider's name follows the name rule: ${oo}`):y.filing!==void 0&&!qv.test(y.filing)?k("a filing is the SHA-256 of the filed documents, in hex"):(P.charter={id:p.id,beat:x,form:y.form,jurisdiction:A?null:y.jurisdiction??null,legal:Er(y.legal,120)||null,provider:y.provider??null,filing:y.filing??null,master:A?m.id:null},v.node=P.id):k(`a charter's form is ${wl.join(", ")}`);break}case"keyring":{if(C=I("node"))k(C);else if(C=Mv(m.id,y))k(C);else{const A=Object.fromEntries(Bt.map(S=>[S,y[S]])),P=yl(A),E=P.findIndex(S=>a.has(S)&&a.get(S)!==m.id);if(E>=0)k(`its ${Bt[E]} key is already bound to ${r.get(a.get(P[E])).name}`);else{f(m),m.keyring={id:p.id,beat:x,keys:A,retired:null};for(const S of P)a.set(S,m.id);v.node=m.id}}break}case"join":case"adopt":{const A=v.op==="join",P=A?m:r.get(y.of),E=A?r.get(y.to)??null:m;if(C=I(A?"node":"parent"))k(C);else if(C=nn(r,P,E))k(C);else{const S=`${E.id}>${P.id}`,b=A?c.get(S):((g=P.joining)==null?void 0:g.to)===E.id?P.joining:null;if(v.node=P.id,N=[P.root,E.root],!b&&A)P.joining={to:E.id,id:p.id,beat:x};else if(!b)c.set(S,{id:p.id});else{c.delete(S),P.joining=null;const _=P.root,U=j=>{j.root=E.root;for(const L of l(j))L.root===_&&U(L)};P.moves.push({from:P.parent,index:P.index,to:E.id,beat:x,join:A?p.id:b.id,adopt:A?b.id:p.id}),P.index=E.children.filter(j=>r.get(j).kind===P.kind).length,P.parent=E.id,E.children.push(P.id),U(P),d(P,"move",E.id,x),v.rekeys=!0}}break}default:k("not a lineage/v0 op")}const R=v.node?r.get(v.node).root:null;v.root=O??R,v.roots=[...new Set([v.root,R,...N].filter(Boolean))],o.push(v)}return{nodes:r,roots:s,log:o,items:i,bound:a}}function xl(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,closed:null,joining:null,moves:[]}}function ep(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 or=(e,t)=>[...new Set(t.children)].map(n=>e.get(n)).filter(n=>n.parent===t.id);function nn(e,t,n){return t?t.kind!=="org"?"only orgs change hands":t.status!=="active"?`${t.name} is ${t.status}`:t.root===t.id?`${t.name} is a holding of its own, and only orgs inside a holding change hands`:or(e,t).some(r=>r.edge==="derived"&&r.status==="active")?`${t.name} has derived children, and an org changes hands alone`:n===void 0?"":n?n.status!=="active"?`the new parent is ${n.status}`:Xt(n)?"agents adopt only once they graduate":n.id===t.id||ep(e,n,t)?`${t.name} cannot join itself or anything below it`:n.id===t.parent?`${t.name} is already ${n.name}'s`:or(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":"the org must be a node in this lineage"}function fs(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!=="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 Fv(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),l=u||o.root!==t;if(n.push({type:"node",node:o,guide:i,path:o.id===t?"●":`${c?c.index:o.index}'`,away:l,moved:u}),l)return;const f={agent:[],org:[]};for(const h of o.children){const g=e.nodes.get(h),p=f[g.kind==="agent"?"agent":"org"];p.push([g,{parent:o.id,index:p.length}])}const d=[["agents",f.agent],["orgs",f.org]].filter(([,h])=>h.length);d.forEach(([h,g],p)=>{const w=p===d.length-1,y=a+(w?" ":"│ ");n.push({type:"group",label:h,guide:a+(w?"└─ ":"├─ ")}),g.forEach(([v,m],x)=>{const k=x===g.length-1;s(v,y+(k?"└─ ":"├─ "),y+(k?" ":"│ "),m)})})};return r&&s(r,"",""),n}function Wv(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 Vr(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 tp(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 “${Er(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)} · ${Vv[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?`, from ${r(a.from)}`:e.op==="join"?`, for ${r(i)} to adopt`:`, once ${r(o)} joins`}`}default:return e.op}}const kn=Be,Gv=ue,Ua=mt,Yv=hr,En="super-testnet-local-v0";class Pn{constructor(t){if(!/^[0-9a-f]{64}$/.test(t)||!_e.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=kn(On.getPublicKey(t)),this.address=ps.p2tr.fromPubKey(this.pubkey,"regtest"),this.script=["OP_1",this.pubkey]}static create(){return new Pn(kn(_e.utils.randomPrivateKey()))}static load(t){if((t==null?void 0:t.network)!==En||(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 Pn(t.secret)}backup(){return{kind:"test-wallet",version:1,network:En,secret:this.secret}}sign(t,n,r=0){return Xn.taproot.sign(this.secret,t,r,n?{extension:n}:{}).hex}}const io=50*1e8,ao="0".repeat(64),vl=e=>kn(Ee(new TextEncoder().encode(JSON.stringify(e)))),xr=(e,t)=>`${e}:${t}`,et=e=>Ue.encode(e,!1).hex,he=(e,t)=>{if(!e)throw new Error(t)},kl=/^5120[0-9a-f]{64}$/,co=/^0014[0-9a-f]{40}$/,np=64,ut=8,Xv=e=>kn(Rc(Ee(Ua(e))));function Jv(e,t){const[n,r]=e.vin[t].witness;return _e.verify(n.slice(0,-2),Xn.segwit.hash(e,t,{pubkey:r,sigflag:1}),r,{lowS:!0,format:"der"})}const Qi=(e,...t)=>{const n=Ee(new TextEncoder().encode(e));return Ee(Gv(n,n,...t))},Qv=e=>e<253?Uint8Array.of(e):Uint8Array.of(253,e&255,e>>8);function ek(e,t){const[n,r,s]=e.vin[t].witness,o=Ua(s),i=Ua(r);if(o.length<33||(o.length-33)%32||i.length>65535||!/^20[0-9a-f]{64}ac/.test(r))return!1;const a=Qi("TapLeaf",Uint8Array.of(o[0]&254),Qv(i.length),i);let c=a;for(let f=33;f=_e.CURVE.n)return!1;const l=_e.ProjectivePoint.fromHex(`02${kn(o.slice(1,33))}`).add(_e.ProjectivePoint.BASE.multiply(u)).toAffine();return`5120${l.x.toString(16).padStart(64,"0")}`!==et(e.vin[t].prevout.scriptPubKey)||Number(l.y&1n)!==(o[0]&1)?!1:On.verify(n,Xn.taproot.hash(e,t,{extension:kn(a)}),r.slice(2,66))}class yi{constructor(t){if(this.blocks=[],this.mempool=[],this.utxos=new Map,this.transactions=new Map,this.imports=[],t){he(t.network===En&&t.version===1,"Unsupported local chain version/network."),he(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:En,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}){he(/^[0-9a-f]{64}$/.test(t)&&Number.isSafeInteger(n)&&n>=0&&Number.isSafeInteger(r)&&r>=330&&r<=io&&(kl.test(s)||co.test(s)),"Invalid imported coin."),he(!this.utxos.has(xr(t,n))&&!this.transactions.has(t)&&!this.imported(t,n),"That coin is already in this chain."),this.utxos.set(xr(t,n),{txid:t,vout:n,value:r,scriptPubKey:s,height:0,ranges:Ol(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=>et(n.scriptPubKey)===et(t))}satLocation(t){for(const n of this.utxos.values()){const r=lo(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 w,y,v;he(typeof t=="string"&&t.length<4e4&&/^(?:[a-f0-9]{2})+$/.test(t),"Invalid raw transaction.");const s=ee.decode(t),o=ee.util.getTxid(s);he(!this.transactions.has(o),"Duplicate transaction."),he(s.version===2&&s.locktime===0,"Unsupported transaction version or locktime.");const i=!r&&s.vin.some(m=>{var x;return((x=m.witness)==null?void 0:x.length)===3}),a=r?1:i?2:ut,c=r?np:i?2:ut;he(s.vin.length>=1&&s.vin.length<=a&&s.vout.length>=1&&s.vout.length<=c,"Unsupported transaction shape.");let u=0;for(const m of s.vout){const x=Number(m.value);he(Number.isSafeInteger(x)&&x>=330&&x<=io,"Invalid output amount.");const k=et(m.scriptPubKey);he(kl.test(k)||co.test(k),"Only Taproot and P2WPKH outputs are supported."),u+=x}let l,f=[];const d=s.vin.findIndex(m=>{var x;return((x=m.witness)==null?void 0:x.length)===3}),h=s.vin[d<0?0:d];if(r)he(h.txid===ao&&h.vout===4294967295&&u===io,"Invalid local coinbase."),he(et(h.scriptSig)===Ue.encode([new TextEncoder().encode(`${En}:${n}`)],!1).hex,"Wrong coinbase height."),he(!((w=h.witness)!=null&&w.length),"Unexpected coinbase witness.");else{f=s.vin.map(x=>this.utxos.get(xr(x.txid,x.vout))),he(f.every(Boolean),"Input is missing or already spent."),he(new Set(s.vin.map(x=>xr(x.txid,x.vout))).size===s.vin.length,"Duplicate input."),s.vin.forEach((x,k)=>{var C,N,O;he(x.sequence==="ffffffff"&&et(x.scriptSig)==="","Unsupported input flags."),x.prevout={value:f[k].value,scriptPubKey:f[k].scriptPubKey};const I=et(f[k].scriptPubKey);if(co.test(I)){const[R,A]=x.witness??[];he(k!==d&&((C=x.witness)==null?void 0:C.length)===2,"Unsupported witness."),he(/^30[0-9a-f]{12,140}01$/.test(R)&&/^0[23][0-9a-f]{64}$/.test(A)&&Xv(A)===I.slice(4),"P2WPKH spends need a SIGHASH_ALL signature by the key they pay.");return}he(((N=x.witness)==null?void 0:N.length)===1||k===d&&((O=x.witness)==null?void 0:O.length)===3,"Unsupported witness."),he(/^[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.")}),he(f.reduce((x,k)=>x+k.value,0)-u===X,"v0 requires a fixed 500 sat fee per transaction.");let m={};if(h.witness.length===3){const x=Bc(h.witness),k=d;if(he(Number(s.vout[k].value)===Ut,"Invalid reveal postage."),he(et(s.vout[k].scriptPubKey)===`5120${x.pubkey}`,"Reveal must return to its signing wallet."),x.parent){const I=d===0?1:0,C=f[I];he((y=C==null?void 0:C.inscriptions)==null?void 0:y.some(N=>N.id===x.parent),"Referenced parent inscription must actually be spent."),he(s.vout.length===2&&Number(s.vout[I].value)===C.value&&et(C.scriptPubKey)===`5120${x.pubkey}`&&et(s.vout[I].scriptPubKey)===et(C.scriptPubKey),"Parent must be owned and preserved in the same wallet.")}else s.vin.length===2&&(he(d===1&&((v=f[0].inscriptions)==null?void 0:v.length)&&x.pointer!==void 0,"Reinscription spend requires correct tag and owned sat."),he(Number(s.vout[0].value)===f[0].value&&et(s.vout[0].scriptPubKey)===et(f[0].scriptPubKey)&&et(f[0].scriptPubKey)===`5120${x.pubkey}`,"Reinscription sat must be returned to owner."));m={pubkey:x.pubkey},l={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:Ut}}s.vin.forEach((x,k)=>{let I=!1;try{I=co.test(et(f[k].scriptPubKey))?Jv(s,k):k===d?ek(s,k)||Xn.taproot.verify(s,k,m):Xn.taproot.verify(s,k,{})}catch{}he(I,"Invalid signature or Taproot commitment.")})}const g=Ul(s,f,n,r),p=f.flatMap(m=>m.inscriptions??[]);if(l){const m=BigInt(l.pointer??0),x=m{var I;return((I=k.inscription)==null?void 0:I.sat)===l.sat}).length,p.push(l)}return he(p.every(m=>g.some(x=>lo(x,m.sat)!==null)),"Local lab protects inscription sats from fee loss."),r||s.vin.forEach(m=>this.utxos.delete(xr(m.txid,m.vout))),s.vout.forEach((m,x)=>{const k=p.filter(I=>lo(g[x],I.sat)!==null);this.utxos.set(xr(o,x),{txid:o,vout:x,value:Number(m.value),scriptPubKey:m.scriptPubKey,height:n,ranges:g[x],inscriptions:k,...k.length?{inscription:k[0]}:{}})}),this.transactions.set(o,{txid:o,raw:t,height:n,coinbase:r,tx:s,...l?{inscription:l}:{}}),o}submitPackage(t){he(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;he(t.height===this.blocks.length+1&&t.previous===(((i=this.blocks.at(-1))==null?void 0:i.hash)??ao),"Invalid block ancestry."),he(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;he(vl(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([xe(io,t)])}mineTo(t){var a;const n=new yi({...this.snapshot(),mempool:[]}),r=this.blocks.length+1,s=ee.create({vin:[{txid:ao,vout:4294967295,scriptSig:[new TextEncoder().encode(`${En}:${r}`)]}],vout:t}),o={height:r,previous:((a=this.blocks.at(-1))==null?void 0:a.hash)??ao,time:Date.now(),raws:[ee.encode(s).hex,...this.mempool]},i={...o,hash:vl(o)};return n.acceptBlock(i),Object.assign(this,n),i}}const rp="lineage-claim",Na=330,Yo=e=>Ue.encode(e,!1).hex,El=e=>({txid:e.txid,vout:e.vout,value:e.value,script:Yo(e.scriptPubKey)}),ea=/^[0-9a-f]{64}$/,tk=/^5120[0-9a-f]{64}$/;function wi(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 sp(e){return ee.create({vin:[Xe(e.holder.txid,e.holder.vout,e.holder.value,e.holder.script),Xe(e.payer.txid,e.payer.vout,e.payer.value,e.payer.script)],vout:[xe(e.holder.value,["OP_1",e.to]),xe(e.payer.value-X,["OP_1",e.to])]})}function nk(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=wi(e,t);if(!s)throw new Error("That inscription is not in an unspent output.");if(Yo(s.scriptPubKey)===Yo(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>=X+Na});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:rp,version:1,inscription:t,carried:s.inscriptions.map(c=>c.id),holder:El(s),payer:El(o),to:n.pubkey,at:r},a=sp(i);return i.txid=ee.util.getTxid(a),i.sig=n.sign(a,void 0,1),i}function rk(e,t,n){const r=ok(t);if((n==null?void 0:n.kind)!=="test-wallet")throw new Error("Countersigning needs a local test wallet.");if(Yo(n.script)!==r.holder.script)throw new Error("Only the current holder can countersign.");if(sk(e,r)!=="open")throw new Error("This claim is stale: an input it spends was already spent.");const s=sp(r);return s.vin[1].witness=[r.sig],s.vin[0].witness=[n.sign(s,void 0,0)],e.submitPackage([ee.encode(s).hex]),ee.util.getTxid(s)}function sk(e,t){return e.utxos.has(`${t.holder.txid}:${t.holder.vout}`)&&e.utxos.has(`${t.payer.txid}:${t.payer.vout}`)?"open":"stale"}function ok(e){const t=n=>n&&ea.test(n.txid)&&Number.isSafeInteger(n.vout)&&n.vout>=0&&Number.isSafeInteger(n.value)&&n.value>=Na&&tk.test(n.script);if((e==null?void 0:e.kind)!==rp||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=$l);const i=new Uint8Array(o*s),a=In.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let l=0;lak(e,ik(e,t,n),r,s);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const bn=BigInt(0),De=BigInt(1),na=BigInt(2),uk=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 fk(e,t={}){const n=hh("edwards",e,t,t.FpFnLE),{Fp:r,Fn:s}=n;let o=n.CURVE;const{h:i}=o;Wr(t,{},{uvRatio:"function"});const a=na<r.create(w),u=t.uvRatio||((w,y)=>{try{return{isValid:!0,value:r.sqrt(r.div(w,y))}}catch{return{isValid:!1,value:bn}}});if(!lk(r,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function l(w,y,v=!1){const m=v?De:bn;return As("coordinate "+w,y,m,a),y}function f(w){if(!(w instanceof g))throw new Error("ExtendedPoint expected")}const d=Ko((w,y)=>{const{X:v,Y:m,Z:x}=w,k=w.is0();y==null&&(y=k?uk:r.inv(x));const I=c(v*y),C=c(m*y),N=r.mul(x,y);if(k)return{x:bn,y:De};if(N!==De)throw new Error("invZ was invalid");return{x:I,y:C}}),h=Ko(w=>{const{a:y,d:v}=o;if(w.is0())throw new Error("bad point: ZERO");const{X:m,Y:x,Z:k,T:I}=w,C=c(m*m),N=c(x*x),O=c(k*k),R=c(O*O),A=c(C*y),P=c(O*c(A+N)),E=c(R+c(v*c(C*N)));if(P!==E)throw new Error("bad point: equation left != right (1)");const S=c(m*x),b=c(k*I);if(S!==b)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(y,v,m,x){this.X=l("x",y),this.Y=l("y",v),this.Z=l("z",m,!0),this.T=l("t",x),Object.freeze(this)}static CURVE(){return o}static fromAffine(y){if(y instanceof g)throw new Error("extended point not allowed");const{x:v,y:m}=y||{};return l("x",v),l("y",m),new g(v,m,De,c(v*m))}static fromBytes(y,v=!1){const m=r.BYTES,{a:x,d:k}=o;y=Gu(Et(y,m,"point")),tr(v,"zip215");const I=Gu(y),C=y[m-1];I[m-1]=C&-129;const N=nr(I),O=v?a:r.ORDER;As("point.y",N,bn,O);const R=c(N*N),A=c(R-De),P=c(k*R-x);let{isValid:E,value:S}=u(A,P);if(!E)throw new Error("bad point: invalid y coordinate");const b=(S&De)===De,_=(C&128)!==0;if(!v&&S===bn&&_)throw new Error("bad point: x=0 and x_0=1");return _!==b&&(S=c(-S)),g.fromAffine({x:S,y:N})}static fromHex(y,v=!1){return g.fromBytes(we("point",y),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,v=!0){return p.createCache(this,y),v||this.multiply(na),this}assertValidity(){h(this)}equals(y){f(y);const{X:v,Y:m,Z:x}=this,{X:k,Y:I,Z:C}=y,N=c(v*C),O=c(k*x),R=c(m*C),A=c(I*x);return N===O&&R===A}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:y}=o,{X:v,Y:m,Z:x}=this,k=c(v*v),I=c(m*m),C=c(na*c(x*x)),N=c(y*k),O=v+m,R=c(c(O*O)-k-I),A=N+I,P=A-C,E=N-I,S=c(R*P),b=c(A*E),_=c(R*E),U=c(P*A);return new g(S,b,U,_)}add(y){f(y);const{a:v,d:m}=o,{X:x,Y:k,Z:I,T:C}=this,{X:N,Y:O,Z:R,T:A}=y,P=c(x*N),E=c(k*O),S=c(C*m*A),b=c(I*R),_=c((x+k)*(N+O)-P-E),U=b-S,j=b+S,L=c(E-v*P),M=c(_*U),V=c(j*L),W=c(_*L),le=c(U*j);return new g(M,V,le,W)}subtract(y){return this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:v,f:m}=p.cached(this,y,x=>zn(g,x));return zn(g,[v,m])[0]}multiplyUnsafe(y,v=g.ZERO){if(!s.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===bn?g.ZERO:this.is0()||y===De?this:p.unsafe(this,y,m=>zn(g,m),v)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return p.unsafe(this,o.n).is0()}toAffine(y){return d(this,y)}clearCofactor(){return i===De?this:this.multiplyUnsafe(i)}toBytes(){const{x:y,y:v}=this.toAffine(),m=r.toBytes(v);return m[m.length-1]|=y&De?128:0,m}toHex(){return Be(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(y){return zn(g,y)}static msm(y,v){return dh(g,s,y,v)}_setWindowSize(y){this.precompute(y)}toRawBytes(){return this.toBytes()}}g.BASE=new g(o.Gx,o.Gy,De,c(o.Gx*o.Gy)),g.ZERO=new g(bn,De,De,bn),g.Fp=r,g.Fn=s;const p=new fh(g,s.BITS);return g.BASE.precompute(8),g}function dk(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');Wr(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||dr,c=n.adjustScalarBytes||(O=>O),u=n.domain||((O,R,A)=>{if(tr(A,"phflag"),R.length||A)throw new Error("Contexts/pre-hash are not supported");return O});function l(O){return i.create(nr(O))}function f(O){const R=m.secretKey;O=we("private key",O,R);const A=we("hashed private key",t(O),2*R),P=c(A.slice(0,R)),E=A.slice(R,2*R),S=l(P);return{head:P,prefix:E,scalar:S}}function d(O){const{head:R,prefix:A,scalar:P}=f(O),E=s.multiply(P),S=E.toBytes();return{head:R,prefix:A,scalar:P,point:E,pointBytes:S}}function h(O){return d(O).pointBytes}function g(O=Uint8Array.of(),...R){const A=ue(...R);return l(t(u(A,we("context",O),!!r)))}function p(O,R,A={}){O=we("message",O),r&&(O=r(O));const{prefix:P,scalar:E,pointBytes:S}=d(R),b=g(A.context,P,O),_=s.multiply(b).toBytes(),U=g(A.context,_,S,O),j=i.create(b+U*E);if(!i.isValid(j))throw new Error("sign failed: invalid s");const L=ue(_,i.toBytes(j));return Et(L,m.signature,"result")}const w={zip215:!0};function y(O,R,A,P=w){const{context:E,zip215:S}=P,b=m.signature;O=we("signature",O,b),R=we("message",R),A=we("publicKey",A,m.publicKey),S!==void 0&&tr(S,"zip215"),r&&(R=r(R));const _=b/2,U=O.subarray(0,_),j=nr(O.subarray(_,b));let L,M,V;try{L=e.fromBytes(A,S),M=e.fromBytes(U,S),V=s.multiplyUnsafe(j)}catch{return!1}if(!S&&L.isSmallOrder())return!1;const W=g(E,M.toBytes(),L.toBytes(),R);return M.add(L.multiplyUnsafe(W)).subtract(V).clearCofactor().is0()}const v=o.BYTES,m={secretKey:v,publicKey:v,signature:2*v,seed:v};function x(O=a(m.seed)){return Et(O,m.seed,"seed")}function k(O){const R=N.randomSecretKey(O);return{secretKey:R,publicKey:h(R)}}function I(O){return Ls(O)&&O.length===i.BYTES}function C(O,R){try{return!!e.fromBytes(O,R)}catch{return!1}}const N={getExtendedPublicKey:d,randomSecretKey:x,isValidSecretKey:I,isValidPublicKey:C,toMontgomery(O){const{y:R}=e.fromBytes(O),A=m.publicKey,P=A===32;if(!P&&A!==57)throw new Error("only defined for 25519 and 448");const E=P?o.div(De+R,De-R):o.div(R-De,R+De);return o.toBytes(E)},toMontgomerySecret(O){const R=m.secretKey;Et(O,R);const A=t(O.subarray(0,R));return c(A).subarray(0,R)},randomPrivateKey:x,precompute(O=8,R=e.BASE){return R.precompute(O,!1)}};return Object.freeze({keygen:k,getPublicKey:h,sign:p,verify:y,utils:N,Point:e,lengths:m})}function hk(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=pr(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 pk(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function gk(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:s}=hk(e),o=fk(t,n),i=dk(o,r,s);return pk(e,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const is=BigInt(0),vr=BigInt(1),uo=BigInt(2);function mk(e){return Wr(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function yk(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||dr,u=a?255:448,l=a?32:56,f=BigInt(a?9:5),d=BigInt(a?121665:39081),h=a?uo**BigInt(254):uo**BigInt(447),g=a?BigInt(8)*uo**BigInt(251)-vr:BigInt(4)*uo**BigInt(445)-vr,p=h+g+vr,w=E=>Se(E,n),y=v(f);function v(E){return Cc(w(E),l)}function m(E){const S=we("u coordinate",E,l);return a&&(S[31]&=127),w(nr(S))}function x(E){return nr(s(we("scalar",E,l)))}function k(E,S){const b=N(m(S),x(E));if(b===is)throw new Error("invalid private or public key received");return v(b)}function I(E){return k(E,y)}function C(E,S,b){const _=w(E*(S-b));return S=w(S-_),b=w(b+_),{x_2:S,x_3:b}}function N(E,S){As("u",E,is,n),As("scalar",S,h,p);const b=S,_=E;let U=vr,j=is,L=E,M=vr,V=is;for(let le=BigInt(u-1);le>=is;le--){const ce=b>>le&vr;V^=ce,{x_2:U,x_3:L}=C(V,U,L),{x_2:j,x_3:M}=C(V,j,M),V=ce;const ne=U+j,pe=w(ne*ne),ge=U-j,Ne=w(ge*ge),de=pe-Ne,ve=L+M,Mt=L-M,lt=w(Mt*ne),qe=w(ve*ge),Zt=lt+qe,es=lt-qe;L=w(Zt*Zt),M=w(_*w(es*es)),U=w(pe*Ne),j=w(de*(pe+w(d*de)))}({x_2:U,x_3:L}=C(V,U,L)),{x_2:j,x_3:M}=C(V,j,M);const W=o(j);return w(U*W)}const O={secretKey:l,publicKey:l,seed:l},R=(E=c(l))=>(Me(E,O.seed),E);function A(E){const S=R(E);return{secretKey:S,publicKey:I(S)}}return{keygen:A,getSharedSecret:(E,S)=>k(E,S),getPublicKey:E=>I(E),scalarMult:k,scalarMultBase:I,utils:{randomSecretKey:R,randomPrivateKey:R},GuBytes:y.slice(),lengths:O}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const wk=BigInt(1),Sl=BigInt(2),bk=BigInt(3),xk=BigInt(5),vk=BigInt(8),Wc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),op={p:Wc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:vk,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ip(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),o=Wc,a=e*e%o*e%o,c=Ie(a,Sl,o)*a%o,u=Ie(c,wk,o)*e%o,l=Ie(u,xk,o)*u%o,f=Ie(l,t,o)*l%o,d=Ie(f,n,o)*f%o,h=Ie(d,r,o)*d%o,g=Ie(h,s,o)*h%o,p=Ie(g,s,o)*h%o,w=Ie(p,t,o)*l%o;return{pow_p_5_8:Ie(w,Sl,o)*e%o,b2:a}}function ap(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const _l=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function kk(e,t){const n=Wc,r=Se(t*t*t,n),s=Se(r*r*t,n),o=ip(e*s).pow_p_5_8;let i=Se(e*r*o,n);const a=Se(t*i*i,n),c=i,u=Se(i*_l,n),l=a===e,f=a===Se(-e,n),d=a===Se(-e*_l,n);return l&&(i=c),(f||d)&&(i=u),v2(i,n)&&(i=Se(-i,n)),{isValid:l||f,value:i}}const cp=pr(op.p,{isLE:!0}),Ek={...op,Fp:cp,hash:_s,adjustScalarBytes:ap,uvRatio:kk},bi=gk(Ek),up=(()=>{const e=cp.ORDER;return yk({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:n,b2:r}=ip(t);return Se(Ie(n,bk,e)*r,e)},adjustScalarBytes:ap})})(),$k=Ke("lineage/v0"),Ht=(e,t)=>ck(Ee,e,$k,Ke(t),32),xi=e=>{const t=Uint8Array.from(e);return t[0]&=248,t[31]&=127,t[31]|=64,t},lp=e=>{const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t},yt=e=>ue(lp(e.length),e),Gc=e=>ue(yt(Ke("ssh-ed25519")),yt(e)),La=(e,t)=>`ssh-ed25519 ${pt.encode(Gc(e))}${t?` ${t}`:""}`,Ha=e=>`SHA256:${pt.encode(Ee(Gc(e))).replace(/=+$/,"")}`;function Sk(e){const t=mt(e),n=r=>bi.getPublicKey(Ht(t,r));return{ssh:n("ssh"),git:n("git"),dkim:n("dkim"),wg:up.getPublicKey(xi(Ht(t,"wg")))}}function _k(e){const t=n=>bi.getPublicKey(Ht(e,n));return{"ssh-ca":t("node/ssh-ca"),mtls:t("node/mtls"),noise:up.getPublicKey(xi(Ht(e,"node/noise")))}}function Ak(e,t,n,r){return[["ssh",Ha(e.ssh),La(e.ssh,t)],["git",Ha(e.git),`${t} namespaces="git" ${La(e.git,t)}`],["dkim",`${n}._domainkey.${r}`,`${n}._domainkey.${r}. IN TXT "v=DKIM1; k=ed25519; p=${pt.encode(e.dkim)}"`],["wg",pt.encode(e.wg),`[Peer] -# ${t} -PublicKey = ${pt.encode(e.wg)}`]]}function Bk(e,t){return[["ssh-ca",Ha(e["ssh-ca"]),La(e["ssh-ca"],`lineage-ca@${t}`)],["mtls",pt.encode(e.mtls),null],["noise",`mkey:${Be(e.noise)}`,null]]}const Tk=mt("302e020100300506032b657004220420");function fp(e,t,n){const r=Ee(e).slice(0,4);let s=ue(r,r,yt(Ke("ssh-ed25519")),yt(t),yt(ue(e,t)),yt(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"),yt(Ke("none")),yt(Ke("none")),yt(new Uint8Array(0)),lp(1),yt(Gc(t)),yt(s));return`-----BEGIN OPENSSH PRIVATE KEY----- -${pt.encode(o).match(/.{1,70}/g).join(` -`)} ------END OPENSSH PRIVATE KEY----- -`}const Ik=(e,t)=>`-----BEGIN ${e}----- -${pt.encode(t).match(/.{1,64}/g).join(` -`)} ------END ${e}----- -`;function Ok(e,t){const n=mt(e),r=s=>{const o=Ht(n,s);return fp(o,bi.getPublicKey(o),t)};return[["ssh","OpenSSH private key",r("ssh")],["git","OpenSSH private key",r("git")],["dkim","Ed25519 private key (base64)",pt.encode(Ht(n,"dkim"))],["wg","Interface entry",`[Interface] -PrivateKey = ${pt.encode(xi(Ht(n,"wg")))}`]]}function Ck(e,t){const n=Ht(e,"node/ssh-ca");return[["ssh-ca","OpenSSH private key",fp(n,bi.getPublicKey(n),`lineage-ca@${t}`)],["mtls","Private key (PKCS#8 PEM)",Ik("PRIVATE KEY",ue(Tk,Ht(e,"node/mtls")))],["noise","noise_private.key",`privkey:${Be(xi(Ht(e,"node/noise")))}`]]}const Pk=["bip86","tapkey","wallet"],Yc=()=>({scheme:"bip86",roots:{},adopted:{}}),Uk=e=>ui.getPubKey(e)[0];function dp(e,t,n){return e.scheme==="wallet"?Pa(t,n):ui.getSecKey(e.scheme==="tapkey"?gi(t,n):Pa(t,n))[0]}const hp=(e,t)=>e.scheme==="tapkey"?nt.nostr(t):nt.wallet(t),Nk=(e,t)=>new Pn(dp(e,t,0)),Ae=e=>Ue.encode(e,!1).hex;function en(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.id]);const s=t.nodes.get(n.parent);if(n.kind==="agent"){const i=en(e,t,s);return i&&{...i,account:n.index+1}}const o=en(e,t,s);return o&&{mnemonic:Av(o.mnemonic,n.index),account:0,origin:o.origin,steps:[...o.steps,`${n.index}'`]}}const ra=new Map;function Te(e,t,n){const r=en(e,t,n);if(!r)return null;const s=`${e.scheme}|${r.mnemonic}|${r.account}`;if(!ra.has(s)){const{npub:u,pubkey:l}=Tv(r.mnemonic,r.account);ra.set(s,{wallet:new Pn(dp(e,r.mnemonic,r.account)),npub:u,pubkey:l})}const{wallet:o,npub:i,pubkey:a}=ra.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} · ${hp(e,r.account)}`}}function Xc(e,t,n){const r=en(e,t,n);if(!r)return null;const s=Te(e,t,n),o=Zh(r.mnemonic,r.account);return{taproot:{address:s.wallet.address,path:hp(e,r.account)},segwit:{address:ps.p2wpkh.fromPubKey(o,"regtest"),path:nt.segwit(r.account)},tapkey:{address:ps.p2tr.fromPubKey(Uk(s.pubkey),"regtest"),path:nt.nostr(r.account)},npub:{address:s.npub,path:nt.nostr(r.account)},ethereum:{address:Bv(r.mnemonic,r.account),path:nt.ethereum(r.account)}}}function Lk(e,t,n){const r=en(e,t,n);if(!r)return null;const s=Te(e,t,n),o=Xc(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:Zc(i,a),nostr:gi(i,a),ethereum:zh(i,a)}}}function Jc(e,t,n){const r=wi(e.chain,n);if(!r)return null;const s=Ae(r.scriptPubKey),o=t.nodes.get(n),i=Te(e.keys,t,o),a=o&&Te(e.keys,t,t.nodes.get(o.parent));return i&&Ae(i.wallet.script)===s?{wallet:i.wallet,who:"own"}:e.wallet&&Ae(e.wallet.script)===s?{wallet:e.wallet,who:"lab"}:a&&Ae(a.wallet.script)===s?{wallet:a.wallet,who:"parent"}:{wallet:null,who:"other",script:s}}function Ds(e,t){const n=e.nodes.get(t),r=[n];for(const s of or(e.nodes,n))s.status==="active"&&s.edge==="derived"&&r.push(...Ds(e,s.id));return r}function Ra(e,t){const n=[];for(let r=t;r;r=e.nodes.get(r.parent))n.push(r.name);return n.join(".")}function Hk(e,t,n){const r=en(e,t,n);if(!r)return null;if(n.kind!=="agent")return Bk(_k(Mc(r.mnemonic)),Ra(t,n));const s=Ra(t,t.nodes.get(n.parent));return Ak(Sk(gi(r.mnemonic,r.account)),`${n.name}@${s}`,n.name,s)}const Rk=Nh(Ee),as=(e,t=239)=>Rk.encode(ue(Uint8Array.of(t),mt(e),Uint8Array.of(1))),jk=e=>sr.encode("nsec",sr.toWords(mt(e))),Kk="0123456789()[],'/*abcdefgh@:$%{}IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ",Dk=[0xf5dee51989n,0xa9fdca3312n,0x1bab10e32dn,0x3706b1677an,0x644d626ffdn];function sa(e){const t=(i,a)=>{const c=i>>35n;return i=(i&0x7ffffffffn)<<5n^BigInt(a),Dk.forEach((u,l)=>{c>>BigInt(l)&1n&&(i^=u)}),i};let n=1n,r=0,s=0;for(const i of e){const a=Kk.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 Mk(e,t,n){const r=en(e,t,n);if(!r)return null;const s=gi(r.mnemonic,r.account),o=Pa(r.mnemonic,r.account),i={bip86:`tr(${as(o)})`,tapkey:`tr(${as(s)})`,wallet:`rawtr(${as(o)})`}[e.scheme],a=n.kind==="agent",c=Ra(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",jk(s)],["taproot","descriptor",sa(i)],["segwit","descriptor",sa(`wpkh(${as(Zc(r.mnemonic,r.account))})`)],["tapkey","descriptor",sa(`tr(${as(s)})`)],["ethereum","private key",`0x${zh(r.mnemonic,r.account)}`]],leaves:a?Ok(s,`${n.name}@${c}`):Ck(Mc(r.mnemonic),c)}}const Br=1e8,ze=50*Br,Pe=330,pp=e=>(e/Br).toFixed(8).replace(/\.?0+$/,""),G=e=>`${pp(e)} tBTC`;function Qc(e){if(e<1e6)return G(e);const t=Math.round(e/1e6)*1e6;return`${t===e?"":"≈"}${G(t)}`}function vi(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)*Br+Number((t[2]??"").padEnd(8,"0"))}class eu{constructor(t,n,r){this.secret=t,this.pubkey=n,this.path=r,this.address=ps.p2wpkh.fromPubKey(n,"regtest"),this.script=ps.toScriptPubKey(this.address)}sign(t,n){return[Xn.segwit.sign(this.secret,t,n,{pubkey:this.pubkey}).hex,this.pubkey]}}const oa=new Map;function ye(e,t,n){const r=en(e,t,n);if(!r)return null;const s=`${r.mnemonic}|${r.account}`;return oa.has(s)||oa.set(s,new eu(Zc(r.mnemonic,r.account),Zh(r.mnemonic,r.account),nt.segwit(r.account))),oa.get(s)}function Zk(e,t,n){var s;const r=n?t.nodes.get(n):null;return r&&r.root===r.id&&r.status==="active"?((s=ye(e,t,r))==null?void 0:s.script)??null:null}const Tr=(e,t)=>{var n,r;return((r=(n=e.mining)==null?void 0:n.rigs)==null?void 0:r[t])??1};function tu(e,t){var n;return((n=e.mining)==null?void 0:n.rule)==="none"?[]:t.roots.filter(r=>r.status==="active"&&Tr(e,r.id)>0&&ye(e.keys,t,r)).slice(0,np)}function gp(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=Zk(e.keys,t,n);return c?[{script:c,value:ze}]:null}const r=tu(e,t),s=r.reduce((c,u)=>c+Tr(e,u.id),0);let o=ze;return r.length?r.map((c,u)=>{const l=u===r.length-1?o:Math.floor(ze*Tr(e,c.id)/s);return o-=l,{script:ye(e.keys,t,c).script,value:l}}):null}function ir(e,t,n=ut){const r=t+X,s=u=>u===r||u-r>=Pe&&u-r<=ze,o=[...e].sort((u,l)=>u.value-l.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 ru(e,t=ut){let n=0,r=-X;for(const s of e.map(o=>o.value).sort((o,i)=>i-o).slice(0,t)){r+=s;const o=r<=ze?r:r-ze>=Pe?ze:r-Pe;o>=Pe&&r-o<=ze&&(n=Math.max(n,o))}return n}function su(e,t,n,r=ut,s="send"){const o=nu(t),i=n+X,a=ru(t,r),c=`${s[0].toUpperCase()}${s.slice(1)}`;if(od.value).sort((d,h)=>h-d),l=u.slice(0,r).map((d,h)=>u.slice(0,h+1).reduce((g,p)=>g+p,0)),f=Math.min(...[...u,...u.flatMap((d,h)=>u.slice(h+1).map(g=>d+g)),...l].filter(d=>d>=i));return Number.isFinite(f)&&f-inew Set((e.offers??[]).flatMap(t=>t.payers.map(n=>`${n.txid}:${n.vout}`))),mp=(e,t)=>e.chain.coins(t.script).filter(n=>{var r;return!((r=n.inscriptions)!=null&&r.length)}),yp=(e,t,n=ut)=>!!ir(e,t,n),wp=(e,t,n)=>yp(mp(e,t),n);function iu(e,t,n,r,s="This node",o="send"){const i=mp(e,t),a=ou(e),c=ir(i.filter(d=>!a.has(`${d.txid}:${d.vout}`)),r)??ir(i,r);if(!c)throw new Error(su(s,i,r,ut,o));const u=nu(c)-r-X,l=ee.create({vin:c.map(d=>Xe(d.txid,d.vout,d.value,d.scriptPubKey)),vout:[xe(r,n),...u?[xe(u,t.script)]:[]]});c.forEach((d,h)=>{l.vin[h].witness=t instanceof eu?t.sign(l,h):[t.sign(l,void 0,h)]});const f=ee.encode(l).hex;return e.chain.submitPackage([f]),ee.util.getTxid(f)}function bp(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=ye(e.keys,t,o),c=ye(e.keys,t,i);if(!a||!c)throw new Error("A holding that predates lab keys has no SegWit addresses.");if(!Number.isSafeInteger(s)||sze)throw new Error("Send at most 50 test BTC at a time: no output on this chain is bigger than one block reward.");return iu(e,a,c.script,s,o.name)}function Vk(e,t,n){if(!t||!n||Ae(t.script)===Ae(n.script))return 0;let r=0;for(const s of e.chain.coins(t.script)){if(s.value-X{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,l)=>u+l.value,0);if(o.length&&c-X>=Pe){const u=ee.create({vin:o.map(l=>Xe(l.txid,l.vout,l.value,l.scriptPubKey)),vout:[xe(c-X,n)]});o.forEach((l,f)=>{u.vin[f].witness=r?t.sign(u,f):[t.sign(u,void 0,f)]}),e.chain.submitPackage([ee.encode(u).hex]),i++}o=[]};for(const c of s)(o.length===ut||o.reduce((u,l)=>u+l.value,0)+c.value-X>ze)&&a(),o.push(c);return a(),i}const au=(e,t)=>[t,...t.log.flatMap((n,r)=>n.ok&&n.rekeys?[Cn(e.slice(0,r),{pending:!0})]:[])];function xp(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 qk=(e,t,n)=>xp(au(t,n),(r,s)=>{const o=ye(e,r,s);return o&&Ae(o.script)}),ia=new Map,zk=(e,t,n)=>xp(au(t,n),(r,s)=>{const o=en(e,r,s),i=o&&`${e.scheme}|${o.mnemonic}|${o.account}`;return i&&!ia.has(i)&&ia.set(i,Ae(Te(e,r,s).wallet.script)),i?ia.get(i):null}),cu=(e,t)=>e.coins(t.script).filter(n=>{var r;return!((r=n.inscriptions)!=null&&r.length)}).reduce((n,r)=>n+r.value,0);function Fk(e,t,n,r){for(const s of au(t,n))for(const o of s.nodes.values()){const i=Te(e,s,o);if(i&&Ae(i.wallet.script)===r)return{node:o.id,wallet:i.wallet}}return null}function Wk(e,t,n=new Map,r=new Map){var a;const s=[],o=c=>t.get(Ae(c))??null,i=c=>c.reduce((u,l)=>u+l.value,0);for(const{txid:c,tx:u,height:l,coinbase:f}of e.transactions.values()){const d=u.vout.map(x=>({script:Ae(x.scriptPubKey),node:o(x.scriptPubKey),value:Number(x.value)}));if(f){d.forEach((x,k)=>{x.node&&s.push({kind:"mine",key:`${c}:${k}`,txid:c,beat:l,from:null,to:x.node,amount:x.value,fee:0,change:0})});continue}const h=u.vin.map(x=>{var I,C;const k=((I=e.transactions.get(x.txid))==null?void 0:I.tx.vout[x.vout])??((C=e.imported)==null?void 0:C.call(e,x.txid,x.vout));return k?{node:o(k.scriptPubKey),tank:n.get(Ae(k.scriptPubKey))??null,value:Number(k.value)}:null}),g=r.get(c);if(g!=null&&g.prep)continue;if(g!=null&&g.ask){s.push({kind:"deal",key:c,txid:c,beat:l,from:g.buyer,to:g.seller,amount:g.price,item:g.item,fee:2*X,change:0,ask:!0});continue}if(g&&h.length>1&&h[0]&&h.slice(1).every(x=>(x==null?void 0:x.node)===g.buyer)){s.push({kind:"deal",key:c,txid:c,beat:l,from:g.buyer,to:g.seller,amount:g.price,item:g.item,fee:i(h)-i(d),change:i(d.filter(x=>x.node===g.buyer))});continue}if(h.every(x=>x&&!x.node)){const x=d.filter(I=>I.node),k=h[0].tank&&h.every(I=>I.tank===h[0].tank)?h[0].tank:null;x.length&&k?s.push({kind:"pay",key:c,txid:c,beat:l,from:k,to:x[0].node,amount:x[0].value,fee:i(h)-i(d),change:0}):x.length&&s.push({kind:"fund",key:c,txid:c,beat:l,from:null,to:x[0].node,amount:x[0].value,fee:i(h)-i(d),change:i(d.filter(I=>!I.node))});continue}const p=(a=h[0])==null?void 0:a.node;if(!p||!h.every(x=>(x==null?void 0:x.node)===p))continue;const w=d.filter(x=>x.node!==p),y=d.filter(x=>x.node===p),v=i(h)-i(d),m={key:c,txid:c,beat:l,from:p,fee:v};w.length&&w.every(x=>n.get(x.script)===p)?s.push({...m,kind:"gas",to:p,amount:i(w),change:i(y)}):w.length?s.push({...m,kind:"pay",to:w[0].node,amount:w[0].value,change:i(y)}):s.push({...m,kind:"move",to:p,amount:i(y),change:0})}return s}function ja(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,l)=>{const f=t.get(Ae(u.scriptPubKey));f&&r.set(`${o}:${l}`,{node:f,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 Ka="lineage-offer",Da="lineage-ask",vt=600,Xo=/^[0-9a-f]{64}$/,Ir=/^[0-9a-f]{64}i0$/,Ma=/^5120[0-9a-f]{64}$/,go=/^0014[0-9a-f]{40}$/,Gk=/^[0-9a-f]{128}83$/,Yk="0".repeat(64),Za=e=>({txid:e.txid,vout:e.vout,value:e.value,script:Ae(e.scriptPubKey)}),Va=(e,t)=>!e.utxos.has(`${t.txid}:${t.vout}`),ki=e=>{const t=Xr(new fr(e.chain));return{events:t,state:Cn(t,{pending:!0})}},uu=e=>`${e[0].toUpperCase()}${e.slice(1)}`,mo=e=>e.reduce((t,n)=>t+n.value,0),Xk=e=>Xe(e.txid,e.vout,e.value,e.scriptPubKey);function vp(e){return ee.create({vin:[e.holder,...e.payers].map(t=>Xe(t.txid,t.vout,t.value,t.script)),vout:[xe(e.holder.value,e.to),...e.price?[xe(e.price,e.pay)]:[],...e.change?[xe(e.change,e.back)]:[]]})}function Ei(e,t,n,r){const s=wi(e.chain,r),o=s&&Fk(e.keys,t,n,Ae(s.scriptPubKey));return o?{coin:s,node:n.nodes.get(o.node),wallet:o.wallet}:null}function lu(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=Ei(e,t,n,r);return{id:r,name:(s??o).name,item:s,org:o,holder:i,seller:o?n.nodes.get(o.parent)??null:(i==null?void 0:i.node)??null}}function fu(e,t){return t.holder?t.org?t.holder.node.id!==t.org.id?`${t.name} is held by ${t.holder.node.name}`:nn(e.nodes,t.org):"":`no node in this lab holds ${t.name}`}function kp(e,t,n,r){const s=n.nodes.get(r);if((s==null?void 0:s.kind)!=="org"||s.status!=="active")return null;const o=Ei(e,t,n,r);return o&&o.node.id!==s.id&&o.node.id!==s.parent?o.node:null}function Ep(e,t,n,r,s=Date.now()){const{events:o,state:i}=ki(e),a=lu(e,o,i,t),c=i.nodes.get(n);if(!a)throw new Error("Pick an item or an org to make an offer on.");if(!c)throw new Error("Pick who makes the offer.");if(!Number.isSafeInteger(r)||r<0||r>0&&rze)throw new Error("Offer at most 50 test BTC: no output on this chain is bigger than one block reward.");const u=fu(i,a)||(a.org?nn(i.nodes,a.org,c):"");if(u)throw new Error(`${uu(u)}.`);const l=a.seller;if(l.id===c.id)throw new Error(`${c.name} already holds ${a.name}.`);for(const m of[c,l])if(m.status!=="active")throw new Error(`${m.name} is ${m.status}.`);const f=ye(e.keys,i,c),d=ye(e.keys,i,l),h=Te(e.keys,i,c);if(!f||!d||!h)throw new Error("A holding that predates lab keys cannot trade.");if((e.offers??[]).some(m=>m.item===t&&m.buyer===c.id&&yo(e,i,m)==="open"))throw new Error(`${c.name} already has an open offer on ${a.name}. Withdraw it first.`);const g=e.chain.coins(f.script),p=ou(e),w=ir(g.filter(m=>!p.has(`${m.txid}:${m.vout}`)),r,ut-1)??ir(g,r,ut-1);if(!w)throw new Error(su(c.name,g,r,ut-1,"offer"));const y={kind:Ka,version:1,item:t,buyer:c.id,seller:l.id,price:r,holder:Za(a.holder.coin),payers:w.map(Za),to:Ae(h.wallet.script),pay:Ae(d.script),back:Ae(f.script),change:mo(w)-r-X,at:s},v=vp(y);return y.txid=ee.util.getTxid(v),y.witnesses=w.map((m,x)=>f.sign(v,x+1)),(e.offers??(e.offers=[])).push(y),y}function du(e,t,n){var l,f;const r=d=>{var h;return((h=t.nodes.get(d))==null?void 0:h.name)??"a node"},s=t.nodes.get(n.item),o=(s==null?void 0:s.name)??((l=t.items.get(n.item))==null?void 0:l.name)??"the item";if(Va(e.chain,n.holder))return s?`${o}'s inscription has moved since`:`${o} has moved since`;if(n.payers.some(d=>Va(e.chain,d)))return`${r(n.buyer)} has spent a coin the offer promised`;for(const d of[n.buyer,n.seller]){const h=t.nodes.get(d);if((h==null?void 0:h.status)!=="active")return`${r(d)} is ${(h==null?void 0:h.status)??"gone"}`}const i=t.nodes.get(n.buyer),a=t.nodes.get(n.seller),c=d=>d?Ae(d.script):"";if(s&&s.parent!==a.id)return`${o} is no longer ${a.name}'s`;const u=s?nn(t.nodes,s,i):"";return u||(c((f=Te(e.keys,t,i))==null?void 0:f.wallet)!==n.to||c(ye(e.keys,t,i))!==n.back?`${i.name} has new keys since`:n.price&&c(ye(e.keys,t,a))!==n.pay?`${a.name} has new keys since`:"")}const yo=(e,t,n)=>e.chain.transactions.has(n.txid)?"done":du(e,t,n)?"stale":"open";function Jk(e,t,n=null){var u;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}=ki(e),i=du(e,o,r);if(i)throw new Error(`This offer is stale: ${i}.`);const a=lu(e,s,o,r.item);if(!a||((u=a.seller)==null?void 0:u.id)!==r.seller||fu(o,a))throw new Error("Only the holder can accept.");n==null||n(o,a);const c=vp(r);return r.witnesses.forEach((l,f)=>{c.vin[f+1].witness=l}),c.vin[0].witness=[a.holder.wallet.sign(c,void 0,0)],e.chain.submitPackage([ee.encode(c).hex]),r}function Qk(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 Jr=e=>`${e.holder.txid}:${e.holder.vout}`,eE=e=>ee.create({vin:[Xe(Yk,0,vt,e.pay),Xe(e.holder.txid,e.holder.vout,e.holder.value,e.holder.script)],vout:[xe(vt+e.holder.value,e.holder.script),xe(e.price,e.pay)]});function tE(e,t,n,r=Date.now(),s=null){var h;const{events:o,state:i}=ki(e),a=lu(e,o,i,t);if(!a)throw new Error("Pick an item or an org to sell.");if(!Number.isSafeInteger(n)||nze-X)throw new Error(`Ask at most ${G(ze-X)}: the buyer funds the price and its fee in one output.`);const c=fu(i,a);if(c)throw new Error(`${uu(c)}.`);const u=a.seller,l=ye(e.keys,i,u);if(u.status!=="active")throw new Error(`${u.name} is ${u.status}.`);if(!l||!((h=a.holder.wallet)!=null&&h.secret))throw new Error("A holding that predates lab keys cannot trade.");const f=(e.asks??[]).find(g=>g.lot===t&&$i(e,i,g)==="open");if(f)throw new Error(`${a.name} is already listed at ${G(f.price)}. Withdraw that ask first.`);s==null||s(i,a);const d={kind:Da,version:1,lot:t,seller:u.id,price:n,holder:Za(a.holder.coin),pay:Ae(l.script),at:r,taken:null};return d.sig=Xn.taproot.sign(a.holder.wallet.secret,eE(d),1,{sigflag:131}).hex,(e.asks??(e.asks=[])).push(d),d}function hu(e,t,n){var a;const r=t.nodes.get(n.lot),s=(r==null?void 0:r.name)??((a=t.items.get(n.lot))==null?void 0:a.name)??"the item",o=t.nodes.get(n.seller);if(Va(e.chain,n.holder))return r?`${s}'s inscription has moved since`:`${s} has moved since`;if((o==null?void 0:o.status)!=="active")return`${(o==null?void 0:o.name)??"the seller"} is ${(o==null?void 0:o.status)??"gone"}`;const i=ye(e.keys,t,o);return!i||Ae(i.script)!==n.pay?`${o.name} has new keys since`:r&&r.parent!==o.id?`${s} is no longer ${o.name}'s`:r?nn(t.nodes,r):""}const $i=(e,t,n)=>n.taken&&e.chain.transactions.has(n.taken.txid)?"done":hu(e,t,n)?"stale":"open",nE=(e,t,n)=>(e.asks??[]).find(r=>r.lot===n&&$i(e,t,r)==="open")??null;function rE(e,t,n,r=Date.now()){const s=(e.asks??[]).find(C=>Jr(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}=ki(e),i=hu(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?nn(o.nodes,c,a):"";if(u)throw new Error(`${uu(u)}.`);const l=ye(e.keys,o,a),f=Te(e.keys,o,a);if(!l||!f)throw new Error("A holding that predates lab keys cannot trade.");const d=e.chain.coins(l.script),h=ou(e),g=vt+s.price+X,p=ir(d.filter(C=>!h.has(`${C.txid}:${C.vout}`)),g)??ir(d,g);if(!p)throw mo(d){v.vin[N].witness=l.sign(v,N)});const m=ee.encode(v).hex,x=ee.util.getTxid(m),k=ee.create({vin:[Xe(x,0,vt,y),Xe(s.holder.txid,s.holder.vout,s.holder.value,s.holder.script),Xe(x,1,s.price+X,y)],vout:[xe(vt+s.holder.value,f.wallet.script),xe(s.price,s.pay)]});k.vin[1].witness=[s.sig],k.vin[0].witness=l.sign(k,0),k.vin[2].witness=l.sign(k,2);const I=ee.encode(k).hex;return e.chain.submitPackage([m,I]),s.taken={txid:ee.util.getTxid(I),prep:x,buyer:a.id,at:r},s}function sE(e,t){const n=(e.asks??[]).find(r=>Jr(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 oE(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}],[n.taken.prep,{prep:!0}]]);return new Map([...(e.offers??[]).map(n=>[n.txid,n]),...t])}const qa=(e,t)=>e&&Xo.test(e.txid)&&Number.isSafeInteger(e.vout)&&e.vout>=0&&Number.isSafeInteger(e.value)&&e.value>=Pe&&e.value<=ze&&t.test(e.script);function iE(e){const t=n=>Number.isSafeInteger(n)&&(n===0||n>=Pe&&n<=ze);if((e==null?void 0:e.kind)!==Ka||e.version!==1||!Ir.test(e.item)||!Ir.test(e.buyer)||!Ir.test(e.seller)||e.buyer===e.seller||!t(e.price)||!t(e.change)||!qa(e.holder,Ma)||!Array.isArray(e.payers)||!e.payers.length||e.payers.length>ut-1||!e.payers.every(n=>qa(n,go))||!Ma.test(e.to)||!go.test(e.pay)||!go.test(e.back)||!Xo.test(e.txid)||!Array.isArray(e.witnesses)||e.witnesses.length!==e.payers.length||!e.witnesses.every(n=>Array.isArray(n)&&n.length===2&&/^30[0-9a-f]{12,140}01$/.test(n[0])&&/^0[23][0-9a-f]{64}$/.test(n[1]))||!Number.isSafeInteger(e.at))throw new Error("Invalid offer.");return{kind:Ka,version:1,item:e.item,buyer:e.buyer,seller:e.seller,price:e.price,holder:{...e.holder},payers:e.payers.map(n=>({...n})),to:e.to,pay:e.pay,back:e.back,change:e.change,at:e.at,txid:e.txid,witnesses:e.witnesses.map(n=>[...n])}}function aE(e){const t=e==null?void 0:e.taken;if((e==null?void 0:e.kind)!==Da||e.version!==1||!Ir.test(e.lot)||!Ir.test(e.seller)||!Number.isSafeInteger(e.price)||e.priceze-X||!qa(e.holder,Ma)||!go.test(e.pay)||typeof e.sig!="string"||!Gk.test(e.sig)||!Number.isSafeInteger(e.at)||!(t===null||t&&Xo.test(t.txid)&&Xo.test(t.prep)&&Ir.test(t.buyer)&&Number.isSafeInteger(t.at)))throw new Error("Invalid ask.");return{kind:Da,version:1,lot:e.lot,seller:e.seller,price:e.price,holder:{...e.holder},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 Si="orgchain:lab:v1",cE=["each",10,30,60,"manual"];function Ms(e={tempo:"each",nextAt:null}){const{tempo:t,nextAt:n}=e??{},r=typeof t=="number";if(!cE.includes(t)||!(n===null||r&&Number.isSafeInteger(n)&&n>0))throw new Error("Invalid clock.");return{tempo:t,nextAt:n}}function $p(e){const t=Yc();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]=Mh(s,24)}if(t.scheme=(e==null?void 0:e.scheme)??(Object.keys(t.roots).length?"wallet":"bip86"),!Pk.includes(t.scheme))throw new Error("Invalid lab keys.");return t}const uE=["split","last","none"];function Zs(e){const t=(e==null?void 0:e.rule)??"split",n={};if(!uE.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 Sp(e=[]){if(!Array.isArray(e)||e.length>1e3)throw new Error("Invalid offers.");const t=e.map(iE);if(new Set(t.map(n=>n.txid)).size!==t.length)throw new Error("Invalid offers.");return t}function _p(e=[]){if(!Array.isArray(e)||e.length>1e3)throw new Error("Invalid asks.");const t=e.map(aE);if(new Set(t.map(Jr)).size!==t.length)throw new Error("Invalid asks.");return t}const Vs=()=>({wallet:null,chain:new yi,clock:Ms(),keys:Yc(),mining:Zs(),offers:[],asks:[]});function Ap(e){if(!e)return Vs();const t=JSON.parse(e);if((t==null?void 0:t.kind)!=="orgchain-lab"||t.network!==En||t.version!==1)throw new Error("That is not an Orgchain v1 lab.");return{wallet:t.wallet?Pn.load(t.wallet):null,chain:new yi(t.chain),clock:Ms(t.clock),keys:$p(t.keys),mining:Zs(t.mining),offers:Sp(t.offers),asks:_p(t.asks)}}const Bp=e=>{var t;return JSON.stringify({kind:"orgchain-lab",network:En,version:1,wallet:((t=e.wallet)==null?void 0:t.backup())??null,chain:e.chain.snapshot(),clock:Ms(e.clock),keys:$p(e.keys),mining:Zs(e.mining),offers:Sp(e.offers),asks:_p(e.asks)})};function lE(e,t,n){var r;e.mining=Zs({...e.mining,rigs:{...(r=e.mining)==null?void 0:r.rigs,[t]:n}})}function fE(e,t){e.mining=Zs({...e.mining,rule:t})}const pu=()=>Ap(localStorage.getItem(Si));function dE(e){try{localStorage.setItem(Si,Bp(e))}catch{throw new Error("Browser storage is full or unavailable, so nothing was saved. Save a backup, then reset.")}}async function hE(e,{locks:t=(s=>(s=globalThis.navigator)==null?void 0:s.locks)(),read:n=pu,save:r=dE}={}){if(!t)throw new Error("Orgchain needs Web Locks: open it over HTTPS or on localhost.");return t.request(Si,async()=>{const o=n(),i=await e(o);return i!==!1&&r(o),{lab:o,result:i}})}function ct(e,t=null){e.wallet||(e.wallet=Pn.create());const n=t!=null&&t.length?e.chain.mineTo(t.map(r=>xe(r.value,r.script))):e.chain.mine(e.wallet.script);return e.clock=Ms({tempo:e.clock.tempo,nextAt:null}),n}function rn(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 pE(e,t,n=Date.now(),r=null){e.clock=Ms({tempo:t,nextAt:null}),t==="each"&&e.chain.mempool.length?ct(e,r):rn(e,n)}function gE(e,t=Date.now(),n=null){const{tempo:r,nextAt:s}=e.clock;return typeof r!="number"||!e.chain.mempool.length?!1:s===null?(rn(e,t),!0):t`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)=>mi(t,e),charter:e=>`charter ${e.form}${e.jurisdiction?` ${e.jurisdiction}`:""}`,graduate:()=>"graduate",close:()=>"close",join:()=>"join",adopt:()=>"adopt"};function yE(e,t={}){if(!Object.hasOwn(Bl,e))throw new Error("Unknown verb.");const n={op:e};for(const s of Bl[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(Bt.filter(s=>typeof r[s]=="string").map(s=>[s,r[s]]))),n}function Tp(e,t){const n=Re(e),r=n.nodes.get(t),s=r&&Lk(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 Dv(t,s.keys,s.secrets)}function gu(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(Ds(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=>Cn(Xr(new fr(e.chain)),{pending:!0});function Jo(e,t,n,r){const s=yE(t,r),o=Xr(new fr(e.chain)),i={id:"check",status:"pending",height:null,metadata:s,parent:n??null,protocol:Fc},{ok:a,why:c}=Cn([...o,i],{pending:!0}).log.at(-1);if(!a)throw new Error(`${c[0].toUpperCase()}${c.slice(1)}.`);return s}const za=Ut+2*X+330,Ip=1e5,_i=1e4,Gt=(e,t=0)=>Ut+2*X+(e==="birth"||e==="join"?1:e==="graduate"?Math.max(0,t-1):0)*X+330,wE=(e,t=0)=>Gt(e,t)-330,ar=(e,t,n)=>e.chain.coins(t.script).find(r=>{var s;return!((s=r.inscriptions)!=null&&s.length)&&r.value>=n}),Fa=e=>Xe(e.txid,e.vout,e.value,e.scriptPubKey),Op=(e,t)=>(t.forEach((n,r)=>{e.vin[r].witness=[n.sign(e,void 0,r)]}),ee.encode(e).hex);function mu(e){e.keys??(e.keys=Yc()),e.wallet||(e.wallet=Pn.create()),ar(e,e.wallet,Ip+X+330)||ct(e)}function Cp(e,t,n=za,r=Ip){if(t===e.wallet||ar(e,t,n))return;const s=ar(e,e.wallet,r+X+330),o=ee.create({vin:[Fa(s)],vout:[xe(r,t.script),xe(s.value-r-X,e.wallet.script)]});e.chain.submitPackage([Op(o,[e.wallet])])}function Is(e,t,n,r,s){if(r===e.wallet||ar(e,r,s))return;const o=n&&ye(e.keys,t,n);if(!o)return Cp(e,r,s);iu(e,o,r.script,Math.max(_i,s),n.name)}function yu(e,t,n,r,s){if(r===e.wallet||ar(e,r,s))return!0;const o=n&&ye(e.keys,t,n);return!o||wp(e,o,Math.max(_i,s))}function wu(e,t,n,r,s={}){var l,f;const o=r?t.nodes.get(r):null,i=o&&((l=Jc(e,t,r))==null?void 0:l.wallet);if(n==="found"||!i)return"";const a=n==="graduate"?t.nodes.get(s.of):null,c=a&&Te(e.keys,t,a)?Ds(t,a.id).length:0;if(!yu(e,t,o,i,Gt(n,c))){const d=t.nodes.get(o.parent);return`${o.name} has no test BTC for gas. ${d?`${d.name} can send some`:((f=e.mining)==null?void 0:f.rule)==="none"?"Fund it from the lab wallet":"It earns some each beat it mines"}`}const u=c?ye(e.keys,t,a):null;return u&&!yp(e.chain.coins(u.script).filter(d=>d.value-X>=Pe).map(d=>({value:d.value-X})),_i)?`${a.name} needs test BTC of its own to claim its new root. Send it some first`:""}function Qo(e,t,n,r,s=n){const o=wi(e.chain,t),i=ar(e,s,X+330),a=ee.create({vin:[Fa(o),Fa(i)],vout:[xe(o.value,r.script),xe(i.value-X,s.script)]});e.chain.submitPackage([Op(a,[n,s])])}function ei(e,t,n,r,s){return new Mx(e.chain,t).inscribe(mE[n](s,r),r??null,s,{metaprotocol:Fc})}const gr=(e,t)=>{var r;const n=Re(e);return gp(e,n,((r=n.nodes.get(t))==null?void 0:r.root)??null)},Ai=(e,t)=>gp(e,Re(e),t);function bu(e){var r,s,o;const t=Re(e),n=new Map;for(const i of t.nodes.values())for(const a of[ye(e.keys,t,i),(r=Te(e.keys,t,i))==null?void 0:r.wallet])a&&n.set(Ae(a.script),i.root);for(const i of[...e.chain.mempool].reverse()){const a=e.chain.transactions.get(ee.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),l=u&&n.get(Ae(u.scriptPubKey));if(l)return l}}return null}function Os(e,t,n){var s;const r=Jc(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 Pp(e,t,n,r){if(t==="found"){const l=dl(),f=Nk(e.keys,l);Cp(e,f,za,za);const d=ei(e,f,t,null,r);return e.keys.roots[d]=l,d}const s=Re(e),o=Os(e,s,n),i=s.nodes.get(n),a=t==="graduate"?s.nodes.get(r.of):null,c=a&&Te(e.keys,s,a)?Ds(s,a.id).map(l=>[l.id,Os(e,s,l.id)]):[];Is(e,s,i,o,Gt(t,c.length));const u=ei(e,o,t,n,r);if(t==="birth"){const l=Re(e),f=Te(e.keys,l,l.nodes.get(u));f&&Qo(e,u,o,f.wallet)}if(c.length){e.keys.adopted[a.id]=dl();const l=Re(e);for(const[f,d]of c){const h=Te(e.keys,l,l.nodes.get(f)).wallet;if(Vk(e,ye(e.keys,s,s.nodes.get(f)),ye(e.keys,l,l.nodes.get(f))),f!==a.id){Qo(e,f,d,h,o);continue}Is(e,l,l.nodes.get(f),h,X+330),rk(e.chain,nk(e.chain,f,h),d)}}return u}function bE(e,t,n,r,s=Date.now()){if(t==="join"||t==="adopt")throw new Error("An org changes hands through Sell and Buy, and its buyer adopts it.");const o=Un(e,Re(e),t,n??null,r??{});if(o)throw new Error(`${o}.`);const i=gu(Re(e),t,n??null,r??{});if(i)throw new Error(`${i}.`);const a=Jo(e,t,n,t==="keyring"?Tp(e,n):r),c=wu(e,Re(e),t,n??null,a);if(c)throw new Error(`${c}.`);mu(e);const u=Pp(e,t,n??null,a);return e.clock.tempo==="each"?ct(e,gr(e,n??u)):rn(e,s),u}function xE(e,t,n,r,s=Date.now()){const o=Un(e,Re(e),"send",t)||Un(e,Re(e),"send",n);if(o)throw new Error(`${o}.`);const i=bp(e,Re(e),t,n,r);return e.clock.tempo==="each"?ct(e,gr(e,t)):rn(e,s),i}function vE(e,t,n,r,s=Date.now()){const o=Un(e,Re(e),"offer",n);if(o)throw new Error(`${o}.`);return Ep(e,t,n,r,s)}function kE(e,t,n=Date.now()){const r=Jk(e,t,(s,o)=>{o.org&&Up(e,s,o.org,o.seller)});return e.clock.tempo==="each"?ct(e,gr(e,r.seller)):rn(e,n),r}const EE=(e,t)=>Qk(e,t);function Un(e,t,n,r,s={},o=Xr(new fr(e.chain))){for(const i of[r,n==="graduate"?s.of:null]){const a=i?t.nodes.get(i):null,c=a?nE(e,t,i):null,u=a&&!c?kp(e,o,t,i):null;if(c)return`${a.name} is listed for sale at ${G(c.price)}. Withdraw its ask first`;if(u)return`${a.name} was sold to ${u.name}, which adopts it next`}return""}function Up(e,t,n,r){var c;const s=(c=Te(e.keys,t,n))==null?void 0:c.wallet,o=ye(e.keys,t,n),i=ye(e.keys,t,r);if(!s||!o||!i)return;const a=e.chain.coins(s.script).filter(u=>{var l;return((l=u.inscriptions)==null?void 0:l.some(f=>t.items.has(f.id)))&&!u.inscriptions.some(f=>f.id===n.id)});if(a.length){const u=Os(e,t,r.id);if(!yu(e,t,r,u,a.length*X+330))throw new Error(`${r.name} needs test BTC to take ${n.name}'s items home.`);for(const l of a)Is(e,t,r,u,X+330),Qo(e,l.inscriptions[0].id,s,u,u)}Al(e,s,i.script),Al(e,o,i.script)}function Np(e,t,n){const r=Re(e),s=Xr(new fr(e.chain)),o=r.nodes.get(t),i=r.nodes.get(n),a=Ei(e,s,r,t);if(!o||!i||(a==null?void 0:a.node.id)!==i.id)throw new Error(`${(i==null?void 0:i.name)??"That node"} does not hold ${(o==null?void 0:o.name)??"that org"}.`);const c=Os(e,r,i.id),u=a.wallet,l=Jo(e,"adopt",i.id,{of:o.id});if(!yu(e,r,i,c,Gt("adopt")+Gt("join")))throw new Error(`${i.name} has no test BTC for gas.`);Is(e,r,i,c,Gt("adopt")),ei(e,c,"adopt",i.id,l);const f=Jo(e,"join",o.id,{to:i.id});Is(e,r,i,u,Gt("join")),ei(e,u,"join",o.id,f);const d=Re(e);Qo(e,o.id,u,Te(e.keys,d,d.nodes.get(o.id)).wallet)}function $E(e,t,n,r){const s=t.nodes.get(r),o=t.nodes.get(n.lot),i=s&&ye(e.keys,t,s);if(!o||!i)return"";const a=nn(t.nodes,o,s);if(a)return`${a[0].toUpperCase()}${a.slice(1)}`;const c=Os(e,t,s.id),u=Gt("adopt")+Gt("join"),l=n.price+vt+2*X+(ar(e,c,u)?0:_i+X),f=e.chain.balance(i.script);return f{a.org&&Up(e,i,a.org,a.seller)});return e.chain.mempool.length>s&&(e.clock.tempo==="each"?ct(e,gr(e,o.seller)):rn(e,r)),o}const SE=(e,t)=>sE(e,t);function _E(e,t,n,r=Date.now()){const s=Re(e),o=(e.asks??[]).find(a=>Jr(a)===t),i=Un(e,s,"take",n)||(o&&!o.taken?$E(e,s,o,n):"");if(i)throw new Error(`${i}.`);return rE(e,t,n,r),s.nodes.has(o.lot)&&Np(e,o.lot,n),e.clock.tempo==="each"?ct(e,gr(e,n)):rn(e,r),o}function AE(e,t,n,r=Date.now()){const s=Un(e,Re(e),"adopt",n);if(s)throw new Error(`${s}.`);Np(e,t,n),e.clock.tempo==="each"?ct(e,gr(e,n)):rn(e,r)}function BE(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=ye(e.keys,s,o);if(!i)throw new Error("A holding that predates lab keys has no SegWit address to fund.");if(!Number.isSafeInteger(n)||nze)throw new Error("Fund at most 50 test BTC at a time: no output on this chain is bigger than one block reward.");mu(e),wp(e,e.wallet,n)||ct(e);const a=iu(e,e.wallet,i.script,n,"The lab wallet","fund");return e.clock.tempo==="each"?ct(e,gr(e,t)):rn(e,r),a}const Wa="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"}],["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 IE(e){mu(e),e.chain.mempool.length&&ct(e);const t={},n={};for(const r of TE){for(const[s,o,i]of r){if(s==="send"){bp(e,Re(e),t[o],t[i.to],i.amount*Br);continue}if(s==="offer"){Ep(e,n[i.item],t[o],i.price*Br);continue}if(s==="sell"){Lp(e,t[i.lot]??n[i.lot],i.price*Br);continue}const a=s==="keyring"?Tp(e,t[o]):Object.fromEntries(Object.entries(i).map(([l,f])=>[l,l==="to"||l==="of"?t[f]:f])),c=o?t[o]:null,u=Pp(e,s,c,Jo(e,s,c,a));(s==="found"||s==="birth")&&(t[i.name]=u),s==="make"&&(n[i.name]=u)}ct(e,Ai(e,t[Wa]))}return t[Wa]}const H=e=>document.getElementById(e);function $(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 ds=(e,t)=>`${e} ${t}${e===1?"":"s"}`,ht=e=>e==="cued"?"cued":`beat ${e}`,OE=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}),Tl=e=>JSON.stringify(e,(t,n)=>typeof n=="bigint"?String(n):n,2),T={holding:null,node:null,event:null,tx:null,beat:null,verb:"birth",busy:!1,replay:null,closing:null,reveal:null};let Z=Vs(),ti=new fr(Z.chain),wt=[],K=Cn([]),ke=K,Ve={owner:new Map,ledger:[],now:new Map,view:new Map},Nt=new Map;const at=()=>Z.chain.blocks.length,Ga=()=>wt.filter(e=>e.status==="pending").length,Ya=e=>Ve.ledger.filter(t=>t.beat===null&&t.kind===e).length,wo=[["pay","cued send"],["deal","cued deal"],["fund","cued deposit"]],CE=()=>Ga()+wo.reduce((e,[t])=>e+Ya(t),0),He=e=>{var t,n;return((t=K.items.get(e))==null?void 0:t.name)??((n=K.nodes.get(e))==null?void 0:n.name)??"an item"},aa=()=>Z.offers??[],Hp=()=>Z.asks??[];let _t=new Map,Nn=new Map;const bo=e=>Ve.view.get(e)??0,Rp=e=>Ve.now.get(e)??0,F=(e,t=K)=>e?t.nodes.get(e)??null:null,PE=e=>{var t;return!!e&&(e.root===T.holding||((t=F(e.parent))==null?void 0:t.root)===T.holding||e.moves.some(n=>{var r;return((r=F(n.from))==null?void 0:r.root)===T.holding}))},xu=e=>Object.assign(T,{event:null,tx:null,closing:null,reveal:null},e),mr=e=>{xu(e),Bi()};function fe(e,t=!1){const n=H("say");n.textContent=e,n.classList.toggle("bad",t)}function jp(){try{Z=pu()}catch(e){Z=Vs(),fe(`This browser's saved lab could not be read (${e.message}) Load a backup, or reset to start over.`,!0)}vu()}function vu(){var n;ti=new fr(Z.chain),wt=Xr(ti),K=Cn(wt,{pending:!0}),T.beat!==null&&T.beat>=at()&&(T.beat=null),F(T.holding)||(T.holding=((n=K.roots.filter(r=>r.kind==="holding").at(-1)??K.roots.at(-1))==null?void 0:n.id)??null),PE(F(T.node))||(T.node=T.holding),T.event&&!K.log.some(r=>r.id===T.event)&&(T.event=null),ke=T.beat===null?K:Cn(wt,{upTo:T.beat});const e=qk(Z.keys,wt,K),t=oE(Z);Ve={owner:e,ledger:Wk(Z.chain,e,zk(Z.keys,wt,K),t),now:ja(Z.chain,e)},Nt=new Map([...K.items.keys()].map(r=>{var s;return[r,((s=Ei(Z,wt,K,r))==null?void 0:s.node.id)??null]})),_t=new Map(Hp().filter(r=>$i(Z,K,r)==="open").map(r=>[r.lot,r])),Nn=new Map([...K.nodes.values()].filter(r=>r.kind==="org"&&r.status==="active").map(r=>{var s;return[r.id,(s=kp(Z,wt,K,r.id))==null?void 0:s.id]}).filter(([,r])=>r)),Ve.view=T.beat===null?Ve.now:ja(Z.chain,e,T.beat),T.tx&&!Ve.ledger.some(r=>r.key===T.tx)&&(T.tx=null),Bi()}function ni(e){T.beat=e>=at()?null:Math.max(0,e),ke=T.beat===null?K:Cn(wt,{upTo:T.beat}),Ve.view=T.beat===null?Ve.now:ja(Z.chain,Ve.owner,T.beat),Bi()}async function Qe(e,t){if(T.busy)return!1;T.busy=!0,document.body.classList.add("busy");try{return Z=(await hE(e,t)).lab,!0}catch(n){return fe((n==null?void 0:n.message)||String(n),!0),!1}finally{T.busy=!1,document.body.classList.remove("busy"),vu()}}async function Kt(e,t,n,r){let s=null;if(!await Qe(i=>{s=bE(i,e,t,n)}))return!1;const o=ti.events.find(i=>i.id===s);return fe(r(s,(o==null?void 0:o.status)==="confirmed"?`at beat ${o.height}`:"cued for the next beat")),Bi(),!0}async function Kp(e){const t=[Ga(),...wo.map(([a])=>Ya(a))],n=at();if(!await Qe(e)||at()===n)return;const r=[Ga(),...wo.map(([a])=>Ya(a))],s=["cued act",...wo.map(([,a])=>a)],o=t.map((a,c)=>[a-r[c],s[c]]).filter(([a])=>a>0).map(([a,c])=>ds(a,c)),i=UE(Ve.ledger.filter(a=>a.kind==="mine"&&a.beat===at()));fe(`Beat ${at()}: ${o.length?`${o.join(" and ")} landed, and ${i}`:i}.`)}function UE(e){if(!e.length)return"the lab wallet earned 50 tBTC";const t=e.map(r=>{var s;return((s=F(r.to))==null?void 0:s.name)??"?"}),n=e.map(r=>Qc(r.amount));return e.length===1?`${t[0]} earned ${G(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 NE(){var t;if(((t=Z.mining)==null?void 0:t.rule)==="last")return"the holding that acts";const e=tu(Z,K);return e.length?e.length===1?e[0].name:`${e.length} holdings, split by hashrate`:"the lab wallet"}function Bi(){Dp(),RE(),jE(),Qr(),Qp(),Eu()}function Dp(){const e=CE(),{tempo:t}=Z.clock;for(const r of document.querySelectorAll("[data-tempo]"))r.setAttribute("aria-pressed",String(String(t)===r.dataset.tempo));H("clock-beat").textContent=String(at()),H("clock-cued").textContent=e?`${e} cued · ${LE()}`:"nothing cued";const n=NE();H("clock-pays").textContent=`beats pay ${n}`,H("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 HE={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 RE(){var a,c;const e=((a=Z.mining)==null?void 0:a.rule)??"split",t=e==="split",n=t?tu(Z,K):[],r=n.reduce((u,l)=>u+Tr(Z,l.id),0);H("holdings-list").replaceChildren(...K.roots.map(u=>{var y;const l=Wv(K,u.id),f=u.id===T.holding,d=u.status==="active",h=n.some(v=>v.id===u.id)?Tr(Z,u.id)/r:0,g=[...K.nodes.values()].reduce((v,m)=>v+(m.root===u.id?Rp(m.id):0),0),w=[u.graduated!==null&&`from ${((y=F(u.parent))==null?void 0:y.name)??"?"}${u.graduated==="cued"?", cued":` at beat ${u.graduated}`}`||ht(u.born),ds(l.orgs,"org"),ds(l.agents,"agent"),ds(l.belts,"belt"),g>0&&Qc(g),t&&d&&(h?`${Math.round(h*100)}% of each beat`:"not mining"),!d&&"closed"].filter(Boolean);return $("li",{},$("button",{type:"button",class:`hold${f?" on":""}${d?"":" gone"}`,"aria-pressed":String(f),onclick:()=>mr({holding:u.id,node:u.id})},$("span",{class:"hn",text:u.name})," ",$("span",{class:"hm",text:w.join(" · ")})),t&&d&&ye(Z.keys,K,u)&&WE(u,Tr(Z,u.id)))}));for(const u of document.querySelectorAll("[data-rule]"))u.setAttribute("aria-pressed",String(e===u.dataset.rule));H("mining-note").textContent=HE[e];const s=K.roots.filter(u=>u.status==="active"&&ye(Z.keys,K,u)),o=H("fund-to"),i=o.value;H("f-fund").hidden=e!=="none"||!s.length||T.beat!==null,o.replaceChildren(...s.map(u=>$("option",{value:u.id,text:u.name}))),o.value=s.some(u=>u.id===i)?i:s.some(u=>u.id===T.holding)?T.holding:((c=s[0])==null?void 0:c.id)??"",H("fund-has").textContent=G(Z.wallet?cu(Z.chain,Z.wallet):0),H("holdings-empty").hidden=K.roots.length>0,H("holdings-sub").textContent=K.roots.length?String(K.roots.length):"",H("sample").disabled=K.roots.some(u=>u.name===Wa&&u.status==="active")}function jE(){var r;const e=H("tree-rows"),t=F(T.holding);if(H("tree-sub").textContent=t?`${t.name} · ${T.beat===null?"now":`beat ${T.beat} of ${at()}`}`:"",!t)return e.replaceChildren($("p",{class:"wait",text:"No holding yet. Found one, or load the yolopreneur sample."}));if(!ke.nodes.has(t.id))return e.replaceChildren($("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(...Fv(ke,t.id).map(s=>s.type==="group"?$("div",{class:"row grp"},$("span",{class:"g","aria-hidden":"true",text:s.guide}),$("span",{class:"gl",text:s.label})):KE(s))),n&&((r=e.querySelector(`[data-id="${n}"]`))==null||r.focus())}function KE({node:e,guide:t,path:n,away:r,moved:s}){const o=e.id===T.node,i=s&&F(e.parent,ke),a=["row",o&&"on",e.status==="closed"&&"gone",e.born==="cued"&&"cue",s&&"moved"].filter(Boolean).join(" ");return $("div",{class:a},$("button",{type:"button",class:"sel","data-id":e.id,"aria-pressed":String(o),onclick:()=>mr({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},$("span",{class:"g","aria-hidden":"true",text:t}),$("span",{class:"p",text:`${n} `}),$("span",{class:"l",text:e.name})," ",$("span",{class:"v"},s?$("span",{class:"mk",text:`to ${(i==null?void 0:i.name)??"?"}`}):DE(e))))}function DE(e){var n;return[e.kind==="agent"&&$("span",{class:"mk",text:"agent"}),T.beat===null&&_t.has(e.id)&&$("span",{class:"mk ok",title:`${G(_t.get(e.id).price)}, asked by ${Ce(_t.get(e.id).seller)}`,text:"for sale"}),T.beat===null&&Nn.has(e.id)&&$("span",{class:"mk",title:`bought by ${Ce(Nn.get(e.id))}, which adopts it next`,text:"sold"}),e.edge==="adopted"&&$("span",{class:"mk ok",text:"graduated"}),e.charter&&$("span",{class:`mk form${(n=fs(ke,e))!=null&&n.ok?"":" lapsed"}`,title:ku(e),text:ME[e.charter.form]}),e.status==="closed"&&$("span",{class:"mk bad",text:"closed"}),e.born==="cued"&&$("span",{class:"mk",text:"cued"}),...e.badges.map(Mp),bo(e.id)>0&&$("span",{class:"mk sats",title:`${G(bo(e.id))} at its SegWit address`,text:Qc(bo(e.id))})].filter(Boolean).flatMap((r,s)=>s?[" ",r]:[r])}const Mp=e=>$("span",{class:`belt ${e.belt}`,title:`${e.skill}: ${e.belt} belt`},e.skill,$("span",{class:"sr",text:` (${e.belt} belt)`})),ME={sole:"sole",llc:"llc","series-llc":"series llc",series:"series",corp:"corp"},ZE={sole:"Sole proprietor",llc:"LLC","series-llc":"Series LLC",series:"Series",corp:"Corporation"},VE={sole:"a sole proprietor",llc:"an LLC","series-llc":"a series LLC",corp:"a corporation"};function ku(e,t=ke){var o;const n=e.charter,r=n.master&&F(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)??"?"}`:ZE[n.form],s,n.legal,n.provider&&`via ${n.provider}`,`since ${ht(n.beat)}`].filter(Boolean).join(" · ")}function Ti(e){var t;for(let n=F(e.parent);n&&n.root===e.root;n=F(n.parent))if(n.status==="active"&&((t=n.charter)==null?void 0:t.form)==="series-llc")return n;return null}function qE(e){var r;const t=e.kind==="org"&&Ti(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}`],!Xt(e)&&["llc","LLC",n?`a company of its own, owned through ${(r=F(e.parent))==null?void 0:r.name} while it is derived`:"a company of its own"],!Xt(e)&&["series-llc","Series LLC","an LLC that can hold series, one for each venture"],!Xt(e)&&["corp","Corporation","a company with shares"]].filter(Boolean)}function Zp(e){return qE(e).map(([t,n,r])=>{const s=t==="series"?Ti(e):e,o=wu(Z,K,"charter",s.id);return{form:t,label:n,hint:o?`${o}.`:r,off:!!o}})}const zE=e=>{var n;const t=Zp(e);return t.some(r=>!r.off)?"":((n=t[0])==null?void 0:n.hint.replace(/\.$/,""))??"No legal form fits"},ri=()=>{var e;return((e=document.querySelector("#charter-forms input:checked"))==null?void 0:e.value)??null};function FE(e){var i;const t=H("charter-forms"),n=Zp(e),r=n.map(a=>`${a.form}=${a.label}=${a.off}`).join("|");if(t.dataset.sig!==r){const a=ri(),c=n.filter(l=>!l.off),u=c.some(l=>l.form===a)?a:(i=c[0])==null?void 0:i.form;t.dataset.sig=r,t.replaceChildren($("legend",{class:"lab",text:"Form"}),...n.map(l=>$("label",{class:l.off?"off":null},$("input",{type:"radio",name:"form",value:l.form,checked:l.form===u,disabled:l.off}),` ${l.label} `,$("span",{text:l.hint}))))}const s=ri()==="series",o=fs(K,e);H("charter-where").hidden=s,H("charter-now").textContent=e.charter?`Now: ${ku(e,K)}${o.ok?"":`, lapsed: ${o.why}`}.`:"It has no legal form yet."}const Vp=(e,t)=>{for(let n=F(e.parent);n;n=F(n.parent))if(n.id===t.id)return!0;return!1},qp=e=>[...K.nodes.values()].filter(t=>t.id!==e.id&&t.status==="active").map(t=>[t,(t.root===e.root?0:4)+(Vp(t,e)?0:2)+(t.kind==="agent"?0:1)]).sort((t,n)=>t[1]-n[1]).map(([t])=>t),zp=e=>or(K.nodes,e).reduce((t,n)=>n.edge==="derived"&&n.status==="active"?t+1+zp(n):t,0);function WE(e,t){const n=async r=>{await Qe(s=>lE(s,e.id,r))&&fe(r?`${e.name} mines at hashrate ${r}.`:`${e.name} sits out of mining.`)};return $("span",{class:"rig"},$("span",{class:"rl",text:"hashrate"}),$("span",{class:"rn"},$("button",{type:"button",class:"rb","aria-label":`Lower ${e.name}'s hashrate`,disabled:t<=0,onclick:()=>n(t-1)},"−"),$("b",{text:String(t)}),$("button",{type:"button",class:"rb","aria-label":`Raise ${e.name}'s hashrate`,disabled:t>=9,onclick:()=>n(t+1)},"+")))}const Fp=e=>[...K.nodes.values()].filter(t=>t.id!==e.id&&t.status==="active").map(t=>[t,(t.root===e.root?0:4)+(Vp(t,e)?0:2)+(t.kind==="agent"?0:1)]).sort((t,n)=>t[1]-n[1]).map(([t])=>t);function GE(e){const t=ye(Z.keys,K,e);return t?ru(Z.chain.coins(t.script))[r,F(Nt.get(r.id))]).filter(([,r])=>r&&r.id!==e.id&&r.status==="active"),n=[...K.nodes.values()].filter(r=>r.kind==="org"&&!Nn.has(r.id)&&!nn(K.nodes,r,e)).map(r=>[r,F(r.parent)]);return[...t,...n].sort((r,s)=>(r[1].root===e.root?0:1)-(s[1].root===e.root?0:1)).map(([r])=>r)}const YE=e=>(K.items.has(e.id)?`${e.name} · held by ${Ce(Nt.get(e.id))}`:`${e.name} · an org of ${Ce(e.parent)}`)+(_t.has(e.id)?` · asks ${G(_t.get(e.id).price)}`:"");function XE(e){const t=ye(Z.keys,K,e);return t?Gp(e).length?Z.chain.coins(t.script).some(n=>n.value>=X+Pe||n.value===X)?"":Wp(e,"to pay with"):"Nothing to buy yet. Items come from Make, and an org changes hands from another parent":"This holding predates lab keys, so it has no SegWit address to pay from"}const Yp=e=>[...[...K.items.values()].filter(t=>Nt.get(t.id)===e.id),...or(K.nodes,e).filter(t=>t.kind==="org"&&!Nn.has(t.id)&&!nn(K.nodes,t))],Xp=e=>Yp(e).filter(t=>!_t.has(t.id));function JE(e){return ye(Z.keys,K,e)?Xp(e).length?"":Yp(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 free to change hands (one without derived children)`:"This holding predates lab keys, so it has no SegWit address to be paid at"}function QE(e){const t=H("offer-item").value,n=_t.get(t),r=K.items.has(t)?null:F(t),s=Ce(r?r.parent:Nt.get(t));H("offer-ask").hidden=!n,H("offer-go").classList.toggle("primary",!n),n&&(H("offer-ask-line").textContent=`${Ce(n.seller)} asks ${G(n.price)} for ${He(t)}. Taking it costs the price, two ${X}-sat fees and a ${vt}-sat coin of ${e.name}'s that leads the deal${r?`, and gas to adopt ${r.name} at once`:""}.`,H("offer-take").textContent=`Take it for ${G(n.price)}`),H("offer-note").textContent=`${n?"Or offer less. ":""}${e.name}'s SegWit key signs the whole deal now: ${r?`${r.name}'s inscription`:"the item"} to its Taproot key, the price to ${s}, the ${X}-sat fee from its balance. Nothing reaches the chain until ${s} accepts. ${r?`Accepting takes ${r.name}'s money and items home to ${s} first; then ${e.name} adopts it. Each act of ${r.name}'s moves its inscription, which voids the offer.`:"Until then the offer stands, unless it's withdrawn or a coin it promised moves."}`}function e$(e){const t=F(H("sell-lot").value);H("sell-note").textContent=t?`Cash-free: ${t.name}'s money, gas tank and items go home to ${e.name} first, and ${t.name} is frozen while it's listed. Its own key signs its input alone, SIGHASH_SINGLE|ANYONECANPAY, for the price to ${e.name}'s SegWit address. Whoever takes it adopts it, and ${t.name} 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 Jp(e,t=K){const n=Xc(Z.keys,t,e);return n&&{taproot:n.taproot.address,segwit:n.segwit.address,nostr:n.npub.address,ethereum:n.ethereum.address}}function t$(e){const t=Jp(e),n=e.keyring;if(!t)return"This holding predates lab keys, so it has no keys to list";const r=gu(K,"keyring",e.id);return r||(!n||n.retired||Bt.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 n$(e){const t=F(e.parent),n=e.status==="closed"?`${e.name} is closed`:"",r=n?"":Un(Z,K,"act",e.id,{},wt),s=(o,i=e.id,a={})=>wu(Z,K,o,i,a);return{birth:n||r||(Xt(e)?"Agents give birth only once they graduate":s("birth")),award:n||r||(Xt(e)?"Agents award belts only once they graduate":qp(e).length?s("award"):"There is nobody else to award yet"),charter:n||r||zE(e),decide:n||r||s("decide"),make:n||r||s("make"),keyring:n||r||t$(e)||s("keyring"),send:n||r||GE(e),offer:n||r||XE(e),sell:n||r||JE(e),graduate:n||(t?e.edge==="adopted"?`${e.name} has already graduated`:t.status!=="active"?`${t.name} is closed`:Un(Z,K,"graduate",t.id,{of:e.id},wt)||gu(K,"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 Qr(){const e=F(T.node),t=T.beat!==null;if(H("act-none").hidden=!!e,H("act-past").hidden=!e||!t,H("act-on").hidden=!e||t,H("act-sub").textContent=(e==null?void 0:e.name)??"",H("past-beat").textContent=String(T.beat??""),!e||t)return;const n=n$(e),r=F(e.parent);for(const p of document.querySelectorAll("[data-verb]"))p.setAttribute("aria-pressed",String(p.dataset.verb===T.verb)),p.classList.toggle("off",!!n[p.dataset.verb]);for(const p of document.querySelectorAll("form[data-form]"))p.hidden=p.dataset.form!==T.verb||!!n[T.verb];H("act-why").textContent=n[T.verb]?`${n[T.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(w=>`${w.value}=${w.textContent}`).join("|"),o=[[H("award-to"),qp(e).map(p=>[p.id,`${Vr(K,p.id)}${p.kind==="agent"?" (agent)":""}`])],[H("send-to"),Fp(e).map(p=>[p.id,`${Vr(K,p.id)}${p.kind==="agent"?" (agent)":""}`])],[H("offer-item"),Gp(e).map(p=>[p.id,YE(p)])],[H("sell-lot"),Xp(e).map(p=>[p.id,K.items.has(p.id)?`${p.name} · an item`:`${p.name} · org ${p.index}'`])]];for(const[p,w]of o){const y=p.value,v=w.map(([m,x])=>$("option",{value:m,text:x}));s(v)!==s([...p.options])&&(p.replaceChildren(...v),v.some(m=>m.value===y)&&(p.value=y))}for(const p of["send-has","offer-has"])H(p).textContent=G(Rp(e.id));H("graduate-go").textContent=`Graduate ${e.name}`,T.verb==="charter"&&!n.charter&&FE(e),T.verb==="offer"&&!n.offer&&QE(e),T.verb==="sell"&&!n.sell&&e$(e);const i=T.verb==="keyring"&&!n.keyring&&Jp(e);i&&H("keyring-keys").replaceChildren(...[["Taproot",i.taproot],["SegWit",i.segwit],["nostr",i.nostr],["Ethereum",i.ethereum]].map(qr));const a=T.verb==="sell"&&F(H("sell-lot").value),c=T.verb==="graduate"?r:T.verb==="charter"&&ri()==="series"?Ti(e):a||e,u=c&&Te(Z.keys,K,c),l=T.verb==="send"||T.verb==="offer",f=u&&(l?`${u.from} · ${ye(Z.keys,K,c).path}`:u.path);H("act-key").textContent=!c||n[T.verb]?"":u?`Signs as ${c.name}: ${f}`:"Signs with the lab wallet: this holding predates lab keys.";const d=T.verb==="graduate"&&Te(Z.keys,K,e)?Ds(K,e.id).length:0;H("act-gas").textContent=!c||n[T.verb]||!u?"":T.verb==="send"?`Fee: ${X} sats, from ${e.name}'s balance.`:T.verb==="offer"?`Fee: ${X} sats, from ${e.name}'s balance, paid only if the holder accepts.`:T.verb==="sell"?"No fee to list: whoever takes the ask pays the fees.":`Gas: ${wE(T.verb,d).toLocaleString("en-US")} sats from ${c.name}'s tank (${G(cu(Z.chain,u.wallet))}), which tops up from its balance.${d?` ${e.name} pays ${X} more, from its own money, to claim its new root.`:""}`;const h=zp(e),g=T.closing===e.id;H("close-note").textContent=h?`Closing ${e.name} spends it for the last time, and its ${ds(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.`,H("close-go").textContent=g?`Yes, close ${e.name}`:`Close ${e.name}`,H("close-keep").hidden=!g}function Qp(){const e=H("inspect-body"),t=T.event?K.log.find(o=>o.id===T.event):null;if(t)return H("inspect-sub").textContent="event",e.replaceChildren(...y$(t));const n=T.tx?Ve.ledger.find(o=>o.key===T.tx):null;if(n)return H("inspect-sub").textContent="money",e.replaceChildren(...w$(n));const r=F(T.node);if(H("inspect-sub").textContent=(r==null?void 0:r.kind)??"",!r)return e.replaceChildren($("p",{class:"note pad",text:"Select a node in the tree, or an event in the timeline."}));const s=F(T.node,ke);if(!s)return e.replaceChildren($("p",{class:"note pad",text:`${r.name} is not born yet at beat ${T.beat}.`}));e.replaceChildren(...r$(s))}const qr=([e,t,n])=>$("div",{class:"f"},$("dt",{text:e}),$("dd",{},t,n&&$("span",{class:"fn",text:n})));function r$(e){var r;const t=F(e.parent,ke),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`from ${((o=F(s.from,ke))==null?void 0:o.name)??"?"} to ${((i=F(s.to,ke))==null?void 0:i.name)??"?"}, ${ht(s.beat)}`}).join("; "),"Each time, it took the next index under its new parent, and keys derived there."],T.beat===null&&(_t.has(e.id)||Nn.has(e.id))&&o$(e),t&&e.root===e.id&&["Holding",$("span",{},"its own, since it graduated",e.id!==T.holding&&$("button",{type:"button",class:"btn sm open",onclick:()=>{mr({holding:e.id,node:e.id}),a$()}},`Open ${e.name}`))],e.closed!==null&&["Closed",ht(e.closed)],["Charter",e.charter?ku(e):"none yet",e.charter?fs(ke,e).ok?e.charter.filing?`Filing SHA-256 ${e.charter.filing.slice(0,16)}…`:"":`Lapsed: ${fs(ke,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",[...ke.nodes.values()].filter(s=>{var o;return((o=s.charter)==null?void 0:o.master)===e.id}).map(s=>`${s.name}${fs(ke,s).ok?"":" (lapsed)"}`).join(", ")||"none yet"],["Children",or(ke.nodes,e).map(s=>s.name).join(", ")||"none yet"],ye(Z.keys,ke,e)&&["Balance",G(bo(e.id)),`Test BTC at its SegWit address${T.beat===null?"":`, as of beat ${T.beat}`}.`],T.beat===null&&Te(Z.keys,K,e)&&["Gas tank",G(cu(Z.chain,Te(Z.keys,K,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]].filter(Boolean);return[$("div",{class:"ih"},$("p",{class:"eyebrow",text:Vr(ke,e.id)}),$("h3",{class:"it",text:e.name}),$("div",{class:"chips"},$("span",{class:"chip",text:e.kind}),$("span",{class:`chip ${e.status==="active"?"ok":"bad"}`,text:e.status}),e.edge==="adopted"&&$("span",{class:"chip ok",text:"graduated"}),e.born==="cued"&&$("span",{class:"chip",text:"cued"}))),$("div",{class:"ib"},$("dl",{class:"fl"},n.map(qr)),e.badges.length>0&&$("div",{},$("p",{class:"lab",text:"Belts"}),$("ul",{class:"list"},e.badges.map(s=>{var o;return $("li",{},Mp(s),$("span",{class:"when",text:` from ${((o=F(s.by))==null?void 0:o.name)??"?"}, ${ht(s.beat)}`}))}))),e.decisions.length>0&&$("div",{},$("p",{class:"lab",text:"Decisions"}),$("ul",{class:"list"},e.decisions.map(s=>$("li",{},$("b",{text:s.title}),s.why&&` · ${s.why}`,$("span",{class:"when",text:` (${ht(s.beat)})`}))))),s$(e),c$(e),d$(e))]}function s$(e){const t=(l,f)=>f.length>0&&$("div",{},$("p",{class:"lab",text:l}),$("ul",{class:"list items"},f)),n=(l,f)=>$("li",{},$("b",{text:l.name}),l.note&&` · ${l.note}`,$("span",{class:"when",text:` (${f})`}));if(T.beat!==null)return t("Made",e.made.map(l=>ke.items.get(l)).filter(Boolean).map(l=>n(l,ht(l.beat))));const r=l=>`made${l.maker===e.id?"":` by ${Ce(l.maker)}`}${l.beat==="cued"?", cued":` at beat ${l.beat}`}`,s=[...K.items.values()].filter(l=>Nt.get(l.id)===e.id).map(l=>{const f=n(l,r(l)),d=aa().filter(h=>h.item===l.id&&h.seller===e.id&&yo(Z,K,h)==="open");return d.length&&f.append($("ul",{class:"bids"},d.map(h=>$("li",{},$("span",{text:`${Ce(h.buyer)} offers ${h.price?G(h.price):"nothing, a free claim"}`}),e.status==="active"&&$("button",{type:"button",class:"btn sm","aria-label":`Accept ${Ce(h.buyer)}'s offer for ${l.name}`,onclick:()=>Il(h)},"Accept"))))),f}),o=e.made.map(l=>K.items.get(l)).filter(l=>l&&Nt.get(l.id)!==e.id).map(l=>n(l,Nt.get(l.id)?`now held by ${Ce(Nt.get(l.id))}`:"held outside this lab")),i=aa().filter(l=>l.buyer===e.id&&yo(Z,K,l)!=="done").map(l=>{const f=du(Z,K,l);return $("li",{},$("b",{text:l.price?G(l.price):"nothing"}),` for ${He(l.item)}`,$("span",{class:"when",text:f?` (stale: ${f})`:` (open until ${Ce(l.seller)} accepts)`}),$("button",{type:"button",class:"btn sm","aria-label":`Withdraw the offer for ${He(l.item)}`,onclick:()=>i$(l)},"Withdraw"))}),a=aa().filter(l=>l.seller===e.id&&K.nodes.has(l.item)&&yo(Z,K,l)==="open").map(l=>$("li",{},$("b",{text:He(l.item)}),$("span",{class:"when",text:` ${Ce(l.buyer)} offers ${l.price?G(l.price):"nothing, a free claim"}`}),e.status==="active"&&$("button",{type:"button",class:"btn sm","aria-label":`Accept ${Ce(l.buyer)}'s offer for ${He(l.item)}`,onclick:()=>Il(l)},"Accept"))),c=Hp().filter(l=>l.seller===e.id&&$i(Z,K,l)!=="done").map(l=>{const f=hu(Z,K,l);return $("li",{},$("b",{text:G(l.price)}),` for ${He(l.lot)}`,$("span",{class:"when",text:f?` (stale: ${f})`:" (open: any node can take it)"}),$("button",{type:"button",class:"btn sm","aria-label":`Withdraw the ask for ${He(l.lot)}`,onclick:()=>e0(l)},"Withdraw"))}),u=[...Nn].filter(([,l])=>l===e.id).map(([l])=>$("li",{},$("b",{text:He(l)}),$("span",{class:"when",text:` bought from ${Ce(F(l).parent)}`}),$("button",{type:"button",class:"btn sm","aria-label":`Adopt ${He(l)}`,onclick:()=>t0(l,e.id)},"Adopt")));return[t("Items",s),t("Made, held elsewhere",o),t("Offers on its orgs",a),t("Asks",c),t("Offers made",i),t("Bought, to adopt",u)]}const Ce=e=>{const t=F(e);return t?t.root===T.holding?t.name:Vr(K,e):"?"};async function Il(e){const t=He(e.item),n=Ce(e.buyer),r=Ce(e.seller),s=K.nodes.has(e.item);if(!await Qe(i=>{kE(i,e.txid)}))return;const o=Ve.ledger.find(i=>i.txid===e.txid);fe(`${r} accepted: ${t} goes to ${n}${e.price?` for ${G(e.price)}`:", free"}, ${o!=null&&o.beat?`at beat ${o.beat}`:"cued for the next beat"}.${s?` Its money and items went home to ${r} first, and ${n} adopts it next.`:""}`)}function o$(e){const t=_t.get(e.id),n=F(Nn.get(e.id));return t?["For sale",$("span",{},`${G(t.price)}, asked by ${Ce(t.seller)}`,$("button",{type:"button",class:"btn sm open",onclick:()=>e0(t)},"Withdraw")),"Its own key signed its input, SIGHASH_SINGLE|ANYONECANPAY: any node can take it. It's frozen until then."]:["Sold",$("span",{},`to ${Ce(n.id)}, which adopts it next`,$("button",{type:"button",class:"btn sm open",onclick:()=>t0(e.id,n.id)},`Adopt into ${n.name}`)),`${n.name}'s key holds its inscription now.`]}async function e0(e){const t=He(e.lot),n=Ce(e.seller);await Qe(r=>{SE(r,Jr(e))})&&fe(`${n} withdrew its ask for ${t}.`)}async function t0(e,t){const n=He(e),r=Ce(t);if(!await Qe(o=>{AE(o,e,t)}))return;const s=K.log.findLast(o=>o.op==="join"&&o.node===e);fe(`${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 i$(e){const t=He(e.item),n=Ce(e.buyer);await Qe(r=>{EE(r,e.txid)})&&fe(`${n} withdrew its offer for ${t}.`)}function a$(){const e=document.querySelector(".tree-blk").getBoundingClientRect().top+scrollY-document.querySelector(".clock").offsetHeight-12;e(n.to===e.id||n.from===e.id)&&(T.beat===null||n.beat!==null&&n.beat<=T.beat)).slice(-6).reverse();return t.length>0&&$("div",{},$("p",{class:"lab",text:"Money"}),$("ul",{class:"list"},t.map(n=>$("li",{},$("b",{text:u$(n,e.id)}),$("span",{class:"when",text:` (${ht(n.beat??"cued")})`})))))}function u$(e,t){const n=r=>{var s;return((s=F(r))==null?void 0:s.name)??"?"};if(e.kind==="mine")return`+${G(e.amount)}, a beat's reward`;if(e.kind==="move")return`${G(e.amount)} moved to its new key, after a ${e.fee}-sat fee`;if(e.kind==="gas")return`−${G(e.amount)} into its gas tank, and a ${e.fee}-sat fee`;if(e.kind==="fund")return`+${G(e.amount)} from the lab wallet`;if(e.kind==="deal"){const r=He(e.item);return e.to===t?e.amount?`+${G(e.amount)} from ${n(e.from)} for ${r}`:`${r} to ${n(e.from)}, free`:e.amount?`−${G(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?`+${G(e.amount)} from ${n(e.from)}`:`−${G(e.amount)} to ${n(e.to)}, and a ${e.fee}-sat fee`}function n0(e){const t=n=>{const r=F(n);return r?r.root===T.holding?r.name:Vr(K,n):"?"};return e.kind==="mine"?`${G(e.amount)} → ${t(e.to)}`:e.kind==="move"?`${G(e.amount)} → ${t(e.to)}'s new key`:e.kind==="gas"?`${G(e.amount)} → ${t(e.to)}'s gas tank`:e.kind==="fund"?`${G(e.amount)} lab wallet → ${t(e.to)}`:e.kind==="deal"?`${He(e.item)} ${t(e.to)} → ${t(e.from)}, ${e.amount?`for ${G(e.amount)}`:"free"}`:`${G(e.amount)} ${t(e.from)} → ${t(e.to)}`}const l$={own:"its own key",lab:"the lab wallet",parent:"its parent's key (its handoff is cued)",other:"a key outside this lab"},f$={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 d$(e){const t=Te(Z.keys,ke,e),n=Jc(Z,K,e.id),r=["Held now by",n?l$[n.who]:"nobody: its inscription has been spent"];if(!t)return $("div",{class:"keys"},$("p",{class:"lab",text:"Keys"}),$("dl",{class:"fl"},[["Signs with","the lab wallet: this holding predates lab keys, so it has no addresses, leaves or secrets of its own"],r].map(qr)));const s=e.kind==="agent",o=Xc(Z.keys,ke,e),i=Hk(Z.keys,ke,e),a=i.map(([,,d])=>d).filter(Boolean),c="Reset the lab for standard BIP-86 keys.",u=s?"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 ${o.taproot.path}. ${u}`,tapkey:`Its npub's key with the BIP-86 tweak, the way v1.2 keyed this lab. ${u} ${c}`,wallet:`An untweaked key at ${o.taproot.path}, the way v1.1 keyed this lab. ${u} ${c}`}[t.scheme],f=[["Taproot",o.taproot.address,l],["SegWit",o.segwit.address,`BIP-84 at ${o.segwit.path}. Its money: ${e.kind==="holding"?"the beats it earns land here, and ":""}sends come and go here.`],["Tapkey",o.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",o.npub.address,`NIP-06 at ${o.npub.path}. Its nostr name; the leaves below hang off it.`],["Ethereum",o.ethereum.address,s&&e.edge!=="adopted"?`BIP-44 at ${o.ethereum.path}: account ${t.account} of its org's seed, the way Ledger Live numbers Ethereum accounts.`:`BIP-44 at ${o.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}`],r,h$(e)];return $("div",{class:"keys"},$("p",{class:"lab",text:"Keys"}),$("dl",{class:"fl"},f.map(qr)),e.keyring&&Or(`${e.keyring.retired?"Retired keyring":"Keyring"} · what each key signed`,mi(e.id,e.keyring.keys)),$("p",{class:"lab"},"Leaves",$("span",{text:` · HKDF-SHA256 from its ${s?"nostr secret":"seed"}`})),$("ul",{class:"list leaves"},i.map(([d,h])=>$("li",{},$("b",{text:d}),$("span",{class:"when",text:` ${f$[d]}`}),$("code",{text:h})))),Or(s?"Public lines to paste":"CA key for TrustedUserCAKeys",a.join(` - -`)),g$(e,t))}function h$(e){var r;const t=e.keyring,n=(t==null?void 0:t.retired)&&(t.retired.by===e.id?"It":((r=F(t.retired.by,ke))==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.`: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 Or(e,t,n=t){const r=$("pre",{text:n}),s=$("button",{type:"button",class:"cp","aria-label":`Copy ${e}`,onclick:()=>p$(t,s,r)},"Copy");return $("div",{class:"code"},$("div",{class:"code-h cph"},$("span",{text:e}),s),r)}async function p$(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 g$(e,t){var a;const n=T.reveal===e.id,r=n&&Mk(Z.keys,ke,e),s=F(e.parent,ke),o=()=>{var c;T.reveal=n?null:e.id,Qp(),(c=H("reveal"))==null||c.focus()},i=(a=r==null?void 0:r.seed)==null?void 0:a.mnemonic.split(" ");return $("div",{class:"secret"},$("div",{class:"hz"},$("span",{class:"hz-l",text:"Secret · stays in this tab"}),$("button",{type:"button",class:"btn sm",id:"reveal","aria-expanded":String(n),onclick:o},n?"Hide":"Reveal")),r&&$("div",{class:"sb"},r.seed?Or(`Seed · ${r.seed.from}`,r.seed.mnemonic,i.map((c,u)=>`${String(u+1).padStart(2,"0")} ${c}`).reduce((c,u,l)=>(l%3?c[c.length-1].push(u):c.push([u]),c),[]).map(c=>c.join(" ")).join(` -`)):$("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,l])=>Or(`${c} · ${u}`,l)),r.leaves.map(([c,u,l])=>Or(`${c} · ${u}`,l))))}function m$(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 l;return((l=u.witness)==null?void 0:l.length)===3}))==null?void 0:a.witness;if(!t)return"?";const n=Bc(t).pubkey,r=F(e.parent),s=e.op==="found"?F(e.node):null,o=[[s&&Te(Z.keys,K,s),`${s==null?void 0:s.name}'s root`],[r&&Te(Z.keys,K,r),`${r==null?void 0:r.name}'s key`],[(r==null?void 0:r.edge)==="adopted"&&Te(Z.keys,K,{...r,edge:"derived"}),`${r==null?void 0:r.name}'s derived key, from before it graduated`]];for(const[u,l]of o)if(u&&u.wallet.pubkey===n)return l;return((c=Z.wallet)==null?void 0:c.pubkey)===n?"the lab wallet":`a key outside this lab (${n.slice(0,12)}…)`}function y$(e){var o,i,a;const t=ti.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=F(e.parent))==null?void 0:a.name)??"an unknown inscription"}, whose inscription this event spent`:"nothing: a founding has no parent"],["Signed by",m$(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[$("div",{class:"ih"},$("p",{class:"eyebrow",text:`${e.op} · ${e.pending?"cued":`beat ${e.beat}`}`}),$("h3",{class:"it",text:tp(e,K)}),$("div",{class:"chips"},$("span",{class:"chip",text:(t==null?void 0:t.protocol)??"?"}),$("span",{class:`chip ${e.ok?"ok":"bad"}`,text:e.ok?"applied":"rejected"})),!e.ok&&$("p",{class:"idesc",text:"The reducer rejected this event. It stays on the chain, but it does not change the tree."})),$("div",{class:"ib"},$("dl",{class:"fl"},r.map(qr)),$("div",{class:"code"},$("p",{class:"code-h",text:"Metadata · CBOR, tag 5"}),$("pre",{text:Tl(e.meta)})),s&&$("div",{class:"code"},$("p",{class:"code-h",text:"Raw index entry"}),$("pre",{text:Tl(s)})))]}function w$(e){const t=i=>{var a;return((a=F(i))==null?void 0:a.name)??"a key outside this lab"},n=Z.chain.transactions.get(e.txid),r=e.kind==="deal",s=e.kind==="fund",o=[["When",e.beat===null?"cued for the next beat":`beat ${e.beat}`],r&&(K.nodes.has(e.item)?["Org",`${He(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",`${He(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":`${t(e.to)}'s ${e.kind==="move"?"new ":""}SegWit address`],[r?"Price":"Amount",r&&!e.amount?"nothing":G(e.amount)],e.kind!=="mine"&&["Fee",`${e.fee} sats${e.ask?` over two transactions (the buyer's split, then the deal), and a ${vt}-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",`${G(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 ${t(e.to)} listed it, then ${t(e.from)}'s SegWit key (SIGHASH_ALL) when it took it`: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[$("div",{class:"ih"},$("p",{class:"eyebrow",text:`${e.kind} · ${e.beat===null?"cued":`beat ${e.beat}`}`}),$("h3",{class:"it",text:n0(e)}),$("div",{class:"chips"},$("span",{class:"chip",text:"test BTC"}),$("span",{class:`chip${e.beat===null?"":" ok"}`,text:e.beat===null?"cued":"confirmed"}))),$("div",{class:"ib"},$("dl",{class:"fl"},o.map(qr)),n&&Or("Raw transaction",n.raw))]}function Eu(){const e=at(),t=H("beat"),n=F(T.holding);t.max=String(e),t.value=String(T.beat??e),t.disabled=e===0,H("beat-label").textContent=T.beat===null?`Now · beat ${e}`:`Beat ${T.beat} of ${e}`,H("replay").textContent=T.replay?"Stop":"Replay",H("replay").disabled=!n||e===0,H("to-now").disabled=T.beat===null,H("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 K.log)a.roots.includes(T.holding)&&o(a.pending?"cued":a.beat,{e:a,at:s.get(a.id.slice(0,-2))??0});for(const a of Ve.ledger)[a.to,a.from].some(c=>{var u;return c&&((u=F(c))==null?void 0:u.root)===T.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 H("timeline-list").replaceChildren($("li",{class:"wait",text:n?"Nothing yet.":"Found a holding to start its timeline."}));H("timeline-list").replaceChildren(...i.map(a=>{const c=a==="cued"?null:Z.chain.blocks[a-1],u=T.beat!==null&&(a==="cued"||a>T.beat),l=T.beat!==null&&a===T.beat;return $("li",{class:`beat${u?" later":""}${l?" now":""}`},$("p",{class:"bh"},$("span",{class:"bn",text:a==="cued"?"Cued":`Beat ${a}`}),$("span",{class:"bt",text:c?OE(c.time):Z.clock.tempo==="manual"?"waiting for Beat now":"landing on the next beat"})),$("ol",{class:"evs"},r.get(a).sort((f,d)=>f.at-d.at).map(({e:f,m:d})=>d?x$(d):b$(f))))}))}function b$(e){const[t,...n]=tp(e,K).split(" ");return $("li",{},$("button",{type:"button",class:`ev${e.ok?"":" bad"}${e.id===T.event?" on":""}`,"aria-pressed":String(e.id===T.event),onclick:()=>mr({event:e.id,node:e.node??T.node})},$("span",{class:"op",text:e.ok?t:`✕ ${t.replace(/:$/,"")}`})," ",$("span",{class:"es",text:n.join(" ")})))}const x$=e=>$("li",{},$("button",{type:"button",class:`ev money${e.kind==="gas"?" gas":""}${e.kind==="deal"?" deal":""}${e.key===T.tx?" on":""}`,"aria-pressed":String(e.key===T.tx),onclick:()=>{var t;return mr({tx:e.key,node:((t=F(e.to))==null?void 0:t.root)===T.holding?e.to:T.node})}},$("span",{class:"op",text:e.kind})," ",$("span",{class:"es",text:n0(e)})));H("f-found").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=Ks(t.elements.name.value);if(!n)return fe("Name the holding: lowercase letters, digits and hyphens.",!0);await Kt("found",null,{name:n},(r,s)=>(xu({holding:r,node:r}),`${n} is founded, ${s}.`))&&t.reset()});H("sample").addEventListener("click",async()=>{let e=null;fe("Rehearsing the yolopreneur tree over six beats…"),await Qe(t=>{e=IE(t)})&&(mr({holding:e,node:e}),fe("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."))});H("f-birth").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=F(T.node),r=Ks(t.elements.name.value),s=t.elements.kind.value;if(!r)return fe("Name the child: lowercase letters, digits and hyphens.",!0);await Kt("birth",n.id,{name:r,kind:s},(o,i)=>`${r} is born to ${n.name}, ${i}.`)&&(t.elements.name.value="")});H("f-award").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=F(T.node),r=t.elements.to.value,s=Ks(t.elements.skill.value),o=t.elements.belt.value;if(!s)return fe("Name the skill, for example launch.",!0);await Kt("award",n.id,{to:r,skill:s,belt:o},(i,a)=>{var c;return`${(c=F(r))==null?void 0:c.name} holds a ${o} belt in ${s}, ${a}.`})&&(t.elements.skill.value="")});H("f-decide").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=F(T.node),r=t.elements.title.value.trim(),s=t.elements.why.value.trim();if(!r)return fe("A decision needs a title.",!0);await Kt("decide",n.id,{title:r,why:s},(o,i)=>`${n.name} decided “${r}”, ${i}.`)&&t.reset()});H("f-send").addEventListener("submit",async e=>{var a;e.preventDefault();const t=e.currentTarget,n=F(T.node),r=t.elements.to.value,s=vi(t.elements.amount.value);if(s===null)return fe("Write an amount in test BTC, for example 1.5 (at most eight decimals).",!0);let o=null;if(!await Qe(c=>{o=xE(c,n.id,r,s)}))return;const i=Ve.ledger.find(c=>c.txid===o);fe(`${n.name} sent ${G(s)} to ${((a=F(r))==null?void 0:a.root)===n.root?F(r).name:Vr(K,r)}, ${i!=null&&i.beat?`at beat ${i.beat}`:"cued for the next beat"}.`),t.elements.amount.value=""});H("f-make").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=F(T.node),r=Ks(t.elements.name.value),s=t.elements.note.value.trim();if(!r)return fe("Name the item: lowercase letters, digits and hyphens.",!0);await Kt("make",n.id,{name:r,note:s},(o,i)=>`${n.name} made ${r}, ${i}.`)&&t.reset()});H("f-charter").addEventListener("change",e=>{e.target.name==="form"&&Qr()});H("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()));H("charter-filing").value=[...n].map(s=>s.toString(16).padStart(2,"0")).join(""),e.target.value="",fe(`Hashed ${t.name} in this tab: only its SHA-256 would go on chain.`)});H("f-charter").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=F(T.node),r=ri();if(!r)return fe("Pick a legal form.",!0);if(r==="series"){const a=Ti(n);await Kt("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:Ks(s("provider")),filing:s("filing").toLowerCase()},i=(a,c)=>`${n.name} is chartered as ${VE[r]}${o.jurisdiction?` in ${o.jurisdiction}`:""}, ${c}.`;if(await Kt("charter",n.id,o,i))for(const a of["legal","filing"])t.querySelector(`[name="${a}"]`).value=""});H("f-keyring").addEventListener("submit",async e=>{e.preventDefault();const t=F(T.node);await Kt("keyring",t.id,{},(n,r)=>`${t.name} published its keyring, ${r}: four keys, each signing the same statement.`)});H("f-offer").addEventListener("submit",async e=>{var a;e.preventDefault();const t=e.currentTarget,n=F(T.node),r=H("offer-item").value,s=vi(t.elements.price.value);if(s===null)return fe("Write a price in test BTC, for example 0.1, or 0 for a free claim.",!0);const o=Ce(K.items.has(r)?Nt.get(r):(a=F(r))==null?void 0:a.parent),i=He(r);await Qe(c=>{vE(c,r,n.id,s)})&&(fe(`${n.name} offers ${s?G(s):"nothing"} for ${i}. The offer stands until ${o} accepts it.`),t.elements.price.value="")});H("offer-take").addEventListener("click",async()=>{const e=F(T.node),t=H("offer-item").value,n=_t.get(t),r=K.nodes.has(t);if(!n)return;const s=He(t),o=Ce(n.seller);if(!await Qe(c=>{_E(c,Jr(n),e.id)}))return;const i=Ve.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 fe(`${e.name} took ${s} from ${o} for ${G(n.price)}, ${a}.`);mr({holding:e.root,node:t}),fe(`${e.name} bought ${s} from ${o} for ${G(n.price)} and adopted it, ${a}: its keys derive from ${e.name}'s seed now.`)});H("f-sell").addEventListener("submit",async e=>{e.preventDefault();const t=e.currentTarget,n=F(T.node),r=H("sell-lot").value,s=vi(t.elements.price.value),o=K.nodes.has(r);if(s===null)return fe("Write a price in test BTC, for example 1.",!0);const i=He(r);await Qe(a=>{Lp(a,r,s)})&&(fe(`${n.name} lists ${i} at ${G(s)}: any node can take it.${o?` Whatever it held went home to ${n.name} first, and it's frozen until the ask is taken or withdrawn.`:""}`),t.elements.price.value="")});for(const e of["offer-item","sell-lot"])H(e).addEventListener("change",()=>Qr());H("send-max").addEventListener("click",()=>{const e=F(T.node),t=e&&ye(Z.keys,K,e);t&&(H("send-amount").value=pp(ru(Z.chain.coins(t.script))))});H("f-graduate").addEventListener("submit",async e=>{e.preventDefault();const t=F(T.node),n=F(t.parent);await Kt("graduate",n.id,{of:t.id},(r,s)=>(xu({node:t.id}),`${t.name} graduates from ${n.name}, ${s}. It's a holding of its own now.`))});H("f-close").addEventListener("submit",async e=>{e.preventDefault();const t=F(T.node);if(T.closing!==t.id)return T.closing=t.id,Qr(),H("close-go").focus();T.closing=null,await Kt("close",t.id,{},(n,r)=>`${t.name} is closed, ${r}.`)});H("close-keep").addEventListener("click",()=>{T.closing=null,Qr(),H("close-go").focus()});for(const e of document.querySelectorAll("[data-verb]"))e.addEventListener("click",()=>{T.verb=e.dataset.verb,T.closing=null,Qr()});for(const e of document.querySelectorAll("[data-rule]"))e.addEventListener("click",async()=>{const t=e.dataset.rule;await Qe(n=>fE(n,t))&&fe({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])});H("f-fund").addEventListener("submit",async e=>{var i;e.preventDefault();const t=e.currentTarget,n=t.elements.to.value,r=vi(t.elements.amount.value);if(r===null)return fe("Write an amount in test BTC, for example 5 (at most eight decimals).",!0);let s=null;if(!await Qe(a=>{s=BE(a,n,r)}))return;const o=Ve.ledger.find(a=>a.txid===s);fe(`The lab wallet funded ${(i=F(n))==null?void 0:i.name} with ${G(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 Qe(r=>pE(r,n,Date.now(),Ai(r,bu(r)??T.holding)))&&fe(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.`)});H("beat-now").addEventListener("click",()=>Kp(e=>{ct(e,Ai(e,bu(e)??T.holding))}));setInterval(()=>{Dp();const{tempo:e,nextAt:t}=Z.clock;T.busy||document.hidden||typeof e!="number"||!Z.chain.mempool.length||t&&Date.now()gE(n,Date.now(),Ai(n,bu(n)??T.holding)))},1e3);addEventListener("storage",e=>{(e.key===Si||e.key===null)&&jp()});function qs(){T.replay&&(clearInterval(T.replay),T.replay=null,Eu())}function v$(){const e=F(T.holding);if(!(!e||!at())){if(ni(typeof e.born=="number"?e.born:at()),T.beat===null)return fe("Nothing to replay yet: this holding has one beat of history.");T.replay=setInterval(()=>{(T.beat===null||T.beat+1>=at())&&qs(),ni(T.beat===null?at():T.beat+1)},800),Eu()}}H("beat").addEventListener("input",e=>{qs(),ni(Number(e.target.value))});H("replay").addEventListener("click",()=>T.replay?qs():v$());for(const e of["to-now","past-now"])H(e).addEventListener("click",()=>{qs(),ni(at())});const ca=["system","light","dark"],r0=()=>{H("theme").textContent=`Theme: ${document.documentElement.dataset.theme??"system"}`};H("theme").addEventListener("click",()=>{const e=ca[(ca.indexOf(document.documentElement.dataset.theme??"system")+1)%ca.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{}r0()});function s0(e,t,n){const r=H("confirm");r.replaceChildren($("span",{text:e}),$("button",{type:"button",class:"btn sm danger",text:t,onclick:()=>{r.hidden=!0,n()}}),$("button",{type:"button",class:"btn sm",text:"Cancel",onclick:()=>{r.hidden=!0}})),r.hidden=!1,r.querySelector("button").focus()}const k$={read:()=>{try{return pu()}catch{return Vs()}}};async function o0(e,t){qs(),await Qe(n=>{Object.assign(n,e())},k$)&&(Object.assign(T,{holding:null,node:null,event:null,tx:null,beat:null,closing:null}),vu(),fe(t))}H("save").addEventListener("click",()=>{const e=$("a",{href:URL.createObjectURL(new Blob([Bp(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),fe("Saved a backup of this lab, test wallet included. Load it in any browser to carry on.")});H("load").addEventListener("click",()=>H("load-file").click());H("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=Ap(await t.text())}catch(s){return fe(`${t.name} is not an Orgchain lab: ${s.message}`,!0)}s0(`Replace this browser's lab with ${t.name}?`,"Replace",()=>o0(()=>n,`Loaded ${t.name}.`))});H("reset").addEventListener("click",()=>s0("Erase this browser's lab: every holding, the chain and the test wallet?","Erase",()=>o0(Vs,"Erased. This is a fresh lab.")));r0();jp(); diff --git a/ventures/lineage/orgchain/index.html b/ventures/lineage/orgchain/index.html index b31481f..6bb888a 100644 --- a/ventures/lineage/orgchain/index.html +++ b/ventures/lineage/orgchain/index.html @@ -4,11 +4,11 @@ Orgchain · Lineage - + - + @@ -17,7 +17,7 @@

Lineage /

Orgchain

-

Found a holding, then birth its orgs and agents, award belts, record decisions, make items, buy and sell items and orgs, publish keyrings, charter legal forms, send test BTC, graduate and close. Each act is an inscription whose parent is the node that authorizes it, paid for with the actor's own gas, and each beat is a block whose 50 test BTC the holdings mine. Lineage gives the structure; the chain adds time.

+

Found a holding, then birth its orgs and agents, award belts, record decisions, make items, buy and sell items, orgs and whole holdings, publish keyrings, charter legal forms, send test BTC, graduate and close. Each act is an inscription whose parent is the node that authorizes it, paid for with the actor's own gas, and each beat is a block whose 50 test BTC the holdings mine. Lineage gives the structure; the chain adds time.

Test coins only @@ -137,11 +137,11 @@
-

The sender pays the chain's 500-sat fee. One send spends at most eight coins and moves at most 50 test BTC, one block reward.

+

The sender pays the chain's 500-sat fee. One send spends at most 64 coins and moves at most 50 test BTC, one block reward.