@vbyte/btc-dev 1.0.7 → 1.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/class/tx.d.ts +6 -6
- package/dist/class/tx.js +10 -6
- package/dist/class/witness.d.ts +3 -3
- package/dist/class/witness.js +1 -10
- package/dist/lib/witness/parse.js +2 -1
- package/dist/main.cjs +12 -16
- package/dist/main.cjs.map +1 -1
- package/dist/module.mjs +12 -16
- package/dist/module.mjs.map +1 -1
- package/dist/package.json +1 -1
- package/dist/script.js +1 -1
- package/dist/script.js.map +1 -1
- package/dist/types/class.d.ts +2 -12
- package/dist/types/witness.d.ts +1 -0
- package/package.json +1 -1
- package/src/class/tx.ts +13 -7
- package/src/class/witness.ts +2 -12
- package/src/lib/witness/parse.ts +2 -1
- package/src/types/class.ts +2 -13
- package/src/types/witness.ts +1 -0
package/dist/script.js
CHANGED
|
@@ -11,5 +11,5 @@ function Ye(e){void 0!==e.lowS&&se("lowS",e.lowS),void 0!==e.prehash&&se("prehas
|
|
|
11
11
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
12
12
|
const dt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},ht=BigInt(0),ft=BigInt(1),lt=BigInt(2),pt=(e,t)=>(e+t/lt)/t;function gt(e){const t=dt.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),u=BigInt(88),c=e*e*e%t,d=c*c*e%t,h=Ae(d,n,t)*d%t,f=Ae(h,n,t)*d%t,l=Ae(f,lt,t)*c%t,p=Ae(l,i,t)*l%t,g=Ae(p,s,t)*p%t,m=Ae(g,a,t)*g%t,y=Ae(m,u,t)*m%t,w=Ae(y,a,t)*g%t,_=Ae(w,n,t)*d%t,v=Ae(_,o,t)*p%t,b=Ae(v,r,t)*c%t,E=Ae(b,lt,t);if(!mt.eql(mt.sqr(E),e))throw new Error("Cannot find square root");return E}const mt=Be(dt.p,void 0,void 0,{sqrt:gt}),yt=function(e,t){const n=t=>ct({...e,hash:t});return{...n(t),create:n}}({...dt,Fp:mt,lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=dt.n,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-ft*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),a=pt(s*e,t),u=pt(-r*e,t);let c=Oe(e-a*n-u*i,t),d=Oe(-a*r-u*s,t);const h=c>o,f=d>o;if(h&&(c=t-c),f&&(d=t-d),c>o||d>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:h,k1:c,k2neg:f,k2:d}}}},ee),wt={};function _t(e,...t){let n=wt[e];if(void 0===n){const t=ee(Uint8Array.from(e,e=>e.charCodeAt(0)));n=V(t,t),wt[e]=n}return ee(V(n,...t))}const vt=e=>e.toBytes(!0).slice(1),bt=e=>de(e,32),Et=e=>Oe(e,dt.p),xt=e=>Oe(e,dt.n),St=(()=>yt.Point)(),kt=e=>e%lt===ht;function Ot(e){let t=yt.utils.normPrivateKeyToScalar(e),n=St.fromPrivateKey(t);return{scalar:kt(n.y)?t:xt(-t),bytes:vt(n)}}function At(e){ge("x",e,ft,dt.p);const t=Et(e*e);let n=gt(Et(t*e+BigInt(7)));kt(n)||(n=Et(-n));const r=St.fromAffine({x:e,y:n});return r.assertValidity(),r}const Pt=ue;function Tt(...e){return xt(Pt(_t("BIP0340/challenge",...e)))}function It(e){return Ot(e).bytes}function Nt(e,t,n=W(32)){const r=fe("message",e),{bytes:i,scalar:s}=Ot(t),o=fe("auxRand",n,32),a=bt(s^Pt(_t("BIP0340/aux",o))),u=_t("BIP0340/nonce",a,i,r),c=xt(Pt(u));if(c===ht)throw new Error("sign failed: k is zero");const{bytes:d,scalar:h}=Ot(c),f=Tt(d,i,r),l=new Uint8Array(64);if(l.set(d,0),l.set(bt(xt(h+f*s)),32),!Ut(l,r,i))throw new Error("sign: Invalid signature produced");return l}function Ut(e,t,n){const r=fe("signature",e,64),i=fe("message",t),s=fe("publicKey",n,32);try{const e=At(Pt(s)),t=Pt(r.subarray(0,32));if(!pe(t,ft,dt.p))return!1;const n=Pt(r.subarray(32,64));if(!pe(n,ft,dt.n))return!1;const o=Tt(bt(t),vt(e),i),a=St.BASE.multiplyUnsafe(n).add(e.multiplyUnsafe(xt(-o))),{x:u,y:c}=a.toAffine();return!(a.is0()||!kt(c)||u!==t)}catch(e){return!1}}const $t=(()=>({getPublicKey:It,sign:Nt,verify:Ut,utils:{randomPrivateKey:yt.utils.randomPrivateKey,lift_x:At,pointToBytes:vt,numberToBytesBE:de,bytesToNumberBE:ue,taggedHash:_t,mod:Oe}}))();BigInt(0),BigInt(2);Be(yt.CURVE.n,32,!0);const Ct=yt.Point.BASE;function Bt(e,t){const n=Ht(e).big;return jt(Ct.multiply(n).toHex(!0),t)}function Rt(e,t,n,r=!1){const i=Ht(t).big,s=function(e){try{const t=jt(e,"ecdsa");return yt.Point.fromHex(t)}catch(t){throw new Error("invalid pubkey: "+e)}}(e),o=Ct.multiply(i);let a=s.add(o);r&&!a.hasEvenY()&&(a=a.negate());return jt(a.toHex(!0),n)}function Lt(e,t){const n=Ht(t),r=yt.sign(n,e).toDERRawBytes();return m.bytes(r)}function zt(e,t){const n=Ht(t);return Ht($t.sign(n,e))}function jt(e,t){try{const n=Ht(e);if(33===n.length&&"bip340"===t)return n.slice(1);if(32===n.length&&"ecdsa"===t){const e=m.num(2,1);return m.join([e,n])}return n}catch(t){throw new Error("invalid pubkey: "+String(e))}}function Ht(e){try{return m.bytes(e)}catch(t){throw new Error("invalid bytes: "+String(e))}}const Dt=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Ft=(()=>Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)))(),Vt=(()=>Ft.map(e=>(9*e+5)%16))(),Zt=(()=>{const e=[[Ft],[Vt]];for(let t=0;t<4;t++)for(let n of e)n.push(n[t].map(e=>Dt[e]));return e})(),Kt=(()=>Zt[0])(),Wt=(()=>Zt[1])(),qt=[[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)),Mt=Kt.map((e,t)=>e.map(e=>qt[t][e])),Gt=Wt.map((e,t)=>e.map(e=>qt[t][e])),Yt=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Qt=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Jt(e,t,n,r){return 0===e?t^n^r:1===e?t&n|~t&r:2===e?(t|~n)^r:3===e?t&r|n&~r:t^(n|~r)}const Xt=new Uint32Array(16);class en extends G{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:t,h2:n,h3:r,h4:i}=this;return[e,t,n,r,i]}set(e,t,n,r,i){this.h0=0|e,this.h1=0|t,this.h2=0|n,this.h3=0|r,this.h4=0|i}process(e,t){for(let n=0;n<16;n++,t+=4)Xt[n]=e.getUint32(t,!0);let n=0|this.h0,r=n,i=0|this.h1,s=i,o=0|this.h2,a=o,u=0|this.h3,c=u,d=0|this.h4,h=d;for(let e=0;e<5;e++){const t=4-e,f=Yt[e],l=Qt[e],p=Kt[e],g=Wt[e],m=Mt[e],y=Gt[e];for(let t=0;t<16;t++){const r=I(n+Jt(e,i,o,u)+Xt[p[t]]+f,m[t])+d|0;n=d,d=u,u=0|I(o,10),o=i,i=r}for(let e=0;e<16;e++){const n=I(r+Jt(t,s,a,c)+Xt[g[e]]+l,y[e])+h|0;r=h,h=c,c=0|I(a,10),a=s,s=n}}this.set(this.h1+o+c|0,this.h2+u+h|0,this.h3+d+r|0,this.h4+n+s|0,this.h0+i+a|0)}roundClean(){A(Xt)}destroy(){this.destroyed=!0,A(this.buffer),this.set(0,0,0,0,0)}}const tn=K(()=>new en);function nn(...e){const t=m.join(e),n=tn(ee(t));return new m(n)}function rn(...e){const t=m.join(e),n=ee(t);return new m(n)}function sn(...e){const t=m.join(e),n=ee(ee(t));return new m(n)}function on(e,...t){const n=function(e){const t=rn(m.str(e));return m.join([t,t])}(e),r=t.map(e=>new m(e));return rn(m.join([n,...r]))}var an,un;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},e.getValidEnumValues=t=>{const n=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),r={};for(const e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(const n of e)if(t(n))return n},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(an||(an={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(un||(un={}));const cn=an.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),dn=e=>{switch(typeof e){case"undefined":return cn.undefined;case"string":return cn.string;case"number":return Number.isNaN(e)?cn.nan:cn.number;case"boolean":return cn.boolean;case"function":return cn.function;case"bigint":return cn.bigint;case"symbol":return cn.symbol;case"object":return Array.isArray(e)?cn.array:null===e?cn.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?cn.promise:"undefined"!=typeof Map&&e instanceof Map?cn.map:"undefined"!=typeof Set&&e instanceof Set?cn.set:"undefined"!=typeof Date&&e instanceof Date?cn.date:cn.object;default:return cn.unknown}},hn=an.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"]);class fn extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(const i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(r);else if("invalid_return_type"===i.code)r(i.returnTypeError);else if("invalid_arguments"===i.code)r(i.argumentsError);else if(0===i.path.length)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){const n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(e){if(!(e instanceof fn))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,an.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},n=[];for(const r of this.issues)r.path.length>0?(t[r.path[0]]=t[r.path[0]]||[],t[r.path[0]].push(e(r))):n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}fn.create=e=>new fn(e);const ln=(e,t)=>{let n;switch(e.code){case hn.invalid_type:n=e.received===cn.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case hn.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,an.jsonStringifyReplacer)}`;break;case hn.unrecognized_keys:n=`Unrecognized key(s) in object: ${an.joinValues(e.keys,", ")}`;break;case hn.invalid_union:n="Invalid input";break;case hn.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${an.joinValues(e.options)}`;break;case hn.invalid_enum_value:n=`Invalid enum value. Expected ${an.joinValues(e.options)}, received '${e.received}'`;break;case hn.invalid_arguments:n="Invalid function arguments";break;case hn.invalid_return_type:n="Invalid function return type";break;case hn.invalid_date:n="Invalid date";break;case hn.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(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}"`:an.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case hn.too_small:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case hn.too_big:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case hn.custom:n="Invalid input";break;case hn.invalid_intersection_types:n="Intersection results could not be merged";break;case hn.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case hn.not_finite:n="Number must be finite";break;default:n=t.defaultError,an.assertNever(e)}return{message:n}};let pn=ln;function gn(e,t){const n=pn,r=(e=>{const{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],o={...i,path:s};if(void 0!==i.message)return{...i,path:s,message:i.message};let a="";const u=r.filter(e=>!!e).slice().reverse();for(const e of u)a=e(o,{data:t,defaultError:a}).message;return{...i,path:s,message:a}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===ln?void 0:ln].filter(e=>!!e)});e.common.issues.push(r)}class mn{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const r of t){if("aborted"===r.status)return yn;"dirty"===r.status&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const e of t){const t=await e.key,r=await e.value;n.push({key:t,value:r})}return mn.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const r of t){const{key:t,value:i}=r;if("aborted"===t.status)return yn;if("aborted"===i.status)return yn;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"===t.value||void 0===i.value&&!r.alwaysSet||(n[t.value]=i.value)}return{status:e.value,value:n}}}const yn=Object.freeze({status:"aborted"}),wn=e=>({status:"dirty",value:e}),_n=e=>({status:"valid",value:e}),vn=e=>"aborted"===e.status,bn=e=>"dirty"===e.status,En=e=>"valid"===e.status,xn=e=>"undefined"!=typeof Promise&&e instanceof Promise;var Sn;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(Sn||(Sn={}));class kn{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const On=(e,t)=>{if(En(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 t=new fn(e.common.issues);return this._error=t,this._error}}};function An(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:i};return{errorMap:(t,i)=>{const{message:s}=e;return"invalid_enum_value"===t.code?{message:s??i.defaultError}:void 0===i.data?{message:s??r??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:s??n??i.defaultError}},description:i}}class Pn{get description(){return this._def.description}_getType(e){return dn(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:dn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new mn,ctx:{common:e.parent.common,data:e.data,parsedType:dn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(xn(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:dn(e)},r=this._parseSync({data:e,path:n.path,parent:n});return On(n,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:dn(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return En(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>En(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:dn(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(xn(r)?r:Promise.resolve(r));return On(n,i)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,r)=>{const i=e(t),s=()=>r.addIssue({code:hn.custom,...n(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(e=>!!e||(s(),!1)):!!i||(s(),!1)})}refinement(e,t){return this._refinement((n,r)=>!!e(n)||(r.addIssue("function"==typeof t?t(n,r):t),!1))}_refinement(e){return new Ar({schema:this,typeName:Lr.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Pr.create(this,this._def)}nullable(){return Tr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return hr.create(this)}promise(){return Or.create(this,this._def)}or(e){return pr.create([this,e],this._def)}and(e){return mr.create(this,e,this._def)}transform(e){return new Ar({...An(this._def),schema:this,typeName:Lr.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ir({...An(this._def),innerType:this,defaultValue:t,typeName:Lr.ZodDefault})}brand(){return new $r({typeName:Lr.ZodBranded,type:this,...An(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Nr({...An(this._def),innerType:this,catchValue:t,typeName:Lr.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Cr.create(this,e)}readonly(){return Br.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Tn=/^c[^\s-]{8,}$/i,In=/^[0-9a-z]+$/,Nn=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Un=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,$n=/^[a-z0-9_-]{21}$/i,Cn=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Bn=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Rn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Ln;const zn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,jn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Hn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Dn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Fn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Vn=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Zn="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Kn=new RegExp(`^${Zn}$`);function Wn(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function qn(e){return new RegExp(`^${Wn(e)}$`)}function Mn(e){let t=`${Zn}T${Wn(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function Gn(e,t){return!("v4"!==t&&t||!zn.test(e))||!("v6"!==t&&t||!Hn.test(e))}function Yn(e,t){if(!Cn.test(e))return!1;try{const[n]=e.split("."),r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return"object"==typeof i&&null!==i&&((!("typ"in i)||"JWT"===i?.typ)&&(!!i.alg&&(!t||i.alg===t)))}catch{return!1}}function Qn(e,t){return!("v4"!==t&&t||!jn.test(e))||!("v6"!==t&&t||!Dn.test(e))}class Jn extends Pn{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==cn.string){const t=this._getOrReturnCtx(e);return gn(t,{code:hn.invalid_type,expected:cn.string,received:t.parsedType}),yn}const t=new mn;let n;for(const r of this._def.checks)if("min"===r.kind)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),gn(n,{code:hn.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("max"===r.kind)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),gn(n,{code:hn.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("length"===r.kind){const i=e.data.length>r.value,s=e.data.length<r.value;(i||s)&&(n=this._getOrReturnCtx(e,n),i?gn(n,{code:hn.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):s&&gn(n,{code:hn.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if("email"===r.kind)Rn.test(e.data)||(n=this._getOrReturnCtx(e,n),gn(n,{validation:"email",code:hn.invalid_string,message:r.message}),t.dirty());else if("emoji"===r.kind)Ln||(Ln=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ln.test(e.data)||(n=this._getOrReturnCtx(e,n),gn(n,{validation:"emoji",code:hn.invalid_string,message:r.message}),t.dirty());else if("uuid"===r.kind)Un.test(e.data)||(n=this._getOrReturnCtx(e,n),gn(n,{validation:"uuid",code:hn.invalid_string,message:r.message}),t.dirty());else if("nanoid"===r.kind)$n.test(e.data)||(n=this._getOrReturnCtx(e,n),gn(n,{validation:"nanoid",code:hn.invalid_string,message:r.message}),t.dirty());else if("cuid"===r.kind)Tn.test(e.data)||(n=this._getOrReturnCtx(e,n),gn(n,{validation:"cuid",code:hn.invalid_string,message:r.message}),t.dirty());else if("cuid2"===r.kind)In.test(e.data)||(n=this._getOrReturnCtx(e,n),gn(n,{validation:"cuid2",code:hn.invalid_string,message:r.message}),t.dirty());else if("ulid"===r.kind)Nn.test(e.data)||(n=this._getOrReturnCtx(e,n),gn(n,{validation:"ulid",code:hn.invalid_string,message:r.message}),t.dirty());else if("url"===r.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),gn(n,{validation:"url",code:hn.invalid_string,message:r.message}),t.dirty()}else if("regex"===r.kind){r.regex.lastIndex=0;r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),gn(n,{validation:"regex",code:hn.invalid_string,message:r.message}),t.dirty())}else if("trim"===r.kind)e.data=e.data.trim();else if("includes"===r.kind)e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),gn(n,{code:hn.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty());else if("toLowerCase"===r.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===r.kind)e.data=e.data.toUpperCase();else if("startsWith"===r.kind)e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),gn(n,{code:hn.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty());else if("endsWith"===r.kind)e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),gn(n,{code:hn.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty());else if("datetime"===r.kind){Mn(r).test(e.data)||(n=this._getOrReturnCtx(e,n),gn(n,{code:hn.invalid_string,validation:"datetime",message:r.message}),t.dirty())}else if("date"===r.kind){Kn.test(e.data)||(n=this._getOrReturnCtx(e,n),gn(n,{code:hn.invalid_string,validation:"date",message:r.message}),t.dirty())}else if("time"===r.kind){qn(r).test(e.data)||(n=this._getOrReturnCtx(e,n),gn(n,{code:hn.invalid_string,validation:"time",message:r.message}),t.dirty())}else"duration"===r.kind?Bn.test(e.data)||(n=this._getOrReturnCtx(e,n),gn(n,{validation:"duration",code:hn.invalid_string,message:r.message}),t.dirty()):"ip"===r.kind?Gn(e.data,r.version)||(n=this._getOrReturnCtx(e,n),gn(n,{validation:"ip",code:hn.invalid_string,message:r.message}),t.dirty()):"jwt"===r.kind?Yn(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),gn(n,{validation:"jwt",code:hn.invalid_string,message:r.message}),t.dirty()):"cidr"===r.kind?Qn(e.data,r.version)||(n=this._getOrReturnCtx(e,n),gn(n,{validation:"cidr",code:hn.invalid_string,message:r.message}),t.dirty()):"base64"===r.kind?Fn.test(e.data)||(n=this._getOrReturnCtx(e,n),gn(n,{validation:"base64",code:hn.invalid_string,message:r.message}),t.dirty()):"base64url"===r.kind?Vn.test(e.data)||(n=this._getOrReturnCtx(e,n),gn(n,{validation:"base64url",code:hn.invalid_string,message:r.message}),t.dirty()):an.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:hn.invalid_string,...Sn.errToObj(n)})}_addCheck(e){return new Jn({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Sn.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Sn.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Sn.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Sn.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Sn.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Sn.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Sn.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Sn.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Sn.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Sn.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Sn.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Sn.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Sn.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Sn.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...Sn.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Sn.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Sn.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Sn.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Sn.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Sn.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Sn.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Sn.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Sn.errToObj(t)})}nonempty(e){return this.min(1,Sn.errToObj(e))}trim(){return new Jn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Jn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Jn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function Xn(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}Jn.create=e=>new Jn({checks:[],typeName:Lr.ZodString,coerce:e?.coerce??!1,...An(e)});class er extends Pn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==cn.number){const t=this._getOrReturnCtx(e);return gn(t,{code:hn.invalid_type,expected:cn.number,received:t.parsedType}),yn}let t;const n=new mn;for(const r of this._def.checks)if("int"===r.kind)an.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),gn(t,{code:hn.invalid_type,expected:"integer",received:"float",message:r.message}),n.dirty());else if("min"===r.kind){(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),gn(t,{code:hn.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty())}else if("max"===r.kind){(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),gn(t,{code:hn.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty())}else"multipleOf"===r.kind?0!==Xn(e.data,r.value)&&(t=this._getOrReturnCtx(e,t),gn(t,{code:hn.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):"finite"===r.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),gn(t,{code:hn.not_finite,message:r.message}),n.dirty()):an.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Sn.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Sn.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Sn.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Sn.toString(t))}setLimit(e,t,n,r){return new er({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:Sn.toString(r)}]})}_addCheck(e){return new er({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Sn.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Sn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Sn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Sn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Sn.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Sn.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Sn.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Sn.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Sn.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&an.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if("finite"===n.kind||"int"===n.kind||"multipleOf"===n.kind)return!0;"min"===n.kind?(null===t||n.value>t)&&(t=n.value):"max"===n.kind&&(null===e||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}er.create=e=>new er({checks:[],typeName:Lr.ZodNumber,coerce:e?.coerce||!1,...An(e)});class tr extends Pn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==cn.bigint)return this._getInvalidInput(e);let t;const n=new mn;for(const r of this._def.checks)if("min"===r.kind){(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),gn(t,{code:hn.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty())}else if("max"===r.kind){(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),gn(t,{code:hn.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty())}else"multipleOf"===r.kind?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),gn(t,{code:hn.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):an.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return gn(t,{code:hn.invalid_type,expected:cn.bigint,received:t.parsedType}),yn}gte(e,t){return this.setLimit("min",e,!0,Sn.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Sn.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Sn.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Sn.toString(t))}setLimit(e,t,n,r){return new tr({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:Sn.toString(r)}]})}_addCheck(e){return new tr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Sn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Sn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Sn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Sn.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Sn.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}tr.create=e=>new tr({checks:[],typeName:Lr.ZodBigInt,coerce:e?.coerce??!1,...An(e)});class nr extends Pn{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==cn.boolean){const t=this._getOrReturnCtx(e);return gn(t,{code:hn.invalid_type,expected:cn.boolean,received:t.parsedType}),yn}return _n(e.data)}}nr.create=e=>new nr({typeName:Lr.ZodBoolean,coerce:e?.coerce||!1,...An(e)});class rr extends Pn{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==cn.date){const t=this._getOrReturnCtx(e);return gn(t,{code:hn.invalid_type,expected:cn.date,received:t.parsedType}),yn}if(Number.isNaN(e.data.getTime())){return gn(this._getOrReturnCtx(e),{code:hn.invalid_date}),yn}const t=new mn;let n;for(const r of this._def.checks)"min"===r.kind?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),gn(n,{code:hn.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),t.dirty()):"max"===r.kind?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),gn(n,{code:hn.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),t.dirty()):an.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new rr({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Sn.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Sn.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}rr.create=e=>new rr({checks:[],coerce:e?.coerce||!1,typeName:Lr.ZodDate,...An(e)});class ir extends Pn{_parse(e){if(this._getType(e)!==cn.symbol){const t=this._getOrReturnCtx(e);return gn(t,{code:hn.invalid_type,expected:cn.symbol,received:t.parsedType}),yn}return _n(e.data)}}ir.create=e=>new ir({typeName:Lr.ZodSymbol,...An(e)});class sr extends Pn{_parse(e){if(this._getType(e)!==cn.undefined){const t=this._getOrReturnCtx(e);return gn(t,{code:hn.invalid_type,expected:cn.undefined,received:t.parsedType}),yn}return _n(e.data)}}sr.create=e=>new sr({typeName:Lr.ZodUndefined,...An(e)});class or extends Pn{_parse(e){if(this._getType(e)!==cn.null){const t=this._getOrReturnCtx(e);return gn(t,{code:hn.invalid_type,expected:cn.null,received:t.parsedType}),yn}return _n(e.data)}}or.create=e=>new or({typeName:Lr.ZodNull,...An(e)});class ar extends Pn{constructor(){super(...arguments),this._any=!0}_parse(e){return _n(e.data)}}ar.create=e=>new ar({typeName:Lr.ZodAny,...An(e)});class ur extends Pn{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _n(e.data)}}ur.create=e=>new ur({typeName:Lr.ZodUnknown,...An(e)});class cr extends Pn{_parse(e){const t=this._getOrReturnCtx(e);return gn(t,{code:hn.invalid_type,expected:cn.never,received:t.parsedType}),yn}}cr.create=e=>new cr({typeName:Lr.ZodNever,...An(e)});class dr extends Pn{_parse(e){if(this._getType(e)!==cn.undefined){const t=this._getOrReturnCtx(e);return gn(t,{code:hn.invalid_type,expected:cn.void,received:t.parsedType}),yn}return _n(e.data)}}dr.create=e=>new dr({typeName:Lr.ZodVoid,...An(e)});class hr extends Pn{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==cn.array)return gn(t,{code:hn.invalid_type,expected:cn.array,received:t.parsedType}),yn;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(gn(t,{code:e?hn.too_big:hn.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(null!==r.minLength&&t.data.length<r.minLength.value&&(gn(t,{code:hn.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),null!==r.maxLength&&t.data.length>r.maxLength.value&&(gn(t,{code:hn.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new kn(t,e,t.path,n)))).then(e=>mn.mergeArray(n,e));const i=[...t.data].map((e,n)=>r.type._parseSync(new kn(t,e,t.path,n)));return mn.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new hr({...this._def,minLength:{value:e,message:Sn.toString(t)}})}max(e,t){return new hr({...this._def,maxLength:{value:e,message:Sn.toString(t)}})}length(e,t){return new hr({...this._def,exactLength:{value:e,message:Sn.toString(t)}})}nonempty(e){return this.min(1,e)}}function fr(e){if(e instanceof lr){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Pr.create(fr(r))}return new lr({...e._def,shape:()=>t})}return e instanceof hr?new hr({...e._def,type:fr(e.element)}):e instanceof Pr?Pr.create(fr(e.unwrap())):e instanceof Tr?Tr.create(fr(e.unwrap())):e instanceof yr?yr.create(e.items.map(e=>fr(e))):e}hr.create=(e,t)=>new hr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Lr.ZodArray,...An(t)});class lr extends Pn{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=an.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==cn.object){const t=this._getOrReturnCtx(e);return gn(t,{code:hn.invalid_type,expected:cn.object,received:t.parsedType}),yn}const{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof cr&&"strip"===this._def.unknownKeys))for(const e in n.data)i.includes(e)||s.push(e);const o=[];for(const e of i){const t=r[e],i=n.data[e];o.push({key:{status:"valid",value:e},value:t._parse(new kn(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof cr){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of s)o.push({key:{status:"valid",value:e},value:{status:"valid",value:n.data[e]}});else if("strict"===e)s.length>0&&(gn(n,{code:hn.unrecognized_keys,keys:s}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of s){const r=n.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new kn(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>mn.mergeObjectSync(t,e)):mn.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return new lr({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,n)=>{const r=this._def.errorMap?.(t,n).message??n.defaultError;return"unrecognized_keys"===t.code?{message:Sn.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new lr({...this._def,unknownKeys:"strip"})}passthrough(){return new lr({...this._def,unknownKeys:"passthrough"})}extend(e){return new lr({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new lr({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Lr.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new lr({...this._def,catchall:e})}pick(e){const t={};for(const n of an.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new lr({...this._def,shape:()=>t})}omit(e){const t={};for(const n of an.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new lr({...this._def,shape:()=>t})}deepPartial(){return fr(this)}partial(e){const t={};for(const n of an.objectKeys(this.shape)){const r=this.shape[n];e&&!e[n]?t[n]=r:t[n]=r.optional()}return new lr({...this._def,shape:()=>t})}required(e){const t={};for(const n of an.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof Pr;)e=e._def.innerType;t[n]=e}return new lr({...this._def,shape:()=>t})}keyof(){return xr(an.objectKeys(this.shape))}}lr.create=(e,t)=>new lr({shape:()=>e,unknownKeys:"strip",catchall:cr.create(),typeName:Lr.ZodObject,...An(t)}),lr.strictCreate=(e,t)=>new lr({shape:()=>e,unknownKeys:"strict",catchall:cr.create(),typeName:Lr.ZodObject,...An(t)}),lr.lazycreate=(e,t)=>new lr({shape:e,unknownKeys:"strip",catchall:cr.create(),typeName:Lr.ZodObject,...An(t)});class pr extends Pn{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map(async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const n=e.map(e=>new fn(e.ctx.common.issues));return gn(t,{code:hn.invalid_union,unionErrors:n}),yn});{let e;const r=[];for(const i of n){const n={...t,common:{...t.common,issues:[]},parent:null},s=i._parseSync({data:t.data,path:t.path,parent:n});if("valid"===s.status)return s;"dirty"!==s.status||e||(e={result:s,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const i=r.map(e=>new fn(e));return gn(t,{code:hn.invalid_union,unionErrors:i}),yn}}get options(){return this._def.options}}function gr(e,t){const n=dn(e),r=dn(t);if(e===t)return{valid:!0,data:e};if(n===cn.object&&r===cn.object){const n=an.objectKeys(t),r=an.objectKeys(e).filter(e=>-1!==n.indexOf(e)),i={...e,...t};for(const n of r){const r=gr(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===cn.array&&r===cn.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let r=0;r<e.length;r++){const i=gr(e[r],t[r]);if(!i.valid)return{valid:!1};n.push(i.data)}return{valid:!0,data:n}}return n===cn.date&&r===cn.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}pr.create=(e,t)=>new pr({options:e,typeName:Lr.ZodUnion,...An(t)});class mr extends Pn{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(vn(e)||vn(r))return yn;const i=gr(e.value,r.value);return i.valid?((bn(e)||bn(r))&&t.dirty(),{status:t.value,value:i.data}):(gn(n,{code:hn.invalid_intersection_types}),yn)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}mr.create=(e,t,n)=>new mr({left:e,right:t,typeName:Lr.ZodIntersection,...An(n)});class yr extends Pn{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==cn.array)return gn(n,{code:hn.invalid_type,expected:cn.array,received:n.parsedType}),yn;if(n.data.length<this._def.items.length)return gn(n,{code:hn.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),yn;!this._def.rest&&n.data.length>this._def.items.length&&(gn(n,{code:hn.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...n.data].map((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new kn(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>mn.mergeArray(t,e)):mn.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new yr({...this._def,rest:e})}}yr.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new yr({items:e,typeName:Lr.ZodTuple,rest:null,...An(t)})};class wr extends Pn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==cn.object)return gn(n,{code:hn.invalid_type,expected:cn.object,received:n.parsedType}),yn;const r=[],i=this._def.keyType,s=this._def.valueType;for(const e in n.data)r.push({key:i._parse(new kn(n,e,n.path,e)),value:s._parse(new kn(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?mn.mergeObjectAsync(t,r):mn.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){return new wr(t instanceof Pn?{keyType:e,valueType:t,typeName:Lr.ZodRecord,...An(n)}:{keyType:Jn.create(),valueType:e,typeName:Lr.ZodRecord,...An(t)})}}class _r extends Pn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==cn.map)return gn(n,{code:hn.invalid_type,expected:cn.map,received:n.parsedType}),yn;const r=this._def.keyType,i=this._def.valueType,s=[...n.data.entries()].map(([e,t],s)=>({key:r._parse(new kn(n,e,n.path,[s,"key"])),value:i._parse(new kn(n,t,n.path,[s,"value"]))}));if(n.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const n of s){const r=await n.key,i=await n.value;if("aborted"===r.status||"aborted"===i.status)return yn;"dirty"!==r.status&&"dirty"!==i.status||t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{const e=new Map;for(const n of s){const r=n.key,i=n.value;if("aborted"===r.status||"aborted"===i.status)return yn;"dirty"!==r.status&&"dirty"!==i.status||t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}}_r.create=(e,t,n)=>new _r({valueType:t,keyType:e,typeName:Lr.ZodMap,...An(n)});class vr extends Pn{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==cn.set)return gn(n,{code:hn.invalid_type,expected:cn.set,received:n.parsedType}),yn;const r=this._def;null!==r.minSize&&n.data.size<r.minSize.value&&(gn(n,{code:hn.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),null!==r.maxSize&&n.data.size>r.maxSize.value&&(gn(n,{code:hn.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const i=this._def.valueType;function s(e){const n=new Set;for(const r of e){if("aborted"===r.status)return yn;"dirty"===r.status&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}const o=[...n.data.values()].map((e,t)=>i._parse(new kn(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>s(e)):s(o)}min(e,t){return new vr({...this._def,minSize:{value:e,message:Sn.toString(t)}})}max(e,t){return new vr({...this._def,maxSize:{value:e,message:Sn.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}vr.create=(e,t)=>new vr({valueType:e,minSize:null,maxSize:null,typeName:Lr.ZodSet,...An(t)});class br extends Pn{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}br.create=(e,t)=>new br({getter:e,typeName:Lr.ZodLazy,...An(t)});class Er extends Pn{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return gn(t,{received:t.data,code:hn.invalid_literal,expected:this._def.value}),yn}return{status:"valid",value:e.data}}get value(){return this._def.value}}function xr(e,t){return new Sr({values:e,typeName:Lr.ZodEnum,...An(t)})}Er.create=(e,t)=>new Er({value:e,typeName:Lr.ZodLiteral,...An(t)});class Sr extends Pn{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return gn(t,{expected:an.joinValues(n),received:t.parsedType,code:hn.invalid_type}),yn}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return gn(t,{received:t.data,code:hn.invalid_enum_value,options:n}),yn}return _n(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Sr.create(e,{...this._def,...t})}exclude(e,t=this._def){return Sr.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Sr.create=xr;class kr extends Pn{_parse(e){const t=an.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==cn.string&&n.parsedType!==cn.number){const e=an.objectValues(t);return gn(n,{expected:an.joinValues(e),received:n.parsedType,code:hn.invalid_type}),yn}if(this._cache||(this._cache=new Set(an.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=an.objectValues(t);return gn(n,{received:n.data,code:hn.invalid_enum_value,options:e}),yn}return _n(e.data)}get enum(){return this._def.values}}kr.create=(e,t)=>new kr({values:e,typeName:Lr.ZodNativeEnum,...An(t)});class Or extends Pn{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==cn.promise&&!1===t.common.async)return gn(t,{code:hn.invalid_type,expected:cn.promise,received:t.parsedType}),yn;const n=t.parsedType===cn.promise?t.data:Promise.resolve(t.data);return _n(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Or.create=(e,t)=>new Or({type:e,typeName:Lr.ZodPromise,...An(t)});class Ar extends Pn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Lr.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{gn(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===r.type){const e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return yn;const r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===r.status?yn:"dirty"===r.status||"dirty"===t.value?wn(r.value):r});{if("aborted"===t.value)return yn;const r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===r.status?yn:"dirty"===r.status||"dirty"===t.value?wn(r.value):r}}if("refinement"===r.type){const e=e=>{const t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===r.status?yn:("dirty"===r.status&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>"aborted"===n.status?yn:("dirty"===n.status&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if("transform"===r.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!En(e))return yn;const s=r.transform(e.value,i);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>En(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):yn)}an.assertNever(r)}}Ar.create=(e,t,n)=>new Ar({schema:e,typeName:Lr.ZodEffects,effect:t,...An(n)}),Ar.createWithPreprocess=(e,t,n)=>new Ar({schema:t,effect:{type:"preprocess",transform:e},typeName:Lr.ZodEffects,...An(n)});class Pr extends Pn{_parse(e){return this._getType(e)===cn.undefined?_n(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Pr.create=(e,t)=>new Pr({innerType:e,typeName:Lr.ZodOptional,...An(t)});class Tr extends Pn{_parse(e){return this._getType(e)===cn.null?_n(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Tr.create=(e,t)=>new Tr({innerType:e,typeName:Lr.ZodNullable,...An(t)});class Ir extends Pn{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===cn.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ir.create=(e,t)=>new Ir({innerType:e,typeName:Lr.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...An(t)});class Nr extends Pn{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return xn(r)?r.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new fn(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===r.status?r.value:this._def.catchValue({get error(){return new fn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Nr.create=(e,t)=>new Nr({innerType:e,typeName:Lr.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...An(t)});class Ur extends Pn{_parse(e){if(this._getType(e)!==cn.nan){const t=this._getOrReturnCtx(e);return gn(t,{code:hn.invalid_type,expected:cn.nan,received:t.parsedType}),yn}return{status:"valid",value:e.data}}}Ur.create=e=>new Ur({typeName:Lr.ZodNaN,...An(e)});class $r extends Pn{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class Cr extends Pn{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?yn:"dirty"===e.status?(t.dirty(),wn(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})()}{const e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?yn:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new Cr({in:e,out:t,typeName:Lr.ZodPipeline})}}class Br extends Pn{_parse(e){const t=this._def.innerType._parse(e),n=e=>(En(e)&&(e.value=Object.freeze(e.value)),e);return xn(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}function Rr(e,t){const n="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof n?{message:n}:n}var Lr;Br.create=(e,t)=>new Br({innerType:e,typeName:Lr.ZodReadonly,...An(t)}),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",e.ZodReadonly="ZodReadonly"}(Lr||(Lr={}));const zr=Jn.create,jr=er.create,Hr=tr.create,Dr=nr.create,Fr=rr.create,Vr=or.create,Zr=ar.create,Kr=hr.create,Wr=lr.create,qr=pr.create,Mr=wr.create,Gr=br.create,Yr=Hr();Dr(),Fr();const Qr=jr().min(Number.MIN_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).int(),Jr=((e,t={message:`Input not instance of ${e.name}`})=>function(e,t={},n){return e?ar.create().superRefine((r,i)=>{const s=e(r);if(s instanceof Promise)return s.then(e=>{if(!e){const e=Rr(t,r),s=e.fatal??n??!0;i.addIssue({code:"custom",...e,fatal:s})}});if(!s){const e=Rr(t,r),s=e.fatal??n??!0;i.addIssue({code:"custom",...e,fatal:s})}}):ar.create()}(t=>t instanceof e,t))(Uint8Array);zr(),Qr.min(5e8),Zr(),Qr.min(0).max(255),Qr.min(0).max(65535);const Xr=Qr.min(0).max(4294967295);jr().refine(e=>String(e).includes(".")).refine(e=>{const t=String(e).split(".").at(1);return void 0!==t&&t.length<=2});const ei=zr().regex(/^[0-9a-fA-F]*$/).refine(e=>e.length%2==0),ti=qr([zr(),jr(),Dr(),Vr()]),ni=Gr(()=>qr([ti,Kr(ni),Mr(ni)]));Jr.refine(e=>20===e.length);const ri=Jr.refine(e=>32===e.length),ii=Jr.refine(e=>33===e.length),si=Jr.refine(e=>64===e.length);ei.refine(e=>40===e.length);const oi=ei.refine(e=>64===e.length),ai=ei.refine(e=>66===e.length),ui=ei.refine(e=>128===e.length);qr([ei,Jr]);const ci=qr([oi,ri]);
|
|
13
13
|
/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
14
|
-
function di(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function hi(e,...t){if(!di(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 fi(e,t){return!!Array.isArray(t)&&(0===t.length||(e?t.every(e=>"string"==typeof e):t.every(e=>Number.isSafeInteger(e))))}function li(e){if("function"!=typeof e)throw new Error("function expected");return!0}function pi(e,t){if("string"!=typeof t)throw new Error(`${e}: string expected`);return!0}function gi(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function mi(e){if(!Array.isArray(e))throw new Error("array expected")}function yi(e,t){if(!fi(!0,t))throw new Error(`${e}: array of strings expected`)}function wi(e,t){if(!fi(!1,t))throw new Error(`${e}: array of numbers expected`)}function _i(...e){const t=e=>e,n=(e,t)=>n=>e(t(n));return{encode:e.map(e=>e.encode).reduceRight(n,t),decode:e.map(e=>e.decode).reduce(n,t)}}function vi(e){const t="string"==typeof e?e.split(""):e,n=t.length;yi("alphabet",t);const r=new Map(t.map((e,t)=>[e,t]));return{encode:r=>(mi(r),r.map(r=>{if(!Number.isSafeInteger(r)||r<0||r>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${r}". Allowed: ${e}`);return t[r]})),decode:t=>(mi(t),t.map(t=>{pi("alphabet.decode",t);const n=r.get(t);if(void 0===n)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return n}))}}function bi(e=""){return pi("join",e),{encode:t=>(yi("join.decode",t),t.join(e)),decode:t=>(pi("join.decode",t),t.split(e))}}function Ei(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(mi(e),!e.length)return[];let r=0;const i=[],s=Array.from(e,e=>{if(gi(e),e<0||e>=t)throw new Error(`invalid integer: ${e}`);return e}),o=s.length;for(;;){let e=0,a=!0;for(let i=r;i<o;i++){const o=s[i],u=t*e,c=u+o;if(!Number.isSafeInteger(c)||u/t!==e||c-o!==u)throw new Error("convertRadix: carry overflow");const d=c/n;e=c%n;const h=Math.floor(d);if(s[i]=h,!Number.isSafeInteger(h)||h*n+e!==c)throw new Error("convertRadix: carry overflow");a&&(h?a=!1:r=i)}if(i.push(e),a)break}for(let t=0;t<e.length-1&&0===e[t];t++)i.push(0);return i.reverse()}qr([ai,ii]),qr([ui,si]),zr().regex(/^[1-9A-HJ-NP-Za-km-z]+$/),zr().regex(/^[a-zA-Z0-9+/]+={0,2}$/),zr().regex(/^[a-zA-Z0-9\-_]+={0,2}$/),zr().regex(/^[a-z]+1[023456789acdefghjklmnpqrstuvwxyz]+$/);const xi=(e,t)=>0===t?e:xi(t,e%t),Si=(e,t)=>e+(t-xi(e,t)),ki=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function Oi(e,t,n,r){if(mi(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(Si(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${Si(t,n)}`);let i=0,s=0;const o=ki[t],a=ki[n]-1,u=[];for(const r of e){if(gi(r),r>=o)throw new Error(`convertRadix2: invalid data word=${r} from=${t}`);if(i=i<<t|r,s+t>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${t}`);for(s+=t;s>=n;s-=n)u.push((i>>s-n&a)>>>0);const e=ki[s];if(void 0===e)throw new Error("invalid carry");i&=e-1}if(i=i<<n-s&a,!r&&s>=t)throw new Error("Excess padding");if(!r&&i>0)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&u.push(i>>>0),u}function Ai(e,t=!1){if(gi(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(Si(8,e)>32||Si(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!di(n))throw new Error("radix2.encode input should be Uint8Array");return Oi(Array.from(n),8,e,!t)},decode:n=>(wi("radix2.decode",n),Uint8Array.from(Oi(n,e,8,t)))}}function Pi(e){return li(e),function(...t){try{return e.apply(null,t)}catch(e){}}}const Ti=(()=>"function"==typeof Uint8Array.from([]).toBase64&&"function"==typeof Uint8Array.fromBase64)()?{encode:e=>(hi(e),e.toBase64()),decode:e=>(e=>{if(pi("base64",e),e.length>0&&!/^[A-Za-z0-9=+/]+$/.test(e))throw new Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:"base64",lastChunkHandling:"strict"})})(e)}:_i(Ai(6),vi("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),function(e,t="="){return gi(e),pi("padding",t),{encode(n){for(yi("padding.encode",n);n.length*e%8;)n.push(t);return n},decode(n){yi("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)}}}(6),bi("")),Ii=_i(Ai(6),vi("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),bi("")),Ni=(Ui="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",_i(function(e){return gi(e),{encode:t=>{if(!di(t))throw new Error("radix.encode input should be Uint8Array");return Ei(Array.from(t),256,e)},decode:t=>(wi("radix.decode",t),Uint8Array.from(Ei(t,e,256)))}}(58),vi(Ui),bi("")));var Ui;const $i=e=>{return _i((n=t=>e(e(t)),gi(t=4),li(n),{encode(e){if(!di(e))throw new Error("checksum.encode: input should be Uint8Array");const r=n(e).slice(0,t),i=new Uint8Array(e.length+t);return i.set(e),i.set(r,e.length),i},decode(e){if(!di(e))throw new Error("checksum.decode: input should be Uint8Array");const r=e.slice(0,-t),i=e.slice(-t),s=n(r).slice(0,t);for(let e=0;e<t;e++)if(s[e]!==i[e])throw new Error("Invalid checksum");return r}}),Ni);var t,n},Ci=_i(vi("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),bi("")),Bi=[996825010,642813549,513874426,1027748829,705979059];function Ri(e){const t=e>>25;let n=(33554431&e)<<5;for(let e=0;e<Bi.length;e++)1==(t>>e&1)&&(n^=Bi[e]);return n}function Li(e,t,n=1){const r=e.length;let i=1;for(let t=0;t<r;t++){const n=e.charCodeAt(t);if(n<33||n>126)throw new Error(`Invalid prefix (${e})`);i=Ri(i)^n>>5}i=Ri(i);for(let t=0;t<r;t++)i=Ri(i)^31&e.charCodeAt(t);for(let e of t)i=Ri(i)^e;for(let e=0;e<6;e++)i=Ri(i);return i^=n,Ci.encode(Oi([i%ki[30]],30,5,!1))}function zi(e){const t="bech32"===e?1:734539939,n=Ai(5),r=n.decode,i=n.encode,s=Pi(r);function o(e,n,r=90){pi("bech32.encode prefix",e),di(n)&&(n=Array.from(n)),wi("bech32.encode",n);const i=e.length;if(0===i)throw new TypeError(`Invalid prefix length ${i}`);const s=i+7+n.length;if(!1!==r&&s>r)throw new TypeError(`Length ${s} exceeds limit ${r}`);const o=e.toLowerCase(),a=Li(o,n,t);return`${o}1${Ci.encode(n)}${a}`}function a(e,n=90){pi("bech32.decode input",e);const r=e.length;if(r<8||!1!==n&&r>n)throw new TypeError(`invalid string length: ${r} (${e}). Expected (8..${n})`);const i=e.toLowerCase();if(e!==i&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const s=i.lastIndexOf("1");if(0===s||-1===s)throw new Error('Letter "1" must be present between prefix and data only');const o=i.slice(0,s),a=i.slice(s+1);if(a.length<6)throw new Error("Data must be at least 6 characters long");const u=Ci.decode(a).slice(0,-6),c=Li(o,u,t);if(!a.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:o,words:u}}return{encode:o,decode:a,encodeFromBytes:function(e,t){return o(e,i(t))},decodeToBytes:function(e){const{prefix:t,words:n}=a(e,!1);return{prefix:t,words:n,bytes:r(n)}},decodeUnsafe:Pi(a),fromWords:r,fromWordsUnsafe:s,toWords:i}}const ji=zi("bech32"),Hi=zi("bech32m"),Di={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},Fi=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)()?{encode:e=>(hi(e),e.toHex()),decode:e=>(pi("hex",e),Uint8Array.fromHex(e))}:_i(Ai(4),vi("0123456789abcdef"),bi(""),(li(Vi=e=>{if("string"!=typeof e||e.length%2!=0)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}),{encode:e=>e,decode:e=>Vi(e)}));var Vi,Zi,Ki,Wi,qi,Mi;function Gi(e){if("string"!=typeof e||0===e.length)throw new Error(`invalid prefix: ${String(e)}`)}function Yi(e){if(!Array.isArray(e)||!e.every(e=>"number"==typeof e))throw new Error(`invalid words: ${String(e)}`)}!function(e){e.encode=e=>(b.is_uint(e),$i(ee).encode(e)),e.decode=e=>(b.is_base58(e),$i(ee).decode(e))}(Zi||(Zi={})),function(e){e.encode=e=>(b.is_uint(e),Ti.encode(e)),e.decode=e=>(b.is_base64(e),Ti.decode(e))}(Ki||(Ki={})),function(e){e.encode=e=>(b.is_uint(e),Ii.encode(e)),e.decode=e=>(b.is_b64url(e),Ii.decode(e))}(Wi||(Wi={})),function(e){e.to_words=ji.toWords,e.to_bytes=ji.fromWords,e.encode=(e,t,n=!1)=>(Gi(e),Yi(t),ji.encode(e,t,n)),e.decode=(e,t=!1)=>(b.is_bech32(e),ji.decode(e,t))}(qi||(qi={})),function(e){e.to_words=Hi.toWords,e.to_bytes=Hi.fromWords,e.encode=(e,t,n=!1)=>(Gi(e),Yi(t),Hi.encode(e,t,n)),e.decode=(e,t=!1)=>(b.is_bech32(e),Hi.decode(e,t))}(Mi||(Mi={}));const Qi={TXID:"00".repeat(32),VOUT:4294967295},Ji={LOCKTIME:0,SEQUENCE:4294967295,VERSION:2},Xi=[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],es={p2pkh:/^76a914[0-9a-f]{40}88ac$/i,p2sh:/^a914[0-9a-f]{40}87$/i,p2wpkh:/^0014[0-9a-f]{40}$/i,p2wsh:/^0020[0-9a-f]{64}$/i,p2tr:/^5120[0-9a-f]{64}$/i,opreturn:/^6a[0-9a-f]{2,}$/i},ts=[1,2,3,129,130,131],ns=[0,...ts];var rs=Object.freeze({__proto__:null,COINBASE:Qi,DEFAULT:Ji,LOCK_SCRIPT_REGEX:es,SCRIPT_INT_KEY:"",SIGHASH_DEFAULT:1,SIGHASH_SEGWIT:ts,SIGHASH_TAPROOT:ns,TAPLEAF_DEFAULT_VERSION:192,TAPLEAF_VERSIONS:Xi,TX_SIZE:{GLOBAL_BASE:8,GLOBAL_WIT:10,TXIN_BASE:40,TXOUT_BASE:8}});const is={prevouts:[],segwit:!0};function ss(e,t={}){const n={...is,...t};b.is_bytes(e,"txbytes must be hex or a unit array");const r=new y(e),i=function(e){return e.read(4).reverse().to_num()}(r),s=!!n.segwit&&function(e){const[t,n]=[...e.peek(2)];if(0===t){if(e.read(2),1===n)return!0;throw new Error(`Invalid witness flag: ${n}`)}return!1}(r),o=function(e,t){const n=[],r=e.varint();for(let i=0;i<r;i++){const r=os(e,t.at(i));n.push(r)}return n}(r,n.prevouts),a=function(e){const t=[],n=e.varint();for(let r=0;r<n;r++)try{t.push(as(e))}catch(e){throw new Error(`failed to decode output: ${r}: ${_(e)}`)}return t}(r);if(s)for(const e of o)e.witness=us(r);const u=function(e){return e.read(4).reverse().to_num()}(r);return{version:i,vin:o,vout:a,locktime:u}}function os(e,t=null){const n=e.read(32).reverse().hex,r=e.read(4).reverse().num,i=cs(e,!0),s=e.read(4).reverse().num,o=[];return n===Qi.TXID&&r===Qi.VOUT?{coinbase:i,prevout:null,script_sig:null,sequence:s,txid:n,vout:r,witness:o}:{coinbase:null,prevout:t,script_sig:i,sequence:s,txid:n,vout:r,witness:o}}function as(e){const t=e.read(8).reverse().big,n=cs(e,!0);return b.exists(n,"failed to decode script_pk"),{value:t,script_pk:n}}function us(e){const t=[],n=e.varint();for(let r=0;r<n;r++){const n=cs(e,!0);if(null===n)throw new Error("failed to decode witness element: "+r);t.push(n)}return t}function cs(e,t){const n=!0===t?e.varint("le"):e.size;return n>0?e.read(n).hex:null}const ds=qr([Kr(ci),ci]),hs=Wr({pubkey:ci,leaves:ds.array().optional(),target:ci.optional(),version:Xr.optional()});var fs=Object.freeze({__proto__:null,config:hs,taptree:ds});const ls=Yr.max(2100000000000000n),ps=Wr({value:ls,script_pk:ei}),gs=Wr({coinbase:ei.nullable(),txid:oi,vout:Xr,prevout:ps.nullable(),script_sig:ei.nullable(),sequence:Xr,witness:Kr(ei)}),ms=Wr({version:Xr,vin:Kr(gs),vout:Kr(ps),locktime:Xr}),ys=gs.extend({coinbase:ei.nullable().optional(),prevout:ps.nullable().optional(),script_sig:ei.nullable().optional(),sequence:Xr.optional(),witness:Kr(ei).optional()}),ws=Wr({version:Xr.optional(),vin:Kr(ys).default([]),vout:Kr(ps).default([]),locktime:Xr.optional()});var _s=Object.freeze({__proto__:null,sats:ls,tx_data:ms,tx_input:gs,tx_output:ps,tx_template:ws,vin_template:ys}),vs=Object.freeze({__proto__:null,taproot:fs,tx:_s});function bs(e){ws.parse(e)}function Es(e){ps.parse(e)}function xs(e){ys.parse(e)}function Ss(e){xs(e),b.exists(e.coinbase,"coinbase is required");const t=e.coinbase,n=e.sequence??Ji.SEQUENCE,r=Qi.TXID,i=Qi.VOUT;return{coinbase:t,prevout:null,script_sig:null,sequence:n,witness:e.witness??[],txid:r,vout:i}}function ks(e){xs(e),b.exists(e.prevout,"prevout is required");const t=e.prevout,n=e.script_sig??null,r=e.sequence??Ji.SEQUENCE,i=e.witness??[];return{...e,coinbase:null,prevout:t,script_sig:n,sequence:r,witness:i}}function Os(e){xs(e),b.exists(e.txid,"txid is required"),b.exists(e.vout,"vout is required");const t=e.coinbase??null,n=e.prevout??null,r=e.script_sig??null,i=e.sequence??Ji.SEQUENCE,s=e.witness??[];return null!==t?Ss(e):null!==n?ks(e):{...e,coinbase:t,prevout:n,script_sig:r,sequence:i,witness:s}}function As(e){Es(e);const{script_pk:t,value:n}=e;return{script_pk:t,value:BigInt(n)}}function Ps(e){bs(e);const{vin:t=[],vout:n=[]}=e,r=e.locktime??Ji.LOCKTIME,i=e.version??Ji.VERSION;return{locktime:r,vin:t.map(e=>Os(e)),vout:n.map(e=>As(e)),version:i}}function Ts(e){return"string"==typeof e?ss(e):(bs(e),Ps(e))}function Is(e,t){let{txindex:n,txinput:r}=t??{};if(void 0!==n){if(n>=e.vin.length)throw new Error("Input index out of bounds: "+String(n));r=e.vin.at(n)}return b.ok(void 0!==r),r}function Ns(e){return 0!==e?m.num(e,1).hex:""}const Us={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};function $s(e){if(e>186&&e<255)return"OP_SUCCESS"+String(e);for(const[t,n]of Object.entries(Us))if(n===e)return t;throw new Error("OPCODE not found:"+String(e))}function Cs(e){for(const[t,n]of Object.entries(Us))if(t===e)return Number(n);throw new Error("OPCODE not found:"+e)}function Bs(e){switch(!0){case 0===e:return"opcode";case e>=1&&e<=75:return"varint";case 76===e:return"pushdata1";case 77===e:return"pushdata2";case 78===e:return"pushdata4";case e<=254:return"opcode";default:throw new Error(`Invalid word range: ${e}`)}}function Rs(e){switch(!0){case"number"!=typeof e:return!1;case 0===e:return!0;case[].includes(e):return!1;case 75<e&&e<254:return!0;default:return!1}}const Ls=520;function zs(e,t=!1){if(0===e.length)return"00";const n=[];for(const t of e)n.push(js(t));const r=m.join(n);return t?r.prepend(m.varint(r.length,"le")).hex:r.hex}function js(e){let t;if("string"==typeof e){if(e.startsWith("OP_")){const t=Cs(e);return m.num(t,1)}t=m.is_hex(e)?m.hex(e):m.str(e)}else if("number"==typeof e)t=m.num(e);else{if(!(e instanceof Uint8Array))throw new Error("invalid word type:"+typeof e);t=new m(e)}if(1===t.length&&t[0]<=16)0!==t[0]&&(t[0]+=80);else if(t.length>Ls){let e;e=Hs(t),e=e.map(e=>Ds(e)),t=m.join(e)}else t=Ds(t);return t}function Hs(e){const t=[],n=new y(e);for(;n.size>Ls;)t.push(n.read(Ls));return t.push(n.read(n.size)),t}function Ds(e){const t=Fs(e.length);return m.join([t,e])}function Fs(e){const t=m.num(76,1),n=m.num(77,1);switch(!0){case e<=75:return m.num(e);case e>75&&e<256:return m.join([t,m.num(e,1,"le")]);case e>=256&&e<=Ls:return m.join([n,m.num(e,2,"le")]);default:throw new Error("Invalid word size:"+e.toString())}}function Vs(e){const t=new y(e),n=[],r=t.size;let i,s,o,a=0;for(;a<r;)switch(i=t.read(1).num,s=Bs(i),a++,s){case"varint":n.push(t.read(i).hex),a+=i;break;case"pushdata1":o=t.read(1).reverse().num,n.push(t.read(o).hex),a+=o+1;break;case"pushdata2":o=t.read(2).reverse().num,n.push(t.read(o).hex),a+=o+2;break;case"pushdata4":o=t.read(4).reverse().num,n.push(t.read(o).hex),a+=o+4;break;case"opcode":if(!Rs(i))throw new Error(`Invalid OPCODE: ${i}`);n.push($s(i));break;default:throw new Error(`Word type undefined: ${i}`)}return n}function Zs(e){try{return Vs(e).length>0}catch{return!1}}function Ks(e){return m.bytes(e).prefix_varint("le").hex}function Ws(e){return[...("string"==typeof e?e:m.bytes(e).hex).matchAll(/20([0-9a-f]{64})(ac|ad|ba)/gi)].map(e=>e[1])}var qs;!function(e){e.prefix_size=Ks,e.decode=Vs,e.encode=zs,e.is_valid=Zs,e.get_pubkeys=Ws,e.OPCODES=Us}(qs||(qs={}));var Ms=Object.freeze({__proto__:null,OPCODE_MAP:Us,get ScriptUtil(){return qs},decode_script:Vs,encode_script:zs,encode_script_word:js,get_asm_code:Cs,get_op_code:$s,get_op_type:Bs,get_size_varint:Fs,is_valid_op:Rs,is_valid_script:Zs,parse_script_pubkeys:Ws,prefix_script_size:Ks,prefix_word_size:Ds,split_script_word:Hs});function Gs(e,t=!0){const n=Ts(e),{version:r,vin:i,vout:s,locktime:o}=n,a=[Ys(r)];if(t&&a.push(m.hex("0001")),a.push(eo(i)),a.push(ro(s)),t)for(const e of i)a.push(so(e.witness));return a.push(oo(o)),m.join(a)}function Ys(e){return m.num(e,4).reverse()}function Qs(e){return m.hex(e,32).reverse()}function Js(e){return m.num(e,4).reverse()}function Xs(e){return m.num(e,4).reverse()}function eo(e){const t=[m.varint(e.length,"le")];for(const n of e)t.push(to(n));return m.join(t)}function to(e){return null!==e.coinbase?m.join([Qs(Qi.TXID),Js(Qi.VOUT),ao(e.coinbase),Xs(e.sequence)]):m.join([Qs(e.txid),Js(e.vout),ao(e.script_sig),Xs(e.sequence)])}function no(e){return m.big(e,8).reverse()}function ro(e){const t=[m.varint(e.length,"le")];for(const n of e)t.push(io(n));return m.join(t)}function io(e){const{value:t,script_pk:n}=e;return m.join([no(t),ao(n)])}function so(e){const t=[m.varint(e.length)];for(const n of e)t.push(ao(n));return m.join(t)}function oo(e){return m.num(e,4).reverse()}function ao(e){return null!==e?(b.is_hex(e),m.hex(e).prefix_varint("le")):m.hex("00")}function uo(e){return e.startsWith("6a")}function co(e){for(const[t,n]of Object.entries(es))if(n.test(e))return t;return"unknown"}function ho(e){switch(e.slice(0,4)){case"0014":return 0;case"5120":return 1;default:return null}}function fo(e){return sn(Gs(Ts(e),!1)).reverse().hex}function lo(e){return sn(Gs(Ts(e),!0)).reverse().hex}function po(e){const t=Ts(e),n=t.vin.reduce((e,t)=>e+(t.prevout?.value??0n),0n),r=t.vout.reduce((e,t)=>e+t.value,0n);return{fees:n>r?n-r:0n,vin:n,vout:r}}function go(e){const t=Ts(e),n=Gs(t,!1).length,r=Gs(t,!0).length,i=3*n+r,s=i%4>0?1:0;return{base:n,total:r,vsize:Math.floor(i/4)+s,weight:i}}function mo(e){return to(e).length}function yo(e){return io(e).length}var wo=Object.freeze({__proto__:null,assert_has_prevouts:function(e){if(e.some(e=>null===e.prevout))throw new Error("transaction missing prevouts")},assert_tx_data:function(e){ms.parse(e)},assert_tx_input:function(e){gs.parse(e)},assert_tx_output:Es,assert_tx_template:bs,assert_vin_template:xs,create_coinbase_input:Ss,create_spend_input:ks,create_tx:Ps,create_tx_input:Os,create_tx_output:As,decode_tx:ss,encode_script_data:ao,encode_tx:Gs,encode_tx_inputs:eo,encode_tx_locktime:oo,encode_tx_outputs:ro,encode_tx_version:Ys,encode_tx_vout:io,encode_txin_sequence:Xs,encode_txin_txid:Qs,encode_txin_vout:Js,encode_vin:to,encode_vin_witness:so,encode_vout_value:no,get_segwit_size:function(e){return 2+e.filter(e=>e.witness.length>0).map(e=>e.witness).reduce((e,t)=>e+so(t).length,0)},get_tx_value:po,get_txhash:lo,get_txid:fo,get_txin_size:mo,get_txout_size:yo,get_txsize:go,get_vin_size:function(e){return eo(e).length},get_vout_info:function(e){return{type:co(e.script_pk),version:ho(e.script_pk)}},get_vout_size:function(e){return ro(e).length},get_vout_type:co,get_vout_version:ho,get_vsize:function(e){const t=m.bytes(e).length,n=t%4>0?1:0;return Math.floor(t/4)+n},is_return_script:uo,parse_tx:Ts,read_script:cs});function _o(e,t={}){const{sigflag:n=1,txindex:r}=t,i=Ts(e),s=!(128&~n),o=n%128;if(!ts.includes(o))throw new Error("Invalid hash type: "+String(n));const{version:a,vin:u,vout:c,locktime:d}=i,h=Is(i,t),{txid:f,vout:l,prevout:p,sequence:g}=h,{value:y}=p??{};if(void 0===y)throw new Error("Prevout value is empty!");let{pubkey:w,script:_}=t;if(void 0===_&&void 0!==w){const e=nn(w).hex;_=`76a914${String(e)}88ac`}if(void 0===_)throw new Error("No pubkey / script has been set!");if(Vs(_).includes("OP_CODESEPARATOR"))throw new Error("This library does not currently support the use of OP_CODESEPARATOR in segwit scripts.");const v=[Ys(a),vo(u,s),bo(u,o,s),Qs(f),Js(l),Ks(_),no(y),Xs(g),Eo(c,o,r),oo(d),m.num(n,4).reverse()];return sn(m.join(v))}function vo(e,t){if(!0===t)return m.num(0,32);const n=[];for(const{txid:t,vout:r}of e)n.push(Qs(t)),n.push(Js(r));return sn(m.join(n))}function bo(e,t,n){if(n||1!==t)return m.num(0,32);const r=[];for(const{sequence:t}of e)r.push(Xs(t));return sn(m.join(r))}function Eo(e,t,n){const r=[];if(1===t){for(const{value:t,script_pk:n}of e)r.push(no(t)),r.push(Ks(n));return sn(m.join(r))}if(3===t&&(b.ok(void 0!==n),n<e.length)){const{value:t,script_pk:i}=e[n];return r.push(no(t)),r.push(Ks(i)),sn(m.join(r))}return m.num(0,32)}function xo(e,t=192){return So(Ks(e),t)}function So(e,t=192){return on("TapLeaf",Oo(t),e)}function ko(e,t){return t<e&&([e,t]=[t,e]),on("TapBranch",e,t)}function Oo(e=192){return 254&e}function Ao(e,t=new Uint8Array){return b.size(e,32),on("TapTweak",e,t)}function Po(e,t={}){const{script:n,txindex:r,sigflag:i=0,extflag:s=0,key_version:o=0,separator_pos:a=4294967295}=t,u=Ts(e),{version:c,vin:d,vout:h,locktime:f}=u,l=Is(u,t),{txid:p,vout:g,sequence:y,witness:w=[]}=l;if(!ns.includes(i))throw new Error("Invalid hash type: "+String(i));if(s<0||s>127)throw new Error("Extention flag out of range: "+String(s));let{extension:_}=t;void 0!==n&&(_=xo(n).hex);const v=!(128&~i),E=function(e){if(void 0===e)return;if(e.length<2)return;const t=e.at(-1);if("string"==typeof t&&t.startsWith("50")){return rn(m.hex(t).prefix_varint("be"))}return}(w),x=2*(s+(void 0!==_?1:0))+(void 0!==E?1:0),S=[on("TapSighash"),m.num(0,1),m.num(i,1),Ys(c),oo(f)];if(!v){const e=d.map(e=>Bo(e));S.push(To(d),No(e),Uo(e),Io(d))}if(((3&i)<2||(3&i)>3)&&S.push($o(h)),S.push(m.num(x,1)),v){const{value:e,script_pk:t}=Bo(l);S.push(Qs(p),Js(g),no(e),Ks(t),Xs(y))}else b.ok("number"==typeof r),S.push(m.num(r,4).reverse());return void 0!==E&&S.push(E),3&~i||(b.ok("number"==typeof r),S.push(Co(h[r]))),void 0!==_&&S.push(m.bytes(_),m.num(o),m.num(a,4)),rn(m.join(S))}function To(e){const t=[];for(const{txid:n,vout:r}of e)t.push(Qs(n)),t.push(Js(r));return rn(m.join(t))}function Io(e){const t=[];for(const{sequence:n}of e)t.push(Xs(n));return rn(m.join(t))}function No(e){const t=[];for(const{value:n}of e)t.push(no(n));return rn(m.join(t))}function Uo(e){const t=[];for(const{script_pk:n}of e)t.push(Ks(n));return rn(m.join(t))}function $o(e){const t=[];for(const{value:n,script_pk:r}of e)t.push(no(n)),t.push(Ks(r));return rn(m.join(t))}function Co(e){return rn(no(e.value),Ks(e.script_pk))}function Bo(e){if(null===e.prevout)throw new Error("Prevout data missing for input: "+String(e.txid));return e.prevout}function Ro(e,t,n){return Lt(e,_o(Ts(t),n)).hex+Ns(n.sigflag??1)}function Lo(e,t,n){return zt(e,Po(Ts(t),n)).hex+Ns(n.sigflag??0)}const zo=5e8;var jo,Ho;function Do(e){switch(e.type){case"timelock":return b.ok(e.stamp>=zo,"Invalid timestamp"),e.stamp;case"heightlock":return b.ok(e.height>0,"height must be greater than 0"),b.ok(e.height<zo,"invalid block height"),e.height;default:throw new Error("Invalid locktime type")}}function Fo(e){return isNaN(e)||e<=0?null:e<zo?{type:"heightlock",height:e}:{type:"timelock",stamp:e}}function Vo(e,t=0){return`${e}i${t}`}function Zo(e){Wo(e);const[t,n]=e.split("i");return{txid:t,order:parseInt(n)}}function Ko(e){return null!==e.match(/^[a-f0-9]{64}i\d+$/)}function Wo(e){if(!Ko(e))throw new Error(`invalid inscription id: ${e}`)}function qo(e,t){return`${e}:${t}`}function Mo(e){Yo(e);const[t,n]=e.split(":");return{block_height:parseInt(t),block_index:parseInt(n)}}function Go(e){return null!==e.match(/^\d+:\d+$/)}function Yo(e){if(!Go(e))throw new Error(`invalid rune id: ${e}`)}function Qo(e,t){return`${e}:${t}`}function Jo(e){ea(e);const[t,n]=e.split(":");return{txid:t,vout:parseInt(n)}}function Xo(e){return null!==e.match(/^[a-f0-9]{64}:[0-9]+$/)}function ea(e){if(!Xo(e))throw new Error(`invalid outpoint: ${e}`)}!function(e){e.encode=Do,e.decode=Fo}(jo||(jo={})),function(e){e.outpoint={encode:Qo,decode:Jo,verify:Xo,assert:ea},e.record_id={encode:Vo,decode:Zo,verify:Ko,assert:Wo},e.rune_id={encode:qo,decode:Mo,verify:Go,assert:Yo}}(Ho||(Ho={}));const ta=BigInt(0),na=BigInt(1),ra=BigInt(26);var ia;function sa(e){const t=function(e){const t=Vs(e),n=t.findIndex(e=>"OP_0"===e);b.ok(-1!==n,"inscription envelope not found");const r=[];for(let e=n;e<t.length;e++){b.ok("OP_IF"===t[e+1],"OP_IF missing from envelope"),b.ok("6f7264"===t[e+2],"magic bytes missing from envelope");const n=t.findIndex(e=>"OP_ENDIF"===e);b.ok(-1!==n,"inscription envelope missing END_IF statement");const i=t.slice(e+3,n);r.push(i),e+=n}return r}(e);return t.map(ua)}function oa(e){return e.map(aa).join("")}function aa(e){let t=["OP_0","OP_IF","6f7264"];if("string"==typeof e.delegate){const n=ca(e.delegate);t.push("OP_11",n)}if("string"==typeof e.ref&&t.push("OP_WITHIN",e.ref),"string"==typeof e.parent){const n=ca(e.parent);t.push("OP_3",n)}if("number"==typeof e.opcode){const n=ha(e.opcode);t.push("OP_NOP",n)}if("number"==typeof e.pointer){const n=ha(e.pointer);t.push("OP_2",n)}if("string"==typeof e.rune){const n=function(e){const t=e.toUpperCase();let n=ta;for(const e of t)e>="A"&&e<="Z"&&(n=n*ra+BigInt(e.charCodeAt(0)-("A".charCodeAt(0)-1)));return n-=na,m.big(n).reverse().hex}(e.rune);t.push("OP_13",n)}if("string"==typeof e.mimetype){const n=function(e){return m.str(e).hex}(e.mimetype);t.push("OP_1",n)}if("string"==typeof e.content){const n=function(e){const t=m.is_hex(e)?m.hex(e):m.str(e),n=new y(t),r=[];for(;n.size>0;)if(n.size>520){const e=n.read(520);r.push(e.hex)}else{const e=n.read(n.size);r.push(e.hex)}return r}(e.content);t.push("OP_0",...n)}return t.push("OP_ENDIF"),zs(t)}function ua(e){const t={};for(let n=0;n<e.length;n++)switch(e[n]){case"OP_1":t.mimetype=la(e[n+1]),n+=1;break;case"OP_2":t.pointer=fa(e[n+1]),n+=1;break;case"OP_3":t.parent=da(e[n+1]),n+=1;break;case"OP_11":t.delegate=da(e[n+1]),n+=1;break;case"OP_13":t.rune=ga(e[n+1]),n+=1;break;case"OP_WITHIN":t.ref=e[n+1],n+=1;break;case"OP_NOP":t.opcode=fa(e[n+1]),n+=1;break;case"OP_0":return t.content=pa(e.slice(n+1)),t}return t}function ca(e){b.ok(e.includes("i"),"identifier must include an index");const t=e.split("i"),n=m.hex(t[0]),r=Number(t[1]),i=n.reverse().hex;return 0!==r?i+m.num(r).hex:i}function da(e){const t=m.hex(e),n=t.at(-1)??0;return t.slice(0,-1).reverse().hex+"i"+String(n)}function ha(e){return m.num(e).reverse().hex}function fa(e){return m.hex(e).reverse().num}function la(e){return m.hex(e).str}function pa(e,t="hex"){const n=m.join(e);return"hex"===t?n.hex:n.str}function ga(e){let t=m.hex(e).reverse().big;t+=na;let n="";for(;t>ta;){const e=t%ra;if(e===ta)n="Z"+n,t=t/ra-na;else{const r=Number(e)+"A".charCodeAt(0)-1;n=String.fromCharCode(r)+n,t/=ra}}return n}!function(e){e.encode=oa,e.decode=sa}(ia||(ia={}));const ma=4194304,ya=65535,wa=65535;var _a;function va(e){if("height"===e.mode){return(function(e){if(void 0===e||!Number.isInteger(e)||e<0||e>wa)throw new Error("Heightlock value must be an integer between 0 and 65535");return e}(e.height)&ya)>>>0}if("stamp"===e.mode){const t=function(e){if(void 0===e||!Number.isInteger(e))throw new Error("timestamp must be a number");const t=Math.floor(e/512);if(!Number.isInteger(t)||t<0||t>wa)throw new Error("timelock value must be an integer between 0 and 65535 (in 512-second increments)");return t}(e.stamp);return(ma|t&ya)>>>0}throw new Error("invalid timelock mode: "+e.mode)}function ba(e){const t=function(e){const t="string"==typeof e?parseInt(e,16):e;if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`invalid sequence value: ${t}`);return t}(e);if(2147483648&t)return null;const n=t&ya;if(t&ma){const e=512*n;if(e>4294967295)throw new Error("Decoded timestamp exceeds 32-bit limit");return{mode:"stamp",stamp:e}}if(n>wa)throw new Error("Decoded height exceeds maximum");return{mode:"height",height:n}}!function(e){e.encode=va,e.decode=ba}(_a||(_a={}));var Ea=Object.freeze({__proto__:null,get LocktimeUtil(){return jo},get RefEncoder(){return Ho},get ScribeEncoder(){return ia},get SequenceUtil(){return _a},decode_inscription:sa,decode_locktime:Fo,decode_sequence:ba,encode_inscription:oa,encode_locktime:Do,encode_sequence:va});class xa{constructor(e){this._txout=e}get data(){return{script_pk:this.script_pk,size:this.size,type:this.type,value:this.value,version:this.version}}get script_pk(){return{hex:this._txout.script_pk,asm:Vs(this._txout.script_pk)}}get size(){return yo(this._txout)}get type(){return co(this._txout.script_pk)}get value(){return this._txout.value}get version(){return ho(this._txout.script_pk)}toJSON(){return this.data}toString(){return JSON.stringify(this.data)}}function Sa(e){const t=e.map(e=>m.bytes(e)),n=function(e){let t=e.at(-1);return e.length>1&&t instanceof Uint8Array&&80===t[0]?new m(t).hex:null}(t);null!==n&&t.pop();const r=function(e){let t=e.at(-1);return e.length>1&&t instanceof Uint8Array&&t.length>32&&Xi.includes(254&t[0])?new m(t).hex:null}(t);null!==r&&t.pop();const i=function(e,t){let n=e.at(0),r=e.at(1),i=e.at(-1);return null!==t&&void 0!==i?"p2tr-ts":2===e.length&&void 0!==n&&void 0!==r&&n.length>=64&&33===r.length?"p2w-pkh":1===e.length&&void 0!==n&&64===n.length?"p2tr-pk":e.length>1&&void 0!==i&&Zs(i)?"p2w-sh":"unknown"}(t,r),s=function(e){return e.startsWith("p2tr")?1:e.startsWith("p2w")?0:null}(i),o=function(e,t){let n;switch(t){case"p2tr-ts":n=e.at(-1);case"p2w-sh":n=e.at(-1)}return void 0!==n?new m(n).hex:null}(t,i);null!==o&&t.pop();return{annex:n,cblock:r,params:t.map(e=>e.hex),script:o,type:i,version:s}}function ka(e){const t=e.map(e=>m.bytes(e)).reduce((e,t)=>e+t.length,0);return{total:t,vsize:Math.ceil(1+t/4)}}var Oa=Object.freeze({__proto__:null,get_witness_size:ka,parse_witness:Sa});class Aa{constructor(e){this._elems=e.map(e=>m.bytes(e)),this._data=Sa(this._elems),this._size=ka(this._elems)}get annex(){return this._data.annex}get cblock(){return this._data.cblock}get data(){return{annex:this.annex,cblock:this.cblock,params:this.params,script:this.script,size:this.size,stack:this.stack,type:this.type,version:this.version}}get params(){return this._data.params}get script(){return null===this._data.script?null:{hex:this._data.script,asm:Vs(this._data.script)}}get size(){return this._size}get stack(){return this._elems.map(e=>e.hex)}get type(){return this._data.type}get version(){return this._data.version}_update(){this._data=Sa(this._elems),this._size=ka(this._elems)}add(e){this._elems.push(m.bytes(e)),this._update()}insert(e,t){b.ok(e>=0&&e<=this._elems.length,"index out of bounds"),e===this._elems.length?this._elems.push(m.bytes(t)):this._elems.splice(e,0,m.bytes(t)),this._update()}remove(e){this._elems.splice(e,1),this._update()}toJSON(){return this.data}toString(){return JSON.stringify(this.data)}}class Pa{constructor(e){this._txin=e}get coinbase(){return this._txin.coinbase}get data(){return{coinbase:this.coinbase,prevout:this.prevout?.data??null,script_sig:this.script_sig,sequence:this.sequence,size:this.size,txid:this.txid,vout:this.vout,witness:this.witness?.data??null}}get has_prevout(){return null!==this._txin.prevout}get is_coinbase(){return null!==this._txin.coinbase}get prevout(){return this._txin.prevout?new xa(this._txin.prevout):null}get script_sig(){return null===this._txin.script_sig?null:{asm:Vs(this._txin.script_sig),hex:this._txin.script_sig}}get sequence(){return{hex:Xs(this._txin.sequence).hex,data:_a.decode(this._txin.sequence),value:this._txin.sequence}}get size(){return mo(this._txin)}get txid(){return this._txin.txid}get vout(){return this._txin.vout}get witness(){return this._txin.witness.length>0?new Aa(this._txin.witness):null}toJSON(){return this.data}toString(){return JSON.stringify(this.data)}}const Ta={base58:/^[13mn2][a-km-zA-HJ-NP-Z1-9]{25,34}$/,bech32:/^(bc|tb|bcrt)1q[ac-hj-np-z02-9]{6,87}$/,bech32m:/^(bc|tb|bcrt)1p[ac-hj-np-z02-9]{6,87}$/},Ia=0,Na=1;function Ua(e){const t=function(e){for(const[t,n]of Object.entries(Ta))if(n.test(e))return t;return null}(e);if(null===t)throw new Error("unrecognized address format: "+t);if("base58"===t)return function(e){const t=Zi.decode(e),n=t.slice(1),r=t[0];return{data:n,format:"base58",version:r}}(e);if("bech32"===t)return function(e){const{prefix:t,words:n}=qi.decode(e),[r,...i]=n;b.ok(r===Ia,"bech32 version mismatch");return{data:qi.to_bytes(i),format:"bech32",prefix:t,version:r}}(e);if("bech32m"===t)return function(e){const{prefix:t,words:n}=Mi.decode(e),[r,...i]=n;b.ok(r===Na,"bech32m version mismatch");return{data:Mi.to_bytes(i),format:"bech32m",prefix:t,version:r}}(e);throw new Error("unable to find a matching address configuration")}function $a(e){if("base58"===e.format)return function(e){b.ok("base58"===e.format,"encoding mismatch"),b.exists(e.version,"must specify a version");const t=m.join([e.version,e.data]);return Zi.encode(t)}(e);if("bech32"===e.format)return function(e){b.ok("bech32"===e.format,"encoding mismatch"),b.exists(e.prefix,"prefix is required");const t=m.bytes(e.data),n=qi.to_words(t);return qi.encode(e.prefix,[Ia,...n])}(e);if("bech32m"===e.format)return function(e){b.ok("bech32m"===e.format,"encoding mismatch"),b.exists(e.prefix,"prefix is required");const t=m.bytes(e.data),n=Mi.to_words(t);return Mi.encode(e.prefix,[Na,...n])}(e);throw new Error("unrecognized encoding format: "+e.format)}const Ca=[["1","p2pkh","main",20,"base58",0],["3","p2sh","main",20,"base58",5],["m","p2pkh","testnet",20,"base58",111],["n","p2pkh","testnet",20,"base58",111],["2","p2sh","testnet",20,"base58",196],["m","p2pkh","regtest",20,"base58",111],["n","p2pkh","regtest",20,"base58",111],["2","p2sh","regtest",20,"base58",196],["bc","p2w-pkh","main",20,"bech32",0],["tb","p2w-pkh","testnet",20,"bech32",0],["bcrt","p2w-pkh","regtest",20,"bech32",0],["bc","p2w-sh","main",32,"bech32",0],["tb","p2w-sh","testnet",32,"bech32",0],["bcrt","p2w-sh","regtest",32,"bech32",0],["bc","p2tr","main",32,"bech32m",1],["tb","p2tr","testnet",32,"bech32m",1],["bcrt","p2tr","regtest",32,"bech32m",1]];function Ba(e,t){for(const[n,r,i,s,o,a]of Ca)if(r===t&&i===e)return{type:r,prefix:n,network:i,size:s,format:o,version:a};return null}function Ra(e){const t=function(e){const t=Ua(e);for(const[n,r,i,s,o,a]of Ca){if(o!==t.format)continue;if(s!==t.data.length)continue;if(a!==t.version)continue;if(t.prefix){if(n!==t.prefix)continue}else if(!e.startsWith(n))continue;const u=m.uint(t.data).hex;return{data:t.data,hex:u,type:r,prefix:n,network:i,size:s,format:o,version:a}}throw new Error("address configuration is invalid")}(e),n=function(e,t){switch(t){case"p2pkh":return function(e){return{script_hex:"76a914"+e+"88ac",script_asm:["OP_DUP","OP_HASH160",e,"OP_EQUALVERIFY","OP_CHECKSIG"]}}(e);case"p2sh":return function(e){return{script_hex:"a914"+e+"87",script_asm:["OP_HASH160",e,"OP_EQUAL"]}}(e);case"p2w-pkh":return function(e){return{script_hex:"0014"+e,script_asm:["OP_0",e]}}(e);case"p2w-sh":return function(e){return{script_hex:"0020"+e,script_asm:["OP_0",e]}}(e);case"p2tr":return function(e){return{script_hex:"5120"+e,script_asm:["OP_1",e]}}(e);default:throw new Error("unrecognized script type: "+t)}}(t.hex,t.type);return{...t,...n}}const La="p2pkh";var za;function ja(e,t="main"){return Ha(nn(m.bytes(e)),t)}function Ha(e,t="main"){const n=m.bytes(e),r=Ba(t,La);return b.exists(r,`unrecognized address config: ${La} on ${t}`),b.size(n,r.size,`invalid payload size: ${n.length} !== ${r.size}`),$a({data:n,format:"base58",version:r.version})}function Da(e){const t=Ra(e);return b.ok("p2pkh"===t.type,`address type mismatch: ${t.type} !== ${La}`),t}!function(e){e.create=ja,e.encode=Ha,e.decode=Da}(za||(za={}));const Fa="p2sh";var Va;function Za(e,t="main"){return Ka(nn(m.bytes(e)),t)}function Ka(e,t="main"){const n=m.bytes(e),r=Ba(t,Fa);return b.exists(r,`unrecognized address config: ${Fa} on ${t}`),b.size(n,r.size,`invalid payload size: ${n.length} !== ${r.size}`),$a({data:n,format:"base58",version:r.version})}function Wa(e){const t=Ra(e);return b.ok("p2sh"===t.type,`address type mismatch: ${t.type} !== ${Fa}`),t}!function(e){e.create=Za,e.encode=Ka,e.decode=Wa}(Va||(Va={}));const qa="p2w-pkh";var Ma;function Ga(e,t="main"){const n=m.bytes(e);b.size(n,33,`invalid payload size: ${n.length} !== 33`);return Ya(nn(n),t)}function Ya(e,t="main"){const n=m.bytes(e),r=Ba(t,qa);return b.exists(r,`unrecognized address config: ${qa} on ${t}`),b.size(n,r.size,`invalid payload size: ${n.length} !== ${r.size}`),$a({data:n,format:"bech32",prefix:r.prefix})}function Qa(e){const t=Ra(e);return b.ok("p2w-pkh"===t.type,`address type mismatch: ${t.type} !== ${qa}`),t}!function(e){e.create=Ga,e.encode=Ya,e.decode=Qa}(Ma||(Ma={}));const Ja="p2w-sh";var Xa;function eu(e,t="main"){return tu(rn(m.bytes(e)),t)}function tu(e,t="main"){const n=m.bytes(e),r=Ba(t,Ja);return b.exists(r,`unrecognized address config: ${Ja} on ${t}`),b.size(n,r.size,`invalid payload size: ${n.length} !== ${r.size}`),$a({data:n,format:"bech32",prefix:r.prefix})}function nu(e){const t=Ra(e);return b.ok("p2w-sh"===t.type,`address type mismatch: ${t.type} !== ${Ja}`),t}!function(e){e.create=eu,e.encode=tu,e.decode=nu}(Xa||(Xa={}));const ru="p2tr";var iu,su;function ou(e,t="main"){const n=m.bytes(e),r=Ba(t,ru);return b.exists(r,`unrecognized address config: ${ru} on ${t}`),b.size(n,r.size,`invalid payload size: ${n.length} !== ${r.size}`),$a({data:n,format:"bech32m",prefix:r.prefix})}function au(e){const t=Ra(e);return b.ok("p2tr"===t.type,`address type mismatch: ${t.type} !== ${ru}`),t}!function(e){e.encode=ou,e.decode=au}(iu||(iu={})),function(e){e.P2PKH=za,e.P2SH=Va,e.P2WPKH=Ma,e.P2WSH=Xa,e.P2TR=iu,e.parse=Ra}(su||(su={}));var uu=Object.freeze({__proto__:null,get AddressTool(){return su},get P2PKH(){return za},get P2SH(){return Va},get P2TR(){return iu},get P2WPKH(){return Ma},get P2WSH(){return Xa},parse_address:Ra});const cu=new Uint8Array,du=new Uint8Array([0]);function hu(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function fu(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}const lu=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);function pu(e){return"[object Object]"===Object.prototype.toString.call(e)}function gu(e){return Number.isSafeInteger(e)}const mu=hu,yu=fu,wu=function(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];if(!fu(r))throw new Error("Uint8Array expected");t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const i=e[t];n.set(i,r),r+=i.length}return n},_u=e=>{if(null!==e&&"string"!=typeof e&&!Tu(e)&&!fu(e)&&!gu(e))throw new Error(`lengthCoder: expected null | number | Uint8Array | CoderType, got ${e} (${typeof e})`);return{encodeStream(t,n){if(null===e)return;if(Tu(e))return e.encodeStream(t,n);let r;if("number"==typeof e?r=e:"string"==typeof e&&(r=bu.resolve(t.stack,e)),"bigint"==typeof r&&(r=Number(r)),void 0===r||r!==n)throw t.err(`Wrong length: ${r} len=${e} exp=${n} (${typeof n})`)},decodeStream(t){let n;if(Tu(e)?n=Number(e.decodeStream(t)):"number"==typeof e?n=e:"string"==typeof e&&(n=bu.resolve(t.stack,e)),"bigint"==typeof n&&(n=Number(n)),"number"!=typeof n)throw t.err(`Wrong length: ${n}`);return n}}},vu={BITS:32,FULL_MASK:-1>>>0,len:e=>Math.ceil(e/32),create:e=>new Uint32Array(vu.len(e)),clean:e=>e.fill(0),debug:e=>Array.from(e).map(e=>(e>>>0).toString(2).padStart(32,"0")),checkLen:(e,t)=>{if(vu.len(t)!==e.length)throw new Error(`wrong length=${e.length}. Expected: ${vu.len(t)}`)},chunkLen:(e,t,n)=>{if(t<0)throw new Error(`wrong pos=${t}`);if(t+n>e)throw new Error(`wrong range=${t}/${n} of ${e}`)},set:(e,t,n,r=!0)=>!(!r&&0!==(e[t]&n))&&(e[t]|=n,!0),pos:(e,t)=>({chunk:Math.floor((e+t)/32),mask:1<<32-(e+t)%32-1}),indices:(e,t,n=!1)=>{vu.checkLen(e,t);const{FULL_MASK:r,BITS:i}=vu,s=i-t%i,o=s?r>>>s<<s:r,a=[];for(let t=0;t<e.length;t++){let r=e[t];if(n&&(r=~r),t===e.length-1&&(r&=o),0!==r)for(let e=0;e<i;e++){r&1<<i-e-1&&a.push(t*i+e)}}return a},range:e=>{const t=[];let n;for(const r of e)void 0===n||r!==n.pos+n.length?t.push(n={pos:r,length:1}):n.length+=1;return t},rangeDebug:(e,t,n=!1)=>`[${vu.range(vu.indices(e,t,n)).map(e=>`(${e.pos}/${e.length})`).join(", ")}]`,setRange:(e,t,n,r,i=!0)=>{vu.chunkLen(t,n,r);const{FULL_MASK:s,BITS:o}=vu,a=n%o?Math.floor(n/o):void 0,u=n+r,c=u%o?Math.floor(u/o):void 0;if(void 0!==a&&a===c)return vu.set(e,a,s>>>o-r<<o-r-n,i);if(void 0!==a&&!vu.set(e,a,s>>>n%o,i))return!1;const d=void 0!==c?c:u/o;for(let t=void 0!==a?a+1:n/o;t<d;t++)if(!vu.set(e,t,s,i))return!1;return!(void 0!==c&&a!==c&&!vu.set(e,c,s<<o-u%o,i))}},bu={pushObj:(e,t,n)=>{const r={obj:t};e.push(r),n((e,t)=>{r.field=e,t(),r.field=void 0}),e.pop()},path:e=>{const t=[];for(const n of e)void 0!==n.field&&t.push(n.field);return t.join("/")},err:(e,t,n)=>{const r=new Error(`${e}(${bu.path(t)}): ${"string"==typeof n?n:n.message}`);return n instanceof Error&&n.stack&&(r.stack=n.stack),r},resolve:(e,t)=>{const n=t.split("/"),r=e.map(e=>e.obj);let i=0;for(;i<n.length&&".."===n[i];i++)r.pop();let s=r.pop();for(;i<n.length;i++){if(!s||void 0===s[n[i]])return;s=s[n[i]]}return s}};class Eu{constructor(e,t={},n=[],r=void 0,i=0){this.pos=0,this.bitBuf=0,this.bitPos=0,this.data=e,this.opts=t,this.stack=n,this.parent=r,this.parentOffset=i,this.view=lu(e)}_enablePointers(){if(this.parent)return this.parent._enablePointers();this.bs||(this.bs=vu.create(this.data.length),vu.setRange(this.bs,this.data.length,0,this.pos,this.opts.allowMultipleReads))}markBytesBS(e,t){return this.parent?this.parent.markBytesBS(this.parentOffset+e,t):!t||(!this.bs||vu.setRange(this.bs,this.data.length,e,t,!1))}markBytes(e){const t=this.pos;this.pos+=e;const n=this.markBytesBS(t,e);if(!this.opts.allowMultipleReads&&!n)throw this.err(`multiple read pos=${this.pos} len=${e}`);return n}pushObj(e,t){return bu.pushObj(this.stack,e,t)}readView(e,t){if(!Number.isFinite(e))throw this.err(`readView: wrong length=${e}`);if(this.pos+e>this.data.length)throw this.err("readView: Unexpected end of buffer");const n=t(this.view,this.pos);return this.markBytes(e),n}absBytes(e){if(e>this.data.length)throw new Error("Unexpected end of buffer");return this.data.subarray(e)}finish(){if(!this.opts.allowUnreadBytes){if(this.bitPos)throw this.err(`${this.bitPos} bits left after unpack: ${Fi.encode(this.data.slice(this.pos))}`);if(this.bs&&!this.parent){const e=vu.indices(this.bs,this.data.length,!0);if(e.length){const t=vu.range(e).map(({pos:e,length:t})=>`(${e}/${t})[${Fi.encode(this.data.subarray(e,e+t))}]`).join(", ");throw this.err(`unread byte ranges: ${t} (total=${this.data.length})`)}return}if(!this.isEnd())throw this.err(`${this.leftBytes} bytes ${this.bitPos} bits left after unpack: ${Fi.encode(this.data.slice(this.pos))}`)}}err(e){return bu.err("Reader",this.stack,e)}offsetReader(e){if(e>this.data.length)throw this.err("offsetReader: Unexpected end of buffer");return new Eu(this.absBytes(e),this.opts,this.stack,this,e)}bytes(e,t=!1){if(this.bitPos)throw this.err("readBytes: bitPos not empty");if(!Number.isFinite(e))throw this.err(`readBytes: wrong length=${e}`);if(this.pos+e>this.data.length)throw this.err("readBytes: Unexpected end of buffer");const n=this.data.subarray(this.pos,this.pos+e);return t||this.markBytes(e),n}byte(e=!1){if(this.bitPos)throw this.err("readByte: bitPos not empty");if(this.pos+1>this.data.length)throw this.err("readBytes: Unexpected end of buffer");const t=this.data[this.pos];return e||this.markBytes(1),t}get leftBytes(){return this.data.length-this.pos}get totalBytes(){return this.data.length}isEnd(){return this.pos>=this.data.length&&!this.bitPos}bits(e){if(e>32)throw this.err("BitReader: cannot read more than 32 bits in single call");let t=0;for(;e;){this.bitPos||(this.bitBuf=this.byte(),this.bitPos=8);const n=Math.min(e,this.bitPos);this.bitPos-=n,t=t<<n|this.bitBuf>>this.bitPos&2**n-1,this.bitBuf&=2**this.bitPos-1,e-=n}return t>>>0}find(e,t=this.pos){if(!fu(e))throw this.err(`find: needle is not bytes! ${e}`);if(this.bitPos)throw this.err("findByte: bitPos not empty");if(!e.length)throw this.err("find: needle is empty");for(let n=t;-1!==(n=this.data.indexOf(e[0],n));n++){if(-1===n)return;if(this.data.length-n<e.length)return;if(hu(e,this.data.subarray(n,n+e.length)))return n}}}class xu{constructor(e=[]){this.pos=0,this.buffers=[],this.ptrs=[],this.bitBuf=0,this.bitPos=0,this.viewBuf=new Uint8Array(8),this.finished=!1,this.stack=e,this.view=lu(this.viewBuf)}pushObj(e,t){return bu.pushObj(this.stack,e,t)}writeView(e,t){if(this.finished)throw this.err("buffer: finished");if(!gu(e)||e>8)throw new Error(`wrong writeView length=${e}`);t(this.view),this.bytes(this.viewBuf.slice(0,e)),this.viewBuf.fill(0)}err(e){if(this.finished)throw this.err("buffer: finished");return bu.err("Reader",this.stack,e)}bytes(e){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeBytes: ends with non-empty bit buffer");this.buffers.push(e),this.pos+=e.length}byte(e){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeByte: ends with non-empty bit buffer");this.buffers.push(new Uint8Array([e])),this.pos++}finish(e=!0){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("buffer: ends with non-empty bit buffer");const t=this.buffers.concat(this.ptrs.map(e=>e.buffer)),n=t.map(e=>e.length).reduce((e,t)=>e+t,0),r=new Uint8Array(n);for(let e=0,n=0;e<t.length;e++){const i=t[e];r.set(i,n),n+=i.length}for(let e=this.pos,t=0;t<this.ptrs.length;t++){const n=this.ptrs[t];r.set(n.ptr.encode(e),n.pos),e+=n.buffer.length}if(e){this.buffers=[];for(const e of this.ptrs)e.buffer.fill(0);this.ptrs=[],this.finished=!0,this.bitBuf=0}return r}bits(e,t){if(t>32)throw this.err("writeBits: cannot write more than 32 bits in single call");if(e>=2**t)throw this.err(`writeBits: value (${e}) >= 2**bits (${t})`);for(;t;){const n=Math.min(t,8-this.bitPos);this.bitBuf=this.bitBuf<<n|e>>t-n,this.bitPos+=n,e&=2**(t-=n)-1,8===this.bitPos&&(this.bitPos=0,this.buffers.push(new Uint8Array([this.bitBuf])),this.pos++)}}}const Su=e=>Uint8Array.from(e).reverse();function ku(e){return{encodeStream:e.encodeStream,decodeStream:e.decodeStream,size:e.size,encode:t=>{const n=new xu;return e.encodeStream(n,t),n.finish()},decode:(t,n={})=>{const r=new Eu(t,n),i=e.decodeStream(r);return r.finish(),i}}}function Ou(e,t){if(!Tu(e))throw new Error(`validate: invalid inner value ${e}`);if("function"!=typeof t)throw new Error("validate: fn should be function");return ku({size:e.size,encodeStream:(n,r)=>{let i;try{i=t(r)}catch(e){throw n.err(e)}e.encodeStream(n,i)},decodeStream:n=>{const r=e.decodeStream(n);try{return t(r)}catch(e){throw n.err(e)}}})}const Au=e=>{const t=ku(e);return e.validate?Ou(t,e.validate):t},Pu=e=>pu(e)&&"function"==typeof e.decode&&"function"==typeof e.encode;function Tu(e){return pu(e)&&Pu(e)&&"function"==typeof e.encodeStream&&"function"==typeof e.decodeStream&&(void 0===e.size||gu(e.size))}const Iu=e=>{if(!Pu(e))throw new Error("BaseCoder expected");return{encode:e.decode,decode:e.encode}},Nu={dict:function(){return{encode:e=>{if(!Array.isArray(e))throw new Error("array expected");const t={};for(const n of e){if(!Array.isArray(n)||2!==n.length)throw new Error("array of two elements expected");const e=n[0],r=n[1];if(void 0!==t[e])throw new Error(`key(${e}) appears twice in struct`);t[e]=r}return t},decode:e=>{if(!pu(e))throw new Error(`expected plain object, got ${e}`);return Object.entries(e)}}},numberBigint:{encode:e=>{if("bigint"!=typeof e)throw new Error("expected bigint, got "+typeof e);if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`element bigger than MAX_SAFE_INTEGER=${e}`);return Number(e)},decode:e=>{if(!gu(e))throw new Error("element is not a safe integer");return BigInt(e)}},tsEnum:function(e){if(!pu(e))throw new Error("plain object expected");return{encode:t=>{if(!gu(t)||!(t in e))throw new Error(`wrong value ${t}`);return e[t]},decode:t=>{if("string"!=typeof t)throw new Error("wrong value "+typeof t);return e[t]}}},decimal:function(e,t=!1){if(!gu(e))throw new Error(`decimal/precision: wrong value ${e}`);if("boolean"!=typeof t)throw new Error("decimal/round: expected boolean, got "+typeof t);const n=10n**BigInt(e);return{encode:t=>{if("bigint"!=typeof t)throw new Error("expected bigint, got "+typeof t);let n=(t<0n?-t:t).toString(10),r=n.length-e;r<0&&(n=n.padStart(n.length-r,"0"),r=0);let i=n.length-1;for(;i>=r&&"0"===n[i];i--);let s=n.slice(0,r),o=n.slice(r,i+1);return s||(s="0"),t<0n&&(s="-"+s),o?`${s}.${o}`:s},decode:r=>{if("string"!=typeof r)throw new Error("expected string, got "+typeof r);if("-0"===r)throw new Error("negative zero is not allowed");let i=!1;if(r.startsWith("-")&&(i=!0,r=r.slice(1)),!/^(0|[1-9]\d*)(\.\d+)?$/.test(r))throw new Error(`wrong string value=${r}`);let s=r.indexOf(".");s=-1===s?r.length:s;const o=r.slice(0,s),a=r.slice(s+1).replace(/0+$/,""),u=BigInt(o)*n;if(!t&&a.length>e)throw new Error(`fractional part cannot be represented with this precision (num=${r}, prec=${e})`);const c=Math.min(a.length,e),d=u+BigInt(a.slice(0,c))*10n**BigInt(e-c);return i?-d:d}}},match:function(e){if(!Array.isArray(e))throw new Error("expected array, got "+typeof e);for(const t of e)if(!Pu(t))throw new Error(`wrong base coder ${t}`);return{encode:t=>{for(const n of e){const e=n.encode(t);if(void 0!==e)return e}throw new Error(`match/encode: cannot find match in ${t}`)},decode:t=>{for(const n of e){const e=n.decode(t);if(void 0!==e)return e}throw new Error(`match/decode: cannot find match in ${t}`)}}},reverse:Iu},Uu=(e,t=!1,n=!1,r=!0)=>{if(!gu(e))throw new Error(`bigint/size: wrong value ${e}`);if("boolean"!=typeof t)throw new Error("bigint/le: expected boolean, got "+typeof t);if("boolean"!=typeof n)throw new Error("bigint/signed: expected boolean, got "+typeof n);if("boolean"!=typeof r)throw new Error("bigint/sized: expected boolean, got "+typeof r);const i=BigInt(e),s=2n**(8n*i-1n);return Au({size:r?e:void 0,encodeStream:(i,o)=>{n&&o<0&&(o|=s);const a=[];for(let t=0;t<e;t++)a.push(Number(255n&o)),o>>=8n;let u=new Uint8Array(a).reverse();if(!r){let e=0;for(e=0;e<u.length&&0===u[e];e++);u=u.subarray(e)}i.bytes(t?u.reverse():u)},decodeStream:i=>{const o=i.bytes(r?e:Math.min(e,i.leftBytes)),a=t?o:Su(o);let u=0n;for(let e=0;e<a.length;e++)u|=BigInt(a[e])<<8n*BigInt(e);return n&&u&s&&(u=(u^s)-s),u},validate:e=>{if("bigint"!=typeof e)throw new Error(`bigint: invalid value: ${e}`);return function(e,t,n){if(n){const n=2n**(t-1n);if(e<-n||e>=n)throw new Error(`value out of signed bounds. Expected ${-n} <= ${e} < ${n}`)}else if(0n>e||e>=2n**t)throw new Error(`value out of unsigned bounds. Expected 0 <= ${e} < ${2n**t}`)}(e,8n*i,!!n),e}})},$u=Uu(32,!1),Cu=Uu(8,!0),Bu=Uu(8,!0,!0),Ru=(e,t,n)=>{const r=8*e,i=2**(r-1),s=2**r;return((e,t)=>Au({size:e,encodeStream:(n,r)=>n.writeView(e,e=>t.write(e,r)),decodeStream:n=>n.readView(e,t.read),validate:e=>{if("number"!=typeof e)throw new Error("viewCoder: expected number, got "+typeof e);return t.validate&&t.validate(e),e}}))(e,{write:n.write,read:n.read,validate:t?e=>{if(!gu(e))throw new Error(`sintView: value is not safe integer: ${e}`);if(e<-i||e>=i)throw new Error(`sintView: value out of bounds. Expected ${-i} <= ${e} < ${i}`)}:e=>{if(!gu(e))throw new Error(`uintView: value is not safe integer: ${e}`);if(0>e||e>=s)throw new Error(`uintView: value out of bounds. Expected 0 <= ${e} < ${s}`)}})},Lu=Ru(4,!1,{read:(e,t)=>e.getUint32(t,!0),write:(e,t)=>e.setUint32(0,t,!0)}),zu=Ru(4,!1,{read:(e,t)=>e.getUint32(t,!1),write:(e,t)=>e.setUint32(0,t,!1)}),ju=Ru(4,!0,{read:(e,t)=>e.getInt32(t,!0),write:(e,t)=>e.setInt32(0,t,!0)}),Hu=Ru(2,!1,{read:(e,t)=>e.getUint16(t,!0),write:(e,t)=>e.setUint16(0,t,!0)}),Du=Ru(1,!1,{read:(e,t)=>e.getUint8(t),write:(e,t)=>e.setUint8(0,t)}),Fu=(e,t=!1)=>{if("boolean"!=typeof t)throw new Error("bytes/le: expected boolean, got "+typeof t);const n=_u(e),r=fu(e);return Au({size:"number"==typeof e?e:void 0,encodeStream:(i,s)=>{r||n.encodeStream(i,s.length),i.bytes(t?Su(s):s),r&&i.bytes(e)},decodeStream:i=>{let s;if(r){const t=i.find(e);if(!t)throw i.err("bytes: cannot find terminator");s=i.bytes(t-i.pos),i.bytes(e.length)}else s=i.bytes(null===e?i.leftBytes:n.decodeStream(i));return t?Su(s):s},validate:e=>{if(!fu(e))throw new Error(`bytes: invalid value ${e}`);return e}})};const Vu=(e,t=!1)=>Ou(Zu(Fu(e,t),Di),e=>{if("string"!=typeof e)throw new Error("expected string, got "+typeof e);return e});function Zu(e,t){if(!Tu(e))throw new Error(`apply: invalid inner value ${e}`);if(!Pu(t))throw new Error(`apply: invalid base value ${e}`);return Au({size:e.size,encodeStream:(n,r)=>{let i;try{i=t.decode(r)}catch(e){throw n.err(""+e)}return e.encodeStream(n,i)},decodeStream:n=>{const r=e.decodeStream(n);try{return t.encode(r)}catch(e){throw n.err(""+e)}}})}function Ku(e,t,n=!0){if(!Tu(e))throw new Error(`magic: invalid inner value ${e}`);if("boolean"!=typeof n)throw new Error("magic: expected boolean, got "+typeof n);return Au({size:e.size,encodeStream:(n,r)=>e.encodeStream(n,t),decodeStream:r=>{const i=e.decodeStream(r);if(n&&"object"!=typeof i&&i!==t||fu(t)&&!hu(t,i))throw r.err(`magic: invalid value: ${i} !== ${t}`)},validate:e=>{if(void 0!==e)throw new Error("magic: wrong value="+typeof e);return e}})}function Wu(e){let t=0;for(const n of e){if(void 0===n.size)return;if(!gu(n.size))throw new Error(`sizeof: wrong element size=${t}`);t+=n.size}return t}function qu(e){if(!pu(e))throw new Error(`struct: expected plain object, got ${e}`);for(const t in e)if(!Tu(e[t]))throw new Error(`struct: field ${t} is not CoderType`);return Au({size:Wu(Object.values(e)),encodeStream:(t,n)=>{t.pushObj(n,r=>{for(const i in e)r(i,()=>e[i].encodeStream(t,n[i]))})},decodeStream:t=>{const n={};return t.pushObj(n,r=>{for(const i in e)r(i,()=>n[i]=e[i].decodeStream(t))}),n},validate:e=>{if("object"!=typeof e||null===e)throw new Error(`struct: invalid value ${e}`);return e}})}function Mu(e,t){if(!Tu(t))throw new Error(`array: invalid inner value ${t}`);const n=_u("string"==typeof e?`../${e}`:e);return Au({size:"number"==typeof e&&t.size?e*t.size:void 0,encodeStream:(r,i)=>{const s=r;s.pushObj(i,o=>{fu(e)||n.encodeStream(r,i.length);for(let n=0;n<i.length;n++)o(`${n}`,()=>{const o=i[n],a=r.pos;if(t.encodeStream(r,o),fu(e)){if(e.length>s.pos-a)return;const t=s.finish(!1).subarray(a,s.pos);if(hu(t.subarray(0,e.length),e))throw s.err(`array: inner element encoding same as separator. elm=${o} data=${t}`)}})}),fu(e)&&r.bytes(e)},decodeStream:r=>{const i=[];return r.pushObj(i,s=>{if(null===e)for(let e=0;!r.isEnd()&&(s(`${e}`,()=>i.push(t.decodeStream(r))),!(t.size&&r.leftBytes<t.size));e++);else if(fu(e))for(let n=0;;n++){if(hu(r.bytes(e.length,!0),e)){r.bytes(e.length);break}s(`${n}`,()=>i.push(t.decodeStream(r)))}else{let e;s("arrayLen",()=>e=n.decodeStream(r));for(let n=0;n<e;n++)s(`${n}`,()=>i.push(t.decodeStream(r)))}}),i},validate:e=>{if(!Array.isArray(e))throw new Error(`array: invalid value ${e}`);return e}})}const Gu=yt.ProjectivePoint,Yu=yt.CURVE.n,Qu=yu,Ju=wu,Xu=mu,ec=e=>tn(ee(e)),tc=(...e)=>ee(ee(Ju(...e))),nc=$t.getPublicKey,rc=yt.getPublicKey,ic=e=>e.r<Yu/2n;const sc=$t.sign,oc=$t.utils.taggedHash;var ac;function uc(e,t){const n=e.length;if(t===ac.ecdsa){if(32===n)throw new Error("Expected non-Schnorr key");return Gu.fromHex(e),e}if(t===ac.schnorr){if(32!==n)throw new Error("Expected 32-byte Schnorr key");return $t.utils.lift_x($t.utils.bytesToNumberBE(e)),e}throw new Error("Unknown key type")}function cc(e,t){const n=$t.utils,r=n.taggedHash("TapTweak",e,t),i=n.bytesToNumberBE(r);if(i>=Yu)throw new Error("tweak higher than curve order");return i}!function(e){e[e.ecdsa=0]="ecdsa",e[e.schnorr=1]="schnorr"}(ac||(ac={})),ee(Gu.BASE.toRawBytes(!1));const dc={bech32:"bc",pubKeyHash:0,scriptHash:5,wif:128};function hc(e,t){if(!Qu(e)||!Qu(t))throw new Error(`cmp: wrong type a=${typeof e} b=${typeof t}`);const n=Math.min(e.length,t.length);for(let r=0;r<n;r++)if(e[r]!=t[r])return Math.sign(e[r]-t[r]);return Math.sign(e.length-t.length)}var fc;function lc(e=6,t=!1){return Au({encodeStream:(e,t)=>{if(0n===t)return;const n=t<0,r=BigInt(t),i=[];for(let e=n?-r:r;e;e>>=8n)i.push(Number(0xffn&e));i[i.length-1]>=128?i.push(n?128:0):n&&(i[i.length-1]|=128),e.bytes(new Uint8Array(i))},decodeStream:n=>{const r=n.leftBytes;if(r>e)throw new Error(`ScriptNum: number (${r}) bigger than limit=${e}`);if(0===r)return 0n;if(t){const e=n.bytes(r,!0);if(!(127&e[e.length-1]||!(r<=1)&&128&e[e.length-2]))throw new Error("Non-minimally encoded ScriptNum")}let i=0,s=0n;for(let e=0;e<r;++e)i=n.byte(),s|=BigInt(i)<<8n*BigInt(e);return i>=128&&(s&=2n**BigInt(8*r)-1n>>1n,s=-s),s}})}!function(e){e[e.OP_0=0]="OP_0",e[e.PUSHDATA1=76]="PUSHDATA1",e[e.PUSHDATA2=77]="PUSHDATA2",e[e.PUSHDATA4=78]="PUSHDATA4",e[e["1NEGATE"]=79]="1NEGATE",e[e.RESERVED=80]="RESERVED",e[e.OP_1=81]="OP_1",e[e.OP_2=82]="OP_2",e[e.OP_3=83]="OP_3",e[e.OP_4=84]="OP_4",e[e.OP_5=85]="OP_5",e[e.OP_6=86]="OP_6",e[e.OP_7=87]="OP_7",e[e.OP_8=88]="OP_8",e[e.OP_9=89]="OP_9",e[e.OP_10=90]="OP_10",e[e.OP_11=91]="OP_11",e[e.OP_12=92]="OP_12",e[e.OP_13=93]="OP_13",e[e.OP_14=94]="OP_14",e[e.OP_15=95]="OP_15",e[e.OP_16=96]="OP_16",e[e.NOP=97]="NOP",e[e.VER=98]="VER",e[e.IF=99]="IF",e[e.NOTIF=100]="NOTIF",e[e.VERIF=101]="VERIF",e[e.VERNOTIF=102]="VERNOTIF",e[e.ELSE=103]="ELSE",e[e.ENDIF=104]="ENDIF",e[e.VERIFY=105]="VERIFY",e[e.RETURN=106]="RETURN",e[e.TOALTSTACK=107]="TOALTSTACK",e[e.FROMALTSTACK=108]="FROMALTSTACK",e[e["2DROP"]=109]="2DROP",e[e["2DUP"]=110]="2DUP",e[e["3DUP"]=111]="3DUP",e[e["2OVER"]=112]="2OVER",e[e["2ROT"]=113]="2ROT",e[e["2SWAP"]=114]="2SWAP",e[e.IFDUP=115]="IFDUP",e[e.DEPTH=116]="DEPTH",e[e.DROP=117]="DROP",e[e.DUP=118]="DUP",e[e.NIP=119]="NIP",e[e.OVER=120]="OVER",e[e.PICK=121]="PICK",e[e.ROLL=122]="ROLL",e[e.ROT=123]="ROT",e[e.SWAP=124]="SWAP",e[e.TUCK=125]="TUCK",e[e.CAT=126]="CAT",e[e.SUBSTR=127]="SUBSTR",e[e.LEFT=128]="LEFT",e[e.RIGHT=129]="RIGHT",e[e.SIZE=130]="SIZE",e[e.INVERT=131]="INVERT",e[e.AND=132]="AND",e[e.OR=133]="OR",e[e.XOR=134]="XOR",e[e.EQUAL=135]="EQUAL",e[e.EQUALVERIFY=136]="EQUALVERIFY",e[e.RESERVED1=137]="RESERVED1",e[e.RESERVED2=138]="RESERVED2",e[e["1ADD"]=139]="1ADD",e[e["1SUB"]=140]="1SUB",e[e["2MUL"]=141]="2MUL",e[e["2DIV"]=142]="2DIV",e[e.NEGATE=143]="NEGATE",e[e.ABS=144]="ABS",e[e.NOT=145]="NOT",e[e["0NOTEQUAL"]=146]="0NOTEQUAL",e[e.ADD=147]="ADD",e[e.SUB=148]="SUB",e[e.MUL=149]="MUL",e[e.DIV=150]="DIV",e[e.MOD=151]="MOD",e[e.LSHIFT=152]="LSHIFT",e[e.RSHIFT=153]="RSHIFT",e[e.BOOLAND=154]="BOOLAND",e[e.BOOLOR=155]="BOOLOR",e[e.NUMEQUAL=156]="NUMEQUAL",e[e.NUMEQUALVERIFY=157]="NUMEQUALVERIFY",e[e.NUMNOTEQUAL=158]="NUMNOTEQUAL",e[e.LESSTHAN=159]="LESSTHAN",e[e.GREATERTHAN=160]="GREATERTHAN",e[e.LESSTHANOREQUAL=161]="LESSTHANOREQUAL",e[e.GREATERTHANOREQUAL=162]="GREATERTHANOREQUAL",e[e.MIN=163]="MIN",e[e.MAX=164]="MAX",e[e.WITHIN=165]="WITHIN",e[e.RIPEMD160=166]="RIPEMD160",e[e.SHA1=167]="SHA1",e[e.SHA256=168]="SHA256",e[e.HASH160=169]="HASH160",e[e.HASH256=170]="HASH256",e[e.CODESEPARATOR=171]="CODESEPARATOR",e[e.CHECKSIG=172]="CHECKSIG",e[e.CHECKSIGVERIFY=173]="CHECKSIGVERIFY",e[e.CHECKMULTISIG=174]="CHECKMULTISIG",e[e.CHECKMULTISIGVERIFY=175]="CHECKMULTISIGVERIFY",e[e.NOP1=176]="NOP1",e[e.CHECKLOCKTIMEVERIFY=177]="CHECKLOCKTIMEVERIFY",e[e.CHECKSEQUENCEVERIFY=178]="CHECKSEQUENCEVERIFY",e[e.NOP4=179]="NOP4",e[e.NOP5=180]="NOP5",e[e.NOP6=181]="NOP6",e[e.NOP7=182]="NOP7",e[e.NOP8=183]="NOP8",e[e.NOP9=184]="NOP9",e[e.NOP10=185]="NOP10",e[e.CHECKSIGADD=186]="CHECKSIGADD",e[e.INVALID=255]="INVALID"}(fc||(fc={}));const pc=Au({encodeStream:(e,t)=>{for(let n of t){if("string"==typeof n){if(void 0===fc[n])throw new Error(`Unknown opcode=${n}`);e.byte(fc[n]);continue}if("number"==typeof n){if(0===n){e.byte(0);continue}if(1<=n&&n<=16){e.byte(fc.OP_1-1+n);continue}}if("number"==typeof n&&(n=lc().encode(BigInt(n))),!Qu(n))throw new Error(`Wrong Script OP=${n} (${typeof n})`);const t=n.length;t<fc.PUSHDATA1?e.byte(t):t<=255?(e.byte(fc.PUSHDATA1),e.byte(t)):t<=65535?(e.byte(fc.PUSHDATA2),e.bytes(Hu.encode(t))):(e.byte(fc.PUSHDATA4),e.bytes(Lu.encode(t))),e.bytes(n)}},decodeStream:e=>{const t=[];for(;!e.isEnd();){const n=e.byte();if(fc.OP_0<n&&n<=fc.PUSHDATA4){let r;if(n<fc.PUSHDATA1)r=n;else if(n===fc.PUSHDATA1)r=Du.decodeStream(e);else if(n===fc.PUSHDATA2)r=Hu.decodeStream(e);else{if(n!==fc.PUSHDATA4)throw new Error("Should be not possible");r=Lu.decodeStream(e)}t.push(e.bytes(r))}else if(0===n)t.push(0);else if(fc.OP_1<=n&&n<=fc.OP_16)t.push(n-(fc.OP_1-1));else{const e=fc[n];if(void 0===e)throw new Error(`Unknown opcode=${n.toString(16)}`);t.push(e)}}return t}}),gc={253:[253,2,253n,65535n],254:[254,4,65536n,4294967295n],255:[255,8,4294967296n,18446744073709551615n]},mc=Au({encodeStream:(e,t)=>{if("number"==typeof t&&(t=BigInt(t)),0n<=t&&t<=252n)return e.byte(Number(t));for(const[n,r,i,s]of Object.values(gc))if(!(i>t||t>s)){e.byte(n);for(let n=0;n<r;n++)e.byte(Number(t>>8n*BigInt(n)&0xffn));return}throw e.err(`VarInt too big: ${t}`)},decodeStream:e=>{const t=e.byte();if(t<=252)return BigInt(t);const[n,r,i]=gc[t];let s=0n;for(let t=0;t<r;t++)s|=BigInt(e.byte())<<8n*BigInt(t);if(s<i)throw e.err(`Wrong CompactSize(${8*r})`);return s}}),yc=Zu(mc,Nu.numberBigint),wc=Fu(mc),_c=Mu(yc,wc),vc=e=>Mu(mc,e),bc=qu({txid:Fu(32,!0),index:Lu,finalScriptSig:wc,sequence:Lu}),Ec=qu({amount:Cu,script:wc});const xc=Ou(qu({version:ju,segwitFlag:((e,t=!1)=>{if(!fu(e))throw new Error("flag/flagValue: expected Uint8Array, got "+typeof e);if("boolean"!=typeof t)throw new Error("flag/xor: expected boolean, got "+typeof t);return Au({size:e.length,encodeStream:(n,r)=>{!!r!==t&&n.bytes(e)},decodeStream:n=>{let r=n.leftBytes>=e.length;return r&&(r=hu(n.bytes(e.length,!0),e),r&&n.bytes(e.length)),r!==t},validate:e=>{if(void 0!==e&&"boolean"!=typeof e)throw new Error("flag: expected boolean value or undefined, got "+typeof e);return e}})})(new Uint8Array([0,1])),inputs:vc(bc),outputs:vc(Ec),witnesses:function(e,t){if(!Tu(t))throw new Error(`flagged: invalid inner value ${t}`);return Au({encodeStream:(n,r)=>{bu.resolve(n.stack,e)&&t.encodeStream(n,r)},decodeStream:n=>{let r=!1;if(r=!!bu.resolve(n.stack,e),r)return t.decodeStream(n)}})}("segwitFlag",Mu("inputs/length",_c)),lockTime:Lu}),function(e){if(e.segwitFlag&&e.witnesses&&!e.witnesses.length)throw new Error("Segwit flag with empty witnesses array");return e}),Sc=qu({version:ju,inputs:vc(bc),outputs:vc(Ec),lockTime:Lu}),kc=Ou(Fu(null),e=>uc(e,ac.ecdsa)),Oc=Ou(Fu(32),e=>uc(e,ac.schnorr)),Ac=Ou(Fu(null),e=>{if(64!==e.length&&65!==e.length)throw new Error("Schnorr signature should be 64 or 65 bytes long");return e}),Pc=qu({fingerprint:zu,path:Mu(null,Lu)}),Tc=qu({hashes:Mu(yc,Fu(32)),der:Pc}),Ic=Fu(78),Nc=qu({pubKey:Oc,leafHash:Fu(32)}),Uc=Ou(qu({version:Du,internalKey:Fu(32),merklePath:Mu(null,Fu(32))}),e=>{if(e.merklePath.length>128)throw new Error("TaprootControlBlock: merklePath should be of length 0..128 (inclusive)");return e}),$c=Mu(null,qu({depth:Du,version:Du,script:wc})),Cc=Fu(null),Bc=Fu(20),Rc=Fu(32),Lc={unsignedTx:[0,!1,Sc,[0],[0],!1],xpub:[1,Ic,Pc,[],[0,2],!1],txVersion:[2,!1,Lu,[2],[2],!1],fallbackLocktime:[3,!1,Lu,[],[2],!1],inputCount:[4,!1,yc,[2],[2],!1],outputCount:[5,!1,yc,[2],[2],!1],txModifiable:[6,!1,Du,[],[2],!1],version:[251,!1,Lu,[],[0,2],!1],proprietary:[252,Cc,Cc,[],[0,2],!1]},zc={nonWitnessUtxo:[0,!1,xc,[],[0,2],!1],witnessUtxo:[1,!1,Ec,[],[0,2],!1],partialSig:[2,kc,Cc,[],[0,2],!1],sighashType:[3,!1,Lu,[],[0,2],!1],redeemScript:[4,!1,Cc,[],[0,2],!1],witnessScript:[5,!1,Cc,[],[0,2],!1],bip32Derivation:[6,kc,Pc,[],[0,2],!1],finalScriptSig:[7,!1,Cc,[],[0,2],!1],finalScriptWitness:[8,!1,_c,[],[0,2],!1],porCommitment:[9,!1,Cc,[],[0,2],!1],ripemd160:[10,Bc,Cc,[],[0,2],!1],sha256:[11,Rc,Cc,[],[0,2],!1],hash160:[12,Bc,Cc,[],[0,2],!1],hash256:[13,Rc,Cc,[],[0,2],!1],txid:[14,!1,Rc,[2],[2],!0],index:[15,!1,Lu,[2],[2],!0],sequence:[16,!1,Lu,[],[2],!0],requiredTimeLocktime:[17,!1,Lu,[],[2],!1],requiredHeightLocktime:[18,!1,Lu,[],[2],!1],tapKeySig:[19,!1,Ac,[],[0,2],!1],tapScriptSig:[20,Nc,Ac,[],[0,2],!1],tapLeafScript:[21,Uc,Cc,[],[0,2],!1],tapBip32Derivation:[22,Rc,Tc,[],[0,2],!1],tapInternalKey:[23,!1,Oc,[],[0,2],!1],tapMerkleRoot:[24,!1,Rc,[],[0,2],!1],proprietary:[252,Cc,Cc,[],[0,2],!1]},jc=["txid","sequence","index","witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknown"],Hc=["partialSig","finalScriptSig","finalScriptWitness","tapKeySig","tapScriptSig"],Dc={redeemScript:[0,!1,Cc,[],[0,2],!1],witnessScript:[1,!1,Cc,[],[0,2],!1],bip32Derivation:[2,kc,Pc,[],[0,2],!1],amount:[3,!1,Bu,[2],[2],!0],script:[4,!1,Cc,[2],[2],!0],tapInternalKey:[5,!1,Oc,[],[0,2],!1],tapTree:[6,!1,$c,[],[0,2],!1],tapBip32Derivation:[7,Oc,Tc,[],[0,2],!1],proprietary:[252,Cc,Cc,[],[0,2],!1]},Fc=[],Vc=Mu(du,qu({key:function(e,t){if(!Tu(t))throw new Error(`prefix: invalid inner value ${t}`);return Zu(Fu(e),Iu(t))}(yc,qu({type:yc,key:Fu(null)})),value:Fu(yc)}));function Zc(e){const[t,n,r,i,s,o]=e;return{type:t,kc:n,vc:r,reqInc:i,allowInc:s,silentIgnore:o}}function Kc(e){const t={};for(const n in e){const[r,i,s]=e[n];t[r]=[n,i,s]}return Au({encodeStream:(t,n)=>{let r=[];for(const t in e){const i=n[t];if(void 0===i)continue;const[s,o,a]=e[t];if(o){const e=i.map(([e,t])=>[o.encode(e),a.encode(t)]);e.sort((e,t)=>hc(e[0],t[0]));for(const[t,n]of e)r.push({key:{key:t,type:s},value:n})}else r.push({key:{type:s,key:cu},value:a.encode(i)})}if(n.unknown){n.unknown.sort((e,t)=>hc(e[0].key,t[0].key));for(const[e,t]of n.unknown)r.push({key:e,value:t})}Vc.encodeStream(t,r)},decodeStream:e=>{const n=Vc.decodeStream(e),r={},i={};for(const e of n){let n="unknown",s=e.key.key,o=e.value;if(t[e.key.type]){const[a,u,c]=t[e.key.type];if(n=a,!u&&s.length)throw new Error(`PSBT: Non-empty key for ${n} (key=${Fi.encode(s)} value=${Fi.encode(o)}`);if(s=u?u.decode(s):void 0,o=c.decode(o),!u){if(r[n])throw new Error(`PSBT: Same keys: ${n} (key=${s} value=${o})`);r[n]=o,i[n]=!0;continue}}else s={type:e.key.type,key:e.key.key};if(i[n])throw new Error(`PSBT: Key type with empty key and no key=${n} val=${o}`);r[n]||(r[n]=[]),r[n].push([s,o])}return r}})}qu({type:yc,key:Fu(null)});const Wc=Ou(Kc(zc),e=>{if(e.finalScriptWitness&&!e.finalScriptWitness.length)throw new Error("validateInput: empty finalScriptWitness");if(e.partialSig&&!e.partialSig.length)throw new Error("Empty partialSig");if(e.partialSig)for(const[t]of e.partialSig)uc(t,ac.ecdsa);if(e.bip32Derivation)for(const[t]of e.bip32Derivation)uc(t,ac.ecdsa);if(void 0!==e.requiredTimeLocktime&&e.requiredTimeLocktime<5e8)throw new Error(`validateInput: wrong timeLocktime=${e.requiredTimeLocktime}`);if(void 0!==e.requiredHeightLocktime&&(e.requiredHeightLocktime<=0||e.requiredHeightLocktime>=5e8))throw new Error(`validateInput: wrong heighLocktime=${e.requiredHeightLocktime}`);if(e.tapLeafScript)for(const[t,n]of e.tapLeafScript){if((254&t.version)!==n[n.length-1])throw new Error("validateInput: tapLeafScript version mimatch");if(1&n[n.length-1])throw new Error("validateInput: tapLeafScript version has parity bit!")}return e}),qc=Ou(Kc(Dc),e=>{if(e.bip32Derivation)for(const[t]of e.bip32Derivation)uc(t,ac.ecdsa);return e}),Mc=Ou(Kc(Lc),e=>{if(0===(e.version||0)){if(!e.unsignedTx)throw new Error("PSBTv0: missing unsignedTx");for(const t of e.unsignedTx.inputs)if(t.finalScriptSig&&t.finalScriptSig.length)throw new Error("PSBTv0: input scriptSig found in unsignedTx")}return e}),Gc=qu({magic:Ku(Vu(new Uint8Array([255])),"psbt"),global:Mc,inputs:Mu("global/unsignedTx/inputs/length",Wc),outputs:Mu(null,qc)}),Yc=qu({magic:Ku(Vu(new Uint8Array([255])),"psbt"),global:Mc,inputs:Mu("global/inputCount",Wc),outputs:Mu("global/outputCount",qc)});function Qc(e,t,n){for(const r in n){if("unknown"===r)continue;if(!t[r])continue;const{allowInc:n}=Zc(t[r]);if(!n.includes(e))throw new Error(`PSBTv${e}: field ${r} is not allowed`)}for(const r in t){const{reqInc:i}=Zc(t[r]);if(i.includes(e)&&void 0===n[r])throw new Error(`PSBTv${e}: missing required field ${r}`)}}function Jc(e,t,n){const r={};for(const i in n){const s=i;if("unknown"!==s){if(!t[s])continue;const{allowInc:n,silentIgnore:r}=Zc(t[s]);if(!n.includes(e)){if(r)continue;throw new Error(`Failed to serialize in PSBTv${e}: ${s} but versions allows inclusion=${n}`)}}r[s]=n[s]}return r}function Xc(e){const t=e&&e.global&&e.global.version||0;Qc(t,Lc,e.global);for(const n of e.inputs)Qc(t,zc,n);for(const n of e.outputs)Qc(t,Dc,n);const n=t?e.global.inputCount:e.global.unsignedTx.inputs.length;if(e.inputs.length<n)throw new Error("Not enough inputs");const r=e.inputs.slice(n);if(r.length>1||r.length&&Object.keys(r[0]).length)throw new Error(`Unexpected inputs left in tx=${r}`);const i=t?e.global.outputCount:e.global.unsignedTx.outputs.length;if(e.outputs.length<i)throw new Error("Not outputs inputs");const s=e.outputs.slice(i);if(s.length>1||s.length&&Object.keys(s[0]).length)throw new Error(`Unexpected outputs left in tx=${s}`);return e}function ed(e,t,n,r,i){const s={...n,...t};for(const i in e){const o=i,[a,u,c]=e[o],d=r&&!r.includes(i);if(void 0===t[i]&&i in t){if(d)throw new Error(`Cannot remove signed field=${i}`);delete s[i]}else if(u){const e=n&&n[i]?n[i]:[];let r=t[o];if(r){if(!Array.isArray(r))throw new Error(`keyMap(${i}): KV pairs should be [k, v][]`);r=r.map(e=>{if(2!==e.length)throw new Error(`keyMap(${i}): KV pairs should be [k, v][]`);return["string"==typeof e[0]?u.decode(Fi.decode(e[0])):e[0],"string"==typeof e[1]?c.decode(Fi.decode(e[1])):e[1]]});const t={},n=(e,n,r)=>{if(void 0===t[e])return void(t[e]=[n,r]);const i=Fi.encode(c.encode(t[e][1])),s=Fi.encode(c.encode(r));if(i!==s)throw new Error(`keyMap(${o}): same key=${e} oldVal=${i} newVal=${s}`)};for(const[t,r]of e){n(Fi.encode(u.encode(t)),t,r)}for(const[e,i]of r){const r=Fi.encode(u.encode(e));if(void 0===i){if(d)throw new Error(`Cannot remove signed field=${o}/${e}`);delete t[r]}else n(r,e,i)}s[o]=Object.values(t)}}else if("string"==typeof s[i])s[i]=c.decode(Fi.decode(s[i]));else if(d&&i in t&&n&&void 0!==n[i]&&!Xu(c.encode(t[i]),c.encode(n[i])))throw new Error(`Cannot change signed field=${i}`)}for(const t in s)if(!e[t]){if(i&&"unknown"===t)continue;delete s[t]}return s}qu({magic:Ku(Vu(new Uint8Array([255])),"psbt"),items:Mu(null,Zu(Mu(du,function(e){if(!Array.isArray(e))throw new Error(`Packed.Tuple: got ${typeof e} instead of array`);for(let t=0;t<e.length;t++)if(!Tu(e[t]))throw new Error(`tuple: field ${t} is not CoderType`);return Au({size:Wu(e),encodeStream:(t,n)=>{if(!Array.isArray(n))throw t.err(`tuple: invalid value ${n}`);t.pushObj(n,r=>{for(let i=0;i<e.length;i++)r(`${i}`,()=>e[i].encodeStream(t,n[i]))})},decodeStream:t=>{const n=[];return t.pushObj(n,r=>{for(let i=0;i<e.length;i++)r(`${i}`,()=>n.push(e[i].decodeStream(t)))}),n},validate:t=>{if(!Array.isArray(t))throw new Error(`tuple: invalid value ${t}`);if(t.length!==e.length)throw new Error(`tuple: wrong length=${t.length}, expected ${e.length}`);return t}})}([((e,t={isLE:!1,with0x:!1})=>{let n=Zu(Fu(e,t.isLE),Fi);const r=t.with0x;if("boolean"!=typeof r)throw new Error("hex/with0x: expected boolean, got "+typeof r);return r&&(n=Zu(n,{encode:e=>`0x${e}`,decode:e=>{if(!e.startsWith("0x"))throw new Error("hex(with0x=true).encode input should start with 0x");return e.slice(2)}})),n})(yc),Fu(mc)])),Nu.dict()))});const td=Ou(Gc,Xc),nd=Ou(Yc,Xc);function rd(e,t){try{return uc(e,t),!0}catch(e){return!1}}const id=[{encode(e){if(2===e.length&&1===e[0]&&Qu(e[1])&&"4e73"===Fi.encode(e[1]))return{type:"p2a",script:pc.encode(e)}},decode:e=>{if("p2a"===e.type)return[1,Fi.decode("4e73")]}},{encode(e){if(2===e.length&&Qu(e[0])&&rd(e[0],ac.ecdsa)&&"CHECKSIG"===e[1])return{type:"pk",pubkey:e[0]}},decode:e=>"pk"===e.type?[e.pubkey,"CHECKSIG"]:void 0},{encode(e){if(5===e.length&&"DUP"===e[0]&&"HASH160"===e[1]&&Qu(e[2])&&"EQUALVERIFY"===e[3]&&"CHECKSIG"===e[4])return{type:"pkh",hash:e[2]}},decode:e=>"pkh"===e.type?["DUP","HASH160",e.hash,"EQUALVERIFY","CHECKSIG"]:void 0},{encode(e){if(3===e.length&&"HASH160"===e[0]&&Qu(e[1])&&"EQUAL"===e[2])return{type:"sh",hash:e[1]}},decode:e=>"sh"===e.type?["HASH160",e.hash,"EQUAL"]:void 0},{encode(e){if(2===e.length&&0===e[0]&&Qu(e[1])&&32===e[1].length)return{type:"wsh",hash:e[1]}},decode:e=>"wsh"===e.type?[0,e.hash]:void 0},{encode(e){if(2===e.length&&0===e[0]&&Qu(e[1])&&20===e[1].length)return{type:"wpkh",hash:e[1]}},decode:e=>"wpkh"===e.type?[0,e.hash]:void 0},{encode(e){const t=e.length-1;if("CHECKMULTISIG"!==e[t])return;const n=e[0],r=e[t-1];if("number"!=typeof n||"number"!=typeof r)return;const i=e.slice(1,-2);if(r===i.length){for(const e of i)if(!Qu(e))return;return{type:"ms",m:n,pubkeys:i}}},decode:e=>"ms"===e.type?[e.m,...e.pubkeys,e.pubkeys.length,"CHECKMULTISIG"]:void 0},{encode(e){if(2===e.length&&1===e[0]&&Qu(e[1]))return{type:"tr",pubkey:e[1]}},decode:e=>"tr"===e.type?[1,e.pubkey]:void 0},{encode(e){const t=e.length-1;if("CHECKSIG"!==e[t])return;const n=[];for(let r=0;r<t;r++){const i=e[r];if(1&r){if("CHECKSIGVERIFY"!==i||r===t-1)return}else{if(!Qu(i))return;n.push(i)}}return{type:"tr_ns",pubkeys:n}},decode:e=>{if("tr_ns"!==e.type)return;const t=[];for(let n=0;n<e.pubkeys.length-1;n++)t.push(e.pubkeys[n],"CHECKSIGVERIFY");return t.push(e.pubkeys[e.pubkeys.length-1],"CHECKSIG"),t}},{encode(e){const t=e.length-1;if("NUMEQUAL"!==e[t]||"CHECKSIG"!==e[1])return;const n=[],r=function(e,t=4,n=!0){if("number"==typeof e)return e;if(Qu(e))try{const r=lc(t,n).decode(e);if(r>Number.MAX_SAFE_INTEGER)return;return Number(r)}catch(e){return}}(e[t-1]);if("number"==typeof r){for(let r=0;r<t-1;r++){const t=e[r];if(1&r){if(t!==(1===r?"CHECKSIG":"CHECKSIGADD"))throw new Error("OutScript.encode/tr_ms: wrong element")}else{if(!Qu(t))throw new Error("OutScript.encode/tr_ms: wrong key element");n.push(t)}}return{type:"tr_ms",pubkeys:n,m:r}}},decode:e=>{if("tr_ms"!==e.type)return;const t=[e.pubkeys[0],"CHECKSIG"];for(let n=1;n<e.pubkeys.length;n++)t.push(e.pubkeys[n],"CHECKSIGADD");return t.push(e.m,"NUMEQUAL"),t}},{encode:e=>({type:"unknown",script:pc.encode(e)}),decode:e=>"unknown"===e.type?pc.decode(e.script):void 0}],sd=Ou(Zu(pc,Nu.match(id)),e=>{if("pk"===e.type&&!rd(e.pubkey,ac.ecdsa))throw new Error("OutScript/pk: wrong key");if(!("pkh"!==e.type&&"sh"!==e.type&&"wpkh"!==e.type||Qu(e.hash)&&20===e.hash.length))throw new Error(`OutScript/${e.type}: wrong hash`);if("wsh"===e.type&&(!Qu(e.hash)||32!==e.hash.length))throw new Error("OutScript/wsh: wrong hash");if(!("tr"!==e.type||Qu(e.pubkey)&&rd(e.pubkey,ac.schnorr)))throw new Error("OutScript/tr: wrong taproot public key");if(("ms"===e.type||"tr_ns"===e.type||"tr_ms"===e.type)&&!Array.isArray(e.pubkeys))throw new Error("OutScript/multisig: wrong pubkeys array");if("ms"===e.type){const t=e.pubkeys.length;for(const t of e.pubkeys)if(!rd(t,ac.ecdsa))throw new Error("OutScript/multisig: wrong pubkey");if(e.m<=0||t>16||e.m>t)throw new Error("OutScript/multisig: invalid params")}if("tr_ns"===e.type||"tr_ms"===e.type)for(const t of e.pubkeys)if(!rd(t,ac.schnorr))throw new Error(`OutScript/${e.type}: wrong pubkey`);if("tr_ms"===e.type){const t=e.pubkeys.length;if(e.m<=0||t>999||e.m>t)throw new Error("OutScript/tr_ms: invalid params")}return e});function od(e,t){if(!Xu(e.hash,ee(t)))throw new Error("checkScript: wsh wrong witnessScript hash");const n=sd.decode(t);if("tr"===n.type||"tr_ns"===n.type||"tr_ms"===n.type)throw new Error(`checkScript: P2${n.type} cannot be wrapped in P2SH`);if("wpkh"===n.type||"sh"===n.type)throw new Error(`checkScript: P2${n.type} cannot be wrapped in P2WSH`)}function ad(e,t,n){if(e){const r=sd.decode(e);if("tr_ns"===r.type||"tr_ms"===r.type||"ms"===r.type||"pk"==r.type)throw new Error(`checkScript: non-wrapped ${r.type}`);if("sh"===r.type&&t){if(!Xu(r.hash,ec(t)))throw new Error("checkScript: sh wrong redeemScript hash");const e=sd.decode(t);if("tr"===e.type||"tr_ns"===e.type||"tr_ms"===e.type)throw new Error(`checkScript: P2${e.type} cannot be wrapped in P2SH`);if("sh"===e.type)throw new Error("checkScript: P2SH cannot be wrapped in P2SH")}"wsh"===r.type&&n&&od(r,n)}if(t){const e=sd.decode(t);"wsh"===e.type&&n&&od(e,n)}}const ud=(e,t=192)=>oc("TapLeaf",new Uint8Array([t]),wc.encode(e)),cd=$i(ee);function dd(e,t){if(t.length<2||t.length>40)throw new Error("Witness: invalid length");if(e>16)throw new Error("Witness: invalid version");if(0===e&&20!==t.length&&32!==t.length)throw new Error("Witness: invalid length for version")}function hd(e,t,n=dc){dd(e,t);const r=0===e?ji:Hi;return r.encode(n.bech32,[e].concat(r.toWords(t)))}function fd(e,t){return cd.encode(Ju(Uint8Array.from(t),e))}function ld(e=dc){return{encode(t){const{type:n}=t;if("wpkh"===n)return hd(0,t.hash,e);if("wsh"===n)return hd(0,t.hash,e);if("tr"===n)return hd(1,t.pubkey,e);if("pkh"===n)return fd(t.hash,[e.pubKeyHash]);if("sh"===n)return fd(t.hash,[e.scriptHash]);throw new Error(`Unknown address type=${n}`)},decode(t){if(t.length<14||t.length>74)throw new Error("Invalid address length");if(e.bech32&&t.toLowerCase().startsWith(`${e.bech32}1`)){let n;try{if(n=ji.decode(t),0!==n.words[0])throw new Error(`bech32: wrong version=${n.words[0]}`)}catch(e){if(n=Hi.decode(t),0===n.words[0])throw new Error(`bech32m: wrong version=${n.words[0]}`)}if(n.prefix!==e.bech32)throw new Error(`wrong bech32 prefix=${n.prefix}`);const[r,...i]=n.words,s=ji.fromWords(i);if(dd(r,s),0===r&&32===s.length)return{type:"wsh",hash:s};if(0===r&&20===s.length)return{type:"wpkh",hash:s};if(1===r&&32===s.length)return{type:"tr",pubkey:s};throw new Error("Unknown witness program")}const n=cd.decode(t);if(21!==n.length)throw new Error("Invalid base58 address");if(n[0]===e.pubKeyHash)return{type:"pkh",hash:n.slice(1)};if(n[0]===e.scriptHash)return{type:"sh",hash:n.slice(1)};throw new Error(`Invalid address prefix=${n[0]}`)}}}const pd=new Uint8Array(32),gd={amount:0xffffffffffffffffn,script:cu},md=4294967295;Nu.decimal(8);const yd=(e,t)=>void 0===e?t:e;function wd(e){if(Array.isArray(e))return e.map(e=>wd(e));if(Qu(e))return Uint8Array.from(e);if(["number","bigint","boolean","string","undefined"].includes(typeof e))return e;if(null===e)return e;if("object"==typeof e)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,wd(t)]));throw new Error(`cloneDeep: unknown type=${e} (${typeof e})`)}var _d,vd;function bd(e,t,n,r=cu){return Xu(n,t)&&(e=function(e,t=Uint8Array.of()){const n=$t.utils,r=n.bytesToNumberBE(e),i=Gu.fromPrivateKey(r),s=i.hasEvenY()?r:n.mod(-r,Yu),o=cc(n.pointToBytes(i),t);return n.numberToBytesBE(n.mod(s+o,Yu),32)}(e,r),t=nc(e)),{privKey:e,pubKey:t}}function Ed(e){if(void 0===e.script||void 0===e.amount)throw new Error("Transaction/output: script and amount required");return{script:e.script,amount:e.amount}}function xd(e){if(void 0===e.txid||void 0===e.index)throw new Error("Transaction/input: txid and index required");return{txid:e.txid,index:e.index,sequence:yd(e.sequence,md),finalScriptSig:yd(e.finalScriptSig,cu)}}function Sd(e){for(const t in e){const n=t;jc.includes(n)||delete e[n]}}!function(e){e[e.DEFAULT=0]="DEFAULT",e[e.ALL=1]="ALL",e[e.NONE=2]="NONE",e[e.SINGLE=3]="SINGLE",e[e.ANYONECANPAY=128]="ANYONECANPAY"}(_d||(_d={})),function(e){e[e.DEFAULT=0]="DEFAULT",e[e.ALL=1]="ALL",e[e.NONE=2]="NONE",e[e.SINGLE=3]="SINGLE",e[e.DEFAULT_ANYONECANPAY=128]="DEFAULT_ANYONECANPAY",e[e.ALL_ANYONECANPAY=129]="ALL_ANYONECANPAY",e[e.NONE_ANYONECANPAY=130]="NONE_ANYONECANPAY",e[e.SINGLE_ANYONECANPAY=131]="SINGLE_ANYONECANPAY"}(vd||(vd={}));const kd=qu({txid:Fu(32,!0),index:Lu});function Od(e){if("number"!=typeof e||"string"!=typeof vd[e])throw new Error(`Invalid SigHash=${e}`);return e}function Ad(e){const t=31&e;return{isAny:!!(e&_d.ANYONECANPAY),isNone:t===_d.NONE,isSingle:t===_d.SINGLE}}function Pd(e){if(e.nonWitnessUtxo&&void 0!==e.index){const t=e.nonWitnessUtxo.outputs.length-1;if(e.index>t)throw new Error(`validateInput: index(${e.index}) not in nonWitnessUtxo`);const n=e.nonWitnessUtxo.outputs[e.index];if(e.witnessUtxo&&(!Xu(e.witnessUtxo.script,n.script)||e.witnessUtxo.amount!==n.amount))throw new Error("validateInput: witnessUtxo different from nonWitnessUtxo");if(e.txid){if(e.nonWitnessUtxo.outputs.length-1<e.index)throw new Error("nonWitnessUtxo: incorect output index");const t=Ud.fromRaw(xc.encode(e.nonWitnessUtxo),{allowUnknownOutputs:!0,disableScriptCheck:!0,allowUnknownInputs:!0}),n=Fi.encode(e.txid);if(t.isFinal&&t.id!==n)throw new Error(`nonWitnessUtxo: wrong txid, exp=${n} got=${t.id}`)}}return e}function Td(e){if(e.nonWitnessUtxo){if(void 0===e.index)throw new Error("Unknown input index");return e.nonWitnessUtxo.outputs[e.index]}if(e.witnessUtxo)return e.witnessUtxo;throw new Error("Cannot find previous output info")}function Id(e,t,n,r=!1,i=!1){let{nonWitnessUtxo:s,txid:o}=e;"string"==typeof s&&(s=Fi.decode(s)),Qu(s)&&(s=xc.decode(s)),"nonWitnessUtxo"in e||void 0!==s||(s=t?.nonWitnessUtxo),"string"==typeof o&&(o=Fi.decode(o)),void 0===o&&(o=t?.txid);let a,u={...t,...e,nonWitnessUtxo:s,txid:o};return"nonWitnessUtxo"in e||void 0!==u.nonWitnessUtxo||delete u.nonWitnessUtxo,void 0===u.sequence&&(u.sequence=md),null===u.tapMerkleRoot&&delete u.tapMerkleRoot,u=ed(zc,u,t,n,i),Wc.encode(u),u.nonWitnessUtxo&&void 0!==u.index?a=u.nonWitnessUtxo.outputs[u.index]:u.witnessUtxo&&(a=u.witnessUtxo),a&&!r&&ad(a&&a.script,u.redeemScript,u.witnessScript),u}function Nd(e,t=!1){let n="legacy",r=_d.ALL;const i=Td(e),s=sd.decode(i.script);let o=s.type,a=s;const u=[s];if("tr"===s.type)return r=_d.DEFAULT,{txType:"taproot",type:"tr",last:s,lastScript:i.script,defaultSighash:r,sighash:e.sighashType||r};{if("wpkh"!==s.type&&"wsh"!==s.type||(n="segwit"),"sh"===s.type){if(!e.redeemScript)throw new Error("inputType: sh without redeemScript");let t=sd.decode(e.redeemScript);"wpkh"!==t.type&&"wsh"!==t.type||(n="segwit"),u.push(t),a=t,o+=`-${t.type}`}if("wsh"===a.type){if(!e.witnessScript)throw new Error("inputType: wsh without witnessScript");let t=sd.decode(e.witnessScript);"wsh"===t.type&&(n="segwit"),u.push(t),a=t,o+=`-${t.type}`}const i=u[u.length-1];if("sh"===i.type||"wsh"===i.type)throw new Error("inputType: sh/wsh cannot be terminal type");const c={type:o,txType:n,last:i,lastScript:sd.encode(i),defaultSighash:r,sighash:e.sighashType||r};if("legacy"===n&&!t&&!e.nonWitnessUtxo)throw new Error("Transaction/sign: legacy input without nonWitnessUtxo, can result in attack that forces paying higher fees. Pass allowLegacyWitnessUtxo=true, if you sure");return c}}class Ud{constructor(e={}){this.global={},this.inputs=[],this.outputs=[];const t=this.opts=function(e){if(void 0!==e&&"[object Object]"!=={}.toString.call(e))throw new Error(`Wrong object type for transaction options: ${e}`);const t={...e,version:yd(e.version,2),lockTime:yd(e.lockTime,0),PSBTVersion:yd(e.PSBTVersion,0)};if(void 0!==t.allowUnknowInput&&(e.allowUnknownInputs=t.allowUnknowInput),void 0!==t.allowUnknowOutput&&(e.allowUnknownOutputs=t.allowUnknowOutput),"number"!=typeof t.lockTime)throw new Error("Transaction lock time should be number");if(Lu.encode(t.lockTime),0!==t.PSBTVersion&&2!==t.PSBTVersion)throw new Error(`Unknown PSBT version ${t.PSBTVersion}`);for(const e of["allowUnknownVersion","allowUnknownOutputs","allowUnknownInputs","disableScriptCheck","bip174jsCompat","allowLegacyWitnessUtxo","lowR"]){const n=t[e];if(void 0!==n&&"boolean"!=typeof n)throw new Error(`Transation options wrong type: ${e}=${n} (${typeof n})`)}if(t.allowUnknownVersion?"number"==typeof t.version:![-1,0,1,2,3].includes(t.version))throw new Error(`Unknown version: ${t.version}`);if(void 0!==t.customScripts){const e=t.customScripts;if(!Array.isArray(e))throw new Error(`wrong custom scripts type (expected array): customScripts=${e} (${typeof e})`);for(const t of e){if("function"!=typeof t.encode||"function"!=typeof t.decode)throw new Error(`wrong script=${t} (${typeof t})`);if(void 0!==t.finalizeTaproot&&"function"!=typeof t.finalizeTaproot)throw new Error(`wrong script=${t} (${typeof t})`)}}return Object.freeze(t)}(e);0!==t.lockTime&&(this.global.fallbackLocktime=t.lockTime),this.global.txVersion=t.version}static fromRaw(e,t={}){const n=xc.decode(e),r=new Ud({...t,version:n.version,lockTime:n.lockTime});for(const e of n.outputs)r.addOutput(e);if(r.outputs=n.outputs,r.inputs=n.inputs,n.witnesses)for(let e=0;e<n.witnesses.length;e++)r.inputs[e].finalScriptWitness=n.witnesses[e];return r}static fromPSBT(e,t={}){let n;try{n=td.decode(e)}catch(t){try{n=nd.decode(e)}catch(e){throw t}}const r=n.global.version||0;if(0!==r&&2!==r)throw new Error(`Wrong PSBT version=${r}`);const i=n.global.unsignedTx,s=0===r?i?.version:n.global.txVersion,o=0===r?i?.lockTime:n.global.fallbackLocktime,a=new Ud({...t,version:s,lockTime:o,PSBTVersion:r}),u=0===r?i?.inputs.length:n.global.inputCount;a.inputs=n.inputs.slice(0,u).map((e,t)=>Pd({finalScriptSig:cu,...n.global.unsignedTx?.inputs[t],...e}));const c=0===r?i?.outputs.length:n.global.outputCount;return a.outputs=n.outputs.slice(0,c).map((e,t)=>({...e,...n.global.unsignedTx?.outputs[t]})),a.global={...n.global,txVersion:s},0!==o&&(a.global.fallbackLocktime=o),a}toPSBT(e=this.opts.PSBTVersion){if(0!==e&&2!==e)throw new Error(`Wrong PSBT version=${e}`);const t=this.inputs.map(t=>Pd(Jc(e,zc,t)));for(const e of t)e.partialSig&&!e.partialSig.length&&delete e.partialSig,e.finalScriptSig&&!e.finalScriptSig.length&&delete e.finalScriptSig,e.finalScriptWitness&&!e.finalScriptWitness.length&&delete e.finalScriptWitness;const n=this.outputs.map(t=>Jc(e,Dc,t)),r={...this.global};return 0===e?(r.unsignedTx=Sc.decode(Sc.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(xd).map(e=>({...e,finalScriptSig:cu})),outputs:this.outputs.map(Ed)})),delete r.fallbackLocktime,delete r.txVersion):(r.version=e,r.txVersion=this.version,r.inputCount=this.inputs.length,r.outputCount=this.outputs.length,r.fallbackLocktime&&0===r.fallbackLocktime&&delete r.fallbackLocktime),this.opts.bip174jsCompat&&(t.length||t.push({}),n.length||n.push({})),(0===e?td:nd).encode({global:r,inputs:t,outputs:n})}get lockTime(){let e=0,t=0,n=0,r=0;for(const i of this.inputs)i.requiredHeightLocktime&&(e=Math.max(e,i.requiredHeightLocktime),t++),i.requiredTimeLocktime&&(n=Math.max(n,i.requiredTimeLocktime),r++);return t&&t>=r?e:0!==n?n:this.global.fallbackLocktime||0}get version(){if(void 0===this.global.txVersion)throw new Error("No global.txVersion");return this.global.txVersion}inputStatus(e){this.checkInputIdx(e);const t=this.inputs[e];return t.finalScriptSig&&t.finalScriptSig.length||t.finalScriptWitness&&t.finalScriptWitness.length?"finalized":t.tapKeySig||t.tapScriptSig&&t.tapScriptSig.length||t.partialSig&&t.partialSig.length?"signed":"unsigned"}inputSighash(e){this.checkInputIdx(e);const t=this.inputs[e].sighashType,n=void 0===t?_d.DEFAULT:t,r=n===_d.DEFAULT?_d.ALL:3&n;return{sigInputs:n&_d.ANYONECANPAY,sigOutputs:r}}signStatus(){let e=!0,t=!0,n=[],r=[];for(let i=0;i<this.inputs.length;i++){if("unsigned"===this.inputStatus(i))continue;const{sigInputs:s,sigOutputs:o}=this.inputSighash(i);if(s===_d.ANYONECANPAY?n.push(i):e=!1,o===_d.ALL)t=!1;else if(o===_d.SINGLE)r.push(i);else if(o!==_d.NONE)throw new Error(`Wrong signature hash output type: ${o}`)}return{addInput:e,addOutput:t,inputs:n,outputs:r}}get isFinal(){for(let e=0;e<this.inputs.length;e++)if("finalized"!==this.inputStatus(e))return!1;return!0}get hasWitnesses(){let e=!1;for(const t of this.inputs)t.finalScriptWitness&&t.finalScriptWitness.length&&(e=!0);return e}get weight(){if(!this.isFinal)throw new Error("Transaction is not finalized");let e=32;const t=this.outputs.map(Ed);e+=4*yc.encode(this.outputs.length).length;for(const n of t)e+=32+4*wc.encode(n.script).length;this.hasWitnesses&&(e+=2),e+=4*yc.encode(this.inputs.length).length;for(const t of this.inputs)e+=160+4*wc.encode(t.finalScriptSig||cu).length,this.hasWitnesses&&t.finalScriptWitness&&(e+=_c.encode(t.finalScriptWitness).length);return e}get vsize(){return e=this.weight,Math.ceil(e/4);var e}toBytes(e=!1,t=!1){return xc.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(xd).map(t=>({...t,finalScriptSig:e&&t.finalScriptSig||cu})),outputs:this.outputs.map(Ed),witnesses:this.inputs.map(e=>e.finalScriptWitness||[]),segwitFlag:t&&this.hasWitnesses})}get unsignedTx(){return this.toBytes(!1,!1)}get hex(){return Fi.encode(this.toBytes(!0,this.hasWitnesses))}get hash(){if(!this.isFinal)throw new Error("Transaction is not finalized");return Fi.encode(tc(this.toBytes(!0)))}get id(){if(!this.isFinal)throw new Error("Transaction is not finalized");return Fi.encode(tc(this.toBytes(!0)).reverse())}checkInputIdx(e){if(!Number.isSafeInteger(e)||0>e||e>=this.inputs.length)throw new Error(`Wrong input index=${e}`)}getInput(e){return this.checkInputIdx(e),wd(this.inputs[e])}get inputsLength(){return this.inputs.length}addInput(e,t=!1){if(!t&&!this.signStatus().addInput)throw new Error("Tx has signed inputs, cannot add new one");return this.inputs.push(Id(e,void 0,void 0,this.opts.disableScriptCheck)),this.inputs.length-1}updateInput(e,t,n=!1){let r;if(this.checkInputIdx(e),!n){const t=this.signStatus();t.addInput&&!t.inputs.includes(e)||(r=Hc)}this.inputs[e]=Id(t,this.inputs[e],r,this.opts.disableScriptCheck,this.opts.allowUnknown)}checkOutputIdx(e){if(!Number.isSafeInteger(e)||0>e||e>=this.outputs.length)throw new Error(`Wrong output index=${e}`)}getOutput(e){return this.checkOutputIdx(e),wd(this.outputs[e])}getOutputAddress(e,t=dc){const n=this.getOutput(e);if(n.script)return ld(t).encode(sd.decode(n.script))}get outputsLength(){return this.outputs.length}normalizeOutput(e,t,n){let{amount:r,script:i}=e;if(void 0===r&&(r=t?.amount),"bigint"!=typeof r)throw new Error(`Wrong amount type, should be of type bigint in sats, but got ${r} of type ${typeof r}`);"string"==typeof i&&(i=Fi.decode(i)),void 0===i&&(i=t?.script);let s={...t,...e,amount:r,script:i};if(void 0===s.amount&&delete s.amount,s=ed(Dc,s,t,n,this.opts.allowUnknown),qc.encode(s),s.script&&!this.opts.allowUnknownOutputs&&"unknown"===sd.decode(s.script).type)throw new Error("Transaction/output: unknown output script type, there is a chance that input is unspendable. Pass allowUnknownOutputs=true, if you sure");return this.opts.disableScriptCheck||ad(s.script,s.redeemScript,s.witnessScript),s}addOutput(e,t=!1){if(!t&&!this.signStatus().addOutput)throw new Error("Tx has signed outputs, cannot add new one");return this.outputs.push(this.normalizeOutput(e)),this.outputs.length-1}updateOutput(e,t,n=!1){let r;if(this.checkOutputIdx(e),!n){const t=this.signStatus();t.addOutput&&!t.outputs.includes(e)||(r=Fc)}this.outputs[e]=this.normalizeOutput(t,this.outputs[e],r)}addOutputAddress(e,t,n=dc){return this.addOutput({script:sd.encode(ld(n).decode(e)),amount:t})}get fee(){let e=0n;for(const t of this.inputs){const n=Td(t);if(!n)throw new Error("Empty input amount");e+=n.amount}const t=this.outputs.map(Ed);for(const n of t)e-=n.amount;return e}preimageLegacy(e,t,n){const{isAny:r,isNone:i,isSingle:s}=Ad(n);if(e<0||!Number.isSafeInteger(e))throw new Error(`Invalid input idx=${e}`);if(s&&e>=this.outputs.length||e>=this.inputs.length)return $u.encode(1n);t=pc.encode(pc.decode(t).filter(e=>"CODESEPARATOR"!==e));let o=this.inputs.map(xd).map((n,r)=>({...n,finalScriptSig:r===e?t:cu}));r?o=[o[e]]:(i||s)&&(o=o.map((t,n)=>({...t,sequence:n===e?t.sequence:0})));let a=this.outputs.map(Ed);i?a=[]:s&&(a=a.slice(0,e).fill(gd).concat([a[e]]));const u=xc.encode({lockTime:this.lockTime,version:this.version,segwitFlag:!1,inputs:o,outputs:a});return tc(u,ju.encode(n))}preimageWitnessV0(e,t,n,r){const{isAny:i,isNone:s,isSingle:o}=Ad(n);let a=pd,u=pd,c=pd;const d=this.inputs.map(xd),h=this.outputs.map(Ed);i||(a=tc(...d.map(kd.encode))),i||o||s||(u=tc(...d.map(e=>Lu.encode(e.sequence)))),o||s?o&&e<h.length&&(c=tc(Ec.encode(h[e]))):c=tc(...h.map(Ec.encode));const f=d[e];return tc(ju.encode(this.version),a,u,Fu(32,!0).encode(f.txid),Lu.encode(f.index),wc.encode(t),Cu.encode(r),Lu.encode(f.sequence),c,Lu.encode(this.lockTime),Lu.encode(n))}preimageWitnessV1(e,t,n,r,i=-1,s,o=192,a){if(!Array.isArray(r)||this.inputs.length!==r.length)throw new Error(`Invalid amounts array=${r}`);if(!Array.isArray(t)||this.inputs.length!==t.length)throw new Error(`Invalid prevOutScript array=${t}`);const u=[Du.encode(0),Du.encode(n),ju.encode(this.version),Lu.encode(this.lockTime)],c=n===_d.DEFAULT?_d.ALL:3&n,d=n&_d.ANYONECANPAY,h=this.inputs.map(xd),f=this.outputs.map(Ed);d!==_d.ANYONECANPAY&&u.push(...[h.map(kd.encode),r.map(Cu.encode),t.map(wc.encode),h.map(e=>Lu.encode(e.sequence))].map(e=>ee(Ju(...e)))),c===_d.ALL&&u.push(ee(Ju(...f.map(Ec.encode))));const l=(a?1:0)|(s?2:0);if(u.push(new Uint8Array([l])),d===_d.ANYONECANPAY){const n=h[e];u.push(kd.encode(n),Cu.encode(r[e]),wc.encode(t[e]),Lu.encode(n.sequence))}else u.push(Lu.encode(e));return 1&l&&u.push(ee(wc.encode(a||cu))),c===_d.SINGLE&&u.push(e<f.length?ee(Ec.encode(f[e])):pd),s&&u.push(ud(s,o),Du.encode(0),ju.encode(i)),oc("TapSighash",...u)}signIdx(e,t,n,r){this.checkInputIdx(t);const i=this.inputs[t],s=Nd(i,this.opts.allowLegacyWitnessUtxo);if(!Qu(e)){if(!i.bip32Derivation||!i.bip32Derivation.length)throw new Error("bip32Derivation: empty");const n=i.bip32Derivation.filter(t=>t[1].fingerprint==e.fingerprint).map(([t,{path:n}])=>{let r=e;for(const e of n)r=r.deriveChild(e);if(!Xu(r.publicKey,t))throw new Error("bip32Derivation: wrong pubKey");if(!r.privateKey)throw new Error("bip32Derivation: no privateKey");return r});if(!n.length)throw new Error(`bip32Derivation: no items with fingerprint=${e.fingerprint}`);let r=!1;for(const e of n)this.signIdx(e.privateKey,t)&&(r=!0);return r}n?n.forEach(Od):n=[s.defaultSighash];const o=s.sighash;if(!n.includes(o))throw new Error(`Input with not allowed sigHash=${o}. Allowed: ${n.join(", ")}`);const{sigOutputs:a}=this.inputSighash(t);if(a===_d.SINGLE&&t>=this.outputs.length)throw new Error(`Input with sighash SINGLE, but there is no output with corresponding index=${t}`);const u=Td(i);if("taproot"===s.txType){const n=this.inputs.map(Td),s=n.map(e=>e.script),a=n.map(e=>e.amount);let u=!1,c=nc(e),d=i.tapMerkleRoot||cu;if(i.tapInternalKey){const{pubKey:n,privKey:h}=bd(e,c,i.tapInternalKey,d),[f,l]=function(e,t){const n=$t.utils,r=cc(e,t),i=n.lift_x(n.bytesToNumberBE(e)).add(Gu.fromPrivateKey(r)),s=i.hasEvenY()?0:1;return[n.pointToBytes(i),s]}(i.tapInternalKey,d);if(Xu(f,n)){const e=this.preimageWitnessV1(t,s,o,a),n=Ju(sc(e,h,r),o!==_d.DEFAULT?new Uint8Array([o]):cu);this.updateInput(t,{tapKeySig:n},!0),u=!0}}if(i.tapLeafScript){i.tapScriptSig=i.tapScriptSig||[];for(const[n,d]of i.tapLeafScript){const n=d.subarray(0,-1),i=pc.decode(n),h=d[d.length-1],f=ud(n,h);if(-1===i.findIndex(e=>Qu(e)&&Xu(e,c)))continue;const l=this.preimageWitnessV1(t,s,o,a,void 0,n,h),p=Ju(sc(l,e,r),o!==_d.DEFAULT?new Uint8Array([o]):cu);this.updateInput(t,{tapScriptSig:[[{pubKey:c,leafHash:f},p]]},!0),u=!0}}if(!u)throw new Error("No taproot scripts signed");return!0}{const n=rc(e);let r=!1;const i=ec(n);for(const e of pc.decode(s.lastScript))Qu(e)&&(Xu(e,n)||Xu(e,i))&&(r=!0);if(!r)throw new Error(`Input script doesn't have pubKey: ${s.lastScript}`);let a;if("legacy"===s.txType)a=this.preimageLegacy(t,s.lastScript,o);else{if("segwit"!==s.txType)throw new Error(`Transaction/sign: unknown tx type: ${s.txType}`);{let e=s.lastScript;"wpkh"===s.last.type&&(e=sd.encode({type:"pkh",hash:s.last.hash})),a=this.preimageWitnessV0(t,e,o,u.amount)}}const c=function(e,t,n=!1){let r=yt.sign(e,t);if(n&&!ic(r)){const n=new Uint8Array(32);let i=0;for(;!ic(r);)if(n.set(Lu.encode(i++)),r=yt.sign(e,t,{extraEntropy:n}),i>4294967295)throw new Error("lowR counter overflow: report the error")}return r.toDERRawBytes()}(a,e,this.opts.lowR);this.updateInput(t,{partialSig:[[n,Ju(c,new Uint8Array([o]))]]},!0)}return!0}sign(e,t,n){let r=0;for(let i=0;i<this.inputs.length;i++)try{this.signIdx(e,i,t,n)&&r++}catch(e){}if(!r)throw new Error("No inputs signed");return r}finalizeIdx(e){if(this.checkInputIdx(e),this.fee<0n)throw new Error("Outputs spends more than inputs amount");const t=this.inputs[e],n=Nd(t,this.opts.allowLegacyWitnessUtxo);if("taproot"===n.txType){if(t.tapKeySig)t.finalScriptWitness=[t.tapKeySig];else{if(!t.tapLeafScript||!t.tapScriptSig)throw new Error("finalize/taproot: unknown input");{const e=t.tapLeafScript.sort((e,t)=>Uc.encode(e[0]).length-Uc.encode(t[0]).length);for(const[n,r]of e){const e=r.slice(0,-1),i=r[r.length-1],s=sd.decode(e),o=ud(e,i),a=t.tapScriptSig.filter(e=>Xu(e[0].leafHash,o));let u=[];if("tr_ms"===s.type){const e=s.m,t=s.pubkeys;let n=0;for(const r of t){const t=a.findIndex(e=>Xu(e[0].pubKey,r));n!==e&&-1!==t?(u.push(a[t][1]),n++):u.push(cu)}if(n!==e)continue}else if("tr_ns"===s.type){for(const e of s.pubkeys){const t=a.findIndex(t=>Xu(t[0].pubKey,e));-1!==t&&u.push(a[t][1])}if(u.length!==s.pubkeys.length)continue}else{if("unknown"!==s.type||!this.opts.allowUnknownInputs){const r=this.opts.customScripts;if(r)for(const i of r){if(!i.finalizeTaproot)continue;const r=pc.decode(e),s=i.encode(r);if(void 0===s)continue;const o=i.finalizeTaproot(e,s,a);if(o)return t.finalScriptWitness=o.concat(Uc.encode(n)),t.finalScriptSig=cu,void Sd(t)}throw new Error("Finalize: Unknown tapLeafScript")}{const t=pc.decode(e);if(u=a.map(([{pubKey:e},n])=>{const r=t.findIndex(t=>Qu(t)&&Xu(t,e));if(-1===r)throw new Error("finalize/taproot: cannot find position of pubkey in script");return{signature:n,pos:r}}).sort((e,t)=>e.pos-t.pos).map(e=>e.signature),!u.length)continue}}t.finalScriptWitness=u.reverse().concat([e,Uc.encode(n)]);break}if(!t.finalScriptWitness)throw new Error("finalize/taproot: empty witness")}}return t.finalScriptSig=cu,void Sd(t)}if(!t.partialSig||!t.partialSig.length)throw new Error("Not enough partial sign");let r,i,s=cu,o=[];if("ms"===n.last.type){const e=n.last.m,r=n.last.pubkeys;let i=[];for(const e of r){const n=t.partialSig.find(t=>Xu(e,t[0]));n&&i.push(n[1])}if(i=i.slice(0,e),i.length!==e)throw new Error(`Multisig: wrong signatures count, m=${e} n=${r.length} signatures=${i.length}`);s=pc.encode([0,...i])}else if("pk"===n.last.type)s=pc.encode([t.partialSig[0][1]]);else if("pkh"===n.last.type)s=pc.encode([t.partialSig[0][1],t.partialSig[0][0]]);else if("wpkh"===n.last.type)s=cu,o=[t.partialSig[0][1],t.partialSig[0][0]];else if("unknown"===n.last.type&&!this.opts.allowUnknownInputs)throw new Error("Unknown inputs not allowed");if(n.type.includes("wsh-")&&(s.length&&n.lastScript.length&&(o=pc.decode(s).map(e=>{if(0===e)return cu;if(Qu(e))return e;throw new Error(`Wrong witness op=${e}`)})),o=o.concat(n.lastScript)),"segwit"===n.txType&&(i=o),n.type.startsWith("sh-wsh-")?r=pc.encode([pc.encode([0,ee(n.lastScript)])]):n.type.startsWith("sh-")?r=pc.encode([...pc.decode(s),n.lastScript]):n.type.startsWith("wsh-")||"segwit"!==n.txType&&(r=s),!r&&!i)throw new Error("Unknown error finalizing input");r&&(t.finalScriptSig=r),i&&(t.finalScriptWitness=i),Sd(t)}finalize(){for(let e=0;e<this.inputs.length;e++)this.finalizeIdx(e)}extract(){if(!this.isFinal)throw new Error("Transaction has unfinalized inputs");if(!this.outputs.length)throw new Error("Transaction has no outputs");if(this.fee<0n)throw new Error("Outputs spends more than inputs amount");return this.toBytes(!0,!0)}combine(e){for(const t of["PSBTVersion","version","lockTime"])if(this.opts[t]!==e.opts[t])throw new Error(`Transaction/combine: different ${t} this=${this.opts[t]} other=${e.opts[t]}`);for(const t of["inputs","outputs"])if(this[t].length!==e[t].length)throw new Error(`Transaction/combine: different ${t} length this=${this[t].length} other=${e[t].length}`);const t=this.global.unsignedTx?Sc.encode(this.global.unsignedTx):cu,n=e.global.unsignedTx?Sc.encode(e.global.unsignedTx):cu;if(!Xu(t,n))throw new Error("Transaction/combine: different unsigned tx");this.global=ed(Lc,this.global,e.global,void 0,this.opts.allowUnknown);for(let t=0;t<this.inputs.length;t++)this.updateInput(t,e.inputs[t],!0);for(let t=0;t<this.outputs.length;t++)this.updateOutput(t,e.outputs[t],!0);return this}clone(){return Ud.fromPSBT(this.toPSBT(this.opts.PSBTVersion),this.opts)}}function $d(e){const t=Ki.decode(e);return Ud.fromPSBT(t,{allowUnknownOutputs:!0})}function Cd(e){if(e instanceof Ud)return e;if("string"==typeof e)return $d(e);throw new Error("invalid psbt input: "+e)}function Bd(e){const t=Cd(e),n=t.inputsLength,r=[];for(let e=0;e<n;e++){const n=t.getInput(e);r.push(n)}return r}function Rd(e){const t=Cd(e),n=t.outputsLength,r=[];for(let e=0;e<n;e++){const n=t.getOutput(e);r.push(n)}return r}function Ld(e){for(let t=0;t<e.inputsLength;t++){const n=e.getInput(t),r=n.redeemScript,i=n.partialSig?.at(0);void 0!==r&&void 0!==i&&e.finalizeIdx(t)}return e}var zd=Object.freeze({__proto__:null,assert_psbt_is_funded:function(e){const t=Cd(e),n=Bd(t),r=Rd(t),i=n.reduce((e,t)=>e+Number(t.witnessUtxo?.amount??0),0),s=r.reduce((e,t)=>e+Number(t.amount??0),0);b.ok(i>=s,`value in (${i}) < value out (${s})`)},collect_prevouts:function(e){const t=[],n=[],r=Cd(e);for(let e=0;e<r.inputsLength;e++){const i=r.getInput(e);b.exists(i.witnessUtxo,`witness utxo does not exist for input ${e}`),t.push(i.witnessUtxo.amount),n.push(i.witnessUtxo.script)}return{amounts:t,scripts:n}},collect_vins:Bd,collect_vouts:Rd,decode_psbt:$d,encode_psbt:function(e){const t=e.toPSBT(0);return Ki.encode(t)},finalize_legacy_inputs:Ld,get_txhex:function(e){let t=Cd(e);return t=Ld(t),t.hex},get_vsize:function(e){return Cd(e).vsize},parse_psbt:Cd}),jd=Object.freeze({__proto__:null,format_sigflag:Ns,hash_amounts:No,hash_outpoints:To,hash_output:Co,hash_outputs:$o,hash_scripts:Uo,hash_segwit_tx:_o,hash_sequence:Io,hash_taproot_tx:Po,parse_txinput:Is});var Hd=Object.freeze({__proto__:null,sign_segwit_tx:Ro,sign_taproot_tx:Lo,verify_segwit_tx:function(e,t={}){return console.warn("verify_segwit_tx is not implemented"),!0},verify_taproot_tx:function(e,t={}){return console.warn("verify_taproot_tx is not implemented"),!0}});function Dd(e,t,n=[]){const r=[],i=[];if(e.length<1)throw new Error("Tree is empty!");for(let i=0;i<e.length;i++){const s=e[i];if(Array.isArray(s)){let[e,i,o]=Dd(s,t);t=i,r.push(e);for(const e of o)n.push(e)}else{const e=m.bytes(s).hex;r.push(e)}}if(1===r.length)return[r[0],t,n];r.sort(),r.length%2!=0&&r.push(r[r.length-1]);for(let e=0;e<r.length-1;e+=2){const s=ko(r[e],r[e+1]).hex;i.push(s),"string"==typeof t&&(t===r[e]?(n.push(r[e+1]),t=s):t===r[e+1]&&(n.push(r[e]),t=s))}return Dd(i,t,n)}function Fd(e){const t=new y(e),n=t.read(1).num,r=t.read(32).hex,[i,s]=Vd(n),o=[];for(;t.size>=32;)o.push(t.read(32).hex);if(0!==t.size)throw new Error("Non-empty buffer on control block: "+String(t));return{int_key:r,path:o,parity:s,version:i}}function Vd(e){return e%2==0?[e-0,2]:[e-1,3]}function Zd(e){b.size(e,33,"invalid pubkey size");const[t]=m.bytes(e);if(2===t)return 0;if(3===t)return 1;throw new Error("Invalid parity bit: "+String(t))}const Kd=192;var Wd=Object.freeze({__proto__:null,create_taproot:function(e){hs.parse(e);const{pubkey:t,version:n=Kd}=e,r=e.leaves??[],i=void 0!==e.target?m.bytes(e.target).hex:void 0;let s,o=[];if(r.length>0){const[e,t,n]=Dd(r,i);o=n,s=e}else s=i;const a=Ao(t,s),u=Rt(t,a,"ecdsa"),c=Zd(u),d=jt(u,"bip340"),h=[m.num(n+c),m.bytes(t)];o.length>0&&o.forEach(e=>h.push(e));const f=m.join(h);return{int_key:m.bytes(t).hex,parity:c,taproot:s??null,cblock:f.hex,tapkey:d.hex,taptweak:a.hex}},encode_leaf_version:Oo,encode_tapbranch:ko,encode_tapleaf:So,encode_tapscript:xo,encode_taptweak:Ao,get_merkle_root:function(e){return Dd(e)[0]},merkleize:Dd,parse_cblock:Fd,parse_cblock_parity:Vd,parse_pubkey_parity:Zd,parse_taproot_witness:function(e){const{cblock:t,params:n,script:r}=Sa(e);b.exists(t,"cblock is null"),b.exists(r,"script is null");const i=Fd(t);let s=xo(r,i.version).hex;for(const e of i.path)s=ko(s,e).hex;const o=Ao(i.int_key,s),a=Rt(i.int_key,o,"bip340");return n.map(e=>m.bytes(e).hex),{cblock:i,params:n,script:r,tapkey:a.hex,tweak:o.hex}},verify_taproot:function(e,t,n){b.size(e,32);const{parity:r,path:i,int_key:s}=Fd(n),o=m.join([r,e]);let a=m.bytes(t).hex;for(const e of i)a=ko(a,e).hex;const u=Rt(s,Ao(s,a),"ecdsa");return o.hex===u.hex}});return e.ADDRESS=uu,e.CONST=rs,e.META=Ea,e.PSBT=zd,e.SCHEMA=vs,e.SCRIPT=Ms,e.SIGHASH=jd,e.SIGNER=Hd,e.TAPROOT=Wd,e.TX=wo,e.Transaction=class{constructor(e){this._tx="string"!=typeof e?Ts(e):ss(e),this._size=this._get_size(),this._hash=lo(this._tx),this._txid=fo(this._tx),this._value=po(this._tx),this._vin=this._tx.vin.map(e=>new Pa(e)),this._vout=this._tx.vout.map(e=>new xa(e))}get data(){return{hash:this.hash,locktime:this.locktime,return:this.return,size:this.size,spends:this.spends,txid:this.txid,value:this.value,version:this.version,vin:this.vin.map(e=>e.data),vout:this.vout.map(e=>e.data)}}get hash(){return this._hash}get locktime(){return{hex:oo(this._tx.locktime).hex,data:jo.decode(this._tx.locktime),value:this._tx.locktime}}get return(){return this._tx.vout.find(e=>uo(e.script_pk))||null}get size(){return this._size}get spends(){return this._tx.vin.filter(e=>null!==e.prevout).map(e=>new xa(e.prevout))}get txid(){return this._txid}get value(){return this._value}get version(){return this._tx.version}get vin(){return this._vin}get vout(){return this._vout}add_vin(e){this._tx.vin.push(e),this._update_vin()}add_vout(e){this._tx.vout.push(e),this._update_vout()}insert_vin(e,t){b.ok(e>=0&&e<=this._tx.vin.length,"input goes out of bounds"),e===this._tx.vin.length?this._tx.vin.push(t):this._tx.vin.splice(e,0,t),this._update_vin()}insert_vout(e,t){b.ok(e>=0&&e<=this._tx.vout.length,"output goes out of bounds"),e===this._tx.vout.length?this._tx.vout.push(t):this._tx.vout.splice(e,0,t),this._update_vout()}remove_vin(e){b.ok(void 0!==this._tx.vin.at(e),"input does not exist at index"),this._tx.vin.splice(e,1),this._update_vin()}remove_vout(e){b.ok(void 0!==this._tx.vout.at(e),"output does not exist at index"),this._tx.vout.splice(e,1),this._update_vout()}_get_size(){return{...go(this._tx),segwit:this.vin.reduce((e,t)=>e+(t.witness?.size.vsize??0),0),vin:this.vin.reduce((e,t)=>e+t.size,0),vout:this.vout.reduce((e,t)=>e+t.size,0),witness:this.vin.reduce((e,t)=>e+(t.witness?.size.total??0),0)}}_update_tx(){this._size=this._get_size(),this._hash=lo(this._tx),this._txid=fo(this._tx),this._value=po(this._tx)}_update_vin(){this._vin=this._tx.vin.map(e=>new Pa(e)),this._update_tx()}_update_vout(){this._vout=this._tx.vout.map(e=>new xa(e)),this._update_tx()}toJSON(){return this.data}toString(){return JSON.stringify(this.data)}},e.TransactionInput=Pa,e.TransactionOutput=xa,e.TransactionWitness=Aa,e.TxSigner=class{constructor(e){this._seckey=m.bytes(e).hex}get pubkey(){return{segwit:Bt(this._seckey,"ecdsa"),taproot:Bt(this._seckey,"bip340")}}get sign_msg(){return{ecdsa:e=>{const t=m.bytes(e);return Lt(this._seckey,t)},bip340:e=>{const t=m.bytes(e);return zt(this._seckey,t)}}}get sign_tx(){return{segwit:(e,t)=>Ro(this._seckey,e,t),taproot:(e,t)=>Lo(this._seckey,e,t)}}},e.WITNESS=Oa,e}({});
|
|
14
|
+
function di(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function hi(e,...t){if(!di(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 fi(e,t){return!!Array.isArray(t)&&(0===t.length||(e?t.every(e=>"string"==typeof e):t.every(e=>Number.isSafeInteger(e))))}function li(e){if("function"!=typeof e)throw new Error("function expected");return!0}function pi(e,t){if("string"!=typeof t)throw new Error(`${e}: string expected`);return!0}function gi(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function mi(e){if(!Array.isArray(e))throw new Error("array expected")}function yi(e,t){if(!fi(!0,t))throw new Error(`${e}: array of strings expected`)}function wi(e,t){if(!fi(!1,t))throw new Error(`${e}: array of numbers expected`)}function _i(...e){const t=e=>e,n=(e,t)=>n=>e(t(n));return{encode:e.map(e=>e.encode).reduceRight(n,t),decode:e.map(e=>e.decode).reduce(n,t)}}function vi(e){const t="string"==typeof e?e.split(""):e,n=t.length;yi("alphabet",t);const r=new Map(t.map((e,t)=>[e,t]));return{encode:r=>(mi(r),r.map(r=>{if(!Number.isSafeInteger(r)||r<0||r>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${r}". Allowed: ${e}`);return t[r]})),decode:t=>(mi(t),t.map(t=>{pi("alphabet.decode",t);const n=r.get(t);if(void 0===n)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return n}))}}function bi(e=""){return pi("join",e),{encode:t=>(yi("join.decode",t),t.join(e)),decode:t=>(pi("join.decode",t),t.split(e))}}function Ei(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(mi(e),!e.length)return[];let r=0;const i=[],s=Array.from(e,e=>{if(gi(e),e<0||e>=t)throw new Error(`invalid integer: ${e}`);return e}),o=s.length;for(;;){let e=0,a=!0;for(let i=r;i<o;i++){const o=s[i],u=t*e,c=u+o;if(!Number.isSafeInteger(c)||u/t!==e||c-o!==u)throw new Error("convertRadix: carry overflow");const d=c/n;e=c%n;const h=Math.floor(d);if(s[i]=h,!Number.isSafeInteger(h)||h*n+e!==c)throw new Error("convertRadix: carry overflow");a&&(h?a=!1:r=i)}if(i.push(e),a)break}for(let t=0;t<e.length-1&&0===e[t];t++)i.push(0);return i.reverse()}qr([ai,ii]),qr([ui,si]),zr().regex(/^[1-9A-HJ-NP-Za-km-z]+$/),zr().regex(/^[a-zA-Z0-9+/]+={0,2}$/),zr().regex(/^[a-zA-Z0-9\-_]+={0,2}$/),zr().regex(/^[a-z]+1[023456789acdefghjklmnpqrstuvwxyz]+$/);const xi=(e,t)=>0===t?e:xi(t,e%t),Si=(e,t)=>e+(t-xi(e,t)),ki=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function Oi(e,t,n,r){if(mi(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(Si(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${Si(t,n)}`);let i=0,s=0;const o=ki[t],a=ki[n]-1,u=[];for(const r of e){if(gi(r),r>=o)throw new Error(`convertRadix2: invalid data word=${r} from=${t}`);if(i=i<<t|r,s+t>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${t}`);for(s+=t;s>=n;s-=n)u.push((i>>s-n&a)>>>0);const e=ki[s];if(void 0===e)throw new Error("invalid carry");i&=e-1}if(i=i<<n-s&a,!r&&s>=t)throw new Error("Excess padding");if(!r&&i>0)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&u.push(i>>>0),u}function Ai(e,t=!1){if(gi(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(Si(8,e)>32||Si(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!di(n))throw new Error("radix2.encode input should be Uint8Array");return Oi(Array.from(n),8,e,!t)},decode:n=>(wi("radix2.decode",n),Uint8Array.from(Oi(n,e,8,t)))}}function Pi(e){return li(e),function(...t){try{return e.apply(null,t)}catch(e){}}}const Ti=(()=>"function"==typeof Uint8Array.from([]).toBase64&&"function"==typeof Uint8Array.fromBase64)()?{encode:e=>(hi(e),e.toBase64()),decode:e=>(e=>{if(pi("base64",e),e.length>0&&!/^[A-Za-z0-9=+/]+$/.test(e))throw new Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:"base64",lastChunkHandling:"strict"})})(e)}:_i(Ai(6),vi("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),function(e,t="="){return gi(e),pi("padding",t),{encode(n){for(yi("padding.encode",n);n.length*e%8;)n.push(t);return n},decode(n){yi("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)}}}(6),bi("")),Ii=_i(Ai(6),vi("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),bi("")),Ni=(Ui="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",_i(function(e){return gi(e),{encode:t=>{if(!di(t))throw new Error("radix.encode input should be Uint8Array");return Ei(Array.from(t),256,e)},decode:t=>(wi("radix.decode",t),Uint8Array.from(Ei(t,e,256)))}}(58),vi(Ui),bi("")));var Ui;const $i=e=>{return _i((n=t=>e(e(t)),gi(t=4),li(n),{encode(e){if(!di(e))throw new Error("checksum.encode: input should be Uint8Array");const r=n(e).slice(0,t),i=new Uint8Array(e.length+t);return i.set(e),i.set(r,e.length),i},decode(e){if(!di(e))throw new Error("checksum.decode: input should be Uint8Array");const r=e.slice(0,-t),i=e.slice(-t),s=n(r).slice(0,t);for(let e=0;e<t;e++)if(s[e]!==i[e])throw new Error("Invalid checksum");return r}}),Ni);var t,n},Ci=_i(vi("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),bi("")),Bi=[996825010,642813549,513874426,1027748829,705979059];function Ri(e){const t=e>>25;let n=(33554431&e)<<5;for(let e=0;e<Bi.length;e++)1==(t>>e&1)&&(n^=Bi[e]);return n}function Li(e,t,n=1){const r=e.length;let i=1;for(let t=0;t<r;t++){const n=e.charCodeAt(t);if(n<33||n>126)throw new Error(`Invalid prefix (${e})`);i=Ri(i)^n>>5}i=Ri(i);for(let t=0;t<r;t++)i=Ri(i)^31&e.charCodeAt(t);for(let e of t)i=Ri(i)^e;for(let e=0;e<6;e++)i=Ri(i);return i^=n,Ci.encode(Oi([i%ki[30]],30,5,!1))}function zi(e){const t="bech32"===e?1:734539939,n=Ai(5),r=n.decode,i=n.encode,s=Pi(r);function o(e,n,r=90){pi("bech32.encode prefix",e),di(n)&&(n=Array.from(n)),wi("bech32.encode",n);const i=e.length;if(0===i)throw new TypeError(`Invalid prefix length ${i}`);const s=i+7+n.length;if(!1!==r&&s>r)throw new TypeError(`Length ${s} exceeds limit ${r}`);const o=e.toLowerCase(),a=Li(o,n,t);return`${o}1${Ci.encode(n)}${a}`}function a(e,n=90){pi("bech32.decode input",e);const r=e.length;if(r<8||!1!==n&&r>n)throw new TypeError(`invalid string length: ${r} (${e}). Expected (8..${n})`);const i=e.toLowerCase();if(e!==i&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const s=i.lastIndexOf("1");if(0===s||-1===s)throw new Error('Letter "1" must be present between prefix and data only');const o=i.slice(0,s),a=i.slice(s+1);if(a.length<6)throw new Error("Data must be at least 6 characters long");const u=Ci.decode(a).slice(0,-6),c=Li(o,u,t);if(!a.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:o,words:u}}return{encode:o,decode:a,encodeFromBytes:function(e,t){return o(e,i(t))},decodeToBytes:function(e){const{prefix:t,words:n}=a(e,!1);return{prefix:t,words:n,bytes:r(n)}},decodeUnsafe:Pi(a),fromWords:r,fromWordsUnsafe:s,toWords:i}}const ji=zi("bech32"),Hi=zi("bech32m"),Di={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},Fi=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)()?{encode:e=>(hi(e),e.toHex()),decode:e=>(pi("hex",e),Uint8Array.fromHex(e))}:_i(Ai(4),vi("0123456789abcdef"),bi(""),(li(Vi=e=>{if("string"!=typeof e||e.length%2!=0)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}),{encode:e=>e,decode:e=>Vi(e)}));var Vi,Zi,Ki,Wi,qi,Mi;function Gi(e){if("string"!=typeof e||0===e.length)throw new Error(`invalid prefix: ${String(e)}`)}function Yi(e){if(!Array.isArray(e)||!e.every(e=>"number"==typeof e))throw new Error(`invalid words: ${String(e)}`)}!function(e){e.encode=e=>(b.is_uint(e),$i(ee).encode(e)),e.decode=e=>(b.is_base58(e),$i(ee).decode(e))}(Zi||(Zi={})),function(e){e.encode=e=>(b.is_uint(e),Ti.encode(e)),e.decode=e=>(b.is_base64(e),Ti.decode(e))}(Ki||(Ki={})),function(e){e.encode=e=>(b.is_uint(e),Ii.encode(e)),e.decode=e=>(b.is_b64url(e),Ii.decode(e))}(Wi||(Wi={})),function(e){e.to_words=ji.toWords,e.to_bytes=ji.fromWords,e.encode=(e,t,n=!1)=>(Gi(e),Yi(t),ji.encode(e,t,n)),e.decode=(e,t=!1)=>(b.is_bech32(e),ji.decode(e,t))}(qi||(qi={})),function(e){e.to_words=Hi.toWords,e.to_bytes=Hi.fromWords,e.encode=(e,t,n=!1)=>(Gi(e),Yi(t),Hi.encode(e,t,n)),e.decode=(e,t=!1)=>(b.is_bech32(e),Hi.decode(e,t))}(Mi||(Mi={}));const Qi={TXID:"00".repeat(32),VOUT:4294967295},Ji={LOCKTIME:0,SEQUENCE:4294967295,VERSION:2},Xi=[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],es={p2pkh:/^76a914[0-9a-f]{40}88ac$/i,p2sh:/^a914[0-9a-f]{40}87$/i,p2wpkh:/^0014[0-9a-f]{40}$/i,p2wsh:/^0020[0-9a-f]{64}$/i,p2tr:/^5120[0-9a-f]{64}$/i,opreturn:/^6a[0-9a-f]{2,}$/i},ts=[1,2,3,129,130,131],ns=[0,...ts];var rs=Object.freeze({__proto__:null,COINBASE:Qi,DEFAULT:Ji,LOCK_SCRIPT_REGEX:es,SCRIPT_INT_KEY:"",SIGHASH_DEFAULT:1,SIGHASH_SEGWIT:ts,SIGHASH_TAPROOT:ns,TAPLEAF_DEFAULT_VERSION:192,TAPLEAF_VERSIONS:Xi,TX_SIZE:{GLOBAL_BASE:8,GLOBAL_WIT:10,TXIN_BASE:40,TXOUT_BASE:8}});const is={prevouts:[],segwit:!0};function ss(e,t={}){const n={...is,...t};b.is_bytes(e,"txbytes must be hex or a unit array");const r=new y(e),i=function(e){return e.read(4).reverse().to_num()}(r),s=!!n.segwit&&function(e){const[t,n]=[...e.peek(2)];if(0===t){if(e.read(2),1===n)return!0;throw new Error(`Invalid witness flag: ${n}`)}return!1}(r),o=function(e,t){const n=[],r=e.varint();for(let i=0;i<r;i++){const r=os(e,t.at(i));n.push(r)}return n}(r,n.prevouts),a=function(e){const t=[],n=e.varint();for(let r=0;r<n;r++)try{t.push(as(e))}catch(e){throw new Error(`failed to decode output: ${r}: ${_(e)}`)}return t}(r);if(s)for(const e of o)e.witness=us(r);const u=function(e){return e.read(4).reverse().to_num()}(r);return{version:i,vin:o,vout:a,locktime:u}}function os(e,t=null){const n=e.read(32).reverse().hex,r=e.read(4).reverse().num,i=cs(e,!0),s=e.read(4).reverse().num,o=[];return n===Qi.TXID&&r===Qi.VOUT?{coinbase:i,prevout:null,script_sig:null,sequence:s,txid:n,vout:r,witness:o}:{coinbase:null,prevout:t,script_sig:i,sequence:s,txid:n,vout:r,witness:o}}function as(e){const t=e.read(8).reverse().big,n=cs(e,!0);return b.exists(n,"failed to decode script_pk"),{value:t,script_pk:n}}function us(e){const t=[],n=e.varint();for(let r=0;r<n;r++){const n=cs(e,!0);if(null===n)throw new Error("failed to decode witness element: "+r);t.push(n)}return t}function cs(e,t){const n=!0===t?e.varint("le"):e.size;return n>0?e.read(n).hex:null}const ds=qr([Kr(ci),ci]),hs=Wr({pubkey:ci,leaves:ds.array().optional(),target:ci.optional(),version:Xr.optional()});var fs=Object.freeze({__proto__:null,config:hs,taptree:ds});const ls=Yr.max(2100000000000000n),ps=Wr({value:ls,script_pk:ei}),gs=Wr({coinbase:ei.nullable(),txid:oi,vout:Xr,prevout:ps.nullable(),script_sig:ei.nullable(),sequence:Xr,witness:Kr(ei)}),ms=Wr({version:Xr,vin:Kr(gs),vout:Kr(ps),locktime:Xr}),ys=gs.extend({coinbase:ei.nullable().optional(),prevout:ps.nullable().optional(),script_sig:ei.nullable().optional(),sequence:Xr.optional(),witness:Kr(ei).optional()}),ws=Wr({version:Xr.optional(),vin:Kr(ys).default([]),vout:Kr(ps).default([]),locktime:Xr.optional()});var _s=Object.freeze({__proto__:null,sats:ls,tx_data:ms,tx_input:gs,tx_output:ps,tx_template:ws,vin_template:ys}),vs=Object.freeze({__proto__:null,taproot:fs,tx:_s});function bs(e){ws.parse(e)}function Es(e){ps.parse(e)}function xs(e){ys.parse(e)}function Ss(e){xs(e),b.exists(e.coinbase,"coinbase is required");const t=e.coinbase,n=e.sequence??Ji.SEQUENCE,r=Qi.TXID,i=Qi.VOUT;return{coinbase:t,prevout:null,script_sig:null,sequence:n,witness:e.witness??[],txid:r,vout:i}}function ks(e){xs(e),b.exists(e.prevout,"prevout is required");const t=e.prevout,n=e.script_sig??null,r=e.sequence??Ji.SEQUENCE,i=e.witness??[];return{...e,coinbase:null,prevout:t,script_sig:n,sequence:r,witness:i}}function Os(e){xs(e),b.exists(e.txid,"txid is required"),b.exists(e.vout,"vout is required");const t=e.coinbase??null,n=e.prevout??null,r=e.script_sig??null,i=e.sequence??Ji.SEQUENCE,s=e.witness??[];return null!==t?Ss(e):null!==n?ks(e):{...e,coinbase:t,prevout:n,script_sig:r,sequence:i,witness:s}}function As(e){Es(e);const{script_pk:t,value:n}=e;return{script_pk:t,value:BigInt(n)}}function Ps(e){bs(e);const{vin:t=[],vout:n=[]}=e,r=e.locktime??Ji.LOCKTIME,i=e.version??Ji.VERSION;return{locktime:r,vin:t.map(e=>Os(e)),vout:n.map(e=>As(e)),version:i}}function Ts(e){return"string"==typeof e?ss(e):(bs(e),Ps(e))}function Is(e,t){let{txindex:n,txinput:r}=t??{};if(void 0!==n){if(n>=e.vin.length)throw new Error("Input index out of bounds: "+String(n));r=e.vin.at(n)}return b.ok(void 0!==r),r}function Ns(e){return 0!==e?m.num(e,1).hex:""}const Us={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};function $s(e){if(e>186&&e<255)return"OP_SUCCESS"+String(e);for(const[t,n]of Object.entries(Us))if(n===e)return t;throw new Error("OPCODE not found:"+String(e))}function Cs(e){for(const[t,n]of Object.entries(Us))if(t===e)return Number(n);throw new Error("OPCODE not found:"+e)}function Bs(e){switch(!0){case 0===e:return"opcode";case e>=1&&e<=75:return"varint";case 76===e:return"pushdata1";case 77===e:return"pushdata2";case 78===e:return"pushdata4";case e<=254:return"opcode";default:throw new Error(`Invalid word range: ${e}`)}}function Rs(e){switch(!0){case"number"!=typeof e:return!1;case 0===e:return!0;case[].includes(e):return!1;case 75<e&&e<254:return!0;default:return!1}}const Ls=520;function zs(e,t=!1){if(0===e.length)return"00";const n=[];for(const t of e)n.push(js(t));const r=m.join(n);return t?r.prepend(m.varint(r.length,"le")).hex:r.hex}function js(e){let t;if("string"==typeof e){if(e.startsWith("OP_")){const t=Cs(e);return m.num(t,1)}t=m.is_hex(e)?m.hex(e):m.str(e)}else if("number"==typeof e)t=m.num(e);else{if(!(e instanceof Uint8Array))throw new Error("invalid word type:"+typeof e);t=new m(e)}if(1===t.length&&t[0]<=16)0!==t[0]&&(t[0]+=80);else if(t.length>Ls){let e;e=Hs(t),e=e.map(e=>Ds(e)),t=m.join(e)}else t=Ds(t);return t}function Hs(e){const t=[],n=new y(e);for(;n.size>Ls;)t.push(n.read(Ls));return t.push(n.read(n.size)),t}function Ds(e){const t=Fs(e.length);return m.join([t,e])}function Fs(e){const t=m.num(76,1),n=m.num(77,1);switch(!0){case e<=75:return m.num(e);case e>75&&e<256:return m.join([t,m.num(e,1,"le")]);case e>=256&&e<=Ls:return m.join([n,m.num(e,2,"le")]);default:throw new Error("Invalid word size:"+e.toString())}}function Vs(e){const t=new y(e),n=[],r=t.size;let i,s,o,a=0;for(;a<r;)switch(i=t.read(1).num,s=Bs(i),a++,s){case"varint":n.push(t.read(i).hex),a+=i;break;case"pushdata1":o=t.read(1).reverse().num,n.push(t.read(o).hex),a+=o+1;break;case"pushdata2":o=t.read(2).reverse().num,n.push(t.read(o).hex),a+=o+2;break;case"pushdata4":o=t.read(4).reverse().num,n.push(t.read(o).hex),a+=o+4;break;case"opcode":if(!Rs(i))throw new Error(`Invalid OPCODE: ${i}`);n.push($s(i));break;default:throw new Error(`Word type undefined: ${i}`)}return n}function Zs(e){try{return Vs(e).length>0}catch{return!1}}function Ks(e){return m.bytes(e).prefix_varint("le").hex}function Ws(e){return[...("string"==typeof e?e:m.bytes(e).hex).matchAll(/20([0-9a-f]{64})(ac|ad|ba)/gi)].map(e=>e[1])}var qs;!function(e){e.prefix_size=Ks,e.decode=Vs,e.encode=zs,e.is_valid=Zs,e.get_pubkeys=Ws,e.OPCODES=Us}(qs||(qs={}));var Ms=Object.freeze({__proto__:null,OPCODE_MAP:Us,get ScriptUtil(){return qs},decode_script:Vs,encode_script:zs,encode_script_word:js,get_asm_code:Cs,get_op_code:$s,get_op_type:Bs,get_size_varint:Fs,is_valid_op:Rs,is_valid_script:Zs,parse_script_pubkeys:Ws,prefix_script_size:Ks,prefix_word_size:Ds,split_script_word:Hs});function Gs(e,t=!0){const n=Ts(e),{version:r,vin:i,vout:s,locktime:o}=n,a=[Ys(r)];if(t&&a.push(m.hex("0001")),a.push(eo(i)),a.push(ro(s)),t)for(const e of i)a.push(so(e.witness));return a.push(oo(o)),m.join(a)}function Ys(e){return m.num(e,4).reverse()}function Qs(e){return m.hex(e,32).reverse()}function Js(e){return m.num(e,4).reverse()}function Xs(e){return m.num(e,4).reverse()}function eo(e){const t=[m.varint(e.length,"le")];for(const n of e)t.push(to(n));return m.join(t)}function to(e){return null!==e.coinbase?m.join([Qs(Qi.TXID),Js(Qi.VOUT),ao(e.coinbase),Xs(e.sequence)]):m.join([Qs(e.txid),Js(e.vout),ao(e.script_sig),Xs(e.sequence)])}function no(e){return m.big(e,8).reverse()}function ro(e){const t=[m.varint(e.length,"le")];for(const n of e)t.push(io(n));return m.join(t)}function io(e){const{value:t,script_pk:n}=e;return m.join([no(t),ao(n)])}function so(e){const t=[m.varint(e.length)];for(const n of e)t.push(ao(n));return m.join(t)}function oo(e){return m.num(e,4).reverse()}function ao(e){return null!==e?(b.is_hex(e),m.hex(e).prefix_varint("le")):m.hex("00")}function uo(e){return e.startsWith("6a")}function co(e){for(const[t,n]of Object.entries(es))if(n.test(e))return t;return"unknown"}function ho(e){switch(e.slice(0,4)){case"0014":return 0;case"5120":return 1;default:return null}}function fo(e){return sn(Gs(Ts(e),!1)).reverse().hex}function lo(e){return sn(Gs(Ts(e),!0)).reverse().hex}function po(e){const t=Ts(e),n=t.vin.reduce((e,t)=>e+(t.prevout?.value??0n),0n),r=t.vout.reduce((e,t)=>e+t.value,0n);return{fees:n>r?n-r:0n,vin:n,vout:r}}function go(e){const t=Ts(e),n=Gs(t,!1).length,r=Gs(t,!0).length,i=3*n+r,s=i%4>0?1:0;return{base:n,total:r,vsize:Math.floor(i/4)+s,weight:i}}function mo(e){return to(e).length}function yo(e){return io(e).length}var wo=Object.freeze({__proto__:null,assert_has_prevouts:function(e){if(e.some(e=>null===e.prevout))throw new Error("transaction missing prevouts")},assert_tx_data:function(e){ms.parse(e)},assert_tx_input:function(e){gs.parse(e)},assert_tx_output:Es,assert_tx_template:bs,assert_vin_template:xs,create_coinbase_input:Ss,create_spend_input:ks,create_tx:Ps,create_tx_input:Os,create_tx_output:As,decode_tx:ss,encode_script_data:ao,encode_tx:Gs,encode_tx_inputs:eo,encode_tx_locktime:oo,encode_tx_outputs:ro,encode_tx_version:Ys,encode_tx_vout:io,encode_txin_sequence:Xs,encode_txin_txid:Qs,encode_txin_vout:Js,encode_vin:to,encode_vin_witness:so,encode_vout_value:no,get_segwit_size:function(e){return 2+e.filter(e=>e.witness.length>0).map(e=>e.witness).reduce((e,t)=>e+so(t).length,0)},get_tx_value:po,get_txhash:lo,get_txid:fo,get_txin_size:mo,get_txout_size:yo,get_txsize:go,get_vin_size:function(e){return eo(e).length},get_vout_info:function(e){return{type:co(e.script_pk),version:ho(e.script_pk)}},get_vout_size:function(e){return ro(e).length},get_vout_type:co,get_vout_version:ho,get_vsize:function(e){const t=m.bytes(e).length,n=t%4>0?1:0;return Math.floor(t/4)+n},is_return_script:uo,parse_tx:Ts,read_script:cs});function _o(e,t={}){const{sigflag:n=1,txindex:r}=t,i=Ts(e),s=!(128&~n),o=n%128;if(!ts.includes(o))throw new Error("Invalid hash type: "+String(n));const{version:a,vin:u,vout:c,locktime:d}=i,h=Is(i,t),{txid:f,vout:l,prevout:p,sequence:g}=h,{value:y}=p??{};if(void 0===y)throw new Error("Prevout value is empty!");let{pubkey:w,script:_}=t;if(void 0===_&&void 0!==w){const e=nn(w).hex;_=`76a914${String(e)}88ac`}if(void 0===_)throw new Error("No pubkey / script has been set!");if(Vs(_).includes("OP_CODESEPARATOR"))throw new Error("This library does not currently support the use of OP_CODESEPARATOR in segwit scripts.");const v=[Ys(a),vo(u,s),bo(u,o,s),Qs(f),Js(l),Ks(_),no(y),Xs(g),Eo(c,o,r),oo(d),m.num(n,4).reverse()];return sn(m.join(v))}function vo(e,t){if(!0===t)return m.num(0,32);const n=[];for(const{txid:t,vout:r}of e)n.push(Qs(t)),n.push(Js(r));return sn(m.join(n))}function bo(e,t,n){if(n||1!==t)return m.num(0,32);const r=[];for(const{sequence:t}of e)r.push(Xs(t));return sn(m.join(r))}function Eo(e,t,n){const r=[];if(1===t){for(const{value:t,script_pk:n}of e)r.push(no(t)),r.push(Ks(n));return sn(m.join(r))}if(3===t&&(b.ok(void 0!==n),n<e.length)){const{value:t,script_pk:i}=e[n];return r.push(no(t)),r.push(Ks(i)),sn(m.join(r))}return m.num(0,32)}function xo(e,t=192){return So(Ks(e),t)}function So(e,t=192){return on("TapLeaf",Oo(t),e)}function ko(e,t){return t<e&&([e,t]=[t,e]),on("TapBranch",e,t)}function Oo(e=192){return 254&e}function Ao(e,t=new Uint8Array){return b.size(e,32),on("TapTweak",e,t)}function Po(e,t={}){const{script:n,txindex:r,sigflag:i=0,extflag:s=0,key_version:o=0,separator_pos:a=4294967295}=t,u=Ts(e),{version:c,vin:d,vout:h,locktime:f}=u,l=Is(u,t),{txid:p,vout:g,sequence:y,witness:w=[]}=l;if(!ns.includes(i))throw new Error("Invalid hash type: "+String(i));if(s<0||s>127)throw new Error("Extention flag out of range: "+String(s));let{extension:_}=t;void 0!==n&&(_=xo(n).hex);const v=!(128&~i),E=function(e){if(void 0===e)return;if(e.length<2)return;const t=e.at(-1);if("string"==typeof t&&t.startsWith("50")){return rn(m.hex(t).prefix_varint("be"))}return}(w),x=2*(s+(void 0!==_?1:0))+(void 0!==E?1:0),S=[on("TapSighash"),m.num(0,1),m.num(i,1),Ys(c),oo(f)];if(!v){const e=d.map(e=>Bo(e));S.push(To(d),No(e),Uo(e),Io(d))}if(((3&i)<2||(3&i)>3)&&S.push($o(h)),S.push(m.num(x,1)),v){const{value:e,script_pk:t}=Bo(l);S.push(Qs(p),Js(g),no(e),Ks(t),Xs(y))}else b.ok("number"==typeof r),S.push(m.num(r,4).reverse());return void 0!==E&&S.push(E),3&~i||(b.ok("number"==typeof r),S.push(Co(h[r]))),void 0!==_&&S.push(m.bytes(_),m.num(o),m.num(a,4)),rn(m.join(S))}function To(e){const t=[];for(const{txid:n,vout:r}of e)t.push(Qs(n)),t.push(Js(r));return rn(m.join(t))}function Io(e){const t=[];for(const{sequence:n}of e)t.push(Xs(n));return rn(m.join(t))}function No(e){const t=[];for(const{value:n}of e)t.push(no(n));return rn(m.join(t))}function Uo(e){const t=[];for(const{script_pk:n}of e)t.push(Ks(n));return rn(m.join(t))}function $o(e){const t=[];for(const{value:n,script_pk:r}of e)t.push(no(n)),t.push(Ks(r));return rn(m.join(t))}function Co(e){return rn(no(e.value),Ks(e.script_pk))}function Bo(e){if(null===e.prevout)throw new Error("Prevout data missing for input: "+String(e.txid));return e.prevout}function Ro(e,t,n){return Lt(e,_o(Ts(t),n)).hex+Ns(n.sigflag??1)}function Lo(e,t,n){return zt(e,Po(Ts(t),n)).hex+Ns(n.sigflag??0)}const zo=5e8;var jo,Ho;function Do(e){switch(e.type){case"timelock":return b.ok(e.stamp>=zo,"Invalid timestamp"),e.stamp;case"heightlock":return b.ok(e.height>0,"height must be greater than 0"),b.ok(e.height<zo,"invalid block height"),e.height;default:throw new Error("Invalid locktime type")}}function Fo(e){return isNaN(e)||e<=0?null:e<zo?{type:"heightlock",height:e}:{type:"timelock",stamp:e}}function Vo(e,t=0){return`${e}i${t}`}function Zo(e){Wo(e);const[t,n]=e.split("i");return{txid:t,order:parseInt(n)}}function Ko(e){return null!==e.match(/^[a-f0-9]{64}i\d+$/)}function Wo(e){if(!Ko(e))throw new Error(`invalid inscription id: ${e}`)}function qo(e,t){return`${e}:${t}`}function Mo(e){Yo(e);const[t,n]=e.split(":");return{block_height:parseInt(t),block_index:parseInt(n)}}function Go(e){return null!==e.match(/^\d+:\d+$/)}function Yo(e){if(!Go(e))throw new Error(`invalid rune id: ${e}`)}function Qo(e,t){return`${e}:${t}`}function Jo(e){ea(e);const[t,n]=e.split(":");return{txid:t,vout:parseInt(n)}}function Xo(e){return null!==e.match(/^[a-f0-9]{64}:[0-9]+$/)}function ea(e){if(!Xo(e))throw new Error(`invalid outpoint: ${e}`)}!function(e){e.encode=Do,e.decode=Fo}(jo||(jo={})),function(e){e.outpoint={encode:Qo,decode:Jo,verify:Xo,assert:ea},e.record_id={encode:Vo,decode:Zo,verify:Ko,assert:Wo},e.rune_id={encode:qo,decode:Mo,verify:Go,assert:Yo}}(Ho||(Ho={}));const ta=BigInt(0),na=BigInt(1),ra=BigInt(26);var ia;function sa(e){const t=function(e){const t=Vs(e),n=t.findIndex(e=>"OP_0"===e);b.ok(-1!==n,"inscription envelope not found");const r=[];for(let e=n;e<t.length;e++){b.ok("OP_IF"===t[e+1],"OP_IF missing from envelope"),b.ok("6f7264"===t[e+2],"magic bytes missing from envelope");const n=t.findIndex(e=>"OP_ENDIF"===e);b.ok(-1!==n,"inscription envelope missing END_IF statement");const i=t.slice(e+3,n);r.push(i),e+=n}return r}(e);return t.map(ua)}function oa(e){return e.map(aa).join("")}function aa(e){let t=["OP_0","OP_IF","6f7264"];if("string"==typeof e.delegate){const n=ca(e.delegate);t.push("OP_11",n)}if("string"==typeof e.ref&&t.push("OP_WITHIN",e.ref),"string"==typeof e.parent){const n=ca(e.parent);t.push("OP_3",n)}if("number"==typeof e.opcode){const n=ha(e.opcode);t.push("OP_NOP",n)}if("number"==typeof e.pointer){const n=ha(e.pointer);t.push("OP_2",n)}if("string"==typeof e.rune){const n=function(e){const t=e.toUpperCase();let n=ta;for(const e of t)e>="A"&&e<="Z"&&(n=n*ra+BigInt(e.charCodeAt(0)-("A".charCodeAt(0)-1)));return n-=na,m.big(n).reverse().hex}(e.rune);t.push("OP_13",n)}if("string"==typeof e.mimetype){const n=function(e){return m.str(e).hex}(e.mimetype);t.push("OP_1",n)}if("string"==typeof e.content){const n=function(e){const t=m.is_hex(e)?m.hex(e):m.str(e),n=new y(t),r=[];for(;n.size>0;)if(n.size>520){const e=n.read(520);r.push(e.hex)}else{const e=n.read(n.size);r.push(e.hex)}return r}(e.content);t.push("OP_0",...n)}return t.push("OP_ENDIF"),zs(t)}function ua(e){const t={};for(let n=0;n<e.length;n++)switch(e[n]){case"OP_1":t.mimetype=la(e[n+1]),n+=1;break;case"OP_2":t.pointer=fa(e[n+1]),n+=1;break;case"OP_3":t.parent=da(e[n+1]),n+=1;break;case"OP_11":t.delegate=da(e[n+1]),n+=1;break;case"OP_13":t.rune=ga(e[n+1]),n+=1;break;case"OP_WITHIN":t.ref=e[n+1],n+=1;break;case"OP_NOP":t.opcode=fa(e[n+1]),n+=1;break;case"OP_0":return t.content=pa(e.slice(n+1)),t}return t}function ca(e){b.ok(e.includes("i"),"identifier must include an index");const t=e.split("i"),n=m.hex(t[0]),r=Number(t[1]),i=n.reverse().hex;return 0!==r?i+m.num(r).hex:i}function da(e){const t=m.hex(e),n=t.at(-1)??0;return t.slice(0,-1).reverse().hex+"i"+String(n)}function ha(e){return m.num(e).reverse().hex}function fa(e){return m.hex(e).reverse().num}function la(e){return m.hex(e).str}function pa(e,t="hex"){const n=m.join(e);return"hex"===t?n.hex:n.str}function ga(e){let t=m.hex(e).reverse().big;t+=na;let n="";for(;t>ta;){const e=t%ra;if(e===ta)n="Z"+n,t=t/ra-na;else{const r=Number(e)+"A".charCodeAt(0)-1;n=String.fromCharCode(r)+n,t/=ra}}return n}!function(e){e.encode=oa,e.decode=sa}(ia||(ia={}));const ma=4194304,ya=65535,wa=65535;var _a;function va(e){if("height"===e.mode){return(function(e){if(void 0===e||!Number.isInteger(e)||e<0||e>wa)throw new Error("Heightlock value must be an integer between 0 and 65535");return e}(e.height)&ya)>>>0}if("stamp"===e.mode){const t=function(e){if(void 0===e||!Number.isInteger(e))throw new Error("timestamp must be a number");const t=Math.floor(e/512);if(!Number.isInteger(t)||t<0||t>wa)throw new Error("timelock value must be an integer between 0 and 65535 (in 512-second increments)");return t}(e.stamp);return(ma|t&ya)>>>0}throw new Error("invalid timelock mode: "+e.mode)}function ba(e){const t=function(e){const t="string"==typeof e?parseInt(e,16):e;if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`invalid sequence value: ${t}`);return t}(e);if(2147483648&t)return null;const n=t&ya;if(t&ma){const e=512*n;if(e>4294967295)throw new Error("Decoded timestamp exceeds 32-bit limit");return{mode:"stamp",stamp:e}}if(n>wa)throw new Error("Decoded height exceeds maximum");return{mode:"height",height:n}}!function(e){e.encode=va,e.decode=ba}(_a||(_a={}));var Ea=Object.freeze({__proto__:null,get LocktimeUtil(){return jo},get RefEncoder(){return Ho},get ScribeEncoder(){return ia},get SequenceUtil(){return _a},decode_inscription:sa,decode_locktime:Fo,decode_sequence:ba,encode_inscription:oa,encode_locktime:Do,encode_sequence:va});class xa{constructor(e){this._txout=e}get data(){return{script_pk:this.script_pk,size:this.size,type:this.type,value:this.value,version:this.version}}get script_pk(){return{hex:this._txout.script_pk,asm:Vs(this._txout.script_pk)}}get size(){return yo(this._txout)}get type(){return co(this._txout.script_pk)}get value(){return this._txout.value}get version(){return ho(this._txout.script_pk)}toJSON(){return this.data}toString(){return JSON.stringify(this.data)}}function Sa(e){const t=e.map(e=>m.bytes(e)),n=e.map(e=>m.bytes(e).hex),r=function(e){let t=e.at(-1);return e.length>1&&t instanceof Uint8Array&&80===t[0]?new m(t).hex:null}(t);null!==r&&t.pop();const i=function(e){let t=e.at(-1);return e.length>1&&t instanceof Uint8Array&&t.length>32&&Xi.includes(254&t[0])?new m(t).hex:null}(t);null!==i&&t.pop();const s=function(e,t){let n=e.at(0),r=e.at(1),i=e.at(-1);return null!==t&&void 0!==i?"p2tr-ts":2===e.length&&void 0!==n&&void 0!==r&&n.length>=64&&33===r.length?"p2w-pkh":1===e.length&&void 0!==n&&64===n.length?"p2tr-pk":e.length>1&&void 0!==i&&Zs(i)?"p2w-sh":"unknown"}(t,i),o=function(e){return e.startsWith("p2tr")?1:e.startsWith("p2w")?0:null}(s),a=function(e,t){let n;switch(t){case"p2tr-ts":n=e.at(-1);case"p2w-sh":n=e.at(-1)}return void 0!==n?new m(n).hex:null}(t,s);null!==a&&t.pop();return{annex:r,cblock:i,params:t.map(e=>e.hex),script:a,stack:n,type:s,version:o}}function ka(e){const t=e.map(e=>m.bytes(e)).reduce((e,t)=>e+t.length,0);return{total:t,vsize:Math.ceil(1+t/4)}}var Oa=Object.freeze({__proto__:null,get_witness_size:ka,parse_witness:Sa});class Aa{constructor(e){this._elems=e.map(e=>m.bytes(e)),this._data=Sa(this._elems),this._size=ka(this._elems)}get annex(){return this._data.annex}get cblock(){return this._data.cblock}get data(){return this._data}get params(){return this._data.params}get script(){return null===this._data.script?null:{hex:this._data.script,asm:Vs(this._data.script)}}get size(){return this._size}get stack(){return this._elems.map(e=>e.hex)}get type(){return this._data.type}get version(){return this._data.version}_update(){this._data=Sa(this._elems),this._size=ka(this._elems)}add(e){this._elems.push(m.bytes(e)),this._update()}insert(e,t){b.ok(e>=0&&e<=this._elems.length,"index out of bounds"),e===this._elems.length?this._elems.push(m.bytes(t)):this._elems.splice(e,0,m.bytes(t)),this._update()}remove(e){this._elems.splice(e,1),this._update()}toJSON(){return this.data}toString(){return JSON.stringify(this.data)}}class Pa{constructor(e){this._txin=e}get coinbase(){return this._txin.coinbase}get data(){return{coinbase:this.coinbase,prevout:this.prevout?.data??null,script_sig:this.script_sig,sequence:this.sequence,size:this.size,txid:this.txid,vout:this.vout,witness:this.witness?.data??null}}get has_prevout(){return null!==this._txin.prevout}get is_coinbase(){return null!==this._txin.coinbase}get prevout(){return this._txin.prevout?new xa(this._txin.prevout):null}get script_sig(){return null===this._txin.script_sig?null:{asm:Vs(this._txin.script_sig),hex:this._txin.script_sig}}get sequence(){return{hex:Xs(this._txin.sequence).hex,data:_a.decode(this._txin.sequence),value:this._txin.sequence}}get size(){return mo(this._txin)}get txid(){return this._txin.txid}get vout(){return this._txin.vout}get witness(){return this._txin.witness.length>0?new Aa(this._txin.witness):null}toJSON(){return this.data}toString(){return JSON.stringify(this.data)}}const Ta={base58:/^[13mn2][a-km-zA-HJ-NP-Z1-9]{25,34}$/,bech32:/^(bc|tb|bcrt)1q[ac-hj-np-z02-9]{6,87}$/,bech32m:/^(bc|tb|bcrt)1p[ac-hj-np-z02-9]{6,87}$/},Ia=0,Na=1;function Ua(e){const t=function(e){for(const[t,n]of Object.entries(Ta))if(n.test(e))return t;return null}(e);if(null===t)throw new Error("unrecognized address format: "+t);if("base58"===t)return function(e){const t=Zi.decode(e),n=t.slice(1),r=t[0];return{data:n,format:"base58",version:r}}(e);if("bech32"===t)return function(e){const{prefix:t,words:n}=qi.decode(e),[r,...i]=n;b.ok(r===Ia,"bech32 version mismatch");return{data:qi.to_bytes(i),format:"bech32",prefix:t,version:r}}(e);if("bech32m"===t)return function(e){const{prefix:t,words:n}=Mi.decode(e),[r,...i]=n;b.ok(r===Na,"bech32m version mismatch");return{data:Mi.to_bytes(i),format:"bech32m",prefix:t,version:r}}(e);throw new Error("unable to find a matching address configuration")}function $a(e){if("base58"===e.format)return function(e){b.ok("base58"===e.format,"encoding mismatch"),b.exists(e.version,"must specify a version");const t=m.join([e.version,e.data]);return Zi.encode(t)}(e);if("bech32"===e.format)return function(e){b.ok("bech32"===e.format,"encoding mismatch"),b.exists(e.prefix,"prefix is required");const t=m.bytes(e.data),n=qi.to_words(t);return qi.encode(e.prefix,[Ia,...n])}(e);if("bech32m"===e.format)return function(e){b.ok("bech32m"===e.format,"encoding mismatch"),b.exists(e.prefix,"prefix is required");const t=m.bytes(e.data),n=Mi.to_words(t);return Mi.encode(e.prefix,[Na,...n])}(e);throw new Error("unrecognized encoding format: "+e.format)}const Ca=[["1","p2pkh","main",20,"base58",0],["3","p2sh","main",20,"base58",5],["m","p2pkh","testnet",20,"base58",111],["n","p2pkh","testnet",20,"base58",111],["2","p2sh","testnet",20,"base58",196],["m","p2pkh","regtest",20,"base58",111],["n","p2pkh","regtest",20,"base58",111],["2","p2sh","regtest",20,"base58",196],["bc","p2w-pkh","main",20,"bech32",0],["tb","p2w-pkh","testnet",20,"bech32",0],["bcrt","p2w-pkh","regtest",20,"bech32",0],["bc","p2w-sh","main",32,"bech32",0],["tb","p2w-sh","testnet",32,"bech32",0],["bcrt","p2w-sh","regtest",32,"bech32",0],["bc","p2tr","main",32,"bech32m",1],["tb","p2tr","testnet",32,"bech32m",1],["bcrt","p2tr","regtest",32,"bech32m",1]];function Ba(e,t){for(const[n,r,i,s,o,a]of Ca)if(r===t&&i===e)return{type:r,prefix:n,network:i,size:s,format:o,version:a};return null}function Ra(e){const t=function(e){const t=Ua(e);for(const[n,r,i,s,o,a]of Ca){if(o!==t.format)continue;if(s!==t.data.length)continue;if(a!==t.version)continue;if(t.prefix){if(n!==t.prefix)continue}else if(!e.startsWith(n))continue;const u=m.uint(t.data).hex;return{data:t.data,hex:u,type:r,prefix:n,network:i,size:s,format:o,version:a}}throw new Error("address configuration is invalid")}(e),n=function(e,t){switch(t){case"p2pkh":return function(e){return{script_hex:"76a914"+e+"88ac",script_asm:["OP_DUP","OP_HASH160",e,"OP_EQUALVERIFY","OP_CHECKSIG"]}}(e);case"p2sh":return function(e){return{script_hex:"a914"+e+"87",script_asm:["OP_HASH160",e,"OP_EQUAL"]}}(e);case"p2w-pkh":return function(e){return{script_hex:"0014"+e,script_asm:["OP_0",e]}}(e);case"p2w-sh":return function(e){return{script_hex:"0020"+e,script_asm:["OP_0",e]}}(e);case"p2tr":return function(e){return{script_hex:"5120"+e,script_asm:["OP_1",e]}}(e);default:throw new Error("unrecognized script type: "+t)}}(t.hex,t.type);return{...t,...n}}const La="p2pkh";var za;function ja(e,t="main"){return Ha(nn(m.bytes(e)),t)}function Ha(e,t="main"){const n=m.bytes(e),r=Ba(t,La);return b.exists(r,`unrecognized address config: ${La} on ${t}`),b.size(n,r.size,`invalid payload size: ${n.length} !== ${r.size}`),$a({data:n,format:"base58",version:r.version})}function Da(e){const t=Ra(e);return b.ok("p2pkh"===t.type,`address type mismatch: ${t.type} !== ${La}`),t}!function(e){e.create=ja,e.encode=Ha,e.decode=Da}(za||(za={}));const Fa="p2sh";var Va;function Za(e,t="main"){return Ka(nn(m.bytes(e)),t)}function Ka(e,t="main"){const n=m.bytes(e),r=Ba(t,Fa);return b.exists(r,`unrecognized address config: ${Fa} on ${t}`),b.size(n,r.size,`invalid payload size: ${n.length} !== ${r.size}`),$a({data:n,format:"base58",version:r.version})}function Wa(e){const t=Ra(e);return b.ok("p2sh"===t.type,`address type mismatch: ${t.type} !== ${Fa}`),t}!function(e){e.create=Za,e.encode=Ka,e.decode=Wa}(Va||(Va={}));const qa="p2w-pkh";var Ma;function Ga(e,t="main"){const n=m.bytes(e);b.size(n,33,`invalid payload size: ${n.length} !== 33`);return Ya(nn(n),t)}function Ya(e,t="main"){const n=m.bytes(e),r=Ba(t,qa);return b.exists(r,`unrecognized address config: ${qa} on ${t}`),b.size(n,r.size,`invalid payload size: ${n.length} !== ${r.size}`),$a({data:n,format:"bech32",prefix:r.prefix})}function Qa(e){const t=Ra(e);return b.ok("p2w-pkh"===t.type,`address type mismatch: ${t.type} !== ${qa}`),t}!function(e){e.create=Ga,e.encode=Ya,e.decode=Qa}(Ma||(Ma={}));const Ja="p2w-sh";var Xa;function eu(e,t="main"){return tu(rn(m.bytes(e)),t)}function tu(e,t="main"){const n=m.bytes(e),r=Ba(t,Ja);return b.exists(r,`unrecognized address config: ${Ja} on ${t}`),b.size(n,r.size,`invalid payload size: ${n.length} !== ${r.size}`),$a({data:n,format:"bech32",prefix:r.prefix})}function nu(e){const t=Ra(e);return b.ok("p2w-sh"===t.type,`address type mismatch: ${t.type} !== ${Ja}`),t}!function(e){e.create=eu,e.encode=tu,e.decode=nu}(Xa||(Xa={}));const ru="p2tr";var iu,su;function ou(e,t="main"){const n=m.bytes(e),r=Ba(t,ru);return b.exists(r,`unrecognized address config: ${ru} on ${t}`),b.size(n,r.size,`invalid payload size: ${n.length} !== ${r.size}`),$a({data:n,format:"bech32m",prefix:r.prefix})}function au(e){const t=Ra(e);return b.ok("p2tr"===t.type,`address type mismatch: ${t.type} !== ${ru}`),t}!function(e){e.encode=ou,e.decode=au}(iu||(iu={})),function(e){e.P2PKH=za,e.P2SH=Va,e.P2WPKH=Ma,e.P2WSH=Xa,e.P2TR=iu,e.parse=Ra}(su||(su={}));var uu=Object.freeze({__proto__:null,get AddressTool(){return su},get P2PKH(){return za},get P2SH(){return Va},get P2TR(){return iu},get P2WPKH(){return Ma},get P2WSH(){return Xa},parse_address:Ra});const cu=new Uint8Array,du=new Uint8Array([0]);function hu(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function fu(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}const lu=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);function pu(e){return"[object Object]"===Object.prototype.toString.call(e)}function gu(e){return Number.isSafeInteger(e)}const mu=hu,yu=fu,wu=function(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];if(!fu(r))throw new Error("Uint8Array expected");t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const i=e[t];n.set(i,r),r+=i.length}return n},_u=e=>{if(null!==e&&"string"!=typeof e&&!Tu(e)&&!fu(e)&&!gu(e))throw new Error(`lengthCoder: expected null | number | Uint8Array | CoderType, got ${e} (${typeof e})`);return{encodeStream(t,n){if(null===e)return;if(Tu(e))return e.encodeStream(t,n);let r;if("number"==typeof e?r=e:"string"==typeof e&&(r=bu.resolve(t.stack,e)),"bigint"==typeof r&&(r=Number(r)),void 0===r||r!==n)throw t.err(`Wrong length: ${r} len=${e} exp=${n} (${typeof n})`)},decodeStream(t){let n;if(Tu(e)?n=Number(e.decodeStream(t)):"number"==typeof e?n=e:"string"==typeof e&&(n=bu.resolve(t.stack,e)),"bigint"==typeof n&&(n=Number(n)),"number"!=typeof n)throw t.err(`Wrong length: ${n}`);return n}}},vu={BITS:32,FULL_MASK:-1>>>0,len:e=>Math.ceil(e/32),create:e=>new Uint32Array(vu.len(e)),clean:e=>e.fill(0),debug:e=>Array.from(e).map(e=>(e>>>0).toString(2).padStart(32,"0")),checkLen:(e,t)=>{if(vu.len(t)!==e.length)throw new Error(`wrong length=${e.length}. Expected: ${vu.len(t)}`)},chunkLen:(e,t,n)=>{if(t<0)throw new Error(`wrong pos=${t}`);if(t+n>e)throw new Error(`wrong range=${t}/${n} of ${e}`)},set:(e,t,n,r=!0)=>!(!r&&0!==(e[t]&n))&&(e[t]|=n,!0),pos:(e,t)=>({chunk:Math.floor((e+t)/32),mask:1<<32-(e+t)%32-1}),indices:(e,t,n=!1)=>{vu.checkLen(e,t);const{FULL_MASK:r,BITS:i}=vu,s=i-t%i,o=s?r>>>s<<s:r,a=[];for(let t=0;t<e.length;t++){let r=e[t];if(n&&(r=~r),t===e.length-1&&(r&=o),0!==r)for(let e=0;e<i;e++){r&1<<i-e-1&&a.push(t*i+e)}}return a},range:e=>{const t=[];let n;for(const r of e)void 0===n||r!==n.pos+n.length?t.push(n={pos:r,length:1}):n.length+=1;return t},rangeDebug:(e,t,n=!1)=>`[${vu.range(vu.indices(e,t,n)).map(e=>`(${e.pos}/${e.length})`).join(", ")}]`,setRange:(e,t,n,r,i=!0)=>{vu.chunkLen(t,n,r);const{FULL_MASK:s,BITS:o}=vu,a=n%o?Math.floor(n/o):void 0,u=n+r,c=u%o?Math.floor(u/o):void 0;if(void 0!==a&&a===c)return vu.set(e,a,s>>>o-r<<o-r-n,i);if(void 0!==a&&!vu.set(e,a,s>>>n%o,i))return!1;const d=void 0!==c?c:u/o;for(let t=void 0!==a?a+1:n/o;t<d;t++)if(!vu.set(e,t,s,i))return!1;return!(void 0!==c&&a!==c&&!vu.set(e,c,s<<o-u%o,i))}},bu={pushObj:(e,t,n)=>{const r={obj:t};e.push(r),n((e,t)=>{r.field=e,t(),r.field=void 0}),e.pop()},path:e=>{const t=[];for(const n of e)void 0!==n.field&&t.push(n.field);return t.join("/")},err:(e,t,n)=>{const r=new Error(`${e}(${bu.path(t)}): ${"string"==typeof n?n:n.message}`);return n instanceof Error&&n.stack&&(r.stack=n.stack),r},resolve:(e,t)=>{const n=t.split("/"),r=e.map(e=>e.obj);let i=0;for(;i<n.length&&".."===n[i];i++)r.pop();let s=r.pop();for(;i<n.length;i++){if(!s||void 0===s[n[i]])return;s=s[n[i]]}return s}};class Eu{constructor(e,t={},n=[],r=void 0,i=0){this.pos=0,this.bitBuf=0,this.bitPos=0,this.data=e,this.opts=t,this.stack=n,this.parent=r,this.parentOffset=i,this.view=lu(e)}_enablePointers(){if(this.parent)return this.parent._enablePointers();this.bs||(this.bs=vu.create(this.data.length),vu.setRange(this.bs,this.data.length,0,this.pos,this.opts.allowMultipleReads))}markBytesBS(e,t){return this.parent?this.parent.markBytesBS(this.parentOffset+e,t):!t||(!this.bs||vu.setRange(this.bs,this.data.length,e,t,!1))}markBytes(e){const t=this.pos;this.pos+=e;const n=this.markBytesBS(t,e);if(!this.opts.allowMultipleReads&&!n)throw this.err(`multiple read pos=${this.pos} len=${e}`);return n}pushObj(e,t){return bu.pushObj(this.stack,e,t)}readView(e,t){if(!Number.isFinite(e))throw this.err(`readView: wrong length=${e}`);if(this.pos+e>this.data.length)throw this.err("readView: Unexpected end of buffer");const n=t(this.view,this.pos);return this.markBytes(e),n}absBytes(e){if(e>this.data.length)throw new Error("Unexpected end of buffer");return this.data.subarray(e)}finish(){if(!this.opts.allowUnreadBytes){if(this.bitPos)throw this.err(`${this.bitPos} bits left after unpack: ${Fi.encode(this.data.slice(this.pos))}`);if(this.bs&&!this.parent){const e=vu.indices(this.bs,this.data.length,!0);if(e.length){const t=vu.range(e).map(({pos:e,length:t})=>`(${e}/${t})[${Fi.encode(this.data.subarray(e,e+t))}]`).join(", ");throw this.err(`unread byte ranges: ${t} (total=${this.data.length})`)}return}if(!this.isEnd())throw this.err(`${this.leftBytes} bytes ${this.bitPos} bits left after unpack: ${Fi.encode(this.data.slice(this.pos))}`)}}err(e){return bu.err("Reader",this.stack,e)}offsetReader(e){if(e>this.data.length)throw this.err("offsetReader: Unexpected end of buffer");return new Eu(this.absBytes(e),this.opts,this.stack,this,e)}bytes(e,t=!1){if(this.bitPos)throw this.err("readBytes: bitPos not empty");if(!Number.isFinite(e))throw this.err(`readBytes: wrong length=${e}`);if(this.pos+e>this.data.length)throw this.err("readBytes: Unexpected end of buffer");const n=this.data.subarray(this.pos,this.pos+e);return t||this.markBytes(e),n}byte(e=!1){if(this.bitPos)throw this.err("readByte: bitPos not empty");if(this.pos+1>this.data.length)throw this.err("readBytes: Unexpected end of buffer");const t=this.data[this.pos];return e||this.markBytes(1),t}get leftBytes(){return this.data.length-this.pos}get totalBytes(){return this.data.length}isEnd(){return this.pos>=this.data.length&&!this.bitPos}bits(e){if(e>32)throw this.err("BitReader: cannot read more than 32 bits in single call");let t=0;for(;e;){this.bitPos||(this.bitBuf=this.byte(),this.bitPos=8);const n=Math.min(e,this.bitPos);this.bitPos-=n,t=t<<n|this.bitBuf>>this.bitPos&2**n-1,this.bitBuf&=2**this.bitPos-1,e-=n}return t>>>0}find(e,t=this.pos){if(!fu(e))throw this.err(`find: needle is not bytes! ${e}`);if(this.bitPos)throw this.err("findByte: bitPos not empty");if(!e.length)throw this.err("find: needle is empty");for(let n=t;-1!==(n=this.data.indexOf(e[0],n));n++){if(-1===n)return;if(this.data.length-n<e.length)return;if(hu(e,this.data.subarray(n,n+e.length)))return n}}}class xu{constructor(e=[]){this.pos=0,this.buffers=[],this.ptrs=[],this.bitBuf=0,this.bitPos=0,this.viewBuf=new Uint8Array(8),this.finished=!1,this.stack=e,this.view=lu(this.viewBuf)}pushObj(e,t){return bu.pushObj(this.stack,e,t)}writeView(e,t){if(this.finished)throw this.err("buffer: finished");if(!gu(e)||e>8)throw new Error(`wrong writeView length=${e}`);t(this.view),this.bytes(this.viewBuf.slice(0,e)),this.viewBuf.fill(0)}err(e){if(this.finished)throw this.err("buffer: finished");return bu.err("Reader",this.stack,e)}bytes(e){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeBytes: ends with non-empty bit buffer");this.buffers.push(e),this.pos+=e.length}byte(e){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeByte: ends with non-empty bit buffer");this.buffers.push(new Uint8Array([e])),this.pos++}finish(e=!0){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("buffer: ends with non-empty bit buffer");const t=this.buffers.concat(this.ptrs.map(e=>e.buffer)),n=t.map(e=>e.length).reduce((e,t)=>e+t,0),r=new Uint8Array(n);for(let e=0,n=0;e<t.length;e++){const i=t[e];r.set(i,n),n+=i.length}for(let e=this.pos,t=0;t<this.ptrs.length;t++){const n=this.ptrs[t];r.set(n.ptr.encode(e),n.pos),e+=n.buffer.length}if(e){this.buffers=[];for(const e of this.ptrs)e.buffer.fill(0);this.ptrs=[],this.finished=!0,this.bitBuf=0}return r}bits(e,t){if(t>32)throw this.err("writeBits: cannot write more than 32 bits in single call");if(e>=2**t)throw this.err(`writeBits: value (${e}) >= 2**bits (${t})`);for(;t;){const n=Math.min(t,8-this.bitPos);this.bitBuf=this.bitBuf<<n|e>>t-n,this.bitPos+=n,e&=2**(t-=n)-1,8===this.bitPos&&(this.bitPos=0,this.buffers.push(new Uint8Array([this.bitBuf])),this.pos++)}}}const Su=e=>Uint8Array.from(e).reverse();function ku(e){return{encodeStream:e.encodeStream,decodeStream:e.decodeStream,size:e.size,encode:t=>{const n=new xu;return e.encodeStream(n,t),n.finish()},decode:(t,n={})=>{const r=new Eu(t,n),i=e.decodeStream(r);return r.finish(),i}}}function Ou(e,t){if(!Tu(e))throw new Error(`validate: invalid inner value ${e}`);if("function"!=typeof t)throw new Error("validate: fn should be function");return ku({size:e.size,encodeStream:(n,r)=>{let i;try{i=t(r)}catch(e){throw n.err(e)}e.encodeStream(n,i)},decodeStream:n=>{const r=e.decodeStream(n);try{return t(r)}catch(e){throw n.err(e)}}})}const Au=e=>{const t=ku(e);return e.validate?Ou(t,e.validate):t},Pu=e=>pu(e)&&"function"==typeof e.decode&&"function"==typeof e.encode;function Tu(e){return pu(e)&&Pu(e)&&"function"==typeof e.encodeStream&&"function"==typeof e.decodeStream&&(void 0===e.size||gu(e.size))}const Iu=e=>{if(!Pu(e))throw new Error("BaseCoder expected");return{encode:e.decode,decode:e.encode}},Nu={dict:function(){return{encode:e=>{if(!Array.isArray(e))throw new Error("array expected");const t={};for(const n of e){if(!Array.isArray(n)||2!==n.length)throw new Error("array of two elements expected");const e=n[0],r=n[1];if(void 0!==t[e])throw new Error(`key(${e}) appears twice in struct`);t[e]=r}return t},decode:e=>{if(!pu(e))throw new Error(`expected plain object, got ${e}`);return Object.entries(e)}}},numberBigint:{encode:e=>{if("bigint"!=typeof e)throw new Error("expected bigint, got "+typeof e);if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`element bigger than MAX_SAFE_INTEGER=${e}`);return Number(e)},decode:e=>{if(!gu(e))throw new Error("element is not a safe integer");return BigInt(e)}},tsEnum:function(e){if(!pu(e))throw new Error("plain object expected");return{encode:t=>{if(!gu(t)||!(t in e))throw new Error(`wrong value ${t}`);return e[t]},decode:t=>{if("string"!=typeof t)throw new Error("wrong value "+typeof t);return e[t]}}},decimal:function(e,t=!1){if(!gu(e))throw new Error(`decimal/precision: wrong value ${e}`);if("boolean"!=typeof t)throw new Error("decimal/round: expected boolean, got "+typeof t);const n=10n**BigInt(e);return{encode:t=>{if("bigint"!=typeof t)throw new Error("expected bigint, got "+typeof t);let n=(t<0n?-t:t).toString(10),r=n.length-e;r<0&&(n=n.padStart(n.length-r,"0"),r=0);let i=n.length-1;for(;i>=r&&"0"===n[i];i--);let s=n.slice(0,r),o=n.slice(r,i+1);return s||(s="0"),t<0n&&(s="-"+s),o?`${s}.${o}`:s},decode:r=>{if("string"!=typeof r)throw new Error("expected string, got "+typeof r);if("-0"===r)throw new Error("negative zero is not allowed");let i=!1;if(r.startsWith("-")&&(i=!0,r=r.slice(1)),!/^(0|[1-9]\d*)(\.\d+)?$/.test(r))throw new Error(`wrong string value=${r}`);let s=r.indexOf(".");s=-1===s?r.length:s;const o=r.slice(0,s),a=r.slice(s+1).replace(/0+$/,""),u=BigInt(o)*n;if(!t&&a.length>e)throw new Error(`fractional part cannot be represented with this precision (num=${r}, prec=${e})`);const c=Math.min(a.length,e),d=u+BigInt(a.slice(0,c))*10n**BigInt(e-c);return i?-d:d}}},match:function(e){if(!Array.isArray(e))throw new Error("expected array, got "+typeof e);for(const t of e)if(!Pu(t))throw new Error(`wrong base coder ${t}`);return{encode:t=>{for(const n of e){const e=n.encode(t);if(void 0!==e)return e}throw new Error(`match/encode: cannot find match in ${t}`)},decode:t=>{for(const n of e){const e=n.decode(t);if(void 0!==e)return e}throw new Error(`match/decode: cannot find match in ${t}`)}}},reverse:Iu},Uu=(e,t=!1,n=!1,r=!0)=>{if(!gu(e))throw new Error(`bigint/size: wrong value ${e}`);if("boolean"!=typeof t)throw new Error("bigint/le: expected boolean, got "+typeof t);if("boolean"!=typeof n)throw new Error("bigint/signed: expected boolean, got "+typeof n);if("boolean"!=typeof r)throw new Error("bigint/sized: expected boolean, got "+typeof r);const i=BigInt(e),s=2n**(8n*i-1n);return Au({size:r?e:void 0,encodeStream:(i,o)=>{n&&o<0&&(o|=s);const a=[];for(let t=0;t<e;t++)a.push(Number(255n&o)),o>>=8n;let u=new Uint8Array(a).reverse();if(!r){let e=0;for(e=0;e<u.length&&0===u[e];e++);u=u.subarray(e)}i.bytes(t?u.reverse():u)},decodeStream:i=>{const o=i.bytes(r?e:Math.min(e,i.leftBytes)),a=t?o:Su(o);let u=0n;for(let e=0;e<a.length;e++)u|=BigInt(a[e])<<8n*BigInt(e);return n&&u&s&&(u=(u^s)-s),u},validate:e=>{if("bigint"!=typeof e)throw new Error(`bigint: invalid value: ${e}`);return function(e,t,n){if(n){const n=2n**(t-1n);if(e<-n||e>=n)throw new Error(`value out of signed bounds. Expected ${-n} <= ${e} < ${n}`)}else if(0n>e||e>=2n**t)throw new Error(`value out of unsigned bounds. Expected 0 <= ${e} < ${2n**t}`)}(e,8n*i,!!n),e}})},$u=Uu(32,!1),Cu=Uu(8,!0),Bu=Uu(8,!0,!0),Ru=(e,t,n)=>{const r=8*e,i=2**(r-1),s=2**r;return((e,t)=>Au({size:e,encodeStream:(n,r)=>n.writeView(e,e=>t.write(e,r)),decodeStream:n=>n.readView(e,t.read),validate:e=>{if("number"!=typeof e)throw new Error("viewCoder: expected number, got "+typeof e);return t.validate&&t.validate(e),e}}))(e,{write:n.write,read:n.read,validate:t?e=>{if(!gu(e))throw new Error(`sintView: value is not safe integer: ${e}`);if(e<-i||e>=i)throw new Error(`sintView: value out of bounds. Expected ${-i} <= ${e} < ${i}`)}:e=>{if(!gu(e))throw new Error(`uintView: value is not safe integer: ${e}`);if(0>e||e>=s)throw new Error(`uintView: value out of bounds. Expected 0 <= ${e} < ${s}`)}})},Lu=Ru(4,!1,{read:(e,t)=>e.getUint32(t,!0),write:(e,t)=>e.setUint32(0,t,!0)}),zu=Ru(4,!1,{read:(e,t)=>e.getUint32(t,!1),write:(e,t)=>e.setUint32(0,t,!1)}),ju=Ru(4,!0,{read:(e,t)=>e.getInt32(t,!0),write:(e,t)=>e.setInt32(0,t,!0)}),Hu=Ru(2,!1,{read:(e,t)=>e.getUint16(t,!0),write:(e,t)=>e.setUint16(0,t,!0)}),Du=Ru(1,!1,{read:(e,t)=>e.getUint8(t),write:(e,t)=>e.setUint8(0,t)}),Fu=(e,t=!1)=>{if("boolean"!=typeof t)throw new Error("bytes/le: expected boolean, got "+typeof t);const n=_u(e),r=fu(e);return Au({size:"number"==typeof e?e:void 0,encodeStream:(i,s)=>{r||n.encodeStream(i,s.length),i.bytes(t?Su(s):s),r&&i.bytes(e)},decodeStream:i=>{let s;if(r){const t=i.find(e);if(!t)throw i.err("bytes: cannot find terminator");s=i.bytes(t-i.pos),i.bytes(e.length)}else s=i.bytes(null===e?i.leftBytes:n.decodeStream(i));return t?Su(s):s},validate:e=>{if(!fu(e))throw new Error(`bytes: invalid value ${e}`);return e}})};const Vu=(e,t=!1)=>Ou(Zu(Fu(e,t),Di),e=>{if("string"!=typeof e)throw new Error("expected string, got "+typeof e);return e});function Zu(e,t){if(!Tu(e))throw new Error(`apply: invalid inner value ${e}`);if(!Pu(t))throw new Error(`apply: invalid base value ${e}`);return Au({size:e.size,encodeStream:(n,r)=>{let i;try{i=t.decode(r)}catch(e){throw n.err(""+e)}return e.encodeStream(n,i)},decodeStream:n=>{const r=e.decodeStream(n);try{return t.encode(r)}catch(e){throw n.err(""+e)}}})}function Ku(e,t,n=!0){if(!Tu(e))throw new Error(`magic: invalid inner value ${e}`);if("boolean"!=typeof n)throw new Error("magic: expected boolean, got "+typeof n);return Au({size:e.size,encodeStream:(n,r)=>e.encodeStream(n,t),decodeStream:r=>{const i=e.decodeStream(r);if(n&&"object"!=typeof i&&i!==t||fu(t)&&!hu(t,i))throw r.err(`magic: invalid value: ${i} !== ${t}`)},validate:e=>{if(void 0!==e)throw new Error("magic: wrong value="+typeof e);return e}})}function Wu(e){let t=0;for(const n of e){if(void 0===n.size)return;if(!gu(n.size))throw new Error(`sizeof: wrong element size=${t}`);t+=n.size}return t}function qu(e){if(!pu(e))throw new Error(`struct: expected plain object, got ${e}`);for(const t in e)if(!Tu(e[t]))throw new Error(`struct: field ${t} is not CoderType`);return Au({size:Wu(Object.values(e)),encodeStream:(t,n)=>{t.pushObj(n,r=>{for(const i in e)r(i,()=>e[i].encodeStream(t,n[i]))})},decodeStream:t=>{const n={};return t.pushObj(n,r=>{for(const i in e)r(i,()=>n[i]=e[i].decodeStream(t))}),n},validate:e=>{if("object"!=typeof e||null===e)throw new Error(`struct: invalid value ${e}`);return e}})}function Mu(e,t){if(!Tu(t))throw new Error(`array: invalid inner value ${t}`);const n=_u("string"==typeof e?`../${e}`:e);return Au({size:"number"==typeof e&&t.size?e*t.size:void 0,encodeStream:(r,i)=>{const s=r;s.pushObj(i,o=>{fu(e)||n.encodeStream(r,i.length);for(let n=0;n<i.length;n++)o(`${n}`,()=>{const o=i[n],a=r.pos;if(t.encodeStream(r,o),fu(e)){if(e.length>s.pos-a)return;const t=s.finish(!1).subarray(a,s.pos);if(hu(t.subarray(0,e.length),e))throw s.err(`array: inner element encoding same as separator. elm=${o} data=${t}`)}})}),fu(e)&&r.bytes(e)},decodeStream:r=>{const i=[];return r.pushObj(i,s=>{if(null===e)for(let e=0;!r.isEnd()&&(s(`${e}`,()=>i.push(t.decodeStream(r))),!(t.size&&r.leftBytes<t.size));e++);else if(fu(e))for(let n=0;;n++){if(hu(r.bytes(e.length,!0),e)){r.bytes(e.length);break}s(`${n}`,()=>i.push(t.decodeStream(r)))}else{let e;s("arrayLen",()=>e=n.decodeStream(r));for(let n=0;n<e;n++)s(`${n}`,()=>i.push(t.decodeStream(r)))}}),i},validate:e=>{if(!Array.isArray(e))throw new Error(`array: invalid value ${e}`);return e}})}const Gu=yt.ProjectivePoint,Yu=yt.CURVE.n,Qu=yu,Ju=wu,Xu=mu,ec=e=>tn(ee(e)),tc=(...e)=>ee(ee(Ju(...e))),nc=$t.getPublicKey,rc=yt.getPublicKey,ic=e=>e.r<Yu/2n;const sc=$t.sign,oc=$t.utils.taggedHash;var ac;function uc(e,t){const n=e.length;if(t===ac.ecdsa){if(32===n)throw new Error("Expected non-Schnorr key");return Gu.fromHex(e),e}if(t===ac.schnorr){if(32!==n)throw new Error("Expected 32-byte Schnorr key");return $t.utils.lift_x($t.utils.bytesToNumberBE(e)),e}throw new Error("Unknown key type")}function cc(e,t){const n=$t.utils,r=n.taggedHash("TapTweak",e,t),i=n.bytesToNumberBE(r);if(i>=Yu)throw new Error("tweak higher than curve order");return i}!function(e){e[e.ecdsa=0]="ecdsa",e[e.schnorr=1]="schnorr"}(ac||(ac={})),ee(Gu.BASE.toRawBytes(!1));const dc={bech32:"bc",pubKeyHash:0,scriptHash:5,wif:128};function hc(e,t){if(!Qu(e)||!Qu(t))throw new Error(`cmp: wrong type a=${typeof e} b=${typeof t}`);const n=Math.min(e.length,t.length);for(let r=0;r<n;r++)if(e[r]!=t[r])return Math.sign(e[r]-t[r]);return Math.sign(e.length-t.length)}var fc;function lc(e=6,t=!1){return Au({encodeStream:(e,t)=>{if(0n===t)return;const n=t<0,r=BigInt(t),i=[];for(let e=n?-r:r;e;e>>=8n)i.push(Number(0xffn&e));i[i.length-1]>=128?i.push(n?128:0):n&&(i[i.length-1]|=128),e.bytes(new Uint8Array(i))},decodeStream:n=>{const r=n.leftBytes;if(r>e)throw new Error(`ScriptNum: number (${r}) bigger than limit=${e}`);if(0===r)return 0n;if(t){const e=n.bytes(r,!0);if(!(127&e[e.length-1]||!(r<=1)&&128&e[e.length-2]))throw new Error("Non-minimally encoded ScriptNum")}let i=0,s=0n;for(let e=0;e<r;++e)i=n.byte(),s|=BigInt(i)<<8n*BigInt(e);return i>=128&&(s&=2n**BigInt(8*r)-1n>>1n,s=-s),s}})}!function(e){e[e.OP_0=0]="OP_0",e[e.PUSHDATA1=76]="PUSHDATA1",e[e.PUSHDATA2=77]="PUSHDATA2",e[e.PUSHDATA4=78]="PUSHDATA4",e[e["1NEGATE"]=79]="1NEGATE",e[e.RESERVED=80]="RESERVED",e[e.OP_1=81]="OP_1",e[e.OP_2=82]="OP_2",e[e.OP_3=83]="OP_3",e[e.OP_4=84]="OP_4",e[e.OP_5=85]="OP_5",e[e.OP_6=86]="OP_6",e[e.OP_7=87]="OP_7",e[e.OP_8=88]="OP_8",e[e.OP_9=89]="OP_9",e[e.OP_10=90]="OP_10",e[e.OP_11=91]="OP_11",e[e.OP_12=92]="OP_12",e[e.OP_13=93]="OP_13",e[e.OP_14=94]="OP_14",e[e.OP_15=95]="OP_15",e[e.OP_16=96]="OP_16",e[e.NOP=97]="NOP",e[e.VER=98]="VER",e[e.IF=99]="IF",e[e.NOTIF=100]="NOTIF",e[e.VERIF=101]="VERIF",e[e.VERNOTIF=102]="VERNOTIF",e[e.ELSE=103]="ELSE",e[e.ENDIF=104]="ENDIF",e[e.VERIFY=105]="VERIFY",e[e.RETURN=106]="RETURN",e[e.TOALTSTACK=107]="TOALTSTACK",e[e.FROMALTSTACK=108]="FROMALTSTACK",e[e["2DROP"]=109]="2DROP",e[e["2DUP"]=110]="2DUP",e[e["3DUP"]=111]="3DUP",e[e["2OVER"]=112]="2OVER",e[e["2ROT"]=113]="2ROT",e[e["2SWAP"]=114]="2SWAP",e[e.IFDUP=115]="IFDUP",e[e.DEPTH=116]="DEPTH",e[e.DROP=117]="DROP",e[e.DUP=118]="DUP",e[e.NIP=119]="NIP",e[e.OVER=120]="OVER",e[e.PICK=121]="PICK",e[e.ROLL=122]="ROLL",e[e.ROT=123]="ROT",e[e.SWAP=124]="SWAP",e[e.TUCK=125]="TUCK",e[e.CAT=126]="CAT",e[e.SUBSTR=127]="SUBSTR",e[e.LEFT=128]="LEFT",e[e.RIGHT=129]="RIGHT",e[e.SIZE=130]="SIZE",e[e.INVERT=131]="INVERT",e[e.AND=132]="AND",e[e.OR=133]="OR",e[e.XOR=134]="XOR",e[e.EQUAL=135]="EQUAL",e[e.EQUALVERIFY=136]="EQUALVERIFY",e[e.RESERVED1=137]="RESERVED1",e[e.RESERVED2=138]="RESERVED2",e[e["1ADD"]=139]="1ADD",e[e["1SUB"]=140]="1SUB",e[e["2MUL"]=141]="2MUL",e[e["2DIV"]=142]="2DIV",e[e.NEGATE=143]="NEGATE",e[e.ABS=144]="ABS",e[e.NOT=145]="NOT",e[e["0NOTEQUAL"]=146]="0NOTEQUAL",e[e.ADD=147]="ADD",e[e.SUB=148]="SUB",e[e.MUL=149]="MUL",e[e.DIV=150]="DIV",e[e.MOD=151]="MOD",e[e.LSHIFT=152]="LSHIFT",e[e.RSHIFT=153]="RSHIFT",e[e.BOOLAND=154]="BOOLAND",e[e.BOOLOR=155]="BOOLOR",e[e.NUMEQUAL=156]="NUMEQUAL",e[e.NUMEQUALVERIFY=157]="NUMEQUALVERIFY",e[e.NUMNOTEQUAL=158]="NUMNOTEQUAL",e[e.LESSTHAN=159]="LESSTHAN",e[e.GREATERTHAN=160]="GREATERTHAN",e[e.LESSTHANOREQUAL=161]="LESSTHANOREQUAL",e[e.GREATERTHANOREQUAL=162]="GREATERTHANOREQUAL",e[e.MIN=163]="MIN",e[e.MAX=164]="MAX",e[e.WITHIN=165]="WITHIN",e[e.RIPEMD160=166]="RIPEMD160",e[e.SHA1=167]="SHA1",e[e.SHA256=168]="SHA256",e[e.HASH160=169]="HASH160",e[e.HASH256=170]="HASH256",e[e.CODESEPARATOR=171]="CODESEPARATOR",e[e.CHECKSIG=172]="CHECKSIG",e[e.CHECKSIGVERIFY=173]="CHECKSIGVERIFY",e[e.CHECKMULTISIG=174]="CHECKMULTISIG",e[e.CHECKMULTISIGVERIFY=175]="CHECKMULTISIGVERIFY",e[e.NOP1=176]="NOP1",e[e.CHECKLOCKTIMEVERIFY=177]="CHECKLOCKTIMEVERIFY",e[e.CHECKSEQUENCEVERIFY=178]="CHECKSEQUENCEVERIFY",e[e.NOP4=179]="NOP4",e[e.NOP5=180]="NOP5",e[e.NOP6=181]="NOP6",e[e.NOP7=182]="NOP7",e[e.NOP8=183]="NOP8",e[e.NOP9=184]="NOP9",e[e.NOP10=185]="NOP10",e[e.CHECKSIGADD=186]="CHECKSIGADD",e[e.INVALID=255]="INVALID"}(fc||(fc={}));const pc=Au({encodeStream:(e,t)=>{for(let n of t){if("string"==typeof n){if(void 0===fc[n])throw new Error(`Unknown opcode=${n}`);e.byte(fc[n]);continue}if("number"==typeof n){if(0===n){e.byte(0);continue}if(1<=n&&n<=16){e.byte(fc.OP_1-1+n);continue}}if("number"==typeof n&&(n=lc().encode(BigInt(n))),!Qu(n))throw new Error(`Wrong Script OP=${n} (${typeof n})`);const t=n.length;t<fc.PUSHDATA1?e.byte(t):t<=255?(e.byte(fc.PUSHDATA1),e.byte(t)):t<=65535?(e.byte(fc.PUSHDATA2),e.bytes(Hu.encode(t))):(e.byte(fc.PUSHDATA4),e.bytes(Lu.encode(t))),e.bytes(n)}},decodeStream:e=>{const t=[];for(;!e.isEnd();){const n=e.byte();if(fc.OP_0<n&&n<=fc.PUSHDATA4){let r;if(n<fc.PUSHDATA1)r=n;else if(n===fc.PUSHDATA1)r=Du.decodeStream(e);else if(n===fc.PUSHDATA2)r=Hu.decodeStream(e);else{if(n!==fc.PUSHDATA4)throw new Error("Should be not possible");r=Lu.decodeStream(e)}t.push(e.bytes(r))}else if(0===n)t.push(0);else if(fc.OP_1<=n&&n<=fc.OP_16)t.push(n-(fc.OP_1-1));else{const e=fc[n];if(void 0===e)throw new Error(`Unknown opcode=${n.toString(16)}`);t.push(e)}}return t}}),gc={253:[253,2,253n,65535n],254:[254,4,65536n,4294967295n],255:[255,8,4294967296n,18446744073709551615n]},mc=Au({encodeStream:(e,t)=>{if("number"==typeof t&&(t=BigInt(t)),0n<=t&&t<=252n)return e.byte(Number(t));for(const[n,r,i,s]of Object.values(gc))if(!(i>t||t>s)){e.byte(n);for(let n=0;n<r;n++)e.byte(Number(t>>8n*BigInt(n)&0xffn));return}throw e.err(`VarInt too big: ${t}`)},decodeStream:e=>{const t=e.byte();if(t<=252)return BigInt(t);const[n,r,i]=gc[t];let s=0n;for(let t=0;t<r;t++)s|=BigInt(e.byte())<<8n*BigInt(t);if(s<i)throw e.err(`Wrong CompactSize(${8*r})`);return s}}),yc=Zu(mc,Nu.numberBigint),wc=Fu(mc),_c=Mu(yc,wc),vc=e=>Mu(mc,e),bc=qu({txid:Fu(32,!0),index:Lu,finalScriptSig:wc,sequence:Lu}),Ec=qu({amount:Cu,script:wc});const xc=Ou(qu({version:ju,segwitFlag:((e,t=!1)=>{if(!fu(e))throw new Error("flag/flagValue: expected Uint8Array, got "+typeof e);if("boolean"!=typeof t)throw new Error("flag/xor: expected boolean, got "+typeof t);return Au({size:e.length,encodeStream:(n,r)=>{!!r!==t&&n.bytes(e)},decodeStream:n=>{let r=n.leftBytes>=e.length;return r&&(r=hu(n.bytes(e.length,!0),e),r&&n.bytes(e.length)),r!==t},validate:e=>{if(void 0!==e&&"boolean"!=typeof e)throw new Error("flag: expected boolean value or undefined, got "+typeof e);return e}})})(new Uint8Array([0,1])),inputs:vc(bc),outputs:vc(Ec),witnesses:function(e,t){if(!Tu(t))throw new Error(`flagged: invalid inner value ${t}`);return Au({encodeStream:(n,r)=>{bu.resolve(n.stack,e)&&t.encodeStream(n,r)},decodeStream:n=>{let r=!1;if(r=!!bu.resolve(n.stack,e),r)return t.decodeStream(n)}})}("segwitFlag",Mu("inputs/length",_c)),lockTime:Lu}),function(e){if(e.segwitFlag&&e.witnesses&&!e.witnesses.length)throw new Error("Segwit flag with empty witnesses array");return e}),Sc=qu({version:ju,inputs:vc(bc),outputs:vc(Ec),lockTime:Lu}),kc=Ou(Fu(null),e=>uc(e,ac.ecdsa)),Oc=Ou(Fu(32),e=>uc(e,ac.schnorr)),Ac=Ou(Fu(null),e=>{if(64!==e.length&&65!==e.length)throw new Error("Schnorr signature should be 64 or 65 bytes long");return e}),Pc=qu({fingerprint:zu,path:Mu(null,Lu)}),Tc=qu({hashes:Mu(yc,Fu(32)),der:Pc}),Ic=Fu(78),Nc=qu({pubKey:Oc,leafHash:Fu(32)}),Uc=Ou(qu({version:Du,internalKey:Fu(32),merklePath:Mu(null,Fu(32))}),e=>{if(e.merklePath.length>128)throw new Error("TaprootControlBlock: merklePath should be of length 0..128 (inclusive)");return e}),$c=Mu(null,qu({depth:Du,version:Du,script:wc})),Cc=Fu(null),Bc=Fu(20),Rc=Fu(32),Lc={unsignedTx:[0,!1,Sc,[0],[0],!1],xpub:[1,Ic,Pc,[],[0,2],!1],txVersion:[2,!1,Lu,[2],[2],!1],fallbackLocktime:[3,!1,Lu,[],[2],!1],inputCount:[4,!1,yc,[2],[2],!1],outputCount:[5,!1,yc,[2],[2],!1],txModifiable:[6,!1,Du,[],[2],!1],version:[251,!1,Lu,[],[0,2],!1],proprietary:[252,Cc,Cc,[],[0,2],!1]},zc={nonWitnessUtxo:[0,!1,xc,[],[0,2],!1],witnessUtxo:[1,!1,Ec,[],[0,2],!1],partialSig:[2,kc,Cc,[],[0,2],!1],sighashType:[3,!1,Lu,[],[0,2],!1],redeemScript:[4,!1,Cc,[],[0,2],!1],witnessScript:[5,!1,Cc,[],[0,2],!1],bip32Derivation:[6,kc,Pc,[],[0,2],!1],finalScriptSig:[7,!1,Cc,[],[0,2],!1],finalScriptWitness:[8,!1,_c,[],[0,2],!1],porCommitment:[9,!1,Cc,[],[0,2],!1],ripemd160:[10,Bc,Cc,[],[0,2],!1],sha256:[11,Rc,Cc,[],[0,2],!1],hash160:[12,Bc,Cc,[],[0,2],!1],hash256:[13,Rc,Cc,[],[0,2],!1],txid:[14,!1,Rc,[2],[2],!0],index:[15,!1,Lu,[2],[2],!0],sequence:[16,!1,Lu,[],[2],!0],requiredTimeLocktime:[17,!1,Lu,[],[2],!1],requiredHeightLocktime:[18,!1,Lu,[],[2],!1],tapKeySig:[19,!1,Ac,[],[0,2],!1],tapScriptSig:[20,Nc,Ac,[],[0,2],!1],tapLeafScript:[21,Uc,Cc,[],[0,2],!1],tapBip32Derivation:[22,Rc,Tc,[],[0,2],!1],tapInternalKey:[23,!1,Oc,[],[0,2],!1],tapMerkleRoot:[24,!1,Rc,[],[0,2],!1],proprietary:[252,Cc,Cc,[],[0,2],!1]},jc=["txid","sequence","index","witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknown"],Hc=["partialSig","finalScriptSig","finalScriptWitness","tapKeySig","tapScriptSig"],Dc={redeemScript:[0,!1,Cc,[],[0,2],!1],witnessScript:[1,!1,Cc,[],[0,2],!1],bip32Derivation:[2,kc,Pc,[],[0,2],!1],amount:[3,!1,Bu,[2],[2],!0],script:[4,!1,Cc,[2],[2],!0],tapInternalKey:[5,!1,Oc,[],[0,2],!1],tapTree:[6,!1,$c,[],[0,2],!1],tapBip32Derivation:[7,Oc,Tc,[],[0,2],!1],proprietary:[252,Cc,Cc,[],[0,2],!1]},Fc=[],Vc=Mu(du,qu({key:function(e,t){if(!Tu(t))throw new Error(`prefix: invalid inner value ${t}`);return Zu(Fu(e),Iu(t))}(yc,qu({type:yc,key:Fu(null)})),value:Fu(yc)}));function Zc(e){const[t,n,r,i,s,o]=e;return{type:t,kc:n,vc:r,reqInc:i,allowInc:s,silentIgnore:o}}function Kc(e){const t={};for(const n in e){const[r,i,s]=e[n];t[r]=[n,i,s]}return Au({encodeStream:(t,n)=>{let r=[];for(const t in e){const i=n[t];if(void 0===i)continue;const[s,o,a]=e[t];if(o){const e=i.map(([e,t])=>[o.encode(e),a.encode(t)]);e.sort((e,t)=>hc(e[0],t[0]));for(const[t,n]of e)r.push({key:{key:t,type:s},value:n})}else r.push({key:{type:s,key:cu},value:a.encode(i)})}if(n.unknown){n.unknown.sort((e,t)=>hc(e[0].key,t[0].key));for(const[e,t]of n.unknown)r.push({key:e,value:t})}Vc.encodeStream(t,r)},decodeStream:e=>{const n=Vc.decodeStream(e),r={},i={};for(const e of n){let n="unknown",s=e.key.key,o=e.value;if(t[e.key.type]){const[a,u,c]=t[e.key.type];if(n=a,!u&&s.length)throw new Error(`PSBT: Non-empty key for ${n} (key=${Fi.encode(s)} value=${Fi.encode(o)}`);if(s=u?u.decode(s):void 0,o=c.decode(o),!u){if(r[n])throw new Error(`PSBT: Same keys: ${n} (key=${s} value=${o})`);r[n]=o,i[n]=!0;continue}}else s={type:e.key.type,key:e.key.key};if(i[n])throw new Error(`PSBT: Key type with empty key and no key=${n} val=${o}`);r[n]||(r[n]=[]),r[n].push([s,o])}return r}})}qu({type:yc,key:Fu(null)});const Wc=Ou(Kc(zc),e=>{if(e.finalScriptWitness&&!e.finalScriptWitness.length)throw new Error("validateInput: empty finalScriptWitness");if(e.partialSig&&!e.partialSig.length)throw new Error("Empty partialSig");if(e.partialSig)for(const[t]of e.partialSig)uc(t,ac.ecdsa);if(e.bip32Derivation)for(const[t]of e.bip32Derivation)uc(t,ac.ecdsa);if(void 0!==e.requiredTimeLocktime&&e.requiredTimeLocktime<5e8)throw new Error(`validateInput: wrong timeLocktime=${e.requiredTimeLocktime}`);if(void 0!==e.requiredHeightLocktime&&(e.requiredHeightLocktime<=0||e.requiredHeightLocktime>=5e8))throw new Error(`validateInput: wrong heighLocktime=${e.requiredHeightLocktime}`);if(e.tapLeafScript)for(const[t,n]of e.tapLeafScript){if((254&t.version)!==n[n.length-1])throw new Error("validateInput: tapLeafScript version mimatch");if(1&n[n.length-1])throw new Error("validateInput: tapLeafScript version has parity bit!")}return e}),qc=Ou(Kc(Dc),e=>{if(e.bip32Derivation)for(const[t]of e.bip32Derivation)uc(t,ac.ecdsa);return e}),Mc=Ou(Kc(Lc),e=>{if(0===(e.version||0)){if(!e.unsignedTx)throw new Error("PSBTv0: missing unsignedTx");for(const t of e.unsignedTx.inputs)if(t.finalScriptSig&&t.finalScriptSig.length)throw new Error("PSBTv0: input scriptSig found in unsignedTx")}return e}),Gc=qu({magic:Ku(Vu(new Uint8Array([255])),"psbt"),global:Mc,inputs:Mu("global/unsignedTx/inputs/length",Wc),outputs:Mu(null,qc)}),Yc=qu({magic:Ku(Vu(new Uint8Array([255])),"psbt"),global:Mc,inputs:Mu("global/inputCount",Wc),outputs:Mu("global/outputCount",qc)});function Qc(e,t,n){for(const r in n){if("unknown"===r)continue;if(!t[r])continue;const{allowInc:n}=Zc(t[r]);if(!n.includes(e))throw new Error(`PSBTv${e}: field ${r} is not allowed`)}for(const r in t){const{reqInc:i}=Zc(t[r]);if(i.includes(e)&&void 0===n[r])throw new Error(`PSBTv${e}: missing required field ${r}`)}}function Jc(e,t,n){const r={};for(const i in n){const s=i;if("unknown"!==s){if(!t[s])continue;const{allowInc:n,silentIgnore:r}=Zc(t[s]);if(!n.includes(e)){if(r)continue;throw new Error(`Failed to serialize in PSBTv${e}: ${s} but versions allows inclusion=${n}`)}}r[s]=n[s]}return r}function Xc(e){const t=e&&e.global&&e.global.version||0;Qc(t,Lc,e.global);for(const n of e.inputs)Qc(t,zc,n);for(const n of e.outputs)Qc(t,Dc,n);const n=t?e.global.inputCount:e.global.unsignedTx.inputs.length;if(e.inputs.length<n)throw new Error("Not enough inputs");const r=e.inputs.slice(n);if(r.length>1||r.length&&Object.keys(r[0]).length)throw new Error(`Unexpected inputs left in tx=${r}`);const i=t?e.global.outputCount:e.global.unsignedTx.outputs.length;if(e.outputs.length<i)throw new Error("Not outputs inputs");const s=e.outputs.slice(i);if(s.length>1||s.length&&Object.keys(s[0]).length)throw new Error(`Unexpected outputs left in tx=${s}`);return e}function ed(e,t,n,r,i){const s={...n,...t};for(const i in e){const o=i,[a,u,c]=e[o],d=r&&!r.includes(i);if(void 0===t[i]&&i in t){if(d)throw new Error(`Cannot remove signed field=${i}`);delete s[i]}else if(u){const e=n&&n[i]?n[i]:[];let r=t[o];if(r){if(!Array.isArray(r))throw new Error(`keyMap(${i}): KV pairs should be [k, v][]`);r=r.map(e=>{if(2!==e.length)throw new Error(`keyMap(${i}): KV pairs should be [k, v][]`);return["string"==typeof e[0]?u.decode(Fi.decode(e[0])):e[0],"string"==typeof e[1]?c.decode(Fi.decode(e[1])):e[1]]});const t={},n=(e,n,r)=>{if(void 0===t[e])return void(t[e]=[n,r]);const i=Fi.encode(c.encode(t[e][1])),s=Fi.encode(c.encode(r));if(i!==s)throw new Error(`keyMap(${o}): same key=${e} oldVal=${i} newVal=${s}`)};for(const[t,r]of e){n(Fi.encode(u.encode(t)),t,r)}for(const[e,i]of r){const r=Fi.encode(u.encode(e));if(void 0===i){if(d)throw new Error(`Cannot remove signed field=${o}/${e}`);delete t[r]}else n(r,e,i)}s[o]=Object.values(t)}}else if("string"==typeof s[i])s[i]=c.decode(Fi.decode(s[i]));else if(d&&i in t&&n&&void 0!==n[i]&&!Xu(c.encode(t[i]),c.encode(n[i])))throw new Error(`Cannot change signed field=${i}`)}for(const t in s)if(!e[t]){if(i&&"unknown"===t)continue;delete s[t]}return s}qu({magic:Ku(Vu(new Uint8Array([255])),"psbt"),items:Mu(null,Zu(Mu(du,function(e){if(!Array.isArray(e))throw new Error(`Packed.Tuple: got ${typeof e} instead of array`);for(let t=0;t<e.length;t++)if(!Tu(e[t]))throw new Error(`tuple: field ${t} is not CoderType`);return Au({size:Wu(e),encodeStream:(t,n)=>{if(!Array.isArray(n))throw t.err(`tuple: invalid value ${n}`);t.pushObj(n,r=>{for(let i=0;i<e.length;i++)r(`${i}`,()=>e[i].encodeStream(t,n[i]))})},decodeStream:t=>{const n=[];return t.pushObj(n,r=>{for(let i=0;i<e.length;i++)r(`${i}`,()=>n.push(e[i].decodeStream(t)))}),n},validate:t=>{if(!Array.isArray(t))throw new Error(`tuple: invalid value ${t}`);if(t.length!==e.length)throw new Error(`tuple: wrong length=${t.length}, expected ${e.length}`);return t}})}([((e,t={isLE:!1,with0x:!1})=>{let n=Zu(Fu(e,t.isLE),Fi);const r=t.with0x;if("boolean"!=typeof r)throw new Error("hex/with0x: expected boolean, got "+typeof r);return r&&(n=Zu(n,{encode:e=>`0x${e}`,decode:e=>{if(!e.startsWith("0x"))throw new Error("hex(with0x=true).encode input should start with 0x");return e.slice(2)}})),n})(yc),Fu(mc)])),Nu.dict()))});const td=Ou(Gc,Xc),nd=Ou(Yc,Xc);function rd(e,t){try{return uc(e,t),!0}catch(e){return!1}}const id=[{encode(e){if(2===e.length&&1===e[0]&&Qu(e[1])&&"4e73"===Fi.encode(e[1]))return{type:"p2a",script:pc.encode(e)}},decode:e=>{if("p2a"===e.type)return[1,Fi.decode("4e73")]}},{encode(e){if(2===e.length&&Qu(e[0])&&rd(e[0],ac.ecdsa)&&"CHECKSIG"===e[1])return{type:"pk",pubkey:e[0]}},decode:e=>"pk"===e.type?[e.pubkey,"CHECKSIG"]:void 0},{encode(e){if(5===e.length&&"DUP"===e[0]&&"HASH160"===e[1]&&Qu(e[2])&&"EQUALVERIFY"===e[3]&&"CHECKSIG"===e[4])return{type:"pkh",hash:e[2]}},decode:e=>"pkh"===e.type?["DUP","HASH160",e.hash,"EQUALVERIFY","CHECKSIG"]:void 0},{encode(e){if(3===e.length&&"HASH160"===e[0]&&Qu(e[1])&&"EQUAL"===e[2])return{type:"sh",hash:e[1]}},decode:e=>"sh"===e.type?["HASH160",e.hash,"EQUAL"]:void 0},{encode(e){if(2===e.length&&0===e[0]&&Qu(e[1])&&32===e[1].length)return{type:"wsh",hash:e[1]}},decode:e=>"wsh"===e.type?[0,e.hash]:void 0},{encode(e){if(2===e.length&&0===e[0]&&Qu(e[1])&&20===e[1].length)return{type:"wpkh",hash:e[1]}},decode:e=>"wpkh"===e.type?[0,e.hash]:void 0},{encode(e){const t=e.length-1;if("CHECKMULTISIG"!==e[t])return;const n=e[0],r=e[t-1];if("number"!=typeof n||"number"!=typeof r)return;const i=e.slice(1,-2);if(r===i.length){for(const e of i)if(!Qu(e))return;return{type:"ms",m:n,pubkeys:i}}},decode:e=>"ms"===e.type?[e.m,...e.pubkeys,e.pubkeys.length,"CHECKMULTISIG"]:void 0},{encode(e){if(2===e.length&&1===e[0]&&Qu(e[1]))return{type:"tr",pubkey:e[1]}},decode:e=>"tr"===e.type?[1,e.pubkey]:void 0},{encode(e){const t=e.length-1;if("CHECKSIG"!==e[t])return;const n=[];for(let r=0;r<t;r++){const i=e[r];if(1&r){if("CHECKSIGVERIFY"!==i||r===t-1)return}else{if(!Qu(i))return;n.push(i)}}return{type:"tr_ns",pubkeys:n}},decode:e=>{if("tr_ns"!==e.type)return;const t=[];for(let n=0;n<e.pubkeys.length-1;n++)t.push(e.pubkeys[n],"CHECKSIGVERIFY");return t.push(e.pubkeys[e.pubkeys.length-1],"CHECKSIG"),t}},{encode(e){const t=e.length-1;if("NUMEQUAL"!==e[t]||"CHECKSIG"!==e[1])return;const n=[],r=function(e,t=4,n=!0){if("number"==typeof e)return e;if(Qu(e))try{const r=lc(t,n).decode(e);if(r>Number.MAX_SAFE_INTEGER)return;return Number(r)}catch(e){return}}(e[t-1]);if("number"==typeof r){for(let r=0;r<t-1;r++){const t=e[r];if(1&r){if(t!==(1===r?"CHECKSIG":"CHECKSIGADD"))throw new Error("OutScript.encode/tr_ms: wrong element")}else{if(!Qu(t))throw new Error("OutScript.encode/tr_ms: wrong key element");n.push(t)}}return{type:"tr_ms",pubkeys:n,m:r}}},decode:e=>{if("tr_ms"!==e.type)return;const t=[e.pubkeys[0],"CHECKSIG"];for(let n=1;n<e.pubkeys.length;n++)t.push(e.pubkeys[n],"CHECKSIGADD");return t.push(e.m,"NUMEQUAL"),t}},{encode:e=>({type:"unknown",script:pc.encode(e)}),decode:e=>"unknown"===e.type?pc.decode(e.script):void 0}],sd=Ou(Zu(pc,Nu.match(id)),e=>{if("pk"===e.type&&!rd(e.pubkey,ac.ecdsa))throw new Error("OutScript/pk: wrong key");if(!("pkh"!==e.type&&"sh"!==e.type&&"wpkh"!==e.type||Qu(e.hash)&&20===e.hash.length))throw new Error(`OutScript/${e.type}: wrong hash`);if("wsh"===e.type&&(!Qu(e.hash)||32!==e.hash.length))throw new Error("OutScript/wsh: wrong hash");if(!("tr"!==e.type||Qu(e.pubkey)&&rd(e.pubkey,ac.schnorr)))throw new Error("OutScript/tr: wrong taproot public key");if(("ms"===e.type||"tr_ns"===e.type||"tr_ms"===e.type)&&!Array.isArray(e.pubkeys))throw new Error("OutScript/multisig: wrong pubkeys array");if("ms"===e.type){const t=e.pubkeys.length;for(const t of e.pubkeys)if(!rd(t,ac.ecdsa))throw new Error("OutScript/multisig: wrong pubkey");if(e.m<=0||t>16||e.m>t)throw new Error("OutScript/multisig: invalid params")}if("tr_ns"===e.type||"tr_ms"===e.type)for(const t of e.pubkeys)if(!rd(t,ac.schnorr))throw new Error(`OutScript/${e.type}: wrong pubkey`);if("tr_ms"===e.type){const t=e.pubkeys.length;if(e.m<=0||t>999||e.m>t)throw new Error("OutScript/tr_ms: invalid params")}return e});function od(e,t){if(!Xu(e.hash,ee(t)))throw new Error("checkScript: wsh wrong witnessScript hash");const n=sd.decode(t);if("tr"===n.type||"tr_ns"===n.type||"tr_ms"===n.type)throw new Error(`checkScript: P2${n.type} cannot be wrapped in P2SH`);if("wpkh"===n.type||"sh"===n.type)throw new Error(`checkScript: P2${n.type} cannot be wrapped in P2WSH`)}function ad(e,t,n){if(e){const r=sd.decode(e);if("tr_ns"===r.type||"tr_ms"===r.type||"ms"===r.type||"pk"==r.type)throw new Error(`checkScript: non-wrapped ${r.type}`);if("sh"===r.type&&t){if(!Xu(r.hash,ec(t)))throw new Error("checkScript: sh wrong redeemScript hash");const e=sd.decode(t);if("tr"===e.type||"tr_ns"===e.type||"tr_ms"===e.type)throw new Error(`checkScript: P2${e.type} cannot be wrapped in P2SH`);if("sh"===e.type)throw new Error("checkScript: P2SH cannot be wrapped in P2SH")}"wsh"===r.type&&n&&od(r,n)}if(t){const e=sd.decode(t);"wsh"===e.type&&n&&od(e,n)}}const ud=(e,t=192)=>oc("TapLeaf",new Uint8Array([t]),wc.encode(e)),cd=$i(ee);function dd(e,t){if(t.length<2||t.length>40)throw new Error("Witness: invalid length");if(e>16)throw new Error("Witness: invalid version");if(0===e&&20!==t.length&&32!==t.length)throw new Error("Witness: invalid length for version")}function hd(e,t,n=dc){dd(e,t);const r=0===e?ji:Hi;return r.encode(n.bech32,[e].concat(r.toWords(t)))}function fd(e,t){return cd.encode(Ju(Uint8Array.from(t),e))}function ld(e=dc){return{encode(t){const{type:n}=t;if("wpkh"===n)return hd(0,t.hash,e);if("wsh"===n)return hd(0,t.hash,e);if("tr"===n)return hd(1,t.pubkey,e);if("pkh"===n)return fd(t.hash,[e.pubKeyHash]);if("sh"===n)return fd(t.hash,[e.scriptHash]);throw new Error(`Unknown address type=${n}`)},decode(t){if(t.length<14||t.length>74)throw new Error("Invalid address length");if(e.bech32&&t.toLowerCase().startsWith(`${e.bech32}1`)){let n;try{if(n=ji.decode(t),0!==n.words[0])throw new Error(`bech32: wrong version=${n.words[0]}`)}catch(e){if(n=Hi.decode(t),0===n.words[0])throw new Error(`bech32m: wrong version=${n.words[0]}`)}if(n.prefix!==e.bech32)throw new Error(`wrong bech32 prefix=${n.prefix}`);const[r,...i]=n.words,s=ji.fromWords(i);if(dd(r,s),0===r&&32===s.length)return{type:"wsh",hash:s};if(0===r&&20===s.length)return{type:"wpkh",hash:s};if(1===r&&32===s.length)return{type:"tr",pubkey:s};throw new Error("Unknown witness program")}const n=cd.decode(t);if(21!==n.length)throw new Error("Invalid base58 address");if(n[0]===e.pubKeyHash)return{type:"pkh",hash:n.slice(1)};if(n[0]===e.scriptHash)return{type:"sh",hash:n.slice(1)};throw new Error(`Invalid address prefix=${n[0]}`)}}}const pd=new Uint8Array(32),gd={amount:0xffffffffffffffffn,script:cu},md=4294967295;Nu.decimal(8);const yd=(e,t)=>void 0===e?t:e;function wd(e){if(Array.isArray(e))return e.map(e=>wd(e));if(Qu(e))return Uint8Array.from(e);if(["number","bigint","boolean","string","undefined"].includes(typeof e))return e;if(null===e)return e;if("object"==typeof e)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,wd(t)]));throw new Error(`cloneDeep: unknown type=${e} (${typeof e})`)}var _d,vd;function bd(e,t,n,r=cu){return Xu(n,t)&&(e=function(e,t=Uint8Array.of()){const n=$t.utils,r=n.bytesToNumberBE(e),i=Gu.fromPrivateKey(r),s=i.hasEvenY()?r:n.mod(-r,Yu),o=cc(n.pointToBytes(i),t);return n.numberToBytesBE(n.mod(s+o,Yu),32)}(e,r),t=nc(e)),{privKey:e,pubKey:t}}function Ed(e){if(void 0===e.script||void 0===e.amount)throw new Error("Transaction/output: script and amount required");return{script:e.script,amount:e.amount}}function xd(e){if(void 0===e.txid||void 0===e.index)throw new Error("Transaction/input: txid and index required");return{txid:e.txid,index:e.index,sequence:yd(e.sequence,md),finalScriptSig:yd(e.finalScriptSig,cu)}}function Sd(e){for(const t in e){const n=t;jc.includes(n)||delete e[n]}}!function(e){e[e.DEFAULT=0]="DEFAULT",e[e.ALL=1]="ALL",e[e.NONE=2]="NONE",e[e.SINGLE=3]="SINGLE",e[e.ANYONECANPAY=128]="ANYONECANPAY"}(_d||(_d={})),function(e){e[e.DEFAULT=0]="DEFAULT",e[e.ALL=1]="ALL",e[e.NONE=2]="NONE",e[e.SINGLE=3]="SINGLE",e[e.DEFAULT_ANYONECANPAY=128]="DEFAULT_ANYONECANPAY",e[e.ALL_ANYONECANPAY=129]="ALL_ANYONECANPAY",e[e.NONE_ANYONECANPAY=130]="NONE_ANYONECANPAY",e[e.SINGLE_ANYONECANPAY=131]="SINGLE_ANYONECANPAY"}(vd||(vd={}));const kd=qu({txid:Fu(32,!0),index:Lu});function Od(e){if("number"!=typeof e||"string"!=typeof vd[e])throw new Error(`Invalid SigHash=${e}`);return e}function Ad(e){const t=31&e;return{isAny:!!(e&_d.ANYONECANPAY),isNone:t===_d.NONE,isSingle:t===_d.SINGLE}}function Pd(e){if(e.nonWitnessUtxo&&void 0!==e.index){const t=e.nonWitnessUtxo.outputs.length-1;if(e.index>t)throw new Error(`validateInput: index(${e.index}) not in nonWitnessUtxo`);const n=e.nonWitnessUtxo.outputs[e.index];if(e.witnessUtxo&&(!Xu(e.witnessUtxo.script,n.script)||e.witnessUtxo.amount!==n.amount))throw new Error("validateInput: witnessUtxo different from nonWitnessUtxo");if(e.txid){if(e.nonWitnessUtxo.outputs.length-1<e.index)throw new Error("nonWitnessUtxo: incorect output index");const t=Ud.fromRaw(xc.encode(e.nonWitnessUtxo),{allowUnknownOutputs:!0,disableScriptCheck:!0,allowUnknownInputs:!0}),n=Fi.encode(e.txid);if(t.isFinal&&t.id!==n)throw new Error(`nonWitnessUtxo: wrong txid, exp=${n} got=${t.id}`)}}return e}function Td(e){if(e.nonWitnessUtxo){if(void 0===e.index)throw new Error("Unknown input index");return e.nonWitnessUtxo.outputs[e.index]}if(e.witnessUtxo)return e.witnessUtxo;throw new Error("Cannot find previous output info")}function Id(e,t,n,r=!1,i=!1){let{nonWitnessUtxo:s,txid:o}=e;"string"==typeof s&&(s=Fi.decode(s)),Qu(s)&&(s=xc.decode(s)),"nonWitnessUtxo"in e||void 0!==s||(s=t?.nonWitnessUtxo),"string"==typeof o&&(o=Fi.decode(o)),void 0===o&&(o=t?.txid);let a,u={...t,...e,nonWitnessUtxo:s,txid:o};return"nonWitnessUtxo"in e||void 0!==u.nonWitnessUtxo||delete u.nonWitnessUtxo,void 0===u.sequence&&(u.sequence=md),null===u.tapMerkleRoot&&delete u.tapMerkleRoot,u=ed(zc,u,t,n,i),Wc.encode(u),u.nonWitnessUtxo&&void 0!==u.index?a=u.nonWitnessUtxo.outputs[u.index]:u.witnessUtxo&&(a=u.witnessUtxo),a&&!r&&ad(a&&a.script,u.redeemScript,u.witnessScript),u}function Nd(e,t=!1){let n="legacy",r=_d.ALL;const i=Td(e),s=sd.decode(i.script);let o=s.type,a=s;const u=[s];if("tr"===s.type)return r=_d.DEFAULT,{txType:"taproot",type:"tr",last:s,lastScript:i.script,defaultSighash:r,sighash:e.sighashType||r};{if("wpkh"!==s.type&&"wsh"!==s.type||(n="segwit"),"sh"===s.type){if(!e.redeemScript)throw new Error("inputType: sh without redeemScript");let t=sd.decode(e.redeemScript);"wpkh"!==t.type&&"wsh"!==t.type||(n="segwit"),u.push(t),a=t,o+=`-${t.type}`}if("wsh"===a.type){if(!e.witnessScript)throw new Error("inputType: wsh without witnessScript");let t=sd.decode(e.witnessScript);"wsh"===t.type&&(n="segwit"),u.push(t),a=t,o+=`-${t.type}`}const i=u[u.length-1];if("sh"===i.type||"wsh"===i.type)throw new Error("inputType: sh/wsh cannot be terminal type");const c={type:o,txType:n,last:i,lastScript:sd.encode(i),defaultSighash:r,sighash:e.sighashType||r};if("legacy"===n&&!t&&!e.nonWitnessUtxo)throw new Error("Transaction/sign: legacy input without nonWitnessUtxo, can result in attack that forces paying higher fees. Pass allowLegacyWitnessUtxo=true, if you sure");return c}}class Ud{constructor(e={}){this.global={},this.inputs=[],this.outputs=[];const t=this.opts=function(e){if(void 0!==e&&"[object Object]"!=={}.toString.call(e))throw new Error(`Wrong object type for transaction options: ${e}`);const t={...e,version:yd(e.version,2),lockTime:yd(e.lockTime,0),PSBTVersion:yd(e.PSBTVersion,0)};if(void 0!==t.allowUnknowInput&&(e.allowUnknownInputs=t.allowUnknowInput),void 0!==t.allowUnknowOutput&&(e.allowUnknownOutputs=t.allowUnknowOutput),"number"!=typeof t.lockTime)throw new Error("Transaction lock time should be number");if(Lu.encode(t.lockTime),0!==t.PSBTVersion&&2!==t.PSBTVersion)throw new Error(`Unknown PSBT version ${t.PSBTVersion}`);for(const e of["allowUnknownVersion","allowUnknownOutputs","allowUnknownInputs","disableScriptCheck","bip174jsCompat","allowLegacyWitnessUtxo","lowR"]){const n=t[e];if(void 0!==n&&"boolean"!=typeof n)throw new Error(`Transation options wrong type: ${e}=${n} (${typeof n})`)}if(t.allowUnknownVersion?"number"==typeof t.version:![-1,0,1,2,3].includes(t.version))throw new Error(`Unknown version: ${t.version}`);if(void 0!==t.customScripts){const e=t.customScripts;if(!Array.isArray(e))throw new Error(`wrong custom scripts type (expected array): customScripts=${e} (${typeof e})`);for(const t of e){if("function"!=typeof t.encode||"function"!=typeof t.decode)throw new Error(`wrong script=${t} (${typeof t})`);if(void 0!==t.finalizeTaproot&&"function"!=typeof t.finalizeTaproot)throw new Error(`wrong script=${t} (${typeof t})`)}}return Object.freeze(t)}(e);0!==t.lockTime&&(this.global.fallbackLocktime=t.lockTime),this.global.txVersion=t.version}static fromRaw(e,t={}){const n=xc.decode(e),r=new Ud({...t,version:n.version,lockTime:n.lockTime});for(const e of n.outputs)r.addOutput(e);if(r.outputs=n.outputs,r.inputs=n.inputs,n.witnesses)for(let e=0;e<n.witnesses.length;e++)r.inputs[e].finalScriptWitness=n.witnesses[e];return r}static fromPSBT(e,t={}){let n;try{n=td.decode(e)}catch(t){try{n=nd.decode(e)}catch(e){throw t}}const r=n.global.version||0;if(0!==r&&2!==r)throw new Error(`Wrong PSBT version=${r}`);const i=n.global.unsignedTx,s=0===r?i?.version:n.global.txVersion,o=0===r?i?.lockTime:n.global.fallbackLocktime,a=new Ud({...t,version:s,lockTime:o,PSBTVersion:r}),u=0===r?i?.inputs.length:n.global.inputCount;a.inputs=n.inputs.slice(0,u).map((e,t)=>Pd({finalScriptSig:cu,...n.global.unsignedTx?.inputs[t],...e}));const c=0===r?i?.outputs.length:n.global.outputCount;return a.outputs=n.outputs.slice(0,c).map((e,t)=>({...e,...n.global.unsignedTx?.outputs[t]})),a.global={...n.global,txVersion:s},0!==o&&(a.global.fallbackLocktime=o),a}toPSBT(e=this.opts.PSBTVersion){if(0!==e&&2!==e)throw new Error(`Wrong PSBT version=${e}`);const t=this.inputs.map(t=>Pd(Jc(e,zc,t)));for(const e of t)e.partialSig&&!e.partialSig.length&&delete e.partialSig,e.finalScriptSig&&!e.finalScriptSig.length&&delete e.finalScriptSig,e.finalScriptWitness&&!e.finalScriptWitness.length&&delete e.finalScriptWitness;const n=this.outputs.map(t=>Jc(e,Dc,t)),r={...this.global};return 0===e?(r.unsignedTx=Sc.decode(Sc.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(xd).map(e=>({...e,finalScriptSig:cu})),outputs:this.outputs.map(Ed)})),delete r.fallbackLocktime,delete r.txVersion):(r.version=e,r.txVersion=this.version,r.inputCount=this.inputs.length,r.outputCount=this.outputs.length,r.fallbackLocktime&&0===r.fallbackLocktime&&delete r.fallbackLocktime),this.opts.bip174jsCompat&&(t.length||t.push({}),n.length||n.push({})),(0===e?td:nd).encode({global:r,inputs:t,outputs:n})}get lockTime(){let e=0,t=0,n=0,r=0;for(const i of this.inputs)i.requiredHeightLocktime&&(e=Math.max(e,i.requiredHeightLocktime),t++),i.requiredTimeLocktime&&(n=Math.max(n,i.requiredTimeLocktime),r++);return t&&t>=r?e:0!==n?n:this.global.fallbackLocktime||0}get version(){if(void 0===this.global.txVersion)throw new Error("No global.txVersion");return this.global.txVersion}inputStatus(e){this.checkInputIdx(e);const t=this.inputs[e];return t.finalScriptSig&&t.finalScriptSig.length||t.finalScriptWitness&&t.finalScriptWitness.length?"finalized":t.tapKeySig||t.tapScriptSig&&t.tapScriptSig.length||t.partialSig&&t.partialSig.length?"signed":"unsigned"}inputSighash(e){this.checkInputIdx(e);const t=this.inputs[e].sighashType,n=void 0===t?_d.DEFAULT:t,r=n===_d.DEFAULT?_d.ALL:3&n;return{sigInputs:n&_d.ANYONECANPAY,sigOutputs:r}}signStatus(){let e=!0,t=!0,n=[],r=[];for(let i=0;i<this.inputs.length;i++){if("unsigned"===this.inputStatus(i))continue;const{sigInputs:s,sigOutputs:o}=this.inputSighash(i);if(s===_d.ANYONECANPAY?n.push(i):e=!1,o===_d.ALL)t=!1;else if(o===_d.SINGLE)r.push(i);else if(o!==_d.NONE)throw new Error(`Wrong signature hash output type: ${o}`)}return{addInput:e,addOutput:t,inputs:n,outputs:r}}get isFinal(){for(let e=0;e<this.inputs.length;e++)if("finalized"!==this.inputStatus(e))return!1;return!0}get hasWitnesses(){let e=!1;for(const t of this.inputs)t.finalScriptWitness&&t.finalScriptWitness.length&&(e=!0);return e}get weight(){if(!this.isFinal)throw new Error("Transaction is not finalized");let e=32;const t=this.outputs.map(Ed);e+=4*yc.encode(this.outputs.length).length;for(const n of t)e+=32+4*wc.encode(n.script).length;this.hasWitnesses&&(e+=2),e+=4*yc.encode(this.inputs.length).length;for(const t of this.inputs)e+=160+4*wc.encode(t.finalScriptSig||cu).length,this.hasWitnesses&&t.finalScriptWitness&&(e+=_c.encode(t.finalScriptWitness).length);return e}get vsize(){return e=this.weight,Math.ceil(e/4);var e}toBytes(e=!1,t=!1){return xc.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(xd).map(t=>({...t,finalScriptSig:e&&t.finalScriptSig||cu})),outputs:this.outputs.map(Ed),witnesses:this.inputs.map(e=>e.finalScriptWitness||[]),segwitFlag:t&&this.hasWitnesses})}get unsignedTx(){return this.toBytes(!1,!1)}get hex(){return Fi.encode(this.toBytes(!0,this.hasWitnesses))}get hash(){if(!this.isFinal)throw new Error("Transaction is not finalized");return Fi.encode(tc(this.toBytes(!0)))}get id(){if(!this.isFinal)throw new Error("Transaction is not finalized");return Fi.encode(tc(this.toBytes(!0)).reverse())}checkInputIdx(e){if(!Number.isSafeInteger(e)||0>e||e>=this.inputs.length)throw new Error(`Wrong input index=${e}`)}getInput(e){return this.checkInputIdx(e),wd(this.inputs[e])}get inputsLength(){return this.inputs.length}addInput(e,t=!1){if(!t&&!this.signStatus().addInput)throw new Error("Tx has signed inputs, cannot add new one");return this.inputs.push(Id(e,void 0,void 0,this.opts.disableScriptCheck)),this.inputs.length-1}updateInput(e,t,n=!1){let r;if(this.checkInputIdx(e),!n){const t=this.signStatus();t.addInput&&!t.inputs.includes(e)||(r=Hc)}this.inputs[e]=Id(t,this.inputs[e],r,this.opts.disableScriptCheck,this.opts.allowUnknown)}checkOutputIdx(e){if(!Number.isSafeInteger(e)||0>e||e>=this.outputs.length)throw new Error(`Wrong output index=${e}`)}getOutput(e){return this.checkOutputIdx(e),wd(this.outputs[e])}getOutputAddress(e,t=dc){const n=this.getOutput(e);if(n.script)return ld(t).encode(sd.decode(n.script))}get outputsLength(){return this.outputs.length}normalizeOutput(e,t,n){let{amount:r,script:i}=e;if(void 0===r&&(r=t?.amount),"bigint"!=typeof r)throw new Error(`Wrong amount type, should be of type bigint in sats, but got ${r} of type ${typeof r}`);"string"==typeof i&&(i=Fi.decode(i)),void 0===i&&(i=t?.script);let s={...t,...e,amount:r,script:i};if(void 0===s.amount&&delete s.amount,s=ed(Dc,s,t,n,this.opts.allowUnknown),qc.encode(s),s.script&&!this.opts.allowUnknownOutputs&&"unknown"===sd.decode(s.script).type)throw new Error("Transaction/output: unknown output script type, there is a chance that input is unspendable. Pass allowUnknownOutputs=true, if you sure");return this.opts.disableScriptCheck||ad(s.script,s.redeemScript,s.witnessScript),s}addOutput(e,t=!1){if(!t&&!this.signStatus().addOutput)throw new Error("Tx has signed outputs, cannot add new one");return this.outputs.push(this.normalizeOutput(e)),this.outputs.length-1}updateOutput(e,t,n=!1){let r;if(this.checkOutputIdx(e),!n){const t=this.signStatus();t.addOutput&&!t.outputs.includes(e)||(r=Fc)}this.outputs[e]=this.normalizeOutput(t,this.outputs[e],r)}addOutputAddress(e,t,n=dc){return this.addOutput({script:sd.encode(ld(n).decode(e)),amount:t})}get fee(){let e=0n;for(const t of this.inputs){const n=Td(t);if(!n)throw new Error("Empty input amount");e+=n.amount}const t=this.outputs.map(Ed);for(const n of t)e-=n.amount;return e}preimageLegacy(e,t,n){const{isAny:r,isNone:i,isSingle:s}=Ad(n);if(e<0||!Number.isSafeInteger(e))throw new Error(`Invalid input idx=${e}`);if(s&&e>=this.outputs.length||e>=this.inputs.length)return $u.encode(1n);t=pc.encode(pc.decode(t).filter(e=>"CODESEPARATOR"!==e));let o=this.inputs.map(xd).map((n,r)=>({...n,finalScriptSig:r===e?t:cu}));r?o=[o[e]]:(i||s)&&(o=o.map((t,n)=>({...t,sequence:n===e?t.sequence:0})));let a=this.outputs.map(Ed);i?a=[]:s&&(a=a.slice(0,e).fill(gd).concat([a[e]]));const u=xc.encode({lockTime:this.lockTime,version:this.version,segwitFlag:!1,inputs:o,outputs:a});return tc(u,ju.encode(n))}preimageWitnessV0(e,t,n,r){const{isAny:i,isNone:s,isSingle:o}=Ad(n);let a=pd,u=pd,c=pd;const d=this.inputs.map(xd),h=this.outputs.map(Ed);i||(a=tc(...d.map(kd.encode))),i||o||s||(u=tc(...d.map(e=>Lu.encode(e.sequence)))),o||s?o&&e<h.length&&(c=tc(Ec.encode(h[e]))):c=tc(...h.map(Ec.encode));const f=d[e];return tc(ju.encode(this.version),a,u,Fu(32,!0).encode(f.txid),Lu.encode(f.index),wc.encode(t),Cu.encode(r),Lu.encode(f.sequence),c,Lu.encode(this.lockTime),Lu.encode(n))}preimageWitnessV1(e,t,n,r,i=-1,s,o=192,a){if(!Array.isArray(r)||this.inputs.length!==r.length)throw new Error(`Invalid amounts array=${r}`);if(!Array.isArray(t)||this.inputs.length!==t.length)throw new Error(`Invalid prevOutScript array=${t}`);const u=[Du.encode(0),Du.encode(n),ju.encode(this.version),Lu.encode(this.lockTime)],c=n===_d.DEFAULT?_d.ALL:3&n,d=n&_d.ANYONECANPAY,h=this.inputs.map(xd),f=this.outputs.map(Ed);d!==_d.ANYONECANPAY&&u.push(...[h.map(kd.encode),r.map(Cu.encode),t.map(wc.encode),h.map(e=>Lu.encode(e.sequence))].map(e=>ee(Ju(...e)))),c===_d.ALL&&u.push(ee(Ju(...f.map(Ec.encode))));const l=(a?1:0)|(s?2:0);if(u.push(new Uint8Array([l])),d===_d.ANYONECANPAY){const n=h[e];u.push(kd.encode(n),Cu.encode(r[e]),wc.encode(t[e]),Lu.encode(n.sequence))}else u.push(Lu.encode(e));return 1&l&&u.push(ee(wc.encode(a||cu))),c===_d.SINGLE&&u.push(e<f.length?ee(Ec.encode(f[e])):pd),s&&u.push(ud(s,o),Du.encode(0),ju.encode(i)),oc("TapSighash",...u)}signIdx(e,t,n,r){this.checkInputIdx(t);const i=this.inputs[t],s=Nd(i,this.opts.allowLegacyWitnessUtxo);if(!Qu(e)){if(!i.bip32Derivation||!i.bip32Derivation.length)throw new Error("bip32Derivation: empty");const n=i.bip32Derivation.filter(t=>t[1].fingerprint==e.fingerprint).map(([t,{path:n}])=>{let r=e;for(const e of n)r=r.deriveChild(e);if(!Xu(r.publicKey,t))throw new Error("bip32Derivation: wrong pubKey");if(!r.privateKey)throw new Error("bip32Derivation: no privateKey");return r});if(!n.length)throw new Error(`bip32Derivation: no items with fingerprint=${e.fingerprint}`);let r=!1;for(const e of n)this.signIdx(e.privateKey,t)&&(r=!0);return r}n?n.forEach(Od):n=[s.defaultSighash];const o=s.sighash;if(!n.includes(o))throw new Error(`Input with not allowed sigHash=${o}. Allowed: ${n.join(", ")}`);const{sigOutputs:a}=this.inputSighash(t);if(a===_d.SINGLE&&t>=this.outputs.length)throw new Error(`Input with sighash SINGLE, but there is no output with corresponding index=${t}`);const u=Td(i);if("taproot"===s.txType){const n=this.inputs.map(Td),s=n.map(e=>e.script),a=n.map(e=>e.amount);let u=!1,c=nc(e),d=i.tapMerkleRoot||cu;if(i.tapInternalKey){const{pubKey:n,privKey:h}=bd(e,c,i.tapInternalKey,d),[f,l]=function(e,t){const n=$t.utils,r=cc(e,t),i=n.lift_x(n.bytesToNumberBE(e)).add(Gu.fromPrivateKey(r)),s=i.hasEvenY()?0:1;return[n.pointToBytes(i),s]}(i.tapInternalKey,d);if(Xu(f,n)){const e=this.preimageWitnessV1(t,s,o,a),n=Ju(sc(e,h,r),o!==_d.DEFAULT?new Uint8Array([o]):cu);this.updateInput(t,{tapKeySig:n},!0),u=!0}}if(i.tapLeafScript){i.tapScriptSig=i.tapScriptSig||[];for(const[n,d]of i.tapLeafScript){const n=d.subarray(0,-1),i=pc.decode(n),h=d[d.length-1],f=ud(n,h);if(-1===i.findIndex(e=>Qu(e)&&Xu(e,c)))continue;const l=this.preimageWitnessV1(t,s,o,a,void 0,n,h),p=Ju(sc(l,e,r),o!==_d.DEFAULT?new Uint8Array([o]):cu);this.updateInput(t,{tapScriptSig:[[{pubKey:c,leafHash:f},p]]},!0),u=!0}}if(!u)throw new Error("No taproot scripts signed");return!0}{const n=rc(e);let r=!1;const i=ec(n);for(const e of pc.decode(s.lastScript))Qu(e)&&(Xu(e,n)||Xu(e,i))&&(r=!0);if(!r)throw new Error(`Input script doesn't have pubKey: ${s.lastScript}`);let a;if("legacy"===s.txType)a=this.preimageLegacy(t,s.lastScript,o);else{if("segwit"!==s.txType)throw new Error(`Transaction/sign: unknown tx type: ${s.txType}`);{let e=s.lastScript;"wpkh"===s.last.type&&(e=sd.encode({type:"pkh",hash:s.last.hash})),a=this.preimageWitnessV0(t,e,o,u.amount)}}const c=function(e,t,n=!1){let r=yt.sign(e,t);if(n&&!ic(r)){const n=new Uint8Array(32);let i=0;for(;!ic(r);)if(n.set(Lu.encode(i++)),r=yt.sign(e,t,{extraEntropy:n}),i>4294967295)throw new Error("lowR counter overflow: report the error")}return r.toDERRawBytes()}(a,e,this.opts.lowR);this.updateInput(t,{partialSig:[[n,Ju(c,new Uint8Array([o]))]]},!0)}return!0}sign(e,t,n){let r=0;for(let i=0;i<this.inputs.length;i++)try{this.signIdx(e,i,t,n)&&r++}catch(e){}if(!r)throw new Error("No inputs signed");return r}finalizeIdx(e){if(this.checkInputIdx(e),this.fee<0n)throw new Error("Outputs spends more than inputs amount");const t=this.inputs[e],n=Nd(t,this.opts.allowLegacyWitnessUtxo);if("taproot"===n.txType){if(t.tapKeySig)t.finalScriptWitness=[t.tapKeySig];else{if(!t.tapLeafScript||!t.tapScriptSig)throw new Error("finalize/taproot: unknown input");{const e=t.tapLeafScript.sort((e,t)=>Uc.encode(e[0]).length-Uc.encode(t[0]).length);for(const[n,r]of e){const e=r.slice(0,-1),i=r[r.length-1],s=sd.decode(e),o=ud(e,i),a=t.tapScriptSig.filter(e=>Xu(e[0].leafHash,o));let u=[];if("tr_ms"===s.type){const e=s.m,t=s.pubkeys;let n=0;for(const r of t){const t=a.findIndex(e=>Xu(e[0].pubKey,r));n!==e&&-1!==t?(u.push(a[t][1]),n++):u.push(cu)}if(n!==e)continue}else if("tr_ns"===s.type){for(const e of s.pubkeys){const t=a.findIndex(t=>Xu(t[0].pubKey,e));-1!==t&&u.push(a[t][1])}if(u.length!==s.pubkeys.length)continue}else{if("unknown"!==s.type||!this.opts.allowUnknownInputs){const r=this.opts.customScripts;if(r)for(const i of r){if(!i.finalizeTaproot)continue;const r=pc.decode(e),s=i.encode(r);if(void 0===s)continue;const o=i.finalizeTaproot(e,s,a);if(o)return t.finalScriptWitness=o.concat(Uc.encode(n)),t.finalScriptSig=cu,void Sd(t)}throw new Error("Finalize: Unknown tapLeafScript")}{const t=pc.decode(e);if(u=a.map(([{pubKey:e},n])=>{const r=t.findIndex(t=>Qu(t)&&Xu(t,e));if(-1===r)throw new Error("finalize/taproot: cannot find position of pubkey in script");return{signature:n,pos:r}}).sort((e,t)=>e.pos-t.pos).map(e=>e.signature),!u.length)continue}}t.finalScriptWitness=u.reverse().concat([e,Uc.encode(n)]);break}if(!t.finalScriptWitness)throw new Error("finalize/taproot: empty witness")}}return t.finalScriptSig=cu,void Sd(t)}if(!t.partialSig||!t.partialSig.length)throw new Error("Not enough partial sign");let r,i,s=cu,o=[];if("ms"===n.last.type){const e=n.last.m,r=n.last.pubkeys;let i=[];for(const e of r){const n=t.partialSig.find(t=>Xu(e,t[0]));n&&i.push(n[1])}if(i=i.slice(0,e),i.length!==e)throw new Error(`Multisig: wrong signatures count, m=${e} n=${r.length} signatures=${i.length}`);s=pc.encode([0,...i])}else if("pk"===n.last.type)s=pc.encode([t.partialSig[0][1]]);else if("pkh"===n.last.type)s=pc.encode([t.partialSig[0][1],t.partialSig[0][0]]);else if("wpkh"===n.last.type)s=cu,o=[t.partialSig[0][1],t.partialSig[0][0]];else if("unknown"===n.last.type&&!this.opts.allowUnknownInputs)throw new Error("Unknown inputs not allowed");if(n.type.includes("wsh-")&&(s.length&&n.lastScript.length&&(o=pc.decode(s).map(e=>{if(0===e)return cu;if(Qu(e))return e;throw new Error(`Wrong witness op=${e}`)})),o=o.concat(n.lastScript)),"segwit"===n.txType&&(i=o),n.type.startsWith("sh-wsh-")?r=pc.encode([pc.encode([0,ee(n.lastScript)])]):n.type.startsWith("sh-")?r=pc.encode([...pc.decode(s),n.lastScript]):n.type.startsWith("wsh-")||"segwit"!==n.txType&&(r=s),!r&&!i)throw new Error("Unknown error finalizing input");r&&(t.finalScriptSig=r),i&&(t.finalScriptWitness=i),Sd(t)}finalize(){for(let e=0;e<this.inputs.length;e++)this.finalizeIdx(e)}extract(){if(!this.isFinal)throw new Error("Transaction has unfinalized inputs");if(!this.outputs.length)throw new Error("Transaction has no outputs");if(this.fee<0n)throw new Error("Outputs spends more than inputs amount");return this.toBytes(!0,!0)}combine(e){for(const t of["PSBTVersion","version","lockTime"])if(this.opts[t]!==e.opts[t])throw new Error(`Transaction/combine: different ${t} this=${this.opts[t]} other=${e.opts[t]}`);for(const t of["inputs","outputs"])if(this[t].length!==e[t].length)throw new Error(`Transaction/combine: different ${t} length this=${this[t].length} other=${e[t].length}`);const t=this.global.unsignedTx?Sc.encode(this.global.unsignedTx):cu,n=e.global.unsignedTx?Sc.encode(e.global.unsignedTx):cu;if(!Xu(t,n))throw new Error("Transaction/combine: different unsigned tx");this.global=ed(Lc,this.global,e.global,void 0,this.opts.allowUnknown);for(let t=0;t<this.inputs.length;t++)this.updateInput(t,e.inputs[t],!0);for(let t=0;t<this.outputs.length;t++)this.updateOutput(t,e.outputs[t],!0);return this}clone(){return Ud.fromPSBT(this.toPSBT(this.opts.PSBTVersion),this.opts)}}function $d(e){const t=Ki.decode(e);return Ud.fromPSBT(t,{allowUnknownOutputs:!0})}function Cd(e){if(e instanceof Ud)return e;if("string"==typeof e)return $d(e);throw new Error("invalid psbt input: "+e)}function Bd(e){const t=Cd(e),n=t.inputsLength,r=[];for(let e=0;e<n;e++){const n=t.getInput(e);r.push(n)}return r}function Rd(e){const t=Cd(e),n=t.outputsLength,r=[];for(let e=0;e<n;e++){const n=t.getOutput(e);r.push(n)}return r}function Ld(e){for(let t=0;t<e.inputsLength;t++){const n=e.getInput(t),r=n.redeemScript,i=n.partialSig?.at(0);void 0!==r&&void 0!==i&&e.finalizeIdx(t)}return e}var zd=Object.freeze({__proto__:null,assert_psbt_is_funded:function(e){const t=Cd(e),n=Bd(t),r=Rd(t),i=n.reduce((e,t)=>e+Number(t.witnessUtxo?.amount??0),0),s=r.reduce((e,t)=>e+Number(t.amount??0),0);b.ok(i>=s,`value in (${i}) < value out (${s})`)},collect_prevouts:function(e){const t=[],n=[],r=Cd(e);for(let e=0;e<r.inputsLength;e++){const i=r.getInput(e);b.exists(i.witnessUtxo,`witness utxo does not exist for input ${e}`),t.push(i.witnessUtxo.amount),n.push(i.witnessUtxo.script)}return{amounts:t,scripts:n}},collect_vins:Bd,collect_vouts:Rd,decode_psbt:$d,encode_psbt:function(e){const t=e.toPSBT(0);return Ki.encode(t)},finalize_legacy_inputs:Ld,get_txhex:function(e){let t=Cd(e);return t=Ld(t),t.hex},get_vsize:function(e){return Cd(e).vsize},parse_psbt:Cd}),jd=Object.freeze({__proto__:null,format_sigflag:Ns,hash_amounts:No,hash_outpoints:To,hash_output:Co,hash_outputs:$o,hash_scripts:Uo,hash_segwit_tx:_o,hash_sequence:Io,hash_taproot_tx:Po,parse_txinput:Is});var Hd=Object.freeze({__proto__:null,sign_segwit_tx:Ro,sign_taproot_tx:Lo,verify_segwit_tx:function(e,t={}){return console.warn("verify_segwit_tx is not implemented"),!0},verify_taproot_tx:function(e,t={}){return console.warn("verify_taproot_tx is not implemented"),!0}});function Dd(e,t,n=[]){const r=[],i=[];if(e.length<1)throw new Error("Tree is empty!");for(let i=0;i<e.length;i++){const s=e[i];if(Array.isArray(s)){let[e,i,o]=Dd(s,t);t=i,r.push(e);for(const e of o)n.push(e)}else{const e=m.bytes(s).hex;r.push(e)}}if(1===r.length)return[r[0],t,n];r.sort(),r.length%2!=0&&r.push(r[r.length-1]);for(let e=0;e<r.length-1;e+=2){const s=ko(r[e],r[e+1]).hex;i.push(s),"string"==typeof t&&(t===r[e]?(n.push(r[e+1]),t=s):t===r[e+1]&&(n.push(r[e]),t=s))}return Dd(i,t,n)}function Fd(e){const t=new y(e),n=t.read(1).num,r=t.read(32).hex,[i,s]=Vd(n),o=[];for(;t.size>=32;)o.push(t.read(32).hex);if(0!==t.size)throw new Error("Non-empty buffer on control block: "+String(t));return{int_key:r,path:o,parity:s,version:i}}function Vd(e){return e%2==0?[e-0,2]:[e-1,3]}function Zd(e){b.size(e,33,"invalid pubkey size");const[t]=m.bytes(e);if(2===t)return 0;if(3===t)return 1;throw new Error("Invalid parity bit: "+String(t))}const Kd=192;var Wd=Object.freeze({__proto__:null,create_taproot:function(e){hs.parse(e);const{pubkey:t,version:n=Kd}=e,r=e.leaves??[],i=void 0!==e.target?m.bytes(e.target).hex:void 0;let s,o=[];if(r.length>0){const[e,t,n]=Dd(r,i);o=n,s=e}else s=i;const a=Ao(t,s),u=Rt(t,a,"ecdsa"),c=Zd(u),d=jt(u,"bip340"),h=[m.num(n+c),m.bytes(t)];o.length>0&&o.forEach(e=>h.push(e));const f=m.join(h);return{int_key:m.bytes(t).hex,parity:c,taproot:s??null,cblock:f.hex,tapkey:d.hex,taptweak:a.hex}},encode_leaf_version:Oo,encode_tapbranch:ko,encode_tapleaf:So,encode_tapscript:xo,encode_taptweak:Ao,get_merkle_root:function(e){return Dd(e)[0]},merkleize:Dd,parse_cblock:Fd,parse_cblock_parity:Vd,parse_pubkey_parity:Zd,parse_taproot_witness:function(e){const{cblock:t,params:n,script:r}=Sa(e);b.exists(t,"cblock is null"),b.exists(r,"script is null");const i=Fd(t);let s=xo(r,i.version).hex;for(const e of i.path)s=ko(s,e).hex;const o=Ao(i.int_key,s),a=Rt(i.int_key,o,"bip340");return n.map(e=>m.bytes(e).hex),{cblock:i,params:n,script:r,tapkey:a.hex,tweak:o.hex}},verify_taproot:function(e,t,n){b.size(e,32);const{parity:r,path:i,int_key:s}=Fd(n),o=m.join([r,e]);let a=m.bytes(t).hex;for(const e of i)a=ko(a,e).hex;const u=Rt(s,Ao(s,a),"ecdsa");return o.hex===u.hex}});return e.ADDRESS=uu,e.CONST=rs,e.META=Ea,e.PSBT=zd,e.SCHEMA=vs,e.SCRIPT=Ms,e.SIGHASH=jd,e.SIGNER=Hd,e.TAPROOT=Wd,e.TX=wo,e.Transaction=class{constructor(e={}){this._tx="string"!=typeof e?Ts(e):ss(e),this._size=this._get_size(),this._hash=lo(this._tx),this._txid=fo(this._tx),this._value=po(this._tx),this._vin=this._tx.vin.map(e=>new Pa(e)),this._vout=this._tx.vout.map(e=>new xa(e))}get data(){return{hash:this.hash,locktime:this.locktime,return:this.return,size:this.size,spends:this.spends,txid:this.txid,value:this.value,version:this.version,vin:this.vin.map(e=>e.data),vout:this.vout.map(e=>e.data)}}get hash(){return this._hash}get locktime(){return{hex:oo(this._tx.locktime).hex,data:jo.decode(this._tx.locktime),value:this._tx.locktime}}get return(){return this._tx.vout.find(e=>uo(e.script_pk))||null}get size(){return this._size}get spends(){return this._tx.vin.filter(e=>null!==e.prevout).map(e=>new xa(e.prevout))}get txid(){return this._txid}get value(){return this._value}get version(){return this._tx.version}get vin(){return this._vin}get vout(){return this._vout}add_vin(e){const t=Os(e);this._tx.vin.push(t),this._update_vin()}add_vout(e){const t=As(e);this._tx.vout.push(t),this._update_vout()}insert_vin(e,t){b.ok(e>=0&&e<=this._tx.vin.length,"input goes out of bounds");const n=Os(t);e===this._tx.vin.length?this._tx.vin.push(n):this._tx.vin.splice(e,0,n),this._update_vin()}insert_vout(e,t){b.ok(e>=0&&e<=this._tx.vout.length,"output goes out of bounds");const n=As(t);e===this._tx.vout.length?this._tx.vout.push(n):this._tx.vout.splice(e,0,n),this._update_vout()}remove_vin(e){b.ok(void 0!==this._tx.vin.at(e),"input does not exist at index"),this._tx.vin.splice(e,1),this._update_vin()}remove_vout(e){b.ok(void 0!==this._tx.vout.at(e),"output does not exist at index"),this._tx.vout.splice(e,1),this._update_vout()}_get_size(){return{...go(this._tx),segwit:this.vin.reduce((e,t)=>e+(t.witness?.size.vsize??0),0),vin:this.vin.reduce((e,t)=>e+t.size,0),vout:this.vout.reduce((e,t)=>e+t.size,0),witness:this.vin.reduce((e,t)=>e+(t.witness?.size.total??0),0)}}_update_tx(){this._size=this._get_size(),this._hash=lo(this._tx),this._txid=fo(this._tx),this._value=po(this._tx)}_update_vin(){this._vin=this._tx.vin.map(e=>new Pa(e)),this._update_tx()}_update_vout(){this._vout=this._tx.vout.map(e=>new xa(e)),this._update_tx()}toJSON(){return this.data}toString(){return JSON.stringify(this.data)}},e.TransactionInput=Pa,e.TransactionOutput=xa,e.TransactionWitness=Aa,e.TxSigner=class{constructor(e){this._seckey=m.bytes(e).hex}get pubkey(){return{segwit:Bt(this._seckey,"ecdsa"),taproot:Bt(this._seckey,"bip340")}}get sign_msg(){return{ecdsa:e=>{const t=m.bytes(e);return Lt(this._seckey,t)},bip340:e=>{const t=m.bytes(e);return zt(this._seckey,t)}}}get sign_tx(){return{segwit:(e,t)=>Ro(this._seckey,e,t),taproot:(e,t)=>Lo(this._seckey,e,t)}}},e.WITNESS=Oa,e}({});
|
|
15
15
|
//# sourceMappingURL=script.js.map
|